radiance 1.2.2

- Static YaRN for the Qwen rotary paths (#37): a container whose config names YaRN gets it in
  attention, the QSA index keys and a DFlash2 drafter; one reader for every rotary type, and a
  LLaMA container whose type is not served (llama3, longrope, dynamic) is refused by name.
- --rope-scaling yarn:FACTOR[:ORIG] (#38) writes YaRN over a container's own rotary keys at load,
  no reconvert; the persisted prefix cache's fingerprint carries the resolved rotary.
- An uneven world's cheaper rank (#36) pages the common token count and gives the rest of its
  VRAM to its experts; a plan and pool that disagree refuse to start.
- MoE prefill (#35): wide gather, parallel scan and run-map prefix, 256-column down tile, early
  weight loads -- by rule, bit-identical.
- MoE decode (#34): the sorted operand's own down kernel, its column tiles by routed rows.
- --draft-window fixed|adaptive (#24): a per-sequence draft window priced by measured step time,
  one head depth per step over the batch; fixed stays the default. New metric
  radiance:draft_position_accepted_total and Grafana panels.
- Out-of-tree plugin builds compile to the tree's device code from any build directory.
This commit is contained in:
Deadcode committed 2026-10-07 12:37:53 +02:00
1 parent 6fa7707dff
commit ac79f4dc8a
63 files changed
+2744 -8759

No files matched your search

+16 -13
View File
@@ -652,19 +652,22 @@ void r4d_moe_gemm_pin_prefill(int form);
// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical,
// and r4d_selftest compares their bytes.
void r4d_moe_gemm_pin_fk(int pin);
// THE PREFILL MoE FORMS (R4D_MOE_PF2), pinned for a test: below zero the switch's rule, otherwise
// the value the switch would hold -- 0 none, 1 every part, else a mask of the parts (r4d_moe.hip
// lists them). Every part is bit-identical to the form it replaces, and r4d_selftest compares their
// bytes: moe_gather and moe_scatter at a prefill chunk, and the GEMM's run-aligned form.
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 RUN-ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule (the down
// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every class's
// width allow it), 1 never that tile, 2 that tile -- refused where the shape cannot take it or the
// launch is not the aligned form. Bit-identical, and r4d_selftest compares their bytes.
void r4d_moe_gemm_pin_down_tile(int pin);
// THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 a column a thread
// (gather_kernel), 2 a wave a token and sixteen bytes a lane (gather_wide_kernel), refused on a
// shape it cannot take. Bit-identical, and r4d_selftest compares their bytes.
void r4d_moe_gather_pin_form(int form);
// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the launcher's rule
// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, at a column-tile count
// set by the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel
// at n column tiles a block, capped at 16 and refused on a shape the kernel does not serve. 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_down_dec(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
+22 -20
View File
@@ -774,11 +774,12 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
row_pitch, 0, nullptr, 0, 0, stream);
}
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
// below and the op without YaRN run the same arithmetic with the same arguments.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -790,10 +791,19 @@ extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_r
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, RadYarn{});
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
mode, sec, n_sec, plane, RadYarn{}, stream);
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
int kv_heads, int block_size, int n_blocks,
int k_ld, int v_ld, long stream) {
@@ -1389,22 +1399,14 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
const float rscale = (float)r4d_getf(a, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL);
if (yarn.factor != 0.0f) {
if (mc == 4 || rscale != 1.0f) return R4D_NO(RAD_E_UNSUPPORTED);
const uint32_t heads = (uint32_t)(n_head + n_head_kv);
const uint32_t gy = (heads * (uint32_t)(rot / 2) + kThreads - 1) / kThreads;
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)Mp, gy), dim3(kThreads), 0, (hipStream_t)s,
(uint16_t*)r4d_addr(qkv), (const int32_t*)r4d_addr(pos),
(uint32_t)head_dim, heads, (uint32_t)rot, gptj, theta, rscale,
(uint32_t)pitch, mc, sec[0], sec[1], sec[2], n_sec, (uint32_t)plane, yarn);
return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE;
}
/* YaRN over the axial vision rotary, or over a linear position divide, is no model's. */
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
* reason this op takes the fused projection rather than two tensors. */
return r4d_rope_mc_bf16(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ kv_store */
+233 -344
View File
@@ -561,79 +561,19 @@ __global__ __launch_bounds__(kScatterTile) void scatter_hist_kernel(
bcnt[(size_t)b * n_expert + e] = s_h[e];
}
/* One workgroup: totals per expert, the exclusive scan across experts, and the exclusive scan
* across tiles within each expert -- the last one in place, so `bcnt[b][e]` becomes "how many of
* expert e are in tiles before b". One thread an expert, which at n_expert 256 is one wave-group
* and no cross-thread communication at all. */
__global__ __launch_bounds__(256) void scatter_scan_kernel(
int32_t* __restrict__ bcnt, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t n_tile, uint32_t n_expert) {
__shared__ int32_t s_cnt[kMaxExpert + 1];
const uint32_t tid = threadIdx.x;
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
int32_t run = 0;
for (uint32_t b = 0; b < n_tile; ++b) {
const int32_t v = bcnt[(size_t)b * n_expert + e];
bcnt[(size_t)b * n_expert + e] = run;
run += v;
}
s_cnt[e] = run;
cnt[e] = run;
}
__syncthreads();
if (tid == 0) {
int32_t run = 0;
for (uint32_t e = 0; e < n_expert; ++e) { off[e] = run; run += s_cnt[e]; }
off[n_expert] = run;
}
}
__global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt,
const int32_t* __restrict__ off, int32_t* __restrict__ sorted,
uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
__shared__ int32_t s_id[kScatterTile];
const uint32_t tid = threadIdx.x, b = blockIdx.x;
const uint32_t i = b * kScatterTile + tid;
/* THE PLACE IN THE SORT throughout -- the local expert index, with any protected experts moved
* last: s_id, the range test and the rank scan all work in the indices the offsets and the
* weight tables are built from. */
const int32_t l = (i < T) ? ids[i] - base : -1;
const int32_t e = (l >= 0 && l < (int32_t)n_expert) ? sort_place(l, n_expert, prot) : -1;
s_id[tid] = e;
__syncthreads();
if (i >= T || e < 0) return;
/* Rank within the tile: how many earlier slots of this tile chose the same expert. A serial
* scan of at most 256 LDS words a thread, which is the price of stability. */
int32_t rank = 0;
for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e);
sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i;
}
__global__ void scatter_tail_kernel(const int32_t* __restrict__ off, int32_t* __restrict__ sorted,
uint32_t T, uint32_t n_expert) {
const uint32_t i = blockIdx.x * blockDim.x + threadIdx.x;
const uint32_t live = (uint32_t)off[n_expert];
if (i >= live && i < T) sorted[i] = -1;
}
/* ---- PF2: THE GENERAL SCATTER'S SCAN AND TAIL, AT A PREFILL CHUNK ----------------------------------
/* ONE WORKGROUP, ONE THREAD AN EXPERT: the exclusive scan across tiles within each expert, in
* place -- so `bcnt[b][e]` becomes "how many of expert e are in tiles before b" -- each expert's
* total, and the exclusive scan of the totals across experts.
*
* scatter_scan_kernel gives each thread an expert -- two at 512 -- and walks that expert's column of
* `bcnt` one tile at a time: load, add, store, and the next load only after. At a 2048 chunk and top
* 10 that is 80 tiles, two experts a thread, 160 dependent round trips on one workgroup, and then
* one thread prefixes the 512 totals alone. Here a thread holds one expert, its column comes in
* kScanBatch loads at a time, all issued before any is used, and the prefix across experts is the
* small sort's: a DPP scan in each wave and one exchange of the wave totals. Integers, and every sum
* has one answer whatever order it is formed in: the same bcnt, offsets and counts.
*
* THE TAIL RIDES IN THE PLACEMENT. scatter_tail_kernel is a launch of its own that writes -1 to the
* sorted rows past the live count; those rows are never a placement target (every placed slot lands
* below `off[n_expert]`), so the placement's own threads can write them, each its own index, with no
* thread able to race another for a row. One dependent launch a layer fewer; the same bytes. */
* A thread's column of `bcnt` comes in kScanBatch loads at a time, all issued before any is used:
* at a 2048-token chunk and top 10 that is 80 tiles, and walked a load at a time -- load, add,
* store, then the next load -- it is 80 dependent round trips on the one workgroup a layer's sort
* waits for. The prefix across experts is the small sort's: a DPP scan in each wave and one
* exchange of the wave totals. Integers, and every sum has one answer whatever order it is formed
* in. */
constexpr uint32_t kScanBatch = 16;
__global__ __launch_bounds__(kMaxExpert) void scatter_scan_par_kernel(
__global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel(
int32_t* __restrict__ bcnt, int32_t* __restrict__ off, int32_t* __restrict__ cnt,
uint32_t n_tile, uint32_t n_expert) {
constexpr uint32_t NW = kMaxExpert / kWave;
@@ -673,15 +613,21 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_par_kernel(
if (e == 0) off[n_expert] = tot;
}
/* scatter_place_kernel, and the tail scatter_tail_kernel writes. The placement is that kernel's,
* line for line. */
__global__ __launch_bounds__(kScatterTile) void scatter_place_tail_kernel(
/* THE PLACEMENT, AND THE TAIL. Every routed slot of the tile goes to its expert's offset, plus the
* expert's count in the tiles before this one, plus its rank in this tile. The sorted rows past the
* live count are -1; they are never a placement target (every placed slot lands below
* `off[n_expert]`), so the placement's own threads write them, each its own index, and no thread
* can race another for a row. */
__global__ __launch_bounds__(kScatterTile) void scatter_place_kernel(
const int32_t* __restrict__ ids, const int32_t* __restrict__ bcnt,
const int32_t* __restrict__ off, int32_t* __restrict__ sorted,
uint32_t T, uint32_t n_expert, int32_t base, Protect prot) {
__shared__ int32_t s_id[kScatterTile];
const uint32_t tid = threadIdx.x, b = blockIdx.x;
const uint32_t i = b * kScatterTile + tid;
/* THE PLACE IN THE SORT throughout -- the local expert index, with any protected experts moved
* last: s_id, the range test and the rank scan all work in the indices the offsets and the
* weight tables are built from. */
const int32_t l = (i < T) ? ids[i] - base : -1;
const int32_t e = (l >= 0 && l < (int32_t)n_expert) ? sort_place(l, n_expert, prot) : -1;
s_id[tid] = e;
@@ -689,12 +635,13 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_tail_kernel(
if (i >= live && i < T) sorted[i] = -1;
__syncthreads();
if (i >= T || e < 0) return;
/* Rank within the tile: how many earlier slots of this tile chose the same expert. A serial
* scan of at most 256 LDS words a thread, which is the price of stability. */
int32_t rank = 0;
for (uint32_t j = 0; j < tid; ++j) rank += (s_id[j] == e);
sorted[off[e] + bcnt[(size_t)b * n_expert + e] + rank] = (int32_t)i;
}
/* ================================================================== the 4-bit expert weight
*
* SIXTEEN PACKED BYTES TO THE THIRTY-TWO E4M3 BYTES OF A Stage8, and nothing downstream of it
@@ -1007,20 +954,17 @@ static_assert(sizeof(MoeTab) == 16, "the code table is four words");
* its own activation scale. Same products, same sums, same order: bit-identical to FK 128.
*
* UW reads the weight and its scales from a uniform global base -- see the UW note at w4_load.
* The decode form always takes it. The prefill forms keep the plain loads: the waits UW removes
* were measured on the decode grid, and the prefill tiles' timing under UW is unmeasured, so
* their instructions stay as they were -- except under EW (R4D_MOE_PF2 64), below, which needs
* the uniform base for its early loads and was measured with it.
* The decode form and the run-aligned prefill form always take it; the aligned form needs it for
* the first pass of weight it issues at the map read (see THE ALIGNED FORM'S FIRST PASS, below
* the map read), and was measured with it. The uniform prefill grid keeps the plain loads: its
* timing under UW was never measured, so its instructions stay as they were.
*
* RS finds an ES block's run in one round trip -- see the RS note at the run search. It covers
* up to kMaxExpert experts; a wider expert count takes the chunked search, which numbers the runs
* the same way.
*
* EW issues an AL block's first pass of weight as soon as its map entry has named the expert -- see
* the EW note below the map read. */
* the same way. */
template <uint32_t MT, uint32_t NTL, uint32_t WGM, uint32_t WGN, int W4 = 0,
bool ES = false, bool AL = false, bool SK = false, uint32_t FK = kFK, bool UW = false,
bool RS = false, bool EW = false>
bool RS = false>
__global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_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,
@@ -1036,7 +980,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
constexpr uint32_t WM = MT / WGM, WN = NTL / WGN;
static_assert(MT % WGM == 0 && NTL % WGN == 0, "the wave grid must divide the tile");
/* The block-fp8 weight has one scale a 128x128 tile; a w4 weight one a ROW, so its block may
* span two of the fp8 grid's scale rows (the 256-column down tile, R4D_MOE_PF2). */
* span two of the fp8 grid's scale rows (the aligned form's 256-column down tile). */
static_assert(W4 != 0 || kBlock % FN == 0,
"a block's N rows must sit in one 128-row weight scale row");
/* Scale groups a 128-wide block: one, or at W4 2, 3 and 4 the 64- or 32-column ones. */
@@ -1067,31 +1011,44 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
/* UNDER AL THE BLOCK IS NAMED BY THE MAP, not by arithmetic on blockIdx: entry i is
* (expert, first row) and the block serves that run and no other. The grid is the upper bound
* `n_expert + T/FM`, so the blocks past the real count exit here. */
const uint32_t n0 = blockIdx.y * FN;
uint32_t r0, rN, e_al = 0;
[[maybe_unused]] uint32_t al_end = 0; /* EW: off[e_al + 1], the run's end */
bool tail = false;
[[maybe_unused]] uint32_t al_end = 0; /* AL: the run's end, off[e_al + 1] */
if constexpr (AL) {
if (blockIdx.x >= map[0]) return;
const uint32_t* ent = map + 1 + 2 * blockIdx.x;
e_al = ent[0];
r0 = ent[1];
tail = (e_al == kMapTail);
const uint32_t lim = tail ? T : (uint32_t)off[e_al + 1];
al_end = lim;
rN = (r0 + FM < lim) ? (r0 + FM) : lim;
/* A TAIL BLOCK OWNS NO RUN: it exists to zero the rows past the live count, which no
* expert owns, and it does that here and leaves -- before the first pass's weight below is
* issued for an expert it does not have. Block-uniform (the map entry is the block's), so
* the early loads below are on one path with no join behind them. */
if (e_al == kMapTail) {
const uint32_t live = (uint32_t)off[n_expert];
const uint32_t rT = (r0 + FM < T) ? (r0 + FM) : T;
for (uint32_t r = (r0 > live ? r0 : live); r < rT; ++r)
for (uint32_t c = tid; c < FN && n0 + c < N; c += NTHR)
Y[(size_t)r * y_ld + n0 + c] = 0;
return;
}
/* The run's end, clamped to the output's rows: an operand may name fewer rows than its
* buffer, never more. */
const uint32_t oe = (uint32_t)off[e_al + 1];
al_end = oe < T ? oe : T;
rN = (r0 + FM < al_end) ? (r0 + FM) : al_end;
} else {
r0 = (ES ? (blockIdx.x / FM) : blockIdx.x) * FM;
if (r0 >= T) return;
rN = (r0 + FM < T) ? (r0 + FM) : T;
}
const uint32_t n0 = blockIdx.y * FN;
/* EW: THE FIRST PASS'S WEIGHT, IN FLIGHT AS SOON AS THE MAP HAS NAMED THE EXPERT. Under AL the
* map entry names the expert, and nothing the weight's address needs comes later -- not the
* tokens, not the run's rows, not the live count. In the run loop, the weight's load waits
* behind the token loads, the barrier that publishes them, the live count, the run's end read
* again and the table entry: four round trips in front of the one that carries the bytes, on a
* block whose whole K is one or two passes at the down projection.
/* THE ALIGNED FORM'S FIRST PASS OF WEIGHT, IN FLIGHT AS SOON AS THE MAP HAS NAMED THE EXPERT
* (the `ew_` registers: the early weight). Under AL the map entry names the expert, and
* nothing the weight's address needs comes later -- not the tokens, not the run's rows, not
* the live count. Loaded in the run loop, the weight would wait behind the token loads, the
* barrier that publishes them, the live count, the run's end read again and the table entry:
* four round trips in front of the one that carries the bytes, on a block whose whole K is one
* or two passes at the down projection.
*
* So the block's loads go out in the order their waits want them. First everything the token
* barrier needs -- the block's sorted rows and the live count -- then the table entries
@@ -1105,23 +1062,23 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
*
* EVERY EARLY LOAD IS UNCONDITIONAL. A load under an exec mask -- `if (live) load` -- may not be
* issued at all, and the waitcnt pass, not knowing how many went out, then waits for every one
* of them where it needs the first. So a dead row (past the class's width, or the whole of a
* tail block) reads the expert's row 0 instead, a dead token slot reads a real one, and the
* zero is selected where the value is used -- the first issue() for the weight, the token's
* store for the slot. */
* of them where it needs the first. So a dead row (past the class's width) reads the expert's
* row 0 instead, a dead token slot reads a real one, and the zero is selected where the value
* is used -- the first issue() for the weight, the token's store for the slot. A tail block
* has already left: it has no expert to load for. */
constexpr uint32_t kEwTPR = FK / 32, kEwRPP = NTHR / kEwTPR;
constexpr uint32_t kEwBP = (FN + kEwRPP - 1) / kEwRPP;
[[maybe_unused]] uint4 ew_b4[EW && W4 ? kEwBP : 1];
[[maybe_unused]] uint32_t ew_sp[EW && W4 == 4 ? kEwBP : 1];
[[maybe_unused]] Stage8 ew_b8[EW && !W4 ? kEwBP : 1];
[[maybe_unused]] bool ew_ok[EW ? kEwBP : 1];
[[maybe_unused]] uint4 ew_b4[AL && W4 ? kEwBP : 1];
[[maybe_unused]] uint32_t ew_sp[AL && W4 == 4 ? kEwBP : 1];
[[maybe_unused]] Stage8 ew_b8[AL && !W4 ? kEwBP : 1];
[[maybe_unused]] bool ew_ok[AL ? kEwBP : 1];
[[maybe_unused]] const uint8_t* ew_wp = nullptr;
[[maybe_unused]] const uint16_t* ew_wsp = nullptr;
[[maybe_unused]] int32_t ew_f = -1;
[[maybe_unused]] uint32_t ew_live = 0;
if constexpr (EW) {
static_assert(AL && !ES && !RS && UW && FM <= NTHR,
"EW is the run-aligned form's, on UW's uniform weight base");
if constexpr (AL) {
static_assert(!ES && !RS && UW && FM <= NTHR,
"the aligned form issues its first pass early, on UW's uniform weight base");
{
const uint32_t i = r0 + tid % FM; /* a real row whatever the thread */
ew_f = sorted[i < T ? i : T - 1u];
@@ -1129,13 +1086,12 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
ew_live = (uint32_t)off[n_expert];
/* Nothing below is scheduled in front of these two: the counter retires in order. */
__builtin_amdgcn_sched_barrier(0);
const uint32_t ee = tail ? 0u : e_al; /* a tail block reads a real entry, unused */
const uint32_t cls = ee & ((1u << cshift) - 1u);
const uint32_t cls = e_al & ((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, part = n0 / fy, j0 = n0 - part * fy;
const uint32_t fc = C.n / parts, wn0 = part * fc + j0;
ew_wp = uw_ptr<true>(wtab_at(C.w, C.w_s0, ee >> cshift));
ew_wsp = uw_ptr<true>((const uint16_t*)wtab_at(C.s, C.s_s0, ee >> cshift));
ew_wp = uw_ptr<true>(wtab_at(C.w, C.w_s0, e_al >> cshift));
ew_wsp = uw_ptr<true>((const uint16_t*)wtab_at(C.s, C.s_s0, e_al >> cshift));
const uint32_t sn = tid / kEwTPR, sk = (tid % kEwTPR) * 32u;
/* Where a staging pass covers the tile's rows exactly, every thread's every row exists:
* no guard, so no exec mask around a load (a thread's `sn` is below kEwRPP). */
@@ -1143,7 +1099,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
for (uint32_t p = 0; p < kEwBP; ++p) {
const uint32_t r = sn + p * kEwRPP;
if constexpr (FN % kEwRPP != 0) { if (r >= FN) continue; }
ew_ok[p] = !tail && (j0 + r) < fc;
ew_ok[p] = (j0 + r) < fc;
const uint8_t* wr = ew_wp + (size_t)(ew_ok[p] ? wn0 + r : 0u) * C.w_ld;
if constexpr (W4) {
ew_b4[p] = w4_load_w<true>(wr + (sk >> 1), true);
@@ -1191,9 +1147,10 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
if (lane == kWave - 1) s_rc[wave] = rs_inc;
/* Both of RS's barriers order LDS alone -- the tokens, the counts, the selection. */
lds_barrier();
} else if constexpr (EW) {
/* The tokens and the live count were loaded with the weight, ahead of it; see EW. A row
* past the block's is a dropped slot, as the loop of the plain form writes it. */
} else if constexpr (AL) {
/* The tokens and the live count were loaded with the weight, ahead of it; see THE ALIGNED
* FORM'S FIRST PASS. A row past the block's is a dropped slot, as the loop of the plain
* form writes it. */
if (tid < FM) {
const int32_t f = r0 + tid < rN ? ew_f : -1;
s_tok[tid] = f < 0 ? -1 : (a_sorted ? (int32_t)(r0 + tid) : f / (int32_t)top_k);
@@ -1218,15 +1175,14 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
}
/* Rows past the live count are dropped slots: zeroed here, and then the run loop below has
* nothing left to do for them. No run owns them, so under ES exactly one of the tile's blocks
* must -- every block writing the same zeros would be a benign race and is still a race. */
if (!ES || jrun == 0)
for (uint32_t r = (r0 > live ? r0 : live); r < rN; ++r)
for (uint32_t c = tid; c < FN && n0 + c < N; c += NTHR)
Y[(size_t)r * y_ld + n0 + c] = 0;
/* A TAIL BLOCK HAS NOW DONE ALL ITS WORK: it exists to zero rows no expert owns and holds no
* run for the loop below. Block-uniform, so no barrier is skipped by some threads only. */
if constexpr (AL) { if (tail) return; }
* must -- every block writing the same zeros would be a benign race and is still a race. Under
* AL the tail blocks zeroed them at the map read, and every other block's rows are its run's. */
if constexpr (!AL) {
if (!ES || jrun == 0)
for (uint32_t r = (r0 > live ? r0 : live); r < rN; ++r)
for (uint32_t c = tid; c < FN && n0 + c < N; c += NTHR)
Y[(size_t)r * y_ld + n0 + c] = 0;
}
/* THE EXPERT OF THE BLOCK'S FIRST RUN. The row-tile grid finds the expert of its first row by
* binary search over the offsets and walks the runs from there, which the loop below does.
@@ -1247,7 +1203,7 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
uint32_t e = 0;
[[maybe_unused]] uint32_t rs_first = 0, rs_end = 0;
if constexpr (AL) {
e = tail ? 0u : e_al; /* the map already named it; a tail block owns no expert */
e = e_al; /* the map already named it */
} else if constexpr (RS) {
/* RS: THE SAME SEARCH, IN ONE ROUND TRIP AND TWO BARRIERS. The pass above walks the
* experts a chunk of NTHR at a time, each chunk a broadcast load to skip it or two
@@ -1358,13 +1314,13 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
* never be walked past the last expert -- `off[e + 1]` is read only for e < n_expert, and
* off[n_expert] is the live row count, which is the bound the loop already respects.
* Under RS the search handed over the run's end, and its start meets it: nothing to walk. */
if constexpr (!RS && !EW) {
if constexpr (!RS && !AL) {
while (e < n_expert && (uint32_t)off[e + 1] <= rs) ++e;
if (e >= n_expert) break;
}
/* EW: the map's run is e_al's from r0 on, so there is nothing to walk, and its end is the
/* AL: the map's run is e_al's from r0 on, so there is nothing to walk, and its end is the
* one the map read loaded. */
const uint32_t ehi = RS ? rs_end : EW ? al_end : (uint32_t)off[e + 1];
const uint32_t ehi = RS ? rs_end : AL ? al_end : (uint32_t)off[e + 1];
const uint32_t re = rN < live ? (rN < ehi ? rN : ehi) : (live < ehi ? live : ehi);
if (re <= rs) break;
/* Not this block's run: walk past it. Block-uniform, so no barrier is skipped by some
@@ -1397,8 +1353,8 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
* readfirstlanes wait on one round trip and not on two. */
const uint8_t* Wp0;
const uint16_t* Wsp0;
if constexpr (EW) {
Wp0 = ew_wp; /* EW: loaded at the map read; AL's run is e_al's */
if constexpr (AL) {
Wp0 = ew_wp; /* loaded at the map read; AL's run is e_al's */
Wsp0 = ew_wsp;
} else {
Wp0 = wtab_at(C.w, C.w_s0, e >> cshift);
@@ -1536,8 +1492,9 @@ __global__ __launch_bounds__(WGM * WGN * kWave) void moe_gemm_q_kernel(
const bool ok = tok >= 0 && (r0 + r) >= rs && (r0 + r) < re;
apre[p] = stage8_load(Aq + (size_t)(ok ? tok : 0) * a_ld + cc + sk, ok);
}
if constexpr (EW) {
static_assert(kEwBP == kBP && kEwRPP == kRPP, "EW stages the pass issue() would");
if constexpr (AL) {
static_assert(kEwBP == kBP && kEwRPP == kRPP,
"the early weight stages the pass issue() would");
if (cc == 0) { /* the first pass's weight is already in flight */
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
@@ -1830,10 +1787,11 @@ static_assert(MoeQArgs::count <= RAD_MAX_KPARAMS,
* 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.
* G is the launcher's (kMoeDownDecG2Rows, kMoeDownDecG4Rows): 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. At most kMoeDownDecMaxG, so the block's column tiles are bits of one word. 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
@@ -1886,12 +1844,18 @@ __global__ __launch_bounds__(4 * kWave) void moe_down_dec_kernel(
/* 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. */
* Both barriers order LDS.
*
* EVERY OFFSET IS CLAMPED TO T, so every run ends at the output's last row at the latest, as
* the (tile, run) form's runs do: an operand may name fewer rows than its buffer, never more.
* A run that would start past T is then empty and has no tile, so the tile count also stays
* inside the grid's bound. */
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;
const uint32_t o = x <= n_expert ? (uint32_t)off[x] : 0u;
ov[k] = o < T ? o : T;
}
uint32_t nt[NPT], cnt = 0;
#pragma unroll
@@ -2529,7 +2493,7 @@ __global__ __launch_bounds__(NTHR) void gather_kernel(
}
}
/* ---- PF2: THE PREFILL GATHER, A WAVE A TOKEN AND EIGHT COLUMNS A LANE ----------------------------
/* ---- THE PREFILL GATHER, A WAVE A TOKEN AND EIGHT COLUMNS A LANE ---------------------------------
*
* At a prefill chunk this op is a read of `ye` -- one row a routed slot, 105 MB a layer at a 2048
* chunk of Qwen3.8-Flash-Next on a rank of four -- and gather_kernel moves it TWO BYTES A LANE: a
@@ -2541,12 +2505,7 @@ __global__ __launch_bounds__(NTHR) void gather_kernel(
* (uniform: scalar loads), then every slot's sixteen bytes are issued before any is used, then
* summed. THE ARITHMETIC IS gather_kernel's: per column, ascending slot order, a dropped slot skipped,
* `acc += w * x` in f32, and the shared arm's two narrows exactly as there -- the same bits.
*
* REV takes the column groups last first. The down projection writes `ye` one 128-column tile at a
* time, every routed row of a tile before the next (the tile is its grid's slow axis), so when it
* ends, the tiles it wrote last are the ones still in the infinity cache. Taken last first, this
* kernel's first column groups are read from there rather than from DRAM. Which block reads which
* group moves; no sum does. */
*/
constexpr uint32_t kGatherWideSlots = 16; /* top_k at most this: the slots live in registers */
constexpr uint32_t kGatherWideCols = 8; /* columns a lane, one sixteen-byte load */
static_assert(kGatherWideSlots <= kWave, "slot j is read off lane j");
@@ -2557,12 +2516,11 @@ __global__ __launch_bounds__(NW * kWave) void gather_wide_kernel(
const int32_t* __restrict__ inv, uint16_t* __restrict__ y,
uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld,
const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg,
uint32_t sh_ld, uint32_t sg_ld, int sig, int rev) {
uint32_t sh_ld, uint32_t sg_ld, int sig) {
const uint32_t lane = threadIdx.x % kWave;
const uint32_t wave = (uint32_t)__builtin_amdgcn_readfirstlane((int)(threadIdx.x / kWave));
const uint32_t t = blockIdx.x * NW + wave;
const uint32_t g = rev ? gridDim.y - 1u - blockIdx.y : blockIdx.y;
const uint32_t c = (g * kWave + lane) * kGatherWideCols;
const uint32_t c = (blockIdx.y * kWave + lane) * kGatherWideCols;
/* No barrier anywhere below, so a wave past the last token simply leaves. */
if (t >= M) return;
@@ -2664,48 +2622,12 @@ __global__ __launch_bounds__(NTHR) void scale_rows_kernel(
} /* namespace */
/* R4D_MOE_PF2: the prefill MoE forms -- the shapes a chunk of thousands of routed rows a layer
* takes and a decode step never reaches. Unset or 0: as upstream. 1: every part. Any other value is
* a mask of the parts, each bit-identical to the form it replaces:
*
* 2 moe_gather at a prefill chunk: a wave a token and eight columns a lane (gather_wide_kernel)
* 4 ...its column groups last first, so the down projection's last tiles come from the cache
* 8 moe_scatter's general form: its scan in parallel and its tail in the placement
* 16 the run map's prefix in parallel (moe_blockmap_par_kernel)
* 32 the down projection's prefill tile 256 columns wide over sixteen waves
* 64 the run-aligned form's first pass of weight issued at the map read (EW, both projections)
*
* Read once, so a recorded pass and a live one take the same kernels. A test pin over it: below
* zero the switch, anything else the value the switch would hold. */
static constexpr uint32_t kPf2Gather = 2, kPf2GatherRev = 4, kPf2Scan = 8, kPf2Map = 16,
kPf2DnWide = 32, kPf2Ew = 64;
static constexpr uint32_t kPf2All = kPf2Gather | kPf2GatherRev | kPf2Scan | kPf2Map | kPf2DnWide |
kPf2Ew;
static uint32_t moe_pf2_mask(long long x) {
if (x <= 0) return 0u;
return x == 1 ? kPf2All : (uint32_t)x & kPf2All;
}
static int g_moe_pf2_pin = -1;
static uint32_t moe_pf2() {
static const uint32_t v = [] {
const char* e = std::getenv("R4D_MOE_PF2");
return moe_pf2_mask(e ? std::atoll(e) : 0);
}();
return g_moe_pf2_pin >= 0 ? moe_pf2_mask(g_moe_pf2_pin) : v;
}
/* WHICH PARTS A PINNED LAUNCH TOOK. A part whose kernel did not run -- a shape it refuses, a
* condition that never held -- would match the default trivially, so the test asks. Recorded only
* under a pin: the pin is a test's, and a serving process never writes either. */
static uint32_t g_moe_pf2_used = 0;
static inline void moe_pf2_note(uint32_t part) {
if (g_moe_pf2_pin >= 0) g_moe_pf2_used |= part;
}
extern "C" void r4d_moe_pf2_pin(int pin) { g_moe_pf2_pin = pin; }
extern "C" uint32_t r4d_moe_pf2_used(void) {
const uint32_t u = g_moe_pf2_used;
g_moe_pf2_used = 0;
return u;
}
/* THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 gather_kernel (a column a
* thread), 2 gather_wide_kernel (a wave a token). The rule takes 2 past the self-scan bound wherever
* the shape allows it; see r4d_rad_moe_gather. A pinned form the shape cannot take is refused. Both
* are bit-identical, and r4d_selftest compares their bytes. */
static int g_moe_gather_pin = 0;
extern "C" void r4d_moe_gather_pin_form(int form) { g_moe_gather_pin = form; }
/* ============================================================== the plugin ABI entry points */
@@ -2924,28 +2846,13 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) {
(unsigned)(n_expert * sizeof(int32_t)), (hipStream_t)s,
idp, bcnt, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot);
R4D_MOE_CHK();
/* R4D_MOE_PF2 (8): the scan in parallel, the tail in the placement -- the same integers. */
if (moe_pf2() & kPf2Scan) {
moe_pf2_note(kPf2Scan);
hipLaunchKernelGGL(scatter_scan_par_kernel, dim3(1), dim3(kMaxExpert), 0, (hipStream_t)s,
bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert);
R4D_MOE_CHK();
hipLaunchKernelGGL(scatter_place_tail_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), 0,
(hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot);
R4D_MOE_CHK();
return RAD_OK;
}
hipLaunchKernelGGL(scatter_scan_kernel, dim3(1), dim3(256), 0, (hipStream_t)s,
hipLaunchKernelGGL(scatter_scan_kernel, dim3(1), dim3(kMaxExpert), 0, (hipStream_t)s,
bcnt, op, cp, (uint32_t)n_tile, (uint32_t)n_expert);
R4D_MOE_CHK();
hipLaunchKernelGGL(scatter_place_kernel, dim3((unsigned)n_tile), dim3(kScatterTile), 0,
(hipStream_t)s, idp, bcnt, op, sp, (uint32_t)T, (uint32_t)n_expert,
(int32_t)base, prot);
R4D_MOE_CHK();
hipLaunchKernelGGL(scatter_tail_kernel, dim3((unsigned)((T + 255) / 256)), dim3(256), 0,
(hipStream_t)s, op, sp, (uint32_t)T, (uint32_t)n_expert);
R4D_MOE_CHK();
return RAD_OK;
}
@@ -3082,25 +2989,44 @@ static inline bool r4d_moe_gu_fk256(long long T, bool a_sorted) {
if (g_moe_fk_pin == 2) return true;
return T <= kMoeGuFk256Rows<W4>;
}
/* 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 SORTED-OPERAND PROJECTION'S DECODE KERNEL, and its column tiles a block. The decode form of
* down -- the sorted operand, one part, at most kMaxExpert experts -- is moe_down_dec_kernel: a
* block a 16-row tile of a run and G 64-column tiles a block, see its note. Any other shape takes
* the (tile, run) form. G follows the routed-row count: one below kMoeDownDecG2Rows, two below
* kMoeDownDecG4Rows, four from there, which keeps a few thousand working blocks from one sequence
* to sixteen. Bit-identical to the (tile, run) form at every G. Constants, so a recorded pass and
* a live one take the same kernel.
*
* MEASURED at TP4 on four R9700 (gfx1201), MTP depth 3, end to end: ms a decode step with this
* rule against the (tile, run) form at the same concurrency.
*
* concurrent sequences 4 8 16
* ms a step -0.9% -3.1% -7.8%
*
* At TP2 on two R9700, Qwen3.8-Flash-Next, MTP depth 3, distinct prompts a sequence, the same
* measure (one window each; boot to boot the same arm moves about 0.5%):
*
* concurrent sequences 1 4 6 8
* (tile, run) form 14.78 25.64 - 36.15 ms a step
* this rule 14.64 25.53 - 36.26
* G = 1 always - - 31.58 36.37
* G = 2 always - 25.59 31.17 36.15
* G = 4 always - - 31.66 36.48
*
* Nothing at TP2 moves by more than that noise, so the TP4 thresholds stand: a rank holding twice
* each expert's width already keeps its blocks busy at the (tile, run) form's grid. */
constexpr long long kMoeDownDecG2Rows = 200;
constexpr long long kMoeDownDecG4Rows = 480;
/* G's bound: the kernel keeps its column tiles in one 32-bit mask. */
constexpr long long kMoeDownDecMaxG = 16;
/* THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the rule above, -1 the (tile, run)
* form, n > 0 moe_down_dec_kernel at n column tiles a block (capped at kMoeDownDecMaxG). A pin to
* the kernel on a shape it does not serve is refused. */
static int g_moe_down_dec_pin = 0;
static inline long long r4d_moe_down_dec_g(long long T) {
if (g_moe_down_dec_pin < 0) return 0;
if (g_moe_down_dec_pin > 0) return g_moe_down_dec_pin;
return T >= kMoeDownDecG4Rows ? 4 : T >= kMoeDownDecG2Rows ? 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
@@ -3117,13 +3043,21 @@ static inline long long r4d_blockmap_bytes(long long cap) {
/* ONE WORKGROUP, because the whole of it is a scan over at most kMaxExpert counters and a second
* launch to split that across the device would cost more than the scan does. The offsets are read
* into LDS once so the scan is not 512 dependent global loads. */
* into LDS once so the scan is not 512 dependent global loads.
*
* THE PREFIX IS PARALLEL: a DPP scan in each wave and one exchange of the wave totals, 256 counts
* a tile -- three tiles at 512 experts, whose n_expert + 1 counts end one past the second. On one
* thread it is 513 dependent LDS round trips in front of a GEMM that waits for the map, and the map
* is built twice a routed layer. Integers: the offsets have one answer whatever order the sums are
* formed in. */
__global__ __launch_bounds__(256) void moe_blockmap_kernel(
const int32_t* __restrict__ off, uint32_t n_expert, uint32_t T, uint32_t FM, uint32_t cap,
uint32_t* __restrict__ map) {
constexpr uint32_t NT = 256, NW = NT / kWave, kTiles = (kMaxExpert + NT) / NT;
__shared__ uint32_t s_cnt[kMaxExpert + 1];
__shared__ int32_t s_off[kMaxExpert + 1];
const uint32_t tid = threadIdx.x;
__shared__ int32_t s_wt[kTiles][NW];
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
for (uint32_t e = tid; e <= n_expert; e += blockDim.x) s_off[e] = off[e];
__syncthreads();
@@ -3138,59 +3072,8 @@ __global__ __launch_bounds__(256) void moe_blockmap_kernel(
if (tid == 0) s_cnt[n_expert] = T > live ? (T - live + FM - 1) / FM : 0u;
__syncthreads();
/* Exclusive scan, one thread. kMaxExpert + 1 adds is nothing beside the launch, and a parallel
* scan here would be three barriers to save a microsecond on a kernel that runs once a layer. */
if (tid == 0) {
uint32_t acc = 0;
for (uint32_t e = 0; e <= n_expert; ++e) { const uint32_t c = s_cnt[e]; s_cnt[e] = acc; acc += c; }
map[0] = acc < cap ? acc : cap; /* the count, clamped to what the grid can serve */
}
__syncthreads();
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]);
uint32_t o = s_cnt[e];
for (uint32_t r = 0; r < run; r += FM, ++o) {
if (o >= cap) break;
map[1 + 2 * o + 0] = e;
map[1 + 2 * o + 1] = (uint32_t)s_off[e] + r;
}
}
if (tid == 0) {
uint32_t o = s_cnt[n_expert];
for (uint32_t r = live; r < T; r += FM, ++o) {
if (o >= cap) break;
map[1 + 2 * o + 0] = kMapTail;
map[1 + 2 * o + 1] = r;
}
}
}
/* PF2: THE SAME MAP WITH ITS PREFIX IN PARALLEL. Above, one thread prefixes the n_expert + 1 block
* counts alone -- 513 LDS round trips at 512 experts, in front of a GEMM that waits for the map,
* and the map is built twice a routed layer. Here the prefix is the small sort's: a DPP scan in each
* wave and one exchange of the wave totals, 256 counts a tile. Integers: the same offsets, so the
* same map entry for entry, and everything else is the kernel above line for line. */
__global__ __launch_bounds__(256) void moe_blockmap_par_kernel(
const int32_t* __restrict__ off, uint32_t n_expert, uint32_t T, uint32_t FM, uint32_t cap,
uint32_t* __restrict__ map) {
constexpr uint32_t NT = 256, NW = NT / kWave, kTiles = (kMaxExpert + NT) / NT;
__shared__ uint32_t s_cnt[kMaxExpert + 1];
__shared__ int32_t s_off[kMaxExpert + 1];
__shared__ int32_t s_wt[kTiles][NW];
const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave;
for (uint32_t e = tid; e <= n_expert; e += blockDim.x) s_off[e] = off[e];
__syncthreads();
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
const uint32_t run = (uint32_t)(s_off[e + 1] - s_off[e]);
s_cnt[e] = (run + FM - 1) / FM;
}
const uint32_t live = (uint32_t)s_off[n_expert];
if (tid == 0) s_cnt[n_expert] = T > live ? (T - live + FM - 1) / FM : 0u;
__syncthreads();
/* Exclusive scan over the n_expert + 1 counts, a tile of NT at a time. */
/* Exclusive scan over the n_expert + 1 counts, a tile of NT at a time. Each tile has its own
* exchange slots, so no tile's writes meet the reads of the one before it. */
uint32_t carry = 0;
for (uint32_t b = 0, tl = 0; b <= n_expert; b += NT, ++tl) {
const uint32_t e = b + tid;
@@ -3208,7 +3091,7 @@ __global__ __launch_bounds__(256) void moe_blockmap_par_kernel(
if (e <= n_expert) s_cnt[e] = carry + (uint32_t)(below + x - v);
carry += (uint32_t)tot;
}
if (tid == 0) map[0] = carry < cap ? carry : cap;
if (tid == 0) map[0] = carry < cap ? carry : cap; /* the count, clamped to the grid */
__syncthreads();
for (uint32_t e = tid; e < n_expert; e += blockDim.x) {
@@ -3234,6 +3117,11 @@ __global__ __launch_bounds__(256) void moe_blockmap_par_kernel(
* (tile, run) decode form and 3 the uniform prefill grid, whatever the band. r4d_selftest --perfmoe
* times each on one input and compares it with form 1: all three must match byte for byte. */
static int g_moe_prefill_form = 0;
/* THE ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule, 1 never the
* down projection's 256-column tile (the 128- or 64-column one), 2 the 256-column tile, refused
* where the shape cannot take it or the launch is not the aligned form. r4d_selftest compares the
* two byte for byte. */
static int g_moe_down_tile_pin = 0;
/* Both instantiations, from one body. The only things that differ are the weight table's dtype and
* its two pitches, so the fp8 launcher and the w4 one are the same forty lines with three values
@@ -3394,12 +3282,14 @@ 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) {
/* THE SORTED OPERAND'S OWN DECODE KERNEL, a block a run tile and G column tiles -- see
* moe_down_dec_kernel and kMoeDownDecG2Rows. 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 bool dn_dec = a_sorted && parts == 1 && n_expert <= (long long)kMaxExpert;
const long long g2 = r4d_moe_down_dec_g(T);
if (!dn_dec && g_moe_down_dec_pin > 0) return R4D_NO(RAD_E_UNSUPPORTED);
if (dn_dec && g2 > 0) {
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<W4>),
@@ -3453,62 +3343,54 @@ static int moe_gemm_launch(const RadArgs* a, const R4dSink& sk, int ncls = 2) {
/* The 128-column tile where no column tile straddles two parts of the weight. */
const bool wide_n = (N / parts) % kPrefillCols == 0;
const unsigned nyw = (unsigned)(N / kPrefillCols);
/* R4D_MOE_PF2: the run map's prefix in parallel (16), and the down projection -- the
* sorted operand, one part, a w4 weight whose scale is a row's -- at 256 columns over
* sixteen waves where every class's width is whole tiles of it (32). Each wave's share is
* the 128-column tile's: one 16-row M tile by two N tiles, the same K passes and the same
* fold, so every element is the same sum in the same order. What the wider block buys is
* its rows' activation and its run's prologue once for twice the columns. */
const uint32_t pf = moe_pf2();
bool dn_wide = W4 != 0 && (pf & kPf2DnWide) && a_sorted && parts == 1;
/* THE DOWN PROJECTION'S 256-COLUMN TILE, a rule of shape: the sorted operand, one part, a
* w4 weight whose scale is a row's, and every class's width whole tiles of it take 256
* columns over sixteen waves instead of 128 over eight. Each wave's share is the
* 128-column tile's: one 16-row M tile by two N tiles, the same K passes and the same fold,
* so every element is the same sum in the same order. What the wider block buys is its
* rows' activation and its run's prologue once for twice the columns. Any other shape keeps
* the 128- or 64-column tile. */
bool dn_wide = W4 != 0 && a_sorted && parts == 1 && N % (2 * kPrefillCols) == 0;
for (int q = 0; q < ncls; ++q) dn_wide = dn_wide && Nc[q] % (2 * kPrefillCols) == 0;
const int tpin = g_moe_down_tile_pin;
if (tpin < 0 || tpin > 2) return R4D_NO(RAD_E_INVAL);
if (tpin == 2 && (!map || !dn_wide)) return R4D_NO(RAD_E_UNSUPPORTED);
if (tpin == 1) dn_wide = false;
if (map) {
auto bmap = (pf & kPf2Map) ? &moe_blockmap_par_kernel : &moe_blockmap_kernel;
moe_pf2_note(pf & kPf2Map);
emit_rc = R4D_EMIT(sk, bmap, dim3(1), dim3(256), 0,
emit_rc = R4D_EMIT(sk, moe_blockmap_kernel, dim3(1), dim3(256), 0,
(const int32_t*)off->data, (uint32_t)n_expert, (uint32_t)T,
(uint32_t)kPrefillRows, (uint32_t)cap, map);
if (emit_rc != RAD_OK) return emit_rc;
/* R4D_MOE_PF2 (64): the first pass's weight at the map read -- see EW at the kernel.
* The same kernels otherwise; a function pointer picks the instantiation. */
const bool ew = (pf & kPf2Ew) != 0;
moe_pf2_note(pf & kPf2Ew);
/* Every aligned instantiation reads the weight from a uniform base (UW) and issues its
* first pass at the map read -- see THE ALIGNED FORM'S FIRST PASS at the kernel. */
if (dn_wide) {
/* Only a w4 weight takes it (dn_wide is false otherwise), and the block-fp8
* instantiation would not compile: its scale is a 128x128 tile's. */
moe_pf2_note(kPf2DnWide);
if constexpr (W4 != 0) {
auto kd = ew ? &moe_gemm_q_kernel<kPrefillRows / 16, 2 * kPrefillCols / 16, 2, 8, W4, false, true, true, kFK, true, false, true>
: &moe_gemm_q_kernel<kPrefillRows / 16, 2 * kPrefillCols / 16, 2, 8, W4, false, true, true>;
emit_rc = R4D_EMIT(sk, kd,
dim3((unsigned)cap, (unsigned)(N / (2 * kPrefillCols))),
dim3(16 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
}
if constexpr (W4 != 0)
emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel<kPrefillRows / 16, 2 * kPrefillCols / 16, 2, 8, W4, false, true, true, kFK, true>),
dim3((unsigned)cap, (unsigned)(N / (2 * kPrefillCols))),
dim3(16 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
} else if (wide_n) {
auto kw = ew ? &moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, true, true, kFK, true, false, true>
: &moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, true, true>;
emit_rc = R4D_EMIT(sk, kw,
dim3((unsigned)cap, nyw), dim3(8 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, true, true, kFK, true>),
dim3((unsigned)cap, nyw), dim3(8 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
} else {
auto kn = ew ? &moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, true, true, kFK, true, false, true>
: &moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, true, true>;
emit_rc = R4D_EMIT(sk, kn,
dim3((unsigned)cap, ny), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel<kPrefillRows / 16, 4, 2, 2, W4, false, true, true, kFK, true>),
dim3((unsigned)cap, ny), dim3(4 * kWave), 0,
(const uint8_t*)Aq->data, (const float*)As->data, ce, co, c2, c3,
(const int32_t*)sorted->data, (const int32_t*)off->data,
(uint16_t*)Y->data, (const uint32_t*)map,
(uint32_t)T, (uint32_t)N, (uint32_t)n_expert, (uint32_t)top_k,
(uint32_t)a_ld, (uint32_t)as_ld, (uint32_t)y_ld, mode, tabv);
}
} else if (wide_n) {
emit_rc = R4D_EMIT(sk, (moe_gemm_q_kernel<kPrefillRows / 16, kPrefillCols / 16, 2, 4, W4, false, false, true>),
@@ -3562,7 +3444,10 @@ 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" void r4d_moe_gemm_pin_down_tile(int pin) { g_moe_down_tile_pin = pin; }
extern "C" void r4d_moe_gemm_pin_down_dec(int pin) {
g_moe_down_dec_pin = pin < (int)kMoeDownDecMaxG ? pin : (int)kMoeDownDecMaxG;
}
extern "C" int r4d_rad_moe_gemm_q(const RadArgs* a, RadStream s) {
return moe_gemm_launch<0>(a, r4d_stream_sink(s));
@@ -3768,18 +3653,22 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
else if (act && std::strcmp(act, "none")) return R4D_NO(RAD_E_UNSUPPORTED);
}
/* R4D_MOE_PF2 (2, and 4 for the column groups last first): the prefill form a wave a token
* and sixteen bytes a lane, where the slots fit its registers and every row it reads or writes
* starts on sixteen bytes. The same sums; see gather_wide_kernel. */
const uint32_t pf = moe_pf2();
/* THE PREFILL FORM, a wave a token and sixteen bytes a lane (gather_wide_kernel), past the
* self-scan bound wherever the slots fit its registers and every row it reads or writes starts
* on sixteen bytes. The same sums as gather_kernel's; see the kernel. Anything else -- a decode
* step, a top_k past kGatherWideSlots, a width or a pitch sixteen-byte pieces do not tile --
* takes gather_kernel. */
auto al16 = [](const void* p, long long ld) {
return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0;
};
if (!self && (pf & kPf2Gather) && top_k <= (long long)kGatherWideSlots &&
n % (long long)kGatherWideCols == 0 && al16(ye->data, ye_ld) && al16(Y->data, y_ld) &&
(!sh || al16(sh->data, sh_ld))) {
const bool wide_ok = !self && top_k <= (long long)kGatherWideSlots &&
n % (long long)kGatherWideCols == 0 && al16(ye->data, ye_ld) &&
al16(Y->data, y_ld) && (!sh || al16(sh->data, sh_ld));
const int gpin = g_moe_gather_pin;
if (gpin < 0 || gpin > 2) return R4D_NO(RAD_E_INVAL);
if (gpin >= 2 && !wide_ok) return R4D_NO(RAD_E_UNSUPPORTED);
if ((gpin == 0 && wide_ok) || gpin >= 2) {
constexpr uint32_t NW = 8;
moe_pf2_note(kPf2Gather | (pf & kPf2GatherRev));
const unsigned gw = (unsigned)((n + kWave * kGatherWideCols - 1) / (kWave * kGatherWideCols));
hipLaunchKernelGGL((gather_wide_kernel<NW>), dim3((unsigned)((M + NW - 1) / NW), gw),
dim3(NW * kWave), 0, (hipStream_t)s,
@@ -3788,7 +3677,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) {
(uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld,
sh ? (const uint16_t*)sh->data : nullptr,
sh ? (const uint16_t*)sg->data : nullptr,
(uint32_t)sh_ld, (uint32_t)sg_ld, sig, (pf & kPf2GatherRev) ? 1 : 0);
(uint32_t)sh_ld, (uint32_t)sg_ld, sig);
R4D_MOE_CHK();
return RAD_OK;
}
+319 -255
View File
@@ -45,8 +45,6 @@
#include "rad_abi.h"
#include "rad_plugin.h"
#include "../vendor/nlohmann/json.hpp"
#include <fstream>
#include "r4d_args.h"
#include "r4d_hc_fp8.h"
#include "r4d_fp8_frag.h"
@@ -165,9 +163,9 @@ struct Plugin {
void (*pin_qsa)(int) = nullptr;
void (*pin_moe)(int) = nullptr;
void (*pin_fk)(int) = nullptr;
void (*pin_pf2)(int) = nullptr;
uint32_t (*pf2_used)(void) = nullptr;
void (*pin_dn2)(int) = nullptr;
void (*pin_dtile)(int) = nullptr;
void (*pin_gather)(int) = nullptr;
void (*pin_ddec)(int) = nullptr;
void (*pin_hc)(int) = nullptr;
void (*pin_qsel)(int) = nullptr;
};
@@ -199,9 +197,9 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "r4d_qsa_score_pin_form", &pl->pin_qsa);
okall &= sym(pl->h, "r4d_moe_gemm_pin_prefill", &pl->pin_moe);
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_moe_gemm_pin_down_tile", &pl->pin_dtile);
okall &= sym(pl->h, "r4d_moe_gather_pin_form", &pl->pin_gather);
okall &= sym(pl->h, "r4d_moe_gemm_pin_down_dec", &pl->pin_ddec);
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;
@@ -1186,6 +1184,36 @@ static bool restores(const RadKernelInfo* r, const std::vector<RadParam>& lp, in
* r's R pairs at [r*R, (r+1)*R) of each row. If that interleave is ever spelled differently in
* the graph, this case is what says so. */
/* ------------------------------------------------- static YaRN, in double
*
* cos and sin of one rotary pair at one position: the inverse frequency theta^(-2i/rot), blended
* toward inv/factor over the linear ramp [low, high] -- vLLM's YaRNScalingRotaryEmbedding, whose
* correction bounds tests/yarn_test.cpp holds yarn_from to -- and both scaled by the magnitude.
* Computed here, so the YaRN cases need nothing beside this binary.
*
* `tol` IS WHAT AN f32 EVALUATION OF THE SAME FORMULA MAY DIFFER BY. powf, the reciprocal, the
* blend and the product with the position each cost an ulp or so of the ANGLE, so the bound is 8
* ulp of the angle plus the rounding of the result. Where the ramp sits it is a few 1e-5 even at
* position 524287, so a wrong factor, bound or blend order is far outside it; it is loose only in
* the fastest pairs at long positions, which YaRN leaves unscaled and which no f32 rotary places
* better than its own angle's ulp. A double reference cannot reproduce the device's powf rounding
* there, and a tolerance that pretended to would be a table of this card's answers. */
struct YarnRef { double c, s, tol; };
static YarnRef yarn_ref(double pos, int i, int rot, double theta, double factor, double low,
double high, double magnitude) {
const double inv = std::pow(theta, -2.0 * i / rot);
const double ramp = std::min(1.0, std::max(0.0, (i - low) / (high == low ? 0.001 : high - low)));
const double a = pos * (inv / factor * ramp + inv * (1.0 - ramp));
return { std::cos(a) * magnitude, std::sin(a) * magnitude,
magnitude * (std::fabs(a) * 0x1p-20 + 0x1p-21) };
}
/* The YaRN cases' parameters: factor 2 over 262144 trained positions at theta 1e7, and the
* positions a 512K context reaches -- the ends, the trained length on both sides, and past it. */
static const double kYarnMag = 1.069314718055994531; /* 1 + 0.1 ln 2 */
static const int32_t kYarnPos[] = { 0, 1, 4096, 262143, 262144, 500000, 524287 };
static double yarn_low(int64_t rot) { return rot == 64 ? 14 : rot == 128 ? 28 : 56; }
static double yarn_high(int64_t rot) { return rot == 64 ? 22 : rot == 128 ? 43 : 85; }
/* ------------------------------------------------- the fused attention prologue, against its pair
*
* THE QUESTION IS BIT EQUALITY AND NOTHING ELSE. `qk_norm_rope_gate` replaces rmsnorm(q) +
@@ -1224,8 +1252,8 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal
const int64_t M = 512, nq = 12, nkv = 2, hd = 256, ctx = yarn ? 524288 : 4096;
auto add_yarn = [&](std::vector<RadParam>& ps) {
if (!yarn) return;
ps.push_back(PF("yarn_factor", 2)); ps.push_back(PF("yarn_low", rot == 64 ? 14 : 28));
ps.push_back(PF("yarn_high", rot == 64 ? 22 : 43)); ps.push_back(PF("yarn_magnitude", 1.069314718));
ps.push_back(PF("yarn_factor", 2)); ps.push_back(PF("yarn_low", yarn_low(rot)));
ps.push_back(PF("yarn_high", yarn_high(rot))); ps.push_back(PF("yarn_magnitude", kYarnMag));
};
const double theta = 1e7, eps = 1e-6, wadd = 1.0;
/* MANY ROWS, because the difference this case is hunting is one bf16 in tens of thousands: two
@@ -1235,10 +1263,7 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal
* near the top. */
std::vector<int32_t> pos((size_t)M);
for (int64_t i = 0; i < M; ++i) pos[(size_t)i] = (int32_t)((i * 7 + i * i) % ctx);
if (yarn) {
const int32_t edges[] = {0, 1, 4096, 262143, 262144, 500000, 524287};
std::copy(std::begin(edges), std::end(edges), pos.begin());
}
if (yarn) std::copy(std::begin(kYarnPos), std::end(kYarnPos), pos.begin());
auto rnd = [](int64_t i) { /* deterministic, and spans the exponent */
const uint32_t x = (uint32_t)(i * 2654435761u + 12345u);
@@ -1340,22 +1365,25 @@ static void qk_prologue_case(const Plugin& pl, uint32_t gain_dt, bool yarn = fal
add_yarn(ps);
run_case(rt, ts, ps);
if (yarn) {
const std::string here = __FILE__;
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/../tests/data/yarn_reference_rocm.json");
if (!input) { ok("YaRN independent vectors", false, "fixture missing"); return; }
const auto fixture = nlohmann::json::parse(input);
const auto& c = fixture["cases"][rot == 64 ? 0 : 1];
std::vector<float> row(rot);
/* The table's rows at the YaRN positions against the double-precision formula, as a
* fraction of what f32 may differ by (yarn_ref): at or under 1 passes. */
std::vector<float> row((size_t)rot);
double worst = 0.0;
for (size_t m = 0; m < fixture["positions"].size(); ++m) {
st_memcpy(row.data(), (float*)d_cs + (size_t)pos[m] * rot, rot * sizeof(float), hipMemcpyDeviceToHost);
for (int32_t p : kYarnPos) {
st_memcpy(row.data(), (float*)d_cs + (size_t)p * rot, (size_t)rot * sizeof(float),
hipMemcpyDeviceToHost);
for (int i = 0; i < rot / 2; ++i) {
worst = std::max(worst, std::abs((double)row[i] - c["cos"][m][i].get<double>()));
worst = std::max(worst, std::abs((double)row[rot/2+i] - c["sin"][m][i].get<double>()));
const YarnRef y = yarn_ref(p, i, (int)rot, theta, 2.0, yarn_low(rot),
yarn_high(rot), kYarnMag);
worst = std::max(worst, std::fabs(row[(size_t)i] - y.c) / y.tol);
worst = std::max(worst, std::fabs(row[(size_t)(rot / 2 + i)] - y.s) / y.tol);
}
}
ok("YaRN GPU table vs independent vLLM through 524287", worst <= 0.004,
("worst absolute error " + std::to_string(worst)).c_str());
char what[96], got[96];
std::snprintf(what, sizeof what, "YaRN table, rot %lld, vs a double YaRN through 524287",
(long long)rot);
std::snprintf(got, sizeof got, "worst %.3g of the f32 bound", worst);
ok(what, worst <= 1.0, got);
}
}
{
@@ -2067,30 +2095,23 @@ static void router_gemm_fused_case(const Plugin& pl) {
* with the rest closed up -- and keep every run stable. Both forms of the standalone sort run: 450
* slots is the one-workgroup form, 3000 the three-pass one, and the first, a middle and the last
* expert of a rank's slice are protected so the closing-up is tested at both ends. The fused
* decode kernel is held to the standalone pair in topk_scatter_case. */
/* `pf2` >= 0 pins R4D_MOE_PF2 for the launch (0 off, 1 every part), and the case is then also run
* at a prefill chunk's sizes: the general form's scan and tail are what that switch replaces, and
* both forms are held to the same host sort. -1 leaves the switch alone. */
static void scatter_protect_at(const Plugin& pl, const RadKernelInfo* rs, int64_t M, int64_t nl,
int64_t base, int pf2);
* decode kernel is held to the standalone pair in topk_scatter_case.
*
* The general form also runs at a prefill chunk's sizes: 79 and 80 tiles of 256 slots, so a
* scan thread's column of tile counts takes several batches of loads with a short last one, on a
* rank's slice and with every one of 512 experts local (the mod4 split's case), where the scan's
* workgroup is every thread an expert. */
static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, int64_t base);
static void scatter_protect_case(const Plugin& pl) {
if (!sel("moe_scatter_i32")) return;
const RadKernelInfo* rs = find(pl, "moe_scatter_i32");
if (!rs) { ok("moe_scatter protect", false, "row absent"); return; }
for (const int64_t M : { 45, 300 }) scatter_protect_at(pl, rs, M, 254, 3, -1);
/* R4D_MOE_PF2, off and on, at a prefill chunk: 79 and 80 tiles of the general form, a rank's
* slice and every one of 512 experts local (the mod4 split's case). */
if (pl.pin_pf2)
for (const int pf : { 0, 1 }) {
scatter_protect_at(pl, rs, 300, 254, 3, pf);
scatter_protect_at(pl, rs, 2000, 254, 3, pf);
scatter_protect_at(pl, rs, 2048, 512, 0, pf);
}
for (const int64_t M : { 45, 300, 2000 }) scatter_protect_at(rs, M, 254, 3);
scatter_protect_at(rs, 2048, 512, 0);
}
static void scatter_protect_at(const Plugin& pl, const RadKernelInfo* rs, int64_t M, int64_t nl,
int64_t base, int pf2) {
static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, int64_t base) {
const int64_t ne = 512, k = 10;
const std::vector<int64_t> prot = { 0, 17, 101, 253 };
std::vector<int64_t> place((size_t)nl);
@@ -2103,7 +2124,6 @@ static void scatter_protect_at(const Plugin& pl, const RadKernelInfo* rs, int64_
{
const int64_t NS = M * k;
const std::string at = " (" + std::to_string(NS) + " slots, slice " + std::to_string(nl) +
(pf2 < 0 ? "" : pf2 ? ", R4D_MOE_PF2 on" : ", R4D_MOE_PF2 off") +
")";
/* Each row's k distinct experts from the whole router, a quarter of them in this slice and
* the protected ones over-represented so their runs are long. */
@@ -2150,17 +2170,7 @@ static void scatter_protect_at(const Plugin& pl, const RadKernelInfo* rs, int64_
T(d_of, RAD_I32, { nl + 1 }), T(d_cn, RAD_I32, { nl }) };
std::vector<RadParam> ps = { PI("M", M), PI("n_expert", nl), PI("top_k", k),
PI("expert_base", base), PS("protect", "0,17,101,253") };
if (pf2 >= 0) { pl.pin_pf2(pf2); pl.pf2_used(); }
run_case(rs, ts, ps);
if (pf2 >= 0) {
/* Pinned on, the general form must have taken the parallel scan -- else the bytes
* below would be the default's against itself. The one-workgroup form takes nothing. */
const uint32_t u = pl.pf2_used();
pl.pin_pf2(-1);
const bool want = pf2 != 0 && NS > 1024;
ok(("moe_scatter took " + std::string(want ? "the R4D_MOE_PF2 scan" : "the default scan") +
at).c_str(), ((u & 8u) != 0) == want, "parts used " + std::to_string(u));
}
std::vector<int32_t> got_s((size_t)NS), got_o((size_t)(nl + 1)), got_c((size_t)nl);
st_memcpy(got_s.data(), d_so, (size_t)NS * 4, hipMemcpyDeviceToHost);
st_memcpy(got_o.data(), d_of, (size_t)(nl + 1) * 4, hipMemcpyDeviceToHost);
@@ -2181,16 +2191,18 @@ static void scatter_protect_at(const Plugin& pl, const RadKernelInfo* rs, int64_
}
}
/* moe_gather AT A PREFILL CHUNK: R4D_MOE_PF2 against the form it replaces, byte for byte.
/* moe_gather'S FORMS, against each other byte for byte.
*
* Past the self-scan cap the op builds the slot inverse in scratch and sums each token's slots a
* column a thread. R4D_MOE_PF2 replaces that sum with a wave a token and sixteen bytes a lane (part
* 2) and takes the column groups last first (part 4). Each must write the default's bytes: with and
* without the shared arm folded in, under both gates, with dropped slots, at a width that ends
* inside a column group, and at Qwen3.8-Flash-Next's 2048-token chunk on a rank of four -- where the
* case also prints what each form costs. A decode step (under the cap), a top_k past the wide
* form's registers and a width it cannot take in sixteen-byte pieces keep the default form, and the
* case checks that they did. `wide` is whether the shape takes it. */
* Past the self-scan cap the op builds the slot inverse in scratch and sums each token's slots.
* Its rule takes gather_wide_kernel there -- a wave a token and sixteen bytes a lane -- wherever
* the slots fit its registers and every row starts on sixteen bytes, and gather_kernel -- a column
* a thread -- everywhere else. r4d_moe_gather_pin_form pins each (1 the column a thread, 2 the wave
* a token), and every form must write the column-a-thread form's bytes: with and without the shared arm folded
* in, under both gates, with dropped slots, at a width that ends inside a column group, and at
* Qwen3.8-Flash-Next's 2048-token chunk on a rank of four -- where the case also prints what each
* form costs. A decode step (under the cap), a top_k past the wide form's registers and a width it
* cannot take in sixteen-byte pieces must refuse the wide pins, and the rule then writes the same
* bytes as the column a thread. `wide` is whether the shape takes the wide form. */
struct MoeGatherShape { int64_t M, n, k; const char* act; bool wide; };
static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGatherShape& sh) {
@@ -2231,7 +2243,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat
void* d_sg = shared ? dalloc(sgv.size() * 2) : nullptr;
void* d_y = dalloc((size_t)(M * n * 2));
if (!d_ye || !d_ew || !d_so || !d_y || (shared && (!d_sh || !d_sg))) {
ok(("moe_gather R4D_MOE_PF2" + at).c_str(), false, "hipMalloc failed");
ok(("moe_gather forms" + at).c_str(), false, "hipMalloc failed");
return;
}
st_memcpy(d_ye, ye.data(), ye.size() * 2, hipMemcpyHostToDevice);
@@ -2256,38 +2268,38 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat
const int64_t need = r->scratch ? r->scratch(&a) : 0;
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
/* One launch at a pin, over stale bytes, and the parts it took. */
auto run = [&](int pin, std::vector<uint16_t>& out, uint32_t* used) -> bool {
/* One launch at a pinned form, over stale bytes; its return code. */
auto run = [&](int form, std::vector<uint16_t>& out) -> int {
std::vector<uint16_t> junk((size_t)(M * n), 0x7f7fu);
st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice);
pl.pin_pf2(pin);
pl.pf2_used();
pl.pin_gather(form);
const int rc = r->launch(&a, nullptr);
const hipError_t he = (hipError_t)st_stream_sync(nullptr);
*used = pl.pf2_used();
pl.pin_pf2(-1);
if (rc != RAD_OK || he != hipSuccess) {
ok(("moe_gather R4D_MOE_PF2 pin " + std::to_string(pin) + at).c_str(), false,
"rc=" + std::to_string(rc) + " hip=" + hipGetErrorString(he));
return false;
}
pl.pin_gather(0);
if (rc == RAD_OK && he != hipSuccess) return RAD_E_DEVICE;
out.resize((size_t)(M * n));
st_memcpy(out.data(), d_y, out.size() * 2, hipMemcpyDeviceToHost);
return true;
return rc;
};
std::vector<uint16_t> base, got;
uint32_t used = 0;
if (!run(0, base, &used)) return;
ok(("moe_gather, R4D_MOE_PF2 off, takes no part of it" + at).c_str(), used == 0,
"parts used " + std::to_string(used));
struct Var { int pin; const char* name; uint32_t parts; };
if (const int rc = run(1, base); rc != RAD_OK) {
ok(("moe_gather, a column a thread" + at).c_str(), false, "rc=" + std::to_string(rc));
return;
}
struct Var { int form; const char* name; bool wide; };
static const Var kVar[] = {
{ 2, "a wave a token", 2u },
{ 6, "a wave a token, column groups last first", 6u },
{ 1, "every part", 6u },
{ 0, "the rule", false },
{ 2, "a wave a token", true },
};
for (const Var& v : kVar) {
if (!run(v.pin, got, &used)) return;
const std::string label = "moe_gather, " + std::string(v.name) + at;
const int rc = run(v.form, got);
if (v.wide && !sh.wide) {
/* A shape the wide form cannot take refuses the pin rather than run another form. */
ok((label + " is refused").c_str(), rc == RAD_E_UNSUPPORTED, "rc=" + std::to_string(rc));
continue;
}
if (rc != RAD_OK) { ok(label.c_str(), false, "rc=" + std::to_string(rc)); continue; }
int64_t diff = 0;
std::string first;
for (size_t i = 0; i < got.size(); ++i)
@@ -2297,21 +2309,18 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat
std::to_string((int64_t)i % n);
++diff;
}
const uint32_t want = sh.wide ? v.parts : 0u;
ok(("moe_gather R4D_MOE_PF2, " + std::string(v.name) +
(sh.wide ? "" : " (the default form, which this shape keeps)") + at).c_str(),
diff == 0 && (used & 6u) == want,
std::to_string(diff) + " of " + std::to_string(M * n) + " differ" + first +
"; parts used " + std::to_string(used) + ", expected " + std::to_string(want));
ok(label.c_str(), diff == 0,
std::to_string(diff) + " of " + std::to_string(M * n) +
" differ from a column a thread" + first);
}
if (M >= 2048) {
if (M >= 2048 && sh.wide) {
hipEvent_t e0, e1;
st_ev_create(&e0);
st_ev_create(&e1);
auto time = [&](int pin) -> float {
auto time = [&](int form) -> float {
const int it = 20;
pl.pin_pf2(pin);
pl.pin_gather(form);
for (int w = 0; w < 3; ++w) r->launch(&a, nullptr);
st_ev_record(e0, nullptr);
for (int i = 0; i < it; ++i) r->launch(&a, nullptr);
@@ -2319,15 +2328,13 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat
st_ev_sync(e1);
float ms = 0.0f;
st_ev_elapsed(&ms, e0, e1);
pl.pin_pf2(-1);
pl.pf2_used();
pl.pin_gather(0);
return ms * 1000.0f / (float)it;
};
const float t0 = time(0), t2 = time(2), t6 = time(6);
std::printf(" moe_gather at %lld routed rows x %lld: default %.1f us, a wave a token "
"%.1f us, last first %.1f us a call, prepass included (the cache that last "
"first is for needs the down projection in front, which this does not run)\n",
(long long)NS, (long long)n, t0, t2, t6);
const float t1 = time(1), t2 = time(2);
std::printf(" moe_gather at %lld routed rows x %lld: a column a thread %.1f us, a wave "
"a token %.1f us a call, prepass included\n",
(long long)NS, (long long)n, t1, t2);
st_ev_destroy(e0);
st_ev_destroy(e1);
}
@@ -2337,7 +2344,7 @@ static void moe_gather_case(const Plugin& pl) {
if (!sel("moe_gather_bf16")) return;
const RadKernelInfo* r = find(pl, "moe_gather_bf16");
if (!r) { ok("moe_gather_bf16", false, "row absent"); return; }
if (!pl.pin_pf2 || !pl.pf2_used) { ok("moe_gather_bf16 R4D_MOE_PF2", false, "pin hooks absent"); return; }
if (!pl.pin_gather) { ok("moe_gather_bf16 forms", false, "pin hook absent"); return; }
static const MoeGatherShape kSh[] = {
{ 600, 2560, 10, "sigmoid", true },
{ 600, 2560, 10, nullptr, true },
@@ -6767,97 +6774,101 @@ static void moe_dec_variants(const Plugin& pl, const RadKernelInfo* row, RadArgs
}
}
/* THE RUN-ALIGNED PREFILL FORM UNDER R4D_MOE_PF2, against the same form without it, byte for byte:
* the run map's prefix in parallel (16) on every shape, the first pass's weight issued at the map
* read (64) on every shape, and on the sorted operand -- one part, every class's width whole
* 256-column tiles -- the down projection's 256-column tile (32); each alone and all together.
* Described first where the row can be: the map's kernel must differ from the default's exactly
* when 16 is on, and the GEMM's exactly when 64 is or the wide tile applies, so the bytes below are
* never one kernel against itself; and the launch must report the parts it took. `base` is the
* form's own bytes, already held to the host decode by the form loop.
/* THE RUN-ALIGNED FORM'S TWO COLUMN TILES ON THE DOWN PROJECTION, byte for byte. Where the
* sorted operand, one part and every class's width in whole 256-column tiles let the rule take the
* 256-column tile, the 128-column tile (r4d_moe_gemm_pin_down_tile 1) must write its bytes. Every
* launch is DESCRIBED first where the row can be: the rule and the 256 pin must name one GEMM and
* the 128 pin another, so the bytes below are never one kernel against itself. Where the shape
* cannot take the 256-column tile, the pin to it is refused. `base` is the aligned form's own bytes
* under the rule, already held to the host decode by the form loop.
*
* PAST 512 EXPERTS THERE IS NO ALIGNED LAUNCH: the map's builder holds kMaxExpert + 1 offsets, so
* the launcher hands a wider expert count the uniform grid whatever scratch it is given, and none
* of these parts has a launch to take. Such a shape is skipped, not failed. */
static void moe_pf2_aligned(const Plugin& pl, const RadKernelInfo* row, RadArgs& a, void* d_y,
void* d_map, int64_t map_bytes, size_t elems,
const std::vector<uint16_t>& base, bool dn_wide, int64_t ne,
const std::string& what) {
if (!pl.pin_pf2 || !pl.pf2_used || !pl.pin_moe || base.empty()) return;
* the launcher hands a wider expert count the uniform grid whatever scratch it is given. Such a
* shape is skipped, not failed. */
static void moe_aligned_down_tile(const Plugin& pl, const RadKernelInfo* row, RadArgs& a,
void* d_y, void* d_map, int64_t map_bytes, size_t elems,
const std::vector<uint16_t>& base, bool dn_wide, int64_t ne,
const std::string& what) {
if (!pl.pin_dtile || !pl.pin_moe || base.empty()) return;
const std::string head = what + " aligned prefill form";
if (ne > 512) {
skip((what + " aligned prefill form, R4D_MOE_PF2").c_str(),
"no run map past 512 experts, so no aligned launch");
skip((head + ", column tiles").c_str(), "no run map past 512 experts, so no aligned launch");
return;
}
void* const sc0 = a.scratch;
const int64_t sb0 = a.scratch_bytes;
struct Var { int pin; uint32_t mask; const char* name; };
static const Var kVar[] = {
{ 16, 16u, "map prefix in parallel" },
{ 48, 48u, "map prefix in parallel, 256-column down tile" },
{ 64, 64u, "first pass's weight at the map read" },
{ 1, 112u, "every part" },
a.scratch = d_map;
a.scratch_bytes = map_bytes;
pl.pin_moe(1);
auto restore = [&] {
pl.pin_dtile(0);
pl.pin_moe(0);
a.scratch = sc0;
a.scratch_bytes = sb0;
};
for (const Var& v : kVar) {
if ((v.mask & 32u) && v.mask != 112u && !dn_wide) continue; /* the same as 16 here */
const bool map_new = (v.mask & 16u) != 0;
const bool gemm_new = (v.mask & 64u) || (dn_wide && (v.mask & 32u));
const uint32_t want = (v.mask & 16u) | (v.mask & 64u) | (dn_wide ? (v.mask & 32u) : 0u);
const std::string label = what + " aligned prefill form, R4D_MOE_PF2 " +
std::to_string(v.pin) + " (" + v.name + ")";
a.scratch = d_map;
a.scratch_bytes = map_bytes;
auto restore = [&] {
pl.pin_pf2(-1);
pl.pf2_used();
pl.pin_moe(0);
a.scratch = sc0;
a.scratch_bytes = sb0;
};
pl.pin_moe(1);
if (row->describe) {
static RadLaunchDesc d0[4], d1[4];
int n0 = 0, n1 = 0;
pl.pin_pf2(0);
const int c0 = row->describe(&a, nullptr, d0, 4, &n0);
pl.pin_pf2(v.pin);
const int c1 = row->describe(&a, nullptr, d1, 4, &n1);
if (c0 != RAD_OK || c1 != RAD_OK || n0 != 2 || n1 != 2) {
restore();
ok(label.c_str(), false, "describe rc " + std::to_string(c0) + "/" +
std::to_string(c1) + ", launches " +
std::to_string(n0) + "/" + std::to_string(n1));
continue;
}
if ((d0[0].func != d1[0].func) != map_new || (d0[1].func != d1[1].func) != gemm_new) {
restore();
ok(label.c_str(), false, std::string("described kernels: the map's ") +
(d0[0].func == d1[0].func ? "is the default's" : "differs") +
", the GEMM's " +
(d0[1].func == d1[1].func ? "is the default's" : "differs"));
continue;
}
}
auto launch = [&](int pin, std::vector<uint16_t>* got) {
{
std::vector<uint16_t> junk(elems, 0x7f7fu);
st_memcpy(d_y, junk.data(), junk.size() * 2, hipMemcpyHostToDevice);
}
pl.pin_pf2(v.pin);
pl.pf2_used();
pl.pin_dtile(pin);
const int rc = row->launch(&a, nullptr);
st_stream_sync(nullptr);
const uint32_t used = pl.pf2_used();
pl.pin_dtile(0);
if (got) {
got->assign(elems, 0);
st_memcpy(got->data(), d_y, elems * 2, hipMemcpyDeviceToHost);
}
return rc;
};
if (!dn_wide) {
const int rc = launch(2, nullptr);
restore();
ok((head + ", the 256-column down tile is refused on this shape").c_str(),
rc == RAD_E_UNSUPPORTED, "rc=" + std::to_string(rc));
return;
}
if (row->describe) {
const void* fn[3] = {};
for (int pin = 0; pin < 3; ++pin) {
static RadLaunchDesc d[4];
int n = 0;
pl.pin_dtile(pin);
const int drc = row->describe(&a, nullptr, d, 4, &n);
pl.pin_dtile(0);
if (drc != RAD_OK || n != 2) {
restore();
ok((head + ", column tiles described").c_str(), false,
"pin " + std::to_string(pin) + ": describe rc " + std::to_string(drc) +
", launches " + std::to_string(n));
return;
}
fn[pin] = d[1].func;
}
if (fn[0] != fn[2] || fn[1] == fn[2]) {
restore();
ok((head + ", column tiles described").c_str(), false,
std::string("the rule ") + (fn[0] == fn[2] ? "names" : "does not name") +
" the 256-column GEMM; the 128 pin " +
(fn[1] == fn[2] ? "names it too" : "names another"));
return;
}
}
struct Var { int pin; const char* name; };
static const Var kVar[] = { { 1, "the 128-column down tile" },
{ 2, "the 256-column down tile, pinned" } };
for (const Var& v : kVar) {
const std::string label = head + ", " + v.name +
(row->describe ? "" : " (launch not described)");
std::vector<uint16_t> got;
const int rc = launch(v.pin, &got);
if (rc != RAD_OK) { ok(label.c_str(), false, "launch rc=" + std::to_string(rc)); continue; }
std::vector<uint16_t> got(elems);
st_memcpy(got.data(), d_y, got.size() * 2, hipMemcpyDeviceToHost);
int64_t diff = 0;
for (size_t i = 0; i < elems; ++i) diff += got[i] != base[i];
ok(label.c_str(), diff == 0 && (used & 112u) == want,
std::to_string(diff) + " of " + std::to_string(elems) +
" elements differ from the form without it; parts used " + std::to_string(used) +
", expected " + std::to_string(want));
ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(elems) +
" elements differ from the rule's 256-column tile");
}
restore();
}
/* EVERY FORM THE LAUNCHER HAS, each against the host decode: the run-aligned prefill form (a run
@@ -6939,11 +6950,14 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int
}
/* The activation is written as E4M3 BYTES and a per-(row, group) f32 scale, so the host and
* the device read the same numbers and the only difference left is summation order. */
* the device read the same numbers and the only difference left is summation order. The scale
* varies along the rows as well as the groups: one the same for every row would let a kernel
* that reads another row's scale pass. */
std::vector<uint8_t> aq((size_t)(M * K));
std::vector<float> as((size_t)(M * kb));
for (int64_t m = 0; m < M; ++m) {
for (int64_t g = 0; g < kb; ++g) as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g;
for (int64_t g = 0; g < kb; ++g)
as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g + 0.0007f * (float)(m % 11);
for (int64_t k = 0; k < K; ++k) {
/* 8..126: no subnormal, and no 0x7F -- which is E4M3's NaN, and which a comparison
* that lets NaN through never noticed. */
@@ -7113,11 +7127,11 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int
diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) +
" elements differ");
}
/* The aligned form under R4D_MOE_PF2: the parallel map prefix always, the 256-column down
* tile where the sorted operand's every class is whole tiles of it. */
/* The aligned form's two column tiles on the down projection, where the sorted operand's every
* class is whole 256-column tiles; elsewhere the 256-column pin is refused. */
const bool dn_wide = sh.sorted_a && sh.parts == 1 && sh.N0 % 256 == 0 && sh.N1 % 256 == 0;
moe_pf2_aligned(pl, r, a, d_y, d_map, map_bytes, (size_t)(Tr * N), two_cls[1], dn_wide, ne,
what);
moe_aligned_down_tile(pl, r, a, d_y, d_map, map_bytes, (size_t)(Tr * N), two_cls[1], dn_wide,
ne, what);
/* The decode form's staged K both ways, where this shape can take two blocks a pass --
* never on the sorted operand, which the rule keeps at one. */
const bool fk2 = !sh.sorted_a && g64 && sh.K0 % 256 == 0 && sh.K1 % 256 == 0;
@@ -7185,8 +7199,8 @@ static void moe_w4_gemm(const Plugin& pl, int64_t Tr, const MoeW4Shape& sh, int
ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) +
" elements differ from the two-class op's");
}
moe_pf2_aligned(pl, r4, a4, d_y, d_map, map_bytes, (size_t)(Tr * N), two_cls[1], dn_wide, ne,
what4);
moe_aligned_down_tile(pl, r4, a4, d_y, d_map, map_bytes, (size_t)(Tr * N), two_cls[1],
dn_wide, ne, what4);
moe_dec_variants(pl, r4, a4, d_y, (size_t)(Tr * N), fk2, what4);
}
@@ -7296,11 +7310,12 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons
}
/* moe_w4_gemm's activation and routing: E4M3 bytes with no subnormal and no NaN, an f32 scale
* a (row, group), an uneven run on each expert and a dropped tail. */
* a (row, group) that varies along both, an uneven run on each expert and a dropped tail. */
std::vector<uint8_t> aq((size_t)(M * K));
std::vector<float> as((size_t)(M * kb));
for (int64_t m = 0; m < M; ++m) {
for (int64_t g = 0; g < kb; ++g) as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g;
for (int64_t g = 0; g < kb; ++g)
as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g + 0.0007f * (float)(m % 11);
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);
@@ -7412,7 +7427,7 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons
}
const int f_lo = pl.pin_moe ? 1 : 0, f_hi = pl.pin_moe ? 3 : 0;
std::vector<uint16_t> aligned; /* the aligned form's bytes, for the R4D_MOE_PF2 pass */
std::vector<uint16_t> aligned; /* the aligned form's bytes, for the column-tile pass */
for (int form = f_lo; form <= f_hi; ++form) {
const std::string label = what + " " + kForm[form];
if (pl.pin_moe) pl.pin_moe(form);
@@ -7451,9 +7466,9 @@ static void moe_q4_gemm(const Plugin& pl, int64_t Tr, const MoeQ4Shape& sh, cons
" elements off, worst " + std::to_string(worst) + first);
if (form == 1) aligned = got;
}
/* The aligned form under R4D_MOE_PF2, each class at its own geometry; fp8a8 runs W4 0 here,
* the token operand, so no 256-column down tile. */
moe_pf2_aligned(pl, r, a, d_y, d_map, map_bytes, (size_t)(Tr * N), aligned, false, ne, what);
/* The token operand takes no 256-column down tile, and the pin to it is refused. */
moe_aligned_down_tile(pl, r, a, d_y, d_map, map_bytes, (size_t)(Tr * N), aligned, false, ne,
what);
/* The decode form's variants, each class at its own geometry; fp8a8 runs W4 0 here. */
bool fk2 = g64;
for (int q = 0; q < 4; ++q) fk2 = fk2 && sh.K[q] % 256 == 0;
@@ -7501,7 +7516,8 @@ static void moe_route(int64_t M, int64_t top_k, int64_t ne, uint64_t seed, bool
}
/* 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_down_dec_kernel, which the rule gives the decode form here, 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
@@ -7511,11 +7527,15 @@ static void moe_route(int64_t M, int64_t top_k, int64_t ne, uint64_t seed, bool
* 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. */
* that named the reference's kernel would match it trivially.
*
* AND AN OUTPUT THAT NAMES FEWER ROWS THAN ITS BUFFER, while the offsets still name the whole
* routing: both decode forms must write those rows as the full launch did and never a row past
* them. */
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<int64_t> Ts) {
static void moe_down_dec_case(const Plugin& pl, const MoeDnShape& sh, const char* dt,
std::initializer_list<int64_t> 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;
@@ -7530,7 +7550,7 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
ok(head.c_str(), false, "row or hooks absent");
return;
}
if (!pl.pin_moe || !pl.pin_dn2) {
if (!pl.pin_moe || !pl.pin_ddec) {
skip(head.c_str(), "the plugin exports no form pins");
return;
}
@@ -7622,11 +7642,12 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
}
/* One activation row a routed slot: E4M3 bytes with no subnormal and no NaN, an f32 scale
* a (row, group). */
* a (row, group) that varies along both, so a row read under another's scale shows. */
std::vector<uint8_t> aq((size_t)(Tr * K));
std::vector<float> 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 g = 0; g < kb; ++g)
as[(size_t)(m * kb + g)] = 0.011f + 0.003f * (float)g + 0.0007f * (float)(m % 11);
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);
@@ -7702,7 +7723,8 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
}
}
/* One pinned launch into stale bytes, its output back. `pins` is (form, down2). */
/* One pinned launch into stale bytes, its output back. `pins` is (form, the sorted
* operand's decode kernel: -1 the (tile, run) form, 0 the rule, n its column tiles). */
auto run = [&](const int (&pins)[2], std::vector<uint16_t>* got) {
{
std::vector<uint16_t> junk((size_t)(Tr * N), 0x7f7fu);
@@ -7711,11 +7733,11 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
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]);
pl.pin_ddec(pins[1]);
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
pl.pin_moe(0);
pl.pin_dn2(0);
pl.pin_ddec(0);
got->assign((size_t)(Tr * N), 0);
st_memcpy(got->data(), d_y, got->size() * 2, hipMemcpyDeviceToHost);
return rc;
@@ -7727,10 +7749,10 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
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]);
pl.pin_ddec(pins[1]);
const int drc = r->describe(&a, nullptr, d, 4, &n);
pl.pin_moe(0);
pl.pin_dn2(0);
pl.pin_ddec(0);
return drc == RAD_OK && n >= 1 ? d[n - 1].func : nullptr;
};
@@ -7776,15 +7798,18 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
" 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; };
/* The sorted operand's own decode kernel under the rule and at several column groups --
* sixteen is the cap, past the output's five tiles here -- each against the (tile, run)
* form's bytes. */
struct Var { int dn; const char* name; };
static const Var kVar[] = {
{ 0, "down kernel, the rule's column tiles" },
{ 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" },
{ 16, "down kernel, sixteen column tiles a block" },
};
const int ref_pins[2] = { 2, -1 };
const void* fn0 = described(ref_pins);
@@ -7793,7 +7818,7 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
std::to_string(nrun) + " runs, longest " +
std::to_string(longest) + ")" +
(r->describe ? "" : " (launch not described)");
const int pins[2] = { 2, v.dn2 };
const int pins[2] = { 2, v.dn };
if (r->describe) {
const void* fn = described(pins);
if (!fn || fn == fn0) {
@@ -7810,6 +7835,33 @@ static void moe_down2_case(const Plugin& pl, const MoeDnShape& sh, const char* d
ok(label.c_str(), diff == 0, std::to_string(diff) + " of " + std::to_string(Tr * N) +
" elements differ from the (tile, run) form");
}
/* THE OUTPUT SEVEN ROWS SHORT: Y declared at Tr - 7 rows over the same buffer, the
* offsets unchanged, so the routing names rows past the output's last. Each decode form
* must write the rows it has exactly as the full launch did and leave the rest stale. */
{
const int64_t Tv = Tr - 7;
ts[12] = T(d_y, RAD_BF16, { Tv, N });
for (const int dn : { -1, 0 }) {
const std::string label = what + " decode form, " +
(dn < 0 ? "(tile, run)" : "down kernel") +
", an output " + std::to_string(Tv) + " rows long, " +
std::to_string(off[(size_t)ne]) + " routed";
const int pins[2] = { 2, dn };
std::vector<uint16_t> 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, past = 0;
for (int64_t i = 0; i < Tr * N; ++i) {
if (i < Tv * N) diff += got[(size_t)i] != base[(size_t)i];
else past += got[(size_t)i] != 0x7f7fu;
}
ok(label.c_str(), diff == 0 && past == 0,
std::to_string(diff) + " of the output's elements differ from the full launch, " +
std::to_string(past) + " written past its last row");
}
ts[12] = T(d_y, RAD_BF16, { Tr, N });
}
}
}
@@ -9336,51 +9388,6 @@ static void qsa_score_rows_case(const Plugin& pl) {
* block's worth of angle, which is the mistake a reader makes when they take the position of the
* block's LAST token instead of its first, and it is invisible in magnitude: the vectors stay the
* same length and point somewhere else. rel_l2 is what sees it. */
static void qsa_block_key_yarn_case(const Plugin& pl) {
const char* what = "qsa_block_key YaRN vs independent ROCm vectors through 524287";
const RadKernelInfo* r = find(pl, "qsa_block_key_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const std::string here = __FILE__;
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/../tests/data/yarn_reference_rocm.json");
if (!input) { ok(what, false, "fixture absent"); return; }
const auto fixture = nlohmann::json::parse(input);
const auto positions = fixture["positions"].get<std::vector<int32_t>>();
const auto& c = fixture["cases"][0];
const int64_t M = positions.size(), n = 128, ratio = 4;
/* Identical unit keys make the block mean exactly one. Unit gain and eps=0
* make the norm exactly one too, isolating the compressed-key rotation. */
std::vector<uint16_t> keys(M * ratio * n, h_to_bf16(1.0f));
std::vector<float> gains(n, 1.0f);
void* dk = dalloc(keys.size()*2), *dw = dalloc(gains.size()*4);
void* dp = dalloc(M*4), *dout = dalloc(M*n*2);
st_memcpy(dk, keys.data(), keys.size()*2, hipMemcpyHostToDevice);
st_memcpy(dw, gains.data(), gains.size()*4, hipMemcpyHostToDevice);
st_memcpy(dp, positions.data(), M*4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {T(dk, RAD_BF16, {M*ratio,n}), T(dw, RAD_F32, {n}),
T(nullptr, RAD_I32, {M}), T(dp, RAD_I32, {M}), T(dout, RAD_BF16, {M,n})};
std::vector<RadParam> ps = {PI("M",M), PI("n",n), PI("ratio",ratio), PI("rotary_dim",64),
PF("eps",0), PF("theta",1e7), PF("scale",1), PF("wadd",0), PS("dtype","bf16"),
PF("yarn_factor",2), PF("yarn_low",14), PF("yarn_high",22), PF("yarn_magnitude",1.069314718)};
RadArgs a{}; a.t=ts.data(); a.n_t=ts.size(); a.p=ps.data(); a.n_p=ps.size();
bool passed = r->launch(&a,nullptr) == RAD_OK;
st_stream_sync(nullptr);
std::vector<uint16_t> got(M*n);
st_memcpy(got.data(),dout,got.size()*2,hipMemcpyDeviceToHost);
double worst=0;
for (int64_t m=0;m<M;++m) for (int i=0;i<n;++i) {
double expected=1;
if (i<64) {
const int j=i%32;
const double cosine=c["cos"][m][j], sine=c["sin"][m][j];
expected=i<32 ? cosine-sine : cosine+sine;
}
const double actual=h_bf16(got[m*n+i]);
passed = passed && std::isfinite(actual);
worst=std::max(worst,std::abs(actual-expected));
}
ok(what,passed && worst<=0.008,"worst absolute BF16 error "+std::to_string(worst));
}
static void qsa_block_key_case(const Plugin& pl) {
const char* what = "qsa_block_key vs an f64 evaluation of the same formula";
const RadKernelInfo* r = find(pl, "qsa_block_key_bf16");
@@ -9667,6 +9674,56 @@ static void qsa_block_key_case(const Plugin& pl) {
ok(what, pass, "rel " + std::to_string(r_ok) + ", control " + std::to_string(r_shift));
}
/* qsa_block_key with YaRN, against yarn_ref. Identical unit keys make the block mean exactly one,
* and unit gain with eps 0 makes the norm one too, so what is left is the rotation of the
* compressed key at each block's position: c - s in the first half of the rotary, s + c in the
* second, and the unrotated tail at one. The bound is yarn_ref's for both terms plus the bf16
* rounding of the output. */
static void qsa_block_key_yarn_case(const Plugin& pl) {
const char* what = "qsa_block_key YaRN vs a double YaRN through 524287";
const RadKernelInfo* r = find(pl, "qsa_block_key_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = (int64_t)(sizeof kYarnPos / sizeof kYarnPos[0]), n = 128, ratio = 4, rot = 64;
std::vector<uint16_t> keys((size_t)(M * ratio * n), h_to_bf16(1.0f));
std::vector<float> gains((size_t)n, 1.0f);
void* dk = dalloc(keys.size() * 2), *dw = dalloc(gains.size() * 4);
void* dp = dalloc((size_t)M * 4), *dout = dalloc((size_t)(M * n * 2));
st_memcpy(dk, keys.data(), keys.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dw, gains.data(), gains.size() * 4, hipMemcpyHostToDevice);
st_memcpy(dp, kYarnPos, (size_t)M * 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = { T(dk, RAD_BF16, { M * ratio, n }), T(dw, RAD_F32, { n }),
T(nullptr, RAD_I32, { M }), T(dp, RAD_I32, { M }),
T(dout, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PI("ratio", ratio), PI("rotary_dim", rot),
PF("eps", 0), PF("theta", 1e7), PF("scale", 1), PF("wadd", 0),
PS("dtype", "bf16"), PF("yarn_factor", 2),
PF("yarn_low", yarn_low(rot)), PF("yarn_high", yarn_high(rot)),
PF("yarn_magnitude", kYarnMag) };
RadArgs a{}; a.t = ts.data(); a.n_t = ts.size(); a.p = ps.data(); a.n_p = ps.size();
bool passed = r->launch(&a, nullptr) == RAD_OK;
st_stream_sync(nullptr);
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), dout, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
for (int64_t m = 0; m < M; ++m)
for (int64_t i = 0; i < n; ++i) {
double want = 1.0, tol = 0.0;
if (i < rot) {
const YarnRef y = yarn_ref(kYarnPos[m], (int)(i % (rot / 2)), (int)rot, 1e7, 2.0,
yarn_low(rot), yarn_high(rot), kYarnMag);
want = i < rot / 2 ? y.c - y.s : y.c + y.s;
tol = 2.0 * y.tol;
}
tol += std::fabs(want) * 0x1p-8 + 1e-6;
const double have = h_bf16(got[(size_t)(m * n + i)]);
passed = passed && std::isfinite(have);
worst = std::max(worst, std::fabs(have - want) / tol);
}
char note[64];
std::snprintf(note, sizeof note, "worst %.3g of the bf16 + f32 bound", worst);
ok(what, passed && worst <= 1.0, note);
}
/* gram_accum, against an f64 host Gram of the same dequantised bytes.
*
* THE THING THIS IS ACTUALLY FOR IS THE ACCUMULATE. A kernel that stored instead of adding would
@@ -11804,8 +11861,12 @@ static void device_phase(const Plugin& pl) {
{ "640 experts, gate/up 2:1, K 256", 256, 256, 128, 256, 2, 640 },
/* The down projection as a rank of four runs it: the sorted operand, one part, the
* classes at 256 and 128 of K -- and a width of whole 256-column tiles, which is what
* R4D_MOE_PF2's wide down tile takes. */
* the aligned form's 256-column down tile takes. Then with the odd class half as wide,
* so that tile is padding for every odd expert's run; and at 512 experts, whose
* n_expert + 1 block counts the run map scans in three 256-count tiles. */
{ "down, sorted rows, 512 x K 256:128", 512, 256, 512, 128, 1, 10, true },
{ "down, sorted rows, 512:256 x K 256:128", 512, 256, 256, 128, 1, 10, true },
{ "512 experts, down, sorted rows, 256 x K 128", 256, 128, 256, 128, 1, 512, true },
};
for (const MoeW4Shape& sh : kShapes) {
moe_w4_gemm(pl, 24, sh);
@@ -11833,6 +11894,8 @@ static void device_phase(const Plugin& pl) {
{ "640 experts, gate/up 2:1, K 256", 256, 256, 128, 256, 2, 640 },
{ "down, sorted rows, 512 x K 256:128", 512, 256, 512, 128, 1, 10, true },
{ "40 experts, down, sorted rows, 256 x K 128", 256, 128, 256, 128, 1, 40, true },
{ "down, sorted rows, 512:256 x K 256:128", 512, 256, 256, 128, 1, 10, true },
{ "512 experts, down, sorted rows, 256 x K 128", 256, 128, 256, 128, 1, 512, true },
};
for (const MoeW4Shape& sh : kShapes4)
for (const int64_t t : { (int64_t)24, (int64_t)200, (int64_t)600 }) {
@@ -11846,11 +11909,12 @@ 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 });
/* The sorted operand at decode, and its own kernel against the (tile, run) form: one
* sequence at depth 3 (T 40), five, sixteen and nineteen -- each side of both of the
* rule's column-tile thresholds. */
moe_down_dec_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 });
moe_down_dec_case(pl, kMoeDnShapes[1], dt, { 40, 96 });
}
if (sel("moe_gemm_fp8a8_mod4")) {
@@ -11859,7 +11923,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 });
moe_down_dec_case(pl, kMoeDnShapes[1], "fp8a8", { 40, 96 });
}
if (sel("hc_read_e4m3")) {