merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across

conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
gearwave00001 committed 2026-10-24 19:03:26 -05:00
commit 7c3b5ab7d5
285 files changed
+30500 -2898

No files matched your search

+12 -3
View File
@@ -46,6 +46,9 @@ set(R4D_UNITS
"r4d_attn_paged_h256_gqa2|"
# Gemma 3 sliding window: head_dim 128, 2 queries per KV head, windowed decode and prefill.
"r4d_attn_paged_h128_gqa2w|"
# One query head per KV head at 128 wide: plain MHA, the Unlimited-OCR decoder (10 over 10).
# Both legs, prefill and decode; see the file's header for why it is not a drafter-shaped unit.
"r4d_attn_paged_h128_gqa1|"
# Eight queries per KV head, one body instantiated at head_dim 256 (the routed 35B-A3B) and 128
# (MiniCPM5-2B).
"r4d_attn_paged_gqa8|"
@@ -57,9 +60,10 @@ set(R4D_UNITS
# gqa6, head_dim 256, 4-token page: the same QSA layers at four ranks, each KV head replicated
# across a rank pair.
"r4d_attn_paged_h256_gqa6_bs4|"
# head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel per geometry
# covers every q_len and reads q at any row pitch (attn_paged_qrow).
# head_dim 128/256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers and Unlimited-OCR's h128 MHA
# decoder. One kernel per geometry covers every q_len and reads q at any row pitch
# (attn_paged_qrow).
"r4d_attn_paged_window|"
# Two queries per KV head at head_dim 128 only (Qwen3-1.7B's 16 over 8, Qwen3-ASR's decoder):
# the gqa8 body with the ratio set.
@@ -68,6 +72,8 @@ set(R4D_UNITS
# An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and
# the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening.
"r4d_attn_dense_bf16|"
# Unlimited-OCR's SAM tower: windowed attention with decomposed relative position.
"r4d_sam_attn_bf16|"
"r4d_encoder_bf16|"
# The image generator: attention over a paged prefix plus the pass's own rows, the causal
# head_dim-128 dense form and the 1152-wide decoder head; plus the sampler, adaptive norm,
@@ -142,6 +148,7 @@ set(R4D_UNITS
"r4d_gemm_mxfp4a8_nt_m64|"
"r4d_gemm_mxfp4a8_tiled|"
"r4d_gemm_mxfp4a8_decode|"
"r4d_gemm_mxfp4a8_gemv|"
# Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the
# checkpoint, and the entry points reject a mismatch.
"r4d_gemm_fp8a16_nt_m1|"
@@ -158,6 +165,8 @@ set(R4D_UNITS
"r4d_sample_chain_f32|"
"r4d_model_bf16|"
"r4d_sample_stages_f32|"
# The windowed no-repeat-ngram ban: one block a row over the row's history.
"r4d_sample_ngram_f32|"
"r4d_quant_act_i8|"
"r4d_rmsnorm_quant_i8|"
"r4d_qkv_norm_rope|"
+124
View File
@@ -52,7 +52,10 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny |
| `gemm_w2a8_nt` | 2-bit weight against int8 activation: the DFlash2 draft head |
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
| `gemm_mxfp4a8_gemv` | the same operands for one to eight rows: the weight streamed straight to registers, no LDS staging; WMMA when K is a multiple of 128, `v_dot4` otherwise, chosen from K alone so a row's bits do not depend on M |
| `gemm_mxfp4a8_gemv_wide` | its WMMA form at 9..64 rows: up to four 16-row tiles a wave over each weight word, two 16-column tiles a block on wide, deep weights |
| `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch |
| `gemm_mxfp4a8_decode_shortk` | the decode kernel at 33..64 rows of a wide, short weight (N ≥ 8192, K ≤ 2560), above `gemm_mxfp4a8_gemv_wide`, which loses there |
| `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block |
| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window: a block-diffusion drafter's geometry. Decode only; there is no prefill row at this geometry |
| `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage |
@@ -110,6 +113,127 @@ diverge by about 1 ULP.
6. Add a case to `libr4d/r4d_selftest.cpp` so the row is called at least once; a row without one
reports `no smoke case`.
## The OCP-MXFP4 GEMM by row count
`gemm_nt_q` at `mxfp4a8` has six rows over one stored weight (the skinny kernel's fragment-order
codes, `[K/32][N]` E8M0 exponents and a per-row reference exponent), so the selector moves between
them by M with no second copy. Each needs N a multiple of 16 and K of 64; of those whose
constraints hold, the highest priority serves:
| row | band | priority |
| --- | --- | --- |
| `gemm_mxfp4a8_decode_shortk` | 33 ≤ M ≤ 64, 8192 ≤ N ≤ 36864, K ≤ 2560 | 59 |
| `gemm_mxfp4a8_gemv` | M ≤ 8 | 58 |
| `gemm_mxfp4a8_gemv_wide` | 9 ≤ M ≤ 64, K a multiple of 128 | 58 |
| `gemm_mxfp4a8_decode` | M ≤ 128, N ≤ 36864 | 55 |
| `gemm_mxfp4a8_nt_m64` | M ≤ 64 | 50 |
| `gemm_mxfp4a8_tiled` | any M | 30 |
One stream's decode (M = 1 + the draft depth) takes `gemv`; several streams with speculation land
in `gemv_wide` (4 × (1 + 7) = 32 rows, 16 × (1 + 3) = 64); `decode` keeps 65..128 rows, and 9..64
where K is not a multiple of 128; `tiled` takes the rest. Unless stated, times are one rank's
weight of Qwen3.8-27B or TranslateGemma 27B at TP2 on an R9700, each row alone (`r4d_selftest
--perfmxd`). Over 16 per-rank shapes of other models and card counts (Qwen3.8-27B at TP4 and TP8,
1B-, 4B- and 8B-class dense at TP1 and TP2, a 31B-class at TP4), M 1..128, the selection below
against the better of the decode and skinny rows before it: median -10.3%, mean -10.6% over 192
cells.
**`gemm_mxfp4a8_gemv`** (M ≤ 8). One stream's decode is a pure weight stream, and staging the
weight through LDS left narrow projections at a third to two thirds of DRAM bandwidth. This row
loads each weight word straight into registers and folds it to e4m3 there: WMMA from register
fragments when K is a multiple of 128, `v_dot4` otherwise. The form and the waves a block depend on
K alone, so a row's bits do not depend on M, and a verify step's first row is the plain decode of
it (`r4d_selftest` checks the first row's bits against M). The scale and reference planes must be
4-byte aligned.
**`gemm_mxfp4a8_gemv_wide`** (9..64 rows, K a multiple of 128). The WMMA form with up to four 16-row
tiles a wave: each weight word of a chunk is loaded and folded once and multiplied with every
tile's activation fragment, so the weight streams once whatever the row count. A row's sum is its
tile's WMMA chain alone, so its bits are `gemv`'s at every M (except in the `decode_shortk` corner,
where the decode kernel serves 33..64 rows). From 25 rows, where N ≥ 4096, K ≥ 3072 and the tile
count is even, a block carries two 16-column tiles: the activation is read per block, and with one
tile a 64-row activation was read N/16 times (356 MB from L2 on a 17408-row gate_up, against a 47 MB
weight). On narrower or shallower weights two tiles lost 4..37 % (fewer blocks than the part has
units, a short K a wave), so they stay at one. Against the decode row that served 9..64 rows
before, in µs: Qwen down 51-80 against 56-105, ssm_out 27-42 against 30-55, q|gate 40-63 against
44-74; TranslateGemma down 61-97 against 66-123, o 22-35 against 25-51; gate_up at 24-48 rows
110-141 against 145-170. With two tiles a block, 17408 × 5120 at 32 rows 125 → 85 µs and at 64
157 → 122, 21504 × 5376 154 → 111 and 183 → 150.
**`gemm_mxfp4a8_decode_shortk`** (33..64 rows, 8192 ≤ N ≤ 36864, K ≤ 2560). The decode row's
kernel, scratch hook and tunables at priority 59, above `gemv_wide`. On a short K a `gemv_wide`
block's three or four row tiles make its cross-wave reduction outweigh its WMMAs, and a wide N
makes many such blocks. Over 24 per-rank shapes (Qwen3.8 and TranslateGemma at TP1, 2, 4 and 8,
and 1B- to 8B-class dense) at 24..64 rows, `gemv_wide` matched or beat the previous decode kernel
everywhere but this corner, where it lost by 7..30 %; there this row wins:
| shape, 64 rows | `gemv_wide` | previous decode kernel | `decode_shortk` |
| --- | --- | --- | --- |
| 19456 × 2560 | 131.8 µs | 104.5 | 93.3 |
| 16384 × 2048 | 92.8 | 76.1 | 68.6 |
| 9728 × 2560 | 74.1 | 67.4 | 52.5 |
Narrower N stays with `gemv_wide` (5120 × 2176 at 40 rows 39.2 µs against 52.8), as do Qwen3.8-27B's
and TranslateGemma's two-rank shapes. It is a row rather than a rule inside the gemv entry so that
the choice stays a lookup over constraints, and `--debug-selection` names it.
**`gemm_mxfp4a8_decode`** (65..128 rows, and 9..64 where K is not a multiple of 128). Past 16 rows
each wave loads its weight words straight into registers, as `gemv` does (a fragment-order word is
the WMMA fragment's register), and only the shared activation is double-buffered in LDS, one
barrier a slab. The fold, k-step, slab order, scale carry and epilogue are unchanged, and the whole
output was compared byte for byte with the LDS-staged kernel's (312 cases, 17..128 rows, both scale
grids, forced splits): 17408 × 5120 at 96 rows 205 → 159 µs, at 128 245 → 214; 5120 × 8704 at 128
169 → 139; 6144 × 5120 at 128 121 → 92. The split and slab rule past 64 rows was then re-tuned for
this kernel: the 128-wide slab always, and a split only while every split keeps 16 slabs, towards a
48-block grid or, at K ≥ 8192, regardless, up to ks·M = 1024 split rows. At 80 / 96 / 128 rows:
17408 × 5120 161 / 187 / 215 → 161 / 175 / 197 µs, 5120 × 3072 71 / 79 / 67 → 55 / 60 / 69, 21504 ×
5376 192 / 207 / 228 → 187 / 200 / 217. A different split sums a row in a different order, so at
65..128 rows the re-tuned rule moves output bits within the selftest's bound. Up to 64 rows the
decode kernel's bits are as they were.
**Bits against the rows these replace.** `gemv` and `gemv_wide` sum a row in their own order (the
K split over eight waves and 128-wide chunks), not the decode kernel's split-K order, so at 1..64
rows their outputs differ from the decode row's in the last bf16 place on a few elements in ten
thousand (within the selftest's bound). A greedy text can therefore differ from one produced
with the decode row at those rows. Within the family a row's bits do not depend on M, as above.
**Tunables.** `gemv` and `gemv_wide` have none, so a `RADIANCE_TUNE` pin on `gemm_nt_q` passes
them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of
those reaches both. A pin applies to every row serving the op, and an axis a serving row lacks
stops startup by name.
## The OCP-MXFP4 tiled GEMM (prefill)
**`gemm_mxfp4a8_tiled`** (`gemm_nt_q` at `mxfp4a8`, the rows past the decode band). TN = 4 (256 ×
128 blocks) from 1024 rows (it was 2048), unless its blocks would number under 128: at the
crossover Qwen3.8-27B's gate_up -2 %, down -3 %, TranslateGemma 27B's gate_up -9 %, its down +1 %,
and at 1536 rows all four better; TranslateGemma's 1024-row chunks run there. The weight words a
thread stages are loaded into registers a slab ahead, right after the staging barrier, so their
DRAM round trip runs under the slab's WMMAs (+1 VGPR at TN = 4, no spills). At 1024 rows Qwen
gate_up 804 → 768 µs, down 443 → 417, ssm_in 396 → 384, ssm_out 249 → 231, q|gate 306 → 318;
TranslateGemma gate_up 1063 → 1029, down 651 → 617; at 2048 rows 0..-4 %; a 41k-token Qwen3.8-27B
prefill on two cards 8.57 → 8.28 s. A thin last row of blocks (1..160 rows, M under 1024) runs a
second kernel whose blocks of that row skip the WMMAs of fragments past M, where the plain kernel
computes them on clamped copies (half the only block's math at 129 rows); every other M runs the
plain kernel, whose code is instruction for instruction the single kernel's from before the split
(a guard inside the one kernel cost full blocks 1..15 %). Same-session A/B over 12 shapes: M
129..160 -8..-20 %, 320..384 -2..-16 % (Qwen gate_up at 320 rows 402 → 339 µs, TranslateGemma's 513
→ 441). Each of the three keeps the fold, the WMMAs and their order per output byte. Times are one
rank's weight at TP2 on an R9700, the row alone, clocks warmed; over 20 shapes, M 129..2048: median
-7.4 % over 140 cells, none slower beyond run-to-run noise.
`tn` (0 the rule, 2, 4) pins the TN choice through `RADIANCE_TUNE`.
## The fp8 and int8 heads past 64 rows
**`logits_gemm_fp8`, `logits_gemm_i8`** took passes of 64 rows and read the head again for each.
With `MH` = 2 a workgroup's eight waves split into two M halves of four 16-row tiles over 64 weight
rows that share one staged tile, so a pass takes 128 rows and reads the head once. Qwen3.8's
per-rank head (124160 × 5120) at 128 rows 3059 → 1984 µs, TranslateGemma's (131072 × 5376) 3242 →
2036; 65..128 rows -33..-39 %, 160..256 -26..-37 %, 64 and fewer unchanged; about 1 ms a step at 16
streams with speculation. Same scale blocks, WMMAs and K order per output: the same bytes (the
numeric cases at 65..150 rows for the fp8 head, 100 for the int8 head).
## Notes on the kernels
Three properties of the architecture are assumed throughout and not restated per kernel:
+12 -3
View File
@@ -454,9 +454,10 @@ void r4d_ar_twoshot_8rank_exact(long peer_scratch0, long peer_scratch1, long pee
const int* shard_weights, long pieces, long timeline,
long form);
// `form` is R4D_AR8_FORM_* (r4d_ar_shards.h), the same on every rank: lockstep, ring or split,
// all with the same bits. `timeline`, a diagnostic, is 0 or a device buffer of nblocks * R4D_AR_TL_WORDS int64 that every
// block of the eight-rank two-shot fills with wall-clock stamps (r4d_ar_wide.h): its start, each
// handshake's arrival and release, its end. r4d_selftest --perfar8 with --timeline reads it.
// all with the same bits. `timeline`, a diagnostic, is 0 or a device buffer of
// nblocks * R4D_AR_TL_WORDS int64 that every block fills with wall-clock stamps (r4d_ar_wide.h):
// its start, each handshake's arrival and release, its end. r4d_selftest --perfar8 --timeline
// reads it.
// The tiered int8 wire on both two-shot hops (r4d_ar_twoshot_Nrank_ti8.hip; codec in
// r4d_ar_ti8.h), 3 or 4 ranks. Int8 groups of 32 with an fp16 scale and a per-group record
// (T1 plain, T2 top-1-exact, T3 wht32), 38 bytes/group; tiering is deterministic and
@@ -688,11 +689,19 @@ void r4d_hc_read_pin_prefill(int form);
// 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: pins the MLA rows row's form. 0 is the launcher's rule (64 heads a workgroup, vector
// key loads where aligned; the matrix row's kernel under 32 rows), 1 the element-wise key load
// (bit-identical to 3), 2 32 heads a workgroup, 3 the rows kernel of the rule at any row count.
void r4d_mla_rows_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
// of its own, so a pin that is ignored cannot pass by comparing a form with itself.
int r4d_record_dispatches(const void** fns, int cap);
// Test hook: the eight-rank two-shot's settings (r4d_ar_shards.h) for instances built after the
// call; null restores the engine's. r4d_selftest checks weighted and empty shards, fixed piece
// counts and the size floors with it, and --perfar8 --ar8-weights times another board's weights.
void r4d_ar8_test_settings(const struct R4DAr8Settings* s);
// The narrow GEMM with r4d_gated_quant_fp8 as its epilogue, for a gate_up projection whose only
// consumer is that quantiser. `wq` is the [2*nout][K] gate_up plane, gate first; outputs are the
// quantiser's: `q` E4M3 [M][nout], `s` f32 [M][ceil(nout/128)], and `y` the bf16 silu product or 0.
+55 -152
View File
@@ -35,8 +35,6 @@
static_assert(R4D_AR_TWOSHOT_WIDE_MAX_ELEMS == 268435456,
"r4d_rows.cpp restates this bound; libr4d changed it");
static_assert(R4D_MAX_RANKS == 8, "the 8-rank entry point names exactly seven peers");
static_assert((long long)R4D_AR8_MIN_ELEMS_MAX == (long long)R4D_AR_TWOSHOT_WIDE_MAX_ELEMS,
"r4d_ar_shards.h restates the two-shot band's top");
/* ------------------------------------------------------------------ throw conversion
*
@@ -72,16 +70,8 @@ struct Rendezvous {
long flags [R4D_MAX_RANKS] = { 0 };
long seq [R4D_MAX_RANKS] = { 0 };
int dev [R4D_MAX_RANKS] = { 0 };
/* What each rank read for the eight-rank two-shot: settings that must agree, and its own
* card's link, which the weights are derived from. */
struct Ar8Seen {
int mode = 0;
int w[R4D_MAX_RANKS] = { 0 };
int pieces = 0;
long long weights_min = 0, pieces_min = 0;
int form = 0;
R4DArLink link;
} ar8[R4D_MAX_RANKS];
/* Each rank's card's link, which the eight-rank two-shot's weights are derived from. */
R4DArLink ar8_link[R4D_MAX_RANKS];
int failed = 0;
};
@@ -129,14 +119,12 @@ struct ArInst {
* scratch was sized for them and a recorded launch keeps its table. */
int shard_weighted = 0;
int shard_w[R4D_MAX_RANKS] = { 0 };
/* Its piece count (RADIANCE_AR8_PIECES), 0 for the size rule (r4d_ar8_auto_pieces); a launch's
* `pieces` parameter overrides it. */
/* Its piece count, 0 for the size rule (r4d_ar8_auto_pieces); a launch's `pieces` parameter
* overrides it. */
int pieces = 0;
/* Messages under these sizes (elements) run even and in one piece, whatever is configured. */
long long weights_min = R4D_AR8_MIN_ELEMS_DEFAULT;
long long pieces_min = R4D_AR8_MIN_ELEMS_DEFAULT;
/* Its form (RADIANCE_AR8_FORM); a launch's `form` parameter overrides it. */
int form = R4D_AR8_FORM_LOCKSTEP;
};
/* A parameter that may be declared as a range: init gets one band's frozen geometry, and buffers
@@ -153,25 +141,14 @@ long long pgeti_hi(const RadParam* p, int n_p, const char* k, long long dflt) {
long align16(long v) { return (v + 15) & ~15L; }
/* RADIANCE_AR8_SHARD_WEIGHTS, read at every eight-rank build so a process can change it between
* instances: unset or "auto" derives the weights from the links by r4d_ar_weights_from_rates,
* "duplex" from the same links by r4d_ar_weights_duplex, "off" keeps the shards even, eight
* integers set them. Anything else is "off", with one warning. */
enum { AR8_EVEN = 0, AR8_SET = 1, AR8_AUTO = 2, AR8_DUPLEX = 3 };
int ar8_weights_mode(int* w) {
const char* e = std::getenv(R4D_AR8_SHARD_WEIGHTS_ENV);
if (!e || !*e || !std::strcmp(e, "auto")) return AR8_AUTO;
if (!std::strcmp(e, "duplex")) return AR8_DUPLEX;
if (!std::strcmp(e, "off")) return AR8_EVEN;
if (r4d_ar_shard_weights_parse(e, 8, w)) return AR8_SET;
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs auto, off or eight non-negative "
"integers, comma-separated, sum > 0, or duplex); eight-rank two-shot shards "
"stay even\n",
R4D_AR8_SHARD_WEIGHTS_ENV, e);
});
return AR8_EVEN;
/* The eight-rank two-shot's settings for the next build: the engine's defaults unless
* r4d_ar8_test_settings set others. */
std::mutex g_ar8_m;
R4DAr8Settings g_ar8;
R4DAr8Settings ar8_settings() {
std::lock_guard<std::mutex> lk(g_ar8_m);
return g_ar8;
}
/* This rank's card's slowest PCIe hop, from sysfs by the runtime's bus id. */
@@ -188,53 +165,6 @@ bool ar8_own_link(R4DArLink* l) {
return r4d_ar_link_bottleneck("", bdf, l);
}
/* RADIANCE_AR8_PIECES and the two size floors, read like the weights. */
int ar8_pieces() {
const char* e = std::getenv(R4D_AR8_PIECES_ENV);
if (!e || !*e) return 0;
long long v = 0;
if (!r4d_ar_parse_count(e, R4D_AR_TS_MAX_PIECES, &v) || v < 1) {
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 1..%d); the eight-rank "
"two-shot takes its piece count from the message size\n",
R4D_AR8_PIECES_ENV, e, (int)R4D_AR_TS_MAX_PIECES);
});
return 0;
}
return (int)v;
}
long long ar8_min_elems(const char* name, std::once_flag* said) {
const char* e = std::getenv(name);
if (!e || !*e) return R4D_AR8_MIN_ELEMS_DEFAULT;
long long v = 0;
if (!r4d_ar_parse_count(e, R4D_AR8_MIN_ELEMS_MAX, &v)) {
std::call_once(*said, [name, e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs 0..%d elements); using %d\n",
name, e, (int)R4D_AR8_MIN_ELEMS_MAX,
(int)R4D_AR8_MIN_ELEMS_DEFAULT);
});
return R4D_AR8_MIN_ELEMS_DEFAULT;
}
return v;
}
/* RADIANCE_AR8_FORM: lockstep (or unset), ring or split. Anything else is lockstep, with one
* warning. */
int ar8_form() {
const char* e = std::getenv(R4D_AR8_FORM_ENV);
if (!e || !*e) return R4D_AR8_FORM_LOCKSTEP;
const int f = r4d_ar8_form_parse(e);
if (f >= 0) return f;
static std::once_flag said;
std::call_once(said, [e] {
std::fprintf(stderr, "[r4d] %s=\"%s\" ignored (needs lockstep, ring or split); the "
"eight-rank two-shot runs in lockstep\n", R4D_AR8_FORM_ENV, e);
});
return R4D_AR8_FORM_LOCKSTEP;
}
/* The eight-rank two-shot's choice for one message, a function of its size and the instance
* alone: a recorded launch keeps the table and piece count it was recorded with, and replays of
* the same size agree with it. */
@@ -246,86 +176,58 @@ long long ar8_pieces_for(const ArInst* in, long numel, long long asked) {
return asked > 0 ? asked : r4d_ar8_auto_pieces(numel);
}
/* The eight-rank two-shot's settings, agreed before anything is sized: each rank publishes what
* it read and its own card's link, and after one barrier every rank derives the same weights from
* the same eight entries. Settings that differ between ranks would cut the message at different
* words or take different handshake steps; all ranks compare the same entries, so all refuse
* together. */
/* The eight-rank two-shot's settings, fixed before anything is sized: each rank publishes its own
* card's link, and after one barrier every rank derives the same weights from the same eight
* entries. */
int ar8_settle(ArInst* in, int rank, int world) {
static std::once_flag said_w, said_p, said_links, said_unknown, said_set;
Rendezvous::Ar8Seen me;
me.mode = ar8_weights_mode(me.w);
me.pieces = ar8_pieces();
me.weights_min = ar8_min_elems(R4D_AR8_SHARD_WEIGHTS_MIN_ENV, &said_w);
me.pieces_min = ar8_min_elems(R4D_AR8_PIECES_MIN_ENV, &said_p);
me.form = ar8_form();
if ((me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) && !ar8_own_link(&me.link))
me.link = R4DArLink();
static std::once_flag said_links, said_unknown, said_set;
const R4DAr8Settings set = ar8_settings();
R4DArLink own;
if (set.weights == R4D_AR8_WEIGHTS_AUTO && !ar8_own_link(&own)) own = R4DArLink();
{
std::lock_guard<std::mutex> lk(g_rv.m);
g_rv.ar8[rank] = me;
g_rv.ar8_link[rank] = own;
}
const int rc = rv_barrier(world);
if (rc != RAD_OK) return rc;
const Rendezvous::Ar8Seen* all = g_rv.ar8;
for (int r = 0; r < world; ++r)
if (all[r].mode != me.mode || std::memcmp(all[r].w, me.w, sizeof(me.w)) ||
all[r].pieces != me.pieces || all[r].weights_min != me.weights_min ||
all[r].pieces_min != me.pieces_min || all[r].form != me.form) {
std::fprintf(stderr, "[r4d] ranks %d and %d read different eight-rank two-shot "
"settings (%s, %s and their _MIN_ELEMS, %s)\n", rank, r,
R4D_AR8_SHARD_WEIGHTS_ENV, R4D_AR8_PIECES_ENV, R4D_AR8_FORM_ENV);
return RAD_E_STATE;
}
in->pieces = me.pieces;
in->weights_min = me.weights_min;
in->pieces_min = me.pieces_min;
in->form = me.form;
if (me.form != R4D_AR8_FORM_LOCKSTEP) {
static std::once_flag said_form;
const int f = me.form;
std::call_once(said_form, [f] {
std::fprintf(stderr, "[r4d] eight-rank two-shot form: %s (%s)\n",
f == R4D_AR8_FORM_RING ? "ring" : "split", R4D_AR8_FORM_ENV);
});
}
const R4DArLink* all = g_rv.ar8_link;
in->pieces = set.pieces;
in->weights_min = set.weights_min;
in->pieces_min = set.pieces_min;
int w[R4D_MAX_RANKS] = { 0 };
if (me.mode == AR8_SET) {
std::memcpy(w, me.w, sizeof(w));
if (set.weights == R4D_AR8_WEIGHTS_SET) {
std::memcpy(w, set.w, sizeof(set.w));
std::call_once(said_set, [&w] {
std::fprintf(stderr, "[r4d] eight-rank two-shot shards weighted "
"%d,%d,%d,%d,%d,%d,%d,%d (%s)\n", w[0], w[1], w[2], w[3], w[4], w[5],
w[6], w[7], R4D_AR8_SHARD_WEIGHTS_ENV);
"%d,%d,%d,%d,%d,%d,%d,%d (r4d_ar8_test_settings)\n", w[0], w[1], w[2],
w[3], w[4], w[5], w[6], w[7]);
});
} else if (me.mode == AR8_AUTO || me.mode == AR8_DUPLEX) {
} else if (set.weights == R4D_AR8_WEIGHTS_AUTO) {
double gbs[R4D_MAX_RANKS] = { 0 };
for (int r = 0; r < world; ++r) gbs[r] = r4d_ar_link_gbs(all[r].link);
const bool known = me.mode == AR8_DUPLEX ? r4d_ar_weights_duplex(gbs, world, w)
: r4d_ar_weights_from_rates(gbs, world, w);
if (!known) {
for (int r = 0; r < world; ++r) gbs[r] = r4d_ar_link_gbs(all[r]);
if (!r4d_ar_weights_from_rates(gbs, world, w)) {
std::call_once(said_unknown, [all, world] {
std::string who;
for (int r = 0; r < world; ++r)
if (r4d_ar_link_gbs(all[r].link) <= 0.0) who += " " + std::to_string(r);
if (r4d_ar_link_gbs(all[r]) <= 0.0) who += " " + std::to_string(r);
std::fprintf(stderr, "[r4d] eight-rank two-shot: no PCIe link speed in sysfs for "
"rank%s; shards stay even\n", who.c_str());
});
return RAD_OK;
}
const bool duplex = me.mode == AR8_DUPLEX;
std::call_once(said_links, [all, world, duplex, &w] {
std::call_once(said_links, [all, world, &w] {
std::string l;
for (int r = 0; r < world; ++r) {
char one[96];
std::snprintf(one, sizeof one, "%s r%d %.1f GT/s x%d %.1f GB/s w%d",
r ? "," : "", r, all[r].link.gts, all[r].link.width,
r4d_ar_link_gbs(all[r].link), w[r]);
r ? "," : "", r, all[r].gts, all[r].width,
r4d_ar_link_gbs(all[r]), w[r]);
l += one;
}
std::fprintf(stderr, "[r4d] eight-rank two-shot shard weights from the slowest PCIe "
"hop of each card%s:%s\n", duplex ? " (duplex)" : "", l.c_str());
"hop of each card:%s\n", l.c_str());
});
bool same = true;
for (int r = 1; r < world; ++r) same = same && w[r] == w[0];
@@ -601,6 +503,11 @@ static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, vo
return RAD_OK;
}
extern "C" void r4d_ar8_test_settings(const R4DAr8Settings* s) {
std::lock_guard<std::mutex> lk(g_ar8_m);
g_ar8 = s ? *s : R4DAr8Settings();
}
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_init(p, n_p, rank, world, 0, out);
}
@@ -709,12 +616,10 @@ static int nb_for(long words16, int max_nb) {
* the junction's tail form, the two-shot row up to kTsDecodeShard words a shard), over the words of
* one shard: one block per 2688 words, floor 2, ceiling 8 (and max_nb). A two-shot takes two
* handshakes, each a PCIe round trip a block, so a block more costs more than its share of the
* bytes saves until the shards are large. One per 672 (the rule before 2026-10-19) launched 16
* blocks at 64 rows of 5376, where the multi-user verify runs (8 users x DFlash2's 8 rows): on 4x
* R9700, one launch at a time on the real payload, 64 rows took 85.6 us at 16 blocks against 75.3
* at 4, 32 rows 58.9 at 16 / 47.1 at 8 against 44.2 at 4, 128 rows 143.5 at 16 against 137.9 at 8;
* 8 rows (two blocks either way) 19.6. The block count moves no byte: every word is folded by one
* thread in ascending rank order whatever the grid. */
* bytes saves until the shards are large. On 4x R9700, one launch at a time on the 31B's payload,
* 64 rows of 5376 (8 users x DFlash2's 8 rows) took 85.6 us at 16 blocks against 75.3 at 4, 32
* rows 47.1 at 8 against 44.2 at 4, and 128 rows 143.5 at 16 against 137.9 at 8. The block count
* moves no byte: every word is folded by one thread in ascending rank order whatever the grid. */
/* The chained two-shot (r4d_chain.h) where the row resolved with `chain`, for a decode-sized
* message only (64 rows of an 8192-wide residual): DFlash2's verify-height reductions. */
static long ar_chain(const RadArgs* a, long numel) {
@@ -1160,10 +1065,10 @@ extern "C" int r4d_rad_ar_twoshot_4rank_exact(const RadArgs* a, RadStream s) {
const ArInst* in = c.in;
/* A reduction beside compute (overlap 1) carries its pushes coded at ~12.2 bits a bf16 value
* (r4d_ar_twoshot_Nrank_exact.hip, the coded form), at 4 blocks of 1024 threads, wherever the
* message fits that form; the same bytes either way. The 31B's prefill (4x R9700, a
* 5033-token prompt): 5724 -> 5949 tok/s (+3.9%), every reply identical; 8 x 512 gave +2.1%,
* 16 x 256 +1.3%, 6 x 1024 -1.9% (the blocks crowd the GEMM beside them). `coded` 0, a launch
* parameter no declaration carries, keeps the plain wire: r4d_selftest's plain arm. */
* message fits that form; the same bytes either way. On 4x R9700 4 x 1024 gave the 31B's
* prefill the most (+3.9%) against 8 x 512, 16 x 256 and 6 x 1024, whose blocks crowd the GEMM
* beside them. `coded` 0, a launch parameter no declaration carries, keeps the plain wire:
* r4d_selftest's plain arm. */
const bool lane = r4d_geti_or(a, "overlap", 0) == 1;
if (lane && r4d_geti_or(a, "coded", 1) != 0 &&
r4d_ar_twoshot_coded_ok(c.numel, in->dtype, 4, in->slot16)) {
@@ -1209,9 +1114,13 @@ extern "C" int r4d_rad_ar_twoshot_8rank_exact(const RadArgs* a, RadStream s) {
const long long asked = r4d_pgeti_or(a->p, a->n_p, "pieces", in->pieces);
if (asked < 0 || asked > R4D_AR_TS_MAX_PIECES) return RAD_E_INVAL;
const long long pieces = ar8_pieces_for(in, c.numel, asked);
/* A diagnostic: a device buffer of nblocks * R4D_AR_TL_WORDS int64 stamps (r4d.h). */
/* Both for measuring a board (r4d_selftest --perfar8), never set by the engine: `timeline` a
* device buffer of nblocks * R4D_AR_TL_WORDS int64 stamps (r4d.h), `form` a schedule other than
* lockstep (r4d_ar_shards.h). Lockstep is the serving form: on eight R9700 the ring form takes
* 2-6% less time for 8 and 16 MiB messages, but at TP8 the split form, which includes the ring
* order, moves neither prefill nor decode beyond run-to-run noise. */
const long long timeline = r4d_pgeti_or(a->p, a->n_p, "timeline", 0);
const long long form = r4d_pgeti_or(a->p, a->n_p, "form", in->form);
const long long form = r4d_pgeti_or(a->p, a->n_p, "form", R4D_AR8_FORM_LOCKSTEP);
if (form < R4D_AR8_FORM_LOCKSTEP || form > R4D_AR8_FORM_SPLIT) return RAD_E_INVAL;
R4D_TRY("ar_twoshot_8rank_exact",
r4d_ar_twoshot_8rank_exact(in->peer_scratch[0], in->peer_scratch[1], in->peer_scratch[2],
@@ -1596,12 +1505,6 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_i8_4rank(const RadArgs* a, RadStream s)
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
/* The fence-free forms rest on fine-grained P2P scratch and a store drain; the host mailbox
* (pinned host memory, cached on the way) keeps both fences. */
if (in->host || cfgv.drain != 3) {
if (cfgv.pub == 2) cfgv.pub = 1;
if (cfgv.acq == 2) cfgv.acq = 0;
}
int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)v.M;
if (nblocks > in->max_blocks) nblocks = in->max_blocks;
/* Above one-shot heights (the plugin's fold band at 5 rows and up), the `tail` axis's form:
+6 -2
View File
@@ -84,8 +84,8 @@ inline bool r4d_ar_weights_from_rates(const double* gbs, int ws, int* w) {
return true;
}
// RADIANCE_AR8_SHARD_WEIGHTS=duplex: the weights that minimise the two-shot's link time when both
// directions of a link run at once (the pieced kernel's aim). Rank r with shard fraction x_r sends
// The duplex model: the weights that minimise the two-shot's link time when both directions of a
// link run at once (the pieced kernel's aim). Rank r with shard fraction x_r sends
// (1 - x_r) of the message in the first hop and (ws - 1) x_r in the second, and receives the same,
// so each direction carries (1 + (ws - 2) x_r) N at rate B_r. The slowest rank sets the time T, so
// the best table makes every rank with a shard finish together: x_r = (T B_r - 1) / (ws - 2) where
@@ -93,6 +93,10 @@ inline bool r4d_ar_weights_from_rates(const double* gbs, int ws, int* w) {
// down). Four ranks at B and four at B / 2 give x of 2/9 and 1/36, 8 to 1 where the quadratic rule
// above gives 4 to 1, and a time 10% lower (7/6 N / B / 2 against 1.3 N / B / 2). Scaled so the
// largest weight is 64. False when a rank's rate is unknown.
//
// The engine keeps r4d_ar_weights_from_rates: on eight R9700 these weights lost their lead within
// a timing run and served no faster at TP8. r4d_selftest --perfar8 prints this table beside the
// engine's, to be set with --ar8-weights when timing another board.
inline bool r4d_ar_weights_duplex(const double* gbs, int ws, int* w) {
if (ws < 3 || ws > 16) return false;
int order[16];
+24 -28
View File
@@ -11,27 +11,36 @@
// crosses, not its fold (fp32, ascending rank), so every table gives the same bits.
#include <cstdlib>
#define R4D_AR8_SHARD_WEIGHTS_ENV "RADIANCE_AR8_SHARD_WEIGHTS"
#define R4D_AR8_PIECES_ENV "RADIANCE_AR8_PIECES"
// The eight-rank two-shot's form (r4d_ar_twoshot_Nrank_exact.hip): lockstep (unset, the one
// handshake a step), ring (the first hop sent to the ranks in ring order from the next one) or
// split (ring, and a flag after each half of a step, each awaited only where its data is read).
// Every form folds the same words in the same order, so all give the same bits.
#define R4D_AR8_FORM_ENV "RADIANCE_AR8_FORM"
// Below these message sizes (elements) the weights and the pieces do not apply: a decode-sized
// message pays more for the extra handshakes and the uneven split than its link time saves
// (measured on the eight R9700: 196608 elements run fastest even and in one piece, 524288 already
// gain from weights and two pieces).
#define R4D_AR8_SHARD_WEIGHTS_MIN_ENV "RADIANCE_AR8_SHARD_WEIGHTS_MIN_ELEMS"
#define R4D_AR8_PIECES_MIN_ENV "RADIANCE_AR8_PIECES_MIN_ELEMS"
// Below R4D_AR8_MIN_ELEMS_DEFAULT elements the weights and the pieces do not apply: a
// decode-sized message pays more for the extra handshakes and the uneven split than its link time
// saves (measured on the eight R9700: 196608 elements run fastest even and in one piece, 524288
// already gain from weights and two pieces).
// The eight-rank two-shot's form, its launch parameter `form` (r4d_ar_twoshot_Nrank_exact.hip):
// lockstep (one handshake a step), ring (the first hop sent to the ranks in ring order from the
// next one) or split (ring, and a flag after each half of a step, each awaited only where its data
// is read). Every form folds the same words in the same order, so all give the same bits. The
// engine runs lockstep; the other two exist to time a board (r4d_selftest --perfar8).
enum { R4D_AR8_FORM_LOCKSTEP = 0, R4D_AR8_FORM_RING = 1, R4D_AR8_FORM_SPLIT = 2 };
enum {
R4D_AR_SHARD_WEIGHT_MAX = 65535,
R4D_AR8_MIN_ELEMS_DEFAULT = 262144,
R4D_AR8_MIN_ELEMS_MAX = 268435456, // the two-shot band's top (r4d.h)
};
// The piece count when RADIANCE_AR8_PIECES is unset, by message size in elements: more pieces
// The eight-rank two-shot's settings. The engine runs the defaults: weights from each card's
// slowest PCIe hop (r4d_ar_weights_from_rates, r4d_ar_links.h), the piece count from the message
// size (r4d_ar8_auto_pieces), both from R4D_AR8_MIN_ELEMS_DEFAULT elements. r4d_selftest sets
// others through r4d_ar8_test_settings (r4d.h) to check unequal and empty shards, fixed piece
// counts and the floors, and to time another board's weights.
enum { R4D_AR8_WEIGHTS_AUTO = 0, R4D_AR8_WEIGHTS_EVEN = 1, R4D_AR8_WEIGHTS_SET = 2 };
struct R4DAr8Settings {
int weights = R4D_AR8_WEIGHTS_AUTO;
int w[8] = { 0 }; // R4D_AR8_WEIGHTS_SET: the eight weights
int pieces = 0; // 0: r4d_ar8_auto_pieces
long long weights_min = R4D_AR8_MIN_ELEMS_DEFAULT;
long long pieces_min = R4D_AR8_MIN_ELEMS_DEFAULT;
};
// The piece count when none is set, by message size in elements: more pieces
// shorten the one-way first and last steps ((K+1)/K of the link time) but add a handshake each,
// which only a large message amortises (measured at 4,1,0,4,0,1,4,4: K2 best at 524288, K4 at
// 2097152, K8 at 8388608).
@@ -55,19 +64,6 @@ inline int r4d_ar8_form_parse(const char* s) {
return -1;
}
// A non-negative decimal integer of at most `max`, nothing else.
inline bool r4d_ar_parse_count(const char* s, long long max, long long* out) {
if (!s || *s < '0' || *s > '9') return false;
long long v = 0;
while (*s >= '0' && *s <= '9') {
v = v * 10 + (*s++ - '0');
if (v > max) return false;
}
if (*s) return false;
*out = v;
return true;
}
// `ws` non-negative integers separated by commas, each at most R4D_AR_SHARD_WEIGHT_MAX, summing
// to more than zero; nothing else (no blanks, signs or trailing text).
inline bool r4d_ar_shard_weights_parse(const char* s, int ws, int* w) {
+6 -6
View File
@@ -11,21 +11,21 @@
//
// The shard table (r4d_ar_shards.h) comes in as a kernel argument. By default it is the even
// split (the first n16 % ws shards one word longer); at 3 ranks engine residuals rarely divide (a
// 2048-wide bf16 row is 256 words). At 8 ranks it may be weighted per link
// (RADIANCE_AR8_SHARD_WEIGHTS); a rank with weight 0 owns nothing and only pushes, gathers and
// 2048-wide bf16 row is 256 words). At 8 ranks it is weighted per link (r4d_ar_links.h); a rank with weight 0 owns nothing and only pushes, gathers and
// handshakes. Over both phases a rank moves N + (ws-2)*len_r each way, but phase 1 only sends
// N - len_r (receiving (ws-1)*len_r) and phase 2 the reverse, so a short shard on a slow link pays
// only as far as the phases overlap on that link (docs/GUIDE.md, 4.7). Each word is the same fp32
// fold in ascending rank order whoever owns it, so the bits match the one-shot's.
//
// At 8 ranks the message may also run in pieces (RADIANCE_AR8_PIECES, by default a count from
// the message size, r4d_ar_shards.h): each block's words split into `pieces` runs pipelined so
// At 8 ranks the message may also run in pieces (a count from the message size, r4d_ar_shards.h): each block's words split into `pieces` runs pipelined so
// piece j+1's phase 1 shares the link with piece j's phase 2. A rank with a short shard then
// sends and receives at once instead of one direction per phase.
//
// Also at 8 ranks, two more forms of the same work (RADIANCE_AR8_FORM, the `form` parameter):
// Also at 8 ranks, two more forms of the same work, chosen by the `form` launch parameter to time
// a board (the engine runs lockstep, r4d_ar_entry.hip):
// * ring sends the first hop to the peers in ring order from rank + 1 instead of ascending, so
// at any moment each card receives from one peer rather than all seven from the same one;
// no card receives from all seven at once, as the lowest rank does when every sender starts
// at its lowest peer;
// * split also replaces the one handshake a step, which waits for every peer to finish the whole
// step, by a flag after each half (the first hop of the next piece, the reduce of this one),
// each awaited only before its data is read: before reducing piece j the peers' first hop of
+2 -13
View File
@@ -55,9 +55,7 @@ __device__ __forceinline__ void r4d_ar_drain(int drain) {
else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory");
}
// acq: 0 acquire-only fence (global_inv, no writeback half), 1 full threadfence_system,
// 2 none -- fine-grained scratch only. Every thread of the block runs it after the handshake, so at
// 0 or 1 that is one system-scope invalidate a wave. The P2P scratch is fine-grained (the reads
// bypass L2; r4d_ar_entry.hip's allocation says why), so 2 is the documented design there.
// 2 none -- fine-grained scratch only.
__device__ __forceinline__ void r4d_ar_acquire(int acq) {
if (acq == 1) __threadfence_system();
else if (acq != 2) __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "");
@@ -82,16 +80,7 @@ __device__ __forceinline__ void r4d_ar_handshake(const R4DArWidePeers<S, NPEERS>
if (tl && tid == 0) tl[0] = (long long)wall_clock64();
if (tid == 0) {
if (drain == 2) __threadfence_system();
if (pub == 2) {
// No release fence: the flags go out behind the data with nothing written back. Meant for
// a P2P instance with drain 3, on the reasoning that fine-grained scratch stores reach past
// L2. They do not: on 4x R9700 the readers saw stale scratch on nearly every element
// (r4d_selftest, 2026-10-17), so no tuned point selects pub 2 (tArQ84); it is kept only
// as the measured negative.
#pragma unroll
for (int p = 0; p < NPEERS; ++p)
r4d_ar_store_sys_rlx(&peers.flags[p][(size_t)b * WS + rank], val);
} else if (pub) {
if (pub) {
// One system writeback for the whole publish, then relaxed stores. Per-peer release stores
// would add writebacks that order nothing, since the flags go to different peers.
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "");
+1 -4
View File
@@ -75,9 +75,6 @@ __host__ __device__ __forceinline__ int r4d_attn_wlo(int ctx, int q_len, int qro
const int lo = ctx - q_len + qrow - window + 1;
return lo > 0 ? lo : 0;
}
__host__ __device__ __forceinline__ int r4d_attn_used(int ctx, int tile, int splits) {
int t = r4d_attn_tiles(ctx, tile), tps = r4d_attn_tps(ctx, tile, splits); return (t + tps - 1) / tps;
}
// WIN enables a sliding window (a.window positions ending at each row's causal limit). As a
// template parameter defaulting to 0, full attention compiles with no window code.
@@ -236,7 +233,7 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
if (WIN && kk < wlo0) kk = wlo0;
const int bk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const uint8_t* base = (const uint8_t*)a.kv + (size_t)bk * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
+ (size_t)kvc * a.kv_head_stride + (size_t)(kk % BS) * ROWB;
v4c[r][j] = *(const uint32_t*)(base + VOFF + o * 4);
sc[j] = *(const uint16_t*)(base + VSOFF + (o >> 2) * 2);
}
+20
View File
@@ -0,0 +1,20 @@
/* r4d_attn_paged_h128_gqa1.hip -- head_dim 128 with ONE query head per KV head: plain MHA.
*
* Everything else in this library pages attention through a grouped ratio (4, 6, 8 or 12 queries
* per KV head). The Unlimited-OCR decoder has 10 query heads over 10 KV heads at 128 wide, so the
* ratio is 1 and none of the existing legs matches it; the engine reports every band of that
* geometry as having no kernel rather than serving it on the host.
*
* The device code is the generic body (r4d_attn_paged_gqa8.hip, which is parameterised by
* R4D_ATTN_GQA rather than fixed at 8) instantiated at ratio 1: the same templated prefill and
* split-KV decode kernels, with GQA=1 substituted. No new kernel, no new masking path.
*
* This unit ships BOTH legs, unlike the h128/gqa4 drafter unit: a decoder runs prefill as well as
* decode, and the caller-side fallback the drafter relies on is an order of magnitude slower.
* The prefill option set is the h128 set (G8_P_OPT_128), which is the one compiled and measured
* for this head width. */
#define R4D_ATTN_GQA 1
#define R4D_ATTN_H128 1
#define R4D_ATTN_H256 0
#include "r4d_attn_paged_gqa8.hip"
+58 -25
View File
@@ -2,10 +2,12 @@
// KV-dtype variants are template instantiations of one device code. The geometry is a hard gate:
// anything else is rejected.
//
// The query is bf16 in every variant. A single-term 8-bit query is ~10x less accurate against an
// fp32 reference (2.58e-02 vs ~2.3e-03 relative), and the two-term e4m3 form that reaches f16
// accuracy is 4-10% slower end to end. Two families ship, differing in KV dtype: bf16 and fp8
// (the production configuration).
// The query is bf16 in every exact variant. A single-term 8-bit query is ~10x less accurate
// against an fp32 reference (2.58e-02 vs ~2.3e-03 relative), and the two-term e4m3 form that
// reaches f16 accuracy is 4-10% slower end to end. Two families ship, differing in KV dtype: bf16
// and 8-bit (fp8, the production configuration, and the fp8_v4 and k6_v4 caches). Over the 8-bit
// caches the prefill also has lossy rows that run Q.K^T, P.V or both as e4m3 WMMA (O_QK8, O_PV8),
// taken only when the caller's `prefill_fp8` asks for them.
//
// `opt` is a bitmask of optimisation steps:
// prefill 3954187 = f16 operands | mask skip | folded query scale | contiguous-k fragments
@@ -19,7 +21,6 @@
#include "r4d_attn_args.h"
#include "r4d_common.h"
#include <cmath>
#include <cstdlib>
#include <algorithm>
using std::max;
#include "r4d_attn_prefill_h256_gqa6.hip"
@@ -50,32 +51,16 @@ extern "C" void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max
// (36-48 bytes per lane, ~4% of the prefill). At 2 the spill is 20 bytes, outside the WMMA groups.
#define P_OPT 3954187
// KVP: 0 = fp8 e4m3 cache, 1 = bf16 cache. Reached only through the two named wrappers below.
// KVP: 0 = an 8-bit cache (XOPT names fp8_v4 or k6_v4 and the e4m3 legs), 1 = bf16 cache.
template <int KVP, int XOPT = 0>
static int prefill_launch(const R4DArgs* a, hipStream_t s) {
if (a->head_dim != A_HEAD_DIM || a->block_size != A_BLOCK_SIZE) return -1;
if (a->q_heads / a->kv_heads != A_GQA) return -2;
constexpr int BQ = (P_NWARPS * 16) / A_GQA;
dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs);
// R4D_ATTN_FP8: 0 = f16 (default), 1 = O_QK8, 2 = O_PV8, 3 = both; fp8, fp8_v4 and k6_v4 KV.
int fp8mode = 0;
if constexpr (KVP == 0) {
static const int m = [] { const char* e = getenv("R4D_ATTN_FP8"); return e ? atoi(e) : 0; }();
fp8mode = m;
}
#define P_LAUNCH(OPTX) \
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE, \
KVP, OPTX>), \
grid, dim3(P_NWARPS * 32), 0, s, *a)
if constexpr (KVP == 0) {
if (fp8mode == 3) P_LAUNCH(P_OPT | XOPT | O_QK8 | O_PV8);
else if (fp8mode == 2) P_LAUNCH(P_OPT | XOPT | O_PV8);
else if (fp8mode == 1) P_LAUNCH(P_OPT | XOPT | O_QK8);
else P_LAUNCH(P_OPT | XOPT);
} else {
P_LAUNCH(P_OPT | XOPT);
}
#undef P_LAUNCH
hipLaunchKernelGGL((r4d_attn_prefill_kernel<P_NWARPS, P_TILE, A_HEAD_DIM, A_GQA, A_BLOCK_SIZE,
KVP, P_OPT | XOPT>),
grid, dim3(P_NWARPS * 32), 0, s, *a);
CHK();
return 0;
}
@@ -92,6 +77,15 @@ extern "C" int r4d_attn_prefill_h256_gqa6_fp8v4kv(const R4DArgs* a, hipStream_t
extern "C" int r4d_attn_prefill_h256_gqa6_k6v4kv(const R4DArgs* a, hipStream_t s) {
return prefill_launch<0, O_V4 | O_K6>(a, s);
}
// The e4m3 product legs over an 8-bit cache (XOPT 0 fp8, O_V4 fp8_v4, O_V4 | O_K6 k6_v4). `legs`
// is 1 Q.K^T, 2 P.V, 3 both. Lossy, so reached only through the rows a caller's attn_paged
// `prefill_fp8` selects.
template <int XOPT>
static int prefill_legs_launch(const R4DArgs* a, hipStream_t s, int legs) {
if (legs == 1) return prefill_launch<0, XOPT | O_QK8>(a, s);
if (legs == 2) return prefill_launch<0, XOPT | O_PV8>(a, s);
return prefill_launch<0, XOPT | O_QK8 | O_PV8>(a, s);
}
// ---- decode ----------------------------------------------------------------------------------
#define D_TILE 16
@@ -189,6 +183,45 @@ extern "C" int r4d_rad_attn_prefill_h256_fp8(const RadArgs* a, RadStream s) {
return r4d_attn_prefill_h256_gqa6_fp8kv(&r, (hipStream_t)s);
}
/* The 8-bit caches with e4m3 products. `legs` is the row's `prefill_fp8`, which its constraint has
* matched: 1 Q.K^T, 2 P.V, 3 both. `row` is a token's bytes in a (block, head) page: 512 for fp8,
* 400 for fp8_v4, 352 for k6_v4. */
template <int XOPT>
static int prefill_h256_legs(const RadArgs* a, RadStream s, long long row, int legs) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
int rc = fill_paged_row(a, &r, 256, row);
if (rc != RAD_OK) return rc;
return prefill_legs_launch<XOPT>(&r, (hipStream_t)s, legs);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<0>(a, s, 512, 3);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_fp8v4_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4>(a, s, 400, 3);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_qk8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 1);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 2);
}
extern "C" int r4d_rad_attn_prefill_h256_k6v4_qk8pv8(const RadArgs* a, RadStream s) {
return prefill_h256_legs<O_V4 | O_K6>(a, s, 352, 3);
}
extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) {
if (check_dims_once() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
R4DArgs r;
+12 -5
View File
@@ -1,5 +1,9 @@
/* r4d_attn_paged_window.hip -- paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV
* head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
/* r4d_attn_paged_window.hip -- paged attention at head_dim 128, 256 and 512, 1/2/4/8 queries per
* KV head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
*
* head_dim 128 is Unlimited-OCR's decoder (10 query heads over 10 KV heads): the plain MHA case,
* served here so its q slice of the fused q|k|v plane is read in place (attn_paged_qrow) instead
* of being lifted into a dense buffer.
*
* Gemma 4's text layers: sliding layers are 16 query heads over 8 KV heads at head_dim 256 with a
* 1024-token window (gqa 2 at every TP); full layers are 16 over 2 at head_dim 512 (gqa 8 at
@@ -62,7 +66,8 @@ constexpr int kMaxSplit = 64;
template <int HD> struct Geo;
/* R query rows per workgroup (R / 8 per wave), BK keys per tile. BK * 2 * HD bf16 = 32 KiB of LDS
* either way: two paged blocks at 256, one at 512. */
* either way: two paged blocks at 256, one at 512, four at 128. */
template <> struct Geo<128> { static constexpr int R = 32, BK = 32; };
template <> struct Geo<256> { static constexpr int R = 32, BK = 32; };
template <> struct Geo<512> { static constexpr int R = 16, BK = 16; };
@@ -1156,8 +1161,8 @@ static int launch_attn(const RadArgs* a, RadStream stream) {
A.n_split = (int)ns;
hipStream_t s = (hipStream_t)stream;
/* The chained forms where the row resolved with `chain` (a chainable row, RADIANCE_CHAIN), at
* decode heights only: the 31B's full layers at a verify. */
/* The chained forms where the row resolved with `chain` (launches chain), at decode heights
* only: the 31B's full layers at a verify. */
const bool chain = rad_args_geti_or(a, "chain", 0) != 0 && rows <= 64;
if (chain)
R4D_KLAUNCH(R4D_KNAME(r4dchain_attn_window<HD, GQA, KV8>),
@@ -1188,12 +1193,14 @@ extern "C" {
int r4d_rad_attn_window_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true>(a, s); \
}
R4D_WIN_DEF(128, 1)
R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8)
R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8)
#undef R4D_WIN_DEF
/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split)
* triples for any batch, so the size is a constant. */
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); }
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*) { return r4d_win::scratch_need<256>(); }
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*) { return r4d_win::scratch_need<512>(); }
+14 -5
View File
@@ -2,7 +2,9 @@
// 128-VGPR accumulator. The query is bf16 and the KV cache is fp8 or bf16; the 16-bit operand
// format for both matmuls is f16 (see r4d_dt16.h for why).
//
// Two families: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). No fp8-P variant.
// Two families: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8, fp8_v4 or k6_v4 KV). The
// mixed family also has lossy e4m3 legs (QK8, PV8), launched only by the rows a caller's
// `prefill_fp8` selects.
//
// Each option below can be turned off on its own after a geometry change:
//
@@ -23,16 +25,21 @@
// DOT2 v_dot2_f32_f16 row sum from the packed f16 P: 4 instructions instead of 8, and the
// denominator uses the p values the PV matmul used.
// BTS/KWIDE/GPREV tile staging; see each define.
// QK8 Lossy. Q rounded to e4m3 once at load, after the folded scale; K as e4m3 bytes in LDS
// (half the tile) and Q.K^T runs as fp8 WMMA at twice the f16 rate.
// PV8 Lossy. P rounded to e4m3 and V as e4m3 bytes in LDS, P.V as fp8 WMMA. GROW is 8
// octaves (e4m3's largest value is 448 = 2^8.8), and DOT2 is off: the denominator sums the
// p values before rounding.
// The LDS bytes are the cache's own for the fp8 cache and fp8_v4's K. k6_v4's K and the
// int4 V of fp8_v4/k6_v4 are widened to value * group scale, as for the f16 legs, and
// rounded once to e4m3 at staging. QK8 and PV8 need an 8-bit cache and CONTIG; a
// static_assert holds both.
#include "r4d.h"
#include "r4d_common.h"
#include "r4d_dt16.h"
#define O_F16 1
#define O_MSKIP 2
// QK8/PV8 (ported from radiance-vllm-mxfp4 r4d_radiance_extras.patch): Q and P as e4m3,
// K and V as e4m3 bytes in LDS, both matmuls as fp8 WMMA. Not with bf16 KV. On the fp8 cache (and
// fp8_v4's K) the bytes are the cache's own; k6_v4's K and the int4 V of fp8_v4/k6_v4 are widened
// to the value times its group scale and rounded once to e4m3 at staging.
#define O_QK8 32
#define O_PV8 64
#define O_FOLDQ 8
@@ -117,6 +124,8 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
constexpr int QK8 = ((OPT & O_QK8) && !KVP) ? 1 : 0;
constexpr int PV8 = ((OPT & O_PV8) && !KVP) ? 1 : 0;
static_assert(!(OPT & (O_QK8 | O_PV8)) || !KVP,
"the e4m3 legs need an 8-bit cache, or they compile to the exact form");
static_assert(!QK8 || KWIDE, "QK8 raw-byte staging is written for the wide K fetch");
typedef DT16<F16> D;
typedef typename D::frag frag16;
+284 -61
View File
@@ -79,7 +79,8 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
int cin, int cout, int k, int dil, int pad, int st, int x_ld, int y_ld, int res_ld, int act) {
int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld,
int res_ld, int act) {
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
constexpr int CPR = C1_BK / 8;
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
@@ -101,9 +102,9 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
const int m = p0 + r;
a_ok[i] = m < r_end;
a_row[i] = a_ok[i] ? m : r_beg;
const int sq = seq_of(cu, n_seq, a_row[i]);
a_s0[i] = cu[sq];
a_s1[i] = cu[sq + 1];
const int sq = seq_of(cu, n_seq, a_row[i] * stride * cdiv);
a_s0[i] = cu[sq] / cdiv;
a_s1[i] = cu[sq + 1] / cdiv;
a_t[i] = e / cin;
a_ci[i] = e % cin;
adst[i] = sA + r * C1_PITCH + e;
@@ -124,7 +125,7 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
const r4d_u32x4 zero = {0u, 0u, 0u, 0u};
auto loadA = [&](int i) -> r4d_u32x4 {
if (!a_ok[i] || a_t[i] >= k) return zero;
const int ir = a_row[i] * st + a_t[i] * dil - pad;
const int ir = a_row[i] * stride + a_t[i] * dil - pad;
if (ir < a_s0[i] || ir >= a_s1[i]) return zero;
return *(const r4d_u32x4*)(x + (size_t)ir * x_ld + a_ci[i]);
};
@@ -216,17 +217,18 @@ __global__ __launch_bounds__(kT) void conv1d_direct_kernel(
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
int cin, int cout, int k, int dil, int pad, int st, int x_ld, int y_ld, int res_ld, int act) {
int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld,
int res_ld, int act) {
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
const int64_t total = (int64_t)(r_end - r_beg) * cout;
if (t >= total) return;
const int co = (int)(t % cout);
const int row = r_beg + (int)(t / cout);
const int sq = seq_of(cu, n_seq, row);
const int s0 = cu[sq], s1 = cu[sq + 1];
const int sq = seq_of(cu, n_seq, row * stride * cdiv);
const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv;
float acc = 0.0f;
for (int kk = 0; kk < k; ++kk) {
const int ir = row * st + kk * dil - pad;
const int ir = row * stride + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const uint16_t* xp = x + (size_t)ir * x_ld;
const uint16_t* wp = w + ((size_t)co * k + kk) * cin;
@@ -386,14 +388,14 @@ __global__ __launch_bounds__(256) void conv_t1d_kernel(
// the output channels, its K the (tap, channel) pairs, channel innermost. A thread stages one K
// column a slab and steps it sixteen at a time, so no K index is divided after the first.
// conv1d's A: output row m's tap t reads input row m + t dil - pad of m's own sequence, zero
// outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an address
// clamped into x's first `r_end` rows and the zero selected after it.
// conv1d's A: output row m's tap t reads input row m stride + t dil - pad of m's own sequence,
// zero outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an
// address clamped into x's first `r_end` stride rows and the zero selected after it.
template <int CNT>
struct Conv1dRows {
const float* x;
const int* cu;
int n_seq, r_end, cin, k, dil, pad, x_ld;
int n_seq, r_end, cin, k, dil, pad, x_ld, stride, cdiv;
int row[CNT], s0[CNT], s1[CNT];
int t = 0, ci = 0;
__device__ void init(int first_row, int kk) {
@@ -401,9 +403,9 @@ struct Conv1dRows {
for (int j = 0; j < CNT; ++j) {
const int m = first_row + 16 * j;
row[j] = m < r_end ? m : -1;
const int sq = seq_of(cu, n_seq, m < r_end ? m : r_end - 1);
s0[j] = cu[sq];
s1[j] = cu[sq + 1];
const int sq = seq_of(cu, n_seq, (m < r_end ? m : r_end - 1) * stride * cdiv);
s0[j] = cu[sq] / cdiv;
s1[j] = cu[sq + 1] / cdiv;
}
t = kk / cin;
ci = kk % cin;
@@ -411,9 +413,10 @@ struct Conv1dRows {
__device__ void fetch(float (&v)[CNT]) const {
#pragma unroll
for (int j = 0; j < CNT; ++j) {
const int ir = row[j] + t * dil - pad;
const int ir = row[j] * stride + t * dil - pad;
const bool live = row[j] >= 0 && t < k && ir >= s0[j] && ir < s1[j];
const int irc = ir < 0 ? 0 : (ir >= r_end ? r_end - 1 : ir);
const int x_rows = r_end * stride;
const int irc = ir < 0 ? 0 : (ir >= x_rows ? x_rows - 1 : ir);
const float xv = x[(uint32_t)irc * (uint32_t)x_ld + (uint32_t)ci];
v[j] = live ? xv : 0.0f;
}
@@ -430,12 +433,13 @@ template <int TN>
__global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel(
const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias,
const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin,
int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld,
int act) {
constexpr int TM = 8, BM = 16 * TM, BN = 16 * TN;
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN;
const int K = k * cin;
Conv1dRows<TM> la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld };
Conv1dRows<TM> la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld, stride, cdiv };
r4d_f32::RowsLoader<TN> lw{ w, K, cout, K };
la.init(m0 + ty, tx);
lw.init(n0 + ty, tx);
@@ -460,16 +464,17 @@ __global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel(
__global__ __launch_bounds__(kT) void conv1d_f32_direct_kernel(
const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias,
const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin,
int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld,
int act) {
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
if (t >= (int64_t)rows * cout) return;
const int co = (int)(t % cout);
const int row = (int)(t / cout);
const int sq = seq_of(cu, n_seq, row);
const int s0 = cu[sq], s1 = cu[sq + 1];
const int sq = seq_of(cu, n_seq, row * stride * cdiv);
const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv;
float acc = 0.0f;
for (int kk = 0; kk < k; ++kk) {
const int ir = row + kk * dil - pad;
const int ir = row * stride + kk * dil - pad;
if (ir < s0 || ir >= s1) continue;
const float* xp = x + (size_t)ir * x_ld;
const float* wp = w + ((size_t)co * k + kk) * cin;
@@ -624,6 +629,11 @@ __device__ uint32_t kth_key(F val, int j0, int j1, int kth, int* sh) {
// [sup_lo, sup_hi) are optional. The kept values are divided by the temperature, as libref divides:
// a multiply by its inverse rounds differently and can move a pick across a CDF boundary. A lane
// with no candidate left writes -1.
//
// `top_p` < 1 cuts the kept list where the whole candidate set's cumulative probability passes it
// (Fish Audio's draw). The normaliser is each thread's slice summed in index order, the slices
// then summed by thread 0 in thread order: index order as libref sums, associated differently,
// which in double moves a cut only for a cumulative within ~1e-16 of top_p.
constexpr int kMaxK = 256;
__global__ __launch_bounds__(kT) void cfg_topk_kernel(
@@ -631,9 +641,10 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
const int* __restrict__ frame, int* __restrict__ ids, int V, int K, int rep, int cond_k,
float cfg, float temp, uint64_t stream, const float* __restrict__ cfgs,
const int* __restrict__ lane, int* __restrict__ hist, int n_hist, int sup_lo, int sup_hi,
float pen) {
float pen, float top_p) {
__shared__ int sh[8];
__shared__ int s_pre[kT];
__shared__ double s_z[kT];
__shared__ float s_g[kMaxK];
__shared__ int s_i[kMaxK];
__shared__ float s_e[kMaxK];
@@ -723,8 +734,29 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
s_pre[rank] = mi;
}
__syncthreads();
if (top_p < 1.f) {
const float m = s_e[0] / temp;
double z = 0;
for (int j = j0; j < j1; ++j)
if (cand(j)) z += exp((double)(gval(j) / temp - m));
s_z[tid] = z;
}
__syncthreads();
if (tid == 0) {
const float m = s_e[0] / temp;
int kp = kk;
if (top_p < 1.f) {
double z = 0;
for (int t = 0; t < kT; ++t) z += s_z[t];
double cum = 0;
kp = 1;
for (int t = 0; t < kk; ++t) {
cum += exp((double)(s_e[t] / temp - m)) / z;
if (t > 0 && cum > (double)top_p) break;
kp = t + 1;
}
}
const int kk = kp;
double tot = 0;
for (int t = 0; t < kk; ++t) tot += exp((double)(s_e[t] / temp - m));
const double u = (double)rad_philox_uniform_s(seed_of(seed, ln),
@@ -763,15 +795,16 @@ __device__ __forceinline__ float ldtab(const void* t, int f32, size_t i) {
__global__ __launch_bounds__(kT) void rvq_embed_kernel(
const int* __restrict__ codes, int64_t kp, int64_t rp, const void* __restrict__ t0,
int t0_f32, const void* __restrict__ t1, int t1_f32, void* __restrict__ y, int y_f32, int D,
int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1) {
int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1, int clamp) {
const int r = blockIdx.x;
const int c0 = codes[(size_t)r * rp] + off0;
auto cl = [clamp](int c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
const int c0 = cl(codes[(size_t)r * rp]) + off0;
if (c0 < 0 || c0 >= r0) return;
for (int d = threadIdx.x; d < D; d += kT) {
const float e0 = ldtab(t0, t0_f32, (size_t)c0 * D + d);
float acc = round1 ? e0 : 0.0f;
for (int k = 1; k < K; ++k) {
const int ck = codes[(size_t)k * kp + (size_t)r * rp] + (k - 1) * voc;
const int ck = cl(codes[(size_t)k * kp + (size_t)r * rp]) + (k - 1) * voc;
if (ck >= 0 && ck < r1) acc += ldtab(t1, t1_f32, (size_t)ck * D + d);
}
const float v = (round1 ? acc : bfr(e0 + bfr(acc))) * scale;
@@ -780,6 +813,86 @@ __global__ __launch_bounds__(kT) void rvq_embed_kernel(
}
}
// One residual quantiser step (DAC's VectorQuantize), a workgroup a row of x. e = in_w x + in_b,
// each of its `dim` sums split over the workgroup and reduced through LDS; each thread then scores
// a strided run of the codebook against e normalised, every row normalised as it is read
// (F.normalize's division), and the workgroup's argmax keeps the lower index on a tie; last the
// chosen raw row's out-projection leaves x's row, rounded once. libref's arithmetic in another
// summation order.
constexpr int kVqMaxDim = 32;
__global__ __launch_bounds__(kT) void vq_encode_kernel(
void* __restrict__ x, int x_f32, int x_ld, const void* __restrict__ iw, int iw_f32,
const void* __restrict__ ib, int ib_f32, const void* __restrict__ cb, int cb_f32,
const void* __restrict__ ow, int ow_f32, const void* __restrict__ ob, int ob_f32,
int* __restrict__ codes, int64_t code_st, int n, int dim, int bins) {
__shared__ float part[kT / 32][kVqMaxDim];
__shared__ float e[kVqMaxDim], eh[kVqMaxDim];
__shared__ float wbest[kT / 32];
__shared__ int wcode[kT / 32];
const int tid = threadIdx.x, wv = tid >> 5, ln = tid & 31;
const size_t xb = (size_t)blockIdx.x * x_ld;
auto ldx = [&](int d) {
return x_f32 ? ((const float*)x)[xb + d] : bf2f(((const uint16_t*)x)[xb + d]);
};
for (int j = 0; j < dim; ++j) {
float acc = 0.0f;
for (int d = tid; d < n; d += kT) acc += ldtab(iw, iw_f32, (size_t)j * n + d) * ldx(d);
#pragma unroll
for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor(acc, o, 32);
if (ln == 0) part[wv][j] = acc;
}
__syncthreads();
if (tid < dim) {
float acc = 0.0f;
for (int w = 0; w < kT / 32; ++w) acc += part[w][tid];
e[tid] = acc + ldtab(ib, ib_f32, (size_t)tid);
}
__syncthreads();
if (tid < dim) {
float ss = 0.0f;
for (int j = 0; j < dim; ++j) ss += e[j] * e[j];
eh[tid] = e[tid] / fmaxf(sqrtf(ss), 1e-12f);
}
__syncthreads();
// Each thread's best over its rows, ascending, so its first maximum is kept; INT_MAX none.
float bs = -INFINITY;
int bc = 0x7fffffff;
for (int c = tid; c < bins; c += kT) {
float ss = 0.0f;
for (int j = 0; j < dim; ++j) {
const float v = ldtab(cb, cb_f32, (size_t)c * dim + j);
ss += v * v;
}
const float nrm = fmaxf(sqrtf(ss), 1e-12f);
float dot = 0.0f;
for (int j = 0; j < dim; ++j) dot += eh[j] * (ldtab(cb, cb_f32, (size_t)c * dim + j) / nrm);
if (dot > bs) { bs = dot; bc = c; }
}
#pragma unroll
for (int o = 16; o > 0; o >>= 1) {
const float os = __shfl_xor(bs, o, 32);
const int oc = __shfl_xor(bc, o, 32);
if (os > bs || (os == bs && oc < bc)) { bs = os; bc = oc; }
}
if (ln == 0) { wbest[wv] = bs; wcode[wv] = bc; }
__syncthreads();
float fs = wbest[0];
int fc = wcode[0];
for (int w = 1; w < kT / 32; ++w)
if (wbest[w] > fs || (wbest[w] == fs && wcode[w] < fc)) { fs = wbest[w]; fc = wcode[w]; }
const int code = fc == 0x7fffffff ? 0 : fc; // no score above -inf: code 0, as libref
if (tid == 0) codes[(size_t)blockIdx.x * code_st] = code;
for (int d = tid; d < n; d += kT) {
float q = 0.0f;
for (int j = 0; j < dim; ++j)
q += ldtab(ow, ow_f32, (size_t)d * dim + j) * ldtab(cb, cb_f32, (size_t)code * dim + j);
const float v = ldx(d) - (q + ldtab(ob, ob_f32, (size_t)d));
if (x_f32) ((float*)x)[xb + d] = v;
else ((uint16_t*)x)[xb + d] = f32_to_bf16(v);
}
}
// dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]; a thread a (lane, code). A lane
// outside `status`, or a frame past `stride` or a lane past `dst`, stores nothing (libref refuses
// the call).
@@ -822,6 +935,32 @@ __global__ __launch_bounds__(kT) void frame_mix_kernel(
}
}
// Fish Audio's repetition-aware choice between two draws, a thread a lane (libref's
// ref_ras_pick): the alternative where the first draw is in [lo, hi) and in the lane's window of
// its last `W` picks, the pick then entering the window. A lane whose window lies outside `hist`
// takes the first draw and keeps no window.
__global__ __launch_bounds__(kT) void ras_pick_kernel(
const int* __restrict__ first, const int* __restrict__ alt, const int* __restrict__ lane,
int* __restrict__ hist, int* __restrict__ ids, int n, int W, int lo, int hi, int rep,
int clear, long long n_hist) {
const int i = blockIdx.x * kT + threadIdx.x;
if (i >= n) return;
const int f = first[rep * i];
const long long L = lane[i];
int pick = f;
if (L >= 0 && (L + 1) * W <= n_hist) {
int* h = hist + L * W;
if (clear)
for (int w = 0; w < W; ++w) h[w] = -1;
if (f >= lo && f < hi)
for (int w = 0; w < W; ++w)
if (h[w] == f) { pick = alt[rep * i]; break; }
for (int w = 0; w + 1 < W; ++w) h[w] = h[w + 1];
h[W - 1] = pick;
}
for (int r = 0; r < rep; ++r) ids[rep * i + r] = pick;
}
__global__ __launch_bounds__(kT) void end_status_kernel(
const int* __restrict__ ids, const int* __restrict__ lane, int* __restrict__ status, int n,
int rep, int end) {
@@ -990,6 +1129,13 @@ __global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ l
if (j < n) y[j] = j * len[0] * mult;
}
__global__ __launch_bounds__(kT) void sub_i32_kernel(const int* __restrict__ x,
const int* __restrict__ s, int* __restrict__ y,
int n) {
const int j = blockIdx.x * kT + threadIdx.x;
if (j < n) y[j] = x[j] - s[0];
}
// ---------------------------------------------------------------------------- attention
// Dense causal attention over short sequences, head_dim 256, one query head a key head: a depth
// decoder runs a frame's handful of positions, the codebooks so far. A workgroup a (sequence,
@@ -1075,38 +1221,43 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
const long long causal = r4d_geti_or(a, "causal", 0);
/* The strided form: `stride` > 1 with `pad` explicit, any k, a single sequence covering all of
* x (the encoder's downsample, k = 2 stride and pad ceil(stride / 2)). `pad` means nothing
* without a stride, and the causal form keeps its own left-only padding. */
/* Two strided forms: the causal one (implicit left pad, `cu_div` bounds) and a zero-padded
* one with `pad` explicit, any k, a single sequence covering all of x (the encoder's
* downsample, k = 2 stride and pad ceil(stride / 2)). `pad` means nothing without a stride,
* and the causal form keeps its own left-only padding. */
const long long st = r4d_geti_or(a, "stride", 1), pp = r4d_geti_or(a, "pad", -1);
const long long cd = r4d_geti_or(a, "cu_div", 1);
const int act = conv1d_act(r4d_gets(a, "act"));
if (act < 0) return R4D_NO(RAD_E_INVAL);
const bool padded = pp >= 0 && st > 1;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || pp < 0)) ||
(st <= 1 && pp >= 0))
causal < 0 || causal > 1 || st < 1 || (pp >= 0 && (st <= 1 || causal || cd != 1)) ||
(st > 1 && pp < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, ry = 0, rr = 0;
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0;
if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k ||
(b && r4d_numel(b) < cout))
if (n_seq <= 0 || ry <= 0 || (!padded && rx < ry * st) || (res && rr < ry) ||
r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout))
return R4D_NO(RAD_E_SHAPE);
/* The strided output length is PyTorch's, exactly (rx and ry are the row counts; xl and yl
* are the pitches): a graph that wants a truncated floor drops the last output row itself.
* One sequence, and cu_seqlens covers every input row (libref, which reads cu, checks its
* ends; the zeroing gather below makes those ends the whole padding, so the length rule is
* the part checkable here). */
if (st > 1) {
/* The padded strided output length is PyTorch's, exactly (rx and ry are the row counts; xl
* and yl are the pitches): a graph that wants a truncated floor drops the last output row
* itself. One sequence, and cu_seqlens covers every input row (libref, which reads cu,
* checks its ends; the zeroing gather below makes those ends the whole padding, so the
* length rule is the part checkable here). */
if (padded) {
if (n_seq != 1 || rx + 2 * pp < dil * (k - 1) + 1 ||
ry != (rx + 2 * pp - dil * (k - 1) - 1) / st + 1)
return R4D_NO(RAD_E_SHAPE);
}
const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr;
/* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, all of
* it on the left for the causal form, or the explicit `pad` around the strided gather. */
const int pad = (int)(pp >= 0 ? pp : (causal ? dil * (k - 1) : dil * (k - 1) / 2));
* it on the left less the stride for the causal form, or PyTorch's zero padding from the
* explicit `pad` around the padded gather (whose bounds then need no cdiv). */
const int pad = (int)(padded ? pp : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2));
const int cdiv = (int)(padded ? 1 : cd);
const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 &&
((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0;
const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr;
@@ -1119,8 +1270,8 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
(const uint16_t*)w->data, bp, rp,
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)xl,
(int)yl, (int)rl, act);
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cdiv,
(int)xl, (int)yl, (int)rl, act);
} else {
constexpr int TP = 4, TC = 1, BP = 128, BC = 64;
hipLaunchKernelGGL((conv1d_igemm_kernel<TP, TC>),
@@ -1128,15 +1279,15 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
(const uint16_t*)w->data, bp, rp,
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)xl,
(int)yl, (int)rl, act);
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cdiv,
(int)xl, (int)yl, (int)rl, act);
}
} else {
hipLaunchKernelGGL(conv1d_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0,
(hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data,
bp, rp, (const int*)cu->data, (uint16_t*)y->data,
(int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad,
(int)st, (int)xl, (int)yl, (int)rl, act);
(int)st, (int)cdiv, (int)xl, (int)yl, (int)rl, act);
}
return st_of(hipGetLastError());
}
@@ -1200,7 +1351,8 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
if (!r4d_contig(w) || (b && !r4d_contig(b)) || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
const long long causal = r4d_geti_or(a, "causal", 0);
const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1);
const long long cd = r4d_geti_or(a, "cu_div", 1);
const int act = conv1d_act(r4d_gets(a, "act"));
if (act < 0) return R4D_NO(RAD_E_INVAL);
/* The strided form lives on the bf16 rows (the DAC encoder it serves runs there); the f32
@@ -1209,7 +1361,7 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
if (r4d_geti_or(a, "stride", 1) != 1 || r4d_geti_or(a, "pad", -1) >= 0)
return R4D_NO(RAD_E_DTYPE);
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
causal > 1)
causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
return R4D_NO(RAD_E_SHAPE);
long long rx = 0, ry = 0, rr = 0;
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
@@ -1217,18 +1369,19 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE);
const long long n_seq = r4d_numel(cu) - 1;
/* The tile's loaders index x and w with 32-bit element offsets. */
if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k ||
(b && r4d_numel(b) < cout) || ry > 0x7fffffffll || (ry + 127) / 128 > 65535 ||
ry * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32))
if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) ||
r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout) || ry > 0x7fffffffll ||
(ry + 127) / 128 > 65535 || ry * st * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32))
return R4D_NO(RAD_E_SHAPE);
const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2);
const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
const float* bp = b ? (const float*)b->data : nullptr;
const float* rp = res ? (const float*)res->data : nullptr;
if (cout < 16) {
hipLaunchKernelGGL(conv1d_f32_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0,
(hipStream_t)s, (const float*)x->data, (const float*)w->data, bp, rp,
(const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin,
(int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act);
(int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl,
(int)rl, act);
return st_of(hipGetLastError());
}
const int tn = cout > 64 ? 8 : cout > 32 ? 4 : 2;
@@ -1237,7 +1390,8 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
hipLaunchKernelGGL((conv1d_f32_kernel<TN>), grid, dim3(r4d_f32::kThr), 0, (hipStream_t)s, \
(const float*)x->data, (const float*)w->data, bp, rp, \
(const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, \
(int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act)
(int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl, \
(int)rl, act)
if (tn == 8) C1F(8);
else if (tn == 4) C1F(4);
else C1F(2);
@@ -1325,9 +1479,11 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
const long long sup_lo = r4d_geti_or(a, "sup_lo", 0), sup_hi = r4d_geti_or(a, "sup_hi", 0);
const double cfg = r4d_getf(a, "cfg", 1.0), temp = r4d_getf(a, "temp", 1.0);
const double pen = r4d_getf(a, "penalty", 1.0);
/* As f32, as libref and libavx read it, so all three cut at the same value. */
const float top_p = (float)r4d_getf(a, "top_p", 1.0);
if (V <= 0 || K <= 0 || K > kMaxK || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V ||
!(temp > 0) || V > (1 << 16) * kT || sup_lo < 0 || sup_hi < sup_lo || sup_hi > V ||
!(pen > 0) || (!hist != !lane))
!(pen > 0) || (!hist != !lane) || !(top_p >= 0.f))
return R4D_NO(RAD_E_SHAPE);
long long rl = 0;
const long long ll = r4d_rows_pitch(lg, V, &rl);
@@ -1343,7 +1499,30 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
cfgs ? (const float*)cfgs->data : nullptr,
lane ? (const int*)lane->data : nullptr, hist ? (int*)hist->data : nullptr,
hist ? (int)(r4d_numel(hist) / V) : 0, (int)sup_lo, (int)sup_hi,
(float)pen);
(float)pen, top_p);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_ras_pick(const RadArgs* a, RadStream s) {
const RadTensor *first = r4d_opt(a, 0), *alt = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
const RadTensor *hist = r4d_opt(a, 3), *ids = r4d_opt(a, 4);
if (!first || !alt || !lane || !hist || !ids) return R4D_NO(RAD_E_INVAL);
if (!is_i32(first) || !is_i32(alt) || !is_i32(lane) || !is_i32(hist) || !is_i32(ids))
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(first) || !r4d_contig(alt) || !r4d_contig(lane) || !r4d_contig(hist) ||
!r4d_contig(ids))
return R4D_NO(RAD_E_STRIDE);
const long long W = r4d_geti_or(a, "win", 0), lo = r4d_geti_or(a, "lo", 0);
const long long hi = r4d_geti_or(a, "hi", 0), rep = r4d_geti_or(a, "rep", 1);
const long long clear = r4d_geti_or(a, "clear", 0);
const long long n = r4d_numel(lane);
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
r4d_numel(first) < rep * n || r4d_numel(alt) < rep * n || r4d_numel(ids) < rep * n)
return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(ras_pick_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s,
(const int*)first->data, (const int*)alt->data, (const int*)lane->data,
(int*)hist->data, (int*)ids->data, (int)n, (int)W, (int)lo, (int)hi,
(int)rep, (int)clear, (long long)r4d_numel(hist));
return st_of(hipGetLastError());
}
@@ -1356,9 +1535,10 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) {
return R4D_NO(RAD_E_DTYPE);
const long long D = r4d_geti_or(a, "n_embd", 0), K = r4d_geti_or(a, "n_codes", 0);
const long long voc = r4d_geti_or(a, "vocab", 0), off0 = r4d_geti_or(a, "off0", 0);
const long long round1 = r4d_geti_or(a, "round", 0);
const long long round1 = r4d_geti_or(a, "round", 0), clamp = r4d_geti_or(a, "clamp", 0);
const double scale = r4d_getf(a, "scale", 1.0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return R4D_NO(RAD_E_SHAPE);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0)
return R4D_NO(RAD_E_SHAPE);
long long ry = 0;
const long long yl = r4d_rows_pitch(y, D, &ry);
if (yl < 0 || !r4d_contig(t0) || !r4d_contig(t1)) return R4D_NO(RAD_E_STRIDE);
@@ -1371,7 +1551,38 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) {
t0->dtype == RAD_F32 ? 1 : 0, t1->data, t1->dtype == RAD_F32 ? 1 : 0,
y->data, y->dtype == RAD_F32 ? 1 : 0, (int)D, (int)K, (int)voc, (int)off0,
(int)(r4d_numel(t0) / D), (int)(r4d_numel(t1) / D), (float)scale, (int)yl,
(int)round1);
(int)round1, (int)clamp);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_vq_encode(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *iw = r4d_opt(a, 1), *ib = r4d_opt(a, 2);
const RadTensor *cb = r4d_opt(a, 3), *ow = r4d_opt(a, 4), *ob = r4d_opt(a, 5);
const RadTensor* codes = r4d_opt(a, 6);
if (!x || !iw || !ib || !cb || !ow || !ob || !codes) return R4D_NO(RAD_E_INVAL);
auto bf_or_f32 = [](const RadTensor* t) { return t->dtype == RAD_BF16 || t->dtype == RAD_F32; };
if (!is_i32(codes) || !bf_or_f32(x) || !bf_or_f32(iw) || !bf_or_f32(ib) || !bf_or_f32(cb) ||
!bf_or_f32(ow) || !bf_or_f32(ob))
return R4D_NO(RAD_E_DTYPE);
const long long n = r4d_geti_or(a, "n", 0), dim = r4d_geti_or(a, "dim", 0);
const long long bins = r4d_geti_or(a, "bins", 0);
if (n <= 0 || dim <= 0 || dim > kVqMaxDim || bins <= 0) return R4D_NO(RAD_E_SHAPE);
long long rx = 0;
const long long xl = r4d_rows_pitch(x, n, &rx);
if (xl < 0 || !r4d_contig(iw) || !r4d_contig(ib) || !r4d_contig(cb) || !r4d_contig(ow) ||
!r4d_contig(ob))
return R4D_NO(RAD_E_STRIDE);
if (rx <= 0 || r4d_numel(codes) < rx || r4d_numel(iw) < dim * n || r4d_numel(ib) < dim ||
r4d_numel(cb) < bins * dim || r4d_numel(ow) < n * dim || r4d_numel(ob) < n ||
rx > 0x7fffffffll)
return R4D_NO(RAD_E_SHAPE);
/* A code at the operand's own stride: a row of a code-major plane, or a column of one. */
const long long cs = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
auto f32 = [](const RadTensor* t) { return t->dtype == RAD_F32 ? 1 : 0; };
hipLaunchKernelGGL(vq_encode_kernel, dim3((unsigned)rx), dim3(kT), 0, (hipStream_t)s, x->data,
f32(x), (int)xl, iw->data, f32(iw), ib->data, f32(ib), cb->data, f32(cb),
ow->data, f32(ow), ob->data, f32(ob), (int*)codes->data, (int64_t)cs,
(int)n, (int)dim, (int)bins);
return st_of(hipGetLastError());
}
@@ -1663,6 +1874,18 @@ extern "C" int r4d_rad_int_affine(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_sub_i32(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *sc = r4d_opt(a, 1), *y = r4d_opt(a, 2);
if (!x || !sc || !y) return R4D_NO(RAD_E_INVAL);
if (!is_i32(x) || !is_i32(sc) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE);
const long long n = r4d_numel(y);
if (n <= 0 || r4d_numel(x) < n || r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(sub_i32_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s,
(const int*)x->data, (const int*)sc->data, (int*)y->data, (int)n);
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) {
const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!len || !y) return R4D_NO(RAD_E_INVAL);
+2 -2
View File
@@ -1,8 +1,8 @@
// r4d_chain.h -- a chained launch's wait and completion (RadKernelChainFn, abi/rad_abi.h).
//
// Between two dependent kernels on one queue the packet processor waits for the first to finish
// before it launches the second (the AQL barrier bit): ~1.3 ms of a 14 ms DFlash2 step on the 31B
// (4x R9700, 2026-10-17). A chained launch drops the bit. The engine writes a record into the
// before it launches the second (the AQL barrier bit): on 4x R9700, ~1.3 ms of a 14 ms DFlash2 step
// on the 31B. A chained launch drops the bit. The engine writes a record into the
// kernel's argument slot, and the kernel waits for its queue's completion counter to reach the
// blocks issued before it, then adds its own blocks as they finish. A kernel's chained form
// (`CHAIN` true) brackets its body with r4d_chain_wait / r4d_chain_done; the plain form never reads
+13 -14
View File
@@ -114,8 +114,6 @@ __device__ __forceinline__ float bf16w_hi(uint32_t w) { return __uint_as_float(w
// address global memory.
typedef __attribute__((address_space(1))) const uint16_t* r4d_gu16;
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r4d_gu16)p; }
// The same element as a bf16 widened to float.
__device__ __forceinline__ float ldg_bf16(const uint16_t* p) { return bf16w_lo(ldg_u16(p)); }
// `lane ^ N` without the LDS pipe. `__shfl_xor` lowers to `ds_bpermute_b32` plus `s_wait_dscnt`,
// an LDS round trip that dominates a dependency chain (e.g. a dot product closed in a token loop).
@@ -283,30 +281,31 @@ __host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) {
return M <= lim ? 512 : 256;
}
// The full-card cliff, measured on the R9700 (gfx1201, 64 CUs). A launch whose wavefronts fall
// in the last 32 before a multiple of 2048 runs about five times slower than the same work one
// The full-card cliff of the R9700 (gfx1201, 64 CUs). A launch whose wavefront count falls in
// the last 32 before a multiple of 2048 runs about five times slower than the same work one
// workgroup wider, whatever the kernel does: 256-thread workgroups take 27.6 us at 253 to 256 of
// them and 5.2 us at 252 or 257, a norm, an LDS-only kernel and a copy alike. The 31B's
// qkv_norm_rope at a tp-4 verify is exactly 256 such workgroups (16 rows x 16 heads), and a
// drafter's 256-row head norm too.
// them and 5.2 us at 252 or 257, for a norm, an LDS-only kernel and a copy alike.
//
// 2048 is every wave slot of the R9700 (64 CUs x 2 SIMDs x 16). Both numbers are that card's and
// apply on every target libr4d builds for; they are not derived from the device, since no other
// card has been measured and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4
// part with fewer CUs a launch padded here costs one idle row and gives the same bytes, and a
// cliff at that part's own full-card size, if it has one, is not stepped past.
// apply on every target libr4d builds for. They are not derived from the device: no other card has
// been measured, and HIP's multiProcessorCount counts WGPs, not CUs, on RDNA. On an RDNA4 part with
// fewer CUs a launch padded here costs one idle row and gives the same bytes; a cliff at that
// part's own full-card size, if it has one, is not stepped past.
//
// r4d_cliff_rows() is the row count to launch for a grid of `rows` x `per_row` workgroups of
// `waves` wavefronts each: `rows` where that is clear of the window, else the first count past it.
// The kernel returns at once in a row at or past `rows`, so the result is unchanged.
// A row of `per_row * waves` wavefronts that is a multiple of 2048 lands every count on the cliff,
// so it is launched as it is. The kernel returns at once in a row at or past `rows`, so the result
// is unchanged.
constexpr uint32_t kR4dCliffWaves = 2048; // the R9700's wave slots: 64 CUs x 2 SIMDs x 16
constexpr uint32_t kR4dCliffWindow = 32; // the slow window, below each multiple of it
__host__ __device__ __forceinline__ uint32_t r4d_cliff_rows(uint32_t rows, uint32_t per_row,
uint32_t waves) {
if ((uint64_t)per_row * waves % kR4dCliffWaves == 0) return rows;
uint32_t r = rows;
for (int i = 0; i < 64; ++i, ++r) {
const uint64_t w = (uint64_t)r * per_row * waves % kR4dCliffWaves;
if (w != 0 && w <= kR4dCliffWaves - kR4dCliffWindow) break;
if (w != 0 && w <= kR4dCliffWaves - kR4dCliffWindow) return r;
}
return r;
return rows;
}
+7 -3
View File
@@ -28,6 +28,8 @@ __device__ __forceinline__ float act_of(float g) {
if (ACT == 0) return g / (1.0f + expf(-g));
if (ACT == 1) return 0.5f * g * (1.0f + erff(g * 0.70710678118654752f));
if (ACT == 3) return 1.0f / (1.0f + expf(-g));
if (ACT == 4) // quick_gelu: sigmoid of the bf16-rounded 1.702*g, as the unfused mul stores it
return 1.0f / (1.0f + expf(-bf2f(f32_to_bf16(g * bf2f(f32_to_bf16(1.702f))))));
return 0.5f * g * (1.0f + tanhf(0.7978845608028654f * (g + 0.044715f * g * g * g)));
}
@@ -757,11 +759,11 @@ __global__ __launch_bounds__(kLrThreads) void attn_local_rel_kernel(
// ============================================================== launchers
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid.
// act: 0 silu, 1 gelu (erf), 2 gelu_tanh, 3 sigmoid, 4 quick_gelu (sigmoid(bf16(1.702*a))).
extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, int a_ld, int b_ld,
int y_ld, long stream) {
if (!a || !b || !y) return -1;
if (M <= 0 || n <= 0 || act < 0 || act > 3) return -2;
if (M <= 0 || n <= 0 || act < 0 || act > 4) return -2;
const dim3 grid((uint32_t)((n + kThreads - 1) / kThreads), grid_rows(M));
#define R4D_AM(A) \
hipLaunchKernelGGL(act_mul_kernel<A>, grid, dim3(kThreads), 0, (hipStream_t)stream, \
@@ -770,7 +772,8 @@ extern "C" int r4d_act_mul_bf16(long a, long b, long y, int M, int n, int act, i
if (act == 0) R4D_AM(0);
else if (act == 1) R4D_AM(1);
else if (act == 2) R4D_AM(2);
else R4D_AM(3);
else if (act == 3) R4D_AM(3);
else R4D_AM(4);
#undef R4D_AM
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1063,6 +1066,7 @@ extern "C" int r4d_rad_act_mul(const RadArgs* a, RadStream s) {
else if (act && !std::strcmp(act, "gelu")) ai = 1;
else if (act && !std::strcmp(act, "gelu_tanh")) ai = 2;
else if (act && !std::strcmp(act, "sigmoid")) ai = 3;
else if (act && !std::strcmp(act, "quick_gelu")) ai = 4;
if (ai < 0) return R4D_NO(RAD_E_INVAL);
const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
+3 -4
View File
@@ -683,10 +683,9 @@ int body(const RadArgs* a, RadStream stream, bool grouped) {
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;
/* The small-M form at the MTP layer's gate_up slice up to 384 routed rows: a draft pass routes
* one token, a verify pass a few. Measured there (perfmxf8, cold), expert-major against
* small-M at 1, 2, 4, 8 and 16 tokens: 73.6/36.7, 83.6/65.8, 118.4/114.9, 214.0/203.9 and
* 375.6/343.9 us. Down's K of 256 gains nothing from it (within a few percent, a quarter slower
* at three tokens). */
* one token, a verify pass a few. On gfx1201 (perfmxf8, cold) it halves the expert-major time
* at one token and gains 3 to 21 % from 2 to 16. Down's K of 256 gains nothing from it (within
* a few percent, a quarter slower at three tokens). */
if (m.experts == 288 && m.topk == 8 && N == 512 && K == 4096 && m.T <= 384)
return R4D_EMIT(stream, fp8_f32scale_small<512>,
dim3(N / 64, (m.T < m.experts ? m.T : m.experts) + 1), dim3(128), 0,
-14
View File
@@ -204,20 +204,6 @@ __device__ __forceinline__ Stage8 stage8_load(const uint8_t* __restrict__ src, b
return r;
}
// Fragment-order counterpart: a lane's 32 bytes in a (16 row, 64 k) tile are four granules of one
// row at k `k0 + t*16`. They are de-permuted on the way into LDS, so the padded pitch and frag()
// apply unchanged; reading fragment order straight from LDS would put eight lanes on one bank.
template <uint32_t FK>
__device__ __forceinline__ void stage8_store_frag(uint8_t* __restrict__ lds, uint32_t row,
uint32_t k0, Stage8 r) {
const uint4 v = r.v, w = r.w;
const uint2 gr[4] = { make_uint2(v.x, v.y), make_uint2(v.z, v.w), make_uint2(w.x, w.y),
make_uint2(w.z, w.w) };
#pragma unroll
for (uint32_t i = 0; i < 4; ++i)
*(uint2*)(lds + (size_t)row * lds_pitch<FK>() + k0 + i * kFragK) = gr[i];
}
template <uint32_t FK>
__device__ __forceinline__ void stage8_store(uint8_t* __restrict__ lds, uint32_t row, uint32_t k0,
Stage8 r) {
@@ -850,8 +850,9 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
// need not wait for, so wait here (as r4d_moe.hip's router counters do).
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
+42 -16
View File
@@ -481,13 +481,15 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
}
// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it.
template <uint32_t MT, uint32_t FKB, bool I8>
template <uint32_t MT, uint32_t FKB, bool I8, uint32_t MH = 1>
__device__ __forceinline__ void lm_wmma_body(
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
float* __restrict__ C, uint32_t c_ld,
uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) {
constexpr uint32_t kFK = FKB * kBlock; /* K a staging round */
constexpr uint32_t kRows = kDenseWaves * 16u; /* weight rows a workgroup covers */
/* Weight rows a workgroup covers: 16 a wave, the waves split into MH halves along M that share
* the staged tile (MH = 2: 64 rows, each half four 16-row activation tiles). */
constexpr uint32_t kRows = kDenseWaves * 16u / MH;
constexpr uint32_t kPitch = lds_pitch<kFK>(); /* BYTES a staged weight row */
constexpr uint32_t kWUnits = kRows * (kFK / 16u); /* 16-byte staging units, weight */
constexpr bool kPre = MT <= 3u; /* activation a K step ahead, below */
@@ -497,12 +499,14 @@ __device__ __forceinline__ void lm_wmma_body(
const uint32_t tid = (uint32_t)threadIdx.x;
const uint32_t lane = tid & (kWave - 1u);
const uint32_t wv = tid / kWave;
const uint32_t wn = wv % (kDenseWaves / MH); /* this wave's 16 weight rows */
const uint32_t mo = (wv / (kDenseWaves / MH)) * 16u * MT; /* its M half's first row */
const uint32_t c = lane & 15u; /* this lane's weight row inside its 16-row tile */
const uint32_t h = lane >> 4; /* which half of the K step */
for (uint32_t base = (uint32_t)blockIdx.x * kRows; base < rows; base += gridDim.x * kRows) {
/* Clamped, not skipped: a tail workgroup recomputes the last row; the store drops it. */
const uint32_t n = base + wv * 16u + c;
const uint32_t n = base + wn * 16u + c;
const uint32_t nc = (n < rows) ? n : (rows - 1u);
const uint16_t* scl = (const uint16_t*)(W + (size_t)nc * w_ld + cols);
@@ -519,7 +523,7 @@ __device__ __forceinline__ void lm_wmma_body(
auto aload = [&](uint32_t kf) {
#pragma unroll
for (uint32_t t = 0; t < MT; ++t) {
const uint32_t m = t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u);
const uint32_t m = mo + t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u);
an[t] = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u);
}
};
@@ -563,7 +567,7 @@ __device__ __forceinline__ void lm_wmma_body(
for (uint32_t t = 0; t < MT; ++t) ac[t] = an[t];
aload(kf + 16u < kFK ? kf + 16u : kf);
}
const i2v raw = frag<kFK>(s_w, wv * 16u, kf, lane);
const i2v raw = frag<kFK>(s_w, wn * 16u, kf, lane);
const lm_s8v bf =
e4m3x8_to_bf16<I8>((uint32_t)raw[0], (uint32_t)raw[1]);
/* The activation load is unconditional: a padding row re-reads the last real row and a select
@@ -571,7 +575,7 @@ __device__ __forceinline__ void lm_wmma_body(
* per K step). */
#pragma unroll
for (uint32_t t = 0; t < MT; ++t) {
const uint32_t m = t * 16u + c;
const uint32_t m = mo + t * 16u + c;
[[maybe_unused]] const uint32_t mr = (m < m_real) ? m : (m_real - 1u);
lm_s8v af;
if constexpr (kPre) af = ac[t];
@@ -594,7 +598,7 @@ __device__ __forceinline__ void lm_wmma_body(
for (uint32_t t = 0; t < MT; ++t)
#pragma unroll
for (uint32_t j = 0; j < 8; ++j) {
const uint32_t m = t * 16u + h * 8u + j;
const uint32_t m = mo + t * 16u + h * 8u + j;
if (m < m_real) C[(size_t)m * c_ld + n] = acc[t][j];
}
}
@@ -603,16 +607,16 @@ __device__ __forceinline__ void lm_wmma_body(
#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \
uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \
uint32_t w_ld, uint32_t m_real
template <uint32_t MT, uint32_t FKB, bool I8 = false>
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
R4D_LMW_PARAMS) {
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
}
template <uint32_t MT, uint32_t FKB, bool I8 = false>
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma(
R4D_LMW_PARAMS) {
r4d_chain_wait();
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
r4d_chain_done();
}
#undef R4D_LMW_PARAMS
@@ -688,8 +692,8 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c,
// wq [N][lm_row_bytes(K)] E4M3 codes, nkb bf16 scales, pad; `w_ld` BYTES a row (0 = that)
// c [M][N] f32, `c_ld` elements a row (0 = N)
//
// The WMMA path takes M > 2 in chunks of 64 rows, each re-reading the weight; the matvec takes
// M <= 2.
// The WMMA path takes M > 2 in passes of up to 128 rows, each reading the weight once (past 64
// rows in two M halves over one staged tile); the matvec takes M <= 2.
//
// This row must serve every M: all bands of one op read the same stored bytes, so a band falling
// to another kernel (e.g. the bf16 projection) would misread the E4M3 codes.
@@ -730,9 +734,31 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
/* WMMA from M = 3, the matvec at or below. The tile's rate is nearly flat in M; the matvec is
* marginally ahead at M = 2 and clearly at M = 1. Both read the same stored bytes. */
if (M > 2) {
/* Sixty-four rows per pass: four WMMA accumulator tiles (32 registers). */
for (int m0 = 0; m0 < M; m0 += 64) {
const int Mc = (M - m0) < 64 ? (M - m0) : 64;
/* Passes of up to 128 rows. Up to 64, one tile of four WMMA accumulator tiles (32
* registers) a wave; past 64, the same four a wave in two M halves over one staged weight
* tile (MH = 2), so the head is read once a pass. */
for (int m0 = 0; m0 < M; m0 += 128) {
const int Mc = (M - m0) < 128 ? (M - m0) : 128;
if (Mc > 64) {
uint32_t fkb = lm_fkb_rule(4u);
while (fkb > 1u && (cols % (fkb * kBlock)) != 0u) fkb >>= 1;
const uint32_t per = kDenseWaves * 16u / 2u;
const uint32_t blocks = std::min<uint32_t>(4096u, (rows + per - 1u) / per);
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
float* cc = (float*)c + (size_t)m0 * c_ld;
if (fkb == 2u)
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 2, I8, 2> : lm_wmma_kernel<4, 2, I8, 2>),
dim3(blocks), dim3(kDenseThreads), 0,
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
else
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 1, I8, 2> : lm_wmma_kernel<4, 1, I8, 2>),
dim3(blocks), dim3(kDenseThreads), 0,
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
if (hipGetLastError() != hipSuccess) return -6;
continue;
}
const uint32_t mt = (uint32_t)((Mc + 15) / 16);
/* FKB = 4 would need kRows * (512 + 8) = 66560 bytes of LDS, over the 64 KiB limit. */
uint32_t fkb = lm_fkb_rule(mt);
+3 -2
View File
@@ -863,8 +863,9 @@ unsigned int* split_ctr(RadStream s, const void* out) {
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
/* Zero before any launch reads it: the memset is on the null stream, which the engine's
* streams need not wait for, so wait here (as r4d_moe.hip's router counters do). */
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
+112 -72
View File
@@ -4,26 +4,32 @@
//
// At decode the GEMM is a weight stream and the goal is DRAM bandwidth. The skinny kernel (split-K
// within a workgroup, weight straight to registers) falls short on narrow projections. This one
// splits K across workgroups with a fused last-arriver reduction, unpacks the weight through LDS,
// and streams it with non-temporal loads.
// splits K across workgroups with a fused last-arriver reduction and streams the weight with
// non-temporal loads.
//
// Tile: DWN = 8 waves over BND = 128 output columns (one 16-column fragment per wave) and DTM
// 16-row M fragments, the fewest that cover M. Each K slab of DBK bytes stages A (16*DTM rows) and
// 128 weight rows, unpacked to e4m3 through r4d_mxfp4.h.
// 16-row M fragments, the fewest that cover M. Each K slab of DBK bytes stages A (16*DTM rows) in
// LDS, shared by the eight waves; each wave loads its own fragment's weight words for the slab
// straight to registers and unpacks them to e4m3 there (r4d_mxfp4.h). The one-fragment form
// (M <= 16) stages the weight through LDS instead.
//
// Split-K is required: N/16 fragments alone (320 waves at N=5120) do not fill the part. DKS blocks
// split the K slabs; each writes an fp32 partial [DKS][M][N], and the last to arrive (an
// agent-scope counter per column block) sums them, with no second launch.
//
// Split, slab and load hint follow a rule tuned per cell on the 27B's per-rank shapes at
// M = 8..128 (tunables `ks`, `bk`, `nt`; 0 selects the rule):
// - split: the smallest power of two whose grid reaches 48 blocks at M <= 16, 56 at M <= 96 and
// 40 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past
// Split, slab and load hint follow a rule tuned on the 27B's and TranslateGemma's per-rank shapes
// (tunables `ks`, `bk`, `nt`; 0 selects the rule):
// - split up to 64 rows: the smallest power of two whose grid reaches 48 blocks at M <= 16 and
// 56 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past
// ks*M = 512, where partial traffic outweighs the gain.
// - slab: 128, or 64 where LDS per block, (16*DTM + 128) * (DBK+8) bytes, would cost a wide or
// deeply split grid its resident blocks (see mxd_plan). A K not a multiple of 128 takes 64 (and
// a 2-way split widens to 4).
// - split past 64 rows: double only while every split keeps 16 128-wide slabs, towards a
// 48-block grid or, at K >= 8192, regardless; never past ks*M = 1024.
// - slab: 128, or 64 where LDS per block would cost a wide grid its resident blocks (see
// mxd_plan); past 64 rows always 128. A K not a multiple of 128 takes 64 (and a 2-way split
// widens to 4).
// - non-temporal weight loads for weights of 4 MiB or more.
// The split count sets a row's summation order, so a change to the rule moves the bits of the rows
// it splits differently.
//
// No state is keyed on the stream, since a recorded pass may replay on another stream. The split
// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get
@@ -77,9 +83,10 @@ static __device__ __forceinline__ T mxd_ld(const T* p) {
// and writes its eight outputs as one 16-byte store (one 32-byte store of partials).
// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a
// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging
// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is
// looked up from the grid.
// boundary early and writes s_prev / s_next to LDS for the boundary's slab (the one-fragment kernel
// at that slab, published by its staging barrier; the multi-fragment kernel a slab early into the
// other half of its double buffer, published by the slab's closing barrier). A zero next block
// keeps the carried scale; after a zero block the carried scale is looked up from the grid.
static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row,
int kb) {
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
@@ -195,6 +202,12 @@ constexpr int mxd_waves(int dbk, int dtm, bool ablk) {
: 6;
}
// The multi-fragment form (M > 16). A fragment-order weight word is the WMMA fragment's own
// register (one dword a lane a k-step), so a wave loads its tile's words for a slab straight to
// registers and folds them there, with no barrier between a wave and its weight. Only the
// activation, shared by the eight tiles, goes through LDS, double-buffered so a slab takes one
// barrier. The next slab's activation and weight are loaded while this slab computes. The fold,
// k-step and slab order, scale carry and epilogue are the one-fragment form's (below).
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(mxd_waves(DBK, DTM, ABLK))
void r4d_gemm_mxfp4a8_decode_kernel(
@@ -206,16 +219,16 @@ void r4d_gemm_mxfp4a8_decode_kernel(
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
constexpr int KST = DBK / 16; // k-steps a slab
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
__shared__ unsigned char sA[2][ROWS * STR];
__shared__ float sR[2][ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
@@ -231,88 +244,104 @@ void r4d_gemm_mxfp4a8_decode_kernel(
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
// This wave's tile and this lane's column. A tile past N (N % 128 != 0) loads the last one, and
// the epilogue drops its columns.
const int nt = min(n0 / 16 + wave, N / 16 - 1);
const int ncol = nt * 16 + col;
const int ref = (int)Wref[ncol];
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
for (int s = s_lo; s < s_hi; ++s) {
unsigned rw[KST];
int re[KST / 2];
mxd_u4 ra[A_IT];
auto load = [&](int s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
}
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
#pragma unroll
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
const int idx = off + tid * 16;
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
ra[j] = *(const mxd_u4*)(A + (size_t)rc * lda + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
{
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
const int kstep0 = k0 / 16;
#pragma unroll
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
const int sl = off + tid * 2;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
const int gn = n0 + r;
// gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in
// bounds; the slot address is recomputed from the clamped row.
const int gc = gn < N - 2 ? gn : N - 2;
const int lanec = (lane_ & 16) | (gc & 15);
const mxd_u2 wv =
mxd_ld<NT>((const mxd_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
lanec]);
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
for (int t = 0; t < KST; ++t)
rw[t] = mxd_ld<NT>(&Wp[((size_t)nt * ksteps_g + k0 / 16 + t) * 32 + lane]);
#pragma unroll
for (int q = 0; q < 2; ++q) {
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
unsigned int lo, hi;
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
}
for (int q = 0; q < KST / 2; ++q)
re[q] = (int)Ws[(size_t)(k0 / R4D_MXFP4_GROUP + q) * ldws + ncol];
};
auto store_a = [&](int buf) {
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
*(mxd_u4*)(&sA[buf][r * STR + c]) = ra[j];
}
}
__syncthreads();
};
if (s_lo < s_hi) {
load(s_lo);
store_a(0); // the first slab never rescales (s > s_lo below)
}
__syncthreads();
for (int s = s_lo; s < s_hi; ++s) {
const int buf = (s - s_lo) & 1;
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
mxd_v2i wf[KST];
#pragma unroll
for (int t = 0; t < KST; ++t) {
unsigned lo, hi;
r4d_mxfp4_unpack8(rw[t], r4d_mxfp4_fold_d(ref, re[t >> 1]), &lo, &hi);
wf[t][0] = (int)lo; wf[t][1] = (int)hi;
}
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
if constexpr (ABLK) {
if (bnd) mxd_rescale(acc, sR, col);
if (bnd) mxd_rescale(acc, sR[buf], col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
for (int step = 0; step < KST; ++step) {
const int kk = step * 16 + kb8;
mxd_v2i af[DTM], wf;
mxd_v2i af[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
const unsigned char* pa = &sA[buf][(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[step], af[i], acc[i]);
}
// The next slab's activation into the other buffer, and its boundary ratio (published by the
// barrier below; a wave still rescaling this slab reads the other half).
if (s + 1 < s_hi) {
store_a(buf ^ 1);
if constexpr (ABLK) {
const int k1 = (s + 1) * DBK;
if ((k1 & 127) == 0 && tid < ROWS) sR[buf ^ 1][tid] = mxd_ratio(ns, np, asrow, k1 >> 7);
}
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
kb_end, &s_last, sR[0]);
}
// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as
// above, plus: the next slab's A, codes and exponents are loaded into registers while this slab
// computes, keeping loads in flight across barriers; a thread takes four adjacent slots (one 16 B
// load); and each row's reference exponent is read once. Bit-identical to the kernel above.
// above, with the weight staged through LDS, plus: the next slab's A, codes and exponents are
// loaded into registers while this slab computes, keeping loads in flight across barriers; a thread
// takes four adjacent slots (one 16 B load); and each row's reference exponent is read once.
// Bit-identical to the kernel above.
template <int DBK, int DKS, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
void r4d_gemm_mxfp4a8_decode1_kernel(
@@ -472,8 +501,9 @@ unsigned* mxd_out_ctr(const void* out) {
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
// need not wait for, so wait here (as r4d_moe.hip's router counters do).
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
// null stream, which a non-blocking stream does not wait for, so wait here.
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return nullptr;
@@ -490,14 +520,24 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
MxdPlan p;
int ks = 1;
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
if (tm > 4) {
// Past 64 rows (see the header): split only while every split keeps 16 128-wide slabs, towards
// a 48-block grid, or at a deep K regardless.
const int slabs = K / 128;
while (ks < R4D_MXD_MAX_KS && (nblk * ks < 48 || K >= 8192) && slabs / (2 * ks) >= 16 &&
2 * ks * M <= 1024)
ks <<= 1;
} else {
const int fill = M <= 16 ? 48 : 56;
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
}
p.ks = KS > 0 ? KS : ks;
// 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column
// blocks, and DTM 8 on those or at a split of 4 or more.
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
// blocks, by the split the launch runs (a pin or a tuned point included); past 64 rows the
// 128-wide slab always.
const bool slab64 = tm == 4 && p.ks == 1 && nblk >= 110;
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
if (K % p.bk) { // a slab may not run past K
+348
View File
@@ -0,0 +1,348 @@
// r4d_gemm_mxfp4a8_gemv.hip - r4d_gemm_mxfp4a8_gemv: the OCP-MXFP4 x fp8 GEMM for one to eight rows
// (and, its WMMA form alone, up to 64: the gemv_wide row), gfx1201. C[M,N] = A[M,K] @
// dequant(Wq)[N,K]^T with the operands, weight layout and fold of r4d_gemm_mxfp4a8_decode (and
// _nt_m64, _tiled).
//
// At one stream's decode (M = 1, or 1 + the draft depth) the GEMM is a pure weight stream, and the
// decode kernel's WMMA tile spends its time staging the weight through LDS between two barriers a
// slab, which leaves narrow projections at a third to two thirds of DRAM bandwidth. This kernel
// keeps the weight out of LDS altogether: every lane loads the weight words it multiplies, folds
// them to e4m3 in registers by r4d_mxfp4_unpack8 exactly as the other MXFP4 kernels fold them (the
// same weight bytes in every M band), and the block's waves split K and meet once in LDS at the end.
//
// Two forms, chosen from K alone so that a row's output bits do not depend on how many rows the
// step carries (a verify step's first row is bit-identical to a plain decode of it):
//
// - K a multiple of 128: the WMMA form. One 16-column tile a block (two from 25 rows where
// N >= 4096, K >= 3072 and the tile count is even), eight waves on its K in chunks of one 128
// block, and up to four 16-row tiles (M <= 64), each weight word multiplied with every row
// tile's fragment once it is loaded. A lane loads its own B-fragment word of each k-step
// straight from the fragment-order weight (the order is the fragment's), the rows sit in the A
// fragments (rows >= M zero), and v_wmma_f32_16x16x16_fp8_fp8 multiplies. The per-(row, 128)
// activation scale is applied to each chunk's partial. At M = 1 the WMMA does sixteen times the
// work it needs, which costs nothing next to the weight stream; from M = 2 up it is what keeps
// the kernel on the stream (the dot form pays a dot per row).
// - Otherwise (K = 64 mod 128): the dot form. A lane loads 16 bytes -- four columns' eight codes of
// one k-step -- so a wave reads four k-steps, 512 contiguous bytes, from each of its TN tiles, and
// multiplies with v_dot4_f32_fp8_fp8; the activation a lane reads (eight k of each row) serves its
// four columns in all TN tiles. A k-step group (64 of K) lies in one 128 block, so the activation
// scale is applied as each partial is made. The lanes holding the same columns are summed by
// shuffles. TN only widens a block; the sum order of a column is fixed by KW, which is constant.
//
// The column's 2^(ref - 127) is applied once, as in the decode kernel's epilogue. No scratch and no
// counters: there is no split across blocks.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
#define R4D_MXG_MAX_M 8
#define R4D_MXG_WMMA_MAX_M 64 // the WMMA form's bound: four 16-row tiles a wave
#define R4D_MXG_KW 8 // waves on a block's K, both forms; a constant, so the sum order is too
typedef unsigned mxg_u4 __attribute__((ext_vector_type(4)));
typedef unsigned mxg_u2 __attribute__((ext_vector_type(2)));
typedef float mxg_v8f __attribute__((ext_vector_type(8)));
typedef int mxg_v2i __attribute__((ext_vector_type(2)));
// The dot form: TN 16-column tiles a block, MT >= M rows. Needs K % 64 == 0.
template <int MT, int TN, bool ABLK>
__global__ __launch_bounds__(R4D_MXG_KW * 32)
void r4d_gemm_mxfp4a8_gemv_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C, int M, int K,
int as_rs, int lda, int ldws, int ldc) {
constexpr int KW = R4D_MXG_KW;
__shared__ float sP[KW][MT][16 * TN];
const int lane = threadIdx.x & 31;
const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5); // uniform: scalar loads
const int nt0 = blockIdx.x * TN; // the block's first 16-column tile
const int g = lane & 7, j = lane >> 3; // the slot quad in a k-step; the k-step of four
const int khalf = g >> 2, cq = (g * 4) & 15; // this lane's k half and first of its four columns
const int ksteps = K >> 4, groups = K >> 6;
const mxg_u4* __restrict__ Wv = (const mxg_u4*)W;
int ref[TN][4];
#pragma unroll
for (int t = 0; t < TN; ++t) {
const unsigned r4 = *(const unsigned*)(Wref + (nt0 + t) * 16 + cq);
#pragma unroll
for (int c = 0; c < 4; ++c) ref[t][c] = (int)((r4 >> (8 * c)) & 0xFFu);
}
float acc[MT][TN][4];
#pragma unroll
for (int m = 0; m < MT; ++m)
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int c = 0; c < 4; ++c) acc[m][t][c] = 0.f;
#pragma unroll 4
for (int gi = wave; gi < groups; gi += KW) {
const int kstep = gi * 4 + j;
const int k0 = kstep * 16 + khalf * 8;
const int kb = gi >> 1; // the wave's 128 block (a group is 64 of K)
mxg_u4 wv[TN];
unsigned e4[TN];
#pragma unroll
for (int t = 0; t < TN; ++t) {
wv[t] = __builtin_nontemporal_load(&Wv[((size_t)(nt0 + t) * ksteps + kstep) * 8 + g]);
e4[t] = *(const unsigned*)(Ws + (size_t)(k0 >> 5) * ldws + (nt0 + t) * 16 + cq);
}
unsigned lo[TN][4], hi[TN][4];
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int c = 0; c < 4; ++c)
r4d_mxfp4_unpack8(wv[t][c], r4d_mxfp4_fold_d(ref[t][c], (int)((e4[t] >> (8 * c)) & 0xFFu)),
&lo[t][c], &hi[t][c]);
#pragma unroll
for (int m = 0; m < MT; ++m) {
if (m < M) {
const mxg_u2 av = *(const mxg_u2*)(A + (size_t)m * lda + k0);
const float sc = ABLK ? As[(size_t)m * as_rs + kb] : 1.f;
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int c = 0; c < 4; ++c) {
float d = __builtin_amdgcn_dot4_f32_fp8_fp8(lo[t][c], av.x, 0.f);
d = __builtin_amdgcn_dot4_f32_fp8_fp8(hi[t][c], av.y, d);
acc[m][t][c] = ABLK ? fmaf(d, sc, acc[m][t][c]) : acc[m][t][c] + d;
}
}
}
}
// The lanes with the same columns: the other k half (lane ^ 4) and the other k-steps (^ 8, ^ 16).
#pragma unroll
for (int m = 0; m < MT; ++m)
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int c = 0; c < 4; ++c) {
float v = acc[m][t][c];
v += __shfl_xor(v, 4, 32);
v += __shfl_xor(v, 8, 32);
v += __shfl_xor(v, 16, 32);
acc[m][t][c] = v;
}
if (lane < 4) {
#pragma unroll
for (int m = 0; m < MT; ++m)
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int c = 0; c < 4; ++c) sP[wave][m][t * 16 + cq + c] = acc[m][t][c];
}
__syncthreads();
for (int idx = threadIdx.x; idx < MT * 16 * TN; idx += KW * 32) {
const int m = idx / (16 * TN), cc = idx % (16 * TN);
if (m < M) {
float sum = 0.f;
#pragma unroll
for (int w = 0; w < KW; ++w) sum += sP[w][m][cc];
const int col = nt0 * 16 + cc;
const float rf = __int_as_float((int)Wref[col] << 23);
C[(size_t)m * ldc + col] = (__hip_bfloat16)(ABLK ? sum * rf : sum * rf * As[(size_t)m * as_rs]);
}
}
}
// The WMMA form: TN 16-column tiles a block, RT 16-row tiles (M <= 16 RT). Needs K % 128 == 0 (a
// chunk is a whole 128 block; a tail would be dropped); the launcher guarantees it and picks RT and TN.
// A wave loads each weight word of a chunk once and runs one WMMA chain per row tile over it, so the
// weight streams once whatever M is, and a row's sum is its tile's chain alone -- the same at every RT
// and TN.
//
// TN: the activation is read per block, so with one column tile a block it is read N/16 times
// (356 MB from L2 at M = 64 on a 17408 x 5120 weight, against its 47 MB). Two tiles a block load
// each activation fragment once for both. On narrow or shallow weights two tiles lose (fewer
// blocks than the part has units, a short K a wave), so the launcher takes two only from N 4096
// and K 3072, past 24 rows. Four tiles spill past 32 rows.
template <bool ABLK, int RT, int TN = 1>
__global__ __launch_bounds__(R4D_MXG_KW * 32)
void r4d_gemm_mxfp4a8_gemvw_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C, int M, int K,
int as_rs, int lda, int ldws, int ldc) {
constexpr int KW = R4D_MXG_KW;
__shared__ float sP[KW][16 * RT][16];
const int lane = threadIdx.x & 31;
const int wave = __builtin_amdgcn_readfirstlane(threadIdx.x >> 5);
const int nt0 = blockIdx.x * TN;
const int col = lane & 15, khalf = lane >> 4; // B fragment: this lane's column and k half
const int ksteps = K >> 4, chunks = K >> 7;
const unsigned* __restrict__ Wp = (const unsigned*)W;
int ref[TN];
#pragma unroll
for (int t = 0; t < TN; ++t) ref[t] = (int)Wref[(nt0 + t) * 16 + col];
mxg_v8f tot[RT][TN];
#pragma unroll
for (int r = 0; r < RT; ++r)
#pragma unroll
for (int t = 0; t < TN; ++t) tot[r][t] = (mxg_v8f)(0.f);
for (int ch = wave; ch < chunks; ch += KW) {
unsigned wv[TN][8];
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int s = 0; s < 8; ++s)
wv[t][s] = __builtin_nontemporal_load(&Wp[((size_t)(nt0 + t) * ksteps + ch * 8 + s) * 32 + lane]);
int e8[TN][4];
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int q = 0; q < 4; ++q) e8[t][q] = (int)Ws[(size_t)(ch * 4 + q) * ldws + (nt0 + t) * 16 + col];
mxg_v2i wf[TN][8];
#pragma unroll
for (int t = 0; t < TN; ++t)
#pragma unroll
for (int s = 0; s < 8; ++s) {
unsigned lo, hi;
r4d_mxfp4_unpack8(wv[t][s], r4d_mxfp4_fold_d(ref[t], e8[t][s >> 1]), &lo, &hi);
wf[t][s][0] = (int)lo; wf[t][s][1] = (int)hi;
}
#pragma unroll
for (int r = 0; r < RT; ++r) {
const int row = r * 16 + col; // A fragment: this lane's row in tile r
const bool live = row < M;
mxg_v2i af[8];
#pragma unroll
for (int s = 0; s < 8; ++s) {
if (live) {
const unsigned* pa = (const unsigned*)(A + (size_t)row * lda + (ch * 8 + s) * 16 + khalf * 8);
af[s][0] = (int)pa[0]; af[s][1] = (int)pa[1];
} else {
af[s][0] = 0; af[s][1] = 0;
}
}
const float sc = ABLK ? (live ? As[(size_t)row * as_rs + ch] : 0.f) : 1.f;
#pragma unroll
for (int t = 0; t < TN; ++t) {
mxg_v8f acc = (mxg_v8f)(0.f);
#pragma unroll
for (int s = 0; s < 8; ++s)
acc = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[t][s], af[s], acc);
// acc[e]: row (lane & 15) of tile r, column (lane >> 4) * 8 + e -- as the decode epilogue reads it.
#pragma unroll
for (int e = 0; e < 8; ++e) tot[r][t][e] = fmaf(acc[e], sc, tot[r][t][e]);
}
}
}
// One column tile at a time through sP (TN of them would not fit in LDS at four row tiles).
#pragma unroll
for (int t = 0; t < TN; ++t) {
if (t) __syncthreads();
#pragma unroll
for (int r = 0; r < RT; ++r)
#pragma unroll
for (int e = 0; e < 8; ++e) sP[wave][r * 16 + col][khalf * 8 + e] = tot[r][t][e];
__syncthreads();
for (int idx = threadIdx.x; idx < 16 * RT * 16; idx += KW * 32) {
const int m = idx >> 4, c = idx & 15;
if (m < M) {
float sum = 0.f;
#pragma unroll
for (int w = 0; w < KW; ++w) sum += sP[w][m][c];
const int cc = (nt0 + t) * 16 + c;
const float rf = __int_as_float((int)Wref[cc] << 23);
C[(size_t)m * ldc + cc] = (__hip_bfloat16)(ABLK ? sum * rf : sum * rf * As[(size_t)m * as_rs]);
}
}
}
}
namespace {
void mxg_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
int as_group, int as_rs, long stream, int lda, int ldws, int ldc) {
if (M < 1 || M > (K % 128 == 0 ? R4D_MXG_WMMA_MAX_M : R4D_MXG_MAX_M))
throw std::runtime_error("r4d gemm_mxfp4a8_gemv: M must be 1..8, or 1..64 when K % 128 == 0");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_gemv: N must be a multiple of 16");
if (K < 64 || K % 64) throw std::runtime_error("r4d gemm_mxfp4a8_gemv: K must be a multiple of 64");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_gemv: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
const int tiles = N / 16;
hipStream_t st = (hipStream_t)stream;
auto Ap = (const unsigned char*)a;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
const dim3 block(R4D_MXG_KW * 32);
if (K % 128 == 0) {
const int rt = (M + 15) / 16;
// Two column tiles a block from 25 rows on a wide and deep enough weight (see the kernel); an
// odd tile count keeps one.
const bool tn2 = M > 24 && tiles % 2 == 0 && N >= 4096 && K >= 3072;
#define MXW_L(AB_, RT_, TN_) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gemvw_kernel<AB_, RT_, TN_>), \
dim3(tiles / TN_), block, 0, st, Ap, Sp, Wp, Zp, Rp, \
Cp, M, K, as_rs, lda, ldws, ldc)
#define MXW_TN(AB_, RT_) { if (tn2) MXW_L(AB_, RT_, 2); else MXW_L(AB_, RT_, 1); }
#define MXW_AB(RT_) { if (ablk) MXW_TN(true, RT_) else MXW_TN(false, RT_) }
// One row tile is at most 16 rows, below the two-column threshold.
if (rt <= 1) { if (ablk) MXW_L(true, 1, 1); else MXW_L(false, 1, 1); }
else if (rt == 2) MXW_AB(2) else if (rt == 3) MXW_AB(3) else MXW_AB(4)
#undef MXW_AB
#undef MXW_TN
#undef MXW_L
return;
}
// Tiles a block carries: enough to amortise the activation loads at several rows, the widest that
// divides the tile count.
int tn = M >= 3 ? 4 : (M == 2 ? 2 : 1);
while (tn > 1 && tiles % tn) tn >>= 1;
const dim3 grid(tiles / tn);
#define MXG_L(MT_, TN_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_gemv_kernel<MT_, TN_, AB_>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Rp, Cp, M, K, as_rs, lda, ldws, ldc)
#define MXG_AB(MT_, TN_) { if (ablk) MXG_L(MT_, TN_, true); else MXG_L(MT_, TN_, false); }
#define MXG_TN(MT_) { if (tn == 4) MXG_AB(MT_, 4) else if (tn == 2) MXG_AB(MT_, 2) else MXG_AB(MT_, 1) }
if (M == 1) MXG_AB(1, 1)
else if (M == 2) { if (tn == 2) MXG_AB(2, 2) else MXG_AB(2, 1) }
else if (M <= 4) MXG_TN(4)
else MXG_TN(8)
#undef MXG_TN
#undef MXG_AB
#undef MXG_L
}
} // namespace
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
/* The dot form reads four columns' exponents and references as one word. */
if (!r4d_aligned((const void*)r4d_addr(g.bscale), 4) || !r4d_aligned((const void*)r4d_addr(g.bref), 4))
return R4D_NO(RAD_E_ALIGN);
MxParts mp;
rc = mx_parts(a, &g, &mp);
if (rc != RAD_OK) return rc;
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > (g.K % 128 == 0 ? R4D_MXG_WMMA_MAX_M : R4D_MXG_MAX_M)) return R4D_NO(RAD_E_SHAPE);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
if (rc != RAD_OK) return rc;
const long long kb = (g.K + 127) / 128;
for (int p = 0; p < mp.n; ++p) {
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
R4D_TRY("gemm_mxfp4a8_gemv",
mxg_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
r4d_addr(g.bref) + n0, r4d_addr(g.y) + n0 * 2,
(int)g.M, (int)g.K, (int)np, as_group, as_rs, (long)(uintptr_t)s,
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
}
return RAD_OK;
}
+108 -34
View File
@@ -24,13 +24,24 @@
// 2^(Wref[n]-127) is applied in the epilogue (see r4d_gemm_mxfp4a8_nt_m64.hip).
//
// Tile: 8 waves as 4 (M) x 2 (N), each owning TM=4 x TN fragments, so a block covers BMF = 256
// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and only wins on long prompts
// (crossover near M=2048 on a 17408x5120 weight), so tn=0 picks TN=4 from M >= 2048. The K slab is
// 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators.
// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and wins from M = 1024 on
// (on gfx1201 at a 27B's per-rank weights, mixed below), so tn=0 picks TN=4 from M >= 1024. The K
// slab is 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators.
// TN does not change an output's bits: each fragment runs the same WMMAs in the same K order.
//
// Barriers fence LDS only: __syncthreads() also drains the global load counter, and nothing in
// global memory is shared between the waves, so the next slab's A loads stay in flight.
//
// The weight words and exponents a thread stages are loaded a slab ahead, into registers, right
// after the staging barrier, so their DRAM round trip runs under the slab's WMMAs instead of in
// front of the next unpack (+1 VGPR at TN=4). Loading the A fragments a slab ahead too (+38 VGPRs)
// is slower.
//
// A thin last row of blocks (1..160 rows, under 1024 rows in all) runs a second kernel whose
// blocks of that row skip the WMMAs of their padding fragments past M. Every other M runs the
// plain kernel, whose body declares its own LDS: a guard inside the one kernel, or the body
// taking the LDS by pointer, slows the full blocks.
//
// Staging is clamped, never predicated: a predicated load gets its own exec-mask region and the
// compiler cannot carry a counted s_wait_loadcnt across the merge. Clamped loads (tile past M ->
// last real tile, row past N -> last aligned group) issue back to back; the epilogue drops them.
@@ -63,7 +74,7 @@
#define R4D_MXT_NTHR (R4D_MXT_WM * R4D_MXT_WN * 32)
#define R4D_MXT_BMF (R4D_MXT_WM * R4D_MXT_TM * 16)
#define R4D_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
#define R4D_MXT_TN4_MIN_M 2048 // tn=0's crossover, see above
#define R4D_MXT_TN4_MIN_M 1024 // tn=0's crossover, see above
typedef int mxt_v2i __attribute__((ext_vector_type(2)));
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
@@ -85,12 +96,16 @@ __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
*(mxt_u2*)(AT + o * 8) = v;
}
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
// The kernel's body. OWN: it declares its LDS arrays itself (the plain kernel); otherwise it takes
// the caller's (the two-body kernel, one set for both bodies). PART: a block the M edge cuts,
// which skips the WMMAs of its padding fragments past M.
template <int TN, int LBK, bool ABLK, bool PART, bool OWN>
__device__ __forceinline__ void r4d_gemm_mxfp4a8_tiled_body(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs, int ldws, int ldc) {
int M, int K, int N, int as_rs, int ldws, int ldc, unsigned char* __restrict__ sW_in,
unsigned int* __restrict__ sMag_in, float* __restrict__ sR_in) {
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
@@ -98,15 +113,23 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[32];
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
__shared__ unsigned char sW_own[OWN ? BNF * STR : 1];
__shared__ unsigned int sMag_own[OWN ? 32 : 1];
__shared__ float sR_own[OWN && ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
unsigned char* __restrict__ sW = OWN ? sW_own : sW_in;
unsigned int* __restrict__ sMag = OWN ? sMag_own : sMag_in;
float* __restrict__ sR = OWN ? sR_own : sR_in;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int wm = wave / WN, wn = wave % WN;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
const int ksteps = K / 16, Mt = (M + 15) >> 4;
// PART: this wave's M fragments that hold a row below M, 0..TM and wave-uniform; the rest are
// padding whose WMMAs are skipped (their rows are dropped at the store). Their A loads stay,
// clamped, in the slab's one clause.
const int live = PART ? __builtin_amdgcn_readfirstlane(min(TM, max(0, Mt - ((m0 >> 4) + wm * TM))))
: TM;
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
@@ -155,6 +178,31 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
lds_barrier(); // sMag
// The slab's weight words and exponents, loaded a slab ahead (the first one here).
unsigned int wqn[NW][WSLOTS], wswn[NW];
auto wload = [&](int k0) {
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
if constexpr (WSLOTS == 4) {
const mxt_u4 v = *(const mxt_u4*)src;
wqn[it][0] = v[0]; wqn[it][1] = v[1]; wqn[it][2] = v[2]; wqn[it][3] = v[3];
wswn[it] = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const mxt_u2 v = *(const mxt_u2*)src;
wqn[it][0] = v[0]; wqn[it][1] = v[1];
wswn[it] = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
} else {
wqn[it][0] = *src;
wswn[it] = Ws[(size_t)blk * ldws + wrc[it]];
}
}
};
wload(0);
for (int k0 = 0; k0 < K; k0 += LBK) {
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
@@ -172,36 +220,20 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
for (int st = 0; st < NS; ++st)
af[i][st] = *(const mxt_v2i*)(abase[i] +
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
// W slab -> LDS, folded to e4m3.
const int kstep0 = k0 / 16;
// W slab -> LDS, folded to e4m3, from the words loaded a slab ago.
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
unsigned int wq[WSLOTS], wsw;
if constexpr (WSLOTS == 4) {
const mxt_u4 v = *(const mxt_u4*)src;
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const mxt_u2 v = *(const mxt_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * ldws + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
(int)((wsw >> (8 * q)) & 0xFF));
(int)((wswn[it] >> (8 * q)) & 0xFF));
unsigned int lo, hi;
r4d_mxfp4_unpack8_t(wq[q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
r4d_mxfp4_unpack8_t(wqn[it][q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
}
}
lds_barrier();
if (k0 + LBK < K) wload(k0 + LBK); // the next slab's weight flies across this slab's WMMAs
if constexpr (ABLK) {
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
@@ -235,11 +267,13 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
// loads above the first WMMA.
__builtin_amdgcn_sched_barrier(0);
#pragma unroll
for (int i = 0; i < TM; ++i)
for (int i = 0; i < TM; ++i) {
if (PART && i >= live) break; // wave-uniform: padding fragments past M
#pragma unroll
for (int j = 0; j < TN; ++j)
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
acc[i][j]);
}
}
lds_barrier();
}
@@ -287,6 +321,37 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
}
}
// The plain kernel: every block the unguarded body, over the body's own LDS.
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs, int ldws, int ldc) {
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, true>(AT, As, W, Ws, Wref, C, M, K, N, as_rs, ldws,
ldc, nullptr, nullptr, nullptr);
}
// The two-body kernel, for a thin last row of blocks: a block of that row takes the guarded body,
// every other block the unguarded one, uniform over the block, over one set of LDS arrays.
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_part_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs, int ldws, int ldc) {
constexpr int BNF = R4D_MXT_WN * TN * 16, STR = LBK + R4D_MXT_PAD;
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[32];
__shared__ float sR[ABLK ? R4D_MXT_BMF : 1];
if ((int)(blockIdx.y + 1) * R4D_MXT_BMF > M)
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, true, false>(AT, As, W, Ws, Wref, C, M, K, N, as_rs,
ldws, ldc, sW, sMag, sR);
else
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, false>(AT, As, W, Ws, Wref, C, M, K, N, as_rs,
ldws, ldc, sW, sMag, sR);
}
extern "C" int r4d_gemm_mxfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
@@ -332,9 +397,18 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define MXT_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
// The two-body kernel only for a thin last row of blocks (1..160 rows) under 1024 rows; see the
// header.
const int rem = M % R4D_MXT_BMF;
const bool part = rem > 0 && rem <= 160 && M < 1024;
#define MXT_LAUNCH(TNv, LBKv, ABv) do { \
if (part) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_part_kernel<TNv, LBKv, ABv>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
else \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, \
Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
} while (0)
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
+3 -5
View File
@@ -100,11 +100,9 @@ int gemm_f32_body(const RadArgs* a, RadStream stream) {
/* The tile form, rows x columns per wave and steps of k in flight, by M; all forms are
* byte-identical, so the choice is speed only. 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. Below 64 rows the steps in flight decide: at N 288 one step
* a lane took 28.1 / 36.0 / 36.3 / 41.9 / 45.4 / 47.9 us at 1 / 4 / 8 / 16 / 24 / 48 rows,
* 2x2 with 16 steps 14.4 / 14.5 / 15.0 / 19.1 us to 16 rows and 8x1 with 8 steps 21.6 / 35.5
* us at 24 / 48; at N 32 2x2 with 16 steps 9.8 to 10.2 us at every count below 64, where one
* step took 27.3 to 36.4.
* N 36; 8x4 holds at every width. Below 64 rows the steps of k in flight decide: 2x2 with 16
* steps is 2 to 2.5 times as fast as one step at N 288 up to 16 rows, and about 3 times at N 32
* at every count below 64; at N 288 from 17 rows 8x1 with 8 steps is faster.
* A projection of a few columns has too few waves for wide tiles at any M. */
const long rows = x.shape[0];
if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
+3 -2
View File
@@ -2187,8 +2187,9 @@ unsigned int* hc_mix_ctr(RadStream s) {
if (fi < 0) return nullptr;
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
/* Zero before any launch reads it: the memset is on the null stream, which the engine's
* streams need not wait for, so wait here (as r4d_moe.hip's router counters do). */
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess ||
hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
+1 -36
View File
@@ -284,7 +284,7 @@ __global__ __launch_bounds__(kT) void s2d3d_kernel(
}
}
// ---------------------------------------------------------------------------- pix_patch / patch_pix8
// ---------------------------------------------------------------------------- pix_patch
__device__ __forceinline__ int patch_col(int c, int ph, int pw, int p, bool wh) {
return c * p * p + (wh ? pw * p + ph : ph * p + pw);
}
@@ -305,23 +305,6 @@ __global__ __launch_bounds__(kT) void pix_patch_kernel(
}
}
// A thread an output byte.
__global__ __launch_bounds__(kT) void patch_pix8_kernel(
const void* __restrict__ x, uint8_t* __restrict__ y, long long R, int w, int C, int p, bool wh,
long long x_ld, long long y_ld, bool xbf) {
const long long Wp = (long long)w * p * C, n = R * p * Wp;
for (long long e = (long long)blockIdx.x * kT + threadIdx.x; e < n;
e += (long long)gridDim.x * kT) {
const long long yy = e / Wp;
const int rem = (int)(e % Wp), xx = rem / C, c = rem % C;
const float v = ldx(x, (size_t)((yy / p) * x_ld + (long long)(xx / p) * C * p * p +
patch_col(c, (int)(yy % p), xx % p, p, wh)), xbf);
const float cl = fminf(fmaxf(v, -1.0f), 1.0f);
const float u = fminf(fmaxf(rdx(rdx(cl / 2.0f, xbf) + 0.5f, xbf), 0.0f), 1.0f);
y[yy * y_ld + xx * C + c] = (uint8_t)rintf(u * 255.0f);
}
}
// ---------------------------------------------------------------------------- attn_na3d
// 3-D neighborhood attention (libref/ref_attn.cpp states it): a thread a (query, head), its query
// in registers, the window's keys streamed from memory -- neighbouring queries share all but a
@@ -904,24 +887,6 @@ extern "C" int r4d_rad_pix_patch(const RadArgs* a, RadStream s) {
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_patch_pix8(const RadArgs* a, RadStream s) {
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
if (!is_bf_or_f32(x) || y->dtype != RAD_U8) return R4D_NO(RAD_E_DTYPE);
const long long p = r4d_geti_or(a, "p", 0), C = r4d_geti_or(a, "C", 0);
const int wh = patch_order(a);
if (wh < 0) return R4D_NO(RAD_E_INVAL);
long long R = 0, Cx = 0, xl = 0, Ry = 0, Cy = 0, yl = 0;
if (!dense2(x, &R, &Cx, &xl) || !dense2(y, &Ry, &Cy, &yl)) return R4D_NO(RAD_E_SHAPE);
if (p <= 0 || C <= 0 || Cx % (C * p * p)) return R4D_NO(RAD_E_SHAPE);
const long long w = Cx / (C * p * p);
if (Ry != R * p || Cy != w * p * C) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL(patch_pix8_kernel, dim3(grid_for(Ry * Cy)), dim3(kT), 0, (hipStream_t)s,
x->data, (uint8_t*)y->data, R, (int)w, (int)C, (int)p, wh == 1, xl, yl,
is_bf16(x));
return st_of(hipGetLastError());
}
extern "C" int r4d_rad_attn_na3d(const RadArgs* a, RadStream s) {
const RadTensor *q = r4d_opt(a, 0), *k = r4d_opt(a, 1), *v = r4d_opt(a, 2), *g = r4d_opt(a, 3);
const RadTensor* o = r4d_opt(a, 4);
+248 -4
View File
@@ -537,9 +537,185 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
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';
/* ROWS gives a workgroup one query row and HG groups of sixteen heads, four waves a group, so a
* key chunk is loaded once for 16*HG heads instead of the head-tiled row's sixteen. GLM's prefill
* splits attention by rows, one rank holding all 64 heads of its rows; that is what this serves.
*
* Scores are S^T = K Q^T: tokens are the matrix rows and heads the columns, so a head is a lane
* and its running maximum and denominator stay in registers. Each wave of a group takes a quarter
* of the latent dimension; the four partial dot products meet in LDS and every wave of the group
* adds them in the same order, so all four hold identical scores and statistics. The
* probabilities become the second product's B operand with one permlanex16 swap, and each wave
* accumulates O^T for its quarter of the latent columns, the keys read transposed from the tile.
* The next chunk's keys are fetched into registers while the current one is multiplied, so a
* chunk costs two barriers. */
constexpr int kRowsPitch = 520;
template <int HG, bool WIDE>
__global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const uint16_t* kv,
const int* bt, const int* len,
uint16_t* out, float* scratch, Meta m) {
constexpr int NT = HG * 128, LOADS = 16 * 64 / NT;
static_assert(LOADS * NT == 16 * 64 && LOADS <= 32, "a chunk's 16-byte pieces over the group");
__shared__ __align__(16) uint16_t keys[2][16 * kRowsPitch];
__shared__ __align__(32) float partial[HG * 4][32 * 8];
__shared__ int visible[2][16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, quarter = wave & 3,
group = wave >> 2, r = blockIdx.x, split = blockIdx.z;
const int head = blockIdx.y * 16 * HG + group * 16 + (lane & 15);
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);
v8bf query[8];
{
const uint16_t* qp =
q + (long)r * m.qr + (long)head * m.qh + quarter * 128 + 4 * (lane >> 4);
#pragma unroll
for (int s = 0; s < 8; ++s) {
union {
uint16_t h[8];
v8bf f;
} u;
#pragma unroll
for (int e = 0; e < 4; ++e) {
u.h[e] = qp[s * 16 + e];
u.h[4 + e] = qp[s * 16 + 8 + e];
}
query[s] = u.f;
}
}
uint4 staged[LOADS];
unsigned staged_ok = 0;
auto fetch = [&](int start) {
#pragma unroll
for (int j = 0; j < LOADS; ++j) {
const int flat = tid + j * NT, token = start + (flat >> 6), piece = flat & 63;
const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1;
const bool ok = page >= 0 && page < m.pages;
const long at = ok ? (long)page * m.kp + (token % m.bs) * m.kt + piece * 8 : 0;
if constexpr (WIDE) {
staged[j] = *(const uint4*)(kv + at);
if (!ok) staged[j] = make_uint4(0, 0, 0, 0);
} else {
uint32_t w[4];
#pragma unroll
for (int i = 0; i < 4; ++i)
w[i] = ok ? (uint32_t)kv[at + 2 * i] | (uint32_t)kv[at + 2 * i + 1] << 16 : 0u;
staged[j] = make_uint4(w[0], w[1], w[2], w[3]);
}
staged_ok = ok ? staged_ok | 1u << j : staged_ok & ~(1u << j);
}
};
auto stash = [&](int b) {
#pragma unroll
for (int j = 0; j < LOADS; ++j) {
const int flat = tid + j * NT, token = flat >> 6, piece = flat & 63;
*(uint4*)(keys[b] + token * kRowsPitch + piece * 8) = staged[j];
if (!piece) visible[b][token] = (int)(staged_ok >> j & 1u);
}
};
v8f value[8];
#pragma unroll
for (int mt = 0; mt < 8; ++mt) value[mt] = (v8f){ 0 };
float run_max = -INFINITY, run_den = 0;
fetch(begin);
stash(0);
__syncthreads();
int buf = 0;
for (int start = begin; start < end; start += 16) {
const bool more = start + 16 < end;
if (more) fetch(start + 16);
const uint16_t* tile = keys[buf];
v8f dot = { 0 };
#pragma unroll
for (int s = 0; s < 8; ++s)
dot = mma(frag(tile, kRowsPitch, 0, quarter * 128 + s * 16, lane), query[s], dot);
*(v8f*)&partial[wave][lane * 8] = dot;
__syncthreads();
v8f score = *(const v8f*)&partial[group * 4][lane * 8];
#pragma unroll
for (int k = 1; k < 4; ++k) score += *(const v8f*)&partial[group * 4 + k][lane * 8];
float chunk_max = -INFINITY;
#pragma unroll
for (int e = 0; e < 8; ++e) {
score[e] = visible[buf][8 * (lane >> 4) + e] ? score[e] * m.scale : -INFINITY;
chunk_max = fmaxf(chunk_max, score[e]);
}
chunk_max = fmaxf(chunk_max, swap16(chunk_max));
const float next_max = fmaxf(run_max, chunk_max);
const float alpha = isfinite(next_max) ? expf(run_max - next_max) : 1;
float p[8], sum = 0;
#pragma unroll
for (int e = 0; e < 8; ++e) {
p[e] = isfinite(score[e]) ? expf(score[e] - next_max) : 0;
sum += p[e];
}
/* Both halves add tokens 0-7 before 8-15, so the sixteen lanes of a head agree. */
const float other = swap16(sum);
run_den = run_den * alpha + (lane < 16 ? sum + other : other + sum);
run_max = next_max;
/* A B fragment's lane holds its head's tokens 0-3 and 8-11 (lanes 0-15) or 4-7 and 12-15
* (16-31); a score lane holds 0-7 or 8-15. Each half sends the other the four it needs. */
uint32_t hi[4], lo[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const uint16_t h0 = f32_to_bf16(p[2 * i]), h1 = f32_to_bf16(p[2 * i + 1]);
hi[i] = (uint32_t)h0 | (uint32_t)h1 << 16;
lo[i] = (uint32_t)f32_to_bf16(p[2 * i] - bf16_to_f32(h0)) |
(uint32_t)f32_to_bf16(p[2 * i + 1] - bf16_to_f32(h1)) << 16;
}
const bool low = lane < 16;
const uint32_t hx0 = r4d_xor_lane_u32<16>(low ? hi[2] : hi[0]),
hx1 = r4d_xor_lane_u32<16>(low ? hi[3] : hi[1]),
lx0 = r4d_xor_lane_u32<16>(low ? lo[2] : lo[0]),
lx1 = r4d_xor_lane_u32<16>(low ? lo[3] : lo[1]);
union {
uint32_t w[4];
v8bf f;
} ph, pl;
ph.w[0] = low ? hi[0] : hx0;
ph.w[1] = low ? hi[1] : hx1;
ph.w[2] = low ? hx0 : hi[2];
ph.w[3] = low ? hx1 : hi[3];
pl.w[0] = low ? lo[0] : lx0;
pl.w[1] = low ? lo[1] : lx1;
pl.w[2] = low ? lx0 : lo[2];
pl.w[3] = low ? lx1 : lo[3];
#pragma unroll
for (int mt = 0; mt < 8; ++mt) {
const auto v = fragT(tile, kRowsPitch, quarter * 128 + mt * 16, 0, lane);
value[mt] *= alpha;
value[mt] = mma(v, ph.f, value[mt]);
value[mt] = mma(v, pl.f, value[mt]);
}
if (more) stash(buf ^ 1);
__syncthreads();
buf ^= 1;
}
#pragma unroll
for (int mt = 0; mt < 8; ++mt)
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int col = quarter * 128 + mt * 16 + 8 * (lane >> 4) + e;
if (m.splits == 1)
out[(long)r * m.orr + (long)head * m.oh + col] =
f32_to_bf16(run_den > 0 ? value[mt][e] / run_den : 0);
else
scratch[(((long)r * m.heads + head) * m.splits + split) * PART + col] =
value[mt][e];
}
if (m.splits > 1 && !quarter && lane < 16) {
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
dst[D] = run_max;
dst[D + 1] = run_den;
}
}
/* Read once: the launch path asks on every matrix launch. */
bool stats_on() {
static const bool on = [] {
const char* e = std::getenv("RADIANCE_MLA_CONFLICT_STATS");
return e && *e && *e != '0';
}();
return on;
}
void read_stats(unsigned long long (&v)[3], bool reset) {
v[0] = v[1] = v[2] = 0;
@@ -609,7 +785,7 @@ int body(const RadArgs* a, RadStream stream) {
/* The union's LDS lists hold a table of at most kUnionBlocks entries; a wider table takes the
* positional pairing. */
const bool by_page = bt.shape[1] <= kUnionBlocks;
const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS");
const bool stats = MATRIX && stats_on();
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],
@@ -643,6 +819,70 @@ int body(const RadArgs* a, RadStream stream) {
if (rc == RAD_OK && stats) report_stats(stream);
return rc;
}
/* r4d_mla_rows_pin_form: 0 is the launcher's rule (64 heads a workgroup, vector key loads where
* the cache is aligned, the matrix row's kernel under kRowsMin rows), 1 the element-wise key load,
* 2 thirty-two heads a workgroup, 3 the rule's rows kernel at any row count, 4 the matrix row's
* kernel at every row count. The pin is a test hook (r4d_selftest, r4d_emu); nothing else sets
* it. */
int g_mla_rows_form = 0;
/* Under it, a decode step's rows at one rank, a workgroup a row leaves the card mostly idle, and
* the matrix row's four tiles a row and its splits are faster (r4d_selftest --case
* mla_attn_rows_bf16, M 7: 0.5x). */
constexpr long kRowsMin = 32;
int rows_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 (heads % 32) return RAD_E_UNSUPPORTED;
const int form = g_mla_rows_form;
if (form == 4 || (!form && q.shape[0] < kRowsMin)) return body<true>(a, stream);
const int group_heads = heads % 64 || form == 2 ? 32 : 64;
const long rows = q.shape[0], groups = heads / group_heads, jobs = rows * groups;
/* Short batches split the history until 64 workgroups run, two to each of the R9700's 32
* WGPs, as far as 16-token chunks and the scratch's 2048 partials allow. */
int splits = (int)std::min(64l, (64 + jobs - 1) / jobs);
splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + 15) / 16));
splits = (int)std::max(1l, std::min((long)splits, 2048 / (rows * heads)));
if (!a->scratch || a->scratch_bytes < matrix_scratch_bytes) splits = 1;
const bool wide = form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
!(kv.stride[2] % 8);
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 };
#define ROWS_EMIT(HG, W) \
R4D_EMIT(stream, (attend_rows<HG, W>), dim3(m.rows, (unsigned)groups, m.splits), \
dim3(HG * 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)
int rc;
if (group_heads == 64)
rc = wide ? ROWS_EMIT(4, true) : ROWS_EMIT(4, false);
else
rc = wide ? ROWS_EMIT(2, true) : ROWS_EMIT(2, false);
#undef ROWS_EMIT
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);
return rc;
}
}
extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
return body<false>(a, stream);
@@ -650,12 +890,16 @@ extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream 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_attn_rows(const RadArgs* a, RadStream stream) {
return rows_body(a, stream);
}
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
return project_body(a, stream);
}
extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; }
extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; }
extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; }
extern "C" void r4d_mla_rows_pin_form(int form) { g_mla_rows_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) {
+3 -2
View File
@@ -3406,8 +3406,9 @@ extern "C" int r4d_rad_router_gemm_topk_scatter_init(const RadParam*, int, int,
const size_t bytes = (size_t)kRgCtrSlots * kRgCtrStride * sizeof(unsigned int);
void* p = nullptr;
if (hipMalloc(&p, bytes) != hipSuccess) return RAD_E_NOMEM;
/* Zero before any launch reads it: the memset is on the null stream, which the engine's
* streams need not wait for, so wait here. */
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
if (hipMemset(p, 0, bytes) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
(void)hipFree(p);
return RAD_E_DEVICE;
+3 -4
View File
@@ -1159,10 +1159,9 @@ int body(const RadArgs* a, RadStream stream) {
}
/* The small-M form at GLM's TP8 slices, ahead of the expert-major band: gate_up up to 384
* routed rows, down up to 32, where it stops gaining (at 5 to 8 tokens it reads 3 to 5 %
* slower than the staged form). Measured at those slices (perfmx, cold), expert-major against
* small-M: gate_up at 1, 3, 6, 8, 16 and 48 tokens 36.8/31.4, 79.5/69.5, 120.5/101.4,
* 145.0/122.4, 230.3/206.8 and 416.7/390.0 us; down at 1, 2 and 4 tokens 21.2/16.4, 26.0/22.5
* and 39.5/37.9 us. */
* slower than the staged form). At those slices on gfx1201 (perfmx, cold) it is 6 to 16 %
* faster than the expert-major form for gate_up from 1 to 48 tokens, and 4 to 23 % for down
* from 1 to 4. */
if (tp8 && m.T <= (m.K <= 256 ? 32 : 384)) {
const long rows = std::min<long>(m.experts, m.T) + 1;
#define MX_SMALL(SK, CT) \
+38 -1
View File
@@ -31,6 +31,9 @@ enum {
* outrank prefill. */
R4D_PRIO_ATTN_DECODE = 70,
R4D_PRIO_ATTN_PREFILL = 60,
/* A lossy prefill row (e4m3 products) matches only a caller that states `prefill_fp8`, where
* the exact row matches too, so it ranks above it and below decode. */
R4D_PRIO_ATTN_PREFILL_FP8 = 61,
/* The windowed kernels (r4d_attn_paged_window.hip) serve every q_len, so where their geometry
* meets another leg's (h256 at gqa 2) they match in both of that leg's bands and rank below
* both: on R9700 at the 31B's shapes (window 1024, fp8 cache) the h256/gqa2 decode kernel takes
@@ -46,6 +49,11 @@ enum {
R4D_PRIO_GEMM_SKINNY = 50,
/* The MXFP4 decode row outranks the MXFP4 skinny row, whose band it shares up to N = 36864. */
R4D_PRIO_GEMM_MXDEC = 55,
/* The MXFP4 gemv row (one to eight rows) outranks the decode row, whose band it shares there. */
R4D_PRIO_GEMM_MXGEMV = 58,
/* The decode kernel's short-K row outranks gemv_wide in the one corner of its band where the
* decode kernel is faster (33..64 rows, N >= 8192, K <= 2560). */
R4D_PRIO_GEMM_MXDEC_SHORTK = 59,
/* The skinny m64 row has no upper bound on M, so the tiled bf16 row (M > 64 only) must outrank
* it, and stays below m16, whose band it never enters. */
R4D_PRIO_GEMM_BF16_TILED = 55,
@@ -92,13 +100,22 @@ extern "C" {
/* -- attention (r4d_attn_*.hip) -- */
int r4d_rad_attn_prefill_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8_qk8pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h256_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_fp8v4_qk8pv8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_v4_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_qk8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_pv8(const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h256_k6v4_qk8pv8(const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_k6_scratch(const RadArgs*);
int r4d_rad_attn_decode_h256_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream);
@@ -131,6 +148,8 @@ int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*);
/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not
* (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q
* row pitch, so they serve both attn_paged and attn_paged_qrow. */
int r4d_rad_attn_window_h128_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream);
@@ -147,6 +166,7 @@ int r4d_rad_attn_window_h512_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
/* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded
@@ -170,6 +190,9 @@ int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream);
int r4d_rad_lora_expand_mm (const RadArgs*, RadStream);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
/* Unlimited-OCR's SAM tower: windowed tiles with decomposed relative position
* (r4d_sam_attn_bf16.hip). */
int r4d_rad_sam_attn (const RadArgs*, RadStream);
int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
/* The image generator's attention (r4d_attn_gen.hip): a paged prefix and the pass's own rows, the
* causal-capable dense form at head_dim 128 (a text encoder's prompt), and one 1152-wide head
@@ -211,8 +234,10 @@ int r4d_rad_conv_t1d_f32 (const RadArgs*, RadStream);
int r4d_rad_snake (const RadArgs*, RadStream);
int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream);
int r4d_rad_rvq_embed (const RadArgs*, RadStream);
int r4d_rad_vq_encode (const RadArgs*, RadStream);
int r4d_rad_frame_mix_store (const RadArgs*, RadStream);
int r4d_rad_end_status (const RadArgs*, RadStream);
int r4d_rad_ras_pick (const RadArgs*, RadStream);
int r4d_rad_frame_store (const RadArgs*, RadStream);
int r4d_rad_resample_nearest (const RadArgs*, RadStream);
int r4d_rad_fourier_embed (const RadArgs*, RadStream);
@@ -225,6 +250,7 @@ int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream);
int r4d_rad_iota (const RadArgs*, RadStream);
int r4d_rad_cu_repeat (const RadArgs*, RadStream);
int r4d_rad_int_affine (const RadArgs*, RadStream);
int r4d_rad_sub_i32 (const RadArgs*, RadStream);
/* r4d_video.hip */
int r4d_rad_rms_mod (const RadArgs*, RadStream);
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
@@ -251,7 +277,6 @@ int r4d_rad_pixel_norm (const RadArgs*, RadStream);
int r4d_rad_d2s3d (const RadArgs*, RadStream);
int r4d_rad_s2d3d (const RadArgs*, RadStream);
int r4d_rad_pix_patch (const RadArgs*, RadStream);
int r4d_rad_patch_pix8 (const RadArgs*, RadStream);
int r4d_rad_vol_index (const RadArgs*, RadStream);
int r4d_rad_attn_na3d (const RadArgs*, RadStream);
int r4d_rad_tile_grid (const RadArgs*, RadStream);
@@ -279,6 +304,13 @@ int r4d_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa8_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa8_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa8_scratch(const RadArgs*);
/* ONE query a KV head, head_dim 128 -- plain MHA, the Unlimited-OCR decoder (10 over 10). Both
* legs from the generic body instantiated at ratio 1 (r4d_attn_paged_h128_gqa1.hip). */
int r4d_rad_attn_prefill_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_prefill_h128_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_decode_h128_gqa1_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h128_gqa1_scratch(const RadArgs*);
/* Four queries per KV head, head_dim 256 only (Qwen3.5-0.8B); same body, another instantiation
* (r4d_attn_paged_h256_gqa4.hip). */
int r4d_rad_attn_prefill_h256_gqa4_fp8 (const RadArgs*, RadStream);
@@ -428,6 +460,7 @@ int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_gemv(const RadArgs*, RadStream);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
@@ -701,6 +734,7 @@ 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_rad_mla_attn_rows(const RadArgs*, RadStream);
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*);
@@ -733,6 +767,9 @@ int r4d_rad_logits_gemm_cols(const RadArgs*, RadStream);
* fused one lacks. */
int r4d_rad_sample_penalties (const RadArgs*, RadStream);
int r4d_rad_sample_dry (const RadArgs*, RadStream);
/* The windowed no-repeat-ngram ban (r4d_sample_ngram_f32.hip): the row's history, one -infinity
* a banned column. */
int r4d_rad_sample_ngram_ban(const RadArgs*, RadStream);
int r4d_rad_sample_temp (const RadArgs*, RadStream);
int r4d_rad_sample_mask (const RadArgs*, RadStream);
int r4d_rad_sample_topk (const RadArgs*, RadStream);
+5 -9
View File
@@ -4,19 +4,15 @@
// GEMMs leaves memory idle for its whole round trip: ~20 us at a DFlash2 verify's 8 rows on 4x
// R9700. A read issued on the second lane in that window puts the next GEMM's first bytes in the
// 64 MB Infinity Cache, and the GEMM then streams them from there. On four cards (a microbenchmark
// of the 8-row two-shot and a GEMM-like stream of a cold 29 MB weight, 2026-10-17) 16 MB read beside
// the all-reduce took a layer from 84.0 us to 70.1; the same read on the same stream gained nothing.
// of the 8-row two-shot and a GEMM-like stream of a cold 29 MB weight) 16 MB read beside the
// all-reduce took a layer from 84.0 us to 70.1; the same read on the same stream gained nothing.
//
// It writes nothing at all. Each lane folds its loads into one word and hands it to an empty
// `asm volatile`, which the compiler can neither drop nor see into, so the loads stay.
//
// Nothing here reaches HIP's runtime. The fold once went to a word hipMalloc'ed on the first
// launch, in the middle of a pass; then to a `__device__` word, which HIP's runtime registers and
// places itself (the engine records only fat binaries and functions). That word cost ~8% of a
// DFlash2 step (321 tok/s against 348 in one A/B on 4x R9700, 2026-10-17, every prefetch size
// alike), not through extra hardware queues (every image held 16 on the four cards); the
// mechanism is not pinned down. Neither form was the cause of the fresh-server divergence the
// reads beside a prefill bring (rad_arch.h, kPrefetchRows): with no word at all it is still there.
// Nothing here reaches HIP's runtime: no allocation at launch and no `__device__` word, which HIP's
// runtime registers and places itself (the engine records only fat binaries and functions). Such a
// word cost ~8% of a DFlash2 step on 4x R9700, for a reason not pinned down.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_chain.h"
+8 -8
View File
@@ -176,13 +176,13 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
// The same kernel at decode heights (THR 1024, n <= 1024 * EPT), with every operand of the row
// loaded in one go before the first reduction. The kernel above reads the row again in each pass,
// each read behind a barrier, so a row costs three dependent memory round trips; on gfx1201 that
// held the kernel at 11 us at any height against a 4.2 us launch floor, and this form at 8.2 us
// (4x R9700, 1 to 16 rows of 5376, 2026-10-17). Every pass partitions the row the same way (thread
// t takes columns t, t+THR, ...), so each thread keeps its own columns in registers and none needs
// another's; only the fragment-order store crosses threads, through `ybuf` as before. The sums,
// the order they are taken in and every element's arithmetic are junction_row's, so the bytes are.
// One row of it, for this kernel and for the all-reduce's tail (ar_rmsnorm_quant_i8_tail_kernel).
// each read behind a barrier, so a row costs three dependent memory round trips; on gfx1201 at
// 1 to 16 rows of 5376 that is 11 us a launch against 8.2 us for this form. Every pass partitions
// the row the same way (thread t takes columns t, t+THR, ...), so each thread keeps its own
// columns in registers and none needs another's; only the fragment-order store crosses threads,
// through `ybuf`. The sums, their order and every element's arithmetic are junction_row's, so the
// output bytes are the same. One row of it, for this kernel and for the all-reduce's tail
// (ar_rmsnorm_quant_i8_tail_kernel).
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
__device__ __forceinline__ void junction_reg_row(
const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w,
@@ -633,7 +633,7 @@ __global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_AR
// rmsnorm_quant_i8), and the residual on its own rows only -- on every row with `gres`. `x` keeps
// this rank's partial sums: nothing past the junction reads the reduced branch output. Against the
// tail form the second hop carries int8 instead of bf16 and no block waits beside the transport;
// one launch at a time on 4x R9700 (2026-10-19) it took 22.9 against 24.5 us at 8 rows of 5376,
// one launch at a time on 4x R9700 it takes 22.9 against 24.5 us at 8 rows of 5376,
// 30.8 against 34.9 at 16, 72.3 against 89.2 at 64, and 19.8 against the one-shot's 21.9 at 4.
template <uint32_t EPT, uint32_t THR, int WS>
__device__ __forceinline__ void ar_rmsnorm_quant_i8_sp_body(
+449 -81
View File
@@ -110,6 +110,8 @@ static const RadParamSpec pAttnPaged[] = {
* Absent, the shim falls back to the tensors, which exist only at issue. */
P_INTO("n_head"),
P_INTO("max_seqs"),
/* e4m3 products a caller accepts (docs/OPS.md): 1 Q.K^T, 2 P.V, 3 both; absent is 0. */
P_INTO("prefill_fp8"),
};
static const RadOperandSpec oAttnPaged[] = {
{ "q", RAD_OPD_IN, 0 },
@@ -206,6 +208,28 @@ static const RadOperandSpec oAttnNa3d[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_O
{ "v", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
{ "out", RAD_OPD_OUT, 0 } };
/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): windowed attention with a decomposed relative
* position. The two tables are weights, [2*L-1, head_dim] with L the window or the grid. */
static const RadParamSpec pSamAttn[] = {
P_INT("M"),
P_INT("head_dim"),
P_INT("n_head"),
P_INT("grid_h"),
P_INT("grid_w"),
P_INT("window"),
P_F64("scale"),
P_STR("dtype"),
};
static const RadOperandSpec oSamAttn[] = {
{ "q", RAD_OPD_IN, 0 },
{ "k", RAD_OPD_IN, 0 },
{ "v", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "out", RAD_OPD_OUT, 0 },
{ "rel_pos_h", RAD_OPD_WEIGHT, 0 },
{ "rel_pos_w", RAD_OPD_WEIGHT, 0 },
};
/* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate]
* projection per head, writes q, k and the gate to three destinations, and takes a precomputed
* cos/sin table. Hence its own op name. */
@@ -724,10 +748,6 @@ static const RadOperandSpec oGemmNt[] = {
{ "y", RAD_OPD_OUT, 0 },
};
/* `pb1` and `pb2` are ParoQuant's, read by the mxfp4a8 rows and the 4- and 5-bit asymmetric rows
* (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each
* meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a
* bound out. Absent on other grids, where a fused projection has one activation. */
/* `add_rmsnorm` is `add` (x += a) followed by `rmsnorm` of the x it wrote (docs/OPS.md). */
static const RadParamSpec pAddRmsNorm[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
@@ -762,6 +782,10 @@ static const RadParamSpec pPrefetch[] = {
static const RadOperandSpec oPrefetch[] = {
{ "w", RAD_OPD_WEIGHT, 0 },
};
/* `pb1` and `pb2` are ParoQuant's, read by the mxfp4a8 rows and the 4- and 5-bit asymmetric rows
* (w5a16, w4a16_asym, w4a8i8_asym, w5a8i8): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each
* meet their own copy of the activation, side by side in a row of `a` ([M, parts * K]). 0 leaves a
* bound out. Absent on other grids, where a fused projection has one activation. */
static const RadParamSpec pGemmNtQ[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "N", RAD_P_INT, RAD_REQUIRED },
@@ -2177,6 +2201,19 @@ static const RadOperandSpec oDry[] = {
{ "history", RAD_OPD_IN, 0 },
{ "breakers", RAD_OPD_IN, 1 },
};
/* The n-gram ban's own plane: one i32 {n-gram length, window} pair a row (n 0 = off, window <= 0
* = the whole staged history). A plane beside `params` rather than fields in it, because the
* params row is the fixed 24-word RadSampleParams every sampler op shares. */
/* `whitelist` is optional: a bitmask plane a row (a SET bit exempts that column from the ban,
* the reference's whitelist), [M, ceil(n_vocab/32)] i32/u32, contiguous. Absent, nothing is
* exempt. */
static const RadOperandSpec oNgramBan[] = {
{ "logits", RAD_OPD_INOUT, 0 },
{ "params", RAD_OPD_IN, 0 },
{ "history", RAD_OPD_IN, 0 },
{ "ngram", RAD_OPD_IN, 0 },
{ "whitelist", RAD_OPD_IN, 1 },
};
static const RadOperandSpec oTemp[] = {
{ "logits", RAD_OPD_INOUT, 0 },
{ "params", RAD_OPD_IN, 0 },
@@ -2462,7 +2499,8 @@ static const RadOperandSpec oAttnPS[] = {
/* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
P_INTO("cu_div") };
static const RadOperandSpec oConv1d[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, { "b", RAD_OPD_WEIGHT, 1 },
@@ -2481,7 +2519,8 @@ static const RadOperandSpec oSnake[] = {
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
P_INTO("sup_hi"), P_F64O("penalty") };
P_INTO("sup_hi"), P_F64O("penalty"),
P_F64O("top_p") };
static const RadOperandSpec oCfgTopk[] = {
{ "logits", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 },
{ "ids", RAD_OPD_OUT, 0 }, { "cfg", RAD_OPD_IN, 1 }, { "lane", RAD_OPD_IN, 1 },
@@ -2489,11 +2528,18 @@ static const RadOperandSpec oCfgTopk[] = {
};
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
P_STR("dtype"), P_INTO("round") };
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
static const RadOperandSpec oRvqEmbed[] = {
{ "codes", RAD_OPD_IN, 0 }, { "t0", RAD_OPD_WEIGHT, 0 }, { "t1", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
P_STR("dtype") };
static const RadOperandSpec oVqEncode[] = {
{ "x", RAD_OPD_INOUT, 0 }, { "in_w", RAD_OPD_WEIGHT, 0 }, { "in_b", RAD_OPD_WEIGHT, 0 },
{ "cb", RAD_OPD_WEIGHT, 0 }, { "out_w", RAD_OPD_WEIGHT, 0 }, { "out_b", RAD_OPD_WEIGHT, 0 },
{ "codes", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
P_INTO("rep"), P_STR("dtype") };
static const RadOperandSpec oFrameMix[] = {
@@ -2505,6 +2551,12 @@ static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep"
static const RadOperandSpec oEndStatus[] = {
{ "ids", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "status", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
P_INTO("rep"), P_INTO("clear") };
static const RadOperandSpec oRasPick[] = {
{ "first", RAD_OPD_IN, 0 }, { "alt", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "hist", RAD_OPD_INOUT, 0 }, { "ids", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
P_INTO("rep"), P_INTO("skip") };
static const RadOperandSpec oFrameStore[] = {
@@ -2545,6 +2597,10 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
P_INTO("period") };
static const RadOperandSpec oIota[] = { { "y", RAD_OPD_OUT, 0 } };
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
static const RadParamSpec pSubI32[] = { P_INT("M") };
static const RadOperandSpec oSubI32[] = {
{ "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oCuRepeat[] = { { "len", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
static const RadOperandSpec oIntAffine[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
@@ -2772,7 +2828,8 @@ static const RadOpSchema kSchemas[] = {
"op, not gelu, because gated feed-forwards are trained with the tanh form and the "
"unary gelu is the exact erf one."),
SCHEMA("act_mul", pActMul, oBinary,
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
"y = act(a) * b, the activation (silu, gelu, gelu_tanh, sigmoid or quick_gelu) rounded "
"to y's dtype before "
"the product: silu_mul with its two halves in two operands."),
SCHEMA("seg_mean", pSegMean, oSegMean,
"Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 "
@@ -2923,6 +2980,13 @@ static const RadOpSchema kSchemas[] = {
"DRY: penalise, once, each token that would extend a suffix of the history that has "
"occurred before, by its longest such repeat -- what stops a model looping on a phrase "
"rather than on a token. Tokens the breaker plane marks are exempt."),
SCHEMA("sample_ngram_ban", pPenal, oNgramBan,
"the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` "
"tokens of the row's history contain is set to -infinity. `ngram` is one i32 "
"{n, window} pair a row; the window bounds the n-gram's START index, as in the "
"reference, window <= 0 searches the whole span and n 0 is off. The optional "
"`whitelist` bitmask exempts a token whose column bit is set; absent, nothing is "
"exempt."),
SCHEMA("sample_temp", pMVocab, oTemp,
"per-request temperature. temp <= 0 leaves the row untouched; greedy is sample_argmax."),
SCHEMA("sample_mask", pMVocab, oMask,
@@ -2978,6 +3042,11 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("attn_na3d", pAttnNa3d, oAttnNa3d,
"3-D neighborhood attention over the voxels of geom = (T, H, W): each query sees the "
"kt x kh x kw window centred on it, shifted inward at the border."),
SCHEMA("sam_attn", pSamAttn, oSamAttn,
"Unlimited-OCR's SAM tower attention: per cu segment of grid_h*grid_w rows, pad to "
"multiples of `window` with zero rows, tile into window x window windows (0 = the whole "
"segment) and attend each tile to all of its rows. logits = scale*q.k + q.Rh[i_h,j_h] + "
"q.Rw[i_w,j_w], softmax in f32, out = sum p*v, pad rows dropped."),
SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate,
"split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate "
"copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a "
@@ -3471,10 +3540,16 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rvq_embed", pRvqEmbed, oRvqEmbed,
"a frame's embedding from code-major residual codes, the first codebook's table and the "
"others' stacked one, times `scale`; `round` 1 rounds the f32 sum once."),
SCHEMA("vq_encode", pVqEncode, oVqEncode,
"one residual vector quantiser step: the code of greatest cosine with in_w x + in_b "
"(the lower index on a tie), then x -= out_w cb[code] + out_b."),
SCHEMA("frame_mix_store", pFrameMix, oFrameMix,
"a frame's conditioning row (softmax-weighted planes times scale) into its lane."),
SCHEMA("end_status", pEndStatus, oEndStatus,
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."),
SCHEMA("ras_pick", pRasPick, oRasPick,
"repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in "
"the lane's window of its last picks, else the first; the pick enters the window."),
SCHEMA("frame_store", pFrameStore, oFrameStore,
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] "
"= codes[k, rep i] when frame >= skip and status[lane] >= 0."),
@@ -3490,6 +3565,9 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("cu_repeat", pCuRepeat, oCuRepeat, "bounds of equal sequences, y[j] = j * len[0] * mult."),
SCHEMA("int_affine", pIntAffine, oIntAffine,
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists."),
SCHEMA("sub_i32", pSubI32, oSubI32,
"y[i] = x[i] - s[0], int32: a device length less a device offset (a pipelined prefill's "
"first piece sees its group's seqused less the second piece's rows)."),
SCHEMA("snake_aa", pSnakeAa, oSnakeAa,
"BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled "
"`ratio` times by `f_up`, SnakeBeta, filtered by `f_down` at stride `ratio`."),
@@ -3562,8 +3640,6 @@ static const RadOpSchema kSchemas[] = {
"box (copy) or each `group` packed channels averaged (mean); `add` adds into y."),
SCHEMA("pix_patch", pPixPatch, oPixPatch,
"an image [H, W C] to patch rows [H/p, (W/p) C p p], order wh or hw."),
SCHEMA("patch_pix8", pPixPatch, oPixPatch,
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule."),
SCHEMA("vol_index", pVolIndex, oVolIndex,
"a volume's voxel coordinates (t, i, j), component-major."),
SCHEMA("tile_grid", pTileGrid, oTileGrid,
@@ -3573,7 +3649,7 @@ static const RadOpSchema kSchemas[] = {
"one tile's voxels out of a volume, box (t, h, w, t0, y0, x0)."),
SCHEMA("tile_stitch", pTileStitch, oTileStitch,
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h, then blend_t "
"across time bands, each tile kept to its stride, patch_pix8's bytes."),
"across time bands, each tile kept to its stride, to_rgba8's bytes."),
SCHEMA("stft_logmel", pStftMel, oStftMel,
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel "
"filterbank, every stored tensor rounded to y's dtype."),
@@ -3613,6 +3689,30 @@ static const RadConstraint cAttnPrefillFp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
/* The e4m3 product legs: the exact row's geometry over the same cache, and only for a caller whose
* `prefill_fp8` states that leg set. */
#define C_ATTN_PREFILL_FP8(kv) \
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16), \
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", kv)
static const RadConstraint cAttnPrefillFp8Qk8[] = { C_ATTN_PREFILL_FP8("fp8_e4m3"),
C_EQ("prefill_fp8", 1) };
static const RadConstraint cAttnPrefillFp8Pv8[] = { C_ATTN_PREFILL_FP8("fp8_e4m3"),
C_EQ("prefill_fp8", 2) };
static const RadConstraint cAttnPrefillFp8QkPv8[] = { C_ATTN_PREFILL_FP8("fp8_e4m3"),
C_EQ("prefill_fp8", 3) };
static const RadConstraint cAttnPrefillFp8v4Qk8[] = { C_ATTN_PREFILL_FP8("fp8_v4"),
C_EQ("prefill_fp8", 1) };
static const RadConstraint cAttnPrefillFp8v4Pv8[] = { C_ATTN_PREFILL_FP8("fp8_v4"),
C_EQ("prefill_fp8", 2) };
static const RadConstraint cAttnPrefillFp8v4QkPv8[] = { C_ATTN_PREFILL_FP8("fp8_v4"),
C_EQ("prefill_fp8", 3) };
static const RadConstraint cAttnPrefillK6v4Qk8[] = { C_ATTN_PREFILL_FP8("k6_v4"),
C_EQ("prefill_fp8", 1) };
static const RadConstraint cAttnPrefillK6v4Pv8[] = { C_ATTN_PREFILL_FP8("k6_v4"),
C_EQ("prefill_fp8", 2) };
static const RadConstraint cAttnPrefillK6v4QkPv8[] = { C_ATTN_PREFILL_FP8("k6_v4"),
C_EQ("prefill_fp8", 3) };
#undef C_ATTN_PREFILL_FP8
static const RadConstraint cAttnPrefillBf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
@@ -3760,11 +3860,12 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* The windowed kernels (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV
* head, any window, causal or not. Gemma 4's sliding layers are h256/gqa2 with a 1024-token
* window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). One kernel serves every
* q_len (splitting the key range when there are too few tiles to fill the card), so `q_len` cuts
* no band. `causal` and `window` are runtime fields; block_size is derived: 16.
/* The windowed kernels (r4d_attn_paged_window.hip): head_dim 128, 256 and 512, 1/2/4/8 queries per
* KV head, any window, causal or not. Gemma 4's sliding layers are h256/gqa2 with a 1024-token
* window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8); h128/gqa1 is Unlimited-OCR's
* MHA decoder. One kernel serves every q_len (splitting the key range when there are too few tiles
* to fill the card), so `q_len` cuts no band. `causal` and `window` are runtime fields; block_size
* is derived: 16.
*
* h256 at gqa 4 and 8 take a window only (C_GE 1), leaving the window-0 band to the gqa4 / gqa8
* legs above. At h256/gqa2 these rows overlap the sliding leg's bands and rank below it
@@ -3774,6 +3875,7 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \
C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \
};
R4D_WIN_C(cWinH128G1Bf16, 128, 1, "bf16", 0) R4D_WIN_C(cWinH128G1Fp8, 128, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G1Bf16, 256, 1, "bf16", 0) R4D_WIN_C(cWinH256G1Fp8, 256, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G2Bf16, 256, 2, "bf16", 0) R4D_WIN_C(cWinH256G2Fp8, 256, 2, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cWinH256G4Fp8, 256, 4, "fp8_e4m3", 1)
@@ -3929,6 +4031,27 @@ static const RadConstraint cAttnDecodeH128G8Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* head_dim 128 at ratio ONE: plain MHA (the Unlimited-OCR decoder, 10 query heads over 10), from
* r4d_attn_paged_h128_gqa1.hip. The decode leg caps at 64 query rows, which at this ratio is a
* plain q_len <= 64; the prefill leg has no query-row cap. */
static const RadConstraint cAttnPrefillH128G1Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH128G1Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cAttnDecodeH128G1Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnDecodeH128G1Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 1), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 64), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Two queries per KV head at head_dim 128 (Qwen3-1.7B, Qwen3-ASR's decoder): the gqa8 pair's
* constraints with the ratio and the decode verify width changed together. A decode workgroup
* holds 64 (query, head) rows, so q_len <= 32 at gqa 2. */
@@ -3991,6 +4114,9 @@ static const RadConstraint cCastNarrow[] = {
* bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is
* attn_dense_small_h256's and the wide kernel's. */
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
};
@@ -3998,6 +4124,14 @@ static const RadConstraint cAttnDenseH64[] = {
static const RadConstraint cAttnDenseH256G1[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 1), C_GE("max_seqlen", 33), C_IN("dtype", "bf16"),
};
/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): one block per (segment, tile, head), a thread
* a query row, q and the output accumulator in registers; only head_dim 64 is instantiated and a
* rel_pos table that is not 2*tile-1 rows is linear-resampled on read (get_rel_pos), so the 127-row
* global tables serve a 40-grid block as 79 rows. */
static const RadConstraint cSamAttn[] = {
C_EQ("head_dim", 64), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH256G2[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_IN("dtype", "bf16"),
};
@@ -4298,6 +4432,16 @@ static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
C_GE("blocks", 1),
C_EQ("block_size", 4),
C_IN("dtype", "bf16") };
/* GLM's prefill splits MLA by rows, a rank holding every head of its rows: the rows row loads a
* key chunk once for a workgroup of 64 heads and outranks the matrix row there. Measured on gfx1201
* (r4d_selftest --perfmla 512 513 64 20 topk:16:16000), a rank's run of 512 rows takes 3.9 ms
* against 12.3 ms on the matrix row, and the 4096 rows x 8 heads it replaces 14.0 ms on the paired
* matrix row. Under 32 rows its launcher runs the matrix row's kernel (r4d_mla.hip); a bound on M
* here would cut every mla_attn band at 32, the eight-head ones too. */
static const RadConstraint cMlaRows[] = { C_GE("M", 1), C_LE("M", 65535),
C_EQ("latent_dim", 512), C_EQ("heads", 64),
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[] = {
@@ -4614,7 +4758,6 @@ static const RadConstraint cQuantActI8[] = {
static const RadConstraint cRmsNormQuantI8[] = {
C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"),
};
/* head_dim 256 or 512: a workgroup is one head, a thread one channel. */
static const RadConstraint cAddRmsNorm[] = {
C_GE("n", 1), C_IN("dtype", "bf16"),
};
@@ -4624,6 +4767,7 @@ static const RadConstraint cKvLenTrim[] = {
static const RadConstraint cPrefetch[] = {
C_GE("bytes", 1),
};
/* head_dim 256 or 512: a workgroup is one head, a thread one channel. */
static const RadConstraint cQkvNormRope[] = {
C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"),
};
@@ -4724,10 +4868,34 @@ static const RadConstraint cGemmW4A8Tiled[] = {
};
/* r4d_gemm_mxfp4a8_decode. Entry point: M <= 128, N % 16, K % 64, and N up to its counter block's
* 36864. Above the skinny row by priority, so it takes the decode band; the skinny row keeps the
* wider N up to M = 64, the tiled row everything else. */
* wider N up to M = 64 (from M = 9: the gemv row below takes M <= 8 at any N, and gemv_wide
* M <= 64 where K % 128 == 0), the tiled row everything else. */
static const RadConstraint cGemmMxfp4A8Decode[] = {
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_mxfp4a8_gemv. Entry point: M <= 8, N % 16, K % 64, no N bound (no counters). Above the
* decode row by priority, so one stream's decode (M = 1 + the draft depth) takes it, at any N; the
* decode row keeps M = 9..128. */
static const RadConstraint cGemmMxfp4A8Gemv[] = {
C_LE("M", 8), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* gemm_mxfp4a8_gemv_wide: the same entry at 9..64 rows, where only the WMMA form serves (K % 128).
* The form's sum order for a row is its 16-row tile's chain alone, so a row's bits are the same in
* both rows at every M. Several streams with speculation (4 x 1 + 7 drafts = 32) land here, except
* in the decode kernel's short-K corner below, which sums 33..64 rows in the decode kernel's order (a
* row's bits there change at M = 33). */
static const RadConstraint cGemmMxfp4A8GemvWide[] = {
C_GE("M", 9), C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* gemm_mxfp4a8_decode_shortk: the decode entry at 33..64 rows of a wide, short weight, above
* gemv_wide by priority. There gemv_wide's blocks hold three or four row tiles over a short K each,
* so the cross-wave reduction of a block weighs more than its WMMAs, and the decode kernel's split
* wins on gfx1201 (19456 x 2560 at 64 rows: 93.3 us against gemv_wide's 131.8). Narrower N and K
* past 2560 stay with gemv_wide. */
static const RadConstraint cGemmMxfp4A8DecodeShortK[] = {
C_GE("M", 33), C_LE("M", 64), C_GE("N", 8192), C_LE("N", 36864), C_LE("K", 2560), C_DIV("K", 64),
C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_mxfp4a8_tiled. Entry point: N % 16 (the fragment-order weight), K % 64 (its narrowest
* K slab), M >= 1. The decode and skinny rows outrank it in their bands by priority, so the band
* starts at 1 rather than at a hand-picked crossover. */
@@ -4860,8 +5028,7 @@ static const RadTunable tAttnSplit[] = {
/* ------------------------------------------------------------------- all-reduce launch geometry
*
* Four independent axes of the handshake: nblocks, nthreads, drain and acq. (`pub` is 1 in every
* arm but the four-rank junction's, tArQ84, where it is an axis.) nblocks 0 scales with the message
* and clamps; drain 3 is
* arm, a constant in r4d_cfg_ar.) nblocks 0 scales with the message and clamps; drain 3 is
* s_wait_storecnt, the correct wait for the fine-grained uncached IPC scratch.
*
* rad-tune cannot reach these rows: the two-rank kernels need a real peer over IPC and rad-tune
@@ -4879,11 +5046,10 @@ static const int64_t kArAcq[] = { 0, 1 };
/* `ts_min`: from this many elements the four-rank exact one-shot hands the message to the exact
* two-shot on the same instance (the same per-element fold, so the same bytes): a rank then sends
* 1.5x the message instead of 3x, for a second handshake. 32768 is about six rows of 5376, so an
* 8-row DFlash2 verify's all-reduces take the two-shot too (on 4x R9700, 2026-10-17: 297 -> 303
* tok/s code, long decode 447 -> 460, against 65536 that kept them one-shot); a 16-row verify's
* already did. 0 keeps the one-shot to its band's top. Read only by that
* adapter; declared by every all-reduce table so one RADIANCE_TUNE=all_reduce:ts_min=N pin is legal
* for every row the op resolves to. */
* 8-row DFlash2 verify's all-reduces take the two-shot too (on 4x R9700 the 31B decoded 2-3% faster
* than at 65536, which kept them one-shot), as a 16-row verify's do. 0 keeps the one-shot to its
* band's top. Read only by that adapter; declared by every all-reduce table so one
* RADIANCE_TUNE=all_reduce:ts_min=N pin is legal for every row the op resolves to. */
static const int64_t kArTsMin[] = { 0, 16384, 32768, 65536, 131072, 262144 };
static const RadTunable tAr[] = {
{ "nblocks", kArNblocks, NELEM(kArNblocks), 0, "blocks in the grid. 0 = scale with the message and clamp" },
@@ -4892,28 +5058,20 @@ static const RadTunable tAr[] = {
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
{ "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "elements from which the four-rank one-shot takes the exact two-shot; 0 = never" },
};
/* The four-rank fused junction (ar_rmsnorm_quant_i8_4rank): tAr's axes, its own value sets.
* On 4x R9700 over PCIe P2P a junction costs about 22 us at one row of 5376 and 57 us at sixteen
* (--profile-ops): it is bound by its handshakes, not its bytes.
*
* Every block takes one handshake, a system-scope release by its first
* thread and a system-scope acquire by every wave. Both are needed: on 4x R9700 behind an EPYC
* root complex, dropping either (an acq 2 and a pub 2 that were here, r4d_selftest 2026-10-16 and
* -17) left the readers with stale scratch on nearly every element, so the peers' stores do not
* reach them past the writer's L2 without the writeback. What can move is how many handshakes a
* call takes: fewer blocks (2 or 4, each owning several rows) take fewer. The defaults are the
* forms that have run on cards; the others are for RADIANCE_TUNE until they have. None of them
* changes the result. */
/* The four-rank fused junction (ar_rmsnorm_quant_i8_4rank): tAr's axes with its own block counts,
* and `tail`. A one-shot junction is bound by its handshakes, not its bytes (on 4x R9700 over PCIe
* P2P about 22 us at one row of 5376 and 57 us at sixteen). Every block takes one handshake, a
* system-scope release by its first thread and a system-scope acquire by every wave; without
* either, the readers see stale scratch on those cards, so no point drops one. What can move is
* the handshake count: fewer blocks (2 or 4, each owning several rows) take fewer. Only the
* defaults have run on cards. No axis changes the result. */
static const int64_t kArQ84Tail[] = { 1, 0 };
static const int64_t kArQ84Nblocks[] = { 0, 2, 4, 8, 16, 24 };
static const int64_t kArQ84Acq[] = { 0, 1 };
static const int64_t kArQ84Pub[] = { 1 };
static const RadTunable tArQ84[] = {
{ "nblocks", kArQ84Nblocks, NELEM(kArQ84Nblocks), 0, "blocks in the grid. 0 = one a row, clamped" },
{ "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "unused: the norm's width sets the block for bit-exactness" },
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
{ "acq", kArQ84Acq, NELEM(kArQ84Acq), 0, "acquire after the flag read: 0 system invalidate a wave, 1 full fence" },
{ "pub", kArQ84Pub, NELEM(kArQ84Pub), 1, "release before the flag store: 1 one system writeback" },
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire after the flag read: 0 system invalidate a wave, 1 full fence" },
{ "tail", kArQ84Tail, NELEM(kArQ84Tail), 1, "from 5 to 32 rows: the standalone two-shot with the junction as its tail, a block a row (no handshake or launch of its own); 0 = the one-shot" },
};
/* The four-rank two-shots beside compute: four blocks of 1024. A pipelined Flash-Next prefill at
@@ -5066,6 +5224,8 @@ static const RadConstraint cRmsMod[] = { C_IN("dtype", "bf16"), C_DIV("n", 8), C
static const RadConstraint cRmsModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192),
C_EQ("group", 128) };
static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") };
/* vq_encode: e's sums staged in LDS, a codebook dimension of 32 at most. */
static const RadConstraint cVqEncode[] = { C_IN("dtype", "bf16 f32"), C_LE("dim", 32) };
static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64) };
static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") };
static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) };
@@ -5586,6 +5746,12 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
r4d_shape_scale },
{ "mla_attn_rows_bf16", "mla_attn", "attn", "row-tiled WMMA latent attention, one key load for 64 heads",
"latent_dim=512, heads=64, block_size=4",
"bf16 operands; FP32 probabilities via high/low BF16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 2, ROW(cMlaRows), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_rows, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "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",
@@ -5744,7 +5910,8 @@ static const RadKernelInfo kKernels[] = {
"the lm_head projection over an fp8 head: C[M, n_vocab] f32 = x[M, n_embd] @ dequant(W)^T, "
"one wave a vocabulary row, the row's own scales in its tail",
"any M -- one pass to 32 rows, instantiated exactly to 8 and rounded up to a multiple of 4 above "
"it, then chunked; n_embd a multiple of 128, which is the group the scales are taken over. The "
"it, to 64 rows in four tiles a wave, to 128 in two M halves of four that share the staged head "
"tile, then chunked by 128; n_embd a multiple of 128, which is the group the scales are taken over. The "
"stored row is padded to 16 bytes so the uint4 load stays aligned at any such n_embd",
"bf16 x, E4M3 head with a bf16 scale per 128x128 tile stored PER ROW, F32 LOGITS OUT, fp32 "
"accumulate",
@@ -5794,6 +5961,20 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_sample_dry, nullptr, nullptr, nullptr,
r4d_shape_sample_dry },
{ "sample_ngram_ban_f32", "sample_ngram_ban", "sample",
"the windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor): every "
"token that would complete an n-gram the last `window` tokens of the row's history contain is "
"set to -infinity",
"any vocabulary; ONE BLOCK A ROW, the search positions dealt across its threads, the n-1-token "
"prefix staged in LDS. Integer comparisons and one constant store, so it is bit-identical to "
"libref; the same column written by two positions is an idempotent -infinity",
"f32 logits in place, i32 history, i32 {n, window} per-row pair",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cSampleVoc), NOTUNE,
/* No `opd_shape`: r4d_shapes.cpp declares the sampler's shapes, and the oracle (libref) describes
* this op for the tools that ask. */
nullptr, nullptr, r4d_rad_sample_ngram_ban },
{ "sample_temp_f32", "sample_temp", "sample",
"per-request temperature",
"any vocabulary; a row with temp <= 0 or exactly 1 is skipped whole",
@@ -5915,6 +6096,37 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
/* Lossy: they match only a caller whose `prefill_fp8` accepts their legs. */
{ "attn_prefill_h256_gqa6_fp8kv_qk8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query rounded to e4m3 after the scale, fp8-e4m3 kv cache with per-(seq,head) descales, "
"bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8Qk8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8_qk8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa6_fp8kv_pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, probabilities rounded to e4m3, "
"bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8Pv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8_pv8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa6_fp8kv_qk8pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T and P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query and probabilities rounded to e4m3, fp8-e4m3 kv cache with per-(seq,head) "
"descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8QkPv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8_qk8pv8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa6_fp8v4", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
@@ -5924,6 +6136,39 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8v4, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_fp8v4_qk8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query rounded to e4m3 after the scale, "
"fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), "
"K as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8v4Qk8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8v4_qk8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_fp8v4_pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query, probabilities rounded to e4m3, "
"fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), "
"V as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8v4Pv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8v4_pv8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_fp8v4_qk8pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T and P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query and probabilities rounded to e4m3, "
"fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), "
"K and V as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillFp8v4QkPv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_fp8v4_qk8pv8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_k6v4", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
@@ -5933,6 +6178,39 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_prefill_h256_k6v4, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_k6v4_qk8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query rounded to e4m3 after the scale, "
"k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), "
"K as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillK6v4Qk8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_k6v4_qk8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_k6v4_pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query, probabilities rounded to e4m3, "
"k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), "
"V as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillK6v4Pv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_k6v4_pv8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_k6v4_qk8pv8", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill), Q.K^T and P.V as e4m3 WMMA",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
"bf16 query and probabilities rounded to e4m3, "
"k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), "
"K and V as e4m3 in LDS, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL_FP8,
ROW(cAttnPrefillK6v4QkPv8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_k6v4_qk8pv8, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefill_h256_gqa6_bf16kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 6 queries per kv head, paged block 16, varlen",
@@ -6132,6 +6410,44 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_attn_qrow_h128_gqa8_bf16, r4d_rad_attn_qrow_h128_gqa8_scratch,
nullptr, nullptr, nullptr },
{ "attn_prefill_h128_gqa1_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 128, 1 query per kv head (plain MHA), paged block 16, varlen",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH128G1Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa1_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h128_gqa1_bf16kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 128, 1 query per kv head (plain MHA), paged block 16, varlen",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH128G1Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h128_gqa1_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h128_gqa1_fp8kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify)",
"head_dim 128, 1 query per kv head (plain MHA), paged block 16, q_len <= 64, no window",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH128G1Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h128_gqa1_fp8, r4d_rad_attn_decode_h128_gqa1_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h128_gqa1_bf16kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify)",
"head_dim 128, 1 query per kv head (plain MHA), paged block 16, q_len <= 64, no window",
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH128G1Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h128_gqa1_bf16, r4d_rad_attn_decode_h128_gqa1_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 8 queries per kv head, paged block 16, varlen",
@@ -6252,6 +6568,7 @@ static const RadKernelInfo kKernels[] = {
#define R4D_WIN_PAIR(HD, GQ) \
R4D_WIN_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \
R4D_WIN_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)")
R4D_WIN_PAIR(128, 1)
R4D_WIN_PAIR(256, 1) R4D_WIN_PAIR(256, 2) R4D_WIN_PAIR(256, 4) R4D_WIN_PAIR(256, 8)
R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, 8)
#undef R4D_WIN_PAIR
@@ -6592,6 +6909,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cAttnVit), NOTUNE,
nullptr, nullptr, r4d_rad_attn_vit },
{ "sam_attn_bf16", "sam_attn", "attn",
"Unlimited-OCR's SAM tower attention: windowed tiles with a decomposed relative-position term",
"head_dim 64; any grid, window and segment count (a segment is one grid_h*grid_w); q/k/v/out at "
"their own row pitch (column slices of one fused projection); rel_pos tables of any row count "
">= 1 (a table that is not 2*tile-1 rows is linear-resampled on read)",
"bf16 query / key / value / out and rel_pos tables, i32 cu_seqlens, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cSamAttn), NOTUNE,
nullptr, nullptr, r4d_rad_sam_attn },
{ "attn_dense_h64_bf16", "attn_dense", "attn",
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or "
"blocks, or causal with an optional window behind",
@@ -7303,6 +7630,31 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_m64, nullptr, r4d_rad_layout_mxfp4,
r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_gemv", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM for ONE TO EIGHT rows: the weight streamed straight to registers and folded "
"to e4m3 there, no LDS staging; WMMA when K is a multiple of 128, v_dot4 otherwise, chosen from "
"K alone so a row's bits do not depend on M",
"M <= 8; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXGEMV,
ROW(cGemmMxfp4A8Gemv), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gemv, nullptr,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_gemv_wide", "gemm_nt_q", "gemm",
"the gemv row's WMMA form at 9 to 64 rows: up to four 16-row tiles a wave over each weight word, "
"so the weight streams once from DRAM to registers whatever the row count; no LDS staging",
"9 <= M <= 64; K a multiple of 128; N a multiple of 16; the skinny kernel's fragment-order "
"weight, [K/32][N] E8M0 exponents and per-row reference exponent",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXGEMV,
ROW(cGemmMxfp4A8GemvWide), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_gemv, nullptr,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver "
"reduction, the weight unpacked through LDS, streaming weight loads",
@@ -7315,6 +7667,20 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_decode, r4d_rad_gemm_mxfp4a8_decode_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_decode_shortk", "gemm_nt_q", "gemm",
"the decode row's kernel at 33 to 64 rows of a wide, short weight (N >= 8192, K <= 2560), where "
"its split-K beats gemv_wide, whose blocks there spend more on the cross-wave reduction than on "
"the WMMAs",
"33 <= M <= 64; 8192 <= N <= 36864, a multiple of 16; K <= 2560, a multiple of 64; the skinny "
"kernel's fragment-order weight, [K/32][N] E8M0 exponents and per-row reference exponent; the "
"split partial in the op's scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC_SHORTK,
ROW(cGemmMxfp4A8DecodeShortK), ROW(tGemmMxfp4Decode), nullptr,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_decode, r4d_rad_gemm_mxfp4a8_decode_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_tiled", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM tiled for PREFILL row counts: the activation re-tiled into fragment order in "
"the op's scratch, its fragments read straight into registers, the weight unpacked once per K "
@@ -7986,11 +8352,10 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cArRmsNormQuantI8), ROW(tAr), nullptr,
r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8 },
/* Its arithmetic is the four-rank exact one-shot's fold followed by the two-rank form's junction,
* each the code those two run. r4d_selftest's case of the same name holds it byte for byte to
* all_reduce + rmsnorm_quant_i8 on a four-card box, and the engine to a decode step's text against
* a build that issues the pair. Both have run on cards that way (the 31B's fused junctions, and
* r4d_selftest on four R9700s). */
/* Its arithmetic is the four-rank exact all-reduce's fold followed by the two-rank form's
* junction, each the code those two run, in every form (one-shot, tail, split). r4d_selftest's
* case of the same name holds each form byte for byte to all_reduce + rmsnorm_quant_i8 on a
* four-card box. */
{ "ar_rmsnorm_quant_i8_4rank", "ar_rmsnorm_quant_i8", "quant",
"the four-rank exact one-shot all-reduce and the junction after it -- post-norm of the reduced "
"sum, residual add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel",
@@ -8738,6 +9103,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_rvq_embed },
{ "vq_encode", "vq_encode", "elem",
"a residual quantiser's step: the nearest code by cosine", "a workgroup a row, dim <= 32",
"bf16 or f32 rows and weights, f32 arithmetic, the row rounded once",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cVqEncode), NOTUNE,
nullptr, nullptr, r4d_rad_vq_encode },
{ "frame_mix_store_bf16", "frame_mix_store", "elem",
"a frame's conditioning row into its lane", "a workgroup a lane, L <= 16",
"bf16 planes and rows, f32 logits and scale",
@@ -8751,6 +9123,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_end_status },
{ "ras_pick", "ras_pick", "elem",
"a repetition-aware choice between two draws a lane", "a thread a lane", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_ras_pick },
{ "frame_store", "frame_store", "elem",
"a frame's codes into its lane's history", "a thread a (lane, code); dst contiguous", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
@@ -8806,6 +9184,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_iota },
{ "sub_i32", "sub_i32", "elem",
"a device int32 vector less a device scalar", "contiguous i32", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
nullptr, 0, NOTUNE,
nullptr, nullptr, r4d_rad_sub_i32 },
{ "cu_repeat", "cu_repeat", "elem",
"bounds of equal sequences from a device length", "contiguous i32", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
@@ -9034,13 +9418,6 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cGenAnyFloat), NOTUNE,
nullptr, nullptr, r4d_rad_pix_patch },
{ "patch_pix8", "patch_pix8", "elem",
"patch rows to RGB bytes: a thread a byte",
"dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenAnyFloat), NOTUNE,
nullptr, nullptr, r4d_rad_patch_pix8 },
{ "vol_index", "vol_index", "elem",
"a volume's voxel coordinates: a thread a voxel", "i32, a dense [3, n]", "i32",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
@@ -9211,10 +9588,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
* every collective the peer flags and exchange buffers the all-reduces own
*
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output;
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
* output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken
* at init, one per declared op and band). Concurrent launches never share these, so those three
* rows are concurrent. A new row with stream-ordered state belongs in the list above.
* gemm_mxfp4a8_decode's (and gemm_mxfp4a8_decode_shortk's, the same entry) split partial is the
* op's scratch and its arrival counters are keyed on the output alone;
* router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken at init, one
* per declared op and band). Concurrent launches never share these, so those four rows are
* concurrent. A new row with stream-ordered state belongs in the list above.
*
* lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they
* update and refills the pools they read between steps with its own copies,
@@ -9378,37 +9756,27 @@ extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
out->splits = TUNE(a, tAttnSplit, "splits");
}
/* A fresh-start divergence (4x R9700 behind an EPYC root complex, 2026-10-17): on a freshly
* started 31B server, a prefill all-reduce now and then reads a peer's scratch before that peer's
* words have landed -- the first reuse of a double-buffered slot, inputs identical on every rank
* (RADIANCE_DEBUG_OPHASH) -- and the first greedy reply flips a near-tie. Every thread's full
* system fence before the flag (drain 1) cures it, as does one after it (acq 1); the per-wave
* store wait (drain 3) and the publisher's one writeback (pub 1) do not, and Relaxed Ordering off
* on every link does not. The mechanism below the fence is not known. Decode heights never showed
* it, and the fence costs them ~0.7 %, so it is taken only from RADIANCE_AR_FENCE_FROM elements
* (default 131072, 24 rows of the 31B's 5376: above any verify height, and every prefill chunk);
* 0 never. Read once. Only at four ranks, where it was seen and cured: at two (Qwen3.8-27B's
* prefill at tp 2) it cost 4.5% of prefill, and no two-rank start ever flipped. */
static long long ar_fence_from() {
static const long long v = [] {
const char* e = std::getenv("RADIANCE_AR_FENCE_FROM");
return e && *e ? std::atoll(e) : 131072LL;
}();
return v;
}
/* Four-rank collectives of at least kArFenceFromElems elements take drain 1, every thread's full
* system fence before the flag, instead of the per-wave store wait. Without it a peer has been seen
* to read stale scratch on 4x R9700 behind an EPYC root complex: a prefill all-reduce at the first
* reuse of a double-buffered slot, on a freshly started server. The publisher's single writeback
* and Relaxed Ordering off do not prevent it; the fence does, and the mechanism below it is not
* known. The threshold, 24 rows of a 5376-wide trunk, lies above every decode and verify height
* and below every prefill chunk, so decode pays nothing (the fence would cost it about 0.7%) and a
* four-rank prefill about 0.5-0.8%. Two ranks have their own handshake and never take it. The
* bytes are the same either way; only when the flag goes out moves. */
static constexpr long long kArFenceFromElems = 131072;
extern "C" void r4d_cfg_ar(const RadArgs* a, R4dArCfg* out) {
out->nblocks = TUNE(a, tAr, "nblocks");
out->nthreads = TUNE(a, tAr, "nthreads");
out->drain = TUNE(a, tAr, "drain");
out->acq = TUNE(a, tAr, "acq");
/* An axis of the four-rank junction only (tArQ84); 1 for every other row, as before. */
out->pub = TUNE(a, tArQ84, "pub");
out->pub = 1; /* not an axis; see the note at tAr */
/* Operand 0 is the message on every collective that reads this (all_reduce's x, a junction's
* [M, n] input, all_gather's source). */
const long long from = ar_fence_from();
if (from > 0 && a && a->t && a->n_t > 0 && rad_tensor_numel(&a->t[0]) >= from &&
r4d_geti_or(a, "world_size", 4) == 4) /* the four-rank rows carry no world_size */
if (a && a->t && a->n_t > 0 && rad_tensor_numel(&a->t[0]) >= kArFenceFromElems &&
r4d_geti_or(a, "world_size", a->world_size) == 4)
out->drain = 1;
}
extern "C" int r4d_cfg_ar_tail(const RadArgs* a) {
+413
View File
@@ -0,0 +1,413 @@
// r4d_sam_attn_bf16 -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative
// position (`sam_attn`; arch/common/rad_block_sam.h, libref/ref_sam_attn.cpp is the oracle).
//
// The logits of a query row i against a key j of the same window tile are
//
// scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w]
//
// over the head's whole head_dim, the tables indexed by the offset inside the tile. With `window`
// > 0 the grid is padded with ZERO rows to a multiple of the window and cut into window x window
// tiles (deepencoder's window_partition, after norm1): the pad rows are keys and values of their
// tile and take part in the softmax, their v being zero. `window` 0 is one tile over the segment.
//
// Shape. One block per (segment, tile, head), so the tile's keys are shared by the block's query
// rows and the k/v rows a wave reads at each step are one address (an L1/L2 hit, broadcast across
// the wave). Each thread owns one query row: q and the output accumulator are HD floats in
// registers, the softmax is the online form (running max and sum), and the rel_pos dot of a tile
// row is computed once per (query row, tile row) rather than once per key.
//
// Head widths. HD is a template parameter and only 64 is instantiated (SAM ViT-B's 12 x 64); the
// shim refuses any other width rather than reading past the registers. A table whose row count is
// not 2*tile-1 is resampled on read (get_rel_pos's F.interpolate(size=want, mode="linear",
// align_corners=False) in f32): the 127-row global tables give 79 rows at a 40 grid, and every
// other geometry the tower declares already has exactly the rows it wants.
//
// Exactness. f32 throughout, one bf16 rounding of the output, exp2 (the hardware transcendental)
// with the log2(e) factor; the selftest holds it to the house tolerance against a host port of the
// reference, not to bits.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include <cmath>
namespace {
constexpr uint32_t kThreads = 128;
constexpr float kLog2e = 1.4426950408889634f;
/* Row loads stay scalar uint16: the operand contract allows any row pitch (the tower's q/k/v are
* column slices of one fused projection, and a tower may pad rows), so a 16-byte bf16x8 read
* would be misaligned for a pitch that is not a multiple of 8 elements. The register diet is the
* w-dot hoist below, not the load width. */
/* q . row(d) of a rel_pos table as the reference resized it to `want` rows: linear interpolation
* between the two source rows at align_corners=False's coordinate, clamped at the edges. With
* rows == want the source is row d itself (f == 0), so the direct read is unchanged bit for bit. */
template <int HD>
__device__ inline float tab_dot(const uint16_t* __restrict__ tab, int rows, int want, int d,
const float* qf) {
if (rows == want) {
const uint16_t* rp = tab + (size_t)d * HD;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(rp[c]);
return s;
}
double src = ((double)d + 0.5) * (double)rows / (double)want - 0.5;
if (src < 0.0) src = 0.0;
if (src > (double)(rows - 1)) src = (double)(rows - 1);
const int i0 = (int)src, i1 = i0 + 1 < rows ? i0 + 1 : i0;
const float f = (float)(src - (double)i0);
const uint16_t* a = tab + (size_t)i0 * HD;
const uint16_t* b = tab + (size_t)i1 * HD;
float s = 0.0f;
#pragma unroll
for (int c = 0; c < HD; ++c) {
const float av = bf16_to_f32(a[c]);
s += qf[c] * (av + (bf16_to_f32(b[c]) - av) * f);
}
return s;
}
/* Eight bf16 of a q/k/v/out row as one 16-byte uint4. VEC is only instantiated when the caller
* proved every involved pointer is 16-byte aligned and every row pitch a multiple of 8 elements
* (launch_sam_attn); otherwise the scalar uint16 path below runs, because the operand contract
* allows any pitch (the tower's q/k/v are column slices and may carry a filler column). The
* element order is the scalar order, so both paths produce bit-identical dots. */
__device__ inline void bf16x8_to_f32(uint4 u, float* f) {
const unsigned* w = (const unsigned*)&u;
#pragma unroll
for (int i = 0; i < 4; ++i) {
f[2 * i] = bf16_to_f32((uint16_t)(w[i] & 0xffffu));
f[2 * i + 1] = bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
template <bool VEC, int HD>
__device__ inline void ld_row(const uint16_t* p, float* f) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) bf16x8_to_f32(u[c8], f + c8 * 8);
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) f[c] = bf16_to_f32(p[c]);
}
}
template <bool VEC, int HD>
__device__ inline void st_row(uint16_t* p, const float* f) {
if (VEC) {
uint4 u[HD / 8];
uint16_t* b = (uint16_t*)u;
#pragma unroll
for (int c = 0; c < HD; ++c) b[c] = f32_to_bf16(f[c]);
uint4* o = (uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) o[c8] = u[c8];
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) p[c] = f32_to_bf16(f[c]);
}
}
template <bool VEC, int HD>
__device__ inline float dot_row(const uint16_t* p, const float* qf) {
float s = 0.0f;
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
const unsigned* w = (const unsigned*)&u[c8];
#pragma unroll
for (int i = 0; i < 4; ++i) {
s += qf[c8 * 8 + 2 * i] * bf16_to_f32((uint16_t)(w[i] & 0xffffu));
s += qf[c8 * 8 + 2 * i + 1] * bf16_to_f32((uint16_t)(w[i] >> 16));
}
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(p[c]);
}
return s;
}
template <bool VEC, int HD>
__device__ inline void axpy_row(float* acc, const uint16_t* p, float pv) {
if (VEC) {
const uint4* u = (const uint4*)p;
#pragma unroll
for (int c8 = 0; c8 < HD / 8; ++c8) {
float f8[8];
bf16x8_to_f32(u[c8], f8);
#pragma unroll
for (int i = 0; i < 8; ++i) acc[c8 * 8 + i] += pv * f8[i];
}
} else {
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] += pv * bf16_to_f32(p[c]);
}
}
template <int HD, bool VEC>
__device__ inline void sam_attn_body(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int seq, int head, int ty, int tx, int row_lo, int row_hi, float scale) {
// The caller supplies the (segment, tile, head) block coordinates: the windowed kernel reads
// them from blockIdx.x's window-tile layout, the global one from its query-tile layout.
const int s0 = cu[seq];
if (cu[seq + 1] - s0 != gh * gw) {
// A segment that is not one grid is a tower bug, not a shape: the shim pre-checks the
// row count against the segment count, and this is the device-side guard. Write NaN over
// the segment's rows (the vit kernel's poison convention) so the corruption reaches the
// consumer -- a silent return would pass a garbage plane on as success.
const int n = cu[seq + 1] - s0;
for (int r = (int)threadIdx.x; r < n; r += (int)kThreads) {
uint16_t* op = go + (size_t)(s0 + r) * (size_t)o_ld + (size_t)head * HD;
for (int c = 0; c < HD; ++c) op[c] = (uint16_t)0x7fc0u; // bf16 NaN, as vit poisons
}
return;
}
for (int r = row_lo + (int)threadIdx.x; r < row_hi; r += (int)kThreads) {
const int lh = r / tw, lw = r % tw;
const int ih = ty * th + lh, iw = tx * tw + lw;
if (ih >= gh || iw >= gw) continue; // a pad row: no output
const size_t qrow = (size_t)(s0 + ih * gw + iw);
const uint16_t* qp = gq + qrow * (size_t)q_ld + (size_t)head * HD;
float qf[HD];
ld_row<VEC, HD>(qp, qf);
float acc[HD];
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] = 0.0f;
float m = -INFINITY, l = 0.0f;
/* The w rel-pos dots depend on (lw, jw) only: computed once for the query row when the
* tile is narrow (the windowed tiles are 14 wide), recomputed per key otherwise. For a
* whole-grid tile that is gw dots a query row instead of gw per key row, i.e. the same
* count as the q.k dots rather than gh times it; the array is spilled to local memory
* when the compiler runs out of registers, which is still far cheaper than the dot. */
float wr[16];
float wr_all[64];
const bool wr_hoist = tw <= 16;
const bool wr_wide = !wr_hoist && tw <= 64;
if (wr_hoist)
for (int jw = 0; jw < tw; ++jw)
wr[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
else if (wr_wide)
for (int jw = 0; jw < tw; ++jw)
wr_all[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
for (int jh = 0; jh < th; ++jh) {
const float hr = tab_dot<HD>(rh, rh_rows, 2 * th - 1, lh - jh + th - 1, qf);
const int kh = ty * th + jh;
const bool hreal = kh < gh;
for (int jw = 0; jw < tw; ++jw) {
float s = hr + (wr_hoist ? wr[jw]
: (wr_wide ? wr_all[jw]
: tab_dot<HD>(rw, rw_rows, 2 * tw - 1,
lw - jw + tw - 1, qf)));
const int kw = tx * tw + jw;
const bool real = hreal && kw < gw;
const uint16_t* vp = nullptr;
if (real) {
const size_t krow = (size_t)(s0 + kh * gw + kw);
const uint16_t* kp = gk + krow * (size_t)k_ld + (size_t)head * HD;
const float d = dot_row<VEC, HD>(kp, qf);
s += scale * d;
vp = gv + krow * (size_t)v_ld + (size_t)head * HD;
}
// Online softmax: a new maximum rescales what has been accumulated.
if (s > m) {
const float corr = ex2((m - s) * kLog2e);
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] *= corr;
l *= corr;
m = s;
}
const float p = ex2((s - m) * kLog2e);
l += p;
if (real) axpy_row<VEC, HD>(acc, vp, p);
}
}
const float inv = l > 0.0f ? 1.0f / l : 0.0f;
uint16_t* op = go + qrow * (size_t)o_ld + (size_t)head * HD;
#pragma unroll
for (int c = 0; c < HD; ++c) acc[c] *= inv;
st_row<VEC, HD>(op, acc);
}
}
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, int vec_rows, float scale) {
// blockIdx.x = ((seq * nth + ty) * ntw + tx) * nhead + head: heads adjacent, so the tile's k/v
// rows stay hot across them.
int b = blockIdx.x;
const int head = b % nhead; b /= nhead;
const int tx = b % ntw; b /= ntw;
const int ty = b % nth; b /= nth;
const int seq = b;
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, seq, head, ty, tx, 0, th * tw, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, seq, head, ty, tx, 0, th * tw, scale);
}
/* The global path (window 0) is one tile over the whole segment, so the kernel above would launch
* nseq*nhead blocks with each thread walking rows/N-threads query rows in series (12-32 on a 40 or
* 64 grid): 60 blocks for a 5-tile page, far too few to fill the card. This variant keeps the same
* per-row math and key order but tiles the query rows, one block per (segment, query tile, head).
* Grid positions are the segment's row-major cells, so a tile is a contiguous row range. */
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_qtile_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw,
int nqb, int qrows, int vec_rows, float scale) {
int b = blockIdx.x;
const int head = b % nhead; b /= nhead;
const int qblk = b % nqb; b /= nqb;
const int seq = b;
const int keys = gh * gw;
const int lo = qblk * qrows;
const int hi = keys < lo + qrows ? keys : lo + qrows;
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, gh, gw, seq, head, 0, 0, lo, hi, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, gh, gw, seq, head, 0, 0, lo, hi, scale);
}
int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o,
const int* cu, const uint16_t* rh, const uint16_t* rw,
int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nseq, int nhead, int gh, int gw,
int win, float scale, long stream) {
const int th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
const int nth = (gh + th - 1) / th, ntw = (gw + tw - 1) / tw;
/* The 16-byte row loads are legal only when every q/k/v/out row starts on a 16-byte
* boundary: all four bases aligned, every row pitch a multiple of 8 bf16. The selftest's
* padded pitch and a slice with a filler column both fail this and take the scalar path. */
const uintptr_t addr_bits = (uintptr_t)q | (uintptr_t)k | (uintptr_t)v | (uintptr_t)o;
const bool vec_rows = (addr_bits & 15u) == 0 &&
((q_ld | k_ld | v_ld | o_ld) & 7) == 0;
if (win == 0) {
/* One block per (segment, 128-row query tile, head): the whole-segment tile above would
* give each thread 12-32 query rows in series and launch only nseq*nhead blocks. */
const int qrows = 128;
const int keys = gh * gw;
const int nqb = (keys + qrows - 1) / qrows;
const size_t qblocks = (size_t)nseq * nqb * nhead;
if (qblocks == 0 || qblocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL((sam_attn_qtile_kernel<64>), dim3((uint32_t)qblocks),
dim3(kThreads), 0, (hipStream_t)stream, q, k, v, o, cu, rh, rw,
rh_rows, rw_rows, q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, nqb, qrows,
vec_rows ? 1 : 0, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)stream, q, k, v, o, cu, rh, rw, rh_rows, rw_rows,
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw,
vec_rows ? 1 : 0, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
} // namespace
// ================================================================================ entry point
//
// The shim checks what the kernel assumes: bf16 operands, rank 2 with dense columns and any row
// pitch (the tower's q/k/v are the three column slices of one fused projection), an i32 cu with one
// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The shim
// checks the row count against the segment count host-side; per-segment length is the kernel's to
// check, and a malformed segment writes NaN over its rows (the vit kernel's poison convention)
// so the corruption reaches the consumer instead of passing as success.
#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0)
static inline int bf16_rows(const RadTensor* t, int64_t cols, int64_t* rows, int64_t* ld) {
if (!t || !t->data) return RAD_E_INVAL;
if (t->dtype != RAD_BF16) return RAD_E_DTYPE;
if (t->rank != 2) return RAD_E_SHAPE;
if (t->shape[1] != cols || t->stride[1] != 1) return RAD_E_SHAPE;
*rows = t->shape[0];
*ld = t->stride[0];
return RAD_OK;
}
extern "C" int r4d_rad_sam_attn(const RadArgs* a, RadStream s) {
enum { V_Q = 0, V_K, V_V, V_CU, V_OUT, V_RH, V_RW };
const RadTensor* q = r4d_opt(a, V_Q);
const RadTensor* k = r4d_opt(a, V_K);
const RadTensor* v = r4d_opt(a, V_V);
const RadTensor* cu = r4d_opt(a, V_CU);
const RadTensor* o = r4d_opt(a, V_OUT);
const RadTensor* rh = r4d_opt(a, V_RH);
const RadTensor* rw = r4d_opt(a, V_RW);
if (!q || !k || !v || !cu || !o || !rh || !rw) return R4D_NO(RAD_E_INVAL);
const long long hd = r4d_geti_or(a, "head_dim", 0);
const long long nh = r4d_geti_or(a, "n_head", 0);
const long long gh = r4d_geti_or(a, "grid_h", 0);
const long long gw = r4d_geti_or(a, "grid_w", 0);
const long long win = r4d_geti_or(a, "window", 0);
if (hd != 64 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return R4D_NO(RAD_E_UNSUPPORTED);
const long long W = nh * hd;
int64_t qrows = 0, qld = 0, krows = 0, kld = 0, vrows = 0, vld = 0, orows = 0, old = 0;
R4D_NEED(bf16_rows(q, W, &qrows, &qld));
R4D_NEED(bf16_rows(k, W, &krows, &kld));
R4D_NEED(bf16_rows(v, W, &vrows, &vld));
R4D_NEED(bf16_rows(o, W, &orows, &old));
if (qrows <= 0 || krows < qrows || vrows < qrows || orows < qrows) return R4D_NO(RAD_E_SHAPE);
if (!cu->data) return R4D_NO(RAD_E_INVAL);
if (cu->dtype != RAD_I32 || !r4d_contig(cu)) return R4D_NO(RAD_E_DTYPE);
const long long nseq = r4d_numel(cu) - 1;
if (nseq < 1) return R4D_NO(RAD_E_SHAPE);
/* The tower declares cu as one segment per grid, so the host-side row count pins the
* segment count. A mismatch is a malformed segment and fails at issue, not on the device
* (the kernel's per-segment guard poisons the visible rows for what this cannot see). */
if (qrows != nseq * gh * gw) return R4D_NO(RAD_E_SHAPE);
// The tables: [2*tile-1, head_dim] when the geometry has its own, else the checkpoint's rows
// (the 127-row global table at a 40 grid), resampled on read.
int64_t rhrows = 0, rhld = 0, rwrows = 0, rwld = 0;
R4D_NEED(bf16_rows(rh, hd, &rhrows, &rhld));
R4D_NEED(bf16_rows(rw, hd, &rwrows, &rwld));
if (rhrows < 1 || rwrows < 1) return R4D_NO(RAD_E_UNSUPPORTED);
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
return launch_sam_attn((const uint16_t*)r4d_addr(q), (const uint16_t*)r4d_addr(k),
(const uint16_t*)r4d_addr(v), (uint16_t*)r4d_addr(o),
(const int*)r4d_addr(cu), (const uint16_t*)r4d_addr(rh),
(const uint16_t*)r4d_addr(rw), (int)rhrows, (int)rwrows,
(int)qld, (int)kld, (int)vld, (int)old,
(int)nseq, (int)nh, (int)gh, (int)gw, (int)win, scale,
(long)(uintptr_t)s);
}
+214
View File
@@ -0,0 +1,214 @@
// r4d_sample_ngram_f32 -- the windowed no-repeat-ngram ban (`sample_ngram_ban`).
//
// Unlimited-OCR's generation_config asks for SlidingWindowNoRepeatNgramProcessor(n=35,
// window=128): a token that would complete an n-gram the last `window` tokens of the sequence
// already contain is banned, by setting its logit to -infinity. modeling_unlimitedocr.py:353-383
// is the reference, which SGLang ships as DeepseekOCRNoRepeatNGramLogitProcessor. A model that
// loops at the n-gram level (OCR layout rows repeat) otherwise repeats a phrase until the context
// ends.
//
// The reference's rule, with the row's history `s[0, hl)` oldest first (the committed tokens,
// including the one just emitted, plus this step's earlier drafts at a speculative verify):
//
// search_start = max(0, hl - w) with w from the row's {n, window} pair, w <= 0 whole span
// search_end = hl - n + 1
// for idx in [search_start, search_end):
// if s[idx .. idx + n - 2] == s[hl - n + 1 .. hl - 1): ban s[idx + n - 1]
//
// and at n = 1 the prefix is empty, so every token in the window is banned. The window bounds the
// n-gram's START, not its end, exactly as the reference slices `sequence[search_start:search_end]`
// -- which is why an n-gram that spans the window boundary is still searched.
//
// Exactness. Nothing here rounds: the kernel compares int32 history ids and stores the constant
// -infinity, so its answer is libref's ref_sample_ngram_ban by construction, not by tolerance. The
// only ordering freedom is that two threads may store -infinity to the same column, and the store
// is idempotent.
//
// Ids are global and the logits row is this rank's vocabulary shard: a token's column is its id
// less `vocab_off`, and a token outside the shard is another rank's to mask (it is not a column
// here at all).
//
// The optional `whitelist` plane is the reference's whitelist (modeling_unlimitedocr.py:359,379):
// word w bit b of the row's own plane row covers column 32w + b, and a SET bit removes that token
// from the banned set -- it is never written. Absent, nothing is exempt, and the kernel's answer
// is the one before the whitelist existed.
//
// The scan is O(w * n) a row over a history of at most max_hist tokens, so one block a row with
// the positions dealt out across the block's threads; the n-1-token prefix is staged in LDS once
// when it fits (n <= 256), which is every request the model card asks for (35).
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include <cfloat>
// The params row is the engine's wire format, included rather than restated (abi/rad_sample.h).
#include "rad_sample.h"
namespace {
constexpr uint32_t kThreads = 256;
// The prefix staged in LDS, one int32 a token: 1 KiB. A longer n falls back to reading the
// history plane, which is correct but repeats the prefix's loads per position.
constexpr uint32_t kMaxPrefix = 256;
using SP = RadSampleParams;
__global__ __launch_bounds__(kThreads) void ngram_ban_kernel(
float* __restrict__ lg, const SP* __restrict__ sp, const int32_t* __restrict__ hist,
const int32_t* __restrict__ ng, const uint32_t* __restrict__ wl, uint32_t wl_words,
uint32_t n_vocab, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
__shared__ int32_t pf[kMaxPrefix];
__shared__ int64_t s_start, s_end, s_plen, s_p0;
const uint32_t m = blockIdx.x;
const SP p = sp[m];
// The row's {n-gram length, window} pair (a separate plane, so the params row keeps the wire
// format every sampler op shares).
const int32_t ngram = ng[2 * m];
const int32_t win_req = ng[2 * m + 1];
// Every test before the barrier reads the row's own planes, so the block leaves together.
if (ngram <= 0) return;
// The whole staged span of the row (hist_off/hist_len both come from the engine; a negative
// hist_off is 0), clamped to the plane.
int32_t hl = p.hist_len;
int32_t ho = p.hist_off < 0 ? 0 : p.hist_off;
if (ho > (int32_t)hmax) ho = (int32_t)hmax;
if (hl > (int32_t)hmax - ho) hl = (int32_t)hmax - ho;
if (threadIdx.x == 0) {
int64_t start = 0, end = 0, plen = 0, p0 = 0;
if (hl >= ngram) {
// w <= 0 is the un-windowed processor: the whole staged history.
const int64_t win = win_req > 0 && win_req < hl ? win_req : hl;
start = hl - win;
end = (int64_t)hl - ngram + 1;
plen = (int64_t)ngram - 1;
p0 = (int64_t)hl - plen;
if (end <= start) end = start; /* nothing to search */
}
s_start = start;
s_end = end;
s_plen = plen;
s_p0 = p0;
}
__syncthreads();
const int64_t start = s_start, end = s_end, plen = s_plen, p0 = s_p0;
if (end <= start) return;
const int32_t* __restrict__ h = hist + (size_t)m * hmax + ho;
float* __restrict__ row = lg + (size_t)m * lg_ld;
// The row's own whitelist words (a SET bit exempts the column, the reference's
// `banned.difference_update(self.whitelist)`), read at the position loop below.
const uint32_t* __restrict__ w = wl ? wl + (size_t)m * wl_words : nullptr;
// The prefix: LDS when it fits, otherwise each position reads it from the plane.
const bool in_lds = plen <= (int64_t)kMaxPrefix;
if (in_lds) {
for (int64_t j = threadIdx.x; j < plen; j += (int64_t)kThreads) pf[j] = h[p0 + j];
__syncthreads();
}
auto prefix_at = [&](int64_t j) -> int32_t {
return in_lds ? pf[j] : h[p0 + j];
};
for (int64_t idx = start + (int64_t)threadIdx.x; idx < end; idx += (int64_t)kThreads) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (h[idx + j] != prefix_at(j)) { match = false; break; }
}
if (!match) continue;
const int32_t tok = h[idx + plen];
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= (int64_t)n_vocab) continue;
if (wl && ((w[col >> 5] >> (uint32_t)(col & 31)) & 1u) != 0u) continue;
// Two positions may ban one token; the store is idempotent and the value is constant.
row[col] = -INFINITY;
}
}
int r4d_sample_ngram_ban_f32(long lg, long params, long hist, long ng, long wl, int wl_words,
int M, int n_vocab, int hmax, int lg_ld, int vocab_off, long stream) {
if (!lg || !params || !hist || !ng) return R4D_NO(RAD_E_INVAL);
if (M <= 0 || n_vocab <= 0 || hmax <= 0) return R4D_NO(RAD_E_SHAPE);
if (wl && wl_words <= 0) return R4D_NO(RAD_E_SHAPE);
if (!lg_ld) lg_ld = n_vocab;
hipLaunchKernelGGL(ngram_ban_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(float*)lg, (const SP*)params, (const int32_t*)hist, (const int32_t*)ng,
(const uint32_t*)wl, (uint32_t)(wl ? wl_words : 0),
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
} // namespace
// ================================================================================ entry point
//
// The shim checks what the kernel assumes: f32 logits, an i32 history contiguous in both rows and
// columns (the kernel walks it as one int32 a token), a params plane of whole RadSampleParams rows
// and the row pitches. `M` is the step's staged row count, never the band's upper bound.
#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0)
static inline int dt_f32(const RadTensor* t) {
return (t && t->dtype == RAD_F32) ? RAD_OK : RAD_E_DTYPE;
}
static inline int dt_i32(const RadTensor* t) {
return (t && (t->dtype == RAD_I32 || t->dtype == RAD_U32)) ? RAD_OK : RAD_E_DTYPE;
}
static int params_ok(const RadTensor* t, long long M) {
if (!t || !t->data) return R4D_NO(RAD_E_INVAL);
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(t)) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return R4D_NO(RAD_E_SHAPE);
return RAD_OK;
}
extern "C" int r4d_rad_sample_ngram_ban(const RadArgs* a, RadStream s) {
enum { V_LOGITS = 0, V_PARAMS, V_HIST, V_NGRAM, V_WL };
const RadTensor* lg = r4d_opt(a, V_LOGITS);
if (!lg) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_f32(lg));
const long long nv = r4d_geti_or(a, "n_vocab", r4d_dim(lg, (int)lg->rank - 1));
if (nv <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0;
const long long ld = r4d_rows_pitch(lg, nv, &M);
if (ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
const RadTensor* pr = r4d_opt(a, V_PARAMS);
const RadTensor* h = r4d_opt(a, V_HIST);
const RadTensor* ng = r4d_opt(a, V_NGRAM);
R4D_NEED(params_ok(pr, M));
if (!h || !ng) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_i32(h));
R4D_NEED(dt_i32(ng));
if (!r4d_contig(h) || !r4d_contig(ng)) return R4D_NO(RAD_E_STRIDE);
const long long hmax = r4d_numel(h) / M;
if (hmax <= 0) return R4D_NO(RAD_E_SHAPE);
/* One {n, window} pair a row, at least M of them. */
if (r4d_numel(ng) < 2 * M) return R4D_NO(RAD_E_SHAPE);
/* The optional whitelist bitmask: contiguous words of 32 columns, M rows of them. */
const RadTensor* wl = r4d_opt(a, V_WL);
const long long wwords = (nv + 31) / 32;
long long wl_addr = 0;
if (wl) {
R4D_NEED(dt_i32(wl));
if (!r4d_contig(wl)) return R4D_NO(RAD_E_STRIDE);
if (r4d_numel(wl) < M * wwords) return R4D_NO(RAD_E_SHAPE);
wl_addr = r4d_addr(wl);
}
const long long voff = r4d_geti_or(a, "vocab_off", 0);
return r4d_sample_ngram_ban_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), r4d_addr(ng),
wl_addr, (int)wwords,
(int)M, (int)nv, (int)hmax, (int)ld, (int)voff,
(long)(uintptr_t)s);
}
+1558 -281
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -145,9 +145,9 @@ __device__ __forceinline__ bool volume_of(const int* geom, long long rows, int*
// once a tap.
//
// Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27
// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The
// select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the
// GEMM's vector instructions. The weight through global loads at a uniform base is 0.2-1% slower;
// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). A
// select-and-pointer form of the gather runs 136 and 134: its loop issues twice the GEMM's vector
// instructions. The weight through global loads at a uniform base is 0.2-1% slower;
// raster groups of 4 or 16 bands are within noise of 8. 512 -> 24 (the output convolution) runs at
// 30 with 13/16 of its 128-wide channel tile idle, a few milliseconds of a whole upscale.
constexpr uint32_t kCTW = 2, kCTA = 4, kCWW = 4, kCWA = 2;
+2 -2
View File
@@ -298,8 +298,8 @@ __global__ __launch_bounds__(256) void vit_gemm_kernel(
// weight rows of one activation row, so the bias is eight consecutive values and the store (with
// its residual read) is one 16-byte access.
//
// Staging both operands through LDS with a 4 x 2 tile a wave (the kernel above at 128 x 128, which
// this replaces) costs 384 bytes of fragment reads and 128 of stores per bf16 WMMA: all of gfx1201's
// Staging both operands through LDS with a 4 x 2 tile a wave (the kernel above at 128 x 128)
// costs 384 bytes of fragment reads and 128 of stores per bf16 WMMA: all of gfx1201's
// LDS bandwidth, 64 bytes a clock per CU against one bf16 WMMA every 16 clocks per SIMD
// (libr4d/isa/wmmamix.hip). Here it is 256 and 64, and the weight's 128 bytes come through the
// vector cache.