Archived
libr4d: GLM-5.3's kernels -- mHC, KDA, the DSA indexer, MLA, f32-scaled FP8, MXFP4 experts
The device rows for GLM-5.3-Flash's ops, at its geometry and at TP4 and TP8 slices: - mhc_pre / mhc_post / mhc_contract, and mhc_pre_partial / mhc_pre_finish, which run mhc_pre's own projection and finishing kernels with its chunk-sum order, so the pair is byte-identical to mhc_pre at n 4096, hc 4, chunk 2048. - kda_update_k128_v128_bf16, one, two or four value rows a wave, both state forms. - dsa_pool_fp8, dsa_query_fp8 and dsa_score_fp8 (fp8 WMMA, 32 heads of 128). - mla_attn: a matrix row whose WMMA tile holds a query's heads, or pairs eight heads of two neighbouring queries over the union of their page tables, above the wave row; mla_project with up to eight rows a thread or wave. - gemm_nt_f32 and router_sigmoid_topk in tiled and one-wave-a-row forms; gemm_fp8a8_f32scale and moe_gemm_fp8a8_f32scale read f32 block scales in place; moe_gemm_mxfp4a8 decodes e2m1 into exact E4M3 bytes for fp8 WMMA, with an expert-major decode form and a wide prefill form. - swiglu_clamped, and the device-only fusions of GLM's MoE block: swiglu_clamped_quant_fp8, router_sigmoid_topk_scatter, and moe_scatter_inv / moe_gather_inv, which pass the gather's slot table from the sort instead of rebuilding it. moe_gather takes f32 routing weights in its column-per-thread kernel. The sort and the gather kernels move from r4d_moe.hip into r4d_moe_sort.h and r4d_moe_gather.h, so the fused router and gather instantiate the same code. Every form that replaces another gives its bytes: tests/r4d_emu runs the kernels on the host (test_f32, test_fp8f32, test_kda, test_mhc, test_mla, test_moefuse, test_moemx), r4d_selftest compares them on a card against libref and against each other, and plugin_test pins the mla_attn band. docs/OPS.md states what libr4d serves. Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com>
This commit is contained in:
1 parent
da77f86332
commit
78c58841bf
31 files changed
+12371
-302
No files matched your search
+123
@@ -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
|
||||
|
||||
@@ -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|"
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
#include <hip/hip_runtime.h>
|
||||
#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 <climits>
|
||||
|
||||
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<false>(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 <int kScoreTiles>
|
||||
__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<NT>), 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<false>(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);
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_launch.h"
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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 <bool Grouped>
|
||||
__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 <int StageK>
|
||||
struct F8Stage {
|
||||
static constexpr int KB = StageK / 128;
|
||||
f8_u4 a[StageK / 128], w[StageK / 32];
|
||||
float wsc[KB], sa;
|
||||
};
|
||||
template <int StageK, int ColTiles>
|
||||
__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<StageK>;
|
||||
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<f8_u4*>(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<f8_u4*>(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<StageK>(qa, 0, k, lane),
|
||||
r4d_fp8::frag<StageK>(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 <int R, int C>
|
||||
__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 <int R>
|
||||
__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 R>
|
||||
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<R>,
|
||||
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<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(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<R_, C_>), 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<SK, C>), \
|
||||
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<true>, 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<false>, 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.
|
||||
}
|
||||
+87
-1
@@ -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)
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_moe_sort.h"
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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 <int R, int C>
|
||||
__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 R, int C>
|
||||
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<R, C>),
|
||||
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<R, C>(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 <int OWN>
|
||||
__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 <int OWN>
|
||||
__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<OWN>(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 <int OWN, uint32_t NW, bool INV>
|
||||
__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<NW> 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<OWN>(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<NW, INV>(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<OWN, NW, INV>), 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);
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_emit.h"
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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 <bool Dpp>
|
||||
__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 <bool Dpp>
|
||||
__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<Dpp>(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<KdaMeta&>(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 <int R, bool Prefetch>
|
||||
__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<KdaMeta&>(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 <class Pitch>
|
||||
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<false>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j))
|
||||
: R4D_EMIT(stream, kda_replay_kernel<true>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(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<KdaMeta>(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<RR, PF>), 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<KdaMeta>(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); }
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_emit.h"
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
|
||||
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<float*>((reinterpret_cast<uintptr_t>(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 <class Out>
|
||||
__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 <class Out>
|
||||
__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 <class Out>
|
||||
__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<const uint4*>(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<uint4*>(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 <class Out, int R>
|
||||
__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<const float4*>(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<const uint2*>(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 <class In, bool VecX>
|
||||
__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 <class In>
|
||||
__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 <class In>
|
||||
__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 <class In>
|
||||
__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<const uint4*>(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<uint4*>(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 <class Out>
|
||||
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<Out, RR>), \
|
||||
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<Out>),
|
||||
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<Out>),
|
||||
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<Out>),
|
||||
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 <class In>
|
||||
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<In>), 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<In>), 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<In, false>), 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<In, true>), 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);
|
||||
}
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_gdn_wmma.h"
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <atomic>
|
||||
|
||||
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 <int R>
|
||||
__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 <int R>
|
||||
__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<RR>), dim3(4, h, groups), dim3(128), 0, \
|
||||
xp, wp, yp, m); \
|
||||
return R4D_EMIT(stream, (project_expand_rows<RR>), 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 <bool PAIR, bool WIDE, bool UNION, bool STATS>
|
||||
__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<unsigned> 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 <bool MATRIX>
|
||||
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<P, W, U, S>), 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<false>(a, stream);
|
||||
}
|
||||
extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
|
||||
return body<true>(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);
|
||||
}
|
||||
+90
-254
@@ -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 <hip/hip_bf16.h>
|
||||
|
||||
@@ -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 <uint32_t NW>
|
||||
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 <uint32_t NW>
|
||||
__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<NW>& 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<kScatWaves> 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 <bool INV>
|
||||
__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 <uint32_t NTHR>
|
||||
__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<true>, 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<false>, 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<true>, 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<false>, 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);
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
#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 <bool F32>
|
||||
__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 <uint32_t NTHR, bool F32 = false>
|
||||
__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<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] = gather_weight<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] : gather_weight<F32>(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
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
#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 <uint32_t NW>
|
||||
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 <uint32_t NW, bool INV = false>
|
||||
__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<NW>& 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 <bool INV>
|
||||
__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<kScatWaves> 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<kScatWaves, INV>(sorted, off, cnt, T, n_expert, sl, inv);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace r4d_moesort
|
||||
@@ -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
|
||||
|
||||
@@ -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*);
|
||||
|
||||
@@ -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",
|
||||
|
||||
+4129
-31
File diff suppressed because it is too large.
Load diff
@@ -66,6 +66,7 @@
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <algorithm>
|
||||
#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,
|
||||
|
||||
+20
-13
@@ -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.
|
||||
|
||||
@@ -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"; }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "rad_plugin.h"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
@@ -47,11 +48,12 @@ struct Sched {
|
||||
std::vector<Fiber> 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];
|
||||
|
||||
@@ -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 <class T>
|
||||
inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
|
||||
template <class T>
|
||||
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 */
|
||||
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
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<int> 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<float> 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<int>& ids, std::vector<float>& 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<int> ids_old, ids_new;
|
||||
std::vector<float> 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<float> 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<uint16_t> x((size_t)M * xp);
|
||||
std::vector<float> 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<float>& 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<float> 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;
|
||||
}
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
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<float> 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<uint8_t> 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<float> 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<float> 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<uint16_t>& 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<uint16_t> 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;
|
||||
}
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> 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<int> cu, idx, accepted, init;
|
||||
std::vector<std::pair<int64_t, float>> counts;
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(41);
|
||||
std::uniform_real_distribution<float> u(-1.f, 1.f);
|
||||
const int64_t H = 2, D = 128, slots = 16, tokens = 9;
|
||||
std::vector<float> 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<uint16_t> 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<Case> 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<float> 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<int> idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init;
|
||||
auto run = [&](std::vector<uint16_t>& out, std::vector<float>& 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<uint16_t> ref_out, out;
|
||||
std::vector<float> 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;
|
||||
}
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
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<float> 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<float> 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<uint16_t> 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<uint16_t> x((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> 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<float> gathered((size_t)(rows * total * S));
|
||||
bool padded = true, launched = true;
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
std::vector<float> 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<uint16_t> x2((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> 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<uint16_t> 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<uint16_t> x, o;
|
||||
std::vector<float> 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;
|
||||
}
|
||||
@@ -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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<int>& bt, std::vector<int>& len, int& pages) {
|
||||
const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk);
|
||||
pages = universe;
|
||||
std::vector<int> page(universe);
|
||||
for (int i = 0; i < universe; ++i) page[i] = i;
|
||||
std::shuffle(page.begin(), page.end(), rng);
|
||||
std::vector<char> in(universe, 0);
|
||||
std::vector<int> 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<int> order(members);
|
||||
std::sort(order.begin(), order.end());
|
||||
if (n > topk) {
|
||||
std::vector<int> 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<int> 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<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> 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<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
|
||||
auto tens = [](void* p, uint32_t dt, std::vector<int64_t> 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<RadParam> 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<char> 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<double> want((size_t)M * H * D);
|
||||
std::vector<double> 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<double> 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<uint16_t> 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<uint16_t> q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D);
|
||||
std::vector<int> bt = { 0, 1 }, len = { 4, 3 };
|
||||
RadTensor t[5]{};
|
||||
auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector<int64_t> 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<Case> 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;
|
||||
}
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<int32_t> sorted, off, cnt;
|
||||
};
|
||||
int32_t place_of(int32_t e, int nl, const std::vector<int>& 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<int32_t>& ids, int M, int k, int ip, int nl, int base,
|
||||
const std::vector<int>& prot) {
|
||||
const int T = M * k;
|
||||
std::vector<int32_t> 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<int32_t> 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<int32_t> inverse_of(const std::vector<int32_t>& sorted) {
|
||||
std::vector<int32_t> 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<int32_t> sorted, off, cnt, inv;
|
||||
};
|
||||
Scatter scatter_kernel(const std::vector<int32_t>& 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<true>), 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<false>), 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<int> 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<float> 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<int> 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<RadParam> 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<int32_t> ids_ref((size_t)M * ip, kPoison);
|
||||
std::vector<float> 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<int32_t> 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<int32_t> 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<float> w((size_t)M * wp, -7.25f);
|
||||
std::vector<uint16_t> 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<float> lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f),
|
||||
w((size_t)M * k, -7.25f);
|
||||
std::vector<int32_t> 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<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> 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<uint16_t> 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<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
|
||||
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
|
||||
std::vector<float> 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<float> 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<int32_t> ids((size_t)T);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
std::vector<int32_t> 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<uint16_t> 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<float> ewf((size_t)M * ew_ld);
|
||||
std::vector<uint16_t> 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<int32_t> table = inverse_of(plain.sorted);
|
||||
const unsigned gy = (unsigned)((n + 255) / 256);
|
||||
auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector<uint16_t>& 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<uint16_t> 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;
|
||||
}
|
||||
@@ -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 <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<int> 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<uint16_t>& a, const std::vector<uint16_t>& 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<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
return a.size() == b.size() && first_diff(a, b) == a.size();
|
||||
}
|
||||
|
||||
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
|
||||
std::vector<int64_t> 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<int> 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<false>", true, true },
|
||||
{ "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel<true>", 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<P64> 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<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
|
||||
std::vector<float> as((size_t)Arows * asp);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> 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<uint8_t> w[2], s[2];
|
||||
std::vector<const void*> 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<uint16_t> 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<uint16_t>& 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<uint16_t>& 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<uint16_t> 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;
|
||||
}
|
||||
Reference in new issue
Block a user