From ee5fcf1024277b9a76a3c025dc4a161266d71528 Mon Sep 17 00:00:00 2001 From: keptn42 Date: Mon, 5 Oct 2026 21:18:57 +0000 Subject: [PATCH] moe_gemm_q decode form: the sorted operand's own kernel, a block a run tile and G column tiles At 16 sequences the (tile, run) grid gives down 25 600 blocks. Many find no run, the others stage 4-8 KB of weight behind a search and a barrier pair, and a run that crosses a 16-row tile is read twice. R4D_MOE_DOWN2=1 sends down's decode-form launch to moe_down_dec_kernel: one block per 16-row tile of a run, found among all runs in one round trip, and G 64-column tiles a block whose passes form one pipeline. G follows the routed rows (1 below 200, 2 below 480, 4 above) or R4D_MOE_DOWN2_G. Bit-identical, off by default. 16 concurrent: 36.4 -> 33.9 ms a step. --- libr4d/r4d.h | 5 + libr4d/r4d_moe.hip | 388 ++++++++++++++++++++++++++++++++++++++++ libr4d/r4d_selftest.cpp | 369 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 762 insertions(+) diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 87dc400f..1e73f840 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -660,6 +660,11 @@ void r4d_moe_pf2_pin(int pin); // The parts the launches since the last call took, under a pin, as R4D_MOE_PF2's mask; cleared by // the call. A test reads it to know a part's kernel ran rather than the default's. uint32_t r4d_moe_pf2_used(void); +// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is R4D_MOE_DOWN2's rule (and +// R4D_MOE_DOWN2_G's), -1 the (tile, run) form, n > 0 moe_down_dec_kernel at n column tiles a block. +// Inside the decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical, and +// r4d_selftest compares their bytes. +void r4d_moe_gemm_pin_down2(int pin); // THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode // tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide // kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index 8ab01a2a..8c7f931a 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -1802,6 +1802,355 @@ static_assert(MoeQArgs::bytes() <= RAD_KPARAM_BLOB, static_assert(MoeQArgs::count <= RAD_MAX_KPARAMS, "moe_gemm_q_kernel has more arguments than RAD_MAX_KPARAMS"); +/* ================================================================== moe_gemm_q, the down decode form + * + * THE SORTED-OPERAND PROJECTION AT DECODE, ONE BLOCK A RUN TILE, G COLUMN TILES A BLOCK. + * + * The (tile, run) grid above gives down -- K 128 or 256 a rank, N the model width -- one block for + * every 16-row tile's every run slot and every 64 columns: at sixteen sequences, 640 routed rows + * over some three hundred experts, that is 640 x 40 = 25 600 blocks for about 63 MB of weight. + * More than half of them find no run and leave after the search, and each of the others stages + * 4 or 8 KB of weight behind a search, a table load and a barrier pair -- one or two K passes, so + * nothing of its own to overlap. A run that crosses a tile boundary is staged by two blocks. + * + * Here a block owns ONE 16-ROW TILE OF ONE RUN -- the tiles start at the run's first row, as the + * run-aligned prefill form's do -- and G 64-column tiles of its output: + * + * - THE GRID IS (run tile, column group). A run of n rows is ceil(n / 16) tiles, so there are at + * most min(T, n_expert) + T/16 of them; block j finds the j-th in expert order in one round + * trip (every offset, four a thread, one load wave, a DPP count and one exchange of the waves' + * totals), the way RS finds a tile's run. One more block at the end zeroes the rows past the + * live count, which no run owns. + * - A RUN IS NEVER SPLIT AT AN ARBITRARY ROW: a run of up to sixteen rows is one tile however it + * falls, so an expert's weight is staged once a column tile, not once for each 16-row band of + * the sorted rows it touches. A longer run is a block a tile, side by side, rather than one + * block walking all of them -- a popular expert does not become the kernel's tail. + * - THE PASSES OF ALL G COLUMN TILES ARE ONE PIPELINE: (column tile, K block), each pass's + * operands loaded one pass ahead as in the K loop above -- so the next tile's weight is in + * flight while this one's last block is computed. The chain the (tile, run) form pays once a + * block -- search, table, first load -- is paid once a G tiles here. + * + * G is the launcher's: one at a step of a few sequences, where every run is needed to fill the part, + * and up to four at sixteen, where there are runs enough. The loads are UW's throughout -- uniform + * global bases and LDS-only barriers -- because a barrier that waits for the prefetch would make the + * pipeline a chain again. + * + * BIT-IDENTICAL to the (tile, run) form: an output element is one wave's WMMA chain over the same K + * in the same order, folded by the same expression under the same scales; only which block, and + * which row of its 16-row tile, computes it moves -- the argument the AL form makes, and the + * selftest compares every form with this one byte for byte. + * + * ONLY THE SORTED OPERAND, where a run's activation rows are its own rows: [rs, re) of `Aq`, with + * no gather. Inside a run every row is a placed slot -- the scatter fills [0, off[n_expert]) and + * nothing else -- so `sorted` decides nothing here and is not read. */ +template +__global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel( + const uint8_t* __restrict__ Aq, const float* __restrict__ As, + const MoeCls c_even, const MoeCls c_odd, const MoeCls c_2, const MoeCls c_3, + const int32_t* __restrict__ off, uint16_t* __restrict__ Y, + uint32_t T, uint32_t N, uint32_t n_expert, uint32_t G, + uint32_t a_ld, uint32_t as_ld, uint32_t y_ld, uint32_t mode, const MoeTab tab) { + constexpr bool UW = true; + constexpr uint32_t FM = 16, FN = 64, FK = kFK, NTHR = 4 * kWave; + constexpr uint32_t kSub = W4 == 3 ? 4u : (W4 == 2 || W4 == 4) ? 2u : 1u; + constexpr uint32_t NPT = kMaxExpert / NTHR; + static_assert(kMaxExpert % NTHR == 0, "the offsets divide over the block's threads"); + static_assert(FK % (kSub * r4d_fp8::kK) == 0, "a scale group is whole WMMA K steps"); + static_assert(FM + FN <= NTHR, "a thread stages each row's and each column's scale"); + const uint32_t cshift = (mode >> 1) & 3u, parts = mode >> 8; + + __shared__ uint8_t s_a[FM * lds_pitch()]; + __shared__ uint8_t s_b[FN * lds_pitch()]; + __shared__ float s_as[FM]; + __shared__ float s_ws[kSub * FN]; + __shared__ uint32_t s_rc[NTHR / kWave]; + __shared__ uint32_t s_sel[3]; + + const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; + /* The block's columns: G 64-wide tiles from cg0, the last group cut at N. */ + const uint32_t cg0 = blockIdx.y * G * FN; + if (cg0 >= N) return; /* the launcher's grid has none; block-uniform */ + const uint32_t cend = cg0 + G * FN < N ? cg0 + G * FN : N; + const uint32_t ng = (cend - cg0 + FN - 1) / FN; + + /* THE LAST BLOCK OWNS NO RUN: the rows past the live count are dropped slots, or the protected + * experts' rows their own GEMM writes after this one, and here they are zero -- every column, + * as the (tile, run) form's first block of a tile leaves them. */ + if (blockIdx.x == gridDim.x - 1) { + const uint32_t live = (uint32_t)off[n_expert]; + for (uint32_t r = live; r < T; ++r) + for (uint32_t c = cg0 + tid; c < cend; c += NTHR) Y[(size_t)r * y_ld + c] = 0; + return; + } + + /* THE TILE: the j-th 16-row tile of a run, in expert order and then row order. Every thread + * holds NPT consecutive experts' offsets and the next one, from one wave of loads; the tiles + * are numbered a thread's own in order, then over the wave (DPP) and the waves before it. + * Both barriers order LDS. */ + uint32_t ov[NPT + 1]; +#pragma unroll + for (uint32_t k = 0; k <= NPT; ++k) { + const uint32_t x = tid * NPT + k; + ov[k] = x <= n_expert ? (uint32_t)off[x] : 0u; + } + uint32_t nt[NPT], cnt = 0; +#pragma unroll + for (uint32_t k = 0; k < NPT; ++k) { + nt[k] = tid * NPT + k < n_expert ? (ov[k + 1] - ov[k] + FM - 1) / FM : 0u; + cnt += nt[k]; + } + const uint32_t inc = (uint32_t)wave_incl_scan_i32((int32_t)cnt, lane); + if (lane == kWave - 1) s_rc[wave] = inc; + lds_barrier(); + uint32_t before = inc - cnt, ntile = 0; +#pragma unroll + for (uint32_t w = 0; w < NTHR / kWave; ++w) { + const uint32_t c = s_rc[w]; + before += w < wave ? c : 0u; + ntile += c; + } + const uint32_t j = blockIdx.x; + if (j >= ntile) return; /* fewer tiles than slots: block-uniform */ + if (j >= before && j < before + cnt) { + uint32_t m = j - before; + bool hit = false; +#pragma unroll + for (uint32_t k = 0; k < NPT; ++k) { + if (!hit && m < nt[k]) { + s_sel[0] = tid * NPT + k; + s_sel[1] = ov[k] + m * FM; + s_sel[2] = ov[k + 1]; + hit = true; + } + if (!hit) m -= nt[k]; + } + } + lds_barrier(); + /* Block-uniform from here on, and said so: the class, the table entry and every pass bound + * below are then scalar. The block's rows are [rs, re), at most a tile. */ + const uint32_t e = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[0]); + const uint32_t rs = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[1]); + const uint32_t r1 = (uint32_t)__builtin_amdgcn_readfirstlane((int)s_sel[2]); + const uint32_t re = rs + FM < r1 ? rs + FM : r1; + + const uint32_t cls = e & ((1u << cshift) - 1u); + const MoeCls& C = cls == 0u ? c_even : cls == 1u ? c_odd : cls == 2u ? c_2 : c_3; + const uint32_t fy = N / parts, fc = C.n / parts; + const uint32_t K = C.k, w_ld = C.w_ld, ws_ld = C.s_ld; + const uint8_t* Wp0 = wtab_at(C.w, C.w_s0, e >> cshift); + const uint16_t* Wsp0 = (const uint16_t*)wtab_at(C.s, C.s_s0, e >> cshift); + const uint8_t* Wp = uw_ptr(Wp0); + const uint16_t* Wsp = uw_ptr(Wsp0); + + /* A COLUMN TILE PAST THE CLASS'S WIDTH holds no weight: the run's rows there are zero, as the + * (tile, run) form writes them, and it takes no pass. The others are `npm`. */ + uint32_t npm = 0; + for (uint32_t g = 0; g < ng; ++g) { + const uint32_t n0 = cg0 + g * FN, part = n0 / fy, j0 = n0 - part * fy; + if (j0 < fc) { npm |= 1u << g; continue; } + const uint32_t nr = re - rs; + for (uint32_t x = tid; x < nr * FN; x += NTHR) { + const uint32_t c = x % FN; + if (n0 + c < N) Y[(size_t)(rs + x / FN) * y_ld + n0 + c] = 0; + } + } + if (!npm) return; + + /* THE PASSES: (column tile, K block), K innermost. The last pass's successor is never + * issued. */ + const uint32_t nK = K / FK; + const uint32_t P = (uint32_t)__builtin_popcount(npm) * nK; + struct Pass { uint32_t g, kp; }; + auto advance = [&](Pass s) { + if (++s.kp < nK) return s; + s.kp = 0; + const uint32_t rest = npm & ~((2u << s.g) - 1u); + s.g = rest ? (uint32_t)__builtin_ctz(rest) : s.g; + return s; + }; + + constexpr uint32_t kSeg = 32; /* bytes a thread stages, contiguous */ + constexpr uint32_t kTPR = FK / kSeg; /* threads covering one staged row */ + constexpr uint32_t kRPP = NTHR / kTPR; /* rows one staging pass covers */ + constexpr uint32_t kAP = (FM + kRPP - 1) / kRPP; + constexpr uint32_t kBP = (FN + kRPP - 1) / kRPP; + const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg; + + /* The operands one pass ahead, as moe_gemm_q_kernel's UW path holds them: the scale loads + * unconditional, the zero selected at the LDS store, and the two scale roles' registers not + * initialised -- see the note there. */ + Stage8 apre[kAP]; + uint4 bpre4[kBP]; + uint32_t spre[W4 == 4 ? kBP : 1]; + Stage8 bpre8[kBP]; + using PwsT = std::conditional_t; + float pau[1]; + PwsT pwu[1]; + bool pok = false; + auto issue = [&](const Pass& s) { + const uint32_t cc = s.kp * FK, kbk = s.kp; /* FK is one 128-wide scale block */ + const uint32_t n0 = cg0 + s.g * FN, part = n0 / fy, j0 = n0 - part * fy; + const uint32_t wn0 = part * fc + j0; /* the weight row of the tile's column 0 */ + const uint32_t kb_n = wn0 / kBlock; + if constexpr (W4) (void)kb_n; + if (tid < FM) { + const uint32_t row = rs + tid; + pok = row < re; + pau[0] = As[(size_t)(pok ? row : 0u) * as_ld + kbk]; + } else if (tid < FM + FN) { + const uint32_t nn = tid - FM; + pok = j0 + nn < fc; + const size_t wr = (size_t)(pok ? wn0 + nn : wn0) * ws_ld + kbk; + if constexpr (W4 == 3) + pwu[0] = u32_load_w((const uint32_t*)Wsp + wr); + else if constexpr (W4) + pwu[0] = u16_load_w(Wsp + wr); + else + pwu[0] = u16_load_w(Wsp + (size_t)kb_n * ws_ld + kbk); + } +#pragma unroll + for (uint32_t p = 0; p < kAP; ++p) { + const uint32_t r = sn + p * kRPP; + if (r >= FM) continue; + const uint32_t row = rs + r; + const bool ok = row < re; + apre[p] = stage8_load(Aq + (size_t)(ok ? row : 0u) * a_ld + cc + sk, ok); + } +#pragma unroll + for (uint32_t p = 0; p < kBP; ++p) { + const uint32_t r = sn + p * kRPP; + if (r >= FN) continue; + const bool ok = (j0 + r) < fc; + if constexpr (W4) { + const uint8_t* wr = Wp + (size_t)(wn0 + r) * w_ld; + bpre4[p] = w4_load_w(wr + ((cc + sk) >> 1), ok); + if constexpr (W4 == 4) + spre[p] = ok ? u32_load_w((const uint32_t*)(wr + (K >> 1) + + ((cc + sk) >> 3))) + : 0u; + } else + bpre8[p] = stage8_load_w(Wp + (size_t)(wn0 + r) * w_ld + cc + sk, ok); + } + }; + + f8v raw = acc_zero(), out = acc_zero(); + /* The other scale groups' accumulators at W4 2 to 4; each starts fresh at its group's first + * WMMA, so none is zeroed. */ + f8v rx[kSub > 1 ? kSub - 1 : 1]; + Pass cur{(uint32_t)__builtin_ctz(npm), 0u}; + issue(cur); + for (uint32_t p = 0; p < P; ++p) { + lds_barrier(); /* the previous pass's reads are done */ + /* The prefetch collected in one wait, as at moe_gemm_q_kernel's UW K loop head. */ + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "global"); +#pragma unroll + for (uint32_t q = 0; q < kAP; ++q) { + const uint32_t r = sn + q * kRPP; + if (r >= FM) continue; + stage8_store(s_a, r, sk, apre[q]); + } +#pragma unroll + for (uint32_t q = 0; q < kBP; ++q) { + const uint32_t r = sn + q * kRPP; + if (r >= FN) continue; + if constexpr (W4 == 4) + stage8_store(s_b, r, sk, w5_expand(bpre4[q], spre[q], tab.v)); + else if constexpr (W4) + stage8_store(s_b, r, sk, w4_expand(bpre4[q], tab.v)); + else + stage8_store(s_b, r, sk, bpre8[q]); + } + if (tid < FM) { + s_as[tid] = pok ? pau[0] : 0.0f; + } else if (tid < FM + FN) { + const PwsT pws = pok ? pwu[0] : (PwsT)0; + if constexpr (kSub > 1) { +#pragma unroll + for (uint32_t q = 0; q < kSub; ++q) + s_ws[q * FN + tid - FM] = + r4d_fp8::e4m3((uint32_t)((pws >> (8 * q)) & 0xFFu)) * kW4G64Scale; + } else { + s_ws[tid - FM] = (W4 || tid == FM) ? bscale(pws) : 0.0f; + } + } + const Pass nxt = advance(cur); + if (p + 1 < P) issue(nxt); + lds_barrier(); + + /* moe_gemm_q_kernel's K step and fold at one M tile by one N tile a wave. */ + auto kstep = [&](uint32_t ks, f8v& acc, bool fresh = false) { + const i2v af = frag(s_a, 0, ks, lane); + const i2v bf = frag(s_b, wave * 16, ks, lane); + acc = mma(af, bf, fresh ? acc_zero() : acc); + }; + if constexpr (kSub > 1) { + constexpr uint32_t kG = FK / kSub; +#pragma unroll + for (uint32_t ks = 0; ks < kG; ks += r4d_fp8::kK) kstep(ks, raw, ks == 0); +#pragma unroll + for (uint32_t q = 1; q < kSub; ++q) +#pragma unroll + for (uint32_t ks = q * kG; ks < (q + 1) * kG; ks += r4d_fp8::kK) + kstep(ks, rx[q - 1], ks == q * kG); + } else { +#pragma unroll + for (uint32_t ks = 0; ks < FK; ks += r4d_fp8::kK) kstep(ks, raw); + } + { + float as[8]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) as[t] = s_as[acc_row(lane, t)]; + if constexpr (kSub > 1) { + float wq[kSub]; +#pragma unroll + for (uint32_t q = 0; q < kSub; ++q) wq[q] = s_ws[q * FN + wave * 16 + frag_c(lane)]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + float v = raw[t] * wq[0]; +#pragma unroll + for (uint32_t q = 1; q < kSub; ++q) v += rx[q - 1][t] * wq[q]; + out[t] += v * as[t]; + } + } else if constexpr (W4) { + const float wsj = s_ws[wave * 16 + frag_c(lane)]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + out[t] += raw[t] * as[t] * wsj; + raw[t] = 0.0f; + } + } else { + const float ws = s_ws[0]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) as[t] *= ws; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + out[t] += raw[t] * as[t]; + raw[t] = 0.0f; + } + } + } + + /* The tile's last K block: its rows of the run, then a fresh accumulator. */ + if (cur.kp + 1 == nK) { + const uint32_t n0 = cg0 + cur.g * FN; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + const uint32_t row = rs + acc_row(lane, t); + const uint32_t c = wave * 16 + frag_c(lane); + if (row >= re || n0 + c >= N) continue; + Y[(size_t)row * y_ld + n0 + c] = f32_to_bf16(out[t]); + } + out = acc_zero(); + } + cur = nxt; + } +} +using MoeDnArgs = R4dParams)>; +static_assert(MoeDnArgs::bytes() <= RAD_KPARAM_BLOB, + "moe_down_dec_kernel's arguments overflow RAD_KPARAM_BLOB"); +static_assert(MoeDnArgs::count <= RAD_MAX_KPARAMS, + "moe_down_dec_kernel has more arguments than RAD_MAX_KPARAMS"); + /* ================================================================== moe_gemm, bf16 * * y[i, :] = a[row(i), :] @ w[e]^T in SORTED order, both operands bf16 and one f32 accumulator over @@ -2733,6 +3082,26 @@ static inline bool r4d_moe_gu_fk256(long long T, bool a_sorted) { if (g_moe_fk_pin == 2) return true; return T <= kMoeGuFk256Rows; } +/* R4D_MOE_DOWN2=1: the decode form of the SORTED-operand projection (down) is moe_down_dec_kernel + * -- a block a 16-row tile of a run, G 64-column tiles a block, see its note. Unset or 0: the + * (tile, run) form, as upstream. R4D_MOE_DOWN2_G=n fixes G (1 to 16); unset, G follows the + * routed-row count: 1 below 200 rows, 2 below 480, 4 from there, which keeps a few thousand working + * blocks from one sequence to sixteen. Bit-identical; read once, so a recorded pass and a live + * one take the same kernel. A test pin over both: 0 the switches, -1 off, n > 0 on at G = n. */ +static int g_moe_dn2_pin = 0; +static long long r4d_moe_down2_g(long long T) { + if (g_moe_dn2_pin) return g_moe_dn2_pin > 0 ? g_moe_dn2_pin : 0; + auto env = [](const char* name) { + const char* e = std::getenv(name); + const long long x = e ? std::atoll(e) : 0; + return x > 0 ? x : 0LL; + }; + static const long long on = env("R4D_MOE_DOWN2"); + static const long long gf = env("R4D_MOE_DOWN2_G"); + if (on <= 0) return 0; + if (gf > 0) return gf < 16 ? gf : 16; + return T >= 480 ? 4 : T >= 200 ? 2 : 1; +} /* THE MAP'S UPPER BOUND, stated once because the scratch hook and the launcher must agree about * it exactly: a hook that answers for a different shape than the launch uses is how a kernel ends * up writing past the arena it was given. Every expert contributes one block, plus one more for @@ -3025,6 +3394,24 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) { /* THE DECODE GRID IS (tile, run) WIDE -- see the kernel's ES note. One tile of rows is all * a decode step has, so without this the whole layer runs on N/64 workgroups. */ const unsigned tiles = (unsigned)((T + 15) / 16); + /* R4D_MOE_DOWN2: the sorted operand's own decode kernel, a block a run tile and G column + * tiles -- see moe_down_dec_kernel. Its grid is the run tiles' upper bound, a tile for + * every run and one more for every 16 rows, and one block for the dropped tail, by the + * column groups. */ + const long long g2 = a_sorted ? r4d_moe_down2_g(T) : 0; + if (g2 > 0 && parts == 1 && n_expert <= (long long)kMaxExpert) { + const unsigned slots = (unsigned)(std::min(T, n_expert) + (T + 15) / 16); + const unsigned groups = (unsigned)((N + 64 * g2 - 1) / (64 * g2)); + emit_rc = R4D_EMIT(sk, (moe_down_dec_kernel), + dim3(slots + 1u, groups), dim3(4 * kWave), 0, + (const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3, + (const int32_t*)off->data, (uint16_t*)Y->data, + (uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)g2, + (uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv); + if (emit_rc != RAD_OK) return emit_rc; + if (!sk.desc) R4D_MOE_CHK(); + return RAD_OK; + } /* WHICH INSTANTIATION: the weight from a uniform global base (UW) always; the run search * in one round trip (RS) up to kMaxExpert experts and the chunked search above that; and * two 128-wide K blocks a pass where kMoeGuFk256Rows admits the row count, every class's @@ -3175,6 +3562,7 @@ extern "C" int64_t r4d_rad_moe_gemm_w4a8_scratch(const RadArgs* a) { return moe_ extern "C" void r4d_moe_gemm_pin_prefill(int form) { g_moe_prefill_form = form; } extern "C" void r4d_moe_gemm_pin_fk(int pin) { g_moe_fk_pin = pin; } +extern "C" void r4d_moe_gemm_pin_down2(int pin) { g_moe_dn2_pin = pin; } extern "C" int r4d_rad_moe_gemm_q(const RadArgs* a, RadStream s) { return moe_gemm_launch<0>(a, r4d_stream_sink(s)); diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index f35c144b..27953d00 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -167,6 +167,7 @@ struct Plugin { void (*pin_fk)(int) = nullptr; void (*pin_pf2)(int) = nullptr; uint32_t (*pf2_used)(void) = nullptr; + void (*pin_dn2)(int) = nullptr; void (*pin_hc)(int) = nullptr; void (*pin_qsel)(int) = nullptr; }; @@ -200,6 +201,7 @@ static bool load(Plugin* pl, const char* path) { okall &= sym(pl->h, "r4d_moe_gemm_pin_fk", &pl->pin_fk); okall &= sym(pl->h, "r4d_moe_pf2_pin", &pl->pin_pf2); okall &= sym(pl->h, "r4d_moe_pf2_used", &pl->pf2_used); + okall &= sym(pl->h, "r4d_moe_gemm_pin_down2", &pl->pin_dn2); okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc); okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel); return okall; @@ -7458,6 +7460,367 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons moe_dec_variants(pl, r, a, d_y, (size_t)(Tr * N), fk2, what); } +/* A DECODE STEP'S ROUTING, the way router_topk_scatter leaves it: M tokens, `top_k` distinct experts + * each -- half of the picks from thirty-two popular experts, the rest anywhere -- and, with `hot`, + * every token's first slot on one expert, whose run is then M rows long and crosses 16-row tiles. + * Every 37th slot goes to another rank (dropped, so the live count is short of T). Then the + * scatter's stable counting sort: runs in expert order, a run's slots in slot order. */ +static void moe_route(int64_t M, int64_t top_k, int64_t ne, uint64_t seed, bool hot, + std::vector& off, std::vector& sorted) { + const int64_t T = M * top_k; + std::vector ids((size_t)T, -1); + uint64_t s = seed; + auto rnd = [&]() { + s = s * 6364136223846793005ull + 1442695040888963407ull; + return (uint32_t)(s >> 33); + }; + for (int64_t m = 0; m < M; ++m) + for (int64_t k = 0; k < top_k; ++k) { + int32_t e = 0; + bool dup = true; + while (dup) { + const uint32_t x = rnd(); + e = (x & 1u) ? (int32_t)((((x >> 1) % 32u) * 13u) % (uint32_t)ne) + : (int32_t)((x >> 1) % (uint32_t)ne); + if (hot && k == 0) e = (int32_t)(ne / 3); + dup = false; + for (int64_t q = 0; q < k; ++q) dup = dup || ids[(size_t)(m * top_k + q)] == e; + } + ids[(size_t)(m * top_k + k)] = e; + } + for (int64_t i = 5; i < T; i += 37) ids[(size_t)i] = -1; + std::vector cnt((size_t)ne, 0); + for (const int32_t e : ids) + if (e >= 0) ++cnt[(size_t)e]; + off.assign((size_t)(ne + 1), 0); + for (int64_t e = 0; e < ne; ++e) off[(size_t)(e + 1)] = off[(size_t)e] + cnt[(size_t)e]; + sorted.assign((size_t)T, -1); + std::vector at(off.begin(), off.end() - 1); + for (int64_t i = 0; i < T; ++i) + if (ids[(size_t)i] >= 0) sorted[(size_t)(at[(size_t)ids[(size_t)i]]++)] = (int32_t)i; +} + +/* THE SORTED OPERAND -- the down projection -- AT DECODE, every form against a host decode, and + * moe_down_dec_kernel (R4D_MOE_DOWN2) against the (tile, run) form BYTE FOR BYTE. + * + * moe_q4_gemm reads the activation in token order; down reads it in sorted order, one row a routed + * slot, so that is the operand here, with a routing shaped like a decode step's (moe_route): at + * T = 40 one sequence at depth 3, at T = 640 sixteen, a run longer than a tile, runs that cross + * tile boundaries, a dropped tail. Each class has its own [N_q, K_q]; one class narrower than the + * output puts a column tile past its width, which both forms must zero. The decode kernel runs at + * several column groups, three of them uneven over the output's 64-column tiles; and the (tile, + * run) form itself against the uniform prefill grid, byte for byte, on the sorted-operand path the + * token-order cases never take. Every pinned variant is DESCRIBED first where the row can be: one + * that named the reference's kernel would match it trivially. */ +struct MoeDnShape { const char* name; int64_t N[4], K[4], ne, top_k; }; + +static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* dt, + std::initializer_list Ts) { + const bool fp8 = std::strcmp(dt, "fp8a8") == 0, w5 = std::strcmp(dt, "w5nl64a8h") == 0; + const int64_t sub = std::strcmp(dt, "w4nl32a8h") == 0 ? 4 + : (w5 || std::strcmp(dt, "w4nl64a8h") == 0) ? 2 : 0; + const bool g64 = sub > 1; + const float* tab = w5 ? kW5nlTable : kW4nlTable; + static const char* const kForm[] = { "rule", "aligned prefill form", "decode form", + "uniform prefill grid" }; + const char* row = fp8 ? "moe_gemm_fp8a8_mod4" : "moe_gemm_w4a8_mod4"; + const std::string head = std::string(row) + ", sorted operand (" + sh.name + ", " + dt + ")"; + const RadKernelInfo* r = find(pl, row); + if (!r || !r->layout || (!fp8 && !r->relayout)) { + ok(head.c_str(), false, "row or hooks absent"); + return; + } + if (!pl.pin_moe || !pl.pin_dn2) { + skip(head.c_str(), "the plugin exports no form pins"); + return; + } + + const int64_t ne = sh.ne, group = 128, top_k = sh.top_k; + int64_t N = 0, K = 0; + for (int q = 0; q < 4; ++q) { + N = std::max(N, sh.N[q]); + K = std::max(K, sh.K[q]); + } + const int64_t kb = K / group; + const std::vector lp = { + PI("N", sh.N[0]), PI("K", sh.K[0]), PI("N_1", sh.N[1]), PI("K_1", sh.K[1]), + PI("N_2", sh.N[2]), PI("K_2", sh.K[2]), PI("N_3", sh.N[3]), PI("K_3", sh.K[3]), + PI("group", group), PS("dtype", dt), + }; + + /* The experts, as moe_q4_gemm builds them: e = 4x + q, each class at its own geometry, the + * bytes the row's own hooks store for them at the class's operands. */ + std::vector wq[4], ws[4]; + std::vector cp[4]; + int64_t nec[4] = { 0, 0, 0, 0 }; + for (int q = 0; q < 4; ++q) { + const int64_t Nq = sh.N[q], Kq = sh.K[q], kbq = Kq / group; + const int ow = q ? 4 + 2 * q : 2, os = ow + 1; + const int64_t wbytes = fp8 ? Nq * Kq : w5 ? Nq * Kq / 8 * 5 : Nq * Kq / 2; + const int64_t sbytes = fp8 ? (Nq + group - 1) / group * kbq * 2 + : Nq * kbq * (g64 ? sub : 2); + nec[q] = (ne + 3 - q) / 4; + std::vector wsrc((size_t)(Nq * Kq)); + for (int64_t x = 0; x < nec[q]; ++x) { + const int64_t e = 4 * x + q; + for (int64_t n = 0; n < Nq; ++n) + for (int64_t k = 0; k < Kq; ++k) + wsrc[(size_t)(n * Kq + k)] = + (float)(((e * 7 + n * 31 + k * 17) % 61) - 30) / 37.0f; + cp[q].push_back(fp8 ? fp8_block_planes(wsrc, Nq, Kq) + : g64 ? nl64_planes(wsrc, Nq, Kq, group / sub, w5) + : int4_planes(wsrc, Nq, Kq, group, RAD_BF16, false)); + std::vector w, sc; + const int rw = g64 ? stored(r, lp, ow, cp[q].back(), { "codes", "table" }, &w) + : stored(r, lp, ow, cp[q].back(), { "codes" }, &w); + const int rs = g64 ? stored(r, lp, os, cp[q].back(), { "scale", "scale.1" }, &sc) + : stored(r, lp, os, cp[q].back(), { "scale" }, &sc); + if (rw != (fp8 ? RAD_E_UNSUPPORTED : RAD_OK) || + rs != (g64 ? RAD_OK : RAD_E_UNSUPPORTED) || + (int64_t)w.size() != wbytes || (int64_t)sc.size() != sbytes) { + ok(head.c_str(), false, "class " + std::to_string(q) + " relayout rc " + + std::to_string(rw) + "/" + std::to_string(rs) + ", " + + std::to_string(w.size()) + " and " + + std::to_string(sc.size()) + " bytes an expert"); + return; + } + wq[q].insert(wq[q].end(), w.begin(), w.end()); + ws[q].insert(ws[q].end(), sc.begin(), sc.end()); + } + } + void* d_w[4]; + void* d_ws[4]; + for (int q = 0; q < 4; ++q) { + d_w[q] = dalloc(wq[q].size()); + d_ws[q] = dalloc(ws[q].size()); + st_memcpy(d_w[q], wq[q].data(), wq[q].size(), hipMemcpyHostToDevice); + st_memcpy(d_ws[q], ws[q].data(), ws[q].size(), hipMemcpyHostToDevice); + } + auto codes_t = [&](int q) { + return T(d_w[q], fp8 ? (uint32_t)RAD_F8E4M3 : w5 ? (uint32_t)R4D_DT_MOEW5 + : (uint32_t)R4D_DT_MOEW4, + { nec[q], sh.N[q], sh.K[q] }); + }; + auto scale_t = [&](int q) { + const int64_t kbq = sh.K[q] / group; + return fp8 ? T(d_ws[q], RAD_BF16, { nec[q], (sh.N[q] + group - 1) / group, kbq }) + : g64 ? T(d_ws[q], RAD_F8E4M3, { nec[q], sh.N[q], sub * kbq }) + : T(d_ws[q], RAD_BF16, { nec[q], sh.N[q], kbq }); + }; + + for (const int64_t Tr : Ts) { + const int64_t M = Tr / top_k; + const std::string what = head + " T=" + std::to_string(Tr); + std::vector off, sorted; + moe_route(M, top_k, ne, 0x9E3779B97F4A7C15ull ^ (uint64_t)Tr, M > 16, off, sorted); + const int64_t live = off[(size_t)ne]; + int64_t nrun = 0, longest = 0; + for (int64_t e = 0; e < ne; ++e) { + const int64_t n = off[(size_t)(e + 1)] - off[(size_t)e]; + nrun += n > 0; + longest = std::max(longest, n); + } + + /* One activation row a routed slot: E4M3 bytes with no subnormal and no NaN, an f32 scale + * a (row, group). */ + std::vector aq((size_t)(Tr * K)); + std::vector as((size_t)(Tr * kb)); + for (int64_t m = 0; m < Tr; ++m) { + for (int64_t g = 0; g < kb; ++g) as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g; + for (int64_t k = 0; k < K; ++k) { + const uint32_t c = (uint32_t)((m * 13 + k * 5) % 119) + 8; + aq[(size_t)(m * K + k)] = (uint8_t)(((m + k) & 1) ? (c | 0x80u) : c); + } + } + void* d_a = dalloc(aq.size()); + void* d_as = dalloc(as.size() * 4); + void* d_s = dalloc(sorted.size() * 4); + void* d_o = dalloc(off.size() * 4); + void* d_y = dalloc((size_t)(Tr * N * 2)); + st_memcpy(d_a, aq.data(), aq.size(), hipMemcpyHostToDevice); + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sorted.data(), sorted.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_o, off.data(), off.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_F8E4M3, { Tr, K }), T(d_as, RAD_F32, { Tr, kb }), codes_t(0), scale_t(0), + T(d_s, RAD_I32, { Tr }), T(d_o, RAD_I32, { ne + 1 }), codes_t(1), scale_t(1), + codes_t(2), scale_t(2), codes_t(3), scale_t(3), T(d_y, RAD_BF16, { Tr, N }), + }; + std::vector ps = { + PI("M", M), PI("N", sh.N[0]), PI("K", sh.K[0]), PI("N_1", sh.N[1]), + PI("K_1", sh.K[1]), PI("N_2", sh.N[2]), PI("K_2", sh.K[2]), PI("N_3", sh.N[3]), + PI("K_3", sh.K[3]), PI("parts", 1), PI("n_expert", ne), PI("top_k", top_k), + PI("group", group), PS("a_order", "sorted"), PS("dtype", dt), + }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + const int64_t map_bytes = (1 + 2 * (ne + Tr / 16 + 2)) * 4; + void* d_map = dalloc((size_t)map_bytes); + + /* The reference: sorted row i reads activation row i, its expert e from the offsets. */ + std::vector ref((size_t)(Tr * N), 0.0); + for (int64_t i = 0; i < live; ++i) { + if (sorted[(size_t)i] < 0) continue; + int64_t e = 0; + while (e + 1 < ne && off[(size_t)(e + 1)] <= i) ++e; + const int q = (int)(e % 4); + const Planes& p = cp[q][(size_t)(e / 4)]; + const int64_t fc = sh.N[q], Kq = sh.K[q], kbq = Kq / group; + for (int64_t n = 0; n < fc; ++n) { + double want = 0.0; + for (int64_t g = 0; g < kbq; ++g) { + const double a_s = (double)as[(size_t)(i * kb + g)]; + if (fp8) { + double part = 0.0; + for (int64_t k = g * group; k < (g + 1) * group; ++k) + part += (double)h_e4m3(p.data[0][(size_t)(n * Kq + k)]) * + (double)st_e4m3(aq[(size_t)(i * K + k)]); + want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, + (n / group) * kbq + g) * a_s; + } else if (g64) { + const int64_t gw = group / sub; + for (int64_t h = 0; h < sub; ++h) { + double part = 0.0; + for (int64_t k = g * group + h * gw; k < g * group + (h + 1) * gw; ++k) + part += (double)tab[code_at(p, n, k)] * + (double)st_e4m3(aq[(size_t)(i * K + k)]); + const uint8_t sb = p.data[1][(size_t)(n * p.row_bytes(1) + sub * g + h)]; + want += part * (double)h_e4m3(sb) * (double)kW4G64Scale * a_s; + } + } else { + double part = 0.0; + for (int64_t k = g * group; k < (g + 1) * group; ++k) + part += (double)code_at(p, n, k) * + (double)st_e4m3(aq[(size_t)(i * K + k)]); + want += part * (double)rad_load_f32(p.data[1].data(), RAD_BF16, + n * kbq + g) * a_s; + } + } + ref[(size_t)(i * N + n)] = want; + } + } + + /* One pinned launch into stale bytes, its output back. `pins` is (form, down2). */ + auto run = [&](const int (&pins)[2], std::vector* got) { + { + std::vector junk((size_t)(Tr * N), 0x7f7fu); + st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice); + } + a.scratch = pins[0] == 3 ? nullptr : d_map; + a.scratch_bytes = pins[0] == 3 ? 0 : map_bytes; + pl.pin_moe(pins[0]); + pl.pin_dn2(pins[1]); + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + pl.pin_moe(0); + pl.pin_dn2(0); + got->assign((size_t)(Tr * N), 0); + st_memcpy(got->data(), d_y, got->size() * 2, hipMemcpyDeviceToHost); + return rc; + }; + auto described = [&](const int (&pins)[2]) -> const void* { + if (!r->describe) return nullptr; + static RadLaunchDesc d[4]; + int n = 0; + a.scratch = pins[0] == 3 ? nullptr : d_map; + a.scratch_bytes = pins[0] == 3 ? 0 : map_bytes; + pl.pin_moe(pins[0]); + pl.pin_dn2(pins[1]); + const int drc = r->describe(&a, nullptr, d, 4, &n); + pl.pin_moe(0); + pl.pin_dn2(0); + return drc == RAD_OK && n >= 1 ? d[n - 1].func : nullptr; + }; + + /* Every form with the decode kernel off, against the host. */ + std::vector base, grid; + for (int form = 1; form <= 3; ++form) { + const std::string label = what + " " + kForm[form]; + const int pins[2] = { form, -1 }; + std::vector got; + const int rc = run(pins, &got); + if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } + double worst = 0.0; + int64_t bad = 0; + std::string first; + for (int64_t i = 0; i < Tr; ++i) + for (int64_t n = 0; n < N; ++n) { + const double want = ref[(size_t)(i * N + n)]; + const double err = std::fabs((double)h_bf16(got[(size_t)(i * N + n)]) - want); + if (!(err <= 0.004 * std::fabs(want) + 1e-4)) { + if (!bad++) + first = ", first at row " + std::to_string(i) + " col " + + std::to_string(n) + ": " + + std::to_string(h_bf16(got[(size_t)(i * N + n)])) + " for " + + std::to_string(want); + if (!(err <= worst)) worst = err; + } + } + ok(label.c_str(), bad == 0, std::to_string(bad) + " of " + std::to_string(Tr * N) + + " elements off, worst " + std::to_string(worst) + first); + if (form == 2) base = got; + if (form == 3) grid = got; + } + if (base.empty()) continue; + + /* The (tile, run) form on the sorted operand against the uniform prefill grid, byte for + * byte: every form keeps each output element's accumulation order, and the grid finds the + * runs a third way. */ + if (!grid.empty()) { + int64_t diff = 0; + for (size_t i = 0; i < grid.size(); ++i) diff += grid[i] != base[i]; + ok((what + " decode form, byte for byte with the uniform prefill grid").c_str(), + diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + + " elements differ"); + } + + /* The sorted operand's own decode kernel at several column groups, each against the + * (tile, run) form's bytes. */ + struct Var { int dn2; const char* name; }; + static const Var kVar[] = { + { 1, "down kernel, one column tile a block" }, + { 2, "down kernel, two column tiles a block" }, + { 3, "down kernel, three column tiles a block" }, + { 4, "down kernel, four column tiles a block" }, + { 8, "down kernel, eight column tiles a block" }, + }; + const int ref_pins[2] = { 2, -1 }; + const void* fn0 = described(ref_pins); + for (const Var& v : kVar) { + const std::string label = what + " decode form, " + v.name + " (" + + std::to_string(nrun) + " runs, longest " + + std::to_string(longest) + ")" + + (r->describe ? "" : " (launch not described)"); + const int pins[2] = { 2, v.dn2 }; + if (r->describe) { + const void* fn = described(pins); + if (!fn || fn == fn0) { + ok(label.c_str(), false, fn ? "named the (tile, run) form's kernel" + : "describe failed"); + continue; + } + } + std::vector got; + const int rc = run(pins, &got); + if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; } + int64_t diff = 0; + for (size_t i = 0; i < got.size(); ++i) diff += got[i] != base[i]; + ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) + + " elements differ from the (tile, run) form"); + } + } +} + +/* QFN's down projection at rank 0 of four, narrowed: 512 experts at top 10, K 256 for class 0 and + * 128 for the others -- and 384 for class 3, so a run takes three K blocks -- and N five 64-column + * tiles, class 2 one short of it. The other formats at 64 experts, top 4. */ +static const MoeDnShape kMoeDnShapes[] = { + { "512 experts, top 10", { 320, 320, 256, 320 }, { 256, 128, 128, 384 }, 512, 10 }, + { "64 experts, top 4", { 320, 320, 256, 320 }, { 256, 128, 128, 384 }, 64, 4 }, +}; + /* THE ARRANGED PLANE, AGAINST THE FORMAT IT STATES, AND BACK. * * `moe_gemm_w4a8` is the one large weight of a routed model, and what a checker reads it through is @@ -11483,6 +11846,11 @@ static void device_phase(const Plugin& pl) { for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) for (const char* dt : { "w4a8", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) moe_q4_gemm(pl, t, sh, dt); + /* The sorted operand at decode, and its own kernel (R4D_MOE_DOWN2) against the (tile, run) + * form: one sequence at depth 3 (T 40), five, sixteen and nineteen. */ + moe_down2_case(pl, kMoeDnShapes[0], "w4nl64a8h", { 40, 200, 640, 760 }); + for (const char* dt : { "w4a8", "w4nl64a8h", "w4nl32a8h", "w5nl64a8h" }) + moe_down2_case(pl, kMoeDnShapes[1], dt, { 40, 96 }); } if (sel("moe_gemm_fp8a8_mod4")) { @@ -11491,6 +11859,7 @@ static void device_phase(const Plugin& pl) { for (const MoeQ4Shape& sh : kMoeQ4Shapes) for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) moe_q4_gemm(pl, t, sh, "fp8a8"); + moe_down2_case(pl, kMoeDnShapes[1], "fp8a8", { 40, 96 }); } if (sel("hc_read_e4m3")) {