Download kernels/L1/044_moe_expert_computation/src/kernel.cu from QianQu/CompoundingKernel-Explorer: direct link, hf CLI and curl.
- Browser
- Download file 202 kB
-
https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/kernels/L1/044_moe_expert_computation/src/kernel.cu
- Command line
-
hf download hf://spaces/QianQu/CompoundingKernel-Explorer/kernels/L1/044_moe_expert_computation/src/kernel.cu
-
curl -L -o kernel.cu https://huggingface.co/spaces/QianQu/CompoundingKernel-Explorer/resolve/main/kernels/L1/044_moe_expert_computation/src/kernel.cu
202 kB
// MoE expert computation (DeepSeek-V3 shapes) -- single persistent warp-specialized tcgen05
// 2-SM (cta_group::2) MoE megakernel, swap-AB (weights = MMA M side, tokens = N side).
//
// Algorithm
// 1. routing, IN the megakernel prologue (no separate launch): all co-resident CTAs build the
// expert histogram (smem partial + global atomics), grid barrier, redundant 256-entry scan,
// scatter (token,slot) -> sorted_slot[p]; CTA 0 cuts each expert's rows into chunks of
// <= NCH tokens and writes the WORK QUEUE item_info[] (see route_in_kernel) and zeroes the
// per-chunk dependency counters done[]; second grid barrier, then the work loop.
//
#include <cuda.h>
#include <cuda_runtime.h>
#include <cuda_bf16.h>
#include <cstdint>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <type_traits>
#include <stdexcept>
#include <string>
#include "kernel.h"
#define HID 7168
#define INTER 2048
#define NEXP 256
#define TOPK 8
#ifndef BK
#define BK 64
#endif
#define SW_BYTES (BK * 2) // swizzle span = one K-row of a stage (64 or 128 B)
#define SW_SBO (8 * SW_BYTES) // 8-row core-matrix group stride
#define SW_DESC_MODE (BK == 64 ? 2 : 4) // SM100 desc layout: 2 = SWIZZLE_128B, 4 = SWIZZLE_64B
#define BM 128 // weight rows per CTA (MMA M = 2*BM = 256 across the pair)
#define BM2 256
// Token-chunk size NCH (max tokens per work item, UMMA N <= 256) is chosen on the host from T
// (128 / 192 / 256): the smem token tile is sized for NCH, so a small NCH buys more pipeline stages.
#define XBOX 32 // rows per TMA box of the token operand (kernel B)
#define RG_THREADS 512 // route block size
#define RG_MAXCHUNK 512
// ----------------------------------------------------------------- PTX helpers
__device__ __forceinline__ uint32_t smem_u32(const void* p) {
return (uint32_t)__cvta_generic_to_shared(p);
}
__device__ __forceinline__ uint32_t cluster_rank() {
uint32_t r;
asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r));
return r;
}
// shared::cluster address of the same smem offset in CTA `rank` of the cluster
__device__ __forceinline__ uint32_t mapa(uint32_t addr, uint32_t rank) {
uint32_t r;
asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(addr), "r"(rank));
return r;
}
__device__ __forceinline__ void cluster_sync() {
asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::
: "memory");
}
__device__ __forceinline__ void mbar_init(uint32_t bar, uint32_t cnt) {
asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(bar), "r"(cnt));
}
__device__ __forceinline__ void mbar_wait(uint32_t bar, uint32_t phase) {
uint32_t done = 0;
while (!done) {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase)
: "memory");
}
}
// wait with a suspend-time hint (ns): the waiting thread is parked by hardware until the phase
// completes (or the hint expires) instead of re-issuing try_wait in a tight loop. Used by the
// epilogue warps' accumulator-full waits (8 warps x 2 CTAs idle for a whole mainloop each item):
// fewer issued instructions / less SM dynamic power in the power-capped regime.
__device__ __forceinline__ void mbar_wait_park(uint32_t bar, uint32_t phase) {
uint32_t done = 0;
while (!done) {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase), "r"(1000000u)
: "memory");
}
}
// #BW producer slack fast path: one NON-BLOCKING test_wait first; when the ring has slack (the stage
// was already released by the MMA commit) the producer issues the TMA immediately without entering the
// suspend-hinted try_wait loop; otherwise falls back to the parked wait. Same barrier semantics.
__device__ __forceinline__ void mbar_wait_probe(uint32_t bar, uint32_t phase) {
uint32_t done;
asm volatile(
"{\n .reg .pred p;\n mbarrier.test_wait.parity.shared::cta.b64 p, [%1], %2;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase)
: "memory");
if (!done) mbar_wait_park(bar, phase);
}
// wait with cluster-scope acquire (data written by the peer CTA via st.shared::cluster)
__device__ __forceinline__ void mbar_wait_cl(uint32_t bar, uint32_t phase) {
uint32_t done = 0;
while (!done) {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase)
: "memory");
}
}
__device__ __forceinline__ void mbar_expect_tx(uint32_t bar, uint32_t bytes) {
asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"(bytes)
: "memory");
}
// arrive on a (possibly remote) barrier given its shared::cluster address
__device__ __forceinline__ void mbar_arrive_cluster(uint32_t cbar) {
asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(cbar)
: "memory");
}
// 2-SM TMA load: data -> this CTA's smem, completion bytes -> barrier `cbar` (leader CTA)
__device__ __forceinline__ void tma_load_2d(uint32_t dst, const CUtensorMap* tm, uint32_t cbar,
int c0, int c1, uint64_t policy) {
asm volatile(
"cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint"
" [%0], [%1, {%3, %4}], [%2], %5;" ::"r"(dst),
"l"((uint64_t)tm), "r"(cbar), "r"(c0), "r"(c1), "l"(policy)
: "memory");
}
__device__ __forceinline__ void tma_load_4d(uint32_t dst, const CUtensorMap* tm, uint32_t cbar,
int c0, int c1, int c2, int c3, uint64_t policy) {
asm volatile(
"cp.async.bulk.tensor.4d.cta_group::2.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint"
" [%0], [%1, {%3, %4, %5, %6}], [%2], %7;" ::"r"(dst),
"l"((uint64_t)tm), "r"(cbar), "r"(c0), "r"(c1), "r"(c2), "r"(c3), "l"(policy)
: "memory");
}
// 2-SM TMA gather4: token rows r0..r3, columns [c0, c0+64) -> 4 consecutive 128-B smem rows
// of this CTA (128B-swizzled per the tensor map, box = {64, 1}); bytes -> leader barrier.
__device__ __forceinline__ void tma_gather4(uint32_t dst, const CUtensorMap* tm, uint32_t cbar, int c0,
int r0, int r1, int r2, int r3, uint64_t policy) {
asm volatile(
"cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.tile::gather4.mbarrier::complete_tx::bytes"
".L2::cache_hint [%0], [%1, {%3, %4, %5, %6, %7}], [%2], %8;" ::"r"(dst),
"l"((uint64_t)tm), "r"(cbar), "r"(c0), "r"(r0), "r"(r1), "r"(r2), "r"(r3), "l"(policy)
: "memory");
}
// same, without an L2 cache hint (the stream's access-policy window decides the L2 property)
__device__ __forceinline__ void tma_gather4_nohint(uint32_t dst, const CUtensorMap* tm, uint32_t cbar, int c0,
int r0, int r1, int r2, int r3) {
asm volatile(
"cp.async.bulk.tensor.2d.cta_group::2.shared::cluster.global.tile::gather4.mbarrier::complete_tx::bytes"
" [%0], [%1, {%3, %4, %5, %6, %7}], [%2];" ::"r"(dst),
"l"((uint64_t)tm), "r"(cbar), "r"(c0), "r"(r0), "r"(r1), "r"(r2), "r"(r3)
: "memory");
}
// Ampere-style 16-B async copy global -> shared (generic proxy; L2-cached, L1 bypass). Used by the
// token-loader warp (CPX variants) instead of TMA gather4 for the token operand.
// PF: L2 prefetch-size hint (0 none, 1 .L2::128B, 2 .L2::256B)
template <int PF>
__device__ __forceinline__ void cp_async16(uint32_t dst, const void* src) {
if (PF == 1) asm volatile("cp.async.cg.shared.global.L2::128B [%0], [%1], 16;" ::"r"(dst), "l"(src) : "memory");
else if (PF == 2) asm volatile("cp.async.cg.shared.global.L2::256B [%0], [%1], 16;" ::"r"(dst), "l"(src) : "memory");
else asm volatile("cp.async.cg.shared.global [%0], [%1], 16;" ::"r"(dst), "l"(src) : "memory");
}
// zero-fill variant: copies `sz` (16 or 0) bytes and zero-fills the rest of the 16-B destination.
// sz = 0 writes 16 zero bytes without reading global memory (src must still be a valid address).
// Used for the MMA N-padding token rows (n..n16) of gate|up items: they only feed ignored D columns,
// and zero operands cut tensor-core switching energy vs a duplicated real token (power-throttled regime).
__device__ __forceinline__ void cp_async16z(uint32_t dst, const void* src, uint32_t sz) {
asm volatile("cp.async.cg.shared.global [%0], [%1], 16, %2;" ::"r"(dst), "l"(src), "r"(sz) : "memory");
}
__device__ __forceinline__ void cp_async_commit() { asm volatile("cp.async.commit_group;" ::: "memory"); }
// hardware-tracked completion: arrive on the (local) mbarrier once all prior cp.async of this thread
// have landed; .noinc = this counts as the thread's arrival (barrier count includes it)
__device__ __forceinline__ void cp_async_mbar_arrive_noinc(uint32_t bar) {
asm volatile("cp.async.mbarrier.arrive.noinc.shared::cta.b64 [%0];" ::"r"(bar) : "memory");
}
// MOE_ARRCNT: ONE arrive op carrying `cnt` arrivals (PTX mbarrier.arrive count operand, sm_90+)
__device__ __forceinline__ void mbar_arrive_local_cnt(uint32_t bar, uint32_t cnt) {
asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"(cnt) : "memory");
}
__device__ __forceinline__ void mbar_arrive_local(uint32_t bar) {
asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(bar) : "memory");
}
// SM100 shared-memory matrix descriptor: K-major, 128B/64B swizzle (by BK), 8-row groups SW_SBO apart.
__device__ __forceinline__ uint64_t make_desc(uint32_t saddr) {
uint64_t d = 0;
d |= (uint64_t)((saddr & 0x3FFFF) >> 4); // start address
d |= (uint64_t)1 << 16; // LBO (ignored for swizzled K-major)
d |= (uint64_t)(SW_SBO >> 4) << 32; // SBO = 8 rows
d |= (uint64_t)1 << 46; // descriptor version (SM100)
d |= (uint64_t)SW_DESC_MODE << 61; // SWIZZLE_128B / SWIZZLE_64B
return d;
}
// 2-SM MMA (issued by the leader CTA): A rows 0-127 / B cols 0..N/2-1 from CTA0 smem,
// A rows 128-255 / B cols N/2..N-1 from CTA1 smem (same offsets); D split by M.
__device__ __forceinline__ void mma_bf16(uint32_t tmem_d, uint64_t da, uint64_t db, uint32_t idesc,
uint32_t acc) {
asm volatile(
"{\n .reg .pred p;\n setp.ne.b32 p, %4, 0;\n"
" tcgen05.mma.cta_group::2.kind::f16 [%0], %1, %2, %3, p;\n}\n" ::"r"(tmem_d),
"l"(da), "l"(db), "r"(idesc), "r"(acc));
}
// commit prior MMAs -> arrive on barrier at the same offset in both CTAs of the pair
__device__ __forceinline__ void mma_commit_mc(uint32_t bar) {
const uint16_t mask = 0x3;
asm volatile(
"tcgen05.commit.cta_group::2.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"(bar),
"h"(mask)
: "memory");
}
__device__ __forceinline__ void tc_fence_after() {
asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory");
}
__device__ __forceinline__ void tc_fence_before() {
asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory");
}
// 32 lanes x 32 columns of fp32 from TMEM: thread lane i gets row (quadrant*32+i), 32 cols.
__device__ __forceinline__ void tmem_ld32(uint32_t taddr, float* v) {
uint32_t r[32];
asm volatile(
"tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15,"
"%16,%17,%18,%19,%20,%21,%22,%23,%24,%25,%26,%27,%28,%29,%30,%31}, [%32];"
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]),
"=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]),
"=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]),
"=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]),
"=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31])
: "r"(taddr));
#pragma unroll
for (int i = 0; i < 32; ++i) v[i] = __uint_as_float(r[i]);
}
// MOE_N16EXACT: 32 lanes x 16 columns (tail chunk of an item whose n16 ends 16 columns into a 32-col chunk)
__device__ __forceinline__ void tmem_ld16(uint32_t taddr, float* v) {
uint32_t r[16];
asm volatile(
"tcgen05.ld.sync.aligned.32x32b.x16.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15}, [%16];"
: "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]),
"=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15])
: "r"(taddr));
#pragma unroll
for (int i = 0; i < 16; ++i) v[i] = __uint_as_float(r[i]);
#pragma unroll
for (int i = 16; i < 32; ++i) v[i] = 0.f;
}
__device__ __forceinline__ void tmem_ld_wait() {
asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");
}
__device__ __forceinline__ int ld_acquire_gpu(const int* p) {
int v;
asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(v) : "l"(p) : "memory");
return v;
}
__device__ __forceinline__ void red_release_gpu_add(int* p, int v) {
asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(p), "r"(v) : "memory");
}
__device__ __forceinline__ void fence_proxy_async_global() {
asm volatile("fence.proxy.async.global;" ::: "memory");
}
// L2 eviction policy by code: 0 evict_last, 1 evict_normal, 2 evict_first (runtime knobs of the out stores)
__device__ __forceinline__ uint64_t make_l2pol(int code) {
uint64_t p;
if (code == 2) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p));
else if (code == 1) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(p));
else asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p));
return p;
}
// Programmatic Dependent Launch (PDL) controls
__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }
__device__ __forceinline__ void pdl_launch_dependents() {
asm volatile("griddepcontrol.launch_dependents;" ::: "memory");
}
// L2-only prefetch of one TMA box (no smem, no barrier): pure cache hint
__device__ __forceinline__ void tma_prefetch_2d(const CUtensorMap* tm, int c0, int c1) {
asm volatile("cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];" ::"l"((uint64_t)tm),
"r"(c0), "r"(c1)
: "memory");
}
__device__ __forceinline__ void prefetch_tmap(const CUtensorMap* tm) {
asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)tm) : "memory");
}
#ifndef MOE_NOWPF
#define MOE_NOWPF 1
#endif
#ifndef NPF_SLABS
#define NPF_SLABS 16 // 16 slabs x 2 tiles x 16 KB x 148 CTAs = 76 MB of first-item weights
// prefetched to L2 under the PDL wait + in-kernel routing (8: 38 MB, DRAM idle sooner)
#endif
// L2 policy of the streamed weight TMA loads: 0 evict_first, 1 evict_normal, 2 evict_unchanged
#ifndef MOE_WPOL
#define MOE_WPOL 0
#endif
#if MOE_WPOL == 0
#define MOE_WPOL_STR "createpolicy.fractional.L2::evict_first.b64 %0, 1.0;"
#elif MOE_WPOL == 1
#define MOE_WPOL_STR "createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;"
#else
#define MOE_WPOL_STR "createpolicy.fractional.L2::evict_unchanged.b64 %0, 1.0;"
#endif
// L2 policy of the Hs TMA reads (down items): 0 evict_first, 1 evict_last, 2 evict_unchanged
#ifndef MOE_HPOL
#define MOE_HPOL 0
#endif
// DEBUG ablation (results wrong, bytes only): 1 skip token gather4, 2 skip Hs TMA reads,
// 3 skip out reds, 4 skip Hs stores, 5 skip out zeroing + reds. 0 = production.
#ifdef MOE_PROF
// PROF builds: runtime ablation code g_abl (set by moe_set_abl) -- 1 skip tokens, 2 skip Hs reads,
// 3 skip out reds, 4 skip Hs stores, 6 half MMA, 7 quarter MMA, 8 skip SwiGLU math, 9 weights only,
// 10 no MMA
__device__ int g_abl;
// 11 constant A (weight TMA loads skipped after the first WS iterations: stale weight smem, tokens real)
// 12 constant A + constant B; 13 B real but every token K-slice = K-slice 0; 14/15/16 MMA N capped at 16/64/128
#define ABL_NOTOK (abl_v == 1 || abl_v == 9 || abl_v == 12)
#define ABL_CONSTA (abl_v == 11 || abl_v == 12)
#define ABL_TOKK0 (abl_v == 13)
#define ABL_PADZ4 (abl_v == 17) // v4: padding rows zeroed once per slot via st.shared, not loaded.
#define ABL_NCAP (abl_v == 14 ? 16 : (abl_v == 15 ? 64 : (abl_v == 16 ? 128 : 0)))
#define ABL_NOHSR (abl_v == 2 || abl_v == 9)
#define ABL_NORED (abl_v == 3 || abl_v == 5 || abl_v == 9)
#define ABL_NOHSST (abl_v == 4 || abl_v == 9)
#define ABL_NOZERO (abl_v == 5 || abl_v == 9)
#define ABL_NOSWI (abl_v == 8)
#define ABL_MMA0 (abl_v == 9 || abl_v == 10)
#define ABL_MMA1 (abl_v == 6 || abl_v == 7)
#define ABL_MMAQ (abl_v == 7)
#define ACC_OLDARR (abl_v == 18) // PROF A/B: old .release.cluster acce arrive
#else
#define ACC_OLDARR 0
#define ABL_NOTOK 0
#define ABL_CONSTA 0
#define ABL_TOKK0 0
#define ABL_NCAP 0
#ifndef MOE_PADZ4
#define MOE_PADZ4 0
#endif
#define ABL_PADZ4 MOE_PADZ4
#define ABL_NOHSR 0
#define ABL_NORED 0
#define ABL_NOHSST 0
#define ABL_NOZERO 0
#define ABL_NOSWI 0
#define ABL_MMA0 0
#define ABL_MMA1 0
#define ABL_MMAQ 0
#endif
#ifndef MOE_EARLYZ
#define MOE_EARLYZ 1
#endif
#ifndef MOE_ZERO_EL
#define MOE_ZERO_EL 1
#endif
#ifndef MOE_WPROMO // L2 promotion of the weight tensor maps: 0 none, 1 128B, 2 256B
#define MOE_WPROMO 2
#endif
// Down-epilogue store coalescing: in TMEM each lane owns ONE hidden feature for 32 tokens.
// An 8x8 butterfly transpose inside each 8-lane group (12 shuffles) gives lane (g,i) token i's
// 8 consecutive features (of lanes 8g..8g+7) -> one 16-B vector reduction per lane per 8 tokens.
// On entry x[t] = value of token t for this lane's feature; on exit x[r] = value of token
// i (= lane%8) for feature 8*(lane/8)+r.
__device__ __forceinline__ void transpose8(float* x, int i) {
#pragma unroll
for (int s = 4; s >= 1; s >>= 1) {
const bool up = (i & s) != 0;
#pragma unroll
for (int t = 0; t < 8; ++t) {
if (t & s) continue;
const float send = up ? x[t] : x[t | s];
const float recv = __shfl_xor_sync(0xffffffffu, send, s);
if (up) x[t] = recv; else x[t | s] = recv;
}
}
}
// fast SiLU with ONE MUFU op: silu(x) = x * sigmoid(x) = h + h * tanh(h), h = x/2
// (tanh.approx.f32, max rel err ~2^-11, well below the bf16 rounding of Hs; was ex2 + rcp = 2 MUFU).
// x -> -inf: tanh -> -1 exactly, so h + h*(-1) = 0; x -> +inf: tanh -> 1, silu -> x.
__device__ __forceinline__ float fast_silu(float x) {
const float h = 0.5f * x;
float t;
asm("tanh.approx.f32 %0, %1;" : "=f"(t) : "f"(h));
return fmaf(h, t, h);
}
__device__ __forceinline__ uint32_t pack_bf16x2(float lo, float hi) {
uint32_t r;
asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(r) : "f"(hi), "f"(lo)); // first source -> upper half
return r;
}
// MOE_BFTANH128: now also the small-T NCH=128 bands (6 instrs/pair vs ~11 for fp32 tanh SiLU + mul + cvt).
// MOE_BFTANH192 (NCH=192/176 variants + MIX NCH>=240 gate|up band (T6144, power-capped: fewer epilogue instrs): T3719 full-mega band, T5120 MIX gate|up band): SwiGLU of a feature
// pair with ONE packed tanh.approx.bf16x2 MUFU op (was 2 x tanh.approx.f32): silu(x) = h + h*tanh(h),
// h = x/2 in fp32, tanh in bf16 (rel err ~2^-8), FMA and up product in fp32, then the usual bf16x2 pack.
// + 1 cvt instead of 1 HMUL2 + 1 MUFU + 1 HFMA2 + 1 cvt per pair.
#ifndef MOE_SWIF16
#define MOE_SWIF16 1
#endif
#ifndef MOE_SWIFX2
#define MOE_SWIFX2 1
#endif
#ifndef MOE_SWIF32
#define MOE_SWIF32 1
#endif
__device__ __forceinline__ uint32_t swiglu2_bf16tanh(float g0, float g1, float u0, float u1) {
if (MOE_SWIF16) {
// MOE_SWIF16: silu(g) = h + h*tanh(h), h = g/2 in fp32, with ONE packed tanh.approx.f16x2 MUFU op
// for the pair (was 2 x tanh.approx.f32). Only tanh runs in f16: h is converted with .satfinite
// (|h| > 65504 -> +-65504, tanh = +-1 exactly, no inf), t in [-1, 1]; the FMA, bf16 rounding of
// silu and the bf16 up product are unchanged. f16 spacing near |t| = 1 is 2^-11, the same as the
// tanh.approx.f32 error, so the 1 + t cancellation for negative g behaves as in the fp32 path.
#if MOE_SWIFX2
// MOE_SWIFX2 (power diet): the fp32 halving and the silu FMA of the feature pair run as ONE
// packed Blackwell FMUL2 (mul.rn.ftz.f32x2) and ONE FFMA2 (fma.rn.ftz.f32x2) instead of 2 FMUL +
// 2 FFMA: same per-lane IEEE rounding (x0.5 exact; fma single-rounded, ftz as --use_fast_math)
// -> bit-identical silu. tanh stays one packed tanh.approx.f16x2 (satfinite h, as before).
uint32_t s2, r;
asm("{\n .reg .b64 G, H, T, S, C;\n .reg .f32 h0, h1, t0, t1, s0, s1, c5;\n .reg .b32 hh, tt;\n .reg .f16 ta, tb;\n"
" mov.b64 G, {%1, %2};\n mov.f32 c5, 0f3F000000;\n mov.b64 C, {c5, c5};\n mul.rn.ftz.f32x2 H, G, C;\n"
" mov.b64 {h0, h1}, H;\n cvt.rn.satfinite.f16x2.f32 hh, h1, h0;\n tanh.approx.f16x2 tt, hh;\n"
" mov.b32 {ta, tb}, tt;\n cvt.f32.f16 t0, ta;\n cvt.f32.f16 t1, tb;\n mov.b64 T, {t0, t1};\n"
" fma.rn.ftz.f32x2 S, H, T, H;\n mov.b64 {s0, s1}, S;\n cvt.rn.bf16x2.f32 %0, s1, s0;\n}\n"
: "=r"(s2) : "f"(g0), "f"(g1));
const uint32_t u2 = pack_bf16x2(u0, u1);
#else
const float h0 = 0.5f * g0, h1 = 0.5f * g1;
uint32_t hh, tt, r;
asm("cvt.rn.satfinite.f16x2.f32 %0, %1, %2;" : "=r"(hh) : "f"(h1), "f"(h0));
asm("tanh.approx.f16x2 %0, %1;" : "=r"(tt) : "r"(hh));
float t0, t1;
asm("{\n .reg .f16 a, b;\n mov.b32 {a, b}, %2;\n cvt.f32.f16 %0, a;\n cvt.f32.f16 %1, b;\n}\n"
: "=f"(t0), "=f"(t1) : "r"(tt));
const uint32_t s2 = pack_bf16x2(fmaf(h0, t0, h0), fmaf(h1, t1, h1)), u2 = pack_bf16x2(u0, u1);
#endif
asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(s2), "r"(u2));
return r;
}
if (MOE_SWIF32) {
uint32_t r;
const uint32_t s2 = pack_bf16x2(fast_silu(g0), fast_silu(g1)), u2 = pack_bf16x2(u0, u1);
asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(s2), "r"(u2));
return r;
}
uint32_t h2, t2, s2, r;
const uint32_t g2 = pack_bf16x2(g0, g1), u2 = pack_bf16x2(u0, u1);
asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(h2) : "r"(g2), "r"(0x3F003F00u));
asm("tanh.approx.bf16x2 %0, %1;" : "=r"(t2) : "r"(h2));
asm("fma.rn.bf16x2 %0, %1, %2, %1;" : "=r"(s2) : "r"(h2), "r"(t2));
asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(s2), "r"(u2));
return r;
}
// Hs store layout from TMEM layout, packing first. On entry x[t] = value of token t (of 8) for this
// lane's feature (lane%8 = i within the 8-lane group). Step 1 (lane ^ 1): the even lane keeps the
// even tokens, the odd lane the odd tokens; each packs (feature 2a, feature 2a+1) of its 4 tokens
// into bf16x2 words w[k] (token 2k+parity). Step 2: 4x4 butterfly transpose of the words over
// (k, j = i>>1) via lane ^ 2 / ^ 4. On exit p[r] = features (8*(lane/8)+2r, +1) of token i.
__device__ __forceinline__ void pack_transpose_bf16x2(const float* x, int i, uint32_t* p) {
// MOE_DNPACK1: pack first (own token pair (2k, 2k+1) of this lane's feature, 1 cvt), swap whole
// words with lane ^ 1, recombine with ONE prmt using a lane-dependent selector register
// (even: (own.lo, recv.lo) = token 2k; odd: (recv.hi, own.hi) = token 2k+1) -> no SELs per word.
// Bit-identical to the old fp32-exchange version (each value rounded to bf16 exactly once).
const uint32_t sel = (i & 1) ? 0x3276u : 0x5410u;
#pragma unroll
for (int k = 0; k < 4; ++k) {
const uint32_t own = pack_bf16x2(x[2 * k], x[2 * k + 1]);
const uint32_t recv = __shfl_xor_sync(0xffffffffu, own, 1);
uint32_t r;
asm("prmt.b32 %0, %1, %2, %3;" : "=r"(r) : "r"(own), "r"(recv), "r"(sel));
p[k] = r;
}
const int j = i >> 1;
#pragma unroll
for (int s = 2; s >= 1; s >>= 1) {
const bool up = (j & s) != 0;
#pragma unroll
for (int t = 0; t < 4; ++t) {
if (t & s) continue;
const uint32_t send = up ? p[t] : p[t | s];
const uint32_t recv = __shfl_xor_sync(0xffffffffu, send, 2 * s);
if (up) p[t] = recv; else p[t | s] = recv;
}
}
}
// MOE_DNXCH4: pack_transpose_bf16x2 WITHOUT its lane^4 butterfly stage (the two butterfly stages
// swap independent bit pairs, so they commute: here only the lane^2 stage is applied). The
// down epilogue fuses the skipped lane^4 stages of both accumulators with its full-line lane^4
// swap into ONE 4-word exchange (was 2 + 2 + 4 = 8 shuffles per 8 tokens).
__device__ __forceinline__ void pack_transpose_bf16x2_s1(const float* x, int i, uint32_t* p) {
const uint32_t sel = (i & 1) ? 0x3276u : 0x5410u;
#pragma unroll
for (int k = 0; k < 4; ++k) {
const uint32_t own = pack_bf16x2(x[2 * k], x[2 * k + 1]);
const uint32_t recv = __shfl_xor_sync(0xffffffffu, own, 1);
uint32_t r;
asm("prmt.b32 %0, %1, %2, %3;" : "=r"(r) : "r"(own), "r"(recv), "r"(sel));
p[k] = r;
}
const bool up = ((i >> 1) & 1) != 0;
#pragma unroll
for (int t = 0; t < 4; t += 2) {
const uint32_t send = up ? p[t] : p[t | 1];
const uint32_t recv = __shfl_xor_sync(0xffffffffu, send, 2);
if (up) p[t] = recv; else p[t | 1] = recv;
}
}
// 16-feature variant for 32-B stores. On entry x[t] = value of token t (of 16) for this lane's feature
// (i = lane%16). Step 1 (lane ^ 1): word k = features (2a, 2a+1), a = i>>1, of token 2k+parity.
// Step 2: 8x8 butterfly transpose over (k, a) via lane ^ 8 / ^ 4 / ^ 2.
// On exit p[r] = features (16*(lane/16)+2r, +1) of token i.
__device__ __forceinline__ void pack_transpose16_bf16x2(const float* x, int i, uint32_t* p) {
const int par = i & 1;
#pragma unroll
for (int k = 0; k < 8; ++k) {
const float send = par ? x[2 * k] : x[2 * k + 1];
const float recv = __shfl_xor_sync(0xffffffffu, send, 1);
p[k] = par ? pack_bf16x2(recv, x[2 * k + 1]) : pack_bf16x2(x[2 * k], recv);
}
const int j = i >> 1;
#pragma unroll
for (int s = 4; s >= 1; s >>= 1) {
const bool up = (j & s) != 0;
#pragma unroll
for (int t = 0; t < 8; ++t) {
if (t & s) continue;
const uint32_t send = up ? p[t] : p[t | s];
const uint32_t recv = __shfl_xor_sync(0xffffffffu, send, 2 * s);
if (up) p[t] = recv; else p[t | s] = recv;
}
}
}
// Same result as pack_transpose16_bf16x2, but starting from the ALREADY-PACKED token-pair words
// w[k] = (token 2k lo | token 2k+1 hi) of this lane's feature (16 tokens, k = 0..7): step 1 swaps
// whole words with lane ^ 1 and recombines halves with one byte-permute (prmt) instead of
// unpack (bf16 -> fp32) + shuffle + cvt.rn.bf16x2 re-pack (bit-identical: bf16 -> fp32 -> bf16 is exact).
// even lane (feature 2a) keeps token 2k: (own.lo, recv.lo)
// odd lane (feature 2a+1) keeps token 2k+1: (recv.hi, own.hi)
__device__ __forceinline__ void pack_transpose16_words(const uint32_t* w, int i, uint32_t* p) {
const int par = i & 1;
const uint32_t sel = par ? 0x7632u : 0x5410u; // prmt selector: lo/hi halves of (own, recv)
#pragma unroll
for (int k = 0; k < 8; ++k) {
const uint32_t recv = __shfl_xor_sync(0xffffffffu, w[k], 1);
// even: result = {own[15:0], recv[15:0]<<16}; odd: result = {recv[31:16], own[31:16]<<16}
uint32_t r;
if (par) asm("prmt.b32 %0, %1, %2, 0x7632;" : "=r"(r) : "r"(recv), "r"(w[k]));
else asm("prmt.b32 %0, %1, %2, 0x5410;" : "=r"(r) : "r"(w[k]), "r"(recv));
(void)sel;
p[k] = r;
}
const int j = i >> 1;
#pragma unroll
for (int s = 4; s >= 1; s >>= 1) {
const bool up = (j & s) != 0;
#pragma unroll
for (int t = 0; t < 8; ++t) {
if (t & s) continue;
const uint32_t send = up ? p[t] : p[t | s];
const uint32_t recv = __shfl_xor_sync(0xffffffffu, send, 2 * s);
if (up) p[t] = recv; else p[t | s] = recv;
}
}
}
// MOE_WFOLDX2: routing-weight fold of a packed bf16x2 Hs word as ONE explicit mul.rn.bf16x2 (was
// __hmul2 through __nv_bfloat162 temporaries); same single IEEE rn rounding per lane -> bit-identical.
__device__ __forceinline__ void bf16x2_mul_inplace(uint32_t& p, uint32_t w2) {
asm("mul.rn.bf16x2 %0, %0, %1;" : "+r"(p) : "r"(w2));
}
// out[0..7] += bf16(x[0..7] * w): one 16-B vector bf16x2 reduction at L2 (out stays L2-resident)
__device__ __forceinline__ void red_add_bf16x8(__nv_bfloat16* dst, const float* x, float w, uint64_t pol) {
uint32_t p[4];
#pragma unroll
for (int j = 0; j < 4; ++j) {
// MOE_WFOLDX2: packed f32x2 weight scaling (one FMUL2 per pair, same per-lane rn.ftz rounding)
uint32_t r2;
asm("{\n .reg .b64 X, W, Y;\n .reg .f32 y0, y1;\n mov.b64 X, {%1, %2};\n mov.b64 W, {%3, %3};\n"
" mul.rn.ftz.f32x2 Y, X, W;\n mov.b64 {y0, y1}, Y;\n cvt.rn.bf16x2.f32 %0, y1, y0;\n}\n"
: "=r"(r2) : "f"(x[2 * j]), "f"(x[2 * j + 1]), "f"(w));
p[j] = r2;
}
asm volatile("red.global.add.noftz.L2::cache_hint.v4.bf16x2 [%0], {%1, %2, %3, %4}, %5;" ::"l"(dst), "r"(p[0]), "r"(p[1]),
"r"(p[2]), "r"(p[3]), "l"(pol)
: "memory");
}
// bf16 store with an L2 cache-policy hint
__device__ __forceinline__ void st_bf16_hint(__nv_bfloat16* p, __nv_bfloat16 v, uint64_t pol) {
const unsigned short b = *reinterpret_cast<unsigned short*>(&v);
asm volatile("st.global.L2::cache_hint.b16 [%0], %1, %2;" ::"l"(p), "h"(b), "l"(pol) : "memory");
}
// drop a (dead) 128-B L2 line without writing it back to DRAM
__device__ __forceinline__ void discard_l2(const void* p) {
asm volatile("discard.global.L2 [%0], 128;" ::"l"(p) : "memory");
}
// ---- debug-only per-CTA timing instrumentation (compile with -DMOE_PROF) ----
#ifdef MOE_PROF
#define PROF_N 32
__device__ unsigned long long g_prof[160 * PROF_N];
__device__ __forceinline__ unsigned long long gtime() {
unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; }
#define PROF(...) __VA_ARGS__
#else
#define PROF(...)
#endif // speculative L2 prefetch depth (BK-slabs per weight tile) before PDL wait
// Hs tensor maps with exact box heights: m[i] = box {BK cols, 8*(i+1) rows} (h64 == 2 path).
// A down item loads exactly its `half` (= n16/2, multiple of 8, <= 128) Hs rows per CTA per K-slice
// with ONE TMA op, instead of whole 32-row units (up to 24 dead rows of L2->SMEM traffic per slice).
struct HsMaps { CUtensorMap m[16]; };
// MOE_HSMAPN (launch-parameter diet): a launch of chunk width NCH only ever uses maps [0, NCH/16)
// (half <= NCH/2 rows), so it takes just those as its kernel parameter (NCH=128: 1 KB instead of 2 KB).
template <int N> struct HsMapsN { CUtensorMap m[N]; };
// Launch-parameter diet: the gather4 token map is only a kernel parameter of the TMA-gather4
// (CPX == 0) variants; cp.async-loader variants (CPX != 0, every production launch) take a 4-B
// placeholder instead (128 B less parameter buffer). The 32/64/96/128-row Hs box maps of the old
// h64 = 0/1 paths are gone: Hs is always loaded with the exact-height HsMaps boxes.
struct NoMap { int unused; };
template <int CPX> using XMapT = typename std::conditional<CPX != 0, NoMap, CUtensorMap>::type;
#define GU_MT (INTER / BM2) // 8 gate|up m-tiles per chunk (256 features per pair)
#define DN_MT (HID / (2 * BM2)) // 14 down m-tiles per chunk (512 hidden rows per pair)
#define ITEMS_PER_CHUNK (GU_MT + DN_MT)
#define EPI_WARPS 8
#define EPI_THREADS (EPI_WARPS * 32)
#define NTHREADS (7 * 32 + 4 * 32) // 7 role warps (0..6) + 4 extra epilogue warps (7..10)
#define DONE_TARGET (GU_MT * 2 * EPI_WARPS) // 8 tiles x 2 CTAs x 8 epilogue warps
// Tail K-split (full megakernel path): the down items of the LAST DSPLIT_CHUNKS chunks (all in the
// trailing pure-down queue region, after every gate|up item) are queued as two K-halves each
// (K = 1024, both red.add their partial into out), so the final queue items are half as long and
// the per-cluster end spread (last claim imbalance) shrinks. Encoded in the down item's m field:
// m < 14 = full item; m = DSPLIT_BASE + 2*mtile + khalf = split half. Same 2-tile stage layout.
#define DSPLIT_BASE 16
#ifndef DSPLIT_CHUNKS
#define DSPLIT_CHUNKS 8
#endif
static_assert(DSPLIT_CHUNKS >= 0 && DSPLIT_CHUNKS <= 16, "main.cpp reserves 14*16 extra queue entries");
// Tail K-QUARTER split (MOE_DQUART, NCH=128 full-mega bands = small T): the down items of the LAST
// DQUART_CHUNKS chunks are queued as four K-quarters each (K = 512, 8 K-slices; 4x the items of an
// unsplit chunk), so the very last claimed items are a quarter as long and the per-cluster end spread
// shrinks further. m = DQUART_BASE + 4*mtile + kquarter (48..103 < 128: bit 7 = gate|up flag unused).
#define DQUART_BASE 48
#ifndef DQUART_CHUNKS
#define DQUART_CHUNKS 1 // MOE_DQ1_SMALL: T<2304 LAG24 sub-band now 1 K-quarter tail chunk (was 2): 22*256+14*8+28 = 5772 = 78 x 74 clusters, like the LAG16 band
#endif
__device__ __forceinline__ int dn_mt(int m) {
return m >= DQUART_BASE ? (m - DQUART_BASE) >> 2 : (m >= DSPLIT_BASE ? (m - DSPLIT_BASE) >> 1 : m);
}
__device__ __forceinline__ int dn_k0(int m) {
return m >= DQUART_BASE ? ((m - DQUART_BASE) & 3) * (INTER / BK / 4)
: (m >= DSPLIT_BASE ? ((m - DSPLIT_BASE) & 1) * (INTER / BK / 2) : 0);
}
__device__ __forceinline__ int dn_kit(int m) {
return m >= DQUART_BASE ? INTER / BK / 4 : (m >= DSPLIT_BASE ? INTER / BK / 2 : INTER / BK);
}
// K-slice rotation (MOE_KROT): every work item walks its K-slices starting at an item-dependent EVEN
// offset rot (wrapping), instead of all items starting at slice 0. Concurrent items of different
// clusters then read different 128-B column offsets of their (14 KB / 4 KB strided) weight rows, so
// the low address bits of the GPU-wide request stream are no longer identical across CTAs (equal-length
// items started together stay in near lockstep). Even offsets keep the 256-B L2 promotion pairs
// (slices 2j, 2j+1) together. Every role (both weight producers, token loader, Hs TMA, prologue L2
// prefetch) uses the same rotated slice for loop iteration k; the MMA's accumulate flag still uses the
// loop index, so the K sum is just reordered (fp32 accumulation).
#ifndef MOE_KROT
#define MOE_KROT 1
#endif
#ifndef MOE_TOKE0
#define MOE_TOKE0 1 // DYNT128 token loader: wait the acc0-half commit when the units' last user is older
#endif
#ifndef MOE_KMUL
#define MOE_KMUL 38
#endif
#ifndef MOE_KCID
#define MOE_KCID 0
#endif
#ifdef MOE_KPROBE
__device__ int g_kmul = MOE_KMUL, g_kcid = MOE_KCID; // probe build: runtime-settable
#define KMUL_V ((unsigned)g_kmul)
#define KCID_V ((unsigned)g_kcid)
#else
#define KMUL_V ((unsigned)MOE_KMUL)
#define KCID_V ((unsigned)MOE_KCID)
#endif
__device__ __forceinline__ int krot(int e, int mfield, int c, int kit, int cid) {
if (!MOE_KROT) return 0;
const bool gk = kit == HID / BK;
const unsigned h = ((unsigned)e * 8u + (unsigned)mfield) * (gk ? KMUL_V : 38u) + (unsigned)c * 6u +
(gk ? (unsigned)cid * KCID_V : 0u);
return (int)(gk ? h % (unsigned)(HID / BK) : (h & (unsigned)(kit - 1))) & ~1;
}
__device__ __forceinline__ int krot_k(int k, int rot, int kit) { const int r = k + rot; return r >= kit ? r - kit : r; }
#ifndef MOE_PUBAGG_GU
#define MOE_PUBAGG_GU 1
#endif
#ifndef MOE_LATE_CLAIM
#define MOE_LATE_CLAIM 1
#endif
#ifndef MOE_LPT2
#define MOE_LPT2 1
#endif
#ifndef MOE_DQ_STATIC_W
#define MOE_DQ_STATIC_W 4
#endif
static_assert(MOE_DQ_STATIC_W >= 1, "static head >= 1");
#ifndef MOE_DNU176
#define MOE_DNU176 49 // NCH=176 DYNTOK ring units (see MOE_DNU49); 49 = max that fits the opt-in smem
#endif
#define IRING 8 // depth of the per-cluster dynamic item ring (DQ variants)
#define DDONE_TARGET (DN_MT * 2 * EPI_WARPS) // 14 down tiles x 2 CTAs x 8 epilogue warps
// ------------------------------------------------- in-kernel routing (megakernel prologue)
// Persistent cross-call state (zero-initialized at module load, never freed):
// g_moe_bar[v]: monotonic ticket counter of the grid barrier of megakernel variant v (each
// variant always launches the same grid, so generations stay aligned; reset-free).
// g_moe_cnt[e]: global per-expert histogram; re-zeroed by CTA 0 after the 2nd grid barrier
// (all CTAs have read it by then), so the next launch starts from zero.
// one counter PER TEMPLATE INSTANTIATION (NCH x ALT x CPX x DQ x NSW): the ticket scheme requires
// every launch on a counter to use the same grid size, which is only guaranteed per variant
#define MOE_NBAR 512
// 64-bit tickets: a 32-bit counter would wrap after ~14.5M calls, and since 2^32 is not a multiple
// of the grid size the generation boundaries (t - t % G) would then misalign -> deadlock.
// MOE_GRIDCAP: a capped (smaller) grid of the same variant gets its own counter bank (slot =
// (full grid - capped grid) / 2 < MOE_NBAR_SLOTS), since the ticket scheme needs a fixed grid per counter
#define MOE_NBAR_SLOTS 16
__device__ unsigned long long g_moe_bar[MOE_NBAR * MOE_NBAR_SLOTS];
// gu_only (large-T) path: epoch of the last call whose routing is complete (done[]/num_items[2]
// reset and valid). Written by CTA 0 after the routing grid barriers; polled by the wait kernel.
__device__ unsigned int g_route_ep[3]; // [0] routing epoch, [1] MOE_MKFILL down-args epoch, [2] MOE_LPTGATE b1c1-started epoch
#define g_route_epoch g_route_ep[0]
// MOE_OUTSLOT: out pointer of the current gu_only call (read by the CUTLASS down epilogue)
__device__ __nv_bfloat16* g_out_slot;
// MOE_PTRBLK (MIX graph miss path): per-call input/output pointers {hidden, ids, ew, out}, written by the host
// with ONE cuStreamBatchMemOp (4 front-end 64-bit write-value ops, values captured at enqueue) right before
// the cached graph's launch; a megakernel launched with knob bit 17 reads its pointers from here instead of
// its kernel parameters -> no cudaGraphExecKernelNodeSetParams (and no argument-pack rebuild) per fresh call.
__device__ unsigned long long g_ptr_blk[4];
__device__ __align__(16) int g_moe_cnt[NEXP];
#ifdef MOE_TLPROBE
__device__ unsigned long long g_tlk[4]; // [0] first gu CTA exit [1] last gu CTA exit [2] first gu CTA entry
void moe_tl_k(unsigned long long* h, bool reset) {
if (reset) { unsigned long long z[4] = {~0ull, 0, ~0ull, 0}; cudaMemcpyToSymbol(g_tlk, z, sizeof z); }
else cudaMemcpyFromSymbol(h, g_tlk, 32);
}
#endif // 16-B aligned: MOE_CNTREG int4 reads
// Grid-wide barrier for a fully co-resident persistent grid (ticket / generation scheme).
// MOE_RGRP (routing warp group): the in-kernel routing runs on the 4 non-epilogue warps only
// (warps 0, 1, 6 and the token-loader warp; 128 threads) and synchronizes with named barrier 8
// instead of __syncthreads. The epilogue warps issue the early out zero stores and do NOT join
// these barriers, so the grid-barrier release RMWs (cumulative over the writes ordered before them
// by the CTA barrier) no longer have to wait for this CTA's ~200 KB of in-flight zero stores
//. The zero stores
// are still published by each epilogue warp's own red.release on the zero counter.
__device__ __forceinline__ void route_sync(int rnt) { asm volatile("bar.sync 8, %0;" ::"r"(rnt) : "memory"); }
__device__ __forceinline__ unsigned long long grid_barrier(unsigned long long* bar, int rnt) {
unsigned long long tgt_out = 0;
route_sync(rnt);
if (threadIdx.x == 0) {
// fence audit: release-RMW ticket (cumulative over the CTA's writes/atomics ordered by the
// __syncthreads above) replaces __threadfence + relaxed atomicAdd
const unsigned long long G = gridDim.x;
unsigned long long t;
asm volatile("atom.add.release.gpu.global.u64 %0, [%1], 1;" : "=l"(t) : "l"(bar) : "memory");
const unsigned long long target = t - t % G + G; // end of this barrier generation
tgt_out = target;
unsigned long long v;
while (true) {
asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(bar) : "memory");
if (v >= target) break;
// MOE_BSPIN: tight acquire spin (no nanosleep): every CTA leaves the routing barriers on the
// first poll after the last arrival (148 pollers, 2 barriers per call: L2 load traffic only)
}
// (fence audit: trailing __threadfence dropped -- the ld.acquire.gpu + __syncthreads already
// order every thread's later reads after the other CTAs' released writes)
}
route_sync(rnt);
return tgt_out; // meaningful in thread 0 only
}
// Split-phase grid barrier (MOE_ROUTE1B): arrive (thread 0, after a __syncthreads, release-RMW
// ticket) returns the generation end; consumers that need other CTAs' writes wait (acquire) lazily.
__device__ __forceinline__ unsigned long long grid_arrive(unsigned long long* bar) {
const unsigned long long G = gridDim.x;
unsigned long long t;
asm volatile("atom.add.release.gpu.global.u64 %0, [%1], 1;" : "=l"(t) : "l"(bar) : "memory");
return t - t % G + G;
}
__device__ __forceinline__ void grid_wait(const unsigned long long* bar, unsigned long long target) {
unsigned long long v;
while (true) {
asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(bar) : "memory");
if (v >= target) break;
// MOE_LAZYSLEEP: lazy (off-critical-path) routing-generation pollers back off between polls
// (fewer spinning acquire loads on one L2 line from up to 3 warps x 148 CTAs during the scatter)
__nanosleep(32);
}
}
// Counting sort of the S = T*8 assignments by expert + work-queue build, done cooperatively by
// all CTAs (all 192 threads each). CTA b owns assignments [b*C, min(S,(b+1)*C)).
// pass 1: smem histogram of the CTA's assignments (local rank of each kept in smem);
// atomicAdd(g_moe_cnt[e], local count) returns this CTA's base offset inside expert e.
// grid barrier 1 -> g_moe_cnt holds the totals; every CTA scans them redundantly (256 entries).
// pass 2: sorted_slot[start[e] + base[e] + local rank] = assignment.
// CTA 0 cuts the experts into chunks and writes the queue item_info[] (expert-major, same
// order as before: step s = [8 gate|up items of chunk s][14 down items of chunk s-LAG]),
// zeroes done[] and the out-zeroed counter. grid barrier 2 -> everything visible.
// `scratch` = dynamic smem (the stage ring is unused until routing finishes).
// first: (MOE_FIRSTLOCAL) this cluster's FIRST queue item (index cid), computed locally from the
// replicated counts after grid barrier 1 -- exact, no speculation -- or x = -1 if not derivable.
struct RouteRes { int num_items; unsigned long long tgt; int4 first; };
__device__ __forceinline__ RouteRes route_in_kernel(int* scratch, const long long* __restrict__ ids, int S, int C,
int4* __restrict__ item_info, int* __restrict__ done,
int* __restrict__ num_items, int* __restrict__ sorted_slot,
int NCHUNK, int LAG, unsigned long long* bar, int gu_only,
int* __restrict__ inv, int gmt, int* __restrict__ cnt_out,
int2* __restrict__ meta, const __nv_bfloat16* __restrict__ ew, int rtid, int rnt) {
// gmt = gate|up items per chunk (8 swapped 256-feature tiles; 16 non-swapped 128-feature slices)
int* lcnt = scratch; // [256] local histogram
int* gbase = scratch + NEXP; // [256] this CTA's base offset within each expert
int* st = scratch + 2 * NEXP; // [256] exclusive scan of the totals
int* cnt = scratch + 3 * NEXP; // [256] totals
int* le = scratch + 4 * NEXP; // [C] expert of each owned assignment
int* lr = le + C; // [C] local rank of each owned assignment
int* cst = lr + C; // [257] first chunk id of each expert (+ total)
// MOE_EWPRE: routing weight (bf16 bits) of each owned assignment, loaded in pass 1 together with
// its expert id (independent loads in flight before grid barrier 1), so the full-path scatter no
// longer issues a dependent cold DRAM load of expert_weights between the two grid barriers
int* lw = cst + NEXP + 1; // [C]
const int tid = rtid, nt = rnt; // MOE_RGRP: routing-group thread index / size
const int cbeg = blockIdx.x * C;
const int cend = min(S, cbeg + C);
for (int i = tid; i < NEXP; i += nt) lcnt[i] = 0;
route_sync(nt);
// MOE_ROUTEVEC (routing audit): pass 1 reads the CTA's expert ids as 16-B pairs (longlong2) and
// the routing weights as 4-B bf16 pairs (half the load instructions / L2 requests of the scalar
// loop, all loads issued before the smem atomics); scalar head/tail for odd / misaligned bounds.
{
const bool vec = ((cbeg & 1) == 0) && ((reinterpret_cast<uintptr_t>(ids) & 15) == 0) &&
((reinterpret_cast<uintptr_t>(ew) & 3) == 0);
int a_scalar = cbeg;
if (vec) {
const int npair = (cend - cbeg) >> 1;
const longlong2* ids2 = reinterpret_cast<const longlong2*>(ids + cbeg);
const unsigned int* ew2 = reinterpret_cast<const unsigned int*>(ew + cbeg);
for (int j = tid; j < npair; j += nt) {
const longlong2 e2 = __ldg(ids2 + j);
const int e0 = (int)e2.x, e1 = (int)e2.y;
if (meta) {
const unsigned int w2 = __ldg(ew2 + j);
lw[2 * j] = (int)(w2 & 0xFFFFu);
lw[2 * j + 1] = (int)(w2 >> 16);
}
le[2 * j] = e0;
le[2 * j + 1] = e1;
lr[2 * j] = atomicAdd(&lcnt[e0], 1);
lr[2 * j + 1] = atomicAdd(&lcnt[e1], 1);
}
a_scalar = cbeg + 2 * npair;
}
for (int a = a_scalar + tid; a < cend; a += nt) {
const int e = (int)__ldg(ids + a);
if (meta) lw[a - cbeg] = (int)__ldg(reinterpret_cast<const unsigned short*>(ew) + a);
le[a - cbeg] = e;
lr[a - cbeg] = atomicAdd(&lcnt[e], 1);
}
}
route_sync(nt);
for (int e0 = tid; e0 < NEXP; e0 += 2 * nt) {
const int e1 = e0 + nt;
const int c0 = lcnt[e0], c1 = e1 < NEXP ? lcnt[e1] : 0;
int r0 = 0, r1 = 0;
asm volatile("{\n .reg .pred p;\n setp.ne.s32 p, %2, 0;\n @p atom.relaxed.gpu.global.add.u32 %0, [%1], %2;\n}\n"
: "+r"(r0) : "l"(g_moe_cnt + e0), "r"(c0) : "memory");
asm volatile("{\n .reg .pred p;\n setp.ne.s32 p, %2, 0;\n @p atom.relaxed.gpu.global.add.u32 %0, [%1], %2;\n}\n"
: "+r"(r1) : "l"(g_moe_cnt + (e1 < NEXP ? e1 : e0)), "r"(c1) : "memory");
gbase[e0] = r0;
if (e1 < NEXP) gbase[e1] = r1;
}
// MOE_ROUTE1B: the per-chunk counters done[] (all 2*max_chunks entries, max_chunks = 256 + S/NCHUNK + 1
// as allocated by main.cpp) and the out-zeroed / DQ-claim counters are reset BEFORE grid barrier 1
// (ordered before every later use by the barrier), so the post-scatter phase needs no full barrier.
{
const int nd = 2 * (NEXP + S / NCHUNK + 1);
for (int i = blockIdx.x * nt + tid; i < nd; i += gridDim.x * nt) done[i] = 0;
if (blockIdx.x == 0 && tid == 0) { num_items[1] = 0; num_items[3] = 0; }
}
const unsigned long long tgt1 = grid_barrier(bar, nt); PROF(if (threadIdx.x == 0) g_prof[blockIdx.x * PROF_N + 17] = gtime();)
// MOE_CNTREG (routing head diet): the scan warp reads its lane's 8 totals straight from global into
// registers (two 16-B __ldcg, ordered after thread 0's barrier acquire by grid_barrier's trailing
// CTA barrier) and publishes them to smem cnt[] itself -- the 128-thread scalar cnt load loop and
// one CTA barrier between it and the scan are gone (cnt[] is next read after the post-scan barrier).
// MOE_ROUTESCAN1 (routing instruction diet): ONE warp section computes BOTH exclusive scans (token
// counts -> st[], chunk counts -> cst[]) from a single register copy of the lane's 8 counts, plus the
// locally derived first item; the second warp section and its __syncthreads after the scatter are gone
// (the scatter does not read cst / first_s; the queue build is ordered by the barrier below).
if (tid < 32) {
int cl[8], loc[8], lch[8], s = 0, sc = 0;
{
const int4 c0 = __ldcg(reinterpret_cast<const int4*>(g_moe_cnt) + 2 * tid);
const int4 c1 = __ldcg(reinterpret_cast<const int4*>(g_moe_cnt) + 2 * tid + 1);
cl[0] = c0.x; cl[1] = c0.y; cl[2] = c0.z; cl[3] = c0.w; cl[4] = c1.x; cl[5] = c1.y; cl[6] = c1.z; cl[7] = c1.w;
reinterpret_cast<int4*>(cnt)[2 * tid] = c0;
reinterpret_cast<int4*>(cnt)[2 * tid + 1] = c1;
// gu_only: CTA 0 exports the per-expert counts for the down-GEMM arg-fill kernel (visible after
// the 2nd grid barrier + CTA 0's release of g_route_epoch)
if (cnt_out && blockIdx.x == 0) {
#pragma unroll
for (int j = 0; j < 8; ++j) cnt_out[tid * 8 + j] = cl[j];
}
}
#pragma unroll
for (int j = 0; j < 8; ++j) {
loc[j] = s; s += cl[j];
lch[j] = sc; sc += (cl[j] + NCHUNK - 1) / NCHUNK;
}
int inc = s, incc = sc;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const int v = __shfl_up_sync(0xffffffff, inc, o), vc = __shfl_up_sync(0xffffffff, incc, o);
if (tid >= o) { inc += v; incc += vc; }
}
const int b0 = inc - s, b0c = incc - sc;
#pragma unroll
for (int j = 0; j < 8; ++j) { st[tid * 8 + j] = b0 + loc[j]; cst[tid * 8 + j] = b0c + lch[j]; }
if (tid == 31) cst[NEXP] = incc; // total chunks
// MOE_FIRSTLOCAL (full path only): queue positions [0, gmt*min(LAG, NC)) are exactly the gate|up
// items of chunks c < LAG at gmt*c + m (route queue build below). The cluster's first item is
// position cid -> chunk fc = cid/gmt, m-tile cid%gmt; its expert / row0 / n follow from cnt, st,
// cst (all replicated in this CTA's smem), so the leader producer can publish it and start the
// weight stream without waiting for grid barrier 2 + an item_info L2 round trip.
int4* first_s = reinterpret_cast<int4*>(scratch + 4); // lcnt[4..7] (dead after barrier 1)
if (tid == 0) *first_s = make_int4(-1, 0, 0, 0);
__syncwarp();
const int fcid = (int)(blockIdx.x >> 1), fc = fcid / gmt;
// MOE_FIRSTLOCAL_GU: gu_only (MIX) queue position p = gmt*chunk + m as well (queue = gate|up items
// only, expert-major) except the MOE_LPT2-reordered batch-1 experts of the NCH>=240 band; the
// first item is derived locally whenever its chunk belongs to an expert outside that reordered range.
const int sp0f = (gu_only && NCHUNK >= 240) ? MOE_SPLIT0_W : MOE_SPLIT0;
const bool lptf = MOE_LPT2 && gu_only && NCHUNK >= 240;
if (gu_only || fc < LAG) {
#pragma unroll
for (int j = 0; j < 8; ++j) {
const int e = tid * 8 + j, ce = cl[j];
const int c0e = b0c + lch[j], nce = (ce + NCHUNK - 1) / NCHUNK;
if (fc >= c0e && fc < c0e + nce && !(lptf && e >= sp0f) && !(gu_only && nce > 1)) {
const int i = fc - c0e;
*first_s = make_int4(e, b0 + loc[j] + i * NCHUNK, min(NCHUNK, ce - i * NCHUNK), (fc << 8) | 128 | (fcid % gmt));
}
}
}
}
route_sync(nt);
for (int a = cbeg + tid; a < cend; a += nt) {
const int e = le[a - cbeg];
const int p = st[e] + gbase[e] + lr[a - cbeg];
sorted_slot[p] = a;
// full path: per-row down-epilogue metadata {out row element offset, bf16x2-splatted routing
// weight}, built once here so each down item's epilogue does ONE 8-B load per token instead of
// the dependent sorted_slot -> expert_weights chain (14 down items re-read it per chunk)
if (meta) {
const uint32_t wb = (uint32_t)lw[a - cbeg];
meta[p] = make_int2((int)((uint32_t)(a >> 3) * HID), (int)((uint32_t)wb | ((uint32_t)wb << 16)));
}
// (MOE_NOINV: the dead inv[a] = p scatter of the gu_only path is gone -- the fused CUTLASS down
// epilogue reads sorted_slot; inv was only used by the removed top-8 reduce kernel)
(void)inv;
}
route_sync(nt);
{
const int NC = cst[NEXP];
const int ipc = gu_only ? gmt : gmt + DN_MT; // queue entries per chunk
// first split chunk: the last min(LAG, DSPLIT_CHUNKS) chunks (all inside the trailing region c >= NC-LAG)
// MOE_DSPLIT16_176: the NCH=176 band (T~3719) K-splits ALL last LAG (16) chunks' down items into halves (<= 14*16 reserved entries)
const int dspl = NCHUNK == 176 ? 16 : ((NCHUNK == 192 || NCHUNK == 160) ? 10 : DSPLIT_CHUNKS); // MOE_DSPLIT10_192: probe between 8 and 12
const int cs = gu_only ? NC : max(0, NC - min(LAG, dspl));
// first K-quarter chunk (NCH=128 full path only): the last DQUART_CHUNKS of the split chunks
const int cq = (gu_only || NCHUNK != 128) ? NC : max(cs, NC - (LAG < 24 ? 1 : DQUART_CHUNKS)); // MOE_WAVE148: n128_dq band (LAG 16, T~2600-3000): 1 K-quarter chunk -> 22*256 + 14*8 + 28 = 5772 items = 39 x 148 CTAs (78 per cluster)
// expert batch split of the MIX path (must match main.cpp split0): the NCH>=240 band (T~6144)
// splits at MOE_SPLIT0_W (192) so less down work is serialized after the gate|up kernel
const int sp0 = (gu_only && NCHUNK >= 240) ? MOE_SPLIT0_W : MOE_SPLIT0;
for (int e = blockIdx.x; e < NEXP; e += gridDim.x) {
const int ce = cnt[e];
const int nce = (ce + NCHUNK - 1) / NCHUNK; // chunks of this expert
const int c0 = cst[e];
// MOE_LPT2 (gu_only NCH=256 band = T6144): the queue TAIL (chunks of experts [128,256)) is
// ordered by expert token count, largest first (LPT), so the last claimed items are the
// shortest ones and the per-cluster end spread shrinks before the batch-1 down GEMM starts.
// Only queue POSITIONS change (chunk ids c, done[], row0 unchanged); positions stay inside
// the half's range [cst[128], cst[256]), so the batch-0 wait and the prefetch guess hold.
int qc0 = c0;
if (MOE_LPT2 && gu_only && NCHUNK >= 240 && e >= sp0) {
int s = 0;
for (int j = (tid & 31); j < NEXP - sp0; j += 32) {
const int e2 = sp0 + j, c2 = cnt[e2];
if (c2 > ce || (c2 == ce && e2 < e)) s += (c2 + NCHUNK - 1) / NCHUNK;
}
s = __reduce_add_sync(0xffffffffu, s);
qc0 = cst[sp0] + s;
}
// full path: chunks c >= cs (last nspl chunks, trailing pure-down region) get 2*DN_MT split items
// (K-quarter chunks c >= cq: 4*DN_MT items)
const int ipc2 = gu_only ? ipc : ipc + ((cq < NC) ? 3 * DN_MT : DN_MT);
for (int idx = tid; idx < nce * ipc2; idx += nt) {
const int i = idx / ipc2, m = idx - i * ipc2;
if (!gu_only && m >= ipc && c0 + i < cs) continue; // unsplit chunk: only ipc entries
if (!gu_only && m >= ipc + DN_MT && c0 + i < cq) continue; // K-half chunk: ipc + DN_MT entries
const int c = c0 + i;
const int row0 = st[e] + i * NCHUNK;
const int n = min(NCHUNK, ce - i * NCHUNK);
// Power-smoothing interleave (full path, gmt == 8): inside a full queue step s (8 gate|up
// items of chunk s + 14 down items of chunk s-LAG, step base gmt*s + DN_MT*(s-LAG)) the
// gate|up items sit at offsets (m*22)/8 = 0,2,5,8,11,13,16,19 and the down items fill the
// rest in order, so consecutive claims alternate item kinds instead of 8-GU / 14-down runs.
// Dependencies unchanged: down items of chunk s-LAG only wait on gate|up items of earlier steps.
constexpr int SPC = GU_MT + DN_MT;
auto gpos = [](int mm) { return (mm * SPC) / GU_MT; };
// j-th offset of the step not taken by a gate|up item: j + 1 + (# gate|up offsets past the
// first before it) = 1,3,4,6,7,9,10,12,14,15,17,18,20,21 -- 3-bit packed table (was a 22-trip loop)
auto dpos = [](int j) {
constexpr unsigned long long DT3 = 0ull | (0ull << 0) | (1ull << 3) | (1ull << 6) | (2ull << 9) |
(2ull << 12) | (3ull << 15) | (3ull << 18) | (4ull << 21) | (5ull << 24) | (5ull << 27) |
(6ull << 30) | (6ull << 33) | (7ull << 36) | (7ull << 39);
return j + 1 + (int)((DT3 >> (3 * j)) & 7ull);
};
const bool ilv = !gu_only && gmt == GU_MT;
if (m < gmt) {
// gu_only: queue = gmt gate|up items per chunk, no down items (CUTLASS down GEMM follows)
if (ilv && c >= LAG) {
const int sb = gmt * c + DN_MT * (c - LAG);
item_info[sb + gpos(m)] = make_int4(e, row0, n, (c << 8) | 128 | m);
} else if (gu_only) {
// MOE_SPLITLOCK (gu_only MIX path, energy): the chunks of a SPLIT expert (nce > 1, T5120 band:
// ~1.5 experts/call overflow 192) are queued m-tile-major (chunk i of m-tile m at m*nce + i), so
// the items streaming the same 7.3 MB of gate|up weight rows are claimed back-to-back by
// different clusters and -- with the chunk term dropped from the gu_only K rotation -- walk the
// same K slices concurrently: the second reader hits L2 instead of re-streaming ~58 MB from DRAM.
// nce == 1: unchanged position gmt*qc0 + m.
item_info[gmt * qc0 + m * nce + i] = make_int4(e, row0, n, (c << 8) | 128 | m);
} else {
const int gub = gmt * c + DN_MT * max(0, c - LAG);
item_info[gub + m] = make_int4(e, row0, n, (c << 8) | 128 | m);
}
} else if (!gu_only && c >= cq) {
// K-quarter chunk (queue end): 4*DN_MT items, the four quarters of an m-tile adjacent
const int j = m - gmt;
const int db = gmt * NC + DN_MT * cs + 2 * DN_MT * (cq - cs) + 4 * DN_MT * (c - cq);
item_info[db + j] = make_int4(e, row0, n, (c << 8) | (DQUART_BASE + j));
} else if (!gu_only && c >= cs) {
// split chunk (trailing region): 2*DN_MT K-half items, the two halves of an m-tile adjacent
const int j = m - gmt;
const int db = gmt * NC + DN_MT * cs + 2 * DN_MT * (c - cs);
item_info[db + j] = make_int4(e, row0, n, (c << 8) | (DSPLIT_BASE + j));
} else {
const int s = c + LAG;
if (ilv && s < NC) {
const int sb = gmt * s + DN_MT * c;
item_info[sb + dpos(m - gmt)] = make_int4(e, row0, n, (c << 8) | (m - gmt));
} else {
const int db = s < NC ? gmt * s + DN_MT * c + gmt : gmt * NC + DN_MT * c;
item_info[db + m - gmt] = make_int4(e, row0, n, (c << 8) | (m - gmt));
}
}
}
}
if (blockIdx.x == 0 && tid == 0) {
*num_items = ipc * NC + (gu_only ? 0 : DN_MT * (NC - cs) + 2 * DN_MT * (NC - cq));
// [2] = chunks of experts [0, 128) = the first chunks of the expert-major queue (gu_only:
// the side-stream batch-0 down GEMM waits for exactly these, see moe_batch_wait_kernel)
num_items[2] = cst[sp0];
}
}
// every CTA computes the queue length itself (cnt / cst are replicated): no global read needed
int nitems_local;
{
const int NC = cst[NEXP];
const int ipc = gu_only ? gmt : gmt + DN_MT;
const int dspl = NCHUNK == 176 ? 16 : ((NCHUNK == 192 || NCHUNK == 160) ? 10 : DSPLIT_CHUNKS); // MOE_DSPLIT16_176 (same as queue build)
const int cs = gu_only ? NC : max(0, NC - min(LAG, dspl));
const int cq = (gu_only || NCHUNK != 128) ? NC : max(cs, NC - (LAG < 24 ? 1 : DQUART_CHUNKS)); // MOE_WAVE148: n128_dq band (LAG 16, T~2600-3000): 1 K-quarter chunk -> 22*256 + 14*8 + 28 = 5772 items = 39 x 148 CTAs (78 per cluster)
nitems_local = ipc * NC + (gu_only ? 0 : DN_MT * (NC - cs) + 2 * DN_MT * (NC - cq));
}
// MOE_ROUTE1B: second phase = ARRIVE only (no wait here). Roles that read other CTAs' routing
// outputs (item_info, sorted_slot, meta) wait for this generation lazily at their start.
// g_moe_cnt is reset by CTA 0 after that wait (all CTAs read it before arriving).
route_sync(nt);
unsigned long long* tslot = reinterpret_cast<unsigned long long*>(scratch); // lcnt area (dead)
// MOE_ARRIVERED (head trim): the second routing generation's target is derived locally -- barrier-1
// tickets of this launch are [tgt1 - G, tgt1); no CTA arrives at barrier 2 before barrier 1 completed and
// the next launch on this counter only arrives after this grid finished (griddepcontrol.wait), so the
// barrier-2 tickets are exactly [tgt1, tgt1 + G) -> target tgt1 + G (== what the returning atomic gave).
// The arrive itself is a non-returning red.release issued by routing thread 32 (warp 1 lane 0; its
// release is cumulative over every routing thread's scatter / queue writes ordered by the route_sync
// above), so the producer thread 0 no longer waits for the release fence + contended atomic round trip
// before publishing the first item and issuing the first weight TMAs.
if (tid == 0) { *tslot = tgt1 + (unsigned long long)gridDim.x; scratch[2] = nitems_local; }
if (tid == 32) asm volatile("red.release.gpu.global.add.u64 [%0], 1;" ::"l"(bar) : "memory");
// (MOE_RGRP: the caller reads tgt / num_items / first from scratch after a full CTA barrier,
// then fences the generic->async proxy before the stage ring is used)
RouteRes rr;
rr.tgt = 0;
rr.num_items = nitems_local;
rr.first = make_int4(-1, 0, 0, 0);
return rr;
}
// MOE_MKFILL: CUTLASS down grouped-GEMM argument fill (one warp; same arrays / order as cutpath's
// fill_down_args_kernel): lane L owns experts [8L, 8L+8); start = warp exclusive scan of the counts;
// class k = cnt > bn0; position in the (batch, class) region = # LATER experts of the same batch & class.
__device__ __forceinline__ void dnf_copy(unsigned char* dst, const unsigned int* t, int sz) {
unsigned int* d = reinterpret_cast<unsigned int*>(dst);
for (int w = 0; w < (sz >> 2); ++w) d[w] = t[w];
}
__device__ __forceinline__ void dn_fill_args(const DnFill& f, const int* cntp, int lane) {
const int bn0 = f.bn0, bn1 = f.bn1, split0 = f.split0;
constexpr int RG = 2 * 2 * NEXP; // NB * NCLS * NE regions entries
auto put = [&](int i, int ce, const __nv_bfloat16* pa, const __nv_bfloat16* pb, __nv_bfloat16* pd, int st) {
f.grow0[i] = st;
int* sh = reinterpret_cast<int*>(f.shapes + 12 * i);
sh[0] = HID; sh[1] = ce; sh[2] = INTER;
f.pA[i] = (void*)pa; f.pB[i] = (void*)pb; f.pD[i] = (void*)pd;
dnf_copy(f.sA + (size_t)f.szA * i, f.tA, f.szA);
dnf_copy(f.sB + (size_t)f.szB * i, f.tB, f.szB);
dnf_copy(f.sD + (size_t)f.szD * i, f.tD, f.szD);
};
int s = 0, n1 = 0;
#pragma unroll
for (int j = 0; j < 8; ++j) { const int cj = __ldcg(cntp + lane * 8 + j); s += cj; n1 += (cj > bn0 && cj <= bn1) ? 1 : 0; }
int inc = s;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) { const int v = __shfl_up_sync(0xffffffffu, inc, o); if (lane >= o) inc += v; }
const int L0 = split0 / 8;
int sufa = n1;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) { const int v = __shfl_down_sync(0xffffffffu, sufa, o); if (lane + o < 32) sufa += v; }
const int sufL0 = __shfl_sync(0xffffffffu, sufa, L0 & 31);
const int sufL0v = L0 < 32 ? sufL0 : 0;
const int b = lane >= L0 ? 1 : 0;
const int suf1 = b ? sufa : sufa - sufL0v;
const int tot1_b0 = __shfl_sync(0xffffffffu, sufa, 0) - sufL0v, tot1_b1 = sufL0v;
int later1 = suf1 - n1;
int later0 = 8 * ((b ? 31 : L0 - 1) - lane) - later1;
int after = 0;
const int end = inc;
#pragma unroll 1
for (int j = 7; j >= 0; --j) {
const int e = lane * 8 + j, ce = __ldcg(cntp + e);
after += ce;
const int st = end - after;
const int k = (ce > bn0 && ce <= bn1) ? 1 : 0; // MOE_DNOVF0: overflow experts -> class 0
const int pos = k ? later1++ : later0++;
const int g2i = (b * 2 + k) * NEXP + pos;
put(g2i, ce, f.dw + (size_t)e * HID * INTER, f.h + (size_t)st * INTER, f.xs + (size_t)st * HID, st);
}
for (int i = lane; i < RG; i += 32) {
const int r = i / NEXP, j = i % NEXP;
const int t1 = (r >> 1) ? tot1_b1 : tot1_b0;
const int nbe = (r >> 1) ? NEXP - split0 : split0;
const int nr = (r & 1) ? t1 : nbe - t1;
if (j >= nbe) continue;
if (j >= nr) put(i, 0, f.dw, f.h, f.xs, 0);
}
}
// ------------------------------------------------------------ megakernel (2-SM, persistent)
// Every work item = two weight tiles (A operands, 128 rows each per CTA) x one token tile
// (B operand, N/2 rows per CTA) -> two TMEM accumulators. Identical smem stage shape for
// both item kinds (2 x 16 KB weights + token half-tile), so one smem ring serves both.
// gate|up item (chunk c, m<8): tiles = gate/up rows e*2048 + m*256 + rank*128, K = 7168,
// tokens gathered from hidden_states by tile::gather4. Epilogue silu(g)*u -> Hs.
// Each epilogue warp then bumps done[c] (release).
// down item (chunk c, m<14): tiles = down rows e*7168 + m*512 + rank*128 (+256), K = 2048,
// tokens = contiguous Hs rows of the chunk (2D TMA boxes, after acquiring done[c]==64).
// Epilogue * routing weight -> red.add into out[token].
// TMEM: two 256-col buffers; items with n16<=128 use one (acc0 +0, acc1 +128) and alternate
// (epilogue of item i overlaps mainloop of item i+1); wider items use both (acc1 at +256).
// CPX = 1: the token operand of gate|up items is loaded by a dedicated token-loader warp (warp 11)
// with cp.async 16-B copies (see the warp 11 branch) instead of TMA gather4 from warp 0.
// NSW = 1 (non-swapped gate|up items, NCHUNK=256 + cp.async token loader only): a gate|up item is
// one 128-feature intermediate slice m (16 per chunk) x 256 token rows of the chunk. Tokens are the
// MMA A operand (M = 256 across the pair: CTA r holds chunk rows [128r, 128r+128) in its token slot),
// weights the B operand (N = 256: CTA 0 holds the slice's 128 GATE rows, CTA 1 the 128 UP rows, so
// each weight byte is streamed once per pair). ONE 256x256x16 MMA per K step; D (256 TMEM cols per
// CTA) = [gate 128 | up 128] for this CTA's 128 tokens (TMEM lane = token) -> the epilogue does
// SwiGLU per thread (no transpose) and stores 64 contiguous bytes of its token's Hs row per chunk.
// EW = epilogue warps (8: warps 2..5 + 7..10, each draining every other 32-col chunk; 4: warps 2..5
// only, each draining ALL 32-col chunks of its TMEM lane quadrant -- small-T variant, fewer threads).
// Token-loader warp (CPX) = warp 11 (EW 8) / warp 7 (EW 4).
// HSN = number of exact-height Hs maps passed as a kernel parameter (MOE_HSN1: gate|up-only launches
// never load Hs -> 1 placeholder map instead of NCHUNK/16 = 2 KB less launch parameter buffer)
template <int WS, int XS, int NCHUNK, int CPX, int DQ = 0, int NSW = 0, int EW = 8, int HSN = NCHUNK / 16>
__global__ void __cluster_dims__(2, 1, 1) __launch_bounds__((CPX ? 32 : 0) + 7 * 32 + (EW - 4) * 32, 1)
moe_mega_kernel(const __grid_constant__ CUtensorMap tmG, const __grid_constant__ CUtensorMap tmU,
const __grid_constant__ CUtensorMap tmD, const __grid_constant__ XMapT<CPX> tmX,
const __grid_constant__ HsMapsN<HSN> hsm,
int4* __restrict__ item_info,
int* __restrict__ num_items_ptr, int* __restrict__ done,
int* __restrict__ sorted_slot, const __nv_bfloat16* __restrict__ ew,
__nv_bfloat16* __restrict__ hs, __nv_bfloat16* __restrict__ out, int lag, int out_vec,
const long long* __restrict__ ids, int S, int RC, int bar_idx, int xpol,
const __nv_bfloat16* __restrict__ hidden, int gu_only_arg, int* __restrict__ inv,
unsigned int epoch, int h64, int* __restrict__ cnt_out,
int2* __restrict__ meta, const __grid_constant__ DnFill dnf) {
constexpr bool GUO = (HSN == 1);
const int gu_only = GUO ? 1 : gu_only_arg;
constexpr bool R3 = (EW == 4 && NCHUNK == 128 && HSN != 1 && !NSW);
constexpr int ACC_BUFS = R3 ? 3 : 2;
const bool r3on = R3 && !((xpol >> 16) & 1);
struct AccPlan { int s0, s1; uint32_t o0, o1; };
auto acc_plan = [&](int n16, bool nsw_, uint32_t& ring) -> AccPlan {
AccPlan p;
if (R3 && r3on) {
constexpr uint32_t SUCC = 0x09u; // [1, 2, 0]
constexpr uint32_t NXT2 = 0x12u; // [2, 0, 1]
const bool two = n16 > 80;
const uint32_t r = ring, sh = 2u * r;
const uint32_t s1 = (SUCC >> sh) & 3u;
p.s0 = (int)r;
p.s1 = two ? (int)s1 : -1;
p.o0 = r * 160u;
p.o1 = two ? s1 * 160u : p.o0 + 80u;
ring = ((two ? NXT2 : SUCC) >> sh) & 3u;
} else {
const bool wide = !nsw_ && (n16 > 128);
if (wide) { p.s0 = 0; p.s1 = 1; p.o0 = 0; p.o1 = 256; }
else { p.s0 = (int)ring; p.s1 = -1; p.o0 = ring * 256u; p.o1 = p.o0 + 128u; ring ^= 1u; }
}
return p;
};
constexpr uint32_t W_BYTES = BM * BK * 2; // 16 KB weight tile (per CTA)
constexpr uint32_t X_BYTES = (NCHUNK / 2) * BK * 2; // token half-tile (max, per CTA): 8/12/16 KB
constexpr uint32_t WSTAGE = 2 * W_BYTES; // weight stage: 2 tiles (32 KB per CTA)
constexpr int STAGES = WS; // barrier sets follow the weight ring
constexpr int TLAG = WS - XS; // token loads trail weights by TLAG iters
// MOE_WT11 (NCH=176 full-mega band = T~3719 only): TILE-granular weight ring. The weight smem is a
// ring of WT 16-KB tile slots (WT = 2*WS-1 = 11) instead of WS 32-KB stages; tile j = 2*it + t
// (t = 0 gate/down-half-0, 1 up/down-half-1) lives in slot j % WT. Barriers stay per iteration
// (WS = 6 sets). Slot reuse: tile 0 of iteration it overwrites tile 1 of it-WS (wait MMA(it-WS),
// as before); tile 1 overwrites tile 0 of it-(WS-1) (warp 6 waits MMA(it-WS+1)). This frees one
// tile (16 KB) so the band gets WS6 barrier depth (5.5-stage weight lead) AND 4 token slots
// (smem 11x16 + 4x11 KB = 220 KB + extra, vs WS6/XS4 = 236 KB > 227 KB opt-in limit).
// MOE_WT11_GU192: the T5120 gate|up-only band (NCH=192, HSN == 1) uses the same tile-granular ring
// (WS6 barrier stages / 11 weight tile slots / XS4 token slots, host launch_mega) -- was WS5/WT10/XS5
// MOE_WT9_GU256 (T6144 gate|up-only band, NCH=256): odd tile ring too -- WS5 barrier stages / 9 weight tile
// slots, freeing one 16 KB tile for a 5th token slot (XS5, TLAG 0; host launch_mega)
constexpr int WT = ((NCHUNK == 176 && HSN != 1 && !NSW) || (NCHUNK == 192 && HSN == 1 && !NSW) ||
(NCHUNK == 256 && HSN == 1 && !NSW)) ? 2 * WS - 1 : 2 * WS;
constexpr int L1 = (WT == 2 * WS) ? WS : WS - 1; // tile-1 slot reuse distance (iterations)
constexpr bool SPLITF = (NCHUNK == 176 && HSN != 1 && !NSW);
// MOE_E0REL (gate|up-only MIX launches = T5120 / T6144 bands): PER-TILE early release of weight tile 0.
// The MMA issues the 4 acc0 (tile 0) MMAs of a stage, commits them to a per-stage empty0_bar, then the
// 4 acc1 MMAs and the usual empty_bar commit. The producer that refills tile 0's slot waits empty0:
// WT == 2*WS (T6144 band): tile 0 of stage s+WS reuses tile 0's slot -> warp 0 waits empty0(it-WS).
// MOE_WT11 ring (T5120 band, WT = 2*WS-1): tile 1 of iteration it reuses the slot of tile 0 of
// it-L1 -> warp 6 waits empty0(it-L1); warp 0 (tile 0 reuses tile 1 of it-WS) keeps empty_bar.
// Phase safety: empty0(q) implies MMA(q) passed full_bar phase q (hence all earlier phases).
// MOE_E0REL_FULL: also the full-megakernel bands with a stage-granular weight ring (NCH=128 / 192,
// WT == 2*WS; gate|up AND down items both use tile 0 -> acc0 only): warp 0 refills tile 0 of stage s
// as soon as the MMA's acc0 half of that stage has committed (empty0), half a stage earlier.
constexpr bool E0REL = !NSW && !SPLITF;
constexpr bool E0W0 = E0REL && (WT == 2 * WS); // warp 0 waits empty0
constexpr bool E0W6 = E0REL && (WT != 2 * WS); // warp 6 waits empty0
// MOE_HSLDR (full-mega NCH=128 bands, cp.async token loader): the down items' Hs token TMA is issued by
// the token-loader warp instead of weight producer warp 0. The loader already waits the slot's
// full-stage empty_bar(it-XS) commit for every stage (token-slot reuse proof incl. acc1 MMAs) and walks
// the same item / rotated K sequence, so warp 0 becomes a pure tile-0 weight producer: neither the
// done[] dependency wait of a down item nor the E0SAFE empty_bar wait stalls the weight stream any more.
// Completion bytes still land on the leader's full_bar (armed by warp 0's expect_tx of the same phase;
// the complete_tx may precede the expect_tx -- the phase cannot complete before warp 0's arrival).
// MOE_HSLDR_ALL: every full-mega cp.async band (NCH 128 / 160 / 176 / 192, incl. the SPLITF T3719 band)
constexpr bool HSLDR = CPX && !GUO && !NSW;
constexpr bool W0SOLO = CPX && !NSW && (HSLDR || GUO);
// MOE_DYNTOK176: also the NCH=176 full-mega band (T~3719; WT11 tile ring, SPLITF, XS4 x 11 KB = 44 units);
// units >= 32 are tracked by a second per-lane register (unit lane + 32).
constexpr bool DYNT176 = CPX && !GUO && !NSW && NCHUNK == 176 && EW == 8;
constexpr bool DYNT = (CPX && !GUO && !NSW && NCHUNK == 128 && EW == 4 && WT == 2 * WS) || DYNT176;
constexpr bool DNDIR = DYNT && !DYNT176 && NCHUNK == 128 && HSLDR;
constexpr int DNU = DYNT176 ? MOE_DNU176 : (DYNT ? XS * (NCHUNK / 16) : 1); // token ring units (1 KB each)
static_assert(!DYNT176 || DNU >= XS * (NCHUNK / 16), "176 ring at least the slot area");
static_assert(!DYNT || DNU <= 64, "at most two ring units per loader lane");
static_assert(XS >= 1 && XS <= WS, "token ring no deeper than the weight ring");
constexpr int KIT_GU = HID / BK, KIT_DN = INTER / BK;
static_assert(NCHUNK / 2 <= 128, "gather4: one 4-row group per producer lane");
static_assert((NCHUNK / 2) % XBOX == 0 || (CPX && (NCHUNK / 2) % 8 == 0), "token tile: whole 32-row boxes (gather4) / 16-row groups (cp.async loader, NCH=160)");
static_assert(!NSW || (NCHUNK == 256 && CPX), "non-swapped gate|up: 128-row token slots, cp.async loader");
constexpr int GMT = NSW ? 2 * GU_MT : GU_MT; // gate|up items per chunk
static_assert(EW == 8 || (EW == 4 && !NSW), "4-epilogue-warp variant: swapped items only");
constexpr int EPI_W = EW, EPI_T = EW * 32; // epilogue warps / threads per CTA
constexpr int CSTEP = EW == 8 ? 64 : 32; // column stride between a warp's 32-col chunks
constexpr int TOKW = EW == 8 ? 11 : 7; // token-loader warp index (CPX)
constexpr int DDT = DN_MT * 2 * EW; // done[2c+1] target: all down epilogue warps
constexpr int DT = GMT * 2 * EPI_W; // done[2c] target: all gate|up epilogue warps
extern __shared__ uint8_t smem_raw[];
// manual 1024-B alignment (required by the 128B swizzle atom); identical in both CTAs
const uint32_t raw_addr = smem_u32(smem_raw);
const uint32_t base = (raw_addr + 1023u) & ~1023u;
uint8_t* smem = smem_raw + (base - raw_addr);
// smem: [WS weight stages][XS token slots][barriers][tmem slot]
const uint32_t xbase = base + WT * W_BYTES;
const uint32_t bar_base = xbase + (DYNT176 ? (uint32_t)DNU * 1024u : XS * X_BYTES);
auto full_bar = [&](int s) { return bar_base + 8u * s; };
auto empty_bar = [&](int s) { return bar_base + 8u * (STAGES + s); };
auto accf_bar = [&](int a) { return bar_base + 8u * (2 * STAGES + a); };
auto acce_bar = [&](int a) { return bar_base + 8u * (2 * STAGES + ACC_BUFS + a); };
// CPX: per-stage token barriers (local, count 32 = token-loader lanes), after the tmem slot
auto tok_bar = [&](int s) { return bar_base + 8u * (2 * STAGES + 2 * ACC_BUFS + 1 + s); };
uint32_t* tmem_slot = reinterpret_cast<uint32_t*>(smem + (bar_base - base) +
8 * (2 * STAGES + 2 * ACC_BUFS));
const int warp = threadIdx.x / 32, lane = threadIdx.x % 32;
// packed policy knobs (host MoeArgs): bits 0-3 token xpol, 4-7 full-path out policy (zero stores +
// down red.adds; 0 evict_last / 1 evict_normal / 2 evict_first), 8-11 gu_only out zero-store policy
// (code as make_l2pol; host default 2 = evict_first)
const int out_pol_code = gu_only ? ((xpol >> 8) & 15) : ((xpol >> 4) & 15);
// down-weight interleave (bits 12-15): 0 = 64-row groups / 32-row halves, 1 = 32-row groups / 16-row halves
const int dil = (xpol >> 12) & 15;
if ((xpol >> 17) & 1) { // MOE_PTRBLK: this call's pointers from the device block (stream-ordered writes)
hidden = reinterpret_cast<const __nv_bfloat16*>(__ldcg(g_ptr_blk + 0));
ids = reinterpret_cast<const long long*>(__ldcg(g_ptr_blk + 1));
ew = reinterpret_cast<const __nv_bfloat16*>(__ldcg(g_ptr_blk + 2));
out = reinterpret_cast<__nv_bfloat16*>(__ldcg(g_ptr_blk + 3));
}
xpol &= 15;
PROF(const int abl_v = g_abl;)
PROF(const unsigned long long t_entry = gtime(); const unsigned long long c_entry = clock64(); unsigned long long* pr = g_prof + blockIdx.x * PROF_N;
unsigned long long pq0 = 0, pq1 = 0, pq2 = 0, pq3 = 0, w0 = 0, w1 = 0, w2 = 0, w3 = 0, x20 = 0, x21 = 0, x22 = 0, x23 = 0;)
const uint32_t rank = cluster_rank();
const bool leader = (rank == 0);
const int cid = blockIdx.x >> 1, ncl = gridDim.x >> 1;
// DQ (dynamic work queue): the leader's producer thread claims items from a global counter and
// broadcasts each claimed item's info into an IRING-deep smem ring in BOTH CTAs (st.shared::cluster
// into the peer; ifull/iempty mbarriers); every role of both CTAs reads its next item from the ring
// and releases the slot on the leader's iempty. Round-robin (DQ=0) leaves a tail imbalance when
// the per-cluster item counts differ.
// Deadlock-free: each cluster processes items in increasing index order and a down item only
// waits on gate|up items with smaller indices (claimed earlier).
auto ifull_bar = [&](int i) { return bar_base + 8u * (3 * STAGES + 2 * ACC_BUFS + 1 + i); };
auto iempty_bar = [&](int i) { return bar_base + 8u * (3 * STAGES + 2 * ACC_BUFS + 1 + IRING + i); };
// SPLITF: full2_bar[STAGES] after the item-ring barriers (item ring shifted past them)
auto full2_bar = [&](int s) { return bar_base + 8u * (3 * STAGES + 2 * ACC_BUFS + 1 + 2 * IRING + s); };
// MOE_E0REL: empty0_bar[STAGES] after the item ring barriers (same slot range as full2: SPLITF and E0REL exclusive)
auto empty0_bar = [&](int s) { return bar_base + 8u * (3 * STAGES + 2 * ACC_BUFS + 1 + 2 * IRING + s); };
const uint32_t iring_base = (bar_base + 8u * (3 * STAGES + 2 * ACC_BUFS + 1 + 2 * IRING + ((SPLITF || E0REL) ? STAGES : 0)) + 15u) & ~15u;
// consumers per ring slot: per CTA warp6 + 8 epilogue warps; leader MMA; peer producer;
// CPX: + peer forwarder + both token loaders
// MOE_EPIMBOX (full-mega DQ launches): only ONE epilogue warp per CTA (warp 2) reads the item ring;
// it copies each item into a 2-deep smem mailbox and the EPI_W epilogue warps pick it up after a named
// barrier (bar 9, EPI_T threads) -> per item and CTA 1 instead of EPI_W cluster-scope ring waits /
// remote iempty arrives. gu_only (MIX) launches keep per-warp ring reads.
constexpr bool EMBOX = DQ != 0; // MOE_EPIMBOX_GU: gu_only (MIX) launches too
constexpr bool LFWD = CPX && GUO && EW == 4 && NCHUNK >= 240 && !NSW;
constexpr int ICONS = 2 * (1 + (EMBOX ? 1 : EPI_W)) + 1 + 1 + (CPX ? 3 : 0) + (LFWD ? 1 : 0);
// MOE_EARLYPDL: full-megakernel launches trigger their PDL dependents at kernel entry, so the next
// call's megakernel (back-to-back calls on one stream) is scheduled as soon as each SM frees up and
// runs its prologue (barrier init, TMEM alloc, tensormap prefetch) under this grid's tail. Legal:
// the dependent touches no global state before its griddepcontrol.wait, which still waits for this
// grid's full completion + memory flush; all CTAs of this grid are resident once they all trigger,
// and 1 CTA/SM (smem) means a dependent CTA only lands on an SM this grid has left.
// (gu_only launches keep their later trigger: the CUTLASS down GEMM follows them.)
if (!gu_only) pdl_launch_dependents();
#ifdef MOE_TLPROBE
if (threadIdx.x == 0 && gu_only) { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); atomicMin(&g_tlk[2], t); }
#endif
if (threadIdx.x == 0) {
for (int s = 0; s < STAGES; ++s) {
// CPX: + 32 token-loader lanes of each CTA arrive (remote for CTA 1) once per stage
// CPX: + CTA 1's forwarded token arrival (warp 1 lane 0 of CTA 1, remote); the leader's own
// token rows are checked by the MMA thread on its local tok_bar
// CPX merged token wait: the leader's 32 token-loader lanes arrive (cp.async.mbarrier.arrive.noinc)
// directly on its full_bar, so the MMA thread does ONE barrier wait per stage (was full_bar + tok_bar)
mbar_init(full_bar(s), CPX ? (leader ? 1 + 1 + (LFWD ? 1 : 32) : 1 + 1) : 1);
if (CPX) mbar_init(tok_bar(s), 32);
mbar_init(empty_bar(s), 1);
if (E0REL) mbar_init(empty0_bar(s), 1); // MMA commit (multicast) after the stage's acc0 MMAs
if (SPLITF) mbar_init(full2_bar(s), 1); // leader's warp-6 expect_tx arrival (+ tx bytes of both CTAs)
}
if (DQ)
for (int i = 0; i < IRING; ++i) {
mbar_init(ifull_bar(i), 1);
mbar_init(iempty_bar(i), ICONS);
}
for (int a = 0; a < ACC_BUFS; ++a) {
mbar_init(accf_bar(a), 1);
mbar_init(acce_bar(a), 2 * EPI_T); // 256 epilogue threads x 2 CTAs (leader's copy used)
}
// MOE_PUBAGG (full path): zero the 8 per-item-slot epilogue publish counters (see the gate|up
// done[] publish in the epilogue); ordered before their use by the routing __syncthreads
// MOE_PUBAGG_GU: gu_only (MIX) launches aggregate the done[] publish too -> counters always zeroed
if (!GUO || MOE_PUBAGG_GU)
for (int i = 0; i < 8; ++i)
asm volatile("st.shared.u32 [%0], %1;" ::"r"(iring_base + 16u * IRING + 4u * i), "r"(0u) : "memory");
asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory");
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
}
if (warp == 1) { // pair-wide allocation of all 512 TMEM columns (1 CTA / SM)
asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], 512;" ::"r"(
smem_u32(tmem_slot)));
asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;");
}
if (warp == 0 && lane < HSN && HSN > 1) prefetch_tmap(&hsm.m[lane]);
if (warp == 0 && lane == 0) {
prefetch_tmap(&tmG); prefetch_tmap(&tmU); prefetch_tmap(&tmD);
if constexpr (!CPX) prefetch_tmap(&tmX);
// Speculative L2 prefetch of this CTA's first work item while route_kernel still runs.
// Queue items [0, 8*lag) are the gate|up items of chunks 0..lag-1; when every expert holds
// one chunk (the common case), chunk c == expert c, so item cid -> expert cid/8, m-tile cid%8.
// If the guess is wrong it only costs bandwidth (a prefetch is a cache hint).
if (cid < GMT * lag) {
const int e = cid / GMT, m = cid % GMT;
const int wrow = NSW ? e * INTER + m * BM : e * INTER + m * BM2 + (int)rank * BM;
const int prot = krot(e, m, GUO ? 0 : e, KIT_GU, cid); // MOE_SPLITLOCK: no chunk term in gu_only // guessed item: chunk == expert
// MOE_NPF8_FULL: full-mega bands (T<4096, hidden warm-up + evict_last out share L2) prefetch 8 slabs
// MOE_NOWPF: speculative weight L2 prefetch dropped (the slabs are re-read by the TMA loads anyway:
// double L2 lookup + extra DRAM traffic if the guess is wrong; energy per byte in the power-capped regime)
const int npf = MOE_NOWPF ? 0 : (gu_only ? NPF_SLABS : 8);
for (int k = 0; k < npf; ++k) {
const int kk = krot_k(k, prot, KIT_GU);
if (!NSW || rank == 0) tma_prefetch_2d(&tmG, kk * BK, wrow);
if (!NSW || rank == 1) tma_prefetch_2d(&tmU, kk * BK, wrow);
}
}
}
tc_fence_before();
// MOE_LATECTASYNC (#AO prologue trim 2): no CTA-wide __syncthreads here any more -- nothing before
// the work loop needs the mbarrier inits or the TMEM allocation (warp 1), and route_in_kernel's
// first __syncthreads orders them for this CTA; the PDL wait / early out zeroing / token L2
// warm-up / routing pass 1 no longer wait for the alloc + barrier-init thread.
// MOE_LATECSYNC (prologue trim): the pair-wide cluster_sync (peer barriers initialized before any
// remote arrive / TMA completion) is deferred to after the in-kernel routing -- no cluster-scope
// operation happens before the work loop, the routing scratch lies below bar_base, and after the
// routing grid barrier the peer is already there, so the sync no longer sits on the launch head.
PROF(if (threadIdx.x == 0) pr[0] = t_entry;)
pdl_wait(); PROF(if (threadIdx.x == 0) g_prof[blockIdx.x * PROF_N + 16] = gtime();)
// EARLY OUT ZEROING (MOE_EARLYZ): the epilogue warps issue their grid-stride share of the `out`
// zero stores right after the PDL wait, BEFORE the in-kernel routing (whose grid barriers they
// would otherwise just wait through), so the 16-B zero stores drain into L2 under the routing /
// speculative weight prefetch instead of competing with the first gate|up mainloops. Same
// L2 policy as before (evict_last; gu_only: evict_first). Each warp still publishes its stores
// (red.release.gpu on the zero counter, cumulative over its earlier stores) AFTER routing, since
// routing resets that counter. `out` is only touched after griddepcontrol.wait (stream order).
if (MOE_EARLYZ && warp >= 2 && warp != 6 && !(CPX && warp == TOKW) && !ABL_NOZERO) {
const int etid0 = (EW == 8 && warp >= 7 ? warp - 3 : warp - 2) * 32 + lane;
uint64_t pz;
pz = make_l2pol(out_pol_code); // full path: MoeArgs.opol; gu_only: MoeArgs.zpol
uint4* o4 = reinterpret_cast<uint4*>(out);
const int nthr = gridDim.x * EPI_T;
for (int i = blockIdx.x * EPI_T + etid0; i < out_vec; i += nthr)
asm volatile("st.global.L2::cache_hint.v4.u32 [%0], {%1, %1, %1, %1}, %2;" ::"l"(o4 + i), "r"(0u), "l"(pz)
: "memory");
}
if (!gu_only && threadIdx.x == 32) {
const size_t tot = (size_t)(S / TOPK) * HID * 2; // hidden_states bytes
const size_t per = ((tot / gridDim.x) + 255) & ~(size_t)255; // 256-B aligned slice
const size_t b0 = per * blockIdx.x;
const size_t b1 = b0 + per < tot ? b0 + per : tot;
const char* hb = reinterpret_cast<const char*>(hidden);
for (size_t o = b0; o < b1; o += 32768) {
const uint32_t sz = (uint32_t)((b1 - o < 32768 ? b1 - o : 32768) & ~(size_t)15);
if (sz) asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(hb + o), "r"(sz) : "memory");
}
}
// PDL: the previous grid on the stream has completed and flushed
// in-kernel routing (all CTAs, two grid barriers): queue, done[], sorted_slot ready after this
RouteRes rres;
{
const bool rwarp = CPX ? (warp == 0 || warp == 1 || warp == 6 || warp == TOKW) : true;
const int rtid = CPX ? ((warp == 0 ? 0 : warp == 1 ? 1 : warp == 6 ? 2 : 3) * 32 + lane) : (int)threadIdx.x;
const int rnt = CPX ? 128 : (int)blockDim.x;
if (rwarp)
(void)route_in_kernel(reinterpret_cast<int*>(smem), ids, S, RC, item_info, done, num_items_ptr, sorted_slot,
NCHUNK, lag, &g_moe_bar[bar_idx], gu_only, inv, GMT, gu_only ? cnt_out : nullptr,
meta, ew, rtid, rnt); // #BO: gu_only builds meta too (1 epilogue weight load)
__syncthreads(); // routing results (scratch[0..7]) + mbarrier init + TMEM alloc visible CTA-wide
const int* sc = reinterpret_cast<const int*>(smem);
rres.tgt = *reinterpret_cast<const unsigned long long*>(sc);
rres.num_items = sc[2];
rres.first = *reinterpret_cast<const int4*>(sc + 4);
PROF(if (threadIdx.x == 0) g_prof[blockIdx.x * PROF_N + 18] = gtime();)
// the scratch smem becomes the TMA stage ring: order generic accesses before async-proxy writes
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
__syncthreads();
}
cluster_sync(); // MOE_LATECSYNC: peer mbarrier inits visible before any remote arrive / TMA completion
// TMEM base address (written by warp 1's tcgen05.alloc before routing's __syncthreads)
tc_fence_after();
const uint32_t tmem_base = *tmem_slot;
// gu_only: publish "routing of call `epoch` done" (done[] zeroed, num_items[2] valid; both are
// visible grid-wide after route_in_kernel's final grid barrier) to the batch-0 wait kernel
if (gu_only && blockIdx.x == 0 && threadIdx.x == 0)
{
// MOE_OUTSLOT: publish this call's out pointer (ordered before the epoch release by program order)
g_out_slot = out;
asm volatile("st.release.gpu.global.u32 [%0], %1;" ::"l"(&g_route_epoch), "r"(epoch) : "memory");
}
// route outputs are read L2-coherent (__ldcg): written by the PDL predecessor grid
const int num_items = rres.num_items;
// lazy wait for the routing scatter / queue writes of ALL CTAs (one lane per warp polls)
auto route_wait = [&]() {
if (lane == 0) grid_wait(&g_moe_bar[bar_idx], rres.tgt);
__syncwarp();
};
PROF(if (threadIdx.x == 0) pr[1] = gtime();)
// Work-item metadata is software-prefetched one item ahead (register double buffer).
auto load_info = [&](int item) -> int4 {
return item < num_items ? __ldcg(item_info + item) : make_int4(0, 0, 0, 0);
};
int* qctr = num_items_ptr + 3; // DQ claim counter (reset by route_in_kernel)
// #CA: cluster addresses of the item-ring barriers / slots mapa'd ONCE (same smem offset in both
// CTAs, so slot sl = base + 8*sl / 16*sl), instead of a mapa per ring_get / dq_publish
const uint32_t iempty_l0 = mapa(iempty_bar(0), 0);
const uint32_t ifull_p0 = mapa(ifull_bar(0), 1);
const uint32_t iring_p0 = mapa(iring_base, 1);
// ring read (one thread): wait slot q (cluster-scope acquire: data may come from the peer), copy, release
auto ring_get = [&](uint32_t q) -> int4 {
const int sl = q % IRING;
mbar_wait_cl(ifull_bar(sl), (q / IRING) & 1);
int4 v;
asm volatile("ld.shared.v4.s32 {%0, %1, %2, %3}, [%4];" : "=r"(v.x), "=r"(v.y), "=r"(v.z), "=r"(v.w)
: "r"(iring_base + 16u * sl) : "memory");
asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(iempty_l0 + 8u * sl) : "memory");
return v;
};
auto bcast4 = [&](int4 v) -> int4 {
v.x = __shfl_sync(0xffffffffu, v.x, 0); v.y = __shfl_sync(0xffffffffu, v.y, 0);
v.z = __shfl_sync(0xffffffffu, v.z, 0); v.w = __shfl_sync(0xffffffffu, v.w, 0);
return v;
};
// Item iterator shared by all roles. DQ=0: static round-robin (cid, cid+ncl, ...) with a one-item
// register prefetch. DQ=1: ring slot qi (warpwide: lane 0 reads, broadcast to the warp).
struct ISrc { int item; int4 nxt; uint32_t qi; int need; int raw; };
auto isrc_init = [&]() { ISrc r; r.item = cid; r.qi = 0; r.need = 0; r.raw = 0; r.nxt = DQ ? make_int4(0, 0, 0, 0) : load_info(cid); return r; };
auto isrc_next = [&](ISrc& r, int4& info, bool warpwide) -> bool {
if (DQ) {
info = make_int4(-1, 0, 0, 0);
if (!warpwide || lane == 0) info = ring_get(r.qi);
if (warpwide) info = bcast4(info);
++r.qi;
return info.x >= 0;
}
if (r.item >= num_items) return false;
info = r.nxt;
r.nxt = load_info(r.item + ncl);
r.item += ncl;
return true;
};
// MOE_DQSTATIC_W: MIX gate|up-only queue (T>=4096) uses a 4-item static head per cluster; full path 1
const int dq_static = gu_only ? MOE_DQ_STATIC_W : 1;
bool pub_rw = false; // MOE_FIRSTLOCAL: leader producer still owes the routing grid wait
auto dq_publish = [&](ISrc& r, uint32_t slot) { // leader, lane 0 only
int4 v = make_int4(-1, 0, 0, 0);
// deferred claim result (need == 2): the atomicAdd issued at the item boundary is first READ
// here (K-iteration 4), so its L2 round trip no longer stalls the producer at the boundary
// MOE_DQSTATIC_W: slots [0, dq_static) are assigned round-robin (deterministic schedule head, no
// claim); dynamic claims start at item dq_static * ncl (items still taken in increasing order).
if (r.need == 2) r.item = dq_static * ncl + r.raw;
else if (slot > 0 && slot < (uint32_t)dq_static) r.item = cid + (int)slot * ncl;
r.need = 0;
if (slot == 0 && rres.first.x >= 0) {
v = rres.first; // == item_info[cid] (locally derived, see route_in_kernel)
r.need = 1;
} else {
if (pub_rw) { grid_wait(&g_moe_bar[bar_idx], rres.tgt); pub_rw = false; } // item_info of all CTAs
if (r.item < num_items) { v = __ldcg(item_info + r.item); r.need = 1; }
}
const int sl = slot % IRING;
// MOE_PUBPARK: parked (suspend-hint) wait for the ring slot to be released by all consumers
mbar_wait_park(iempty_bar(sl), ((slot / IRING) & 1) ^ 1);
const uint32_t a = iring_base + 16u * sl;
asm volatile("st.shared.v4.s32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory");
mbar_arrive_local(ifull_bar(sl));
// peer copy: st.async writes the 16-B slot into CTA 1 and completes 16 transaction bytes on
// CTA 1's ifull (async-proxy data+signal, no fence); the relaxed arrive.expect_tx supplies the
// phase's single arrival + tx expectation (either may land first: tx-count may go negative).
const uint32_t pfb = ifull_p0 + 8u * sl;
asm volatile("mbarrier.arrive.expect_tx.relaxed.cluster.shared::cluster.b64 _, [%0], 16;" ::"r"(pfb) : "memory");
asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.s32 [%0], {%1, %2, %3, %4}, [%5];" ::"r"(iring_p0 + 16u * sl),
"r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w), "r"(pfb) : "memory");
r.nxt = v;
};
auto prod_next = [&](ISrc& r, int4& info) -> bool {
if (!DQ) return isrc_next(r, info, false);
info = make_int4(-1, 0, 0, 0);
if (lane == 0) {
if (leader) {
PROF(const unsigned long long q0 = clock64();)
if (r.qi == 0) dq_publish(r, 0); // first item: nothing streaming yet to overlap with
info = r.nxt; // slot qi was published (early) already
if (!MOE_LATE_CLAIM && r.need == 1) { r.raw = atomicAdd(qctr, 1); r.need = 2; } // claim: result consumed at the next publish
PROF(pq0 += clock64() - q0;)
} else {
PROF(const unsigned long long q0 = clock64();)
info = ring_get(r.qi);
PROF(pq3 += clock64() - q0;)
}
}
if (!W0SOLO) info = bcast4(info); // W0SOLO: lane 0 is the only producer thread
++r.qi;
return info.x >= 0;
};
if (warp == 0 && (!W0SOLO || lane == 0)) {
// MOE_FIRSTLOCAL: with DQ + the cp.async token loader the producers read no routing output for
// the first item (published from the locally derived rres.first); the leader does the grid wait
// lazily before its first item_info read (next publish), the peer needs none (ring + done[] only).
const bool fast0 = DQ && CPX && rres.first.x >= 0;
if (!fast0) { if (W0SOLO) grid_wait(&g_moe_bar[bar_idx], rres.tgt); else route_wait(); } // leader reads item_info (dq_publish); non-CPX peers read sorted_slot
else pub_rw = leader;
// (g_moe_cnt reset moved to CTA 0's epilogue warp 2, after its route_wait)
// ------------------------------------------------ TMA producer (both CTAs)
// Global iteration `it` (one BK slice of one item): weights -> weight stage it%WS, tokens ->
// token slot it%XS; both complete on full_bar(it%WS). Token loads are issued TLAG = WS-XS
// iterations after their weights: by then the weight wait for stage (it+TLAG)%WS has proven
// MMA(it+TLAG-WS) = MMA(it-XS) done, i.e. token slot it%XS is free -- so a small token ring
// needs no barrier of its own while the weight ring runs WS deep. The leader arms
// full_bar(it%WS) with weights+tokens bytes when it issues the weights.
uint64_t pol_w, pol_x; // weights streamed once (evict_first); tokens: no hint by default (xpol=1)
asm volatile(MOE_WPOL_STR : "=l"(pol_w));
if (xpol == 2) asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_x));
else asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_x));
// Hs rows are dead after the chunk's 14 down items (issued back-to-back, read in near
// lockstep): read them evict_first so dead Hs never crowds out the L2-resident out / tokens.
uint64_t pol_h;
#if MOE_HPOL == 0
asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_h));
#elif MOE_HPOL == 1
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_h));
#else
asm volatile("createpolicy.fractional.L2::evict_unchanged.b64 %0, 1.0;" : "=l"(pol_h));
#endif
struct TokLd { int gu, active, t0, t1, t2, t3, xrow0, nb, c, kit, half, k0, rot; };
TokLd cur = {}, prev = {};
const uint32_t fb0 = mapa(full_bar(0), 0); // leader full_bar(0) (cluster address); stage s = fb0 + 8*s
// issue the token loads of K-slice kk of item p (global iteration jt)
// (jws, jxs) = (jt % WS, jt % XS) of the token iteration jt, kept as running counters by the caller
auto issue_tok = [&](const TokLd& p, int kk_loop, uint32_t jws, uint32_t jxs, uint32_t jt) {
// #CA: address math only inside the branches that issue (CPX gate|up stages issue nothing here;
// the per-stage volatile mapa ran on all 32 lanes for nothing); leader full_bar mapa'd once (fb0)
if (p.gu) {
if constexpr (!CPX) if (p.active && !ABL_NOTOK)
{
const int kk = krot_k(kk_loop, p.rot, p.kit);
const uint32_t fb = fb0 + 8u * jws;
const uint32_t xs = xbase + jxs * X_BYTES;
if (xpol == 1) tma_gather4_nohint(xs + lane * (4 * BK * 2), &tmX, fb, kk * BK, p.t0, p.t1, p.t2, p.t3);
else tma_gather4(xs + lane * (4 * BK * 2), &tmX, fb, kk * BK, p.t0, p.t1, p.t2, p.t3, pol_x);
}
} else if (!HSLDR && lane == 0) {
const int kk = krot_k(kk_loop, p.rot, p.kit); // rotated K-slice (kk_loop == 0: first issued)
const uint32_t fb = fb0 + 8u * jws;
const uint32_t xs = xbase + jxs * X_BYTES;
// MOE_E0SAFE (token-slot reuse proof under MOE_E0REL with warp 0 waiting empty0): the weight wait
// of iteration jt+TLAG only proves the acc0 MMAs of iteration jt+TLAG-WS = jt-XS complete, but its
// acc1 MMAs also read this Hs token slot -> wait the slot's full-stage empty_bar commit first
// (cp.async gate|up tokens already wait empty_bar in the token-loader warp).
if (E0W0 && jt >= (uint32_t)XS) {
const uint32_t pi = jt - (uint32_t)XS;
mbar_wait_probe(empty_bar((int)(pi % (uint32_t)WS)), (pi / (uint32_t)WS) & 1u);
}
if (kk_loop == 0) {
// dependency: all 8 gate|up tiles of this chunk have written their Hs rows
if (ld_acquire_gpu(done + 2 * p.c) < DT) {
PROF(const unsigned long long t0 = clock64(); ++w3;)
while (ld_acquire_gpu(done + 2 * p.c) < DT) __nanosleep(16);
PROF(w1 += clock64() - t0;)
}
fence_proxy_async_global(); // generic-proxy Hs stores -> visible to TMA (async proxy)
}
// exact box: this CTA's `half` rows (multiple of 8) in one TMA op; bytes = half * 128
if (!ABL_NOHSR)
tma_load_2d(xs, &hsm.m[HSN == 1 ? 0 : (p.half >> 3) - 1], fb, (p.k0 + kk) * BK, p.xrow0, pol_h);
}
};
uint32_t it = 0;
// running ring counters (no per-stage % / divisions): weight stage ps / phase pph of `it`;
// token iteration it-TLAG: weight-ring slot tws, token slot txs
uint32_t ps = 0, pph = 0, tws = 0, txs = 0;
ISrc isrc = isrc_init();
int4 info;
PROF(unsigned long long y0 = 0, y1 = 0, y2 = 0; unsigned long long tq = clock64();)
while (prod_next(isrc, info)) {
PROF(y0 += clock64() - tq;)
const int e = info.x, n = info.z;
const bool gu = GUO || ((info.w >> 7) & 1);
const int m = info.w & 127;
const int dm = gu ? m : dn_mt(m), dk0 = gu ? 0 : dn_k0(m); // down: m-tile, first K-slice
const int half = ((n + 15) & ~15) >> 1; // token rows held by each CTA (mult of 8)
cur.gu = gu;
cur.k0 = dk0;
cur.c = info.w >> 8;
cur.kit = gu ? KIT_GU : dn_kit(m);
cur.rot = krot(e, m, GUO ? 0 : cur.c, cur.kit, cid); // MOE_SPLITLOCK
int wrow, wrow1;
uint32_t bytes;
const CUtensorMap* tw0;
const CUtensorMap* tw1;
if (gu && NSW) {
// non-swapped: one weight tile per CTA (CTA 0 gate rows, CTA 1 up rows of slice m);
// tokens come from the cp.async loader warp (not transaction bytes)
wrow = e * INTER + m * BM;
wrow1 = wrow;
tw0 = rank ? &tmU : &tmG;
tw1 = tw0;
cur.kit = KIT_GU;
cur.active = 0;
cur.t0 = cur.t1 = cur.t2 = cur.t3 = 0;
bytes = 2u * W_BYTES;
} else if (gu) {
wrow = e * INTER + m * BM2 + (int)rank * BM; // this CTA's 128 gate rows; up: same rows
wrow1 = wrow;
tw0 = &tmG;
tw1 = &tmU;
cur.kit = KIT_GU;
// lane L gathers rows [4L, 4L+4) of this CTA's half (if 4L < half). Rows past the
// chunk's n (MMA N padding) reuse a valid token: they only feed ignored D columns.
// CPX: the token-loader warp copies the tokens; the producer needs no token indices, so
// skip the 2 dependent sorted_slot loads per lane at every gate|up item start (they sat on
// the producer's item-boundary critical path for nothing).
if (!CPX) {
const int lr = (int)rank * half + 4 * lane;
cur.active = 4 * lane < half;
int tok[4];
const int tok0 = __ldcg(sorted_slot + info.y) / TOPK;
#pragma unroll
for (int j = 0; j < 4; ++j)
tok[j] = (cur.active && lr + j < n) ? __ldcg(sorted_slot + info.y + lr + j) / TOPK : tok0;
cur.t0 = tok[0]; cur.t1 = tok[1]; cur.t2 = tok[2]; cur.t3 = tok[3];
} else {
cur.active = 0;
cur.t0 = cur.t1 = cur.t2 = cur.t3 = 0;
}
// CPX: token bytes arrive via cp.async (counted as loader arrivals, not transaction bytes)
bytes = 2u * (2 * W_BYTES + ((ABL_NOTOK || CPX) ? 0u : (uint32_t)half * (BK * 2)));
} else {
// DOWN ROW INTERLEAVE: CTA r owns rows [256r, 256r+256) of the 512-row m-tile; tile0 = the
// first 32 rows of each of its 4 64-row groups, tile1 = the second 32 (4D map, one TMA op).
// wrow = index of the CTA's first 64-row group (4D coordinate c3).
wrow = (e * HID + dm * (2 * BM2) + (int)rank * BM2) >> (dil ? 5 : 6);
wrow1 = wrow;
tw0 = &tmD;
tw1 = &tmD;
cur.kit = dn_kit(m);
cur.xrow0 = info.y + (int)rank * half;
cur.nb = (half + XBOX - 1) / XBOX;
cur.half = half;
// Hs bytes per CTA: exact half rows (h64 == 2) or whole 32-row units
(void)h64;
const uint32_t hsb = (uint32_t)half * (BK * 2);
bytes = 2u * (2 * W_BYTES + (ABL_NOHSR ? 0u : hsb));
}
const int kclaim = max(0, cur.kit - ((NCHUNK == 128 && HSN != 1) ? 16 : ((NCHUNK == 128 || HSN != 1 || NCHUNK >= 240) ? 12 : 8))),
kpub = cur.kit - ((NCHUNK == 128 && HSN != 1) ? 6 : 4); // MOE_PUB6_128: earlier ring publish (more consumer lead)
(void)kclaim; (void)kpub;
int kwr = cur.rot;
for (int k = 0; k < cur.kit; ++k, ++it) {
const int kkw = kwr;
if (++kwr == cur.kit) kwr = 0;
const int s = (int)ps;
const uint32_t ph = pph;
if (++ps == (uint32_t)WS) { ps = 0; pph ^= 1u; }
if (lane == 0) {
PROF(const unsigned long long t0 = clock64();)
// parked wait (suspend hint): the producer idles most stages waiting for the MMA commit
mbar_wait_probe(E0W0 ? empty0_bar(s) : empty_bar(s), ph ^ 1); // MOE_E0REL: tile-0 release
PROF(const unsigned long long t1 = clock64(); w0 += t1 - t0;)
const uint32_t fb = fb0 + 8u * (uint32_t)s; // #CA: hoisted mapa
// ABL_CONSTA (PROF only): after the first WS iterations no weight bytes are loaded or expected
const bool skw = ABL_CONSTA && it >= (uint32_t)WS;
const uint32_t wbytes = (gu && NSW) ? 2u * W_BYTES : 4u * W_BYTES;
// SPLITF: tile 1 of both CTAs (2 x W_BYTES) is expected on full2_bar by warp 6 instead
if (leader) mbar_expect_tx(full_bar(s), (skw ? bytes - wbytes : bytes) - ((SPLITF && !skw) ? 2u * W_BYTES : 0u));
uint32_t st = base + s * WSTAGE;
if constexpr (WT != 2 * WS) st = base + ((2u * it) % (uint32_t)WT) * W_BYTES; // MOE_WT11 tile slot
if (!skw) {
if (gu) tma_load_2d(st, tw0, fb, (kkw + dk0) * BK, wrow, pol_w);
else tma_load_4d(st, &tmD, fb, (kkw + dk0) * BK, 0, 0, wrow, pol_w);
}
// DQ early publish of the next item's ring slot (r.qi = index of the NEXT item here)
if (DQ && leader) {
if (MOE_LATE_CLAIM) {
if (k == kclaim && isrc.need == 1 && isrc.qi >= (uint32_t)dq_static) { isrc.raw = atomicAdd(qctr, 1); isrc.need = 2; }
if (k == kpub) dq_publish(isrc, isrc.qi);
} else if (k == 4) {
dq_publish(isrc, isrc.qi);
}
}
PROF(if (it == 0) pr[27] = gtime(); y1 += clock64() - t1;)
}
if (!W0SOLO) __syncwarp(); // weight stage it is armed; token slot of it-TLAG is free (see above)
PROF(const unsigned long long t4 = clock64();)
if (it >= (uint32_t)TLAG) {
if (k >= TLAG) issue_tok(cur, k - TLAG, tws, txs, it - (uint32_t)TLAG);
else issue_tok(prev, prev.kit - TLAG + k, tws, txs, it - (uint32_t)TLAG);
if (++tws == (uint32_t)WS) tws = 0;
if (++txs == (uint32_t)XS) txs = 0;
}
PROF(y2 += clock64() - t4;)
}
prev = cur;
PROF(tq = clock64();)
}
// drain: token loads of the last TLAG iterations
// (no later weight wait proves token slot (it-j)%XS free here, so wait explicitly for the
// MMA of iteration it-j-XS -- the slot's previous user -- via its empty_bar commit)
for (int j = TLAG; j >= 1; --j)
if (it >= (uint32_t)j) {
const uint32_t jt = it - j;
if (lane == 0 && jt >= (uint32_t)XS) {
const uint32_t i = jt - XS;
mbar_wait(empty_bar(i % WS), (i / WS) & 1);
}
if (!W0SOLO) __syncwarp();
issue_tok(prev, prev.kit - j, tws, txs, jt); // tws/txs index jt (= max(0, it-TLAG) + issued)
if (++tws == (uint32_t)WS) tws = 0;
if (++txs == (uint32_t)XS) txs = 0;
}
if (gu_only) pdl_launch_dependents(); // producer done issuing (see MMA thread)
PROF(if (lane == 0) { pr[2] = gtime(); pr[6] = w0; pr[7] = w1; pr[13] = w3; pr[24] = y0; pr[25] = y1; pr[26] = y2; pr[28] = pq0; pr[29] = pq1; pr[30] = pq2; pr[31] = pq3; })
} else if (warp == 0) {
// MOE_W0SOLO: idle lanes 1..31 of the weight producer warp (straight to the teardown barriers)
} else if (warp == 1) {
if (!DQ) route_wait(); // DQ: item info arrives by value through the smem ring
if (lane == 0 && leader) {
// ------------------------------------------------ MMA issuer (leader CTA, single thread)
uint32_t it = 0, upar = 0, ring = 0; // upar bit s = use parity of accumulator slot s
// Per-stage loop diet: ring indices kept as running counters (no it % WS / it / WS / it % XS
// integer divisions per stage) and the smem descriptors built once (stage-0 base) and offset by
// the stage's 16-B-unit address delta (the 14-bit start-address field never carries: smem < 256 KB).
uint32_t ms = 0, mph = 0, mxs = 0;
const uint64_t dbw = make_desc(base), dbx = make_desc(xbase);
uint64_t dwc = dbw, dxc = dbx; // descriptors of the current weight stage / token slot
uint32_t mts = 0; // MOE_WT11: tile slot of the current iteration's tile 0
int dyp = 0; // MOE_DYNTOK128: next free token unit
(void)it; (void)dyp;
ISrc isrc = isrc_init();
int4 info;
while (isrc_next(isrc, info, false)) {
const int n = info.z;
const bool gu = GUO || ((info.w >> 7) & 1);
const int kiters = gu ? KIT_GU : dn_kit(info.w & 127);
const int n16 = (n + 15) & ~15;
// kind::f16 instr desc: D=f32, A=B=bf16, both K-major, N>>3 @17, M>>4 @24 (M=256)
const bool nsw = NSW && gu; // non-swapped gate|up item: N = 256 (gate|up weight rows)
const int nmma = (ABL_NCAP && !nsw) ? min(n16, ABL_NCAP) : (nsw ? 256 : n16); // ABL_NCAP: PROF only
// MMA-issuer instruction diet: the item-invariant descriptor bits are one compile-time constant;
// the N field of a swapped item is (n16 >> 3) << 17 == ((n + 15) >> 4) << 18 (one add + shift + or).
// Bit-identical to the former field-by-field build.
constexpr uint32_t IDESC_BASE = (1u << 4) | (1u << 7) | (1u << 10) | ((uint32_t)(BM2 >> 4) << 24);
const uint32_t idesc = (ABL_NCAP || NSW) ? (IDESC_BASE | ((uint32_t)(nmma >> 3) << 17))
: (IDESC_BASE | ((uint32_t)((n + 15) >> 4) << 18));
const AccPlan ap = acc_plan(n16, nsw, ring);
PROF(const unsigned long long ta = clock64();)
// parked (suspend-hint) accumulator-empty waits: item-boundary only, the MMA thread idles
// here while the epilogue drains; fewer spin-issued instructions on the leader SM
mbar_wait_park(acce_bar(ap.s0), ((upar >> ap.s0) & 1u) ^ 1u);
if (ap.s1 >= 0) mbar_wait_park(acce_bar(ap.s1), ((upar >> ap.s1) & 1u) ^ 1u);
const uint32_t d0 = tmem_base + ap.o0, d1 = tmem_base + ap.o1;
PROF(w1 += clock64() - ta;)
tc_fence_after();
auto mma_kloop = [&](auto gt) {
constexpr bool G = decltype(gt)::value;
const int kit_ = G ? KIT_GU : kiters;
#pragma unroll 4
for (int k = 0; k < kit_; ++k) {
const int s = (int)ms;
const uint32_t ph = mph;
PROF(const unsigned long long t0 = clock64();)
// MOE_MFULLPARK: parked (suspend-hint) wait -- the thread is woken on phase completion,
// so no added latency, but no tight try_wait re-issue while the DRAM-bound stage lands
// MOE_MFULL176PARK: NCH=176 full-mega band (T~3719, DRAM-paced stages) parks directly (no test_wait probe)
if (NCHUNK == 176 && HSN != 1) mbar_wait_park(full_bar(s), ph); else
mbar_wait_probe(full_bar(s), ph); // MOE_MFULLPROBE: non-blocking test_wait first (MMA-bound bands: stage usually already landed -> no suspend/wake round trip), parked wait otherwise
PROF(const unsigned long long t1 = clock64(); x20 += t1 - t0;)
if (CPX && G && !LFWD) {
// leader's own cp.async token rows are part of full_bar (merged wait above);
// generic-proxy writes -> async-proxy MMA reads. Down stages: the token operand is Hs
// via TMA (async proxy, no generic writes in this stage) -> no proxy fence needed
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
}
PROF(w0 += clock64() - t0; const unsigned long long t3 = clock64();)
// (MMA-issuer audit: no per-stage tcgen05.fence::after_thread_sync -- the full_bar wait
// already makes the TMA/cp.async stage data visible to the MMA (CUTLASS's SM100 UMMA
// consumer issues no fence there either); the fence stays at the item-level acce wait,
// which orders the MMA's TMEM writes after the epilogue's tcgen05.ld drain.)
// #BV: running stage descriptors (no per-stage multiply); bit-identical addresses
uint64_t dw0 = dwc;
uint64_t dw1 = dw0 + (W_BYTES >> 4);
if constexpr (WT != 2 * WS) { // MOE_WT11: tile slots t0s = (2it) % WT, (t0s + 1) % WT
dw0 = dbw + (uint64_t)(mts * (W_BYTES >> 4));
dw1 = dbw + (uint64_t)((mts + 1u == (uint32_t)WT ? 0u : mts + 1u) * (W_BYTES >> 4));
}
uint64_t dx = dxc;
if constexpr (DYNT) { // MOE_DYNTOK128: this stage's token range [dyp, dyp + u) of the unit ring
const int du = n16 >> 4;
if (dyp + du > DNU) dyp = 0;
dx = dbx + (uint64_t)(dyp * (1024 >> 4));
dyp += du;
}
if (NSW && G) {
// A = 128 token rows per CTA (token slot), B = 128 weight rows per CTA (gate | up)
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk)
mma_bf16(d0, dx + 2 * kk, dw0 + 2 * kk, idesc, (k | kk) ? 1u : 0u);
} else if (E0REL) {
// MOE_E0REL: acc0 (tile 0) MMAs, commit -> tile 0 slot free, then acc1 (tile 1) MMAs
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk)
if (!ABL_MMA0 && !(ABL_MMAQ && kk >= 2)) mma_bf16(d0, dw0 + 2 * kk, dx + 2 * kk, idesc, (k | kk) ? 1u : 0u);
mma_commit_mc(empty0_bar(s));
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk)
if (!ABL_MMA0 && !ABL_MMA1) mma_bf16(d1, dw1 + 2 * kk, dx + 2 * kk, idesc, (k | kk) ? 1u : 0u);
} else if (SPLITF) {
// acc0 (tile 0) MMAs as soon as tile 0 + tokens landed; then tile 1 -> acc1 MMAs
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk)
if (!ABL_MMA0 && !(ABL_MMAQ && kk >= 2)) mma_bf16(d0, dw0 + 2 * kk, dx + 2 * kk, idesc, (k | kk) ? 1u : 0u);
mbar_wait_probe(full2_bar(s), ph);
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk)
if (!ABL_MMA0 && !ABL_MMA1) mma_bf16(d1, dw1 + 2 * kk, dx + 2 * kk, idesc, (k | kk) ? 1u : 0u);
} else {
#pragma unroll
for (int kk = 0; kk < BK / 16; ++kk) { // BK/16 x (K=16) MMAs; +32 B per K step
// MOE_SERP: serpentine issue order g0,u0 | u1,g1 | g2,u2 | u3,g3 -- each pair shares the
// token (B) descriptor, and the pair boundary shares the accumulator D (same TMEM columns),
// so consecutive tcgen05.mma instructions always reuse one operand stream (operand-fetch /
// TMEM switching energy in the power-throttled regime). Per-accumulator K order unchanged.
const uint32_t acc = (k | kk) ? 1u : 0u;
if (kk & 1) {
if (!ABL_MMA0 && !ABL_MMA1) mma_bf16(d1, dw1 + 2 * kk, dx + 2 * kk, idesc, acc);
if (!ABL_MMA0 && !(ABL_MMAQ && kk >= 2)) mma_bf16(d0, dw0 + 2 * kk, dx + 2 * kk, idesc, acc);
} else {
if (!ABL_MMA0 && !(ABL_MMAQ && kk >= 2)) mma_bf16(d0, dw0 + 2 * kk, dx + 2 * kk, idesc, acc);
if (!ABL_MMA0 && !ABL_MMA1) mma_bf16(d1, dw1 + 2 * kk, dx + 2 * kk, idesc, acc);
}
}
}
mma_commit_mc(empty_bar(s)); // frees the smem stage in both CTAs
if (++ms == (uint32_t)STAGES) { ms = 0; mph ^= 1u; dwc = dbw; } else dwc += (WSTAGE >> 4);
if constexpr (WT != 2 * WS) { mts += 2u; if (mts >= (uint32_t)WT) mts -= (uint32_t)WT; }
if (++mxs == (uint32_t)XS) { mxs = 0; dxc = dbx; } else dxc += (X_BYTES >> 4);
PROF(x23 += clock64() - t3;)
}
};
if (gu) mma_kloop(std::true_type{}); else mma_kloop(std::false_type{});
mma_commit_mc(accf_bar(ap.s0));
upar ^= 1u << ap.s0;
if (ap.s1 >= 0) { mma_commit_mc(accf_bar(ap.s1)); upar ^= 1u << ap.s1; }
}
PROF(pr[3] = gtime(); pr[8] = w0; pr[9] = w1; pr[20] = x20; pr[21] = x21; pr[22] = x22; pr[23] = x23;)
// gu_only (MIX path): all MMAs of this CTA pair's last item are issued -> let the PDL-launched
// CUTLASS down GEMM be scheduled now (its load warps still griddepcontrol.wait for full
// completion + flush of this grid before reading Hs), instead of at kernel exit
if (gu_only) pdl_launch_dependents();
} else if (CPX && lane == 0 && !leader) {
// ------------------------------------- token-arrival forwarder (CPX, CTA 1's idle MMA warp)
// tok_bar(s) phase of iteration it complete (CTA 1's token rows landed) -> proxy fence
// (generic cp.async writes -> async-proxy MMA reads) -> arrive on the leader's full_bar(s).
// Instruction diet: the per-stage addresses are running pointers (local tok_bar, leader's
// full_bar mapa'd ONCE -- same offset in both CTAs, so stage s = base + 8*s), and the item kind
// test is hoisted out of the K loop (was a mapa + 2 address computes + a shift/and per stage).
uint32_t fs = 0, fpar = 0; // running stage counter, per-slot tok_bar parity bits
const uint32_t tb0 = tok_bar(0), rfb0 = mapa(full_bar(0), 0);
ISrc isrc = isrc_init();
int4 info;
while (isrc_next(isrc, info, false)) {
const bool gu = GUO || ((info.w >> 7) & 1);
const int kit = gu ? KIT_GU : dn_kit(info.w & 127);
auto fwd_kloop = [&](auto gt) { // compile-time item kind (see mma_kloop)
constexpr bool G = decltype(gt)::value;
const int kit_ = G ? KIT_GU : kit;
for (int k = 0; k < kit_; ++k) {
const uint32_t off = 8u * fs;
const uint32_t fsc = fs;
if (++fs == (uint32_t)WS) fs = 0;
if (DNDIR && !G) continue; // MOE_DNDIR: CTA 1's loader arrived on the leader's full_bar directly
mbar_wait_park(tb0 + off, (fpar >> fsc) & 1u);
fpar ^= 1u << fsc;
// down stages: the loader only arrives (no cp.async writes; Hs comes via TMA) -> no fence
if (G) asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
// default-semantics (release.cta) remote arrive, as CUTLASS ClusterBarrier::arrive.
asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(rfb0 + off) : "memory");
}
};
if (gu) fwd_kloop(std::true_type{}); else fwd_kloop(std::false_type{});
}
}
} else if (CPX && warp == TOKW) {
route_wait(); // reads sorted_slot
// ------------------------------------- token loader (CPX variants, both CTAs, all 32 lanes)
// Walks the same item / K-iteration sequence. For a gate|up item, iteration `it` copies this
// CTA's `half` token rows x 64 K-columns (128 B each = 8 x 16 B) from hidden_states into token
// slot it%XS: lane = (row sub-index rsub = lane/8, 16-B chunk cch = lane%8), rows rsub + 4i.
// The smem slot is SWIZZLE_128B K-major (what the MMA descriptor expects): chunk c of row r
// lands at r*128 + ((c ^ (r & 7)) * 16) (slot bases are 1024-B aligned).
// Slot reuse: slot it%XS was last read by the MMA of iteration it-XS -> wait its empty_bar commit.
// Completion is hardware-tracked (the loader never waits for its copies): each lane does
// cp.async.mbarrier.arrive.noinc on the local tok_bar(it%WS); down items (Hs via TMA from warp 0)
// just arrive. Leader: the MMA thread waits tok_bar itself; CTA 1: warp 1 lane 0 forwards each
// completed tok_bar phase to the leader's full_bar.
constexpr int RPL = NCHUNK / 8; // max rows per lane: half <= NCHUNK/2, 4 rows per pass
const int cch = lane & 7, rsub = lane >> 3;
int toff[RPL]; // element offset (token*HID + 8*cch) of each row this lane copies
uint32_t zmask = 0; // bit i: row i is MMA N padding -> zero-filled
// v4 padding (ABL_PADZ4): per token slot, the row range [lo, hi) currently known to be zero
// (packed lo | hi << 8; hi <= lo = none). Padding rows [p0, half) of a gate|up item (p0 = real
// rows of this CTA) are zeroed with st.shared only when not already covered; cp.async skips them.
// Down items (Hs TMA writes whole 32-row boxes) invalidate the slot's state. Padding rows only
// feed ignored D columns, so their content never affects results (zero = less MMA power).
// MOE_DYNTOK128: last stage that used token unit `lane`; -1 = never
int dyo0 = -1, dyo1 = -1, dyp = 0; // dyo1: unit lane + 32 (DNU > 32)
(void)dyo0; (void)dyo1; (void)dyp;
uint32_t zst[XS];
#pragma unroll
for (int s2 = 0; s2 < XS; ++s2) zst[s2] = 0;
uint32_t it = 0;
// running counters: ls = it % WS, lx = it % XS; (es, eph) = stage / phase of iteration it-XS
uint32_t ls = 0, lx = 0, es = 0, eph = 0;
// #BZ running addresses: token slot smem address of lx, arrive-barrier address of ls (leader:
// full_bar, CTA 1: tok_bar), and the lane's two SW128 swizzle offsets (r & 7 = rsub or rsub+4
// for r = rsub + 4i, rsub < 4) -- hoisted out of the per-stage loop (bit-identical addresses)
uint32_t xsr = xbase;
const uint32_t tb0 = (leader && !LFWD) ? full_bar(0) : tok_bar(0);
uint32_t tbr = tb0;
// MOE_HSLDR: leader full_bar(0) cluster address + Hs read L2 policy (same as warp 0's pol_h)
const uint32_t hfb0 = HSLDR ? mapa(full_bar(0), 0) : 0u;
uint64_t pol_hl = 0;
if (HSLDR) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_hl));
(void)hfb0; (void)pol_hl;
const uint32_t swz0 = (uint32_t)(cch ^ rsub) << 4, swz1 = (uint32_t)(cch ^ (rsub + 4)) << 4;
ISrc isrc = isrc_init();
int4 info;
// MOE_TOKPF176: also the NCH=176/192 full-megakernel bands (T~2900-4095, incl. T3719); not the
// gate|up-only MIX launches (HSN == 1)
constexpr bool PFN = ((NCHUNK == 128 || NCHUNK == 160 || NCHUNK == 176 || NCHUNK == 192) && !NSW && HSN != 1);
int4 pinfo = make_int4(-1, 0, 0, 0);
bool have_p = false, pvalid = false, pre_ok = false;
int praw[PFN ? RPL : 1];
while (true) {
if (PFN && have_p) { info = pinfo; if (!pvalid) break; }
else if (!isrc_next(isrc, info, true)) break;
const bool use_pre = PFN && have_p && pre_ok;
have_p = false;
const int n = info.z;
const bool gu = GUO || ((info.w >> 7) & 1);
// NSW gate|up: this CTA loads chunk rows [128*rank, 128*rank + 128) (MMA M = 256 tokens)
const int half = (NSW && gu) ? 128 : ((n + 15) & ~15) >> 1;
if (PFN && gu && use_pre) {
#pragma unroll
for (int i = 0; i < RPL; ++i) toff[i] = (praw[i] / TOPK) * HID + 8 * cch;
zmask = 0;
} else if (gu) {
// rows past n (MMA N padding) only feed ignored D columns: they reuse token tok0 (MOE_ZEROPAD: zero-filled)
const int tok0 = __ldcg(sorted_slot + info.y) / TOPK;
#pragma unroll
for (int i = 0; i < RPL; ++i) {
const int r = rsub + 4 * i, lr = (int)rank * half + r;
const int tok = (r < half && lr < n) ? __ldcg(sorted_slot + info.y + lr) / TOPK : tok0;
toff[i] = tok * HID + 8 * cch;
if (i == 0) zmask = 0;
#ifdef MOE_ZEROPAD
if (r < half && lr >= n) zmask |= 1u << i;
#endif
}
}
const int kit = gu ? KIT_GU : dn_kit(info.w & 127);
const int lrot = krot(info.x, info.w & 127, GUO ? 0 : (info.w >> 8), kit, cid); // MOE_SPLITLOCK // same rotation as the producers
int kcur = lrot;
for (int k = 0; k < kit; ++k, ++it) {
const int kk_run = kcur;
if (++kcur == kit) kcur = 0;
if (PFN && k == kit - 2) { // MOE_TOKPF: next item's info + token indices, early
pvalid = isrc_next(isrc, pinfo, true);
have_p = true;
pre_ok = false;
if (pvalid && (GUO || ((pinfo.w >> 7) & 1))) {
const int pn = pinfo.z;
const int phalf = NSW ? 128 : ((pn + 15) & ~15) >> 1;
const int s0 = __ldcg(sorted_slot + pinfo.y);
#pragma unroll
for (int i = 0; i < (PFN ? RPL : 1); ++i) {
const int r = rsub + 4 * i, lr = (int)rank * phalf + r;
praw[i] = (r < phalf && lr < pn) ? __ldcg(sorted_slot + pinfo.y + lr) : s0;
}
pre_ok = true;
}
}
// MMA(it-XS) done: token slot it%XS free; it also implies the tok_bar phase of it-WS
// was forwarded (so this arrival lands in the right phase)
uint32_t xs_dyn = 0;
if constexpr (DYNT) {
// MOE_DYNTOK128: allocate u units; wait MMA(q), q = max(latest earlier user of the range, it - WS)
const int du = half >> 3;
if (dyp + du > DNU) dyp = 0;
const bool in0 = lane >= dyp && lane < dyp + du;
const bool in1 = DNU > 32 && lane + 32 < DNU && lane + 32 >= dyp && lane + 32 < dyp + du;
int mo = in0 ? dyo0 : -1;
if (in1) mo = max(mo, dyo1);
mo = __reduce_max_sync(0xffffffffu, mo);
const int q = max(mo, (int)it - WS);
if (q >= 0 && lane == 0) {
if (DYNT176) mbar_wait(empty_bar(q % WS), (uint32_t)(q / WS) & 1u); // MOE_TOKEPROBE176: no suspend hint
else if (MOE_TOKE0 && E0W0 && q == (int)it - WS && mo < q)
mbar_wait_park(empty0_bar(q % WS), (uint32_t)(q / WS) & 1u);
else mbar_wait_park(empty_bar(q % WS), (uint32_t)(q / WS) & 1u);
}
__syncwarp();
if (in0) dyo0 = (int)it;
if (in1) dyo1 = (int)it;
xs_dyn = xbase + (uint32_t)dyp * 1024u;
dyp += du;
} else if (it >= (uint32_t)XS) {
if (lane == 0) {
PROF(const unsigned long long t0 = clock64();)
// MOE_TOKEPROBE192GU: also the NCH=192 gate|up-only MIX band
if ((NCHUNK == 176 && HSN != 1) || (NCHUNK == 192 && HSN == 1)) mbar_wait(empty_bar(es), eph); else
mbar_wait_park(empty_bar(es), eph);
PROF(w2 += clock64() - t0;)
}
if (++es == (uint32_t)WS) { es = 0; eph ^= 1u; }
__syncwarp();
}
const uint32_t clx = lx;
const uint32_t xs_cur = DYNT ? xs_dyn : xsr;
// leader: arrive straight on full_bar (phase-safe: the empty_bar wait above proved MMA(it-XS),
// hence full_bar phase it-WS, complete); CTA 1: local tok_bar, forwarded by warp 1 lane 0
const uint32_t tb = tbr;
const uint32_t lsc = ls; // MOE_HSLDR: weight-ring stage (full_bar index) of iteration it
if (++ls == (uint32_t)WS) { ls = 0; tbr = tb0; } else tbr += 8u;
if (++lx == (uint32_t)XS) { lx = 0; xsr = xbase; } else xsr += X_BYTES;
(void)clx;
const bool padz = ABL_PADZ4 && !NSW;
const int p0 = min(half, max(0, n - (int)rank * half)); // real token rows of this CTA's half
if (padz) {
const int sl = (int)clx;
uint32_t zs = 0;
#pragma unroll
for (int s2 = 0; s2 < XS; ++s2) if (s2 == sl) zs = zst[s2];
int zlo = zs & 0xff, zhi = zs >> 8;
if (!gu) {
zlo = zhi = 0; // TMA Hs boxes overwrite the slot
} else {
if (p0 < half && !(zhi > zlo && zlo <= p0 && zhi >= half)) {
const uint32_t xz = xbase + sl * X_BYTES;
for (int r = p0 + rsub; r < half; r += 4)
asm volatile("st.shared.v4.u32 [%0], {%1, %1, %1, %1};" ::"r"(xz + r * 128 + ((cch ^ (r & 7)) << 4)), "r"(0u)
: "memory");
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
zlo = p0; zhi = half;
} else {
zlo = max(zlo, p0); // rows [0, p0) get real tokens
}
}
zs = (zhi > zlo) ? ((uint32_t)zlo | ((uint32_t)zhi << 8)) : 0u;
#pragma unroll
for (int s2 = 0; s2 < XS; ++s2) if (s2 == sl) zst[s2] = zs;
}
if (gu) {
if (!ABL_NOTOK) {
const uint32_t xs = xs_cur;
const __nv_bfloat16* src = hidden + (ABL_TOKK0 ? 0 : kk_run * BK);
#pragma unroll
for (int i = 0; i < RPL; ++i) {
const int r = rsub + 4 * i;
// NSW: rows past the chunk's n are not loaded (they only feed ignored D rows / TMEM lanes;
// MMA rows are independent, so stale smem there cannot reach a stored result)
// MOE_PADSKIP128 (NCH=128 bands, token energy): MMA N-padding rows (r >= p0, only feed ignored D
// columns; MMA columns are independent) are no longer copied at all (was: duplicate of token 0)
if (r < ((padz || NCHUNK == 128) ? p0 : half) && (!NSW || !gu || (int)rank * BM + r < n))
#ifdef MOE_ZEROPAD
cp_async16z(xs + r * 128 + ((cch ^ (r & 7)) << 4), src + toff[i], ((zmask >> i) & 1) ? 0u : 16u);
#else
cp_async16<0>(xs + r * 128 + ((i & 1) ? swz1 : swz0), src + toff[i]); // padding rows duplicate token 0
#endif
}
}
cp_async_mbar_arrive_noinc(tb);
} else {
if constexpr (HSLDR) {
// MOE_HSLDR: down item -> this CTA's `half` Hs rows of rotated K-slice kk_run, one exact-height TMA
if (lane == 0) {
const int dc = info.w >> 8, dm0 = info.w & 127;
if (k == 0) {
// dependency: all gate|up tiles of chunk dc have written (and proxy-fenced) their Hs rows
while (ld_acquire_gpu(done + 2 * dc) < DT) __nanosleep(16);
fence_proxy_async_global(); // generic-proxy Hs stores -> visible to the TMA (async proxy)
}
tma_load_2d(xs_cur, &hsm.m[HSN == 1 ? 0 : (half >> 3) - 1], hfb0 + 8u * lsc,
(dn_k0(dm0) + kk_run) * BK, info.y + (int)rank * half, pol_hl);
}
__syncwarp();
}
// MOE_ARRCNT (barrier-protocol diet): down stages carry no cp.async writes, so the 32 per-lane
// arrivals of the token loader on tb are issued as ONE arrive with count 32 by lane 0 (after its
// Hs TMA issue); same barrier count / phase completion, 31 fewer shared-memory atomics per stage.
if (lane == 0) {
if (DNDIR && !leader) // MOE_DNDIR: direct remote arrive on the leader's full_bar (count 1)
asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(hfb0 + 8u * lsc) : "memory");
else mbar_arrive_local_cnt(tb, 32u);
}
__syncwarp();
}
}
}
PROF(if (lane == 0) pr[19] = w2;)
} else if (warp == 6) {
if (LFWD && leader && lane == 1) {
// ------------------------------- MOE_LFWD_W leader token-arrival forwarder (see ICONS)
uint32_t fs = 0, fph = 0;
const uint32_t tb0 = tok_bar(0), lfb0 = full_bar(0);
ISrc isrc = isrc_init();
int4 info;
while (isrc_next(isrc, info, false)) {
for (int k = 0; k < KIT_GU; ++k) {
const uint32_t off = 8u * fs;
mbar_wait_park(tb0 + off, fph);
if (++fs == (uint32_t)WS) { fs = 0; fph ^= 1u; }
asm volatile("fence.proxy.async.shared::cta;" ::: "memory");
mbar_arrive_local(lfb0 + off);
}
}
}
if (!DQ) route_wait();
// ------------------------------------- second weight producer (both CTAs): tile 1 of each stage
// Walks the same item / K-iteration sequence as warp 0 and waits on the same empty_bar; its
// bytes are already counted in the leader's expect_tx (armed by warp 0 for the whole stage).
if (lane == 0) {
uint64_t pol_w;
asm volatile(MOE_WPOL_STR : "=l"(pol_w));
uint32_t it = 0, ws6 = 0, wph6 = 0; // running stage / phase counters
const uint32_t fb06 = mapa(SPLITF ? full2_bar(0) : full_bar(0), 0); // SPLITF: tile 1 completes on full2
ISrc isrc = isrc_init();
int4 info;
while (isrc_next(isrc, info, false)) {
const int e = info.x;
const bool gu = GUO || ((info.w >> 7) & 1);
const int m = info.w & 127;
const int wrow1 = gu ? e * INTER + m * BM2 + (int)rank * BM // up rows (same as gate)
: (e * HID + dn_mt(m) * (2 * BM2) + (int)rank * BM2) >> (dil ? 5 : 6); // down: first 64-row group
const CUtensorMap* tw1 = gu ? &tmU : &tmD;
const int kit = gu ? KIT_GU : dn_kit(m);
const int dk0 = gu ? 0 : dn_k0(m);
if (NSW && gu) { // non-swapped gate|up: warp 0 loads the only tile (item-level, rare)
it += kit; ws6 = it % WS; wph6 = (it / WS) & 1; continue;
}
const int rot6 = krot(e, m, GUO ? 0 : (info.w >> 8), kit, cid); // MOE_SPLITLOCK
const uint32_t kc6 = (uint32_t)(dk0 * BK); // per-item column base (hoisted)
auto w6_kloop = [&](auto gt) { // compile-time item kind (see mma_kloop)
constexpr bool G = decltype(gt)::value;
const int kit_ = G ? KIT_GU : kit;
// MOE_WKRUN: running rotated column (== krot_k(k, rot6, kit_) * BK + kc6)
const int kcend = kit_ * BK + (int)kc6;
int kcr = rot6 * BK + (int)kc6;
#pragma unroll 2
for (int k = 0; k < kit_; ++k, ++it) {
const int kc = kcr;
kcr += BK;
if (kcr == kcend) kcr = (int)kc6;
const int s = (int)ws6;
if constexpr (WT == 2 * WS) {
mbar_wait_probe(empty_bar(s), wph6 ^ 1);
} else if (it >= (uint32_t)L1) { // MOE_WT11: tile-1 slot last held tile 0 of iteration it-L1
const uint32_t q = it - (uint32_t)L1;
const int qs = (int)(q % (uint32_t)WS);
mbar_wait_probe(E0W6 ? empty0_bar(qs) : empty_bar(qs), (q / (uint32_t)WS) & 1u); // MOE_E0REL
}
if (++ws6 == (uint32_t)WS) { ws6 = 0; wph6 ^= 1u; }
if (SPLITF && leader) {
// phase-safe: the empty wait above proved MMA(it-WS) -- which waited full2 phase it-WS -- done
if (ABL_CONSTA && it >= (uint32_t)WS) mbar_arrive_local(full2_bar(s));
else mbar_expect_tx(full2_bar(s), 2u * W_BYTES);
}
if (!(ABL_CONSTA && it >= (uint32_t)WS))
{
const uint32_t fb6 = fb06 + 8u * (uint32_t)s; // #CA: hoisted mapa
uint32_t d6 = base + s * WSTAGE + W_BYTES;
if constexpr (WT != 2 * WS) d6 = base + ((2u * it + 1u) % (uint32_t)WT) * W_BYTES; // MOE_WT11
if (G) tma_load_2d(d6, tw1, fb6, kc, wrow1, pol_w);
else tma_load_4d(d6, tw1, fb6, kc, 0, 1, wrow1, pol_w); // second 32 rows
}
}
};
if (gu) w6_kloop(std::true_type{}); else w6_kloop(std::false_type{});
}
}
} else {
// -------------------------------------------------- epilogue (warps 2..5, both CTAs)
// MOE_EPIRWAGG: ONE poller per CTA for the epilogue group (warp 2 lane 0 acquires the routing grid
// barrier generation, then named barrier 11 over the EPI_T epilogue threads orders every epilogue
// thread's later reads after that acquire -- same pattern as grid_barrier's thread-0 acquire +
// CTA barrier), instead of EPI_W lanes per CTA spinning on the same L2 line.
if (warp == 2 && lane == 0) grid_wait(&g_moe_bar[bar_idx], rres.tgt);
asm volatile("bar.sync 11, %0;" ::"r"(EPI_T) : "memory");
if (blockIdx.x == 0 && warp == 2) { // every CTA read g_moe_cnt before arriving: reset it for the next launch
// MOE_MKFILL (gu_only): write the CUTLASS down-GEMM argument arrays from the final counts NOW
//, then publish the args epoch for the gate-only fill kernel
if (GUO && dnf.on) {
dn_fill_args(dnf, g_moe_cnt, lane);
__syncwarp();
if (lane == 0) {
__threadfence();
asm volatile("st.release.gpu.global.u32 [%0], %1;" ::"l"(&g_route_ep[1]), "r"(epoch) : "memory");
}
__syncwarp();
}
for (int e = lane; e < NEXP; e += 32) g_moe_cnt[e] = 0;
}
const int q = warp & 3; // TMEM lane quadrant accessible by this warp
const int row = q * 32 + lane;
const int eh = (EW == 8 && warp >= 7) ? 1 : 0; // which half of the 32-col chunks this warp drains
const int etid = (EW == 8 && warp >= 7 ? warp - 3 : warp - 2) * 32 + lane; // 0..255 epilogue thread id
// XCH (gu_only launches): per quadrant pair 1 KB of smem staging after the item ring; pair id =
// eh*2 + q/2, named barrier 1 + pair id (64 threads). xok: staging fits the dynamic smem window
// (CTA-uniform; otherwise the half-line store path is used).
constexpr bool XCH = (HSN == 1) && !NSW;
const int xpair = eh * 2 + (q >> 1);
const uint32_t xstage0 = (iring_base + 16u * IRING + 64u + 127u) & ~127u; // past PUBAGG counters + mailbox
const uint32_t xstage = xstage0 + 1024u * (uint32_t)xpair;
const uint32_t xbar = 1u + (uint32_t)xpair;
uint32_t dsz;
asm volatile("mov.u32 %0, %%dynamic_smem_size;" : "=r"(dsz));
const bool xok = XCH && (xstage0 + 1024u * (EW / 2) <= raw_addr + dsz);
(void)xstage; (void)xbar; (void)xok;
uint32_t upar = 0, ring = 0; // upar bit s = use parity of accumulator slot s
// out accumulates via L2 reductions: tag its lines evict_last (live for the whole kernel)
uint64_t pol_out;
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_out));
// gu_only (large T, gu_zero): this kernel only zeroes out for the later CUTLASS down GEMM's
// red.adds; evict_first so the 88 MB of zero lines do not crowd the weight/token lines
// (evict_first: the 73-88 MB of zero lines must not crowd the re-gathered hidden_states token
// rows (each token is read by its 8 experts' gate|up items spread over the whole kernel) out of L2;
// zero lines are written back early and re-fetched by the down GEMM's reds instead)
pol_out = make_l2pol(out_pol_code); // runtime knob (full path: opol, gu_only: zpol)
// Hs is written once and read by the chunk's 14 down items: keep it L2-resident (evict_last);
// #BK: the 32-B Hs stores also carry .L1::no_allocate (never re-read through L1: consumers are TMA)
uint64_t pol_hs;
#ifdef MOE_HS_NORMAL
asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(pol_hs));
#else
asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol_hs));
#endif
// gu_only (large T): Hs (T*8 rows x 4 KB, >> L2) is consumed by the later CUTLASS down GEMM;
// write it evict_first so it streams to DRAM instead of displacing the shared token lines
if (gu_only) asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol_hs));
// Zero `out` here (folded out of route_kernel, overlapped with the first gate|up mainloops,
// which the epilogue warps would otherwise idle through). Grid-stride over 16-B vectors by
// all 128*gridDim epilogue threads; each warp then bumps the zero counter (num_items[1], reset
// by route_kernel); a down epilogue waits for all 4*gridDim warps before its first red.add.
int* zero_cnt = const_cast<int*>(num_items_ptr) + 1;
{
uint4* o4 = reinterpret_cast<uint4*>(out);
const int nthr = gridDim.x * EPI_T;
// zero stores carry the same L2 evict_last policy as the later red.adds, so the zeroed out
// lines stay L2-resident (no early DRAM writeback + re-fetch before the first reduction)
// (MOE_EARLYZ: the zero stores were already issued before route_in_kernel; only the publish
// remains here -- the counter is reset by the routing, so the bump must stay after it)
if (!MOE_EARLYZ)
for (int i = blockIdx.x * EPI_T + etid; i < (ABL_NOZERO ? 0 : out_vec); i += nthr) {
#if MOE_ZERO_EL
asm volatile("st.global.L2::cache_hint.v4.u32 [%0], {%1, %1, %1, %1}, %2;" ::"l"(o4 + i), "r"(0u), "l"(pol_out)
: "memory");
#else
o4[i] = make_uint4(0, 0, 0, 0);
#endif
}
(void)o4; (void)nthr;
__syncwarp();
#ifndef MOE_ZAGG
#define MOE_ZAGG 1
#endif
// MOE_ZAGG: CTA-aggregated out-zero publish -- all EPI_W epilogue warps meet at named barrier 10
// (EPI_T threads; CTA-scope ordering of every warp's zero stores), then ONE thread does a
// cumulative gpu-scope red.release of +EPI_W (zero_target unchanged): EPI_W x fewer same-address
// gpu atomics on num_items[1] right at the routing-barrier exit.
if (MOE_ZAGG) {
asm volatile("bar.sync 10, %0;" ::"r"(EPI_T) : "memory");
if (warp == 2 && lane == 0) red_release_gpu_add(zero_cnt, EPI_W);
} else if (lane == 0) {
// fence audit: red.release.gpu is cumulative over the warp's zero stores (ordered by
// __syncwarp, same as the Hs publish) -> the former __threadfence was redundant
red_release_gpu_add(zero_cnt, 1);
}
}
bool zero_seen = false;
const int zero_target = gridDim.x * EPI_W;
ISrc isrc = isrc_init();
int4 info;
uint32_t pj = 0; // MOE_PUBAGG: epilogue item sequence number (same in every epilogue warp)
// mailbox: 2 int4 slots after the 8 PUBAGG counters (smem reserved by launch_mega's +128 B)
const uint32_t mbox = iring_base + 16u * IRING + 32u;
auto epi_next = [&](int4& inf) -> bool {
if constexpr (EMBOX) {
const uint32_t slot = mbox + 16u * (isrc.qi & 1u);
if (warp == 2) {
int4 v = make_int4(-1, 0, 0, 0);
if (lane == 0) {
v = ring_get(isrc.qi);
asm volatile("st.shared.v4.s32 [%0], {%1, %2, %3, %4};" ::"r"(slot), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w) : "memory");
}
}
// writer's st.shared ordered before the readers' loads by the barrier; a 2-deep mailbox is safe
// with one barrier per item (slot q&1 is rewritten only after every warp passed barrier q+1)
asm volatile("bar.sync 9, %0;" ::"r"(EPI_T) : "memory");
asm volatile("ld.shared.v4.s32 {%0, %1, %2, %3}, [%4];" : "=r"(inf.x), "=r"(inf.y), "=r"(inf.z), "=r"(inf.w) : "r"(slot) : "memory");
++isrc.qi;
return inf.x >= 0;
} else {
return isrc_next(isrc, inf, true);
}
};
while (epi_next(info)) {
const bool gu = GUO || ((info.w >> 7) & 1);
const int m = info.w & 127, c = info.w >> 8;
const int row0 = info.y, n = info.z;
const int n16 = (n + 15) & ~15;
const bool nsw = NSW && gu; // non-swapped gate|up item: one 256-col buffer [gate | up]
const AccPlan ap = acc_plan(n16, nsw, ring);
// MOE_METAPRE: down items load the first 32-token step's metadata {out row offset, splatted
// weight} BEFORE the accumulator-full wait (meta is written by the routing, before the work
// loop), so the dependent L2 load is off the post-wait critical path of every down item.
// MOE_GUPRE: gate|up items compute their per-item Hs destination base pointers (swapped: this
// lane's 16-feature column group; NSW: this thread's token row) before the accf wait as well.
__nv_bfloat16* pre_hsq = hs + (size_t)row0 * INTER +
(m * BM2 + (int)rank * BM + q * 32 + 16 * (lane >> 4));
__nv_bfloat16* pre_hrow = hs + (size_t)(row0 + (int)rank * BM + row) * INTER + m * BM;
// down items: only the out row offset (meta.x) is needed -- the routing weight is folded into Hs
// MOE_DNROWPRE: the out row offsets of ALL this warp's 32-col down steps (column 32*eh + CSTEP*ci
// + lane) are loaded before the accf wait, so no dependent L2 load remains inside the drain loop
constexpr int DMAXC = (NCHUNK + CSTEP - 1) / CSTEP;
uint32_t pre_rows[DMAXC];
#pragma unroll
for (int ci = 0; ci < DMAXC; ++ci) {
const int col = 32 * eh + CSTEP * ci + lane;
pre_rows[ci] = (!gu && col < n) ? (uint32_t)__ldcg(reinterpret_cast<const int*>(meta + row0 + col)) : 0u;
}
// MOE_HSW (gu_only launches = MIX path, HSN == 1): the routing weight is folded into Hs,
// Hs' = bf16(bf16(silu(g)*u) * w), so the CUTLASS down epilogue red.adds bf16(acc) unscaled.
// Lane L prefetches (before the accf wait) the bf16x2-splatted weight of token column
// 32*eh + CSTEP*ci + L of each of its 32-col chunks ci: sorted_slot[row0 + col] -> ew[slot].
constexpr bool HSW = !NSW; // MOE_HSW_FULL: all swapped launches (full-mega + MIX)
constexpr int MAXCW = (NCHUNK + CSTEP - 1) / CSTEP;
uint32_t wpre[MAXCW];
#pragma unroll
for (int ci = 0; ci < MAXCW; ++ci) {
wpre[ci] = 0;
const int col = 32 * eh + CSTEP * ci + lane;
if (HSW && gu && meta != nullptr && col < n) { // #BO: meta also on gu_only launches
// full path: routing-time metadata already holds the bf16x2-splatted weight (one 8-B load)
wpre[ci] = (uint32_t)__ldcg(meta + row0 + col).y;
} else if (HSW && gu && col < n) { // fallback: no meta array
const int sl = __ldcg(sorted_slot + row0 + col);
const uint32_t wb = (uint32_t)__ldg(reinterpret_cast<const unsigned short*>(ew) + sl);
wpre[ci] = wb | (wb << 16);
}
}
uint32_t c_0, c_1; // TMEM column offsets of acc0 and acc1
PROF(const unsigned long long ta = clock64();)
mbar_wait_park(accf_bar(ap.s0), (upar >> ap.s0) & 1u);
if (ap.s1 >= 0) mbar_wait_park(accf_bar(ap.s1), (upar >> ap.s1) & 1u);
c_0 = ap.o0;
c_1 = ap.o1;
PROF(const unsigned long long tb = clock64(); w0 += tb - ta; ++w3;)
tc_fence_after();
const uint32_t tbase = tmem_base + ((uint32_t)(q * 32) << 16);
// Early accumulator release: each thread arrives on the leader's acce_bar(s) as soon as its
// LAST TMEM load of this item has completed (tcgen05.wait::ld), i.e. before the last chunk's
// SwiGLU math / Hs stores (or scale + red.adds). The MMA warp of the next item can then start
// writing the buffer(s) while this warp finishes its register-resident work. Threads with no
// 32-col chunk for this item (n <= 32*eh) arrive after the (empty) loop.
bool released = false;
// Release primitive: default-semantics (release.cta) remote arrive, as CUTLASS's TMEM-empty
// ClusterBarrier::arrive(cta, pred). Ordering needed is only "this thread's tcgen05.ld's
// completed before the MMA re-writes TMEM", given by tcgen05.wait::ld + fence::before_thread_sync.
// The former .release.cluster arrive had to wait for this thread's earlier in-flight global
// stores / red.adds (Hs, out) to be performed at cluster scope before signalling the MMA.
auto acc_arrive = [&](uint32_t cbar) {
if (ACC_OLDARR) mbar_arrive_cluster(cbar);
else asm volatile("mbarrier.arrive.shared::cluster.b64 _, [%0];" ::"r"(cbar) : "memory");
};
auto release_acc = [&]() {
tc_fence_before();
acc_arrive(mapa(acce_bar(ap.s0), 0));
if (ap.s1 >= 0) acc_arrive(mapa(acce_bar(ap.s1), 0));
released = true;
};
if (nsw) {
// Non-swapped: TMEM lane = token row (rank*128 + q*32 + lane) of the chunk, cols [0,128) =
// gate features m*128 + col, cols [128,256) = up. Warp half eh drains 32-col chunks eh,
// eh+2: per chunk SwiGLU of 32 consecutive features of ONE token -> 4 x 16-B Hs stores.
const int tr = (int)rank * BM + row;
if ((int)rank * BM + q * 32 < n) { // warp-uniform: some row of this warp is a real token
__nv_bfloat16* hrow = pre_hrow; // hoisted before the accf wait
#pragma unroll
for (int ci = 0; ci < 2; ++ci) {
const int cc = 32 * (eh + 2 * ci);
float g[32], u[32];
tmem_ld32(tbase + c_0 + cc, g);
tmem_ld32(tbase + c_0 + 128 + cc, u);
tmem_ld_wait();
if (ci == 1) release_acc(); // TMEM no longer needed by this thread
uint32_t p[16];
#pragma unroll
for (int j = 0; j < 16; ++j)
p[j] = pack_bf16x2(fast_silu(g[2 * j]) * u[2 * j], fast_silu(g[2 * j + 1]) * u[2 * j + 1]);
if (tr < n && !ABL_NOHSST) {
#pragma unroll
for (int v = 0; v < 4; ++v)
asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(hrow + cc + 8 * v),
"r"(p[4 * v]), "r"(p[4 * v + 1]), "r"(p[4 * v + 2]), "r"(p[4 * v + 3]), "l"(pol_hs)
: "memory");
}
}
}
} else if (gu) {
// Hs stores, 16 B per lane: SwiGLU for this lane's feature over 32 tokens, then the same
// 8x8 in-group transpose as the down epilogue -> lane (gg, gi) holds token tg*8+gi's 8
// consecutive features [colv, colv+8) -> one st.v4 per lane per 8 tokens (8x fewer stores)
const int gi = lane & 7, gg = lane >> 3;
const int colv = m * BM2 + (int)rank * BM + q * 32 + 8 * gg;
(void)colv;
// 16-lane groups for the 32-B Hs stores (32-B aligned: row stride 4 KB, colv16 multiple of 16)
const int gi16 = lane & 15;
const int colv16 = m * BM2 + (int)rank * BM + q * 32 + 16 * (lane >> 4);
__nv_bfloat16* const hsq = pre_hsq; // per-item Hs base (computed before the accf wait)
// full-line exchange (XCH): pair = quadrants (q, q^1) of the same column half eh
const bool qodd = (q & 1) != 0;
__nv_bfloat16* const hline = pre_hsq - (qodd ? 32 : 0) - 16 * (lane >> 4); // line start (feature q&~1 * 32)
(void)qodd; (void)hline;
(void)colv16;
// Phase A (TMEM drain): every 32-col chunk of this warp (cols 32*eh + 64*ci) is loaded from
// TMEM, SwiGLU'd in fp32 and packed to bf16x2 token pairs in registers (hp, 16 words per
// chunk); the accumulator buffer(s) are released right after the LAST chunk's math, so the
// next item's MMAs (wide items occupy both TMEM buffers) do not wait for the transposes and
// Hs stores of the earlier chunks. Phase B: unpack (exact) -> same pack+transpose -> stores.
// Rounding is unchanged: fp32 -> bf16 (rn) once, bf16 -> fp32 -> bf16 is exact.
constexpr int MAXC = (NCHUNK + CSTEP - 1) / CSTEP; // n <= NCHUNK -> at most ceil(NCHUNK/CSTEP) chunks per warp (NCH=160: 3)
uint32_t hp[MAXC][16];
#pragma unroll
for (int ci = 0; ci < MAXC; ++ci) {
const int c0 = 32 * eh + CSTEP * ci;
if (c0 < n) { // warp-uniform
float g[32], u[32];
// MOE_N16EXACT: n16 is a multiple of 16 -> a chunk holds 16 or 32 valid columns; a 16-column
// tail loads (and SwiGLUs / stores) only those 16 TMEM columns (warp-uniform)
const bool h16 = n - c0 <= 16;
if (h16) { tmem_ld16(tbase + c_0 + c0, g); tmem_ld16(tbase + c_1 + c0, u); }
else { tmem_ld32(tbase + c_0 + c0, g); tmem_ld32(tbase + c_1 + c0, u); }
tmem_ld_wait();
// last chunk of this warp: its TMEM loads have completed -> release the accumulator
// buffer(s) BEFORE this chunk's SwiGLU math (the next item's MMAs no longer wait for it)
if (c0 + CSTEP >= n || ci == MAXC - 1) release_acc();
// SwiGLU in fp32: silu(x) = x * rcp.approx(1 + ex2.approx(-x*log2e)) (no IEEE divide)
#pragma unroll
for (int j = 0; j < 16; ++j)
if (j < 8 || !h16) hp[ci][j] = ABL_NOSWI ? pack_bf16x2(g[2 * j] + u[2 * j], g[2 * j + 1] + u[2 * j + 1])
: swiglu2_bf16tanh(g[2 * j], g[2 * j + 1], u[2 * j], u[2 * j + 1]); // #BL: every swapped band (audit: all instantiated NCH already took this path)
}
}
if (!released) release_acc(); // warps with no 32-col chunk for this item
#pragma unroll
for (int ci = 0; ci < MAXC; ++ci) {
const int c0 = 32 * eh + CSTEP * ci;
if (c0 < n) {
#pragma unroll
for (int tg = 0; tg < 2; ++tg) {
if (tg == 1 && n - c0 <= 16) break; // MOE_N16EXACT: no token of this half is valid (pair-uniform)
// 256-bit stores: pack-then-transpose within each 16-lane group (pair exchange + 8x8
// 32-bit butterfly) -> lane (g16, i16) holds token tg*16+i16's 16 consecutive features
// [colv16, colv16+16) as 8 bf16x2 words -> one 32-B st.global.v8.b32 per lane
uint32_t p[8];
pack_transpose16_words(&hp[ci][tg * 8], gi16, p); // packed words: no unpack/re-cvt
if (XCH && xok) {
// FULL-LINE Hs STORES (gu_only launches): the two warps of a quadrant pair (q even = A,
// features [0,32) of a 64-feature / 128-B Hs line; q odd = B, features [32,64)) swap half
// their data through smem: A sends tokens 8..15 of this 16-token group, B tokens 0..7.
// Afterwards A holds full lines of tokens 0..7 and B of tokens 8..15, so each st.v8
// warp instruction writes 8 complete 128-B lines (was 16 half lines per warp, each line
// completed by a second warp). Same values -> bit-identical.
const bool sendme = qodd ? (gi16 < 8) : (gi16 >= 8);
const uint32_t slot = (uint32_t)((lane >> 4) * 8 + (gi16 & 7)) * 32u;
if (sendme) {
const uint32_t a = xstage + (qodd ? 512u : 0u) + slot;
asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a), "r"(p[0]), "r"(p[1]), "r"(p[2]), "r"(p[3]) : "memory");
asm volatile("st.shared.v4.b32 [%0], {%1, %2, %3, %4};" ::"r"(a + 16), "r"(p[4]), "r"(p[5]), "r"(p[6]), "r"(p[7]) : "memory");
}
asm volatile("bar.sync %0, 64;" ::"r"(xbar) : "memory");
if (sendme) { // the lanes that sent now receive the partner's data of the kept tokens
const uint32_t a = xstage + (qodd ? 0u : 512u) + slot;
asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" : "=r"(p[0]), "=r"(p[1]), "=r"(p[2]), "=r"(p[3]) : "r"(a) : "memory");
asm volatile("ld.shared.v4.b32 {%0, %1, %2, %3}, [%4];" : "=r"(p[4]), "=r"(p[5]), "=r"(p[6]), "=r"(p[7]) : "r"(a + 16) : "memory");
}
asm volatile("bar.sync %0, 64;" ::"r"(xbar) : "memory"); // staging free for the next round
// token of this lane's 32 B: A keeps tokens 0..7 (recv lanes gi16>=8 -> token gi16-8),
// B keeps 8..15 (recv lanes gi16<8 -> token gi16+8); features: low half of the line iff
// the data came from A
const int tk = qodd ? (gi16 | 8) : (gi16 & 7);
const int fo = ((qodd != sendme) ? 32 : 0) + 16 * (lane >> 4);
const int tl2 = tg * 16 + tk;
if (HSW) { // fold the routing weight of token c0 + tl2 into its Hs row
const uint32_t w2 = __shfl_sync(0xffffffffu, wpre[ci], tl2);
#pragma unroll
for (int j = 0; j < 8; ++j) bf16x2_mul_inplace(p[j], w2);
}
if (c0 + tl2 < n && !ABL_NOHSST) {
__nv_bfloat16* dst = hline + (size_t)(c0 + tl2) * INTER + fo;
asm volatile("st.global.L1::no_allocate.L2::cache_hint.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8}, %9;" ::"l"(dst),
"r"(p[0]), "r"(p[1]), "r"(p[2]), "r"(p[3]), "r"(p[4]), "r"(p[5]), "r"(p[6]), "r"(p[7]),
"l"(pol_hs)
: "memory");
}
continue;
}
const int tl = tg * 16 + gi16;
if (HSW) { // fold the routing weight of token c0 + tl into its Hs row
const uint32_t w2 = __shfl_sync(0xffffffffu, wpre[ci], tl);
#pragma unroll
for (int j = 0; j < 8; ++j) bf16x2_mul_inplace(p[j], w2);
}
if (c0 + tl < n && !ABL_NOHSST) {
__nv_bfloat16* dst = hsq + (size_t)(c0 + tl) * INTER;
asm volatile("st.global.L1::no_allocate.L2::cache_hint.v8.b32 [%0], {%1, %2, %3, %4, %5, %6, %7, %8}, %9;" ::"l"(dst),
"r"(p[0]), "r"(p[1]), "r"(p[2]), "r"(p[3]), "r"(p[4]), "r"(p[5]), "r"(p[6]), "r"(p[7]),
"l"(pol_hs)
: "memory");
}
}
}
}
} else {
// out[token, f] += w * acc (both 128-row tiles; acc1 = hidden rows +256), 8 features per op
if (!zero_seen) { // all CTAs finished zeroing out (once per kernel)
while (ld_acquire_gpu(zero_cnt) < zero_target) __nanosleep(128);
zero_seen = true;
}
const int gi = lane & 7, gg = lane >> 3; // 8-lane transpose group: index in group, group
// dil 0: acc0 lane (q, i) = feature 256r + 64q + i, acc1 = +32 -> group gg = features 8gg.
// dil 1: acc0 lane (q, i) = feature 64q + 32*(i/16) + i%16, acc1 = +16 -> group gg = 32*(gg>>1) + 8*(gg&1)
const int colq = dn_mt(m) * (2 * BM2) + (int)rank * BM2 + q * 64 + (dil ? 32 * (gg >> 1) + 8 * (gg & 1) : 8 * gg);
const int fofs = dil ? 16 : 32; // feature offset of the acc1 (p1) words
const bool upr = gi >= 4; // upper half of the 8-lane group
const int fA = upr ? fofs : 0, fB = upr ? 0 : fofs;
__nv_bfloat16* outq = out + colq;
__nv_bfloat16* const outA = outq + fA; // hoisted per-lane red base pointers
__nv_bfloat16* const outB = outq + fB;
#pragma unroll
for (int ci = 0; ci < DMAXC; ++ci) {
const int c0 = 32 * eh + CSTEP * ci;
if (c0 >= n) break; // warp-uniform
const uint32_t my_row = pre_rows[ci]; // prefetched before the accf wait
float a0[32], a1[32];
const bool h16 = n - c0 <= 16; // MOE_N16EXACT: 16-column tail chunk (warp-uniform)
if (h16) { tmem_ld16(tbase + c_0 + c0, a0); tmem_ld16(tbase + c_1 + c0, a1); }
else { tmem_ld32(tbase + c_0 + c0, a0); // both 32-col loads in flight, one wait
tmem_ld32(tbase + c_1 + c0, a1); }
tmem_ld_wait();
if (c0 + CSTEP >= n) release_acc(); // last chunk of this warp: TMEM no longer needed
#pragma unroll
for (int tg = 0; tg < 4; ++tg) {
if (tg >= 2 && h16) break; // MOE_N16EXACT: tokens c0+16.. invalid
// lane (gg, gi) -> token tg*8+gi's features [8gg, +8) (p0) and acc1 counterpart (p1)
uint32_t P[4], Q[4];
pack_transpose_bf16x2_s1(a0 + tg * 8, gi, P);
pack_transpose_bf16x2_s1(a1 + tg * 8, gi, Q);
uint32_t R[4];
R[0] = __shfl_xor_sync(0xffffffffu, upr ? P[0] : P[2], 4);
R[1] = __shfl_xor_sync(0xffffffffu, upr ? P[1] : P[3], 4);
R[2] = __shfl_xor_sync(0xffffffffu, upr ? Q[2] : Q[0], 4);
R[3] = __shfl_xor_sync(0xffffffffu, upr ? Q[3] : Q[1], 4);
uint32_t qa[4], qb[4];
qa[0] = upr ? R[2] : P[0]; qa[1] = upr ? R[3] : P[1]; qa[2] = upr ? Q[0] : R[0]; qa[3] = upr ? Q[1] : R[1];
qb[0] = upr ? R[0] : Q[2]; qb[1] = upr ? R[1] : Q[3]; qb[2] = upr ? P[2] : R[2]; qb[3] = upr ? P[3] : R[3];
const int tA = tg * 8 + (gi & 3), tB = tA + 4;
const uint32_t roffA = __shfl_sync(0xffffffffu, my_row, tA);
const uint32_t roffB = __shfl_sync(0xffffffffu, my_row, tB);
if (!ABL_NORED) {
if (c0 + tA < n)
asm volatile("red.global.add.noftz.L2::cache_hint.v4.bf16x2 [%0], {%1, %2, %3, %4}, %5;" ::"l"(outA + roffA),
"r"(qa[0]), "r"(qa[1]), "r"(qa[2]), "r"(qa[3]), "l"(pol_out) : "memory");
if (c0 + tB < n)
asm volatile("red.global.add.noftz.L2::cache_hint.v4.bf16x2 [%0], {%1, %2, %3, %4}, %5;" ::"l"(outB + roffB),
"r"(qb[0]), "r"(qb[1]), "r"(qb[2]), "r"(qb[3]), "l"(pol_out) : "memory");
}
}
}
}
PROF(w1 += clock64() - tb;)
// signal the leader's MMA warp that the buffer(s) are drained (if not already done early)
if (!released) release_acc();
upar ^= 1u << ap.s0;
if (ap.s1 >= 0) upar ^= 1u << ap.s1;
if (!gu) {
// Hs of chunk c is dead once every down epilogue warp of the chunk has finished (their
// MMAs, hence the TMA reads of Hs, completed before the accumulator was readable).
// The last of the 112 warps drops the chunk's Hs lines from L2 without DRAM writeback.
#ifndef MOE_DNAGG
#define MOE_DNAGG 1
#endif
// MOE_DNAGG: CTA-aggregated down-done arrival (same per-item smem slot scheme as the gate|up
// MOE_PUBAGG publish; every item, either kind, adds exactly EPI_W to slot pj % 8, and the
// epilogue warps are at most one item apart (mailbox barrier), so slots never mix live items).
// Only the CTA's LAST epilogue warp of this item does ONE returning global atomicAdd(+EPI_W)
// and the Hs-discard test; the other EPI_W-1 warps no longer stall on a global atomic round trip.
// All warps of the CTA have passed this item's accf wait (MMAs, hence Hs TMA reads, complete)
// before the aggregated arrival, so the discard condition is unchanged.
int prevc = -1;
if (lane == 0) {
if (MOE_DNAGG) {
uint32_t v;
asm volatile("atom.acq_rel.cta.shared::cta.add.u32 %0, [%1], 1;"
: "=r"(v) : "r"(iring_base + 16u * IRING + 4u * (pj & 7u)) : "memory");
if ((v % (uint32_t)EPI_W) == (uint32_t)EPI_W - 1u) prevc = atomicAdd(done + 2 * c + 1, EPI_W);
} else {
prevc = atomicAdd(done + 2 * c + 1, 1);
}
}
prevc = __shfl_sync(0xffffffffu, prevc, 0);
// MOE_TAILNODISC: split chunks (queue tail, m >= DSPLIT_BASE) skip the fence + discard loop so the
// final epilogue warps finish sooner (their ~2 MB of dead Hs is simply left dirty in L2)
if (m < DSPLIT_BASE && prevc == (MOE_DNAGG ? DDT - EPI_W : DDT - 1)) {
__threadfence();
const char* hb = reinterpret_cast<const char*>(hs + (size_t)row0 * INTER);
const int nlines = n * (INTER * 2 / 128); // 32 x 128-B lines per Hs row
for (int i = lane; i < nlines; i += 32) discard_l2(hb + (size_t)i * 128);
}
}
if (gu) {
// publish this warp's Hs rows to the down items of chunk c (other SMs, TMA readers)
// __syncwarp orders the other lanes' Hs stores before lane 0's release (PTX release is
// cumulative over writes observed via the warp barrier); fence.proxy.async makes the generic
// stores visible to the consumers' TMA (async proxy) reads; red.release.gpu publishes.
// (The former extra __threadfence = fence.sc.gpu was redundant with the release.)
__syncwarp();
if (lane == 0) {
fence_proxy_async_global();
// MOE_PUBAGG_GU (T>=4096 MIX gate|up launches): same CTA-level aggregation as the full path --
// 1 gpu-scope red.release (+EPI_W) per CTA per item instead of EPI_W; done[2c] target unchanged
if (GUO && !MOE_PUBAGG_GU) {
red_release_gpu_add(done + 2 * c, 1);
} else {
// MOE_PUBAGG (full path): CTA-level aggregation of the done[2c] publish. Each warp does a
// CTA-scope acq_rel add on the smem counter of its item slot (pj % 8; epilogue warps are at
// most ACC_BUFS <= 3 items apart, so a slot is never shared by two live items); the LAST of
// the CTA's EPI_W warps (count % EPI_W == EPI_W-1) acquires every other warp's Hs stores and
// publishes them all with ONE gpu-scope red.release of +EPI_W (cumulative), so done[] targets
// are unchanged and only 1 of EPI_W warps per item pays the gpu-scope release fence.
uint32_t v;
asm volatile("atom.acq_rel.cta.shared::cta.add.u32 %0, [%1], 1;"
: "=r"(v) : "r"(iring_base + 16u * IRING + 4u * (pj & 7u)) : "memory");
if ((v % (uint32_t)EPI_W) == (uint32_t)EPI_W - 1u) red_release_gpu_add(done + 2 * c, EPI_W);
}
}
}
++pj;
}
PROF(if (warp == 2 && lane == 0) { pr[4] = gtime(); pr[10] = w0; pr[11] = w1; pr[12] = w3; })
}
// MOE_EARLYTRIG (MIX path): every thread of a gu_only launch triggers its PDL dependents (the
// CUTLASS batch-1 down GEMM) as soon as its role's DQ queue is exhausted, BEFORE the teardown
// CTA/cluster barriers, so the CTA counts as triggered without waiting for its slowest role and
// the dependent grid is scheduled onto SMs as soon as megakernel CTAs exit. Safe: the down
// GEMM's load warps griddepcontrol.wait for this grid's full completion + flush before reading Hs.
if (gu_only) pdl_launch_dependents();
tc_fence_before();
__syncthreads();
cluster_sync(); // peer must not exit/dealloc while the pair still uses its smem/TMEM
#ifdef MOE_TLPROBE
if (threadIdx.x == 0 && gu_only) { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); atomicMin(&g_tlk[0], t); atomicMax(&g_tlk[1], t); }
#endif
PROF(if (threadIdx.x == 0) { pr[5] = gtime(); pr[14] = clock64() - c_entry; pr[15] = pr[5] - t_entry; })
// all roles of this CTA finished: the next PDL kernel on the stream may start
pdl_launch_dependents();
if (warp == 1) {
tc_fence_after();
asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, 512;" ::"r"(tmem_base));
}
}
// ------------------------------------------------------------------- host side
// Down-weight 4D view [K=2048][32 rows][2 halves][NEXP*HID/64 groups of 64 rows]; box {64, 32, 1, 4}
// = rows 0..31 (half 0) or 32..63 (half 1) of 4 consecutive 64-row groups -> 128 smem rows (SW128).
static void make_tmap_down4(CUtensorMap* tm, const void* ptr, CUtensorMapL2promotion promo, int dil = 0) {
// dil 0: [K][32 rows][2 halves][groups of 64 rows], box {64, 32, 1, 4};
// dil 1: [K][16 rows][2 halves][groups of 32 rows], box {64, 16, 1, 8} (both 128 smem rows)
// 8-entry cache keyed by (ptr, promo, dil): the small-T band (dil 1), other full-mega bands (dil 0)
// and the MIX path (256B, dil 0) no longer evict each other's encoded map.
struct D4 { const void* p; int pr, dl; CUtensorMap m; };
static D4* c4 = new D4[8]();
static int n4 = 0;
for (int i = 0; i < 8; ++i)
if (c4[i].p == ptr && ptr && c4[i].pr == (int)promo && c4[i].dl == dil) { *tm = c4[i].m; return; }
const uint64_t hr = dil ? 16 : 32;
cuuint64_t dims[4] = {INTER, hr, 2, (cuuint64_t)NEXP * HID / (2 * hr)};
cuuint64_t strides[3] = {INTER * 2, hr * INTER * 2, 2 * hr * INTER * 2};
cuuint32_t box[4] = {BK, (cuuint32_t)hr, 1, (cuuint32_t)(128 / hr)};
cuuint32_t es[4] = {1, 1, 1, 1};
CUresult r = cuTensorMapEncodeTiled(tm, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 4, const_cast<void*>(ptr), dims, strides, box,
es, CU_TENSOR_MAP_INTERLEAVE_NONE,
BK == 64 ? CU_TENSOR_MAP_SWIZZLE_128B : CU_TENSOR_MAP_SWIZZLE_64B, promo,
CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE);
if (r != CUDA_SUCCESS) { fprintf(stderr, "cuTensorMapEncodeTiled(down4) failed %d\n", (int)r); return; }
c4[n4].p = ptr; c4[n4].pr = (int)promo; c4[n4].dl = dil; c4[n4].m = *tm; n4 = (n4 + 1) & 7;
}
static void make_tmap(CUtensorMap* tm, const void* ptr, uint64_t inner, uint64_t outer,
uint32_t box_inner, uint32_t box_outer,
CUtensorMapL2promotion promo = CU_TENSOR_MAP_L2_PROMOTION_L2_256B) {
// Host-side cache of encoded maps keyed by every encode parameter (encoding is deterministic):
// repeated calls with the same tensors skip the driver encode (8 maps per call).
struct TmEnt { const void* p; uint64_t in, out; uint32_t bi, bo; int pr; CUtensorMap m; };
static TmEnt* cache = new TmEnt[64](); // heap, never freed (no device state)
static int nxt = 0;
for (int i = 0; i < 64; ++i) {
const TmEnt& c = cache[i];
if (c.p == ptr && c.p && c.in == inner && c.out == outer && c.bi == box_inner && c.bo == box_outer && c.pr == (int)promo) {
*tm = c.m;
return;
}
}
cuuint64_t dims[2] = {inner, outer};
cuuint64_t strides[1] = {inner * 2};
cuuint32_t box[2] = {box_inner, box_outer};
cuuint32_t es[2] = {1, 1};
CUresult r = cuTensorMapEncodeTiled(tm, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast<void*>(ptr),
dims, strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE,
BK == 64 ? CU_TENSOR_MAP_SWIZZLE_128B : CU_TENSOR_MAP_SWIZZLE_64B, promo,
CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE);
if (r != CUDA_SUCCESS) { fprintf(stderr, "cuTensorMapEncodeTiled failed %d\n", (int)r); return; }
TmEnt& c = cache[nxt];
nxt = (nxt + 1) & 63;
c.p = ptr; c.in = inner; c.out = outer; c.bi = box_inner; c.bo = box_outer; c.pr = (int)promo; c.m = *tm;
}
// Pipeline depth (227 KB opt-in smem): WS weight stages (32 KB) + XS token slots (NCH/2 rows).
// NCH=128: 6 x 32 KB + 4 x 8 KB; NCH=192: 5 x 32 KB + 5 x 12 KB; NCH=256: 5 x 32 KB + 4 x 16 KB
// (seed: one shared 40/44/48 KB stage -> only 5/5/4 weight stages)
constexpr size_t SMEM_MAX = 232448, SMEM_EXTRA = 1024 + 512; // + DQ item ring / barriers
constexpr int wstage_bytes() { return 2 * BM * BK * 2; }
constexpr int xslot_bytes(int nch) { return (nch / 2) * BK * 2; }
// MOE_WT11: NCH=176 -> WS 6 barrier stages / 11 weight tile slots / XS 4 token slots (was WS5/XS5)
constexpr int num_wstages(int nch) { return (nch == 128 || nch == 160 || nch == 176) ? 6 : 5; }
constexpr int num_xslots(int nch) { return nch == 128 ? 4 : (nch == 160 ? 3 : (nch == 176 ? 4 : (nch == 192 ? 5 : 4))); }
// weight smem bytes (full-mega launches; NCH=176 is never a gate|up-only launch)
constexpr int num_wtiles(int nch) { return nch == 176 ? 2 * num_wstages(nch) - 1 : 2 * num_wstages(nch); }
constexpr size_t wring_bytes(int nch) { return (size_t)num_wtiles(nch) * (wstage_bytes() / 2); }
// alternative split (knob a.ring=1): fewer token slots -> longer token trail TLAG
constexpr int num_xslots_alt(int nch) { return nch == 128 ? 3 : (nch == 160 ? 3 : ((nch == 192 || nch == 176) ? 4 : 3)); }
constexpr size_t smem_bytes(int nch) {
return wring_bytes(nch) + (size_t)num_xslots(nch) * xslot_bytes(nch) + SMEM_EXTRA;
}
static_assert(num_xslots(128) >= 3 && num_xslots(192) >= 3 && num_xslots(256) >= 3, "token ring >= 3");
static_assert(smem_bytes(224) + 4096 <= SMEM_MAX && smem_bytes(240) + 2048 <= SMEM_MAX && smem_bytes(176) <= SMEM_MAX && smem_bytes(160) <= SMEM_MAX && smem_bytes(256) <= SMEM_MAX && smem_bytes(192) <= SMEM_MAX && smem_bytes(128) <= SMEM_MAX, "smem");
static int g_num_sms = 0;
#ifdef MOE_HPROBE
#include <chrono>
double g_hp_lu = 0, g_hp_pre = 0; int g_hp_nowin = 0;
#endif
static HsMaps g_hsm; // exact-height Hs maps of the current launch
static int g_grid = 0; // megakernel grid (CTAs) of the last launch
void** g_mega_args = nullptr; // kernelParams of the last launch_mega (graph node update)
int g_mega_dry = 0, g_mega_nopdl = 0;
static bool g_lwin_on = false; // launch-attribute L2 window of the next launch_mega
static cudaAccessPolicyWindow g_lwin = {};
// persistent grid = number of co-resident 2-CTA clusters (required: down items spin-wait on
// gate|up items of other clusters, so every cluster must be resident)
static int cluster_grid(const void* f, size_t smem, int nthreads) {
cudaLaunchConfig_t cfg = {};
cfg.gridDim = dim3(g_num_sms & ~1);
cfg.blockDim = dim3(nthreads);
cfg.dynamicSmemBytes = smem;
int nc = 0;
if (cudaOccupancyMaxActiveClusters(&nc, f, &cfg) != cudaSuccess || nc <= 0) {
cudaGetLastError();
nc = g_num_sms / 2;
}
return 2 * min(nc, g_num_sms / 2);
}
template <int NCH, int ALT, int CPX = 0, int DQ = 0, int NSW = 0, int EW = 8, int HSN = NCH / 16>
static void launch_mega(const MoeArgs& a, const CUtensorMap& tg, const CUtensorMap& tu, const CUtensorMap& td,
const CUtensorMap& tx, cudaStream_t st) {
// MOE_WT11_GU192: NCH=192 gate|up-only launch -> WS6 / WT11 / XS4 (tile-granular weight ring)
constexpr bool WT11G = (NCH == 192 && HSN == 1 && !NSW && !ALT);
// MOE_WT9_GU256: NCH=256 gate|up-only launch -> WS5 / WT9 / XS5 (one more 16 KB token slot)
constexpr bool WT9G = (NCH == 256 && HSN == 1 && !NSW && !ALT);
constexpr int WSL = WT11G ? 6 : num_wstages(NCH);
constexpr int XS = WT11G ? 4 : (WT9G ? 5 : (ALT ? num_xslots_alt(NCH) : num_xslots(NCH)));
constexpr size_t WRB = (WT11G || WT9G) ? (size_t)(2 * WSL - 1) * (wstage_bytes() / 2) : wring_bytes(NCH);
static_assert(!WT9G || (WSL == 5 && XS <= WSL), "WT9 ring: WS5, XS <= WS");
auto k = moe_mega_kernel<WSL, XS, NCH, CPX, DQ, NSW, EW, HSN>;
constexpr int nthr = (CPX ? 32 : 0) + 7 * 32 + (EW - 4) * 32; // CPX: + token-loader warp
// gu_only launches (HSN == 1): + full-line Hs exchange staging (1 KB per epilogue quadrant pair), capped
// at the opt-in limit (kernel falls back to half-line stores if it does not fit at run time)
// MOE_DNU49: NCH=176 full-mega DYNTOK band -> token area = MOE_DNU176 1-KB units (kernel DNU / bar_base)
constexpr bool D176 = (NCH == 176 && CPX && HSN != 1 && !NSW && EW == 8);
constexpr size_t TOKB = D176 ? (size_t)MOE_DNU176 * 1024 : (size_t)XS * xslot_bytes(NCH);
static_assert(!D176 || TOKB >= (size_t)XS * xslot_bytes(NCH), "176 token area");
constexpr size_t sm0 = WRB + TOKB + SMEM_EXTRA +
(DQ ? 128 : 0); // MOE_EPIMBOX mailbox (all DQ launches)
static_assert(sm0 <= SMEM_MAX, "smem");
constexpr size_t sm = (HSN == 1 && !NSW) ? std::min(SMEM_MAX, sm0 + 1024 * (EW / 2)) : sm0;
static int grid = 0;
if (!grid) {
cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)sm);
grid = cluster_grid((const void*)k, sm, nthr);
}
// MOE_GRIDCAP (power-capped MIX band): optionally run the gate|up-only launch on fewer clusters
// (fewer active SMs -> higher sustained clock under the power cap). Persistent DQ grid, so any
// even grid <= the co-resident maximum is valid.
const int grid_full = grid;
int glaunch = grid_full;
if (HSN == 1 && a.grid_cap > 0 && a.grid_cap < grid_full) {
glaunch = std::max(2, a.grid_cap & ~1);
if ((grid_full - glaunch) / 2 >= MOE_NBAR_SLOTS) glaunch = grid_full - 2 * (MOE_NBAR_SLOTS - 1);
}
const int bar_slot = (grid_full - glaunch) / 2;
// PDL launch: overlaps the prologue with route_kernel (kernel calls griddepcontrol.wait)
g_grid = glaunch;
cudaLaunchConfig_t cfg = {};
cfg.gridDim = dim3(glaunch);
cfg.blockDim = dim3(nthr);
cfg.dynamicSmemBytes = sm;
cfg.stream = st;
cudaLaunchAttribute attr[2];
attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization;
attr[0].val.programmaticStreamSerializationAllowed = 1;
cfg.attrs = attr;
cfg.numAttrs = 1;
// MOE_LAUNCHWIN: persisting-L2 access-policy window as a PER-LAUNCH attribute (applies to this
// launch only) instead of a stream attribute set before + cleared after the launch (2 driver calls,
// the first on the host critical path before the launch).
if (g_lwin_on) {
attr[1].id = cudaLaunchAttributeAccessPolicyWindow;
attr[1].val.accessPolicyWindow = g_lwin;
cfg.numAttrs = 2;
}
const int S = a.T * TOPK;
const int RC = (S + glaunch - 1) / glaunch; // assignments routed per CTA
// routing scratch (5x256+8 + 2*RC ints) must fit in the (not yet used) stage ring
if ((size_t)(5 * NEXP + 8 + 3 * RC) * 4 > WRB) {
// fail loudly (Python RuntimeError) instead of silently returning an unwritten output
throw std::runtime_error("moe: num_tokens " + std::to_string(a.T) + " too large for in-kernel routing");
}
constexpr int bar_idx = NCH == 224 ? 416 + (DQ ? 1 : 0) + 2 * CPX : NCH == 240 ? 400 + (DQ ? 1 : 0) + 2 * CPX + (EW == 4 ? 8 : 0) : NCH == 176 ? 384 + (DQ ? 1 : 0) + 2 * CPX : (((((NCH == 128 ? 0 : (NCH == 192 ? 1 : (NCH == 160 ? 3 : 2))) * 2 + (ALT ? 1 : 0)) * 4 + CPX) * 2 + (DQ ? 1 : 0)) * 2 + (NSW ? 1 : 0) + (EW == 4 ? 128 : 0) + (HSN == 1 ? 256 : 0));
static_assert(bar_idx < MOE_NBAR, "barrier counter index");
XMapT<CPX> xm;
if constexpr (CPX) xm.unused = 0; else xm = tx;
HsMapsN<HSN> hm;
for (int i = 0; i < HSN; ++i) hm.m[i] = g_hsm.m[i];
// MIX-path CUDA graph support: the launch arguments are kept in a per-instantiation heap pack
// (never freed) and exposed as a kernelParams array (g_mega_args), so the host can update the
// megakernel node of an instantiated graph (cudaGraphExecKernelNodeSetParams) with this call's
// pointers. g_mega_dry: only rebuild the pack, no launch. g_mega_nopdl: no PDL attribute
// (graph capture: the megakernel is the graph's first kernel).
struct Pack {
CUtensorMap tg, tu, td; XMapT<CPX> xm; HsMapsN<HSN> hm; int4* item_info; int* num_items; int* done;
int* sorted_slot; const __nv_bfloat16* ew; __nv_bfloat16* hs; __nv_bfloat16* out; int lag; int out_vec;
const long long* ids; int S; int RC; int bar; int xpol; const __nv_bfloat16* hidden; int gu_only; int* inv;
unsigned int epoch; int h64; int* cnt_out; int2* meta; DnFill dnf;
};
static Pack* pk = new Pack();
static void** pp = nullptr;
if (!pp) {
pp = new void*[27];
void* q[27] = {&pk->tg, &pk->tu, &pk->td, &pk->xm, &pk->hm, &pk->item_info, &pk->num_items, &pk->done,
&pk->sorted_slot, &pk->ew, &pk->hs, &pk->out, &pk->lag, &pk->out_vec, &pk->ids, &pk->S, &pk->RC,
&pk->bar, &pk->xpol, &pk->hidden, &pk->gu_only, &pk->inv, &pk->epoch, &pk->h64, &pk->cnt_out,
&pk->meta, &pk->dnf};
for (int i = 0; i < 27; ++i) pp[i] = q[i];
}
pk->tg = tg; pk->tu = tu; pk->td = td; pk->xm = xm; pk->hm = hm; pk->item_info = a.item_info;
pk->num_items = a.num_items; pk->done = a.done; pk->sorted_slot = a.sorted_slot; pk->ew = a.ew; pk->hs = a.hs;
pk->out = a.out; pk->lag = a.lag; pk->out_vec = (a.gu_only && !a.gu_zero) ? 0 : a.T * (HID / 8); pk->ids = a.ids;
pk->S = S; pk->RC = RC; pk->bar = bar_idx + MOE_NBAR * bar_slot;
pk->xpol = (a.xpol & 15) | ((a.opol & 15) << 4) | ((a.zpol & 15) << 8) | ((a.gu_only ? 0 : (a.dil & 15)) << 12) |
((a.r3off & 1) << 16) | ((a.pblk & 1) << 17);
pk->hidden = a.hidden; pk->gu_only = a.gu_only; pk->inv = a.inv; pk->epoch = a.epoch; pk->h64 = a.h64;
pk->cnt_out = a.cnt_out; pk->meta = a.meta;
pk->dnf = a.dnf;
if (!a.gu_only) pk->dnf.on = 0;
g_mega_args = pp;
if (g_mega_dry) return;
if (g_mega_nopdl) cfg.numAttrs = 0;
#ifdef MOE_HPROBE
if (g_hp_nowin) cfg.numAttrs = 1;
const auto hp0 = std::chrono::steady_clock::now();
g_hp_pre = std::chrono::duration<double, std::micro>(hp0.time_since_epoch()).count();
#endif
cudaLaunchKernelEx(&cfg, k, pk->tg, pk->tu, pk->td, pk->xm, pk->hm, pk->item_info, pk->num_items, pk->done,
pk->sorted_slot, pk->ew, pk->hs, pk->out, pk->lag, pk->out_vec, pk->ids, pk->S, pk->RC, pk->bar,
pk->xpol, pk->hidden, pk->gu_only, pk->inv, pk->epoch, pk->h64, pk->cnt_out, pk->meta, pk->dnf);
#ifdef MOE_HPROBE
g_hp_lu = std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - hp0).count();
#endif
}
#ifdef MOE_PROF
#include <string>
#include <vector>
#include <algorithm>
#include <stdexcept>
static int g_prof_T = 0;
#include <chrono>
__device__ unsigned long long g_stamp;
__global__ void prof_stamp_kernel() { g_stamp = gtime(); }
static double g_h[4]; // host us: pre-launch setup, launch, post (window clear)
static double hnow() { return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
#define HT(i) g_h[i] = hnow()
static std::string prof_report(int nblk, int T);
std::string moe_prof_last() { return prof_report(g_grid, g_prof_T); }
void moe_set_abl(int v) { cudaMemcpyToSymbol(g_abl, &v, 4); cudaDeviceSynchronize(); }
void moe_prof_waits(double* mfull, double* tokE, double* pEmpty) {
std::vector<unsigned long long> h(160 * PROF_N);
cudaDeviceSynchronize();
cudaMemcpyFromSymbol(h.data(), g_prof, h.size() * 8);
double cy = 0, ns = 0;
for (int b = 0; b < g_grid; ++b) { cy += h[b * PROF_N + 14]; ns += h[b * PROF_N + 15]; }
const double c2u = ns / cy / 1000.0;
auto med = [&](int f, bool lead) { std::vector<double> v; for (int b = 0; b < g_grid; ++b) { if (lead && (b & 1)) continue; v.push_back(h[b * PROF_N + f] * c2u); }
std::sort(v.begin(), v.end()); return v[v.size() / 2]; };
*mfull = med(8, true); *tokE = med(9, true); /* MMA acce wait (leader) */ *pEmpty = med(6, false);
}
void moe_prof_clk(double* mhz, double* span_us) {
std::vector<unsigned long long> h(160 * PROF_N);
cudaDeviceSynchronize();
cudaMemcpyFromSymbol(h.data(), g_prof, h.size() * 8);
double cy = 0, ns = 0; unsigned long long t0 = ~0ull, t1 = 0;
for (int b = 0; b < g_grid; ++b) { cy += h[b * PROF_N + 14]; ns += h[b * PROF_N + 15];
t0 = std::min(t0, h[b * PROF_N]); t1 = std::max(t1, h[b * PROF_N + 5]); }
*mhz = cy / ns * 1000.0; *span_us = (double)(t1 - t0) / 1000.0;
}
static std::string prof_report(int nblk, int T) {
std::vector<unsigned long long> h(160 * PROF_N);
cudaDeviceSynchronize();
cudaMemcpyFromSymbol(h.data(), g_prof, h.size() * 8);
int khz = 0; cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, 0);
double cy = 0, ns = 0;
for (int b = 0; b < nblk; ++b) { cy += h[b * PROF_N + 14]; ns += h[b * PROF_N + 15]; }
const double cyc2us = ns / cy / 1000.0;
(void)khz;
unsigned long long t0 = ~0ull;
for (int b = 0; b < nblk; ++b) t0 = std::min(t0, h[b * PROF_N]);
auto stat = [&](int f, bool abs_t, double sc) {
std::vector<double> v;
for (int b = 0; b < nblk; ++b) {
if (f == 3 || f == 8 || f == 9 || (f >= 20 && f < 24)) { if (b & 1) continue; } // MMA: leader only
unsigned long long x = h[b * PROF_N + f];
v.push_back(abs_t ? (double)(x - t0) / 1000.0 : x * sc);
}
std::sort(v.begin(), v.end());
double s = 0; for (double x : v) s += x;
char buf[160];
snprintf(buf, sizeof buf, "f%d min %.1f med %.1f mean %.1f max %.1f | ", f, v.front(), v[v.size() / 2], s / v.size(), v.back());
return std::string(buf);
};
auto st3 = [&](int f, bool abs_t, double sc) { // compact min/med/max
std::vector<double> v;
for (int b = 0; b < nblk; ++b) {
if (f == 3 || f == 8 || f == 9 || (f >= 20 && f < 24)) { if (b & 1) continue; }
if (f == 27 && (b & 1)) continue;
unsigned long long x = h[b * PROF_N + f];
v.push_back(abs_t ? (double)(x - t0) / 1000.0 : x * sc);
}
std::sort(v.begin(), v.end());
char buf[64]; snprintf(buf, sizeof buf, "%.0f/%.0f/%.0f", v.front(), v[v.size() / 2], v.back());
return std::string(buf);
};
unsigned long long stamp = 0; cudaMemcpyFromSymbol(&stamp, g_stamp, 8);
char hb[128]; snprintf(hb, sizeof hb, " stamp->entry %.1f host pre %.1f launch %.1f post %.1f ", (double)((long long)(t0 - stamp)) / 1000.0, g_h[1] - g_h[0], g_h[2] - g_h[1], g_h[3] - g_h[2]);
std::string r = std::string(hb) + "MHz" + std::to_string((int)(cy / ns * 1000)) + " pdl " + st3(16, true, 0) + " gb1 " + st3(17, true, 0) +
" gb2 " + st3(18, true, 0) + " tma0 " + st3(27, true, 0) + " end " + st3(5, true, 0) + " pEmpty " + st3(6, false, cyc2us) +
" pDep " + st3(7, false, cyc2us) + " nDep " + st3(13, false, 1) + " mFull " + st3(8, false, cyc2us) + " mAcce " + st3(9, false, cyc2us) +
" eAccf " + st3(10, false, cyc2us) + " eWork " + st3(11, false, cyc2us) + " eItems " + st3(12, false, 1) + " tokE " + st3(19, false, cyc2us) +
" mTok " + st3(21, false, cyc2us) + " pNext " + st3(24, false, cyc2us) + " qClaim " + st3(28, false, cyc2us) + " qIempty " + st3(29, false, cyc2us) + " qPub " + st3(30, false, cyc2us) + " qPeer " + st3(31, false, cyc2us);
return r;
}
#endif
// persisting-L2 state (device-wide set-aside), shared by moe_forward and moe_clear_persist
static int maxp = -1, maxw = 0;
static size_t cur_limit = 0;
static bool g_win_dirty = true; // stream window possibly set (unknown at start)
// CUTLASS path (large T): no window is set there; drop the megakernel's persisting set-aside so
// the whole L2 is available to it (only when it is currently non-zero).
// Large-T probe ('large-T no-persist'): besides dropping the set-aside to 0, demote any lines still
// marked persisting by earlier mid-T calls (cudaCtxResetPersistingL2Cache, only on the transition)
// and explicitly clear the stream's access-policy window, so out / Hs / tokens on the MIX path see
// plain L2 behaviour. The mid-T path (moe_forward) re-reserves its set-aside on its next call.
void moe_clear_persist(cudaStream_t st) {
if (maxp < 0) {
cudaDeviceGetLimit(&cur_limit, cudaLimitPersistingL2CacheSize);
cudaGetLastError();
}
if (cur_limit != 0) {
if (cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, 0) == cudaSuccess) cur_limit = 0;
cudaCtxResetPersistingL2Cache();
cudaGetLastError();
}
// moe_forward always clears its window after its launch, so a window can only be left on the
// stream if a set succeeded without the matching clear (g_win_dirty): skip the redundant call.
if (g_win_dirty) {
cudaStreamAttrValue v = {};
v.accessPolicyWindow.num_bytes = 0;
if (cudaStreamSetAttribute(st, cudaStreamAttributeAccessPolicyWindow, &v) == cudaSuccess) g_win_dirty = false;
cudaGetLastError();
}
}
#ifdef MOE_DIAG
#include <string>
std::string moe_persist_info() {
size_t lim = 0; cudaDeviceGetLimit(&lim, cudaLimitPersistingL2CacheSize);
int l2 = 0; cudaDeviceGetAttribute(&l2, cudaDevAttrL2CacheSize, 0);
cudaStreamAttrValue v = {};
char b[256];
snprintf(b, sizeof b, "DIAG maxp=%d maxw=%d cur_limit=%zu actual_limit=%zu l2=%d err=%s", maxp, maxw, cur_limit, lim, l2,
cudaGetErrorString(cudaGetLastError()));
return std::string(b);
}
#endif
void moe_forward(const MoeArgs& a, cudaStream_t st) {
#ifdef MOE_PROF
prof_stamp_kernel<<<1, 1, 0, st>>>(); HT(0);
#endif
const int T = a.T, S = T * TOPK;
(void)S;
if (!g_num_sms) {
cudaDeviceGetAttribute(&g_num_sms, cudaDevAttrMultiProcessorCount, 0);
#ifdef MOE_PERSIST
// The L2::evict_last cache hints (tokens, out, Hs) are "persisting" accesses: they only
// protect lines inside the device's persisting-L2 set-aside, which defaults to 0 bytes (then
// evict_last == evict_normal and the re-read token rows get evicted by the weight stream:
// ablation T=2048, skipping token gathers cut DRAM traffic by 0.44 GB). Reserve the maximum
// set-aside once so the evict_last hints actually take effect.
int maxp = 0;
if (cudaDeviceGetAttribute(&maxp, cudaDevAttrMaxPersistingL2CacheSize, 0) == cudaSuccess && maxp > 0) {
size_t cur = 0;
cudaDeviceGetLimit(&cur, cudaLimitPersistingL2CacheSize);
if (cur < (size_t)maxp) cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, (size_t)maxp);
}
cudaGetLastError();
#endif
}
const int num_sms = g_num_sms;
const int nch = a.nchunk;
CUtensorMap tg, tu, tx = {}, td;
const CUtensorMapL2promotion wp = a.wpromo == 0 ? CU_TENSOR_MAP_L2_PROMOTION_NONE
: (a.wpromo == 1 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B);
// MOE_HSPROMO0_N128DQ: the NCH=128 8-epilogue-warp band (T~2400-3000, n128_dq incl. T2767) loads Hs with
// L2 promotion NONE (exact-height boxes = 128-B row pieces; no 256-B over-fetch); other bands keep 256B
// (n128_dq band = mean + 5 sd of the per-expert count > 128; keeps Hs promotion NONE with ew4 as well)
const double hav = (double)a.T * TOPK / NEXP;
const bool dq_band = hav + 5.0 * std::sqrt(hav) > 128.0;
// MOE_HSPROMO0_SMALLDQ: the small NCH=128 band now runs the same config as the n128_dq band (DQ, EW4,
// 2-buffer TMEM) but kept 256B Hs promotion only because of the ew4 term; all NCH=128 bands: NONE
(void)dq_band;
const CUtensorMapL2promotion hpro = (nch == 128) ? CU_TENSOR_MAP_L2_PROMOTION_NONE : CU_TENSOR_MAP_L2_PROMOTION_L2_256B;
// MOE_MAPBUNDLE (host overhead trim, full-mega path): the whole per-call tensor-map set (gate, up,
// down, nch/16 exact-height Hs maps) is cached as ONE bundle keyed on every encode input (data
// pointers, S, nch, promotions, interleave). Steady state (same weights, same scratch Hs buffer, same
// T) = one key compare + a memcpy instead of 3 + nch/16 linear scans of the 64-entry map cache.
// cpx != 1 (gather4 token map keyed on hidden_states) always takes the full path.
struct MapBundle { const void *g, *u, *d, *h; int S, nch, wp, dil, hp; CUtensorMap tg, tu, td; HsMaps hsm; };
static MapBundle* mb = new MapBundle(); // heap, never freed (host data only)
static bool mb_ok = false;
// MOE_MAPPATCH (fresh-pointer host diet): the bundle key is split into the SHAPE part (S, nch,
// promotions, interleave: every encode input except the base addresses) and the 4 base pointers.
// Shape hit + changed pointers (fresh weight / scratch tensors per call): the cached maps are used as
// templates and only their global address is rewritten with cuTensorMapReplaceAddress (no full
// cuTensorMapEncodeTiled per map; dims/strides/box/swizzle/promotion are unchanged by construction).
// Any replace failure (e.g. misaligned address) falls back to the full re-encode below.
bool mb_hit = a.cpx == 1 && mb_ok && mb->S == S && mb->nch == nch && mb->wp == (int)wp && mb->dil == a.dil &&
mb->hp == (int)hpro;
if (mb_hit && (mb->g != a.gate || mb->u != a.up || mb->d != a.down || mb->h != a.hs)) {
MapBundle nb = *mb;
bool ok = true;
if (nb.g != a.gate) ok = ok && cuTensorMapReplaceAddress(&nb.tg, const_cast<__nv_bfloat16*>(a.gate)) == CUDA_SUCCESS;
if (nb.u != a.up) ok = ok && cuTensorMapReplaceAddress(&nb.tu, const_cast<__nv_bfloat16*>(a.up)) == CUDA_SUCCESS;
if (nb.d != a.down) ok = ok && cuTensorMapReplaceAddress(&nb.td, const_cast<__nv_bfloat16*>(a.down)) == CUDA_SUCCESS;
if (nb.h != a.hs)
for (int i = 0; i < nch / 16 && ok; ++i) ok = cuTensorMapReplaceAddress(&nb.hsm.m[i], a.hs) == CUDA_SUCCESS;
if (ok) {
nb.g = a.gate; nb.u = a.up; nb.d = a.down; nb.h = a.hs;
*mb = nb;
} else {
mb_hit = false;
}
}
if (mb_hit) {
tg = mb->tg; tu = mb->tu; td = mb->td;
for (int i = 0; i < nch / 16; ++i) g_hsm.m[i] = mb->hsm.m[i];
} else {
make_tmap(&tg, a.gate, HID, (uint64_t)NEXP * INTER, BK, BM, wp);
make_tmap(&tu, a.up, HID, (uint64_t)NEXP * INTER, BK, BM, wp);
#ifndef MOE_XPROMO
#define MOE_XPROMO 0
#endif
// #AU host diet: the gather4 token map is only a kernel parameter of CPX == 0 variants; production
// (cpx = 1) never uses it, and since hidden_states gets a new address per call this was a real
// cuTensorMapEncodeTiled driver call on most invocations -> skipped.
if (a.cpx != 1)
make_tmap(&tx, a.hidden, HID, (uint64_t)T, BK, 1,
a.xpromo == 0 ? CU_TENSOR_MAP_L2_PROMOTION_NONE
: (a.xpromo == 1 ? CU_TENSOR_MAP_L2_PROMOTION_L2_128B : CU_TENSOR_MAP_L2_PROMOTION_L2_256B)); // gather4 source: box = 1 row x 64 cols
make_tmap_down4(&td, a.down, wp, a.dil);
for (int i = 0; i < nch / 16; ++i) make_tmap(&g_hsm.m[i], a.hs, INTER, (uint64_t)S, BK, 8 * (i + 1), hpro);
if (a.cpx == 1) {
mb->g = a.gate; mb->u = a.up; mb->d = a.down; mb->h = a.hs; mb->S = S; mb->nch = nch; mb->wp = (int)wp;
mb->dil = a.dil; mb->hp = (int)hpro; mb->tg = tg; mb->tu = tu; mb->td = td;
for (int i = 0; i < nch / 16; ++i) mb->hsm.m[i] = g_hsm.m[i];
mb_ok = true;
}
}
#ifndef MOE_XWIN
#define MOE_XWIN 0
#endif
#ifndef MOE_PMODE
#define MOE_PMODE 3
#endif
bool win = false;
if (maxp < 0) {
if (cudaDeviceGetAttribute(&maxp, cudaDevAttrMaxPersistingL2CacheSize, 0) != cudaSuccess) maxp = 0;
if (cudaDeviceGetAttribute(&maxw, cudaDevAttrMaxAccessPolicyWindowSize, 0) != cudaSuccess) maxw = 0;
cudaDeviceGetLimit(&cur_limit, cudaLimitPersistingL2CacheSize);
cudaGetLastError();
}
const size_t xbytes = (size_t)T * HID * 2; // hidden_states == out bytes
// Live-Hs term of the persisting set-aside, in rows per chunk. NCH=192 band (T~2900-4000, one
// chunk of ~mean tokens per expert): size by the EXPECTED rows per chunk min(nch, mean + 1 sd)
// instead of nch -- the 192-row bound over-reserves ~1/3 of the Hs term, shrinking normal L2 for
// the re-gathered token rows. The NCH=128
// bands keep the nch bound.
const double avg_rows = (double)T * TOPK / NEXP;
const size_t live_rows = (nch == 192 || nch == 176 || nch == 160) ? (size_t)std::min((double)nch, avg_rows + std::sqrt(avg_rows) + 1.0) : (size_t)nch;
// MOE_HSLIVE8_ALL: every band (NCH=128 incl. the DQ band, and NCH=192) reserves lag + 8 live-Hs chunks
// MOE_HSLIVE16_SMALL: small-T NCH=128 bands (T<=~3000) reserve lag + 16 live-Hs chunks (was lag + 8) so
// the evict_last Hs rows read by the 14 down items of a chunk stay inside the persisting set-aside
const size_t hs_live = (size_t)(a.lag + (nch == 128 ? 16 : 8)) * live_rows * INTER * 2;
const bool use_win = MOE_XWIN && a.xwin && MOE_PMODE != 2;
const void* win_ptr = MOE_PMODE == 3 ? (const void*)a.out : (const void*)a.hidden;
if (maxp > 0) {
size_t want;
if (MOE_PMODE == 0) want = std::max(cur_limit, xbytes + xbytes / 4);
else want = (use_win && MOE_PMODE != 3 ? xbytes : 0) + xbytes + hs_live;
want = std::min((size_t)maxp, want);
if (want != cur_limit) { // same T on repeated calls -> set only when the size changes
if (cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, want) == cudaSuccess) cur_limit = want;
cudaGetLastError();
}
}
if (use_win && maxw > 0 && cur_limit > 0) {
cudaStreamAttrValue v = {};
v.accessPolicyWindow.base_ptr = const_cast<void*>(win_ptr);
v.accessPolicyWindow.num_bytes = std::min(xbytes, (size_t)maxw);
v.accessPolicyWindow.hitRatio = std::min(1.0f, (float)cur_limit / (float)v.accessPolicyWindow.num_bytes);
v.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting;
v.accessPolicyWindow.missProp = cudaAccessPropertyStreaming;
g_lwin = v.accessPolicyWindow; // passed as a launch attribute by launch_mega
g_lwin_on = true;
}
#ifdef MOE_PROF
HT(1);
#endif
// Production dispatch (dead-code trim): main.cpp always selects the cp.async token loader (cpx=1)
// and the dynamic work queue (dq=1) on the full-megakernel path; chunk widths 128 (4 or 8 epilogue
// warps), 176 and 192 cover every T < MOE_CUT_MIN. Other variants are no longer instantiated.
if (a.cpx != 1 || !a.dq) throw std::runtime_error("moe: unsupported megakernel config (cpx/dq)");
if (nch == 128 && a.ew4) launch_mega<128, 0, 1, 1, 0, 4>(a, tg, tu, td, tx, st);
else if (nch == 128) launch_mega<128, 0, 1, 1>(a, tg, tu, td, tx, st);
else if (nch == 176) launch_mega<176, 0, 1, 1>(a, tg, tu, td, tx, st);
else if (nch == 160) launch_mega<160, 0, 1, 1>(a, tg, tu, td, tx, st); // NCH=160: WS6/XS3 ring // MOE_N176: T~2900-3900 band
else if (nch == 192) launch_mega<192, 0, 1, 1>(a, tg, tu, td, tx, st);
else throw std::runtime_error("moe: unsupported megakernel chunk width " + std::to_string(nch));
#ifdef MOE_PROF
HT(2);
#endif
if (g_lwin_on) { // launch failed with the window attribute? (not expected) -> clear error
g_lwin_on = false;
}
if (win) { // the window applies only to this launch: clear it on the (shared torch) stream
cudaStreamAttrValue v = {};
v.accessPolicyWindow.num_bytes = 0;
if (cudaStreamSetAttribute(st, cudaStreamAttributeAccessPolicyWindow, &v) == cudaSuccess) g_win_dirty = false;
else cudaGetLastError();
}
#ifdef MOE_PROF
HT(3);
g_prof_T = T;
#endif
}
#ifdef MOE_PROBE
#include <string>
// DEBUG: static resource usage + persistent grid of the megakernel variants
template <int NCH, int CPX>
static std::string kinfo1() {
auto k = moe_mega_kernel<num_wstages(NCH), num_xslots(NCH), NCH, CPX>;
cudaFuncAttributes fa = {};
cudaFuncGetAttributes(&fa, (const void*)k);
const size_t sm = (size_t)num_wstages(NCH) * wstage_bytes() + (size_t)num_xslots(NCH) * xslot_bytes(NCH) + SMEM_EXTRA;
cudaFuncSetAttribute(k, cudaFuncAttributeMaxDynamicSharedMemorySize, (int)sm);
const int g = cluster_grid((const void*)k, sm, CPX ? NTHREADS + 32 : NTHREADS);
char b[160];
snprintf(b, sizeof b, " [N%d cpx%d regs=%d lmem=%zu grid=%d]", NCH, CPX, fa.numRegs, fa.localSizeBytes, g);
return std::string(b);
}
std::string moe_kernel_info() { return kinfo1<128, 0>() + kinfo1<128, 1>() + kinfo1<192, 0>() + kinfo1<192, 1>(); }
#endif
// Large-T path, stage 1 (see main.cpp cutlass_run): routing + gate|up GEMM with the SwiGLU epilogue
// fused (2 MMAs per K-step into gate / up TMEM accumulators, silu(g)*u -> bf16 Hs rows in expert-
// sorted order), replacing the CUTLASS gate|up grouped GEMM, the token gather (Xs) and the act kernel.
// No persisting-L2 window (Hs is far larger than L2 here and is consumed by the CUTLASS down GEMM).
void moe_gateup_forward(const MoeArgs& a, cudaStream_t st) {
if (!g_num_sms) cudaDeviceGetAttribute(&g_num_sms, cudaDevAttrMultiProcessorCount, 0);
const int T = a.T, S = T * TOPK;
CUtensorMap tg, tu, tx = {}, td;
make_tmap(&tg, a.gate, HID, (uint64_t)NEXP * INTER, BK, BM);
make_tmap(&tu, a.up, HID, (uint64_t)NEXP * INTER, BK, BM);
if (a.cpx != 1) make_tmap(&tx, a.hidden, HID, (uint64_t)T, BK, 1, CU_TENSOR_MAP_L2_PROMOTION_L2_256B); // unused by cpx=1
make_tmap_down4(&td, a.down, CU_TENSOR_MAP_L2_PROMOTION_L2_256B);
// MOE_HSN1: gate|up-only queue has no down items -> only a placeholder Hs map is passed
make_tmap(&g_hsm.m[0], a.hs, INTER, (uint64_t)S, BK, 8);
// variant by chunk width / token loader / ring split (all instantiated for the full path too)
// Production dispatch (dead-code trim): cpx=1, dq=1, swapped items; NCH 192 (8 epilogue warps),
// 240 / 256 (4 epilogue warps, MOE_GU_EW4).
if (a.cpx != 1 || !a.dq || a.nsw) throw std::runtime_error("moe: unsupported gate|up config (cpx/dq/nsw)");
if (a.nchunk == 192) launch_mega<192, 0, 1, 1, 0, 8, 1>(a, tg, tu, td, tx, st);
else if (a.nchunk == 240 && a.ew4) launch_mega<240, 0, 1, 1, 0, 4, 1>(a, tg, tu, td, tx, st);
else if (a.nchunk == 256 && a.ew4) launch_mega<256, 0, 1, 1, 0, 4, 1>(a, tg, tu, td, tx, st);
else throw std::runtime_error("moe: unsupported gate|up chunk width " + std::to_string(a.nchunk));
}
// ---------------------------------------------------------------- large-T path: batch-0 gate
// Single-warp kernel on the side stream, between the gate|up-only megakernel (main stream) and the
// CUTLASS down GEMM of expert batch 0 (experts [0,128)). It spins until (1) the megakernel of THIS
// call has finished routing (g_route_epoch == epoch) and (2) every chunk of batch 0 has all its
// gate|up epilogue warps done (done[2c] == DONE_TARGET, Hs rows written + proxy-fenced). The
// batch-0 down GEMM, ordered after this kernel on the side stream, then fills the SMs that the
// megakernel's CTAs free during its tail (it cannot co-reside with a megakernel CTA: registers).
// Co-residency: this kernel may land on an SM before the megakernel's CTA does. It uses one warp,
// <= 32 regs and no smem, which still fits next to one megakernel CTA (12 warps x 168 regs =
// 64512 of 65536 regs; 230656 + 1 KB reserved smem of 233472 B), so it never blocks the
// megakernel's grid from becoming fully resident (required by its grid barriers).
__global__ void __maxnreg__(32)
moe_batch_wait_kernel(const int* __restrict__ num_items, const int* __restrict__ done, unsigned int epoch,
int target, int zero_target) {
const int lane = threadIdx.x;
int nc0 = 0;
if (lane == 0) {
unsigned int v;
while (true) {
asm volatile("ld.acquire.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(&g_route_epoch) : "memory");
if ((int)(v - epoch) >= 0) break;
__nanosleep(256);
}
nc0 = __ldcg(num_items + 2);
}
nc0 = __shfl_sync(0xffffffffu, nc0, 0);
for (int c = lane; c < nc0; c += 32)
while (ld_acquire_gpu(done + 2 * c) < target) __nanosleep(256);
// gu_zero: the megakernel's epilogue warps zero `out` (replacing a memset); every warp bumps
// num_items[1] (release) after its zero stores -> the batch-0 down red.adds must see them all
if (lane == 0 && zero_target > 0)
while (ld_acquire_gpu(num_items + 1) < zero_target) __nanosleep(256);
__syncwarp();
__threadfence();
}
void moe_batch_wait_targets(const MoeArgs& a, int* target, int* zero_target);
static unsigned int g_epoch = 0;
unsigned int moe_next_epoch() { return ++g_epoch; }
void moe_batch_wait(const MoeArgs& a, cudaStream_t st) {
// done[2c] target = gate|up items per chunk x 2 CTAs x 8 epilogue warps (NSW: 16 items per chunk)
const bool nsw = a.nsw && a.cpx && a.nchunk == 256;
int tgt = 0, ztgt = 0;
(void)nsw;
moe_batch_wait_targets(a, &tgt, &ztgt);
moe_batch_wait_kernel<<<1, 32, 0, st>>>(a.num_items, a.done, a.epoch, tgt, ztgt);
}
// epilogue warps per CTA of the gu_only launch (must match moe_gateup_forward's dispatch)
static int gu_epi_warps(const MoeArgs& a) {
return (a.cpx && (a.nchunk == 256 || a.nchunk == 240) && !a.nsw && a.dq && a.ew4) ? 4 : EPI_WARPS;
}
void moe_batch_wait_targets(const MoeArgs& a, int* target, int* zero_target) {
const bool nsw = a.nsw && a.cpx && a.nchunk == 256;
const int ew = gu_epi_warps(a);
*target = (nsw ? 2 : 1) * GU_MT * 2 * ew;
*zero_target = a.gu_zero ? g_grid * ew : 0;
}
#ifdef MOE_KPROBE
void moe_set_krot(int mul, int kc) { cudaMemcpyToSymbol(g_kmul, &mul, 4); cudaMemcpyToSymbol(g_kcid, &kc, 4); cudaDeviceSynchronize(); }
#endif
void* moe_out_slot_ptr() {
static void* p = nullptr;
if (!p) cudaGetSymbolAddress(&p, g_out_slot);
return p;
}
void* moe_ptr_blk_ptr() {
static void* p = nullptr;
if (!p) cudaGetSymbolAddress(&p, g_ptr_blk);
return p;
}
unsigned int* moe_route_epoch_ptr() {
static unsigned int* p = nullptr;
if (!p) cudaGetSymbolAddress((void**)&p, g_route_ep);
return p;
}
// MoE expert computation (DeepSeek-V3 shapes) -- single persistent warp-specialized tcgen05
// 2-SM (cta_group::2) MoE megakernel, swap-AB (weights = MMA M side, tokens = N side).
//
// Algorithm
// 1. routing, IN the megakernel prologue (no separate launch): all co-resident CTAs build the
// expert histogram (smem partial + global atomics), grid barrier, redundant 256-entry scan,
// scatter (token,slot) -> sorted_slot[p]; CTA 0 cuts each expert's rows into chunks of
// <= NCH tokens and writes the WORK QUEUE item_info[] (see route_in_kernel) and zeroes the
// per-chunk dependency counters done[]; second grid barrier, then the work loop.
//
// Token-chunk size NCH (max tokens per work item, UMMA N <= 256) is chosen on the host from T
// (128 / 192 / 256): the smem token tile is sized for NCH, so a small NCH buys more pipeline stages.
// ----------------------------------------------------------------- PTX helpers
__device__ __forceinline__ uint32_t smem_u32(const void* p) {
return (uint32_t)__cvta_generic_to_shared(p);
}
__device__ __forceinline__ uint32_t cluster_rank() {
uint32_t r;
asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r));
return r;
}
// shared::cluster address of the same smem offset in CTA `rank` of the cluster
__device__ __forceinline__ uint32_t mapa(uint32_t addr, uint32_t rank) {
uint32_t r;
asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(addr), "r"(rank));
return r;
}
__device__ __forceinline__ void cluster_sync() {
asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::
: "memory");
}
__device__ __forceinline__ void mbar_init(uint32_t bar, uint32_t cnt) {
asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(bar), "r"(cnt));
}
__device__ __forceinline__ void mbar_wait(uint32_t bar, uint32_t phase) {
uint32_t done = 0;
while (!done) {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase)
: "memory");
}
}
// wait with a suspend-time hint (ns): the waiting thread is parked by hardware until the phase
// completes (or the hint expires) instead of re-issuing try_wait in a tight loop. Used by the
// epilogue warps' accumulator-full waits (8 warps x 2 CTAs idle for a whole mainloop each item):
// fewer issued instructions / less SM dynamic power in the power-capped regime.
__device__ __forceinline__ void mbar_wait_park(uint32_t bar, uint32_t phase) {
uint32_t done = 0;
while (!done) {
asm volatile(
"{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase), "r"(1000000u)
: "memory");
}
}
// #BW producer slack fast path: one NON-BLOCKING test_wait first; when the ring has slack (the stage
// was already released by the MMA commit) the producer issues the TMA immediately without entering the
// suspend-hinted try_wait loop; otherwise falls back to the parked wait. Same barrier semantics.
__device__ __forceinline__ void mbar_wait_probe(uint32_t bar, uint32_t phase) {
uint32_t done;
asm volatile(
"{\n .reg .pred p;\n mbarrier.test_wait.parity.shared::cta.b64 p, [%1], %2;\n"
" selp.u32 %0, 1, 0, p;\n}\n"
: "=r"(done)
: "r"(bar), "r"(phase)
: "memory");
if (!done) mbar_wait_park(bar, phase);