diff --git a/arch/common/rad_block_moe_fp8.h b/arch/common/rad_block_moe_fp8.h index 8cdadd25..e1212f0b 100644 --- a/arch/common/rad_block_moe_fp8.h +++ b/arch/common/rad_block_moe_fp8.h @@ -76,6 +76,23 @@ namespace arch { * decide, at declare time and identically on both ranks, whether the op exists at all. */ static const int64_t kMoeSortRows = 1024; +/* R4D_ROUTER_FUSED: the router's GEMM in the same launch as `router_topk_scatter` + * (`router_gemm_topk_scatter`), at decode shapes. 1 also computes the shared expert's one-column + * gate in that launch, 2 leaves the gate its own `gemm_nt`; unset or 0 declares nothing new and the + * graph is the one without it. Read once, at declare, so a recorded pass and a live one issue the + * same ops. Every output is byte-identical either way (see libr4d's r4d_moe.hip). */ +inline int moe_router_fused_mode() { + static const int v = [] { + const char* e = std::getenv("R4D_ROUTER_FUSED"); + const int x = e ? std::atoi(e) : 0; + return (x == 1 || x == 2) ? x : 0; + }(); + return v; +} +/* The skinny bf16 GEMM's decode band, which is where the fused op's GEMM is that GEMM's own + * arithmetic; past it the router runs the tiled kernel and the pair is issued as before. */ +static const int64_t kMoeRouterFusedRows = 64; + /* ---- RADIANCE_DEBUG_ROUTING: the routing WEIGHTS of token 0, which nothing else reports. @@ -362,6 +379,12 @@ struct MoeFP8 { * a prefill chunk is past it. */ rad_op op_topk_scatter = 0; int64_t topk_scatter_rows = 0; + /* `router_gemm_topk_scatter` (R4D_ROUTER_FUSED), if declared: the router GEMM in front of the + * pair above, up to `router_fused_rows` tokens, and with `router_fused_gate` the shared + * expert's gate (`op_sgate`'s work) as well. 0 issues the router and the pair as always. */ + rad_op op_router_fused = 0; + int64_t router_fused_rows = 0; + bool router_fused_gate = false; /* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and * the caller does not already write `w.hr`. */ rad_op op_hq = 0; @@ -452,7 +475,7 @@ struct MoeFP8 { void step(RadCtx* c, const RadBatch* batch) const; /* One pass of at most `c.rows` tokens. */ void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; - void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; + void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const; }; inline int MoeFP8::format_of(const RadEncoding& e) { @@ -1367,6 +1390,68 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, {w.h.x}, {w.sgate}); } + /* ---- R4D_ROUTER_FUSED: the router GEMM and `router_topk_scatter` as one op, and with mode 1 + * the shared gate as well. Declared HERE, after the gate's weight, and not beside the router: + * the op names both weights, and declaring it late only lengthens the planned lifetime of the + * buffers it touches, never shortens one -- each of them is also declared by the op it stands + * in for, at that op's place. Only where the pair itself is declared, and only up to the + * pair's own row bound. */ + if (moe_router_fused_mode() && op_topk_scatter) { + router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows + : kMoeRouterFusedRows; + router_fused_gate = moe_router_fused_mode() == 1 && op_sgate != 0; + const int64_t fr = router_fused_rows; + if (router_fused_gate && !prot_list) + op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base)), + RAD_WEIGHTS(w_router, w_sgate)), + {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, + w.sgate}); + else if (router_fused_gate) + op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list)), + RAD_WEIGHTS(w_router, w_sgate)), + {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, + w.sgate}); + else if (!prot_list) + op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base)), + RAD_WEIGHTS(w_router)), + {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); + else + op_router_fused = rw(b, RAD_OP(b, "router_gemm_topk_scatter", + RAD_PARAMS(RAD_RANGE("M", 1, fr), RAD_INT("K", g.n_embd), + RAD_INT("n_expert", c.n_expert_all), + RAD_INT("n_local", c.n_expert), + RAD_INT("top_k", c.top_k), + RAD_INT("norm", c.norm_topk), + RAD_STR("dtype", g.dtype), + RAD_INT("expert_base", c.expert_base), + RAD_STR("protect", prot_list)), + RAD_WEIGHTS(w_router)), + {w.h.x}, {w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt}); + if (!op_router_fused) router_fused_gate = false; + } + if (g.world > 1) op_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -1399,7 +1484,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, * The shared expert is ordinary dense linears over that input, and every buffer it touches is the * step's height -- so the pass offset goes through all of them exactly as it does through an * MlpFP8 slice. */ -inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const { +inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows, + bool gate_done) const { + /* `gate_done`: the fused router already wrote this pass's gate (R4D_ROUTER_FUSED=1). */ + if (!gate_done) RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate), brow_slice(w.sgate, r0, rows, 1)); sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows); @@ -1431,11 +1519,24 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const * a routed layer, a whole dependent dispatch for a kilobyte. */ int32_t* const counts = rad_route_counts(c_, layer, ne); const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne); + /* R4D_ROUTER_FUSED: the router, the pair below and -- with `router_fused_gate` -- the shared + * gate, in one launch with the operands the three are handed. */ + const bool rfused = op_router_fused && rows <= router_fused_rows; + if (rfused) + RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd), + RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE, + brow_slice(w.logits, r0, rows, ne_all), + brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k), + brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt, + router_fused_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE); + else RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router), brow_slice(w.logits, r0, rows, ne_all)); /* One launch or two. `w.ids` is the fused op's OUTPUT where it was the sort's input, and * every other operand is the one the pair is handed. */ - if (op_topk_scatter && rows <= topk_scatter_rows) { + if (rfused) { + /* the fused router wrote all five */ + } else if (op_topk_scatter && rows <= topk_scatter_rows) { RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all), brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k), brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt); @@ -1482,7 +1583,7 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1), RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2), brows(w.egu, rows * k)); - if (shared) shared_up(c_, T, r0, rows); + if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate); gq_exp.step(c_, w.egu, rows * k, 0, rows * k); if (shared) gq_sh.step(c_, w.sgu, T, r0, rows); if (c.expert_bf16) diff --git a/docs/OPS.md b/docs/OPS.md index 4653a9c4..9e2d5276 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -479,6 +479,7 @@ and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are th | `router_topk` | `M`(range) `n_expert` `top_k` `norm` `dtype` | `logits` → `expert_ids`, `expert_w` | | `moe_scatter` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count` | | `router_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `logits` → `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count` | +| `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? | | `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` | | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | @@ -531,6 +532,17 @@ sequences at depth 3 and top_k 10 is 320 slots — and a prefill chunk is past i where the pair is amortised over real work and a fusion would buy nothing. A caller past the bound gets a refusal, not a silent change of cost. +**`router_gemm_topk_scatter` puts the router's GEMM in front of that pair**, in the same launch: +`gemm_nt` of `a` [M, K] against the router `b` [n_expert, K] into `logits`, then exactly +`router_topk_scatter` over those logits. With `gate_b` [1, K] and `gate` [M, 1] present it is +also the shared expert's one-column `gemm_nt` over the same `a`; the two come together or not at +all. The selection needs every logit of a row, so it runs in the workgroup that finishes the GEMM +last (an arrival counter, self-resetting, one a stream and logits buffer). It is byte-identical to +the launches it stands in for: an element of the skinny bf16 GEMM depends only on its split-K +count, which this op takes from the same law at the same N, and the selection and sort are the +same code. Decode only, `M <= 64` -- past that the router is the tiled GEMM -- and bounded like the +pair. The logits stay an output. + `moe_scatter`'s output is what `rad_route_report` hands the heat engine. The histogram is read back asynchronously and consumed on the next step; nothing here blocks the compute stream (`spec.md` §5.5). diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 3ac6b918..f5dbcf28 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -57,11 +57,17 @@ #include "r4d_fp8_wmma.h" #include "r4d_plugin.h" #include "r4d_emit.h" +#include "r4d_gemm_args.h" + +#include #include #include +#include +#include #include +#include namespace { @@ -2656,3 +2662,322 @@ extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { R4D_MOE_CHK(); return RAD_OK; } + +/* ================================================================== router GEMM + router_topk_scatter + * + * THE ROUTER, ITS SELECTION AND ITS SORT IN ONE LAUNCH -- and, where the layer has a shared expert, + * that expert's one-column gate beside them. rad_block_moe_fp8.h declares it under + * R4D_ROUTER_FUSED; this is the kernel and its shim. + * + * At a decode step the router is a [n_expert, n_embd] bf16 GEMM over a handful of rows, and what + * follows it -- `router_topk_scatter` -- is one workgroup with almost no work in it. They are two + * DEPENDENT dispatches on every routed layer, and the boundary between them is a command-processor + * gap plus a second launch, on the critical path. The selection needs every logit of a row, so it + * cannot run inside a column tile; it runs in whichever workgroup finishes LAST, which an arrival + * counter names. That is the device-wide pattern gemm_fp8a8's split-K finisher and hc_up_mix's + * quantiser already use, and its rule is theirs: one counter a (stream, output), self-resetting. + * + * The shared expert's gate is a gemm_nt at N = 1 over the SAME input, a launch of its own for one + * output column. It rides along as one more workgroup of this grid (`skg` > 0), so the launch the + * routed gate_up was overlapping disappears from the queue. + * + * BYTE-IDENTICAL TO THE LAUNCHES IT STANDS IN FOR, and the claim rests on two things: + * + * - THE GEMM IS r4d_gemm_bf16_nt_m64_kernel'S ARITHMETIC, ELEMENT BY ELEMENT. An output element of + * that kernel is SK partial tiles, each ONE wave's WMMA chain over one contiguous K slice in + * ascending K, summed in ascending split order from 0.f and narrowed by the language's own + * conversion. Which block owns the tile, how many tiles a block holds (WV, MB) and how many + * waves a block has do not enter it -- only SK does. So the split counts are asked of the law + * the unfused launches ask (cfg_for with the same N-tile count: a 512-wide router and a + * one-column gate get different ones), and a wave here may run several (tile, split) items + * one after another: each item is the same chain from zero into an LDS slot of its own, so the + * sum sees exactly the operands it saw before. + * - THE SELECTION AND THE SORT ARE router_topk_scatter_kernel'S BODY: the same two device + * functions over the same logits, wave-local per row and stable without an atomic ordering + * anything, so the number of waves the last block happens to have moves no bit. + * + * A TUNED POINT for the unfused router would break the first of those: this row is NOTUNE and + * always takes the law's split. No shipped configuration tunes these GEMMs. + * + * DECODE ONLY: at most kRgMaxM rows (four 16-row tiles), which is the skinny GEMM's decode band; + * past it the router is the tiled kernel and the architecture issues the pair. */ +constexpr long long kRgMaxM = 64; + +namespace { + +constexpr int kRgKU = 8; /* r4d_gemm_bf16_nt_m64's KU: the unroll, not the order */ + +typedef __bf16 rg_v8bf __attribute__((ext_vector_type(8))); +typedef float rg_v8f __attribute__((ext_vector_type(8))); +/* Global-address-space pointer for the fragment loads, as r4d_gemm_bf16_nt_m64.hip holds it. */ +typedef __attribute__((address_space(1))) const unsigned long long* rg_gu2; + +__device__ __forceinline__ rg_v8f rg_mma(rg_v8bf a, rg_v8bf b, rg_v8f c) { + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c); +} +/* r4d_gemm_bf16_nt_m64.hip's fragU: k step `u` of a K-contiguous row, two runs of four. */ +__device__ __forceinline__ rg_v8bf rg_fragU(rg_gu2 p, int u) { + union { unsigned long long w[2]; rg_v8bf f; } x; + x.w[0] = p[4 * u]; + x.w[1] = p[4 * u + 2]; + return x.f; +} +/* r4d_gdn_wmma.h's rowGo: this lane's row, clamped to `lim`, as a 32-bit element offset. */ +__device__ __forceinline__ unsigned rg_rowGo(unsigned rowstride, int row0, int lim, int lane) { + int r = row0 + (lane & 15); + r = r < lim ? r : lim; + return (unsigned)r * rowstride + 4u * (unsigned)(lane >> 4); +} + +/* ONE (tile, split) ITEM: the 16 x 16 partial tile r4d_gemm_bf16_nt_m64_kernel's wave (n0, ks) + * accumulates at MT = 1 -- the same loads, the same WMMA chain in the same order from zero. */ +__device__ __forceinline__ rg_v8f rg_item(const uint16_t* __restrict__ A, + const uint16_t* __restrict__ W, int M, int K, int N, + int n0, int m0, int ks, int SK, int lane) { + const int Ks = K / SK, ksteps = Ks / 16, kbase = ks * Ks; + rg_v8f acc = (rg_v8f)(0.f); + const unsigned woff = rg_rowGo((unsigned)K, n0, N - 1, lane) + (unsigned)kbase; + const unsigned aoff = rg_rowGo((unsigned)K, m0, M - 1, lane) + (unsigned)kbase; + if (n0 < N) { + rg_gu2 pw = (rg_gu2)(const unsigned long long*)(W + woff); + rg_gu2 pa = (rg_gu2)(const unsigned long long*)(A + aoff); + int s = 0; + for (; s + kRgKU <= ksteps; s += kRgKU) { +#pragma unroll + for (int u = 0; u < kRgKU; u++) { + const rg_v8bf b = rg_fragU(pw, u); + acc = rg_mma(rg_fragU(pa, u), b, acc); + } + pw += kRgKU * 4; + pa += kRgKU * 4; + } + for (; s < ksteps; s++) { + const rg_v8bf b = rg_fragU(pw, 0); + pw += 4; + acc = rg_mma(rg_fragU(pa, 0), b, acc); + pa += 4; + } + } + return acc; +} + +/* The launch geometry, one argument: `sk` the router's split and `tpb` its 16-column tiles a + * block, `nrb` the router's blocks along x, `skg` the gate's split (0: no gate; its block is + * x = nrb). Rows are tiled along y, one 16-row tile a block. */ +struct RgGeom { + uint32_t M, K, n_expert, n_local, top_k, lg_ld; + int32_t norm, base; + uint32_t sk, tpb, nrb, skg; +}; + +/* `lg` is neither const nor __restrict__: every block writes it and the last one reads it back. */ +template +__global__ __launch_bounds__(NW * kWave) void router_gemm_topk_scatter_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ W, + const uint16_t* __restrict__ Wg, uint16_t* lg, uint16_t* __restrict__ gate, + int32_t* __restrict__ ids, uint16_t* __restrict__ w, int32_t* __restrict__ sorted, + int32_t* __restrict__ off, int32_t* __restrict__ cnt, unsigned int* __restrict__ ctr, + RgGeom g, Protect prot) { + /* The partial tiles of the GEMM, then -- in the last block only, after two barriers -- the + * sort's LDS. The shim sizes it for the larger of the two. */ + extern __shared__ __align__(16) unsigned char rg_smem[]; + float* const red = (float*)rg_smem; + const uint32_t tid = threadIdx.x, wave = tid / kWave, lane = tid % kWave; + + const bool gb = g.skg > 0 && blockIdx.x == g.nrb; + const int SK = (int)(gb ? g.skg : g.sk); + const uint32_t nti = gb ? 1u : g.tpb; + const int N = gb ? 1 : (int)g.n_expert; + const uint32_t nt0 = gb ? 0u : blockIdx.x * g.tpb; + const uint16_t* Wb = gb ? Wg : W; + const int m0 = (int)(blockIdx.y * 16u); + + const uint32_t items = nti * (uint32_t)SK; + for (uint32_t it = wave; it < items; it += NW) { + const uint32_t j = it / (uint32_t)SK, ks = it % (uint32_t)SK; + const rg_v8f acc = rg_item(A, Wb, (int)g.M, (int)g.K, N, (int)((nt0 + j) * 16u), m0, + (int)ks, SK, (int)lane); + float* const slot = red + (size_t)it * 256; /* it == j * SK + ks */ +#pragma unroll + for (int e = 0; e < 8; e++) slot[e * (int)kWave + (int)lane] = acc[e]; + } + __syncthreads(); + /* THE REDUCTION, r4d_gemm_bf16_nt_m64_kernel's: the splits in ascending order from 0.f, and + * the language's float-to-bf16 conversion -- not f32_to_bf16, which is the same only away + * from NaN. */ + for (uint32_t idx = tid; idx < nti * 256u; idx += NW * kWave) { + const uint32_t j = idx >> 8, o = idx & 255u; + float v = 0.f; + for (int s = 0; s < SK; s++) v += red[((size_t)j * (size_t)SK + (size_t)s) * 256 + o]; + const uint32_t l = o & 31u; + const int n = (int)((nt0 + j) * 16u + (l & 15u)); + const int m = m0 + (int)(8u * (l >> 4) + (o >> 5)); + if (n < N && m < (int)g.M) { + if (gb) ((__hip_bfloat16*)gate)[m] = (__hip_bfloat16)v; + else ((__hip_bfloat16*)lg)[(size_t)m * g.lg_ld + (size_t)n] = (__hip_bfloat16)v; + } + } + + /* ---- THE LAST BLOCK RANKS. Every store above is made visible device-wide before the + * arrival is published, and the block that completes the count resets it for the next + * launch and acquires the other blocks' logits. */ + __threadfence(); + __syncthreads(); + __shared__ unsigned int s_arrived; + if (tid == 0) + s_arrived = __hip_atomic_fetch_add(ctr, 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_arrived + 1u != gridDim.x * gridDim.y) return; + if (tid == 0) __hip_atomic_store(ctr, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __threadfence(); + + /* router_topk_scatter_kernel, from here to the end. */ + ScatterLds& sl = *reinterpret_cast*>(rg_smem); + for (uint32_t e = tid; e < g.n_local; e += blockDim.x) sl.cnt[e] = 0; + const SlotSink snk{sl.e, g.base, g.n_local, prot}; + for (uint32_t m = wave; m < g.M; m += NW) + router_topk_row(lg, ids, w, m, g.n_expert, g.top_k, g.lg_ld, g.norm, lane, snk); + lds_barrier(); + scatter_small_place(sorted, off, cnt, g.M * g.top_k, g.n_local, sl); +} + +} /* namespace */ + +/* THE ARRIVAL COUNTER, one a (stream, logits buffer): ctx.h's rule TWO, and gemm_fp8a8's split_ctr + * says why the output is part of the key. Launches that share a logits buffer on one stream are + * ordered through it -- every routed layer writes the same plane -- so they reuse one counter. + * Zeroed once and reset by the last block of every launch. Null when it cannot be allocated; the + * op then refuses rather than computing without it. */ +static unsigned int* router_fused_ctr(RadStream s, const void* out) { + static std::mutex m; + static std::map, unsigned int*> blocks; + std::lock_guard lk(m); + const auto key = std::make_pair(s, out); + if (auto it = blocks.find(key); it != blocks.end()) return it->second; + void* p = nullptr; + if (hipMalloc(&p, 64) != hipSuccess) return nullptr; + if (hipMemset(p, 0, 64) != hipSuccess) { + (void)hipFree(p); + return nullptr; + } + blocks.emplace(key, (unsigned int*)p); + return (unsigned int*)p; +} + +/* Operands: a, b (the router), gate_b? -> logits, expert_ids, expert_w, sorted_tok, + * expert_offset, expert_count, gate?. The two optional ones come together or not at all. Every + * check of the two shims it stands in for is made here too; nothing new is asserted beyond the + * row bound. */ +static int rad_router_gemm_topk_scatter_body(const RadArgs* a, const R4dSink& sk) { + int emit_rc = RAD_OK; + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* wr = r4d_opt(a, 1); + const RadTensor* wg = r4d_opt(a, 2); + const RadTensor* lg = r4d_opt(a, 3); + const RadTensor* ids = r4d_opt(a, 4); + const RadTensor* w = r4d_opt(a, 5); + const RadTensor* sorted = r4d_opt(a, 6); + const RadTensor* off = r4d_opt(a, 7); + const RadTensor* cnt = r4d_opt(a, 8); + const RadTensor* gate = r4d_opt(a, 9); + if (!x || !wr || !lg || !ids || !w || !sorted || !off || !cnt) return R4D_NO(RAD_E_INVAL); + if ((wg != nullptr) != (gate != nullptr)) return R4D_NO(RAD_E_INVAL); + + const long long n_expert = r4d_geti_or(a, "n_expert", 0); + const long long n_local = r4d_geti_or(a, "n_local", n_expert); + const long long top_k = r4d_geti_or(a, "top_k", 0); + const long long norm = r4d_geti_or(a, "norm", 0); + const long long base = r4d_geti_or(a, "expert_base", 0); + if (n_expert <= 0 || n_expert > (long long)kMaxExpert || top_k <= 0 || top_k > n_expert) + return R4D_NO(RAD_E_SHAPE); + if (top_k > (long long)kWave) return R4D_NO(RAD_E_SHAPE); + if (n_local <= 0 || n_local > n_expert) return R4D_NO(RAD_E_SHAPE); + if (base < 0 || base + n_local > n_expert) return R4D_NO(RAD_E_SHAPE); + Protect prot; + const int prc = protect_of(a, n_local, &prot); + if (prc != RAD_OK) return prc; + if (x->dtype != RAD_BF16 || wr->dtype != RAD_BF16 || lg->dtype != RAD_BF16 || + w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (wg && (wg->dtype != RAD_BF16 || gate->dtype != RAD_BF16)) return R4D_NO(RAD_E_DTYPE); + if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || + cnt->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + + /* The GEMM's operands, as gemm_ops reads them: A [M, K] contiguous, the output contiguous, + * A and the weights 16-byte aligned. */ + long long M = 0, K = 0; + if (r4d_rows_of(x, &M, &K) != RAD_OK) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(x)) return R4D_NO(RAD_E_STRIDE); + if (r4d_geti_or(a, "K", K) != K) return R4D_NO(RAD_E_SHAPE); + if (M > kRgMaxM) return R4D_NO(RAD_E_SHAPE); + if (!r4d_aligned(x->data, 16) || !r4d_aligned(wr->data, 16) || + (wg && !r4d_aligned(wg->data, 16))) return R4D_NO(RAD_E_ALIGN); + if (r4d_numel(wr) < n_expert * K || (wg && r4d_numel(wg) < K)) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(lg) || r4d_numel(lg) < M * n_expert) return R4D_NO(RAD_E_STRIDE); + if (gate && (!r4d_contig(gate) || r4d_numel(gate) < M)) return R4D_NO(RAD_E_STRIDE); + + const long long T = M * top_k; + if (T > (long long)kScatterSmall) return R4D_NO(RAD_E_SHAPE); + if (!r4d_contig(ids) || !r4d_contig(w) || !r4d_contig(sorted) || !r4d_contig(off) || + !r4d_contig(cnt)) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(ids) < T || r4d_numel(w) < T) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(sorted) < T) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(off) < n_local + 1 || r4d_numel(cnt) < n_local) return R4D_NO(RAD_E_SHAPE); + + /* THE SPLITS THE UNFUSED LAUNCHES TAKE: gemm_bf16_nt_m16/_m64 ask cfg_for with ceil(N/16) + * tiles, so the router asks with its own width and the gate with one tile. */ + const long long ntiles = (n_expert + 15) / 16; + Cfg cr{}, cg{}; + int rc = cfg_for(a, K, M, 16, BR_FLAT, &cr, ntiles); + if (rc != RAD_OK) return rc; + if (wg) { + rc = cfg_for(a, K, M, 16, BR_FLAT, &cg, 1); + if (rc != RAD_OK) return rc; + } + unsigned int* const ctr = router_fused_ctr(sk.stream, lg->data); + if (!ctr) return R4D_NO(RAD_E_DEVICE); + + /* THE WAVE COUNT IS THE SELECTION'S, router_topk_scatter's rule: a wave a row up to 32. The + * GEMM then takes as many 16-column tiles a block as fills those waves at its split. */ + const uint32_t nw = M <= 8 ? 8u : M <= 16 ? 16u : 32u; + long long tpb = (long long)nw / cr.sk; + if (tpb < 1) tpb = 1; + if (tpb > ntiles) tpb = ntiles; + const long long nrb = (ntiles + tpb - 1) / tpb; + size_t lds = (size_t)(tpb * cr.sk) * 256 * sizeof(float); + if (wg) lds = std::max(lds, (size_t)cg.sk * 256 * sizeof(float)); + const size_t sort_lds = nw == 8 ? sizeof(ScatterLds<8>) + : nw == 16 ? sizeof(ScatterLds<16>) : sizeof(ScatterLds<32>); + lds = std::max(lds, sort_lds); + + RgGeom g{}; + g.M = (uint32_t)M; g.K = (uint32_t)K; + g.n_expert = (uint32_t)n_expert; g.n_local = (uint32_t)n_local; + g.top_k = (uint32_t)top_k; g.lg_ld = (uint32_t)n_expert; + g.norm = (int32_t)norm; g.base = (int32_t)base; + g.sk = (uint32_t)cr.sk; g.tpb = (uint32_t)tpb; + g.nrb = (uint32_t)nrb; g.skg = wg ? (uint32_t)cg.sk : 0u; + const dim3 grid((unsigned)(nrb + (wg ? 1 : 0)), (unsigned)((M + 15) / 16)); + +#define R4D_RG_L(OWN, NWV) \ + emit_rc = R4D_EMIT(sk, (router_gemm_topk_scatter_kernel), grid, \ + dim3((NWV) * kWave), lds, \ + (const uint16_t*)x->data, (const uint16_t*)wr->data, \ + wg ? (const uint16_t*)wg->data : (const uint16_t*)nullptr, \ + (uint16_t*)lg->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \ + (int32_t*)ids->data, (uint16_t*)w->data, (int32_t*)sorted->data, \ + (int32_t*)off->data, (int32_t*)cnt->data, ctr, g, prot) + if (n_expert <= (long long)(8 * kWave)) { + if (nw == 8) R4D_RG_L(8, 8); + else if (nw == 16) R4D_RG_L(8, 16); + else R4D_RG_L(8, 32); + } else { + if (nw == 8) R4D_RG_L(16, 8); + else if (nw == 16) R4D_RG_L(16, 16); + else R4D_RG_L(16, 32); + } +#undef R4D_RG_L + if (emit_rc != RAD_OK) return emit_rc; + if (!sk.desc) R4D_MOE_CHK(); + return RAD_OK; +} +R4D_ENTRY(r4d_rad_router_gemm_topk_scatter, rad_router_gemm_topk_scatter_body) diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 0c66deb5..4fedfcdc 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -226,6 +226,11 @@ int r4d_rad_router_topk (const RadArgs*, RadStream); int r4d_rad_moe_scatter (const RadArgs*, RadStream); int r4d_rad_router_topk_scatter(const RadArgs*, RadStream); int r4d_rad_router_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +/* The router GEMM, the selection and the sort in one launch, the shared gate optionally beside + * them (R4D_ROUTER_FUSED in rad_block_moe_fp8.h). */ +int r4d_rad_router_gemm_topk_scatter(const RadArgs*, RadStream); +int r4d_rad_router_gemm_topk_scatter_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, + int*); int64_t r4d_rad_moe_scatter_scratch(const RadArgs*); int r4d_rad_moe_gemm_q (const RadArgs*, RadStream); /* Scratch for the run map the prefill form is aligned by. Zero in the decode band and zero for a @@ -487,6 +492,7 @@ int r4d_shape_dequant_w4 (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_router_topk (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_router_topk_scatter(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_router_gemm_topk_scatter(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_moe_scatter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gemm_q (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gemm_q_mod4(const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 0a94898c..71ee013a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -827,6 +827,29 @@ static const RadOperandSpec oRouterTopkScatter[] = { { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 }, }; +/* THE ROUTER'S GEMM IN FRONT OF THAT PAIR, and the shared expert's one-column gate beside it: + * `gemm_nt` [M, K] x [n_expert, K]^T, then `router_topk_scatter` over what it wrote, and -- with + * `gate_b` and `gate` present -- `gemm_nt` at N = 1 over the same input. The parameters are the + * union again; N is `n_expert` for the router and 1 for the gate, so neither is a parameter. + * The logits stay an OUTPUT: the routing report and the debug paths read them after the step. */ +static const RadParamSpec pRouterGemmTopkScatter[] = { + P_INT("M"), P_INT("K"), P_INT("n_expert"), P_INTO("n_local"), + P_INT("top_k"), P_INT("norm"), P_STR("dtype"), + P_INTO("expert_base"), + P_STRO("protect"), +}; +static const RadOperandSpec oRouterGemmTopkScatter[] = { + { "a", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "gate_b", RAD_OPD_WEIGHT, 1 }, + { "logits", RAD_OPD_OUT, 0 }, + { "expert_ids", RAD_OPD_OUT, 0 }, + { "expert_w", RAD_OPD_OUT, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, + { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 }, + { "gate", RAD_OPD_OUT, 1 }, +}; static const RadOperandSpec oMoeScatter[] = { { "expert_ids", RAD_OPD_IN, 0 }, { "sorted_tok", RAD_OPD_OUT, 0 }, @@ -2008,6 +2031,14 @@ static const RadOpSchema kSchemas[] = { "256-thread workgroup ranking about a kilobyte, and each costs the one-workgroup " "dispatch floor. Bounded: `M * top_k` must fit the sort's single-workgroup form, and a " "caller past that gets a refusal rather than a silent fallback to a different cost."), + SCHEMA("router_gemm_topk_scatter", pRouterGemmTopkScatter, oRouterGemmTopkScatter, + "`gemm_nt` (the router, N = n_expert) then `router_topk_scatter` over its logits, in " + "one launch -- and with `gate_b` and `gate` present, the shared expert's `gemm_nt` at " + "N = 1 over the same input as well. The workgroup that finishes the GEMM last runs the " + "selection and the sort. Byte-identical to the launches it stands in for: the same " + "split-K WMMA arithmetic at the split the unfused GEMM's own law picks, and the same " + "selection and sort. Decode only: M <= 64 and M * top_k within the sort's " + "single-workgroup form."), SCHEMA("moe_scatter", pMoeScatter, oMoeScatter, "a STABLE counting sort of the (token, slot) pairs by expert. `sorted_tok` holds the " "FLATTENED index token*top_k + slot and not the bare token id, because gather has to " @@ -2543,6 +2574,11 @@ static const RadConstraint cRouterTopkScatter[] = { C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "bf16"), }; +/* The selection's bounds and the skinny GEMM's decode band: four 16-row tiles. */ +static const RadConstraint cRouterGemmTopkScatter[] = { + C_GE("M", 1), C_LE("M", 64), C_DIV("K", 16), C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "bf16"), +}; static const RadConstraint cMoeScatter[] = { C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), }; @@ -4340,6 +4376,19 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_router_topk_scatter, nullptr, nullptr, nullptr, r4d_shape_router_topk_scatter, nullptr, nullptr, r4d_rad_router_topk_scatter_describe }, +{ "router_gemm_topk_scatter_bf16", "router_gemm_topk_scatter", "moe", + "the router GEMM, its top-k and the stable counting sort in one launch -- the last workgroup " + "of the GEMM ranks -- and optionally the shared expert's one-column gate beside it", + "M <= 64 and M*top_k <= 1024; n_expert <= 512, top_k <= min(n_expert, 32); K a multiple of " + "16 times the split the bf16 skinny GEMM's law picks", + "bf16 activation and weights, fp32 accumulate; bf16 logits, gate and weights, i32 ids, " + "sorted slots, offsets and counts out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterGemmTopkScatter), NOTUNE, + nullptr, nullptr, r4d_rad_router_gemm_topk_scatter, nullptr, nullptr, nullptr, + r4d_shape_router_gemm_topk_scatter, nullptr, nullptr, + r4d_rad_router_gemm_topk_scatter_describe }, + { "moe_scatter_i32", "moe_scatter", "moe", "a stable counting sort of the routing slots by expert, with the offsets and the histogram", "n_expert <= 256; one launch at M*top_k <= 1024 and four above it, and the four exist to keep " diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 9f3ab668..0e60aed7 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -1794,6 +1794,200 @@ static void topk_scatter_at(const RadKernelInfo* rf, const RadKernelInfo* rt, } } +/* -------------------------------- router_gemm_topk_scatter, against the launches it stands in for + * + * The claim is byte equality with THREE launches: the router's gemm_nt, the shared gate's gemm_nt + * at N = 1, and router_topk_scatter over the router's logits -- so all seven outputs are compared, + * the logits and the gate included. Those two are what the claim rests on: an element of the + * skinny bf16 GEMM is a function of its split-K count alone, and the fused op asks the unfused + * launch's own law for that count at each N (four at 512 x 2560, twenty for the one-column gate; + * eight and sixteen at 256 x 2048). + * + * ROWS AT EVERY WAVE COUNT AND EVERY ROW-TILE COUNT the fused op launches -- 8, 16 and 32 waves, + * one to four 16-row tiles, partial tiles included -- at the served geometry (512 experts, + * top_k 10, K 2560) and at a 256-expert one, which takes the other selection instantiation and + * other splits. An expert-parallel slice with a protect list, and the form without the gate. + * + * AND TWICE, BACK TO BACK, ON ONE OUTPUT. The last workgroup is named by a counter that resets + * itself; a counter left behind by one launch would make the next one rank before the GEMM was + * done, or never. The configurations share one logits buffer -- and with it one counter -- in + * an order that changes the grid between consecutive launches. */ +static void router_gemm_fused_case(const Plugin& pl) { + if (!sel("router_gemm_topk_scatter_bf16")) return; + const RadKernelInfo* rg = find(pl, "router_gemm_topk_scatter_bf16"); + const RadKernelInfo* m16 = find(pl, "gemm_bf16_nt_m16"); + const RadKernelInfo* m64 = find(pl, "gemm_bf16_nt_m64"); + const RadKernelInfo* rf = find(pl, "router_topk_scatter_bf16"); + if (!rg || !m16 || !m64 || !rf) { ok("router_gemm_topk_scatter", false, "row absent"); return; } + + struct RgCase { + int64_t ne, K, k, nl, base; + const char* prot; + bool gate; + std::vector Ms; + }; + const std::vector cfgs = { + { 512, 2560, 10, 512, 0, nullptr, true, { 1, 4, 5, 8, 13, 16, 20, 33, 45, 64 } }, + { 512, 2560, 10, 512, 0, nullptr, false, { 4, 20 } }, + { 512, 2560, 10, 254, 3, "0,17,101,253", true, { 5, 45 } }, + { 512, 2560, 10, 254, 3, nullptr, false, { 13 } }, + { 256, 2048, 8, 256, 0, nullptr, true, { 4, 33 } }, + }; + const int64_t maxM = 64, maxNe = 512, maxK = 2560, maxNS = 64 * 10; + + uint64_t rs64 = 0x2545F4914F6CDD1Dull; + auto rnd = [&]() { rs64 ^= rs64 << 13; rs64 ^= rs64 >> 7; rs64 ^= rs64 << 17; return rs64; }; + auto uni = [&](float lo, float hi) { + return lo + (hi - lo) * (float)((rnd() >> 40) & 0xFFFFFFu) * (1.0f / 16777216.0f); + }; + + void* d_a = dalloc((size_t)maxM * maxK * 2); + void* d_w = dalloc((size_t)maxNe * maxK * 2); + void* d_wg = dalloc((size_t)maxK * 2); + void* d_lg[2] = { dalloc((size_t)maxM * maxNe * 2), dalloc((size_t)maxM * maxNe * 2) }; + void* d_g [2] = { dalloc((size_t)maxM * 2), dalloc((size_t)maxM * 2) }; + void* d_id[2] = { dalloc((size_t)maxNS * 4), dalloc((size_t)maxNS * 4) }; + void* d_ew[2] = { dalloc((size_t)maxNS * 2), dalloc((size_t)maxNS * 2) }; + void* d_so[2] = { dalloc((size_t)maxNS * 4), dalloc((size_t)maxNS * 4) }; + void* d_of[2] = { dalloc((size_t)(maxNe + 1) * 4), dalloc((size_t)(maxNe + 1) * 4) }; + void* d_cn[2] = { dalloc((size_t)maxNe * 4), dalloc((size_t)maxNe * 4) }; + if (!d_a || !d_w || !d_wg || !d_lg[0] || !d_lg[1] || !d_g[0] || !d_g[1] || !d_id[0] || + !d_id[1] || !d_ew[0] || !d_ew[1] || !d_so[0] || !d_so[1] || !d_of[0] || !d_of[1] || + !d_cn[0] || !d_cn[1]) { + ok("router_gemm_topk_scatter", false, "hipMalloc failed"); + return; + } + + for (const RgCase& c : cfgs) { + /* A trained router's logits are a few units wide; these are about that, with a tie + * planted in every row so the selection's tie rule decides something. */ + std::vector hw((size_t)c.ne * c.K), hwg((size_t)c.K); + for (auto& v : hw) v = h_to_bf16(uni(-0.06f, 0.06f)); + for (auto& v : hwg) v = h_to_bf16(uni(-0.06f, 0.06f)); + for (int64_t kk = 0; kk < c.K; ++kk) hw[(size_t)(7 * c.K + kk)] = hw[(size_t)(3 * c.K + kk)]; + st_memcpy(d_w, hw.data(), hw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_wg, hwg.data(), hwg.size() * 2, hipMemcpyHostToDevice); + + for (const int64_t M : c.Ms) { + const int64_t NS = M * c.k; + const std::string at = fmt(" (n_expert %lld, n_local %lld, M=%lld%s%s)", + (long long)c.ne, (long long)c.nl, (long long)M, + c.gate ? ", gate" : "", + c.prot ? ", protect" : ""); + std::vector ha((size_t)M * c.K); + for (auto& v : ha) v = h_to_bf16(uni(-2.0f, 2.0f)); + st_memcpy(d_a, ha.data(), ha.size() * 2, hipMemcpyHostToDevice); + for (int i = 0; i < 2; ++i) { + st_memset(d_lg[i], 0xFF, (size_t)maxM * maxNe * 2); + st_memset(d_g[i], 0xFF, (size_t)maxM * 2); + st_memset(d_id[i], 0xFF, (size_t)maxNS * 4); + st_memset(d_ew[i], 0, (size_t)maxNS * 2); + st_memset(d_so[i], 0xFF, (size_t)maxNS * 4); + st_memset(d_of[i], 0xFF, (size_t)(maxNe + 1) * 4); + st_memset(d_cn[i], 0xFF, (size_t)maxNe * 4); + } + + /* ---- the three launches */ + const RadKernelInfo* gr = M <= 16 ? m16 : m64; + { + std::vector ts = { T(d_a, RAD_BF16, { M, c.K }), + T(d_w, RAD_BF16, { c.ne, c.K }), + T(d_lg[0], RAD_BF16, { M, c.ne }) }; + std::vector ps = { PI("M", M), PI("N", c.ne), PI("K", c.K), + PS("dtype", "bf16") }; + run_case(gr, ts, ps); + } + if (c.gate) { + std::vector ts = { T(d_a, RAD_BF16, { M, c.K }), + T(d_wg, RAD_BF16, { 1, c.K }), + T(d_g[0], RAD_BF16, { M, 1 }) }; + std::vector ps = { PI("M", M), PI("N", 1), PI("K", c.K), + PS("dtype", "bf16") }; + run_case(gr, ts, ps); + } + { + std::vector ts = { T(d_lg[0], RAD_BF16, { M, c.ne }), + T(d_id[0], RAD_I32, { M, c.k }), + T(d_ew[0], RAD_BF16, { M, c.k }), + T(d_so[0], RAD_I32, { NS }), + T(d_of[0], RAD_I32, { c.nl + 1 }), + T(d_cn[0], RAD_I32, { c.nl }) }; + std::vector ps = { PI("M", M), PI("n_expert", c.ne), + PI("n_local", c.nl), PI("top_k", c.k), PI("norm", 1), + PS("dtype", "bf16"), PI("expert_base", c.base) }; + if (c.prot) ps.push_back(PS("protect", c.prot)); + run_case(rf, ts, ps); + } + + /* ---- the fused op, twice */ + for (int rep = 0; rep < 2; ++rep) { + std::vector ts = { T(d_a, RAD_BF16, { M, c.K }), + T(d_w, RAD_BF16, { c.ne, c.K }), + T(d_wg, RAD_BF16, { 1, c.K }), + T(d_lg[1], RAD_BF16, { M, c.ne }), + T(d_id[1], RAD_I32, { M, c.k }), + T(d_ew[1], RAD_BF16, { M, c.k }), + T(d_so[1], RAD_I32, { NS }), + T(d_of[1], RAD_I32, { c.nl + 1 }), + T(d_cn[1], RAD_I32, { c.nl }), + T(d_g[1], RAD_BF16, { M, 1 }) }; + if (!c.gate) { absent(ts[2]); absent(ts[9]); } + std::vector ps = { PI("M", M), PI("K", c.K), PI("n_expert", c.ne), + PI("n_local", c.nl), PI("top_k", c.k), PI("norm", 1), + PS("dtype", "bf16"), PI("expert_base", c.base) }; + if (c.prot) ps.push_back(PS("protect", c.prot)); + if (rep == 1) { + /* The second launch must not find anything the first one left. */ + st_memset(d_id[1], 0xFF, (size_t)maxNS * 4); + st_memset(d_so[1], 0xFF, (size_t)maxNS * 4); + st_memset(d_of[1], 0xFF, (size_t)(maxNe + 1) * 4); + } + run_case(rg, ts, ps); + + const std::string tag = at + (rep ? ", second launch" : ""); + auto same = [&](const char* what, void* a, void* b, size_t bytes) { + std::vector x(bytes), y(bytes); + st_memcpy(x.data(), a, bytes, hipMemcpyDeviceToHost); + st_memcpy(y.data(), b, bytes, hipMemcpyDeviceToHost); + size_t first = bytes; + int64_t n_off = 0; + for (size_t i = 0; i < bytes; ++i) + if (x[i] != y[i]) { if (first == bytes) first = i; ++n_off; } + ok((std::string("router_gemm_topk_scatter ") + what + + " is byte-identical to the unfused launches" + tag).c_str(), + n_off == 0, + n_off ? fmt("%lld byte(s) differ, first at byte %zu", (long long)n_off, + first) : std::string()); + }; + same("logits", d_lg[0], d_lg[1], (size_t)M * c.ne * 2); + if (c.gate) same("shared gate", d_g[0], d_g[1], (size_t)M * 2); + same("expert_ids", d_id[0], d_id[1], (size_t)NS * 4); + same("expert_w", d_ew[0], d_ew[1], (size_t)NS * 2); + same("sorted_tok", d_so[0], d_so[1], (size_t)NS * 4); + same("expert_offset", d_of[0], d_of[1], (size_t)(c.nl + 1) * 4); + same("expert_count", d_cn[0], d_cn[1], (size_t)c.nl * 4); + } + } + } + /* A shape past the decode band is refused, not served at another arithmetic. */ + { + const int64_t M = 65; + std::vector ts = { T(nullptr, RAD_BF16, { M, 2560 }), + T(d_w, RAD_BF16, { 512, 2560 }), + T(d_wg, RAD_BF16, { 1, 2560 }), + T(nullptr, RAD_BF16, { M, 512 }), + T(nullptr, RAD_I32, { M, 10 }), + T(nullptr, RAD_BF16, { M, 10 }), + T(nullptr, RAD_I32, { M * 10 }), + T(nullptr, RAD_I32, { 513 }), + T(nullptr, RAD_I32, { 512 }), + T(nullptr, RAD_BF16, { M, 1 }) }; + std::vector ps = { PI("M", M), PI("K", 2560), PI("n_expert", 512), + PI("top_k", 10), PI("norm", 1), PS("dtype", "bf16") }; + run_case(rg, ts, ps, RAD_E_SHAPE); + } +} + /* THE PROTECTED EXPERTS ARE SORTED LAST, against a host stable sort by place. A layer that keeps a * few experts at a higher precision serves them with a second grouped GEMM over a trailing run of * the offsets, so the sort has to put their rows after every other expert's, in the order listed, @@ -10152,6 +10346,7 @@ static void device_phase(const Plugin& pl) { qk_kv_fold_case(pl, true); qsa_qprep_case(pl); topk_scatter_case(pl); + router_gemm_fused_case(pl); scatter_protect_case(pl); if (sel("rowtopk_bf16")) { const RadKernelInfo* r = find(pl, "rowtopk_bf16"); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 295057e9..13676915 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1277,6 +1277,33 @@ extern "C" int r4d_shape_router_topk_scatter(const RadParam* p, int n_p, int ope }; R4D_PICK(l); } +/* The router's gemm_nt in front of router_topk_scatter, and the shared gate's gemm_nt at N = 1 + * beside it: the three lists, with `logits` named once as the GEMM's output. */ +extern "C" int r4d_shape_router_gemm_topk_scatter(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t K = pi(p, n_p, "K"); + const int64_t ne = pi(p, n_p, "n_expert"); + const int64_t k = pi(p, n_p, "top_k"); + if (ne <= 0 || ne > 256 || k <= 0 || k > ne || K <= 0) return RAD_E_UNSUPPORTED; + if (M > 64 || M * k > 1024) return RAD_E_UNSUPPORTED; + const int64_t nl = pi(p, n_p, "n_local", ne); + if (nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { + opd(D, M, K), + opd(D, ne, K), + opd(D, 1, K), + opd(D, M, ne), + opd((uint32_t)RAD_I32, M, k), + opd(D, M, k), + opd((uint32_t)RAD_I32, M * k), + opd((uint32_t)RAD_I32, nl + 1), + opd((uint32_t)RAD_I32, nl), + opd(D, M, 1), + }; + R4D_PICK(l); +} extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t ne = pi(p, n_p, "n_expert");