radiance 1.2.0

- MXFP4 weights: block-fp8 Qwen3.5/3.6/3.8 dense models serve OCP-MXFP4 linears (e2m1, an E8M0
  exponent per 32) at 4-bit weights against E4M3 activations. New libr4d rows: the decode GEMM
  (M <= 128, split-K with a fused last-arriver reduction) and the prefill GEMM on a fragment-tiled
  activation. Qwen3.8-27B MXFP4 (AMD Quark AWQ) is in the model table.
- Cards without peer-to-peer access serve: every collective has a host-memory twin; --p2p
  auto|on|off.
- Stop strings apply to the answer, not to the reasoning block a reply starts in.
- A prefix hit ends one drafter window before the prompt's end, so a windowed block drafter
  (DFlash2) drafts from the first token of a follow-up turn.
This commit is contained in:
Deadcode committed 2026-10-06 21:36:24 +02:00
1 parent 7001841e45
commit e95d397288
47 files changed
+2611 -219

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
# a plugin contract and a server release do not move together.
project(radiance VERSION 1.1.1 LANGUAGES C CXX)
project(radiance VERSION 1.2.0 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+3 -1
View File
@@ -2,7 +2,9 @@ radiance
Copyright 2026 Deadcode and the radiance contributors
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
(the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, and
+1
View File
@@ -17,6 +17,7 @@ If you wish to support the developement of the radiance engine you can do so [he
|---|---|---|---|
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
+3 -2
View File
@@ -122,10 +122,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
/* The fold, over the same weights and into the same activation the pair writes. Not
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold. */
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */
{
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
if (hi > 0 && !gate_up.bf16) {
if (hi > 0 && !gate_up.bf16 && !gate_up.mx) {
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
RAD_INT("K", gate_up.K),
+86
View File
@@ -681,6 +681,15 @@ struct LinearFP8 {
* GEMM. Read off the weight's encoding like `bf16`. */
bool i8 = false;
rad_op op_q = 0;
/* AN OCP-MXFP4 WEIGHT, read by `gemm_nt_q` at dtype mxfp4a8 against the SAME E4M3 pair every
* other linear here reads (`a.q`, `a.s` at an f32 scale per (row, 128)): e2m1 codes and one
* E8M0 exponent per 32 of K, as libquant writes `codes=fp4_e2m1 group=32 scale=e8m0`. libr4d
* folds each block's exponent into the e4m3 operand against a per-row reference, so the scale
* plane is handed over TWICE: as `b_scale` and as `b_ref`, whose layout hook reduces the same
* plane to that reference -- `wref` is the second view. The activation grid is the fp8 family's, so every producer's fused quantiser
* feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */
bool mx = false;
rad_weight wref = 0;
/* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear
* before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */
bool probed_i8 = false;
@@ -778,6 +787,16 @@ inline bool linear_is_w8(const RadEncoding& e) {
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
}
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes one a value and an E8M0 exponent
* per [1 x 32], no transform -- what libr4d's MXFP4 layout hook accepts. */
enum { RAD_MX_GROUP = 32 };
inline bool linear_is_mxfp4(const RadEncoding& e) {
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
}
inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base,
std::initializer_list<const char*> src) {
if (src.size() == 0) return RAD_E_INVAL;
@@ -918,6 +937,67 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
return RAD_E_DTYPE;
}
/* ---- AN OCP-MXFP4 WEIGHT over the E4M3 pair. Three views of one stored weight: the codes,
* the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the
* weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in
* whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */
mx = known && linear_is_mxfp4(enc);
if (mx) {
if (!a.q || !a.s) {
fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 "
"pair, and its input has none\n", wn);
return RAD_E_DTYPE;
}
if (N % 16 || K % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
"16s and K in whole %d-column activation scale blocks.\n",
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
int64_t parts[RAD_MAX_ROW_PARTS] = {0};
int np = 0;
for (int64_t p : row_parts) {
if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
if (p % 16) {
fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole "
"number of 16-row MXFP4 tiles; it cannot be row-sharded.\n",
base, (long long)p);
return RAD_E_INVAL;
}
parts[np++] = p;
}
const char* sn = nm.f("%s.scale", base);
const char* rn = nm.f("%s.ref", base);
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN,
shard, grp, parts, np);
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
if (!w || !ws || !wref) return RAD_E_INVAL;
if (span_hi > 0) {
const bool col = shard == RAD_SHARD_COL;
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
"%d-column activation scale block.\n", base, (long long)span_lo,
(long long)span_hi, RAD_FP8_BLOCK);
return RAD_E_INVAL;
}
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
const int64_t hi = col ? span_hi / RAD_MX_GROUP : span_hi;
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
}
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
op = rw(b, RAD_OP(b, "gemm_nt_q",
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
RAD_WEIGHTS(w, ws, wref)),
{ a.q, a.s }, { y });
return op ? RAD_OK : RAD_E_INVAL;
}
/* The one geometric precondition, checked here so it is reported once per weight with the
* weight named rather than as a kernel miss with a band in it. These are PER-RANK extents, so
* this is also the check that a tensor-parallel width does not cut a scale block in half. */
@@ -1016,6 +1096,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
return;
}
if (mx) {
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
return;
}
if (op_m1 && rows <= mv_rows)
RAD_ISSUE_N(c, op_m1, rows, brow_slice(a.x, r0, rows, K), RAD_NONE,
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
+10
View File
@@ -39,6 +39,9 @@ static const Flag g_flags[] = {
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
"none at 8" },
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
"asks the driver, on requires peer access and stops without\n"
"it, off exchanges through pinned host memory" },
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
@@ -362,6 +365,13 @@ int config_parse(int argc, char** argv, Config* c) {
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--p2p")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
else if (!std::strcmp(v, "on")) c->p2p = RAD_P2P_ON;
else if (!std::strcmp(v, "off")) c->p2p = RAD_P2P_OFF;
else { RAD_ERR("--p2p takes auto, on or off, not '%s'", v); return RAD_E_INVAL; }
}
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
+22 -7
View File
@@ -3028,9 +3028,11 @@ int Engine::start() {
/* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
* card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
* it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
* kernel is not selected, and declare names the constraint instead of the all-reduce faulting
* or hanging on its first message. Every ordered pair, because access is granted one way at a
* time. */
* kernel is not selected, and one that exchanges through host memory takes the op instead (or
* declare names the constraint) rather than the all-reduce faulting or hanging on its first
* message. Every ordered pair, because access is granted one way at a time. --p2p overrides the
* answer in one direction each way (Config::p2p): off turns it down whatever the driver says,
* on refuses to start without it. */
{
long long p2p = 1;
std::string blocked;
@@ -3048,14 +3050,27 @@ int Engine::start() {
blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]);
}
}
if (cfg_.tp > 1 && cfg_.p2p == RAD_P2P_ON && !p2p) {
RAD_ERR("device: --p2p on, but the driver reports no peer-to-peer access between cards "
"%s. IOMMU settings and the PCIe topology decide this, not radiance; --p2p auto "
"serves through host memory instead", blocked.c_str());
return RAD_E_UNSUPPORTED;
}
const bool forced_off = cfg_.p2p == RAD_P2P_OFF;
if (forced_off) p2p = 0;
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
if (cfg_.tp > 1) {
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
"peer)", cfg_.tp);
else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs "
"it (device.p2p == 1) is not selected; if nothing else implements its "
"op, startup stops below naming it. IOMMU settings and the PCIe "
"topology decide this, not radiance", blocked.c_str());
else if (forced_off)
RAD_INFO("device: --p2p off: the collectives exchange through pinned host memory%s",
blocked.empty() ? " although the driver reports peer-to-peer access"
: "");
else RAD_WARN("device: no peer-to-peer access between cards %s. The collectives "
"exchange through pinned host memory instead, and a kernel that needs "
"peer access (device.p2p == 1) is not selected; if nothing else "
"implements its op, startup stops below naming it. IOMMU settings and "
"the PCIe topology decide this, not radiance", blocked.c_str());
}
}
+40 -16
View File
@@ -224,7 +224,8 @@ void PrefixCache::touch(const BlockHash& h) const {
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out) const {
std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const {
CacheHit hit;
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
if (!enabled_ || tokens.empty()) return hit;
@@ -261,6 +262,43 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
* forward pass. */
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
* at or below `limit` is found by asking each snapshot whether this chain passes through it:
* its key is the chained hash at its own position, which matches only on the same prefix. The
* index holds a few hundred snapshots against tens of thousands of block positions. */
auto deepest = [&](int64_t limit) {
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
return best;
};
/* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
* to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
auto reusable = [&](int64_t m) -> int64_t {
if (!has_linear_) return m * block_size_;
const auto b = deepest(m * block_size_);
return b == ck_by_prefix_.end() ? 0 : b->second.pos;
};
if (cap && matched > cap->tokens / block_size_) {
const int64_t whole = reusable(matched);
if (whole > cap->tokens) {
const int64_t m = cap->tokens > 0 ? cap->tokens / block_size_ : 0;
const int64_t lost = whole - reusable(m);
if (lost <= cap->max_give_back) {
matched = m;
hit.given_back = (int32_t)lost;
}
}
}
for (int64_t b = 0; b < matched; ++b) {
touch(hs[(size_t)b]);
if (!blocks_out) continue;
@@ -287,21 +325,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
hit.n_linear_tokens = hit.n_attn_tokens;
return hit;
}
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
* under the hit is found by asking each snapshot whether this chain passes through it: its
* key is the chained hash at its own position, which matches only on the same prefix. The
* index holds a few hundred snapshots against tens of thousands of block positions. */
auto best = ck_by_prefix_.end();
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
const Ckpt& c = it->second;
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > hit.n_attn_tokens ||
c.pos % block_size_ != 0)
continue;
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
best = it;
}
const auto best = deepest(hit.n_attn_tokens);
if (best == ck_by_prefix_.end()) {
++stats_.ckpt_misses;
return hit;
+15 -2
View File
@@ -108,6 +108,18 @@ struct CacheHit {
int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */
int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */
int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */
int32_t given_back = 0; /* reusable tokens a HitCap took off the whole hit */
};
/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
* with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
* than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
* exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
* recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
* would recompute far more than that tail. */
struct HitCap {
int64_t tokens = 0;
int64_t max_give_back = 0;
};
/* ------------------------------------------------------------------ retention policy */
@@ -181,10 +193,11 @@ public:
*
* NEVER returns the whole prompt: at least one token must remain for the step to compute a
* logit from, so a full hit is backed off by one block. That is not a subtlety the caller
* should have to know. */
* should have to know. `cap`, when given, ends the hit early (HitCap). */
CacheHit lookup(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
std::vector<std::vector<int32_t>>* blocks_out = nullptr) const;
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
const HitCap* cap = nullptr) const;
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
+11
View File
@@ -583,6 +583,9 @@ struct Request {
/* ================================================================== engine config */
/* --p2p: whether the collectives use the cards' peer access. */
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
struct Config {
std::string model; /* path to the .rad */
std::string radiance_home;
@@ -609,6 +612,14 @@ struct Config {
* floor that compresses everything which benefits while leaving single-sequence decode
* exact. */
int64_t tp_wire_min_kb = 128; /* --tp-wire-min-kb */
/* HOW THE COLLECTIVES REACH THE OTHER CARDS. Auto asks the driver, for every ordered pair of
* the ranks' cards, whether one can address the other's memory, and takes the P2P kernels only
* if every pair can. A driver can answer yes on a board where peer traffic is broken or slower
* than going through host memory, and that is what `off` is for: it takes the host-mailbox
* collectives whatever the driver says. `on` takes the P2P kernels and stops startup naming
* the pairs the driver refuses, rather than falling back -- a deployment that was measured on
* P2P should not quietly serve on something else. */
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
int64_t max_tok = 8192; /* --max-num-batched-tokens */
int64_t max_seqs = 256;
int64_t max_ctx = 0; /* 0 = the model's training context */
+6 -5
View File
@@ -148,8 +148,9 @@ struct IPrefixCache {
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
virtual void release(const Request&) {}
virtual CacheHit lookup(const Request& r,
std::vector<std::vector<int32_t>>* blocks_out) const = 0;
/* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const = 0;
virtual const std::vector<int32_t>& cached_groups() const = 0;
/* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it.
@@ -335,10 +336,10 @@ struct PCBinding final : IPrefixCache {
mutable std::vector<MMContentKey> mm_;
explicit PCBinding(PC* p) : m(p) {}
CacheHit lookup(const Request& r,
std::vector<std::vector<int32_t>>* out) const override {
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
const HitCap* cap) const override {
media_keys(r, &mm_);
return m->lookup(r.prompt, mm_, out);
return m->lookup(r.prompt, mm_, out, cap);
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
+4
View File
@@ -123,6 +123,10 @@ struct SchedMetrics {
/* Speculation (§10). */
int64_t draft_tokens = 0;
int64_t draft_accepted = 0;
/* Prefix hits ended early so a windowed block drafter has context (Scheduler::draft_refill_),
* and the reusable tokens they gave back to be recomputed. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
float draft_acceptance = 0.0f;
int draft_depth = 0; /* what the controller would choose right now */
/* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every
+17 -1
View File
@@ -87,6 +87,13 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
n_paged, pc->cached_groups().size(),
hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
}
draft_refill_ = 0;
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
hit_holes_draft_) {
draft_refill_ = prog.drafter.window;
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
"drafter's window is recomputed", (long long)draft_refill_);
}
DraftController::Params dp;
dp.max_depth = cfg.n_spec;
@@ -788,7 +795,16 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
* context back instead of re-prefilling it: it costs a copy, and the alternative
* costs a prefill. */
if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait;
CacheHit h = pc_->lookup(r, &hit_blocks_);
HitCap cap;
if (draft_refill_ > 0) {
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
cap.max_give_back = 2 * draft_refill_;
}
const CacheHit h = pc_->lookup(r, &hit_blocks_, draft_refill_ > 0 ? &cap : nullptr);
if (h.given_back > 0) {
m_.draft_refill_tokens += h.given_back;
++m_.draft_refills;
}
int32_t reuse = h.n_attn_tokens;
if (geo_.checkpoints() && h.n_linear_tokens < reuse) {
/* A hit landing between checkpoints reuses the attention blocks and must replay the
+9
View File
@@ -472,6 +472,15 @@ private:
* also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
* copy is free to drift out of step with the first. */
bool hit_holes_draft_ = true;
/* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
* declined until its window has slid past the hole, which on the follow-up turn of a chat --
* the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
* before the end of the prompt (HitCap): the trunk recomputes that window, the drafter's
* context pass covers it, and the sequence drafts from its first decode step. Output is
* unchanged; only which tokens are recomputed moves. A hit whose nearest checkpoint below
* that point would give back more than two windows is kept whole. The drafter's window, or 0
* where no hit can leave such a hole. */
int64_t draft_refill_ = 0;
BatchBuilder builder_;
DraftController draft_;
+2
View File
@@ -268,6 +268,7 @@ public:
o.draft_acceptance = m.draft_acceptance;
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
o.linear_hit_rate = m.linear_hit_rate;
o.attn_cached_tokens = m.attn_cached_tokens;
o.linear_cached_tokens = m.linear_cached_tokens;
@@ -311,6 +312,7 @@ public:
std::string push(int32_t t) override { return d_.push(t); }
std::string flush() override { return d_.flush(); }
bool stopped() const override { return d_.stopped(); }
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
private:
Detokenizer d_;
};
+6
View File
@@ -102,6 +102,9 @@ struct SchedMetrics {
/* The exact pair the ratio is computed from, for the same reason. */
int64_t draft_tokens = 0;
int64_t draft_accepted = 0;
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
/* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
* cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
* both read as one small number. These carry the conditional rate at each position -- of the
@@ -299,6 +302,9 @@ public:
* search text that can no longer contain what it is searching for, and the generation would
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
virtual bool stopped() const { return false; }
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
* defer_stops_until): the reply starts inside its reasoning block. */
virtual void defer_stops_until(const std::string& /*marker*/) {}
};
class ITokenizer {
+9
View File
@@ -160,6 +160,9 @@ void Metrics::sample(const SchedMetrics& m) {
c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
c_draft_refill_tokens_.inc(
std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
@@ -345,6 +348,12 @@ std::string Metrics::render() const {
w.counter("radiance:draft_accepted_total",
"Speculative tokens accepted; the pair the acceptance ratio is computed from.",
L, c_draft_accepted_.get());
w.counter("radiance:draft_refills_total",
"Prefix hits ended a drafter window early so a windowed block drafter has context.",
L, c_draft_refills_.get());
w.counter("radiance:draft_refill_tokens_total",
"Cached prompt tokens those hits gave back to be recomputed.",
L, c_draft_refill_tokens_.get());
/* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one,
* because that is what vLLM's single number has always meant. The linear side hits at a
+1
View File
@@ -144,6 +144,7 @@ private:
* answers "how much between these two scrapes", and only the second survives a comparison
* between two runs that settled into different mixes. */
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Gauge g_linear_hit_;
+6
View File
@@ -1456,6 +1456,12 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end())
out->stop.push_back(s);
/* A reply that starts inside the reasoning block: its stop strings are the answer's, so they
* apply only after the block's closer (Detokenizer::defer_stops_until). The chat format says
* whether the rendered prompt leaves the block open and what closes it. */
if (render.think_starts_open && !render.think_close.empty())
out->stops_after = render.think_close;
/* Checked HERE, where the answer is still a 400. The grammar being validated may be the
* caller's, or one the template produced for its own tool-call syntax; either way the first
* moment it can fail is when the automaton is built, and building it on the step path would
+3
View File
@@ -77,6 +77,9 @@ struct OaiRequest {
SamplingParams sp;
int32_t max_tokens = 0;
std::vector<std::string> stop;
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
std::string stops_after;
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
bool ignore_eos = false;
int priority = 0;
+25 -2
View File
@@ -30,6 +30,10 @@ struct Server::Generation {
Finish finish = Finish::None;
bool closed = false; /* the server has decided this choice is over */
size_t scanned = 0; /* how far the stop-string scan has reached */
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
* has been generated) and how far the search for it has reached. */
size_t stops_floor = std::string::npos;
size_t closer_scanned = 0;
size_t stop_cut = std::string::npos;
size_t emitted = 0; /* streaming: text already handed to the delta stream */
bool retired = false; /* reap() has been said for this id, at most once */
@@ -330,6 +334,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
return RAD_E_UNSUPPORTED;
}
if (!r.stops_after.empty()) g.detok->defer_stops_until(r.stops_after);
Request rq;
rq.prompt = r.prompts[p].tokens;
@@ -338,7 +343,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
* Offsetting is enough: the sampler's stream is seeded, not chained. */
rq.sp.seed = r.sp.seed + (uint64_t)k;
rq.max_tokens = r.max_tokens;
rq.stop = r.stop;
/* With the stop strings deferred past the reasoning block, the scheduler -- which
* cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
rq.stop = r.stops_after.empty() ? r.stop : std::vector<std::string>{};
rq.ignore_eos = r.ignore_eos;
rq.priority = r.priority;
rq.stream = r.stream;
@@ -429,8 +436,24 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
* string straddles token boundaries and only the detokenised text can be searched, so the
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
* end so a match spanning two drains is still found. */
if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) {
/* Stop strings deferred past the reasoning block match only after its closer. The closer
* is searched for incrementally, from (closer length - 1) bytes behind the previous end,
* so a reply that thinks for a long time is not rescanned from its start every drain. */
size_t floor = 0;
if (!r.stops_after.empty()) {
if (g.stops_floor == std::string::npos) {
const size_t n = r.stops_after.size();
const size_t from = g.closer_scanned >= n ? g.closer_scanned - n + 1 : 0;
const size_t m = g.text.find(r.stops_after, from);
g.closer_scanned = g.text.size();
if (m != std::string::npos) g.stops_floor = m + n;
}
floor = g.stops_floor;
}
if (maxstop && floor != std::string::npos && g.stop_cut == std::string::npos &&
!g.text.empty()) {
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
if (start < floor) start = floor;
for (const auto& s : r.stop) {
if (s.empty()) continue;
size_t at = g.text.find(s, start);
+21 -2
View File
@@ -1606,13 +1606,32 @@ std::string Detokenizer::push(int32_t token) {
all_ += p;
pending_ += p;
/* Inside the reasoning block no stop string applies (defer_stops_until). The closer is
* searched for incrementally in all_, from (closer length - 1) bytes behind the previous end.
* Once it has been generated, matching starts in the text AFTER it: the closer may still be in
* pending_, and nothing before its end may count. */
size_t from = 0;
if (!armed_) {
const size_t n = arm_after_.size();
const size_t start = arm_scanned_ >= n ? arm_scanned_ - n + 1 : 0;
const size_t m = all_.find(arm_after_, start);
arm_scanned_ = all_.size();
if (m == std::string::npos) {
from = std::string::npos;
} else {
armed_ = true;
const size_t pending_at = all_.size() - pending_.size();
from = m + n > pending_at ? m + n - pending_at : 0;
}
}
/* A complete stop string inside pending_ ends the stream. Everything before it is emitted;
* the stop string and anything after it never is. */
if (!stops_.empty()) {
if (!stops_.empty() && from != std::string::npos) {
size_t best = std::string::npos;
const std::string* which = nullptr;
for (const std::string& s : stops_) {
const size_t m = pending_.find(s);
const size_t m = pending_.find(s, from);
if (m != std::string::npos && m < best) { best = m; which = &s; }
}
if (which) {
+16
View File
@@ -247,6 +247,19 @@ public:
bool stopped() const { return stopped_; }
const std::string& stop_hit() const { return stop_hit_; }
/* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
* reasoning block is matched against its stop strings only after `marker` -- the block's
* closer -- has been generated, and only in the text after it. Otherwise a stop string the
* model happens to write while thinking ends the request with the reasoning cut short and no
* answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
* restates the question. "" = match from the first token, the behaviour of every request that
* does not start in a block. */
void defer_stops_until(std::string marker) {
arm_after_ = std::move(marker);
armed_ = arm_after_.empty();
arm_scanned_ = 0;
}
/* Everything pushed so far, stop string included. The scheduler wants this to decide whether
* a request finished on a stop or on a length limit. */
const std::string& text() const { return all_; }
@@ -264,6 +277,9 @@ private:
std::string stop_hit_;
size_t max_stop_ = 0;
bool first_ = true;
std::string arm_after_; /* see defer_stops_until */
bool armed_ = true;
size_t arm_scanned_ = 0; /* how far into all_ the search for arm_after_ has reached */
Tokenizer tok_; /* over v_, set up by the first push */
bool tok_ready_ = false;
+12
View File
@@ -0,0 +1,12 @@
# Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk (4-bit weights, E4M3 activations) and its DFlash2
# block-diffusion drafter merged into the container; the speculation depth is the drafter's own
# operating point.
name: radiance-qwen3.8-27b-mxfp4
services:
radiance:
extends: { file: common.yaml, service: radiance }
container_name: radiance-qwen3.8-27b-mxfp4
command: >
--model /models/qwen3.8-27b-mxfp4.rad
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8
+1
View File
@@ -123,6 +123,7 @@ the cards the engine runs on.
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
| `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
+32 -9
View File
@@ -208,7 +208,7 @@ Three ship with the tree:
| library | |
|---|---|
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, P2P all-reduce, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
| `libref` | every op naively and generically. The last-resort fallback **and** the correctness oracle `rad-kbench` measures against |
| `libavx` | the host library: the same vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, the n-gram embedding's gather among them. Built on x86-64 |
@@ -697,6 +697,15 @@ error that says so rather than being quietly ignored.
When you measure speculation, **measure step time, not tokens per second.**
A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
cache, so a prefix hit leaves it with nothing to attend to for the cached part of the prompt, and
it cannot draft until its window has slid past the hit. On the follow-up turn of a chat that is
most of the reply. Such a hit is therefore ended one drafter window before the end of the prompt,
at a checkpoint: the window is recomputed, which costs that much prefill, and the drafter drafts
from the first token. The reply is the same either way. A hit whose nearest checkpoint below that
point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
### 4.7 Two cards
```sh
@@ -729,13 +738,25 @@ the decode and verify steps — up to `--max-num-seqs` × (1 + `--num-speculativ
prefill chunk, and a message that goes out on the tiered-int8 wire, runs the unfused chain, where
the all-reduce's own size choice between one-shot and two-shot applies.
**The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce
kernels push into the other card's memory. At launch radiance asks the driver, for every pair of
the cards it will use, whether that works, and logs the answer. When some pair cannot, those
kernels are not selected, and startup stops naming `device.p2p` instead of the first all-reduce
faulting or hanging. Whether P2P works is decided by the platform: the IOMMU setting, the PCIe
topology, and whether the cards sit behind a switch that allows peer traffic. The startup line
names the pairs that failed.
**Cards that cannot reach each other's memory still serve.** The all-reduce kernels normally push
into the other card's memory directly (peer to peer, P2P). At launch radiance asks the driver,
for every pair of the cards it will use, whether that works, and logs the answer. Whether it does
is decided by the platform: the IOMMU setting, the PCIe topology, and whether the cards sit behind
a switch that allows peer traffic. When some pair cannot, the same kernels run with their
exchange buffers in pinned host memory instead: every card writes its share to host RAM over its
own link and reads the others' back the same way, and no card touches another card's VRAM. The
startup line names the pairs that failed, and the selection report names the `_host` rows that
took the collectives. The results are the same bytes either way; the cost is a message crossing
two links instead of one. On two R9700s on PCIe 4.0 that cost is within run-to-run noise for
decode, at one stream and at four, and 2–10% on a 23.6K-token prefill, because there the peer
link is no faster than the host link. A machine whose cards reach host memory over a narrower
link than they reach each other pays more.
`--p2p` overrides the driver's answer. `off` takes the host-memory path even where the driver
reports peer access, for a board where peer traffic is broken or slow while the driver still says
it works. `on` takes the peer-to-peer kernels and stops at startup, naming the pairs, if the driver
refuses any of them, so a deployment measured on P2P never quietly serves on host memory. `auto`,
the default, trusts the driver.
### 4.8 Finished conversations: copied to host, VRAM given up on demand
@@ -925,6 +946,7 @@ one line naming each one the command line moved.
| `--tp N` | 1 | tensor-parallel ranks |
| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
| `--tp-wire-min-kb N` | 128 | smallest all-reduce the lossy wire is used for |
| `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
**Speculation**
@@ -1399,6 +1421,7 @@ under the request's own spelling of each. `server.default_max_tokens` is `null`
| `decode_tokens_per_second`, `prefill_tokens_per_second` | |
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position, since start |
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
| `decode_rows_unspeculated_total` | rows that never drafted at all |
| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
@@ -1487,7 +1510,7 @@ released until it does.
| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` |
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` |
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, and every multi-rank kernel requires it. Report the kernel version, the IOMMU mode and the refusal line |
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
+3 -1
View File
@@ -103,7 +103,9 @@ op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says
another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
such a kernel is not selected. The next row that does not need it takes the op. With no such row,
startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
measured at launch`). Every collective in libr4d carries it. A machine fact is in no geometry, so
measured at launch`). Every collective in libr4d carries it, and each has a `_host` twin that
requires `device.p2p == 0` and exchanges through pinned host memory, so exactly one of the pair
matches any machine. A machine fact is in no geometry, so
it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
kernel is not selected there either.
+2
View File
@@ -108,6 +108,8 @@ set(R4D_UNITS
"r4d_gemm_w4a8_tiled|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
"r4d_gemm_w4a8_prefill|-DR4D_GEMM_W4A8_GROUP=${RAD_W4_GROUP}"
"r4d_gemm_mxfp4a8_nt_m64|"
"r4d_gemm_mxfp4a8_tiled|"
"r4d_gemm_mxfp4a8_decode|"
# Block-scaled FP8 -- the format Qwen3.8-27B-FP8 ships in.
# No -D: the 128x128 block is a property of the checkpoint on disk and not a quantiser choice
# like RAD_W4_GROUP, so it is a constant in the source and the entry points reject a mismatch.
+2
View File
@@ -52,6 +52,8 @@ target architecture. They are reported by the `r4d_*_dims()` accessors in
| `gemm_w8a16_nt_m64` | 8-bit weight, f16 activation, skinny |
| `gemm_w2a8_nt` | 2-bit weight against int8 activation — the fast draft head |
| `gemm_mxfp4a8_nt_m64` | OCP-MXFP4 weight, fp8 activation, skinny |
| `gemm_mxfp4a8_decode` | the same operands for the decode band (M ≤ 128): split-K across workgroups with a last-arriver reduction, the partial in the op's scratch |
| `gemm_mxfp4a8_tiled` | the prefill sibling: the activation re-tiled into fragment order in the op's scratch and read straight into registers, the weight unpacked once per K slab for a 256-row block |
| `attn_decode_h128_gqa4_fp8kv` / `..._bf16kv` | head_dim 128, 4 queries per KV head, sliding window — a block-diffusion drafter's geometry. Decode only; `attn_h128_gqa4_have_prefill()` reports 0 so a caller routes long queries to its own fallback |
| `rowtopk_bf16` / `rowtopk_bf16_chunks` | exact per-row top-K over a bf16 matrix, two-stage |
| `dflash_conv_t2_g16_bf16` | the drafter's causal conv, two taps, 16 groups |
+21 -1
View File
@@ -262,6 +262,11 @@ int r4d_p2p_copy2d(long dst, long src, long dpitch, long spitch, long width, lon
void r4d_ar_ipc_free(long p);
void r4d_ar_ipc_memzero(long p, long size);
void r4d_ar_ipc_enable_peer(long peer);
// Exchange buffers in pinned, fine-grained HOST memory, for cards that cannot reach each other's
// VRAM: every card reads and writes the same host pages over its own link. Zeroed, and the
// returned address is valid on every card and on the CPU alike. Startup-only.
long r4d_ar_host_alloc(long size);
void r4d_ar_host_free(long p);
// Exact sum, fp32 accumulate, bf16 / fp16 / fp32 payload (dtype 0 / 1 / 2).
void r4d_ar_oneshot_2rank_exact(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16, long inp, long out, long n_elem,
@@ -547,10 +552,25 @@ void r4d_gemm_w8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, i
// OCP-MXFP4 weight, fp8 activation. e2m1 elements with one E8M0 exponent per 32 K, folded
// against a per-row reference exponent so the inner loop has no rescale; fp8 WMMA.
// as_group 0 = one f32 activation scale per row, 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW, long stream);
int M, int K, int N, int WV, int SK, int MB, int NPW,
int as_group, int as_rs, long stream);
int r4d_gemm_mxfp4a8_nt_m64_max_m(void);
int r4d_gemm_mxfp4a8_nt_m64_group(void);
// The same weight tiled for PREFILL: a 256-row block reads A fragments straight from a
// FRAGMENT-ORDERED copy of the activation (`at`, written by r4d_mxfp4a8_tile_a, at least
// r4d_mxfp4a8_tile_a_bytes long) and unpacks the weight once per K slab. TN (2 or 4, 0 = by M) is
// the per-wave column width in 16-column fragments. as_group 0 = one f32 activation scale per row,
// 128 = one per (row, 128 of K) at row stride as_rs.
void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs, long stream);
void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream);
long r4d_mxfp4a8_tile_a_bytes(int M, int K);
int r4d_gemm_mxfp4a8_tiled_group(void);
// The DECODE band (M <= 128) is r4d_rad_gemm_mxfp4a8_decode alone: its split-K partial is the op's
// scratch, which only the plugin ABI hands over.
int r4d_gemm_mxfp4a8_decode_max_m(void);
// ---- BLOCK-SCALED FP8: the format a checkpoint ships in ----------------------------------------
//
+69 -21
View File
@@ -120,6 +120,9 @@ struct ArInst {
* that buys nothing but round trips: at a 2048-token prefill chunk the capacity rule asks for
* 936 blocks and the tuning rule asks for 24. */
int nb_cap = 0;
/* Where the exchange buffers live: 0 in each rank's own VRAM, written by its peers over P2P;
* 1 in pinned host memory that every card reaches over its own link (build, below). */
int host = 0;
};
/* A parameter that may have been declared as a RANGE: init is handed the frozen geometry for one
@@ -150,13 +153,14 @@ long align16(long v) { return (v + 15) & ~15L; }
* residual that is 40 MiB a slot and 80 MiB for the pair. ONE set serves every op that resolved
* to the same (rank, world, dtype, bound) -- see the cache below, which is what keeps a 64-layer
* model from building 128 of these. */
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code) {
int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code, int host) {
if (world < 2 || world > R4D_MAX_RANKS) return RAD_E_SHAPE;
if (rank < 0 || rank >= world) return RAD_E_INVAL;
if (max_numel <= 0) return RAD_E_INVAL;
in->rank = rank;
in->world = world;
in->host = host;
in->dtype = dtype_code;
in->esize = r4d_ar_esize(dtype_code);
in->max_numel = (long)max_numel;
@@ -196,12 +200,26 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
* invalidates. libr4d's driver falls back to coarse when fine fails; so does this, because a
* deterministic fallback stays symmetric across ranks (same environment, same hardware). */
int fine_sc = 1, fine_fl = 1, fine_sq = 1;
/* WITHOUT PEER ACCESS THE MAILBOX MOVES TO THE HOST, AND NOTHING ELSE CHANGES. Every kernel in
* the family touches another rank only through its scratch slots and its flag words -- its
* input, its output and its sequence counters are its own card's -- so with those two in
* pinned host memory no card ever addresses another card's VRAM, and the same kernels run on a
* machine whose PCIe topology or IOMMU forbids peer traffic. A push then lands in host memory
* over the writer's link and the reduce reads it back over the reader's, so a message crosses
* two links where P2P crosses one; that is the price, and it is paid only where P2P is absent
* (the rows that take this path require device.p2p == 0, r4d_rows.cpp). The sequence counters
* stay in VRAM: only their own rank reads them. */
R4D_TRY("ar_ipc_alloc",
if (hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
if (host) {
sc = r4d_ar_host_alloc((long)nslots * in->slot_bytes);
fl = r4d_ar_host_alloc(flag_words * 4);
} else {
sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 1, handle, &hlen);
if (!sc) { fine_sc = 0; sc = r4d_ar_ipc_alloc((long)nslots * in->slot_bytes, 0, handle, &hlen); }
fl = r4d_ar_ipc_alloc(flag_words * 4, 1, handle, &hlen);
if (!fl) { fine_fl = 0; fl = r4d_ar_ipc_alloc(flag_words * 4, 0, handle, &hlen); }
}
sq = r4d_ar_ipc_alloc(2L * maxb * 4, 1, handle, &hlen);
if (!sq) { fine_sq = 0; sq = r4d_ar_ipc_alloc(2L * maxb * 4, 0, handle, &hlen); });
if (!sc || !fl || !sq) return RAD_E_NOMEM;
@@ -258,7 +276,7 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
in->peer_scratch[j] = g_rv.scratch[r];
in->peer_flags[j] = g_rv.flags[r];
++j;
R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
if (!host) R4D_TRY("ar_ipc_enable_peer", r4d_ar_ipc_enable_peer((long)g_rv.dev[r]));
}
/* Second barrier: no rank may launch until every rank has enabled peer access, or the first
@@ -295,8 +313,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code)
struct CacheKey {
int rank, world, dtype;
long long numel;
int host;
bool operator==(const CacheKey& o) const {
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel;
return rank == o.rank && world == o.world && dtype == o.dtype && numel == o.numel &&
host == o.host;
}
};
@@ -320,7 +340,7 @@ int acquire(const CacheKey& k, ArInst** out) {
* and a rank-keyed entry means no two builders race for the same key. */
ArInst* in = new (std::nothrow) ArInst();
if (!in) return RAD_E_NOMEM;
int rc = build(in, k.rank, k.world, k.numel, k.dtype);
int rc = build(in, k.rank, k.world, k.numel, k.dtype, k.host);
if (rc != RAD_OK) { delete in; return rc; }
{
std::lock_guard<std::mutex> lk(g_cache_mu);
@@ -343,8 +363,13 @@ void release(ArInst* in) {
}
/* Only this rank's own allocations. A peer pointer is the peer's to free, and freeing it here
* would be a double free the moment two ranks tear down in either order. */
r4d_ar_ipc_free(in->my_scratch);
r4d_ar_ipc_free(in->my_flags);
if (in->host) {
r4d_ar_host_free(in->my_scratch);
r4d_ar_host_free(in->my_flags);
} else {
r4d_ar_ipc_free(in->my_scratch);
r4d_ar_ipc_free(in->my_flags);
}
r4d_ar_ipc_free(in->my_seq);
r4d_ar_ipc_free(in->locpack);
delete in;
@@ -354,8 +379,7 @@ void release(ArInst* in) {
/* ------------------------------------------------------------------ init / fini */
extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -373,28 +397,35 @@ extern "C" int r4d_rad_ar_init(const RadParam* p, int n_p, int rank, int world,
if (numel <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, dt, numel }, &in);
int rc = acquire(CacheKey{ rank, world, dt, numel, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
}
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);
}
extern "C" int r4d_rad_ar_host_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_init(p, n_p, rank, world, 1, out);
}
/* The fused all-reduce + norm declares `M`(range) and `n` rather than `numel`: its message is the
* post-projection activation. Same world, same buffers, different arithmetic to get the bound. */
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, void** out) {
static int ar_mn_acquire(const RadParam* p, int n_p, int rank, int world, int host,
void** out) {
const long long M = pgeti_hi(p, n_p, "M", 0);
const long long K = pgeti_hi(p, n_p, "n", 0);
if (M <= 0 || K <= 0) return RAD_E_INVAL;
ArInst* in = nullptr;
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K }, &in);
int rc = acquire(CacheKey{ rank, world, 0 /* bf16 */, M * K, host }, &in);
if (rc != RAD_OK) return rc;
*out = in;
return RAD_OK;
}
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_ln_init(const RadParam* p, int n_p, int rank, int world, int host, void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -402,7 +433,15 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
if (ws_param != world) return RAD_E_SHAPE;
if (world != 2) return RAD_E_SHAPE; /* the handshake is one peer flag per block */
return ar_mn_acquire(p, n_p, rank, world, out);
return ar_mn_acquire(p, n_p, rank, world, host, out);
}
extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int world, void** out) {
return ar_ln_init(p, n_p, rank, world, 0, out);
}
extern "C" int r4d_rad_ar_ln_host_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_ln_init(p, n_p, rank, world, 1, out);
}
/* The four-rank ar_hc_write and ar_gather_hc_write. The key is the family's -- {rank, 4, bf16,
@@ -413,8 +452,8 @@ extern "C" int r4d_rad_ar_ln_init(const RadParam* p, int n_p, int rank, int worl
* (r4d_ar_wide.h), so ops sharing an instance interleave in any order every rank issues them in,
* and ops on separate instances touch nothing of each other's. Exact wire only: the rows constrain
* `wire` to 0, and a `wire` 6 that reaches this init anyway is refused. */
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
static int ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world, int host,
void** out) {
if (!out) return RAD_E_INVAL;
*out = nullptr;
@@ -423,7 +462,16 @@ extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int
if (world != 4) return RAD_E_SHAPE; /* the peer bundle is compiled for four */
if (pgeti_hi(p, n_p, "wire", 0) != 0) return RAD_E_UNSUPPORTED;
return ar_mn_acquire(p, n_p, rank, world, out);
return ar_mn_acquire(p, n_p, rank, world, host, out);
}
extern "C" int r4d_rad_ar_hc_wide_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_hc_wide_init(p, n_p, rank, world, 0, out);
}
extern "C" int r4d_rad_ar_hc_wide_host_init(const RadParam* p, int n_p, int rank, int world,
void** out) {
return ar_hc_wide_init(p, n_p, rank, world, 1, out);
}
extern "C" void r4d_rad_ar_fini(void* instance) {
+23
View File
@@ -489,6 +489,29 @@ int r4d_ar_gather_inv(long inv, long sorted, long T, long stream_i) {
void r4d_ar_ipc_free(long p) { if (p) (void)hipFree((void*)p); }
void r4d_ar_ipc_memzero(long p, long size) { if (p) HIPOK(hipMemset((void*)p, 0, size)); }
// THE HOST MAILBOX. Coherent so a peer's stores are not held in a CPU cache line this card reads
// around, mapped so the cards address it, portable so every card does and not only the one
// current at allocation. A card reaches it through the same fine-grained path a peer's VRAM
// scratch is reached by, so the kernels' fences mean what they mean there. The address a card
// uses must be the CPU's own, because one pointer is published to every rank: a mapping that put
// the pages elsewhere on some card would have each rank write where no other rank reads.
long r4d_ar_host_alloc(long size) {
void* p = nullptr;
HIPOK(hipHostMalloc(&p, size, hipHostMallocCoherent | hipHostMallocMapped |
hipHostMallocPortable));
std::memset(p, 0, (size_t)size);
void* d = nullptr;
const hipError_t e = hipHostGetDevicePointer(&d, p, 0);
if (e != hipSuccess || d != p) {
(void)hipHostFree(p);
throw std::runtime_error(e != hipSuccess
? std::string("host mailbox: no card address: ") + hipGetErrorString(e)
: std::string("host mailbox: the card address differs from the CPU address"));
}
return (long)p;
}
void r4d_ar_host_free(long p) { if (p) (void)hipHostFree((void*)p); }
// Enable direct peer access. radiance runs one process with a thread per rank sharing an address
// space, so a peer pointer is valid here once this has run and no IPC handle exchange is needed;
// see the header of r4d_ar_entry.hip.
+12
View File
@@ -334,6 +334,16 @@ struct R4dGemmCfg { int wv, sk, mb, npw, nt; };
* not compute the GEMM and then pick it. */
struct R4dTileCfg { int variant; int bm; int bn; };
/* The MXFP4 tiled GEMM's column width in 32-column units per wave: TN=2 gives a 256 x 64 block,
* TN=4 a 256 x 128 one. Its crossover is a function of M (r4d_gemm_mxfp4a8_tiled.hip carries the
* measurement), so 0 -- the default -- decides at issue and a fixed value is for a tuner. */
struct R4dMxTileCfg { int tn; };
/* The MXFP4 decode GEMM's split-K width, K slab and weight-load hint. 0 on each is the rule in
* r4d_gemm_mxfp4a8_decode.hip (it needs M and the shape, which exist only at issue); `nt` 1 streams
* the weight past L2/MALL, 2 loads it plainly. */
struct R4dMxDecCfg { int ks; int bk; int nt; };
/* Split-KV segment count for the paged decode kernels. 0 is libr4d's own split law, which is
* measured (r4d_attn_paged_h256_gqa6.hip carries the table) and reads num_seqs and max_ctx that
* only exist at issue -- so it stays the default and the fixed counts are there for a tuner that
@@ -375,6 +385,8 @@ extern "C" {
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*);
void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*);
void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*);
void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*);
void r4d_cfg_topk (const RadArgs*, struct R4dTopkCfg*);
+24
View File
@@ -321,6 +321,30 @@ struct GemmOps {
long long M, N, K;
};
/* THE MXFP4 GEMMS' ACTIVATION SCALE GRID, read off the operand rather than assumed. One f32 a row
* (`[M]` or `[M][1]`: a per-token quantiser) is group 0; one per (row, 128 of K) (`[M][ceil(K/128)]`:
* the block-scaled fp8 family's quantisers, which every fused producer in arch/common writes) is
* group 128, read at the operand's own row stride. Anything else is refused by shape: a grid read
* at the wrong width is an answer that is merely wrong. */
static inline int mx_ascale_grid(const GemmOps& g, int* group, int* rs) {
const RadTensor* s = g.ascale;
if (!s || g.M <= 0) return R4D_NO(RAD_E_INVAL);
long long cols = 1, rstride = 1;
if (s->rank >= 2) {
cols = s->shape[s->rank - 1];
rstride = s->stride[s->rank - 2];
if (s->shape[s->rank - 2] < g.M) return R4D_NO(RAD_E_SHAPE);
} else if (s->rank == 1) {
if (s->shape[0] < g.M) return R4D_NO(RAD_E_SHAPE);
cols = s->shape[0] / g.M;
rstride = cols;
}
const long long kb = (g.K + 127) / 128;
if (cols == 1 && (s->rank < 2 || rstride == 1)) { *group = 0; *rs = 1; return RAD_OK; }
if (cols == kb && rstride >= kb) { *group = 128; *rs = (int)rstride; return RAD_OK; }
return R4D_NO(RAD_E_SHAPE);
}
/* Common shape and layout checks. A is [M,K] row-major, C is [M,N] row-major and the weight is
* an opaque packed blob whose element count the layout hook owns -- so the weight's SHAPE is not
* checked here beyond being present, which is deliberate: the byte count that matters is the one
+617
View File
@@ -0,0 +1,617 @@
// r4d_gemm_mxfp4a8_decode.hip - r4d_gemm_mxfp4a8_decode: the OCP-MXFP4 x fp8 GEMM for the DECODE
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T over the same operands, weight
// layout and fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_tiled.
//
// WHY A THIRD MXFP4 KERNEL. At decode the GEMM is a weight stream: a speculative verify step is
// a handful of rows against the whole 4-bit trunk, and the only number that matters is how close
// the stream runs to the card's DRAM bandwidth. The skinny kernel splits K inside one workgroup
// and reads the weight straight into registers, which leaves the narrow projections well short of
// it. This one splits K ACROSS workgroups with a fused last-arriver reduction, unpacks the weight
// through LDS, gives each block one 16-row A fragment per M tile, and streams the weight with
// non-temporal loads.
//
// THE TILE. A block is DWN = 8 waves over BND = 128 output columns, one 16-column fragment a wave,
// and DTM 16-row M fragments -- the SMALLEST that covers M, because a wider tile computes rows
// nobody asked for. A K slab of DBK bytes is staged: A (16*DTM rows) and the weight's 128 rows,
// unpacked to e4m3 with the block exponent folded in through r4d_mxfp4.h, as the other two MXFP4
// kernels fold it.
//
// SPLIT-K IS NOT OPTIONAL. With one 16-row M fragment the independent N fragments number N/16, so
// N=5120 is 320 waves -- 2.5 a SIMD however the N tile is chosen. DKS blocks split the K slabs;
// each writes an fp32 partial [DKS][M][N] and the LAST to arrive (an agent-scope counter per column
// block) sums them in place, so there is no second launch.
//
// THE SPLIT, SLAB AND LOAD HINT are a rule measured cell by cell on this kernel -- every split x
// slab x hint against the 27B's per-rank shapes at M = 8..128, DRAM-fed -- because no single
// fill target fits: the split is the smallest power of two whose grid reaches 48 blocks at M <= 16,
// 56 at M <= 96 and 40 above (an unsplit 40-block grid already streams a short-K weight at the
// card's rate there, and a split's partial traffic grows with M); a deep K (8192 or more, down at
// K=8704) keeps doubling while a split still has 24 or more 128-wide slabs, since 40-odd blocks
// do not keep its long slab loop fed; and no split goes past ks*M = 512, where the partials
// outweigh what the split buys. The slab is 128 except where LDS per block, (16*DTM + 128) *
// (DBK+8) bytes, would cost a wide or deeply split grid its resident blocks (see mxd_plan); a K
// that is not a multiple of 128 takes 64 (and a 2-way split widens to 4). Weight loads are non-temporal for weights of 4 MiB or more,
// plain below, where the weight is too small to evict anything the split partials need. All three
// are tunables (`ks`, `bk`, `nt`) whose 0 is this rule.
//
// NO STATE IS KEYED ON THE STREAM. The split partial is the op's own scratch -- the core sizes it
// from the scratch hook and treats it as read+write, so two ops that could overlap get disjoint
// slices -- and the arrival counters are a small block keyed on the OUTPUT buffer (mxd_out_ctr),
// zero at entry and left zero by the reducer. A recorded pass is replayed with its recorded
// arguments, possibly on another stream than it was recorded on, so a pointer that depended on the
// stream would make the replay differ from its recording. Two launches writing the same output are
// ordered by that dependency; two that can overlap write different outputs. The row is therefore
// concurrent (rad_kernel_concurrent), as gemm_fp8a8_nt_m16 is. A scratch shorter than the split
// needs is refused: the hook sizes it for every M of the band, so a short one is a caller's error.
//
// Every thread fences its partial stores before the counter: a fence on thread 0 alone orders
// only thread 0's stores, and the reducer would then read whatever happened to drain.
//
// TWO ACTIVATION SCALE GRIDS, as in the tiled kernel: one f32 a row, or one a (row, 128 of K). The
// per-block form carries each row's accumulator in the current block's scale and rescales it by
// s_prev / s_next at each 128 boundary, the ratio computed once a row into LDS from scales loaded a
// boundary early; with the accumulator transposed a lane reads one ratio for each of its rows. A split's partial is brought back
// to absolute units before it is written, because the splits end in different blocks.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <map>
#include <mutex>
#include <stdexcept>
#define R4D_MXD_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
#define R4D_MXD_MTILE 16
#define R4D_MXD_MAX_TM 8 // M <= 128
#define R4D_MXD_PAD 8
#define R4D_MXD_MAX_KS 16
#define R4D_MXD_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
typedef int mxd_v2i __attribute__((ext_vector_type(2)));
typedef unsigned mxd_u2 __attribute__((ext_vector_type(2)));
typedef unsigned mxd_u4 __attribute__((ext_vector_type(4)));
typedef float mxd_f4 __attribute__((ext_vector_type(4)));
template <bool NT, typename T>
static __device__ __forceinline__ T mxd_ld(const T* p) {
if constexpr (NT) return __builtin_nontemporal_load(p);
else return *p;
}
// ---- what both kernels share: the scale grid at a 128 boundary, and the epilogue.
//
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
// activation fragment as its B operand -- the two fragments have the same register layout, so
// this is only an argument order -- and computes C^T: a lane's accumulator for M fragment i holds
// ONE row, m = 16i + col, and the eight consecutive columns n0 + 16*wave + kb8 + e. So a row's
// activation scale is one value a lane, not eight: the (row, 128) grid's boundary rescale reads
// DTM scales instead of 8*DTM, and the epilogue writes each lane's eight outputs as one 16-byte
// store (one 32-byte store of partials) instead of eight 2-byte ones.
// THE (ROW, 128) SCALE GRID, computed once a row: thread t < ROWS owns row t. It loads the next
// 128 boundary's two scales -- the block that starts there and the one before it -- a boundary
// early, writes the row's ratio s_prev / s_next to LDS at the boundary (published by the staging
// barrier), and a lane then reads ONE ratio for each of its rows. A zero block keeps the carried
// scale; a zero block before this one sends the carried scale back to the grid, which only an
// all-zero activation block ever does.
static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row,
int kb) {
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
}
template <int DTM>
static __device__ __forceinline__ void mxd_rescale(v8f (&acc)[DTM], const float* sR, int col) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const float r = sR[i * 16 + col];
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
}
}
// The split's result: written straight to C when the accumulator holds the whole K range, else as
// an fp32 partial that the last block to arrive on this column block sums. `kb_end` is the block
// the split's last slab ends in (ABLK: the scale the accumulators are carried in).
template <int DTM, int DKS, bool ABLK>
static __device__ __forceinline__ void mxd_epilogue(
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int N, int n0, int wave, int col, int kb8, int ks,
int kb_end, unsigned* s_last, float* sR) {
constexpr int NTHR = R4D_MXD_DWN * 32, BND = R4D_MXD_DWN * 16;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
const int tid = threadIdx.x;
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
// Each row's final scale, once a row: the scale the split's accumulators end in (ABLK), or the
// row's own. The K loop's closing barrier retired the last ratio reads.
if (tid < ROWS) {
const int m = tid < M ? tid : M - 1;
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
}
__syncthreads();
float sc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
if constexpr (DKS == 1) {
if (nb < N) {
const mxd_u2 rb = *(const mxd_u2*)(Wref + nb);
float rf[8];
#pragma unroll
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
union { __hip_bfloat16 h[8]; mxd_u4 v; } o;
#pragma unroll
for (int e = 0; e < 8; ++e)
o.h[e] = (__hip_bfloat16)(ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i]);
*(mxd_u4*)(C + (size_t)m * N + nb) = o.v;
}
}
}
return;
}
if (nb < N) {
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const int m = i * 16 + col;
if (m < M) {
mxd_f4 lo, hi;
#pragma unroll
for (int e = 0; e < 4; ++e) {
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
}
mxd_f4* dst = (mxd_f4*)(P + ((size_t)ks * M + m) * N + nb);
dst[0] = lo;
dst[1] = hi;
}
}
}
// EVERY thread's partial stores are ordered before the counter, then the last arriver reduces.
__threadfence();
__syncthreads();
if (tid == 0)
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (*s_last != (unsigned)(DKS - 1)) return;
if (tid == 0) cnt[blockIdx.x] = 0u; // left clean for the next launch on this stream
__threadfence(); // acquire, before reading the other partials
const int nhi = min(n0 + BND, N);
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
const float rf = __int_as_float((int)Wref[nn] << 23);
for (int m = 0; m < M; ++m) {
float sum = 0.f;
#pragma unroll
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
C[(size_t)m * N + nn] = (__hip_bfloat16)(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
}
}
}
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
// a split that starts mid-block meets its first boundary one slab in
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
}
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
#pragma unroll
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
const int idx = off + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
*(mxd_u4*)(&sA[r * STR + c]) = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
}
}
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3
{
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
const int kstep0 = k0 / 16;
#pragma unroll
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
const int sl = off + tid * 2;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
const int gn = n0 + r;
// gn is even and N % 16 == 0: clamping to the last even row keeps the 8 B read aligned and
// gc + 1 in bounds; the slot address is recomputed from the clamped row.
const int gc = gn < N - 2 ? gn : N - 2;
const int lanec = (lane_ & 16) | (gc & 15);
const mxd_u2 wv =
mxd_ld<NT>((const mxd_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
lanec]);
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < 2; ++q) {
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * N + gc + q]);
unsigned int lo, hi;
r4d_mxfp4_unpack8(q ? wv[1] : wv[0], d, &lo, &hi);
*(mxd_u2*)(&sW[(r + q) * STR + kloc]) = mxd_u2{lo, hi};
}
}
}
__syncthreads();
if constexpr (ABLK) {
if (bnd) mxd_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
mxd_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
// THE ONE-FRAGMENT FORM (M <= 16), which is every single-sequence verify step. The same tile, fold
// and split as above, with two changes that pay only when one M fragment leaves the block waiting
// on memory: the NEXT slab's A, codes and exponents are loaded into registers while this slab
// computes, so a block keeps its loads in flight across the WMMA phase instead of draining at every
// barrier; and a thread takes four adjacent slots, one 16 B load instead of two 8 B ones. Each
// row's reference exponent is read once, not once a slab. Bit-identical to the kernel above at
// every split: the K order, the fold and the reduction are unchanged.
template <int DBK, int DKS, bool NT, bool ABLK>
__global__ __launch_bounds__(R4D_MXD_DWN * 32) void r4d_gemm_mxfp4a8_decode1_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
__hip_bfloat16* __restrict__ C, int M, int K, int N, int as_rs) {
constexpr int DTM = 1, VEC = 4;
constexpr int DWN = R4D_MXD_DWN, BND = DWN * 16, NTHR = DWN * 32;
constexpr int ROWS = R4D_MXD_MTILE * DTM;
constexpr int STR = DBK + R4D_MXD_PAD;
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
__shared__ unsigned char sA[ROWS * STR];
__shared__ unsigned char sW[BND * STR];
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
__shared__ unsigned s_last;
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int n0 = blockIdx.x * BND;
const int ks = blockIdx.z;
const int slabs = (K + DBK - 1) / DBK;
const int spb = (slabs + DKS - 1) / DKS;
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
v8f acc[DTM];
#pragma unroll
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
float ns = 0.f, np = 0.f;
if constexpr (ABLK) {
const int kb = ((s_lo * DBK) >> 7) + 1;
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
}
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps_g = K / 16;
// per-thread slot geometry, fixed across slabs
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT];
int s_ref[W_IT][VEC];
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const int sl = it * NTHR * VEC + tid * VEC;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
const int r = ntl * 16 + (lane_ & 15);
const int gn = n0 + r;
const int gc = gn < N - VEC ? gn : N - VEC;
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
#pragma unroll
for (int q = 0; q < VEC; ++q) s_ref[it][q] = (int)Wref[gc + q];
}
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
wv_t rw[W_IT];
int rd[W_IT][VEC];
mxd_u4 ra[A_IT];
auto load = [&](int s) {
const int k0 = s * DBK;
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
const int rc = r < M - 1 ? r : M - 1;
ra[j] = *(const mxd_u4*)(A + (size_t)rc * K + k0 + c);
}
}
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
const size_t slot =
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
rw[it] = mxd_ld<NT>((const wv_t*)&Wp[slot]);
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
#pragma unroll
for (int q = 0; q < VEC; ++q) rd[it][q] = (int)Ws[(size_t)blk * N + s_gc[it] + q];
}
};
auto store = [&]() {
#pragma unroll
for (int j = 0; j < A_IT; ++j) {
const int idx = j * NTHR * 16 + tid * 16;
if (idx < ROWS * DBK) {
const int r = idx / DBK, c = idx % DBK;
*(mxd_u4*)(&sA[r * STR + c]) = ra[j];
}
}
#pragma unroll
for (int it = 0; it < W_IT; ++it) {
#pragma unroll
for (int q = 0; q < VEC; ++q) {
unsigned int lo, hi;
r4d_mxfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]), &lo, &hi);
*(mxd_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = mxd_u2{lo, hi};
}
}
};
if (s_lo < s_hi) load(s_lo);
for (int s = s_lo; s < s_hi; ++s) {
const int k0 = s * DBK;
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd && tid < ROWS) sR[tid] = mxd_ratio(ns, np, asrow, k0 >> 7);
}
store();
__syncthreads();
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
if constexpr (ABLK) {
if (bnd) mxd_rescale(acc, sR, col);
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < DBK / 16; ++step) {
const int kk = step * 16 + kb8;
mxd_v2i af[DTM], wf;
#pragma unroll
for (int i = 0; i < DTM; ++i) {
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
}
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
#pragma unroll
for (int i = 0; i < DTM; ++i)
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
}
__syncthreads();
}
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
mxd_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, n0, wave, col, kb8, ks,
kb_end, &s_last, sR);
}
namespace {
// THE ARRIVAL COUNTERS, one block an output buffer -- see the header. The counters cannot live in
// the scratch: other ops write the arena between two of ours, and the counters must be zero at
// entry. So they are a small device allocation of their own, taken once per (device, output) and
// kept zero by the reducer, as gemm_fp8a8_nt_m16 keys its split_ctr.
unsigned* mxd_out_ctr(const void* out) {
static std::mutex mu;
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
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;
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess) { (void)hipFree(p); return nullptr; }
blocks.emplace(key, p);
return p;
}
// THE SPLIT, SLAB AND LOAD HINT A LAUNCH RUNS, from M, the shape and the tunables (0 = the rule).
// One function for the launch and the scratch hook, so the partial the hook sizes is the one
// written. See the header for the rule and what it was measured on.
struct MxdPlan { int ks, bk; bool nt; };
MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
MxdPlan p;
int ks = 1;
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
p.ks = KS > 0 ? KS : ks;
// 64-wide slabs where LDS per block, (16*DTM + 128)*(DBK+8) bytes, costs a wide or deeply split
// grid its resident blocks: DTM 4 unsplit on 110+ column blocks, and DTM 8 on those or at a 4-way
// split.
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
if (K % p.bk) { // a slab may not run past K
p.bk = 64;
if (p.ks == 2) p.ks = 4;
}
return p;
}
long mxd_partial_bytes(int M, int N, int ks) {
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
}
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
long scratch_bytes) {
if (M < 1 || M > R4D_MXD_MTILE * R4D_MXD_MAX_TM)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: M must be 1..128");
if (N < 16 || N % 16 || N > R4D_MXD_MAX_N)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: N must be a multiple of 16 up to 36864");
if (K < 64 || K % 64)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: K must be a multiple of 64");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the activation scale is per row or per "
"128 of K");
const MxdPlan pl = mxd_plan(M, K, N, KS, BK, NT);
const int ks = pl.ks, bk = pl.bk;
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
if (bk != 64 && bk != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_decode: BK must be 64 or 128");
if (scratch_bytes < mxd_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the op's scratch is shorter than the split "
"partial; the scratch hook sizes it");
float* P = (float*)scratch;
unsigned* cnt = mxd_out_ctr((const void*)c);
if (!cnt) throw std::runtime_error("r4d gemm_mxfp4a8_decode: split counter alloc failed");
const bool ablk = as_group == 128, nt = pl.nt;
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
hipStream_t st = (hipStream_t)stream;
dim3 grid(nblk, 1, ks), block(R4D_MXD_DWN * 32);
auto Ap = (const unsigned char*)a;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
#define MXD_L(BK_, KS_, TM_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
st, Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
#define MXD_L1(BK_, KS_, NT_, AB_) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
Ap, Sp, Wp, Zp, Rp, P, cnt, Cp, M, K, N, as_rs)
#define MXD_AB(BK_, KS_, TM_, NT_) \
{ if (ablk) MXD_L(BK_, KS_, TM_, NT_, true); else MXD_L(BK_, KS_, TM_, NT_, false); }
#define MXD_NT(BK_, KS_, TM_) \
{ if (nt) MXD_AB(BK_, KS_, TM_, true) else MXD_AB(BK_, KS_, TM_, false) }
#define MXD_AB1(BK_, KS_, NT_) \
{ if (ablk) MXD_L1(BK_, KS_, NT_, true); else MXD_L1(BK_, KS_, NT_, false); }
#define MXD_NT1(BK_, KS_) { if (nt) MXD_AB1(BK_, KS_, true) else MXD_AB1(BK_, KS_, false) }
#define MXD_TM(BK_, KS_) \
{ switch (tm) { case 1: MXD_NT1(BK_, KS_) break; case 2: MXD_NT(BK_, KS_, 2) break; \
case 3: MXD_NT(BK_, KS_, 3) break; case 4: MXD_NT(BK_, KS_, 4) break; \
case 5: MXD_NT(BK_, KS_, 5) break; case 6: MXD_NT(BK_, KS_, 6) break; \
case 7: MXD_NT(BK_, KS_, 7) break; default: MXD_NT(BK_, KS_, 8) break; } }
#define MXD_KS(BK_) \
{ switch (ks) { case 1: MXD_TM(BK_, 1) break; case 2: MXD_TM(BK_, 2) break; \
case 4: MXD_TM(BK_, 4) break; case 8: MXD_TM(BK_, 8) break; \
default: MXD_TM(BK_, 16) break; } }
if (bk == 64) MXD_KS(64) else MXD_KS(128)
#undef MXD_KS
#undef MXD_TM
#undef MXD_NT1
#undef MXD_AB1
#undef MXD_NT
#undef MXD_AB
#undef MXD_L1
#undef MXD_L
}
} // namespace
extern "C" int r4d_gemm_mxfp4a8_decode_max_m(void) { return R4D_MXD_MTILE * R4D_MXD_MAX_TM; }
// ============================================================== the plugin ABI entry point
extern "C" int r4d_rad_gemm_mxfp4a8_decode(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
if (g.M > r4d_gemm_mxfp4a8_decode_max_m() || g.N > R4D_MXD_MAX_N) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
R4D_TRY("gemm_mxfp4a8_decode",
mxd_launch(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, t.ks, t.bk, t.nt, as_group, as_rs,
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes));
return RAD_OK;
}
/* The core sizes the op's scratch from this. `M` is the band's widest, and a narrower M can split
* wider (the fill rule asks for more blocks at M <= 24), so the size is the widest split over the
* band times its widest M -- an upper bound on every launch the band can make. */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
const long long K = r4d_geti_or(a, "K", 0);
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_mxfp4a8_decode_max_m()) return 0;
R4dMxDecCfg t;
r4d_cfg_mxfp4_decode(a, &t);
int ks = 1;
for (int m = 1; m <= (int)M; ++m) {
const int k = mxd_plan(m, (int)K, (int)N, t.ks, t.bk, t.nt).ks;
if (k > ks) ks = k;
}
return (int64_t)mxd_partial_bytes((int)M, (int)N, ks);
}
+69 -40
View File
@@ -68,6 +68,14 @@
// The E8M0 scales are left in [K/32][N] order -- a half-wave reads sixteen consecutive bytes of
// those already.
//
// TWO ACTIVATION SCALE GRIDS, as in r4d_gemm_mxfp4a8_tiled.hip: one f32 per row (ABLK=false), or
// one per (row, 128 of K) (ABLK=true, the block-scaled fp8 family's grid). With ABLK each wave
// carries its partial sums in units of the current 128-block's scale and rescales them by
// s_prev / s_next at each block boundary inside its split-K segment. The segments end in
// DIFFERENT blocks, so each partial is brought back to absolute units -- multiplied by its own
// last scale -- before the LDS reduction adds them, and the epilogue applies only the weight's
// reference factor.
//
// TRAP FOR ANYONE MEASURING THIS KERNEL: a weight of tens of megabytes streamed in a loop is
// Infinity-Cache resident on this part, so a bandwidth figure taken that way can read above the
// DRAM roofline. It ranks kernels reading the same bytes; it is not achieved DRAM bandwidth.
@@ -78,56 +86,36 @@
// the last valid row and the store discards it -- which keeps the inner loop branch-free.
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
#define R4D_GEMM_MXFP4_MAX_M 64
#define R4D_GEMM_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
#define R4D_GEMM_MXFP4_GROUP R4D_MXFP4_GROUP
#define WAVE32 32
typedef int v2i __attribute__((ext_vector_type(2)));
typedef unsigned uint2v __attribute__((ext_vector_type(2)));
// Folded magnitudes: kMag[d] is the eight e2m1 magnitudes scaled by 2^-d, as packed e4m3 bytes,
// low table then high table, indexed by the 3-bit magnitude through v_perm_b32.
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and
// a rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the
// same exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter
// little (such an element is 2.9e-3 of its row's reference) but the table is generated, not
// hand-rounded, so it should agree with the hardware's own conversion.
__device__ __constant__ unsigned int kMag[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
};
// Eight e2m1 codes (four packed bytes) -> eight e4m3 bytes in k order, with the block's exponent
// difference already folded in.
__device__ __forceinline__ v2i r4d_mxfp4_unpack8(unsigned int wv, int dsh) {
const unsigned int t0 = kMag[dsh][0], t1 = kMag[dsh][1];
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
// Eight e2m1 codes (four packed bytes) -> the B fragment, eight e4m3 bytes in k order with the
// block's exponent difference folded in (r4d_mxfp4.h, shared with the other two MXFP4 kernels).
__device__ __forceinline__ v2i r4d_mxfp4_frag8(unsigned int wv, int d) {
unsigned int lo, hi;
r4d_mxfp4_unpack8(wv, d, &lo, &hi);
v2i out;
out[0] = (int)__builtin_amdgcn_perm(bo, be, 0x05010400u); // elements 0..3
out[1] = (int)__builtin_amdgcn_perm(bo, be, 0x07030602u); // elements 4..7
out[0] = (int)lo;
out[1] = (int)hi;
return out;
}
template <int MT, int NPW>
template <int MT, int NPW, bool ABLK>
__global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
const unsigned char* __restrict__ A, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int WV, int SK) {
int M, int K, int N, int WV, int SK, int as_rs) {
extern __shared__ float red[];
const int tid = threadIdx.x, wave = tid / WAVE32, lane = tid % WAVE32;
const int col_local = wave / SK, ksplit = wave % SK;
@@ -161,8 +149,39 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
const int ksteps = K / 16;
// ABLK: the scale each accumulator row of this lane is carried in -- row (mt0+i)*16 + mhalf + e.
float scur[ABLK ? MT : 1][8];
if constexpr (ABLK) {
#pragma unroll
for (int i = 0; i < MT; i++)
#pragma unroll
for (int e = 0; e < 8; e++) {
int r = (mt0 + i) * 16 + mhalf + e;
r = r < M - 1 ? r : M - 1;
const float s = As[(size_t)r * as_rs + (kbase >> 7)];
scur[i][e] = s > 0.f ? s : 1.f;
}
}
for (int k = 0; k < Ks; k += 16) {
const int kg = kbase + k; // fragment base, both lane halves
if constexpr (ABLK) {
if (k && (kg & 127) == 0) { // a new 128-wide activation block
#pragma unroll
for (int i = 0; i < MT; i++)
#pragma unroll
for (int e = 0; e < 8; e++) {
int r = (mt0 + i) * 16 + mhalf + e;
r = r < M - 1 ? r : M - 1;
float s = As[(size_t)r * as_rs + (kg >> 7)];
s = s > 0.f ? s : scur[i][e];
const float q = scur[i][e] / s;
scur[i][e] = s;
#pragma unroll
for (int j = 0; j < NPW; j++) acc[j][i][e] *= q;
}
}
}
const int kstep = kg / 16;
const int blk = kg / R4D_GEMM_MXFP4_GROUP; // one E8M0 block covers this whole step
v2i af[MT];
@@ -181,9 +200,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
// wave reads 128 contiguous bytes. In checkpoint order these would be sixteen rows K/2 bytes
// apart -- a fully strided read on the operand that dominates traffic.
const unsigned int wv = Wp[((size_t)wtile[j] * ksteps + kstep) * WAVE32 + lane];
int dsh = (int)wref[j] - (int)Ws[(size_t)blk * N + n];
dsh = dsh < 0 ? 0 : (dsh > 15 ? 15 : dsh);
const v2i wf = r4d_mxfp4_unpack8(wv, dsh);
const v2i wf = r4d_mxfp4_frag8(wv, r4d_mxfp4_fold_d(wref[j], Ws[(size_t)blk * N + n]));
#pragma unroll
for (int i = 0; i < MT; i++)
acc[j][i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(af[i], wf, acc[j][i]);
@@ -199,7 +216,8 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
for (int j = 0; j < NPW; j++) {
const int slot = ((col_local * NPW + j) * SK + ksplit) * 256;
#pragma unroll
for (int e = 0; e < 8; e++) red[slot + lane * 8 + e] = acc[j][i][e];
for (int e = 0; e < 8; e++)
red[slot + lane * 8 + e] = ABLK ? acc[j][i][e] * scur[i][e] : acc[j][i][e];
}
__syncthreads();
// One pass over the block's 256-element tiles; every thread takes a stride.
@@ -215,7 +233,7 @@ __global__ void r4d_gemm_mxfp4a8_nt_m64_kernel(
float v = 0.f;
for (int s = 0; s < SK; s++) v += red[(col * SK + s) * 256 + off];
C[(size_t)m * N + n] =
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * As[m]);
(__hip_bfloat16)(v * __int_as_float((int)Wref[n] << 23) * (ABLK ? 1.f : As[m]));
}
}
}
@@ -225,7 +243,7 @@ extern "C" int r4d_gemm_mxfp4a8_nt_m64_group(void) { return R4D_GEMM_MXFP4_GROUP
extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int WV, int SK, int MB, int NPW,
long stream) {
int as_group, int as_rs, long stream) {
if (M < 1 || M > R4D_GEMM_MXFP4_MAX_M)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: M must be 1..64");
if (N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: N must be a multiple of 16");
@@ -236,6 +254,9 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
if (MB < 1 || MB > 4) throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: MB must be 1..4");
if (NPW != 1 && NPW != 2 && NPW != 4 && NPW != 8)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: NPW must be 1, 2, 4 or 8");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_nt_m64: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
const int ntiles = N / 16, mtiles = (M + 15) / 16;
const int ncols = WV * NPW;
dim3 grid((ntiles + ncols - 1) / ncols, (mtiles + MB - 1) / MB), block(WV * SK * WAVE32);
@@ -249,8 +270,13 @@ extern "C" void r4d_gemm_mxfp4a8_nt_m64(long a, long ascale, long wq, long ws, l
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define LAUNCH(MTv, NPv) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv>), grid, \
block, smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK)
#define LAUNCH(MTv, NPv) \
do { \
if (ablk) hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, true>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
else hipLaunchKernelGGL((r4d_gemm_mxfp4a8_nt_m64_kernel<MTv, NPv, false>), grid, block, \
smem, st, Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, WV, SK, as_rs); \
} while (0)
#define LAUNCH_MB(NPv) switch (MB) { \
case 1: LAUNCH(1, NPv); break; \
case 2: LAUNCH(2, NPv); break; \
@@ -284,6 +310,9 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
const int group = r4d_gemm_mxfp4a8_nt_m64_group();
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
Cfg c;
rc = cfg_for(a, g.K, g.M, group, BR_FLAT, &c);
if (rc != RAD_OK) return rc;
@@ -291,7 +320,7 @@ extern "C" int r4d_rad_gemm_mxfp4a8_m64(const RadArgs* a, RadStream s) {
r4d_gemm_mxfp4a8_nt_m64(r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b),
r4d_addr(g.bscale), r4d_addr(g.bref), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, c.wv, c.sk, c.mb, c.npw,
(long)(uintptr_t)s));
as_group, as_rs, (long)(uintptr_t)s));
return RAD_OK;
}
+398
View File
@@ -0,0 +1,398 @@
// r4d_gemm_mxfp4a8_tiled.hip - r4d_gemm_mxfp4a8_tiled: the OCP-MXFP4 x fp8 GEMM for PREFILL row
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the same operands, the same weight
// layout and the same fold as r4d_gemm_mxfp4a8_nt_m64 and r4d_gemm_mxfp4a8_decode -- the band
// above theirs.
//
// WHY A SEPARATE KERNEL. The decode kernels give a block at most 128 rows, so at prefill they
// would re-read the whole weight ceil(M/128) times. Here a block is a 256 x (32*TN) tile and each
// weight byte is unpacked once per K slab into LDS, where all four row-waves of the block read it.
//
// A COMES STRAIGHT FROM GLOBAL INTO REGISTERS, NOT THROUGH LDS. Staging A through LDS costs a
// write, a barrier and a second read of the operand the block uses most, and a WMMA A fragment --
// lane l holds row l%16, k-bytes 8*(l/16)..+8 of a 16 x 16 tile -- is 16 rows apart in a row-major
// plane, so it cannot be loaded straight from one either. So A is re-tiled first, into the op's
// scratch, in FRAGMENT ORDER:
//
// AT[((m/16) * (K/16) + k/16) * 256 + ((m%16) + 16 * ((k/8)%2)) * 8 + k%8] = A[m][k]
//
// One 16 x 16 fragment is 256 contiguous bytes and a lane's eight are one aligned 8-byte load, so
// every A fragment a wave needs for a slab issues as one clause of global loads off a wave-uniform
// base (SGPR, the SADDR form) and is consumed at the WMMAs. The re-tile is one read and one write
// of A -- tens of microseconds at a 2048-row chunk against the hundreds the A-direct loop saves on
// every large projection -- and it is the op's own, so no producer has to know about the layout.
// Rows past M in the last fragment are written as zeros; they only reach accumulators the
// epilogue drops.
//
// THE WEIGHT AND THE FOLD ARE THE SKINNY KERNEL'S. It reads the fragment-order weight that
// r4d_rad_layout_mxfp4 stores and folds each block's exponent into the e4m3 value through the
// table in r4d_mxfp4.h, so all three MXFP4 kernels produce the same e4m3 byte for every element.
// The table is copied to LDS once per block: read from global it would be a dependent load issued
// behind the A fragments, and the in-order load counter would make the fold wait for all of them.
// 2^(Wref[n]-127) is applied once in the epilogue next to the activation's scale; see
// r4d_gemm_mxfp4a8_nt_m64.hip for the fold and its error analysis.
//
// THE TILE. 8 waves as 4 (M) x 2 (N); a wave owns TM=4 x TN accumulator fragments, so the block
// covers BMF = 4*4*16 = 256 rows and BNF = 2*TN*16 columns. The tall tile is for reuse: every
// weight byte staged is multiplied against 256 rows. TN is the axis that depends on M. Widening
// N halves the column-block count while BMF still masks most of a short M, so TN=4 wins only on
// long prompts; on a 17408x5120 weight the two cross near M=2048. Hence tn=0, the default, picks
// TN=4 from M >= 2048 and TN=2 below. The K slab is 128 at TN=2 and 64 at TN=4 (and 64 at TN=2
// when K is not a multiple of 128): TN=4 holds twice the accumulators, and a 128 slab's A
// fragments on top of them would cost occupancy.
//
// BARRIERS FENCE LDS ONLY. __syncthreads() is a workgroup acquire/release over every address
// space, which drains the global load counter at each barrier. Nothing in global memory is
// shared between the block's waves, so the barrier is scoped to LDS and the next slab's A loads
// stay in flight across it.
//
// STAGING IS CLAMPED, NEVER PREDICATED. A bounds-predicated load lands in its own exec-mask
// region and the compiler then cannot carry a counted s_wait_loadcnt across the merge. Clamped
// (a tile past M reads the last real tile, a weight row past N the last aligned group), a slab's
// loads issue back to back; the epilogue drops what they computed.
//
// THE ACCUMULATOR IS C TRANSPOSED. The WMMA takes the weight fragment as its A operand and the
// activation fragment as its B operand -- the two have the same register layout, so this is only
// an argument order -- and computes C^T: a lane's accumulator for (M fragment i, N fragment j)
// holds ONE row and eight consecutive columns. So a row's activation scale is one value a lane
// for each of its TM rows, and the epilogue writes each (i, j) as one 16-byte store.
//
// TWO ACTIVATION SCALE GRIDS. `a_scale` is either one f32 per row (ABLK=false) or one per (row,
// 128 of K) (ABLK=true: the block-scaled fp8 family's grid, which every fused producer in
// arch/common writes). Per-block scales vary along K and so cannot wait for the epilogue. The
// accumulator is carried IN UNITS OF THE CURRENT BLOCK'S SCALE: at each 128 boundary every row's
// partial sum is multiplied by s_prev / s_next, and the epilogue applies the last block's scale --
// one multiply per accumulator element per 128 of K, ~K/128 fp32 ulps of extra rounding. The
// ratio is computed once a row: thread t owns row t of the block, loads the next boundary's two
// scales a boundary early (no slab waits on a scale load) and writes the ratio to LDS, and a lane
// reads one ratio for each of its TM rows.
//
// TRAP FOR ANYONE MEASURING THIS KERNEL: the same as the skinny kernel's. A weight of tens of
// megabytes streamed in a loop is Infinity-Cache resident on this part, so a bandwidth figure
// taken that way reads above the DRAM roofline.
#include "r4d.h"
#include "r4d_gemm_args.h"
#include "r4d_common.h"
#include "r4d_mxfp4.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <stdexcept>
#define R4D_MXT_TM 4 // 16-row fragments per wave
#define R4D_MXT_WM 4 // waves along M
#define R4D_MXT_WN 2 // waves along N
#define R4D_MXT_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
#define R4D_MXT_NTHR (R4D_MXT_WM * R4D_MXT_WN * 32)
#define R4D_MXT_BMF (R4D_MXT_WM * R4D_MXT_TM * 16)
#define R4D_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
#define R4D_MXT_TN4_MIN_M 2048 // tn=0's crossover, see above
typedef int mxt_v2i __attribute__((ext_vector_type(2)));
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
typedef unsigned mxt_u4 __attribute__((ext_vector_type(4)));
static __device__ __forceinline__ void mxt_lds_barrier() {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local");
__builtin_amdgcn_s_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local");
}
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane, so the writes are
// contiguous and each lane reads one 8-byte group of one row.
__global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
long long slots) {
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
if (o >= slots) return;
const int ks = K / 16;
const int lane = (int)(o & 31);
const long long f = o >> 5;
const int mt = (int)(f / ks), kst = (int)(f % ks);
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
mxt_u2 v = { 0u, 0u };
if (r < M) v = *(const mxt_u2*)(A + (size_t)r * K + k);
*(mxt_u2*)(AT + o * 8) = v;
}
template <int TN, int LBK, bool ABLK>
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
const unsigned char* __restrict__ AT, const float* __restrict__ As,
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
int M, int K, int N, int as_rs) {
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
__shared__ unsigned char sW[BNF * STR];
__shared__ unsigned int sMag[32];
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int wm = wave / WN, wn = wave % WN;
const int col = lane & 15, kb8 = (lane >> 4) * 8;
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
const int ksteps = K / 16, Mt = (M + 15) >> 4;
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
// One A base per M fragment: wave-uniform, so readfirstlane keeps it in an SGPR and every load
// takes the SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
const unsigned char* abase[TM];
#pragma unroll
for (int i = 0; i < TM; ++i) {
int mt = (m0 >> 4) + wm * TM + i;
mt = mt < Mt - 1 ? mt : Mt - 1;
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
}
const unsigned int aoff = (unsigned int)lane * 8;
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned.
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW];
unsigned int wref[NW];
#pragma unroll
for (int it = 0; it < NW; ++it) {
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
const int lane_ = sl & 31, rest = sl >> 5;
const int kst = rest % NS, ntl = rest / NS;
wrow[it] = ntl * 16 + (lane_ & 15);
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
const int gn = n0 + wrow[it];
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
wkst[it] = kst;
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
: Wref[wrc[it]];
}
v8f acc[TM][TN];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
// ABLK, once a row: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two
// scales -- the block that starts there and the one before it -- a boundary early.
const int trow = m0 + tid < M ? m0 + tid : M - 1;
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
float ns = 0.f, np = 0.f;
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
mxt_lds_barrier(); // sMag
for (int k0 = 0; k0 < K; k0 += LBK) {
// ABLK: a new 128-wide activation block starts with this slab; each row's ratio goes to LDS,
// published by the staging barrier below (sR's previous readers were behind the last slab's
// closing barrier). A zero block keeps the carried scale; a zero block before this one sends
// the carried scale back to the grid, which only an all-zero activation block ever does.
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
if constexpr (ABLK) {
if (bnd)
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
}
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
mxt_v2i af[TM][NS];
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int st = 0; st < NS; ++st)
af[i][st] = *(const mxt_v2i*)(abase[i] +
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
// W slab -> LDS, folded to e4m3.
const int kstep0 = k0 / 16;
#pragma unroll
for (int it = 0; it < NW; ++it) {
const unsigned int* src =
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
unsigned int wq[WSLOTS], wsw;
if constexpr (WSLOTS == 4) {
const mxt_u4 v = *(const mxt_u4*)src;
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
wsw = *(const unsigned int*)(Ws + (size_t)blk * N + wrc[it]);
} else if constexpr (WSLOTS == 2) {
const mxt_u2 v = *(const mxt_u2*)src;
wq[0] = v[0]; wq[1] = v[1];
wsw = *(const unsigned short*)(Ws + (size_t)blk * N + wrc[it]);
} else {
wq[0] = *src;
wsw = Ws[(size_t)blk * N + wrc[it]];
}
#pragma unroll
for (int q = 0; q < WSLOTS; ++q) {
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
(int)((wsw >> (8 * q)) & 0xFF));
unsigned int lo, hi;
r4d_mxfp4_unpack8_t(wq[q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
}
}
mxt_lds_barrier();
if constexpr (ABLK) {
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
if (bnd) {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const float r = sR[wm * TM * 16 + i * 16 + col];
#pragma unroll
for (int j = 0; j < TN; ++j)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
}
}
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
if ((k0 & 127) == 0 && k0 + 128 < K) {
ns = asrow[(k0 >> 7) + 1];
np = asrow[k0 >> 7];
}
}
#pragma unroll
for (int step = 0; step < NS; ++step) {
const int kk = step * 16 + kb8;
mxt_v2i wf[TN];
#pragma unroll
for (int j = 0; j < TN; ++j) {
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
}
// One step's W fragments live at a time: without the fence the compiler hoists every
// step's loads above the first WMMA and holds them all.
__builtin_amdgcn_sched_barrier(0);
#pragma unroll
for (int i = 0; i < TM; ++i)
#pragma unroll
for (int j = 0; j < TN; ++j)
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
acc[i][j]);
}
mxt_lds_barrier();
}
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns of N fragment
// j, so each (i, j) is one 16-byte store. 2^(Wref[n]-127) is exactly the float whose exponent
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside N or all outside it.
float sc[TM];
if constexpr (ABLK) {
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
mxt_lds_barrier();
#pragma unroll
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
} else {
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
}
}
#pragma unroll
for (int j = 0; j < TN; ++j) {
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
if (nb >= N) continue;
const mxt_u2 rb = *(const mxt_u2*)(Wref + nb);
#pragma unroll
for (int i = 0; i < TM; ++i) {
const int m = m0 + wm * TM * 16 + i * 16 + col;
if (m >= M) continue;
union { __hip_bfloat16 h[8]; mxt_u4 v; } o;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
o.h[e] = (__hip_bfloat16)(acc[i][j][e] * rf * sc[i]);
}
*(mxt_u4*)(C + (size_t)m * N + nb) = o.v;
}
}
}
extern "C" int r4d_gemm_mxfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
}
extern "C" void r4d_mxfp4a8_tile_a(long a, long at, int M, int K, long stream) {
if (M < 1) throw std::runtime_error("r4d mxfp4a8_tile_a: M must be >= 1");
if (K < 16 || K % 16) throw std::runtime_error("r4d mxfp4a8_tile_a: K must be a multiple of 16");
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
hipLaunchKernelGGL(r4d_mxfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256), 0,
(hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K, slots);
}
extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, long wref, long c,
int M, int K, int N, int TN, int as_group, int as_rs,
long stream) {
if (M < 1) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: M must be >= 1");
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: N must be a multiple of 16");
if (K < R4D_MXT_KUNIT || K % R4D_MXT_KUNIT)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: K must be a multiple of 64");
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves the grid short of 128
// blocks (a narrow N): there the TN=2 grid's extra blocks win.
if (TN == 0)
TN = M >= R4D_MXT_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_MXT_BMF - 1) / R4D_MXT_BMF) >= 128
? 4 : 2;
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_mxfp4a8_tiled: TN must be 2 or 4");
if (as_group != 0 && as_group != 128)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: the activation scale is per row or per 128 of K");
const bool ablk = as_group == 128;
if (ablk && as_rs < (K + 127) / 128)
throw std::runtime_error("r4d gemm_mxfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
const bool wide_slab = TN == 2 && K % 128 == 0;
const int bnf = R4D_MXT_WN * TN * 16;
dim3 grid((N + bnf - 1) / bnf, (M + R4D_MXT_BMF - 1) / R4D_MXT_BMF), block(R4D_MXT_NTHR);
auto Ap = (const unsigned char*)at;
auto Sp = (const float*)ascale;
auto Wp = (const unsigned char*)wq;
auto Zp = (const unsigned char*)ws;
auto Rp = (const unsigned char*)wref;
auto Cp = (__hip_bfloat16*)c;
hipStream_t st = (hipStream_t)stream;
#define MXT_LAUNCH(TNv, LBKv, ABv) \
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
Wp, Zp, Rp, Cp, M, K, N, as_rs)
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
#undef MXT_LAUNCH
}
// ============================================================== the plugin ABI entry point
// The row-major activation is re-tiled into the op's scratch, then the GEMM reads it from there.
extern "C" int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs* a, RadStream s) {
GemmOps g;
int rc = gemm_ops(a, &g, 1);
if (rc != RAD_OK) return rc;
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
if (g.K % R4D_MXT_KUNIT) return R4D_NO(RAD_E_SHAPE);
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
/* The per-row reference exponent, as in r4d_rad_gemm_mxfp4a8_m64: without it the fold has no
* reference and every element would be scaled against zero. */
if (!g.bref) return R4D_NO(RAD_E_INVAL);
int as_group = 0, as_rs = 1;
rc = mx_ascale_grid(g, &as_group, &as_rs);
if (rc != RAD_OK) return rc;
if (!a->scratch || a->scratch_bytes < r4d_mxfp4a8_tile_a_bytes((int)g.M, (int)g.K))
return R4D_NO(RAD_E_INVAL);
R4dMxTileCfg t;
r4d_cfg_mxfp4_tiled(a, &t);
const long at = (long)(uintptr_t)a->scratch;
R4D_TRY("gemm_mxfp4a8_tiled",
r4d_mxfp4a8_tile_a(r4d_addr(g.a), at, (int)g.M, (int)g.K, (long)(uintptr_t)s);
r4d_gemm_mxfp4a8_tiled(at, r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale),
r4d_addr(g.bref), r4d_addr(g.y), (int)g.M, (int)g.K, (int)g.N,
t.tn, as_group, as_rs, (long)(uintptr_t)s));
return RAD_OK;
}
/* The core sizes the op's scratch from this, at the band's widest M: the fragment-tiled copy of
* the activation, whole 16-row fragments. */
extern "C" int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
return (int64_t)r4d_mxfp4a8_tile_a_bytes((int)M, (int)K);
}
+74
View File
@@ -0,0 +1,74 @@
// Shared device-side machinery for the OCP-MXFP4 GEMMs (r4d_gemm_mxfp4a8_nt_m64, _tiled, _decode):
// the folded-magnitude table and the eight-element unpack that reads it. One definition, because
// the three kernels must fold every weight element to the same e4m3 byte -- a model whose step
// crosses from one row's band into another's must not change what the weight is.
//
// r4d_gemm_mxfp4a8_nt_m64.hip explains the fold: d = Wref[n] - E8M0[n][blk] is pushed into the
// e4m3 value through this table, and 2^(Wref[n]-127) is applied once in the epilogue.
#pragma once
#include <hip/hip_runtime.h>
#define R4D_MXFP4_GROUP 32 // K per E8M0 exponent, fixed by the OCP MX format
// kMxfp4Mag[d] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by 2^-d, as packed
// e4m3 bytes, low word then high word, indexed by the 3-bit magnitude through v_perm_b32.
// Every entry is the round-to-nearest-EVEN e4m3 of that product, which is exact for d <= 8 and a
// rounding for d >= 9 -- three entries there (d=9 mag 1.5, d=10 mag 3, d=11 mag 6) are the same
// exact tie 1.5*2^-9 and take the even neighbour 2^-8, not the smaller one. They matter little
// (such an element is 2.9e-3 of its row's reference), but the table is generated, not hand-rounded,
// so it agrees with the hardware's own conversion. d >= 13 is zero: below the row's range.
//
// Static: each kernel's code object carries its own copy, and no two define the same symbol.
static __device__ __constant__ unsigned int kMxfp4Mag[16][2] = {
{0x3c383000u, 0x4c484440u}, {0x34302800u, 0x44403c38u},
{0x2c282000u, 0x3c383430u}, {0x24201800u, 0x34302c28u},
{0x1c181000u, 0x2c282420u}, {0x14100800u, 0x24201c18u},
{0x0c080400u, 0x1c181410u}, {0x06040200u, 0x14100c08u},
{0x03020100u, 0x0c080604u}, {0x02010000u, 0x06040302u},
{0x01000000u, 0x03020201u}, {0x00000000u, 0x02010100u},
{0x00000000u, 0x01000000u}, {0x00000000u, 0x00000000u},
{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
};
// The exponent difference a block is folded at, clamped to the table: a block above its row's
// reference cannot occur (the reference is the row's maximum), and one 15 or more below is zero.
static __device__ __forceinline__ int r4d_mxfp4_fold_d(int ref, int e8) {
const int d = ref - e8;
return d < 0 ? 0 : (d > 15 ? 15 : d);
}
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
// in k order, word 0 holding elements 0..3 and word 1 elements 4..7, with the block's exponent
// difference `d` already folded in. Splitting the nibbles gives the even and odd elements; each is
// mapped through the table by a v_perm_b32 indexed with the 3-bit magnitude, the sign rides along
// as bit 3 shifted into the e4m3 sign position, and two more v_perm_b32 interleave the halves.
//
// `_t` takes the table row (t0, t1) the caller already holds -- a kernel that copies the table to
// LDS reads it there, off the global load counter its weight and activation loads wait on.
static __device__ __forceinline__ void r4d_mxfp4_unpack8_t(unsigned int wv, unsigned int t0,
unsigned int t1, unsigned int* lo,
unsigned int* hi) {
const unsigned int ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements
const unsigned int od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements
const unsigned int be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4);
const unsigned int bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4);
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
}
static __device__ __forceinline__ void r4d_mxfp4_unpack8(unsigned int wv, int d,
unsigned int* lo, unsigned int* hi) {
r4d_mxfp4_unpack8_t(wv, kMxfp4Mag[d][0], kMxfp4Mag[d][1], lo, hi);
}
// THE ACTIVATION SCALE A ROW'S ACCUMULATOR IS CARRIED IN, for the per-(row, 128 of K) grid: the
// last non-zero entry of row `row` at or before block `kb`, or 1 when there is none. A block whose
// scale is zero has zero codes and adds nothing whichever scale the sum is carried in, so it keeps
// the previous one rather than dividing by zero.
static __device__ __forceinline__ float r4d_mxfp4_carried(const float* __restrict__ row, int kb) {
for (int j = kb; j >= 0; --j) {
const float s = row[j];
if (s > 0.f) return s;
}
return 1.f;
}
+11
View File
@@ -42,6 +42,8 @@ enum {
* asks with M=64 to exclude m16. */
R4D_PRIO_GEMM_M16 = 60,
R4D_PRIO_GEMM_SKINNY = 50,
/* The MXFP4 decode row outranks the MXFP4 skinny row, whose band it shares up to N = 36864. */
R4D_PRIO_GEMM_MXDEC = 55,
/* The skinny m64 row has no upper bound on M, so the tiled bf16 row -- M > 64 only -- has to
* outrank it to be reached, and stays below m16 whose band it never enters. */
R4D_PRIO_GEMM_BF16_TILED = 55,
@@ -167,6 +169,11 @@ int r4d_rad_hc_write_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, in
/* -- all-reduce (r4d_ar_entry.hip) -- */
int r4d_rad_ar_init(const RadParam*, int, int rank, int world, void** out);
void r4d_rad_ar_fini(void*);
/* The same three inits with every rank's exchange buffers in pinned host memory: the host twins
* of the collective rows (r4d_rows.cpp) take them, and every launch and the fini are shared. */
int r4d_rad_ar_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_ln_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_hc_wide_host_init(const RadParam*, int, int rank, int world, void** out);
int r4d_rad_ar_oneshot_2rank_exact(const RadArgs*, RadStream);
int r4d_rad_ar_gather_2rank (const RadArgs*, RadStream);
/* The gather at a wide group's handshake (r4d_ar_gather_Nrank.hip launches it). */
@@ -207,6 +214,10 @@ int r4d_rad_gemm_w8a8_m64 (const RadArgs*, RadStream);
int r4d_rad_gemm_w8a8_tiled (const RadArgs*, RadStream);
int r4d_rad_gemm_w2a8 (const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_m64(const RadArgs*, RadStream);
int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
int r4d_rad_rowtopk (const RadArgs*, RadStream);
int r4d_rad_rowtopk_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*);
+157 -8
View File
@@ -34,6 +34,8 @@
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0])))
@@ -2923,6 +2925,18 @@ static const RadConstraint cGemmNtW8A8[] = {
static const RadConstraint cGemmW4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8 w4a8_asym"),
};
/* r4d_gemm_mxfp4a8_decode. Entry point: M <= 128, N % 16, K % 64, and N up to its counter block's
* 36864. Above the skinny row by priority, so it takes the decode band; the skinny row keeps the
* wider N up to M = 64, the tiled row everything else. */
static const RadConstraint cGemmMxfp4A8Decode[] = {
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_mxfp4a8_tiled. Entry point: N % 16 (the fragment-order weight), K % 64 (its narrowest
* K slab), M >= 1. The decode and skinny rows outrank it in their bands by priority, so the band
* starts at 1 rather than at a hand-picked crossover. */
static const RadConstraint cGemmMxfp4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
};
/* r4d_gemm_w8a8_tiled. The same kernel at radix 8; the asym arm exists in the .hip but is NOT
* declared in r4d.h, so this plugin cannot reach it and `w8a8_asym` is deliberately absent from
* the dtype set. */
@@ -3042,6 +3056,25 @@ static const RadTunable tGemmPrefill[] = {
"compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" },
};
/* The MXFP4 tiled GEMM's one axis. Both values are compiled arms of one template; 0 is the M
* crossover (TN=4 from M >= 2048), which needs M and so cannot be a constant. */
static const int64_t kMxTn[] = { 0, 2, 4 };
static const RadTunable tGemmMxfp4Tiled[] = {
{ "tn", kMxTn, NELEM(kMxTn), 0,
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
};
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
* `nt` 1 streams the weight past the caches, 2 loads it plainly. */
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
static const int64_t kMxDecBk[] = { 0, 64, 128 };
static const int64_t kMxDecNt[] = { 0, 1, 2 };
static const RadTunable tGemmMxfp4Decode[] = {
{ "ks", kMxDecKs, NELEM(kMxDecKs), 0, "split-K workgroups a column block. 0 = the fill rule" },
{ "bk", kMxDecBk, NELEM(kMxDecBk), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
{ "nt", kMxDecNt, NELEM(kMxDecNt), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
};
/* ------------------------------------------------------------------------ split-KV attention
* 0 is libr4d's measured split law (r4d_attn_paged_h256_gqa6.hip carries the table), which reads
* num_seqs and max_ctx -- values that exist only at issue -- so it cannot be a constant and stays
@@ -4319,6 +4352,32 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_m64, nullptr, r4d_rad_layout_mxfp4,
r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_decode", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM for the DECODE band: split-K across workgroups with a fused last-arriver "
"reduction, the weight unpacked through LDS, streaming weight loads",
"M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent; the split partial in the op's scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC,
ROW(cGemmMxfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_decode, r4d_rad_gemm_mxfp4a8_decode_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
{ "gemm_mxfp4a8_tiled", "gemm_nt_q", "gemm",
"the OCP-MXFP4 GEMM tiled for PREFILL row counts: the activation re-tiled into fragment order in "
"the op's scratch, its fragments read straight into registers, the weight unpacked once per K "
"slab into LDS for a 256-row block",
"any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
"[K/32][N] E8M0 exponents and per-row reference exponent; the re-tiled activation in the op's "
"scratch",
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K folded "
"into the element against a per-row reference, bf16 C, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED,
ROW(cGemmMxfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr,
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch,
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
/* BAND READ OFF THE ENTRY POINT'S OWN REJECTION TESTS. */
{ "gemm_w4a8_prefill", "gemm_nt_q", "gemm",
"the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is "
@@ -5067,8 +5126,9 @@ static const RadPluginInfo kInfo = {
RAD_PLUGIN_KERNEL,
"libr4d",
"0.5.0",
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, P2P "
"all-reduce, skinny and tiled quantised GEMM, and the rotate-and-quantise fusions",
"the RDNA4 (gfx1201) kernel library: paged and dense attention, gated delta net, "
"all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, and the "
"rotate-and-quantise fusions",
"gfx1201",
};
@@ -5082,12 +5142,91 @@ extern "C" const RadOpSchema* rad_kernel_schema_at(int i) {
if (i < 0 || i >= rad_kernel_schema_count()) return nullptr;
return &kSchemas[i];
}
/* ================================================================================ the host twins
*
* A MACHINE WITHOUT PEER ACCESS RUNS THE SAME COLLECTIVES WITH THEIR MAILBOX IN HOST MEMORY. Every
* row that takes one of the three all-reduce inits has a twin: the same op, kernel, launch, fini,
* priority and tuning axes, `_host` appended to its name, its device.p2p == 1 turned into
* device.p2p == 0, and the init that puts every rank's exchange buffers in pinned host memory
* (r4d_ar_entry.hip, build). Exactly one of a pair matches any machine, so neither outranks the
* other, and a band report names which transport the step runs.
*
* DERIVED, NOT WRITTEN OUT, so a collective row added to the table above has its twin by being
* added and the two cannot drift: the transport is the only thing they differ in. A collective row
* that does not require device.p2p == 1 gets no twin, and r4d_selftest fails it for the missing
* constraint. */
namespace {
struct HostTwin {
RadKernelInfo info;
std::string name, computes, shape;
std::vector<RadConstraint> c;
};
RadInitFn host_init_for(RadInitFn f) {
if (f == r4d_rad_ar_init) return r4d_rad_ar_host_init;
if (f == r4d_rad_ar_ln_init) return r4d_rad_ar_ln_host_init;
if (f == r4d_rad_ar_hc_wide_init) return r4d_rad_ar_hc_wide_host_init;
return nullptr;
}
std::string replaced(std::string s, const char* from, const char* to) {
const size_t at = s.find(from);
if (at != std::string::npos) s.replace(at, std::strlen(from), to);
return s;
}
const std::vector<HostTwin>& host_twins() {
static const std::vector<HostTwin> v = [] {
std::vector<HostTwin> t;
for (const RadKernelInfo& k : kKernels) {
const RadInitFn init = host_init_for(k.init);
if (!init) continue;
HostTwin h;
h.c.assign(k.constraints, k.constraints + k.n_constraints);
int p2p = 0;
for (RadConstraint& c : h.c)
if (!std::strcmp(c.key, RAD_FACT_P2P) && c.op == RAD_C_EQ && c.ival == 1) {
c.ival = 0;
++p2p;
}
if (p2p != 1) continue;
h.info = k;
h.info.init = init;
h.name = std::string(k.name) + "_host";
h.computes = k.computes;
if (h.computes.find("over P2P IPC scratch") != std::string::npos)
h.computes = replaced(h.computes, "over P2P IPC scratch",
"through a pinned host-memory mailbox");
else
h.computes += ", exchanged through a pinned host-memory mailbox";
h.shape = replaced(replaced(k.shape, "all peer-accessible", "no peer access needed"),
"peer-accessible", "no peer access needed");
t.push_back(std::move(h));
}
/* The strings are pointed into only once the vector has stopped growing. */
for (HostTwin& h : t) {
h.info.name = h.name.c_str();
h.info.computes = h.computes.c_str();
h.info.shape = h.shape.c_str();
h.info.constraints = h.c.data();
h.info.n_constraints = (int)h.c.size();
}
return t;
}();
return v;
}
} /* namespace */
extern "C" int rad_kernel_count(void) {
return (int)(sizeof(kKernels) / sizeof(kKernels[0]));
return (int)(sizeof(kKernels) / sizeof(kKernels[0])) + (int)host_twins().size();
}
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
const int base = (int)(sizeof(kKernels) / sizeof(kKernels[0]));
if (i < 0 || i >= rad_kernel_count()) return nullptr;
return &kKernels[i];
if (i < base) return &kKernels[i];
return &host_twins()[(size_t)(i - base)].info;
}
/* WHICH ROWS TOUCH NOTHING BUT THEIR OPERANDS AND SCRATCH (rad_abi.h). Nothing on an R4D launch
@@ -5100,11 +5239,13 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
* gemm_w8a8_tiled
* every collective the peer flags and exchange buffers the all-reduces own
*
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output, and
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream AND the output;
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
* output alone, so no argument depends on the stream a pass is recorded or replayed on; and
* router_gemm_topk_scatter_bf16's arrival counter is its op instance's (taken at init, one a
* declared op and band), so two launches that could run at once never share them, and both rows
* are concurrent. A row added with state of its own that the stream's order protects belongs in
* this list. */
* declared op and band). Two launches that could run at once never share any of them, so all three
* rows are concurrent. A row added with state of its own that the stream's order protects belongs
* in this list. */
extern "C" int rad_kernel_concurrent(int i) {
const RadKernelInfo* k = rad_kernel_at(i);
if (!k) return 0;
@@ -5179,6 +5320,14 @@ extern "C" void r4d_cfg_tiled(const RadArgs* a, R4dTileCfg* out) {
extern "C" void r4d_cfg_prefill(const RadArgs* a, R4dTileCfg* out) {
tile_bmbn(TUNE(a, tGemmPrefill, "tile"), 1, out);
}
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
out->ks = TUNE(a, tGemmMxfp4Decode, "ks");
out->bk = TUNE(a, tGemmMxfp4Decode, "bk");
out->nt = TUNE(a, tGemmMxfp4Decode, "nt");
}
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
out->tn = TUNE(a, tGemmMxfp4Tiled, "tn");
}
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
out->splits = TUNE(a, tAttnSplit, "splits");
}
+497 -78
View File
@@ -353,17 +353,20 @@ static void cross_check(const Plugin& pl) {
"' which op '" + r->op + "' does not declare; ";
}
}
/* EVERY MULTI-CARD ROW NEEDS PEER ACCESS. Each kernel in this library that runs only at
* two or more ranks reads or writes the other cards' memory directly, so without
* device.p2p a machine whose cards cannot reach each other resolves it and the launch
* faults or hangs instead of being refused by name at selection. */
/* EVERY MULTI-CARD ROW STATES THE TRANSPORT IT NEEDS. A kernel in this library that runs
* only at two or more ranks either reads and writes the other cards' memory directly and
* requires device.p2p == 1, or is a host twin whose mailbox is pinned host memory and
* requires device.p2p == 0. Without the key, a machine whose cards cannot reach each other
* resolves a P2P kernel and the launch faults or hangs instead of being refused by name at
* selection; and a host twin without it would compete with its original where P2P works. */
bool multi = false, p2p = false;
for (int c = 0; c < r->n_constraints; ++c) {
const RadConstraint& rc = r->constraints[c];
if (!std::strcmp(rc.key, "world_size") &&
(rc.op == RAD_C_EQ || rc.op == RAD_C_GE) && rc.ival >= 2)
multi = true;
if (!std::strcmp(rc.key, RAD_FACT_P2P) && rc.op == RAD_C_EQ && rc.ival == 1)
if (!std::strcmp(rc.key, RAD_FACT_P2P) && rc.op == RAD_C_EQ &&
(rc.ival == 1 || rc.ival == 0))
p2p = true;
}
if (multi && !p2p) {
@@ -379,7 +382,8 @@ static void cross_check(const Plugin& pl) {
ok("no row declares the same axis key twice", dup_axis == 0, axisdetail);
ok("every row's op has a schema", no_schema == 0, keydetail);
ok("every constraint key is a declared parameter of its op", bad_key == 0, keydetail);
ok("every row that needs two or more ranks requires device.p2p", no_p2p == 0, p2pdetail);
ok("every row that needs two or more ranks requires device.p2p 1 or 0", no_p2p == 0,
p2pdetail);
/* The libr4d orderings the integer priority has to preserve. */
int p_ts = -1, p_os = -1, p_dec = -1, p_pre = -1, p_m16 = -1, p_m64 = -1, p_bt = -1;
@@ -3308,6 +3312,351 @@ static void w8a16_numeric(const Plugin& pl, const char* row, int64_t M, int64_t
}
/* An OCP-MXFP4 weight's planes, drawn through st_mix32 of each coordinate and `seed`: codes over
* all sixteen e2m1 values, and an exponent per (row, 32 of K) within three binades of 127. With
* `deep`, about one block in eleven sits 6..12 binades lower still -- the folded table's subnormal
* tail. */
static void mxfp4_fill(Planes& p, int ic, int is, int64_t N, int64_t K, uint32_t seed, bool deep) {
const int64_t nblk = K / 32;
for (int64_t n = 0; n < N; ++n)
for (int64_t k = 0; k < K; k += 2) {
const uint32_t h = st_mix32((uint32_t)(n * K + k) ^ (seed * 0x9e3779b9u));
p.data[(size_t)ic][(size_t)((n * K + k) / 2)] =
(uint8_t)((h & 15) | (((h >> 8) & 15) << 4));
}
for (int64_t n = 0; n < N; ++n)
for (int64_t b = 0; b < nblk; ++b) {
const uint32_t h = st_mix32((uint32_t)(n * nblk + b) ^ (seed * 0x85ebca6bu) ^ 0x2545u);
int e = 127 + (int)(h % 7) - 3;
if (deep && (h >> 8) % 11 == 0) e -= 6 + (int)((h >> 16) % 7);
p.data[(size_t)is][(size_t)(n * nblk + b)] = (uint8_t)e;
}
}
/* An E4M3-representable activation value in [-4, 4], drawn the same way. */
static float mxfp4_act(int64_t i, int64_t k, uint32_t seed) {
const uint32_t h = st_mix32((uint32_t)(i * 0x10001 + k) ^ (seed * 0xc2b2ae35u));
return (float)((int)(h % 401) - 200) * 0.02f;
}
/* THE MXFP4 GEMMS AGAINST WHAT THE PLANES MEAN. The weight is an OCP-MXFP4 plane pair -- e2m1
* codes and an E8M0 exponent per 32 K -- stored through the row's own hooks, so the fragment
* order, the [K/32][N] exponents and the per-row reference all come from r4d_layout.cpp and the
* kernel is checked on what the loader would hand it. The reference decodes the planes on the host
* with no fold at all, so a misread arrangement shows as a column that disagrees.
*
* Codes, exponents and activations are drawn through st_mix32 of their coordinates, so a misread
* pitch or lane map reads unrelated numbers rather than a shifted copy of the right ones. The
* exponents are spread so a row's blocks sit up to 12 binades under its reference: d <= 8 is exact
* in the folded e4m3 table and d = 9..12 rounds, which is the subnormal tail every MXFP4 row
* shares. M and N are chosen ragged against the tiled row's 256-row block and 64/128-column tile,
* so the clamped staging and the guarded epilogue both run. `tn` pins the tiled row's column
* width; 0 leaves it to the row's own M rule (and is ignored by the skinny row).
*
* `ablk` hands the activation scale as the block-scaled fp8 family's grid, one f32 per (row, 128
* of K), instead of one per row -- what an architecture's fused quantisers write. The scales are
* spread over two decades and every eleventh block's is ZERO with zero codes behind it (an
* all-zero activation block), which is the case the kernels carry their previous scale through. */
static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int tn, bool ablk = false, std::vector<RadParam> extra = {}) {
if (!sel(row)) return;
char nm[160];
std::string ex;
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
const RadKernelInfo* r = find(pl, row);
if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; }
const int64_t nblk = K / 32;
Planes p;
p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale");
if (ic < 0 || is < 0) { ok(nm, false, "encoding has no codes/scale plane"); return; }
mxfp4_fill(p, ic, is, N, K, 0x51u, true);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
const int rw = stored(r, lp, 2, p, { "codes" }, &wq);
const int rs = stored(r, lp, 3, p, { "scale" }, &ws);
const int rr = stored(r, lp, 6, p, { "scale" }, &wr);
if (rw != RAD_OK || rs != RAD_OK || rr != RAD_OK) {
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs) + "/" +
std::to_string(rr));
return;
}
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> av((size_t)(M * K)), as((size_t)(M * asc));
for (int64_t i = 0; i < M; ++i) {
for (int64_t c = 0; c < asc; ++c) {
const uint32_t h = st_mix32((uint32_t)(i * asc + c) ^ 0xa5u);
as[(size_t)(i * asc + c)] =
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
: 0.0125f * (float)(1 + h % 5);
}
for (int64_t k = 0; k < K; ++k) {
const bool zero = ablk && as[(size_t)(i * asc + k / 128)] == 0.0f;
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, v);
av[(size_t)(i * K + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * K + k);
}
}
std::vector<uint16_t> hy((size_t)(M * N), 0);
void* d_a = dalloc(ha.size());
void* d_s = dalloc(as.size() * 4);
void* d_w = dalloc(wq.size());
void* d_e = dalloc(ws.size());
void* d_r = dalloc(wr.size());
void* d_y = dalloc(hy.size() * 2);
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_a, RAD_F8E4M3, { M, K }),
ablk ? T(d_s, RAD_F32, { M, asc }) : T(d_s, RAD_F32, { M }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }),
};
absent(ts[5]);
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
PS("dtype", "mxfp4a8") };
if (tn) ps.push_back(PI("tn", tn));
for (const RadParam& p : extra) ps.push_back(p);
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
/* A row with a scratch hook (the decode row's split partial) gets what it asks for, as the
* core would hand it; the decode row refuses a split with too little. */
if (r->scratch) {
const int64_t sb = r->scratch(&a);
if (sb > 0) {
a.scratch = dalloc((size_t)sb);
a.scratch_bytes = sb;
if (!a.scratch) { ok(nm, false, "hipMalloc failed"); return; }
}
}
const int rc = r->launch(&a, (RadStream) nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
ok(nm, false, "rc=" + std::to_string(rc));
return;
}
st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost);
/* Every column for small N, a stride otherwise -- always including the last column, which is
* the clamped tail of the tiled row's weight staging. */
const int64_t nstep = N > 96 ? N / 96 : 1;
double num = 0, den = 0, worst = 0;
for (int64_t i = 0; i < M; ++i)
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
double acc = 0;
for (int64_t k = 0; k < K; ++k) {
const double w = (double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
acc += (double)av[(size_t)(i * K + k)] * w *
(ablk ? (double)as[(size_t)(i * asc + k / 128)] : 1.0);
}
if (!ablk) acc *= (double)as[(size_t)i];
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
num += d * d;
den += acc * acc;
worst = std::max(worst, std::fabs(d) / (std::fabs(acc) + 1e-3));
}
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
char d[96];
std::snprintf(d, sizeof d, "rel_l2 %.3e, worst %.3e", rel, worst);
ok(nm, rel < 1e-2, d);
}
/* TWO DECODE GEMMS THE ENGINE MAY OVERLAP (gemm_mxfp4a8_decode is a concurrent row: its split partial
* is the op's scratch and its arrival counters are keyed on the output). Each GEMM has its own
* weights, activations and output and a DISJOINT slice of one scratch allocation, with a split
* (ks > 1) so the partial and the counters are live. The reference is each launched alone, then the
* pair is launched on two non-blocking streams with nothing ordering them -- repeated, so the
* launches overlap in different phases -- and every output must be BYTE-identical to the serial one
* (the reducer sums the splits in a fixed order, so a lost or shared counter / partial shows as a
* different byte or a hang). A last serial launch after the loop checks that the counters were
* left at zero. */
struct MxdOverlapGemm {
int64_t M, N, K;
int ks;
std::vector<RadTensor> ts;
std::vector<RadParam> ps;
void* y = nullptr;
int64_t scratch = 0;
bool ready = false;
};
static bool mxd_overlap_build(const RadKernelInfo* r, MxdOverlapGemm& g, int seed) {
const int64_t M = g.M, N = g.N, K = g.K, nkb = K / 128;
Planes p;
p.enc = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale");
if (ic < 0 || is < 0) return false;
mxfp4_fill(p, ic, is, N, K, (uint32_t)seed, false);
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
std::vector<uint8_t> wq, ws, wr;
if (stored(r, lp, 2, p, { "codes" }, &wq) != RAD_OK ||
stored(r, lp, 3, p, { "scale" }, &ws) != RAD_OK ||
stored(r, lp, 6, p, { "scale" }, &wr) != RAD_OK)
return false;
std::vector<uint8_t> ha((size_t)(M * K));
std::vector<float> as((size_t)(M * nkb));
for (int64_t i = 0; i < M; ++i) {
for (int64_t c = 0; c < nkb; ++c)
as[(size_t)(i * nkb + c)] =
0.002f * (float)(1 + st_mix32((uint32_t)(i * nkb + c) ^ (uint32_t)seed) % 97);
for (int64_t k = 0; k < K; ++k)
rad_store_f32(ha.data(), RAD_F8E4M3, i * K + k, mxfp4_act(i, k, (uint32_t)seed));
}
void* d_a = dalloc(ha.size());
void* d_s = dalloc(as.size() * 4);
void* d_w = dalloc(wq.size());
void* d_e = dalloc(ws.size());
void* d_r = dalloc(wr.size());
g.y = dalloc((size_t)(M * N) * 2);
if (!d_a || !d_s || !d_w || !d_e || !d_r || !g.y) return false;
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
g.ts = { T(d_a, RAD_F8E4M3, { M, K }), T(d_s, RAD_F32, { M, nkb }),
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
T(g.y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }),
T(d_r, RAD_U8, { (int64_t)wr.size() }) };
absent(g.ts[5]);
g.ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"),
PI("ks", g.ks), PI("bk", 128), PI("nt", 1) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = g.ts.data(); a.n_t = (int)g.ts.size();
a.p = g.ps.data(); a.n_p = (int)g.ps.size();
a.world_size = 1;
g.scratch = r->scratch ? r->scratch(&a) : 0;
g.ready = g.scratch >= (int64_t)g.ks * M * N * 4;
return g.ready;
}
static int mxd_overlap_launch(const RadKernelInfo* r, MxdOverlapGemm& g, void* scratch,
hipStream_t st, int64_t scratch_bytes = -1) {
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = g.ts.data(); a.n_t = (int)g.ts.size();
a.p = g.ps.data(); a.n_p = (int)g.ps.size();
a.world_size = 1;
a.scratch = scratch;
a.scratch_bytes = scratch_bytes < 0 ? g.scratch : scratch_bytes;
return r->launch(&a, (RadStream)st);
}
static void mxd_overlap_case(const Plugin& pl) {
if (!sel("gemm_mxfp4a8_decode_overlap") && !sel("gemm_mxfp4a8_decode")) return;
const char* nm = "gemm_mxfp4a8_decode: two split GEMMs on two streams, disjoint scratch, "
"byte-identical to serial";
const RadKernelInfo* r = find(pl, "gemm_mxfp4a8_decode");
if (!r || !r->layout || !r->relayout || !r->scratch) { ok(nm, false, "row or hooks absent"); return; }
MxdOverlapGemm g[3];
g[0] = MxdOverlapGemm{}; g[0].M = 8; g[0].N = 400; g[0].K = 2560; g[0].ks = 4;
g[1] = MxdOverlapGemm{}; g[1].M = 8; g[1].N = 272; g[1].K = 2560; g[1].ks = 2;
g[2] = MxdOverlapGemm{}; g[2].M = 24; g[2].N = 1040; g[2].K = 1152; g[2].ks = 4;
for (int i = 0; i < 3; ++i)
if (!mxd_overlap_build(r, g[i], 1 + 2 * i)) {
ok(nm, false, "operands or scratch hook (ks > 1 needs a split partial)");
return;
}
/* One allocation, a slice each, 256-byte aligned: the core's disjoint scratch slices. */
int64_t off[3], tot = 0;
for (int i = 0; i < 3; ++i) { off[i] = tot; tot += (g[i].scratch + 255) & ~int64_t(255); }
char* base = (char*)dalloc((size_t)tot);
if (!base) { ok(nm, false, "hipMalloc failed"); return; }
/* The serial reference gets its own scratch, so the two runs share nothing but the kernel. */
std::vector<std::vector<uint16_t>> want(3);
for (int i = 0; i < 3; ++i) {
void* sc = dalloc((size_t)g[i].scratch);
if (!sc) { ok(nm, false, "hipMalloc failed"); return; }
const int rc = mxd_overlap_launch(r, g[i], sc, nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
ok(nm, false, "serial rc=" + std::to_string(rc));
return;
}
want[(size_t)i].assign((size_t)(g[i].M * g[i].N), 0);
st_memcpy(want[(size_t)i].data(), g[i].y, want[(size_t)i].size() * 2, hipMemcpyDeviceToHost);
}
hipStream_t s1 = nullptr, s2 = nullptr;
if (hipStreamCreateWithFlags(&s1, hipStreamNonBlocking) != hipSuccess ||
hipStreamCreateWithFlags(&s2, hipStreamNonBlocking) != hipSuccess) {
ok(nm, false, "hipStreamCreate failed");
return;
}
int bad = 0, iters = 0;
std::string why;
for (int it = 0; it < 200 && !bad; ++it) {
const int a = it % 3, b = (it + 1 + (it / 3) % 2) % 3; /* every ordered pair of distinct GEMMs */
for (int i : { a, b }) st_memset(g[i].y, 0, (size_t)(g[i].M * g[i].N) * 2);
/* The streams are non-blocking, so nothing orders them after the legacy-stream memset. */
(void)hipDeviceSynchronize();
const int ra = mxd_overlap_launch(r, g[a], base + off[a], s1);
const int rb = mxd_overlap_launch(r, g[b], base + off[b], s2);
const bool sa = st_stream_sync(s1) == hipSuccess, sb = st_stream_sync(s2) == hipSuccess;
if (ra != RAD_OK || rb != RAD_OK || !sa || !sb) {
bad = 1;
why = "launch rc " + std::to_string(ra) + "/" + std::to_string(rb);
break;
}
for (int i : { a, b }) {
std::vector<uint16_t> got((size_t)(g[i].M * g[i].N));
st_memcpy(got.data(), g[i].y, got.size() * 2, hipMemcpyDeviceToHost);
if (std::memcmp(got.data(), want[(size_t)i].data(), got.size() * 2) != 0) {
bad = 1;
size_t nd = 0, first = got.size(), nz = 0;
for (size_t j = 0; j < got.size(); ++j) {
if (got[j] != want[(size_t)i][j]) { ++nd; if (first == got.size()) first = j; }
if (got[j] == 0) ++nz;
}
why = "iter " + std::to_string(it) + ": GEMM " + std::to_string(i) + " (ks=" +
std::to_string(g[i].ks) + ") differs from serial: " + std::to_string(nd) +
"/" + std::to_string(got.size()) + " elements, first at " +
std::to_string(first) + " (m=" + std::to_string(first / (size_t)g[i].N) +
" n=" + std::to_string(first % (size_t)g[i].N) + "), " +
std::to_string(nz) + " zero, partner GEMM " + std::to_string(i == a ? b : a);
}
}
++iters;
}
(void)hipStreamDestroy(s1);
(void)hipStreamDestroy(s2);
ok(nm, !bad, bad ? why : std::to_string(iters) + " overlapped pairs identical");
/* The counters must be zero again: a serial launch after the storm is still byte-identical. */
bool again = true;
for (int i = 0; i < 3 && again; ++i) {
st_memset(g[i].y, 0, (size_t)(g[i].M * g[i].N) * 2);
const int rc = mxd_overlap_launch(r, g[i], base + off[i], nullptr);
std::vector<uint16_t> got((size_t)(g[i].M * g[i].N));
again = rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess;
if (again) {
st_memcpy(got.data(), g[i].y, got.size() * 2, hipMemcpyDeviceToHost);
again = std::memcmp(got.data(), want[(size_t)i].data(), got.size() * 2) == 0;
}
}
ok("gemm_mxfp4a8_decode: serial after the overlap storm is still identical (counters left at "
"zero)", again);
/* A split given less scratch than its partial is refused, not run unsplit: the hook sized it
* for the whole band, so a short one is a caller's error and must surface as one. */
const int rc = mxd_overlap_launch(r, g[0], base + off[0], nullptr, g[0].scratch / 2);
(void)st_stream_sync(nullptr);
ok("gemm_mxfp4a8_decode: a split with half its scratch is refused", rc != RAD_OK,
"rc=" + std::to_string(rc));
}
/* THE INT8 TRUNK CHAIN: quant_act_i8g on a bf16 activation, then one of the i8a8 GEMMs on what it
* wrote, against the planes' meaning. The weight is i8 with a bf16 scale per row per 128 K (what
* libquant writes for `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's own
@@ -9200,10 +9549,10 @@ static void ar_worker(ArThread* t) {
st_free(out);
}
static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_2rank_exact");
if (!row) { ok("ar_oneshot_2rank_exact", false, "row absent"); return; }
if (devs.size() < 2) { skip("ar_oneshot_2rank_exact (2 ranks)", "fewer than two gfx1201 cards"); return; }
static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
/* 8192 fp32 elements: a whole number of 16-byte pushes and small enough that the handshake,
* not the link, is what is being exercised. */
@@ -9243,6 +9592,11 @@ static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs) {
* a hang. The sizes give 11, 4 and 7 blocks under the default block rule. */
static const int64_t kArSweepNumel[] = { 65536, 8192, 40000, 65536, 12000, 24576, 65536, 8192 };
constexpr int kArSweepN = (int)(sizeof(kArSweepNumel) / sizeof(kArSweepNumel[0]));
/* The sweep again and again with new values each round, so every slot is reused many times over.
* A reader that is served a slot's previous contents -- a cached line of host memory or of a
* peer's, a flag seen before the bytes behind it -- folds the value of an earlier launch, and every
* launch's value is distinct, so that is a wrong sum and not a lucky one. */
constexpr int kArSweepRounds = 32;
struct ArSweep {
const RadKernelInfo* row;
@@ -9262,7 +9616,7 @@ static void ar_sweep_worker(ArSweep* t) {
};
t->rc_init = t->row->init(ps.data(), (int)ps.size(), t->rank, t->world, &t->inst);
if (t->rc_init != RAD_OK) return;
/* Rank r contributes (r + 1) * (j + 1), so launch j sums to (1 + 2 + .. + world) * (j + 1). */
/* Rank r contributes (r + 1) * v, so a launch with value v sums to (1 + 2 + .. + world) * v. */
const float tri = (float)(t->world * (t->world + 1) / 2);
void* in[kArSweepN] = {};
@@ -9273,40 +9627,45 @@ static void ar_sweep_worker(ArSweep* t) {
t->rc_launch = RAD_E_NOMEM;
return;
}
/* Rank r contributes (r + 1) * (j + 1), so launch j sums to 3 * (j + 1) exactly. */
std::vector<float> h((size_t)kArSweepNumel[j], (float)((t->rank + 1) * (j + 1)));
st_memcpy(in[j], h.data(), bytes, hipMemcpyHostToDevice);
st_memset(out[j], 0, bytes);
}
for (int j = 0; j < kArSweepN && t->rc_launch == RAD_OK; ++j) {
RadTensor ts[2] = { T(in[j], RAD_F32, { kArSweepNumel[j] }),
T(out[j], RAD_F32, { kArSweepNumel[j] }) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts; a.n_t = 2;
a.p = ps.data(); a.n_p = (int)ps.size();
a.instance = t->inst;
a.rank = t->rank;
a.world_size = t->world;
t->rc_launch = t->row->launch(&a, nullptr);
for (int round = 0; round < kArSweepRounds && t->rc_launch == RAD_OK; ++round) {
for (int j = 0; j < kArSweepN; ++j) {
const size_t bytes = (size_t)kArSweepNumel[j] * 4;
const float v = (float)(round * kArSweepN + j + 1);
std::vector<float> h((size_t)kArSweepNumel[j], (float)(t->rank + 1) * v);
st_memcpy(in[j], h.data(), bytes, hipMemcpyHostToDevice);
st_memset(out[j], 0, bytes);
}
for (int j = 0; j < kArSweepN && t->rc_launch == RAD_OK; ++j) {
RadTensor ts[2] = { T(in[j], RAD_F32, { kArSweepNumel[j] }),
T(out[j], RAD_F32, { kArSweepNumel[j] }) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts; a.n_t = 2;
a.p = ps.data(); a.n_p = (int)ps.size();
a.instance = t->inst;
a.rank = t->rank;
a.world_size = t->world;
t->rc_launch = t->row->launch(&a, nullptr);
}
st_stream_sync(nullptr);
for (int j = 0; j < kArSweepN; ++j) {
const float v = (float)(round * kArSweepN + j + 1);
std::vector<float> h((size_t)kArSweepNumel[j]);
st_memcpy(h.data(), out[j], h.size() * 4, hipMemcpyDeviceToHost);
for (float x : h) if (x != tri * v) ++t->bad;
}
}
st_stream_sync(nullptr);
for (int j = 0; j < kArSweepN; ++j) {
std::vector<float> h((size_t)kArSweepNumel[j]);
st_memcpy(h.data(), out[j], h.size() * 4, hipMemcpyDeviceToHost);
for (float v : h) if (v != tri * (float)(j + 1)) ++t->bad;
st_free(in[j]);
st_free(out[j]);
}
}
static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_2rank_exact");
if (!row) { ok("ar_oneshot_2rank_exact", false, "row absent"); return; }
if (devs.size() < 2) {
skip("ar_oneshot_2rank_exact (block counts)", "fewer than two gfx1201 cards");
return;
}
static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] };
std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b);
ta.join();
@@ -9315,8 +9674,8 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs) {
a.rc_init == RAD_OK && b.rc_init == RAD_OK,
"rc " + std::to_string(a.rc_init) + "/" + std::to_string(b.rc_init));
if (a.rc_init != RAD_OK || b.rc_init != RAD_OK) return;
ok("2-rank all-reduce, launches back to back at changing block counts, every sum exact on "
"both ranks",
ok("2-rank all-reduce, 32 rounds of launches back to back at changing block counts, every "
"sum exact on both ranks",
a.rc_launch == RAD_OK && b.rc_launch == RAD_OK && a.bad == 0 && b.bad == 0,
"rc " + std::to_string(a.rc_launch) + "/" + std::to_string(b.rc_launch) + ", " +
std::to_string(a.bad + b.bad) + " elements wrong");
@@ -9369,10 +9728,10 @@ static void gather_worker(ArThread* t) {
st_free(out);
}
static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_gather_2rank");
if (!row) { ok("ar_gather_2rank", false, "row absent"); return; }
if (devs.size() < 2) { skip("ar_gather_2rank (2 ranks)", "fewer than two gfx1201 cards"); return; }
static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 2) { skip(name, "fewer than two gfx1201 cards"); return; }
const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */
ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel };
@@ -9459,10 +9818,10 @@ static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs) {
* the instantiation, the dispatch rows and the entry points agree: a rendezvous of three, a sum of
* 1 + 2 + 3 on every rank bit for bit, the slot parity surviving a block-count sweep, and the
* gather placing three slices in both of its layouts. Skipped, not failed, on fewer cards. */
static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_oneshot_3rank_exact");
if (!row) { ok("ar_oneshot_3rank_exact", false, "row absent"); return; }
if (devs.size() < 3) { skip("ar_oneshot_3rank_exact (3 ranks)", "fewer than three gfx1201 cards"); return; }
static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; }
const int64_t numel = 8192;
ArThread a{ row, 0, devs[0], numel }, b{ row, 1, devs[1], numel }, c{ row, 2, devs[2], numel };
a.world = b.world = c.world = 3;
@@ -9501,7 +9860,7 @@ static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
tz.join();
const bool up = x.rc_init == RAD_OK && y.rc_init == RAD_OK && z.rc_init == RAD_OK &&
x.rc_launch == RAD_OK && y.rc_launch == RAD_OK && z.rc_launch == RAD_OK;
ok("3-rank all-reduce, eight launches at changing block counts on one instance",
ok("3-rank all-reduce, 32 rounds of eight launches at changing block counts on one instance",
up && x.bad == 0 && y.bad == 0 && z.bad == 0,
up ? std::to_string(x.bad + y.bad + z.bad) + " elements wrong"
: "rc " + std::to_string(x.rc_init) + "/" + std::to_string(y.rc_init) + "/" +
@@ -9514,10 +9873,10 @@ static void ar_three_rank(const Plugin& pl, const std::vector<int>& devs) {
}
}
static void gather_three_rank(const Plugin& pl, const std::vector<int>& devs) {
const RadKernelInfo* row = find(pl, "ar_gather_3rank");
if (!row) { ok("ar_gather_3rank", false, "row absent"); return; }
if (devs.size() < 3) { skip("ar_gather_3rank (3 ranks)", "fewer than three gfx1201 cards"); return; }
static void gather_three_rank(const Plugin& pl, const std::vector<int>& devs, const char* name) {
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if (devs.size() < 3) { skip(name, "fewer than three gfx1201 cards"); return; }
const int64_t numel = 8192; /* the sampler's own message at 4 rows and 1024 candidates */
const int W = 3;
/* What each rank sent, rebuilt here rather than read back off the device (gather_two_rank). */
@@ -10347,6 +10706,61 @@ static void device_phase(const Plugin& pl) {
gemm_case(pl, "gemm_w8a8_nt_m64", "w8a8", M, N, K, RAD_I8, 1, 0, 0, N*K, N*(K/128)*2);
gemm_case(pl, "gemm_w2a8_nt", "w2a8", M, N, K, RAD_I8, 1, 1, 0, N*K/4, N*(K/128)*4);
gemm_case(pl, "gemm_mxfp4a8_nt_m64", "mxfp4a8", M, N, K, RAD_F8E4M3, 1, 0, 1, N*K/2, (K/32)*N);
gemm_case(pl, "gemm_mxfp4a8_tiled", "mxfp4a8", 256, 256, K, RAD_F8E4M3, 1, 0, 1, 256*K/2, (K/32)*256);
/* The skinny row is known-good, so it checks the check; the tiled row at both widths, ragged
* in M and N, then at the size where tn=0 crosses over to TN=4. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 40, 272, 640, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0);
/* ...and against the fp8 family's (row, 128) activation grid, which is what an architecture
* feeds them. K = 640 is five blocks and 2560 twenty, so every split-K segment of the
* skinny row and every slab pair of the tiled one crosses block boundaries. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 40, 272, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_nt_m64", 7, 512, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true);
/* K not a multiple of 128: the TN=2 kernel takes the 64-wide slab. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2, true);
/* The decode row over its whole band: the split rule's own choice, then every split and
* slab forced, at both activation grids; N past a 128-column block, K a multiple of 64
* but not 128 (the slab falls back to 64), and DTM 1..4. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, false);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 272, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 40, 400, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 64, 512, 2560, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 5, 1040, 576, 0, true);
mxd_overlap_case(pl);
/* Above 64 rows, every branch of the measured table: 110+ column blocks, 48+, 8 or
* fewer (with a K that is not a multiple of 128, so the slab falls back to 64), a deep K
* on both sides of M=80, and the plain case; then every split and slab forced. */
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 14336, 640, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 128, 6144, 1152, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 100, 1024, 576, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 72, 5120, 6144, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 120, 5120, 6144, 0, true);
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 112, 5120, 2560, 0, false);
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", 1) });
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 24, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", ks == 2 ? 2 : 1) });
/* ...and the one-fragment form (DTM = 1: the register prefetch and 16 B loads) at every
* split, slab and load hint, on both activation grids, N past a column block. */
for (int ks : { 1, 2, 4, 8, 16 })
for (int bk : { 64, 128 })
for (int nt : { 1, 2 }) {
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 8, 400, 2560, 0, true,
{ PI("ks", ks), PI("bk", bk), PI("nt", nt) });
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 13, 272, 1152, 0, false,
{ PI("ks", ks), PI("bk", bk), PI("nt", nt) });
}
gemm_case(pl, "gemm_w4a8_tiled", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
gemm_case(pl, "gemm_w8a8_tiled", "w8a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K, 256*(K/128)*2);
gemm_case(pl, "gemm_w4a8_prefill", "w4a8", 256, 256, K, RAD_I8, 1, 0, 0, 256*K/2, 256*(K/128)*4);
@@ -10842,44 +11256,49 @@ static void device_phase(const Plugin& pl) {
bf16_gemm_numeric(pl, "gemm_bf16_nt_tiled", 300, 1040, 2560);
}
if (sel("ar_oneshot_2rank_exact")) {
if (!g_case) std::printf("\ncross-rank\n");
ar_two_rank(pl, devs);
ar_two_rank_sweep(pl, devs);
}
if (sel("ar_gather_2rank")) {
if (!g_case) std::printf("\ncross-rank\n");
gather_two_rank(pl, devs);
}
/* The wide family at three. Its own rows, so the sweep names them (a row the sweep never
* mentions is reported as a coverage hole) and so `--case ar_oneshot_3rank_exact` reproduces
* one of them alone. */
if (sel("ar_oneshot_3rank_exact")) {
if (!g_case) std::printf("\ncross-rank, three\n");
ar_three_rank(pl, devs);
}
if (sel("ar_gather_3rank")) {
if (!g_case) std::printf("\ncross-rank, three\n");
gather_three_rank(pl, devs);
/* Every collective has a host twin (r4d_rows.cpp): the same kernel with its mailbox in pinned
* host memory. A case is the pair's, so the twin is held to exactly the original's checks. */
for (const char* base : { "ar_oneshot_2rank_exact", "ar_gather_2rank", "ar_oneshot_3rank_exact",
"ar_gather_3rank" }) {
for (const std::string& n : { std::string(base), std::string(base) + "_host" }) {
if (!sel(n.c_str())) continue;
const bool three = std::strstr(base, "3rank") != nullptr;
if (!g_case) std::printf(three ? "\ncross-rank, three\n" : "\ncross-rank\n");
std::printf(" %s\n", n.c_str());
if (!std::strcmp(base, "ar_oneshot_2rank_exact")) {
ar_two_rank(pl, devs, n.c_str());
ar_two_rank_sweep(pl, devs, n.c_str());
} else if (!std::strcmp(base, "ar_gather_2rank")) {
gather_two_rank(pl, devs, n.c_str());
/* The wide family at three. Its own rows, so the sweep names them (a row the sweep
* never mentions is reported as a coverage hole) and so `--case
* ar_oneshot_3rank_exact` reproduces one of them alone. */
} else if (three && std::strstr(base, "gather")) {
gather_three_rank(pl, devs, n.c_str());
} else {
ar_three_rank(pl, devs, n.c_str());
}
}
}
/* The 4- and 8-rank rows cannot be exercised on a two-card box. Reported as skipped rather
* than quietly passing: a row that has never been launched is not a row that works. */
auto skip_pair = [](const char* base, const char* why) {
for (const std::string& n : { std::string(base), std::string(base) + "_host" })
if (sel(n.c_str())) skip(n.c_str(), why);
};
for (const char* n : { "ar_oneshot_4rank_exact", "ar_oneshot_8rank_exact",
"ar_twoshot_4rank_exact", "ar_twoshot_8rank_exact",
"ar_twoshot_4rank_ti8" })
if (sel(n)) skip(n, "needs 4 or 8 peer-accessible cards");
if (sel("ar_oneshot_2rank_wht6"))
skip("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test");
if (sel("ar_ln_had_quant_i8"))
skip("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire");
skip_pair(n, "needs 4 or 8 cards");
skip_pair("ar_oneshot_2rank_wht6", "lossy wire: needs a tolerance harness, not a smoke test");
skip_pair("ar_ln_had_quant_i8", "two-rank fusion: needs the same harness as the wht6 wire");
/* Same reason, and one more: the norm half of it is rmsnorm_quant_fp8's, called through the
* same device function, so what a single-rank harness could check here is already checked
* there. What it cannot check without a peer -- the handshake and the reduced sum -- is what
* the two-rank harness is for. The engine covers it end to end: a decode step issues this op
* at every one of the 128 sites, and the generated text is compared byte for byte against a
* build that issues the pair instead. */
if (sel("ar_rmsnorm_quant_fp8"))
skip("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank");
skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank");
dfree_all();
}
+16
View File
@@ -307,6 +307,22 @@ TEST(the_wire_mode_is_one_of_two_names) {
CHECK_EQ(parse({ "--tp-wire", "EXACT" }, &c), RAD_E_INVAL);
}
TEST(the_p2p_mode_is_one_of_three_names) {
Config c;
CHECK_EQ(c.p2p, RAD_P2P_AUTO);
CHECK_EQ(parse({ "--p2p", "on" }, &c), RAD_OK);
CHECK_EQ(c.p2p, RAD_P2P_ON);
CHECK_EQ(parse({ "--p2p", "off" }, &c), RAD_OK);
CHECK_EQ(c.p2p, RAD_P2P_OFF);
CHECK_EQ(parse({ "--p2p", "auto" }, &c), RAD_OK);
CHECK_EQ(c.p2p, RAD_P2P_AUTO);
/* A name this build does not know stops the server: `on` exists so a deployment measured on
* P2P cannot quietly serve on host memory, and a typo falling through to auto would do that. */
CHECK_EQ(parse({ "--p2p", "yes" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--p2p", "" }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--p2p", "OFF" }, &c), RAD_E_INVAL);
}
TEST(the_kv_cache_dtype_is_one_of_two_names) {
Config c;
CHECK_EQ(parse({ "--kv-cache-dtype", "bf16" }, &c), RAD_OK);
+53
View File
@@ -1141,6 +1141,59 @@ TEST(split_lookup_reuses_attention_between_checkpoints) {
CHECK_EQ(f.pc.lookup(other, {}).n_linear_tokens, 0);
}
/* A CAPPED LOOKUP (HitCap) ends the hit at a block and the linear state at a checkpoint at or
* below the cap, never past it -- unless that gives back more than the cap allows, in which case
* the whole hit stands. The statistics count one lookup either way. */
TEST(a_capped_lookup_lands_on_a_checkpoint_at_or_below_the_cap) {
Fixture f;
CHECK_OK(f.build(/*with_linear=*/true, /*ckpt_slots=*/4));
auto prompt = tok_run(7000, 336);
publish(f, 1, prompt, 320);
BlockHash parent;
std::vector<BlockHash> hs;
for (int b = 0; b < 21; ++b) {
parent = chain_block_hash(parent, prompt.data() + b * 16, 16, nullptr, 0, b * 16);
hs.push_back(parent);
}
int32_t s128 = -1, s256 = -1;
CHECK_OK(f.pc.reserve_checkpoint(1, 128, hs[128 / 16 - 1], &s128));
f.pc.commit_checkpoint(hs[128 / 16 - 1]);
CHECK_OK(f.pc.reserve_checkpoint(1, 256, hs[256 / 16 - 1], &s256));
f.pc.commit_checkpoint(hs[256 / 16 - 1]);
const CacheHit u = f.pc.lookup(prompt, {});
CHECK_EQ(u.n_attn_tokens, 320);
CHECK_EQ(u.n_linear_tokens, 256);
CHECK_EQ(u.given_back, 0);
HitCap cap;
cap.tokens = 250;
cap.max_give_back = 1000;
const int64_t lookups = f.pc.stats().lookups;
const CacheHit c = f.pc.lookup(prompt, {}, nullptr, &cap);
CHECK_EQ(f.pc.stats().lookups, lookups + 1);
CHECK_EQ(c.n_attn_tokens, 240);
CHECK_EQ(c.n_linear_tokens, 128);
CHECK_EQ(c.checkpoint_slot, s128);
CHECK_EQ(c.given_back, 128); /* 256 reusable before, 128 after */
cap.tokens = 100; /* below every checkpoint: all 256 go back */
const CacheHit z = f.pc.lookup(prompt, {}, nullptr, &cap);
CHECK_EQ(z.n_attn_tokens, 96);
CHECK_EQ(z.n_linear_tokens, 0);
CHECK_EQ(z.checkpoint_slot, -1);
CHECK_EQ(z.given_back, 256);
cap.max_give_back = 255; /* ...which is more than this cap allows */
const CacheHit w = f.pc.lookup(prompt, {}, nullptr, &cap);
CHECK_EQ(w.n_attn_tokens, 320);
CHECK_EQ(w.n_linear_tokens, 256);
CHECK_EQ(w.given_back, 0);
cap.tokens = 100000; /* a cap above the hit changes nothing */
CHECK_EQ(f.pc.lookup(prompt, {}, nullptr, &cap).n_attn_tokens, 320);
}
/* The chained block hashes of `tokens`, one a block, as the cache computes them. */
static std::vector<BlockHash> chain_of(const std::vector<int32_t>& tokens, int bs) {
std::vector<BlockHash> hs;
+105 -9
View File
@@ -359,14 +359,35 @@ struct FakePC : IPrefixCache {
}
mutable int64_t lookups = 0;
CacheHit lookup(const Request&, std::vector<std::vector<int32_t>>* out) const override {
/* A cap (HitCap) as prefix.cpp applies one: attention ends at a block at or below it, the
* linear state at the deepest checkpoint under that -- checkpoints at multiples of `interval`,
* none below `ckpt_lo` -- and the whole hit stands if that gives back too much. */
int64_t ckpt_lo = 0;
CacheHit lookup(const Request&, std::vector<std::vector<int32_t>>* out,
const HitCap* cap) const override {
++lookups;
if (out) {
out->resize(groups.size());
for (size_t i = 0; i < groups.size() && i < seeded.size(); ++i)
(*out)[i] = seeded[i];
}
return CacheHit{ attn, lin, src };
CacheHit h{ attn, lin, src };
const int64_t whole = src >= 0 ? lin : 0;
if (cap && attn > cap->tokens / 16 * 16 && whole > cap->tokens) {
const int64_t a = cap->tokens / 16 * 16;
int64_t l = std::min<int64_t>(lin, a) / interval * interval;
if (l < ckpt_lo) l = 0;
if (whole - l <= cap->max_give_back) {
h.n_attn_tokens = (int32_t)a;
h.n_linear_tokens = (int32_t)l;
h.checkpoint_slot = l > 0 ? src : -1;
h.given_back = (int32_t)(whole - l);
if (out)
for (auto& b : *out)
if ((int64_t)b.size() > a / 16) b.resize((size_t)(a / 16));
}
}
return h;
}
const std::vector<int32_t>& cached_groups() const override { return groups; }
@@ -462,7 +483,8 @@ struct Fixture {
~Fixture() { sch.fini(); for (void* p : owned) std::free(p); }
void build(int64_t blocks = 4096, int64_t states = 64, int64_t max_tok = 512) {
void build(int64_t blocks = 4096, int64_t states = 64, int64_t max_tok = 512,
int64_t max_ctx = 4096) {
g_gdn_ki = RadKernelInfo{};
g_gdn_ki.name = "gdn_fake";
g_gdn_ki.op = "gdn_chunked";
@@ -513,7 +535,7 @@ struct Fixture {
cfg.max_tok = max_tok;
cfg.max_seqs = 32;
cfg.max_ctx = 4096;
cfg.max_ctx = max_ctx;
cfg.checkpoint_interval = 256;
cfg.prefix_cache = true;
/* `Config::n_spec` defaults to -1, which is `auto`: a REQUEST that engine_bringup resolves
@@ -1208,16 +1230,90 @@ TEST(a_prefix_hit_does_not_stop_a_full_attention_drafter) {
* wrote: there is no hole and the floor is 0. Taking the floor to be the hit position
* instead stops a windowless drafter from ever drafting again after a hit.
*
* THE OTHER SIDE -- a drafter whose group the cache SKIPS must still decline -- is not
* testable here: giving the fixture a second paged group the FakePC does not index makes
* its lookup hand back a block list that does not cover it, so the hit is refused and
* ctx_len is 0 either way. That case needs a windowed drafter over a cache that leaves a
* hole, which this fixture cannot construct. */
* THE OTHER SIDE -- a windowed drafter whose group the cache SKIPS, so a hit leaves a hole
* -- is the draft-refill cases below. */
Scheduler::BlockRow rows[4];
CHECK_EQ(f.sch.block_begin(/*block=*/8, /*depth=*/7, /*window=*/0, /*mask=*/99, rows, 4), 1);
CHECK_EQ((int)rows[0].seq, (int)a);
}
/* ====================================== a prefix hit and a windowed block drafter (draft refill)
* The drafter's own windowed KV group is not prefix-cached, so a hit leaves it without K and V for
* the cached tokens, and block_begin declines the sequence until the window has slid past the hole.
* The scheduler ends such a hit one drafter window before the end of the prompt, at a checkpoint,
* so the recompute covers the window and the drafter drafts from the first decode step. */
namespace {
struct RefillRun {
int64_t n_after_first = 0; /* n_computed after the admitting step */
int rows = -1; /* drafting rows block_begin offers at the first decode step */
SchedMetrics m;
};
RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/512, /*max_ctx=*/8192);
f.cfg.n_spec = 7;
f.prog.drafter.kind = RAD_DRAFT_BLOCK;
f.prog.drafter.window = 512;
KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached */
w.name = "draft";
w.decl.kind = RAD_KV_WINDOW;
w.decl.window = 512;
w.block_size = 16;
f.prog.kv_groups.push_back(w);
f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64);
f.pc.groups = { 0 };
f.pc.ckpt_lo = ckpt_lo;
CHECK_OK(f.start());
if (seeded > 0) { f.pc.seed(seeded); f.pc.lin = seeded; f.pc.src = 3; }
RefillRun r;
const uint64_t a = f.submit(n_prompt, 64);
Scheduler::BlockRow rows[4];
for (int st = 0; st < 40; ++st) {
CHECK(f.sch.step() != nullptr);
if (st == 0) r.n_after_first = f.sch.find(a)->n_computed;
f.commit_plain(11);
const int n = f.sch.block_begin(8, 7, 512, 99, rows, 4);
f.sch.block_end();
if (!f.sch.find(a)->output.empty()) { r.rows = n; break; }
}
r.m = f.sch.metrics();
return r;
}
} /* namespace */
TEST(a_prefix_hit_ends_a_drafter_window_before_the_prompt_and_the_drafter_drafts_at_once) {
const RefillRun r = refill_run(/*prompt=*/1100, /*seeded=*/1024);
/* The cap is 1100 - 512 = 588: attention 576, and the checkpoint under it 512. */
CHECK_EQ(r.n_after_first, 512);
CHECK_EQ(r.rows, 1);
CHECK_EQ(r.m.draft_refills, (int64_t)1);
CHECK_EQ(r.m.draft_refill_tokens, (int64_t)512);
CHECK_EQ(r.m.linear_cached_tokens, (int64_t)512); /* what was actually skipped */
}
TEST(a_prefix_hit_already_a_window_back_is_kept_whole) {
/* 5000 - 512 is past the 1024-token hit: the drafter's window is recomputed anyway. */
const RefillRun r = refill_run(5000, 1024);
CHECK_EQ(r.n_after_first, 1024);
CHECK_EQ(r.m.draft_refills, (int64_t)0);
CHECK_EQ(r.rows, 1);
}
TEST(a_prefix_hit_with_no_checkpoint_near_the_cap_is_kept_whole) {
/* No checkpoint below 2048: the cap would give back all 2048 tokens, more than two windows,
* so the whole hit stands and the drafter waits for its window as it would without a cap. */
const RefillRun r = refill_run(2200, 2048, /*ckpt_lo=*/2048);
CHECK_EQ(r.m.draft_refills, (int64_t)0);
CHECK_EQ(r.m.linear_cached_tokens, (int64_t)2048);
CHECK_EQ(r.rows, 0);
}
TEST(no_prefix_hit_gives_nothing_back) {
const RefillRun r = refill_run(1100, 0);
CHECK_EQ(r.m.draft_refills, (int64_t)0);
CHECK_EQ(r.rows, 1);
}
/* ================================================================== speculation */
TEST(rejection_rolls_back_paged_kv_and_moves_the_linear_read_offset) {
Fixture f;
+34
View File
@@ -258,6 +258,7 @@ struct FakeScheduler : IScheduler {
std::mutex mu;
std::vector<uint64_t> submitted;
SamplingParams last_sp; /* what the last submitted request was to sample with */
std::vector<std::string> last_stop; /* ...and the stop strings it was handed */
std::vector<uint64_t> cancelled;
std::vector<std::thread> workers;
std::atomic<uint64_t> next_id{1};
@@ -275,6 +276,7 @@ struct FakeScheduler : IScheduler {
std::lock_guard<std::mutex> lk(mu);
submitted.push_back(id);
last_sp = r.sp;
last_stop = r.stop;
}
void* sink = r.sink;
int32_t cap = r.max_tokens;
@@ -1797,6 +1799,38 @@ TEST(usage_reports_the_reasoning_tokens_inside_completion_tokens) {
}
}
/* A REPLY THAT STARTS INSIDE ITS REASONING BLOCK keeps its stop strings for the answer: one
* written while thinking is text, and the first one after the closer cuts. The scheduler, which
* cannot tell reasoning from answer, is handed none. A closer of several tokens arrives across
* drains, which the incremental search for it has to bridge. */
TEST(stop_strings_wait_for_the_reasoning_closer) {
for (const char* close : { "|", "</t>" }) {
Fixture f;
f.tmpl.think_close = close;
f.tmpl.think_starts_open = true;
f.sched.reply = std::string("aENDb") + close + "cENDd";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"stop":["END"]})");
CHECK_EQ(r.status, 200);
const json j = json::parse(r.body);
CHECK_EQ(j["choices"][0]["message"]["content"].get<std::string>(),
std::string("aENDb") + close + "c");
CHECK_EQ(j["choices"][0]["finish_reason"].get<std::string>(), std::string("stop"));
CHECK(f.sched.last_stop.empty());
}
/* A stop string only inside the reasoning never stops the reply. */
Fixture f;
f.tmpl.think_close = "|";
f.tmpl.think_starts_open = true;
f.sched.reply = "aENDb|cd";
HttpResponse r = f.post("/v1/chat/completions",
R"({"messages":[{"role":"user","content":"hi"}],"stop":["END"]})");
CHECK_EQ(r.status, 200);
const json j = json::parse(r.body);
CHECK_EQ(j["choices"][0]["message"]["content"].get<std::string>(), std::string("aENDb|cd"));
CHECK(!f.sched.saw_cancel()); /* ended by the reply itself, not cut */
}
/* THE BUDGET REACHES THE ENGINE in either spelling, with the block it is held on; one the block
* cannot hold, a negative one, and two spellings that disagree are 400s naming the field. */
TEST(a_thinking_budget_reaches_the_engine_or_is_refused_by_name) {
+31
View File
@@ -396,6 +396,37 @@ TEST(detokenize_stop_string_straddle) {
CHECK_EQ(d.flush(), std::string());
}
/* A reply that starts inside its reasoning block: a stop string written while thinking is text,
* not a stop, and the first one after the closer cuts as usual. */
TEST(detokenize_stops_wait_for_the_reasoning_closer) {
if (!need_vocab("detokenize_stops_wait_for_the_reasoning_closer")) return;
Tokenizer t;
CHECK_OK(t.init(qwen_vocab()));
const std::string think = "restating it, Q: what is two and two</think>";
std::vector<int32_t> ids;
CHECK_OK(t.encode(think + "The answer is 4. Q: next", ids, false, true));
Detokenizer d(qwen_vocab(), { "Q:" });
d.defer_stops_until("</think>");
std::string s;
for (int32_t id : ids) {
s += d.push(id);
if (d.stopped()) break;
}
CHECK(d.stopped());
CHECK_EQ(d.stop_hit(), std::string("Q:"));
CHECK_EQ(s, think + "The answer is 4. ");
/* Without the deferral the same text stops inside the reasoning. */
Detokenizer plain(qwen_vocab(), { "Q:" });
std::string p;
for (int32_t id : ids) {
p += plain.push(id);
if (plain.stopped()) break;
}
CHECK_EQ(p, std::string("restating it, "));
}
/* A stop string that never completes must be released at flush() rather than swallowed. */
TEST(detokenize_incomplete_stop_is_flushed) {
if (!need_vocab("detokenize_incomplete_stop_is_flushed")) return;
+31 -13
View File
@@ -261,19 +261,37 @@ inline int rad_operand_shapes(const std::string& op, const Geometry& g, int n_op
*
* `a_sum` and `b_ref` belong to the asymmetric-integer and mxfp4 grids and are absent. */
const char* q = g.get_s("dtype");
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
if ((!a8 && !a16) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
const int64_t kb = (K + group - 1) / group;
const int64_t nb = (N + group - 1) / group;
/* a, a_scale */
if (a8) { add((uint32_t)RAD_F8E4M3, {M, K}); add((uint32_t)RAD_F32, {M, kb}); }
else { add((uint32_t)RAD_BF16, {M, K}); skip_opd(); }
add((uint32_t)RAD_F8E4M3, {N, K}); /* b -- the checkpoint's own bytes */
add((uint32_t)RAD_BF16, {nb, kb}); /* b_scale -- weight_scale_inv, one per 128x128 tile */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
skip_opd(); /* b_ref */
/* OCP-MXFP4 is the other grid: e2m1 codes with one E8M0 exponent per 32 of K (`group`
* 32), read against the fp8 family's own activation pair -- E4M3 with an f32 scale per
* (row, 128 of K), which is what LinearFP8 feeds it. The weight operands arrive in libr4d's
* stored layout, and their BYTE COUNTS are what is sized here: the codes are K/2 bytes a
* row in fragment order, the exponents [K/32][N] and the per-row reference [N]. Drawn
* bytes are fine for timing -- the kernel's work does not depend on which exponents it
* folds. */
if (q && std::strcmp(q, "mxfp4a8") == 0) {
if (N <= 0 || K <= 0 || group != 32) return RAD_E_UNSUPPORTED;
add((uint32_t)RAD_F8E4M3, {M, K});
add((uint32_t)RAD_F32, {M, (K + 127) / 128});
add((uint32_t)RAD_U8, {N, K / 2}); /* b -- e2m1 codes, fragment order */
add((uint32_t)RAD_U8, {K / 32, N}); /* b_scale -- E8M0, [K/32][N] */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
add((uint32_t)RAD_U8, {N}); /* b_ref -- the per-row reference */
} else {
const bool a8 = q && std::strcmp(q, "fp8a8") == 0;
const bool a16 = q && std::strcmp(q, "fp8a16") == 0;
if ((!a8 && !a16) || N <= 0 || K <= 0 || group <= 0) return RAD_E_UNSUPPORTED;
const int64_t kb = (K + group - 1) / group;
const int64_t nb = (N + group - 1) / group;
/* a, a_scale */
if (a8) { add((uint32_t)RAD_F8E4M3, {M, K}); add((uint32_t)RAD_F32, {M, kb}); }
else { add((uint32_t)RAD_BF16, {M, K}); skip_opd(); }
add((uint32_t)RAD_F8E4M3, {N, K}); /* b -- the checkpoint's own bytes */
add((uint32_t)RAD_BF16, {nb, kb}); /* b_scale -- weight_scale_inv, one per 128x128 */
add((uint32_t)RAD_BF16, {M, N}); /* y */
skip_opd(); /* a_sum */
skip_opd(); /* b_ref */
}
}
else if (op == "dequant") {
add((uint32_t)RAD_I8, {M, n}); add((uint32_t)RAD_F32, {M, group ? n / group : 1});