radiance 1.11.0

New models:
- GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget),
  with decode kernels for a few rows and the DSA indexer split over the ranks
- Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter
- Unlimited-OCR (bf16)
- Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces
  are fused with the junctions, overlapped with the compute and sent compressed
- Ornith-1.5-35B-A3B w4a8 compose files

Speed:
- Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued
  ahead
- The four-rank all-reduce is faster for every --tp 4 model
- qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly
- --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20%
  prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default

Features:
- Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch,
  and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE)
- Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance
- Cards with a small PCI BAR run, with kernel arguments kept in host memory
- Dashboard: live acceptance figures; statsdump rotates its file at a size cap
- KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot

Fixes:
- Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore
  makes room as memory pressure does and waits a step for the previous turn's release (two
  conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now)
- Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory
  management is turned off there, with a warning
- Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output
- The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start
- GLM-5.3: every refusal names the setting and the reason; its template keeps string content
- Several pictures in one request no longer refuse processors that take one image at a time

Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
Deadcode committed 2026-10-23 11:57:52 +02:00
210 files changed
+14363 -2138

No files matched your search

+11 -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,
@@ -158,6 +164,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|"
+8 -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
@@ -693,6 +694,10 @@ void r4d_mla_matrix_pin_form(int form);
// 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;
+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)));
}
@@ -739,11 +741,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, \
@@ -752,7 +754,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;
}
@@ -1033,6 +1036,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);
+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);
+3 -2
View File
@@ -472,8 +472,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;
+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);
+8 -4
View File
@@ -537,9 +537,13 @@ __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';
/* 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 +613,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],
+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) \
+28 -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
@@ -92,13 +95,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 +143,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 +161,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 +185,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
@@ -249,7 +267,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);
@@ -277,6 +294,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);
@@ -730,6 +754,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(
+310 -72
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 },
@@ -2764,7 +2801,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 "
@@ -2911,6 +2949,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,
@@ -2966,6 +3011,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 "
@@ -3534,8 +3584,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,
@@ -3545,7 +3593,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."),
@@ -3585,6 +3633,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"),
@@ -3732,11 +3804,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
@@ -3746,6 +3819,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)
@@ -3901,6 +3975,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. */
@@ -3963,9 +4058,20 @@ 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"),
};
/* 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"),
};
@@ -4582,7 +4688,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"),
};
@@ -4592,6 +4697,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"),
};
@@ -4828,8 +4934,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
@@ -4847,11 +4952,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" },
@@ -4860,28 +4964,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
@@ -5749,6 +5845,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",
@@ -5870,6 +5980,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",
@@ -5879,6 +6020,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",
@@ -5888,6 +6062,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",
@@ -6087,6 +6294,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",
@@ -6207,6 +6452,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
@@ -6547,6 +6793,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",
@@ -7931,11 +8187,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",
@@ -8964,13 +9219,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,
@@ -9308,37 +9556,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);
}
+1038 -211
View File
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -146,9 +146,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.