diff --git a/docs/OPS.md b/docs/OPS.md index 650a27c9..2fe30b51 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -251,6 +251,9 @@ with the gate in the first half. is positive and finite (GLM-5.3's is 10). The clip precedes the SiLU, and the gate has no lower clip. +libr4d's `swiglu_clamped_bf16` serves bf16 in and out at any width, pitched rows, `M` up to +65535. + **`add` and `mul`** broadcast a `b` of exactly `n` elements along the rows of a taller output (a bias add). Nothing else broadcasts, in these or any other elementwise op. `add`'s `div` divides the sum after its rounding, `y = rd(rd(a + b) / div)` with `rd` `y`'s dtype (absent, 1: the plain @@ -359,6 +362,19 @@ the sum of its chunks' partials, then `mhc_pre`'s gates, Sinkhorn mixing and col of that sum is the implementation's, so the pair matches `mhc_pre` to rounding, and bit for bit only where an implementation says so. +libr4d serves `mhc_pre`, `mhc_post` and `mhc_contract` at `hc` 2 to 8, `n` up to 16384 and +`M` up to 65535 (`iterations` 1 to 256), bf16 activations with f32 `fn`, `scale`, `base`, +`post` and `comb`. At GLM's geometry (`n` 4096, `hc` 4) `mhc_pre` runs as eight 2048-column chunk +partials held in `x`'s rows, then a finishing kernel; other geometries project and finish in one +workgroup per row. `mhc_pre_partial` and `mhc_pre_finish` serve that geometry only (`n` 4096, +`hc` 4, `chunk` 2048, a 28-float chunk stride) and run `mhc_pre`'s own projection and finishing +kernels with its chunk-sum order, so the pair is byte-identical to `mhc_pre` (`r4d_selftest`, +`tests/r4d_emu/test_mhc.cpp`). The projection takes a four-slot form from two rows, one row a wave +and two from 32, where the weight rows are 16-byte and the residual rows 8-byte aligned; the +finish forms the 4x4 mixing on one wave and collapses the row over the workgroup; `mhc_post` at +`hc` 4 writes eight columns of every stream a thread on 16-byte rows. Every form gives the bytes +of the scalar kernels it replaces. + ### Gemma 4's audio tower - **`relu`** is `max(x, 0)` at each operand's own row pitch. @@ -494,6 +510,16 @@ f32, read as the checkpoint stores them. A scale that bf16 cannot represent exac value, which `fp8a8`'s bf16 scale plane would round. It applies to `gemm_nt_q` and `moe_gemm_q` with `group` 128. +libr4d reads both canonical planes in place, with no relayout: `gemm_fp8a8_f32scale` for +`gemm_nt_q` and `moe_gemm_fp8a8_f32scale` for `moe_gemm_q`, `N` and `K` multiples of 128, E4M3 +WMMA with the f32 scale product folded per 128 of K, bf16 out. The dense row picks a decode form +(row tiles sharing each weight fragment, several waves on consecutive K blocks) or a row-tile +form by `M`, `N` and `K`; on rows that are not 16-byte aligned it takes the 16x64 tile. The forms +are byte-identical (`tests/r4d_emu/test_fp8f32.cpp`). The grouped row takes equal-width parity +tables (`N_odd = N`, `K_odd = K`), token or sorted activations, and stacked planes or pointer +tables, and runs expert-major: a block per (column span, expert) takes every row of its expert, +each element keeping the row-tile form's sequence. + **`group` has different meanings in this table.** A kernel that reads it the other way is wrong, not slow. `libref/ref_quant.cpp` is the definition. @@ -545,6 +571,7 @@ and is optional. | `givens_rotate` | `M` `n` `group` `dtype` `stages` `parts` | `x`, `pairs`w, `angle`w, `rscale`w → `y` | | `rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | +| `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | `quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, @@ -559,6 +586,12 @@ it does not produce that op's `y`. `act` is required here, unlike on the quantis implementation may compile one gate only, and an optional parameter would let it resolve for another. +`swiglu_clamped_quant_fp8` (device-only) is `swiglu_clamped` then `quant_act_fp8` over its +product in one pass. The product is rounded to bf16 before the quantiser reads it, as the pair +reads it from its bf16 tensor, so the codes, scales and `out_bf16` are the pair's bytes, NaN and +infinite inputs included (`r4d_selftest`). `n` is a multiple of 4, `group` 128, `M` up to 65535, +rows pitched. + `out_bf16` is part of the function, not an optimisation: the unfused pair leaves a bf16 tensor behind and takes the codes over it, so a layer with a bf16 consumer of the post-norm value must ask for it. `residual` present is the `fused_add_rms_norm` form. @@ -687,6 +720,12 @@ accumulation and an f32 `y`; `dtype` (`bf16`) names the activation. It exists fo whose weights and results must not narrow to bf16: GLM's router logits and its indexer's signed head gates. +libr4d's `gemm_nt_f32_bf16` takes `N` up to 512, `K` up to 16384, `M` up to 65535 and pitched +rows. A wave computes a tile of rows by columns, chosen by `M` and `N` (a single column per wave +at one row, eight rows by four columns from 64 rows, four rows by one column at `N <= 8`); each +output keeps one order (lane `l` sums `k = l, l+32, ...` with fused multiply-add, then a fixed +butterfly), so every tile is byte-identical (`tests/r4d_emu/test_f32.cpp`). + ### Runtime LoRA: `lora_shrink` and `lora_expand` | op | params | operands | @@ -1408,6 +1447,9 @@ Every op honours its activation operands' row pitches. `rd` is a rounding into t | `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? | | `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` | | `router_sigmoid_topk` | `M`(range) `n_expert` `top_k` `norm` `route_scale`:f64 `dtype` | `logits`, `bias`w → `ids`, `weights` | +| `router_sigmoid_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `route_scale`:f64 `dtype` `expert_base`/opt `protect`:str/opt | `logits`, `bias`w → `ids`, `weights`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`?, `inverse`? | +| `moe_scatter_inv` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count`, `inverse` | +| `moe_gather_inv` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `inverse`, `shared`?, `shared_gate`? → `y` | | `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` | | `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? | | `row_topk_merge` | `M` `R` `world_size` `dtype` | `gathered` → `idx`, `val` | @@ -1502,6 +1544,11 @@ block's all-reduce. With bf16 expert outputs, `expert_w` may be bf16 or f32. f32 mixture weights stay f32 through the sum; only the gathered result narrows to bf16, as with bf16 weights. +libr4d's `moe_gather_bf16` takes f32 weights in its column-per-thread kernel, with the self-scan +up to 512 slots (and `top_k` up to 64) and the two prepass launches above. The wave-per-token +form past 512 slots reads bf16 weights only, so f32 weights stay on the column-per-thread kernel +at every size. + ### Quantised experts and the row gate | op | params | operands | @@ -1532,11 +1579,51 @@ with fewer than `top_k` selectable experts has no defined selection (libref refu Grouped selection (`n_group > 1`) is not this op. GLM-5.3 routes 8 of 288 experts in one group with `route_scale` 2.5. +libr4d's `router_sigmoid_topk_f32` takes up to 512 experts and `top_k` up to 32, f32 logits, bias +and weights, i32 ids, pitched rows, `M` up to 65535. It selects in one wave per row: each lane +holds its experts as order-preserving keys (`-0` as `+0`, ties to the lower expert), and round `j` +takes the largest key below round `j-1`'s winner. A row without NaN ranks gives the bytes of the +serial scan. A NaN rank is never selected, and a row with fewer than `top_k` other ranks names +expert 0 in its empty slots, weighted by expert 0's `p`. + +**`router_sigmoid_topk_scatter`** (device-only) is `router_sigmoid_topk` and `moe_scatter` over its +`ids` in one launch, and with `gate` `[M, 1]` also the `fill` of an ungated shared arm's gate with +1 (GLM-5.3's shared expert has no gate, and the gather reads one). `n_expert`, `n_local`, +`expert_base` and `protect` are as in `router_topk_scatter`. Every output is the bytes the +separate launches write, including a row with fewer than `top_k` non-NaN ranks (NaN logits), +whose empty slots carry expert 0 into the sort as `ids` does (`r4d_selftest`). Bounded like +`router_topk_scatter` (`M * top_k <= 1024`, one workgroup) and refused past it. With `inverse` the +sort is `moe_scatter_inv`'s. + +**`moe_scatter_inv`** and **`moe_gather_inv`** (device-only) are `moe_scatter` and `moe_gather` +with the gather's slot table passed between them. `inverse` `[M * top_k]` holds, for slot +`token * top_k + slot`, its row in `sorted_tok`, or -1 when the slot was dropped; `moe_gather` +builds exactly that table from `sorted_tok` before it sums (a scan of the sort per token up to 512 +slots, two prepass launches above), and `moe_gather_inv` reads it instead. They are ops of their +own because `moe_scatter`'s and `moe_gather`'s operand lists are the shared vocabulary's. +`moe_scatter_inv` is the same sort (one launch up to 1024 slots, three above, `n_expert` up to +512), and `moe_gather_inv` runs the kernel `moe_gather` picks at the same size, bf16 or f32 +weights; both are byte-identical to the pair they replace, at GLM's shape with f32 routing weights +and the shared arm folded in (`r4d_selftest`). + At `dtype=mxfp4a8`, `w` and `w_odd` are OCP e2m1 codes and `w_scale` and `w_odd_scale` hold one E8M0 exponent per (row, 32 of K), typed `e8m0` or raw `u8`; either way a byte is an exponent, not an integer multiplier. `a` and `a_scale` are `quant_act_fp8`'s pair, and `group` is that activation's scale group, independent of the weight's 32-wide grid. +libr4d's `moe_gemm_mxfp4a8` keeps the canonical bytes, including pointer tables of device or +device-mapped host addresses: a wave decodes the packed e2m1 words into exact E4M3 bytes and runs +fp8 WMMA, folding each 32-wide E8M0 exponent into the f32 accumulator. Per 128 of K, each 32-wide +group is a fresh WMMA pair, folded as raw * activation scale * E8M0 scale. It serves `group` 128, +`K` a multiple of 128, 2 to 512 experts, `top_k` up to 32, token or sorted activations, `parts`, +and an odd class narrower in `N` or `K`, with `M` up to 32767; there is no `moe_gemm_q_mod4` row +at this dtype. The form follows the routed rows. The expert-major form, a block per (column block, +expert) that reads each expert slice once, takes up to 511 rows, and at GLM's TP8 slices (288 +experts, top 8) gate_up up to 768 and down up to 6143. At those slices the wide prefill form (P64: +jobs of 32 or 64 rows of one expert) takes gate_up from 769 rows and down from 5760, ahead of the +expert-major band. Elsewhere the row-group forms serve. Every form gives the bytes of the +arithmetic-decode row-group form (`tests/r4d_emu/test_moemx.cpp`). + **`moe_gemm_q_mod4`** is the same GEMM over four classes by the expert's number mod 4. `w`/`w_scale` hold class 0 at `[N, K]` and `w_q`/`w_q_scale` class `q` at `[N_q, K_q]` (defaulting to `N`, `K`); expert `e` is entry `e / 4` of class `e % 4`, so class `q` holds `ceil((n_expert - q) / 4)` of them. @@ -1642,6 +1729,14 @@ as the new count; the committed state does not advance past the accepted prefix, at most 32 tokens. `mode=prefill` commits its final state and sets the count to zero. A zeroed scratch slot replays nothing. +libr4d's `kda_update_k128_v128_bf16` takes `head_k = head_v = 128`, 1 to 65535 heads, bf16 +activations, f32 `A_log`, `dt_bias` and state, both modes and both state forms. A wave holds one, +two or four value rows of a head (four by default, the next token's operands loaded while the +current one reduces) and runs the sequence's tokens in order; every form gives the bytes of the +one-row kernel (`tests/r4d_emu/test_kda.cpp`). Under `anchor`, `verify` replays the accepted prefix +in a separate dispatch before the window, so no value row overwrites factors another is still +reading. A sequence whose window or slots are out of bounds is skipped on the device, not refused. + **Speculative rollback is part of the schema** (`spec.md` §10). The recurrent state and the conv window have already absorbed rejected tokens, so the state cache is a rolling window of `conv_width-1 + n_spec` entries read at the slot the last accepted token left, and a rejection is a @@ -2354,12 +2449,17 @@ contiguous inner rows and a four-byte-aligned page pitch of at least 136 bytes: untouched. That is one block-size-4 group of the indexer's KV, with no separate scale allocation. `block_size`, when given, is 4 and names the consuming layout to the cache planner. +libr4d's `dsa_pool_fp8` serves `n` 128 and `ratio` 4, the cache form included: one wave per pooled +row, the softmax channels and the Hadamard in registers, pitched rows. + `dsa_query` rotates each bf16 query head by the same normalized Walsh-Hadamard transform, rounds to bf16, and quantises to E4M3 with the same power-of-two scale: `x` `[M, n]`, `q` `[M, n]`, `scale` `[M, 1]`, token and head flattened into `M`. There is no RoPE and no RMS norm. Unlike `had_quant_act_fp8`, both the normalization of the rotation and the power-of-two scale are part of the op. `n` is a power of two up to 256. +libr4d's `dsa_query_fp8` serves `n` 128, one wave per query head, pitched rows. + `dsa_score` takes E4M3 queries `[M, heads, n]` with f32 scales and signed f32 gates `[M, heads]`, E4M3 pooled keys `[pages, n]` with f32 scales `[pages]`. `bt[seqs, blocks]` names key pages, `cu[seqs+1]` holds absolute query offsets and `nc[seqs]` bounds the live blocks. The score of block @@ -2374,6 +2474,11 @@ history makes no future block eligible. embedded scale are read in place. `q` may be flattened `[M*heads, n]` with `q_scale` `[M*heads, 1]`, each with its own row pitch, which is `dsa_query`'s output as written. +libr4d's `dsa_score_fp8` serves `n` 128 and 32 heads, `M` up to 65535, both key forms and both +query forms. A block of two waves covers the 32 heads of one query row against one or two 16-key +tiles (two past 32 blocks); the dot products run on fp8 WMMA, and scales and gates fold only after +each head's ReLU. + `mla_attn` is absorbed latent attention: one latent vector per token is both key and value. `q` and `out` are `[M, heads, latent_dim]`, `kv` is `[pages, 1, block_size, latent_dim]`, and `bt[M, blocks]` is each query's own page table, the selected complete pages followed by its tail. @@ -2383,6 +2488,19 @@ contributes nothing, and a row with no visible key outputs zero. The softmax is rounded once. `scale` is positive and finite and comes from the original query/key head width, not the latent width (GLM: `1/sqrt(256)` against a latent of 512). +libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The +matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the +heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter +it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of +one query; otherwise it pairs eight heads of two neighbouring queries, loading a key once where +both tables name the page, so GLM-5.3's 8 heads a rank fill the tile. The pairing walks the union +of the two tables, so each chunk runs once, for tables of up to 520 entries; past that it pairs +by table position, with a second pass where the two differ. +`RADIANCE_MLA_MATRIX_MAX_M` lowers the matrix row's `M` bound (65535 by default); past it the +wave row, `mla_attn_bf16`, serves: a wave per head with an online softmax. Both split a short +batch's history across workgroups and merge the f32 partials before narrowing, into the fixed +scratch their hooks reserve; without scratch they compute unsplit. + `mla_project` moves a query into the latent and a latent result out of it, through the bf16 weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows. `mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored, @@ -2392,6 +2510,11 @@ accumulate in f32 and round once to bf16. The KV cache stays latent; only this w per-head width. Its rows are head-major, so a tensor-parallel slice of whole heads is a row range. `a` and `y` may also be `[M, heads*width]`, heads contiguous, with their own token pitch. +libr4d's `mla_project_bf16` serves `head_dim` 256 and `latent_dim` 512, up to 64 heads, pitched +tensors. It takes up to eight rows a thread (`absorb`) or a wave (`expand`), loading each weight +element once for them, with every row's sum in the one-row kernels' order, so all forms give the +same bytes. + ## Draft heads A drafter is an ordinary graph over ordinary ops except at its two ends: what proposes the diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index a8944e37..351dca26 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -103,6 +103,13 @@ set(R4D_UNITS # launches behind one entry point: the mix depends on every column of the low-rank waist, so it # needs a grid-wide barrier. "r4d_hc_bf16|" + "r4d_mhc|" + "r4d_glm|" + "r4d_dsa|" + "r4d_mla|" + "r4d_kda|" + "r4d_moe_mxfp4|" + "r4d_fp8_f32scale|" "r4d_ngram_ids|" "r4d_ple_gate_bf16|" "r4d_ple_conv_bf16|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 9308639e..141b1b85 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -643,6 +643,10 @@ void r4d_moe_gemm_pin_down_dec(int pin); // (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes). // All bit-identical; r4d_selftest compares their bytes. void r4d_hc_read_pin_prefill(int form); +// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors +// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to. +// Bit-identical; r4d_selftest compares them and --perfmla times both. +void r4d_mla_matrix_pin_form(int form); // Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the // next call, and returns how many launches the previous recording saw (which may exceed its cap). // Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel diff --git a/libr4d/r4d_dsa.hip b/libr4d/r4d_dsa.hip new file mode 100644 index 00000000..839a2f8e --- /dev/null +++ b/libr4d/r4d_dsa.hip @@ -0,0 +1,298 @@ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_fwht.h" +#include "r4d_q8.h" +#include "r4d_fp8_wmma.h" +#include + +namespace { +__global__ void dsa_query_kernel(const uint16_t* x, uint8_t* q, float* scale, long xp, long qp, + long sp, int rows) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= rows) return; + float v[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) v[d] = bf16_to_f32(x[(long)r * xp + lane * 4 + d]); + r4d_fwht_wave<128>(v, lane); + float am = 1e-4f; +#pragma unroll + for (int d = 0; d < 4; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f)); + am = fmaxf(am, fabsf(v[d])); + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32)); + const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f)); + const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0)); + if (!lane) scale[(long)r * sp] = sc; + const uint32_t packed = q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); + uint8_t* dst = q + (long)r * qp + lane * 4; + if (((uintptr_t)dst & 3) == 0) + *(uint32_t*)dst = packed; + else { +#pragma unroll + for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d)); + } +} +int query_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &x = a->t[0], &q = a->t[1], &s = a->t[2]; + if (x.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !q.data || !s.data) return RAD_E_INVAL; + if (r4d_geti_or(a, "n", 0) != 128 || x.rank != 2 || q.rank != 2 || s.rank != 2 || + x.shape[0] < 1 || x.shape[0] > INT_MAX - 3 || x.shape[1] != 128 || + q.shape[0] != x.shape[0] || q.shape[1] != 128 || s.shape[0] != x.shape[0] || + s.shape[1] != 1 || x.stride[1] != 1 || q.stride[1] != 1 || s.stride[1] != 1 || + x.stride[0] < 128 || q.stride[0] < 128 || s.stride[0] < 1) + return RAD_E_SHAPE; + return R4D_EMIT(stream, dsa_query_kernel, dim3((x.shape[0] + 3) / 4), dim3(128), 0, + (const uint16_t*)x.data, (uint8_t*)q.data, (float*)s.data, x.stride[0], + q.stride[0], s.stride[0], (int)x.shape[0]); +} +struct ScoreMeta { + long qr, qh, qsr, qsc, gr, gc, kr, ksr, btr, btc, cur, ncr, op; + int rows, blocks, seqs, pages; +}; +__device__ uint32_t bytes4(const uint8_t* p) { + if (!((uintptr_t)p & 3)) return *(const uint32_t*)p; + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +/* Two waves cover all 32 heads and reuse the query across `kScoreTiles` 16-key tiles, one up to 32 + * blocks and two past them. FP8 dot products stay on WMMA; scales and the signed per-head gates + * fold only after the per-head ReLU. */ +template +__global__ void dsa_score_kernel(const uint8_t* q, const float* qs, const float* gate, + const uint8_t* k, const float* ks, const int* bt, const int* cu, + const int* nc, float* out, ScoreMeta m) { + constexpr int kScoreKeys = 16 * kScoreTiles; + __shared__ __align__(16) uint8_t qa[32 * 136], kb[kScoreKeys * 136]; + __shared__ int seq, pages[kScoreKeys]; + __shared__ float scales[kScoreKeys], coefficients[32], partial[2][kScoreKeys]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int r = blockIdx.y, b0 = blockIdx.x * kScoreKeys; + if (!tid) { + seq = -1; + for (int s = 0; s < m.seqs; ++s) + if (r >= cu[(long)s * m.cur] && r < cu[(long)(s + 1) * m.cur]) { + seq = s; + break; + } + } + __syncthreads(); + const int live = seq >= 0 ? min(nc[(long)seq * m.ncr], m.blocks) : 0; + if (b0 >= live) { + for (int i = tid; i < kScoreKeys; i += 64) + if (b0 + i < m.blocks) out[(long)r * m.op + b0 + i] = -INFINITY; + return; + } + for (int i = tid; i < kScoreKeys; i += 64) { + const int b = b0 + i; + int p = seq >= 0 && b < m.blocks && b < nc[(long)seq * m.ncr] + ? bt[(long)seq * m.btr + b * m.btc] + : -1; + if (p >= m.pages) p = -1; + pages[i] = p; + scales[i] = p >= 0 ? ks[(long)p * m.ksr] : 0; + } + if (tid < 32) + coefficients[tid] = qs[(long)r * m.qsr + tid * m.qsc] * gate[(long)r * m.gr + tid * m.gc]; + for (int j = tid; j < 32 * 32; j += 64) { + const int h = j / 32, d = (j % 32) * 4; + *(uint32_t*)(qa + h * 136 + d) = bytes4(q + (long)r * m.qr + (long)h * m.qh + d); + } + __syncthreads(); + for (int j = tid; j < kScoreKeys * 32; j += 64) { + const int b = j / 32, d = (j % 32) * 4, p = pages[b]; + *(uint32_t*)(kb + b * 136 + d) = p >= 0 ? bytes4(k + (long)p * m.kr + d) : 0; + } + __syncthreads(); + r4d_fp8::f8v acc[kScoreTiles]; +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) acc[tile] = r4d_fp8::acc_zero(); +#pragma unroll + for (int d = 0; d < 128; d += 16) { + const auto a = r4d_fp8::frag<128>(qa, wave * 16, d, lane); +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) + acc[tile] = r4d_fp8::mma(a, r4d_fp8::frag<128>(kb, tile * 16, d, lane), acc[tile]); + } +#pragma unroll + for (int tile = 0; tile < kScoreTiles; ++tile) { + float value = 0; +#pragma unroll + for (int j = 0; j < 8; ++j) + value += fmaxf(acc[tile][j], 0.0f) * coefficients[wave * 16 + (lane >> 4) * 8 + j]; + value += __shfl_xor(value, 16, 32); + if (lane < 16) partial[wave][tile * 16 + lane] = value; + } + __syncthreads(); + for (int i = tid; i < kScoreKeys; i += 64) + if (b0 + i < m.blocks) + out[(long)r * m.op + b0 + i] = + pages[i] >= 0 ? (partial[0][i] + partial[1][i]) * scales[i] * 0.015625f : -INFINITY; +} +int score_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 9) return RAD_E_INVAL; + RadTensor q = a->t[0], qs = a->t[1]; + const auto& g = a->t[2]; + RadTensor k = a->t[3], ks = a->t[4]; + const bool packed = k.dtype == RAD_U8; + if (packed) { + if (ks.data || k.rank != 4 || k.shape[1] != 1 || k.shape[2] != 4 || k.shape[3] != 34 || + k.stride[3] != 1 || k.stride[2] != 34 || k.stride[0] < 136 || k.stride[0] % 4 || + ((uintptr_t)k.data & 3)) + return RAD_E_SHAPE; + ks = {}; + ks.data = k.data ? (uint8_t*)k.data + 128 : nullptr; + ks.dtype = RAD_F32; + ks.rank = 1; + ks.shape[0] = k.shape[0]; + ks.stride[0] = k.stride[0] / 4; + k.dtype = RAD_F8E4M3; + k.rank = 2; + k.shape[1] = 128; + k.stride[1] = 1; + } + const auto &bt = a->t[5], &cu = a->t[6], &nc = a->t[7], &o = a->t[8]; + if (q.rank == 2 && qs.rank == 2 && qs.shape[1] == 1 && q.shape[0] == o.shape[0] * 32 && + qs.shape[0] == q.shape[0]) { + q.rank = 3; + q.shape[0] = o.shape[0]; + q.shape[2] = q.shape[1]; + q.shape[1] = 32; + q.stride[2] = q.stride[1]; + q.stride[1] = q.stride[0]; + q.stride[0] *= 32; + qs.shape[0] = o.shape[0]; + qs.shape[1] = 32; + qs.stride[1] = qs.stride[0]; + qs.stride[0] *= 32; + } + if (q.dtype != RAD_F8E4M3 || k.dtype != RAD_F8E4M3 || qs.dtype != RAD_F32 || + g.dtype != RAD_F32 || ks.dtype != RAD_F32 || o.dtype != RAD_F32 || bt.dtype != RAD_I32 || + cu.dtype != RAD_I32 || nc.dtype != RAD_I32) + return RAD_E_DTYPE; + for (int i = 0; i < 9; ++i) + if (!(packed && i == 4) && !a->t[i].data) return RAD_E_INVAL; + if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "heads", 0) != 32 || q.rank != 3 || + q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != 32 || q.shape[2] != 128 || + q.stride[2] != 1 || q.stride[1] < 128 || q.stride[0] < 32 * q.stride[1] || qs.rank != 2 || + g.rank != 2 || qs.shape[0] != q.shape[0] || g.shape[0] != q.shape[0] || qs.shape[1] != 32 || + g.shape[1] != 32 || qs.stride[1] < 1 || g.stride[1] < 1 || + qs.stride[0] < 32 * qs.stride[1] || g.stride[0] < 32 * g.stride[1] || k.rank != 2 || + k.shape[0] < 1 || k.shape[0] > INT_MAX || k.shape[1] != 128 || k.stride[1] != 1 || + k.stride[0] < 128 || ks.rank != 1 || ks.shape[0] != k.shape[0] || ks.stride[0] < 1 || + bt.rank != 2 || bt.shape[0] < 1 || bt.shape[0] > INT_MAX || bt.stride[1] < 1 || + cu.rank != 1 || cu.shape[0] != bt.shape[0] + 1 || nc.rank != 1 || + nc.shape[0] != bt.shape[0] || cu.stride[0] < 1 || nc.stride[0] < 1 || o.rank != 2 || + o.shape[0] != q.shape[0] || o.shape[1] < 1 || o.shape[1] > INT_MAX - 15 || + o.shape[1] > bt.shape[1] || o.stride[1] != 1 || o.stride[0] < o.shape[1] || + bt.stride[0] < bt.shape[1] * bt.stride[1]) + return RAD_E_SHAPE; + ScoreMeta m{ q.stride[0], q.stride[1], qs.stride[0], qs.stride[1], g.stride[0], + g.stride[1], k.stride[0], ks.stride[0], bt.stride[0], bt.stride[1], + cu.stride[0], nc.stride[0], o.stride[0], (int)q.shape[0], (int)o.shape[1], + (int)bt.shape[0], (int)k.shape[0] }; +#define SCORE(NT) \ + R4D_EMIT(stream, (dsa_score_kernel), dim3((m.blocks + 16 * NT - 1) / (16 * NT), m.rows), \ + dim3(64), 0, (const uint8_t*)q.data, (const float*)qs.data, (const float*)g.data, \ + (const uint8_t*)k.data, (const float*)ks.data, (const int*)bt.data, \ + (const int*)cu.data, (const int*)nc.data, (float*)o.data, m) + if (m.blocks <= 32) return SCORE(1); + return SCORE(2); +#undef SCORE +} +/* One wave per pool: all softmax channels and the full Hadamard stay in registers. */ +__global__ void dsa_pool_kernel(const uint16_t* kg, const float* ape, uint8_t* q, float* scale, + const int* page, uint8_t* cache, long kp, long ap, long qp, long sp, + long pp, long cp, int rows, int pages) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= rows) return; + float v[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int col = lane * 4 + d; + float g[4], mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) { + g[j] = bf16_to_f32(kg[((long)r * 4 + j) * kp + 128 + col]) + ape[(long)j * ap + col]; + mx = fmaxf(mx, g[j]); + } + float num = 0, den = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float p = expf(g[j] - mx); + num += p * bf16_to_f32(kg[((long)r * 4 + j) * kp + col]); + den += p; + } + v[d] = bf16_to_f32(f32_to_bf16(num / den)); + } + r4d_fwht_wave<128>(v, lane); + float am = 1e-4f; +#pragma unroll + for (int d = 0; d < 4; ++d) { + v[d] = bf16_to_f32(f32_to_bf16(v[d] * 0.08838834764831845f)); + am = fmaxf(am, fabsf(v[d])); + } +#pragma unroll + for (int mask = 16; mask; mask >>= 1) am = fmaxf(am, __shfl_xor(am, mask, 32)); + const uint32_t bits = __float_as_uint(am * (1.0f / 448.0f)); + const float sc = __uint_as_float((bits & 0x7f800000u) + ((bits & 0x7fffffu) ? 0x800000u : 0)); + if (!lane) scale[(long)r * sp] = sc; + const uint32_t packed = q8_pack4(v[0], v[1], v[2], v[3], 1.0f / sc); + uint8_t* dst = q + (long)r * qp + lane * 4; + if (((uintptr_t)dst & 3) == 0) + *(uint32_t*)dst = packed; + else { +#pragma unroll + for (int d = 0; d < 4; ++d) dst[d] = (uint8_t)(packed >> (8 * d)); + } + if (cache) { + const int p = page[(long)r * pp]; + if (p >= 0 && p < pages) { + uint8_t* out = cache + (long)p * cp; + *(uint32_t*)(out + lane * 4) = packed; + if (!lane) *(float*)(out + 128) = sc; + } + } +} +int pool_body(const RadArgs* a, RadStream stream) { + if (r4d_geti_or(a, "block_size", 4) != 4) return RAD_E_SHAPE; + if (!a || a->n_t < 4) return RAD_E_INVAL; + const auto &kg = a->t[0], &ape = a->t[1], &q = a->t[2], &s = a->t[3]; + const auto *page = rad_arg_in(a, 4), *cache = rad_arg_in(a, 5); + if ((page != nullptr) != (cache != nullptr)) return RAD_E_INVAL; + if (cache && + (page->dtype != RAD_I32 || page->rank != 1 || page->shape[0] != q.shape[0] || + page->stride[0] < 1 || cache->dtype != RAD_U8 || cache->rank != 4 || cache->shape[0] < 1 || + cache->shape[0] > INT_MAX || cache->shape[1] != 1 || cache->shape[2] != 4 || + cache->shape[3] != 34 || cache->stride[3] != 1 || cache->stride[2] != 34 || + cache->stride[0] < 136 || cache->stride[0] % 4 || ((uintptr_t)cache->data & 3))) + return RAD_E_SHAPE; + if (kg.dtype != RAD_BF16 || ape.dtype != RAD_F32 || q.dtype != RAD_F8E4M3 || s.dtype != RAD_F32) + return RAD_E_DTYPE; + if (r4d_geti_or(a, "n", 0) != 128 || r4d_geti_or(a, "ratio", 0) != 4 || kg.rank != 2 || + ape.rank != 2 || q.rank != 2 || s.rank != 2 || !kg.data || !ape.data || !q.data || + !s.data || q.shape[0] < 1 || q.shape[0] > INT_MAX / 4 || kg.shape[0] != q.shape[0] * 4 || + kg.shape[1] != 256 || ape.shape[0] != 4 || ape.shape[1] != 128 || q.shape[1] != 128 || + s.shape[0] != q.shape[0] || s.shape[1] != 1 || kg.stride[1] != 1 || ape.stride[1] != 1 || + q.stride[1] != 1 || s.stride[1] != 1 || kg.stride[0] < 256 || ape.stride[0] < 128 || + q.stride[0] < 128 || s.stride[0] < 1) + return RAD_E_SHAPE; + return R4D_EMIT( + stream, dsa_pool_kernel, dim3((q.shape[0] + 3) / 4), dim3(128), 0, (const uint16_t*)kg.data, + (const float*)ape.data, (uint8_t*)q.data, (float*)s.data, + page ? (const int*)page->data : nullptr, cache ? (uint8_t*)cache->data : nullptr, + kg.stride[0], ape.stride[0], q.stride[0], s.stride[0], page ? page->stride[0] : 0, + cache ? cache->stride[0] : 0, (int)q.shape[0], cache ? (int)cache->shape[0] : 0); +} +} +extern "C" int r4d_rad_dsa_pool(const RadArgs* a, RadStream stream) { return pool_body(a, stream); } +extern "C" int r4d_rad_dsa_query(const RadArgs* a, RadStream stream) { + return query_body(a, stream); +} +extern "C" int r4d_rad_dsa_score(const RadArgs* a, RadStream stream) { + return score_body(a, stream); +} diff --git a/libr4d/r4d_fp8_f32scale.hip b/libr4d/r4d_fp8_f32scale.hip new file mode 100644 index 00000000..fe947940 --- /dev/null +++ b/libr4d/r4d_fp8_f32scale.hip @@ -0,0 +1,642 @@ +/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no + * checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output + * tile a block; the dense decode and prefill forms below them produce the same bytes faster. */ +#include +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include "r4d_fp8_wmma.h" +#include "r4d_launch.h" +#include +#include +#include +#include +#include + +namespace { +struct Meta { + long ar, asr, yr, wr, sr, wstep[2], sstep[2]; + int T, N, K, experts, topk, sorted_a, tile; +}; +__device__ const uint8_t* entry(const void* p, long step, int e) { + return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e]; +} +template +__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0, + const void* w1, const void* s1, const int* sorted, const int* offsets, + uint16_t* y, Meta m) { + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64; + __shared__ uint8_t qa[16 * 136], wb[64 * 136]; + __shared__ int source[16]; + int first = (int)blockIdx.y * (Grouped ? m.tile : 16); + const int limit = min(first + (Grouped ? m.tile : 16), m.T); + while (first < limit) { + int expert = 0, end = limit; + if constexpr (Grouped) { + // Tile sorted rows rather than launching every expert, most of which are empty + // during native MTP decode. Split a tile at each expert boundary. + if (sorted[first] < 0 || offsets[m.experts] <= first) { + for (int c = tid; c < 64; c += 128) + if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0; + ++first; + continue; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offsets[mid] <= first) + lo = mid; + else + hi = mid; + } + expert = lo; + end = min(limit, offsets[expert + 1]); + if (end <= first) return; + } + const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0; + const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e); + const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e); + if (tid < 16) { + const int r = first + tid; + const int flat = Grouped && r < end ? sorted[r] : r; + source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1; + } + __syncthreads(); + auto acc = r4d_fp8::acc_zero(); + for (int k0 = 0; k0 < m.K; k0 += 128) { + for (int j = tid; j < 16 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4, src = source[r]; + uint32_t v = 0; + if (src >= 0) { + const auto* p = a + (long)src * m.ar + k0 + c; + v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); + } + *(uint32_t*)(qa + r * 136 + c) = v; + } + for (int j = tid; j < 64 * 32; j += 128) { + const int r = j / 32, c = (j % 32) * 4; + const auto* p = w + (long)(n0 + r) * m.wr + k0 + c; + *(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | + ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); + } + __syncthreads(); + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = 0; k < 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane), + r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); + const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int src = source[(lane >> 4) * 8 + j]; + const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0; + acc[j] += raw[j] * scale; + } + __syncthreads(); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15); + if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + } + __syncthreads(); + first = end; + } +} +/* The grouped form expert-major: a block per (column span, expert) takes every row of its + * expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in + * the sorted order (the row tiles above re-read it once per tile its run spans). Each element + * keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw * + * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in + * stages of StageK, as one stage sequence with the next stage loaded into registers while the + * current one computes from LDS. Block row `experts` zeroes the dropped rows past + * offsets[experts]. */ +typedef unsigned f8_u4 __attribute__((ext_vector_type(4))); +template +struct F8Stage { + static constexpr int KB = StageK / 128; + f8_u4 a[StageK / 128], w[StageK / 32]; + float wsc[KB], sa; +}; +template +__global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, const float* as, + const void* w0, const void* s0, + const void* w1, const void* s1, + const int* sorted, const int* offsets, + uint16_t* y, Meta m) { + using St = F8Stage; + constexpr int KB = St::KB, P = StageK + 8; + __shared__ __align__(16) uint8_t qa[16 * P], wb[64 * P]; + __shared__ float sa[16 * KB]; + __shared__ int source[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y, + colb = blockIdx.x * 64 * ColTiles; + if (e == m.experts) { + const int r0 = offsets[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * 64 * ColTiles; i += 128) { + const int c = colb + (int)(i % (64 * ColTiles)); + if (c < m.N) y[(long)(r0 + i / (64 * ColTiles)) * m.yr + c] = 0; + } + return; + } + const int lo = offsets[e], hi = offsets[e + 1]; + if (lo >= hi) return; + const int parity = e & 1; + const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e / 2); + const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e / 2); + const int ksn = (m.K + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + 63) / 64), + S = tiles * ksn; + const int rowbase = (lane >> 4) * 8; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + source[tid] = r < hi && flat >= 0 ? (m.sorted_a ? r : flat / m.topk) : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = source[rowbase + j] >= 0; + auto load = [&](int s, St& R) { + const int col0 = colb + (s / ksn) * 64, k0 = (s % ksn) * StageK; +#pragma unroll + for (int i = 0; i < StageK / 128; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16, + src = source[r]; + R.a[i] = f8_u4{ 0, 0, 0, 0 }; + if (src >= 0 && k0 + c < m.K) + __builtin_memcpy(&R.a[i], a + (long)src * m.ar + k0 + c, 16); + } +#pragma unroll + for (int i = 0; i < StageK / 32; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + R.w[i] = f8_u4{ 0, 0, 0, 0 }; + if (k0 + c < m.K) + __builtin_memcpy(&R.w[i], w + (long)(col0 + r) * m.wr + k0 + c, 16); + } +#pragma unroll + for (int kb = 0; kb < KB; ++kb) + R.wsc[kb] = + k0 + kb * 128 < m.K ? ws[(long)(col0 / 128) * m.sr + (k0 + kb * 128) / 128] : 0; + if (tid < 16 * KB) { + const int src = source[tid / KB], kb = k0 + (tid % KB) * 128; + R.sa = src >= 0 && kb < m.K ? as[(long)src * m.asr + kb / 128] : 0; + } + }; + auto store = [&](const St& R) { +#pragma unroll + for (int i = 0; i < StageK / 128; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(qa + r * P + c) = R.a[i]; + } +#pragma unroll + for (int i = 0; i < StageK / 32; ++i) { + const int j = tid + i * 128, r = j / (StageK / 16), c = (j % (StageK / 16)) * 16; + *reinterpret_cast(wb + r * P + c) = R.w[i]; + } + if (tid < 16 * KB) sa[tid] = R.sa; + }; + auto acc = r4d_fp8::acc_zero(); + St R; + load(0, R); + for (int s = 0; s < S; ++s) { + store(R); + float wsc[KB]; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) wsc[kb] = R.wsc[kb]; + __syncthreads(); + if (s + 1 < S) load(s + 1, R); + const int k0 = (s % ksn) * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= m.K) break; + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128; k < (kb + 1) * 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(qa, 0, k, lane), + r4d_fp8::frag(wb, wave * 16, k, lane), raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const float scale = rv[j] ? sa[(rowbase + j) * KB + kb] * wsc[kb] : 0; + acc[j] += raw[j] * scale; + } + } + if (s % ksn == ksn - 1) { + const int c = colb + (s / ksn) * 64 + wave * 16 + (lane & 15); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = r0 + rowbase + j; + if (r < hi) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]); + } + acc = r4d_fp8::acc_zero(); + } + __syncthreads(); + } + } +} +// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same +// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's +// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale * +// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and +// C, so which rows and columns share a tile does not change it. + +// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at +// once, the fragments loaded straight from global memory; R row tiles share each weight fragment +// and C column tiles each activation fragment. Each wave scales its own partial products (the +// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then +// every wave folds a share of the outputs, adding the round's products in block order to the +// output's running sum, which lives in LDS between rounds. The block's activation scales are +// staged in LDS when they fit (`stage`). +template +__global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uint8_t* w, + const float* ws, uint16_t* y, Meta m, int stage) { + constexpr int SL = R * C * 8; + R4D_DYN_LDS(float, lds); + const int lane = threadIdx.x & 31, s = threadIdx.x >> 5, S = blockDim.x >> 5, h = lane >> 4; + const int c0 = blockIdx.x * 16 * C, first = (int)blockIdx.y * R * 16, KB = m.K / 128; + float* part = lds; + float* sums = part + S * SL * 32; + float* scales = sums + SL * 32; + if (stage) + for (int i = threadIdx.x; i < R * 16 * KB; i += blockDim.x) { + const int r = first + i / KB; + scales[i] = r < m.T ? as[(long)r * m.asr + i % KB] : 0; + } + for (int i = threadIdx.x; i < SL * 32; i += blockDim.x) sums[i] = 0; + const uint8_t* arow[R]; + bool alive[R]; +#pragma unroll + for (int t = 0; t < R; ++t) { + const int r = first + t * 16 + (lane & 15); + alive[t] = r < m.T; + arow[t] = a + (long)(alive[t] ? r : 0) * m.ar + h * 8; + } + __syncthreads(); + for (int k0 = 0; k0 < KB; k0 += S) { + const int kb = k0 + s; + if (kb < KB) { + r4d_fp8::i2v b[C][8]; + float weight_scale[C]; +#pragma unroll + for (int c = 0; c < C; ++c) { + const uint8_t* wrow = + w + (long)(c0 + c * 16 + (lane & 15)) * m.wr + h * 8 + (long)kb * 128; +#pragma unroll + for (int q = 0; q < 8; ++q) { + const uint2 v = *(const uint2*)(wrow + q * 16); + b[c][q][0] = (int)v.x; + b[c][q][1] = (int)v.y; + } + weight_scale[c] = ws[(long)((c0 + c * 16) / 128) * m.sr + kb]; + } +#pragma unroll + for (int t = 0; t < R; ++t) { + r4d_fp8::i2v f[8]; +#pragma unroll + for (int q = 0; q < 8; ++q) { + uint2 v = make_uint2(0, 0); + if (alive[t]) v = *(const uint2*)(arow[t] + (long)kb * 128 + q * 16); + f[q][0] = (int)v.x; + f[q][1] = (int)v.y; + } + float act[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int rr = t * 16 + h * 8 + j, r = first + rr; + act[j] = + stage ? scales[rr * KB + kb] : (r < m.T ? as[(long)r * m.asr + kb] : 0); + } +#pragma unroll + for (int c = 0; c < C; ++c) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int q = 0; q < 8; ++q) raw = r4d_fp8::mma(f[q], b[c][q], raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j; + const float scale = r < m.T ? act[j] * weight_scale[c] : 0; + part[((long)s * SL + (t * C + c) * 8 + j) * 32 + lane] = raw[j] * scale; + } + } + } + } + __syncthreads(); + for (int slot = s; slot < SL; slot += S) { + float acc = sums[slot * 32 + lane]; + for (int q = 0; q < S && k0 + q < KB; ++q) + acc += part[((long)q * SL + slot) * 32 + lane]; + sums[slot * 32 + lane] = acc; + } + __syncthreads(); + } + for (int slot = s; slot < SL; slot += S) { + const int t = slot / (C * 8), c = slot / 8 % C, j = slot % 8, + r = first + t * 16 + h * 8 + j; + if (r < m.T) + y[(long)r * m.yr + c0 + c * 16 + (lane & 15)] = f32_to_bf16(sums[slot * 32 + lane]); + } +} + +// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight +// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded +// into registers while the current one is multiplied. +template +__global__ void __launch_bounds__(128) + fp8_f32scale_rows(const uint8_t* a, const float* as, const uint8_t* w, const float* ws, + uint16_t* y, Meta m) { + constexpr int P = 136, AV = R * 16 * 8 / 128, WV = 64 * 8 / 128; + __shared__ uint8_t qa[R * 16 * P], wb[64 * P]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, h = lane >> 4, + n0 = blockIdx.x * 64; + const int first = (int)blockIdx.y * R * 16, KB = m.K / 128; + uint4 av[AV], wv[WV]; + auto load = [&](int kb) { +#pragma unroll + for (int i = 0; i < AV; ++i) { + const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16; + av[i] = first + r < m.T + ? *(const uint4*)(a + (long)(first + r) * m.ar + (long)kb * 128 + c) + : make_uint4(0, 0, 0, 0); + } +#pragma unroll + for (int i = 0; i < WV; ++i) { + const int j = tid + i * 128, r = j / 8, c = (j % 8) * 16; + wv[i] = *(const uint4*)(w + (long)(n0 + r) * m.wr + (long)kb * 128 + c); + } + }; + r4d_fp8::f8v acc[R]; +#pragma unroll + for (int t = 0; t < R; ++t) acc[t] = r4d_fp8::acc_zero(); + load(0); + for (int kb = 0; kb < KB; ++kb) { + // The 136-byte pitch keeps 8-byte alignment only, so each 16 bytes go in as two halves. + auto put = [](uint8_t* p, const uint4& v) { + ((uint2*)p)[0] = make_uint2(v.x, v.y); + ((uint2*)p)[1] = make_uint2(v.z, v.w); + }; +#pragma unroll + for (int i = 0; i < AV; ++i) { + const int j = tid + i * 128; + put(qa + (j / 8) * P + (j % 8) * 16, av[i]); + } +#pragma unroll + for (int i = 0; i < WV; ++i) { + const int j = tid + i * 128; + put(wb + (j / 8) * P + (j % 8) * 16, wv[i]); + } + __syncthreads(); + if (kb + 1 < KB) load(kb + 1); + const float weight_scale = ws[(long)(n0 / 128) * m.sr + kb]; +#pragma unroll + for (int t = 0; t < R; ++t) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = 0; k < 128; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, t * 16, k, lane), + r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j; + const float scale = r < m.T ? as[(long)r * m.asr + kb] * weight_scale : 0; + acc[t][j] += raw[j] * scale; + } + } + __syncthreads(); + } +#pragma unroll + for (int t = 0; t < R; ++t) +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int r = first + t * 16 + h * 8 + j, c = n0 + wave * 16 + (lane & 15); + if (r < m.T) y[(long)r * m.yr + c] = f32_to_bf16(acc[t][j]); + } +} + +// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a +// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C +// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical; +// the choice is speed only. +struct Form { + int kind = 0, r = 0, s = 0, c = 1; +}; // kind 0 legacy, 1 decode, 2 rows +constexpr int kLdsCap = 64 * 1024; +long decode_lds(int R, int S, int C, long KB, bool stage) { + return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4; +} +// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers +// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last +// and the exchange fits the LDS. +Form decode_plan(long N, long K, long T) { + Form f; + f.kind = 1; + const long tiles = (T + 15) / 16, kb = K / 128; + f.r = (int)(tiles >= 3 ? 3 : tiles); + const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r); + f.s = 1; + while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 && + decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap) + f.s *= 2; + return f; +} +Form dense_form(long N, long K, long T) { + if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) { + if (!std::strcmp(e, "legacy")) return Form{}; + if (!std::strncmp(e, "rows", 4)) { + Form f; + f.kind = 2; + f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4; + return f; + } + if (!std::strncmp(e, "decode", 6)) { + Form f = decode_plan(N, K, T); + int r = 0, s = 0, c = 1; + const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c); + if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 && + (c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) { + f.r = r; + f.s = s; + f.c = c; + } + return f; + } + } + // Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16 + // rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512 + // (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65 + // to 128 rows decode1x8 holds at K 4096 and the row tiles win at K 2048 and below. Among the + // row tiles (and past 128 rows) the 16-row tile beats the 64-row tile by a quarter; the 32-row + // tile wins at N 4096. + const long kb = K / 128; + Form f; + const bool rows = + T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096); + if (!rows) { + f.kind = 1; + f.r = 1; + f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1; + f.s = 8; + while (f.s > 1 && f.s > kb) f.s /= 2; + return f; + } + f.kind = 2; + f.r = T > 64 && N >= 4096 ? 2 : 1; + return f; +} +template +int emit_rows(RadStream stream, const uint8_t* xa, const float* xsa, const uint8_t* wa, + const float* wsa, uint16_t* ya, const Meta& m) { + return R4D_EMIT(stream, fp8_f32scale_rows, + dim3(m.N / 64, (unsigned)((m.T + R * 16 - 1) / (R * 16))), dim3(128), 0, xa, + xsa, wa, wsa, ya, m); +} +int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const RadTensor& w, + const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) { + *done = false; + const Form f = dense_form(m.N, m.K, m.T); + if (!f.kind || m.wr % 16 || m.ar % 16 || + (reinterpret_cast(x.data) | reinterpret_cast(w.data)) % 16) + return RAD_OK; + const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data; + const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data; + uint16_t* ya = (uint16_t*)y.data; + if (f.kind == 1) { + const long kb = m.K / 128; + const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap; + const long lds = decode_lds(f.r, f.s, f.c, kb, stage); + if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK; + *done = true; + const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)), + block(32 * f.s); +#define F32S_DECODE(R_, C_) \ + if (f.r == R_ && f.c == C_) \ + return R4D_EMIT(stream, (fp8_f32scale_decode), grid, block, (uint32_t)lds, xa, \ + xsa, wa, wsa, ya, m, stage); + F32S_DECODE(1, 1) + F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2) + F32S_DECODE(1, 4) F32S_DECODE(2, 4) +#undef F32S_DECODE + * done = false; + return RAD_OK; + } + *done = true; + if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m); + if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m); + return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m); +} +int body(const RadArgs* a, RadStream stream, bool grouped) { + if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL; + const auto &x = a->t[0], &xs = a->t[1], &w = a->t[2], &ws = a->t[3], &y = a->t[grouped ? 8 : 4]; + const int64_t N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0); + if (N < 128 || N % 128 || K < 128 || K % 128 || N > INT_MAX || K > INT_MAX || + r4d_geti_or(a, "group", 0) != 128 || r4d_geti_or(a, "pb1", 0) > 0) + return RAD_E_SHAPE; + if (x.dtype != RAD_F8E4M3 || xs.dtype != RAD_F32 || w.dtype != RAD_F8E4M3 || + ws.dtype != RAD_F32 || y.dtype != RAD_BF16) + return RAD_E_DTYPE; + if (!x.data || !xs.data || !w.data || !ws.data || !y.data || x.rank != 2 || xs.rank != 2 || + y.rank != 2 || x.shape[1] != K || xs.shape[0] != x.shape[0] || xs.shape[1] != K / 128 || + y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 || + y.shape[0] < 1 || y.shape[0] > INT_MAX) + return RAD_E_SHAPE; + const int rank = grouped ? 3 : 2; + if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K || + ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 || + ws.stride[rank - 1] != 1) + return RAD_E_SHAPE; + Meta m{}; + m.ar = x.stride[0]; + m.asr = xs.stride[0]; + m.yr = y.stride[0]; + m.wr = w.stride[rank - 2]; + m.sr = ws.stride[rank - 2]; + m.T = (int)y.shape[0]; + m.N = N; + m.K = K; + const void *w1 = nullptr, *s1 = nullptr; + const int *sorted = nullptr, *offsets = nullptr; + if (grouped) { + m.experts = r4d_geti_or(a, "n_expert", 0); + m.topk = r4d_geti_or(a, "top_k", 0); + const char* order = r4d_gets(a, "a_order"); + m.sorted_a = order && !std::strcmp(order, "sorted"); + const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5]; + if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N || + r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 || + wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K || + so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr || + so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 || + off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 || + off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data || + !so.data || !st.data || !off.data) + return RAD_E_SHAPE; + m.wstep[0] = w.stride[0]; + m.wstep[1] = wo.stride[0]; + m.sstep[0] = ws.stride[0] * 4; + m.sstep[1] = so.stride[0] * 4; + if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE; + w1 = wo.data; + s1 = so.data; + sorted = (const int*)st.data; + offsets = (const int*)off.data; + } else { + if (x.shape[0] != m.T) return RAD_E_SHAPE; + m.wstep[0] = N * m.wr; + m.sstep[0] = (N / 128) * m.sr * 4; + bool done = false; + const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done); + if (done || rc < 0) return rc; + } + m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; + if (grouped) { + /* The expert-major form at every routed-row count unless the environment bounds or + * refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8 + * slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and + * under 128 routed rows four tiles a block on top; at down's K of 256 every variant + * reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage + * and tiles can be pinned, for the microbenchmark. */ + auto env_long = [](const char* name, long dflt) { + const char* v = std::getenv(name); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS"); + const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1); + if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) { + const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256); + const long tiles = + env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1); +#define F8_EXPERTS(SK, C) \ + R4D_EMIT(stream, (fp8_f32scale_experts), \ + dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \ + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \ + offsets, (uint16_t*)y.data, m) + if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1); + return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1); +#undef F8_EXPERTS + } + } + if (grouped) + return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + m.tile - 1) / m.tile), + dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data, + ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m); + return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0, + (const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, + offsets, (uint16_t*)y.data, m); +} +int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); } +int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); } +} +extern "C" int r4d_rad_fp8_f32scale(const RadArgs* a, RadStream stream) { return dense(a, stream); } +extern "C" int r4d_rad_moe_fp8_f32scale(const RadArgs* a, RadStream stream) { + return grouped(a, stream); +} +extern "C" int r4d_layout_fp8_f32scale(const RadParam*, int, int operand, const RadEncoding* e, + const int* sel, const RadTensor*, int n, RadLayout*) { + if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED; + if (!e || !sel || n != 1 || !rad_enc_is(e, "affine") || e->n_planes != 2 || + e->plane[0].dtype != RAD_F8E4M3 || e->plane[1].dtype != RAD_F32 || + e->plane[1].block[0] != 128 || e->plane[1].block[1] != 128 || + sel[0] != (operand == 3 || operand == 7 ? 1 : 0)) + return RAD_E_DTYPE; + return RAD_E_UNSUPPORTED; // Both canonical planes are read without a relayout. +} diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 668ef541..bc176795 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -1,7 +1,7 @@ /* r4d_fuse.cpp -- the chain of unfused ops each fused kernel computes in one launch. * * `RadKernelInfo::replaces` (rad_abi.h) makes a fused row's claim to be byte-identical to the ops - * it replaces executable. Eleven of libr4d's fusions have no libref kernel, so this is their only + * it replaces executable. Most of libr4d's fusions have no libref kernel, so this is their only * oracle: a caller runs the fused row against its chain built from this plugin's own unfused rows, * and expects identical bytes, not a tolerance. * @@ -149,6 +149,16 @@ struct Step { return *this; } + Step& pf64(const char* key, double v) { + if (s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } + RadParam q{}; + q.key = key; + q.kind = RAD_P_F64; + q.dval = v; + s->p[s->n_p++] = q; + return *this; + } + Step& pstr(const char* key, const char* v) { if (!v || s->n_p >= RAD_MAX_FUSE_PARAMS) { ok = false; return *this; } RadParam q{}; @@ -306,6 +316,82 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre } } +/* ========================================================================================== + * swiglu_clamped_quant_fp8 -- GLM's clipped SwiGLU and the fp8 quantiser in one pass. + * (kernel: libr4d/r4d_glm.hip, swiglu_clamped_quant_kernel) + * + * Operands: [0] gate_up [1] q [2] scale [3] out_bf16? + * + * Each element is `swiglu_clamped_bf16`'s expression, rounded to bf16 once, and the codes are + * quant_act_fp8's over that rounded value, so the chain is the two rows with the product between. + */ +extern "C" int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + + if (!out) return RAD_E_INVAL; + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; + const int16_t mid = RAD_FUSE_HAS(present, 3) ? (int16_t)3 : RAD_FUSE_TMP(0); + + switch (step) { + case 0: { + Step s(out, "swiglu_clamped"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "limit").mirror(p, n_p, "dtype"); + return s.wire({ 0, mid }); /* gate_up, y */ + } + case 1: { + Step s(out, "quant_act_fp8"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group").mirror(p, n_p, "dtype"); + return s.wire({ mid, 1, 2 }); /* x, q, scale */ + } + default: + return RAD_E_NOTFOUND; + } +} + +/* ========================================================================================== + * router_sigmoid_topk_scatter -- GLM's selection, the sort over its ids and the shared gate's fill. + * (kernel: libr4d/r4d_glm.hip, router_sigmoid_scatter_kernel) + * + * Operands: [0] logits [1] bias [2] ids [3] weights [4] sorted_tok [5] expert_offset + * [6] expert_count [7] gate? [8] inverse? + * + * The sort runs over this rank's slice, so `moe_scatter`'s `n_expert` is the fused op's `n_local`; + * with the inverse it is `moe_scatter_inv`. The fill steps in only with the gate. + */ +extern "C" int r4d_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p, uint64_t present, + int step, RadFuseStep* out) { + + if (!out) return RAD_E_INVAL; + const int64_t ne = pi(p, n_p, "n_expert"), nl = pi(p, n_p, "n_local", ne); + if (ne <= 0 || nl <= 0 || nl > ne) return RAD_E_UNSUPPORTED; + + switch (step) { + case 0: { + Step s(out, "router_sigmoid_topk"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n_expert").mirror(p, n_p, "top_k") + .mirror(p, n_p, "norm").mirror(p, n_p, "route_scale").mirror(p, n_p, "dtype"); + return s.wire({ 0, 1, 2, 3 }); /* logits, bias, ids, weights */ + } + case 1: { + const bool inv = RAD_FUSE_HAS(present, 8) != 0; + Step s(out, inv ? "moe_scatter_inv" : "moe_scatter"); + s.mirror(p, n_p, "M").pint("n_expert", nl).mirror(p, n_p, "top_k") + .mirror_opt(p, n_p, "expert_base").mirror_opt(p, n_p, "protect"); + if (inv) return s.wire({ 2, 4, 5, 6, 8 }); /* expert_ids, sorted_tok, offset, count, inverse */ + return s.wire({ 2, 4, 5, 6 }); /* expert_ids, sorted_tok, offset, count */ + } + case 2: { + if (!RAD_FUSE_HAS(present, 7)) return RAD_E_NOTFOUND; + Step s(out, "fill"); + s.mirror(p, n_p, "M").pint("n", 1).pstr("dtype", "bf16").pf64("value", 1.0); + return s.wire({ 7 }); /* y */ + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * gate_quant_fp8 -- the same epilogue with the gate in its own operand. * (kernel: libr4d/r4d_fused_quant_fp8.hip, gate_quant_fp8_kernel) diff --git a/libr4d/r4d_glm.hip b/libr4d/r4d_glm.hip new file mode 100644 index 00000000..b8324b27 --- /dev/null +++ b/libr4d/r4d_glm.hip @@ -0,0 +1,471 @@ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_moe_sort.h" +#include +#include +#include +#include +#include + +namespace { +__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, + long yp, int n, int k) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), r = blockIdx.y; + if (col >= n) return; + float sum = 0; + for (int j = lane; j < k; j += 32) + sum = fmaf(bf16_to_f32(x[(long)r * xp + j]), w[(long)col * wp + j], sum); +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (!lane) y[(long)r * yp + col] = sum; +} + +// One wave computes R rows by C columns, so each loaded weight serves R rows and each input +// C columns. Every output keeps gemm_nt_f32_kernel's arithmetic: lane l accumulates +// k = l, l+32, ... in ascending order with fmaf, then the same xor butterfly. Tail rows and +// columns read a clamped valid address and are never stored. +template +__global__ void __launch_bounds__(128) + gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp, + int m, int n, int k) { + const int lane = threadIdx.x & 31, c0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * C, + r0 = blockIdx.y * R; + if (c0 >= n) return; + const uint16_t* xr[R]; + const float* wc[C]; +#pragma unroll + for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp; +#pragma unroll + for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp; + float sum[R][C]; +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = 0; + for (int j = lane; j < k; j += 32) { + float weight[C]; +#pragma unroll + for (int c = 0; c < C; ++c) weight[c] = wc[c][j]; +#pragma unroll + for (int q = 0; q < R; ++q) { + const float v = bf16_to_f32(xr[q][j]); +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[c], sum[q][c]); + } + } +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) { +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum[q][c] += __shfl_xor(sum[q][c], mask, 32); + } + if (lane) return; +#pragma unroll + for (int q = 0; q < R; ++q) + if (r0 + q < m) +#pragma unroll + for (int c = 0; c < C; ++c) + if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c]; +} + +// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or +// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only. +struct F32Tile { + int r, c; +}; +constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 }, + { 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } }; +F32Tile f32_tile(long rows, long n) { + if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) { + if (!std::strcmp(e, "legacy")) return { 0, 0 }; + int r = 0, c = 0; + if (std::sscanf(e, "%dx%d", &r, &c) == 2) + for (const F32Tile& t : kF32Tiles) + if (t.r == r && t.c == c) return t; + } + // Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains + // 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A + // projection of a few columns has too few waves for wide tiles at any M. + if (n <= 8) return { 4, 1 }; + if (rows <= 1) return { 0, 0 }; + if (rows <= 2) return { 2, 1 }; + if (rows < 16) return { 4, 1 }; + if (rows < 64) return { 4, 4 }; + return { 8, 4 }; +} +template +int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y, + long n, long k) { + const long m = x.shape[0]; + return R4D_EMIT(stream, (gemm_nt_f32_tile_kernel), + dim3((unsigned)((n + 4 * C - 1) / (4 * C)), (unsigned)((m + R - 1) / R)), + dim3(128), 0, (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, + x.stride[0], w.stride[0], y.stride[0], (int)m, (int)n, (int)k); +} +int gemm_f32_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &x = a->t[0], &w = a->t[1], &y = a->t[2]; + const long n = r4d_geti_or(a, "N", 0), k = r4d_geti_or(a, "K", 0); + if (x.dtype != RAD_BF16 || w.dtype != RAD_F32 || y.dtype != RAD_F32) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + if (n < 1 || n > 512 || k < 1 || k > 16384 || x.rank != 2 || w.rank != 2 || y.rank != 2 || + x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != k || w.shape[0] != n || + w.shape[1] != k || y.shape[0] != x.shape[0] || y.shape[1] != n || x.stride[1] != 1 || + w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k || + y.stride[0] < n) + return RAD_E_SHAPE; + const F32Tile t = f32_tile(x.shape[0], n); +#define R4D_F32_TILE(R, C) \ + if (t.r == R && t.c == C) return gemm_f32_tile(stream, x, w, y, n, k); + R4D_F32_TILE(1, 1) + R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2) + R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4) +#undef R4D_F32_TILE + return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0, + (const uint16_t*)x.data, (const float*)w.data, (float*)y.data, + x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k); +} +__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids, + float* weights, long lp, long bp, long ip, long wp, int ne, + int k, int norm, float factor) { + __shared__ float probabilities[512], ranking[512]; + const int r = blockIdx.x; + for (int e = threadIdx.x; e < ne; e += 256) { + const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e])); + probabilities[e] = p; + ranking[e] = p + bias[(long)e * bp]; + } + __syncthreads(); + if (threadIdx.x) return; + int index[32]; + float chosen[32], total = 0; + for (int j = 0; j < k; ++j) { + int best = 0; + for (int e = 1; e < ne; ++e) + if (ranking[e] > ranking[best]) best = e; + index[j] = best; + chosen[j] = probabilities[best]; + total += chosen[j]; + ranking[best] = -INFINITY; + } + const float mult = norm ? factor / (total + 1e-20f) : factor; + for (int j = 0; j < k; ++j) { + ids[(long)r * ip + j] = index[j]; + weights[(long)r * wp + j] = chosen[j] * mult; + } +} +// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the +// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict +// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks +// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are +// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here, +// while the scan takes expert 0 first when its rank is NaN. +// OWN is a template bound because the keys are registers; a lane-derived trip count would index +// them divergently, which gfx12 lowers to a v_movrels loop. +__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) { + uint32_t u = __float_as_uint(rank); + if (u == 0x80000000u) u = 0; + const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u); + return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull; +} +__device__ __forceinline__ unsigned long long router_wave_max(unsigned long long b) { + unsigned long long o; + o = r4d_xor_lane_u64<16>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<8>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<4>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<2>(b); + b = b > o ? b : o; + o = r4d_xor_lane_u64<1>(b); + b = b > o ? b : o; + return b; +} +// One row in one wave, from any grid: the standalone select and the fused one below run this. A +// lane below `k` returns its slot's expert as written to `ids`. +template +__device__ __forceinline__ int router_sigmoid_row(const float* logits, const float* bias, int* ids, + float* weights, long lp, long bp, long ip, + long wp, int r, int ne, int k, int norm, + float factor, int lane) { + float p[OWN]; + unsigned long long key[OWN]; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const int e = lane + 32 * i, s = e < ne ? e : 0; + p[i] = 1.0f / (1.0f + expf(-logits[(long)r * lp + s])); + key[i] = e < ne ? router_rank_key(p[i] + bias[(long)s * bp], e) : 0ull; + } + unsigned long long below = ~0ull, mine = 0; + for (int j = 0; j < k; ++j) { + unsigned long long best = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const unsigned long long c = key[i] < below ? key[i] : 0ull; + best = c > best ? c : best; + } + best = router_wave_max(best); + if (lane == j) mine = best; + below = best; + } + const int e = mine ? (int)~(uint32_t)mine : 0; + float chosen = 0; +#pragma unroll + for (int i = 0; i < OWN; ++i) { + const float v = __shfl(p[i], e & 31, 32); + if ((e >> 5) == i) chosen = v; + } + float total = 0; + for (int j = 0; j < k; ++j) + total += __int_as_float(__builtin_amdgcn_readlane(__float_as_int(chosen), j)); + const float mult = norm ? factor / (total + 1e-20f) : factor; + if (lane < k) { + ids[(long)r * ip + lane] = e; + weights[(long)r * wp + lane] = chosen * mult; + } + return e; +} +template +__global__ void __launch_bounds__(128) + router_sigmoid_wave_kernel(const float* logits, const float* bias, int* ids, float* weights, + long lp, long bp, long ip, long wp, int m, int ne, int k, int norm, + float factor) { + const int lane = threadIdx.x & 31, r = blockIdx.x * 4 + (threadIdx.x >> 5); + if (r >= m) return; + (void)router_sigmoid_row(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, norm, + factor, lane); +} +// router_sigmoid_topk, then moe_scatter over its ids, then the `fill` of an ungated shared arm's +// gate with 1, in one workgroup. Rows wrap over the NW waves; each leaves its slots in the sort's +// LDS list instead of re-reading `ids`. A slot carries the expert its row wrote, including the +// expert 0 of a row with fewer finite ranks than top_k, so every output equals the three launches'. +// INV also writes the inverse, as moe_scatter_inv does. +template +__global__ void __launch_bounds__(NW * 32) + router_sigmoid_scatter_kernel(const float* logits, const float* bias, int* ids, float* weights, + int32_t* sorted, int32_t* off, int32_t* cnt, uint16_t* gate, + int32_t* inv, long lp, long bp, long ip, long wp, long gp, int m, + int ne, int n_local, int k, int norm, float factor, int base, + r4d_moesort::Protect prot) { + __shared__ r4d_moesort::ScatterLds sl; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int e = threadIdx.x; e < n_local; e += (int)(NW * 32)) sl.cnt[e] = 0; + for (int r = wave; r < m; r += (int)NW) { + const int e = router_sigmoid_row(logits, bias, ids, weights, lp, bp, ip, wp, r, ne, k, + norm, factor, lane) - + base; + if (lane < k) + sl.e[r * k + lane] = + e >= 0 && e < n_local ? r4d_moesort::sort_place(e, (uint32_t)n_local, prot) : -1; + if (gate && !lane) gate[(long)r * gp] = f32_to_bf16(1.0f); + } + lds_barrier(); + r4d_moesort::scatter_small_place(sorted, off, cnt, (uint32_t)(m * k), + (uint32_t)n_local, sl, inv); +} +int router_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 4) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0); + const float factor = (float)r4d_getf(a, "route_scale", 0); + if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || w.dtype != RAD_F32) + return RAD_E_DTYPE; + if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 || + !lg.data || !bias.data || !ids.data || !w.data || lg.rank != 2 || lg.shape[0] < 1 || + lg.shape[0] > 65535 || lg.shape[1] != ne || bias.rank != 1 || bias.shape[0] != ne || + ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || w.shape[0] != lg.shape[0] || + ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || ids.stride[1] != 1 || + w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || w.stride[0] < k || + bias.stride[0] < 1) + return RAD_E_SHAPE; + const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); + const char* select = std::getenv("RADIANCE_ROUTER_SELECT"); + if (select && !std::strcmp(select, "old")) + return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, + (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], + (int)ne, (int)k, norm, factor); + const dim3 grid((unsigned)((lg.shape[0] + 3) / 4)); + if (ne <= 9 * 32) + return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, + (float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], + (int)lg.shape[0], (int)ne, (int)k, norm, factor); + return R4D_EMIT(stream, router_sigmoid_wave_kernel<16>, grid, dim3(128), 0, + (const float*)lg.data, (const float*)bias.data, (int*)ids.data, (float*)w.data, + lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0], (int)lg.shape[0], + (int)ne, (int)k, norm, factor); +} +/* Operands: router_sigmoid_topk's four, moe_scatter's three outputs, then the optional gate and the + * optional inverse. The sort is the single-workgroup form, so M * top_k must fit it; a larger pass + * is refused rather than served at another cost. */ +int router_scatter_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + const auto &lg = a->t[0], &bias = a->t[1], &ids = a->t[2], &w = a->t[3]; + const RadTensor *sorted = &a->t[4], *off = &a->t[5], *cnt = &a->t[6]; + const RadTensor* gate = a->n_t > 7 ? r4d_opt(a, 7) : nullptr; + const RadTensor* inv = a->n_t > 8 ? r4d_opt(a, 8) : nullptr; + const long ne = r4d_geti_or(a, "n_expert", 0), k = r4d_geti_or(a, "top_k", 0); + const long nl = r4d_geti_or(a, "n_local", ne), base = r4d_geti_or(a, "expert_base", 0); + const float factor = (float)r4d_getf(a, "route_scale", 0); + if (lg.dtype != RAD_F32 || bias.dtype != RAD_F32 || ids.dtype != RAD_I32 || + w.dtype != RAD_F32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || + cnt->dtype != RAD_I32 || (gate && gate->dtype != RAD_BF16) || + (inv && inv->dtype != RAD_I32)) + return RAD_E_DTYPE; + if (ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne || !std::isfinite(factor) || factor <= 0 || + !lg.data || !bias.data || !ids.data || !w.data || !sorted->data || !off->data || + !cnt->data || lg.rank != 2 || lg.shape[0] < 1 || lg.shape[1] != ne || bias.rank != 1 || + bias.shape[0] != ne || ids.rank != 2 || w.rank != 2 || ids.shape[0] != lg.shape[0] || + w.shape[0] != lg.shape[0] || ids.shape[1] != k || w.shape[1] != k || lg.stride[1] != 1 || + ids.stride[1] != 1 || w.stride[1] != 1 || lg.stride[0] < ne || ids.stride[0] < k || + w.stride[0] < k || bias.stride[0] < 1) + return RAD_E_SHAPE; + const long m = lg.shape[0], T = m * k; + if (T > (long)r4d_moesort::kScatterSmall || nl < 1 || nl > ne || base < 0 || base + nl > ne || + !r4d_contig(sorted) || !r4d_contig(off) || !r4d_contig(cnt) || r4d_numel(sorted) < T || + r4d_numel(off) < nl + 1 || r4d_numel(cnt) < nl || + (inv && (!r4d_contig(inv) || r4d_numel(inv) < T))) + return RAD_E_SHAPE; + long long grows = 0; + const long long gp = gate ? r4d_rows_pitch(gate, 1, &grows) : 0; + if (gate && (gp < 1 || grows < m)) return RAD_E_SHAPE; + r4d_moesort::Protect prot; + const int prc = r4d_moesort::protect_of(a, nl, &prot); + if (prc != RAD_OK) return prc; + const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0); + // A wave a row up to 32 rows, as router_topk_scatter: the rows a wave serves run back to back. + const int nw = m <= 8 ? 8 : m <= 16 ? 16 : 32; +#define R4D_RSS_I(OWN, NW, INV) \ + return R4D_EMIT(stream, (router_sigmoid_scatter_kernel), dim3(1), \ + dim3((NW) * 32), 0, (const float*)lg.data, (const float*)bias.data, \ + (int*)ids.data, (float*)w.data, (int32_t*)sorted->data, (int32_t*)off->data, \ + (int32_t*)cnt->data, gate ? (uint16_t*)gate->data : (uint16_t*)nullptr, \ + inv ? (int32_t*)inv->data : (int32_t*)nullptr, lg.stride[0], bias.stride[0], \ + ids.stride[0], w.stride[0], (long)gp, (int)m, (int)ne, (int)nl, (int)k, norm, \ + factor, (int)base, prot) +#define R4D_RSS(OWN, NW) \ + do { \ + if (inv) R4D_RSS_I(OWN, NW, true); \ + R4D_RSS_I(OWN, NW, false); \ + } while (0) + if (ne <= 9 * 32) { + if (nw == 8) R4D_RSS(9, 8u); + if (nw == 16) R4D_RSS(9, 16u); + R4D_RSS(9, 32u); + } + if (nw == 8) R4D_RSS(16, 8u); + if (nw == 16) R4D_RSS(16, 16u); + R4D_RSS(16, 32u); +#undef R4D_RSS +#undef R4D_RSS_I +} +__global__ void swiglu_clamped_kernel(const uint16_t* gu, uint16_t* y, long gp, long yp, int n, + float limit) { + const long r = blockIdx.x; + const int i = blockIdx.y * 256 + threadIdx.x; + if (i >= n) return; + const float g = fminf(bf16_to_f32(gu[r * gp + i]), limit); + const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + i]), -limit), limit); + y[r * yp + i] = f32_to_bf16((g / (1.0f + expf(-g))) * u); +} +int clamped_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 2) return RAD_E_INVAL; + const auto &gu = a->t[0], &y = a->t[1]; + const long n = r4d_geti_or(a, "n", 0); + const float limit = (float)r4d_getf(a, "limit", 0); + if (gu.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (n < 1 || n > INT_MAX / 2 || !std::isfinite(limit) || limit <= 0 || !gu.data || !y.data || + gu.rank != 2 || y.rank != 2 || y.shape[0] < 1 || y.shape[0] > 65535 || + gu.shape[0] != y.shape[0] || gu.shape[1] != 2 * n || y.shape[1] != n || gu.stride[1] != 1 || + y.stride[1] != 1 || gu.stride[0] < 2 * n || y.stride[0] < n) + return RAD_E_SHAPE; + return R4D_EMIT(stream, swiglu_clamped_kernel, dim3(y.shape[0], (n + 255) / 256), dim3(256), 0, + (const uint16_t*)gu.data, (uint16_t*)y.data, gu.stride[0], y.stride[0], (int)n, + limit); +} +// swiglu_clamped, then quant_act_fp8 over its product, in one pass: a wave per (row, 128 columns), +// four columns a lane, as the quantiser maps them. Each element is swiglu_clamped_kernel's +// expression and each group quant_act_fp8_kernel's. The product is rounded to bf16 and read back +// before the absmax because the separate quantiser reads the stored bf16 bytes. +__global__ void __launch_bounds__(256) + swiglu_clamped_quant_kernel(const uint16_t* gu, uint16_t* y, uint8_t* q, float* s, long gp, + long yp, long qp, long sp, int n, int nkb, float limit) { + const long r = blockIdx.x; + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (int kb = wave; kb < nkb; kb += (int)(blockDim.x >> 5)) { + const int c0 = kb * 128 + lane * 4; + float v[4], m = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int c = c0 + j; + v[j] = 0.0f; + if (c < n) { + const float g = fminf(bf16_to_f32(gu[r * gp + c]), limit); + const float u = fminf(fmaxf(bf16_to_f32(gu[r * gp + n + c]), -limit), limit); + const uint16_t h = f32_to_bf16((g / (1.0f + expf(-g))) * u); + if (y) y[r * yp + c] = h; + v[j] = bf16_to_f32(h); + } + } +#pragma unroll + for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); + m = r4d_wave_max(m); + const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; + if (!lane) s[r * sp + kb] = sc; + const float inv = 1.0f / sc; + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); + if (c0 < n) *(uint32_t*)(q + r * qp + c0) = (uint32_t)pk; + } +} +/* Operands: gate_up [M, 2n], q [M, n] E4M3, scale [M, ceil(n/128)] f32, out_bf16 [M, n] optional. + * n a multiple of 4 and group 128, as quant_act_fp8 requires. */ +int clamped_quant_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + const auto &gu = a->t[0], &q = a->t[1], &sc = a->t[2]; + const RadTensor* y = a->n_t > 3 ? r4d_opt(a, 3) : nullptr; + const long n = r4d_geti_or(a, "n", 0), nkb = (n + 127) / 128; + const float limit = (float)r4d_getf(a, "limit", 0); + if (gu.dtype != RAD_BF16 || q.dtype != RAD_F8E4M3 || sc.dtype != RAD_F32 || + (y && y->dtype != RAD_BF16)) + return RAD_E_DTYPE; + if (r4d_geti_or(a, "group", 128) != 128 || n < 4 || n % 4 || n > INT_MAX / 2 || + !std::isfinite(limit) || limit <= 0 || !gu.data || !q.data || !sc.data || gu.rank != 2 || + q.rank != 2 || sc.rank != 2 || gu.shape[0] < 1 || gu.shape[0] > 65535 || + gu.shape[1] != 2 * n || q.shape[0] != gu.shape[0] || q.shape[1] != n || + sc.shape[0] != gu.shape[0] || sc.shape[1] != nkb || gu.stride[1] != 1 || q.stride[1] != 1 || + sc.stride[1] != 1 || gu.stride[0] < 2 * n || q.stride[0] < n || sc.stride[0] < nkb || + (y && (y->rank != 2 || y->shape[0] != gu.shape[0] || y->shape[1] != n || + y->stride[1] != 1 || y->stride[0] < n))) + return RAD_E_SHAPE; + // A wave a group, at most eight: a row of GLM's TP8 expert width is two groups. + const unsigned thr = (unsigned)(nkb < 8 ? nkb : 8) * 32u; + return R4D_EMIT(stream, swiglu_clamped_quant_kernel, dim3((unsigned)gu.shape[0]), dim3(thr), 0, + (const uint16_t*)gu.data, y ? (uint16_t*)y->data : (uint16_t*)nullptr, + (uint8_t*)q.data, (float*)sc.data, gu.stride[0], y ? (long)y->stride[0] : 0L, + q.stride[0], sc.stride[0], (int)n, (int)nkb, limit); +} +} +extern "C" int r4d_rad_swiglu_clamped(const RadArgs* a, RadStream stream) { + return clamped_body(a, stream); +} +extern "C" int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs* a, RadStream stream) { + return clamped_quant_body(a, stream); +} +extern "C" int r4d_rad_gemm_nt_f32(const RadArgs* a, RadStream stream) { + return gemm_f32_body(a, stream); +} +extern "C" int r4d_rad_router_sigmoid_topk(const RadArgs* a, RadStream stream) { + return router_body(a, stream); +} +extern "C" int r4d_rad_router_sigmoid_topk_scatter(const RadArgs* a, RadStream stream) { + return router_scatter_body(a, stream); +} diff --git a/libr4d/r4d_kda.hip b/libr4d/r4d_kda.hip new file mode 100644 index 00000000..fdbcd799 --- /dev/null +++ b/libr4d/r4d_kda.hip @@ -0,0 +1,491 @@ +/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots. + * One wave owns one, two or four value rows and keeps each row's 128-wide state in four + * registers per lane. + * Prefill uses the same recurrence and commits only its final state. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include +#include +#include + +namespace { +struct KdaMeta { + int row[5], head[5]; + long os0, os1, ss0, ss1, ss2; + long is0, is1, cs0, as0, hs0; + int tokens, slots, width, verify, anchor; + float lower, eps, scale; +}; +struct KdaJob : KdaMeta { + const uint16_t* input[5]; + const float *alog, *bias; + float* state; + uint16_t* out; + const int *idx, *cu, *accepted, *init; +}; + +__device__ float sum(float v) { + for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32); + return __shfl(v, 0, 32); +} +/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every + * other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits + * without the broadcast. */ +template +__device__ __forceinline__ float wave_total(float v) { + if constexpr (Dpp) + return r4d_wave_sum(v); + else + return sum(v); +} +__device__ long factor_offset(long base, int logical, long pitch) { + return base + (logical / 128) * pitch + (logical % 128); +} +/* Separate dispatch: all old factor reads finish before the next window overwrites them. */ +template +__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted, + const int* init, KdaMeta m) { + const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + seq = blockIdx.z; + const int anchor = idx[(long)seq * m.is0], + scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1]; + if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch) + return; + const long fb = (long)scratch * m.ss0 + (long)head * m.ss1; + const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2; + if (init && !init[(long)seq * m.hs0]) { +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0; + return; + } + const float count = state[fb]; + const int na = accepted ? accepted[(long)seq * m.as0] : 1; + if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 || + (count > 0 && na > count)) + return; + float s[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32]; + for (int t = 0; t < (count > 0 ? na : 0); ++t) { + const int f = 1 + t * 385; + float k[4], prediction = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + d * 32; + k[d] = state[factor_offset(fb, f + c, m.ss2)]; + s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)]; + prediction += s[d] * k[d]; + } + const float delta = + state[factor_offset(fb, f + 384, m.ss2)] * + (state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total(prediction)); +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] += delta * k[d]; + } +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d]; +} +__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, + const uint16_t* g, const uint16_t* beta, const float* alog, + const float* bias, float* state_ptr, uint16_t* out, + const int* idx, const int* cu, const int* accepted_ptr, + const int* init, KdaMeta meta) { + KdaJob j{}; + static_cast(j) = meta; + j.input[0] = q; + j.input[1] = k; + j.input[2] = v; + j.input[3] = g; + j.input[4] = beta; + j.alog = alog; + j.bias = bias; + j.state = state_ptr; + j.out = out; + j.idx = idx; + j.cu = cu; + j.accepted = accepted_ptr; + j.init = init; + const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5); + const int head = blockIdx.y, seq = blockIdx.z; + const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; + const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; + if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || + accepted > (j.anchor ? 32 : j.width) || + (j.verify && end - begin > (j.anchor ? 32 : j.width))) + return; + const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; + if (read >= j.slots) return; + if (read < 0) { + if (!lane) + for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0; + return; + } + const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; + const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; + if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; + const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; + const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; + float state[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0; + const float gain = expf(j.alog[head]); + for (int t = begin; t < end; ++t) { + float q[4], k[4], decay[4], sq = 0, sk = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int channel = lane + d * 32; + q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]); + k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]); + sq += q[d] * q[d]; + sk += k[d] * k[d]; + const float raw = + bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]); + decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel])))); + } + const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps); + const float beta = + 1.0f / + (1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]]))); + float predicted = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + q[d] *= qi; + k[d] *= ki; + state[d] *= decay[d]; + predicted += state[d] * k[d]; + } + predicted = sum(predicted); + const float value = + bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]); + if (j.anchor && j.verify) { + const int f = 1 + (t - begin) * 385; + if (e == 0) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + 32 * d; + j.state[factor_offset(fb, f + c, j.ss2)] = k[d]; + j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; + } + if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta; + } + if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value; + } + const float delta = beta * (value - predicted); + float result = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + state[d] += delta * k[d]; + result += state[d] * q[d]; + } + result = sum(result); + if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result); + if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { + const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; + if (write >= 0 && write < j.slots) { + const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2; +#pragma unroll + for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d]; + } + } + } + if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; +} +/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do + * not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each + * row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda). + * With Prefetch the next token's operands are loaded while this one is reduced. */ +template +__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v, + const uint16_t* g, const uint16_t* beta, const float* alog, + const float* bias, float* state_ptr, uint16_t* out, const int* idx, + const int* cu, const int* accepted_ptr, const int* init, + KdaMeta meta) { + static_assert(32 % R == 0, "the 128 value rows split evenly over the waves"); + KdaJob j{}; + static_cast(j) = meta; + j.input[0] = q; + j.input[1] = k; + j.input[2] = v; + j.input[3] = g; + j.input[4] = beta; + j.alog = alog; + j.bias = bias; + j.state = state_ptr; + j.out = out; + j.idx = idx; + j.cu = cu; + j.accepted = accepted_ptr; + j.init = init; + const int lane = threadIdx.x & 31, e0 = (blockIdx.x * 4 + (threadIdx.x >> 5)) * R; + const int head = blockIdx.y, seq = blockIdx.z; + const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; + const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; + if (begin < 0 || end < begin || end > j.tokens || accepted < 1 || + accepted > (j.anchor ? 32 : j.width) || + (j.verify && end - begin > (j.anchor ? 32 : j.width))) + return; + const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; + if (read >= j.slots) return; + uint16_t* const out_row = j.out + (long)head * j.os1 + e0; + if (read < 0) { + if (lane < R) + for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0; + return; + } + const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; + const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; + if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; + const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; + const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; + float state[R][4]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0; + const float gain = expf(j.alog[head]); + float shift[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d]; + const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane; + const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane; + const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0; + const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane; + const uint16_t* const bb = j.input[4] + (long)head * j.head[4]; + struct Token { + uint32_t q[4], k[4], g[4], beta, value[R]; + }; + auto fetch = [&](int t, Token& o) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d); + o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d); + o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d); + } + o.beta = ldg_u16(bb + (long)t * j.row[4]); +#pragma unroll + for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r); + }; + Token cur; + if (Prefetch && begin < end) fetch(begin, cur); + for (int t = begin; t < end; ++t) { + [[maybe_unused]] Token next; + /* The last token loads itself again rather than a row past `end`. */ + if constexpr (Prefetch) + fetch(t + 1 < end ? t + 1 : t, next); + else + fetch(t, cur); + float qv[4], kv[4], decay[4], sq = 0, sk = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] = bf16w_lo(cur.q[d]); + kv[d] = bf16w_lo(cur.k[d]); + sq += qv[d] * qv[d]; + sk += kv[d] * kv[d]; + const float raw = bf16w_lo(cur.g[d]); + decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d])))); + } + const float qi = j.scale * rsqrtf(r4d_wave_sum(sq) + j.eps), + ki = rsqrtf(r4d_wave_sum(sk) + j.eps); + const float b = 1.0f / (1.0f + expf(-bf16w_lo(cur.beta))); + float predicted[R]; +#pragma unroll + for (int r = 0; r < R; ++r) predicted[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] *= qi; + kv[d] *= ki; +#pragma unroll + for (int r = 0; r < R; ++r) { + state[r][d] *= decay[d]; + predicted[r] += state[r][d] * kv[d]; + } + } + float value[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + predicted[r] = r4d_wave_sum(predicted[r]); + value[r] = bf16w_lo(cur.value[r]); + } + if (j.anchor && j.verify) { + const int f = 1 + (t - begin) * 385; + if (e0 == 0) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + 32 * d; + j.state[factor_offset(fb, f + c, j.ss2)] = kv[d]; + j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; + } + if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b; + } + if (!lane) { +#pragma unroll + for (int r = 0; r < R; ++r) + j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r]; + } + } + float result[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float delta = b * (value[r] - predicted[r]); + result[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + state[r][d] += delta * kv[d]; + result[r] += state[r][d] * qv[d]; + } + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + result[r] = r4d_wave_sum(result[r]); + if (lane == r) mine = result[r]; + } + if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine); + if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { + const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; + if (write >= 0 && write < j.slots) { + const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d]; + } + } + if constexpr (Prefetch) cur = next; + } + if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; +} + +template +bool headed(const RadTensor& t, long tokens, long heads, long dim, Pitch* row, Pitch* head) { + if (!t.data || t.dtype != RAD_BF16 || t.shape[0] != tokens || t.stride[0] > INT_MAX || + (t.rank == 3 && t.stride[1] > INT_MAX)) + return false; + if (t.rank == 3 && t.shape[1] == heads && t.shape[2] == dim && t.stride[2] == 1 && + t.stride[1] >= dim && t.stride[0] >= heads * t.stride[1]) { + *row = t.stride[0]; + *head = t.stride[1]; + return true; + } + if (t.rank == 2 && t.shape[1] == heads * dim && t.stride[1] == 1 && + t.stride[0] >= heads * dim) { + *row = t.stride[0]; + *head = dim; + return true; + } + return false; +} +bool vector(const RadTensor& t, uint32_t dt, long n) { + return t.data && t.dtype == dt && t.rank == 1 && t.shape[0] >= n && t.stride[0] == 1; +} +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 13) return RAD_E_INVAL; + const long H = r4d_geti_or(a, "heads", 0); + if (H < 1 || H > 65535 || r4d_geti_or(a, "head_k", 0) != 128 || + r4d_geti_or(a, "head_v", 0) != 128) + return RAD_E_SHAPE; + KdaJob j{}; + const auto &state = a->t[7], &idx = a->t[8], &cu = a->t[9]; + const long tokens = a->t[0].shape[0]; + if (tokens < 1 || tokens > INT_MAX || state.rank != 4 || state.dtype != RAD_F32 || + !state.data || state.shape[0] < 1 || state.shape[0] > INT_MAX || state.shape[1] != H || + state.shape[2] != 128 || state.shape[3] != 128 || state.stride[3] != 1 || + state.stride[2] < 128 || state.stride[1] < 128 * state.stride[2] || + state.stride[0] < H * state.stride[1] || cu.rank != 1 || cu.dtype != RAD_I32 || !cu.data || + cu.shape[0] < 2 || cu.shape[0] > 65536 || cu.stride[0] < 1 || idx.rank != 2 || + idx.dtype != RAD_I32 || !idx.data || idx.shape[0] < cu.shape[0] - 1 || idx.shape[1] < 1 || + idx.shape[1] > INT_MAX || idx.stride[1] < 1 || idx.stride[0] < idx.shape[1] * idx.stride[1]) + return RAD_E_SHAPE; + for (int i = 0; i < 5; ++i) { + if (!headed(a->t[i], tokens, H, i == 4 ? 1 : 128, &j.row[i], &j.head[i])) + return RAD_E_SHAPE; + j.input[i] = (const uint16_t*)a->t[i].data; + } + if (!headed(a->t[12], tokens, H, 128, &j.os0, &j.os1) || !vector(a->t[5], RAD_F32, H) || + !vector(a->t[6], RAD_F32, H * 128)) + return RAD_E_SHAPE; + const RadTensor *accepted = rad_arg_in(a, 10), *init = rad_arg_in(a, 11); + if ((accepted && !vector(*accepted, RAD_I32, cu.shape[0] - 1)) || + (init && !vector(*init, RAD_I32, cu.shape[0] - 1))) + return RAD_E_SHAPE; + const char* mode = r4d_gets(a, "mode"); + if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) return RAD_E_INVAL; + j.verify = !std::strcmp(mode, "verify"); + const char* form = r4d_gets(a, "state_form"); + j.anchor = form && !std::strcmp(form, "anchor"); + if (form && !j.anchor && std::strcmp(form, "per_candidate")) return RAD_E_INVAL; + if (j.anchor && idx.shape[1] < 2) return RAD_E_SHAPE; + j.lower = (float)r4d_getf(a, "lower_bound", 0); + j.eps = (float)r4d_getf(a, "l2_eps", 0); + j.scale = (float)r4d_getf(a, "scale", 1); + if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 || + !std::isfinite(j.scale)) + return RAD_E_SHAPE; + j.tokens = (int)tokens; + j.slots = (int)state.shape[0]; + j.width = (int)idx.shape[1]; + j.alog = (const float*)a->t[5].data; + j.bias = (const float*)a->t[6].data; + j.state = (float*)state.data; + j.out = (uint16_t*)a->t[12].data; + j.ss0 = state.stride[0]; + j.ss1 = state.stride[1]; + j.ss2 = state.stride[2]; + j.idx = (const int*)idx.data; + j.is0 = idx.stride[0]; + j.is1 = idx.stride[1]; + j.cu = (const int*)cu.data; + j.cs0 = cu.stride[0]; + if (accepted) { + j.accepted = (const int*)accepted->data; + j.as0 = accepted->stride[0]; + } + if (init) { + j.init = (const int*)init->data; + j.hs0 = init->stride[0]; + } + /* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest + * holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and + * RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */ + const char* kform = std::getenv("RADIANCE_KDA_FORM"); + const bool old = kform && !std::strcmp(kform, "old"); + const unsigned seqs = (unsigned)(cu.shape[0] - 1); + if (j.anchor && j.verify) { + const int rc = + old ? R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), + 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)) + : R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), + 0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + if (rc != RAD_OK) return rc; + } + if (old) + return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, + j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias, + j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + const char* rows_env = std::getenv("RADIANCE_KDA_ROWS"); + const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4; + const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH"); + const bool prefetch = !prefetch_env || prefetch_env[0] != '0'; +#define KDA_ROWS(RR, PF) \ + return R4D_EMIT(stream, (kda_rows_kernel), dim3(32 / RR, (unsigned)H, seqs), \ + dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \ + j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \ + static_cast(j)) + if (rows == 1) { + if (prefetch) KDA_ROWS(1, true); + KDA_ROWS(1, false); + } + if (rows == 2) { + if (prefetch) KDA_ROWS(2, true); + KDA_ROWS(2, false); + } + if (prefetch) KDA_ROWS(4, true); + KDA_ROWS(4, false); +#undef KDA_ROWS +} +} +extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 88b34adb..6ef46f6f 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -1197,6 +1197,23 @@ extern "C" int r4d_rad_unrelayout_moe_w4_mod4(const RadParam* p, int n_p, int op return moew4_unrelayout_by(moe_view_mod4, p, n_p, operand, enc, sel, src, src_bytes, pl, n); } +extern "C" int r4d_rad_layout_moe_mxfp4(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout*) { + if (operand != 2 && operand != 3 && operand != 6 && operand != 7) return RAD_E_UNSUPPORTED; + if (!r4d_enc::affine(enc, RAD_FP4E2M1, RAD_E8M0, 1, 32)) return RAD_E_DTYPE; + MoeView v; + const int rc = moe_view(p, n_p, operand, &v); + if (rc != RAD_OK) return rc; + const long long N = r4d_pgeti_or(v.p, v.n, "N", 0), K = r4d_pgeti_or(v.p, v.n, "K", 0); + const bool scale = operand == 3 || operand == 7; + if (n != 1 || !pl || !sel || !selects(enc, sel, n, scale ? "scale" : "codes") || + !dims(pl[0], N, scale ? K / 32 : K) || K % 128) return RAD_E_SHAPE; + /* The exact selected canonical plane, not a relayout: it remains readable in place + * from the container or a mapped host pool. Unsupported is the ABI spelling for that. */ + return RAD_E_UNSUPPORTED; +} + extern "C" int r4d_rad_layout_moe_fp8(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, RadLayout* out) { diff --git a/libr4d/r4d_mhc.hip b/libr4d/r4d_mhc.hip new file mode 100644 index 00000000..53a2b8ea --- /dev/null +++ b/libr4d/r4d_mhc.hip @@ -0,0 +1,731 @@ +/* GLM's mHC, kept separate from the Qwen gated-residual kernels. The GLM shape + * projects in parallel before one workgroup per token forms the Sinkhorn matrix. + * Mixing weights are declared f32; activations are bf16, coefficients stay f32. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include +#include +#include +#include + +namespace { +__device__ float warp_sum(float v) { + for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32); + return v; +} + +// The final collapsed output is large enough to hold the projection partials +// until the finishing kernel has read them. Align within each pitched row. +__device__ float* partials(uint16_t* x, long row, long pitch) { + return reinterpret_cast((reinterpret_cast(x + row * pitch) + 3) & + ~uintptr_t(3)); +} +// Where projection partial (row, coefficient j, chunk) lives: inside the collapsed output's rows +// (mhc_pre), or a separate [rows][chunk][stride] matrix (mhc_pre_partial writes this rank's chunks +// from `first`, mhc_pre_finish reads every rank's after the gather). Kernels differ in address only. +// `pad` clears a Dense chunk's slots past the last partial, so the gathered payload is defined. +struct InX { + uint16_t* x; + long xp; + int chunks; + __device__ float* at(long row, int j, int chunk) const { + return partials(x, row, xp) + j * chunks + chunk; + } + __device__ void pad(long, int, int) const {} +}; +struct Dense { + float* p; + long pp; + int stride, first; + __device__ float* at(long row, int j, int chunk) const { + return p + row * pp + (long)(chunk - first) * stride + j; + } + __device__ void pad(long row, int last, int chunk) const { + for (int j = last + 1; j < stride; ++j) *at(row, j, chunk) = 0; + } +}; +template +__global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out, int width, int mix, + int chunk0, long hp, long fp) { + __shared__ float sums[4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int j = blockIdx.y, chunk = chunk0 + blockIdx.x; + const long row = blockIdx.z; + float sum = 0; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + const float v = bf16_to_f32(h[row * hp + i]); + sum += v * (j == mix ? v : fn[(long)j * fp + i]); + } + sum = warp_sum(sum); + if (!lane) sums[wave] = sum; + __syncthreads(); + if (!tid) { + *out.at(row, j, chunk) = sums[0] + sums[1] + sums[2] + sums[3]; + if (j == mix) out.pad(row, mix, chunk); + } +} + +// Prefill reuses each F32 mixing weight across four BF16 token rows. +// Each row keeps the same accumulation and reduction order as the scalar-row path. +template +__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width, + int mix, int chunk0, long hp, long fp, long rows) { + __shared__ float sums[4][4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int j = blockIdx.y, chunk = chunk0 + blockIdx.x; + const long first = (long)blockIdx.z * 4; + float sum[4] = { 0, 0, 0, 0 }; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + const float weight = j == mix ? 0 : fn[(long)j * fp + i]; +#pragma unroll + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + const float v = bf16_to_f32(h[(first + r) * hp + i]); + sum[r] += v * (j == mix ? v : weight); + } + } +#pragma unroll + for (int r = 0; r < 4; ++r) { + sum[r] = warp_sum(sum[r]); + if (!lane) sums[r][wave] = sum[r]; + } + __syncthreads(); + if (!tid) + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + *out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3]; + if (j == mix) out.pad(first + r, mix, chunk); + } +} + +// Reuse each input across four coefficients and each weight across four rows. +// All per-output K accumulation and reduction orders match the rows4 path. +template +__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out, + int width, int mix, int chunk0, long hp, long fp, + long rows) { + __shared__ float sums[4][4][4]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int first_j = blockIdx.y * 4, chunk = chunk0 + blockIdx.x; + const long first = (long)blockIdx.z * 4; + float sum[4][4]{}; + for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) { + float weight[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + weight[q] = first_j + q < mix ? fn[(long)(first_j + q) * fp + i] : 0; +#pragma unroll + for (int r = 0; r < 4; ++r) + if (first + r < rows) { + const float v = bf16_to_f32(h[(first + r) * hp + i]); +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) sum[q][r] += v * (first_j + q == mix ? v : weight[q]); + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int r = 0; r < 4; ++r) { + sum[q][r] = warp_sum(sum[q][r]); + if (!lane) sums[q][r][wave] = sum[q][r]; + } + } + __syncthreads(); + if (tid < 16) { + const int q = tid / 4, r = tid % 4; + if (first_j + q <= mix && first + r < rows) { + *out.at(first + r, first_j + q, chunk) = + sums[q][r][0] + sums[q][r][1] + sums[q][r][2] + sums[q][r][3]; + if (first_j + q == mix) out.pad(first + r, mix, chunk); + } + } +} + +// The collapsed read x[i] = sum_j pre[j] * h[j*n + i] eight columns a thread, in 16-byte loads +// and stores. Each element keeps the scalar loop's order (from zero, j ascending), so its bits +// are the same; false when the rows are not 16-byte aligned, and the caller runs its own loop. +__device__ __forceinline__ bool mix_rows_vec(const uint16_t* hr, uint16_t* xr, const float* pre, + int n, int hc, int tid, int nt) { + if ((((uintptr_t)hr | (uintptr_t)xr) & 15) || (n & 7)) return false; + for (int i = tid * 8; i < n; i += nt * 8) { + float v[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int j = 0; j < hc; ++j) { + const uint4 q = *reinterpret_cast(hr + (long)j * n + i); + const uint32_t w[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < 8; ++e) + v[e] += pre[j] * bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1)))); + } + uint32_t o[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) + o[e] = (uint32_t)f32_to_bf16(v[2 * e]) | ((uint32_t)f32_to_bf16(v[2 * e + 1]) << 16); + *reinterpret_cast(xr + i) = uint4{ o[0], o[1], o[2], o[3] }; + } + return true; +} + +// The projection partials four slots a lane. The kernels above give each of 128 threads one slot +// s, the sum over the chunk's columns s, s+128, ... in order; here lane L holds slots 4L..4L+3, +// so a row is read 8 bytes and a weight 16 bytes a load, and one wave does a whole block's work. +// Their reduction is replayed exactly: warp_sum pairs slot l with l+16, l+8, l+4, l+2 and l+1, +// here lanes +4, +2, +1 and then the lane's own slots, and the four waves' sums, at lanes 0, 8, +// 16 and 24, are added in order. R rows and four coefficients a wave, four independent waves a +// block, no barrier. +template +__global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h, const float* fn, + Out out, int mix, int chunk0, + int count, long hp, long fp, + long rows, long items) { + const int lane = threadIdx.x & 31; + const long item = (long)blockIdx.x * 4 + (threadIdx.x >> 5); + if (item >= items) return; + const int groups = (mix + 4) / 4; + const int chunk = chunk0 + (int)(item % count); + const int first_j = (int)((item / count) % groups) * 4; + const long first = item / count / groups * R; + float acc[4][R][4]{}; + for (int t = 0; t < 16; ++t) { + const int col = chunk * 2048 + t * 128 + lane * 4; + float w[4][4]; +#pragma unroll + for (int q = 0; q < 4; ++q) { + const float4 v = + first_j + q < mix + ? *reinterpret_cast(fn + (long)(first_j + q) * fp + col) + : float4{ 0, 0, 0, 0 }; + w[q][0] = v.x; + w[q][1] = v.y; + w[q][2] = v.z; + w[q][3] = v.w; + } +#pragma unroll + for (int r = 0; r < R; ++r) + if (first + r < rows) { + const uint2 hv = *reinterpret_cast(h + (first + r) * hp + col); + const float v[4] = { bf16_to_f32((uint16_t)hv.x), + bf16_to_f32((uint16_t)(hv.x >> 16)), + bf16_to_f32((uint16_t)hv.y), + bf16_to_f32((uint16_t)(hv.y >> 16)) }; +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int u = 0; u < 4; ++u) + acc[q][r][u] += v[u] * (first_j + q == mix ? v[u] : w[q][u]); + } + } + } +#pragma unroll + for (int q = 0; q < 4; ++q) + if (first_j + q <= mix) { +#pragma unroll + for (int r = 0; r < R; ++r) + if (first + r < rows) { + float c[4]; +#pragma unroll + for (int u = 0; u < 4; ++u) { + float a = acc[q][r][u]; + a += __shfl_down(a, 4, 32); + a += __shfl_down(a, 2, 32); + a += __shfl_down(a, 1, 32); + c[u] = a; + } + const float e0 = c[0] + c[2], e1 = c[1] + c[3], f = e0 + e1; + const float s1 = __shfl(f, 8, 32), s2 = __shfl(f, 16, 32), + s3 = __shfl(f, 24, 32); + if (!lane) { + *out.at(first + r, first_j + q, chunk) = f + s1 + s2 + s3; + if (first_j + q == mix) out.pad(first + r, mix, chunk); + } + } + } +} + +template +__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale, + const float* base, uint16_t* x, float* post, float* comb, int n, + int hc, int iterations, float eps, float heps, long hp, long fp, + long xp, long pp, long cp, int chunks, In in) { + __shared__ float sums[8], inverse, coefficients[80], pre[8], c[64]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const long r = blockIdx.x; + const int width = hc * n, mix = hc * (hc + 2); + float ss = 0; + for (int i = tid; !chunks && i < width; i += 256) { + const float v = bf16_to_f32(h[r * hp + i]); + ss += v * v; + } + ss = warp_sum(ss); + if (!lane) sums[wave] = ss; + __syncthreads(); + if (!tid) { + float s = 0; + if (chunks) + for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i); + else + for (int i = 0; i < 8; ++i) s += sums[i]; + inverse = rsqrtf(s / (float)width + eps); + } + __syncthreads(); + for (int j = wave; j < mix; j += 8) { + float dot = 0; + if (chunks) + for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i); + else + for (int i = lane; i < width; i += 32) + dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i]; + dot = warp_sum(dot); + if (!lane) coefficients[j] = dot * inverse; + } + __syncthreads(); + if (!tid) { + for (int j = 0; j < hc; ++j) { + pre[j] = 1.0f / (1.0f + expf(-(coefficients[j] * scale[0] + base[j]))) + heps; + post[r * pp + j] = + 2.0f / (1.0f + expf(-(coefficients[hc + j] * scale[1] + base[hc + j]))); + } + for (int j = 0; j < hc; ++j) { + float mx = -INFINITY; + for (int k = 0; k < hc; ++k) { + const int q = 2 * hc + j * hc + k; + c[j * hc + k] = coefficients[q] * scale[2] + base[q]; + mx = fmaxf(mx, c[j * hc + k]); + } + float sum = 0; + for (int k = 0; k < hc; ++k) { + c[j * hc + k] = expf(c[j * hc + k] - mx); + sum += c[j * hc + k]; + } + for (int k = 0; k < hc; ++k) c[j * hc + k] = c[j * hc + k] / sum + heps; + } + for (int it = 0; it < iterations; ++it) { + if (it) + for (int j = 0; j < hc; ++j) { + float sum = 0; + for (int k = 0; k < hc; ++k) sum += c[j * hc + k]; + for (int k = 0; k < hc; ++k) c[j * hc + k] /= sum + heps; + } + for (int k = 0; k < hc; ++k) { + float sum = 0; + for (int j = 0; j < hc; ++j) sum += c[j * hc + k]; + for (int j = 0; j < hc; ++j) c[j * hc + k] /= sum + heps; + } + } + for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j]; + } + __syncthreads(); + if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return; + for (int i = tid; i < n; i += 256) { + float v = 0; + for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]); + x[r * xp + i] = f32_to_bf16(v); + } +} + +// One wave handles GLM's 4x4 Sinkhorn matrix. Keep row/column sums in the +// scalar reference order; the other rows never participate in these shuffles. +// Writes post and comb; returns pre[lane] in lanes 0..3. +template +__device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* scale, + const float* base, float* post, float* comb, + int iterations, float eps, float heps, long pp, + long cp, const In& in) { + float inverse = 0; + if (!lane) { + float ss = 0; + for (int i = 0; i < 8; ++i) ss += *in.at(row, 24, i); + inverse = rsqrtf(ss / 16384.0f + eps); + } + inverse = __shfl(inverse, 0, 32); + float dot = 0; + if (lane < 24) { + float v[8]; + for (int i = 0; i < 8; ++i) v[i] = *in.at(row, lane, i); + // The existing eight-chunk warp reduction pairs 0/4, 2/6, 1/5, 3/7. + dot = ((v[0] + v[4]) + (v[2] + v[6])) + ((v[1] + v[5]) + (v[3] + v[7])); + } + const float coefficient = dot * inverse; + const float post_coefficient = __shfl(coefficient, (lane + 4) & 31, 32); + const float matrix_coefficient = __shfl(coefficient, (lane + 8) & 31, 32); + float pre = 0; + if (lane < 4) { + pre = 1.0f / (1.0f + expf(-(coefficient * scale[0] + base[lane]))) + heps; + post[row * pp + lane] = + 2.0f / (1.0f + expf(-(post_coefficient * scale[1] + base[4 + lane]))); + } + float value = lane < 16 ? matrix_coefficient * scale[2] + base[8 + lane] : 0; + const int row_base = lane & ~3, col = lane & 3; + float mx = -INFINITY; +#pragma unroll + for (int j = 0; j < 4; ++j) mx = fmaxf(mx, __shfl(value, row_base + j, 32)); + value = expf(value - mx); + float sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32); + value = value / sum + heps; + for (int it = 0; it < iterations; ++it) { + if (it) { + sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, row_base + j, 32); + value /= sum + heps; + } + sum = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) sum += __shfl(value, col + 4 * j, 32); + value /= sum + heps; + } + if (lane < 16) comb[row * cp + lane] = value; + return pre; +} +template +__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base, + uint16_t* x, float* post, float* comb, int iterations, + float eps, float heps, long hp, long xp, long pp, long cp, + In in) { + const int lane = threadIdx.x; + const long row = blockIdx.x; + const float pre = + glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in); + const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32), + p3 = __shfl(pre, 3, 32); + for (int i = lane; i < 4096; i += 32) { + float v = 0; + v += p0 * bf16_to_f32(h[row * hp + i]); + v += p1 * bf16_to_f32(h[row * hp + 4096 + i]); + v += p2 * bf16_to_f32(h[row * hp + 8192 + i]); + v += p3 * bf16_to_f32(h[row * hp + 12288 + i]); + x[row * xp + i] = f32_to_bf16(v); + } +} + +// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing +// 4096 columns a row was most of a decode step's mhc_pre. +template +__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel( + const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb, + int iterations, float eps, float heps, long hp, long xp, long pp, long cp, In in) { + __shared__ float spre[4]; + const int tid = threadIdx.x; + const long row = blockIdx.x; + if (tid < 32) { + const float pre = + glm_warp_mix(tid, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in); + if (tid < 4) spre[tid] = pre; + } + __syncthreads(); + const float pre[4] = { spre[0], spre[1], spre[2], spre[3] }; + if (mix_rows_vec(h + row * hp, x + row * xp, pre, 4096, 4, tid, 256)) return; + for (int i = tid; i < 4096; i += 256) { + float v = 0; + v += pre[0] * bf16_to_f32(h[row * hp + i]); + v += pre[1] * bf16_to_f32(h[row * hp + 4096 + i]); + v += pre[2] * bf16_to_f32(h[row * hp + 8192 + i]); + v += pre[3] * bf16_to_f32(h[row * hp + 12288 + i]); + x[row * xp + i] = f32_to_bf16(v); + } +} + +__global__ void mhc_post_kernel(const uint16_t* x, const uint16_t* h, const float* post, + const float* comb, uint16_t* out, int n, int hc, long xp, long hp, + long pp, long cp, long op) { + const long r = blockIdx.y; + const int q = blockIdx.x * blockDim.x + threadIdx.x; + if (q >= n * hc) return; + const int k = q / n, i = q % n; + float v = 0; + for (int j = 0; j < hc; ++j) + v += comb[r * cp + j * hc + k] * bf16_to_f32(h[r * hp + j * n + i]); + v += post[r * pp + k] * bf16_to_f32(x[r * xp + i]); + out[r * op + q] = f32_to_bf16(v); +} + +// mhc_post at four streams, eight columns of every output stream a thread: each input word is +// loaded once instead of once per output stream. Every output keeps mhc_post_kernel's order. +__global__ void mhc_post_vec_kernel(const uint16_t* x, const uint16_t* h, const float* post, + const float* comb, uint16_t* out, int n, long xp, long hp, + long pp, long cp, long op) { + const long r = blockIdx.y; + const int i = (blockIdx.x * blockDim.x + threadIdx.x) * 8; + if (i >= n) return; + float hv[4][8], xv[8]; + auto unpack = [](const uint16_t* p, float* v) { + const uint4 q = *reinterpret_cast(p); + const uint32_t w[4] = { q.x, q.y, q.z, q.w }; +#pragma unroll + for (int e = 0; e < 8; ++e) v[e] = bf16_to_f32((uint16_t)(w[e >> 1] >> (16 * (e & 1)))); + }; +#pragma unroll + for (int j = 0; j < 4; ++j) unpack(h + r * hp + (long)j * n + i, hv[j]); + unpack(x + r * xp + i, xv); +#pragma unroll + for (int k = 0; k < 4; ++k) { + float c[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) c[j] = comb[r * cp + j * 4 + k]; + const float pk = post[r * pp + k]; + uint32_t o[4]; +#pragma unroll + for (int e = 0; e < 8; e += 2) { + float v0 = 0, v1 = 0; +#pragma unroll + for (int j = 0; j < 4; ++j) { + v0 += c[j] * hv[j][e]; + v1 += c[j] * hv[j][e + 1]; + } + v0 += pk * xv[e]; + v1 += pk * xv[e + 1]; + o[e >> 1] = (uint32_t)f32_to_bf16(v0) | ((uint32_t)f32_to_bf16(v1) << 16); + } + *reinterpret_cast(out + r * op + (long)k * n + i) = uint4{ o[0], o[1], o[2], o[3] }; + } +} + +__global__ void mhc_contract_kernel(const uint16_t* h, uint16_t* x, int n, int hc, long hp, + long xp) { + const long r = blockIdx.y; + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= n) return; + float v = 0; + for (int j = 0; j < hc; ++j) v += bf16_to_f32(h[r * hp + j * n + i]); + x[r * xp + i] = f32_to_bf16(v / (float)hc); +} + +bool matrix(const RadTensor& t, uint32_t dt, long rows, long cols) { + return t.data && t.dtype == dt && t.rank == 2 && t.shape[0] == rows && t.shape[1] == cols && + t.stride[1] == 1 && t.stride[0] >= cols; +} +bool vector(const RadTensor& t, long n) { + return t.data && t.dtype == RAD_F32 && t.rank == 1 && t.shape[0] == n && t.stride[0] == 1; +} +bool geometry(const RadArgs* a, int* n, int* hc) { + const long nn = r4d_geti_or(a, "n", 0), hh = r4d_geti_or(a, "hc", 0); + if (nn < 1 || nn > 16384 || hh < 2 || hh > 8) return false; + *n = (int)nn; + *hc = (int)hh; + return true; +} +// GLM's split projection: eight 2048-column chunks of the 16384-wide residual, 24 coefficients +// and the sum of squares each. A Dense chunk holds those 25 partials in kPartStride slots. +constexpr int kChunkCols = 2048, kPartStride = 28; +template +int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc, + int chunk0, int count, long rows) { + const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4"); + const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4"); + /* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count; + * RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte + * residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: + * one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48 + * (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave + * trail two at every count. */ + const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC"); + const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 && + ((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 && + hc * n % kChunkCols == 0; + if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) { + const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS"); + const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10) + : rows >= 32 ? 2 + : 1; + const int mix = hc * (hc + 2), groups = (mix + 4) / 4; +#define MHC_VEC(RR) \ + do { \ + const long items = (long)count * groups * ((rows + RR - 1) / RR); \ + return R4D_EMIT(stream, (mhc_partial_vec_kernel), \ + dim3((unsigned)((items + 3) / 4)), dim3(128), 0, (const uint16_t*)h.data, \ + (const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \ + (long)fn.stride[0], rows, items); \ + } while (0) + if (R == 4) MHC_VEC(4); + if (R == 2) MHC_VEC(2); + MHC_VEC(1); +#undef MHC_VEC + } + const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN"); + const bool use_rows4 = + (!rows4 || rows4[0] == '1') && + rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32); + if (use_rows4 && (!coeff4 || coeff4[0] == '1')) + return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel), + dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128), + 0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, + hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows); + if (use_rows4) + return R4D_EMIT(stream, (mhc_partial_rows4_kernel), + dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0, + (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), + chunk0, (long)h.stride[0], (long)fn.stride[0], rows); + return R4D_EMIT(stream, (mhc_partial_kernel), + dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0, + (const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2), + chunk0, (long)h.stride[0], (long)fn.stride[0]); +} +// The finishing dispatch. `split` says the partials exist (in `in`); without them +// mhc_pre_kernel projects the residual itself from `fn`. +template +int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s, + const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c, + int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split, + In in) { + const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP"); + /* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time + * at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish + * from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */ + const char* form = std::getenv("RADIANCE_MHC_FINISH"); + const bool old = form && !std::strcmp(form, "old"); + const bool warp_mix = split && (warp ? warp[0] == '1' : true) && + (old ? rows >= 32 : !(form && !std::strcmp(form, "scalar"))); + if (warp_mix && old) + return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel), dim3((unsigned)rows), dim3(32), 0, + (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, + (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + in); + if (warp_mix) + return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps, + (long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + in); + if (old) + return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, + (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], + (long)c.stride[0], split ? chunks : 0, in); + return R4D_EMIT(stream, (mhc_pre_kernel), dim3((unsigned)rows), dim3(256), 0, + (const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data, + (uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps, + (long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0], + split ? chunks : 0, in); +} +bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) { + *iters = r4d_geti_or(a, "iterations", 0); + *eps = (float)r4d_getf(a, "eps", 0); + *heps = (float)r4d_getf(a, "hc_eps", 0); + return *iters >= 1 && *iters <= 256 && std::isfinite(*eps) && std::isfinite(*heps) && + *eps > 0 && *heps >= 0; +} +// mhc_pre_partial and mhc_pre_finish serve GLM's split geometry only. +bool glm_chunks(const RadArgs* a, int n, int hc) { + return n == 4096 && hc == 4 && r4d_geti_or(a, "chunk", 0) == kChunkCols; +} +int pre_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + long iters; + float eps, heps; + if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &s = a->t[2], &b = a->t[3]; + const auto &x = a->t[4], &p = a->t[5], &c = a->t[6]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > INT_MAX) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) || + !vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc)) + return RAD_E_SHAPE; + const int chunks = (hc * n + kChunkCols - 1) / kChunkCols; + const bool split = + n == 4096 && hc == 4 && rows <= 65535 && (hc * (hc + 2) + 1) * chunks * 4 + 2 <= n * 2; + const InX in{ (uint16_t*)x.data, (long)x.stride[0], chunks }; + if (split) { + const int rc = emit_partials(stream, h, fn, in, n, hc, 0, chunks, rows); + if (rc < 0) return rc; + } + return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc, + (int)iters, eps, heps, rows, chunks, split, in); +} +int partial_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE; + const int total = hc * n / kChunkCols; + const long first = r4d_geti_or(a, "first", -1), count = r4d_geti_or(a, "chunks", 0); + if (first < 0 || count < 1 || first + count > total) return RAD_E_SHAPE; + const auto &h = a->t[0], &fn = a->t[1], &part = a->t[2]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(fn, RAD_F32, hc * (hc + 2), hc * n) || + !matrix(part, RAD_F32, rows, count * kPartStride)) + return RAD_E_SHAPE; + const Dense out{ (float*)part.data, (long)part.stride[0], kPartStride, (int)first }; + return emit_partials(stream, h, fn, out, n, hc, (int)first, (int)count, rows); +} +int finish_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc) || !glm_chunks(a, n, hc)) return RAD_E_SHAPE; + long iters; + float eps, heps; + if (!coefficients(a, &iters, &eps, &heps)) return RAD_E_SHAPE; + const int chunks = hc * n / kChunkCols; + const auto &part = a->t[0], &h = a->t[1], &s = a->t[2], &b = a->t[3]; + const auto &x = a->t[4], &p = a->t[5], &c = a->t[6]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(part, RAD_F32, rows, chunks * kPartStride) || !matrix(h, RAD_BF16, rows, hc * n) || + !vector(s, 3) || !vector(b, hc * (hc + 2)) || !matrix(x, RAD_BF16, rows, n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc)) + return RAD_E_SHAPE; + const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 }; + return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows, + chunks, true, in); +} +int post_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + const auto &x = a->t[0], &h = a->t[1], &p = a->t[2], &c = a->t[3], &o = a->t[4]; + if (x.rank != 2 || x.shape[0] < 1 || x.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = x.shape[0]; + if (!matrix(x, RAD_BF16, rows, n) || !matrix(h, RAD_BF16, rows, hc * n) || + !matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) || + !matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data) + return RAD_E_SHAPE; + /* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */ + const char* vec = std::getenv("RADIANCE_MHC_POST_VEC"); + const auto aligned = [](const RadTensor& t) { + return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0; + }; + if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o)) + return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows), + dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data, + (const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n, + (long)x.stride[0], (long)h.stride[0], (long)p.stride[0], (long)c.stride[0], + (long)o.stride[0]); + return R4D_EMIT(stream, mhc_post_kernel, dim3((n * hc + 255) / 256, (unsigned)rows), dim3(256), + 0, (const uint16_t*)x.data, (const uint16_t*)h.data, (const float*)p.data, + (const float*)c.data, (uint16_t*)o.data, n, hc, (long)x.stride[0], + (long)h.stride[0], (long)p.stride[0], (long)c.stride[0], (long)o.stride[0]); +} +int contract_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 2) return RAD_E_INVAL; + int n, hc; + if (!geometry(a, &n, &hc)) return RAD_E_SHAPE; + const auto &h = a->t[0], &x = a->t[1]; + if (h.rank != 2 || h.shape[0] < 1 || h.shape[0] > 65535) return RAD_E_SHAPE; + const long rows = h.shape[0]; + if (!matrix(h, RAD_BF16, rows, hc * n) || !matrix(x, RAD_BF16, rows, n)) return RAD_E_SHAPE; + return R4D_EMIT(stream, mhc_contract_kernel, dim3((n + 255) / 256, (unsigned)rows), dim3(256), + 0, (const uint16_t*)h.data, (uint16_t*)x.data, n, hc, (long)h.stride[0], + (long)x.stride[0]); +} +} +extern "C" int r4d_rad_mhc_pre(const RadArgs* a, RadStream stream) { return pre_body(a, stream); } +extern "C" int r4d_rad_mhc_pre_partial(const RadArgs* a, RadStream stream) { + return partial_body(a, stream); +} +extern "C" int r4d_rad_mhc_pre_finish(const RadArgs* a, RadStream stream) { + return finish_body(a, stream); +} +extern "C" int r4d_rad_mhc_post(const RadArgs* a, RadStream stream) { return post_body(a, stream); } +extern "C" int r4d_rad_mhc_contract(const RadArgs* a, RadStream stream) { + return contract_body(a, stream); +} diff --git a/libr4d/r4d_mla.hip b/libr4d/r4d_mla.hip new file mode 100644 index 00000000..710c1a35 --- /dev/null +++ b/libr4d/r4d_mla.hip @@ -0,0 +1,700 @@ +/* Absorbed MLA keeps a single 512-wide latent per token. Decode splits the + * selected history across waves, then merges FP32 softmax statistics. It never + * materializes per-head K/V in the growing cache. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_gdn_wmma.h" +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct ProjectMeta { + long xr, xh, wp, yr, yh; + int rows, heads; +}; +/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */ +__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { + const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z; + if (col >= 512) return; + float sum = 0; + for (int j = 0; j < 256; ++j) + sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), + bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum); + y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); +} +__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + r = blockIdx.z; + float sum = 0; + for (int j = lane; j < 512; j += 32) + sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]), + bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum); +#pragma unroll + for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32); + if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum); +} +/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight + * element is loaded once for R rows. Every row's sum runs over j in the same order, and + * r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels. + * A tail group past the last row reads that row again and stores nothing for it. */ +template +__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, + ProjectMeta m) { + const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r0 = blockIdx.z * R; + if (col >= 512) return; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = 0; j < 256; ++j) { + const float wv = bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]); + } +#pragma unroll + for (int r = 0; r < R; ++r) + if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + head * m.yh + col] = f32_to_bf16(sum[r]); +} +template +__global__ void project_expand_rows(const uint16_t* x, const uint16_t* w, uint16_t* y, + ProjectMeta m) { + const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y, + r0 = blockIdx.z * R; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) xr[r] = x + (long)min(r0 + r, m.rows - 1) * m.xr + head * m.xh; + const uint16_t* const wr = w + ((long)head * 512 + 256 + col) * m.wp; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = lane; j < 512; j += 32) { + const float wv = bf16_to_f32(wr[j]); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32(xr[r][j]), wv, sum[r]); + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + sum[r] = r4d_xor_sum<32>(sum[r]); + if (lane == r) mine = sum[r]; + } + if (lane < R && r0 + lane < m.rows) + y[(long)(r0 + lane) * m.yr + head * m.yh + col] = f32_to_bf16(mine); +} +int project_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return RAD_E_INVAL; + RadTensor x = a->t[0], y = a->t[2]; + const auto& w = a->t[1]; + const char* mode = r4d_gets(a, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + const long h = r4d_geti_or(a, "heads", 0); + auto heads_view = [&](RadTensor& t, long width) { + if (h > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(x, absorb ? 256 : 512); + heads_view(y, absorb ? 512 : 256); + if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) return RAD_E_DTYPE; + if (!x.data || !w.data || !y.data) return RAD_E_INVAL; + if ((!absorb && !expand) || h < 1 || h > 64 || r4d_geti_or(a, "head_dim", 0) != 256 || + r4d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 || + x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h || + x.shape[2] != (absorb ? 256 : 512) || w.shape[0] != h * 512 || w.shape[1] != 512 || + y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : 256) || + x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] || + x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] || + y.stride[0] < h * y.stride[1]) + return RAD_E_SHAPE; + const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0], + y.stride[1], (int)x.shape[0], (int)h }; + /* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest + * holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a + * wave (expand). */ + const char* form = std::getenv("RADIANCE_MLA_PROJECT"); + const auto* xp = (const uint16_t*)x.data; + const auto* wp = (const uint16_t*)w.data; + auto* yp = (uint16_t*)y.data; + if (form && !std::strcmp(form, "old")) { + if (absorb) + return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp, + m); + return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m); + } + const long R = form && *form ? std::strtol(form, nullptr, 10) + : m.rows >= 8 ? 8 + : m.rows >= 4 ? 4 + : m.rows >= 2 ? 2 + : 1; +#define MLA_PROJECT_ROWS(RR) \ + do { \ + const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \ + if (absorb) \ + return R4D_EMIT(stream, (project_absorb_rows), dim3(4, h, groups), dim3(128), 0, \ + xp, wp, yp, m); \ + return R4D_EMIT(stream, (project_expand_rows), dim3(64, h, groups), dim3(128), 0, xp, \ + wp, yp, m); \ + } while (0) + if (R == 8) MLA_PROJECT_ROWS(8); + if (R == 4) MLA_PROJECT_ROWS(4); + if (R == 2) MLA_PROJECT_ROWS(2); + MLA_PROJECT_ROWS(1); +#undef MLA_PROJECT_ROWS +} +constexpr int D = 512, PART = D + 2; +constexpr int64_t scratch_bytes = 512ll * PART * 4; +constexpr int64_t matrix_scratch_bytes = 2048ll * PART * 4; +/* r4d_mla_matrix_pin_form: 0 is the launcher's rule (vector key loads where the cache is + * aligned), 1 the element-wise key load. */ +int g_mla_matrix_form = 0; +struct Meta { + long qr, qh, kp, kt, bp, bc, lp, orr, oh; + int rows, heads, blocks, bs, pages, splits; + float scale; +}; +/* RADIANCE_MLA_CONFLICT_STATS: per device, the 16-token passes the matrix row ran, how many of them + * were a pair's second pass, and the chunks of the max(length) raster a pass-free pairing would + * run. Read back by r4d_mla_matrix_stats, and printed every 1024th counted launch. */ +__device__ unsigned long long g_mla_stats[3]; +__device__ void load_latent(const uint16_t* p, float (&v)[16]) { + if (!((uintptr_t)p & 15)) { + const uint4 a = *(const uint4*)p, b = *(const uint4*)(p + 8); + const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w }; +#pragma unroll + for (int j = 0; j < 16; ++j) + v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1)))); + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32(p[j]); + } +} +__global__ __launch_bounds__(128) void attend(const uint16_t* q, const uint16_t* kv, const int* bt, + const int* len, uint16_t* out, float* scratch, + Meta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x, + split = blockIdx.z; + if (head >= m.heads) return; + const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs); + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + float query[16], value[16] = {}; + load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query); + float max_score = -INFINITY, den = 0; + for (int token = begin; token < end; ++token) { + const int page = bt[(long)r * m.bp + (token / m.bs) * m.bc]; + if (page < 0 || page >= m.pages) continue; + float key[16]; + load_latent(kv + (long)page * m.kp + (token % m.bs) * m.kt + lane * 16, key); + float score = 0; +#pragma unroll + for (int j = 0; j < 16; ++j) score += query[j] * key[j]; + score = r4d_wave_sum(score) * m.scale; + const bool higher = score > max_score; + const float weight = expf(higher ? max_score - score : score - max_score); + if (higher) { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j]; + den = den * weight + 1; + max_score = score; + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += key[j] * weight; + den += weight; + } + } + if (m.splits == 1) { +#pragma unroll + for (int j = 0; j < 16; ++j) + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = + f32_to_bf16(den > 0 ? value[j] / den : 0); + } else { + float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART; +#pragma unroll + for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j]; + if (!lane) { + dst[D] = max_score; + dst[D + 1] = den; + } + } +} +__global__ __launch_bounds__(128) void merge(const float* scratch, uint16_t* out, Meta m) { + const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x; + if (head >= m.heads) return; + const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART; + float max_score = -INFINITY; + for (int s = 0; s < m.splits; ++s) + if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]); + float value[16] = {}, den = 0; + for (int s = 0; s < m.splits; ++s) { + const float part_den = src[s * PART + D + 1]; + if (!(part_den > 0)) continue; + const float w = expf(src[s * PART + D] - max_score); + den += part_den * w; +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w; + } +#pragma unroll + for (int j = 0; j < 16; ++j) + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = + f32_to_bf16(den > 0 ? value[j] / den : 0); +} +/* Heads are the matrix rows, so all sixteen share each latent load even when + * each query selected different pages. Splitting P into BF16 high/low parts + * preserves FP32 softmax precision without a materialized per-head KV cache. + * + * PAIR fills the sixteen rows with eight heads of two neighbouring requests + * (rows 0-7 request r, rows 8-15 request r+1). A key is loaded once when both + * requests address the same cache row at that table position, as consecutive + * queries of one sequence do; each half masks columns that are not its own, + * which carries the causal edge. Where the two tables name different rows the + * chunk runs a second pass with the second request's keys. + * + * UNION pairs by page instead of by position: past the DSA budget each request + * selects its own blocks, neighbours share most of them at shifted positions, + * and the positional pairing would run nearly every chunk twice. The walk is + * request r's table in its own order (so r sums exactly as it does unpaired at + * one split), each entry carrying where r+1's table names the same page, then + * the pages only r+1 names, in r+1's order. Every chunk runs once. */ +constexpr int kUnionBlocks = 520, kUnionSlots = 1024; +__device__ __forceinline__ unsigned union_slot(int page) { + return ((unsigned)page * 2654435761u) >> 22; +} +/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. */ +template +__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const uint16_t* kv, + const int* bt, const int* len, uint16_t* out, + float* scratch, Meta m) { + static_assert(PAIR || !UNION, "the union pairs two requests"); + static_assert(16 * 520 * sizeof(uint16_t) >= (2 * kUnionSlots + 2 * kUnionBlocks) * sizeof(int), + "the union's hash lives in the key tile"); + __shared__ __align__(16) uint16_t query[16 * 520], keys[16 * 520], prob_hi[16 * 24], + prob_lo[16 * 24]; + __shared__ float score[16 * 16], maximum[16], denominator[16], alpha[16]; + __shared__ long source[16]; + __shared__ long own[PAIR ? 32 : 1]; + __shared__ short pair_of[UNION ? kUnionBlocks : 1], only_b[UNION ? kUnionBlocks : 1]; + __shared__ int union_count[UNION ? 4 : 1], union_end; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5; + const int r = PAIR ? blockIdx.x * 2 : blockIdx.x, h0 = blockIdx.y * (PAIR ? 8 : 16), + split = blockIdx.z; + int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs), live_pair[2] = { live, 0 }; + if constexpr (PAIR) { + if (r + 1 < m.rows) live_pair[1] = min(max(len[(long)(r + 1) * m.lp], 0), m.blocks * m.bs); + live = max(live_pair[0], live_pair[1]); + } + for (int j = tid; j < 16 * 512; j += 128) { + if constexpr (PAIR) { + const int row = j / 512, request = r + row / 8; + query[row * 520 + j % 512] = + request < m.rows ? q[(long)request * m.qr + (long)(h0 + row % 8) * m.qh + j % 512] + : 0; + } else + query[(j / 512) * 520 + j % 512] = + q[(long)r * m.qr + (long)(h0 + j / 512) * m.qh + j % 512]; + } + if (tid < 16) { + maximum[tid] = -INFINITY; + denominator[tid] = 0; + } + v8f value[8]; +#pragma unroll + for (int nt = 0; nt < 8; ++nt) value[nt] = (v8f){ 0 }; + const int* const bt_a = bt + (long)r * m.bp; + const int* const bt_b = bt + (long)(r + 1) * m.bp; + int blocks_a = 0; + if constexpr (UNION) { + /* The key tile is free until the first chunk: an open-addressed page -> lowest r entry + * hash, the lowest r+1 entry naming each r entry's page, and each r+1 entry's match. */ + int* const slot_page = (int*)keys; + int* const slot_first = slot_page + kUnionSlots; + int* const first_b = slot_first + kUnionSlots; + int* const match = first_b + kUnionBlocks; + blocks_a = (live_pair[0] + m.bs - 1) / m.bs; + const int blocks_b = (live_pair[1] + m.bs - 1) / m.bs; + for (int i = tid; i < kUnionSlots; i += 128) { + slot_page[i] = -1; + slot_first[i] = INT_MAX; + } + for (int i = tid; i < blocks_a; i += 128) first_b[i] = INT_MAX; + if (!tid) union_end = live_pair[0]; + __syncthreads(); + for (int i = tid; i < blocks_a; i += 128) { + const int page = bt_a[(long)i * m.bc]; + if (page < 0 || page >= m.pages) continue; + for (unsigned at = union_slot(page);; at = (at + 1) & (kUnionSlots - 1)) { + const int seen = atomicCAS(&slot_page[at], -1, page); + if (seen == -1 || seen == page) { + atomicMin(&slot_first[at], i); + break; + } + } + } + __syncthreads(); + for (int j = tid; j < blocks_b; j += 128) { + const int page = bt_b[(long)j * m.bc]; + int found = -1; + if (page >= 0 && page < m.pages) + for (unsigned at = union_slot(page); slot_page[at] != -1; + at = (at + 1) & (kUnionSlots - 1)) + if (slot_page[at] == page) { + found = slot_first[at]; + break; + } + match[j] = found; + if (found >= 0) atomicMin(&first_b[found], j); + } + __syncthreads(); + for (int i = tid; i < blocks_a; i += 128) + pair_of[i] = (short)(first_b[i] == INT_MAX ? -1 : first_b[i]); + /* r+1's own pages in its table order: slots from a ballot prefix, not an atomic, so the + * walk (and the summation order) is the same on every run. */ + int appended = 0; + for (int j0 = 0; j0 < blocks_b; j0 += 128) { + const int j = j0 + tid; + bool only = false; + if (j < blocks_b) { + const int page = bt_b[(long)j * m.bc]; + only = page >= 0 && page < m.pages && (match[j] < 0 || first_b[match[j]] != j); + } + const unsigned long long ballot = __ballot(only); + if (!lane) union_count[wave] = (int)__popcll(ballot); + __syncthreads(); + int before = appended, total = appended; +#pragma unroll + for (int w = 0; w < 4; ++w) { + before += w < wave ? union_count[w] : 0; + total += union_count[w]; + } + if (only) { + const int at = before + (int)__popcll(ballot & ((1ull << lane) - 1ull)); + only_b[at] = (short)j; + const int seen = min(m.bs, live_pair[1] - j * m.bs); + atomicMax(&union_end, (blocks_a + at) * m.bs + seen); + } else if (j < blocks_b && match[j] >= 0 && first_b[match[j]] == j) + atomicMax(&union_end, match[j] * m.bs + min(m.bs, live_pair[1] - j * m.bs)); + appended = total; + __syncthreads(); + } + live = union_end; + } + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + __syncthreads(); + for (int start = begin; start < end; start += 16) { + bool second = false; + if constexpr (UNION) { + if (tid < 16) { + const int token = start + tid, entry = token / m.bs, offset = token % m.bs; + long row[2] = { -1, -1 }; + if (token < end) { + const int at_a = entry < blocks_a ? entry : -1; + const int at_b = entry < blocks_a ? pair_of[entry] : only_b[entry - blocks_a]; + const int page = at_a >= 0 ? bt_a[(long)at_a * m.bc] : bt_b[(long)at_b * m.bc]; + if (page >= 0 && page < m.pages) { + const long at = (long)page * m.kp + offset * m.kt; + if (at_a >= 0 && at_a * m.bs + offset < live_pair[0]) row[0] = at; + if (at_b >= 0 && at_b * m.bs + offset < live_pair[1]) row[1] = at; + } + } + own[tid] = row[0]; + own[16 + tid] = row[1]; + source[tid] = row[0] >= 0 ? row[0] : row[1]; + } + __syncthreads(); + } else if constexpr (PAIR) { + bool conflict = false; + if (tid < 16) { + const int token = start + tid; + long row[2]; +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int page = token < end && token < live_pair[k] + ? bt[(long)(r + k) * m.bp + (token / m.bs) * m.bc] + : -1; + row[k] = page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt + : -1; + own[k * 16 + tid] = row[k]; + } + source[tid] = row[0] >= 0 ? row[0] : row[1]; + conflict = row[0] >= 0 && row[1] >= 0 && row[0] != row[1]; + } + second = __syncthreads_or(conflict); + if (STATS && second && !tid) { + atomicAdd(&g_mla_stats[0], 1ull); + atomicAdd(&g_mla_stats[1], 1ull); + } + } else { + if (tid < 16) { + const int token = start + tid; + const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1; + source[tid] = + page >= 0 && page < m.pages ? (long)page * m.kp + (token % m.bs) * m.kt : -1; + } + __syncthreads(); + } + for (int pass = 0; pass < (second ? 2 : 1); ++pass) { + if constexpr (PAIR) + if (pass) { + if (tid < 16) { + const long first = own[tid], other = own[16 + tid]; + source[tid] = first >= 0 && other >= 0 && first != other ? other : -1; + } + __syncthreads(); + } + if constexpr (WIDE) { + /* Unconditional loads (an absent row reads row 0 and is zeroed after) so all + * eight are in flight before the first wait. */ + uint4 part[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int flat = tid + j * 128; + const long at = source[flat >> 6]; + part[j] = *(const uint4*)(kv + (at >= 0 ? at : 0) + (flat & 63) * 8); + if (at < 0) part[j] = make_uint4(0, 0, 0, 0); + } +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int flat = tid + j * 128; + *(uint4*)(keys + (flat >> 6) * 520 + (flat & 63) * 8) = part[j]; + } + } else { + for (int j = tid; j < 16 * 512; j += 128) { + const int token = j / 512, col = j % 512; + keys[token * 520 + col] = source[token] >= 0 ? kv[source[token] + col] : 0; + } + } + __syncthreads(); + if (!wave) { + v8f dot = { 0 }; +#pragma unroll + for (int d = 0; d < 512; d += 16) + dot = mma(frag(query, 520, 0, d, lane), frag(keys, 520, 0, d, lane), dot); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int head = (lane >> 4) * 8 + j, col = lane & 15; + bool visible = source[col] >= 0; + if constexpr (PAIR) + visible = visible && own[(lane >> 4) * 16 + col] == source[col]; + score[head * 16 + col] = visible ? dot[j] * m.scale : -INFINITY; + } + } + __syncthreads(); + if (tid < 16) { + float mx = maximum[tid]; + for (int j = 0; j < 16; ++j) mx = fmaxf(mx, score[tid * 16 + j]); + const float a = isfinite(mx) ? expf(maximum[tid] - mx) : 1; + float den = denominator[tid] * a; + for (int j = 0; j < 16; ++j) { + const float p = + isfinite(score[tid * 16 + j]) ? expf(score[tid * 16 + j] - mx) : 0; + const uint16_t hi = f32_to_bf16(p); + prob_hi[tid * 24 + j] = hi; + prob_lo[tid * 24 + j] = f32_to_bf16(p - bf16_to_f32(hi)); + den += p; + } + maximum[tid] = mx; + denominator[tid] = den; + alpha[tid] = a; + } + // Read before the in-place transpose overwrites keys. Query remains resident. + uint16_t held[64]; +#pragma unroll + for (int j = 0; j < 64; ++j) { + const int flat = tid + j * 128; + held[j] = keys[(flat / 512) * 520 + flat % 512]; + } + __syncthreads(); +#pragma unroll + for (int j = 0; j < 64; ++j) { + const int flat = tid + j * 128; + keys[(flat % 512) * 16 + flat / 512] = held[j]; + } + __syncthreads(); + const auto hi = frag(prob_hi, 24, 0, 0, lane), lo = frag(prob_lo, 24, 0, 0, lane); +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { +#pragma unroll + for (int j = 0; j < 8; ++j) value[nt][j] *= alpha[(lane >> 4) * 8 + j]; + const auto v = frag(keys, 16, wave * 128 + nt * 16, 0, lane); + value[nt] = mma(hi, v, value[nt]); + value[nt] = mma(lo, v, value[nt]); + } + __syncthreads(); + } + } +#pragma unroll + for (int nt = 0; nt < 8; ++nt) { + const int col = wave * 128 + nt * 16 + (lane & 15); +#pragma unroll + for (int j = 0; j < 8; ++j) { + const int row = (lane >> 4) * 8 + j, request = PAIR ? r + (lane >> 4) : r, + head = PAIR ? h0 + j : h0 + row; + if (PAIR && request >= m.rows) continue; + if (m.splits == 1) { + const float den = denominator[row]; + out[(long)request * m.orr + (long)head * m.oh + col] = + f32_to_bf16(den > 0 ? value[nt][j] / den : 0); + } else + scratch[(((long)request * m.heads + head) * m.splits + split) * PART + col] = + value[nt][j]; + } + } + if (m.splits > 1 && tid < 16) { + const int request = PAIR ? r + tid / 8 : r, head = PAIR ? h0 + tid % 8 : h0 + tid; + if (!PAIR || request < m.rows) { + float* dst = scratch + (((long)request * m.heads + head) * m.splits + split) * PART; + dst[D] = maximum[tid]; + dst[D + 1] = denominator[tid]; + } + } + if (STATS && !tid) { + const int whole = max(live_pair[0], live_pair[1]); + const int raster = + (int)((long)whole * (split + 1) / m.splits) - (int)((long)whole * split / m.splits); + const unsigned long long chunks = (unsigned long long)(end - begin + 15) / 16; + atomicAdd(&g_mla_stats[0], chunks); + atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16); + } +} +bool env_on(const char* name) { + const char* e = std::getenv(name); + return e && *e && *e != '0'; +} +void read_stats(unsigned long long (&v)[3], bool reset) { + v[0] = v[1] = v[2] = 0; + if (hipMemcpyFromSymbol(v, HIP_SYMBOL(g_mla_stats), sizeof v, 0, hipMemcpyDeviceToHost) != + hipSuccess) + return; + const unsigned long long zero[3] = {}; + if (reset) + (void)hipMemcpyToSymbol(HIP_SYMBOL(g_mla_stats), zero, sizeof zero, 0, + hipMemcpyHostToDevice); +} +/* A server has no point at which to read the counters: running totals every 1024th counted launch. + * Not at exit, where a HIP call meets a runtime that is tearing down; not inside a graph capture, + * which a blocking copy would break. */ +void report_stats(RadStream stream) { + static std::atomic launches{ 0 }; + if (++launches % 1024) return; + hipStreamCaptureStatus capture = hipStreamCaptureStatusNone; + if (hipStreamIsCapturing((hipStream_t)stream, &capture) != hipSuccess || + capture != hipStreamCaptureStatusNone) + return; + int device = 0; + if (hipGetDevice(&device) != hipSuccess) return; + unsigned long long v[3]; + read_stats(v, false); + if (!v[2]) return; + std::fprintf(stderr, + "r4d mla_attn_matrix device %d: %llu passes over %llu raster chunks, " + "%llu second passes (%.3fx)\n", + device, v[0], v[2], v[1], (double)v[0] / (double)v[2]); +} +template +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 5) return RAD_E_INVAL; + const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4]; + if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || + len.dtype != RAD_I32) + return RAD_E_DTYPE; + for (int i = 0; i < 5; ++i) + if (!a->t[i].data) return RAD_E_INVAL; + const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0); + const float scale = (float)r4d_getf(a, "scale", 0); + if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 || + !std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 || + q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 || + q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 || + kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D || + kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || + bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs || + bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 || + len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 || + o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 || + o.stride[1] < D || o.stride[0] < heads * o.stride[1]) + return RAD_E_SHAPE; + if (MATRIX && heads % 8) return RAD_E_UNSUPPORTED; + const bool pair = MATRIX && heads % 16; + const long jobs = MATRIX ? (pair ? (q.shape[0] + 1) / 2 * (heads / 8) : q.shape[0] * heads / 16) + : q.shape[0] * heads; + int splits = (int)std::min(MATRIX ? 64l : 16l, ((MATRIX ? 64 : 256) + jobs - 1) / jobs); + const long minimum = MATRIX ? 16 : 64; + splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + minimum - 1) / minimum)); + if (!a->scratch || a->scratch_bytes < (MATRIX ? matrix_scratch_bytes : scratch_bytes)) + splits = 1; + // Vectors need every cache row on a sixteen-byte boundary. + const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) && + !(kv.stride[2] % 8); + /* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists + * hold a table of at most kUnionBlocks entries. */ + const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks; + const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS"); + Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2], + bt.stride[0], bt.stride[1], len.stride[0], o.stride[0], + o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1], + (int)bs, (int)kv.shape[0], splits, scale }; + int rc; + if constexpr (MATRIX) { +#define MATRIX_EMIT(P, W, U, S, X, Y) \ + R4D_EMIT(stream, (attend_matrix), dim3(X, Y, m.splits), dim3(128), 0, \ + (const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, \ + (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m) +#define MATRIX_LAUNCH(P, W, U, X, Y) \ + (stats ? MATRIX_EMIT(P, W, U, true, X, Y) : MATRIX_EMIT(P, W, U, false, X, Y)) + if (pair && by_page) + rc = wide ? MATRIX_LAUNCH(true, true, true, (m.rows + 1) / 2, m.heads / 8) + : MATRIX_LAUNCH(true, false, true, (m.rows + 1) / 2, m.heads / 8); + else if (pair) + rc = wide ? MATRIX_LAUNCH(true, true, false, (m.rows + 1) / 2, m.heads / 8) + : MATRIX_LAUNCH(true, false, false, (m.rows + 1) / 2, m.heads / 8); + else + rc = wide ? MATRIX_LAUNCH(false, true, false, m.rows, m.heads / 16) + : MATRIX_LAUNCH(false, false, false, m.rows, m.heads / 16); +#undef MATRIX_LAUNCH +#undef MATRIX_EMIT + } else + rc = R4D_EMIT(stream, attend, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0, + (const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, + (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m); + if (rc == RAD_OK && splits > 1) + rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0, + (const float*)a->scratch, (uint16_t*)o.data, m); + if (rc == RAD_OK && stats) report_stats(stream); + return rc; +} +} +extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) { + return body(a, stream); +} +extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) { + return body(a, stream); +} +extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) { + return project_body(a, stream); +} +extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; } +extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; } +extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; } +/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes, + * second passes, raster chunks), then zeroed. */ +extern "C" void r4d_mla_matrix_stats(unsigned long long* out) { + unsigned long long v[3]; + (void)hipDeviceSynchronize(); + read_stats(v, true); + if (out) std::memcpy(out, v, sizeof v); +} diff --git a/libr4d/r4d_moe.hip b/libr4d/r4d_moe.hip index f23e0819..75528e13 100644 --- a/libr4d/r4d_moe.hip +++ b/libr4d/r4d_moe.hip @@ -43,6 +43,8 @@ #include "r4d_plugin.h" #include "r4d_emit.h" #include "r4d_gemm_args.h" +#include "r4d_moe_sort.h" +#include "r4d_moe_gather.h" #include @@ -57,11 +59,20 @@ namespace { constexpr uint32_t kWave = 32; -/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in - * registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers - * Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router - * instantiation. */ -constexpr uint32_t kMaxExpert = 512; +using r4d_moesort::kMaxExpert; +using r4d_moesort::kMaxProtect; +using r4d_moesort::Protect; +using r4d_moesort::sort_place; +using r4d_moesort::protect_of; +using r4d_moesort::kScatterSmall; +using r4d_moesort::ScatterLds; +using r4d_moesort::wave_incl_scan_i32; +using r4d_moesort::scatter_small_place; +using r4d_moesort::kScatWaves; +using r4d_moesort::scatter_small_kernel; +using r4d_moegather::kGatherSlots; +using r4d_moegather::kGatherSelfT; +using r4d_moegather::gather_kernel; constexpr uint32_t kBlock = 128; // the fp8 scale block, along K and along N /* Run-map entry that owns no expert: rows above `off[n_expert]` are dropped slots whose output must * be zeroed. Declared here because the GEMM reads it; the map is built further down. */ @@ -152,27 +163,6 @@ __device__ __forceinline__ uint32_t wave_min_u32(uint32_t b) { * `router_topk_scatter_kernel` run this same code from a different grid, byte-identically. */ /* In the fused kernel a row also hands its slots to the sort through `e`: each slot's expert * relative to the slice, or -1 for another rank's. The standalone selection passes a null `e`. */ -/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output - * dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort - * places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and - * [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an - * expert's place is itself. */ -constexpr uint32_t kMaxProtect = 8; -struct Protect { - uint32_t n; - uint16_t e[kMaxProtect]; -}; - -/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */ -__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) { - int32_t below = 0; - for (uint32_t j = 0; j < p.n; ++j) { - if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j); - below += (int32_t)p.e[j] < e; - } - return e - below; -} - struct SlotSink { int32_t* e; int32_t base; @@ -292,123 +282,8 @@ __global__ __launch_bounds__(NW * kWave) void router_topk_kernel( /* ================================================================== moe_scatter * - * The small form: one workgroup does the whole sort, for T <= kScatterSmall, which covers every - * decode and verify step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch - * instead of three. Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert - * counts, and each slot placed by its rank inside its expert's run. - * - * On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work: - * - * - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one - * barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts). - * - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its - * expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's - * place is the number of the run's slots with a lower index. That count is as long as the run - * (a row picks an expert at most once), far shorter than counting all earlier slots. - * - * Stable and byte-identical: a slot's place is its position among the same expert's slots in - * ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so - * none waits on or invalidates the vector memory path. */ -constexpr uint32_t kScatterSmall = 1024; -constexpr uint32_t kScatWaves = 8; /* the standalone sort: 256 threads */ - -/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the - * workgroup's wave count, which sizes the scan's exchange. */ -template -struct ScatterLds { - static constexpr uint32_t kTiles = (kMaxExpert + NW * kWave - 1) / (NW * kWave); - int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */ - int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */ - int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */ - int32_t cnt[kMaxExpert + 1]; - int32_t off[kMaxExpert + 1]; - int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */ -}; - -/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then - * the upper row adds the lower row's total. Lanes shifted in from outside the row read zero - * (bound_ctrl). */ -__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) { - x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ - x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ - const int32_t lo = __builtin_amdgcn_readlane(x, 15); - return lane >= 16u ? x + lo : x; -} - -/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has - * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the - * standalone sort and the fused kernel. The workgroup is exactly NW waves. */ -template -__device__ __forceinline__ void scatter_small_place( - int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, - uint32_t T, uint32_t n_expert, ScatterLds& sl) { - const uint32_t tid = threadIdx.x, lane = tid % kWave, wave = tid / kWave; - - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1); - } - lds_barrier(); - - /* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same - * in every thread. */ - int32_t carry = 0; - for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kWave, ++t) { - const uint32_t e = b + tid; - const int32_t v = (e < n_expert) ? sl.cnt[e] : 0; - const int32_t x = wave_incl_scan_i32(v, lane); - if (lane == kWave - 1) sl.wt[t][wave] = x; - lds_barrier(); - int32_t below = 0, tot = 0; -#pragma unroll - for (uint32_t k = 0; k < NW; ++k) { - const int32_t c = sl.wt[t][k]; - below += (k < wave) ? c : 0; - tot += c; - } - if (e < n_expert) { - const int32_t o = carry + below + x - v; /* inclusive -> exclusive */ - sl.off[e] = o; - off[e] = o; - cnt[e] = v; - } - carry += tot; - } - if (tid == 0) off[n_expert] = carry; - lds_barrier(); - - for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1; - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i; - } - lds_barrier(); - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = sl.e[i]; - if (e < 0) continue; - const int32_t o = sl.off[e], n = sl.cnt[e]; - int32_t rank = 0; - for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i; - sorted[o + rank] = (int32_t)i; - } -} - -__global__ __launch_bounds__(kScatWaves * kWave) void scatter_small_kernel( - const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off, - int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot) { - __shared__ ScatterLds sl; - const uint32_t tid = threadIdx.x; - for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0; - for (uint32_t i = tid; i < T; i += blockDim.x) { - const int32_t e = ids[i] - base; - sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1; - } - lds_barrier(); - scatter_small_place(sorted, off, cnt, T, n_expert, sl); -} - + * The small form is one workgroup and the sort of r4d_moe_sort.h; the general form below takes + * three passes. */ /* ================================================================== router_topk + moe_scatter * * One launch for the pair: at decode each half is a single 256-thread workgroup moving about a @@ -520,11 +395,12 @@ __global__ __launch_bounds__(kMaxExpert) void scatter_scan_kernel( /* Placement and tail. Each routed slot goes to its expert's offset plus the expert's count in * earlier tiles plus its rank in this tile. Sorted rows past the live count are -1; no placement * lands there (all placed slots are below `off[n_expert]`), so each thread writes its own index - * without races. */ + * without races. INV also writes each slot's row, -1 when dropped (scatter_small_place). */ +template __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) { + uint32_t T, uint32_t n_expert, int32_t base, Protect prot, int32_t* __restrict__ inv) { __shared__ int32_t s_id[kScatterTile]; const uint32_t tid = threadIdx.x, b = blockIdx.x; const uint32_t i = b * kScatterTile + tid; @@ -536,12 +412,15 @@ __global__ __launch_bounds__(kScatterTile) void scatter_place_kernel( const uint32_t live = (uint32_t)off[n_expert]; if (i >= live && i < T) sorted[i] = -1; __syncthreads(); + if constexpr (INV) if (i < T && e < 0) inv[i] = -1; if (i >= T || e < 0) return; /* Rank within the tile: earlier slots of this tile with the same expert. A serial scan of at * most 256 LDS words per thread, 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; + const int32_t at = off[e] + bcnt[(size_t)b * n_expert + e] + rank; + sorted[at] = (int32_t)i; + if constexpr (INV) inv[i] = at; } /* ================================================================== the 4-bit expert weight @@ -2155,78 +2034,6 @@ __global__ void gather_scatter_kernel(const int32_t* __restrict__ sorted, if (f >= 0 && f < (int32_t)T) inv[f] = (int32_t)i; } -/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the - * column, and read inside the column loop each `inv` load would serialise the `ye` load behind it - * (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline. - * - * The column range is also split over blocks, since decode has one token. Neither change touches - * the sum: each column's slots are still summed in ascending order within one block. */ -constexpr uint32_t kGatherSlots = 64; -/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not - * launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k), - * giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it - * (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches - * (~2.1 us each) of single-block kernels. - * - * `sorted == nullptr` selects the prepass path, used at prefill. */ -constexpr uint32_t kGatherSelfT = 512; - -template -__global__ __launch_bounds__(NTHR) void gather_kernel( - const uint16_t* __restrict__ ye, const uint16_t* __restrict__ ew, - 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 int32_t* __restrict__ sorted, uint32_t T, - const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg, - uint32_t sh_ld, uint32_t sg_ld, int sig) { - __shared__ int32_t s_i[kGatherSlots]; - __shared__ float s_w[kGatherSlots]; - const uint32_t t = blockIdx.x; - if (t >= M) return; - const bool cached = top_k <= kGatherSlots; - /* The shared arm's scalar, read once per block as scale_rows reads it once per row. */ - float gate = 0.0f; - if (sh) { - const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); - gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; - } - if (sorted) { - /* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the - * prepass is two kernels). */ - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1; - __syncthreads(); - const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; - for (uint32_t i = threadIdx.x; i < T; i += NTHR) { - const int32_t f = sorted[i]; - if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i; - } - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) - s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]); - __syncthreads(); - } else if (cached) { - for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) { - s_i[j] = inv[t * top_k + j]; - s_w[j] = bf16_to_f32(ew[(size_t)t * ew_ld + j]); - } - __syncthreads(); - } - for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) { - float acc = 0.0f; - for (uint32_t j = 0; j < top_k; ++j) { - const int32_t i = cached ? s_i[j] : inv[t * top_k + j]; - if (i < 0) continue; - const float wj = cached ? s_w[j] : bf16_to_f32(ew[(size_t)t * ew_ld + j]); - acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]); - } - const uint16_t g = f32_to_bf16(acc); - if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } - /* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather - * as bf16 and narrows its own product before adding. */ - const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); - y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); - } -} - /* ---- prefill gather: a wave per token, eight columns per lane --------------------------------- * * At prefill this op reads `ye` (105 MB per layer at a 2048 chunk of Qwen3.8-Flash-Next on four @@ -2397,27 +2204,6 @@ extern "C" int r4d_rad_router_topk(const RadArgs* a, RadStream s) { return RAD_OK; } -/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most - * kMaxProtect. Absent or empty is none. */ -static int protect_of(const RadArgs* a, long long n_local, Protect* p) { - *p = Protect{}; - const char* s = r4d_gets(a, "protect"); - if (!s) return RAD_OK; - long long prev = -1; - while (*s) { - char* end = nullptr; - const long long v = std::strtoll(s, &end, 10); - if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect) - return R4D_NO(RAD_E_SHAPE); - p->e[p->n++] = (uint16_t)v; - prev = v; - s = end; - if (*s == ',') ++s; - else if (*s) return R4D_NO(RAD_E_SHAPE); - } - return RAD_OK; -} - /* The pair in one launch. Operands are the two ops' own, selection first: logits -> expert_ids, * expert_w, sorted_tok, expert_offset, expert_count. The checks are the two shims' checks. * @@ -2518,7 +2304,8 @@ extern "C" int64_t r4d_rad_moe_scatter_scratch(const RadArgs* a) { return n_tile * n_expert * (long long)sizeof(int32_t); } -extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { +/* moe_scatter, and with `inv` (moe_scatter_inv's fifth operand) the inverse beside it. */ +static int moe_scatter_body(const RadArgs* a, RadStream s, const RadTensor* inv) { const RadTensor* ids = r4d_opt(a, 0); const RadTensor* sorted = r4d_opt(a, 1); const RadTensor* off = r4d_opt(a, 2); @@ -2543,15 +2330,24 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { const int prc = protect_of(a, n_expert, &prot); if (prc != RAD_OK) return prc; + if (inv && (inv->dtype != RAD_I32 || !r4d_contig(inv) || r4d_numel(inv) < T)) + return R4D_NO(RAD_E_SHAPE); + const int32_t* idp = (const int32_t*)ids->data; int32_t* sp = (int32_t*)sorted->data; int32_t* op = (int32_t*)off->data; int32_t* cp = (int32_t*)cnt->data; + int32_t* ip = inv ? (int32_t*)inv->data : nullptr; if (T <= (long long)kScatterSmall) { - hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(256), 0, (hipStream_t)s, - idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, - prot); + if (ip) + hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(kScatWaves * kWave), 0, + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); + else + hipLaunchKernelGGL(scatter_small_kernel, dim3(1), dim3(kScatWaves * kWave), 0, + (hipStream_t)s, idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, + (int32_t)base, prot, ip); R4D_MOE_CHK(); return RAD_OK; } @@ -2568,13 +2364,30 @@ extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream 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); + if (ip) + 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, ip); + else + 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, ip); R4D_MOE_CHK(); return RAD_OK; } +extern "C" int r4d_rad_moe_scatter(const RadArgs* a, RadStream s) { + return moe_scatter_body(a, s, nullptr); +} + +/* moe_scatter that also writes, for every slot, its row in `sorted_tok` (-1 when dropped): the + * table moe_gather_inv reads instead of rebuilding it from `sorted_tok`. Same sort, same scratch. */ +extern "C" int r4d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) { + const RadTensor* inv = r4d_opt(a, 4); + if (!inv) return R4D_NO(RAD_E_INVAL); + return moe_scatter_body(a, s, inv); +} + /* The weight-table operand from the core's tensor. A zero leading stride marks a pointer array * (abi/rad_runtime.h, RAD_WTAB); otherwise it is a stacked plane with the stride in elements of the * weight's dtype (bytes for E4M3). */ @@ -3220,7 +3033,9 @@ extern "C" int64_t r4d_rad_moe_gather_scratch(const RadArgs* a) { return M * top_k * (long long)sizeof(int32_t); } -extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { +/* moe_gather, or with `given` moe_gather_inv, whose third operand is the inverse moe_scatter_inv + * wrote: no prepass and no self-scan, and the same kernel at the same T, so the same sums. */ +static int moe_gather_body(const RadArgs* a, RadStream s, bool given) { const RadTensor* ye = r4d_opt(a, 0); const RadTensor* ew = r4d_opt(a, 1); const RadTensor* sorted = r4d_opt(a, 2); @@ -3232,7 +3047,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { const long long n = r4d_geti_or(a, "n", 0); const long long top_k = r4d_geti_or(a, "top_k", 0); if (n <= 0 || top_k <= 0) return R4D_NO(RAD_E_SHAPE); - if (ye->dtype != RAD_BF16 || ew->dtype != RAD_BF16 || Y->dtype != RAD_BF16) + if (ye->dtype != RAD_BF16 || (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) || Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (sorted->dtype != RAD_I32 || !r4d_contig(sorted)) return R4D_NO(RAD_E_STRIDE); /* The shared arm is a pair: the plane and its per-row gate, or neither. */ @@ -3253,12 +3068,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { /* SELF: small enough for the gather to build its own slot table, skipping the two prepass * kernels (see gather_kernel). Bounded on T because each of the M*gy blocks repeats the scan; - * at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. */ - const bool self = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots; + * at the cap it is under half a megabyte of L2 traffic. Prefill takes the prepass. A given + * table replaces both, and `small` keeps the kernel choice the self-scan would make. */ + const bool small = T <= (long long)kGatherSelfT && top_k <= (long long)kGatherSlots; + const bool self = small && !given; - const int64_t need = self ? 0 : T * (long long)sizeof(int32_t); - int32_t* inv = nullptr; - if (!self) { + const int64_t need = self || given ? 0 : T * (long long)sizeof(int32_t); + int32_t* inv = given ? (int32_t*)sorted->data : nullptr; + if (!self && !given) { if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); inv = (int32_t*)a->scratch; const unsigned blocks = (unsigned)((T + 255) / 256); @@ -3288,7 +3105,7 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { auto al16 = [](const void* p, long long ld) { return ((uintptr_t)p % 16) == 0 && ld % (long long)kGatherWideCols == 0; }; - const bool wide_ok = !self && top_k <= (long long)kGatherWideSlots && + const bool wide_ok = ew->dtype == RAD_BF16 && !small && 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; @@ -3310,6 +3127,17 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { } const unsigned gy = (unsigned)((n + 255) / 256); + if (ew->dtype == RAD_F32) { + hipLaunchKernelGGL( + (gather_kernel<256, true>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s, + (const uint16_t*)ye->data, ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, + (uint32_t)top_k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, + self ? (const int32_t*)sorted->data : nullptr, (uint32_t)T, + sh ? (const uint16_t*)sh->data : nullptr, sh ? (const uint16_t*)sg->data : nullptr, + (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + R4D_MOE_CHK(); + return RAD_OK; + } hipLaunchKernelGGL((gather_kernel<256>), dim3((unsigned)M, gy), dim3(256), 0, (hipStream_t)s, (const uint16_t*)ye->data, (const uint16_t*)ew->data, inv, (uint16_t*)Y->data, (uint32_t)M, (uint32_t)n, (uint32_t)top_k, @@ -3322,6 +3150,14 @@ extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { return RAD_OK; } +extern "C" int r4d_rad_moe_gather(const RadArgs* a, RadStream s) { + return moe_gather_body(a, s, false); +} + +extern "C" int r4d_rad_moe_gather_inv(const RadArgs* a, RadStream s) { + return moe_gather_body(a, s, true); +} + extern "C" int r4d_rad_scale_rows(const RadArgs* a, RadStream s) { const RadTensor* x = r4d_opt(a, 0); const RadTensor* sc = r4d_opt(a, 1); diff --git a/libr4d/r4d_moe_gather.h b/libr4d/r4d_moe_gather.h new file mode 100644 index 00000000..8eabec4f --- /dev/null +++ b/libr4d/r4d_moe_gather.h @@ -0,0 +1,92 @@ +// r4d_moe_gather.h -- moe_gather's kernel for decode and short passes, beside its launcher in +// r4d_moe.hip; tests/r4d_emu runs it from here against the inverse the sort writes. +#pragma once +#include +#include + +#include "r4d_common.h" + +// Internal linkage, as the unit's own definition had. +namespace r4d_moegather { +namespace { + +/* The slot table is hoisted: `inv[t * top_k + j]` and `ew[t * ew_ld + j]` do not depend on the + * column, and read inside the column loop each `inv` load would serialise the `ye` load behind it + * (110 dependent latencies per layer at decode). Read once into LDS, the `ye` loads pipeline. + * + * The column range is also split over blocks, since decode has one token. Neither change touches + * the sum: each column's slots are still summed in ascending order within one block. */ +constexpr uint32_t kGatherSlots = 64; +/* When small, the inverse permutation is built in this kernel and the two prepass kernels are not + * launched. A block owns one token, so it scans `sorted` for entries in [t*top_k, (t+1)*top_k), + * giving exactly the table `inv` would hold. Every block repeats the scan, so the launcher caps it + * (r4d_rad_moe_gather); at decode T = 40 and the scan is one pass, against two dependent dispatches + * (~2.1 us each) of single-block kernels. + * + * `sorted == nullptr` selects the prepass path, used at prefill. */ +constexpr uint32_t kGatherSelfT = 512; + +template +__device__ float gather_weight(const void* ew, size_t i) { + if constexpr (F32) return ((const float*)ew)[i]; + else return bf16_to_f32(((const uint16_t*)ew)[i]); +} +template +__global__ __launch_bounds__(NTHR) void gather_kernel( + const uint16_t* __restrict__ ye, const void* __restrict__ ew, + 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 int32_t* __restrict__ sorted, uint32_t T, + const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg, + uint32_t sh_ld, uint32_t sg_ld, int sig) { + __shared__ int32_t s_i[kGatherSlots]; + __shared__ float s_w[kGatherSlots]; + const uint32_t t = blockIdx.x; + if (t >= M) return; + const bool cached = top_k <= kGatherSlots; + /* The shared arm's scalar, read once per block as scale_rows reads it once per row. */ + float gate = 0.0f; + if (sh) { + const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); + gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; + } + if (sorted) { + /* An unclaimed slot must read -1, so fill and scan are separated by a barrier (as the + * prepass is two kernels). */ + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) s_i[j] = -1; + __syncthreads(); + const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; + for (uint32_t i = threadIdx.x; i < T; i += NTHR) { + const int32_t f = sorted[i]; + if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i; + } + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + __syncthreads(); + } else if (cached) { + for (uint32_t j = threadIdx.x; j < top_k; j += NTHR) { + s_i[j] = inv[t * top_k + j]; + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + } + __syncthreads(); + } + for (uint32_t c = blockIdx.y * NTHR + threadIdx.x; c < n; c += NTHR * gridDim.y) { + float acc = 0.0f; + for (uint32_t j = 0; j < top_k; ++j) { + const int32_t i = cached ? s_i[j] : inv[t * top_k + j]; + if (i < 0) continue; + const float wj = cached ? s_w[j] : gather_weight(ew, (size_t)t * ew_ld + j); + if constexpr (F32) acc = fmaf(wj, bf16_to_f32(ye[(size_t)i * ye_ld + c]), acc); + else acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]); + } + const uint16_t g = f32_to_bf16(acc); + if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } + /* The shared arm, folded with the unfused pair's two narrows: `scale_rows` reads the gather + * as bf16 and narrows its own product before adding. */ + const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); + y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); + } +} + +} // namespace +} // namespace r4d_moegather diff --git a/libr4d/r4d_moe_mxfp4.hip b/libr4d/r4d_moe_mxfp4.hip new file mode 100644 index 00000000..ad22b3b5 --- /dev/null +++ b/libr4d/r4d_moe_mxfp4.hip @@ -0,0 +1,1156 @@ +/* Canonical MXFP4 experts: packed E2M1 codes and E8M0 bytes remain in their + * source layout, including mapped host expert tables. A wave decodes packed + * words into exact E4M3 staging bytes for FP8 WMMA. Activation then weight + * scales fold in F32 per 32 values, matching the reference grouping. */ +#include +#include "r4d_args.h" +#include "r4d_common.h" +#include "r4d_emit.h" +#include "r4d_fp8_wmma.h" +#include "r4d_mxfp4.h" +#include +#include +#include + +namespace { +struct MxMeta { + long wstep[2], sstep[2]; + int wrow[2], srow[2], n[2], k[2]; + long ar, asr, yr; + int T, Arows, N, K, experts, topk, sorted_a, tile, parts, aligned_jobs; + int stage_out, out16; +}; +__device__ const uint8_t* entry(const void* base, long step, int e) { + return step ? (const uint8_t*)base + (long)e * step : ((const uint8_t* const*)base)[e]; +} +/* E2M1 values are exactly representable in E4M3. Stage those codes directly, + * use FP8 WMMA, and fold each 32-wide E8M0 scale into the F32 accumulator. + * No persistent expansion or checkpoint relayout is needed. */ +// Four independent bytes: magnitudes >=2 map to (m+12)*4; 0/1 map to 0/48. +// Expand each magnitude-test bit into a byte mask without cross-byte carries. +__device__ __forceinline__ uint32_t fp4x4(uint32_t n) { + const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; + const uint32_t mask = (flag << 5) - (flag >> 3); + return ((((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) | + ((n & 0x08080808u) << 4)); +} +/* Eight codes of a packed word to their E4M3 bytes in k order. The table form (r4d_mxfp4.h, v_perm + * on the magnitude) gives the same bytes in about a third of the instructions; the arithmetic form + * stays reachable (RADIANCE_MXFP4_LUT=0) as the bytewise reference. */ +template +__device__ __forceinline__ uint2 mx_codes8(uint32_t packed) { + if constexpr (Lut) { + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact(packed, &lo, &hi); + return uint2{ lo, hi }; + } else { + const uint32_t low = fp4x4(packed & 0x0f0f0f0fu), high = fp4x4((packed >> 4) & 0x0f0f0f0fu); + return uint2{ __byte_perm(low, high, 0x5140), __byte_perm(low, high, 0x7362) }; + } +} +template +__global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const void* w0, + const void* s0, const void* w1, const void* s1, + const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + __shared__ __align__(16) uint8_t aa[16 * RowTiles * 136], bb[16 * ColTiles * 136]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, + col0 = blockIdx.x * (16 * ColTiles); + constexpr int JobRows = 16 * RowTiles, Threads = 32 * ColTiles * RowTiles; + const int wave_col = ColTiles == 1 ? 0 : wave % ColTiles, + wave_row = RowTiles == 1 ? 0 : wave / ColTiles; + int first = blockIdx.y * m.tile; + int group_end = min((int)(blockIdx.y + 1) * m.tile, m.T), job_expert = 0; + if (m.aligned_jobs) { + // Expert e begins at job floor(offset[e]/JobRows)+e. The extra job per expert + // bounds padding without a prefix-sum pass; every live job owns one row tile + // of one expert, so hot experts still spread across independent CTAs. + const int job = blockIdx.y, tail = offset[m.experts] / JobRows + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * JobRows; + for (int r = r0; r < min(r0 + JobRows, m.T); ++r) + if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0; + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / JobRows + mid <= job) + lo = mid; + else + hi = mid; + } + job_expert = lo; + first = offset[lo] + (job - (offset[lo] / JobRows + lo)) * JobRows; + group_end = min(first + JobRows, offset[lo + 1]); + } + for (int start = first; start < group_end;) { + if (sorted[start] < 0 || offset[m.experts] <= start) { + if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0; + ++start; + continue; + } + int lo = m.aligned_jobs ? job_expert : 0, hi = m.experts; + if (!m.aligned_jobs) + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] <= start) + lo = mid; + else + hi = mid; + } + const int cls = lo & 1, end = min(group_end, offset[lo + 1]); + if (end <= start) return; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + auto total = r4d_fp8::acc_zero(); + // Routing is invariant across K; each activation scale covers all four groups. + int sources[8]; + if constexpr (CachedRows) { +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; + const int flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + sources[row] = ar >= 0 && ar < m.Arows ? ar : -1; + } + } + for (int kb = 0; kb < m.k[cls]; kb += 128) { + for (int j = tid; j < 16 * RowTiles * 16; j += Threads) { + const int r = j / 16, d = (j % 16) * 8; + const int ar = start + r < end && sorted[start + r] >= 0 + ? (m.sorted_a ? start + r : sorted[start + r] / m.topk) + : -1; + uint2 av{}; + if (ar >= 0 && ar < m.Arows) __builtin_memcpy(&av, a + (long)ar * m.ar + kb + d, 8); + *reinterpret_cast(aa + r * 136 + d) = av; + } + for (int j = tid; j < 16 * ColTiles * 16; j += Threads) { + const int r = j / 16, d = (j % 16) * 8; + const int n = col0 + r, part = n / (m.N / m.parts), within = n % (m.N / m.parts); + const int wn = part * (m.n[cls] / m.parts) + within; + uint32_t packed = 0; + if (n < m.N && within < m.n[cls] / m.parts) + __builtin_memcpy(&packed, w + (long)wn * m.wrow[cls] + (kb + d) / 2, 4); + *reinterpret_cast(bb + r * 136 + d) = mx_codes8(packed); + } + __syncthreads(); + if (start + wave_row * 16 < end) { + const int n = col0 + wave_col * 16 + (lane & 15), part = n / (m.N / m.parts), + within = n % (m.N / m.parts); + const int wn = part * (m.n[cls] / m.parts) + within; + const bool valid = n < m.N && within < m.n[cls] / m.parts; + float activation[8]; + if constexpr (CachedRows) { +#pragma unroll + for (int row = 0; row < 8; ++row) + activation[row] = + sources[row] >= 0 ? as[(long)sources[row] * m.asr + kb / 128] : 0; + } +#pragma unroll + for (int group = 0; group < 4; ++group) { + const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127; + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = group * 32; k < (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane), + r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw); + // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, + // a representable subnormal, and code 255 is NaN. + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? ((uint32_t)exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) { + if constexpr (CachedRows) { + if (sources[row] >= 0) total[row] += raw[row] * activation[row] * scale; + } else { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row; + if (r < end) { + const int ar = sorted[r] < 0 ? -1 + : m.sorted_a ? r + : sorted[r] / m.topk; + if (ar >= 0 && ar < m.Arows) + total[row] += + raw[row] * as[(long)ar * m.asr + kb / 128] * scale; + } + } + } + } + } + __syncthreads(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = start + wave_row * 16 + (lane >> 4) * 8 + row, + n = col0 + wave_col * 16 + (lane & 15); + if (r < end && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + start = end; + } +} + +/* An expert's weight and exponent rows reached through entry() are generic pointers, so their loads + * compile to flat loads, which every LDS wait (s_wait_dscnt) also waits for: a barrier then stalls + * on the prefetch. The tables hold device or device-mapped host addresses, so a global load reads + * the same bytes. Byte-aligned, as a stacked plane's row pitch may be odd. */ +typedef r4d_u32x4 mx_g16 __attribute__((aligned(1))); +typedef uint32_t mx_g4 __attribute__((aligned(1))); +__device__ __forceinline__ r4d_u32x4 mx_ldg16(const uint8_t* p) { + return *(const __attribute__((address_space(1))) mx_g16*)p; +} +__device__ __forceinline__ uint32_t mx_ldg4(const uint8_t* p) { + return *(const __attribute__((address_space(1))) mx_g4*)p; +} +/* The TP8 prefill form (M32N64, aligned jobs, cached rows) with its loads a stage ahead. A job's + * row table resolves into LDS once; the next 128 of K (activation bytes, weight codes, an exponent + * dword a column, the activation scales) is loaded into registers while the current stage computes + * from LDS. The form above waits on three dependent latencies a stage: the routing entry, the + * activation row it names, and the exponent bytes it reads after the barrier. A job begins at its + * first row even when that slot is dropped; rows are independent, so the bytes are the same. + * The exponents are decoded once, at staging; the fold carries no row predicate, the epilogue + * writes a dropped row's zero instead. + * One stage ahead only: a deeper prefetch measured slower on the expert-major forms. The barriers + * order LDS only (lds_barrier), so the prefetch stays in flight across them and L0 keeps the + * activation rows the next column block reads. */ +template +__global__ __launch_bounds__(256) + R4D_WAVES(16) void moe_mxfp4_prefill_kernel(const uint8_t* a, const float* as, const void* w0, + const void* s0, const void* w1, const void* s1, + const int* sorted, const int* offset, uint16_t* y, + MxMeta m) { + constexpr int BN = 64, BM = 32, Threads = 256, P = 136; + static_assert(BM * 128 / 16 == Threads && BN * 64 / 16 == Threads, + "one 16-byte chunk a thread and operand"); + __shared__ __align__(16) uint8_t aa[BM * P], bb[BN * P]; + __shared__ __align__(16) float ss[4 * BN]; + __shared__ float sa[BM]; + __shared__ int src[BM]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * BN; + const int wave_col = wave & 3, wave_row = wave >> 2; + const int job = blockIdx.y, tail = offset[m.experts] / BM + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * BM; + for (int r = r0; r < min(r0 + BM, m.T); ++r) + if (tid < BN && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0; + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / BM + mid <= job) + lo = mid; + else + hi = mid; + } + const int first = offset[lo] + (job - (offset[lo] / BM + lo)) * BM, + end = min(first + BM, offset[lo + 1]); + if (first >= end) return; + const int cls = lo & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + if (tid < BM) { + const int r = first + tid, flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + // The block's columns are fixed, so each thread's weight row and exponent row are too. + const int wcol = tid >> 2, wd = (tid & 3) * 16, wn_c = col0 + wcol, wn_w = wn_c % pw; + const bool wvalid = wn_c < m.N && wn_w < cw; + const uint8_t* wp = w + (long)((wn_c / pw) * cw + wn_w) * m.wrow[cls] + wd; + const int en_c = col0 + tid, en_w = en_c % pw; + const bool evalid = tid < BN && en_c < m.N && en_w < cw; + const uint8_t* ep = ws + (long)((en_c / pw) * cw + en_w) * m.srow[cls]; + lds_barrier(); + const int arow = tid >> 3, ad = (tid & 7) * 16, a_src = src[arow]; + const uint8_t* ap = a + (long)max(a_src, 0) * m.ar + ad; + const int sa_row = tid - BN, sa_src = sa_row >= 0 && sa_row < BM ? src[sa_row] : -1; + const float* asp = as + (long)max(sa_src, 0) * m.asr; + const int rowbase = wave_row * 16 + (lane >> 4) * 8, mycol = wave_col * 16 + (lane & 15); + const bool live = first + wave_row * 16 < end; + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + r4d_u32x4 ra, rw; + uint32_t rs = 0x7f7f7f7fu; + float rsa = 0; + auto load = [&](int k0) { + ra = r4d_u32x4{ 0, 0, 0, 0 }; + if (a_src >= 0) __builtin_memcpy(&ra, ap + k0, 16); + rw = r4d_u32x4{ 0, 0, 0, 0 }; + if (wvalid) rw = mx_ldg16(wp + k0 / 2); + if (evalid) rs = mx_ldg4(ep + k0 / 32); + if (sa_src >= 0) rsa = asp[k0 / 128]; + }; + auto store = [&]() { + *reinterpret_cast(aa + arow * P + ad) = ra; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]); + if (tid < BN) { + // E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable + // subnormal, and code 255 is NaN. + float sc[4]; +#pragma unroll + for (int g = 0; g < 4; ++g) { + const uint32_t exp = (rs >> (8 * g)) & 0xffu; + sc[g] = __uint_as_float(exp == 255 ? 0x7fc00000u : exp ? (exp << 23) : 0x00400000u); + } + *reinterpret_cast(ss + 4 * tid) = make_float4(sc[0], sc[1], sc[2], sc[3]); + } + if (sa_row >= 0 && sa_row < BM) sa[sa_row] = rsa; + }; + auto total = r4d_fp8::acc_zero(); + load(0); + for (int k0 = 0; k0 < kc; k0 += 128) { + store(); + lds_barrier(); + if (k0 + 128 < kc) load(k0 + 128); + if (live) { + const float4 sc4 = *reinterpret_cast(ss + 4 * mycol); + const float scales[4] = { sc4.x, sc4.y, sc4.z, sc4.w }; + float activation[8]; +#pragma unroll + for (int row = 0; row < 8; ++row) activation[row] = sa[rowbase + row]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = group * 32; k < (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane), + r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw); +// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0. +#pragma unroll + for (int row = 0; row < 8; ++row) + total[row] += raw[row] * activation[row] * scales[group]; + // Two groups' WMMA chains at a time: with all four in flight the kernel takes 104 + // VGPRs, 12 waves a SIMD at gfx1201's 24-register granule instead of 16. + if (group == 1) sched_barrier(); + } + } + lds_barrier(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = first + rowbase + row, n = col0 + mycol; + if (r < end && n < m.N) y[(long)r * m.yr + n] = rv[row] ? f32_to_bf16(total[row]) : 0; + } +} + +/* The wide prefill form (P64): jobs of BM rows of one expert, blocks of BN columns, eight waves + * as BM/16 row waves times 8/(BM/16) column waves, so a wave holds BN/(16*column waves) tiles of + * 16x16 and reuses each A fragment across them. M32N64 reads every expert slice once per 32 rows + * and a fragment pair per WMMA pair; at 57 rows an expert (2048 tokens) BM 64 halves the slice + * reads, and a row wave past the run's end skips its compute, so the taller job costs no WMMA. + * + * Resident (K <= 256, down): the job's whole A tile sits in LDS for the block's CT column tiles, + * walked as one stage sequence whose next stage (weight codes, exponents) is loaded while the + * current one computes, across tile boundaries; A is read once per CT tiles instead of once per + * column block. Otherwise (gate_up) A streams with the weights, a stage ahead. + * + * Each element keeps the row-group form's sequence: per 128 of K in order, per 32-wide group a + * fresh WMMA pair from zero, folded as (raw * activation scale) * E8M0 scale and added, two + * roundings and an add (the unit is built -ffp-contract=off). The tiles of a wave are separate + * accumulators, so no element sees another order. `stage_out` writes the output through LDS in + * 16-byte rows instead of a lane's 2-byte column stores. + * + * DB (streamed A only): two LDS stages, one barrier a stage. The next stage is stored into the + * other buffer after the current one computes, which every wave last read before the previous + * barrier; the single-buffer order needs a second barrier before it may overwrite the stage it + * computes from. Same bytes in LDS, same per-element sequence. */ +template +struct MxP64 { + static constexpr int Threads = 256, WR = BM / 16, WC = 8 / WR, TC = BN / (16 * WC), + KB = StageK / 128; + static constexpr int KR = 256, AK = Resident ? KR : StageK, PA = AK + 8, PB = StageK + 8, + PO = 2 * BN + 16; + static constexpr int TPA = Threads / BM, ACh = StageK / 16 / TPA, RCh = KR / 16 / TPA; + static constexpr int TPW = Threads / BN, WCh = StageK / 32 / TPW, + SAK = Resident ? KR / 128 : KB; + static constexpr int NB = DB ? 2 : 1, BB = NB * BN * PB > BM *PO ? NB * BN * PB : BM * PO; + static constexpr int Lds = NB * (BM * PA + 16 * KB * BN + 4 * SAK * BM) + BB + 4 * BM; + // The waves a SIMD the LDS admits (128 KiB a WGP, a block's eight waves over four SIMDs): + // stating it keeps the compiler from trading the stage registers for waves it cannot get. + static constexpr int Waves = 2 * (131072 / Lds > 8 ? 8 : 131072 / Lds); +}; +template +__global__ __launch_bounds__(256) + R4D_WAVES((MxP64::Waves)) void moe_mxfp4_p64_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + using G = MxP64; + constexpr int Threads = G::Threads, WC = G::WC, TC = G::TC, KB = G::KB, AK = G::AK, PA = G::PA, + PB = G::PB; + constexpr int PO = G::PO, TPA = G::TPA, TPW = G::TPW, SAK = G::SAK; + static_assert(BM % 16 == 0 && 8 % G::WR == 0 && TC >= 1 && TC * 16 * WC == BN && + (Resident || CT == 1) && G::ACh >= 1 && G::WCh >= 1 && BN * KB <= Threads && + BM * SAK <= Threads && !(DB && Resident) && G::Lds <= 65536, + "stage chunks must divide evenly over the block, in 64 KiB of LDS"); + constexpr int NB = G::NB; + __shared__ __align__(16) uint8_t aa[NB * BM * PA], bb[G::BB]; + __shared__ __align__(16) float ss[NB * 4 * KB * BN], sa[NB * SAK * BM]; + __shared__ int src[BM]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, wave_row = wave / WC, + wave_col = wave % WC; + const int colb = blockIdx.x * (BN * CT), job = blockIdx.y, + tail = offset[m.experts] / BM + m.experts; + if (job >= tail) { + const int r0 = offset[m.experts] + (job - tail) * BM, rows = min(r0 + BM, m.T) - r0; + for (int i = tid; i < rows * BN * CT; i += Threads) { + const int n = colb + i % (BN * CT); + if (n < m.N) y[(long)(r0 + i / (BN * CT)) * m.yr + n] = 0; + } + return; + } + int lo = 0, hi = m.experts; + while (lo + 1 < hi) { + const int mid = (lo + hi) / 2; + if (offset[mid] / BM + mid <= job) + lo = mid; + else + hi = mid; + } + const int first = offset[lo] + (job - (offset[lo] / BM + lo)) * BM, + end = min(first + BM, offset[lo + 1]); + if (first >= end) return; + const int cls = lo & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2); + if (tid < BM) { + const int r = first + tid, flat = r < end ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + lds_barrier(); + // A thread's A chunks share one row and its weight chunks one column, so each keeps a single + // row pointer; neighbouring threads cover neighbouring 16 bytes, as one coalesced row. + const int arow = tid / TPA, a0 = tid % TPA, a_src = src[arow]; + const uint8_t* ap = a + (long)max(a_src, 0) * m.ar + a0 * 16; + const int wcol = tid / TPW, w0c = tid % TPW, ecol = tid / KB, ekb = tid % KB, skb = tid / BM; + const int sa_src = tid < BM * SAK ? src[tid % BM] : -1; + const float* asp = as + (long)max(sa_src, 0) * m.asr; + const int rowbase = wave_row * 16 + (lane >> 4) * 8, colw = wave_col * 16 * TC; + const bool live = first + wave_row * 16 < end; + const uint8_t *wp = w, *ep = ws; + bool wvalid = false, evalid = false; + auto columns = [&](int col0) { + const int wn = col0 + wcol, wi = wn % pw, en = col0 + ecol, ei = en % pw; + wvalid = wn < m.N && wi < cw; + wp = w + (long)((wn / pw) * cw + wi) * m.wrow[cls] + w0c * 16; + evalid = tid < BN * KB && en < m.N && ei < cw; + ep = ws + (long)((en / pw) * cw + ei) * m.srow[cls]; + }; + if constexpr (Resident) { +#pragma unroll + for (int i = 0; i < G::RCh; ++i) { + const int d = (a0 + i * TPA) * 16; + r4d_u32x4 v{ 0, 0, 0, 0 }; + if (a_src >= 0 && d < kc) __builtin_memcpy(&v, ap + i * TPA * 16, 16); + *reinterpret_cast(aa + arow * PA + d) = v; + } + if (tid < BM * SAK) sa[tid] = sa_src >= 0 && skb * 128 < kc ? asp[skb] : 0; + } + const int ksn = (kc + StageK - 1) / StageK, + tiles = Resident ? min(CT, (m.N - colb + BN - 1) / BN) : 1, S = tiles * ksn; + r4d_u32x4 ra[Resident ? 1 : G::ACh], rw[G::WCh]; + uint32_t re = 0x7f7f7f7fu; + float rsa = 0; + int cur = -1; + auto load = [&](int s) { + const int tile = s / ksn, k0 = (s - tile * ksn) * StageK; + if (tile != cur) { + cur = tile; + columns(colb + tile * BN); + } + if constexpr (!Resident) { +#pragma unroll + for (int i = 0; i < G::ACh; ++i) { + ra[i] = r4d_u32x4{ 0, 0, 0, 0 }; + if (a_src >= 0 && k0 + (a0 + i * TPA) * 16 < kc) + __builtin_memcpy(&ra[i], ap + k0 + i * TPA * 16, 16); + } + if (tid < BM * KB) rsa = sa_src >= 0 && k0 + skb * 128 < kc ? asp[k0 / 128 + skb] : 0; + } +#pragma unroll + for (int i = 0; i < G::WCh; ++i) { + rw[i] = r4d_u32x4{ 0, 0, 0, 0 }; + if (wvalid && k0 + (w0c + i * TPW) * 32 < kc) + rw[i] = mx_ldg16(wp + k0 / 2 + i * TPW * 16); + } + re = 0x7f7f7f7fu; + if (evalid && k0 + ekb * 128 < kc) re = mx_ldg4(ep + (k0 + ekb * 128) / 32); + }; + auto store = [&](int b) { + if constexpr (!Resident) { +#pragma unroll + for (int i = 0; i < G::ACh; ++i) + *reinterpret_cast(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) = + ra[i]; + if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa; + } +#pragma unroll + for (int i = 0; i < G::WCh; ++i) { +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 + + 8 * t) = mx_codes8(rw[i][t]); + } + if (tid < BN * KB) { +// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable +// subnormal, and code 255 is NaN. +#pragma unroll + for (int g = 0; g < 4; ++g) { + const uint32_t exp = (re >> (8 * g)) & 0xffu; + ss[b * 4 * KB * BN + (ekb * 4 + g) * BN + ecol] = + __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); + } + } + }; + r4d_fp8::f8v total[TC]; +#pragma unroll + for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero(); + auto compute = [&](int s, int b) { + const int k0 = (s % ksn) * StageK; + const uint8_t *ab = aa + b * BM * PA, *bp = bb + b * BN * PB; + const float* sp = ss + b * 4 * KB * BN; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const float* sar = sa + b * SAK * BM + (Resident ? k0 / 128 + kb : kb) * BM + rowbase; + float activation[8]; +#pragma unroll + for (int row = 0; row < 8; ++row) activation[row] = sar[row]; + const int ka = (Resident ? k0 : 0) + kb * 128; +#pragma unroll + for (int group = 0; group < 4; ++group) { + const auto fa0 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32, lane); + const auto fa1 = r4d_fp8::frag(ab, wave_row * 16, ka + group * 32 + 16, lane); +#pragma unroll + for (int t = 0; t < TC; ++t) { + auto raw = r4d_fp8::mma( + fa0, r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32, lane), + r4d_fp8::acc_zero()); + raw = r4d_fp8::mma( + fa1, + r4d_fp8::frag(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane), + raw); + const float scale = sp[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)]; +// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0. +#pragma unroll + for (int row = 0; row < 8; ++row) + total[t][row] += raw[row] * activation[row] * scale; + } + // One group's TC chains at a time: they already give the WMMA pipe independent + // work, and a second group in flight would double the raw registers. + sched_barrier(); + } + } + }; + auto epilogue = [&](int col0) { + if (m.stage_out) { + if (live) { +#pragma unroll + for (int t = 0; t < TC; ++t) { +#pragma unroll + for (int row = 0; row < 8; ++row) + *reinterpret_cast(bb + (rowbase + row) * PO + + 2 * (colw + t * 16 + (lane & 15))) = + src[rowbase + row] >= 0 ? f32_to_bf16(total[t][row]) : 0; + } + } + lds_barrier(); + for (int j = tid; j < BM * BN / 8; j += Threads) { + const int r = j / (BN / 8), c = (j % (BN / 8)) * 8, n = col0 + c; + if (first + r >= end || n >= m.N) continue; + const r4d_u32x4 v = *reinterpret_cast(bb + r * PO + 2 * c); + uint16_t* dst = y + (long)(first + r) * m.yr + n; + if (m.out16 && n + 8 <= m.N) + *reinterpret_cast(dst) = v; + else + for (int q = 0; q < 8 && n + q < m.N; ++q) + dst[q] = (uint16_t)(v[q / 2] >> (16 * (q & 1))); + } + lds_barrier(); + } else if (live) { +#pragma unroll + for (int t = 0; t < TC; ++t) { +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = first + rowbase + row, n = col0 + colw + t * 16 + (lane & 15); + if (r < end && n < m.N) + y[(long)r * m.yr + n] = + src[rowbase + row] >= 0 ? f32_to_bf16(total[t][row]) : 0; + } + } + } + }; + load(0); + if constexpr (DB) { + store(0); + lds_barrier(); + } + for (int s = 0; s < S; ++s) { + if constexpr (DB) { + if (s + 1 < S) load(s + 1); + if (live) compute(s, s & 1); + if (s + 1 < S) store((s + 1) & 1); + } else { + store(0); + lds_barrier(); + if (s + 1 < S) load(s + 1); + if (live) compute(s, 0); + } + lds_barrier(); + if (s % ksn == ksn - 1) { + epilogue(colb + (s / ksn) * BN); +#pragma unroll + for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero(); + } + } +} + +/* The decode form, expert-major: a block per (column block, expert) takes every row of its expert + * in 16-row tiles, so an expert slice is read from memory once however its rows fall in the + * sorted order (row groups re-read it once per group its run spans). Parallelism is column + * blocks times touched experts. Split-K would sum partials in another order than the row-group + * form and lose its bits, so each element keeps that form's sequence: per 128 of K in order, per + * 32-wide group a fresh WMMA pair, folded as raw * activation scale * E8M0 scale. + * + * A stage of StageK of K is loaded into registers while the previous one computes from LDS; at + * gate_up's K of 4096 the 256 stage measured fastest. Block row `experts` zeroes the dropped rows + * past offset[experts]. */ +template +__global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + constexpr int BN = 16 * Waves, Threads = 32 * Waves, KB = StageK / 128, P = StageK + 8; + constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads; + constexpr int SChunks = (BN * KB + Threads - 1) / Threads; + static_assert(StageK % Threads == 0 && (BN * StageK / 32) % Threads == 0 && 16 * KB <= Threads, + "stage chunks must divide evenly over the block"); + __shared__ __align__(16) uint8_t aa[16 * P], bb[BN * P]; + __shared__ uint32_t ss[BN * KB]; + __shared__ float sa[16 * KB]; + __shared__ int src[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, col0 = blockIdx.x * BN, + e = blockIdx.y; + if (e == m.experts) { + const int r0 = offset[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * BN; i += Threads) { + const int n = col0 + (int)(i % BN); + if (n < m.N) y[(long)(r0 + i / BN) * m.yr + n] = 0; + } + return; + } + const int lo = offset[e], hi = offset[e + 1]; + if (lo >= hi) return; + const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2); + const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15); + auto wrow = [&](int c, bool& valid) { + const int n = col0 + c, within = n % pw; + valid = n < m.N && within < cw; + return (n / pw) * cw + within; + }; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + uint4 ra[AChunks], rw[WChunks]; + uint32_t rs[SChunks]; + float rsa = 0; + auto load = [&](int k0) { +#pragma unroll + for (int i = 0; i < AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16, ar = src[r]; + ra[i] = uint4{ 0, 0, 0, 0 }; + if (ar >= 0 && k0 + d < kc) + __builtin_memcpy(&ra[i], a + (long)ar * m.ar + k0 + d, 16); + } +#pragma unroll + for (int i = 0; i < WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + bool valid; + const int wn = wrow(c, valid); + rw[i] = uint4{ 0, 0, 0, 0 }; + if (valid && k0 + 2 * d < kc) + __builtin_memcpy(&rw[i], w + (long)wn * m.wrow[cls] + k0 / 2 + d, 16); + } +#pragma unroll + for (int i = 0; i < SChunks; ++i) { + const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128; + bool valid; + const int wn = wrow(c, valid); + rs[i] = 0x7f7f7f7fu; + if (j < BN * KB && valid && kb < kc) + __builtin_memcpy(&rs[i], ws + (long)wn * m.srow[cls] + kb / 32, 4); + } + if (tid < 16 * KB) { + const int ar = src[tid / KB], kb = k0 + (tid % KB) * 128; + rsa = ar >= 0 && kb < kc ? as[(long)ar * m.asr + kb / 128] : 0; + } + }; + auto store = [&]() { +#pragma unroll + for (int i = 0; i < AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16; + *reinterpret_cast(aa + r * P + d) = ra[i]; + } +#pragma unroll + for (int i = 0; i < WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + const uint32_t q[4] = { rw[i].x, rw[i].y, rw[i].z, rw[i].w }; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]); + } +#pragma unroll + for (int i = 0; i < SChunks; ++i) { + const int j = tid + i * Threads; + if (j < BN * KB) ss[j] = rs[i]; + } + if (tid < 16 * KB) sa[tid] = rsa; + }; + auto total = r4d_fp8::acc_zero(); + load(0); + for (int k0 = 0; k0 < kc; k0 += StageK) { + store(); + __syncthreads(); + if (k0 + StageK < kc) load(k0 + StageK); +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const uint32_t exps = ss[mycol * KB + kb]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128 + group * 32; k < kb * 128 + (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(aa, 0, k, lane), + r4d_fp8::frag(bb, wave * 16, k, lane), raw); + const uint32_t exp = (exps >> (8 * group)) & 0xffu; + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) + if (rv[row]) total[row] += raw[row] * sa[(rowbase + row) * KB + kb] * scale; + } + } + __syncthreads(); + } +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = r0 + rowbase + row, n = col0 + mycol; + if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + } +} + +/* The expert-major form for a short K, same per-element sequence as the one above: a block walks + * ColTiles column tiles of 64, each over K in stages of StageK, as one stage sequence with the + * next stage loaded into registers while the current one computes. At down's K of 256 a single + * stage leaves a block nothing to overlap; 128 stages over four tiles give it eight, and halve + * LDS and registers a block, so twice the blocks are resident. Measured fastest for down at + * every routed-row count up to 16384, prefill forms included. A deeper prefetch, two-wave + * blocks and non-temporal weight loads measured slower. */ +typedef unsigned mx_u4 __attribute__((ext_vector_type(4))); +template +struct MxStage { + static constexpr int Threads = 128, BN = 64, KB = StageK / 128; + static constexpr int AChunks = StageK / Threads, WChunks = BN * StageK / 32 / Threads; + static constexpr int SChunks = (BN * KB + Threads - 1) / Threads; + mx_u4 a[AChunks], w[WChunks]; + uint32_t s[SChunks]; + float sa; +}; +template +__global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel( + const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1, + const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) { + using St = MxStage; + constexpr int BN = St::BN, Threads = St::Threads, KB = St::KB, P = StageK + 8; + static_assert(StageK % Threads == 0 && (BN * StageK / 32) % Threads == 0 && 16 * KB <= Threads, + "stage chunks must divide evenly over the block"); + __shared__ __align__(16) uint8_t aa[16 * P], bb[BN * P]; + __shared__ uint32_t ss[BN * KB]; + __shared__ float sa[16 * KB]; + __shared__ int src[16]; + const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, e = blockIdx.y; + const int colb = blockIdx.x * (BN * ColTiles); + if (e == m.experts) { + const int r0 = offset[m.experts]; + for (long i = tid; i < (long)(m.T - r0) * BN * ColTiles; i += Threads) { + const int n = colb + (int)(i % (BN * ColTiles)); + if (n < m.N) y[(long)(r0 + i / (BN * ColTiles)) * m.yr + n] = 0; + } + return; + } + const int lo = offset[e], hi = offset[e + 1]; + if (lo >= hi) return; + const int cls = e & 1, kc = m.k[cls], pw = m.N / m.parts, cw = m.n[cls] / m.parts; + const auto* w = entry(cls ? w1 : w0, m.wstep[cls], e / 2); + const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], e / 2); + const int ksn = (kc + StageK - 1) / StageK, tiles = min(ColTiles, (m.N - colb + BN - 1) / BN), + S = tiles * ksn; + const int rowbase = (lane >> 4) * 8, mycol = wave * 16 + (lane & 15); + auto wrow = [&](int n, bool& valid) { + const int within = n % pw; + valid = n < m.N && within < cw; + return (n / pw) * cw + within; + }; + for (int r0 = lo; r0 < hi; r0 += 16) { + __syncthreads(); + if (tid < 16) { + const int r = r0 + tid, flat = r < hi ? sorted[r] : -1; + const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk; + src[tid] = ar >= 0 && ar < m.Arows ? ar : -1; + } + __syncthreads(); + bool rv[8]; +#pragma unroll + for (int j = 0; j < 8; ++j) rv[j] = src[rowbase + j] >= 0; + auto load = [&](int s, St& R) { + const int col0 = colb + (s / ksn) * BN, k0 = (s % ksn) * StageK; +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16, ar = src[r]; + R.a[i] = mx_u4{ 0, 0, 0, 0 }; + if (ar >= 0 && k0 + d < kc) + __builtin_memcpy(&R.a[i], a + (long)ar * m.ar + k0 + d, 16); + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; + bool valid; + const int wn = wrow(col0 + c, valid); + R.w[i] = mx_u4{ 0, 0, 0, 0 }; + if (valid && k0 + 2 * d < kc) + __builtin_memcpy(&R.w[i], w + (long)wn * m.wrow[cls] + k0 / 2 + d, 16); + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads, c = j / KB, kb = k0 + (j % KB) * 128; + bool valid; + const int wn = wrow(col0 + c, valid); + R.s[i] = 0x7f7f7f7fu; + if (j < BN * KB && valid && kb < kc) + __builtin_memcpy(&R.s[i], ws + (long)wn * m.srow[cls] + kb / 32, 4); + } + if (tid < 16 * KB) { + const int ar = src[tid / KB], kb = k0 + (tid % KB) * 128; + R.sa = ar >= 0 && kb < kc ? as[(long)ar * m.asr + kb / 128] : 0; + } + }; + auto store = [&](const St& R) { +#pragma unroll + for (int i = 0; i < St::AChunks; ++i) { + const int j = tid + i * Threads, r = j / (StageK / 16), + d = (j % (StageK / 16)) * 16; + *reinterpret_cast(aa + r * P + d) = R.a[i]; + } +#pragma unroll + for (int i = 0; i < St::WChunks; ++i) { + const int j = tid + i * Threads, c = j / (StageK / 32), + d = (j % (StageK / 32)) * 16; +#pragma unroll + for (int t = 0; t < 4; ++t) + *reinterpret_cast(bb + c * P + 2 * d + 8 * t) = + mx_codes8(R.w[i][t]); + } +#pragma unroll + for (int i = 0; i < St::SChunks; ++i) { + const int j = tid + i * Threads; + if (j < BN * KB) ss[j] = R.s[i]; + } + if (tid < 16 * KB) sa[tid] = R.sa; + }; + auto total = r4d_fp8::acc_zero(); + auto compute = [&](int s) { + const int k0 = (s % ksn) * StageK; +#pragma unroll + for (int kb = 0; kb < KB; ++kb) { + if (k0 + kb * 128 >= kc) break; + const uint32_t exps = ss[mycol * KB + kb]; +#pragma unroll + for (int group = 0; group < 4; ++group) { + auto raw = r4d_fp8::acc_zero(); +#pragma unroll + for (int k = kb * 128 + group * 32; k < kb * 128 + (group + 1) * 32; k += 16) + raw = r4d_fp8::mma(r4d_fp8::frag(aa, 0, k, lane), + r4d_fp8::frag(bb, wave * 16, k, lane), raw); + const uint32_t exp = (exps >> (8 * group)) & 0xffu; + const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u + : exp ? (exp << 23) + : 0x00400000u); +#pragma unroll + for (int row = 0; row < 8; ++row) + if (rv[row]) total[row] += raw[row] * sa[(rowbase + row) * KB + kb] * scale; + } + } + if (s % ksn == ksn - 1) { + const int n = colb + (s / ksn) * BN + mycol; +#pragma unroll + for (int row = 0; row < 8; ++row) { + const int r = r0 + rowbase + row; + if (r < hi && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]); + } + total = r4d_fp8::acc_zero(); + } + }; + St R; + load(0, R); + for (int s = 0; s < S; ++s) { + store(R); + __syncthreads(); + if (s + 1 < S) load(s + 1, R); + compute(s); + __syncthreads(); + } + } +} + +int table(const RadTensor* t, uint32_t dtype, int bits, long experts, long n, long k, long* step, + int* row) { + if (!t || !t->data || t->rank != 3 || t->dtype != dtype || t->shape[0] < experts || + t->shape[1] != n || t->shape[2] != k || t->stride[2] != 1 || t->stride[1] < k || + (t->stride[1] * bits) % 8 || t->stride[1] * bits / 8 > INT_MAX) + return RAD_E_SHAPE; + if (t->stride[0] && (t->stride[0] < n * t->stride[1] || (t->stride[0] * bits) % 8)) + return RAD_E_STRIDE; + *step = t->stride[0] * bits / 8; + *row = (int)(t->stride[1] * bits / 8); + return RAD_OK; +} +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 9) return RAD_E_INVAL; + const auto *aq = rad_arg_in(a, 0), *as = rad_arg_in(a, 1), *sorted = rad_arg_in(a, 4), + *off = rad_arg_in(a, 5); + const auto* y = rad_arg_in(a, 8); + if (!aq || !as || !sorted || !off || !y) return RAD_E_INVAL; + MxMeta m{}; + const long n0 = r4d_geti_or(a, "N", 0), k0 = r4d_geti_or(a, "K", 0); + const long nn[2] = { n0, r4d_geti_or(a, "N_odd", n0) }, + kk[2] = { k0, r4d_geti_or(a, "K_odd", k0) }; + const long ne = r4d_geti_or(a, "n_expert", 0), top = r4d_geti_or(a, "top_k", 0), + parts = r4d_geti_or(a, "parts", 1); + if (ne < 2 || ne > 512 || top < 1 || top > ne || parts < 1 || parts > INT_MAX || + r4d_geti_or(a, "group", 0) != 128) + return RAD_E_SHAPE; + const RadTensor* w[2] = { rad_arg_in(a, 2), rad_arg_in(a, 6) }; + const RadTensor* s[2] = { rad_arg_in(a, 3), rad_arg_in(a, 7) }; + for (int q = 0; q < 2; ++q) { + if (nn[q] < 1 || nn[q] > INT_MAX - 16 || kk[q] < 128 || kk[q] > INT_MAX || kk[q] % 128 || + nn[q] % parts) + return RAD_E_SHAPE; + m.n[q] = (int)nn[q]; + m.k[q] = (int)kk[q]; + int rc = + table(w[q], RAD_FP4E2M1, 4, (ne + 1 - q) / 2, nn[q], kk[q], &m.wstep[q], &m.wrow[q]); + if (rc < 0) return rc; + const uint32_t dt = s[q] ? s[q]->dtype : 0; + if (dt != RAD_U8 && dt != RAD_E8M0) return RAD_E_DTYPE; + rc = table(s[q], dt, 8, (ne + 1 - q) / 2, nn[q], kk[q] / 32, &m.sstep[q], &m.srow[q]); + if (rc < 0) return rc; + } + m.N = (int)std::max(nn[0], nn[1]); + m.K = (int)std::max(kk[0], kk[1]); + if (aq->dtype != RAD_F8E4M3 || as->dtype != RAD_F32 || y->dtype != RAD_BF16 || + sorted->dtype != RAD_I32 || off->dtype != RAD_I32) + return RAD_E_DTYPE; + if (aq->rank != 2 || aq->shape[0] > INT_MAX || aq->shape[1] != m.K || aq->stride[1] != 1 || + aq->stride[0] < m.K || as->rank != 2 || as->shape[0] != aq->shape[0] || + as->shape[1] != m.K / 128 || as->stride[1] != 1 || as->stride[0] < m.K / 128 || + y->rank != 2 || y->shape[0] < 1 || y->shape[0] > INT_MAX || y->shape[1] != m.N || + y->stride[1] != 1 || y->stride[0] < m.N || sorted->rank != 1 || sorted->stride[0] != 1 || + sorted->shape[0] < y->shape[0] || off->rank != 1 || off->stride[0] != 1 || + off->shape[0] < ne + 1) + return RAD_E_SHAPE; + const char* ord = r4d_gets(a, "a_order"); + if (!ord || (std::strcmp(ord, "token") && std::strcmp(ord, "sorted"))) return RAD_E_INVAL; + m.sorted_a = !std::strcmp(ord, "sorted"); + m.T = (int)y->shape[0]; + m.Arows = (int)aq->shape[0]; + if (m.T % top || m.Arows < (m.sorted_a ? m.T : m.T / top)) return RAD_E_SHAPE; + m.experts = (int)ne; + m.topk = (int)top; + m.parts = (int)parts; + m.ar = aq->stride[0]; + m.asr = as->stride[0]; + m.yr = y->stride[0]; + m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16; + // Validated GLM projections at TP4 and TP8: retain the small/decode path and other models. + const bool glm_prefill = ne == 288 && top == 8 && nn[0] == nn[1] && kk[0] == kk[1] && + ((parts == 2 && (nn[0] == 1024 || nn[0] == 512) && kk[0] == 4096) || + (parts == 1 && nn[0] == 4096 && (kk[0] == 512 || kk[0] == 256))); + auto enabled = [&](const char* name) { + const char* v = std::getenv(name); + return v ? v[0] == '1' : glm_prefill; + }; + /* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted + * rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form + * overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice + * 2.2 times less often and wins by a quarter). Other shapes keep the decode band. The environment + * moves the bounds, forces either side (RADIANCE_MXFP4_DECODE_EXPERTS 0 or 1) and pins stage + * and tiles, for the microbenchmark. */ + const char* lut_env = std::getenv("RADIANCE_MXFP4_LUT"); + const bool lut = lut_env ? lut_env[0] == '1' : true; + auto env_long = [](const char* name, long dflt) { + const char* v = std::getenv(name); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + const long max_t = + env_long(m.sorted_a ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" + : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", + glm_prefill && (nn[0] == 512 || kk[0] == 256) ? (m.sorted_a ? 6143 : 768) : 511); + const char* experts_env = std::getenv("RADIANCE_MXFP4_DECODE_EXPERTS"); + /* The P64 form from a routed-row bound per projection, ahead of the expert-major band (its + * down bound overlaps it): gate_up from 769 rows, where the prefill forms begin, down from + * 20 rows an expert at GLM's 288. Default at GLM's TP8 slices only, the measured ones + * (RADIANCE_MXFP4_PREFILL_P64=0 keeps the TP8 prefill form of stage 1, which also takes a grid + * P64 cannot address). The + * tile follows the rows an expert, measured at the TP8 slices (perfmx, cold): down BM32 BN64 + * K128 over four column tiles up to 3072 tokens (2048: 647 against 831 us), above BM64 BN128 + * K128 x4 with the LDS output (4096: 1101 against 1607); gate_up BM32 BN64 K256 up to 1536 + * tokens (768: 563 against 660), BM64 BN64 K256 up to 3072 (2048: 941 against 995), above + * BM64 BN128 K128 with the LDS output (4096: 1715 against 1915). BM, BN, stage, column tiles, + * the LDS output, the double buffer and the three row bounds move with the environment, and a + * forced expert-major form (DECODE_EXPERTS=1) keeps precedence. */ + const char* p64_env = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); + const bool resident = m.K <= 256; + long dbm = 32, dbn = 64, dsk = 128, dout = 0; + if (resident) { + if (m.T >= env_long("RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", 24576)) { + dbm = 64; + dbn = 128; + dout = 1; + } + } else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BM64", 12288)) + dsk = 256; + else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BN128", 24576)) { + dbm = 64; + dsk = 256; + } else { + dbm = 64; + dbn = 128; + dout = 1; + } + const long bm = env_long("RADIANCE_MXFP4_PREFILL_P64_BM", dbm) == 32 ? 32 : 64; + const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256); + if ((p64_env ? p64_env[0] == '1' : tp8) && !(experts_env && experts_env[0] == '1') && + m.T >= env_long(m.sorted_a ? "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN" + : "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + m.sorted_a ? 5760 : 769) && + (m.T + bm - 1) / bm + m.experts <= 65535) { + const long bn = env_long("RADIANCE_MXFP4_PREFILL_P64_BN", dbn) == 64 ? 64 : 128; + const long sk = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", dsk) == 256 ? 256 : 128; + const long ct = resident && env_long("RADIANCE_MXFP4_PREFILL_P64_COLTILES", 4) != 1 ? 4 : 1; + m.stage_out = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", dout) == 1; + // The double buffer exists where two stages fit in 64 KiB of LDS: every 128 stage, and + // the 256 stage at BM32 BN64. + const bool db = !resident && env_long("RADIANCE_MXFP4_PREFILL_P64_DB", 0) == 1 && + (sk == 128 || (bm == 32 && bn == 64)); + m.out16 = (reinterpret_cast(y->data) & 15) == 0 && m.yr % 8 == 0; + const long jobs = (m.T + bm - 1) / bm + m.experts; +#define MX_P64(BM, BN, SK, CT, R) \ + R4D_EMIT(stream, (moe_mxfp4_p64_kernel), \ + dim3(((long)m.N + BN * CT - 1) / (BN * CT), jobs), dim3(256), 0, \ + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ + s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) +#define MX_P64D(BM, BN, SK) \ + R4D_EMIT(stream, (moe_mxfp4_p64_kernel), \ + dim3(((long)m.N + BN - 1) / BN, jobs), dim3(256), 0, (const uint8_t*)aq->data, \ + (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, s[1]->data, \ + (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) + if (db) { + if (sk == 256) return MX_P64D(32, 64, 256); + if (bm == 32) return bn == 64 ? MX_P64D(32, 64, 128) : MX_P64D(32, 128, 128); + return bn == 64 ? MX_P64D(64, 64, 128) : MX_P64D(64, 128, 128); + } +#undef MX_P64D +#define MX_P64_SK(BM, BN, CT, R) \ + return sk == 256 ? MX_P64(BM, BN, 256, CT, R) : MX_P64(BM, BN, 128, CT, R); +#define MX_P64_BN(BM, CT, R) \ + if (bn == 64) { MX_P64_SK(BM, 64, CT, R) } \ + MX_P64_SK(BM, 128, CT, R) +#define MX_P64_BM(CT, R) \ + if (bm == 32) { MX_P64_BN(32, CT, R) } \ + MX_P64_BN(64, CT, R) + if (!resident) { MX_P64_BM(1, false) } + if (ct == 1) { MX_P64_BM(1, true) } + MX_P64_BM(4, true) +#undef MX_P64_BM +#undef MX_P64_BN +#undef MX_P64_SK +#undef MX_P64 + } + if (experts_env ? experts_env[0] == '1' : max_t < 0 || m.T <= max_t) { + const long stage = env_long("RADIANCE_MXFP4_EXPERTS_STAGE_K", m.K <= 256 ? 128 : 256); + const long tiles = env_long("RADIANCE_MXFP4_EXPERTS_COLTILES", m.K <= 256 ? 4 : 1); +#define MX_EXPERTS(KERNEL, C) \ + R4D_EMIT(stream, KERNEL, dim3(((long)m.N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), \ + 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ + (uint16_t*)y->data, m) +#define MX_EXPERTS_LUT(L) \ + if (stage == 128) \ + return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4, L>), 4) \ + : MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 1, L>), 1); \ + return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<256, 4, L>), 4) \ + : MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256, L>), 1); + if (lut) { MX_EXPERTS_LUT(true) } + MX_EXPERTS_LUT(false) +#undef MX_EXPERTS_LUT +#undef MX_EXPERTS + } + m.aligned_jobs = enabled("RADIANCE_MXFP4_ALIGNED_JOBS") && m.T >= 512; + const bool wide = enabled("RADIANCE_MXFP4_PREFILL_N32") && m.T >= 512; + const bool tall = wide && m.aligned_jobs && enabled("RADIANCE_MXFP4_PREFILL_M32"); + const int job_rows = tall ? 32 : 16; + const int jobs = + m.aligned_jobs ? (m.T + job_rows - 1) / job_rows + m.experts : (m.T + m.tile - 1) / m.tile; + if (jobs > 65535) return RAD_E_SHAPE; +#define MX_EMIT(CT, RT, CACHE, L) \ + R4D_EMIT(stream, (moe_mxfp4_fp8_kernel), \ + dim3(((long)m.N + 16 * CT - 1) / (16 * CT), jobs), dim3(32 * CT * RT), 0, \ + (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \ + s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m) +#define MX_PIPE(L) \ + R4D_EMIT(stream, (moe_mxfp4_prefill_kernel), dim3(((long)m.N + 63) / 64, jobs), dim3(256), \ + 0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \ + w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \ + (uint16_t*)y->data, m) + const char* cached = std::getenv("RADIANCE_MXFP4_PREFILL_CACHE_ROWS"); + const bool pipe = enabled("RADIANCE_MXFP4_PREFILL_PIPE"); +#define MX_EMIT_LUT(L) \ + if (tall && enabled("RADIANCE_MXFP4_PREFILL_N64")) { \ + if (cached ? cached[0] == '1' : glm_prefill) \ + return pipe ? MX_PIPE(L) : MX_EMIT(4, 2, true, L); \ + return MX_EMIT(4, 2, false, L); \ + } \ + if (tall) return MX_EMIT(2, 2, false, L); \ + if (wide) return MX_EMIT(2, 1, false, L); \ + return MX_EMIT(1, 1, false, L); + if (lut) { MX_EMIT_LUT(true) } + MX_EMIT_LUT(false) +#undef MX_EMIT_LUT +#undef MX_PIPE +#undef MX_EMIT +} +} +extern "C" int r4d_rad_moe_mxfp4(const RadArgs* a, RadStream stream) { return body(a, stream); } diff --git a/libr4d/r4d_moe_sort.h b/libr4d/r4d_moe_sort.h new file mode 100644 index 00000000..12ccba6a --- /dev/null +++ b/libr4d/r4d_moe_sort.h @@ -0,0 +1,198 @@ +// r4d_moe_sort.h -- the routed slots' stable counting sort in one workgroup, shared by every +// kernel that ends in it: moe_scatter's small form and router_topk_scatter (r4d_moe.hip), and +// GLM's router_sigmoid_topk_scatter (r4d_glm.hip). One definition, so a fused selection and the +// standalone sort place every slot alike; tests/r4d_emu runs it from here. +#pragma once +#include +#include +#include + +#include "r4d_args.h" +#include "r4d_common.h" + +// Internal linkage, as each unit's own definitions had: the same code generation in every kernel +// that takes the sort. +namespace r4d_moesort { +namespace { + +constexpr uint32_t kSortWave = 32; +/* Expert-count ceiling, a hard limit of these kernels: the router keeps a lane's logits in + * registers (MAXOWN) and both scatter forms keep n_expert + 1 counters in LDS. 512 covers + * Qwen3.8-Flash-Next (512 experts of 640, top-10) for 4 KiB of scatter LDS and a second router + * instantiation. */ +constexpr uint32_t kMaxExpert = 512; + +/* Protected experts of a slice, sorted last. A layer may keep a few experts (those whose output + * dwarfs the rest) at higher precision, and one grouped GEMM takes one weight format, so the sort + * places their runs after all others, in the listed order, and two GEMMs serve [0, n - p) and + * [n - p, n) of the offsets. Local indices, strictly ascending; p <= kMaxProtect. With none, an + * expert's place is itself. */ +constexpr uint32_t kMaxProtect = 8; +struct Protect { + uint32_t n; + uint16_t e[kMaxProtect]; +}; + +/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */ +__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) { + int32_t below = 0; + for (uint32_t j = 0; j < p.n; ++j) { + if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j); + below += (int32_t)p.e[j] < e; + } + return e - below; +} + +/* `protect`, a comma list of local expert indices: strictly ascending, inside the slice, at most + * kMaxProtect. Absent or empty is none. */ +inline int protect_of(const RadArgs* a, long long n_local, Protect* p) { + *p = Protect{}; + const char* s = r4d_gets(a, "protect"); + if (!s) return RAD_OK; + long long prev = -1; + while (*s) { + char* end = nullptr; + const long long v = std::strtoll(s, &end, 10); + if (end == s || v <= prev || v >= n_local || p->n >= kMaxProtect) + return R4D_NO(RAD_E_SHAPE); + p->e[p->n++] = (uint16_t)v; + prev = v; + s = end; + if (*s == ',') ++s; + else if (*s) return R4D_NO(RAD_E_SHAPE); + } + return RAD_OK; +} + +/* ================================================================== the small sort + * + * One workgroup does the whole sort, for T <= kScatterSmall, which covers every decode and verify + * step (eight sequences at depth 3 and top_k 10 is T = 320), in one launch instead of three. + * Histogram in LDS, offsets an exclusive prefix over n_expert <= kMaxExpert counts, and each slot + * placed by its rank inside its expert's run. + * + * On one workgroup the critical path (barriers, serial LDS chains) is the cost, not the work: + * + * - The prefix is a DPP scan inside each wave plus one exchange of wave totals through LDS: one + * barrier per tile of 32 counts per wave (at most two tiles at eight waves for 512 experts). + * - Placement groups first and orders after. The histogram atomic hands each slot a ticket in its + * expert's run (arrival order); slots are gathered into runs in ticket order, then each slot's + * place is the number of the run's slots with a lower index. That count is as long as the run + * (a row picks an expert at most once), far shorter than counting all earlier slots. + * + * Stable and byte-identical: a slot's place is its position among the same expert's slots in + * ascending i, as in the reference, whatever the ticket order. Every barrier orders LDS only, so + * none waits on or invalidates the vector memory path. */ +constexpr uint32_t kScatterSmall = 1024; + +/* The small sort's LDS (about 16 KiB), defined once for the standalone and fused kernels. NW is the + * workgroup's wave count, which sizes the scan's exchange. */ +template +struct ScatterLds { + static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave); + int32_t e[kScatterSmall]; /* the slot list: expert in the slice, or -1 */ + int32_t tk[kScatterSmall]; /* the slot's ticket inside its expert's run */ + int32_t run[kScatterSmall]; /* slots grouped by expert, tickets' order */ + int32_t cnt[kMaxExpert + 1]; + int32_t off[kMaxExpert + 1]; + int32_t wt[kTiles][NW]; /* each wave's total, a slot per tile */ +}; + +/* Inclusive prefix sum over a wave32 with DPP row shifts: four steps within each 16-lane row, then + * the upper row adds the lower row's total. Lanes shifted in from outside the row read zero + * (bound_ctrl). */ +__device__ __forceinline__ int32_t wave_incl_scan_i32(int32_t x, uint32_t lane) { + x += __builtin_amdgcn_update_dpp(0, x, 0x111, 0xF, 0xF, true); /* row_shr:1 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x112, 0xF, 0xF, true); /* row_shr:2 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x114, 0xF, 0xF, true); /* row_shr:4 */ + x += __builtin_amdgcn_update_dpp(0, x, 0x118, 0xF, 0xF, true); /* row_shr:8 */ + const int32_t lo = __builtin_amdgcn_readlane(x, 15); + return lane >= 16u ? x + lo : x; +} + +/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has + * written `sl.e[0, T)` and zeroed `sl.cnt[0, n_expert)`, followed by a barrier. Shared by the + * standalone sort and the fused kernels. The workgroup is exactly NW waves. + * + * INV also writes the inverse: `inv[i]` is slot i's row in `sorted`, -1 for a dropped slot, the + * table moe_gather would otherwise build from `sorted`. */ +template +__device__ __forceinline__ void scatter_small_place( + int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, + uint32_t T, uint32_t n_expert, ScatterLds& sl, int32_t* __restrict__ inv = nullptr) { + const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave; + + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1); + } + lds_barrier(); + + /* Every thread sums all NW wave totals, so `carry` (finally the live slot count) is the same + * in every thread. */ + int32_t carry = 0; + for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) { + const uint32_t e = b + tid; + const int32_t v = (e < n_expert) ? sl.cnt[e] : 0; + const int32_t x = wave_incl_scan_i32(v, lane); + if (lane == kSortWave - 1) sl.wt[t][wave] = x; + lds_barrier(); + int32_t below = 0, tot = 0; +#pragma unroll + for (uint32_t k = 0; k < NW; ++k) { + const int32_t c = sl.wt[t][k]; + below += (k < wave) ? c : 0; + tot += c; + } + if (e < n_expert) { + const int32_t o = carry + below + x - v; /* inclusive -> exclusive */ + sl.off[e] = o; + off[e] = o; + cnt[e] = v; + } + carry += tot; + } + if (tid == 0) off[n_expert] = carry; + lds_barrier(); + + for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i; + } + lds_barrier(); + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e < 0) { + if constexpr (INV) inv[i] = -1; + continue; + } + const int32_t o = sl.off[e], n = sl.cnt[e]; + int32_t rank = 0; + for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i; + sorted[o + rank] = (int32_t)i; + if constexpr (INV) inv[i] = o + rank; + } +} + +/* moe_scatter's small form: the slot list from `ids`, then the sort. A template only so a unit that + * includes this header and does not launch it compiles no kernel. */ +constexpr uint32_t kScatWaves = 8; /* 256 threads */ +template +__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel( + const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off, + int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot, + int32_t* __restrict__ inv) { + __shared__ ScatterLds sl; + const uint32_t tid = threadIdx.x; + for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = ids[i] - base; + sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1; + } + lds_barrier(); + scatter_small_place(sorted, off, cnt, T, n_expert, sl, inv); +} + +} // namespace +} // namespace r4d_moesort diff --git a/libr4d/r4d_mxfp4.h b/libr4d/r4d_mxfp4.h index b0d15200..7bb8a002 100644 --- a/libr4d/r4d_mxfp4.h +++ b/libr4d/r4d_mxfp4.h @@ -56,6 +56,15 @@ static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d, unsigned int* lo, unsigned int* hi) { r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi); } +// Row d = 0 as immediates, for kernels that fold the E8M0 scale in F32 and need the exact e2m1 +// values: no table load, v_perm_b32 takes the two words as literals. tests/r4d_emu/test_moemx +// holds them to row 0 of the table. +#define R4D_MXFP4_MAG0_LO 0x3c383000u +#define R4D_MXFP4_MAG0_HI 0x4c484440u +static __device__ __forceinline__ void r4d_mxfp4_unpack8_exact(unsigned int wv, unsigned int* lo, + unsigned int* hi) { + r4d_mxfp4_unpack8_t(wv, R4D_MXFP4_MAG0_LO, R4D_MXFP4_MAG0_HI, lo, hi); +} // The activation scale a row's accumulator is carried in, for the per-(row, 128 of K) grid: the // last non-zero entry of `row` at or before block `kb`, or 1 if none. A zero-scale block has zero diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 52e747c4..7db0f3a9 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -296,6 +296,15 @@ int r4d_rad_dflash_select (const RadArgs*, RadStream); /* -- the gated residual (r4d_hc_bf16.hip) -- */ int r4d_rad_hc_enter (const RadArgs*, RadStream); +int r4d_rad_mhc_pre(const RadArgs*, RadStream); +int r4d_rad_mhc_pre_partial(const RadArgs*, RadStream); +int r4d_rad_mhc_pre_finish(const RadArgs*, RadStream); +int r4d_rad_kda_update(const RadArgs*, RadStream); +int r4d_rad_moe_mxfp4(const RadArgs*, RadStream); +int r4d_rad_layout_moe_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_rad_mhc_post(const RadArgs*, RadStream); +int r4d_rad_mhc_contract(const RadArgs*, RadStream); int r4d_rad_mtp_enter (const RadArgs*, RadStream); int64_t r4d_rad_mtp_enter_scratch(const RadArgs*); int r4d_rad_hc_read (const RadArgs*, RadStream); @@ -604,6 +613,35 @@ int r4d_rad_fill (const RadArgs*, RadStream); int r4d_rad_logit_softcap (const RadArgs*, RadStream); int r4d_rad_scale (const RadArgs*, RadStream); int r4d_rad_silu_mul (const RadArgs*, RadStream); +int r4d_rad_swiglu_clamped(const RadArgs*, RadStream); +int r4d_rad_swiglu_clamped_quant_fp8(const RadArgs*, RadStream); +int r4d_rad_dsa_pool(const RadArgs*, RadStream); +int r4d_shape_dsa_pool(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_dsa_query(const RadArgs*, RadStream); +int r4d_rad_fp8_f32scale(const RadArgs*, RadStream); +int r4d_rad_moe_fp8_f32scale(const RadArgs*, RadStream); +int r4d_layout_fp8_f32scale(const RadParam*, int, int, const RadEncoding*, const int*, + const RadTensor*, int, RadLayout*); +int r4d_shape_dsa_query(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_gemm_nt_f32(const RadArgs*, RadStream); +int r4d_shape_gemm_nt_f32(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_mla_project(const RadArgs*, RadStream); +int r4d_shape_mla_project(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_dsa_score(const RadArgs*, RadStream); +int r4d_shape_dsa_score(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_mla_attn(const RadArgs*, RadStream); +int64_t r4d_rad_mla_attn_scratch(const RadArgs*); +int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream); +int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*); +int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream); +int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_router_sigmoid_topk_scatter(const RadArgs*, RadStream); +int r4d_rad_moe_scatter_inv(const RadArgs*, RadStream); +int r4d_shape_moe_scatter_inv(const RadParam*, int, int, RadOpdDesc*); +int r4d_rad_moe_gather_inv(const RadArgs*, RadStream); +int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_gelu_mul (const RadArgs*, RadStream); int r4d_rad_rope (const RadArgs*, RadStream); /* -- the vision tower's ops (r4d_vit_bf16.hip) -- */ @@ -656,6 +694,13 @@ int r4d_shape_scatter_rows_u8(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_cast (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_enter (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_mhc_pre(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_pre_partial(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_pre_finish(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_kda_update(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_moe_mxfp4(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_post(const RadParam*, int, int, RadOpdDesc*); +int r4d_shape_mhc_contract(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*); @@ -750,6 +795,8 @@ int r4d_shape_dflash_select (const RadParam*, int, int operand, RadOpdDesc*); * Pure host code, like r4d_rows.cpp, r4d_layout.cpp and r4d_shapes.cpp. */ int r4d_fuse_rmsnorm_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gated_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_swiglu_clamped_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index c72dd76b..a4d7038a 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -469,6 +469,50 @@ static const RadParamSpec pHcPlain[] = { static const RadOperandSpec oHcEnter[] = { { "x", RAD_OPD_IN, 0 }, { "h", RAD_OPD_OUT, 0 }, }; +static const RadParamSpec pMhcPre[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"), + P_F64("hc_eps"), P_STR("dtype"), +}; +static const RadOperandSpec oMhcPre[] = { + {"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"scale", RAD_OPD_WEIGHT, 0}, + {"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0}, + {"comb", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pMhcPrePartial[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("chunk"), P_INT("first"), P_INT("chunks"), + P_STR("dtype"), +}; +static const RadOperandSpec oMhcPrePartial[] = { + {"h", RAD_OPD_IN, 0}, {"fn", RAD_OPD_WEIGHT, 0}, {"part", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pMhcPreFinish[] = { + P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("iterations"), P_F64("eps"), + P_F64("hc_eps"), P_INT("chunk"), P_STR("dtype"), +}; +static const RadOperandSpec oMhcPreFinish[] = { + {"part", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"scale", RAD_OPD_WEIGHT, 0}, + {"base", RAD_OPD_WEIGHT, 0}, {"x", RAD_OPD_OUT, 0}, {"post", RAD_OPD_OUT, 0}, + {"comb", RAD_OPD_OUT, 0}, +}; +static const RadOperandSpec oMhcPost[] = { + {"x", RAD_OPD_IN, 0}, {"h", RAD_OPD_IN, 0}, {"post", RAD_OPD_IN, 0}, + {"comb", RAD_OPD_IN, 0}, {"out", RAD_OPD_OUT, 0}, +}; +static const RadOperandSpec oMhcContract[] = { + {"h", RAD_OPD_IN, 0}, {"x", RAD_OPD_OUT, 0}, +}; +static const RadParamSpec pKdaUpdate[] = { + P_INT("M"), P_INT("heads"), P_INT("head_k"), P_INT("head_v"), P_F64("lower_bound"), + P_F64("scale"), P_F64("l2_eps"), P_STR("mode"), P_STR("dtype"), + P_STRO("state_form"), +}; +static const RadOperandSpec oKdaUpdate[] = { + {"q", RAD_OPD_IN, 0}, {"k", RAD_OPD_IN, 0}, {"v", RAD_OPD_IN, 0}, + {"a", RAD_OPD_IN, 0}, {"b", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0}, + {"dt_bias", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0}, + {"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1}, + {"o", RAD_OPD_OUT, 0}, +}; static const RadOperandSpec oHcWrite[] = { { "y", RAD_OPD_IN, 0 }, { "inj", RAD_OPD_IN, 0 }, { "h", RAD_OPD_INOUT, 0 }, }; @@ -816,6 +860,16 @@ static const RadOperandSpec oMoeScatter[] = { { "expert_offset", RAD_OPD_OUT, 0 }, { "expert_count", RAD_OPD_OUT, 0 }, }; +/* moe_scatter with each slot's row in `sorted_tok` beside it: moe_gather_inv reads that table + * instead of rebuilding it. Ops of their own, since the shared vocabulary fixes moe_scatter's and + * moe_gather's operands. */ +static const RadOperandSpec oMoeScatterInv[] = { + { "expert_ids", RAD_OPD_IN, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, + { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 }, + { "inverse", RAD_OPD_OUT, 0 }, +}; /* `a_order` ("token" or "sorted") says which rows the activation has: one per token, gathered * through sorted_tok, or one per (token, slot) already in scatter order. A routed block's two * grouped GEMMs differ (gate_up reads the block input, down reads gate_up's output), and the row @@ -902,6 +956,14 @@ static const RadOperandSpec oMoeGather[] = { { "shared_gate", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, }; +static const RadOperandSpec oMoeGatherInv[] = { + { "y_expert", RAD_OPD_IN, 0 }, + { "expert_w", RAD_OPD_IN, 0 }, + { "inverse", RAD_OPD_IN, 0 }, + { "shared", RAD_OPD_IN, 1 }, + { "shared_gate", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* `vocab_off` and `pairs` are the vocab-parallel form, both absent on a single-rank graph (which * keeps it byte-identical to the unsplit form). With them, `x` is one rank's slice, `idx` carries @@ -1566,6 +1628,51 @@ static const RadParamSpec pMnDtype[] = { { "n", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; +static const RadParamSpec pSwigluClamped[] = { P_INT("M"), P_INT("n"), P_F64("limit"), + P_STR("dtype") }; +static const RadParamSpec pSwigluClampedQuant[] = { P_INT("M"), P_INT("n"), P_F64("limit"), + P_INT("group"), P_STR("dtype") }; +static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"), + P_INTO("block_size") }; +static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"), + P_INT("blocks"), P_INT("block_size"), P_F64("scale"), + P_STR("dtype") }; +static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; +static const RadOperandSpec oMlaAttn[] = { { "q", RAD_OPD_IN, 0 }, + { "kv", RAD_OPD_IN, 0 }, + { "bt", RAD_OPD_IN, 0 }, + { "length", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pDsaScore[] = { P_INT("M"), P_INT("n"), P_INT("heads"), + P_INT("blocks"), P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oDsaScore[] = { + { "q", RAD_OPD_IN, 0 }, { "q_scale", RAD_OPD_IN, 0 }, { "gate", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, { "k_scale", RAD_OPD_IN, 1 }, { "bt", RAD_OPD_IN, 0 }, + { "cu", RAD_OPD_IN, 0 }, { "nc", RAD_OPD_IN, 0 }, { "score", RAD_OPD_OUT, 0 } +}; +static const RadOperandSpec oDsaPool[] = { + { "kg", RAD_OPD_IN, 0 }, { "ape", RAD_OPD_WEIGHT, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, { "page", RAD_OPD_IN, 1 }, { "cache", RAD_OPD_INOUT, 1 } +}; +static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadOperandSpec oRouterSigmoid[] = { + { "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 }, + { "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 } +}; +/* router_sigmoid_topk and moe_scatter as one op, with `ids` named once, and the `fill` of an + * ungated shared arm's gate with 1 as an optional output. */ +static const RadParamSpec pRouterSigmoidScatter[] = { P_INT("M"), P_INT("n_expert"), + P_INTO("n_local"), P_INT("top_k"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype"), + P_INTO("expert_base"), P_STRO("protect") }; +static const RadOperandSpec oRouterSigmoidScatter[] = { + { "logits", RAD_OPD_IN, 0 }, { "bias", RAD_OPD_WEIGHT, 0 }, + { "ids", RAD_OPD_OUT, 0 }, { "weights", RAD_OPD_OUT, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 }, { "gate", RAD_OPD_OUT, 1 }, + { "inverse", RAD_OPD_OUT, 1 } +}; /* `logit_softcap`'s, matching ref's `pMnCap` (spec §2.3). `cap` must be > 0; the op refuses a * non-positive cap (a division by zero in every lane). */ static const RadParamSpec pMnCap[] = { @@ -2432,6 +2539,23 @@ static const RadOpSchema kSchemas[] = { SCHEMA("mul_weight", pMulWeight, oMulWeight, "y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row " "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."), + SCHEMA("mla_attn", pMlaAttn, oMlaAttn, + "Softmax over selected latent vectors used as both key and value; per-query page tables and visible lengths."), + SCHEMA("mla_project", pMlaProject, oGemmNt, + "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."), + SCHEMA("dsa_score", pDsaScore, oDsaScore, + "Per-head ReLU of FP8 dot products, then signed head gates and scales; invalid history is -inf."), + SCHEMA("dsa_pool", pDsaPool, oDsaPool, + "Channel-wise softmax pooling with learned position bias, BF16, normalized Hadamard, BF16, power-of-two FP8."), + SCHEMA("dsa_query", pMnDtype, oQuantActFp8, + "Normalized Hadamard, BF16 boundary and power-of-two E4M3 quantization per query head."), + SCHEMA("gemm_nt_f32", pGemmNt, oGemmNt, + "BF16 activations times F32 weights, F32 accumulation and output; preserves routing and index gate precision."), + SCHEMA("swiglu_clamped", pSwigluClamped, oGateUp, + "silu(min(gate,limit))*clamp(up,-limit,limit); gate is the first half."), + SCHEMA("swiglu_clamped_quant_fp8", pSwigluClampedQuant, oGatedQuantFp8, + "`swiglu_clamped` then `quant_act_fp8` over its product, in one pass: the codes are " + "taken over the BF16-ROUNDED product, which `out_bf16` receives when present."), SCHEMA("silu_mul", pMnDtype, oGateUp, "y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, " "which is the order rad-convert fuses gate_proj and up_proj in."), @@ -2673,6 +2797,22 @@ static const RadOpSchema kSchemas[] = { "the two ops it replaces."), SCHEMA("hc_enter", pHcPlain, oHcEnter, "h[s] = x for each of the hc streams -- the wide residual stream's first value."), + SCHEMA("mhc_pre", pMhcPre, oMhcPre, + "Whole-residual RMS-scaled projection, sigmoid gates and Sinkhorn mixing; coefficients f32."), + SCHEMA("mhc_pre_partial", pMhcPrePartial, oMhcPrePartial, + "mhc_pre's projection over chunks [first, first+chunks) of `chunk` residual columns: " + "per chunk the hc*(hc+2) coefficient partials and the sum of squares, zero-padded to " + "a multiple of four floats; tensor-parallel ranks each take their chunks."), + SCHEMA("mhc_pre_finish", pMhcPreFinish, oMhcPreFinish, + "mhc_pre from every chunk's partials: chunk sums, gates, Sinkhorn mixing and the " + "collapse of h; the pair is mhc_pre."), + SCHEMA("mhc_post", pHcPlain, oMhcPost, + "out[dst,i] = post[dst]*x[i] + sum_src comb[src,dst]*h[src,i]; separate output."), + SCHEMA("mhc_contract", pHcPlain, oMhcContract, + "Mean over the hc residual streams, rounded once to dtype."), + SCHEMA("kda_update", pKdaUpdate, oKdaUpdate, + "Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. " + "Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."), SCHEMA("hc_read", pHcRead, oHcRead, "the read half of a gated residual: a grouped rmsnorm, a low-rank sigmoid gate, and " "the mean of the gated streams -- plus the per-branch write gains and, optionally, " @@ -2722,6 +2862,14 @@ static const RadOpSchema kSchemas[] = { "With `add` present the form is y = bf16(x * act(s)) + add: the product is NARROWED " "before the sum, which is what makes the fused form bit-identical to the two ops it " "stands in for rather than merely close to them."), + SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid, + "Single-group sigmoid routing; correction bias selects experts, original scores weight them."), + SCHEMA("router_sigmoid_topk_scatter", pRouterSigmoidScatter, oRouterSigmoidScatter, + "`router_sigmoid_topk` then `moe_scatter` over its ids, in one launch, and with `gate` " + "present the ungated shared arm's `fill` of its gate with 1; with `inverse` the sort is " + "`moe_scatter_inv`. Every output is the bytes the separate launches write, including a " + "row with fewer finite ranks than top_k. Bounded by the sort's single-workgroup form: " + "M * top_k <= 1024, refused above."), SCHEMA("router_topk", pRouterTopk, oRouterTopk, "softmax over ALL n_expert logits, then the top_k of them by value with ties to the " "lower expert id, then -- if `norm` -- the kept weights renormalised to sum to one. The " @@ -2755,6 +2903,13 @@ static const RadOpSchema kSchemas[] = { "does not depend on the scheduler. `protect` lists local experts sorted LAST, in that " "order, the rest closed up: `expert_offset` and `expert_count` are then in sort order, " "and a layer's protected experts are one trailing run a second grouped GEMM serves."), + SCHEMA("moe_scatter_inv", pMoeScatter, oMoeScatterInv, + "`moe_scatter`, also writing `inverse`: for every slot token*top_k + slot its row in " + "`sorted_tok`, -1 for a dropped slot. That is the table `moe_gather` builds from " + "`sorted_tok` before it sums, so `moe_gather_inv` reads it instead."), + SCHEMA("moe_gather_inv", pMoeGather, oMoeGatherInv, + "`moe_gather` reading the slot table `moe_scatter_inv` wrote instead of rebuilding it " + "from `sorted_tok`: the same sums in ascending slot order, the same bytes."), SCHEMA("moe_gemm", pMoeGemm, oMoeGemm, "y[i] = a[row(i)] @ w[e]^T in SORTED order, e being the expert whose offset range " "contains i, both operands unquantised and one accumulator over K. `a_order` picks " @@ -3662,6 +3817,77 @@ static const RadConstraint cHcReadE4m3[] = { static const RadConstraint cHcPlain[] = { C_GE("M", 1), C_GE("n", 1), C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), }; +static const RadConstraint cMhcPlain[] = { + C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), C_LE("n", 16384), + C_GE("hc", 2), C_LE("hc", 8), C_IN("dtype", "bf16"), +}; +/* GLM's split projection only: eight 2048-column chunks of a 4 x 4096 residual. */ +static const RadConstraint cMhcPrePartial[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4), C_EQ("chunk", 2048), + C_GE("first", 0), C_LE("first", 7), C_GE("chunks", 1), C_LE("chunks", 8), C_IN("dtype", "bf16"), +}; +static const RadConstraint cMhcPreFinish[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 4096), C_EQ("hc", 4), + C_EQ("chunk", 2048), C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256), +}; +static const RadConstraint cKdaUpdate[] = { + C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535), + C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"), + C_IN("dtype", "bf16"), +}; +static const RadConstraint cMhcPre[] = { + C_GE("M", 1), C_LE("M", 65535), C_GE("n", 1), + C_LE("n", 16384), C_GE("hc", 2), C_LE("hc", 8), + C_IN("dtype", "bf16"), C_GE("iterations", 1), C_LE("iterations", 256), +}; +static const RadConstraint cDsaPool[] = { C_GE("M", 1), C_EQ("n", 128), C_EQ("ratio", 4), + C_IN("dtype", "bf16") }; +static const RadConstraint cDsaQuery[] = { C_GE("M", 1), C_LE("M", 2147483644), C_EQ("n", 128), + C_IN("dtype", "bf16") }; +static const RadConstraint cFp8F32Scale[] = { + C_GE("M", 1), C_GE("N", 128), C_DIV("N", 128), C_GE("K", 128), + C_DIV("K", 128), C_EQ("group", 128), C_IN("dtype", "fp8a8f32") +}; +static const RadConstraint cGemmNtF32[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("N", 1), C_LE("N", 512), + C_GE("K", 1), C_LE("K", 16384), + C_IN("dtype", "bf16") }; +static const RadConstraint cDsaScore[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("n", 128), C_EQ("heads", 32), + C_GE("blocks", 1), C_GE("seqs", 1), C_IN("dtype", "fp8_e4m3") +}; +static const RadConstraint cMlaAttn[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 1), + C_LE("heads", 64), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16") +}; +static const RadConstraint cMlaProject[] = { C_GE("M", 1), + C_LE("M", 65535), + C_GE("heads", 1), + C_LE("heads", 64), + C_EQ("head_dim", 256), + C_EQ("latent_dim", 512), + C_IN("mode", "absorb expand"), + C_IN("dtype", "bf16") }; +/* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union + * of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk + * with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the + * positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. + * RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */ +static long long mla_matrix_max_m() { + const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M"); + char* end = nullptr; + const long long v = e && *e ? std::strtoll(e, &end, 10) : -1; + return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535; +} +static const RadConstraint cMlaMatrix[] = { C_GE("M", 1), + C_LE("M", mla_matrix_max_m()), + C_EQ("latent_dim", 512), + C_GE("heads", 8), + C_LE("heads", 64), + C_DIV("heads", 8), + C_GE("blocks", 1), + C_EQ("block_size", 4), + C_IN("dtype", "bf16") }; /* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase; * 28672 elements is that budget at hc 4. */ static const RadConstraint cMtpEnter[] = { @@ -3681,6 +3907,15 @@ static const RadConstraint cRouterTopK[] = { C_GE("M", 1), C_GE("n_expert", 1), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), C_IN("dtype", "bf16"), }; +static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_IN("dtype", "f32") }; +/* The sort's single-workgroup form bounds M * top_k at 1024, which the shim checks. */ +static const RadConstraint cRouterSigmoidScatter[] = { C_GE("M", 1), C_LE("M", 1024), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_IN("dtype", "f32") }; /* The selection's bounds and the skinny GEMM's decode band: four 16-row tiles. */ static const RadConstraint cRouterGemmTopkScatter[] = { C_GE("M", 1), C_LE("M", 64), C_DIV("K", 16), C_GE("n_expert", 1), C_LE("n_expert", 512), @@ -3693,6 +3928,11 @@ static const RadConstraint cMoeGemmQ[] = { C_GE("M", 1), C_DIV("N", 64), C_DIV("K", 128), C_GE("n_expert", 1), C_LE("n_expert", 65536), C_GE("top_k", 1), C_EQ("group", 128), C_IN("dtype", "fp8a8"), }; +static const RadConstraint cMoeMx[] = { + C_GE("M", 1), C_LE("M", 32767), C_GE("N", 1), C_DIV("K", 128), + C_GE("n_expert", 2), C_LE("n_expert", 512), C_GE("top_k", 1), C_LE("top_k", 32), + C_EQ("group", 128), C_IN("dtype", "mxfp4a8"), +}; /* The same op at a four-bit expert weight: same band and operands, only the stored weight plane * and scale grid differ, so the dtype string alone separates the rows. * @@ -3916,6 +4156,10 @@ static const RadConstraint cArGatherHcWrite4[] = { static const RadConstraint cGatedQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; +static const RadConstraint cSwigluClampedQuant[] = { + C_GE("M", 1), C_LE("M", 65535), C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), + C_IN("dtype", "bf16"), +}; /* n divisible by the group, as in cHadQuantActFp8. */ static const RadConstraint cGatedHadQuantFp8[] = { C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), @@ -4805,6 +5049,70 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr, r4d_shape_scale }, +{ "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax", + "latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4", + "bf16 operands; FP32 probabilities via high/low BF16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 1, ROW(cMlaMatrix), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn_matrix, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr, + r4d_shape_mla_attn }, +{ "mla_attn_bf16", "mla_attn", "attn", "absorbed MLA with a shared latent cache and split history", + "latent_dim=512, heads<=64, block_size=4", "bf16 Q/cache/output, f32 softmax and partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaAttn), NOTUNE, + nullptr, nullptr, r4d_rad_mla_attn, r4d_rad_mla_attn_scratch, nullptr, nullptr, + r4d_shape_mla_attn }, +{ "gemm_fp8a8_f32scale", "gemm_nt_q", "gemm", "FP8 WMMA with canonical F32 block scales", + "N and K multiples of 128; pitched activations and row-major weights", "E4M3 codes, F32 scales, BF16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE, + nullptr, nullptr, r4d_rad_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr, + nullptr }, +{ "moe_gemm_fp8a8_f32scale", "moe_gemm_q", "moe", "grouped FP8 WMMA with canonical F32 block scales", + "equal parity widths; token/sorted activations; canonical pointer tables", "E4M3 codes, F32 scales, BF16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE, + nullptr, nullptr, r4d_rad_moe_fp8_f32scale, nullptr, r4d_layout_fp8_f32scale, nullptr, + nullptr }, +{ "dsa_score_fp8", "dsa_score", "attn", "32-head FP8 WMMA index scoring over paged keys", + "n=128, heads=32; ragged sequences and pitched tensors", "E4M3 codes, f32 scales and gates", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaScore), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_score, nullptr, nullptr, nullptr, + r4d_shape_dsa_score }, +{ "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections", + "head_dim=256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaProject), NOTUNE, + nullptr, nullptr, r4d_rad_mla_project, nullptr, nullptr, nullptr, + r4d_shape_mla_project }, +{ "dsa_query_fp8", "dsa_query", "attn", "normalized index queries in wave-local registers", + "n=128; flattened heads and pitched rows", "bf16 input, E4M3 codes and power-of-two f32 scale", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaQuery), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_query, nullptr, nullptr, nullptr, + r4d_shape_dsa_query }, +{ "gemm_nt_f32_bf16", "gemm_nt_f32", "gemm", "F32 routing and index gate projection", + "N<=512, K<=16384; pitched rows", "bf16 input, f32 weights and output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmNtF32), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_nt_f32, nullptr, nullptr, nullptr, + r4d_shape_gemm_nt_f32 }, +{ "dsa_pool_fp8", "dsa_pool", "attn", "learned compressed index keys in wave-local registers", + "n=128, ratio=4; pitched rows", "bf16 keys/gates, f32 position bias; FP8 codes and f32 scale", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cDsaPool), NOTUNE, + nullptr, nullptr, r4d_rad_dsa_pool, nullptr, nullptr, nullptr, + r4d_shape_dsa_pool }, +{ "swiglu_clamped_bf16", "swiglu_clamped", "elem", + "asymmetrically clipped SwiGLU", "positive finite limit; pitched rows", + "bf16 in and out, fp32 arithmetic", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_swiglu_clamped, nullptr, nullptr, nullptr, + r4d_shape_silu_mul }, +{ "swiglu_clamped_quant_fp8", "swiglu_clamped_quant_fp8", "quant", + "asymmetrically clipped SwiGLU and the fp8 activation quantiser in one pass", + "positive finite limit; n a multiple of 4; the gated operand is [M][2n], gate then up; " + "group 128; pitched rows", + "bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes " + "are taken over the BF16-ROUNDED product", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cSwigluClampedQuant), NOTUNE, + nullptr, nullptr, r4d_rad_swiglu_clamped_quant_fp8, nullptr, nullptr, nullptr, + r4d_shape_gated_quant_fp8, nullptr, + /* `swiglu_clamped` + `quant_act_fp8` (r4d_fuse.cpp). */ + r4d_fuse_swiglu_clamped_quant_fp8 }, { "silu_mul_bf16", "silu_mul", "elem", "silu-gated product over a fused [M, 2n] gate_up", "any n; the gate is the first half", @@ -5663,6 +5971,37 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update, nullptr, nullptr, nullptr, nullptr, nullptr, r4d_fuse_gdn_conv_recurrent_update }, +{ "kda_update_k128_v128_bf16", "kda_update", "gdn", "per-channel KDA recurrence and candidate rollback", + "heads 1..65535, K=V=128, prefill and verify", "bf16 activations, f32 gates and state", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKdaUpdate), NOTUNE, + nullptr, nullptr, r4d_rad_kda_update, nullptr, nullptr, nullptr, + r4d_shape_kda_update }, +{ "mhc_pre_bf16", "mhc_pre", "norm", "manifold residual gates and Sinkhorn mixing", + "M 1..65535, n 1..16384, hc 2..8, iterations 1..256", "bf16 activation, f32 weights and coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPre), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre }, +{ "mhc_pre_partial_bf16", "mhc_pre_partial", "norm", "mHC projection partials of a chunk range", + "n 4096, hc 4, chunk 2048 (GLM)", "bf16 activation, f32 weights and partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPrePartial), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre_partial, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre_partial }, +{ "mhc_pre_finish_bf16", "mhc_pre_finish", "norm", "mHC gates and Sinkhorn mixing from gathered partials", + "n 4096, hc 4, chunk 2048 (GLM), iterations 1..256", "bf16 activation, f32 partials and coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPreFinish), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_pre_finish, nullptr, nullptr, nullptr, + r4d_shape_mhc_pre_finish }, +{ "mhc_post_bf16", "mhc_post", "norm", "source-to-destination manifold residual update", + "M 1..65535, n 1..16384, hc 2..8", "bf16 activation, f32 coefficients", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_post, nullptr, nullptr, nullptr, + r4d_shape_mhc_post }, +{ "mhc_contract_bf16", "mhc_contract", "norm", "mean over manifold residual streams", + "M 1..65535, n 1..16384, hc 2..8", "bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMhcPlain), NOTUNE, + nullptr, nullptr, r4d_rad_mhc_contract, nullptr, nullptr, nullptr, + r4d_shape_mhc_contract }, + /* ---------------------------------------------------------------- the gated residual -------- * r4d_hc_bf16.hip. Three rows; the read is two launches behind one entry point, because `x` * depends on every column of the low-rank waist and the kernel boundary is the grid-wide @@ -6275,6 +6614,22 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_scale_rows, nullptr, nullptr, nullptr, r4d_shape_scale_rows }, +{ "router_sigmoid_topk_f32", "router_sigmoid_topk", "moe", + "sigmoid correction-bias routing", "single group, experts <=512, top_k<=32", + "f32 logits, bias and weights; i32 ids", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterSigmoid), NOTUNE, + nullptr, nullptr, r4d_rad_router_sigmoid_topk, nullptr, nullptr, nullptr, + r4d_shape_router_sigmoid_topk }, +{ "router_sigmoid_topk_scatter_f32", "router_sigmoid_topk_scatter", "moe", + "sigmoid correction-bias routing, the stable counting sort and the ungated shared gate in one " + "launch", "single group, experts <=512, top_k<=32, M*top_k<=1024", + "f32 logits, bias and weights; i32 ids, sorted slots, offsets and counts; bf16 gate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRouterSigmoidScatter), NOTUNE, + nullptr, nullptr, r4d_rad_router_sigmoid_topk_scatter, nullptr, nullptr, nullptr, + r4d_shape_router_sigmoid_topk_scatter, nullptr, + /* `router_sigmoid_topk` + `moe_scatter` (+ `fill` with the gate) (r4d_fuse.cpp). */ + r4d_fuse_router_sigmoid_topk_scatter }, { "router_topk_bf16", "router_topk", "moe", "softmax over a row of expert logits and the exact top-k of it, one wave a row", "n_expert <= 512, top_k <= min(n_expert, 32); bf16 logits and weights, i32 ids", @@ -6317,6 +6672,23 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_moe_scatter, r4d_rad_moe_scatter_scratch, nullptr, nullptr, r4d_shape_moe_scatter }, +{ "moe_scatter_inv_i32", "moe_scatter_inv", "moe", + "moe_scatter's stable counting sort, also writing every slot's row in the sort", + "n_expert <= 512; one launch at M*top_k <= 1024 and three above it", + "i32 throughout", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeScatter), NOTUNE, + nullptr, nullptr, r4d_rad_moe_scatter_inv, r4d_rad_moe_scatter_scratch, nullptr, nullptr, + r4d_shape_moe_scatter_inv }, + +{ "moe_gemm_mxfp4a8", "moe_gemm_q", "moe", + "canonical MXFP4 experts decoded in packed words into exact FP8 WMMA tiles, scales folded per 32 values", + "K multiple 128, parity tables, token and sorted order, parts and narrower odd experts", + "E2M1 and E8M0 weights, E4M3 activations and f32 scales, bf16 output", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMoeMx), NOTUNE, + nullptr, nullptr, r4d_rad_moe_mxfp4, nullptr, r4d_rad_layout_moe_mxfp4, nullptr, + r4d_shape_moe_mxfp4 }, + { "moe_gemm_fp8a8", "moe_gemm_q", "moe", "the grouped block-scaled fp8 GEMM: one contiguous range of expert-sorted rows a block, looping " "over the experts that range covers", @@ -6407,6 +6779,15 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_moe_gather, r4d_rad_moe_gather_scratch, nullptr, nullptr, r4d_shape_moe_gather }, +{ "moe_gather_inv_bf16", "moe_gather_inv", "moe", + "moe_gather over the slot table moe_scatter_inv wrote: no prepass and no scan of the sort", + "any M and n; the decode kernel up to 512 slots, the prefill forms above, as moe_gather", + "bf16 in and out, f32 or bf16 routing weights", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cMoeGather), NOTUNE, + nullptr, nullptr, r4d_rad_moe_gather_inv, nullptr, nullptr, nullptr, + r4d_shape_moe_gather_inv }, + { "rowtopk_bf16", "row_topk", "select", "exact per-row top-R of a bf16 matrix, descending, ties to the lower column", "any M, N a multiple of 8, R <= 32; two launches, caller-sized partial buffer", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index e9c4748d..3844acbd 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -59,6 +59,7 @@ #include #include #include +#include #include #include #include @@ -78,6 +79,10 @@ static int g_skip = 0; /* The row this process was asked to run, or null for the parent. Set from --case. */ static const char* g_case = nullptr; +/* The plugin under test's path, set in the child. Cases that compare against libref open the + * libref.so beside it. */ +static const char* g_plugin = nullptr; + /* Whether any case block claimed g_case; a row no case mentions is reported as a coverage hole. */ static bool g_matched = false; @@ -137,6 +142,8 @@ struct Plugin { void (*pin_ddec)(int) = nullptr; void (*pin_hc)(int) = nullptr; void (*pin_qsel)(int) = nullptr; + void (*pin_mla)(int) = nullptr; + void (*mla_stats)(unsigned long long*) = nullptr; int (*record)(const void**, int) = nullptr; }; @@ -172,6 +179,8 @@ static bool load(Plugin* pl, const char* path) { 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); + okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla); + okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats); okall &= sym(pl->h, "r4d_record_dispatches", &pl->record); return okall; } @@ -2373,7 +2382,8 @@ static void scatter_protect_at(const RadKernelInfo* rs, int64_t M, int64_t nl, i * `wide` says 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) { +static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGatherShape& sh, + bool f32 = false) { const int64_t M = sh.M, n = sh.n, k = sh.k, NS = M * k; const bool shared = sh.act != nullptr; const std::string at = " (M=" + std::to_string(M) + ", n=" + std::to_string(n) + ", top " + @@ -2398,14 +2408,17 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat std::vector ye((size_t)(NS * n)), ew((size_t)(M * k)), shv, sgv; for (auto& v : ye) v = h_to_bf16((float)((int64_t)(rnd() % 4001) - 2000) / 512.0f); for (auto& v : ew) v = h_to_bf16((float)(rnd() % 1000 + 1) / 1024.0f); + std::vector ewf(ew.size()); + for (size_t i = 0; i < ew.size(); ++i) ewf[i] = h_bf16(ew[i]) + 0.0001f * (float)(i % 7 + 1); if (shared) { shv.resize((size_t)(M * n)); sgv.resize((size_t)M); for (auto& v : shv) v = h_to_bf16((float)((int64_t)(rnd() % 4001) - 2000) / 256.0f); for (auto& v : sgv) v = h_to_bf16((float)((int64_t)(rnd() % 801) - 400) / 100.0f); + if (f32) std::fill(sgv.begin(), sgv.end(), h_to_bf16(1.0f)); } void* d_ye = dalloc(ye.size() * 2); - void* d_ew = dalloc(ew.size() * 2); + void* d_ew = dalloc(ew.size() * (f32?4:2)); void* d_so = dalloc(sorted.size() * 4); void* d_sh = shared ? dalloc(shv.size() * 2) : nullptr; void* d_sg = shared ? dalloc(sgv.size() * 2) : nullptr; @@ -2415,13 +2428,13 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat return; } st_memcpy(d_ye, ye.data(), ye.size() * 2, hipMemcpyHostToDevice); - st_memcpy(d_ew, ew.data(), ew.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_ew, f32?(const void*)ewf.data():(const void*)ew.data(), ew.size() * (f32?4:2), hipMemcpyHostToDevice); st_memcpy(d_so, sorted.data(), sorted.size() * 4, hipMemcpyHostToDevice); if (shared) { st_memcpy(d_sh, shv.data(), shv.size() * 2, hipMemcpyHostToDevice); st_memcpy(d_sg, sgv.data(), sgv.size() * 2, hipMemcpyHostToDevice); } - std::vector ts = { T(d_ye, RAD_BF16, { NS, n }), T(d_ew, RAD_BF16, { M, k }), + std::vector ts = { T(d_ye, RAD_BF16, { NS, n }), T(d_ew, f32?RAD_F32:RAD_BF16, { M, k }), T(d_so, RAD_I32, { NS }), T(d_sh, RAD_BF16, { M, n }), T(d_sg, RAD_BF16, { M, 1 }), T(d_y, RAD_BF16, { M, n }) }; @@ -2454,6 +2467,24 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat ok(("moe_gather, a column a thread" + at).c_str(), false, "rc=" + std::to_string(rc)); return; } + if (f32) { + std::vector inverse((size_t)NS, -1); + for (int64_t i = 0; i < NS; ++i) + if (sorted[i] >= 0) inverse[sorted[i]] = i; + bool exact = true; + for (int64_t t = 0; t < M; ++t) + for (int64_t c = 0; c < n; ++c) { + float sum = 0; + for (int64_t j = 0; j < k; ++j) { + const int64_t i = inverse[t * k + j]; + if (i >= 0) sum = std::fma(ewf[t * k + j], h_bf16(ye[i * n + c]), sum); + } + uint16_t want = h_to_bf16(sum); + if (shared) want = h_to_bf16(h_bf16(want) + h_bf16(shv[t * n + c])); + exact = exact && base[t * n + c] == want; + } + ok(("GLM gather preserves F32 mixture weights" + at).c_str(), exact); + } struct Var { int form; const char* name; bool wide; }; static const Var kVar[] = { { 0, "the rule", false }, @@ -2462,7 +2493,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat for (const Var& v : kVar) { const std::string label = "moe_gather, " + std::string(v.name) + at; const int rc = run(v.form, got); - if (v.wide && !sh.wide) { + if (v.wide && (!sh.wide || f32)) { /* 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; @@ -2482,7 +2513,7 @@ static void moe_gather_at(const Plugin& pl, const RadKernelInfo* r, const MoeGat " differ from a column a thread" + first); } - if (M >= 2048 && sh.wide) { + if (M >= 2048 && sh.wide && !f32) { hipEvent_t e0, e1; st_ev_create(&e0); st_ev_create(&e1); @@ -2524,6 +2555,9 @@ static void moe_gather_case(const Plugin& pl) { { 2048, 2560, 10, "sigmoid", true }, /* Qwen3.8-Flash-Next's chunk, timed */ }; for (const MoeGatherShape& sh : kSh) moe_gather_at(pl, r, sh); + for (int64_t m : { 1, 4, 65 }) + for (bool shared : { false, true }) + moe_gather_at(pl, r, { m, 4096, 8, shared ? "none" : nullptr, false }, true); } /* ------------------------------------------------------- the vocab-parallel top-R, end to end @@ -2898,17 +2932,19 @@ static void kv_store_v4_case(const Plugin& pl, bool k6 = false) { bad ? first : fmt("every live row decodes exactly; %d bytes of other rows touched", touched)); } -static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype) { +static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dtype, + bool latent = false) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } const bool fp8 = std::strcmp(kv_dtype, "bf16") != 0; - const int64_t head_dim = 256, kv_heads = 2, block_size = 16, n_blocks = 4; + const int64_t head_dim = 256, kv_heads = latent?1:2, block_size = latent?4:16, n_blocks = 4; const int64_t lane = kv_heads * head_dim; const int64_t cache_elts = n_blocks * kv_heads * block_size * 2 * head_dim; /* Slot 0 is real; -1 is the pad; the last is past the end of the four blocks. */ - const std::vector slots = { 0, 17, 63, -1, (int32_t)(n_blocks * block_size), 33 }; + const std::vector slots = { 0, (int32_t)(block_size+1), + (int32_t)(n_blocks*block_size-1), -1, (int32_t)(n_blocks * block_size), (int32_t)(2*block_size+1) }; const int64_t T_tok = (int64_t)slots.size(); /* Exact in E4M3 and bf16. Sign separates K from V, the magnitude encodes head and column, so @@ -2946,6 +2982,22 @@ static void kv_store_case(const Plugin& pl, const char* name, const char* kv_dty T(d_sm, RAD_I32, { T_tok }), T(d_c, fp8 ? RAD_F8E4M3 : RAD_BF16, { n_blocks, kv_heads, block_size, 2 * head_dim }), }; + if (latent) { + std::vector joined((size_t)T_tok * 512); + for (int64_t t = 0; t < T_tok; ++t) { + std::memcpy(joined.data() + t * 512, hk.data() + t * 256, 512); + std::memcpy(joined.data() + t * 512 + 256, hv.data() + t * 256, 512); + } + void* data = dalloc(joined.size() * 2); + if (!data) { + ok("MLA latent cache store", false, "allocation failed"); + return; + } + st_memcpy(data, joined.data(), joined.size() * 2, hipMemcpyHostToDevice); + ts[0].data = data; + ts[1].data = (uint16_t*)data + 256; + ts[0].stride[0] = ts[1].stride[0] = 512; + } std::vector ps = { PI("M", T_tok), PI("head_dim", head_dim), PI("n_head_kv", kv_heads), PI("block_size", block_size), PS("kv_dtype", kv_dtype), @@ -10985,6 +11037,2505 @@ static void moe_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E = 512, * sizes `u` for its weight planes; below it the pin to PF2 is refused. */ static constexpr int64_t kHcPf2MinRows = 512; +/* Independent host oracle, with pitched rows, narrowed runtime extents, and poisoned + * row padding and allocation margins. All three rows run at GLM's actual hidden width. */ +static void mhc_check(const Plugin& pl, const char* name, int64_t rows, int64_t n, int64_t hc, + bool paged = false) { + const RadKernelInfo* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (std::strcmp(at(i)->op, row->op) == 0) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + const bool clipped = !std::strcmp(row->op, "swiglu_clamped"); + const bool routed = !std::strcmp(row->op, "router_sigmoid_topk"); + const bool pooled = !std::strcmp(row->op, "dsa_pool"); + const bool query = !std::strcmp(row->op, "dsa_query"); + const bool projection = !std::strcmp(row->op, "gemm_nt_f32"); + std::vector ps = { PI("M", rows + 7), PS("dtype", routed ? "f32" : "bf16") }; + if (routed) { + ps.push_back(PI("n_expert", n)); + ps.push_back(PI("top_k", 8)); + ps.push_back(PI("norm", hc)); + ps.push_back(PF("route_scale", 2.5)); + } else if (projection) { + ps.push_back(PI("N", n)); + ps.push_back(PI("K", hc)); + } else + ps.push_back(PI("n", n)); + if (clipped) + ps.push_back(PF("limit", 10)); + else if (pooled) + ps.push_back(PI("ratio", 4)); + else if (query || projection) { /* hc selects input pattern or projection width */ + } else if (routed) { /* hc is the normalization choice in this test */ + } else + ps.push_back(PI("hc", hc)); + if (!std::strcmp(row->op, "mhc_pre")) { + ps.push_back(PI("iterations", 20)); + ps.push_back(PF("eps", 1e-5)); + ps.push_back(PF("hc_eps", 1e-6)); + } + const bool is_pre = !std::strcmp(row->op, "mhc_pre"); + const bool is_post = !std::strcmp(row->op, "mhc_post"); + const int operands = paged ? 6 + : (query || projection) ? 3 + : (routed || pooled) ? 4 + : is_pre ? 7 + : is_post ? 5 + : 2; + const int output_first = projection ? 2 + : query ? 1 + : (routed || pooled) ? 2 + : is_pre ? 4 + : is_post ? 4 + : 1; + std::vector host, device; + std::vector> bytes((size_t)operands); + std::vector allocations; + for (int i = 0; i < operands; ++i) { + RadOpdDesc desc{}; + int rc = RAD_OK; + if (paged && i == 4) { + desc.dtype = RAD_I32; + desc.rank = 1; + desc.shape[0] = rows; + } else if (paged && i == 5) { + desc.dtype = RAD_U8; + desc.rank = 4; + desc.shape[0] = rows + 3; + desc.shape[1] = 1; + desc.shape[2] = 4; + desc.shape[3] = 34; + } else + rc = oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc); + if (rc != RAD_OK) { + ok(name, false, "oracle shape refused"); + dlclose(ref); + return; + } + std::vector shape(desc.shape, desc.shape + desc.rank); + if (paged && i >= 4) { /* cache capacity and page list are not token outputs */ + } else if (pooled) { + if (i == 0) + shape[0] = rows * 4; + else if (i != 1) + shape[0] = rows; + } else if (desc.rank == 2 && !(is_pre && i == 1) && !(projection && i == 1)) + shape[0] = rows; + RadTensor ht = T(nullptr, desc.dtype, shape); + if (ht.rank == 2) ht.stride[0] += 5; + if (paged && i == 4) ht.stride[0] = 2; + if (paged && i == 5) ht.stride[0] = 160; + const int64_t elements = ht.shape[0] * ht.stride[0]; + bytes[(size_t)i].assign((size_t)elements * esz(ht.dtype) + 256, 0xa5); + ht.data = bytes[(size_t)i].data() + 128; + if (paged && i == 4) + for (int64_t r = 0; r < rows; ++r) + ((int*)ht.data)[r * ht.stride[0]] = r == 1 ? -1 + : r == 2 ? (int)rows + 9 + : (int)(rows - r); + if (i < output_first) { + const int64_t nr = ht.rank == 2 ? ht.shape[0] : 1; + const int64_t nc = ht.rank == 2 ? ht.shape[1] : ht.shape[0]; + for (int64_t r = 0; r < nr; ++r) + for (int64_t c = 0; c < nc; ++c) { + const int64_t off = ht.rank == 2 ? r * ht.stride[0] + c : c; + float v = + (float)((int)(st_mix32((uint32_t)(r * nc + c + i * 271)) % 2001) - 1000) / + 1000; + if (is_pre && i == 1) v *= 0.01f; + if (clipped) v *= 40; + if (routed) v = i == 1 ? (float)(c % 5 - 2) * 0.125f : r == 0 ? 0 : v * 5; + if (pooled) { + if (hc == 1) + v = 0; + else if (hc == 2) + v = i == 0 && c < 128 ? 224 : 0; + else if (hc == 3) + v = i == 0 && c >= 128 ? (float)(r % 4) * 100 : v * 3; + } + if (query && hc == 1) v = 0; + if (query && hc == 2) v = 224; + if (query && hc == 3) v = c == 0 ? 0.5f : 0; + if (projection) v *= 0.125f; + if (ht.dtype == RAD_F32) + ((float*)ht.data)[off] = v; + else + ((uint16_t*)ht.data)[off] = h_to_bf16(v); + } + } + void* d = dalloc(bytes[(size_t)i].size()); + if (!d) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + allocations.push_back(d); + st_memcpy(d, bytes[(size_t)i].data(), bytes[(size_t)i].size(), hipMemcpyHostToDevice); + RadTensor dt = ht; + dt.data = (char*)d + 128; + host.push_back(ht); + device.push_back(dt); + } + RadArgs args{}; + args.t = host.data(); + args.n_t = operands; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rr = oracle->launch(&args, nullptr); + ok(fmt("%s host oracle", name).c_str(), rr == RAD_OK); + if (rr == RAD_OK) run_case(row, device, ps); + bool matches = rr == RAD_OK, guards = true; + int mismatches = 0; + double pool_error2 = 0, pool_energy2 = 0; + for (int i = output_first; i < (paged ? 4 : operands) && rr == RAD_OK; ++i) { + const auto& ht = host[(size_t)i]; + std::vector got(bytes[(size_t)i].size()); + st_memcpy(got.data(), allocations[(size_t)i], got.size(), hipMemcpyDeviceToHost); + for (size_t j = 0; j < 128; ++j) + guards = guards && got[j] == 0xa5 && got[got.size() - 128 + j] == 0xa5; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < ht.shape[1]; ++c) { + const int64_t off = r * ht.stride[0] + c; + float expected, actual; + if (ht.dtype == RAD_F8E4M3) { + expected = rad_fp8e4m3_to_f32(((const uint8_t*)ht.data)[off]); + actual = rad_fp8e4m3_to_f32(got[128 + (size_t)off]); + } else if (ht.dtype == RAD_I32) { + expected = (float)((const int32_t*)ht.data)[off]; + actual = (float)((const int32_t*)(got.data() + 128))[off]; + } else if (ht.dtype == RAD_F32) { + expected = ((const float*)ht.data)[off]; + actual = ((const float*)(got.data() + 128))[off]; + } else { + expected = h_bf16(((const uint16_t*)ht.data)[off]); + actual = h_bf16(((const uint16_t*)(got.data() + 128))[off]); + } + // libm/OCML softmax can straddle a BF16 midpoint by one FP32 ulp. + // Only random pooling admits sparse quantization-boundary differences; + // fixed patterns and every power-of-two scale still compare exactly. + const float tol = query ? 0 + : pooled ? (hc == 0 && ht.dtype == RAD_F8E4M3 + ? std::max(0.125f, 0.125f * std::fabs(expected)) + : 0) + : ht.dtype == RAD_I32 ? 0 + : ht.dtype == RAD_F32 ? 3e-4f + : 0.016f + 0.008f * std::fabs(expected); + matches = matches && std::isfinite(actual) && std::fabs(actual - expected) <= tol; + if (pooled && ht.dtype == RAD_F8E4M3) { + mismatches += actual != expected; + pool_error2 += (double)(actual - expected) * (actual - expected); + pool_energy2 += (double)expected * expected; + } + } + for (int64_t c = ht.shape[1] * (int64_t)esz(ht.dtype); + c < ht.stride[0] * (int64_t)esz(ht.dtype); ++c) + guards = guards && + got[128 + (size_t)r * ht.stride[0] * esz(ht.dtype) + (size_t)c] == 0xa5; + } + } + if (pooled) { + const double nrmse = std::sqrt(pool_error2 / std::max(pool_energy2, 1e-30)); + matches = matches && mismatches <= std::max((int64_t)1, rows * n / 1000) && nrmse <= 0.001; + std::printf(" pool codes differ %d/%lld, normalized RMS error %.7g; scales exact\n", + mismatches, (long long)(rows * n), nrmse); + } + if (paged && rr == RAD_OK) { + std::vector got(bytes[5].size()); + st_memcpy(got.data(), allocations[5], got.size(), hipMemcpyDeviceToHost); + ok("DSA paged cache codes/scales, unused pages, padding and red zones", got == bytes[5]); + } + ok(fmt("%s oracle at M=%lld n=%lld hc=%lld", name, (long long)rows, (long long)n, (long long)hc) + .c_str(), + matches); + ok(fmt("%s red zones and row padding", name).c_str(), guards); + dlclose(ref); +} + +static void fp8_f32scale_check(const Plugin& pl, bool grouped, int64_t rows, bool sorted_a = false, + bool tables = false, int64_t experts = 6, int64_t N = 128, + int64_t K = 256) { + const char* name = grouped ? "moe_gemm_fp8a8_f32scale" : "gemm_fp8a8_f32scale"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "oracle missing"); + return; + } + const auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + const auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + for (int i = 0; count && at && i < count(); ++i) + if (!std::strcmp(at(i)->op, grouped ? "moe_gemm_q" : "gemm_nt_q")) oracle = at(i); + if (!oracle) { + ok(name, false, "oracle row missing"); + dlclose(ref); + return; + } + constexpr int64_t top = 4; + const int64_t E = experts; + std::vector ps = { PI("M", rows), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8f32") }; + if (grouped) { + ps.push_back(PI("n_expert", E)); + ps.push_back(PI("top_k", top)); + ps.push_back(PS("a_order", sorted_a ? "sorted" : "token")); + ps.push_back(PI("N_odd", N)); + ps.push_back(PI("K_odd", K)); + } + const int operands = grouped ? 9 : 7, out = grouped ? 8 : 4; + std::vector host, device; + std::vector> bytes(operands); + std::vector alloc(operands, nullptr); + for (int i = 0; i < operands; ++i) { + RadOpdDesc d{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &d) != RAD_OK) { + ok(name, false, "oracle shape refused"); + dlclose(ref); + return; + } + if (!d.rank) { + host.push_back({}); + device.push_back({}); + continue; + } + auto t = T(nullptr, d.dtype, std::vector(d.shape, d.shape + d.rank)); + const int64_t nel = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)nel * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i != out) + for (int64_t j = 0; j < nel; ++j) { + const float v = + (float)((int)(st_mix32((uint32_t)(j + i * 371)) % 2001) - 1000) / 256; + if (t.dtype == RAD_F8E4M3) + ((uint8_t*)t.data)[j] = rad_f32_to_fp8e4m3(v); + else if (t.dtype == RAD_F32) + ((float*)t.data)[j] = 0.003456789f + (float)(j % 11) * 0.0001234567f; + else + ((int*)t.data)[j] = 0; + } + if (grouped && i == 4) + for (int64_t j = 0; j < nel; ++j) + ((int*)t.data)[j] = j < rows * top * 3 / 4 ? (int)(rows * top - 1 - j) : -1; + if (grouped && i == 5) + for (int64_t j = 0; j < nel; ++j) + ((int*)t.data)[j] = (int)((rows * top * 3 / 4) * j / E); + alloc[i] = dalloc(bytes[i].size()); + if (!alloc[i]) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(alloc[i], bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + host.push_back(t); + t.data = (char*)alloc[i] + 128; + device.push_back(t); + } + if (tables && grouped) + for (int i : { 2, 3, 6, 7 }) { + auto& t = device[i]; + std::vector ptrs((size_t)t.shape[0]); + for (int64_t e = 0; e < t.shape[0]; ++e) + ptrs[e] = (uint8_t*)t.data + e * t.stride[0] * esz(t.dtype); + void* table = dalloc(ptrs.size() * sizeof(void*)); + st_memcpy(table, ptrs.data(), ptrs.size() * sizeof(void*), hipMemcpyHostToDevice); + t.data = table; + t.stride[0] = 0; + } + RadArgs args{}; + args.t = host.data(); + args.n_t = operands; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("FP8 F32-scale host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, device, ps); + std::vector got(bytes[out].size()); + st_memcpy(got.data(), alloc[out], got.size(), hipMemcpyDeviceToHost); + const int64_t count_y = host[out].shape[0] * N; + bool matches = rc == RAD_OK, guards = true; + float worst = 0; + for (int64_t i = 0; i < count_y; ++i) { + const float want = h_bf16(((const uint16_t*)host[out].data)[i]), + actual = h_bf16(((const uint16_t*)(got.data() + 128))[i]); + worst = std::max(worst, std::fabs(actual - want)); + matches = matches && std::isfinite(actual) && + std::fabs(actual - want) <= 1e-6f + 0.008f * std::fabs(want); + } + for (int i = 0; i < 128; ++i) + guards = guards && got[i] == 0xa5 && got[got.size() - 1 - i] == 0xa5; + ok(fmt("%s M=%lld N=%lld K=%lld sorted=%d tables=%d, max error %.8g", name, (long long)rows, + (long long)N, (long long)K, sorted_a, tables, worst) + .c_str(), + matches); + ok("FP8 F32-scale output guards", guards); + dlclose(ref); +} + +static void glm_index_layout_check(const Plugin& pl) { + const auto* row = find(pl, "cast_bf16_bf16"); + if (!row) { + ok("GLM index layout", false, "BF16 copy row missing"); + return; + } + for (int64_t tokens : { 1, 4, 33 }) + for (bool gate : { false, true }) { + const int64_t width = gate ? 128 : 4096, src_pitch = gate ? 256 : 4096; + const int64_t dst_pitch = gate ? 256 : 128, heads = gate ? 1 : 32; + std::vector input((size_t)tokens * src_pitch), + want((size_t)tokens * src_pitch, 0x7fff); + for (size_t i = 0; i < input.size(); ++i) + input[i] = h_to_bf16((float)((int)(i % 71) - 35) * 0.125f); + if (gate) + for (int64_t t = 0; t < tokens; ++t) + std::memcpy(want.data() + t * 256 + 128, input.data() + t * 256 + 128, 256); + else + want = input; + void* x = dalloc(input.size() * 2); + void* y = dalloc(want.size() * 2); + if (!x || !y) { + ok("GLM index layout", false, "allocation failed"); + return; + } + st_memcpy(x, input.data(), input.size() * 2, hipMemcpyHostToDevice); + st_memset(y, 0x7f, want.size() * 2); + // memset's BF16 poison is 0x7f7f, including the untouched normalized-key half. + if (gate) + for (int64_t t = 0; t < tokens; ++t) + for (int d = 0; d < 128; ++d) want[t * 256 + d] = 0x7f7f; + auto xt = T(gate ? (uint16_t*)x + 128 : x, RAD_BF16, { tokens, gate ? 128 : width }); + xt.stride[0] = src_pitch; + auto yt = T(gate ? (uint16_t*)y + 128 : y, RAD_BF16, { tokens * heads, 128 }); + yt.stride[0] = dst_pitch; + std::vector ts = { xt, yt }; + std::vector ps = { PI("M", tokens * heads), PI("n", 128), PS("from", "bf16"), + PS("to", "bf16") }; + run_case(row, ts, ps); + std::vector got(want.size()); + st_memcpy(got.data(), y, got.size() * 2, hipMemcpyDeviceToHost); + ok(gate ? "GLM pool gate column copy preserves key columns" + : "GLM query head flatten copy", + got == want); + } +} + +static void dsa_score_check(const Plugin& pl, int64_t rows, int64_t blocks, bool packed = false) { + const auto* row = find(pl, "dsa_score_fp8"); + if (!row || !g_plugin) { + ok("DSA scorer", false, "row or plugin missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("DSA scorer", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "dsa_score")) oracle = at(i); + if (!oracle) { + ok("DSA scorer", false, "oracle row missing"); + dlclose(ref); + return; + } + const int64_t seqs = rows > 1 ? 2 : 1; + std::vector ps = { PI("M", rows), PI("n", 128), PI("heads", 32), + PI("blocks", blocks), PI("seqs", seqs), PS("dtype", "fp8_e4m3") }; + std::vector host, device; + std::vector> bytes(9); + std::vector allocations; + for (int i = 0; i < 9; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + ok("DSA scorer", false, "oracle shape refused"); + dlclose(ref); + return; + } + RadTensor t = + T(nullptr, desc.dtype, std::vector(desc.shape, desc.shape + desc.rank)); + if (t.rank == 3) { + t.stride[1] += 5; + t.stride[0] = t.shape[1] * t.stride[1] + (packed ? 0 : 7); + } else if (t.rank == 2) { + if (!(packed && i == 1)) t.stride[0] += 7; + } else + t.stride[0] = 2; + const int64_t elements = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)elements * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 8) { + const int64_t heads = t.rank == 3 ? t.shape[1] : 1; + const int64_t cols = t.rank >= 2 ? t.shape[t.rank - 1] : 1; + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t c = 0; c < cols; ++c) { + const int64_t off = + r * t.stride[0] + (t.rank == 3 ? h * t.stride[1] + c : c); + const float v = (float)((int)(st_mix32((uint32_t)(r * heads * cols + + h * cols + c + i * 271)) % + 2001) - + 1000) / + 1000; + if (t.dtype == RAD_F8E4M3) + ((uint8_t*)t.data)[off] = rad_f32_to_fp8e4m3(v * 16); + else if (t.dtype == RAD_F32) + ((float*)t.data)[off] = i == 1 ? std::ldexp(1.0f, -6 - (r + h) % 3) + : i == 4 ? std::ldexp(1.0f, -5 - r % 3) + : v; + else { + int val = 0; + if (i == 5) + val = c % 11 == 3 ? -1 + : c % 17 == 5 ? (int)(seqs * blocks + 3) + : (int)((c * 7 + r * 11) % (seqs * blocks)); + else if (i == 6) + val = r == 0 ? (rows > 2 ? 1 : 0) + : r == seqs ? (int)rows + : (int)(rows / 2); + else + val = (int)(r == 0 ? blocks : blocks / 2); + ((int32_t*)t.data)[off] = val; + } + } + } + void* d = dalloc(bytes[i].size()); + if (!d) { + ok("DSA scorer", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(d, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + allocations.push_back(d); + host.push_back(t); + t.data = (char*)d + 128; + device.push_back(t); + } + std::vector packed_bytes; + void* packed_device = nullptr; + if (packed) { + const int64_t pages = host[3].shape[0]; + packed_bytes.assign((size_t)pages * 160 + 256, 0xa5); + RadTensor cache = T(packed_bytes.data() + 128, RAD_U8, { pages, 1, 4, 34 }); + cache.stride[0] = 160; + for (int64_t p = 0; p < pages; ++p) { + std::memcpy((uint8_t*)cache.data + p * 160, + (uint8_t*)host[3].data + p * host[3].stride[0], 128); + const float scale = ((float*)host[4].data)[p * host[4].stride[0]]; + std::memcpy((uint8_t*)cache.data + p * 160 + 128, &scale, sizeof(scale)); + } + packed_device = dalloc(packed_bytes.size()); + if (!packed_device) { + ok("DSA packed cache", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(packed_device, packed_bytes.data(), packed_bytes.size(), hipMemcpyHostToDevice); + host[3] = cache; + host[4] = {}; + cache.data = (char*)packed_device + 128; + device[3] = cache; + device[4] = {}; + for (auto* ts : { &host, &device }) { + auto& q = (*ts)[0]; + q.rank = 2; + q.shape[0] = rows * 32; + q.shape[1] = 128; + q.stride[0] = q.stride[1]; + q.stride[1] = 1; + auto& qs = (*ts)[1]; + qs.shape[0] = rows * 32; + qs.shape[1] = 1; + qs.stride[0] = qs.stride[1]; + } + } + ps[0] = PI("M", rows + 7); // tensors narrow a declared bucket + RadArgs args{}; + args.t = host.data(); + args.n_t = 9; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("DSA scorer host oracle", rc == RAD_OK); + run_case(row, device, ps); + std::vector got(bytes[8].size()); + st_memcpy(got.data(), allocations[8], got.size(), hipMemcpyDeviceToHost); + const auto& out = host[8]; + bool matches = rc == RAD_OK, guards = true; + float max_error = 0; + for (int64_t r = 0; r < rows; ++r) + for (int64_t b = 0; b < blocks; ++b) { + const long off = r * out.stride[0] + b; + const float want = ((float*)out.data)[off], actual = ((float*)(got.data() + 128))[off]; + const float error = std::fabs(actual - want); + matches = matches && (actual == want || (std::isfinite(actual) && std::isfinite(want) && + error <= 1e-5f + 1e-5f * std::fabs(want))); + if (std::isfinite(error)) max_error = std::max(max_error, error); + } + for (size_t j = 0; j < 128; ++j) + guards = guards && got[j] == 0xa5 && got[got.size() - 128 + j] == 0xa5; + for (int64_t r = 0; r < rows; ++r) + for (int64_t b = blocks * 4; b < out.stride[0] * 4; ++b) + guards = guards && got[128 + (size_t)r * out.stride[0] * 4 + b] == 0xa5; + ok(fmt("DSA FP8 WMMA M=%lld blocks=%lld, signed gates, ragged cu, max error %.8g", + (long long)rows, (long long)blocks, max_error) + .c_str(), + matches); + ok("DSA scorer guards and pitched output", guards); + if (packed) { + std::vector after(packed_bytes.size()); + st_memcpy(after.data(), packed_device, after.size(), hipMemcpyDeviceToHost); + ok("DSA packed cache and its guards remain unchanged", after == packed_bytes); + } + if (matches && guards) { + args.t = device.data(); + for (int i = 0; i < 4; ++i) row->launch(&args, nullptr); + const double us = st_time_us([&](int) { row->launch(&args, nullptr); }, 30, nullptr); + std::printf(" DSA score M=%lld blocks=%lld: %.3f us (component timing)\n", + (long long)rows, (long long)blocks, us); + } + dlclose(ref); +} + +static void mla_project_check(const Plugin& pl, int64_t rows, int64_t heads, const char* mode, + bool flat = false) { + const auto* row = find(pl, "mla_project_bf16"); + if (!row || !g_plugin) { + ok("MLA projection", false, "kernel missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("MLA projection", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "mla_project")) oracle = at(i); + if (!oracle) { + ok("MLA projection", false, "oracle row missing"); + dlclose(ref); + return; + } + std::vector ps = { PI("M", rows + 7), PI("heads", heads), PI("head_dim", 256), + PI("latent_dim", 512), PS("mode", mode), PS("dtype", "bf16") }; + std::vector host, device; + std::vector> bytes(3); + std::vector allocations; + bool allocated = true; + for (int i = 0; i < 3; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + allocated = false; + break; + } + std::vector shape(desc.shape, desc.shape + desc.rank); + if (i != 1) shape[0] = rows; + RadTensor t = T(nullptr, desc.dtype, shape); + if (t.rank == 3) { + t.stride[1] += flat ? 0 : 5; + t.stride[0] = heads * t.stride[1] + 7; + } else + t.stride[0] += 7; + bytes[i].assign((size_t)(t.shape[0] * t.stride[0]) * 2 + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 2) + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t h = 0; h < (t.rank == 3 ? heads : 1); ++h) + for (int64_t d = 0; d < t.shape[t.rank - 1]; ++d) { + const long off = r * t.stride[0] + (t.rank == 3 ? h * t.stride[1] : 0) + d; + const float v = + (float)((int)(st_mix32((uint32_t)(r * 7919 + h * 1031 + d + i * 271)) % + 2001) - + 1000) / + 8000; + ((uint16_t*)t.data)[off] = h_to_bf16(v); + } + void* ptr = dalloc(bytes[i].size()); + if (!ptr) { + allocated = false; + break; + } + allocations.push_back(ptr); + st_memcpy(ptr, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + host.push_back(t); + t.data = (char*)ptr + 128; + device.push_back(t); + } + if (allocated) { + auto hargs = host, dargs = device; + if (flat) + for (auto* ts : { &hargs, &dargs }) + for (int i : { 0, 2 }) { + auto& t = (*ts)[i]; + t.rank = 2; + t.shape[1] = t.shape[1] * t.shape[2]; + t.stride[1] = 1; + } + RadArgs args{}; + args.t = hargs.data(); + args.n_t = 3; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("MLA projection host oracle", rc == RAD_OK); + if (rc == RAD_OK) { + run_case(row, dargs, ps); + std::vector got(bytes[2].size()); + st_memcpy(got.data(), allocations[2], got.size(), hipMemcpyDeviceToHost); + std::vector written(got.size(), false); + bool matches = true, guards = true; + float max_error = 0; + const auto& t = host[2]; + for (int64_t r = 0; r < rows; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < t.shape[2]; ++d) { + const long off = r * t.stride[0] + h * t.stride[1] + d; + const float want = h_bf16(((uint16_t*)t.data)[off]), + actual = h_bf16(((uint16_t*)(got.data() + 128))[off]); + const float error = std::fabs(actual - want); + max_error = std::max(max_error, error); + matches = matches && std::isfinite(actual) && + error <= 0.0001f + 0.008f * std::fabs(want); + written[128 + off * 2] = written[129 + off * 2] = true; + } + for (size_t j = 0; j < got.size(); ++j) + if (!written[j]) guards = guards && got[j] == 0xa5; + ok(fmt("MLA %s M=%lld H=%lld max error %.8g", mode, (long long)rows, (long long)heads, + max_error) + .c_str(), + matches); + ok("MLA projection pitched tensors and guards", guards); + } + } else + ok("MLA projection", false, "allocation or shape failed"); + dlclose(ref); +} + +/* An environment variable set (or, with a null value, cleared) for one scope and restored after + * it: the MLA launcher and the eight-rank two-shot read their settings at every call. */ +struct ScopedEnv { + const char* name; + bool had; + std::string kept; + ScopedEnv(const char* n, const char* v) : name(n) { + const char* was = std::getenv(n); + had = was != nullptr; + if (was) kept = was; + if (v) + setenv(n, v, 1); + else + unsetenv(n); + } + ~ScopedEnv() { + if (had) + setenv(name, kept.c_str(), 1); + else + unsetenv(name); + } + ScopedEnv(const ScopedEnv&) = delete; + ScopedEnv& operator=(const ScopedEnv&) = delete; +}; + +/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows .. + * context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher + * ones in block order and a short tie run after them, then the partial page. Row r's choice is row + * r-1's with `swaps` members exchanged for non-members, so neighbours share most blocks but rarely + * a table position once a swap shifts the order. Pages are a fixed shuffle of the sequence's + * blocks, context/4+1 of them. */ +static void mla_topk_tables(int64_t rows, int64_t blocks, int64_t context, int64_t swaps, + std::vector& bt, std::vector& len) { + const int64_t topk = blocks - 1, universe = context / 4 + 1, ties = std::min(4, topk); + uint32_t draw = 0x6d2b79f5u; + auto rnd = [&](int64_t n) { return (int64_t)(st_mix32(draw++) % (uint32_t)n); }; + std::vector page((size_t)universe); + for (int64_t i = 0; i < universe; ++i) page[(size_t)i] = (int32_t)i; + for (int64_t i = universe - 1; i > 0; --i) std::swap(page[(size_t)i], page[(size_t)rnd(i + 1)]); + std::vector in((size_t)universe, 0); + std::vector members; + auto tie_rank = [](int64_t b) { return st_mix32((uint32_t)b ^ 0x9e3779b9u); }; + bt.assign((size_t)(rows * blocks), -1); + len.assign((size_t)rows, 0); + for (int64_t r = 0; r < rows; ++r) { + const int64_t p = context - rows + r, n = (p + 1) / 4; + if (n <= topk) { + for (int64_t b = 0; b < n; ++b) + if (!in[(size_t)b]) { + in[(size_t)b] = 1; + members.push_back(b); + } + } else { + while ((int64_t)members.size() < topk) { + const int64_t b = rnd(n); + if (!in[(size_t)b]) { + in[(size_t)b] = 1; + members.push_back(b); + } + } + for (int64_t k = 0; k < swaps; ++k) { + int64_t add; + do add = rnd(n); + while (in[(size_t)add]); + const size_t drop = (size_t)rnd((int64_t)members.size()); + in[(size_t)members[drop]] = 0; + members[drop] = add; + in[(size_t)add] = 1; + } + } + std::vector order(members); + std::sort(order.begin(), order.end()); + if (n > topk) { + std::vector tied(order); + std::sort(tied.begin(), tied.end(), + [&](int64_t a, int64_t b) { return tie_rank(a) < tie_rank(b); }); + tied.resize((size_t)ties); + std::sort(tied.begin(), tied.end()); + order.erase(std::remove_if(order.begin(), order.end(), + [&](int64_t b) { + return std::binary_search(tied.begin(), tied.end(), b); + }), + order.end()); + order.insert(order.end(), tied.begin(), tied.end()); + } + int64_t out = 0; + for (int64_t b : order) bt[(size_t)(r * blocks + out++)] = page[(size_t)b]; + if ((p + 1) % 4) bt[(size_t)(r * blocks + out++)] = page[(size_t)n]; + len[(size_t)r] = (int32_t)(out ? (out - 1) * 4 + p % 4 + 1 : 0); + } +} + +/* ragged: every request its own scattered table with holes; full: every request its own fully + * populated pages; prefill: requests are consecutive queries of two sequences that share a table + * and grow by one token a row (the second sequence starts at an odd row, so a pair of rows can + * straddle it), with an occasional row whose table differs in one position; topk: one sequence + * past the DSA budget (mla_topk_tables), `swaps` blocks exchanged between neighbouring rows. */ +enum class MlaFill { ragged, full, prefill, topk }; +static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blocks, + const char* name = "mla_attn_bf16", MlaFill fill = MlaFill::ragged, + const char* versus = nullptr, int form = 0, int64_t swaps = 0) { + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok("MLA attention", false, "row or plugin missing"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok("MLA attention", false, "oracle missing"); + return; + } + auto count = (int (*)())dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "mla_attn")) oracle = at(i); + if (!oracle) { + ok("MLA attention", false, "oracle row missing"); + dlclose(ref); + return; + } + std::vector ps = { PI("M", rows), PI("latent_dim", 512), PI("heads", heads), + PI("blocks", blocks), PI("block_size", 4), PF("scale", 0.0625), + PS("dtype", "bf16") }; + std::vector host, device; + std::vector> bytes(5); + std::vector allocations; + /* The oracle's cache has rows*blocks pages: three budgets of context where that allows. */ + std::vector topk_bt, topk_len; + if (fill == MlaFill::topk) + mla_topk_tables(rows, blocks, 4 * std::min(rows * blocks - 1, 3 * (blocks - 1)), + swaps, topk_bt, topk_len); + for (int i = 0; i < 5; ++i) { + RadOpdDesc desc{}; + if (oracle->opd_shape(ps.data(), (int)ps.size(), i, &desc) != RAD_OK) { + ok("MLA attention", false, "oracle shape refused"); + dlclose(ref); + return; + } + RadTensor t = + T(nullptr, desc.dtype, std::vector(desc.shape, desc.shape + desc.rank)); + if (t.rank == 4) { + t.stride[2] += 8; + t.stride[1] = t.shape[2] * t.stride[2] + 8; + t.stride[0] = t.stride[1] + 8; + } else if (t.rank == 3) { + t.stride[1] += 5; + t.stride[0] = t.shape[1] * t.stride[1] + 7; + } else if (t.rank == 2) + t.stride[0] += 7; + else + t.stride[0] = 2; + const int64_t elements = t.shape[0] * t.stride[0]; + bytes[i].assign((size_t)elements * esz(t.dtype) + 256, 0xa5); + t.data = bytes[i].data() + 128; + if (i < 4) { + const int64_t n1 = t.rank > 1 ? t.shape[1] : 1; + const int64_t n2 = t.rank > 2 ? t.shape[2] : 1; + const int64_t n3 = t.rank > 3 ? t.shape[3] : 1; + for (int64_t r = 0; r < t.shape[0]; ++r) + for (int64_t a1 = 0; a1 < n1; ++a1) + for (int64_t a2 = 0; a2 < n2; ++a2) + for (int64_t a3 = 0; a3 < n3; ++a3) { + const long off = r * t.stride[0] + a1 * t.stride[1] + a2 * t.stride[2] + + a3 * t.stride[3]; + const float v = + (float)((int)(st_mix32((uint32_t)(((r * n1 + a1) * n2 + a2) * n3 + + a3 + i * 271)) % + 2001) - + 1000) / + 1000; + if (t.dtype == RAD_BF16) + ((uint16_t*)t.data)[off] = h_to_bf16(i == 0 ? v * 0.25f : v); + else if (fill == MlaFill::full) + ((int32_t*)t.data)[off] = + i == 2 ? (int)(r * blocks + a1) : (int)(blocks * 4); + else if (fill == MlaFill::topk) + ((int32_t*)t.data)[off] = i == 2 + ? topk_bt[(size_t)(r * blocks + a1)] + : topk_len[(size_t)r]; + else if (fill == MlaFill::prefill) { + const int64_t boundary = rows > 2 ? (rows / 2) | 1 : rows, + seq = r >= boundary; + const int64_t index = seq ? r - boundary : r, + count = seq ? rows - boundary : boundary; + ((int32_t*)t.data)[off] = + i == 2 + ? (a1 % 11 == 7 ? -1 + : r % 4 == 2 && a1 == 5 ? (int)(rows * blocks - 1 - a1) + : (int)(seq * blocks + a1)) + : (int)(blocks * 4 - count + index + 1); + } else + ((int32_t*)t.data)[off] = + i == 2 ? (a1 % 17 == 3 ? -1 + : a1 % 19 == 5 + ? (int)(rows * blocks + 3) + : (int)((a1 * 7 + r * 11) % (rows * blocks))) + : r % 5 == 4 ? 0 + : (int)(blocks * 4 - 1 - r % 7); + } + } + void* d = dalloc(bytes[i].size()); + if (!d) { + ok("MLA attention", false, "allocation failed"); + dlclose(ref); + return; + } + st_memcpy(d, bytes[i].data(), bytes[i].size(), hipMemcpyHostToDevice); + allocations.push_back(d); + host.push_back(t); + t.data = (char*)d + 128; + device.push_back(t); + } + ps[0] = PI("M", rows + 7); + RadArgs args{}; + args.t = host.data(); + args.n_t = 5; + args.p = ps.data(); + args.n_p = (int)ps.size(); + const int rc = oracle->launch(&args, nullptr); + ok("MLA host oracle", rc == RAD_OK); + args.t = device.data(); + /* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix); + * other head counts must be refused rather than computed. */ + if (std::strstr(name, "matrix") && heads % 8) { + args.scratch = nullptr; + args.scratch_bytes = 0; + const int grc = row->launch(&args, nullptr); + st_stream_sync(nullptr); + ok(fmt("MLA %s refuses heads=%lld (not a multiple of 8) with RAD_E_UNSUPPORTED, no launch", + name, (long long)heads) + .c_str(), + grc == RAD_E_UNSUPPORTED); + dlclose(ref); + return; + } + if (form && pl.pin_mla) pl.pin_mla(form); + const int64_t need = row->scratch ? row->scratch(&args) : 0; + void* scratch = need > 0 ? dalloc((size_t)need + 256) : nullptr; + if (need <= 0 || !scratch) { + if (form && pl.pin_mla) pl.pin_mla(0); + ok("MLA scratch allocation", false); + dlclose(ref); + return; + } + bool matches = rc == RAD_OK, guards = true; + float max_error = 0; + const auto& out = host[4]; + for (int pass = 0; pass < 2; ++pass) { + st_memset(allocations[4], 0xa5, bytes[4].size()); + st_memset(scratch, 0xa5, (size_t)need + 256); + args.scratch = pass ? (char*)scratch + 128 : nullptr; + args.scratch_bytes = pass ? need : 0; + const int grc = row->launch(&args, nullptr); + const auto he = st_stream_sync(nullptr); + matches = matches && grc == RAD_OK && he == hipSuccess; + std::vector got(bytes[4].size()); + st_memcpy(got.data(), allocations[4], got.size(), hipMemcpyDeviceToHost); + std::vector written(got.size(), false); + for (int64_t r = 0; r < rows; ++r) + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < 512; ++d) { + const long off = r * out.stride[0] + h * out.stride[1] + d; + const float want = h_bf16(((uint16_t*)out.data)[off]), + actual = h_bf16(((uint16_t*)(got.data() + 128))[off]); + const float error = std::fabs(actual - want); + max_error = std::max(max_error, error); + matches = matches && std::isfinite(actual) && + error <= 1e-5f + 0.008f * std::fabs(want); + written[128 + off * 2] = written[129 + off * 2] = true; + } + for (size_t i = 0; i < got.size(); ++i) + if (!written[i]) guards = guards && got[i] == 0xa5; + uint8_t left[128], right[128]; + st_memcpy(left, scratch, 128, hipMemcpyDeviceToHost); + st_memcpy(right, (char*)scratch + 128 + need, 128, hipMemcpyDeviceToHost); + for (int i = 0; i < 128; ++i) guards = guards && left[i] == 0xa5 && right[i] == 0xa5; + } + const char* pairing = std::getenv("RADIANCE_MLA_PAIR"); + ok(fmt("MLA M=%lld heads=%lld blocks=%lld%s%s%s split/unsplit, max error %.8g", (long long)rows, + (long long)heads, (long long)blocks, + fill == MlaFill::topk ? fmt(" topk:%lld", (long long)swaps).c_str() : "", + form ? fmt(" pinned form %d", form).c_str() : "", + pairing && std::strstr(name, "matrix") ? fmt(" pairing %s", pairing).c_str() : "", + max_error) + .c_str(), + matches); + ok("MLA pitched rows, heads, cache, padding and scratch red zones", guards); + if (matches && guards) { + const char* shape = fill == MlaFill::full ? "fully populated" + : fill == MlaFill::prefill ? "prefill" + : fill == MlaFill::topk ? "topk" + : "ragged"; + const double us = st_time_us([&](int) { row->launch(&args, nullptr); }, 30, nullptr); + std::printf( + " %s M=%lld heads=%lld capacity=%lld tokens: %.3f us (%s component timing)\n", + name, (long long)rows, (long long)heads, (long long)(blocks * 4), us, shape); + if (const auto* other = versus ? find(pl, versus) : nullptr) { + const int64_t other_need = other->scratch ? other->scratch(&args) : 0; + void* other_scratch = other_need > need ? dalloc((size_t)other_need) : nullptr; + args.scratch = other_scratch ? other_scratch : (char*)scratch + 128; + args.scratch_bytes = other_scratch ? other_need : need; + const double base = + st_time_us([&](int) { other->launch(&args, nullptr); }, 30, nullptr); + std::printf(" %s same case: %.3f us, %s %.2fx faster (%s component timing)\n", + versus, base, name, base / us, shape); + } + } + if (form && pl.pin_mla) pl.pin_mla(0); + dlclose(ref); +} + +/* ------------------------------------------------------------- MLA attention, timed at length + * + * mla_check's operands without the oracle, so a prefill chunk of 2048 rows at 2k or 8k of context + * fits: one block table a sequence and a pool of pages a sequence instead of M*blocks. fill + * "prefill" is mla_check's two sequences, "fresh" one sequence whose rows are the last M positions + * of the capacity (a new prompt's chunk), "ragged" scattered per-row tables with holes, and "SxR" + * (e.g. 8x6) a decode step: S sequences of R rows each (the token and its drafts), one table and + * one context between 1024 positions and the capacity a sequence; M is then S*R. "topk:d[:context]" + * is one sequence past the DSA budget (mla_topk_tables): the pairing of the matrix row shares a key + * load only where both rows name the same page at the same table position, which the other fills + * always or never give. The matrix row is timed at both key loads (paired tiles at heads%16 == 8) + * against the wave row on the same operands, with its second passes counted on one more launch; + * differences are against the wave row's output. */ +static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads, int iters, + const char* fill) { + if (iters <= 0) iters = 20; + const bool ragged = !std::strcmp(fill, "ragged"), fresh = !std::strcmp(fill, "fresh"); + long long seqs = 0, rows_per = 0, swaps = -1, context = 0; + char tail = 0; + const bool decode = + std::sscanf(fill, "%lldx%lld%c", &seqs, &rows_per, &tail) == 2 && seqs > 0 && rows_per > 0; + const int topk_fields = std::sscanf(fill, "topk:%lld:%lld%c", &swaps, &context, &tail); + const bool topk = (topk_fields == 1 || topk_fields == 2) && swaps >= 0; + if (topk && topk_fields == 1) context = 16 * (blocks - 1); + if (!ragged && !fresh && !decode && !topk && std::strcmp(fill, "prefill")) { + std::printf("--perfmla: fill prefill|fresh|ragged|SxR|topk:d[:context]\n"); + return; + } + if (decode) { + if (M != seqs * rows_per) + std::printf("--perfmla: decode %s sets M=%lld\n", fill, seqs * rows_per); + M = seqs * rows_per; + } + if (M < 1 || M > 65535 || blocks < 1 || heads < 1 || heads > 64 || + (topk && (blocks < 2 || context < M))) { + std::printf("--perfmla: shape out of range\n"); + return; + } + const int64_t D = 512, bs = 4, cap = blocks * bs; + const int64_t pages = + topk ? context / bs + 1 : std::max(2, decode ? seqs : 2) * blocks; + std::vector qh((size_t)(M * heads * D)), kvh((size_t)(pages * bs * D)); + for (size_t i = 0; i < qh.size(); ++i) + qh[i] = h_to_bf16(0.25f * (float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + for (size_t i = 0; i < kvh.size(); ++i) + kvh[i] = + h_to_bf16((float)((int)(st_mix32((uint32_t)i + 0x9e3779b9u) % 2001) - 1000) / 1000); + std::vector bth((size_t)(M * blocks)), lh((size_t)M); + const int64_t boundary = fresh ? M : M > 2 ? (M / 2) | 1 : M; + double visible = 0; + if (topk) { + std::vector tl; + mla_topk_tables(M, blocks, context, swaps, bth, tl); + for (int64_t r = 0; r < M; ++r) lh[(size_t)r] = tl[(size_t)r]; + } + for (int64_t r = 0; r < M && topk; ++r) + for (int64_t t = 0; t < lh[(size_t)r]; ++t) + if (bth[(size_t)(r * blocks + t / bs)] >= 0) visible += 1; + for (int64_t r = 0; r < M && !topk; ++r) { + int64_t seq, l; + if (decode) { + seq = r / rows_per; + const int64_t context = cap > 1024 ? 1024 + (seq * 7919) % (cap - 1023) : cap; + l = std::max(1, context - (rows_per - 1 - r % rows_per)); + } else { + seq = r >= boundary; + const int64_t index = seq ? r - boundary : r, count = seq ? M - boundary : boundary; + l = ragged ? (r % 5 == 4 ? 0 : cap - 1 - r % 7) + : std::max(1, cap - count + index + 1); + } + for (int64_t b = 0; b < blocks; ++b) + bth[(size_t)(r * blocks + b)] = + ragged ? (b % 17 == 3 ? -1 : (int32_t)((b * 7 + r * 11) % pages)) + : (int32_t)(seq * blocks + b); + lh[(size_t)r] = (int32_t)l; + for (int64_t t = 0; t < l; ++t) + if (bth[(size_t)(r * blocks + t / bs)] >= 0) visible += 1; + } + const double flops = visible * (double)D * (double)heads * 4; + std::printf( + "mla_attn M=%lld blocks=%lld (capacity %lld) heads=%lld fill=%s: %.0f visible positions, " + "%.3f GFLOP, %d launches%s\n", + (long long)M, (long long)blocks, (long long)cap, (long long)heads, fill, visible, + flops * 1e-9, iters, g_cold > 0 ? " (cold)" : ""); + void* dq = dalloc(qh.size() * 2); + void* dkv = dalloc(kvh.size() * 2); + void* dbt = dalloc(bth.size() * 4); + void* dl = dalloc(lh.size() * 4); + void* dout = dalloc(qh.size() * 2); + if (!dq || !dkv || !dbt || !dl || !dout) { + std::printf(" alloc failed\n"); + return; + } + st_memcpy(dq, qh.data(), qh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dkv, kvh.data(), kvh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dbt, bth.data(), bth.size() * 4, hipMemcpyHostToDevice); + st_memcpy(dl, lh.data(), lh.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(dq, RAD_BF16, { M, heads, D }), + T(dkv, RAD_BF16, { pages, 1, bs, D }), + T(dbt, RAD_I32, { M, blocks }), T(dl, RAD_I32, { M }), + T(dout, RAD_BF16, { M, heads, D }) }; + std::vector ps = { PI("M", M), PI("latent_dim", D), PI("heads", heads), + PI("blocks", blocks), PI("block_size", bs), PF("scale", 0.0625), + PS("dtype", "bf16") }; + std::vector base, rule; + auto run = [&](const char* name, int form, const char* label, bool positional = false) { + ScopedEnv pairing("RADIANCE_MLA_PAIR", positional ? "pos" : nullptr); + const RadKernelInfo* r = find(pl, name); + if (!r) { + std::printf(" %-34s row absent\n", label); + return; + } + if (form >= 0) { + if (!pl.pin_mla) { + std::printf(" %-34s no pin hook\n", label); + return; + } + pl.pin_mla(form); + } + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); + a.n_t = (int)ts.size(); + a.p = ps.data(); + a.n_p = (int)ps.size(); + const int64_t need = r->scratch ? r->scratch(&a) : 0; + if (need > 0) { + a.scratch = dalloc((size_t)need); + a.scratch_bytes = need; + } + st_memset(dout, 0xff, qh.size() * 2); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + std::printf(" %-34s rc=%d (shape not served)\n", label, rc); + if (form >= 0) pl.pin_mla(0); + return; + } + std::vector got(qh.size()); + st_memcpy(got.data(), dout, got.size() * 2, hipMemcpyDeviceToHost); + { /* Clocks to deployment speed first, as qsa_perf does. */ + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0; + for (int guard = 0; guard < 100000 && wms < 500.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(&a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + if (form >= 0) pl.pin_mla(0); + char diff[192] = "reference"; + if (base.empty()) + base = got; + else { + /* bf16 as an ordered integer, so the distance counts representable steps. */ + auto ord = [](uint16_t h) { return (h & 0x8000) ? -(int)(h & 0x7fff) : (int)h; }; + int ulp = 0; + float abs_err = 0; + bool finite = true; + for (size_t i = 0; i < got.size(); ++i) { + const float x = h_bf16(got[i]), y = h_bf16(base[i]); + finite = finite && std::isfinite(x); + ulp = std::max(ulp, std::abs(ord(got[i]) - ord(base[i]))); + abs_err = std::max(abs_err, std::fabs(x - y)); + } + /* The two key loads stage the same values: their outputs must agree to the bit. The + * pairings walk request r of a pair in the same order (equal at one split) and r+1 in + * another. */ + std::string same = + form == 1 && !rule.empty() + ? (rule == got ? ", bit-identical to form 0" : ", DIFFERS from form 0") + : ""; + if (positional && !rule.empty()) { + size_t differ[2] = { 0, 0 }; + float apart = 0; + for (size_t i = 0; i < got.size(); ++i) + if (got[i] != rule[i]) { + ++differ[(i / (size_t)(heads * D)) % 2]; + apart = std::max(apart, std::fabs(h_bf16(got[i]) - h_bf16(rule[i]))); + } + same = fmt(", vs union %zu/%zu values differ (r/r+1), max abs %.3g", differ[0], + differ[1], apart); + } + std::snprintf(diff, sizeof diff, "%smax %d ulp, max abs %.3g%s", + finite ? "" : "NONFINITE ", ulp, abs_err, same.c_str()); + } + if (form == 0 && !positional) rule = got; + std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff); + if (form >= 0 && pl.mla_stats) { + /* One more launch with the conflict counters on, outside the timing. */ + ScopedEnv counting("RADIANCE_MLA_CONFLICT_STATS", "1"); + unsigned long long v[3]; + pl.mla_stats(v); + pl.pin_mla(form); + r->launch(&a, nullptr); + pl.pin_mla(0); + pl.mla_stats(v); + std::printf(" %-34s %llu passes over %llu raster chunks, %llu second passes (%.3fx)\n", + "", v[0], v[2], v[1], v[2] ? (double)v[0] / (double)v[2] : 0.0); + } + }; + run("mla_attn_bf16", -1, "mla_attn_bf16 (wave)"); + if (heads % 8) { + std::printf(" mla_attn_matrix_bf16 serves heads a multiple of 8 only\n"); + return; + } + if (heads % 16) { + run("mla_attn_matrix_bf16", 0, "matrix paired, union, vector load"); + run("mla_attn_matrix_bf16", 1, "matrix paired, union, element load"); + run("mla_attn_matrix_bf16", 0, "matrix paired, positional, vector", true); + } else { + run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load"); + run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load"); + } +} + +static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepted_count, + bool anchor = false) { + const char* name = "kda_update_k128_v128_bf16"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "kda_update")) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + const int H = 2, T0 = 6, D = 128; + const std::vector> shapes = { + { T0, H, D }, { T0, H, D }, { T0, H, D }, { T0, H, D }, { T0, H }, + { H }, { H * D }, { 8, H, D, D }, { 2, anchor ? 6 : 3 }, { 3 }, + { 2 }, { 2 }, { T0, H, D }, + }; + std::vector> bytes(13), visible(13); + std::vector host, device; + std::vector allocations; + auto offset = [](const RadTensor& t, int64_t logical) { + int64_t physical = 0; + for (int d = (int)t.rank - 1; d >= 0; --d) { + physical += (logical % t.shape[d]) * t.stride[d]; + logical /= t.shape[d]; + } + return physical; + }; + for (int i = 0; i < 13; ++i) { + const uint32_t dt = i >= 8 && i <= 11 ? (uint32_t)RAD_I32 + : i >= 5 && i <= 7 ? (uint32_t)RAD_F32 + : (uint32_t)RAD_BF16; + auto ht = T(nullptr, dt, shapes[(size_t)i]); + if (ht.rank >= 2) { + int64_t pitch = ht.shape[ht.rank - 1] + 4; + for (int d = (int)ht.rank - 2; d >= 0; --d) { + ht.stride[d] = pitch; + pitch = ht.shape[d] * pitch + 8; + } + } + const size_t size = (size_t)(ht.shape[0] * ht.stride[0]) * esz(dt) + 256; + bytes[(size_t)i].assign(size, 0xa5); + visible[(size_t)i].assign(size, 0); + ht.data = bytes[(size_t)i].data() + 128; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const int64_t off0 = offset(ht, j); + const float value = + (float)((int)(st_mix32((uint32_t)(i * 173 + j)) % 2001) - 1000) / 2000; + if (dt == RAD_F32) + ((float*)ht.data)[off0] = value; + else if (dt == RAD_BF16) + ((uint16_t*)ht.data)[off0] = h_to_bf16(value); + else + ((int*)ht.data)[off0] = 0; + for (size_t b0 = 0; b0 < esz(dt); ++b0) + visible[(size_t)i][128 + (size_t)off0 * esz(dt) + b0] = 1; + } + host.push_back(ht); + } + auto integers = [&](int i, std::initializer_list values) { + int64_t j = 0; + for (int v : values) ((int*)host[(size_t)i].data)[offset(host[(size_t)i], j++)] = v; + }; + if (anchor) { + integers(8, { 2, 2, 2, 0, 0, 0, 5, 5, 5, 6, 6, 6 }); + integers(9, { 0, 3, 6 }); + for (int slot : { 0, 6 }) + for (int h = 0; h < H; ++h) + ((float*)host[7].data)[slot * host[7].stride[0] + h * host[7].stride[1]] = 0; + } else { + integers(8, { 2, 0, 3, 5, 6, 7 }); + integers(9, { 1, 3, 6 }); + } + integers(10, { accepted_count, 1 }); + integers(11, { cold ? 0 : 1, 1 }); + for (int i = 0; i < 13; ++i) { + void* d = dalloc(bytes[(size_t)i].size()); + if (!d) { + ok(name, false, "allocation failed"); + dlclose(ref); + return; + } + allocations.push_back(d); + st_memcpy(d, bytes[(size_t)i].data(), bytes[(size_t)i].size(), hipMemcpyHostToDevice); + auto dt = host[(size_t)i]; + dt.data = (char*)d + 128; + device.push_back(dt); + } + std::vector ps = { + PI("M", T0 + 7), PI("heads", H), + PI("head_k", D), PI("head_v", D), + PF("lower_bound", -5), PF("scale", 1.0 / std::sqrt(128.0)), + PF("l2_eps", 1e-6), PS("mode", mode), + PS("dtype", "bf16"), PS("state_form", anchor ? "anchor" : "per_candidate") + }; + RadArgs args{}; + args.t = host.data(); + args.n_t = 13; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok("KDA host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, device, ps); + if (rc == RAD_OK && anchor && !std::strcmp(mode, "verify")) { + // A second window must replay only the accepted prefix of the first window. + integers(11, { 1, 1 }); + st_memcpy(allocations[11], bytes[11].data(), bytes[11].size(), hipMemcpyHostToDevice); + args.t = host.data(); + ok("KDA anchor second-window host replay", oracle->launch(&args, nullptr) == RAD_OK); + run_case(row, device, ps); + } + bool matches = rc == RAD_OK, guards = true; + for (int i : { 7, 12 }) + if (rc == RAD_OK) { + std::vector got(bytes[(size_t)i].size()); + st_memcpy(got.data(), allocations[(size_t)i], got.size(), hipMemcpyDeviceToHost); + for (size_t j = 0; j < got.size(); ++j) + if (!visible[(size_t)i][j]) guards = guards && got[j] == 0xa5; + const auto& ht = host[(size_t)i]; + int64_t count0 = 1; + for (uint32_t d = 0; d < ht.rank; ++d) count0 *= ht.shape[d]; + for (int64_t j = 0; j < count0; ++j) { + const auto off0 = offset(ht, j); + const float expected = ht.dtype == RAD_F32 + ? ((const float*)ht.data)[off0] + : h_bf16(((const uint16_t*)ht.data)[off0]); + const float actual = ht.dtype == RAD_F32 + ? ((const float*)(got.data() + 128))[off0] + : h_bf16(((const uint16_t*)(got.data() + 128))[off0]); + const float tol = + ht.dtype == RAD_F32 ? 2e-5f : 0.008f + 0.008f * std::fabs(expected); + matches = matches && std::isfinite(actual) && std::fabs(actual - expected) <= tol; + } + } + ok(fmt("KDA %s %s cold=%d accepted=%d: output, state, untouched slots", + anchor ? "anchor" : "candidate", mode, cold, accepted_count) + .c_str(), + matches); + ok("KDA pitched rows and state red zones", guards); + dlclose(ref); +} + +/* Saves the given switches on construction and restores them on destruction; pin() sets each + * to its value or, for nullptr, back to what the caller had. */ +struct EnvPins { + std::vector names; + std::vector saved; + std::vector had; + explicit EnvPins(std::initializer_list n) : names(n) { + for (const char* k : names) { + const char* v = std::getenv(k); + had.push_back(v != nullptr); + saved.push_back(v ? v : ""); + } + } + void pin(std::initializer_list values) { + size_t i = 0; + for (const char* v : values) { + if (v) + setenv(names[i], v, 1); + else if (had[i]) + setenv(names[i], saved[i].c_str(), 1); + else + unsetenv(names[i]); + ++i; + } + } + ~EnvPins() { + for (size_t i = 0; i < names.size(); ++i) { + if (had[i]) + setenv(names[i], saved[i].c_str(), 1); + else + unsetenv(names[i]); + } + } +}; + +/* One launch, then a 200 ms warm-up and `iters` timed launches (st_time_us: --cold gives the + * median of flushed launches). -1 when the row refuses the arguments. */ +static double form_us(const RadKernelInfo* r, RadArgs* a, int iters) { + if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 200.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + return st_time_us([&](int) { r->launch(a, nullptr); }, iters, nullptr); +} + +static std::vector fetch_bytes(const void* d, size_t bytes) { + std::vector v(bytes); + st_memcpy(v.data(), d, bytes, hipMemcpyDeviceToHost); + return v; +} + +/* kda_update at GLM's TP8 shape (eight heads, 128 x 128 state per head), every form held byte for + * byte to the one-row kernel on shuffle sums (RADIANCE_KDA_FORM=old) over the output and the + * whole state buffer, the slots no sequence names included: prefill of M tokens as one sequence + * per candidate and as three anchored sequences (one cold, one unseated), and the verify step of + * eight sequences with up to six candidates, per candidate and anchored, the anchored one after a + * replay of the accepted prefix. `iters` below zero compares only, as a case. */ +static void kda_forms(const Plugin& pl, int64_t M, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 50; + if (M < 1 || M > 65535) { + std::printf("--perfkda: 1 <= M <= 65535\n"); + return; + } + const RadKernelInfo* row = find(pl, "kda_update_k128_v128_bf16"); + if (!row) { + std::printf("--perfkda: row kda_update_k128_v128_bf16 absent\n"); + return; + } + const int64_t H = 8, D = 128, slots = 64, tokens = std::max(M, 48); + const size_t state_floats = (size_t)(slots * H * D * D); + std::vector state0(state_floats), alog((size_t)H), bias((size_t)(H * D)); + auto uni = [](uint32_t i, float span) { + return (float)((int)(st_mix32(i) % 2001) - 1000) / 1000 * span; + }; + for (size_t i = 0; i < state0.size(); ++i) state0[i] = uni((uint32_t)i * 7u + 1u, 1.0f); + for (size_t i = 0; i < alog.size(); ++i) alog[i] = uni((uint32_t)i + 91u, 0.75f) - 0.25f; + for (size_t i = 0; i < bias.size(); ++i) bias[i] = uni((uint32_t)i * 3u + 17u, 1.0f); + std::vector in[5]; + for (int i = 0; i < 5; ++i) { + in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D))); + for (size_t j = 0; j < in[i].size(); ++j) + in[i][j] = + h_to_bf16(uni((uint32_t)(j * 5 + (size_t)i * 1000003u), i >= 3 ? 2.0f : 1.0f)); + } + void* d_in[5]; + for (int i = 0; i < 5; ++i) { + d_in[i] = dalloc(in[i].size() * 2); + if (!d_in[i]) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_in[i], in[i].data(), in[i].size() * 2, hipMemcpyHostToDevice); + } + void* d_alog = dalloc(alog.size() * 4); + void* d_bias = dalloc(bias.size() * 4); + void* d_state = dalloc(state_floats * 4); + void* d_out = dalloc((size_t)(tokens * H * D * 2)); + if (!d_alog || !d_bias || !d_state || !d_out) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_alog, alog.data(), alog.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_bias, bias.data(), bias.size() * 4, hipMemcpyHostToDevice); + + struct Case { + std::string what; + const char* mode; + bool anchor; + int64_t width; + std::vector cu, idx, accepted, init; + std::vector> counts; /* scratch slots' window counts */ + }; + std::vector cases; + { + Case c{ fmt("prefill M=%lld, one sequence, per candidate", (long long)M), + "prefill", + false, + 1, + { 0, (int)M }, + { 5 }, + { 1 }, + { 1 }, + {} }; + cases.push_back(c); + } + { + const int a = (int)(M / 2), b = (int)(M - M / 4); + Case c{ fmt("prefill M=%lld, three sequences, anchored", (long long)M), + "prefill", + true, + 2, + { 0, a, b, (int)M }, + { 7, 8, 9, 10, -1, 11 }, + { 1, 1, 1 }, + { 0, 1, 1 }, + {} }; + cases.push_back(c); + } + { + Case c{ "verify 8x6, per candidate", "verify", false, 6, {}, {}, {}, {}, {} }; + int t = 0; + for (int s = 0; s < 8; ++s) { + c.cu.push_back(t); + t += s == 3 ? 5 : 6; + for (int k = 0; k < 6; ++k) c.idx.push_back(12 + s * 6 + k); + c.accepted.push_back(1 + s % 6); + c.init.push_back(s == 5 ? 0 : 1); + } + c.cu.push_back(t); + cases.push_back(c); + } + { + Case c{ "verify 8x6, anchored (replay first)", "verify", true, 6, {}, {}, {}, {}, {} }; + int t = 0; + for (int s = 0; s < 8; ++s) { + c.cu.push_back(t); + t += s == 2 ? 4 : 6; + const int anchor_slot = 1 + s, scratch = 20 + s; + for (int k = 0; k < 6; ++k) + c.idx.push_back(k == 0 ? anchor_slot : k == 3 ? scratch : 40 + s); + c.accepted.push_back(1 + (s * 5) % 6); + c.init.push_back(s == 6 ? 0 : 1); + c.counts.push_back({ scratch, s == 4 ? 0.0f : 6.0f }); + } + c.cu.push_back(t); + cases.push_back(c); + } + + EnvPins env({ "RADIANCE_KDA_FORM", "RADIANCE_KDA_ROWS", "RADIANCE_KDA_PREFETCH" }); + struct Form { + const char* what; + const char* form; + const char* rows; + const char* prefetch; + }; + const Form forms[] = { { "rule", nullptr, nullptr, nullptr }, + { "1 row a wave", "new", "1", "1" }, + { "2 rows a wave", "new", "2", "1" }, + { "4 rows a wave", "new", "4", "1" }, + { "1 row a wave, no prefetch", "new", "1", "0" }, + { "2 rows a wave, no prefetch", "new", "2", "0" }, + { "4 rows a wave, no prefetch", "new", "4", "0" } }; + if (!check) + std::printf("kda_update at GLM's TP8 shape (8 heads, 128 x 128), %s, %d launches\n", + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + const size_t out_bytes = (size_t)(tokens * H * D * 2), state_bytes = state_floats * 4; + for (Case& c : cases) { + const int64_t seqs = (int64_t)c.cu.size() - 1; + std::vector start = state0; + for (const auto& sc : c.counts) + for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; + void* d_idx = dalloc(c.idx.size() * 4); + void* d_cu = dalloc(c.cu.size() * 4); + void* d_acc = dalloc(c.accepted.size() * 4); + void* d_init = dalloc(c.init.size() * 4); + if (!d_idx || !d_cu || !d_acc || !d_init) { + std::printf("--perfkda: alloc failed\n"); + return; + } + st_memcpy(d_idx, c.idx.data(), c.idx.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_cu, c.cu.data(), c.cu.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_acc, c.accepted.data(), c.accepted.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_init, c.init.data(), c.init.size() * 4, hipMemcpyHostToDevice); + std::vector t = { T(d_in[0], RAD_BF16, { tokens, H, D }), + T(d_in[1], RAD_BF16, { tokens, H, D }), + T(d_in[2], RAD_BF16, { tokens, H, D }), + T(d_in[3], RAD_BF16, { tokens, H, D }), + T(d_in[4], RAD_BF16, { tokens, H }), + T(d_alog, RAD_F32, { H }), + T(d_bias, RAD_F32, { H * D }), + T(d_state, RAD_F32, { slots, H, D, D }), + T(d_idx, RAD_I32, { seqs, c.width }), + T(d_cu, RAD_I32, { seqs + 1 }), + T(d_acc, RAD_I32, { seqs }), + T(d_init, RAD_I32, { seqs }), + T(d_out, RAD_BF16, { tokens, H, D }) }; + std::vector ps = { + PI("M", tokens), PI("heads", H), + PI("head_k", D), PI("head_v", D), + PF("lower_bound", -5), PF("scale", 1.0 / std::sqrt(128.0)), + PF("l2_eps", 1e-6), PS("mode", c.mode), + PS("dtype", "bf16"), PS("state_form", c.anchor ? "anchor" : "per_candidate") + }; + RadArgs a{}; + a.t = t.data(); + a.n_t = (int)t.size(); + a.p = ps.data(); + a.n_p = (int)ps.size(); + a.world_size = 1; + auto run = [&]() { + st_memcpy(d_state, start.data(), state_bytes, hipMemcpyHostToDevice); + st_memset(d_out, 0xff, out_bytes); + if (row->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) + return false; + return true; + }; + auto outputs = [&]() { + std::vector o = fetch_bytes(d_out, out_bytes); + const std::vector s = fetch_bytes(d_state, state_bytes); + o.insert(o.end(), s.begin(), s.end()); + return o; + }; + env.pin({ "old", nullptr, nullptr }); + const bool ref_ok = run(); + const std::vector ref = outputs(); + if (check) + ok(fmt("KDA %s: old form served", c.what.c_str()).c_str(), ref_ok); + else + std::printf(" %s\n %-34s %8.1f us\n", c.what.c_str(), "old", + ref_ok ? form_us(row, &a, iters) : -1.0); + for (const Form& f : forms) { + env.pin({ f.form, f.rows, f.prefetch }); + const bool served = run(); + const bool same = served && outputs() == ref; + if (check) { + ok(fmt("KDA %s, %s: byte-identical to the old form", c.what.c_str(), f.what) + .c_str(), + ref_ok && same, served ? "" : "not served"); + continue; + } + const double us = served ? form_us(row, &a, iters) : -1.0; + if (us < 0) + std::printf(" %-34s not served\n", f.what); + else + std::printf(" %-34s %8.1f us%s\n", f.what, us, + same ? " = old" : " DIFFERS from old"); + } + } +} + +/* mla_project at GLM's TP8 shape (eight heads, head_dim 256, latent 512) in both modes, every row + * form held byte for byte to the one-row kernels on shuffle sums (RADIANCE_MLA_PROJECT=old) over + * the whole pitched output, so a store past a row or into the pitch shows. M not a multiple of the + * rows a group checks the tail. `iters` below zero compares only, as a case. */ +static void project_forms(const Plugin& pl, int64_t M, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 100; + if (M < 1 || M > 65535) { + std::printf("--perfproject: 1 <= M <= 65535\n"); + return; + } + const RadKernelInfo* row = find(pl, "mla_project_bf16"); + if (!row) { + std::printf("--perfproject: row mla_project_bf16 absent\n"); + return; + } + const int64_t H = 8, wp = 512 + 8; + std::vector w((size_t)(H * 512 * wp)); + for (size_t i = 0; i < w.size(); ++i) + w[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 5u) % 2001) - 1000) / 8000); + void* d_w = dalloc(w.size() * 2); + if (!d_w) { + std::printf("--perfproject: alloc failed\n"); + return; + } + st_memcpy(d_w, w.data(), w.size() * 2, hipMemcpyHostToDevice); + EnvPins env({ "RADIANCE_MLA_PROJECT" }); + if (!check) + std::printf( + "mla_project at GLM's TP8 shape (8 heads, 256 <-> 512), M=%lld, %s, %d launches\n", + (long long)M, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + for (const char* mode : { "absorb", "expand" }) { + const bool absorb = !std::strcmp(mode, "absorb"); + const int64_t xd = absorb ? 256 : 512, yd = absorb ? 512 : 256; + const int64_t xh = xd + 3, xr = H * xh + 5, yh = yd + 4, yr = H * yh + 6; + std::vector x((size_t)(M * xr)); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 7u + 13u) % 2001) - 1000) / 1000); + void* d_x = dalloc(x.size() * 2); + void* d_y = dalloc((size_t)(M * yr * 2)); + if (!d_x || !d_y) { + std::printf("--perfproject: alloc failed\n"); + return; + } + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + RadTensor tx = T(d_x, RAD_BF16, { M, H, xd }), tw = T(d_w, RAD_BF16, { H * 512, 512 }), + ty = T(d_y, RAD_BF16, { M, H, yd }); + tx.stride[1] = xh; + tx.stride[0] = xr; + tw.stride[0] = wp; + ty.stride[1] = yh; + ty.stride[0] = yr; + std::vector t = { tx, tw, ty }; + std::vector ps = { PI("M", M), PI("heads", H), + PI("head_dim", 256), PI("latent_dim", 512), + PS("mode", mode), PS("dtype", "bf16") }; + RadArgs a{}; + a.t = t.data(); + a.n_t = 3; + a.p = ps.data(); + a.n_p = (int)ps.size(); + a.world_size = 1; + const size_t y_bytes = (size_t)(M * yr * 2); + auto run = [&]() { + st_memset(d_y, 0xa5, y_bytes); + return row->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + }; + env.pin({ "old" }); + const bool ref_ok = run(); + const std::vector ref = fetch_bytes(d_y, y_bytes); + if (check) + ok(fmt("MLA project %s M=%lld: old form served", mode, (long long)M).c_str(), ref_ok); + else + std::printf(" %s\n %-20s %8.1f us\n", mode, "old", + ref_ok ? form_us(row, &a, iters) : -1.0); + for (const char* f : { (const char*)nullptr, "1", "2", "4", "8" }) { + env.pin({ f }); + const bool served = run(); + const bool same = served && fetch_bytes(d_y, y_bytes) == ref; + const std::string what = f ? fmt("%s rows a group", f) : std::string("rule"); + if (check) { + ok(fmt("MLA project %s M=%lld, %s: byte-identical to the old form", mode, + (long long)M, what.c_str()) + .c_str(), + ref_ok && same, served ? "" : "not served"); + continue; + } + const double us = served ? form_us(row, &a, iters) : -1.0; + if (us < 0) + std::printf(" %-20s not served\n", what.c_str()); + else + std::printf(" %-20s %8.1f us%s\n", what.c_str(), us, + same ? " = old" : " DIFFERS from old"); + } + } +} + +static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, const char* order, + int model_shape = 0, bool exceptional = false, int NE = 3, int top = 2, + bool holes = false) { + const char* name = "moe_gemm_mxfp4a8"; + const auto* row = find(pl, name); + if (!row || !g_plugin) { + ok(name, false, "row or plugin path absent"); + return; + } + std::string path(g_plugin); + path = path.substr(0, path.find_last_of('/') + 1) + "libref.so"; + void* ref = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!ref) { + ok(name, false, "reference plugin unavailable"); + return; + } + auto count = (int (*)(void))dlsym(ref, "rad_kernel_count"); + auto at = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at"); + const RadKernelInfo* oracle = nullptr; + if (count && at) + for (int i = 0; i < count(); ++i) + if (!std::strcmp(at(i)->op, "moe_gemm_q")) { + oracle = at(i); + break; + } + if (!oracle) { + ok(name, false, "reference operation unavailable"); + dlclose(ref); + return; + } + // Model shapes: 1/2 are GLM's gate_up/down slices at TP4, 3/4 the same at TP8. + static const int MN[5] = { 0, 1024, 4096, 512, 4096 }, MK[5] = { 0, 4096, 512, 4096, 256 }; + const int N[2] = { model_shape ? MN[model_shape] : 64, model_shape ? MN[model_shape] + : parts == 2 ? 32 + : 64 }; + const int K[2] = { model_shape ? MK[model_shape] : 128, model_shape ? MK[model_shape] + : parts == 2 ? 256 + : 128 }; + const int OUT = std::max(N[0], N[1]); + const int NK = std::max(K[0], K[1]), T0 = M * top, AR = !std::strcmp(order, "sorted") ? T0 : M; + const int ap = NK + 8, asp = NK / 128 + 3, yp = OUT + 5; + std::vector av((size_t)AR * ap, 0x7f); + std::vector asc((size_t)AR * asp, 0); + for (int r = 0; r < AR; ++r) { + for (int k = 0; k < NK; ++k) + av[(size_t)r * ap + k] = + rad_f32_to_fp8e4m3((float)((int)(st_mix32(r * NK + k) % 33) - 16) / 4); + for (int g = 0; g < NK / 128; ++g) asc[(size_t)r * asp + g] = 0.003f * (1 + (r + g) % 5); + } + std::vector sorted((size_t)T0, -1), offsets(NE + 1, 0); + std::vector> by(NE); + for (int i = 0; i < T0 - (T0 > 2 ? 2 : 0); ++i) + by[(size_t)((i * 17 + i / 2) % NE)].push_back(i); + int next = 0; + // `holes` drops about every seventh slot inside the runs, a run's first rows included. + for (int e = 0; e < NE; ++e) { + offsets[(size_t)e] = next; + for (size_t j = 0; j < by[(size_t)e].size(); ++j) + sorted[(size_t)next++] = holes && (j + (size_t)e) % 7 == 3 ? -1 : by[(size_t)e][j]; + } + offsets[NE] = next; + std::vector> weights(NE), scales(NE); + std::vector hw[2], hs[2], dw[2], ds[2], pinned; + bool memory_ok = true; + for (int e = 0; e < NE; ++e) { + const int q = e & 1; + weights[(size_t)e].resize((size_t)N[q] * K[q] / 2); + scales[(size_t)e].resize((size_t)N[q] * K[q] / 32); + for (size_t i = 0; i < weights[(size_t)e].size(); ++i) + weights[(size_t)e][i] = (uint8_t)st_mix32((uint32_t)(i + e * 1879)); + for (size_t i = 0; i < scales[(size_t)e].size(); ++i) + scales[(size_t)e][i] = (uint8_t)(122 + st_mix32((uint32_t)(i + e * 271)) % 8); + if (exceptional) { + const uint8_t exponents[] = { 0, 1, 2, 252, 253, 254, 255 }; + for (size_t i = 0; i < scales[(size_t)e].size(); ++i) + scales[(size_t)e][i] = exponents[i % 7]; + } + hw[q].push_back(weights[(size_t)e].data()); + hs[q].push_back(scales[(size_t)e].data()); + auto upload = [&](std::vector& source) -> void* { + if (pooled && e == 0) { + void *h = nullptr, *d = nullptr; + if (hipHostMalloc(&h, source.size(), hipHostMallocMapped) != hipSuccess) { + memory_ok = false; + return nullptr; + } + pinned.push_back(h); + std::memcpy(h, source.data(), source.size()); + if (hipHostGetDevicePointer(&d, h, 0) != hipSuccess) { + memory_ok = false; + return nullptr; + } + return d; + } + void* d = dalloc(source.size()); + if (!d) { + memory_ok = false; + return nullptr; + } + st_memcpy(d, source.data(), source.size(), hipMemcpyHostToDevice); + return d; + }; + dw[q].push_back(upload(weights[(size_t)e])); + ds[q].push_back(upload(scales[(size_t)e])); + } + ok("MXFP4 expert storage allocation", memory_ok); + if (!memory_ok) { + for (void* p : pinned) hipHostFree(p); + dlclose(ref); + return; + } + std::vector expected((size_t)T0 * yp, h_to_bf16(-4)); + std::vector ht = { T(av.data(), RAD_F8E4M3, { AR, NK }), + T(asc.data(), RAD_F32, { AR, NK / 128 }), + T(hw[0].data(), RAD_FP4E2M1, { (NE + 1) / 2, N[0], K[0] }), + T(hs[0].data(), RAD_E8M0, { (NE + 1) / 2, N[0], K[0] / 32 }), + T(sorted.data(), RAD_I32, { T0 }), + T(offsets.data(), RAD_I32, { NE + 1 }), + T(hw[1].data(), RAD_FP4E2M1, { NE / 2, N[1], K[1] }), + T(hs[1].data(), RAD_E8M0, { NE / 2, N[1], K[1] / 32 }), + T(expected.data(), RAD_BF16, { T0, OUT }) }; + ht[0].stride[0] = ap; + ht[1].stride[0] = asp; + ht[8].stride[0] = yp; + for (int i : { 2, 3, 6, 7 }) ht[(size_t)i].stride[0] = 0; + std::vector dt = ht; + auto upload_plain = [&](int i, const void* source, size_t bytes) { + void* d = dalloc(bytes); + st_memcpy(d, source, bytes, hipMemcpyHostToDevice); + dt[(size_t)i].data = d; + }; + upload_plain(0, av.data(), av.size()); + upload_plain(1, asc.data(), asc.size() * 4); + upload_plain(2, dw[0].data(), dw[0].size() * sizeof(void*)); + upload_plain(3, ds[0].data(), ds[0].size() * sizeof(void*)); + upload_plain(6, dw[1].data(), dw[1].size() * sizeof(void*)); + upload_plain(7, ds[1].data(), ds[1].size() * sizeof(void*)); + upload_plain(4, sorted.data(), sorted.size() * 4); + upload_plain(5, offsets.data(), offsets.size() * 4); + const size_t ybytes = expected.size() * 2; + void* dy = dalloc(ybytes + 256); + st_memset(dy, 0xa5, ybytes + 256); + dt[8].data = (char*)dy + 128; + st_memcpy(dt[8].data, expected.data(), ybytes, hipMemcpyHostToDevice); + std::vector ps = { PI("M", M), PI("N", N[0]), PI("K", K[0]), + PI("N_odd", N[1]), PI("K_odd", K[1]), PI("n_expert", NE), + PI("top_k", top), PI("parts", parts), PI("group", 128), + PS("a_order", order), PS("dtype", "mxfp4a8") }; + RadArgs args{}; + args.t = ht.data(); + args.n_t = 9; + args.p = ps.data(); + args.n_p = (int)ps.size(); + args.world_size = 1; + const int rc = oracle->launch(&args, nullptr); + ok("MXFP4 grouped host oracle", rc == RAD_OK); + if (rc == RAD_OK) run_case(row, dt, ps); + std::vector got(ybytes + 256); + st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost); + bool match = rc == RAD_OK, guards = true; + for (size_t i = 0; i < 128; ++i) + guards = guards && got[i] == 0xa5 && got[got.size() - 128 + i] == 0xa5; + const auto* values = (const uint16_t*)(got.data() + 128); + for (int r = 0; r < T0; ++r) + for (int c = 0; c < yp; ++c) { + if (c >= OUT) + guards = guards && values[r * yp + c] == h_to_bf16(-4); + else { + const float want = h_bf16(expected[(size_t)r * yp + c]), + value = h_bf16(values[r * yp + c]); + match = match && (std::isnan(want) ? std::isnan(value) + : std::isinf(want) ? value == want + : std::isfinite(value) && + std::fabs(value - want) <= + 0.004f + 0.008f * std::fabs(want)); + } + } + const char* lut = std::getenv("RADIANCE_MXFP4_LUT"); + const char* pipe = std::getenv("RADIANCE_MXFP4_PREFILL_PIPE"); + auto env_or = [](const char* n, const char* d) { + const char* v = std::getenv(n); + return v ? v : d; + }; + const char* p64 = std::getenv("RADIANCE_MXFP4_PREFILL_P64"); + const std::string p64s = + !p64 ? std::string("rule") + : p64[0] == '1' + ? fmt("BM%s BN%s K%s x%s out%s db%s", env_or("RADIANCE_MXFP4_PREFILL_P64_BM", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_BN", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_COLTILES", "4"), + env_or("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", "rule"), + env_or("RADIANCE_MXFP4_PREFILL_P64_DB", "0")) + : std::string("off"); + ok(fmt("MXFP4 M=%d N=%d K=%d parts=%d pooled=%d %s exceptional=%d holes=%d lut=%s pipe=%s " + "p64=%s, pointer tables and dropped slots", + M, OUT, NK, parts, pooled, order, exceptional, holes, lut ? lut : "rule", + pipe ? pipe : "rule", p64s.c_str()) + .c_str(), + match); + ok("MXFP4 grouped output red zones and pitch", guards); + RadEncoding enc{}; + rad_enc_copy_str(enc.scheme, "affine"); + rad_enc_add_plane(&enc, "codes", RAD_FP4E2M1, 1, 1); + rad_enc_add_plane(&enc, "scale", RAD_E8M0, 1, 32); + int selection = 0; + RadLayout layout{}; + RadTensor plane = T(nullptr, RAD_FP4E2M1, { N[0], K[0] }); + ok("MXFP4 layout keeps canonical bytes", + row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == + RAD_E_UNSUPPORTED); + enc.plane[1].block[1] = 64; + ok("MXFP4 layout rejects a different scale group", + row->layout(ps.data(), (int)ps.size(), 2, &enc, &selection, &plane, 1, &layout) == + RAD_E_DTYPE); + for (void* p : pinned) hipHostFree(p); + dlclose(ref); +} + +/* The MXFP4 expert GEMM at GLM's TP8 slices (mx_experts_check's model shapes 3 and 4): gate_up + * 512 x 4096 over token rows (parts 2), down 4096 x 256 over sorted rows, over an M-token chunk. + * + * Routing is uniform with top_k distinct experts a token, as a trained router spreads load at + * decode, or skewed (`skew`): a Gamma load per expert with the given coefficient of variation + * ("g1.0" or "1.0"), or Zipf ("z1.1") over a shuffled rank, each token drawing its top_k distinct + * experts by that load. The fill of tall row tiles hangs on that skew, and the real router's is not + * measured. Every expert has its own bytes behind a pointer table, as the engine passes them, so + * the touched experts are the real traffic. Warm, a touched set under 64 MiB is cache-resident + * after the first launch; --cold is the engine's case. + * + * Forms are chosen by the RADIANCE_MXFP4_* environment, read at every launch. Their rule is + * mirrored here only to name the form and count the expert slices it streams: a (job, expert) + * pair reads the whole slice across the column blocks, so row groups re-read an expert once per + * group its run spans, and the expert-major decode form once per 16 of its rows. Every form must + * match the bytes of a pinned reference ("old": the TP8 prefill form with its stage prefetch from + * 512 routed rows, below that the rule), since each keeps one accumulation order per element. */ +static void mx_perf(const Plugin& pl, int64_t Mtok, int iters, int64_t E, int64_t top_k, + bool f8 = false, const char* skew = nullptr) { + if (iters <= 0) iters = 100; + if (Mtok < 1 || E < 2 || E > 512 || top_k < 1 || top_k > E) { + std::printf("--perfmx: M >= 1, 2 <= experts <= 512 and 1 <= top_k <= experts\n"); + return; + } + const char* const rname = f8 ? "moe_gemm_fp8a8_f32scale" : "moe_gemm_mxfp4a8"; + const RadKernelInfo* r = find(pl, rname); + if (!r) { + std::printf("--perfmx: row %s absent\n", rname); + return; + } + const int64_t Tr = Mtok * top_k; + + uint64_t rs = 0x9E3779B97F4A7C15ull; + auto rnd = [&]() { + rs ^= rs << 13; + rs ^= rs >> 7; + rs ^= rs << 17; + return rs; + }; + /* An expert's load: none (uniform), Gamma(1/cv^2) or 1/rank^s. */ + char kind = 'u'; + double sk = 0.0; + if (skew && *skew) { + kind = std::isalpha((unsigned char)skew[0]) ? (char)skew[0] : 'g'; + sk = std::strtod(std::isalpha((unsigned char)skew[0]) ? skew + 1 : skew, nullptr); + if ((kind != 'g' && kind != 'z') || !(sk >= 0.0)) { + std::printf("--perfmx: skew is a Gamma CV (\"g1.0\" or \"1.0\") or a Zipf exponent " + "(\"z1.1\")\n"); + return; + } + if (sk == 0.0) kind = 'u'; + } + std::vector load((size_t)E, 1.0); + if (kind == 'g') { + std::mt19937_64 gen(0x5EEDull); + std::gamma_distribution gam(1.0 / (sk * sk), 1.0); + for (double& v : load) v = std::max(gam(gen), 1e-12); + } else if (kind == 'z') { + std::vector rank((size_t)E); + for (int64_t e = 0; e < E; ++e) rank[(size_t)e] = e; + for (int64_t e = E - 1; e > 0; --e) + std::swap(rank[(size_t)e], rank[(size_t)(rnd() % (uint64_t)(e + 1))]); + for (int64_t e = 0; e < E; ++e) + load[(size_t)e] = std::pow((double)(rank[(size_t)e] + 1), -sk); + } + std::vector perm((size_t)E); + for (int64_t e = 0; e < E; ++e) perm[(size_t)e] = (int32_t)e; + std::vector> by_e((size_t)E); + std::vector left((size_t)E); + for (int64_t t = 0; t < Mtok; ++t) { + if (kind == 'u') { + for (int64_t j = 0; j < top_k; ++j) { + std::swap(perm[(size_t)j], + perm[(size_t)(j + (int64_t)(rnd() % (uint64_t)(E - j)))]); + by_e[(size_t)perm[(size_t)j]].push_back((int32_t)(t * top_k + j)); + } + continue; + } + left = load; + double sum = 0.0; + for (double v : left) sum += v; + for (int64_t j = 0; j < top_k; ++j) { + double u = (double)(rnd() >> 11) * (1.0 / 9007199254740992.0) * sum; + int64_t e = 0; + while (e + 1 < E && (left[(size_t)e] == 0.0 || u >= left[(size_t)e])) { + u -= left[(size_t)e]; + ++e; + } + while (left[(size_t)e] == 0.0) e = (e + 1) % E; + sum -= left[(size_t)e]; + left[(size_t)e] = 0.0; + by_e[(size_t)e].push_back((int32_t)(t * top_k + j)); + } + } + std::vector off((size_t)(E + 1), 0), sorted, owner; + sorted.reserve((size_t)Tr); + owner.reserve((size_t)Tr); + int64_t touched = 0, rmax = 0, under16 = 0; + double sq = 0.0; + for (int64_t e = 0; e < E; ++e) { + const int64_t n = (int64_t)by_e[(size_t)e].size(); + off[(size_t)(e + 1)] = off[(size_t)e] + (int32_t)n; + sorted.insert(sorted.end(), by_e[(size_t)e].begin(), by_e[(size_t)e].end()); + owner.insert(owner.end(), (size_t)n, (int32_t)e); + touched += n > 0; + rmax = std::max(rmax, n); + under16 += n < 16; + sq += (double)n * (double)n; + } + const double mean = (double)Tr / (double)E; + const double cv = + mean > 0 ? std::sqrt(std::max(sq / (double)E - mean * mean, 0.0)) / mean : 0.0; + const std::string routing = kind == 'u' + ? std::string("uniform") + : fmt("%s %.2f", kind == 'g' ? "Gamma CV" : "Zipf s", sk); + std::printf( + "%s at GLM's TP8 slices, a %lld-token chunk: Tr=%lld routed rows, " + "top %lld of %lld experts (%s), %lld touched, a run 1..%lld rows, %.1f mean, CV %.2f, " + "%lld under 16; %s, %d launches\n", + rname, (long long)Mtok, (long long)Tr, (long long)top_k, (long long)E, routing.c_str(), + (long long)touched, (long long)rmax, mean, cv, (long long)under16, + g_cold > 0 + ? fmt("cold (%lld MiB read before each, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", + iters); + + constexpr int kEnvs = 22; + static const char* const kEnvMx[kEnvs] = { "RADIANCE_MXFP4_DECODE_EXPERTS", + "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", + "RADIANCE_MXFP4_EXPERTS_STAGE_K", + "RADIANCE_MXFP4_EXPERTS_COLTILES", + "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_PREFILL_PIPE", + "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + /* The F32-scale row has no prefill forms; its slots 1..5 and 8..21 name the MXFP4 switches, + * which it does not read. */ + static const char* const kEnvF8[kEnvs] = { "RADIANCE_FP8F32_DECODE_EXPERTS", + "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", + "RADIANCE_FP8F32_EXPERTS_STAGE_K", + "RADIANCE_FP8F32_EXPERTS_COLTILES", + "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_PREFILL_PIPE", + "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + const char* const* const kEnv = f8 ? kEnvF8 : kEnvMx; + std::string saved[kEnvs]; + bool had[kEnvs]; + for (int i = 0; i < kEnvs; ++i) { + const char* v = std::getenv(kEnv[i]); + had[i] = v != nullptr; + if (v) saved[i] = v; + } + auto restore = [&]() { + for (int i = 0; i < kEnvs; ++i) { + if (had[i]) + setenv(kEnv[i], saved[i].c_str(), 1); + else + unsetenv(kEnv[i]); + } + }; + auto on = [](const char* n, bool dflt) { + const char* v = std::getenv(n); + return v ? v[0] == '1' : dflt; + }; + /* body()'s glm_prefill: the default of the prefill switches at GLM's projections. */ + const bool glm = !f8 && E == 288 && top_k == 8; + auto num = [](const char* n, long dflt) { + const char* v = std::getenv(n); + return v && *v ? std::strtol(v, nullptr, 10) : dflt; + }; + /* env nullptr: the environment as given. Expert-major forms pin stage and column tiles; the + * prefill forms exist only from 512 routed rows. `lut` 0 or 1 pins the weight decode, `pipe` + * the TP8 prefill form's stage prefetch (-1: as given); the arithmetic decode without the + * prefetch is the bytewise reference of the others. `bm` > 0 pins the P64 form below its row + * bound at BM, BN, stage, column tiles (down only), LDS output and double buffer (gate_up + * only); every other pinned form pins P64 off. */ + struct Form { + const char* env; + int stage, tiles, lut, pipe = -1, bm = 0, bn = 0, sk = 0, ct = 0, out = 0, db = 0; + }; + std::vector
forms = { { nullptr, 0, 0, -1 }, { "100000", 256, 1, -1 }, + { "100000", 256, 4, -1 }, { "100000", 128, 1, -1 }, + { "100000", 128, 4, -1 }, { "000000", 0, 0, -1 } }; + if (!f8) + for (int lut : { 0, 1 }) { + forms.push_back({ "100000", 256, 1, lut }); + forms.push_back({ "100000", 128, 4, lut }); + } + if (Tr >= 512 && !f8) { + for (const char* f : { "010000", "001000", "011000", "011100", "011110", "011111" }) + forms.push_back({ f, 0, 0, -1 }); + for (int pipe : { 0, 1 }) + for (int lut : { 0, 1 }) forms.push_back({ "011111", 0, 0, lut, pipe }); + } + const Form old = Tr >= 512 && !f8 ? Form{ "011111", 0, 0, 1, 1 } : Form{ nullptr, 0, 0, -1 }; + auto apply = [&](const Form& F) { + restore(); + if (!F.env) return; + for (int i = 0; i < 6; ++i) setenv(kEnv[i], F.env[i] == '1' ? "1" : "0", 1); + const int pinned[2] = { F.stage, F.tiles }; + for (int i = 0; i < 2; ++i) { + if (F.stage) + setenv(kEnv[6 + i], std::to_string(pinned[i]).c_str(), 1); + else + unsetenv(kEnv[6 + i]); + } + const int pinned2[2] = { F.lut, F.pipe }; + for (int i = 8; i < 10; ++i) + if (pinned2[i - 8] >= 0) setenv(kEnv[i], pinned2[i - 8] ? "1" : "0", 1); + setenv(kEnv[10], F.bm ? "1" : "0", 1); + if (F.bm) { + const int v[7] = { 0, 0, F.bm, F.bn, F.sk, F.ct, F.out }; + for (int i = 0; i < 7; ++i) setenv(kEnv[11 + i], std::to_string(v[i]).c_str(), 1); + setenv(kEnv[21], F.db ? "1" : "0", 1); + } + }; + + struct Proj { + const char* name; + int64_t N, K, parts; + bool srt; + }; + const Proj projs[2] = { { "gate_up", 512, 4096, 2, false }, { "down", 4096, 256, 1, true } }; + double rule_us = 0.0, rule_bytes = 0.0; + for (const Proj& P : projs) { + const int64_t N = P.N, K = P.K, Ma = P.srt ? Tr : Mtok; + /* Per expert: E2M1 codes and an E8M0 byte per 32, or E4M3 codes and an f32 per 128 x 128. */ + const int64_t cb = f8 ? N * K : N * K / 2, sb = f8 ? N / 128 * (K / 128) * 4 : N * K / 32; + const int64_t nec[2] = { (E + 1) / 2, E / 2 }; + const double slice = (double)(cb + sb); + std::printf(" %-7s %lld x %lld (parts %lld, %s rows): %.3f MiB an expert slice, %.1f MiB " + "touched of %.1f MiB\n", + P.name, (long long)N, (long long)K, (long long)P.parts, + P.srt ? "sorted" : "token", slice / 1048576.0, touched * slice / 1048576.0, + E * slice / 1048576.0); + /* P64 over BM x BN x stage; at down's K (A resident) also over column tiles, and the LDS + * output at the default. */ + std::vector pf = forms; + if (Tr >= 512 && !f8) { + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk2 : { 128, 256 }) + for (int ct : { 1, 4 }) { + if (ct == 1 && K > 256) continue; + pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, sk2, ct, 0 }); + } + pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1 }); + /* The double buffer where two stages fit in LDS (streamed A, gate_up). */ + if (K > 256) { + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + pf.push_back({ "000000", 0, 0, -1, -1, bm, bn, 128, 4, 0, 1 }); + pf.push_back({ "000000", 0, 0, -1, -1, 32, 64, 256, 4, 0, 1 }); + pf.push_back({ "000000", 0, 0, -1, -1, 64, 128, 128, 4, 1, 1 }); + } + } + + std::vector av((size_t)(Ma * K)); + for (size_t i = 0; i < av.size(); ++i) + av[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i) % 33) - 16) / 4); + std::vector asc((size_t)(Ma * (K / 128))); + for (size_t i = 0; i < asc.size(); ++i) asc[i] = 0.003f * (float)(1 + i % 5); + void* d_a = dalloc(av.size()); + void* d_as = dalloc(asc.size() * 4); + void* d_s = dalloc((size_t)Tr * 4); + void* d_o = dalloc((size_t)(E + 1) * 4); + void* d_y = dalloc((size_t)(Tr * N) * 2); + void *d_w[2], *d_sc[2], *d_tw[2], *d_ts[2]; + bool alloc_ok = d_a && d_as && d_s && d_o && d_y; + for (int c = 0; c < 2 && alloc_ok; ++c) { + d_w[c] = dalloc((size_t)(nec[c] * cb)); + d_sc[c] = dalloc((size_t)(nec[c] * sb)); + d_tw[c] = dalloc((size_t)nec[c] * sizeof(void*)); + d_ts[c] = dalloc((size_t)nec[c] * sizeof(void*)); + alloc_ok = d_w[c] && d_sc[c] && d_tw[c] && d_ts[c]; + if (!alloc_ok) break; + /* E4M3 codes with the top exponent bit clear: finite, under 2 in magnitude. */ + std::vector hw((size_t)(nec[c] * cb + 7) / 8); + for (uint64_t& v : hw) v = f8 ? rnd() & 0xF7F7F7F7F7F7F7F7ull : rnd(); + st_memcpy(d_w[c], hw.data(), (size_t)(nec[c] * cb), hipMemcpyHostToDevice); + /* E8M0 2^-5..2^2 or f32 near 0.01: finite products, no exceptional codes on the timed + * path. */ + std::vector hs((size_t)(nec[c] * sb)); + if (f8) + for (size_t i = 0; i < hs.size(); i += 4) { + const float v = 0.01f * (float)(1 + rnd() % 7); + std::memcpy(&hs[i], &v, 4); + } + else + for (uint8_t& v : hs) v = (uint8_t)(122 + rnd() % 8); + st_memcpy(d_sc[c], hs.data(), hs.size(), hipMemcpyHostToDevice); + std::vector tw((size_t)nec[c]), tsc((size_t)nec[c]); + for (int64_t x = 0; x < nec[c]; ++x) { + tw[(size_t)x] = (const char*)d_w[c] + x * cb; + tsc[(size_t)x] = (const char*)d_sc[c] + x * sb; + } + st_memcpy(d_tw[c], tw.data(), tw.size() * sizeof(void*), hipMemcpyHostToDevice); + st_memcpy(d_ts[c], tsc.data(), tsc.size() * sizeof(void*), hipMemcpyHostToDevice); + } + if (!alloc_ok) { + std::printf(" %s: alloc failed\n", P.name); + dfree_all(); + break; + } + st_memcpy(d_a, av.data(), av.size(), hipMemcpyHostToDevice); + st_memcpy(d_as, asc.data(), asc.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sorted.data(), (size_t)Tr * 4, hipMemcpyHostToDevice); + st_memcpy(d_o, off.data(), (size_t)(E + 1) * 4, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_a, RAD_F8E4M3, { Ma, K }), + T(d_as, RAD_F32, { Ma, K / 128 }), + f8 ? T(d_tw[0], RAD_F8E4M3, { nec[0], N, K }) + : T(d_tw[0], RAD_FP4E2M1, { nec[0], N, K }), + f8 ? T(d_ts[0], RAD_F32, { nec[0], N / 128, K / 128 }) + : T(d_ts[0], RAD_E8M0, { nec[0], N, K / 32 }), + T(d_s, RAD_I32, { Tr }), + T(d_o, RAD_I32, { E + 1 }), + f8 ? T(d_tw[1], RAD_F8E4M3, { nec[1], N, K }) + : T(d_tw[1], RAD_FP4E2M1, { nec[1], N, K }), + f8 ? T(d_ts[1], RAD_F32, { nec[1], N / 128, K / 128 }) + : T(d_ts[1], RAD_E8M0, { nec[1], N, K / 32 }), + T(d_y, RAD_BF16, { Tr, N }), + }; + /* A pointer table is told from a stacked plane by a leading stride of zero. */ + for (int i : { 2, 3, 6, 7 }) ts[(size_t)i].stride[0] = 0; + std::vector ps = { + PI("M", Mtok), + PI("N", N), + PI("K", K), + PI("N_odd", N), + PI("K_odd", K), + PI("n_expert", E), + PI("top_k", top_k), + PI("parts", P.parts), + PI("group", 128), + PS("a_order", P.srt ? "sorted" : "token"), + PS("dtype", f8 ? "fp8a8f32" : "mxfp4a8"), + }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); + a.n_t = (int)ts.size(); + a.p = ps.data(); + a.n_p = (int)ps.size(); + a.world_size = 1; + const double flop = 2.0 * (double)Tr * (double)N * (double)K; + const size_t ybytes = (size_t)(Tr * N) * 2; + std::vector reference(ybytes), got(ybytes); + apply(old); + st_memset(d_y, 0xff, ybytes); + bool have_old = r->launch(&a, nullptr) == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + if (have_old) st_memcpy(reference.data(), d_y, ybytes, hipMemcpyDeviceToHost); + std::printf(" old: %s\n", + !have_old ? "not served, no byte comparison" + : old.env ? "TP8 prefill form, stage prefetch and table decode pinned" + : "the rule"); + for (size_t f = 0; f < pf.size(); ++f) { + apply(pf[f]); + const long max_t = f8 ? num("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1) + : num(P.srt ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN" + : "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP", + glm ? (P.srt ? 6143 : 768) : 511); + const char* forced = std::getenv(kEnv[0]); + const bool pwide = K > 256 ? Tr >= num(kEnv[19], 24576) : Tr >= num(kEnv[20], 24576); + const long dbm = pwide || (K > 256 && Tr >= num(kEnv[18], 12288)) ? 64 : 32; + const long dbn = pwide ? 128 : 64; + const long dsk = K > 256 && !pwide ? 256 : 128; + const long pbm = num(kEnv[13], dbm) == 32 ? 32 : 64, + pbn = num(kEnv[14], dbn) == 64 ? 64 : 128; + const long psk = num(kEnv[15], dsk) == 256 ? 256 : 128; + const bool p64 = !f8 && on(kEnv[10], glm) && !(forced && forced[0] == '1') && + Tr >= num(P.srt ? kEnv[12] : kEnv[11], P.srt ? 5760 : 769) && + (Tr + pbm - 1) / pbm + E <= 65535; + const bool expert = !p64 && on(kEnv[0], max_t < 0 || Tr <= max_t); + const long esk = num(kEnv[6], K <= 256 ? 128 : 256) == 128 ? 128 : 256; + const long et = num(kEnv[7], K <= 256 || (f8 && Tr < 128) ? 4 : 1) == 4 ? 4 : 1; + const bool aligned = !p64 && !expert && !f8 && on(kEnv[1], glm) && Tr >= 512; + const bool wide = !p64 && !expert && !f8 && on(kEnv[2], glm) && Tr >= 512; + const bool tall = wide && aligned && on(kEnv[3], glm), n64 = tall && on(kEnv[4], glm); + const bool cached = n64 && on(kEnv[5], glm), lut = f8 || p64 || on(kEnv[8], true); + const bool pipe = cached && on(kEnv[9], glm); + const long pct = K <= 256 && num(kEnv[16], 4) != 1 ? 4 : 1; + const bool pout = num(kEnv[17], pwide ? 1 : 0) == 1; + const bool pdb = + K > 256 && num(kEnv[21], 0) == 1 && (psk == 128 || (pbm == 32 && pbn == 64)); + const int64_t jr = p64 ? pbm : tall ? 32 : 16, tile = Tr < 32 ? 1 : Tr < 128 ? 4 : 16; + int64_t streams = 0; + if (p64 || aligned || expert) + for (int64_t e = 0; e < E; ++e) + streams += (off[(size_t)(e + 1)] - off[(size_t)e] + jr - 1) / jr; + else + for (int64_t i = 0; i < Tr; ++i) + streams += i % tile == 0 || owner[(size_t)i] != owner[(size_t)(i - 1)]; + const std::string label = + std::string(pf[f].env ? "" : "rule: ") + + (p64 ? fmt("P64 BM%ld BN%ld K%ld", pbm, pbn, psk) + + (K <= 256 ? fmt(" x%ld, A resident", pct) : "") + + (pout ? ", LDS out" : "") + (pdb ? ", double buffer" : "") + : expert ? fmt("expert-major K%ld x%ld tiles", esk, et) + : std::string(n64 ? "M32N64" + : tall ? "M32N32" + : wide ? "M16N32" + : f8 ? "M16N64" + : "M16N16") + + (aligned ? " aligned jobs" + : fmt(" row groups of %lld", (long long)tile)) + + (cached ? ", cached rows" : "") + (pipe ? ", pipe" : "")) + + (lut ? "" : ", fp4x4"); + st_memset(d_y, 0xff, ybytes); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { + std::printf(" %-46s rc=%d (not served)\n", label.c_str(), rc); + continue; + } + st_memcpy(got.data(), d_y, ybytes, hipMemcpyDeviceToHost); + { + hipEvent_t w0, w1; + st_ev_create(&w0); + st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 500.0f; ++guard) { + for (int i = 0; i < 4; ++i) r->launch(&a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); + st_ev_destroy(w1); + } + const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + if (f == 0) { + rule_us += us; + rule_bytes += touched * slice; + } + std::string same; + if (have_old) { + int64_t diff = 0; + for (size_t i = 0; i < ybytes; i += 2) + diff += std::memcmp(&got[i], &reference[i], 2) != 0; + same = diff ? fmt(" %lld elements differ from old", (long long)diff) : " = old"; + } + std::printf( + " %-46s %9.1f us %7.1f GB/s touched %5.2fx streamed %6.1f TFLOP/s%s\n", + label.c_str(), us, touched * slice / (us * 1e3), + touched ? (double)streams / (double)touched : 0.0, flop / (us * 1e6), same.c_str()); + } + restore(); + dfree_all(); + } + if (rule_us > 0) + std::printf(" the rule's forms, gate_up + down: %.1f us a layer, %.1f GB/s touched\n", + rule_us, rule_bytes / (rule_us * 1e3)); +} + /* The gated residual's read at int8 codes. The same inputs run with the codes plane as E4M3 and * as I8: the bf16 block input and the rotated E4M3 twin must be byte-identical, and the int8 codes * must equal quant_act_i8g's over the bf16 input (per (row, 128) at amax / 127). Row counts reach @@ -11278,6 +13829,995 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool (void)hipStreamDestroy(hs); } +/* mHC's chunk-split read, as tensor parallelism issues it: every rank's mhc_pre_partial over its + * chunks, the partials joined row by row as the row-interleaved all_gather lays them out (here on + * the host), then mhc_pre_finish. The result must be byte-identical to mhc_pre on the same inputs, + * under each of mhc_pre's kernel switches, since both run the same projection and finishing + * kernels; the partial matrix's padding slots must be zero. */ +static void mhc_split_check(const Plugin& pl, int64_t rows, int world, const char* env, + const char* value) { + const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); + const RadKernelInfo* part_row = find(pl, "mhc_pre_partial_bf16"); + const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); + const char* nm = "mhc_pre_partial_bf16 + mhc_pre_finish_bf16"; + if (!pre || !part_row || !fin) { ok(nm, false, "row absent"); return; } + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + const int64_t mine = total / world, hp = W + 6, xp = n + 2; + const char* saved = env ? std::getenv(env) : nullptr; + const std::string keep = saved ? saved : ""; + if (env) setenv(env, value, 1); + + std::vector hv((size_t)(rows * hp)); + for (size_t i = 0; i < hv.size(); ++i) + hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); + for (size_t i = 0; i < fv.size(); ++i) + fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; + void* d_h = dalloc(hv.size() * 2); + void* d_f = dalloc(fv.size() * 4); + void* d_s = dalloc(12); + void* d_b = dalloc(bv.size() * 4); + st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + RadTensor th = T(d_h, RAD_BF16, { rows, W }); th.stride[0] = hp; + const RadTensor tf = T(d_f, RAD_F32, { mix, W }), ts = T(d_s, RAD_F32, { 3 }), + tb = T(d_b, RAD_F32, { mix }); + struct Out { std::vector x, p, c; }; + auto outputs = [&](void** dx, void** dp, void** dc, std::vector* t) { + *dx = dalloc((size_t)(rows * xp * 2)); *dp = dalloc((size_t)(rows * hc * 4)); + *dc = dalloc((size_t)(rows * hc * hc * 4)); + RadTensor tx = T(*dx, RAD_BF16, { rows, n }); tx.stride[0] = xp; + t->push_back(tx); + t->push_back(T(*dp, RAD_F32, { rows, hc })); + t->push_back(T(*dc, RAD_F32, { rows, hc * hc })); + }; + auto fetch = [&](void* dx, void* dp, void* dc) { + Out o; + o.x.resize((size_t)(rows * xp * 2)); o.p.resize((size_t)(rows * hc * 4)); + o.c.resize((size_t)(rows * hc * hc * 4)); + st_memcpy(o.x.data(), dx, o.x.size(), hipMemcpyDeviceToHost); + st_memcpy(o.p.data(), dp, o.p.size(), hipMemcpyDeviceToHost); + st_memcpy(o.c.data(), dc, o.c.size(), hipMemcpyDeviceToHost); + return o; + }; + auto launch = [&](const RadKernelInfo* r, std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); + a.world_size = 1; + const int rc = r->launch(&a, nullptr); + return rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + }; + std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), + PF("eps", 1e-5), PF("hc_eps", 1e-6) }; + + void *wx, *wp, *wc; + std::vector whole = { th, tf, ts, tb }; + outputs(&wx, &wp, &wc, &whole); + std::vector pp = coef; pp.push_back(PS("dtype", "bf16")); + bool good = launch(pre, whole, pp); + const Out want = fetch(wx, wp, wc); + + std::vector gathered((size_t)(rows * total * S)); + bool padded = true; + for (int rank = 0; rank < world && good; ++rank) { + void* d_p = dalloc((size_t)(rows * mine * S * 4)); + std::vector t = { th, tf, T(d_p, RAD_F32, { rows, mine * S }) }; + std::vector p = { PI("M", rows), PI("n", n), PI("hc", hc), PI("chunk", 2048), + PI("first", rank * mine), PI("chunks", mine), + PS("dtype", "bf16") }; + std::vector fill((size_t)(rows * mine * S), 7.0f); + st_memcpy(d_p, fill.data(), fill.size() * 4, hipMemcpyHostToDevice); + good = launch(part_row, t, p); + st_memcpy(fill.data(), d_p, fill.size() * 4, hipMemcpyDeviceToHost); + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && fill[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &fill[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + void* d_g = dalloc(gathered.size() * 4); + st_memcpy(d_g, gathered.data(), gathered.size() * 4, hipMemcpyHostToDevice); + void *sx, *sp, *sc; + std::vector split = { T(d_g, RAD_F32, { rows, total * S }), th, ts, tb }; + outputs(&sx, &sp, &sc, &split); + std::vector fp = coef; fp.push_back(PI("chunk", 2048)); fp.push_back(PS("dtype", "bf16")); + good = good && launch(fin, split, fp); + const Out got = fetch(sx, sp, sc); + const bool same = good && got.x == want.x && got.p == want.p && got.c == want.c; + ok(fmt("%s at M=%lld over %d ranks%s%s%s: byte-identical to mhc_pre", nm, (long long)rows, + world, env ? ", " : "", env ? env : "", env ? (std::string("=") + value).c_str() : "") + .c_str(), same, good ? (got.x != want.x ? "x differs" : got.p != want.p ? "post differs" + : got.c != want.c ? "comb differs" : "") + : "launch failed"); + ok(fmt("%s at M=%lld over %d ranks: zero padding", nm, (long long)rows, world).c_str(), padded); + if (env) { if (saved) setenv(env, keep.c_str(), 1); else unsetenv(env); } +} + +/* mhc_pre and mhc_post at GLM's shape (n 4096, four streams, 2048-column chunks, 20 Sinkhorn + * rounds), every form timed and compared byte for byte with the old dispatch + * (RADIANCE_MHC_FINISH=old, RADIANCE_MHC_PARTIAL_VEC=0, the per-output mhc_post). + * The whole op, its partials alone (all eight chunks, and the one chunk a rank computes at TP8) + * and its finish alone over those partials. GB/s counts h and x (and mhc_post's output); the + * mixing weights (1.5 MiB) stay in L2. `iters` below zero runs each form once and reports only + * the comparisons, as a case. */ +static void mhcpre_perf(const Plugin& pl, int64_t rows, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + if (rows < 1 || rows > 65535) { std::printf("--perfmhcpre: 1 <= M <= 65535\n"); return; } + const RadKernelInfo* pre = find(pl, "mhc_pre_bf16"); + const RadKernelInfo* part = find(pl, "mhc_pre_partial_bf16"); + const RadKernelInfo* fin = find(pl, "mhc_pre_finish_bf16"); + const RadKernelInfo* post = find(pl, "mhc_post_bf16"); + if (!pre || !part || !fin || !post) { std::printf("--perfmhcpre: an mhc row is absent\n"); return; } + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + static const char* const kEnv[5] = { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_ROWS4_MIN", + "RADIANCE_MHC_POST_VEC", "RADIANCE_MHC_PARTIAL_VEC", + "RADIANCE_MHC_PARTIAL_ROWS" }; + std::string saved[5]; + bool had[5]; + for (int i = 0; i < 5; ++i) { + const char* v = std::getenv(kEnv[i]); + had[i] = v != nullptr; + if (v) saved[i] = v; + } + auto pin = [&](const char* finish, const char* rows4, const char* vec, + const char* pvec = nullptr, const char* prows = nullptr) { + const char* v[5] = { finish, rows4, vec, pvec, prows }; + for (int i = 0; i < 5; ++i) { + if (v[i]) setenv(kEnv[i], v[i], 1); + else if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); + else unsetenv(kEnv[i]); + } + }; + + std::vector hv((size_t)(rows * W)), yv((size_t)(rows * n)); + for (size_t i = 0; i < hv.size(); ++i) + hv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 3u + 11u) % 2001) - 1000) / 1000); + for (size_t i = 0; i < yv.size(); ++i) + yv[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i * 5u + 3u) % 2001) - 1000) / 500); + std::vector fv((size_t)(mix * W)), sv = { 0.7f, 0.9f, 1.1f }, bv((size_t)mix); + for (size_t i = 0; i < fv.size(); ++i) + fv[i] = (float)((int)(st_mix32((uint32_t)i + 77u) % 2001) - 1000) / 100000; + for (size_t i = 0; i < bv.size(); ++i) bv[i] = (float)((int)(i % 7) - 3) * 0.25f; + void* d_h = dalloc(hv.size() * 2); + void* d_y = dalloc(yv.size() * 2); + void* d_f = dalloc(fv.size() * 4); + void* d_s = dalloc(12); + void* d_b = dalloc(bv.size() * 4); + void* d_x = dalloc((size_t)(rows * n * 2)); + void* d_p = dalloc((size_t)(rows * hc * 4)); + void* d_c = dalloc((size_t)(rows * hc * hc * 4)); + void* d_part = dalloc((size_t)(rows * total * S * 4)); + void* d_part1 = dalloc((size_t)(rows * S * 4)); + void* d_out = dalloc((size_t)(rows * W * 2)); + if (!d_h || !d_y || !d_f || !d_s || !d_b || !d_x || !d_p || !d_c || !d_part || !d_part1 || !d_out) { + std::printf("--perfmhcpre: alloc failed\n"); + return; + } + st_memcpy(d_h, hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_y, yv.data(), yv.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_f, fv.data(), fv.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, sv.data(), 12, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + const RadTensor th = T(d_h, RAD_BF16, { rows, W }), tf = T(d_f, RAD_F32, { mix, W }), + ts = T(d_s, RAD_F32, { 3 }), tb = T(d_b, RAD_F32, { mix }), + tx = T(d_x, RAD_BF16, { rows, n }), tp = T(d_p, RAD_F32, { rows, hc }), + tc = T(d_c, RAD_F32, { rows, hc * hc }); + std::vector coef = { PI("M", rows), PI("n", n), PI("hc", hc), PI("iterations", 20), + PF("eps", 1e-6), PF("hc_eps", 1e-6), PI("chunk", 2048), + PS("dtype", "bf16") }; + std::vector p_all = { PI("M", rows), PI("n", n), PI("hc", hc), PI("chunk", 2048), + PI("first", 0), PI("chunks", total), PS("dtype", "bf16") }; + std::vector p_one = p_all; + p_one[5] = PI("chunks", 1); + std::vector a_pre = { th, tf, ts, tb, tx, tp, tc }; + std::vector a_all = { th, tf, T(d_part, RAD_F32, { rows, total * S }) }; + std::vector a_one = { th, tf, T(d_part1, RAD_F32, { rows, S }) }; + std::vector a_fin = { T(d_part, RAD_F32, { rows, total * S }), th, ts, tb, tx, tp, tc }; + std::vector a_post = { T(d_y, RAD_BF16, { rows, n }), th, tp, tc, + T(d_out, RAD_BF16, { rows, W }) }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); + a.world_size = 1; + return a; + }; + RadArgs A_pre = args(a_pre, coef), A_all = args(a_all, p_all), A_one = args(a_one, p_one), + A_fin = args(a_fin, coef), A_post = args(a_post, coef); + auto timed = [&](const RadKernelInfo* r, RadArgs* a) { + if (r->launch(a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0; + if (check) return 0.0; + hipEvent_t w0, w1; + st_ev_create(&w0); st_ev_create(&w1); + st_ev_record(w0, nullptr); + float wms = 0.0f; + for (int guard = 0; guard < 100000 && wms < 200.0f; ++guard) { + for (int i = 0; i < 8; ++i) r->launch(a, nullptr); + st_ev_record(w1, nullptr); + st_ev_sync(w1); + st_ev_elapsed(&wms, w0, w1); + } + st_ev_destroy(w0); st_ev_destroy(w1); + return st_time_us([&](int) { r->launch(a, nullptr); }, iters, nullptr); + }; + auto fetch = [&](void* d, size_t bytes) { + std::vector v(bytes); + st_memcpy(v.data(), d, bytes, hipMemcpyDeviceToHost); + return v; + }; + auto outputs = [&]() { + std::vector o = fetch(d_x, (size_t)(rows * n * 2)); + for (auto* d : { d_p, d_c }) { + const std::vector q = fetch(d, d == d_p ? (size_t)(rows * hc * 4) + : (size_t)(rows * hc * hc * 4)); + o.insert(o.end(), q.begin(), q.end()); + } + return o; + }; + const double hx = (double)rows * (W + n) * 2; + if (!check) + std::printf("mhc at GLM's shape, M=%lld (n 4096, hc 4, 20 rounds), %s, %d launches\n", + (long long)rows, g_cold > 0 ? fmt("cold (%lld MiB, median)", + (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + auto line = [&](const char* what, double us, double bytes, const std::string& same) { + if (check) { + ok(fmt("%s at M=%lld%s", what, (long long)rows, + same.empty() ? " is served" : ": byte-identical to the old dispatch").c_str(), + us >= 0 && same.find("DIFFERS") == std::string::npos, us < 0 ? "not served" : ""); + return; + } + if (us < 0) { std::printf(" %-44s not served\n", what); return; } + std::printf(" %-44s %8.1f us %7.1f GB/s%s\n", what, us, bytes / (us * 1e3), same.c_str()); + }; + auto cmp = [](const std::vector& a, const std::vector& b) { + return a == b ? std::string(" = old") : std::string(" DIFFERS from old"); + }; + + pin("old", nullptr, "0", "0"); + const double us_old = timed(pre, &A_pre); + const std::vector ref = outputs(); + line("mhc_pre, old dispatch", us_old, hx, ""); + struct Pv { const char* what; const char* finish; const char* rows4; const char* pvec; + const char* prows; }; + for (const Pv& v : { Pv{ "mhc_pre, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre, finish: scalar mix, wide read", "scalar", nullptr, nullptr, nullptr }, + Pv{ "mhc_pre, old partials (rows4 from 32)", nullptr, nullptr, "0", nullptr }, + Pv{ "mhc_pre, four-slot partials, 1 row a wave", nullptr, nullptr, "1", "1" }, + Pv{ "mhc_pre, four-slot partials, 2 rows a wave", nullptr, nullptr, "1", "2" }, + Pv{ "mhc_pre, four-slot partials, 4 rows a wave", nullptr, nullptr, "1", "4" } }) { + pin(v.finish, v.rows4, nullptr, v.pvec, v.prows); + st_memset(d_x, 0xff, (size_t)(rows * n * 2)); + const double us = timed(pre, &A_pre); + line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); + } + pin(nullptr, nullptr, nullptr, "0"); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); + const std::vector part_ref = fetch(d_part, (size_t)(rows * total * S * 4)); + for (const Pv& v : { Pv{ "mhc_pre_partial, 8 chunks, old", nullptr, nullptr, "0", nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x1", nullptr, nullptr, "1", "1" }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x2", nullptr, nullptr, "1", "2" }, + Pv{ "mhc_pre_partial, 8 chunks, four-slot x4", nullptr, nullptr, "1", "4" }, + Pv{ "mhc_pre_partial, 8 chunks, rows4 at every M", nullptr, "1", "0", nullptr }, + Pv{ "mhc_pre_partial, 8 chunks, scalar-row", nullptr, "1000000", "0", nullptr } }) { + pin(nullptr, v.rows4, nullptr, v.pvec, v.prows); + st_memset(d_part, 0xff, (size_t)(rows * total * S * 4)); + const double us = timed(part, &A_all); + const bool is_ref = v.pvec && !std::strcmp(v.pvec, "0") && !v.rows4; + line(v.what, us, (double)rows * W * 2, us < 0 || is_ref ? std::string() + : cmp(fetch(d_part, (size_t)(rows * total * S * 4)), part_ref)); + } + pin(nullptr, nullptr, nullptr); + line("mhc_pre_partial, 1 chunk (a TP8 rank's)", timed(part, &A_one), (double)rows * W * 2 / 8, ""); + if (part->launch(&A_all, nullptr) == RAD_OK) st_stream_sync(nullptr); + for (const Pv& v : { Pv{ "mhc_pre_finish, old", "old", nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_finish, rule", nullptr, nullptr, nullptr, nullptr }, + Pv{ "mhc_pre_finish, scalar mix, wide read", "scalar", nullptr, nullptr, nullptr } }) { + pin(v.finish, nullptr, nullptr); + st_memset(d_x, 0xff, (size_t)(rows * n * 2)); + const double us = timed(fin, &A_fin); + line(v.what, us, hx, us < 0 ? "" : cmp(outputs(), ref)); + } + const double post_bytes = (double)rows * (2 * W + n) * 2; + pin(nullptr, nullptr, "0"); + const double us_post_old = timed(post, &A_post); + const std::vector post_ref = fetch(d_out, (size_t)(rows * W * 2)); + line("mhc_post, old", us_post_old, post_bytes, ""); + pin(nullptr, nullptr, nullptr); + st_memset(d_out, 0xff, (size_t)(rows * W * 2)); + const double us_post = timed(post, &A_post); + line("mhc_post, rule", us_post, post_bytes, + us_post < 0 ? "" : cmp(fetch(d_out, (size_t)(rows * W * 2)), post_ref)); + for (int i = 0; i < 5; ++i) { + if (had[i]) setenv(kEnv[i], saved[i].c_str(), 1); + else unsetenv(kEnv[i]); + } +} + +/* router_sigmoid_topk's wave-per-row select against the serial scan (RADIANCE_ROUTER_SELECT=old), + * byte for byte over ids and weights with their pitches filled, so an overrun or a missed slot + * shows. Logits, bias and outputs are pitched, the bias strided. `ties` puts logits on steps of + * 1/2 and the bias on steps of 1/8, so many experts share a rank and the lower-index rule + * decides. `iters` below zero compares only, as a case; otherwise both are timed. */ +static void router_select(const Plugin& pl, int64_t rows, int64_t ne, int64_t k, int norm, + bool ties, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const RadKernelInfo* r = find(pl, "router_sigmoid_topk_f32"); + if (!r) { ok("router_sigmoid_topk_f32 select", false, "row absent"); return; } + if (rows < 1 || rows > 65535 || ne < 1 || ne > 512 || k < 1 || k > 32 || k > ne) { + std::printf("--perfrouter: 1 <= M <= 65535, top_k <= n_expert <= 512, top_k <= 32\n"); + return; + } + const int64_t lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1; + std::vector lg((size_t)(rows * lp)), bv((size_t)(ne * bp)); + for (size_t i = 0; i < lg.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 7u + 13u) % 2001) - 1000; + lg[i] = ties ? (float)(u % 8) * 0.5f : (float)u / 200; + } + for (size_t i = 0; i < bv.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 3u + 101u) % 2001) - 1000; + bv[i] = ties ? (float)(u % 5) * 0.125f : (float)u / 2000; + } + void* d_l = dalloc(lg.size() * 4); + void* d_b = dalloc(bv.size() * 4); + void* d_i = dalloc((size_t)(rows * ip * 4)); + void* d_w = dalloc((size_t)(rows * wp * 4)); + if (!d_l || !d_b || !d_i || !d_w) { ok("router_sigmoid_topk_f32 select", false, "allocation failed"); return; } + st_memcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + std::vector ts = { T(d_l, RAD_F32, { rows, ne }), T(d_b, RAD_F32, { ne }), + T(d_i, RAD_I32, { rows, k }), T(d_w, RAD_F32, { rows, k }) }; + ts[0].stride[0] = lp; ts[1].stride[0] = bp; ts[2].stride[0] = ip; ts[3].stride[0] = wp; + std::vector ps = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), + PI("norm", norm), PF("route_scale", 2.5), PS("dtype", "f32") }; + RadArgs a{}; + a.t = ts.data(); a.n_t = 4; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + + const char* saved = std::getenv("RADIANCE_ROUTER_SELECT"); + const std::string keep = saved ? saved : ""; + auto run = [&](const char* form, std::vector* out, double* us) -> int { + if (form) setenv("RADIANCE_ROUTER_SELECT", form, 1); + else unsetenv("RADIANCE_ROUTER_SELECT"); + st_memset(d_i, 0xa5, (size_t)(rows * ip * 4)); + st_memset(d_w, 0xa5, (size_t)(rows * wp * 4)); + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; + out->resize((size_t)(rows * (ip + wp) * 4)); + st_memcpy(out->data(), d_i, (size_t)(rows * ip * 4), hipMemcpyDeviceToHost); + st_memcpy(out->data() + rows * ip * 4, d_w, (size_t)(rows * wp * 4), hipMemcpyDeviceToHost); + if (!check) *us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr); + return (int)RAD_OK; + }; + std::vector old, got; + double us_old = 0, us_new = 0; + const int orc = run("old", &old, &us_old); + const int nrc = orc == RAD_OK ? run(nullptr, &got, &us_new) : orc; + if (saved) setenv("RADIANCE_ROUTER_SELECT", keep.c_str(), 1); + else unsetenv("RADIANCE_ROUTER_SELECT"); + const bool same = nrc == RAD_OK && got == old; + if (check) { + size_t first = 0; + if (nrc == RAD_OK && !same) while (first < got.size() && got[first] == old[first]) ++first; + ok(fmt("router_sigmoid_topk select at M=%lld n_expert=%lld top_k=%lld norm=%d%s: " + "byte-identical to the serial scan", (long long)rows, (long long)ne, (long long)k, + norm, ties ? ", tied ranks" : "").c_str(), same, + nrc != RAD_OK ? fmt("rc=%d", nrc) : same ? "" : fmt("first byte %zu", first)); + return; + } + if (nrc != RAD_OK) { std::printf("--perfrouter: launch failed (rc %d)\n", nrc); return; } + std::printf("router_sigmoid_topk, M=%lld (n_expert %lld, top %lld, norm %d), %s, %d launches\n", + (long long)rows, (long long)ne, (long long)k, norm, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + std::printf(" %-28s %8.1f us\n", "serial scan (old)", us_old); + std::printf(" %-28s %8.1f us%s\n", "wave per row", us_new, + same ? " = old" : " DIFFERS from old"); +} + +/* ---- GLM's decode fusions of the MoE block (r4d_glm.hip), each against the separate launches it + * replaces, byte for byte over every output buffer including its tail. `iters` below zero compares + * only, as a case; otherwise both are timed, the chain as its launches back to back. */ +static void fuse_line(const char* what, double us_old, double us_new, bool same) { + std::printf(" %-34s %8.1f us\n", fmt("%s, separate", what).c_str(), us_old); + std::printf(" %-34s %8.1f us%s\n", fmt("%s, fused", what).c_str(), us_new, + same ? " = old" : " DIFFERS from old"); +} + +/* router_sigmoid_topk_scatter against router_sigmoid_topk, moe_scatter and the ungated shared + * arm's `fill`, at GLM's shape (288 experts, top 8). `mode` 0 random ranks, 1 tied ranks, 2 every + * other row with fewer finite ranks than top_k (NaN logits): the selection writes expert 0 for the + * empty slots and both forms sort them as written. */ +static void moefuse_router(const Plugin& pl, int64_t rows, int mode, int iters, + bool inverse = false) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "router_sigmoid_topk_scatter_f32"; + const RadKernelInfo* fr = find(pl, what); + const RadKernelInfo* sr = find(pl, "router_sigmoid_topk_f32"); + const RadKernelInfo* sc = find(pl, inverse ? "moe_scatter_inv_i32" : "moe_scatter_i32"); + const RadKernelInfo* fl = find(pl, "fill_bf16"); + if (!fr || !sr || !sc || !fl) { ok(what, false, "a row is absent"); return; } + const int64_t ne = 288, k = 8, slots = rows * k; + if (rows < 1 || slots > 1024) { + std::printf(" router at M=%lld: past the sort's one workgroup (M <= 128); the separate " + "launches serve\n", (long long)rows); + return; + } + std::vector lg((size_t)(rows * ne)), bv((size_t)ne); + for (size_t i = 0; i < lg.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 7u + 13u + (uint32_t)rows) % 2001) - 1000; + lg[i] = mode == 1 ? (float)(u % 8) * 0.5f : (float)u / 200; + } + for (size_t i = 0; i < bv.size(); ++i) { + const int u = (int)(st_mix32((uint32_t)i * 3u + 101u) % 2001) - 1000; + bv[i] = mode == 1 ? (float)(u % 5) * 0.125f : (float)u / 2000; + } + if (mode == 2) + for (int64_t r = 0; r < rows; r += 2) { + for (int64_t e = 0; e < ne; ++e) lg[(size_t)(r * ne + e)] = NAN; + for (int64_t j = 0; j < r % 5; ++j) + lg[(size_t)(r * ne + (int64_t)(st_mix32((uint32_t)(r * 31 + j)) % (uint32_t)ne))] = + 0.25f * (float)j; + } + /* ids, weights, sorted, offsets, counts, gate, inverse: each with a 64-byte tail */ + const int n_out = inverse ? 7 : 6; + const size_t sz[7] = { (size_t)slots * 4 + 64, (size_t)slots * 4 + 64, (size_t)slots * 4 + 64, + (size_t)(ne + 1) * 4 + 64, (size_t)ne * 4 + 64, (size_t)rows * 2 + 64, + (size_t)slots * 4 + 64 }; + void* d_l = dalloc(lg.size() * 4); + void* d_b = dalloc(bv.size() * 4); + void* o[2][7]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) o[f][j] = dalloc(sz[j]); + if (!d_l || !d_b) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_l, lg.data(), lg.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_b, bv.data(), bv.size() * 4, hipMemcpyHostToDevice); + auto opds = [&](int f) { + return std::vector{ + T(d_l, RAD_F32, { rows, ne }), T(d_b, RAD_F32, { ne }), T(o[f][0], RAD_I32, { rows, k }), + T(o[f][1], RAD_F32, { rows, k }), T(o[f][2], RAD_I32, { slots }), + T(o[f][3], RAD_I32, { ne + 1 }), T(o[f][4], RAD_I32, { ne }), + T(o[f][5], RAD_BF16, { rows, 1 }), T(o[f][6], RAD_I32, { slots }) }; + }; + std::vector ch = opds(0), fu = opds(1); + if (!inverse) fu.pop_back(); + std::vector t_sel(ch.begin(), ch.begin() + 4); + std::vector t_sort = { ch[2], ch[4], ch[5], ch[6] }; + if (inverse) t_sort.push_back(ch[8]); + std::vector t_fill = { ch[7] }; + std::vector p_sel = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), PI("norm", 1), + PF("route_scale", 2.5), PS("dtype", "f32") }; + std::vector p_sort = { PI("M", rows), PI("n_expert", ne), PI("top_k", k), + PI("expert_base", 0) }; + std::vector p_fill = { PI("M", rows), PI("n", 1), PS("dtype", "bf16"), PF("value", 1.0) }; + std::vector p_fu = { PI("M", rows), PI("n_expert", ne), PI("n_local", ne), + PI("top_k", k), PI("norm", 1), PF("route_scale", 2.5), + PS("dtype", "f32"), PI("expert_base", 0) }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + return a; + }; + RadArgs a_sel = args(t_sel, p_sel), a_sort = args(t_sort, p_sort), a_fill = args(t_fill, p_fill); + RadArgs a_fu = args(fu, p_fu); + auto chain = [&]() { + int rc = sr->launch(&a_sel, nullptr); + if (rc == RAD_OK) rc = sc->launch(&a_sort, nullptr); + if (rc == RAD_OK) rc = fl->launch(&a_fill, nullptr); + return rc; + }; + auto fused = [&]() { return fr->launch(&a_fu, nullptr); }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 7; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = chain(), nrc = fused(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < n_out && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + static const char* const kOut[7] = { "ids", "weights", "sorted", "offsets", "counts", "gate", + "inverse" }; + if (check) { + ok(fmt("router_sigmoid_topk_scatter at M=%lld%s%s: byte-identical to the selection, the " + "sort and the gate fill", (long long)rows, + mode == 1 ? ", tied ranks" : mode == 2 ? ", NaN rows" : "", + inverse ? ", with the inverse" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: router launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_old = st_time_us([&](int) { chain(); }, iters, nullptr); + const double us_new = st_time_us([&](int) { fused(); }, iters, nullptr); + fuse_line(inverse ? "router + scatter_inv + gate" : "router + scatter + gate", us_old, us_new, + same); +} + +/* moe_scatter_inv and moe_gather_inv against moe_scatter and moe_gather at GLM's shape (288 experts, + * top 8, 4096 wide, f32 routing weights, the ungated shared arm folded in): the sort's three outputs, + * the inverse against the table built from `sorted`, and the gathered rows, byte for byte. Each row + * routes to 8 distinct experts; `slice` sorts only experts [72, 216), dropping the rest. Timed, the + * pairs and the gathers alone. Above 512 slots the old gather builds its table in two prepass + * launches, above 1024 the sort takes three. */ +static void moefuse_gather(const Plugin& pl, int64_t rows, bool slice, int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "moe_gather_inv_bf16"; + const RadKernelInfo* si = find(pl, "moe_scatter_inv_i32"); + const RadKernelInfo* gi = find(pl, what); + const RadKernelInfo* so = find(pl, "moe_scatter_i32"); + const RadKernelInfo* go = find(pl, "moe_gather_bf16"); + if (!si || !gi || !so || !go) { ok(what, false, "a row is absent"); return; } + const int64_t ne = 288, k = 8, n = 4096, slots = rows * k; + const int64_t nl = slice ? 144 : ne, base = slice ? 72 : 0; + std::vector ids((size_t)slots); + for (int64_t r = 0; r < rows; ++r) { + std::vector pool((size_t)ne); + for (int64_t e = 0; e < ne; ++e) pool[(size_t)e] = (int32_t)e; + for (int64_t j = 0; j < k; ++j) { + const int64_t pick = j + (int64_t)(st_mix32((uint32_t)(r * 97 + j)) % (uint32_t)(ne - j)); + std::swap(pool[(size_t)j], pool[(size_t)pick]); + ids[(size_t)(r * k + j)] = pool[(size_t)j]; + } + } + std::vector ye((size_t)(slots * n)), sh((size_t)(rows * n)), sg((size_t)rows, h_to_bf16(1.0f)); + for (size_t i = 0; i < ye.size(); ++i) + ye[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i + 7u) % 2001) - 1000) / 1000); + for (size_t i = 0; i < sh.size(); ++i) + sh[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i + 99u) % 2001) - 1000) / 1000); + std::vector ew((size_t)slots); + for (size_t i = 0; i < ew.size(); ++i) ew[i] = (float)(st_mix32((uint32_t)i + 5u) % 1000) / 2000; + void* d_ids = dalloc(ids.size() * 4); + void* d_ye = dalloc(ye.size() * 2); + void* d_sh = dalloc(sh.size() * 2); + void* d_sg = dalloc(sg.size() * 2); + void* d_ew = dalloc(ew.size() * 4); + /* sorted, offsets, counts, gathered rows, then the inverse: each with a 64-byte tail */ + const size_t sz[5] = { (size_t)slots * 4 + 64, (size_t)(nl + 1) * 4 + 64, (size_t)nl * 4 + 64, + (size_t)(rows * n) * 2 + 64, (size_t)slots * 4 + 64 }; + void* o[2][5]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) o[f][j] = dalloc(sz[j]); + if (!d_ids || !d_ye || !d_sh || !d_sg || !d_ew) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_ids, ids.data(), ids.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_ye, ye.data(), ye.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_sh, sh.data(), sh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_sg, sg.data(), sg.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_ew, ew.data(), ew.size() * 4, hipMemcpyHostToDevice); + std::vector p_s = { PI("M", rows), PI("n_expert", nl), PI("top_k", k), + PI("expert_base", base) }; + std::vector p_g = { PI("M", rows), PI("n", n), PI("top_k", k), PS("dtype", "bf16"), + PS("act", "none") }; + std::vector s_old = { T(d_ids, RAD_I32, { rows, k }), T(o[0][0], RAD_I32, { slots }), + T(o[0][1], RAD_I32, { nl + 1 }), T(o[0][2], RAD_I32, { nl }) }; + std::vector s_new = { s_old[0], T(o[1][0], RAD_I32, { slots }), + T(o[1][1], RAD_I32, { nl + 1 }), T(o[1][2], RAD_I32, { nl }), + T(o[1][4], RAD_I32, { slots }) }; + auto gops = [&](void* table, void* y) { + return std::vector{ T(d_ye, RAD_BF16, { slots, n }), T(d_ew, RAD_F32, { rows, k }), + T(table, RAD_I32, { slots }), T(d_sh, RAD_BF16, { rows, n }), + T(d_sg, RAD_BF16, { rows, 1 }), T(y, RAD_BF16, { rows, n }) }; + }; + std::vector g_old = gops(o[0][0], o[0][3]), g_new = gops(o[1][4], o[1][3]); + auto args = [](std::vector& t, std::vector& p, const RadKernelInfo* r) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + const int64_t need = r->scratch ? r->scratch(&a) : 0; + if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; } + return a; + }; + RadArgs a_so = args(s_old, p_s, so), a_si = args(s_new, p_s, si); + RadArgs a_go = args(g_old, p_g, go), a_gi = args(g_new, p_g, gi); + auto pair_old = [&]() { int rc = so->launch(&a_so, nullptr); return rc == RAD_OK ? go->launch(&a_go, nullptr) : rc; }; + auto pair_new = [&]() { int rc = si->launch(&a_si, nullptr); return rc == RAD_OK ? gi->launch(&a_gi, nullptr) : rc; }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 5; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = pair_old(), nrc = pair_new(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < 4 && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + if (ran) { + /* the inverse is the table the old gather builds from `sorted` */ + std::vector srt((size_t)slots), inv((size_t)slots + 16), want((size_t)slots, -1); + st_memcpy(srt.data(), o[0][0], (size_t)slots * 4, hipMemcpyDeviceToHost); + st_memcpy(inv.data(), o[1][4], ((size_t)slots + 16) * 4, hipMemcpyDeviceToHost); + for (int64_t p = 0; p < slots; ++p) if (srt[(size_t)p] >= 0) want[(size_t)srt[(size_t)p]] = (int32_t)p; + bool tail = true; + for (int i = 0; i < 16; ++i) tail = tail && inv[(size_t)slots + (size_t)i] == (int32_t)0xa5a5a5a5; + if (!tail || !std::equal(want.begin(), want.end(), inv.begin())) { same = false; if (first < 0) first = 4; } + } + static const char* const kOut[5] = { "sorted", "offsets", "counts", "gathered rows", "inverse" }; + if (check) { + ok(fmt("moe_scatter_inv + moe_gather_inv at M=%lld%s: byte-identical to moe_scatter + " + "moe_gather", (long long)rows, slice ? ", a slice" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: gather launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_po = st_time_us([&](int) { pair_old(); }, iters, nullptr); + const double us_pn = st_time_us([&](int) { pair_new(); }, iters, nullptr); + const double us_go = st_time_us([&](int) { go->launch(&a_go, nullptr); }, iters, nullptr); + const double us_gn = st_time_us([&](int) { gi->launch(&a_gi, nullptr); }, iters, nullptr); + fuse_line("scatter + gather", us_po, us_pn, same); + fuse_line("gather alone", us_go, us_gn, same); +} + +/* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 at limit 10, over `rows` rows + * of width `n` (GLM at TP8: 256 for the routed and shared experts, 1536 for the dense layers). + * `mode` 0 values far past the clamp, 1 the clamp edges and all-zero groups, 2 NaN and infinite + * inputs. `with_y` also has the fused op write the bf16 product, compared with the chain's. */ +static void moefuse_swiglu(const Plugin& pl, int64_t rows, int64_t n, int mode, bool with_y, + int iters) { + const bool check = iters < 0; + if (iters == 0) iters = 200; + const char* what = "swiglu_clamped_quant_fp8"; + const RadKernelInfo* fr = find(pl, what); + const RadKernelInfo* sw = find(pl, "swiglu_clamped_bf16"); + const RadKernelInfo* qa = find(pl, "quant_act_fp8"); + if (!fr || !sw || !qa) { ok(what, false, "a row is absent"); return; } + const int64_t nkb = (n + 127) / 128; + std::vector gu((size_t)(rows * 2 * n)); + const uint16_t lim = h_to_bf16(10.0f), past = (uint16_t)(lim + 1); + for (int64_t r = 0; r < rows; ++r) + for (int64_t c = 0; c < 2 * n; ++c) { + const size_t i = (size_t)(r * 2 * n + c); + const uint32_t h = st_mix32((uint32_t)i * 5u + 77u); + uint16_t v = h_to_bf16((float)((int)(h % 2001) - 1000) / 25); + const uint32_t pick = (h >> 16) % 16; + if (mode == 1) { + if (pick == 0) v = lim; + else if (pick == 1) v = past; + else if (pick == 2) v = (uint16_t)(lim | 0x8000u); + else if (pick == 3) v = (uint16_t)(past | 0x8000u); + else if (pick == 4) v = h_to_bf16(-200.0f); + if (r % 3 == 0 && c % n < 128) v = 0; + } else if (mode == 2) { + if (pick == 0) v = 0x7fc0; + else if (pick == 1) v = 0x7f80; + else if (pick == 2) v = 0xff80; + } + gu[i] = v; + } + /* q, scale, product: each with a 64-byte tail */ + const size_t sz[3] = { (size_t)(rows * n) + 64, (size_t)(rows * nkb) * 4 + 64, + (size_t)(rows * n) * 2 + 64 }; + void* d_g = dalloc(gu.size() * 2); + void* o[2][3]; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) o[f][j] = dalloc(sz[j]); + if (!d_g) { ok(what, false, "allocation failed"); return; } + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) + if (!o[f][j]) { ok(what, false, "allocation failed"); return; } + st_memcpy(d_g, gu.data(), gu.size() * 2, hipMemcpyHostToDevice); + std::vector t_sw = { T(d_g, RAD_BF16, { rows, 2 * n }), T(o[0][2], RAD_BF16, { rows, n }) }; + std::vector t_qa = { t_sw[1], T(o[0][0], RAD_F8E4M3, { rows, n }), + T(o[0][1], RAD_F32, { rows, nkb }) }; + std::vector t_fu = { t_sw[0], T(o[1][0], RAD_F8E4M3, { rows, n }), + T(o[1][1], RAD_F32, { rows, nkb }), T(o[1][2], RAD_BF16, { rows, n }) }; + if (!with_y) absent(t_fu[3]); + std::vector p_sw = { PI("M", rows), PI("n", n), PF("limit", 10.0), PS("dtype", "bf16") }; + std::vector p_qa = { PI("M", rows), PI("n", n), PI("group", 128), PS("dtype", "bf16") }; + std::vector p_fu = { PI("M", rows), PI("n", n), PF("limit", 10.0), PI("group", 128), + PS("dtype", "bf16") }; + auto args = [](std::vector& t, std::vector& p) { + RadArgs a{}; + a.t = t.data(); a.n_t = (int)t.size(); a.p = p.data(); a.n_p = (int)p.size(); a.world_size = 1; + return a; + }; + RadArgs a_sw = args(t_sw, p_sw), a_qa = args(t_qa, p_qa), a_fu = args(t_fu, p_fu); + auto chain = [&]() { + int rc = sw->launch(&a_sw, nullptr); + if (rc == RAD_OK) rc = qa->launch(&a_qa, nullptr); + return rc; + }; + auto fused = [&]() { return fr->launch(&a_fu, nullptr); }; + for (int f = 0; f < 2; ++f) for (int j = 0; j < 3; ++j) st_memset(o[f][j], 0xa5, sz[j]); + const int orc = chain(), nrc = fused(); + const bool ran = orc == RAD_OK && nrc == RAD_OK && st_stream_sync(nullptr) == hipSuccess; + bool same = ran; + int first = -1; + for (int j = 0; j < (with_y ? 3 : 2) && ran; ++j) + if (fetch_bytes(o[0][j], sz[j]) != fetch_bytes(o[1][j], sz[j])) { same = false; if (first < 0) first = j; } + if (ran && !with_y && fetch_bytes(o[1][2], sz[2]) != std::vector(sz[2], 0xa5)) { + same = false; if (first < 0) first = 2; + } + static const char* const kOut[3] = { "codes", "scales", "bf16 product" }; + if (check) { + ok(fmt("swiglu_clamped_quant_fp8 at M=%lld n=%lld%s%s: byte-identical to swiglu_clamped " + "and quant_act_fp8", (long long)rows, (long long)n, with_y ? ", with bf16" : "", + mode == 1 ? ", clamp edges" : mode == 2 ? ", NaN and inf" : "").c_str(), same, + !ran ? fmt("rc %d / %d", orc, nrc) : same ? "" : fmt("%s differ", kOut[first])); + return; + } + if (!ran) { std::printf("--perfmoefuse: swiglu launch failed (rc %d / %d)\n", orc, nrc); return; } + const double us_old = st_time_us([&](int) { chain(); }, iters, nullptr); + const double us_new = st_time_us([&](int) { fused(); }, iters, nullptr); + fuse_line(fmt("swiglu + quant %lldx%lld", (long long)rows, (long long)n).c_str(), us_old, us_new, + same); +} + +/* --perfmoefuse: every decode fusion of GLM's MoE block at one M, separate against fused. */ +static void moefuse_perf(const Plugin& pl, int64_t rows, int iters) { + std::printf("GLM MoE decode fusions, M=%lld (288 experts, top 8, TP8 widths), %s, %d launches\n", + (long long)rows, + g_cold > 0 ? fmt("cold (%lld MiB, median)", (long long)(g_cold >> 20)).c_str() + : "warm (back to back, mean)", iters); + moefuse_router(pl, rows, 0, iters); + /* The routed arm's rows (M times top_k) and the shared arm's, both 256 wide at TP8. */ + moefuse_swiglu(pl, rows * 8, 256, 0, false, iters); + moefuse_swiglu(pl, rows, 256, 0, false, iters); + moefuse_router(pl, rows, 0, iters, true); + moefuse_gather(pl, rows, false, iters); +} + +/* gemm_nt_f32 at every tile form (RADIANCE_F32_GEMM_TILE), each compared byte for byte with the + * one-wave-per-output legacy kernel. Rows are pitched and the output keeps a filled pitch, so an + * overrun or a missed tail shows as a byte difference. Timed, every form also prints its time, + * its GB/s on weight + input + output and its TFLOP/s; weights rotate over copies past the + * last-level cache, as in bf16_perf. */ +static void f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { + const RadKernelInfo* r = find(pl, "gemm_nt_f32_bf16"); + if (!r) { ok("gemm_nt_f32_bf16 forms", false, "row absent"); return; } + const int64_t xp = K + 5, yp = N + 3; + const size_t wbytes = (size_t)N * (size_t)K * 4, ybytes = (size_t)M * (size_t)yp * 4; + int copies = 1; + if (timed) { + copies = (int)(((size_t)256 << 20) / wbytes) + 1; + if (copies > 64) copies = 64; + } + void* d_x = dalloc((size_t)M * (size_t)xp * 2); + void* d_w = dalloc(wbytes * (size_t)copies); + void* d_y = dalloc(ybytes); + if (!d_x || !d_w || !d_y) { ok("gemm_nt_f32_bf16 forms", false, "allocation failed"); return; } + { + std::vector x((size_t)M * (size_t)xp); + for (size_t i = 0; i < x.size(); ++i) + x[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 2001) - 1000) / 1000); + st_memcpy(d_x, x.data(), x.size() * 2, hipMemcpyHostToDevice); + std::vector w((size_t)N * (size_t)K); + for (size_t i = 0; i < w.size(); ++i) + w[i] = (float)((int)(st_mix32((uint32_t)i + 0x51ed27u) % 2001) - 1000) / 8000; + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wbytes, w.data(), wbytes, hipMemcpyHostToDevice); + } + std::vector ts = { + T(d_x, RAD_BF16, { M, K }), T(d_w, RAD_F32, { N, K }), T(d_y, RAD_F32, { M, N }), + }; + ts[0].stride[0] = xp; ts[2].stride[0] = yp; + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = 3; a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + + const char* saved = std::getenv("RADIANCE_F32_GEMM_TILE"); + const std::string keep = saved ? saved : ""; + auto run = [&](const char* form, std::vector* out) -> int { + if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); + std::vector fill(ybytes, 0xa5); + st_memcpy(d_y, fill.data(), ybytes, hipMemcpyHostToDevice); + ts[1].data = d_w; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : RAD_E_DEVICE; + out->resize(ybytes); + st_memcpy(out->data(), d_y, ybytes, hipMemcpyDeviceToHost); + return (int)RAD_OK; + }; + static const char* kForms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", "8x4", + "16x2", "16x4", nullptr }; + std::vector legacy, got; + const int lrc = run("legacy", &legacy); + ok(fmt("gemm_nt_f32 legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, + (long long)K).c_str(), lrc == RAD_OK); + if (lrc == RAD_OK) { + for (const char* const* f = kForms;; ++f) { + const char* form = *f; + const int rc = run(form, &got); + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) + while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_nt_f32 form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", + form ? form : "default", (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (!form) break; + } + } + if (timed && lrc == RAD_OK) { + const double bytes = (double)wbytes + (double)M * K * 2 + (double)M * N * 4; + const double flop = 2.0 * (double)M * (double)N * (double)K; + std::printf("\ngemm_nt_f32 N=%lld K=%lld M=%lld %.2f MiB weight, %d copies, %d iters\n", + (long long)N, (long long)K, (long long)M, (double)wbytes / (1 << 20), copies, + iters); + static const char* kTimed[] = { "legacy", "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", "4x4", + "8x4", "16x2", "16x4", nullptr }; + for (const char* const* f = kTimed;; ++f) { + const char* form = *f; + if (form) setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); + const double us = st_time_us([&](int i) { + ts[1].data = (uint8_t*)d_w + (size_t)(i % copies) * wbytes; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-8s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", form ? form : "default", + us, bytes / (us * 1e3), flop / (us * 1e6)); + if (!form) break; + } + ts[1].data = d_w; + } + if (saved) setenv("RADIANCE_F32_GEMM_TILE", keep.c_str(), 1); + else unsetenv("RADIANCE_F32_GEMM_TILE"); +} + +/* gemm_fp8a8_f32scale's dense forms (RADIANCE_FP8F32_FORM: decode at several R x S, rows) each + * compared byte for byte with the legacy 16x64 tile; the output keeps a filled pitch, so an + * overrun or a missed row shows. Timed, every form also prints its time and GB/s on the weight and its scale plane, the + * weight rotating over copies past the last-level cache. */ +static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int iters, bool timed) { + const RadKernelInfo* r = find(pl, "gemm_fp8a8_f32scale"); + if (!r) { ok("gemm_fp8a8_f32scale forms", false, "row absent"); return; } + const int64_t sk = K / 128, yp = N + 8; + const size_t wb = (size_t)(N * K), sb = (size_t)((N / 128) * sk * 4), yb = (size_t)(M * yp * 2); + int copies = 1; + if (timed) { + copies = (int)(((size_t)256 << 20) / wb) + 1; + if (copies > 64) copies = 64; + } + void* d_a = dalloc((size_t)(M * K)); + void* d_as = dalloc((size_t)(M * sk * 4)); + void* d_w = dalloc(wb * (size_t)copies); + void* d_s = dalloc(sb); + void* d_y = dalloc(yb); + if (!d_a || !d_as || !d_w || !d_s || !d_y) { ok("gemm_fp8a8_f32scale forms", false, "allocation failed"); return; } + { + std::vector a((size_t)(M * K)), w(wb); + for (size_t i = 0; i < a.size(); ++i) + a[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i * 7u + 3u) % 2001) - 1000) / 250); + for (size_t i = 0; i < w.size(); ++i) + w[i] = rad_f32_to_fp8e4m3((float)((int)(st_mix32((uint32_t)i + 0x9e37u) % 2001) - 1000) / 500); + st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); + std::vector as((size_t)(M * sk)), s(sb / 4); + for (size_t i = 0; i < as.size(); ++i) as[i] = 0.001f + (float)(st_mix32((uint32_t)i + 5u) % 97) * 1e-4f; + for (size_t i = 0; i < s.size(); ++i) s[i] = 0.002f + (float)(st_mix32((uint32_t)i + 11u) % 89) * 1e-4f; + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_s, s.data(), sb, hipMemcpyHostToDevice); + } + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, sk }), T(d_w, RAD_F8E4M3, { N, K }), + T(d_s, RAD_F32, { N / 128, sk }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(nullptr, RAD_U8, { 1 }), + }; + ts[4].stride[0] = yp; + absent(ts[5]); absent(ts[6]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8f32") }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1; + const char* saved = std::getenv("RADIANCE_FP8F32_FORM"); + const std::string keep = saved ? saved : ""; + auto set = [](const char* form) { + if (form) setenv("RADIANCE_FP8F32_FORM", form, 1); + else unsetenv("RADIANCE_FP8F32_FORM"); + }; + auto run = [&](const char* form, std::vector* out) -> int { + set(form); + std::vector fill(yb, 0xa5); + st_memcpy(d_y, fill.data(), yb, hipMemcpyHostToDevice); + ts[2].data = d_w; + const int rc = r->launch(&a, nullptr); + if (rc != RAD_OK) return rc; + if (st_stream_sync(nullptr) != hipSuccess) return (int)RAD_E_DEVICE; + out->resize(yb); + st_memcpy(out->data(), d_y, yb, hipMemcpyDeviceToHost); + return (int)RAD_OK; + }; + std::vector legacy, got; + const int lrc = run("legacy", &legacy); + ok(fmt("gemm_fp8a8_f32scale legacy form at M=%lld N=%lld K=%lld", (long long)M, (long long)N, + (long long)K).c_str(), lrc == RAD_OK); + static const char* kForms[] = { "decode", "decode1x16", "decode2x16", "decode3x8", + "decode1x8x2", "decode1x8x4", "decode2x8x2", "decode3x8x2", + "decode2x4x4", "rows1", "rows4", nullptr }; + if (lrc == RAD_OK) { + for (const char* const* f = kForms;; ++f) { + const int rc = run(*f, &got); + const bool same = rc == RAD_OK && got == legacy; + size_t first = 0; + if (rc == RAD_OK && !same) while (first < got.size() && got[first] == legacy[first]) ++first; + ok(fmt("gemm_fp8a8_f32scale form %s at M=%lld N=%lld K=%lld: byte-identical to legacy", + *f ? *f : "default", (long long)M, (long long)N, (long long)K).c_str(), + same, rc != RAD_OK ? fmt("rc=%d", rc) : same ? "" : fmt("first byte %zu", first)); + if (!*f) break; + } + } + if (timed && lrc == RAD_OK) { + const double bytes = (double)(wb + sb), flop = 2.0 * (double)M * (double)N * (double)K; + std::printf("\ngemm_fp8a8_f32scale N=%lld K=%lld M=%lld %.2f MiB weight + scales, %d copies, " + "%d iters\n", (long long)N, (long long)K, (long long)M, bytes / (1 << 20), copies, iters); + static const char* kTimed[] = { "legacy", "decode1x8", "decode1x16", "decode3x8", + "decode1x8x2", "decode1x16x2", "decode1x4x4", + "decode1x8x4", "decode2x8x2", "decode2x4x2", + "decode2x4x4", "decode3x8x2", "decode3x4x2", "rows1", + "rows2", nullptr }; + for (const char* const* f = kTimed;; ++f) { + set(*f); + const double us = st_time_us([&](int i) { + ts[2].data = (uint8_t*)d_w + (size_t)(i % copies) * wb; + r->launch(&a, nullptr); + }, iters, nullptr); + std::printf(" %-11s %9.1f us %7.1f GB/s %6.2f TFLOP/s\n", *f ? *f : "default", us, + bytes / (us * 1e3), flop / (us * 1e6)); + if (!*f) break; + } + ts[2].data = d_w; + } + if (saved) setenv("RADIANCE_FP8F32_FORM", keep.c_str(), 1); + else unsetenv("RADIANCE_FP8F32_FORM"); +} + +/* The block-quantised trunk GEMMs GLM's checkpoints resolve to, at one shape: E4M3 with F32 + * 128x128 block scales (gemm_fp8a8_f32scale, the MLA and dense-MLP projections) and OCP-MXFP4 + * (the shared experts' rows: skinny, decode split and tiled). GB/s is on the weight and its scale + * plane; weights rotate over copies past the last-level cache. Operands hold constants. */ +static void q_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters) { + if (N % 16 || K % 64 || M < 1) { + std::printf("--perfq: N a multiple of 16, K of 64, M >= 1\n"); + return; + } + const int64_t sk = (K + 127) / 128; + void* d_a = dalloc((size_t)(M * K)); + void* d_as = dalloc((size_t)(M * sk * 4)); + void* d_y = dalloc((size_t)(M * N * 2)); + if (!d_a || !d_as || !d_y) { std::printf("--perfq: hipMalloc failed\n"); return; } + { + std::vector a((size_t)(M * K), 0x38); + st_memcpy(d_a, a.data(), a.size(), hipMemcpyHostToDevice); + std::vector as((size_t)(M * sk), 1.0f / 448); + st_memcpy(d_as, as.data(), as.size() * 4, hipMemcpyHostToDevice); + } + auto copies_for = [](size_t bytes) { + int c = (int)(((size_t)256 << 20) / bytes) + 1; + return c > 64 ? 64 : c; + }; + std::printf("\nquantised trunk GEMMs N=%lld K=%lld M=%lld %d iters\n", (long long)N, + (long long)K, (long long)M, iters); + if (N % 128 == 0 && K % 128 == 0) fp8f32_forms(pl, M, N, K, iters, true); + { + const size_t wb = (size_t)(N * K / 2), sb = (size_t)((K / 32) * N); + const int copies = copies_for(wb); + void* d_w = dalloc(wb * (size_t)copies); + void* d_s = dalloc(sb); + void* d_r = dalloc((size_t)N); + if (!d_w || !d_s || !d_r) { std::printf("--perfq: hipMalloc failed\n"); return; } + std::vector w(wb, 0x22), s(sb, 127), r((size_t)N, 127); + for (int c = 0; c < copies; ++c) + st_memcpy((uint8_t*)d_w + (size_t)c * wb, w.data(), wb, hipMemcpyHostToDevice); + st_memcpy(d_s, s.data(), sb, hipMemcpyHostToDevice); + st_memcpy(d_r, r.data(), (size_t)N, hipMemcpyHostToDevice); + std::vector ts = { + T(d_a, RAD_F8E4M3, { M, K }), T(d_as, RAD_F32, { M, sk }), T(d_w, RAD_U8, { (int64_t)wb }), + T(d_s, RAD_U8, { (int64_t)sb }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), + T(d_r, RAD_U8, { N }), + }; + absent(ts[5]); + std::vector ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "mxfp4a8") }; + std::printf(" OCP-MXFP4: %.2f MiB, %d copies\n", (double)(wb + sb) / (1 << 20), copies); + for (const char* row : { "gemm_mxfp4a8_nt_m64", "gemm_mxfp4a8_decode", "gemm_mxfp4a8_tiled" }) + perf_row(pl, row, ts, ps, d_w, wb, copies, (double)(wb + sb), iters); + } +} + /* The bf16 skinny GEMM at one shape, every variant, side by side, with the working set rotated * past the last-level cache (rad-tune's absolute numbers vary too much between runs to choose a * default from). @@ -14360,7 +17900,7 @@ static void sample_argmax_case(const Plugin& pl) { * a page id of -1 inside the scored range is never selected, whatever its score; * two runs give byte-identical tables (atomic placement would not). */ -static void qsa_select_case(const Plugin& pl) { +static void qsa_select_case(const Plugin& pl, int signed_scores = 0) { const char* what = "qsa_select vs a host sort, with ties, a tail and a dead page"; const RadKernelInfo* r = find(pl, "qsa_select_i32"); if (!r) { ok(what, false, "row absent"); return; } @@ -14379,6 +17919,7 @@ static void qsa_select_case(const Plugin& pl) { if (b < live) { /* A coarse grid: 40 values over hundreds of blocks puts many on the threshold. */ sc[i] = (float)((b * 17 + m * 7) % 40) * 0.25f; + if (signed_scores) sc[i] -= signed_scores == 1 ? 5.0f : 20.0f; bt[i] = (int32_t)((b * 31 + m * 11) % pages); /* A dead page with a winning score, inside the scored range. */ if (b == live / 3) { sc[i] = 1e6f; bt[i] = -1; } @@ -14447,6 +17988,7 @@ static void qsa_select_case(const Plugin& pl) { }; std::vector ps = { PI("M", M), PI("blocks", nb), PI("topk", topk), PI("ratio", ratio), PI("seqs", M) }; + if (signed_scores) ps.push_back(PI("signed", 1)); RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -14667,8 +18209,9 @@ static void qsa_select_wide_case(const Plugin& pl) { static const char* const kDist[] = { "continuous", "coarse, heavy ties", "one first-digit bin, in LDS", "one first-digit bin, past LDS", - "fine ties at the threshold" }; - for (int dist = 0; dist < 5; ++dist) { + "fine ties at the threshold", "signed, heavy ties", + "negative, heavy ties" }; + for (int dist = 0; dist < 7; ++dist) { std::vector sc((size_t)(M * nb)); for (auto& v : sc) { const uint64_t u = rnd(); @@ -14681,6 +18224,8 @@ static void qsa_select_wide_case(const Plugin& pl) { case 2: v = (u % 8 == 0) ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break; case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break; + case 5: v = (float)(u % 23)*0.25f-3.0f; break; + case 6: v = -(float)(u % 23)*0.25f-1.0f; break; /* ~5000 distinct scores, a few times each: the sampled list is short and the * threshold is a tie. */ default: v = (float)(u % 4999) * 0.01f; break; @@ -14707,6 +18252,7 @@ static void qsa_select_wide_case(const Plugin& pl) { T(d_se, RAD_I32, { M, topk + 1 }), T(d_ns, RAD_I32, { M }), T(d_su, RAD_I32, { M }) }; std::vector ps = { PI("M", M), PI("blocks", nb), PI("topk", topk), PI("ratio", ratio), PI("seqs", S) }; + if (dist >= 5) ps.push_back(PI("signed", 1)); RadArgs a; std::memset(&a, 0, sizeof(a)); a.t = ts.data(); a.n_t = (int)ts.size(); @@ -16578,23 +20124,6 @@ static void ar_pattern_worker(ArPattern* t) { st_free(out); } -/* An environment variable set (or, with a null value, cleared) for one scope and restored after - * it: the eight-rank two-shot reads its settings at every init. */ -struct ScopedEnv { - const char* name; - bool had; - std::string kept; - ScopedEnv(const char* n, const char* v) : name(n) { - const char* was = std::getenv(n); - had = was != nullptr; - if (was) kept = was; - if (v) setenv(n, v, 1); else unsetenv(n); - } - ~ScopedEnv() { if (had) setenv(name, kept.c_str(), 1); else unsetenv(name); } - ScopedEnv(const ScopedEnv&) = delete; - ScopedEnv& operator=(const ScopedEnv&) = delete; -}; - struct ArPatternRun { const char* dtype; std::vector sizes; int oop; std::vector pieces = {}; /* per size, as ArPattern::pieces */ @@ -18513,6 +22042,7 @@ static void device_phase(const Plugin& pl) { /* --- the paged cache's write side --- */ kv_store_case(pl, "kv_store_bf16", "bf16"); + kv_store_case(pl, "kv_store_bf16", "bf16", true); kv_store_case(pl, "kv_store_fp8", "fp8_e4m3"); kv_store_v4_case(pl); kv_store_v4_case(pl, true); @@ -20073,6 +23603,8 @@ static void device_phase(const Plugin& pl) { if (sel("qsa_select_i32")) { if (!g_case) std::printf("\nthe QSA selection, against a host sort\n"); qsa_select_case(pl); + qsa_select_case(pl, 1); + qsa_select_case(pl, 2); qsa_select_prefill_case(pl); qsa_select_wide_case(pl); qsa_select_split_one(pl, "qsa_select split across chunks vs the same launch unsplit", @@ -20243,6 +23775,61 @@ static void device_phase(const Plugin& pl) { } } + if (sel("glm_index_layout")) glm_index_layout_check(pl); + if (sel("fp8_f32scale")) { + for (int64_t m : { 1, 17, 65 }) { + fp8_f32scale_check(pl, false, m); + fp8_f32scale_check(pl, true, m); + fp8_f32scale_check(pl, true, m, true); + } + fp8_f32scale_check(pl, false, 130); + for (int64_t n : { 1536, 512, 2048, 4096, 3072 }) + for (int64_t m : { 1, 6, 48, 128, 2048 }) { + const int64_t k = n == 2048 ? 1536 : n == 4096 ? 2048 : 4096; + fp8f32_forms(pl, m, n, k, 0, false); + } + for (int64_t m : { 1, 6, 48, 128, 2048 }) fp8f32_forms(pl, m, 4096, 1536, 0, false); + fp8f32_forms(pl, 37, 256, 1536, 0, false); + fp8f32_forms(pl, 129, 128, 384, 0, false); + fp8_f32scale_check(pl, true, 4, false, true); + fp8_f32scale_check(pl, true, 4, true, true); + fp8_f32scale_check(pl, true, 1, false, true, 288); + fp8_f32scale_check(pl, true, 4, true, true, 288); + fp8_f32scale_check(pl, true, 65, false); + fp8_f32scale_check(pl, true, 65, true); + // The rule takes the expert-major form; pinned, the row tiles stay covered, and every + // stage and column-tile count meets several column tiles, a K of one stage and of + // several, and runs past sixteen rows. + const char* const pins[3] = { "RADIANCE_FP8F32_DECODE_EXPERTS", + "RADIANCE_FP8F32_EXPERTS_STAGE_K", + "RADIANCE_FP8F32_EXPERTS_COLTILES" }; + std::string kept[3]; + bool given[3]; + for (int i = 0; i < 3; ++i) { + const char* v = std::getenv(pins[i]); + given[i] = v; + if (v) kept[i] = v; + } + setenv(pins[0], "0", 1); + fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 65, false); + setenv(pins[0], "1", 1); + for (const char* stage : { "128", "256" }) + for (const char* tiles : { "1", "4" }) { + setenv(pins[1], stage, 1); + setenv(pins[2], tiles, 1); + fp8_f32scale_check(pl, true, 17, true, true, 6, 512, 512); + fp8_f32scale_check(pl, true, 4, false, true, 288, 512, 384); + fp8_f32scale_check(pl, true, 65, false); + } + for (int i = 0; i < 3; ++i) { + if (given[i]) + setenv(pins[i], kept[i].c_str(), 1); + else + unsetenv(pins[i]); + } + } + if (sel("moe_gemm_w4a8_mod4")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM over four classes, against its " "two-class form and a host decode\n"); @@ -20289,6 +23876,344 @@ static void device_phase(const Plugin& pl) { moe_down_dec_case(pl, kMoeDnShapes[1], "fp8a8", { 40, 96 }); } + for (const char* nm : { "mhc_pre_bf16", "mhc_post_bf16", "mhc_contract_bf16" }) + if (sel(nm)) { + mhc_check(pl, nm, 1, 31, 2); + mhc_check(pl, nm, 7, 4096, 4); + if (!std::strcmp(nm, "mhc_pre_bf16")) { + mhc_check(pl, nm, 1, 4096, 4); + mhc_check(pl, nm, 4, 4096, 4); + mhc_check(pl, nm, 33, 4096, 4); + mhc_check(pl, nm, 65, 4096, 4); + } + mhc_check(pl, nm, 33, 129, 8); + } + if (sel("mhc_pre_bf16") || sel("mhc_post_bf16")) { + /* Every finish and partial form and the vector mhc_post against the old dispatch, at the + * decode, verify and prefill row counts and on 16-byte rows, the vector paths' case. */ + for (int64_t rows : { 1, 6, 48, 128, 2048 }) mhcpre_perf(pl, rows, -1); + } + if (sel("mhc_pre_partial_bf16") || sel("mhc_pre_finish_bf16")) { + for (int world : { 2, 4, 8 }) + for (int64_t rows : { 1, 4, 31, 32, 33, 65, 130 }) + mhc_split_check(pl, rows, world, nullptr, nullptr); + for (const char* env : { "RADIANCE_MHC_PREFILL_COEFF4", "RADIANCE_MHC_PREFILL_ROWS4", + "RADIANCE_MHC_PREFILL_WARP" }) + for (int64_t rows : { 33, 130 }) mhc_split_check(pl, rows, 8, env, "0"); + } + if (sel("swiglu_clamped_bf16")) { + for (int64_t rows : { 1, 7, 33 }) + for (int64_t n : { 31, 259, 4096 }) mhc_check(pl, "swiglu_clamped_bf16", rows, n, 0); + } + if (sel("router_sigmoid_topk_f32")) { + for (int64_t rows : { 1, 7, 33 }) + for (int64_t ne : { 32, 288, 512 }) + for (int norm : { 0, 1 }) mhc_check(pl, "router_sigmoid_topk_f32", rows, ne, norm); + for (int64_t rows : { 1, 6, 20, 48, 256 }) + for (bool ties : { false, true }) router_select(pl, rows, 288, 8, 1, ties, -1); + for (int64_t ne : { 8, 32, 300, 512 }) + for (int64_t k : { (int64_t)1, (int64_t)8, ne < 32 ? ne : 32 }) + router_select(pl, 20, ne, k, 0, true, -1); + } + if (sel("swiglu_clamped_quant_fp8")) { + for (int64_t rows : { 1, 8, 48, 384 }) + for (int mode : { 0, 1, 2 }) moefuse_swiglu(pl, rows, 256, mode, false, -1); + for (int64_t n : { 4, 132, 1536 }) moefuse_swiglu(pl, 7, n, 1, true, -1); + moefuse_swiglu(pl, 6, 256, 2, true, -1); + } + if (sel("router_sigmoid_topk_scatter_f32")) { + for (int64_t rows : { 1, 6, 8, 24, 33, 48, 128 }) + for (int mode : { 0, 1, 2 }) moefuse_router(pl, rows, mode, -1); + for (int64_t rows : { 1, 48, 128 }) moefuse_router(pl, rows, 2, -1, true); + } + if (sel("moe_scatter_inv_i32") || sel("moe_gather_inv_bf16")) { + /* 512 slots is the old gather's self-scan bound, 1024 the sort's one workgroup. */ + for (int64_t rows : { 1, 6, 48, 64, 65, 128, 129, 256 }) + for (bool slice : { false, true }) moefuse_gather(pl, rows, slice, -1); + } + if (sel("dsa_pool_fp8")) { + for (int64_t rows : { 1, 7, 33, 2048 }) + for (int pattern : { 0, 1, 2, 3 }) mhc_check(pl, "dsa_pool_fp8", rows, 128, pattern); + for (int64_t rows : { 1, 7, 33, 2048 }) + for (int pattern : { 1, 2 }) mhc_check(pl, "dsa_pool_fp8", rows, 128, pattern, true); + } + if (sel("dsa_query_fp8")) { + for (int64_t rows : { 1, 32, 64, 128, 1056 }) + for (int pattern : { 0, 1, 2, 3 }) mhc_check(pl, "dsa_query_fp8", rows, 128, pattern); + } + if (sel("gemm_nt_f32_bf16")) { + for (int64_t rows : { 1, 2, 4, 33 }) + for (int64_t cols : { 32, 288 }) mhc_check(pl, "gemm_nt_f32_bf16", rows, cols, 4096); + mhc_check(pl, "gemm_nt_f32_bf16", 7, 31, 129); + for (int64_t rows : { 64, 130 }) + for (int64_t cols : { 36, 288 }) mhc_check(pl, "gemm_nt_f32_bf16", rows, cols, 4096); + for (int64_t rows : { 1, 2, 3, 8, 33, 64, 130 }) + for (int64_t cols : { 4, 32, 36, 288 }) f32_forms(pl, rows, cols, 4096, 0, false); + f32_forms(pl, 7, 31, 129, 0, false); + f32_forms(pl, 70, 13, 130, 0, false); + } + if (sel("dsa_score_fp8")) { + dsa_score_check(pl, 1, 17); + dsa_score_check(pl, 7, 257); + dsa_score_check(pl, 33, 17); + dsa_score_check(pl, 1, 4096); + dsa_score_check(pl, 4, 32768); + dsa_score_check(pl, 1, 17, true); + dsa_score_check(pl, 4, 257, true); + dsa_score_check(pl, 4, 32768, true); + } + if (sel("mla_attn_bf16")) { + mla_check(pl, 1, 1, 3); + mla_check(pl, 7, 16, 17); + mla_check(pl, 33, 16, 17); + mla_check(pl, 1, 16, 513); + mla_check(pl, 2, 16, 513); + mla_check(pl, 4, 16, 513); + mla_check(pl, 1, 64, 17); + mla_check(pl, 7, 8, 17); + mla_check(pl, 4, 8, 513); + mla_check(pl, 33, 8, 17); + for (int requests : { 1, 2, 4 }) + for (int64_t heads : { 8, 16 }) + mla_check(pl, requests, heads, 513, "mla_attn_bf16", MlaFill::full); + mla_check(pl, 7, 8, 65, "mla_attn_bf16", MlaFill::topk, nullptr, 0, 16); + } + if (sel("mla_project_bf16")) { + for (const char* mode : { "absorb", "expand" }) { + for (int64_t rows : { 1, 2, 4, 33 }) + for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode); + mla_project_check(pl, 1, 1, mode); + mla_project_check(pl, 1, 64, mode); + for (int64_t rows : { 1, 4, 33 }) + for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true); + } + /* Every row form against the one-row kernels, byte for byte, with tails at 3, 33 and 130. */ + for (int64_t rows : { 1, 3, 6, 33, 130 }) project_forms(pl, rows, -1); + } + if (sel("mla_attn_matrix_bf16")) { + mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 1, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 2, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 16, 513, "mla_attn_matrix_bf16"); + mla_check(pl, 1, 64, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 4, 17, "mla_attn_matrix_bf16"); + mla_check(pl, 4, 12, 17, "mla_attn_matrix_bf16"); + for (int requests : { 1, 2, 4 }) + for (int64_t heads : { 8, 16 }) + mla_check(pl, requests, heads, 513, "mla_attn_matrix_bf16", MlaFill::full, + heads == 8 ? "mla_attn_bf16" : nullptr); + /* Eight heads pair two requests a tile: odd counts leave a half-empty last tile, ragged and + * full tables never share a key between the pair, prefill tables mostly do. */ + for (int requests : { 1, 2, 4, 7, 33 }) + for (int64_t blocks : { 17, 513 }) + mla_check(pl, requests, 8, blocks, "mla_attn_matrix_bf16", MlaFill::ragged, + "mla_attn_bf16"); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::full, "mla_attn_bf16"); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::full, "mla_attn_bf16"); + mla_check(pl, 25, 40, 17, "mla_attn_matrix_bf16", MlaFill::ragged, "mla_attn_bf16"); + for (int requests : { 2, 7, 33 }) + for (int64_t blocks : { 17, 513 }) + mla_check(pl, requests, 8, blocks, "mla_attn_matrix_bf16", MlaFill::prefill, + "mla_attn_bf16"); + for (int64_t heads : { 8, 16 }) + mla_check(pl, 128, heads, 513, "mla_attn_matrix_bf16", MlaFill::prefill, + "mla_attn_bf16"); + /* Past the DSA budget every row selects its own blocks: neighbours share most of them, at + * table positions a single exchange shifts. */ + for (int64_t swaps : { 0, 4, 16, 64 }) + mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, + swaps); + mla_check(pl, 33, 8, 513, "mla_attn_matrix_bf16", MlaFill::topk, "mla_attn_bf16", 0, 16); + mla_check(pl, 4, 16, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 4); + { /* The positional pairing, kept for comparison; tables wider than the union's lists + * (kUnionBlocks, 520) take it too. */ + ScopedEnv positional("RADIANCE_MLA_PAIR", "pos"); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr); + mla_check(pl, 7, 8, 65, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); + } + mla_check(pl, 4, 8, 600, "mla_attn_matrix_bf16", MlaFill::topk, nullptr, 0, 16); + /* The element-wise key load, the fallback for a cache the vectors cannot read. */ + mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); + mla_check(pl, 4, 16, 513, "mla_attn_matrix_bf16", MlaFill::full, nullptr, 1); + mla_check(pl, 33, 8, 17, "mla_attn_matrix_bf16", MlaFill::ragged, nullptr, 1); + mla_check(pl, 7, 8, 513, "mla_attn_matrix_bf16", MlaFill::prefill, nullptr, 1); + } + if (sel("kda_update_k128_v128_bf16")) { + for (const char* mode : { "prefill", "verify" }) + for (int accepted : { 1, 2, 3 }) { + kda_check(pl, mode, false, accepted); + kda_check(pl, mode, true, accepted); + kda_check(pl, mode, false, accepted, true); + kda_check(pl, mode, true, accepted, true); + } + /* Every form against the one-row shuffle-sum kernel, byte for byte, in all four modes. */ + for (int64_t M : { 1, 7, 48, 300 }) kda_forms(pl, M, -1); + } + if (sel("moe_gemm_mxfp4a8")) { + for (int m : { 1, 17, 65, 257 }) + for (int parts : { 1, 2 }) + for (bool pooled : { false, true }) + for (const char* order : { "token", "sorted" }) + mx_experts_check(pl, m, parts, pooled, order); + for (int shape : { 1, 2, 3, 4 }) + for (int m : { 1, 4, 17 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, m == 1, m == 17 ? "sorted" : "token", + shape); + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, "sorted", shape); + // Exercise automatic GLM prefill selection with the real expert count/top-k. + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, 8); + mx_experts_check(pl, 1, 1, false, "token", 0, true); + // The rule takes the expert-major form at decode (at GLM's TP8 slices also above). Pinned, + // the row groups and the TP8 prefill form stay covered, and every expert-major stage and + // column-tile count meets narrow, parted and wide experts and runs of a hundred rows. + // Both weight decodes (RADIANCE_MXFP4_LUT) meet every form; dropped slots inside the runs + // and runs under 16 rows (288 experts) reach the TP8 prefill form at 65 and 257 tokens, + // with and without its stage prefetch (RADIANCE_MXFP4_PREFILL_PIPE). + constexpr int kPins = 10; + const char* const pins[kPins] = { + "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_EXPERTS_STAGE_K", + "RADIANCE_MXFP4_EXPERTS_COLTILES", "RADIANCE_MXFP4_LUT", + "RADIANCE_MXFP4_ALIGNED_JOBS", "RADIANCE_MXFP4_PREFILL_N32", + "RADIANCE_MXFP4_PREFILL_M32", "RADIANCE_MXFP4_PREFILL_N64", + "RADIANCE_MXFP4_PREFILL_CACHE_ROWS", "RADIANCE_MXFP4_PREFILL_PIPE" + }; + std::string kept[kPins]; + bool given[kPins]; + for (int i = 0; i < kPins; ++i) { + const char* v = std::getenv(pins[i]); + given[i] = v; + if (v) kept[i] = v; + } + // P64 is the rule at GLM's TP8 slices from 769 rows; off here, so the forms above stay the + // ones these cases name, and pinned or by its rule further down. + constexpr int kP64 = 12; + const char* const p64[kP64] = { "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + std::string kept64[kP64]; + bool given64[kP64]; + for (int i = 0; i < kP64; ++i) { + const char* v = std::getenv(p64[i]); + given64[i] = v; + if (v) kept64[i] = v; + } + for (int i = 1; i < kP64; ++i) unsetenv(p64[i]); + setenv(p64[0], "0", 1); + for (const char* lut : { "0", "1" }) { + setenv(pins[3], lut, 1); + setenv(pins[0], "0", 1); + for (int shape : { 1, 2, 3, 4 }) + mx_experts_check(pl, 17, shape % 2 ? 2 : 1, false, "sorted", shape); + mx_experts_check(pl, 1, 1, false, "token", 0, true); + for (const char* pipe : { "0", "1" }) { + setenv(pins[9], pipe, 1); + for (int shape : { 3, 4 }) { + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, "sorted", shape, false, 288, + 8); + for (int m : { 65, 257 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, + true); + } + // The TP8 prefill form outside GLM's slices: E8M0 codes 0 and 255, narrower and + // shorter odd experts, dropped slots. + for (int i = 4; i < 9; ++i) setenv(pins[i], "1", 1); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + for (int i = 4; i < 9; ++i) unsetenv(pins[i]); + } + unsetenv(pins[9]); + setenv(pins[0], "1", 1); + for (const char* stage : { "128", "256" }) + for (const char* tiles : { "1", "4" }) { + setenv(pins[1], stage, 1); + setenv(pins[2], tiles, 1); + mx_experts_check(pl, 17, 1, false, "sorted", 2); + mx_experts_check(pl, 4, 2, true, "token", 3); + mx_experts_check(pl, 17, 2, false, "token"); + mx_experts_check(pl, 257, 2, true, "sorted"); + mx_experts_check(pl, 65, 1, false, "sorted", 4, false, 288, 8, true); + } + unsetenv(pins[1]); + unsetenv(pins[2]); + } + // The P64 form pinned below its row bounds: every BM x BN x stage at GLM's TP8 slices over + // 288 experts and 65 tokens (runs of about two rows, dropped slots), column tiles 1 and 4 + // with and without the LDS output at 257 tokens, and outside GLM's slices E8M0 codes 0 and + // 255 with narrower and shorter odd experts; then by its rule at 1024, 2048 and 4096 tokens + // (gate_up BM32 BN64 K256, BM64 BN64 K256 and BM64 BN128 K128 with the LDS output, down BM32 + // BN64 K128 x4 and BM64 BN128 K128 x4 with the LDS output). It always takes the table decode. + auto pin = [&](int bm, int bn, int sk, int ct, int out, int db = 0) { + const int v[8] = { 1, 0, 0, bm, bn, sk, ct, out }; + for (int i = 0; i < 8; ++i) setenv(p64[i], std::to_string(v[i]).c_str(), 1); + setenv(p64[11], db ? "1" : "0", 1); + }; + setenv(pins[0], "0", 1); + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) { + pin(bm, bn, sk, 4, 0); + for (int shape : { 3, 4 }) + mx_experts_check(pl, 65, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, + true); + } + for (int out : { 0, 1 }) + for (int ct : { 1, 4 }) { + pin(64, 128, 128, ct, out); + for (int shape : { 3, 4 }) + mx_experts_check(pl, 257, shape % 2 ? 2 : 1, true, + shape == 4 ? "sorted" : "token", shape, false, 288, 8, true); + } + for (int out : { 0, 1 }) { + pin(64, 128, 128, 4, out); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + mx_experts_check(pl, 257, 1, true, "sorted", 0, false, 3, 2, true); + } + // The double buffer at gate_up's slice wherever two stages fit, and with E8M0 codes 0 and + // 255 outside GLM's slices. + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) { + pin(bm, bn, 128, 4, bm == 64 && bn == 128, 1); + mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + } + pin(32, 64, 256, 4, 0, 1); + mx_experts_check(pl, 257, 2, true, "token", 3, false, 288, 8, true); + mx_experts_check(pl, 257, 2, false, "token", 0, true, 3, 2, true); + for (int i = 0; i < kP64; ++i) unsetenv(p64[i]); + unsetenv(pins[0]); + for (int m : { 1024, 2048 }) + for (int shape : { 3, 4 }) + mx_experts_check(pl, m, shape % 2 ? 2 : 1, true, shape == 4 ? "sorted" : "token", + shape, false, 288, 8, true); + mx_experts_check(pl, 4096, 1, true, "sorted", 4, false, 288, 8, true); + for (int i = 0; i < kP64; ++i) { + if (given64[i]) + setenv(p64[i], kept64[i].c_str(), 1); + else + unsetenv(p64[i]); + } + for (int i = 0; i < kPins; ++i) { + if (given[i]) + setenv(pins[i], kept[i].c_str(), 1); + else + unsetenv(pins[i]); + } + } + if (sel("hc_read_e4m3")) { if (!g_case) std::printf("\nthe gated residual's read at the prefill tile, every form " "against the decode tiles'\n"); @@ -20689,6 +24614,10 @@ static void usage(void) { " --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n" " weight bandwidth each reaches.\n" " --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n" + " --perff32 N K M [iters]: gemm_nt_f32 at every tile form, each compared byte\n" + " for byte with the legacy kernel, with GB/s and TFLOP/s.\n" + " --perfq N K M [iters]: the block-quantised trunk rows GLM resolves to: E4M3 with\n" + " F32 block scales and the three OCP-MXFP4 rows, GB/s on weight + scales.\n" " --perfw8 N K M [iters]: the 8-bit trunk GEMMs -- block E4M3 W8A8 and the int8\n" " rows -- at one shape, each with its TFLOP/s.\n" " --perfw2 N K M [iters]: the int2 DFlash2 draft head at every variant it has.\n" @@ -20737,6 +24666,41 @@ static void usage(void) { " a card: one-shot and two-shot at the block rule and at 4..64 blocks,\n" " each checked against the rank-order fold; numel 0 runs the decode\n" " and prefill messages at 4096 wide. dtype bf16 (default) or fp32.\n" + " --perfmxf8 M [iters] [experts] [top_k] [skew]: the same at the FP8 experts with f32\n" + " block scales (moe_gemm_fp8a8_f32scale, GLM's MTP layer).\n" + " --perfmhcpre M [iters]: mhc_pre (whole, partials alone, finish alone) and\n" + " mhc_post at GLM's shape, every form against the old dispatch.\n" + " --perfrouter M [iters]: router_sigmoid_topk at GLM's shape (288 experts, top 8),\n" + " the wave-per-row select against the serial scan.\n" + " --perfmoefuse M [iters]: GLM's decode fusions of the MoE block at M token\n" + " rows (288 experts, top 8, TP8 widths), each against the separate\n" + " launches it replaces: time of both and a byte comparison of every\n" + " output (`= old` or DIFFERS). The router fusion takes M <= 128.\n" + " --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n" + " sequence, and three anchored) and the 8x6 verify step, every row and\n" + " prefetch form timed and compared byte for byte with the old kernel.\n" + " --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, every\n" + " rows-a-group form timed and compared byte for byte with the old kernels.\n" + " --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n" + " TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n" + " M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n" + " CV per expert as g1.0 or a Zipf exponent as z1.1): time, touched weight\n" + " bytes, GB/s and TFLOP/s per projection; the rule, the expert-major form\n" + " at each pinned stage and column-tile count, the row groups and from 512\n" + " routed rows every prefill form and the P64 raster (BM x BN x stage,\n" + " down also x column tiles), each compared with the bytes of the pinned\n" + " TP8 prefill form.\n" + " --perfmla M blocks heads [iters] [fill]: MLA attention without the oracle, so\n" + " a 2048-row prefill chunk at 2k/8k context fits (blocks 513/2049).\n" + " The wave row and the matrix row at both key loads (paired tiles at\n" + " 8 heads) on the same operands: us, TFLOP/s over the visible\n" + " positions, and the difference to the wave row in bf16 steps. fill is\n" + " prefill (two sequences, default), fresh (one), ragged, SxR for a\n" + " decode step of S sequences with R rows each (M becomes S*R), or\n" + " topk:d[:context] for one sequence past the DSA budget: each row its\n" + " own top blocks-1 in block order, d blocks exchanged between\n" + " neighbours (context 16*(blocks-1) tokens by default). Each matrix\n" + " form also reports its second passes.\n" " --perfqsa CTX [M] [iters]: the QSA indexer at a real context length. It is\n" " the only decode op that grows with context, and at 200K it is\n" " about a third of the step. M is 1 + n_spec.\n" @@ -20750,10 +24714,13 @@ int main(int argc, char** argv) { const char* real_file = nullptr; long long real_woff = 0, real_soff = 0, real_n = 0, real_k = 0; long long perf_n = 0, perf_k = 0, perf_m = 0; - int perf_it = 50, perf_w2 = 0, perf_bf = 0, perf_w8 = 0; + int perf_it = 50, perf_w2 = 0, perf_bf = 0, perf_w8 = 0, perf_f32 = 0, perf_q = 0; long long sop_m = 0, sop_k = 0; int sop_it = 2000; long long qsa_ctx = 0, qsa_m = 4; + long long mla_m = 0, mla_blocks = 0, mla_heads = 0; + int mla_it = 20; + const char* mla_fill = "prefill"; int qsa_it = 200; long long hc_m = 0; int hc_it = 20; @@ -20776,6 +24743,18 @@ int main(int argc, char** argv) { long long ar8_n = -1; int ar8_it = 200; const char* ar8_dt = "bf16"; + long long mx_m = 0, mx_e = 288, mx_k = 8; + const char* mx_skew = nullptr; + bool mx_f8 = false; + int mx_it = 100; + long long mhc_m = 0; + int mhc_it = 200; + long long rt_m = 0; + int rt_it = 200; + long long mf_m = 0; + int mf_it = 200; + long long kda_m = 0, proj_m = 0; + int kda_it = 50, proj_it = 100; for (int i = 1; i < argc; ++i) { if (!std::strcmp(argv[i], "--real")) { if (i + 5 >= argc) { usage(); return 2; } @@ -20798,6 +24777,22 @@ int main(int argc, char** argv) { perf_k = std::strtoll(argv[++i], nullptr, 0); perf_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perff32")) { + /* gemm_nt_f32 at every tile form (see f32_forms). */ + if (i + 3 >= argc) { usage(); return 2; } + perf_f32 = 1; + perf_n = std::strtoll(argv[++i], nullptr, 0); + perf_k = std::strtoll(argv[++i], nullptr, 0); + perf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfq")) { + /* GLM's block-quantised trunk rows (see q_perf). */ + if (i + 3 >= argc) { usage(); return 2; } + perf_q = 1; + perf_n = std::strtoll(argv[++i], nullptr, 0); + perf_k = std::strtoll(argv[++i], nullptr, 0); + perf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0); } else if (!std::strcmp(argv[i], "--perfw8")) { if (i + 3 >= argc) { usage(); return 2; } perf_w8 = 1; @@ -20819,6 +24814,15 @@ int main(int argc, char** argv) { qsa_ctx = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_m = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) qsa_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmla")) { + /* MLA attention at a prefill chunk, matrix forms against the wave row. */ + if (i + 3 >= argc) { usage(); return 2; } + mla_m = std::strtoll(argv[++i], nullptr, 0); + mla_blocks = std::strtoll(argv[++i], nullptr, 0); + mla_heads = std::strtoll(argv[++i], nullptr, 0); + auto digits = [](const char* t) { return *t && std::strspn(t, "0123456789") == std::strlen(t); }; + if (i + 1 < argc && digits(argv[i + 1])) mla_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d && !digits(argv[i + 1])) mla_fill = argv[++i]; } else if (!std::strcmp(argv[i], "--cold")) { if (i + 1 >= argc) { usage(); return 2; } g_cold = std::strtoll(argv[++i], nullptr, 0) << 20; @@ -20869,6 +24873,36 @@ int main(int argc, char** argv) { ar8_n = std::strtoll(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_it = (int)std::strtol(argv[++i], nullptr, 0); if (i + 1 < argc && argv[i + 1][0] != 0x2d) ar8_dt = argv[++i]; + } else if (!std::strcmp(argv[i], "--perfmhcpre")) { + /* mhc_pre and mhc_post at GLM's shape, every form, against the old dispatch. */ + if (i + 1 >= argc) { usage(); return 2; } + mhc_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mhc_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfrouter")) { + if (i + 1 >= argc) { usage(); return 2; } + rt_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) rt_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmoefuse")) { + if (i + 1 >= argc) { usage(); return 2; } + mf_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mf_it = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfkda") || !std::strcmp(argv[i], "--perfproject")) { + /* kda_update or mla_project at GLM's TP8 shape, every form, against the old kernel. */ + if (i + 1 >= argc) { usage(); return 2; } + const bool kda = !std::strcmp(argv[i], "--perfkda"); + (kda ? kda_m : proj_m) = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) + (kda ? kda_it : proj_it) = (int)std::strtol(argv[++i], nullptr, 0); + } else if (!std::strcmp(argv[i], "--perfmx") || !std::strcmp(argv[i], "--perfmxf8")) { + mx_f8 = !std::strcmp(argv[i], "--perfmxf8"); + /* An expert GEMM at GLM's TP8 slices over an M-token chunk, every form: MXFP4, or with + * --perfmxf8 the FP8 experts with f32 block scales. */ + if (i + 1 >= argc) { usage(); return 2; } + mx_m = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_it = (int)std::strtol(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_e = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_k = std::strtoll(argv[++i], nullptr, 0); + if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_skew = argv[++i]; } else if (!std::strcmp(argv[i], "--perfhc")) { /* The gated residual's read at M rows. */ if (i + 1 >= argc) { usage(); return 2; } @@ -20988,6 +25022,67 @@ int main(int argc, char** argv) { dfree_all(); #else skip("eight-rank all-reduce timing", "built without HIP"); +#endif + return 0; + } + if (mhc_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mhcpre_perf(pl, mhc_m, mhc_it); + dfree_all(); +#else + skip("mhc timing", "built without HIP"); +#endif + return 0; + } + if (rt_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + router_select(pl, rt_m, 288, 8, 1, false, rt_it); + dfree_all(); +#else + skip("router timing", "built without HIP"); +#endif + return 0; + } + if (mf_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + moefuse_perf(pl, mf_m, mf_it); + dfree_all(); +#else + skip("MoE fusion timing", "built without HIP"); +#endif + return g_fail ? 1 : 0; + } + if (kda_m || proj_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + if (kda_m) kda_forms(pl, kda_m, kda_it); + if (proj_m) project_forms(pl, proj_m, proj_it); + dfree_all(); +#else + skip("kda_update and mla_project timing", "built without HIP"); +#endif + return 0; + } + if (mx_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mx_perf(pl, mx_m, mx_it, mx_e, mx_k, mx_f8, mx_skew); + dfree_all(); +#else + skip("MXFP4 expert GEMM timing", "built without HIP"); +#endif + return 0; + } + if (mla_m) { + if (!load(&pl, path)) return 1; +#ifdef RAD_HAVE_HIP + mla_perf(pl, mla_m, mla_blocks, mla_heads, mla_it, mla_fill); + dfree_all(); +#else + skip("MLA attention timing", "built without HIP"); #endif return 0; } @@ -21015,7 +25110,9 @@ int main(int argc, char** argv) { if (perf_n) { if (!load(&pl, path)) return 1; #ifdef RAD_HAVE_HIP - if (perf_bf) bf16_perf(pl, perf_n, perf_k, perf_m, perf_it); + if (perf_f32) f32_forms(pl, perf_m, perf_n, perf_k, perf_it, true); + else if (perf_q) q_perf(pl, perf_n, perf_k, perf_m, perf_it); + else if (perf_bf) bf16_perf(pl, perf_n, perf_k, perf_m, perf_it); else if (perf_w8) w8_perf(pl, perf_n, perf_k, perf_m, perf_it); else if (perf_w2) w2_perf(pl, perf_n, perf_k, perf_m, perf_it); else fp8_perf(pl, perf_n, perf_k, perf_m, perf_it); @@ -21043,6 +25140,7 @@ int main(int argc, char** argv) { * a faulting row may print nothing. */ if (g_case) { if (!load(&pl, path)) return CH_FAIL; + g_plugin = path; device_phase(pl); if (!g_matched) skip(g_case, "no smoke case"); std::fflush(stdout); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 91505e41..8caf64ae 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -66,6 +66,7 @@ #include #include +#include #include "r4d_plugin.h" #include "rad_sample.h" @@ -364,6 +365,91 @@ extern "C" int r4d_shape_gemm_nt_bias(const RadParam* p, int n_p, int operand, R R4D_PICK(l); } +extern "C" int r4d_shape_moe_mxfp4(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const int64_t N1 = rad_param_geti(p, n_p, "N_odd", N), K1 = rad_param_geti(p, n_p, "K_odd", K); + const int64_t ne = pi(p, n_p, "n_expert"), top = pi(p, n_p, "top_k"); + const char* order = rad_param_gets(p, n_p, "a_order", ""); + const int64_t ar = !std::strcmp(order, "sorted") ? M * top : M; + const int64_t nk = std::max(K, K1), nn = std::max(N, N1); + RadOpdDesc s0 = opd((uint32_t)RAD_U8, (ne + 1) / 2, N, K / 32); + RadOpdDesc s1 = opd((uint32_t)RAD_U8, ne / 2, N1, K1 / 32); + s0.fill = s1.fill = RAD_FILL_INDEX; + s0.idx_const = s1.idx_const = 127; + const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, ar, nk), + opd((uint32_t)RAD_F32, ar, nk / 128), + opd((uint32_t)RAD_FP4E2M1, (ne + 1) / 2, N, K), + s0, + opd_idx(M * top, 0, M * top), + opd_idx(ne + 1, 0, M * top + 1), + opd((uint32_t)RAD_FP4E2M1, ne / 2, N1, K1), + s1, + opd((uint32_t)RAD_BF16, M * top, nn) }; + R4D_PICK(l); +} + +extern "C" int r4d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = rad_param_gets(p, n_p, "state_form", ""); + if (!std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED; + const int64_t M = pi(p, n_p, "M"), H = pi(p, n_p, "heads"); + const int64_t K = pi(p, n_p, "head_k"), V = pi(p, n_p, "head_v"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const char* mode = rad_param_gets(p, n_p, "mode", ""); + const int64_t history = !std::strcmp(mode, "verify") ? M : 1; + const RadOpdDesc l[] = { + opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H), + opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K), + opd((uint32_t)RAD_F32, history + 1, H, V, K), + opd_idx(1, history, history + 1, -1, RAD_OPD_F_IDX_UNIQUE), + opd_idx(2, 0, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(1, 0, 0, 1), opd_idx(1, 0, 0, 1), opd(D, M, H, V), + }; + R4D_PICK(l); +} + +extern "C" int r4d_shape_mhc_pre(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n), + opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), opd(D, M, n), + opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) }; + R4D_PICK(l); +} +/* The partial matrix: per chunk the hc*(hc+2) coefficient partials and the sum of squares, padded to + * a multiple of four floats (docs/OPS.md). */ +static int64_t mhc_part_stride(int64_t hc) { return (hc * (hc + 2) + 1 + 3) / 4 * 4; } +extern "C" int r4d_shape_mhc_pre_partial(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const int64_t chunks = pi(p, n_p, "chunks"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd((uint32_t)RAD_F32, hc * (hc + 2), hc * n), + opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_pre_finish(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const int64_t chunk = pi(p, n_p, "chunk"); + const int64_t chunks = chunk > 0 ? hc * n / chunk : 0; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_F32, M, chunks * mhc_part_stride(hc)), + opd(D, M, hc * n), opd((uint32_t)RAD_F32, 3), opd((uint32_t)RAD_F32, hc * (hc + 2)), + opd(D, M, n), opd((uint32_t)RAD_F32, M, hc), opd((uint32_t)RAD_F32, M, hc * hc) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_post(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, n), opd(D, M, hc * n), opd((uint32_t)RAD_F32, M, hc), + opd((uint32_t)RAD_F32, M, hc * hc), opd(D, M, hc * n) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mhc_contract(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), hc = pi(p, n_p, "hc"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, hc * n), opd(D, M, n) }; + R4D_PICK(l); +} + /* ---- the gated residual (r4d_hc_bf16.hip's three shims). `inject` and `group` default on, so a * query naming neither describes what every trunk connection runs; 0 for either describes one of * the two exceptions: the final mixer, and a read whose consumer wants bf16. */ @@ -496,6 +582,83 @@ extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand, const RadOpdDesc l[] = { opd(D, M, 2 * n), opd(D, M, n) }; R4D_PICK(l); } +extern "C" int r4d_shape_router_sigmoid_topk(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), opd_idx(M, k, ne), + opd(D, M, k) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_router_sigmoid_topk_scatter(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), ne = pi(p, n_p, "n_expert"), k = pi(p, n_p, "top_k"); + const int64_t nl = pi(p, n_p, "n_local", ne); + if (ne <= 0 || ne > 512 || k <= 0 || k > ne || nl <= 0 || nl > ne || M * k > 1024) + return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, ne), + opd((uint32_t)RAD_F32, ne), + opd_idx(M, k, ne), + opd(D, M, k), + opd((uint32_t)RAD_I32, M * k), + opd((uint32_t)RAD_I32, nl + 1), + opd((uint32_t)RAD_I32, nl), + opd((uint32_t)RAD_BF16, M, 1), + opd((uint32_t)RAD_I32, M * k) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_dsa_pool(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), ratio = pi(p, n_p, "ratio"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M * ratio, 2 * n), + opd((uint32_t)RAD_F32, ratio, n), + opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, 1), + opd_none(), + opd_none() }; + R4D_PICK(l); +} +extern "C" int r4d_shape_dsa_query(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, 1) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), h = pi(p, n_p, "heads"), d = pi(p, n_p, "head_dim"), + l = pi(p, n_p, "latent_dim"); + const char* mode = r4d_pgets(p, n_p, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + if (!absorb && !expand) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l), + opd((uint32_t)RAD_BF16, h * 2 * d, l), + opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) }; + R4D_PICK(list); +} +extern "C" int r4d_shape_dsa_score(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"), H = pi(p, n_p, "heads"); + const int64_t B = pi(p, n_p, "blocks"), S = pi(p, n_p, "seqs"), pages = S * B; + const RadOpdDesc l[] = { opd((uint32_t)RAD_F8E4M3, M, H, n), + opd((uint32_t)RAD_F32, M, H), + opd((uint32_t)RAD_F32, M, H), + opd((uint32_t)RAD_F8E4M3, pages, n), + opd((uint32_t)RAD_F32, pages), + opd_idx(S, B, pages), + opd_idx(S + 1, 0, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(S, 0, 0, B), + opd((uint32_t)RAD_F32, M, B) }; + R4D_PICK(l); +} +extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), D = pi(p, n_p, "latent_dim"), H = pi(p, n_p, "heads"); + const int64_t B = pi(p, n_p, "blocks"), bs = pi(p, n_p, "block_size"), + pages = std::max((int64_t)2, B * M); + const uint32_t dt = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(dt, M, H, D), opd(dt, pages, 1, bs, D), opd_idx(M, B, pages), + opd_idx(M, 0, 0, B * bs), opd(dt, M, H, D) }; + R4D_PICK(l); +} extern "C" int r4d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1020,6 +1183,12 @@ extern "C" int r4d_shape_ar_rmsnorm_quant_fp8(const RadParam* p, int n_p, int op * r4d_rowtopk_bf16.hip). * ========================================================================================= */ +extern "C" int r4d_shape_gemm_nt_f32(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K"); + const RadOpdDesc l[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K), + opd((uint32_t)RAD_F32, M, N) }; + R4D_PICK(l); +} extern "C" int r4d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1243,6 +1412,22 @@ extern "C" int r4d_shape_moe_scatter(const RadParam* p, int n_p, int operand, Ra R4D_PICK(l); } +extern "C" int r4d_shape_moe_scatter_inv(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t ne = pi(p, n_p, "n_expert"); + const int64_t k = pi(p, n_p, "top_k"); + if (ne <= 0 || ne > 512 || k <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd_idx(M, k, ne, -1), + opd((uint32_t)RAD_I32, M * k), + opd((uint32_t)RAD_I32, ne + 1), + opd((uint32_t)RAD_I32, ne), + opd((uint32_t)RAD_I32, M * k), + }; + R4D_PICK(l); +} + extern "C" int r4d_shape_moe_gemm_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t N0 = pi(p, n_p, "N"), K0 = pi(p, n_p, "K"); @@ -1339,6 +1524,12 @@ extern "C" int r4d_shape_moe_gather(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* moe_gather's list with the slot table in place of `sorted_tok`: the same draw, since a valid + * table, like a valid sort, holds distinct rows of `y_expert` (and -1 for a dropped slot). */ +extern "C" int r4d_shape_moe_gather_inv(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return r4d_shape_moe_gather(p, n_p, operand, out); +} + /* row_topk -- exact per-row top-R of a wide bf16 matrix (shim in r4d_rowtopk_bf16.hip). R is at * most 32, stage 2's PT. */ extern "C" int r4d_shape_row_topk(const RadParam* p, int n_p, int operand, diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 51e97566..bf2b8296 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -357,14 +357,16 @@ endif() # ================================================================== libr4d's kernels, on the host # # Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design -# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of six units written -# against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, -# expert_scale, the QSA block selection, whose four kernels a card-less build otherwise never -# runs, and the runtime-LoRA pair. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread -# is a fiber, and __syncthreads and cross-lane ops are barriers (one not reached uniformly is -# reported as a deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select, -# the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, and for the -# LoRA pair libref itself when the test can load it. +# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of thirteen units +# written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins, +# expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile +# forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA +# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings and GLM's MoE decode +# fusions, whose kernels a card-less build otherwise never runs. emu/hip/hip_runtime.h supplies the +# HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not +# reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and +# ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, +# and for the LoRA pair libref itself when the test can load it. # # Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang # C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so @@ -376,8 +378,10 @@ set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d) set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu) set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip ${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip - ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip) -set(R4D_EMU_TESTS attn pick norm escale qsa lora) + ${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip + ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip + ${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip) +set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -413,7 +417,10 @@ else() set(objs "") foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp ${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp - ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp) + ${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp + ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp + ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp + ${R4D_EMU}/test_moefuse.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -450,7 +457,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora) + foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -460,7 +467,7 @@ if(R4D_EMU_BUILT) COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3) endforeach() set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick - r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora + r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT}) # The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can # load one -- expand bit for bit, shrink to its bound. diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 3349b8a5..67b6ed7c 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -995,6 +995,25 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) { for (const Band& x : b) CHECK_EQ(picked(x.dom[RAD_DOMAIN_DEVICE].row), "attn_vit_h72_bf16"); } +/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves + * every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M + * lowers that bound, which this case does not cover. */ +TEST(libr4d_resolves_the_mla_attention_by_rows) { + const std::string so = libr4d(); + if (so.empty()) return; + if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return; + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + Geometry g; + g.set_i("latent_dim", 512); + g.set_i("heads", 8); + g.set_i("blocks", 513); + g.set_i("block_size", 4); + g.set_s("dtype", "bf16"); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 "); + CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 "); +} + /* ================================================================== constraints that are not intervals */ namespace { std::string extra_dir() { return home() + "/testkernels/extra"; } diff --git a/tests/r4d_emu/emu/emu.cpp b/tests/r4d_emu/emu/emu.cpp index 840c96b2..7a8cd47c 100644 --- a/tests/r4d_emu/emu/emu.cpp +++ b/tests/r4d_emu/emu/emu.cpp @@ -2,6 +2,7 @@ #include "rad_plugin.h" #include #include +#include #include #include #include @@ -47,11 +48,12 @@ struct Sched { std::vector f; void* main_sp = nullptr; int cur = -1, nthreads = 0; - EmuIdx bid{}; + EmuIdx bid{}, bdim{}, gdim{}; void (*body)(void*) = nullptr; void* ctx = nullptr; - /* block barrier */ + /* block barrier; or_acc[g % 3] collects __syncthreads_or's predicates at generation g */ int arrive = 0; unsigned gen = 0; + int or_acc[3] = {}; /* wave barriers and exchange slots, double-buffered by parity */ int warrive[64] = {}; unsigned wgen[64] = {}; int slot[64][2][32] = {}; @@ -82,15 +84,26 @@ extern "C" void emu_entry(); EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; } EmuIdx& emu_block_idx() { return S.bid; } +EmuIdx& emu_block_dim() { return S.bdim; } +EmuIdx& emu_grid_dim() { return S.gdim; } void __syncthreads() { Fiber& me = S.f[S.cur]; const unsigned g = S.gen; - if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; } + /* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every + * write to it (threads arrive at g + 1 only after g completes) and behind every read of the + * slot it shares a residue with (g - 2's, read before arriving at g - 1). */ + if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; } me.waiting = 1; while (S.gen == g) yield(); me.waiting = 0; } +int __syncthreads_or(int p) { + const unsigned g = S.gen; + if (p) S.or_acc[g % 3] = 1; + __syncthreads(); + return S.or_acc[g % 3]; +} static void wave_barrier(int w) { Fiber& me = S.f[S.cur]; @@ -165,6 +178,23 @@ static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8]; emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) { return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; }); } +namespace { +struct Bytes8 { + uint8_t v[8]; + uint8_t operator[](int e) const { return v[e]; } +}; +} +static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8]; +emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) { + Bytes8 pa, pb; + std::memcpy(pa.v, &a, 8); + std::memcpy(pb.v, &b, 8); + return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); }); +} +emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) { + std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n"); + std::abort(); +} unsigned emu_ballot(bool p) { int l; const int* s = exchange(p ? 1 : 0, &l, kOpBallot); @@ -236,6 +266,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t } lds_reserve(dyn_lds); S.body = body; S.ctx = ctx; S.nthreads = n; + S.bdim = EmuIdx{block.x, block.y, block.z}; + S.gdim = EmuIdx{grid.x, grid.y, grid.z}; S.f.resize(n); for (auto& f : S.f) if (!f.stack) f.stack.reset(new char[kStack]); for (unsigned bz = 0; bz < grid.z; ++bz) @@ -244,6 +276,7 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t S.bid = EmuIdx{bx, by, bz}; std::memset(g_lds, 0xA5, dyn_lds); S.arrive = 0; S.gen = 0; + for (int& a : S.or_acc) a = 0; for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; } for (int t = 0; t < n; ++t) { Fiber& f = S.f[t]; diff --git a/tests/r4d_emu/emu/hip/hip_runtime.h b/tests/r4d_emu/emu/hip/hip_runtime.h index 31d786d9..8f46b49e 100644 --- a/tests/r4d_emu/emu/hip/hip_runtime.h +++ b/tests/r4d_emu/emu/hip/hip_runtime.h @@ -15,8 +15,12 @@ #define __device__ #define __host__ #define __shared__ static +#define __constant__ #define __forceinline__ inline #define __launch_bounds__(n) +/* R4D_WAVES (r4d_common.h) names a kernel attribute; on the host it becomes an empty attribute */ +#define amdgpu_waves_per_eu(lo, hi) +#define __align__(n) __attribute__((aligned(n))) struct dim3 { unsigned x, y, z; @@ -29,6 +33,25 @@ inline hipError_t hipGetLastError() { return 0; } /* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */ struct hipDeviceProp_t { size_t sharedMemPerBlock; }; inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; } +/* no graphs: a stream never captures */ +enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 }; +inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) { + *s = hipStreamCaptureStatusNone; + return hipSuccess; +} +/* every launch runs to completion before it returns */ +inline hipError_t hipDeviceSynchronize() { return hipSuccess; } +/* __device__ variables are host globals, so a symbol copy is a memcpy */ +enum hipMemcpyKind { hipMemcpyHostToDevice = 1, hipMemcpyDeviceToHost = 2 }; +#define HIP_SYMBOL(s) (&(s)) +inline hipError_t hipMemcpyFromSymbol(void* dst, const void* sym, size_t n, size_t off, hipMemcpyKind) { + std::memcpy(dst, (const char*)sym + off, n); + return hipSuccess; +} +inline hipError_t hipMemcpyToSymbol(const void* sym, const void* src, size_t n, size_t off, hipMemcpyKind) { + std::memcpy((char*)sym + off, src, n); + return hipSuccess; +} inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) { *p = hipDeviceProp_t{}; p->sharedMemPerBlock = 64 * 1024; @@ -38,9 +61,15 @@ inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) { struct EmuIdx { unsigned x, y, z; }; EmuIdx& emu_thread_idx(); EmuIdx& emu_block_idx(); +EmuIdx& emu_block_dim(); +EmuIdx& emu_grid_dim(); #define threadIdx (emu_thread_idx()) #define blockIdx (emu_block_idx()) +#define blockDim (emu_block_dim()) +#define gridDim (emu_grid_dim()) void __syncthreads(); +/* the block barrier, returning whether any thread passed a nonzero predicate */ +int __syncthreads_or(int p); int emu_bpermute(int addr, int v); int emu_readlane(int v, int lane); #define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v)) @@ -73,6 +102,14 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) { return r; } #define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s)) +/* HIP's __byte_perm: result byte i is the byte of {y, x} (x low) that the low three bits of + * nibble i of s name; only the low four nibbles are read */ +inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) { + const unsigned long long d = ((unsigned long long)y << 32) | x; + unsigned r = 0; + for (int i = 0; i < 4; ++i) r |= (unsigned)((d >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i); + return r; +} /* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a * fence or a scheduling barrier orders nothing more. */ #define __builtin_amdgcn_s_barrier() __syncthreads() @@ -81,15 +118,38 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) { /* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */ template inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; } +template +inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; } +template +inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; } +template +inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; } /* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N] * lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */ typedef short emu_v8s __attribute__((ext_vector_type(8))); typedef float emu_v8f __attribute__((ext_vector_type(8))); emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c); +/* the __bf16 fragments of r4d_gdn_wmma.h, the same bits */ +typedef __bf16 emu_v8bf __attribute__((ext_vector_type(8))); +inline emu_v8f emu_wmma_bf16(emu_v8bf a, emu_v8bf b, emu_v8f c) { + return emu_wmma_bf16(__builtin_bit_cast(emu_v8s, a), __builtin_bit_cast(emu_v8s, b), c); +} #define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c)) typedef _Float16 emu_v8h __attribute__((ext_vector_type(8))); emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c); #define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c)) +/* v_wmma_f32_16x16x16_fp8_fp8 (gfx12, wave32): the bf16 form's layout with eight E4M3 bytes a + * lane, element e in byte e. Each output is c plus its 16 products in k order: not the hardware's + * internal order, but a function of the output's own row, column and c alone, as the hardware's + * is, which is what a comparison of two kernels over the same fragments relies on. */ +typedef int emu_v2i __attribute__((ext_vector_type(2))); +emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c); +#define __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c) emu_wmma_fp8((a), (b), (c)) +/* v_wmma_i32_16x16x16_iu8: not emulated; reported when reached */ +typedef int emu_v8i __attribute__((ext_vector_type(8))); +emu_v8i emu_wmma_iu8(bool sa, emu_v2i a, bool sb, emu_v2i b, emu_v8i c, bool clamp); +#define __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(sa, a, sb, b, c, cl) \ + emu_wmma_iu8((sa), (a), (sb), (b), (c), (cl)) /* global_load_tr_b128: not emulated; reported when reached */ emu_v8s emu_load_tr_b128(const void* p); #define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p)) @@ -120,9 +180,34 @@ inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; } inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; } inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; } inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */ +/* The device's fast exponential is not bit-exact to expf; here it is expf, so a test compares two + * kernels that both take it, never a kernel against a host value of it. */ +inline float __expf(float x) { return std::exp(x); } inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; } inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; } inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; } +/* The float shuffles over ds_bpermute, for one-dimensional blocks, within groups of `width` + * lanes: __shfl_xor reads lane L ^ mask, __shfl lane `src`, __shfl_down lane L + delta (its own + * value past the group's end) */ +inline float emu_shfl_from(float v, int src) { + return __int_as_float(emu_bpermute(src << 2, __float_as_int(v))); +} +inline float __shfl_xor(float v, int mask, int width = 32) { + const int lane = (int)threadIdx.x & 31; + return emu_shfl_from(v, (lane & ~(width - 1)) | ((lane ^ mask) & (width - 1))); +} +inline float __shfl(float v, int src, int width = 32) { + const int lane = (int)threadIdx.x & 31; + return emu_shfl_from(v, (lane & ~(width - 1)) | (src & (width - 1))); +} +inline float __shfl_down(float v, unsigned delta, int width = 32) { + const int lane = (int)threadIdx.x & 31, in_group = lane & (width - 1); + return emu_shfl_from(v, in_group + (int)delta < width ? lane + (int)delta : lane); +} +/* HIP declares the classification functions in the global namespace */ +using std::isfinite; +inline int min(int a, int b) { return a < b ? a : b; } +inline int max(int a, int b) { return a > b ? a : b; } /* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0); @@ -154,6 +239,9 @@ int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, cons } #define R4D_EMIT(stream, kernel, grid, block, lds, ...) \ emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__) +/* hipLaunchKernelGGL, for units that launch with it directly: the same call as R4D_EMIT. */ +#define hipLaunchKernelGGL(kernel, grid, block, lds, stream, ...) \ + ((void)(stream), (void)emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)) /* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending * at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one * past the end faults */ diff --git a/tests/r4d_emu/test_f32.cpp b/tests/r4d_emu/test_f32.cpp new file mode 100644 index 00000000..b6232903 --- /dev/null +++ b/tests/r4d_emu/test_f32.cpp @@ -0,0 +1,260 @@ +/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form + * (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the + * legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with + * fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding + * stay untouched. + * + * router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan + * (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on + * random and on tied ranks, with the outputs' pitch padding untouched. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static float legacy_model(const uint16_t* x, const float* w, int k) { + float lane[32]; + for (int l = 0; l < 32; ++l) { + float s = 0; + for (int j = l; j < k; j += 32) s = std::fmaf(b2f(x[j]), w[j], s); + lane[l] = s; + } + for (int mask = 16; mask; mask >>= 1) { + float next[32]; + for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask]; + std::memcpy(lane, next, sizeof lane); + } + return lane[0]; +} + +static void router_model(const float* lg, const float* bias, int bp, int ne, int k, int norm, + float factor, int* ids, float* w) { + float prob[512], rank[512], chosen[32], total = 0; + int index[32]; + for (int e = 0; e < ne; ++e) { + prob[e] = 1.0f / (1.0f + expf(-lg[e])); + rank[e] = prob[e] + bias[(size_t)e * bp]; + } + for (int j = 0; j < k; ++j) { + int best = 0; + for (int e = 1; e < ne; ++e) + if (rank[e] > rank[best]) best = e; + index[j] = best; + chosen[j] = prob[best]; + total += chosen[j]; + rank[best] = -INFINITY; + } + const float mult = norm ? factor / (total + 1e-20f) : factor; + for (int j = 0; j < k; ++j) { + ids[j] = index[j]; + w[j] = chosen[j] * mult; + } +} + +static void router_cases(std::mt19937& rng, int& cases, int& fails) { + struct Shape { + int M, ne, k, norm; + bool ties; + }; + const Shape shapes[] = { { 1, 288, 8, 1, false }, { 6, 288, 8, 1, false }, + { 20, 288, 8, 1, true }, { 48, 288, 8, 1, false }, + { 6, 288, 8, 1, true }, { 5, 8, 8, 0, true }, + { 5, 32, 32, 0, true }, { 7, 300, 8, 1, false }, + { 3, 512, 32, 1, true } }; + std::uniform_int_distribution ud(-1000, 1000); + for (const Shape& sh : shapes) { + const int M = sh.M, ne = sh.ne, k = sh.k, lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1; + const float factor = 2.5f; + std::vector lg((size_t)M * lp), bias((size_t)ne * bp); + for (auto& v : lg) v = sh.ties ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200; + for (auto& v : bias) v = sh.ties ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000; + RadTensor t[4]{}; + t[0].data = lg.data(); + t[0].dtype = RAD_F32; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = ne; + t[0].stride[0] = lp; + t[0].stride[1] = 1; + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = bp; + t[2].dtype = RAD_I32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = k; + t[2].stride[0] = ip; + t[2].stride[1] = 1; + t[3].dtype = RAD_F32; + t[3].rank = 2; + t[3].shape[0] = M; + t[3].shape[1] = k; + t[3].stride[0] = wp; + t[3].stride[1] = 1; + RadParam p[6]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, sh.norm }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = factor; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + RadArgs a{}; + a.t = t; + a.n_t = 4; + a.p = p; + a.n_p = 6; + auto run = [&](const char* form, std::vector& ids, std::vector& w) { + ids.assign((size_t)M * ip, -77); + w.assign((size_t)M * wp, -7.25f); + t[2].data = ids.data(); + t[3].data = w.data(); + if (form) + setenv("RADIANCE_ROUTER_SELECT", form, 1); + else + unsetenv("RADIANCE_ROUTER_SELECT"); + return r4d_rad_router_sigmoid_topk(&a, nullptr); + }; + std::vector ids_old, ids_new; + std::vector w_old, w_new; + ++cases; + if (run("old", ids_old, w_old) != RAD_OK) { + std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne); + ++fails; + continue; + } + int bad = 0; + for (int r = 0; r < M; ++r) { + int mi[32]; + float mw[32]; + router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw); + bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0; + bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0; + for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77; + for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f; + } + if (bad) { + std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k, + bad); + ++fails; + } + ++cases; + const int rc = run(nullptr, ids_new, w_new); + if (rc != RAD_OK || ids_new != ids_old || + std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) { + std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k, + sh.ties ? " tied" : "", rc); + ++fails; + } + } + unsetenv("RADIANCE_ROUTER_SELECT"); +} + +int main() { + std::mt19937 rng(17); + std::normal_distribution nd(0.f, 1.f); + const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2", + "4x4", "8x4", "16x2", "16x4", nullptr }; + struct Shape { + int M, N, K; + }; + const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 }, + { 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } }; + int fails = 0, cases = 0; + for (const Shape& sh : shapes) { + const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3; + std::vector x((size_t)M * xp); + std::vector w((size_t)N * K); + for (auto& v : x) v = f2b(nd(rng)); + for (auto& v : w) v = nd(rng) * 0.03f; + RadTensor t[3]{}; + t[0].data = x.data(); + t[0].dtype = RAD_BF16; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = K; + t[0].stride[0] = xp; + t[0].stride[1] = 1; + t[1].data = w.data(); + t[1].dtype = RAD_F32; + t[1].rank = 2; + t[1].shape[0] = N; + t[1].shape[1] = K; + t[1].stride[0] = K; + t[1].stride[1] = 1; + t[2].dtype = RAD_F32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = N; + t[2].stride[0] = yp; + t[2].stride[1] = 1; + RadParam p[4]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "N", RAD_P_INT, N }; + p[2] = { "K", RAD_P_INT, K }; + p[3].key = "dtype"; + p[3].kind = RAD_P_STR; + p[3].sval = "bf16"; + RadArgs a{}; + a.t = t; + a.n_t = 3; + a.p = p; + a.n_p = 4; + auto run = [&](const char* form, std::vector& y) { + y.assign((size_t)M * yp, -7.25f); + t[2].data = y.data(); + if (form) + setenv("RADIANCE_F32_GEMM_TILE", form, 1); + else + unsetenv("RADIANCE_F32_GEMM_TILE"); + return r4d_rad_gemm_nt_f32(&a, nullptr); + }; + std::vector legacy, got; + ++cases; + if (run("legacy", legacy) != RAD_OK) { + std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K); + ++fails; + continue; + } + int bad = 0; + for (int r = 0; r < M; ++r) { + for (int c = 0; c < N; ++c) { + const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K); + bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0; + } + for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f; + } + if (bad) { + std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N, + K, bad); + ++fails; + } + for (const char* const* f = forms;; ++f) { + ++cases; + const int rc = run(*f, got); + const bool same = + rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0; + if (!same) { + std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N, + K, rc); + ++fails; + } + if (!*f) break; + } + } + unsetenv("RADIANCE_F32_GEMM_TILE"); + router_cases(rng, cases, fails); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_fp8f32.cpp b/tests/r4d_emu/test_fp8f32.cpp new file mode 100644 index 00000000..e68543e5 --- /dev/null +++ b/tests/r4d_emu/test_fp8f32.cpp @@ -0,0 +1,110 @@ +/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT + * emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must + * match the legacy 16x64 tile + * bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order. + * Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly + * idle are covered; the output's pitch padding stays untouched. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; + t.shape[1] = cols; + t.stride[0] = ld; + t.stride[1] = 1; + return t; +} + +int main() { + std::mt19937 rng(31); + std::normal_distribution nd(0.f, 1.f); + struct Shape { + int M, N, K; + }; + const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 }, + { 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 }, + { 3, 128, 4096 } }; + const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8", + "decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2", + "decode3x4x2", "decode2x4x4", "rows1", "rows2", + "rows4", nullptr }; + int fails = 0, cases = 0; + for (const Shape& sh : shapes) { + const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8; + std::vector a((size_t)M * ap), w((size_t)N * K); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng)); + for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f); + std::vector as((size_t)M * kb), ws((size_t)(N / 128) * kb); + // Scales over twelve octaves: K blocks of very different weight cancel, so a changed + // summation order shows through the bf16 output. + std::uniform_real_distribution oct(-6.f, 6.f); + for (auto& v : as) v = std::exp2(oct(rng)); + for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f; + RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap), + mat(as.data(), RAD_F32, M, kb, kb), + mat(w.data(), RAD_F8E4M3, N, K, K), + mat(ws.data(), RAD_F32, N / 128, kb, kb), + RadTensor{}, + RadTensor{}, + RadTensor{} }; + RadParam p[5]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "N", RAD_P_INT, N }; + p[2] = { "K", RAD_P_INT, K }; + p[3] = { "group", RAD_P_INT, 128 }; + p[4].key = "dtype"; + p[4].kind = RAD_P_STR; + p[4].sval = "fp8a8f32"; + auto run = [&](const char* form, std::vector& y) { + y.assign((size_t)M * yp, 0x7777); + t[4] = mat(y.data(), RAD_BF16, M, N, yp); + setenv("RADIANCE_FP8F32_FORM", form, 1); + RadArgs ar{}; + ar.t = t; + ar.n_t = 7; + ar.p = p; + ar.n_p = 5; + return r4d_rad_fp8_f32scale(&ar, nullptr); + }; + std::vector legacy, got; + ++cases; + if (run("legacy", legacy) != RAD_OK) { + std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K); + ++fails; + continue; + } + int nonzero = 0; + for (int r = 0; r < M; ++r) + for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0; + if (nonzero < M * N / 2) { + std::printf("FAIL legacy output mostly zero at M=%d\n", M); + ++fails; + } + for (const char* const* f = forms; *f; ++f) { + ++cases; + const int rc = run(*f, got); + if (rc != RAD_OK || got != legacy) { + size_t i = 0; + while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i; + std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K, + rc, i); + ++fails; + } + } + } + unsetenv("RADIANCE_FP8F32_FORM"); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_kda.cpp b/tests/r4d_emu/test_kda.cpp new file mode 100644 index 00000000..65cdba48 --- /dev/null +++ b/tests/r4d_emu/test_kda.cpp @@ -0,0 +1,187 @@ +/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form + * must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes: + * prefill per candidate and anchored, verify per candidate and anchored (after the replay of the + * accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot + * are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include +#include +#include +#include +#include +#include +#include + +static RadTensor tens(void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; +} +static uint16_t f2b(float f) { + uint32_t u; + std::memcpy(&u, &f, 4); + return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); +} + +struct Case { + const char* name; + const char* mode; + bool anchor; + int64_t width; + std::vector cu, idx, accepted, init; + std::vector> counts; +}; + +int main() { + std::mt19937 rng(41); + std::uniform_real_distribution u(-1.f, 1.f); + const int64_t H = 2, D = 128, slots = 16, tokens = 9; + std::vector state0((size_t)(slots * H * D * D)), alog((size_t)H), bias((size_t)(H * D)); + for (auto& v : state0) v = u(rng); + for (auto& v : alog) v = 0.5f * u(rng); + for (auto& v : bias) v = u(rng); + std::vector in[5]; + for (int i = 0; i < 5; ++i) { + in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D))); + for (auto& v : in[i]) v = f2b((i >= 3 ? 2.f : 1.f) * u(rng)); + } + const std::vector cases = { + { "prefill, per candidate", + "prefill", + false, + 1, + { 0, 4, 4, 9 }, + { 3, 4, -1 }, + { 1, 1, 1 }, + { 0, 1, 1 }, + {} }, + { "prefill, anchored", + "prefill", + true, + 2, + { 0, 5, 9 }, + { 1, 2, 3, 4 }, + { 1, 1 }, + { 1, 0 }, + {} }, + { "verify, per candidate", + "verify", + false, + 4, + { 0, 4, 7, 9 }, + { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1 }, + { 3, 2, 1 }, + { 1, 0, 1 }, + {} }, + { "verify, anchored", + "verify", + true, + 4, + { 0, 4, 7, 9 }, + { 1, 9, 5, 9, 2, 9, 6, 9, 3, 9, 7, 9 }, + { 3, 2, 1 }, + { 1, 1, 0 }, + { { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } }, + }; + struct Form { + const char* rows; + const char* prefetch; + }; + const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" }, + { "1", "0" }, { "2", "0" }, { "4", "0" } }; + int fails = 0, checks = 0; + for (const Case& c : cases) { + std::vector start = state0; + for (const auto& sc : c.counts) + for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second; + const int64_t seqs = (int64_t)c.cu.size() - 1; + std::vector idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init; + auto run = [&](std::vector& out, std::vector& state) { + out.assign((size_t)(tokens * H * D), 0x7777); + state = start; + RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }), + tens(in[1].data(), RAD_BF16, { tokens, H, D }), + tens(in[2].data(), RAD_BF16, { tokens, H, D }), + tens(in[3].data(), RAD_BF16, { tokens, H, D }), + tens(in[4].data(), RAD_BF16, { tokens, H }), + tens(alog.data(), RAD_F32, { H }), + tens(bias.data(), RAD_F32, { H * D }), + tens(state.data(), RAD_F32, { slots, H, D, D }), + tens(idx.data(), RAD_I32, { seqs, c.width }), + tens(cu.data(), RAD_I32, { seqs + 1 }), + tens(acc.data(), RAD_I32, { seqs }), + tens(init.data(), RAD_I32, { seqs }), + tens(out.data(), RAD_BF16, { tokens, H, D }) }; + RadParam p[10]{}; + p[0] = { "heads", RAD_P_INT, H }; + p[1] = { "head_k", RAD_P_INT, D }; + p[2] = { "head_v", RAD_P_INT, D }; + p[3].key = "lower_bound"; + p[3].kind = RAD_P_F64; + p[3].dval = -5; + p[4].key = "scale"; + p[4].kind = RAD_P_F64; + p[4].dval = 1.0 / std::sqrt(128.0); + p[5].key = "l2_eps"; + p[5].kind = RAD_P_F64; + p[5].dval = 1e-6; + p[6].key = "mode"; + p[6].kind = RAD_P_STR; + p[6].sval = c.mode; + p[7].key = "state_form"; + p[7].kind = RAD_P_STR; + p[7].sval = c.anchor ? "anchor" : "per_candidate"; + p[8].key = "dtype"; + p[8].kind = RAD_P_STR; + p[8].sval = "bf16"; + RadArgs a{}; + a.t = t; + a.n_t = 13; + a.p = p; + a.n_p = 9; + return r4d_rad_kda_update(&a, nullptr); + }; + std::vector ref_out, out; + std::vector ref_state, state; + setenv("RADIANCE_KDA_FORM", "old", 1); + if (run(ref_out, ref_state) != RAD_OK) { + std::printf("FAIL %s: old form refused\n", c.name); + ++fails; + continue; + } + unsetenv("RADIANCE_KDA_FORM"); + bool written = false; + for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777; + if (!written) { + std::printf("FAIL %s: the old form wrote no output\n", c.name); + ++fails; + } + for (const Form& f : forms) { + setenv("RADIANCE_KDA_ROWS", f.rows, 1); + setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1); + ++checks; + const bool same = run(out, state) == RAD_OK && out == ref_out && + std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0; + if (!same) { + ++fails; + std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n", + c.name, f.rows, f.prefetch); + } + } + unsetenv("RADIANCE_KDA_ROWS"); + unsetenv("RADIANCE_KDA_PREFETCH"); + } + std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails, + checks); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_mhc.cpp b/tests/r4d_emu/test_mhc.cpp new file mode 100644 index 00000000..82bd77e6 --- /dev/null +++ b/tests/r4d_emu/test_mhc.cpp @@ -0,0 +1,283 @@ +/* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator. + * Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the + * row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and + * comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots + * are zero. Every form is also held to the old dispatch, bit for bit. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include +#include + +static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = 2; + t.shape[0] = rows; + t.shape[1] = cols; + t.stride[0] = ld; + t.stride[1] = 1; + return t; +} +static RadTensor vec(void* p, int64_t n) { + RadTensor t{}; + t.data = p; + t.dtype = RAD_F32; + t.rank = 1; + t.shape[0] = n; + t.stride[0] = 1; + return t; +} + +int main() { + std::mt19937 rng(23); + std::normal_distribution nd(0.f, 1.f); + const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8; + std::vector fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix); + for (auto& v : fn) v = nd(rng) * 0.01f; + for (auto& v : base) v = nd(rng) * 0.5f; + struct Form { + const char* env; + const char* value; + }; + const Form forms[] = { { nullptr, nullptr }, + { "RADIANCE_MHC_PREFILL_COEFF4", "0" }, + { "RADIANCE_MHC_PREFILL_ROWS4", "0" }, + { "RADIANCE_MHC_PREFILL_WARP", "0" } }; + int fails = 0, cases = 0; + for (int64_t rows : { 1, 5, 37 }) { + const int64_t hp = W + 6, xp = n + 2; + std::vector h((size_t)(rows * hp)); + for (auto& v : h) v = f2b(nd(rng)); + for (const Form& f : forms) { + if (f.env) setenv(f.env, f.value, 1); + RadParam coef[8]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-5; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + std::vector x((size_t)(rows * xp), 0x7777); + std::vector post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc)); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(x.data(), RAD_BF16, rows, n, xp), + mat(post.data(), RAD_F32, rows, hc, hc), + mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) { + std::printf("FAIL mhc_pre M=%lld\n", (long long)rows); + ++fails; + continue; + } + for (int world : { 2, 4, 8 }) { + ++cases; + const int64_t mine = total / world; + std::vector gathered((size_t)(rows * total * S)); + bool padded = true, launched = true; + for (int rank = 0; rank < world; ++rank) { + std::vector part((size_t)(rows * mine * S), 7.0f); + RadTensor pt[3] = { t[0], t[1], + mat(part.data(), RAD_F32, rows, mine * S, mine * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, rank * mine }; + pp[5] = { "chunks", RAD_P_INT, mine }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + for (int64_t r = 0; r < rows; ++r) { + for (int64_t c = 0; c < mine; ++c) + for (int64_t j = mix + 1; j < S; ++j) + padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f; + std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)], + &part[(size_t)(r * mine * S)], (size_t)(mine * S * 4)); + } + } + std::vector x2((size_t)(rows * xp), 0x7777); + std::vector post2(post.size()), comb2(comb.size()); + RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S), + t[0], + t[2], + t[3], + mat(x2.data(), RAD_BF16, rows, n, xp), + mat(post2.data(), RAD_F32, rows, hc, hc), + mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadParam fp[8]; + std::memcpy(fp, coef, sizeof coef); + fp[6] = { "chunk", RAD_P_INT, 2048 }; + fp[7].key = "dtype"; + fp[7].kind = RAD_P_STR; + fp[7].sval = "bf16"; + RadArgs fa{}; + fa.t = ft; + fa.n_t = 7; + fa.p = fp; + fa.n_p = 8; + launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK; + const bool same = launched && x2 == x && + std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 && + std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0; + if (!same || !padded) { + std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world, + f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "", + !launched ? "launch" + : !padded ? "padding" + : "differs"); + ++fails; + } + } + if (f.env) unsetenv(f.env); + } + } + /* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read + * below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the + * vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's + * output, bit for bit. */ + struct Pin { + const char* what; + const char* finish; + const char* vec; + const char* prow; + }; + const Pin pins[] = { { "rule", nullptr, nullptr, nullptr }, + { "finish scalar", "scalar", nullptr, nullptr }, + { "partials four-slot, 1 row a wave", nullptr, "1", "1" }, + { "partials four-slot, 2 rows a wave", nullptr, "1", "2" }, + { "partials four-slot, 4 rows a wave", nullptr, "1", "4" } }; + auto pin = [](const char* k, const char* v) { + if (v) + setenv(k, v, 1); + else + unsetenv(k); + }; + for (int64_t rows : { 1, 5, 16, 37, 64 }) { + std::vector h((size_t)(rows * W)), y((size_t)(rows * n)); + for (auto& v : h) v = f2b(nd(rng)); + for (auto& v : y) v = f2b(nd(rng)); + RadParam coef[7]{}; + coef[0] = { "M", RAD_P_INT, rows }; + coef[1] = { "n", RAD_P_INT, n }; + coef[2] = { "hc", RAD_P_INT, hc }; + coef[3] = { "iterations", RAD_P_INT, 20 }; + coef[4].key = "eps"; + coef[4].kind = RAD_P_F64; + coef[4].dval = 1e-6; + coef[5].key = "hc_eps"; + coef[5].kind = RAD_P_F64; + coef[5].dval = 1e-6; + coef[6].key = "dtype"; + coef[6].kind = RAD_P_STR; + coef[6].sval = "bf16"; + struct Out { + std::vector x, o; + std::vector p, c, part; + }; + auto run = [&](Out* r) { + r->x.assign((size_t)(rows * n), 0x7777); + r->o.assign((size_t)(rows * W), 0x7777); + r->p.assign((size_t)(rows * hc), 0); + r->c.assign((size_t)(rows * hc * hc), 0); + r->part.assign((size_t)(rows * total * S), 7.0f); + RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W), + mat(fn.data(), RAD_F32, mix, W, W), + vec(scale.data(), 3), + vec(base.data(), mix), + mat(r->x.data(), RAD_BF16, rows, n, n), + mat(r->p.data(), RAD_F32, rows, hc, hc), + mat(r->c.data(), RAD_F32, rows, hc * hc, hc * hc) }; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = coef; + a.n_p = 7; + bool okay = r4d_rad_mhc_pre(&a, nullptr) == RAD_OK; + RadTensor pt[3] = { t[0], t[1], + mat(r->part.data(), RAD_F32, rows, total * S, total * S) }; + RadParam pp[7]{}; + pp[0] = { "M", RAD_P_INT, rows }; + pp[1] = { "n", RAD_P_INT, n }; + pp[2] = { "hc", RAD_P_INT, hc }; + pp[3] = { "chunk", RAD_P_INT, 2048 }; + pp[4] = { "first", RAD_P_INT, 0 }; + pp[5] = { "chunks", RAD_P_INT, total }; + pp[6].key = "dtype"; + pp[6].kind = RAD_P_STR; + pp[6].sval = "bf16"; + RadArgs pa{}; + pa.t = pt; + pa.n_t = 3; + pa.p = pp; + pa.n_p = 7; + okay = okay && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK; + RadTensor ot[5] = { mat(y.data(), RAD_BF16, rows, n, n), t[0], t[5], t[6], + mat(r->o.data(), RAD_BF16, rows, W, W) }; + RadArgs oa{}; + oa.t = ot; + oa.n_t = 5; + oa.p = coef; + oa.n_p = 7; + return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK; + }; + Out ref, got; + pin("RADIANCE_MHC_FINISH", "old"); + pin("RADIANCE_MHC_PARTIAL_VEC", "0"); + pin("RADIANCE_MHC_POST_VEC", "0"); + const bool ref_ok = run(&ref); + pin("RADIANCE_MHC_POST_VEC", nullptr); + for (const Pin& f : pins) { + ++cases; + pin("RADIANCE_MHC_FINISH", f.finish); + pin("RADIANCE_MHC_PARTIAL_VEC", f.vec); + pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow); + const bool launched = ref_ok && run(&got); + const char* bad = !launched ? "launch" + : got.x != ref.x ? "x" + : std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post" + : std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb" + : std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4) + ? "partials" + : got.o != ref.o ? "mhc_post" + : nullptr; + if (bad) { + std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n", + (long long)rows, f.what, bad); + ++fails; + } + } + for (const char* k : + { "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" }) + unsetenv(k); + } + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_mla.cpp b/tests/r4d_emu/test_mla.cpp new file mode 100644 index 00000000..fd8d5330 --- /dev/null +++ b/tests/r4d_emu/test_mla.cpp @@ -0,0 +1,408 @@ +/* Drives libr4d's MLA matrix row (r4d_mla.hip, attend_matrix) through the SIMT emulator and checks + * every output element against an f64 softmax over each row's own table. The cases put the paired + * tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk + * whose rows share one table, and rows past the DSA budget, where each row selects its own top + * blocks and neighbours share most blocks but rarely a table position. The conflict counters + * (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +extern "C" void r4d_mla_matrix_pin_form(int form); +extern "C" void r4d_mla_matrix_stats(unsigned long long* out); + +namespace { + +constexpr int D = 512, BS = 4; + +enum class Fill { prefill, topk, ragged, repeat }; + +struct Case { + std::string name; + int rows, heads, blocks; + Fill fill; + int swaps = 0; /* topk: blocks exchanged between neighbouring rows */ + int context = 0; /* topk: tokens of the sequence the rows end */ + bool scratch = false; /* lets the launcher split the history */ + int form = 0; /* r4d_mla_matrix_pin_form */ + int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */ + bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */ + bool bitwise_all = false; /* both requests do (the tables agree position by position) */ + bool union_falls_back = false; /* the table is wider than the union's lists */ +}; + +/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows .. + * context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher + * ones in block order and a short tie run after them, then the partial page. Row r's choice is row + * r-1's with `swaps` members exchanged for non-members. Pages are a fixed shuffle of the blocks. */ +void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng, + std::vector& bt, std::vector& len, int& pages) { + const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk); + pages = universe; + std::vector page(universe); + for (int i = 0; i < universe; ++i) page[i] = i; + std::shuffle(page.begin(), page.end(), rng); + std::vector in(universe, 0); + std::vector members; + auto tie_rank = [](int b) { return (uint32_t)b * 2654435761u ^ 0x9e3779b9u; }; + bt.assign((size_t)rows * blocks, -1); + len.assign(rows, 0); + for (int r = 0; r < rows; ++r) { + const int p = context - rows + r, n = (p + 1) / BS; + if (n <= topk) { + for (int b = 0; b < n; ++b) + if (!in[b]) { + in[b] = 1; + members.push_back(b); + } + } else { + while ((int)members.size() < topk) { + const int b = (int)(rng() % (unsigned)n); + if (!in[b]) { + in[b] = 1; + members.push_back(b); + } + } + for (int s = 0; s < swaps; ++s) { + int add; + do add = (int)(rng() % (unsigned)n); + while (in[add]); + const size_t drop = rng() % members.size(); + in[members[drop]] = 0; + members[drop] = add; + in[add] = 1; + } + } + std::vector order(members); + std::sort(order.begin(), order.end()); + if (n > topk) { + std::vector tied(order); + std::sort(tied.begin(), tied.end(), + [&](int a, int b) { return tie_rank(a) < tie_rank(b); }); + tied.resize(ties); + std::sort(tied.begin(), tied.end()); + order.erase(std::remove_if( + order.begin(), order.end(), + [&](int b) { return std::binary_search(tied.begin(), tied.end(), b); }), + order.end()); + order.insert(order.end(), tied.begin(), tied.end()); + } + int out = 0; + for (int b : order) bt[(size_t)r * blocks + out++] = page[b]; + if ((p + 1) % BS) bt[(size_t)r * blocks + out++] = page[n]; + len[r] = out ? (out - 1) * BS + p % BS + 1 : 0; + } +} + +int run(const Case& c, std::mt19937& rng) { + const int M = c.rows, H = c.heads, B = c.blocks; + std::vector bt, len; + int pages = 0; + if (c.fill == Fill::topk) { + topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages); + } else if (c.fill == Fill::prefill) { + /* one sequence, its rows the last M positions of the capacity, one table */ + pages = B + 1; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = (b * 7 + 3) % pages; + len[r] = B * BS - M + r + 1; + } + } else if (c.fill == Fill::repeat) { + /* every page twice in a row's table and shifted by one entry from row to row, so a page + * repeats within a table and between the pair */ + pages = M + B; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = ((b + r) / 2 * 5) % pages; + len[r] = B * BS - r % 3; + } + } else { + /* every row its own scattered table, with holes and out-of-range pages */ + pages = M * B; + bt.assign((size_t)M * B, -1); + len.assign(M, 0); + for (int r = 0; r < M; ++r) { + for (int b = 0; b < B; ++b) + bt[(size_t)r * B + b] = b % 17 == 3 ? -1 + : b % 19 == 5 ? pages + 3 + : (b * 7 + r * 11) % pages; + len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7; + } + } + std::normal_distribution nrm(0.f, 1.f); + std::vector qb((size_t)M * H * D), kvb((size_t)pages * BS * D); + for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng)); + for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng)); + std::vector out((size_t)M * H * D, 0xffff); + + auto tens = [](void* p, uint32_t dt, std::vector shape) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + t.shape[i] = shape[i]; + t.stride[i] = st; + st *= shape[i]; + } + return t; + }; + RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }), + tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }), + tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }), + tens(out.data(), RAD_BF16, { M, H, D }) }; + std::vector p; + auto pi = [&](const char* k, long long v) { + RadParam x{}; + x.key = k; + x.kind = RAD_P_INT; + x.ival = v; + p.push_back(x); + }; + auto pf = [&](const char* k, double v) { + RadParam x{}; + x.key = k; + x.kind = RAD_P_F64; + x.dval = v; + p.push_back(x); + }; + pi("M", M); + pi("latent_dim", D); + pi("heads", H); + pi("blocks", B); + pi("block_size", BS); + const double scale = 0.0625; + pf("scale", scale); + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p.data(); + a.n_p = (int)p.size(); + std::vector scratch; + if (c.scratch) { + const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a); + scratch.assign((size_t)need + 16, 0); + a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15); + a.scratch_bytes = need; + } + + /* the f64 reference */ + std::vector want((size_t)M * H * D); + std::vector sc; + for (int r = 0; r < M; ++r) + for (int h = 0; h < H; ++h) { + const int live = std::min(std::max(len[r], 0), B * BS); + sc.assign(live, -INFINITY); + double mx = -INFINITY; + auto row_of = [&](int j) -> const uint16_t* { + const int pg = bt[(size_t)r * B + j / BS]; + return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr; + }; + const uint16_t* qr = &qb[((size_t)r * H + h) * D]; + for (int j = 0; j < live; ++j) { + const uint16_t* k = row_of(j); + if (!k) continue; + double dot = 0; + for (int d = 0; d < D; ++d) + dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]); + sc[j] = dot * scale; + mx = std::max(mx, sc[j]); + } + std::vector acc(D, 0.0); + double sum = 0; + for (int j = 0; j < live; ++j) { + if (sc[j] == -INFINITY) continue; + const double w = std::exp(sc[j] - mx); + sum += w; + const uint16_t* k = row_of(j); + for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]); + } + for (int d = 0; d < D; ++d) + want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0; + } + + /* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the + * union, which must never take a second pass. */ + const bool paired = H % 16 == 8; + std::vector by_pos; + int fails = 0; + for (const char* pairing : { "pos", "union" }) { + if (!paired && !std::strcmp(pairing, "union")) break; + setenv("RADIANCE_MLA_PAIR", pairing, 1); + std::fill(out.begin(), out.end(), 0xffff); + unsigned long long stats[3]; + r4d_mla_matrix_stats(stats); + r4d_mla_matrix_pin_form(c.form); + const int rc = r4d_rad_mla_attn_matrix(&a, nullptr); + r4d_mla_matrix_pin_form(0); + r4d_mla_matrix_stats(stats); + unsetenv("RADIANCE_MLA_PAIR"); + if (rc != RAD_OK) { + std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc); + ++fails; + continue; + } + double max_err = 0; + long bad = 0; + for (size_t i = 0; i < out.size(); ++i) { + const float got = rad_bf16_to_f32(out[i]); + const double e = std::fabs(got - want[i]); + if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad; + if (std::isfinite(got)) max_err = std::max(max_err, e); + } + bool ok = bad == 0; + std::string note; + const bool by_page = !std::strcmp(pairing, "union"); + if (!by_page) { + by_pos = out; + if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) { + note += + c.expect_second ? " (expected a second pass)" : " (expected no second pass)"; + ok = false; + } + } else { + if ((stats[1] > 0) != c.union_falls_back) { + note += c.union_falls_back ? " (expected the positional fallback)" + : " (the union took a second pass)"; + ok = false; + } + /* Request r of each pair walks its own table in its own order, as the positional + * pairing does, so at one split it must agree to the bit; r+1 sums in another order. */ + size_t first_diff_a = 0, diff_b = 0; + double max_ab = 0; + for (int r = 0; r < M; ++r) + for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) { + if (out[i] == by_pos[i]) continue; + if (r % 2 == 0) + ++first_diff_a; + else + ++diff_b; + max_ab = std::max(max_ab, (double)std::fabs(rad_bf16_to_f32(out[i]) - + rad_bf16_to_f32(by_pos[i]))); + } + char buf[160]; + std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e", + first_diff_a, diff_b, max_ab); + note += buf; + if (c.bitwise_a && first_diff_a) { + note += " (request r differs)"; + ok = false; + } + if (c.bitwise_all && diff_b) { + note += " (request r+1 differs)"; + ok = false; + } + } + std::printf("%-40s %-5s M %3d H %2d blocks %3d passes %5llu raster %5llu second %5llu " + "max_abs %.2e bad %ld%s %s\n", + c.name.c_str(), pairing, M, H, B, stats[0], stats[2], stats[1], max_err, bad, + note.c_str(), ok ? "PASS" : "FAIL"); + fails += !ok; + } + return fails; +} + +/* The launcher prints the running totals every 1024th counted launch and must leave them + * standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */ +int periodic_report() { + std::vector q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D); + std::vector bt = { 0, 1 }, len = { 4, 3 }; + RadTensor t[5]{}; + auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector shape) { + x.data = p; + x.dtype = dt; + x.rank = (uint32_t)shape.size(); + int64_t st = 1; + for (int i = (int)shape.size() - 1; i >= 0; --i) { + x.shape[i] = shape[i]; + x.stride[i] = st; + st *= shape[i]; + } + }; + set(t[0], q.data(), RAD_BF16, { 2, 8, D }); + set(t[1], kv.data(), RAD_BF16, { 4, 1, BS, D }); + set(t[2], bt.data(), RAD_I32, { 2, 1 }); + set(t[3], len.data(), RAD_I32, { 2 }); + set(t[4], out.data(), RAD_BF16, { 2, 8, D }); + RadParam p[6]{}; + const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" }; + const long long vals[5] = { 2, D, 8, 1, BS }; + for (int i = 0; i < 5; ++i) { + p[i].key = keys[i]; + p[i].kind = RAD_P_INT; + p[i].ival = vals[i]; + } + p[5].key = "scale"; + p[5].kind = RAD_P_F64; + p[5].dval = 0.0625; + RadArgs a{}; + a.t = t; + a.n_t = 5; + a.p = p; + a.n_p = 6; + unsigned long long stats[3]; + r4d_mla_matrix_stats(stats); + for (int i = 0; i < 1024; ++i) + if (r4d_rad_mla_attn_matrix(&a, nullptr) != RAD_OK) { + std::printf("periodic report: launch failed\n"); + return 1; + } + r4d_mla_matrix_stats(stats); + const bool ok = stats[0] == 1024 && stats[2] == 1024 && stats[1] == 0; + std::printf("periodic report: %llu passes over %llu raster chunks after 1024 launches %s\n", + stats[0], stats[2], ok ? "PASS" : "FAIL"); + return ok ? 0 : 1; +} + +} // namespace + +int main(int argc, char** argv) { + setenv("RADIANCE_MLA_CONFLICT_STATS", "1", 1); + /* name, rows, heads, blocks, fill, swaps, context, scratch, form, expect_second, bitwise_a, + * bitwise_all, union_falls_back */ + std::vector cases = { + { "prefill, one table", 8, 8, 65, Fill::prefill, 0, 0, false, 0, 0, true, true }, + { "prefill, odd rows, split", 7, 8, 33, Fill::prefill, 0, 0, true, 0, 0, true, true }, + { "prefill, 16 heads", 4, 16, 33, Fill::prefill, 0, 0, false, 0, 0 }, + { "prefill, 24 heads (three pairs)", 5, 24, 17, Fill::prefill, 0, 0, false, 0, 0, true, + true }, + { "topk d=0", 8, 8, 65, Fill::topk, 0, 600, false, 0, 0, true, true }, + { "topk d=4", 8, 8, 65, Fill::topk, 4, 600, false, 0, 1 }, + { "topk d=16", 8, 8, 65, Fill::topk, 16, 600, false, 0, 1 }, + { "topk d=64 (disjoint neighbours)", 6, 8, 65, Fill::topk, 64, 600, false, 0, 1 }, + { "topk d=16, 513 blocks", 4, 8, 513, Fill::topk, 16, 8192, false, 0, 1 }, + /* a split cuts the union's walk elsewhere than the positional raster */ + { "topk d=4, odd rows, split", 5, 8, 33, Fill::topk, 4, 400, true, 0, 1, false }, + { "topk d=4, element load", 4, 8, 33, Fill::topk, 4, 400, false, 1, 1 }, + { "topk d=4, 16 heads", 4, 16, 33, Fill::topk, 4, 400, false, 0, 0 }, + { "topk, table past the union's lists", 4, 8, 600, Fill::topk, 16, 4000, false, 0, 1, true, + true, true }, + { "repeated pages", 6, 8, 33, Fill::repeat, 0, 0, false, 0, -1 }, + { "repeated pages, split", 3, 8, 33, Fill::repeat, 0, 0, true, 0, -1, false }, + { "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 }, + { "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false }, + }; + const char* filter = argc > 1 ? argv[1] : nullptr; + int fails = 0; + for (size_t i = 0; i < cases.size(); ++i) { + if (filter && cases[i].name.find(filter) == std::string::npos) continue; + std::mt19937 rng(20261018u + (unsigned)i); + fails += run(cases[i], rng); + } + if (!filter) fails += periodic_report(); + std::printf("%d failure(s)\n", fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_moefuse.cpp b/tests/r4d_emu/test_moefuse.cpp new file mode 100644 index 00000000..eb7a1da5 --- /dev/null +++ b/tests/r4d_emu/test_moefuse.cpp @@ -0,0 +1,614 @@ +/* tests/r4d_emu: GLM's decode fusions of the MoE block (r4d_glm.hip) on the host SIMT emulator, + * each byte for byte against the separate launches it replaces. + * + * router_sigmoid_topk_scatter against router_sigmoid_topk (the emulated kernel), then moe_scatter's + * stable counting sort over its ids written out here, then the `fill` of the shared gate with 1: + * random, tied and NaN ranks (a row with fewer finite ranks than top_k selects expert 0 for its + * empty slots, and the sort takes those as written), slices and protected experts, rows past 64 + * wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past + * every output and the gate's untouched rows show an overrun. + * + * swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes, + * scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the + * clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the + * sigmoid underflows, and NaN and infinite inputs. + * + * moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself + * without, and the inverse against the table the gather builds from `sorted`; then moe_gather's + * kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at + * GLM's f32 routing weights and bf16 ones, with the ungated shared arm, a sigmoid-gated one and + * none, and slices that drop slots. moe_scatter's three-pass form (T > 1024) is not here: its + * kernels take dynamic LDS through `extern __shared__`, which the emulator cannot give; the card + * checks it (r4d_selftest --case moe_scatter_inv_i32). */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include "r4d_moe_sort.h" +#include "r4d_moe_gather.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr int32_t kPoison = -77; +constexpr uint16_t kGatePoison = 0x7e57; + +/* moe_scatter's contract: slot i = token * top_k + slot goes to its expert's run in ascending i; + * an expert outside the slice drops the slot; protected experts are placed last in list order; + * sorted rows past the live count are -1. */ +struct SortModel { + std::vector sorted, off, cnt; +}; +int32_t place_of(int32_t e, int nl, const std::vector& prot) { + int32_t below = 0; + for (size_t j = 0; j < prot.size(); ++j) { + if (prot[j] == e) return nl - (int32_t)prot.size() + (int32_t)j; + below += prot[j] < e; + } + return e - below; +} +SortModel sort_model(const std::vector& ids, int M, int k, int ip, int nl, int base, + const std::vector& prot) { + const int T = M * k; + std::vector place((size_t)T); + SortModel s; + s.cnt.assign((size_t)nl, 0); + s.off.assign((size_t)nl + 1, 0); + s.sorted.assign((size_t)T, -1); + for (int i = 0; i < T; ++i) { + const int32_t e = ids[(size_t)(i / k) * ip + i % k] - base; + place[(size_t)i] = e >= 0 && e < nl ? place_of(e, nl, prot) : -1; + if (place[(size_t)i] >= 0) ++s.cnt[(size_t)place[(size_t)i]]; + } + for (int e = 0; e < nl; ++e) s.off[(size_t)e + 1] = s.off[(size_t)e] + s.cnt[(size_t)e]; + std::vector seen((size_t)nl, 0); + for (int i = 0; i < T; ++i) + if (place[(size_t)i] >= 0) { + const int32_t e = place[(size_t)i]; + s.sorted[(size_t)(s.off[(size_t)e] + seen[(size_t)e]++)] = i; + } + return s; +} + +/* The table the gather builds from `sorted` (gather_kernel's self-scan, or its prepass): slot + * sorted[p] at row p, every other slot -1. */ +std::vector inverse_of(const std::vector& sorted) { + std::vector inv(sorted.size(), -1); + for (size_t p = 0; p < sorted.size(); ++p) + if (sorted[p] >= 0) inv[(size_t)sorted[p]] = (int32_t)p; + return inv; +} + +/* moe_scatter's small-form kernel (r4d_moe_sort.h) over contiguous ids, with or without the + * inverse. */ +struct Scatter { + int rc = RAD_OK; + std::vector sorted, off, cnt, inv; +}; +Scatter scatter_kernel(const std::vector& ids, int nl, int base, const char* protect, + bool with_inv) { + const int T = (int)ids.size(); + Scatter s; + s.sorted.assign((size_t)T, kPoison); + s.off.assign((size_t)nl + 1, kPoison); + s.cnt.assign((size_t)nl, kPoison); + s.inv.assign((size_t)T, kPoison); + RadParam pp{}; + pp.key = "protect"; + pp.kind = RAD_P_STR; + pp.sval = protect; + RadArgs pa{}; + pa.p = &pp; + pa.n_p = protect ? 1 : 0; + r4d_moesort::Protect prot; + s.rc = r4d_moesort::protect_of(&pa, nl, &prot); + if (s.rc != RAD_OK) return s; + if (with_inv) + R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel), dim3(1), dim3(256), 0, + ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl, + (int32_t)base, prot, s.inv.data()); + else + R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel), dim3(1), dim3(256), 0, + ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl, + (int32_t)base, prot, (int32_t*)nullptr); + return s; +} + +struct RouterShape { + int M, ne, k, norm; + int mode; /* 0 random, 1 tied ranks, 2 NaN rows */ + int nl, base; /* the slice: nl 0 is the whole router */ + const char* protect; + bool gate; +}; + +void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) { + const RouterShape shapes[] = { + { 1, 288, 8, 1, 0, 0, 0, nullptr, true }, { 2, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 6, 288, 8, 1, 0, 0, 0, nullptr, true }, { 8, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 9, 288, 8, 1, 0, 0, 0, nullptr, false }, { 16, 288, 8, 1, 2, 0, 0, nullptr, true }, + { 17, 288, 8, 1, 0, 0, 0, nullptr, true }, { 24, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 33, 288, 8, 1, 0, 0, 0, nullptr, true }, { 48, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 48, 288, 8, 1, 2, 0, 0, nullptr, true }, { 65, 288, 8, 1, 1, 0, 0, nullptr, true }, + { 100, 288, 8, 0, 0, 0, 0, nullptr, true }, { 128, 288, 8, 1, 0, 0, 0, nullptr, true }, + { 24, 288, 8, 1, 0, 144, 144, nullptr, true }, { 24, 288, 8, 1, 1, 96, 32, "3,7,90", true }, + { 48, 512, 8, 1, 0, 0, 0, nullptr, true }, { 32, 32, 32, 0, 1, 0, 0, nullptr, true }, + { 5, 300, 10, 1, 2, 0, 0, "0,299", true }, + }; + std::uniform_int_distribution ud(-1000, 1000); + for (const RouterShape& sh : shapes) { + const int M = sh.M, ne = sh.ne, k = sh.k, T = M * k; + const int nl = sh.nl ? sh.nl : ne, base = sh.base; + const int lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1, gp = 3; + const float factor = 2.5f; + std::vector lg((size_t)M * lp), bias((size_t)ne * bp); + for (auto& v : lg) v = sh.mode == 1 ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200; + for (auto& v : bias) + v = sh.mode == 1 ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000; + if (sh.mode == 2) + for (int r = 0; r < M; r += 2) { + /* every other row keeps (r % 5) finite ranks, fewer than top_k */ + for (int e = 0; e < ne; ++e) lg[(size_t)r * lp + e] = NAN; + for (int j = 0; j < r % 5; ++j) + lg[(size_t)r * lp + (size_t)(ud(rng) + 1000) % ne] = 0.25f * (float)j; + } + std::vector prot; + if (sh.protect) + for (const char* p = sh.protect; *p;) { + char* end = nullptr; + prot.push_back((int)std::strtol(p, &end, 10)); + p = *end == ',' ? end + 1 : end; + } + + RadTensor t[8]{}; + t[0].data = lg.data(); + t[0].dtype = RAD_F32; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = ne; + t[0].stride[0] = lp; + t[0].stride[1] = 1; + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = bp; + t[2].dtype = RAD_I32; + t[2].rank = 2; + t[2].shape[0] = M; + t[2].shape[1] = k; + t[2].stride[0] = ip; + t[2].stride[1] = 1; + t[3].dtype = RAD_F32; + t[3].rank = 2; + t[3].shape[0] = M; + t[3].shape[1] = k; + t[3].stride[0] = wp; + t[3].stride[1] = 1; + t[4].dtype = RAD_I32; + t[4].rank = 1; + t[4].shape[0] = T; + t[4].stride[0] = 1; + t[5].dtype = RAD_I32; + t[5].rank = 1; + t[5].shape[0] = nl + 1; + t[5].stride[0] = 1; + t[6].dtype = RAD_I32; + t[6].rank = 1; + t[6].shape[0] = nl; + t[6].stride[0] = 1; + t[7].dtype = RAD_BF16; + t[7].rank = 2; + t[7].shape[0] = M; + t[7].shape[1] = 1; + t[7].stride[0] = gp; + t[7].stride[1] = 1; + std::vector p(9); + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, sh.norm }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = factor; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + p[6] = { "n_local", RAD_P_INT, nl }; + p[7] = { "expert_base", RAD_P_INT, base }; + p[8].key = "protect"; + p[8].kind = RAD_P_STR; + p[8].sval = sh.protect; + const int n_p = sh.protect ? 9 : 8; + + /* the separate launches: the selection, then the sort and fill modelled */ + std::vector ids_ref((size_t)M * ip, kPoison); + std::vector w_ref((size_t)M * wp, -7.25f); + t[2].data = ids_ref.data(); + t[3].data = w_ref.data(); + RadArgs sel{}; + sel.t = t; + sel.n_t = 4; + sel.p = p.data(); + sel.n_p = 6; + ++cases; + if (r4d_rad_router_sigmoid_topk(&sel, nullptr) != RAD_OK) { + std::printf("FAIL router_sigmoid_topk launch M=%d ne=%d\n", M, ne); + ++fails; + continue; + } + const SortModel ref = sort_model(ids_ref, M, k, ip, nl, base, prot); + /* moe_scatter's own kernel over the ids, contiguous as it reads them, held to the model; + * with the inverse, which must be the table the gather builds from `sorted`. */ + std::vector flat((size_t)T); + for (int i = 0; i < T; ++i) flat[(size_t)i] = ids_ref[(size_t)(i / k) * ip + i % k]; + Scatter ks = scatter_kernel(flat, nl, base, sh.protect, true); + ++cases; + if (ks.rc != RAD_OK || ks.sorted != ref.sorted || ks.off != ref.off || ks.cnt != ref.cnt || + ks.inv != inverse_of(ref.sorted)) { + std::printf("FAIL moe_scatter kernel against its model at M=%d ne=%d slice %d+%d\n", M, + ne, base, nl); + ++fails; + } + + for (int with_inv = 0; with_inv < 2; ++with_inv) { + std::vector ids((size_t)M * ip, kPoison), sorted((size_t)T + 4, kPoison), + off((size_t)nl + 5, kPoison), cnt((size_t)nl + 4, kPoison), + inv((size_t)T + 4, kPoison); + std::vector w((size_t)M * wp, -7.25f); + std::vector gate((size_t)(M + 2) * gp, kGatePoison); + RadTensor tf[9]; + std::memcpy(tf, t, sizeof t); + tf[2].data = ids.data(); + tf[3].data = w.data(); + tf[4].data = sorted.data(); + tf[5].data = off.data(); + tf[6].data = cnt.data(); + tf[7].data = sh.gate ? gate.data() : nullptr; + tf[8] = tf[4]; + tf[8].data = inv.data(); + RadArgs a{}; + a.t = tf; + a.n_t = with_inv ? 9 : 8; + a.p = p.data(); + a.n_p = n_p; + ++cases; + const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr); + int bad = 0; + bad += ids != ids_ref; + bad += std::memcmp(w.data(), w_ref.data(), w.size() * 4) != 0; + bad += std::memcmp(sorted.data(), ks.sorted.data(), (size_t)T * 4) != 0; + bad += std::memcmp(off.data(), ks.off.data(), (size_t)(nl + 1) * 4) != 0; + bad += std::memcmp(cnt.data(), ks.cnt.data(), (size_t)nl * 4) != 0; + if (with_inv) bad += std::memcmp(inv.data(), ks.inv.data(), (size_t)T * 4) != 0; + for (int i = 0; i < 4; ++i) + bad += sorted[(size_t)T + i] != kPoison || off[(size_t)nl + 1 + i] != kPoison || + cnt[(size_t)nl + i] != kPoison || inv[(size_t)T + i] != kPoison; + if (!with_inv) + for (int i = 0; i < T; ++i) bad += inv[(size_t)i] != kPoison; + for (int r = 0; r < M + 2; ++r) + for (int c = 0; c < gp; ++c) { + const uint16_t want = sh.gate && r < M && c == 0 ? 0x3f80 : kGatePoison; + bad += gate[(size_t)r * gp + c] != want; + } + if (rc != RAD_OK || bad) { + std::printf( + "FAIL router_sigmoid_topk_scatter at M=%d ne=%d k=%d mode %d slice %d+%d%s%s%s " + "(rc %d, %d mismatching outputs)\n", + M, ne, k, sh.mode, base, nl, sh.protect ? " protect " : "", + sh.protect ? sh.protect : "", with_inv ? " with inverse" : "", rc, bad); + ++fails; + } + } + } + /* Past the sort's one workgroup: refused, nothing written. */ + { + const int M = 129, ne = 288, k = 8; + std::vector lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f), + w((size_t)M * k, -7.25f); + std::vector ids((size_t)M * k, kPoison), sorted((size_t)M * k, kPoison), + off((size_t)ne + 1, kPoison), cnt((size_t)ne, kPoison); + RadTensor t[7]{}; + auto mat = [](RadTensor& x, void* d, uint32_t dt, int r, int c) { + x.data = d; + x.dtype = dt; + x.rank = 2; + x.shape[0] = r; + x.shape[1] = c; + x.stride[0] = c; + x.stride[1] = 1; + }; + auto vec = [](RadTensor& x, void* d, int n) { + x.data = d; + x.dtype = RAD_I32; + x.rank = 1; + x.shape[0] = n; + x.stride[0] = 1; + }; + mat(t[0], lg.data(), RAD_F32, M, ne); + t[1].data = bias.data(); + t[1].dtype = RAD_F32; + t[1].rank = 1; + t[1].shape[0] = ne; + t[1].stride[0] = 1; + mat(t[2], ids.data(), RAD_I32, M, k); + mat(t[3], w.data(), RAD_F32, M, k); + vec(t[4], sorted.data(), M * k); + vec(t[5], off.data(), ne + 1); + vec(t[6], cnt.data(), ne); + RadParam p[6]{}; + p[0] = { "M", RAD_P_INT, M }; + p[1] = { "n_expert", RAD_P_INT, ne }; + p[2] = { "top_k", RAD_P_INT, k }; + p[3] = { "norm", RAD_P_INT, 1 }; + p[4].key = "route_scale"; + p[4].kind = RAD_P_F64; + p[4].dval = 2.5; + p[5].key = "dtype"; + p[5].kind = RAD_P_STR; + p[5].sval = "f32"; + RadArgs a{}; + a.t = t; + a.n_t = 7; + a.p = p; + a.n_p = 6; + ++cases; + const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr); + if (rc == RAD_OK || ids[0] != kPoison || sorted[0] != kPoison) { + std::printf("FAIL router_sigmoid_topk_scatter served M*top_k=%d past the sort's bound " + "(rc %d)\n", + M * k, rc); + ++fails; + } + } +} + +struct QuantShape { + int M, n; + float limit; + int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */ + bool y; /* the fused op also writes the bf16 product */ +}; + +void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) { + const QuantShape shapes[] = { + { 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false }, + { 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true }, + { 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true }, + { 2, 260, 0.5f, 2, false }, + }; + std::normal_distribution nd(0.f, 1.f); + std::uniform_int_distribution ud(0, 15); + for (const QuantShape& sh : shapes) { + const int M = sh.M, n = sh.n, nkb = (n + 127) / 128; + const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3; + std::vector gu((size_t)M * gp, f2b(-3.f)); + const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1); + for (int r = 0; r < M; ++r) + for (int c = 0; c < 2 * n; ++c) { + float v = nd(rng) * 6.f; + uint16_t h = f2b(v); + if (sh.mode == 1) { + const int pick = ud(rng); + if (pick == 0) + h = lim; + else if (pick == 1) + h = past; + else if (pick == 2) + h = (uint16_t)(lim | 0x8000u); + else if (pick == 3) + h = (uint16_t)(past | 0x8000u); + else if (pick == 4) + h = f2b(-200.f); + /* rows divisible by 3 hold an all-zero first group */ + if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0; + } else if (sh.mode == 2) { + const int pick = ud(rng); + if (pick == 0) + h = 0x7fc0; /* NaN */ + else if (pick == 1) + h = 0x7f80; /* +inf */ + else if (pick == 2) + h = 0xff80; /* -inf */ + } + gu[(size_t)r * gp + c] = h; + } + RadTensor t[4]{}; + t[0].data = gu.data(); + t[0].dtype = RAD_BF16; + t[0].rank = 2; + t[0].shape[0] = M; + t[0].shape[1] = 2 * n; + t[0].stride[0] = gp; + t[0].stride[1] = 1; + auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) { + x.dtype = dt; + x.rank = 2; + x.shape[0] = r; + x.shape[1] = c; + x.stride[0] = pitch; + x.stride[1] = 1; + }; + RadParam pc[4]{}; + pc[0] = { "M", RAD_P_INT, M }; + pc[1] = { "n", RAD_P_INT, n }; + pc[2].key = "limit"; + pc[2].kind = RAD_P_F64; + pc[2].dval = sh.limit; + pc[3].key = "dtype"; + pc[3].kind = RAD_P_STR; + pc[3].sval = "bf16"; + RadParam pq[4]{}; + pq[0] = { "M", RAD_P_INT, M }; + pq[1] = { "n", RAD_P_INT, n }; + pq[2] = { "group", RAD_P_INT, 128 }; + pq[3].key = "dtype"; + pq[3].kind = RAD_P_STR; + pq[3].sval = "bf16"; + RadParam pf[5]{}; + pf[0] = pc[0]; + pf[1] = pc[1]; + pf[2] = pc[2]; + pf[3] = pq[2]; + pf[4] = pc[3]; + + std::vector y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57); + std::vector q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5); + std::vector s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f); + RadTensor tc[2] = { t[0], {} }; + mat(tc[1], RAD_BF16, M, n, yp); + tc[1].data = y_ref.data(); + RadArgs ac{}; + ac.t = tc; + ac.n_t = 2; + ac.p = pc; + ac.n_p = 4; + RadTensor tq[3] = { tc[1], {}, {} }; + mat(tq[1], RAD_F8E4M3, M, n, qp); + tq[1].data = q_ref.data(); + mat(tq[2], RAD_F32, M, nkb, sp); + tq[2].data = s_ref.data(); + RadArgs aq{}; + aq.t = tq; + aq.n_t = 3; + aq.p = pq; + aq.n_p = 4; + ++cases; + if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK || + r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) { + std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n); + ++fails; + continue; + } + RadTensor tf[4] = { t[0], {}, {}, {} }; + mat(tf[1], RAD_F8E4M3, M, n, qp); + tf[1].data = q.data(); + mat(tf[2], RAD_F32, M, nkb, sp); + tf[2].data = s.data(); + mat(tf[3], RAD_BF16, M, n, yp); + tf[3].data = sh.y ? y.data() : nullptr; + RadArgs af{}; + af.t = tf; + af.n_t = 4; + af.p = pf; + af.n_p = 5; + const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr); + int bad = 0; + bad += q != q_ref; + bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0; + if (sh.y) + bad += y != y_ref; + else + for (uint16_t v : y) bad += v != 0x7e57; + if (rc != RAD_OK || bad) { + std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d " + "mismatching outputs)\n", + M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad); + ++fails; + } + } +} + +struct GatherShape { + int M, n, nl, base; + bool f32w; /* GLM's f32 routing weights, else bf16 */ + int shared; /* 0 none, 1 the ungated arm (gate 1, act none), 2 a sigmoid gate */ +}; + +/* moe_gather's kernel (r4d_moe_gather.h) as its launcher runs it, reading the table moe_scatter_inv + * wrote, against the same kernel building the table itself from `sorted` (T <= 512) or reading the + * prepass's table (above). Ids are distinct per row from 288 experts, a slice drops slots. */ +void gather_inverse_cases(std::mt19937& rng, int& cases, int& fails) { + const GatherShape shapes[] = { + { 1, 4096, 288, 0, true, 1 }, { 6, 4096, 288, 0, true, 1 }, { 8, 512, 288, 0, true, 1 }, + { 24, 512, 144, 72, true, 1 }, { 48, 256, 288, 0, true, 1 }, { 64, 256, 288, 0, true, 0 }, + { 100, 256, 96, 0, true, 1 }, { 6, 300, 288, 0, false, 2 }, { 33, 256, 288, 0, false, 0 }, + }; + const int k = 8, ne = 288; + std::normal_distribution nd(0.f, 1.f); + for (const GatherShape& sh : shapes) { + const int M = sh.M, n = sh.n, T = M * k, nl = sh.nl; + std::vector ids((size_t)T); + for (int r = 0; r < M; ++r) { + std::vector pool(ne); + for (int e = 0; e < ne; ++e) pool[(size_t)e] = e; + std::shuffle(pool.begin(), pool.end(), rng); + for (int j = 0; j < k; ++j) ids[(size_t)(r * k + j)] = pool[(size_t)j]; + } + Scatter plain = scatter_kernel(ids, nl, sh.base, nullptr, false); + Scatter inv = scatter_kernel(ids, nl, sh.base, nullptr, true); + ++cases; + if (plain.rc != RAD_OK || inv.rc != RAD_OK || inv.sorted != plain.sorted || + inv.off != plain.off || inv.cnt != plain.cnt || inv.inv != inverse_of(plain.sorted)) { + std::printf("FAIL moe_scatter with the inverse at M=%d slice %d+%d\n", M, sh.base, nl); + ++fails; + continue; + } + const int ye_ld = n + 3, ew_ld = k + 2, y_ld = n + 5, sh_ld = n + 1, sg_ld = 2; + std::vector ye((size_t)T * ye_ld), shp((size_t)M * sh_ld), sg((size_t)M * sg_ld); + for (auto& v : ye) v = f2b(nd(rng)); + for (auto& v : shp) v = f2b(nd(rng)); + for (size_t i = 0; i < sg.size(); ++i) sg[i] = sh.shared == 1 ? f2b(1.f) : f2b(nd(rng)); + std::vector ewf((size_t)M * ew_ld); + std::vector ewb((size_t)M * ew_ld); + for (size_t i = 0; i < ewf.size(); ++i) { + ewf[i] = std::fabs(nd(rng)) * 0.3f; + ewb[i] = f2b(ewf[i]); + } + const void* ew = sh.f32w ? (const void*)ewf.data() : (const void*)ewb.data(); + const uint16_t* shv = sh.shared ? shp.data() : nullptr; + const uint16_t* sgv = sh.shared ? sg.data() : nullptr; + const int sig = sh.shared == 2; + const bool small = T <= (int)r4d_moegather::kGatherSelfT; + /* the launcher's rule: the self-scan up to 512 slots, the prepass's table above */ + const std::vector table = inverse_of(plain.sorted); + const unsigned gy = (unsigned)((n + 255) / 256); + auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector& y) { + y.assign((size_t)M * y_ld, 0x7e57); + if (sh.f32w) + R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, true>), dim3((unsigned)M, gy), + dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n, + (uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted, + (uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + else + R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, false>), dim3((unsigned)M, gy), + dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n, + (uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted, + (uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig); + }; + std::vector y_old, y_new; + if (small) + gather(nullptr, plain.sorted.data(), y_old); + else + gather(table.data(), nullptr, y_old); + gather(inv.inv.data(), nullptr, y_new); + ++cases; + if (y_new != y_old) { + size_t first = 0; + while (first < y_new.size() && y_new[first] == y_old[first]) ++first; + std::printf("FAIL moe_gather from the inverse at M=%d n=%d slice %d+%d %s weights, " + "shared %d: first difference at %zu\n", + M, n, sh.base, nl, sh.f32w ? "f32" : "bf16", sh.shared, first); + ++fails; + } + } +} + +} // namespace + +int main() { + std::mt19937 rng(23); + int fails = 0, cases = 0; + router_scatter_cases(rng, cases, fails); + swiglu_quant_cases(rng, cases, fails); + gather_inverse_cases(rng, cases, fails); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +} diff --git a/tests/r4d_emu/test_moemx.cpp b/tests/r4d_emu/test_moemx.cpp new file mode 100644 index 00000000..1ef630ce --- /dev/null +++ b/tests/r4d_emu/test_moemx.cpp @@ -0,0 +1,482 @@ +/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form + * the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit, + * and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group + * a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * + * E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, + * dropped slots inside runs and past the routed rows, columns an odd expert does not have, a + * shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes + * and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and + * column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column + * blocks past N and the output through LDS at aligned and odd pitches. The table decode is also + * held to the arithmetic one over every code. */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "r4d_mxfp4.h" +#include +#include +#include +#include +#include +#include +#include + +extern const char* emu_last_kernel; + +/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its + * byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */ +static uint32_t fp4x4_ref(uint32_t n) { + const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u; + const uint32_t mask = (flag << 5) - (flag >> 3); + return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) | + ((n & 0x08080808u) << 4); +} +static int check_decode() { + int fails = 0; + auto one = [&](uint32_t w) { + const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu); + const uint32_t lo_ref = __byte_perm(low, high, 0x5140), + hi_ref = __byte_perm(low, high, 0x7362); + uint32_t lo, hi, tlo, thi; + r4d_mxfp4_unpack8_exact(w, &lo, &hi); + r4d_mxfp4_unpack8(w, 0, &tlo, &thi); + if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) { + if (fails < 4) + std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi, + lo, hi_ref, lo_ref); + ++fails; + } + /* each byte against the e2m1 value it encodes */ + for (int e = 0; e < 8; ++e) { + const uint32_t c = (w >> (4 * e)) & 15u; + static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f }; + const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u]; + const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu); + if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) { + if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b); + ++fails; + } + } + }; + /* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves + * of the word, and random words over all four */ + for (uint32_t v = 0; v < 65536; ++v) { + one(v); + one(v << 16); + one(v << 8); + } + std::mt19937 rng(7); + for (int i = 0; i < 200000; ++i) one((uint32_t)rng()); + return fails; +} + +struct Case { + const char* name; + int N, K, N_odd, K_odd, parts, top; + bool sorted_a, tables, exceptional; + std::vector runs; + int tail; // dropped slots past the routed rows +}; + +/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative + * default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap; + * the card generates the positive quiet NaN, so a NaN's sign carries no information here. */ +static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); } +static size_t first_diff(const std::vector& a, const std::vector& b) { + for (size_t i = 0; i < a.size() && i < b.size(); ++i) + if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i; + return a.size() == b.size() ? a.size() : std::min(a.size(), b.size()); +} +static bool same16(const std::vector& a, const std::vector& b) { + return a.size() == b.size() && first_diff(a, b) == a.size(); +} + +static RadTensor ten(void* p, uint32_t dt, std::vector shape, + std::vector stride) { + RadTensor t{}; + t.data = p; + t.dtype = dt; + t.rank = (uint32_t)shape.size(); + for (size_t i = 0; i < shape.size(); ++i) { + t.shape[i] = shape[i]; + t.stride[i] = stride[i]; + } + return t; +} + +int main() { + int fails = check_decode(), cases = 1; + if (fails) std::printf("FAIL table decode: %d mismatches\n", fails); + + const std::vector runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 }; + const Case all[] = { + { "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 }, + { "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9, + 2 }, + { "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 }, + { "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 }, + { "decode band, row groups of 4", + 64, + 384, + 64, + 384, + 2, + 2, + false, + true, + false, + { 0, 1, 15, 16, 17, 30 }, + 3 }, + { "decode band, row groups of 1", + 64, + 256, + 32, + 256, + 1, + 2, + true, + false, + true, + { 1, 0, 3, 15, 1 }, + 2 }, + { "P64 jobs at 32 and 64 rows, N under a block", + 96, + 512, + 96, + 384, + 1, + 2, + false, + false, + false, + { 32, 33, 31, 96, 128, 129, 0, 2 }, + 9 }, + { "P64 resident A, column tiles cut", + 192, + 256, + 128, + 128, + 2, + 4, + true, + true, + true, + { 64, 63, 65, 1, 0, 127, 17 }, + 5 }, + }; + struct Form { + const char* env; + int stage, tiles, lut; + const char* kernel; + bool prefill; + bool pipe = false; + }; + /* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */ + const Form forms[] = { + { "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false }, + { "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false }, + { "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false }, + { "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false }, + { "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false }, + { "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false }, + { "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false }, + { "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false }, + { "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false }, + { "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true }, + { "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, + { "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true }, + { "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true }, + { "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true }, + { "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true }, + { "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true }, + { "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel", true, true }, + { "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel", true, true }, + }; + /* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS + * output at the default; the K of a case picks streamed or resident A. */ + struct P64 { + int bm, bn, sk, ct, out, db = 0; + }; + std::vector p64s; + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) + for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 }); + p64s.push_back({ 64, 128, 128, 4, 1 }); + p64s.push_back({ 32, 64, 256, 1, 1 }); + /* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with + * resident A, the single-buffer form runs. */ + for (int bm : { 32, 64 }) + for (int bn : { 64, 128 }) + for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 }); + p64s.push_back({ 64, 128, 128, 4, 1, 1 }); + static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP", + "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN", + "RADIANCE_MXFP4_PREFILL_P64_BM", + "RADIANCE_MXFP4_PREFILL_P64_BN", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_K", + "RADIANCE_MXFP4_PREFILL_P64_COLTILES", + "RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", + "RADIANCE_MXFP4_PREFILL_P64_T_BM64", + "RADIANCE_MXFP4_PREFILL_P64_T_BN128", + "RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", + "RADIANCE_MXFP4_PREFILL_P64_DB" }; + /* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are + * under all of them); the widest tiles take the LDS output. */ + struct Rule { + const char* t_bm64; + const char* t_bn128; + const char* t_down; + const char* streamed; + const char* resident; + }; + const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>", + "<32, 64, 128, 4, true>" }, + { "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" }, + { "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } }; + static const char* const kEnv[] = { + "RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS", + "RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32", + "RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS" + }; + + for (const Case& c : all) { + const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd); + int routed = 0; + for (int r : c.runs) routed += r; + const int T = (routed + c.tail + c.top - 1) / c.top * c.top; + // An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row. + const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1, + yp = OUT + ((&c - all) % 2 ? 5 : 8); + std::mt19937 rng(1000 + cases); + std::normal_distribution nd(0.f, 1.f); + std::uniform_real_distribution oct(-6.f, 6.f); + std::vector a((size_t)Arows * ap); + for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f); + std::vector as((size_t)Arows * asp); + for (auto& v : as) v = std::exp2(oct(rng)); + std::vector offsets(E + 1, 0), sorted(T, -1), owner(T, -1); + for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e]; + for (int e = 0; e < E; ++e) + for (int r = offsets[e]; r < offsets[e + 1]; ++r) { + owner[r] = e; + // A dropped slot about every eleventh row, the first rows of some runs included. + sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T); + } + const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd }, + nexp[2] = { (E + 1) / 2, E / 2 }; + std::vector w[2], s[2]; + std::vector wt[2], st[2]; + for (int q = 0; q < 2; ++q) { + w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2); + s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32); + for (auto& v : w[q]) v = (uint8_t)rng(); + static const uint8_t special[] = { 0, 255, 1, 254, 127 }; + for (size_t i = 0; i < s[q].size(); ++i) + s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5] + : (uint8_t)(118 + rng() % 16); + for (int x = 0; x < nexp[q]; ++x) { + wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2); + st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32); + } + } + auto plane = [&](int q, bool scale) { + const int64_t cols = scale ? k[q] / 32 : k[q]; + void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data()) + : (void*)(scale ? s[q].data() : w[q].data()); + RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols }, + { c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 }); + return t; + }; + + /* the per-element sequence, on the host */ + std::vector ref((size_t)T * yp, 0x7777); + for (int r = 0; r < T; ++r) + for (int col = 0; col < OUT; ++col) { + uint16_t& out = ref[(size_t)r * yp + col]; + out = 0; + if (owner[r] < 0 || sorted[r] < 0) continue; + const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top; + const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw; + const bool valid = within < cw; + const int wn = (col / pw) * cw + within; + const uint8_t* wr = + w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2; + const uint8_t* sr = + s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32; + float total = 0.f; + for (int kb = 0; kb < k[q]; kb += 128) + for (int g = 0; g < 4; ++g) { + float raw = 0.f; + for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) { + const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u; + uint32_t lo, hi; + r4d_mxfp4_unpack8_exact(code, &lo, &hi); + raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) * + rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu)); + } + const uint32_t x = valid ? sr[kb / 32 + g] : 127u; + uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u; + float scale; + std::memcpy(&scale, &bits, 4); + float t = raw * as[(size_t)ar * asp + kb / 128]; + t = t * scale; + total = total + t; + } + uint32_t u; + std::memcpy(&u, &total, 4); + out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> + 16); // f32_to_bf16, r4d_common.h + } + + RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }), + ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }), + plane(0, false), + plane(0, true), + ten(sorted.data(), RAD_I32, { T }, { 1 }), + ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }), + plane(1, false), + plane(1, true), + RadTensor{} }; + RadParam p[11]{}; + auto pi = [](const char* key, long long v) { + RadParam x{}; + x.key = key; + x.kind = RAD_P_INT; + x.ival = v; + return x; + }; + auto ps = [](const char* key, const char* v) { + RadParam x{}; + x.key = key; + x.kind = RAD_P_STR; + x.sval = v; + return x; + }; + p[0] = pi("M", T / c.top); + p[1] = pi("N", c.N); + p[2] = pi("K", c.K); + p[3] = pi("N_odd", c.N_odd); + p[4] = pi("K_odd", c.K_odd); + p[5] = pi("n_expert", E); + p[6] = pi("top_k", c.top); + p[7] = pi("parts", c.parts); + p[8] = pi("group", 128); + p[9] = ps("a_order", c.sorted_a ? "sorted" : "token"); + p[10] = ps("dtype", "mxfp4a8"); + auto run = [&](const Form& f, std::vector& y) { + y.assign((size_t)T * yp, 0x7777); + t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 }); + for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1); + if (f.stage) { + setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1); + setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1); + } + setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1); + setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1); + RadArgs ar{}; + ar.t = t; + ar.n_t = 9; + ar.p = p; + ar.n_p = 11; + emu_last_kernel = ""; + return r4d_rad_moe_mxfp4(&ar, nullptr); + }; + auto run_p64 = [&](const P64& f, std::vector& y) { + const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out }; + for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1); + setenv(kP64[11], f.db ? "1" : "0", 1); + const Form base = { "000000", 0, 0, 1, "", false }; + const int rc = run(base, y); + setenv(kP64[0], "0", 1); + return rc; + }; + const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false }; + std::vector legacy, got; + ++cases; + int rc = run(alt, legacy); + if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) { + std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel); + ++fails; + continue; + } + if (!same16(legacy, ref)) { + const size_t i = first_diff(legacy, ref); + std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: " + "%04x, want %04x\n", + c.name, i / yp, i % yp, legacy[i], ref[i]); + ++fails; + } + int live = 0; + for (uint16_t v : ref) live += v != 0 && v != 0x7777; + if (live < T * OUT / 3) { + std::printf("FAIL %s: output mostly zero\n", c.name); + ++fails; + } + for (const Form& f : forms) { + if (f.prefill && T < 512) continue; + ++cases; + rc = run(f, got); + const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr; + if (rc != RAD_OK || !reached || !same16(got, legacy)) { + const size_t i = first_diff(got, legacy); + std::printf( + "FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first " + "word %zu\n", + c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i); + ++fails; + } + } + const bool resident = NK <= 256; + for (const Rule& u : rules) { + ++cases; + for (const char* v : kP64) unsetenv(v); + setenv(kP64[0], "1", 1); + setenv(kP64[1], "0", 1); + setenv(kP64[2], "0", 1); + if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1); + if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1); + if (u.t_down) setenv(kP64[10], u.t_down, 1); + const Form base = { "000000", 0, 0, 1, "", false }; + rc = run(base, got); + for (const char* v : kP64) unsetenv(v); + const std::string want = + std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed); + if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) || + !same16(got, legacy)) { + std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name, + emu_last_kernel, want.c_str(), rc, first_diff(got, legacy)); + ++fails; + } + } + for (const P64& f : p64s) { + ++cases; + rc = run_p64(f, got); + const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64)); + const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " + + std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " + + (resident ? std::to_string(f.ct) : "1") + ", " + + (resident ? "true" : "false") + (db ? ", true>" : ">"); + const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr; + if (rc != RAD_OK || !reached || !same16(got, legacy)) { + const size_t i = first_diff(got, legacy); + std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want " + "%s), rc %d, " + "first word %zu (row %zu col %zu: %04x, want %04x)\n", + c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel, + want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0, + i < legacy.size() ? legacy[i] : 0); + ++fails; + } + } + } + for (const char* v : kEnv) unsetenv(v); + for (const char* v : kP64) unsetenv(v); + unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K"); + unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES"); + unsetenv("RADIANCE_MXFP4_LUT"); + unsetenv("RADIANCE_MXFP4_PREFILL_PIPE"); + std::printf("%d case(s), %d failure(s)\n", cases, fails); + return fails ? 1 : 0; +}