Merge main into clef-flash-arch-plugin

This commit is contained in:
Brandon Bertelsen committed 2026-10-28 22:53:52 -04:00
commit d24cf32a13
114 files changed
+26614 -621

No files matched your search

+8
View File
@@ -297,6 +297,14 @@ add_subdirectory(libquant)
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr4d/CMakeLists.txt)
add_subdirectory(libr4d)
endif()
# libr3d: the RDNA3 kernel library, same shape as libr4d and same guard -- device code needs a HIP
# toolchain. It declares itself for `^gfx11` and returns without a target when the build's
# RAD_GPU_TARGETS holds no RDNA3, so a gfx12-only build of this tree does not produce it (and a card
# with no kernel library of its own keeps refusing device-only ops, which is the rule, not a
# regression: docs/PLUGIN.md §10).
if(RAD_HIP_FOUND AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/libr3d/CMakeLists.txt)
add_subdirectory(libr3d)
endif()
# libavx: the production host kernels (x86 SIMD, dispatched by CPU feature), built on every x86-64.
# Not optional: host-placed ops need a kernel other than the oracle (rad_gate_reference_kernels
# refuses libref), and a table too large for the card, such as the n-gram embedding's gather, runs
+4 -1
View File
@@ -1258,7 +1258,10 @@ int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
* encoder.
*
* `enc_kind` (RAD_ENC_*, rad_runtime.h) and `enc_slot`, the media's 1-based number within its kind,
* say where the latents go. The media's shape is the plugin's to accept: rad_arch_encode_geom
* say where the latents go. A latent-upscaled request's keyframes, pinned on the grid its steps
* run on, are encoded at W' x H' before the prompt pass and again at W x H, into the same slots,
* after the VUPSCALE pass and before the first evaluation at W x H; references, in their own grid,
* are encoded once. The media's shape is the plugin's to accept: rad_arch_encode_geom
* (below) refuses what the encoders cannot take, and the step's packed sequence with the encoded
* media in it is the plugin's rad_arch_video_pack.
*
+51 -9
View File
@@ -828,6 +828,17 @@ struct G3Junction {
}
};
/* The tallest step that takes the fp8 junction's lossy twin (G3JunctionFP8::op_ar6); a taller one
* keeps the standalone lossy all-reduce, unfused. The fused kernel gives each block one row, so past
* a few sequences the standalone all-reduce, spread over more blocks, wins despite its extra
* launches. TranslateGemma-27B MXFP4 + DFlash2 at tp 2 on 2x R9700, --tp-wire wht6, production's
* flags (--draft-short-from 8), greedy, aggregate tok/s, two rounds, limit never / 16 / 24 / any:
* 2 streams (16 rows) 350.7 346.2 / 371.8 367.7 / 370.4 367.0 / 357.7 356.0; 3 (24 rows) 455.8
* 451.2 / 455.1 454.2 / 462.8 460.6 / 437.3 436.8; 4 (32 rows) 553.7 553.6 / 557.9 554.2 / 553.9
* 560.2 / 521.0 523.0; 8 (32 rows, the short block) 717.4 718.0 / 717.2 720.5 / 716.7 720.8 /
* 662.4 661.9. One stream's 8 rows go out exact under the default --tp-wire-min-kb (op_ar). */
constexpr int64_t kAr6MaxRows = 24;
/* ---- the MXFP4 trunk's junction (libr4d `rmsnorm_quant_fp8`): the add of the branch `x` into
* the stream `res`, the next block's norm and its E4M3 quantiser, in one op. It has no post-norm
* slot (rmsnorm_quant_i8's w_post is Gemma 4's), so the branch's post-norm runs just before it:
@@ -836,18 +847,20 @@ struct G3Junction {
struct G3JunctionFP8 {
rad_op op = 0;
/* At two ranks: the branch's all-reduce and post-norm folded in front
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. The kernel
* sends the exact wire only, so under --tp-wire it is declared all the same and taken by the
* steps whose message goes out exact anyway (ar_wire_is_exact: a decode step of a few rows,
* under --tp-wire-min-kb); a wider step keeps the lossy all-reduce, unfused. */
rad_op op_ar = 0;
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. `op_ar` sends
* the exact wire, taken by the steps whose message goes out exact (ar_wire_is_exact: a decode
* step of a few rows, under --tp-wire-min-kb); `op_ar6` the rotated 6-bit one, declared under a
* lossy --tp-wire and taken by the steps above that up to kAr6MaxRows, byte-identical to the
* standalone lossy all-reduce, rmsnorm and rmsnorm_quant_fp8 it replaces. */
rad_op op_ar = 0, op_ar6 = 0;
Geom gm{};
rad_buf x = 0, res = 0, q = 0, s = 0;
rad_weight w = 0, wp = 0;
int64_t n = 0;
int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_,
const G3Linear& into, rad_weight wp_ = 0) {
x = x_; res = res_; w = w_; wp = wp_; q = into.q8; s = into.s8; n = g.n_embd;
x = x_; res = res_; w = w_; wp = wp_; q = into.q8; s = into.s8; n = g.n_embd; gm = g;
if (!into.mx || into.shared_in || !q || !s || !w) return RAD_E_INVAL;
if (!rad_op_declared(b, "rmsnorm_quant_fp8")) return RAD_OK;
op = RAD_OP(b, "rmsnorm_quant_fp8",
@@ -870,14 +883,33 @@ struct G3JunctionFP8 {
const rad_buf wa[4] = { x, q, s, res };
rad_op_reads (b, op_ar, rd, 2);
rad_op_writes(b, op_ar, wa, 4);
/* The lossy twin where that wire is reachable and the row is whole 64-element
* groups (the kernel pads a partial last 512-element chunk). */
if (!g.wire_exact && n % 64 == 0) {
const RadParam p6[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n),
RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK),
RAD_INT("world_size", g.world), RAD_STR("dtype", g.dtype),
RAD_F64("wadd", g.wadd), RAD_INT("wire", 6) };
op_ar6 = rad_decl_op(b, "ar_rmsnorm_post_quant_fp8", p6,
(int)(sizeof p6 / sizeof p6[0]), ws, 2);
if (op_ar6) {
rad_op_reads (b, op_ar6, rd, 2);
rad_op_writes(b, op_ar6, wa, 4);
}
}
}
}
return RAD_OK;
}
/* The fused op for a T-row step's wire, or 0 when its all-reduce stays standalone. */
rad_op ar_op(int64_t T) const {
if (op_ar && ar_wire_is_exact(gm, T)) return op_ar;
return T <= kAr6MaxRows ? op_ar6 : 0;
}
/* x, residual?, w -> q, scale, out_bf16?[, w_post]: the bf16 normed copy is not wanted. */
void step(RadCtx* c, int64_t T, bool with_ar = false) const {
if (with_ar)
RAD_ISSUE_N(c, op_ar, T, brows(x, T), brows(res, T), RAD_W(w), brows(q, T), brows(s, T),
RAD_ISSUE_N(c, ar_op(T), T, brows(x, T), brows(res, T), RAD_W(w), brows(q, T), brows(s, T),
RAD_NONE, RAD_W(wp));
else
RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w),
@@ -935,6 +967,7 @@ struct Model {
G3JunctionFP8 jf0{};
bool fuse_mx = false; /* the MXFP4 trunk's junctions (G3JunctionFP8) */
bool fuse_mx_ar = false; /* ... each with the all-reduce and post-norm folded in */
bool fuse_mx_ar6 = false; /* ... on the lossy wire too (G3JunctionFP8::op_ar6) */
bool fuse_ar = false;
/* The DFlash2 drafter and the trunk taps it reads, only when the container carries one and
@@ -1346,6 +1379,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
ar = lay.jf_am.op_ar != 0 && (l + 1 >= g.n_layer || lay.jf_ma.op_ar != 0);
}
m.fuse_mx_ar = ar;
bool ar6 = ar;
for (int64_t l = 0; ar6 && l < g.n_layer; ++l) {
const Layer& lay = m.layers[(size_t)l];
ar6 = lay.jf_am.op_ar6 != 0 && (l + 1 >= g.n_layer || lay.jf_ma.op_ar6 != 0);
}
m.fuse_mx_ar6 = ar6;
}
/* ---- the weight reads beside the decode all-reduces, at more than one rank;
* --weight-prefetch off declares none. */
@@ -1674,8 +1713,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
for (size_t li = 0; li < m.layers.size(); ++li) {
const Layer& l = m.layers[li];
const bool last = li + 1 == m.layers.size();
/* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */
const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T);
/* Per step: the fused junction takes the step's all-reduce on the exact wire
* (G3JunctionFP8::op_ar), and on the lossy one up to kAr6MaxRows where every junction
* declared its twin (op_ar6). */
const bool far = m.fuse_mx_ar &&
(ar_wire_is_exact(m.g, T) || (m.fuse_mx_ar6 && T <= kAr6MaxRows));
l.attn.step(c, batch, true, true, far);
prefetch_beside(c, l.op_pf_gu, l.pf_gu_w, pf_h);
if (!far) l.attn.post(c, T);
+52
View File
@@ -167,6 +167,11 @@ static const Flag g_flags[] = {
" one, for each of --max-num-seqs, within an eighth of host\n"
" memory. N fixes the total; 0 keeps none" },
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
{ "--prefix-resume", "MODE", "where a prefix hit resumes: exact (default) only where\n"
" an idle server's cold prefill of the prompt starts a\n"
" chunk, so the hit answers bit-identically to a cold run;\n"
" nearest at the deepest snapshot, up to a chunk less to\n"
" re-prefill" },
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
"(default), tip-only, keep-all" },
@@ -298,6 +303,18 @@ static const Flag g_flags[] = {
" mixed steps and draft-head passes, and write the counts to FILE as\n"
" JSON every 30 s and at shutdown. From the routing histograms the core\n"
" already copies back: no device work, no synchronisation" },
{ "--expert-profile", "FILE", "rank the expert plane by this radiance-expert-stats JSON's `decode`\n"
" counts instead of the container's activation profile, which is\n"
" prefill-heavy: decode-hot experts differ. The planner keeps the\n"
" hottest resident; --expert-pin-top makes a chosen slice unmovable" },
{ "--expert-pin-top", "F", "pin the hottest fraction F of the routed experts (0 < F <= 1) by\n"
" --expert-profile's share: heat never demotes them, so the decode-hot\n"
" set stays resident while the rest streams. 0 is off" },
{ "--draft-expert-placement", "PLACEMENT", "where a draft head's (MTP/DSpark) routed experts live.\n"
" `host` pins them in the host pool before any strategy runs, read in\n"
" place like a pooled expert: the drafter's experts fit beside a trunk\n"
" that already fills the card, instead of the strategy having to make\n"
" room on the card. `auto` (the default) leaves them to the strategy" },
{ "--live", nullptr, "the live view: cards, throughput, draft acceptance, the expert plane.\n"
" Redirected it prints one greppable key=value line instead" },
{ "-v", nullptr, "verbose" },
@@ -670,6 +687,15 @@ int config_parse(int argc, char** argv, Config* c) {
}
}
else if (S("--no-prefix-cache")) c->prefix_cache = false;
else if (S("--prefix-resume")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "exact")) c->prefix_exact = true;
else if (!std::strcmp(v, "nearest")) c->prefix_exact = false;
else {
RAD_ERR("--prefix-resume '%s' is not one of exact, nearest", v);
return RAD_E_INVAL;
}
}
else if (S("--checkpoint-policy")) {
if (!(v = need(i))) return RAD_E_INVAL;
/* Validated, so an unknown name does not silently fall back to the default. */
@@ -914,6 +940,27 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true;
else if (S("--profile-ops")) c->profile_ops = true;
else if (S("--expert-stats")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_stats = v; }
else if (S("--expert-profile")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_profile = v; c->expert_profile_given = true; }
else if (S("--expert-pin-top")) {
if (!(v = need(i))) return RAD_E_INVAL;
char* e = nullptr;
const double d = strtod(v, &e);
if (e == v || *e != '\0' || d < 0.0 || d > 1.0) {
RAD_ERR("--expert-pin-top: '%s' is not a fraction in [0, 1]", v);
return RAD_E_INVAL;
}
c->expert_pin_top = (float)d;
c->expert_pin_top_given = true;
}
else if (S("--draft-expert-placement")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (std::strcmp(v, "auto") != 0 && std::strcmp(v, "host") != 0) {
RAD_ERR("--draft-expert-placement: '%s' is not auto or host", v);
return RAD_E_INVAL;
}
c->draft_expert_placement = v;
c->draft_expert_placement_given = true;
}
else if (S("--live")) c->live_view = true;
else {
RAD_ERR("unknown option '%s'", a.c_str());
@@ -1149,6 +1196,8 @@ const ShowRow kShow[] = {
return c.checkpoint_slots < 0 ? std::string("auto") : num(c.checkpoint_slots); } },
{ "--no-prefix-cache", [](const Config& c) {
return std::string(c.prefix_cache ? "not given: prefix caching on" : "prefix caching off"); } },
{ "--prefix-resume", [](const Config& c) {
return std::string(c.prefix_exact ? "exact" : "nearest"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
@@ -1235,6 +1284,9 @@ const ShowRow kShow[] = {
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
{ "--expert-stats", [](const Config& c) { return or_none(c.expert_stats, "off"); } },
{ "--expert-profile", [](const Config& c) { return or_none(c.expert_profile, "off"); } },
{ "--expert-pin-top", [](const Config& c) { return fmt("%.4g", c.expert_pin_top); } },
{ "--draft-expert-placement", [](const Config& c) { return c.draft_expert_placement; } },
{ "--live", [](const Config& c) { return onoff(c.live_view); } },
{ "-v", [](const Config& c) { return onoff(c.given.count("-v") > 0); } },
{ "-vv", [](const Config& c) { return onoff(c.given.count("-vv") > 0); } },
+1
View File
@@ -109,6 +109,7 @@ struct HostFacts {
std::string io_uring; /* available | refused (why) | unknown */
std::string cpu_governor, cpu_epp, cpu_driver;
std::string runtime; /* the device runtime's version, "" for none */
std::string media; /* "libavformat <v>" / "absent (built without libav*)" */
};
struct Facts {
+3
View File
@@ -89,6 +89,8 @@ std::string host_lines(const HostFacts& h, const RunFacts& r) {
o += fmt(" runtime %s | backend %s\n",
h.runtime.empty() ? "no device runtime" : h.runtime.c_str(),
r.host_backend ? "host (CPU)" : "device");
if (!h.media.empty())
o += fmt(" media decoders %s\n", h.media.c_str());
return o;
}
@@ -224,6 +226,7 @@ std::string to_json(const std::vector<ConfigRow>& config, const std::vector<Deci
host["cpu_epp"] = h.cpu_epp;
host["cpu_driver"] = h.cpu_driver;
host["runtime"] = h.runtime;
host["media"] = h.media;
J cards = J::array();
for (const CardFacts& c : f.cards) {
J e;
+2 -2
View File
@@ -1818,8 +1818,8 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
ranks_[0]->tierx.report_pass(jobs, ok, rad_mono_ns());
/* Rebind every entry that came back, not only the leading run: the tiers already
* marked each resident at its new blocks. */
const std::vector<int32_t>& cg = pc.cached_groups();
* marked each resident at its new blocks. A job's blocks are one per entry slot. */
const std::vector<int32_t>& cg = pc.entry_groups();
for (size_t i = 0; i < jobs.size(); ++i) {
TierJob& j = jobs[i];
if (!ok[i]) { res = RestoreResult::Cut; continue; }
+3
View File
@@ -241,6 +241,9 @@ private:
std::vector<TableCopy> table_copies_;
std::vector<void*> card_copies_;
std::vector<std::pair<const void*, void*>> table_copy_of_;
/* --expert-profile: the decode ranking loaded once, before any rank plans, and handed to every
* rank's planner in place of the container's activation profile. */
std::vector<RadFileProfile> expert_profile_;
int load_weights();
int configure_kv();
/* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */
+68 -9
View File
@@ -37,6 +37,7 @@
#include <cstring>
#include <fstream>
#include <numeric>
#include <sstream>
#include <cstdint>
#include <cstdlib>
@@ -1652,16 +1653,21 @@ int Engine::plan() {
int64_t lazy = r->program.scratch_regions > 1 ? f.queue_bytes : 0;
/* The KV tiers' copy staging, built by TierExec::device_init on the first copy out.
* The cached groups are settled later, so every paged group is counted (an upper
* bound). */
* bound), each with the blocks an entry at the lcm of their block sizes holds
* (PrefixCache::entry_groups). */
if (cfg_.prefix_cache_mib > 0) {
int64_t entry = 0, bs = 0;
int ng = 0;
for (size_t g = 0; g < r->program.kv_groups.size(); ++g) {
const KVGroupPlan* p = probe.plan((int32_t)g);
if (!p || !p->paged() || p->bytes_per_block <= 0) continue;
entry += p->bytes_per_block;
bs = bs > 0 ? std::min<int64_t>(bs, p->block_size) : p->block_size;
++ng;
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
bs = bs > 0 ? std::lcm<int64_t>(bs, p->block_size) : p->block_size;
}
for (size_t g = 0; g < r->program.kv_groups.size() && bs > 0; ++g) {
const KVGroupPlan* p = probe.plan((int32_t)g);
if (!p || !p->paged() || p->bytes_per_block <= 0 || p->block_size <= 0) continue;
entry += p->bytes_per_block * (bs / p->block_size);
ng += (int)(bs / p->block_size);
}
const int64_t tier = TierExec::device_bytes(entry, ng, TierExec::sizes(entry, ctx, bs));
f.staging += tier;
@@ -1695,6 +1701,39 @@ int Engine::plan() {
for (VramFacts& f : facts) f.held_out = cvec_bytes;
RAD_TRY(resolve_table_placement(facts, emb_bytes, wfs, kv_floor, ngram_bytes,
ngram_device, ngram_host, ck_store + host_arenas));
/* --draft-expert-placement host: the drafter's experts are pinned in the host pool before
* the strategy runs, so they are not part of the elastic plane the card must hold and the
* pool must have room for them on top of the trunk's spill. Growing the pool here, before
* the split, is what lets a drafter fit beside a trunk that already fills the card. */
if (cfg_.draft_expert_placement == "host") {
const int64_t MiB = (int64_t)1 << 20;
int64_t draft_max = 0;
for (const WeightFootprint& wf : wfs) draft_max = std::max(draft_max, wf.draft_experts);
if (draft_max == 0 && cfg_.draft_expert_placement_given) {
RAD_ERR("--draft-expert-placement host: this model declares no draft head with "
"routed experts");
return RAD_E_INVAL;
}
if (draft_max > 0) {
/* The pool must hold the drafter on top of the trunk's own spill, so it grows by
* the drafter's bytes and the floor is recomputed against that larger room with
* the drafter taken out of the plane the card places. */
const int64_t add = (align_up(draft_max, MiB) + MiB - 1) / MiB;
cfg_.host_pool_mib += add;
for (size_t i = 0; i < facts.size(); ++i) {
int64_t room = cfg_.host_pool_mib * MiB;
if (cfg_.weights_disk_tier)
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
facts[i].expert_floor = expert_vram_floor_draft_hosted(
wfs[i], std::max<int64_t>(room - align_up(wfs[i].draft_experts, MiB), 0));
facts[i].experts = std::max<int64_t>(wfs[i].experts - wfs[i].draft_experts, 0);
}
RAD_INFO("placement: --draft-expert-placement host pins %s of drafter experts a "
"rank in the host pool; --host-pool-mib grows by %lld to hold them, and "
"the card places only the trunk's experts",
humanb(draft_max).c_str(), (long long)add);
}
}
/* The n-gram table was counted off the card; on it, every rank holds the whole table. */
if (cfg_.ngram_resolved == TablePlacement::Vram)
for (VramFacts& f : facts) f.statics += ngram_bytes;
@@ -1843,6 +1882,20 @@ int Engine::plan() {
in.profile = file_->profile();
in.n_profile = (int64_t)file_->header().prof_count;
}
/* --expert-profile replaces the container's activation profile, which is prefill-heavy:
* decode-hot experts differ, and the pin below keeps them resident. Loaded once, before
* any rank plans, so every rank ranks the same way. */
if (!cfg_.expert_profile.empty()) {
if (expert_profile_.empty() && ri == 0) {
int32_t trunk = -1;
const int pr = xs_profile_load(cfg_.expert_profile, &expert_profile_, &trunk);
if (pr < 0) return pr;
}
if (!expert_profile_.empty()) {
in.profile = expert_profile_.data();
in.n_profile = (int64_t)expert_profile_.size();
}
}
in.container = file_ != nullptr;
in.host_backend = device_is_host();
Planner planner(in);
@@ -1864,7 +1917,8 @@ int Engine::plan() {
humanb(r->plan.totals.bytes[(int)Tier::Mapped]).c_str()),
r->plan.forced_host_used > 0
? fmt("the host pool holds the %s the placement flags put there (the token "
"embedding, the encoder towers) beside the weights placed in it",
"embedding, the encoder towers, the drafter's experts) beside the "
"weights placed in it",
humanb(r->plan.forced_host_used).c_str())
: std::string());
}
@@ -3184,8 +3238,11 @@ int Engine::configure_kv() {
shard_off[i] = slot;
slot += ranks_[i]->kv.checkpoint_bytes();
}
/* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */
const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state";
/* A slot holds linear state, a trunk's window (KVGroupPlan::win_snap), or both. */
bool linear = false;
for (const KVGroupPlan& p : ranks_[0]->kv.plans()) linear = linear || p.stateful();
const char* what = !ranks_[0]->kv.has_window_snapshot() ? "linear-state"
: linear ? "linear-state + sliding-window" : "sliding-window";
const bool sized_auto = cfg_.checkpoint_slots < 0;
if (sized_auto) RAD_TRY(size_checkpoint_store(slot, what));
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
@@ -3235,7 +3292,9 @@ int Engine::configure_kv() {
* sessions view reads. The flags gate only the mover, below. */
{
const bool tier_asked = cfg_.prefix_cache_mib > 0;
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
/* An entry's blocks, one group per block: a cached group whose blocks are shorter than
* the entry appears once for each of its blocks (PrefixCache::entry_groups). */
const std::vector<int32_t>& cg = ranks_[0]->prefix.entry_groups();
/* One slot holds the whole engine's entry: the groups every rank holds alike
* (rad_kv_group_replicated) once, at the front, then every rank's own shard in its own
* window. Shards can differ or be empty (uneven heads, rad_kv_group_zero). The layout is
+2
View File
@@ -6,6 +6,7 @@
*/
#include "engine_priv.h"
#include "device/device.h"
#include "mm/media.h"
#include <algorithm>
@@ -37,6 +38,7 @@ diag::Facts Engine::hardware_facts(bool serving) const {
if (r->device == id.device) mine.push_back(id.bdf);
diag::Facts f = diag::collect("", serving ? &mine : nullptr);
f.host.runtime = runtime_version_;
f.host.media = mm::decoder_version();
if (probed_) {
f.host.memlock_soft = memlock_soft_;
f.host.io_uring = io_uring_;
+46
View File
@@ -1,5 +1,6 @@
/* checkpoint.cpp -- see checkpoint.h. */
#include "checkpoint.h"
#include "ggml_planes.h"
#include "rad_plugin.h"
#include <nlohmann/json.hpp>
@@ -2499,6 +2500,26 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
if (dt == RAD_DT_INVALID) {
out->why = std::string("'") + p0.name + "' is a GGUF " +
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
/* Q8_0, Q4_K and Q6_K become their planes when every piece is of that type and they join
* along rows, so each row of the weight is one source row of blocks; the loader still
* refuses them, since the blocks interleave what the planes hold apart. */
bool one_type = true;
for (const SrcTensor* pk : out->pieces) one_type = one_type && pk->ggml == p0.ggml;
RadEncoding enc;
if (!one_type) {
out->why = "its GGUF pieces are of different block types";
} else if (ggml_plane_encoding(p0.ggml, &enc)) {
if (out->pieces.size() > 1 && (d != 0 || out->rank < 2)) {
out->why = "its GGUF pieces are joined along a column, across their blocks";
} else {
out->imported = true;
out->ggml_blocks = true;
out->enc = enc;
out->why = std::string("it is a GGUF ") + gguf_dtype(p0.ggml)->name +
" tensor, which rad-convert imports as its planes -- serve the "
"container it writes";
}
}
} else if (!same) {
out->why = "its pieces are stored in different dtypes";
} else if (p0.pbits) {
@@ -3395,6 +3416,31 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
}
return RAD_OK;
}
if (w.ggml_blocks) {
/* GGUF blocks, split one row at a time into every plane's row: a call pays the whole row
* for the one plane it keeps, and rad-convert asks plane by plane. */
int64_t at[RAD_ENC_MAX_PLANES + 1] = { 0 };
for (int i = 0; i < w.enc.n_planes; ++i) {
int64_t qr = 0, qc = 0;
rad_enc_plane_dims(&w.enc.plane[i], 1, w.cols, &qr, &qc);
at[i + 1] = at[i] + rad_enc_row_bytes(w.enc.plane[i].dtype, qc);
}
std::vector<uint8_t> split((size_t)at[w.enc.n_planes]);
uint8_t* row[RAD_ENC_MAX_PLANES] = { nullptr };
for (int i = 0; i < w.enc.n_planes; ++i) row[i] = split.data() + at[i];
int64_t base = 0;
for (const SrcTensor* piece : w.pieces) {
const int64_t prows = piece->numel() / w.cols, rb = piece->bytes / prows;
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + prows); ++r) {
ggml_plane_row(piece->ggml, (const uint8_t*)piece->data + (r - base) * rb, w.cols,
row);
std::memcpy(o, row[k], (size_t)(at[k + 1] - at[k]));
o += at[k + 1] - at[k];
}
base += prows;
}
return RAD_OK;
}
if (k == 0) {
/* Codes: the pieces joined, bytes as stored. Sub-byte codes (MXFP4) join along rows of even
* width, so every run is byte-aligned. */
+3
View File
@@ -282,6 +282,9 @@ struct CkptWeight {
* from `pq_meta`. */
bool paro = false;
std::vector<const SrcTensor*> pq_pairs, pq_theta, pq_scale, pq_meta;
/* GGUF Q8_0, Q4_K or Q6_K blocks (also `imported`): ckpt_plane_rows splits each row's blocks
* into the planes of `enc` (ggml_planes.h), and ckpt_rows_f32 dequantises them. */
bool ggml_blocks = false;
/* A weight-normalised tensor (RAD_MAP_WNORM): `pieces` is its direction v alone, and every
* element of v with first index i reads times wnorm_scale[i] = g_i / ||v_i||. Not trivial
* (the values change), so a recipe rule stores it. */
+191
View File
@@ -0,0 +1,191 @@
/* ggml_planes.h -- llama.cpp's Q8_0, Q4_K and Q6_K blocks as the affine planes libquant/lq_ggml.cpp
* writes them, for reading a GGUF without a recipe. The core cannot call libquant, so this is the
* reader's copy; quant_ggml_test holds the two to the same encoding, and checkpoint_test decodes
* the planes against the block definition.
*
* The planes are bit for bit what lq_ggml's unpack_<type> writes from the same blocks (its header
* lists them), so a container holds the same numbers whichever way a GGUF reached it. The blocks
* are read as raw bytes at their GGUF offsets, so no struct layout is assumed, and gguf_dtype gives
* their size.
*/
#pragma once
#include "rad_encoding.h"
#include "../text/gguf.h"
#include <cstdint>
#include <cstring>
namespace rad {
namespace ggml_planes {
constexpr int kQK8_0 = 32, kQK_K = 256;
/* Writes a plane row front to back, `bits` per element, lowest bits first (rad_encoding.h's bit
* stream). 32 bits go out at a time and the tail on flush(), so each byte is stored exactly once
* and never read back; this does not rely on the row arriving zeroed. */
class Bits {
public:
explicit Bits(uint8_t* row) : p_(row) {}
void put(uint32_t v, int bits) {
acc_ |= (uint64_t)(v & ((1u << bits) - 1u)) << n_;
n_ += bits;
if (n_ >= 32) {
p_[0] = (uint8_t)acc_;
p_[1] = (uint8_t)(acc_ >> 8);
p_[2] = (uint8_t)(acc_ >> 16);
p_[3] = (uint8_t)(acc_ >> 24);
p_ += 4;
acc_ >>= 32;
n_ -= 32;
}
}
void flush() {
for (; n_ > 0; n_ -= 8, acc_ >>= 8) *p_++ = (uint8_t)acc_;
n_ = 0;
}
private:
uint8_t* p_;
uint64_t acc_ = 0;
int n_ = 0;
};
/* Element i of a 16-bit plane row: an f16 super-scale's two bytes as the block holds them. */
inline void copy16(uint8_t* row, int64_t i, const uint8_t* half) {
row[2 * i] = half[0];
row[2 * i + 1] = half[1];
}
/* Two 4-bit codes per byte, element 2k low; q[] holds a block's codes in value order. */
inline void put_nibbles(uint8_t* row, const uint8_t* q, int n) {
for (int k = 0; k < n / 2; ++k)
row[k] = (uint8_t)((q[2 * k] & 15) | ((q[2 * k + 1] & 15) << 4));
}
/* Q4_K: value v is a nibble of qs[32*(v/64) + v%32], the low one for the first 32 of each 64. The
* 6-bit scale and min of sub-block j are get_scale_min_k4's. */
inline uint32_t k_low4(const uint8_t* qs, int v) {
const uint8_t q = qs[32 * (v / 64) + v % 32];
return (uint32_t)((v % 64) < 32 ? q & 15 : q >> 4);
}
inline void k4_scale_min(int j, const uint8_t* q, uint32_t* d, uint32_t* m) {
if (j < 4) {
*d = q[j] & 63u;
*m = q[j + 4] & 63u;
} else {
*d = (q[j + 4] & 0xFu) | ((uint32_t)(q[j - 4] >> 6) << 4);
*m = (uint32_t)(q[j + 4] >> 4) | ((uint32_t)(q[j] >> 6) << 4);
}
}
/* block_q8_0: d f16 @0, qs i8[32] @2. */
inline void split_q8_0(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
std::memcpy(row[0] + kQK8_0 * i, b + 2, kQK8_0);
copy16(row[1], i, b);
}
}
/* block_q4_K: d f16 @0, dmin f16 @2, scales u8[12] @4, qs u8[128] @16. */
inline void split_q4_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
Bits s(row[1]), m(row[3]);
uint8_t q[kQK_K];
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
for (int k = 0; k < kQK_K; ++k) q[k] = (uint8_t)k_low4(b + 16, k);
put_nibbles(row[0] + (kQK_K / 2) * i, q, kQK_K);
for (int j = 0; j < kQK_K / 32; ++j) {
uint32_t sc, mn;
k4_scale_min(j, b + 4, &sc, &mn);
s.put(sc, 6);
m.put(mn, 6);
}
copy16(row[2], i, b);
copy16(row[4], i, b + 2);
}
s.flush();
m.flush();
}
/* block_q6_K: ql u8[128] @0, qh u8[64] @128, scales i8[16] @192, d f16 @208. In each 128 values,
* quarter t of 32 takes its low four bits from ql[64n + l (+32 for odd t)] (the high nibble for
* t >= 2) and its top two from bits 2t of qh[32n + l]. */
inline void split_q6_K(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row) {
Bits c(row[0]);
for (int64_t i = 0; i < nb; ++i) {
const uint8_t* b = blocks + bb * i;
const uint8_t *ql = b, *qh = b + 128;
for (int k = 0; k < kQK_K; ++k) {
const int n = k / 128, t = (k % 128) / 32, l = k % 32;
const uint8_t lo = ql[64 * n + l + 32 * (t & 1)];
const uint32_t q = (uint32_t)(t < 2 ? lo & 15 : lo >> 4) |
(uint32_t)((qh[32 * n + l] >> (2 * t)) & 3) << 4;
c.put(q - 32u, 6);
}
std::memcpy(row[1] + (kQK_K / 16) * i, b + 192, kQK_K / 16);
copy16(row[2], i, b + 208);
}
c.flush();
}
/* A plane as lq_ggml's encoding_of lists it: one row high, `block` values wide. */
struct Plane {
const char* role;
uint32_t dtype;
int64_t block;
};
/* A block type this header splits: ggml's type number, its planes in encoding order (the rest
* empty), and the split of a row's `nb` blocks of `bb` bytes into one row of each. */
struct Type {
uint32_t ggml;
Plane planes[RAD_ENC_MAX_PLANES];
void (*split)(const uint8_t* blocks, int64_t nb, size_t bb, uint8_t* const* row);
};
inline constexpr Type kTypes[] = {
{ 8, { { "codes", RAD_I8, 1 }, { "scale", RAD_F16, 32 } }, split_q8_0 },
{ 12,
{ { "codes", RAD_U4, 1 }, { "scale", RAD_U6, 32 }, { "scale.1", RAD_F16, 256 },
{ "min", RAD_U6, 32 }, { "min.1", RAD_F16, 256 } },
split_q4_K },
{ 14, { { "codes", RAD_I6, 1 }, { "scale", RAD_I8, 16 }, { "scale.1", RAD_F16, 256 } },
split_q6_K },
};
inline const Type* type_of(uint32_t ggml_type) {
for (const Type& t : kTypes)
if (t.ggml == ggml_type) return &t;
return nullptr;
}
} /* namespace ggml_planes */
/* The encoding a GGUF block type is read as, plane for plane as lq_ggml's encoding_of lists it.
* False for a type this header does not split. */
inline bool ggml_plane_encoding(uint32_t ggml_type, RadEncoding* e) {
const ggml_planes::Type* t = ggml_planes::type_of(ggml_type);
if (!t) return false;
rad_enc_clear(e);
rad_enc_copy_str(e->scheme, "affine");
for (const ggml_planes::Plane& p : t->planes) {
if (!p.role) break;
rad_enc_add_plane(e, p.role, p.dtype, 1, p.block);
}
return true;
}
/* One row of `cols` values held as GGUF blocks, split into one row of every plane of
* ggml_plane_encoding's encoding: plane i's row goes to row[i], sized rad_enc_plane_dims and
* rad_enc_row_bytes give for a one-row weight. `cols` is a whole number of blocks, and the type one
* ggml_plane_encoding accepts. */
inline void ggml_plane_row(uint32_t ggml_type, const uint8_t* blocks, int64_t cols,
uint8_t* const* row) {
const GgufDtype& gd = *gguf_dtype(ggml_type);
ggml_planes::type_of(ggml_type)->split(blocks, cols / gd.blck, gd.block_bytes, row);
}
} /* namespace rad */
+4
View File
@@ -98,6 +98,10 @@ struct VideoRefMedia {
std::vector<float> enc_samples;
int64_t enc_n = 0;
int32_t enc_channels = 0;
/* A keyframe of a latent-upscaled request again at the small size, prepared as at the full
* one: the steps before the upscale pin it on their own grid. Empty otherwise. */
std::vector<float> small_pixels;
int32_t small_h = 0, small_w = 0;
};
struct VideoRequest {
+44 -16
View File
@@ -391,6 +391,7 @@ int VideoDriver::plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::s
};
j.ref_tab.clear();
j.enc_q.clear();
j.enc_pre = 0;
if (r.refs.empty()) return RAD_OK;
if (!pack_ || !enc_geom_)
return no("this model conditions on no reference media");
@@ -466,6 +467,7 @@ int VideoDriver::plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::s
}
j.ref_tab[1] = (int32_t)keys.size() / 3;
j.ref_tab.insert(j.ref_tab.end(), keys.begin(), keys.end());
j.enc_pre = j.enc_q.size();
/* The prompt's vision pads: each picture's tokens, which ComfyUI modulates as video. */
const size_t at = j.ref_tab.size();
j.ref_tab.push_back(0);
@@ -510,6 +512,33 @@ int VideoDriver::lay_out(const RadVideoGeom& g, const std::vector<int32_t>& tab,
return RAD_OK;
}
/* An upscaled request's keyframes, pinned on the grid its steps run on: encoded at the small size
* before the prompt, then at the full size into the same slots once the upscale is done. */
int VideoDriver::plan_small_keys(Job& j, const VideoRequest& r, std::string* why) const {
const RadVideoGenDecl& d = decl_;
std::vector<Job::EncItem> q;
int32_t eg[kEncGeomCap];
for (const Job::EncItem& it : j.enc_q) {
if (it.kind != RAD_ENC_KEYFRAME) continue;
const VideoRefMedia& m = r.refs[(size_t)it.ref];
const int64_t in[4] = { m.enc_frames, m.small_h, m.small_w, 3 };
if (m.small_pixels.size() != (size_t)m.enc_frames * m.small_h * m.small_w * 3 ||
d.enc_ratio < 1 || m.small_h % d.enc_ratio || m.small_w % d.enc_ratio ||
m.small_h / d.enc_ratio != j.geom_small.lat_h ||
m.small_w / d.enc_ratio != j.geom_small.lat_w ||
enc_geom_(RAD_GEN_PASS_VENCODE, in, eg, kEncGeomCap) < 0) {
if (why) *why = "'" + m.name + "' has no picture at the latent upscale's small size "
"the model's encoder takes";
return RAD_E_INVAL;
}
q.push_back({ it.kind, it.slot, it.ref, true });
}
j.enc_pre = q.size();
q.insert(q.end(), j.enc_q.begin(), j.enc_q.end());
j.enc_q = std::move(q);
return RAD_OK;
}
/* The request's shape at `chunks` long: its geometry, rows and positions, its schedule, the
* upscale's split and what its ticket says it makes. Run at submit, and again for a request whose
* length the model predicts once its VCOND pass has written the prediction. */
@@ -544,14 +573,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_
RAD_TRY(plan_refs(j, r, s.frames, why));
j.pack = Pack{};
j.pack_small = Pack{};
if (!j.ref_tab.empty()) {
/* A keyframe is pinned on the video's grid, which an upscale's small steps are not on. */
if (r.upscale > 1.0 && j.ref_tab[1] > 0)
return no("a keyframe pins a frame of the video at its size, and latent_upscale "
"denoises a smaller one first: send the keyframe request without "
"latent_upscale");
RAD_TRY(lay_out(j.geom, j.ref_tab, &j.pack, why));
}
if (!j.ref_tab.empty()) RAD_TRY(lay_out(j.geom, j.ref_tab, &j.pack, why));
/* The schedule follows the upscale's split, which needs the small size first. */
const bool upscaling = r.upscale > 1.0;
const bool own_refine = upscaling && d.n_refine_rungs > 0;
@@ -610,6 +632,7 @@ int VideoDriver::shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_
if (positions_(RAD_VPOS_STEP, &j.geom_small, j.pos_small.data(), ns) != ns)
return no("the model could not lay the small size out");
if (!j.ref_tab.empty()) RAD_TRY(lay_out(j.geom_small, j.ref_tab, &j.pack_small, why));
if (!j.ref_tab.empty() && j.ref_tab[1] > 0) RAD_TRY(plan_small_keys(j, r, why));
j.split = evals - refine;
j.factor = (float)(((double)r.width / sw + (double)r.height / sh) / 2.0);
r.ticket->small_width = sw;
@@ -935,18 +958,20 @@ const RadBatch* VideoDriver::next(int step) {
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || j.cond_done) continue;
if (j.enc_next < j.enc_q.size()) return build_encode(j, step);
if (j.enc_next < j.enc_pre) return build_encode(j, step);
}
/* 3. A prompt. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (j.admitted && !j.failed && !j.cond_done) return build_cond(j, step);
}
/* 4. The oldest lane's next step, or its upscale once its small steps are done. */
/* 4. The oldest lane's next step, or its upscale once its small steps are done, and after it
* the keyframes again at the full size. */
for (auto& jp : jobs_) {
Job& j = *jp;
if (!j.admitted || j.failed || !j.cond_done || j.step >= j.sched.steps) continue;
if (small_now(j) && j.step == j.split) return build_upscale(j, step);
if (!small_now(j) && j.enc_next < j.enc_q.size()) return build_encode(j, step);
return build_step(j, step);
}
return nullptr;
@@ -1189,9 +1214,12 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
const Job::EncItem& it = j.enc_q[j.enc_next];
const VideoRefMedia& m = j.req->refs[(size_t)it.ref];
const bool audio = it.kind == RAD_ENC_VAUDIO || it.kind == RAD_ENC_AUDIO;
/* A keyframe at an upscale's small size is the media's second picture. */
const std::vector<float>& pix = it.small ? m.small_pixels : m.enc_pixels;
const int32_t eh = it.small ? m.small_h : m.enc_h, ew = it.small ? m.small_w : m.enc_w;
int32_t* gd = hptr<int32_t>(R_ENCG);
const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : m.enc_h,
audio ? 0 : m.enc_w, audio ? m.enc_channels : 3 };
const int64_t in[4] = { audio ? m.enc_n : m.enc_frames, audio ? 0 : eh, audio ? 0 : ew,
audio ? m.enc_channels : 3 };
const int64_t ng = enc_geom_(audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE, in, gd,
kEncGeomCap);
int64_t stage_frames = 0, stage_samples = 0;
@@ -1208,14 +1236,14 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
std::memcpy(sm + c * stage_samples, m.enc_samples.data() + c * n, (size_t)n * 4);
reg_[R_ENCSM].used = stage_samples * ch * 4;
} else {
const int64_t nf = m.enc_frames, area = (int64_t)m.enc_h * m.enc_w * 3;
const int64_t nf = m.enc_frames, area = (int64_t)eh * ew * 3;
stage_frames = ng > 23 ? gd[23] : 0;
if (stage_frames < nf || stage_frames * area * 4 > reg_[R_ENCPX].bytes) {
fail_locked(j, RAD_E_STATE, "'" + m.name + "' does not fit an encode pass");
return nullptr;
}
float* px = hptr<float>(R_ENCPX);
std::memcpy(px, m.enc_pixels.data(), (size_t)(nf * area) * 4);
std::memcpy(px, pix.data(), (size_t)(nf * area) * 4);
for (int64_t f = nf; f < stage_frames; ++f)
std::memcpy(px + f * area, px + (nf - 1) * area, (size_t)area * 4);
reg_[R_ENCPX].used = stage_frames * area * 4;
@@ -1238,8 +1266,8 @@ const RadBatch* VideoDriver::build_encode(Job& j, int step) {
} else {
V.enc_pixels = dptr<float>(ri, R_ENCPX);
V.enc_frames = (int32_t)stage_frames;
V.enc_height = m.enc_h;
V.enc_width = m.enc_w;
V.enc_height = eh;
V.enc_width = ew;
}
}
const int32_t kind = audio ? RAD_GEN_PASS_AENCODE : RAD_GEN_PASS_VENCODE;
+11 -6
View File
@@ -16,9 +16,10 @@
* 2. VENCODE or AENCODE of an admitted request's reference media, one per reference, so the
* video and audio VAE latents are in the lane's slots before its prompt runs.
* 3. VCOND of an admitted request, so its steps can follow the current request's without a gap.
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done.
* Requests are denoised one after another, not in turns: a pass is one request's whole
* sequence, so taking turns would only delay the first.
* 4. VSTEP of the oldest lane with steps left, or its VUPSCALE once its small steps are done,
* then its keyframes' VENCODEs at the full size (an upscaled request's keyframes are encoded
* at the small size in 2). Requests are denoised one after another, not in turns: a pass is
* one request's whole sequence, so taking turns would only delay the first.
*/
#pragma once
#include "video.h"
@@ -86,12 +87,15 @@ private:
std::vector<float> pos; /* [3, rows] */
/* References and keyframes: their table (RadVideoGenBatch::ref_tab), the step's packed
* sequence at the full size and at an upscale's small one (rows 0 without references),
* and the encode passes, one a media in order, `enc_next` the next to run. */
* and the encode passes, one a media in order, `enc_next` the next to run. The first
* `enc_pre` run before the prompt; the rest, an upscaled request's keyframes at the full
* size, run into the same slots once the upscale is done. */
std::vector<int32_t> ref_tab;
Pack pack, pack_small;
struct EncItem { int32_t kind, slot, ref; }; /* RAD_ENC_*, its number, its req->refs */
/* RAD_ENC_*, its number, its req->refs, and whether it is the media's small_pixels. */
struct EncItem { int32_t kind, slot, ref; bool small = false; };
std::vector<EncItem> enc_q;
size_t enc_next = 0;
size_t enc_next = 0, enc_pre = 0;
/* Latent upscaling: the evaluations at the small size (0: none), its geometry, rows and
* positions, the factor the network is told, and whether the upscale has run. */
int32_t split = 0;
@@ -143,6 +147,7 @@ private:
bool small_now(const Job& j) const { return j.split > 0 && !j.upscaled; }
int shape_job(Job& j, const VideoRequest& r, int32_t chunks, int32_t steps, std::string* why);
int plan_refs(Job& j, const VideoRequest& r, int32_t frames, std::string* why) const;
int plan_small_keys(Job& j, const VideoRequest& r, std::string* why) const;
int lay_out(const RadVideoGeom& g, const std::vector<int32_t>& tab, Pack* out,
std::string* why) const;
int32_t predicted_chunks(double log_seconds, std::string* note) const;
+4 -4
View File
@@ -270,12 +270,12 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
checkpoint_bytes_ = 0;
window_ck_bytes_ = 0;
for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state;
/* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). */
bool has_state = false;
for (const auto& p : plans_) has_state = has_state || p.stateful();
/* Then the window behind a checkpoint, after the linear state (see has_window_snapshot). A
* trunk's window rides in the slot whether or not linear state is beside it: a hit resumes at
* a snapshot either way, and without the window there it could not resume at all. */
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
p.win_snap = p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
!p.runtime_win && !groups[i].drafter;
if (p.win_snap && !p.zero && p.n_layers > 0)
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
+3 -4
View File
@@ -121,10 +121,9 @@ struct KVGroupPlan {
return runtime_tokens > 0 && block_size > 0
? (runtime_tokens + block_size - 1) / block_size : 0;
}
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
* snapshot would be read. */
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot), after any
* linear state. Set for a trunk group; a drafter's window is recomputed by draft refill, so
* its snapshot would not be read. */
bool win_snap = false;
int64_t n_blocks = 0; /* paged groups: blocks the group addresses (its context) */
+1 -1
View File
@@ -79,7 +79,7 @@ struct TierJob {
};
Kind kind = Kind::WriteBack;
BlockHash key;
/* Per cached group, in PrefixCache::cached_groups() order: the blocks to read for a
/* One per entry block, in PrefixCache::entry_groups() order: the blocks to read for a
* write-back, or the blocks the engine allocated for a promotion. */
std::vector<int32_t> blocks;
int32_t host_slot = -1;
+74 -58
View File
@@ -5,6 +5,7 @@
#include <algorithm>
#include <cstring>
#include <numeric>
#include <unordered_set>
namespace rad {
@@ -144,6 +145,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
block_size_ = 0;
interval_ = 0;
groups_.clear();
per_.clear();
entry_groups_.clear();
map_.clear(); lru_.clear();
ck_by_prefix_.clear(); ck_by_session_.clear();
/* set_policy() may override this afterwards. */
@@ -156,12 +159,17 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
return RAD_OK;
}
/* Granularity is the first full-attention group's block size, since that is what a hit
* reuses. Paged groups with another block size are not cached and are named in the report. */
/* Every paged group but a windowed one is cached. An entry covers the lcm of their block
* sizes, and holds that over a group's block size of the group's blocks: a hit then ends on
* a block of every group, which adopt() needs. The chunk quantum is a multiple of every paged
* group's block (core/sched/geometry.cpp), so the lcm divides every checkpoint position. */
for (const auto& p : kv->plans()) {
if (p.kind == RAD_KV_FULL && block_size_ == 0) block_size_ = p.block_size;
if (p.stateful()) has_linear_ = true;
if (p.paged() && p.kind != RAD_KV_WINDOW && p.block_size > 0)
block_size_ = block_size_ > 0 ? std::lcm(block_size_, p.block_size) : p.block_size;
}
/* With only windowed groups, nothing is indexed and a hit is a window snapshot alone, keyed
* on the chain at the first group's block. */
if (block_size_ == 0) {
for (const auto& p : kv->plans()) if (p.paged()) { block_size_ = p.block_size; break; }
}
@@ -170,20 +178,25 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
RAD_WARN("%s", report_.c_str());
return RAD_OK;
}
std::string skipped;
std::string skipped, split;
for (const auto& p : kv->plans()) {
if (!p.paged()) continue;
/* A window group is not prefix-cached. Its blocks below the window are recycled, adopt()
* would overfill a table capped at window_blocks, and a hit does not set first_block_pos.
* A drafter or windowed layer's cache then starts where the hit ended. */
* A checkpoint slot can carry a trunk's window instead (KVManager::has_window_snapshot);
* a drafter or a windowed layer without one starts its cache where the hit ended. */
if (p.kind == RAD_KV_WINDOW) {
skipped += fmt(" group '%s' is windowed (%lld blocks): not cached\n",
p.name.c_str(), (long long)p.window_blocks);
skipped += fmt(" group '%s' is windowed (%lld blocks): not cached%s\n",
p.name.c_str(), (long long)p.window_blocks,
p.win_snap ? "; a checkpoint slot carries its window" : "");
continue;
}
if (p.block_size == block_size_) groups_.push_back(p.index);
else skipped += fmt(" group '%s' block %lld != cache granularity %lld: not cached\n",
p.name.c_str(), (long long)p.block_size, (long long)block_size_);
groups_.push_back(p.index);
per_.push_back((int32_t)(block_size_ / p.block_size));
for (int64_t k = 0; k < block_size_ / p.block_size; ++k) entry_groups_.push_back(p.index);
if (p.block_size != block_size_)
split += fmt(" group '%s' block %lld: %lld blocks an entry\n", p.name.c_str(),
(long long)p.block_size, (long long)(block_size_ / p.block_size));
}
/* An entry can be demoted only when the host tier can hold every group in it. A streamed
@@ -209,8 +222,8 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
/* A checkpoint is found by the chained hash at its position, which exists only on
* block boundaries, so an interval off the block grid would never hit. */
RAD_ERR("the checkpoint interval resolves to %lld (from --checkpoint-interval %lld, "
"rounded up to the chunk quantum), which is not a multiple of the attention "
"block size %lld, so no checkpoint would ever hit (spec §7.3)",
"rounded up to the chunk quantum), which is not a multiple of the cache's "
"%lld-token entry, so no checkpoint would ever hit (spec §7.3)",
(long long)interval_, (long long)cfg.checkpoint_interval,
(long long)block_size_);
return RAD_E_INVAL;
@@ -218,13 +231,14 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
}
enabled_ = true;
report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
report_ = fmt("prefix cache: %zu paged group(s) in %lld-token entries; checkpoints "
"every %lld tokens (%lld slots of %s a rank, pinned host memory), retention "
"'%s'\n",
groups_.size(), (long long)block_size_,
(long long)(has_linear_ ? interval_ : 0),
(long long)kv->checkpoint_slots(), humanb(kv->checkpoint_bytes()).c_str(),
policy_->name());
report_ += split;
report_ += skipped;
if (!demotable_) {
/* Stated whether or not a host tier is configured. */
@@ -306,7 +320,7 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
if (departed && matched > 0 && map_.find(hs[(size_t)matched - 1])->second.n_children >= 2)
hit.branch_at = (int32_t)(matched * block_size_);
/* Back a full hit off by one block so one token remains to compute a logit from. */
/* Back a full hit off by one entry so one token remains to compute a logit from. */
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
auto deepest = [&](int64_t limit) { return deepest_ckpt(hs, limit); };
@@ -336,8 +350,9 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
if (blocks_out)
for (int64_t b = 0; b < matched; ++b) {
const Entry& e = map_.find(hs[(size_t)b])->second;
for (size_t g = 0; g < groups_.size(); ++g)
(*blocks_out)[g].push_back(e.blocks[g]);
for (size_t k = 0, g = 0; g < groups_.size(); ++g)
for (int32_t j = 0; j < per_[g]; ++j, ++k)
(*blocks_out)[g].push_back(e.blocks[k]);
}
/* A hit is a use for the tiers' idle clock too; otherwise a prefix hit every turn, or one just
* promoted for this lookup, would look idle since its publish. */
@@ -368,6 +383,23 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
return hit;
}
bool PrefixCache::retain_entry(const std::vector<std::vector<int32_t>>& bt, int64_t b,
std::vector<int32_t>* out) {
out->assign(entry_groups_.size(), -1);
size_t k = 0;
for (size_t g = 0; g < groups_.size(); ++g)
for (int32_t j = 0; j < per_[g]; ++j, ++k) {
const int32_t blk = bt[g][(size_t)(b * per_[g] + j)];
if (kv_->retain_block(groups_[g], blk) >= 0) { (*out)[k] = blk; continue; }
/* Unwind exactly what was retained: anything else leaks a block or frees one under a
* live sequence. */
for (size_t i = 0; i < k; ++i) kv_->release_block(entry_groups_[i], (*out)[i]);
out->clear();
return false;
}
return true;
}
int PrefixCache::insert(uint64_t session,
const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
@@ -379,7 +411,8 @@ int PrefixCache::insert(uint64_t session,
const int64_t n_full = n_tokens / block_size_;
if (n_full <= 0) return RAD_OK;
for (const auto& bt : blocks) if ((int64_t)bt.size() < n_full) return RAD_E_INVAL;
for (size_t g = 0; g < blocks.size(); ++g)
if ((int64_t)blocks[g].size() < n_full * per_[g]) return RAD_E_INVAL;
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
const uint64_t now = rad_mono_ns();
@@ -397,17 +430,8 @@ int PrefixCache::insert(uint64_t session,
* tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left
* alone. */
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
std::vector<int32_t> mine(groups_.size(), -1);
size_t held = 0;
for (; held < groups_.size(); ++held) {
const int32_t blk = blocks[held][(size_t)b];
if (kv_->retain_block(groups_[held], blk) < 0) break;
mine[held] = blk;
}
if (held != groups_.size()) {
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], mine[g]);
return RAD_E_STATE;
}
std::vector<int32_t> mine;
if (!retain_entry(blocks, b, &mine)) return RAD_E_STATE;
Entry& e = it->second;
e.blocks = std::move(mine);
e.used_ns = now;
@@ -419,19 +443,7 @@ int PrefixCache::insert(uint64_t session,
}
Entry e;
e.blocks.assign(groups_.size(), -1);
size_t held = 0;
for (; held < groups_.size(); ++held) {
int32_t blk = blocks[held][(size_t)b];
if (kv_->retain_block(groups_[held], blk) < 0) break;
e.blocks[held] = blk;
}
if (held != groups_.size()) {
/* Unwind exactly what was retained: anything else leaks a block or frees one under a
* live sequence. */
for (size_t g = 0; g < held; ++g) kv_->release_block(groups_[g], e.blocks[g]);
return RAD_E_STATE;
}
if (!retain_entry(blocks, b, &e.blocks)) return RAD_E_STATE;
e.tokens.assign(tokens.begin() + b * block_size_,
tokens.begin() + (b + 1) * block_size_);
e.used_ns = now;
@@ -534,18 +546,20 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
int64_t PrefixCache::restore_room() const {
if (!kv_ || groups_.empty()) return 0;
int64_t room = INT64_MAX;
for (int32_t g : groups_) room = std::min(room, kv_->total_blocks(g) - kv_->held_blocks(g));
for (size_t i = 0; i < groups_.size(); ++i)
room = std::min(room, (kv_->total_blocks(groups_[i]) - kv_->held_blocks(groups_[i])) /
std::max<int32_t>(per_[i], 1));
return std::max<int64_t>(0, room);
}
int64_t PrefixCache::trim_for(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm, int64_t n_blocks) {
const std::vector<MMContentKey>& mm, int64_t n_entries) {
/* Without a host tier a trim erases, and making room for a restore must lose nothing. */
if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0;
if (!enabled_ || n_entries <= 0 || !tiers_ || !tiers_->host_on()) return 0;
const std::vector<BlockHash> hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_);
std::unordered_set<BlockHash, BlockHashHash> spare(hs.begin(), hs.end());
for (const auto& h : held_) spare.insert(h.first);
return trim_sparing(n_blocks, &spare);
return trim_sparing(n_entries, &spare);
}
void PrefixCache::drop_offdevice(const BlockHash& key) {
@@ -563,14 +577,15 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
auto it = map_.find(key);
if (it == map_.end()) return RAD_E_NOTFOUND;
if (blocks.size() != groups_.size()) return RAD_E_SHAPE;
if (blocks.size() != entry_groups_.size()) return RAD_E_SHAPE;
for (int32_t b : blocks) if (b < 0) return RAD_E_INVAL;
/* The reservation's reference becomes the cache's: KVManager::reserve_block left each block at
* refcount one with no sequence attached, and the cache's release path frees it from now on.
* No extra retain. */
Entry& e = it->second;
e.blocks = blocks;
for (size_t g = 0; g < groups_.size(); ++g) kv_->cache_reserved_block(groups_[g], blocks[g]);
for (size_t k = 0; k < entry_groups_.size(); ++k)
kv_->cache_reserved_block(entry_groups_[k], blocks[k]);
if (!e.in_lru) {
/* A restore is a use: a request is about to hit it. */
e.used_ns = rad_mono_ns();
@@ -582,8 +597,8 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
}
bool PrefixCache::shared_with_live(const Entry& e) const {
for (size_t g = 0; g < groups_.size(); ++g)
if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true;
for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k)
if (kv_->block_refcount(entry_groups_[k], e.blocks[k]) > 1) return true;
return false;
}
@@ -595,7 +610,8 @@ bool PrefixCache::same_tokens(const Entry& e, const int32_t* src) const {
}
void PrefixCache::release_blocks(const Entry& e) {
for (size_t g = 0; g < groups_.size(); ++g) kv_->release_block(groups_[g], e.blocks[g]);
for (size_t k = 0; k < entry_groups_.size() && k < e.blocks.size(); ++k)
kv_->release_block(entry_groups_[k], e.blocks[k]);
}
int64_t PrefixCache::evict_lru(int64_t n) {
@@ -634,16 +650,16 @@ int64_t PrefixCache::evict_lru(int64_t n) {
return done;
}
int64_t PrefixCache::trim(int64_t n_blocks) { return trim_sparing(n_blocks, nullptr); }
int64_t PrefixCache::trim(int64_t n_entries) { return trim_sparing(n_entries, nullptr); }
int64_t PrefixCache::trim_sparing(int64_t n_blocks,
int64_t PrefixCache::trim_sparing(int64_t n_entries,
const std::unordered_set<BlockHash, BlockHashHash>* spare) {
/* Tiers attached but off count as no tiers: no copy will ever land, so do not wait for one. */
const bool keep = tiers_ && tiers_->host_on();
const uint64_t now = rad_mono_ns();
int64_t done = 0;
auto it = lru_.begin();
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0;
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_entries && seen > 0;
--seen) {
const BlockHash h = *it;
auto m = map_.find(h);
@@ -714,11 +730,11 @@ int64_t PrefixCache::drop_clean() {
}
/* The KV manager tracks how many cache-held blocks are at refcount one. One group only: the paged
* groups share a token axis and an entry is one block in each, so summing groups would multiply
* the answer. Off-device entries hold no blocks and count for nothing. */
* groups share a token axis and an entry is blocks_per_entry() blocks in each, so summing groups
* would multiply the answer. Off-device entries hold no blocks and count for nothing. */
int64_t PrefixCache::unshared_tokens() const {
if (!kv_ || groups_.empty() || block_size_ <= 0) return 0;
return kv_->cache_only_blocks(groups_[0]) * block_size_;
if (!kv_ || groups_.empty() || block_size_ <= 0 || per_.empty() || per_[0] <= 0) return 0;
return kv_->cache_only_blocks(groups_[0]) * (block_size_ / per_[0]);
}
void PrefixCache::clear() {
@@ -1035,7 +1051,7 @@ int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t
/* A kept token keeps its whole block: the block holding it is what the next turn hits. */
const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_;
int64_t entry_bytes = 0;
for (int32_t g : groups_) {
for (int32_t g : entry_groups_) {
const KVGroupPlan* p = kv_->plan(g);
if (p) entry_bytes += p->bytes_per_block;
}
+44 -18
View File
@@ -23,6 +23,12 @@
* interval (next_checkpoint_after()), so a checkpoint is always written, at the cost of an
* occasional short chunk.
*
* Block sizes: an entry covers block_size() tokens, the lcm of the cached groups' block sizes, and
* holds block_size() / B blocks of a group whose blocks are B tokens. A model whose layers keep KV
* at different strides (a compressed group at one row per r tokens beside one per token) is cached
* in every group; a hit is then a multiple of every group's block. The chunk quantum is a multiple
* of every paged group's block (core/sched/geometry.cpp), so checkpoints land on entries.
*
* Sizing: the cache holds a KV reference on every block it indexes, so pool demand scales with
* live sessions, not running requests. Hit rate falls off a cliff with pool utilisation: intact
* below about 75%, half gone by about 81%, and zero once the sessions no longer fit, because each
@@ -207,6 +213,8 @@ public:
* make reserve_checkpoint refuse every checkpoint and lookups search the wrong stride. */
int configure(const Config& cfg, KVManager* kv, int64_t checkpoint_interval);
bool enabled() const { return enabled_; }
/* Tokens one entry covers: the lcm of the cached groups' block sizes. Hits, publishes and
* checkpoint keys are whole entries. */
int64_t block_size() const { return block_size_; }
int64_t checkpoint_interval() const { return interval_; }
const std::vector<int32_t>& cached_groups() const { return groups_; }
@@ -214,6 +222,13 @@ public:
* rows are addressed by the sequence's block ids, so entries stay in VRAM and are evicted
* whole (docs/KV-STREAMING.md §4.1). */
bool demotable() const { return demotable_; }
/* Blocks of cached_groups()[i] in one entry: block_size() over that group's block size. */
int64_t blocks_per_entry(size_t i) const { return i < per_.size() ? per_[i] : 0; }
/* The group of each block an entry holds, in the order of its block list (Entry::blocks,
* TierJob::blocks, rebind): cached_groups()[i] repeated blocks_per_entry(i) times. The idle
* tiers move an entry as these blocks, one per slot. Equal to cached_groups() when every
* cached group has the same block size. */
const std::vector<int32_t>& entry_groups() const { return entry_groups_; }
std::string report() const;
/* Overrides the policy configure() installed from Config::checkpoint_policy (custom policies,
@@ -222,12 +237,12 @@ public:
const CheckpointPolicy& policy() const { return *policy_; }
/* ---------------- full attention ---------------- */
/* Longest cached prefix, in whole blocks, plus the checkpoint that covers the linear state
/* Longest cached prefix, in whole entries, plus the checkpoint that covers the linear state
* for a prefix of it. `blocks_out`, when given, receives the block ids per cached group, in
* cached_groups() order, ready for KVManager::adopt().
* cached_groups() order, ready for KVManager::adopt(): blocks_per_entry(i) of them an entry.
*
* Never returns the whole prompt: one token must remain to compute a logit from, so a full
* hit is backed off by one block. `cap`, when given, ends the hit early (HitCap). `session`,
* hit is backed off by one entry. `cap`, when given, ends the hit early (HitCap). `session`,
* when not 0, is the request being admitted: it takes over the snapshots on the chain it hit
* (take_over). */
CacheHit lookup(const std::vector<int32_t>& tokens,
@@ -235,7 +250,7 @@ public:
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
const HitCap* cap = nullptr, uint64_t session = 0) const;
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
/* Publish the whole entries a sequence just filled. `blocks[i]` is the block table of
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
int insert(uint64_t session,
const std::vector<int32_t>& tokens,
@@ -249,11 +264,12 @@ public:
* idle tiers on, an entry whose host copy has landed moves to the host tier instead of being
* forgotten; only one with no host copy is lost. */
int64_t evict_lru(int64_t n_entries);
/* Free up to `n_blocks` pool blocks for the scheduler's reserve without losing anything a
* later turn could reuse. One oldest-first walk that skips entries a live sequence also holds
* and, with the tiers on, entries whose host copy has not landed yet. Pressure that cannot
* wait goes to evict_lru. Returns how many blocks went back. */
int64_t trim(int64_t n_blocks);
/* Give back up to `n_entries` entries' blocks for the scheduler's reserve without losing
* anything a later turn could reuse. One oldest-first walk that skips entries a live sequence
* also holds and, with the tiers on, entries whose host copy has not landed yet. Pressure
* that cannot wait goes to evict_lru. Returns how many entries went: each gave back
* blocks_per_entry(i) blocks of cached group i. */
int64_t trim(int64_t n_entries);
/* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence
* reading it. Used when the memory has a better use (the expert slab's loan). Entries still
* shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */
@@ -288,23 +304,25 @@ public:
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
const std::vector<MMContentKey>& mm,
int64_t fit = INT64_MAX, bool* cut = nullptr) const;
/* Entries a restore can place now: free blocks against the carve, the least over the cached
* groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */
/* Entries a restore can place now: free blocks against the carve over the blocks an entry
* takes in the group, the least over the cached groups. Lent blocks count, since
* KVManager::reserve_blocks recalls the loan for them. */
int64_t restore_room() const;
/* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks
* would only have to come back too) and every chain a waiting request holds (hold()), whose
* next attempt would restore it again. Only entries whose host copy has landed leave VRAM,
* so nothing is lost; with no host tier it takes nothing. */
* so nothing is lost; with no host tier it takes nothing. In entries, as trim(). */
int64_t trim_for(const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm,
int64_t n_blocks);
int64_t n_entries);
/* The tiers lost the bytes. Erases the entry without releasing blocks: an off-device entry
* owns none, and its recorded ids now belong to other sequences. Installed as
* IdleTiers::set_drop_sink. */
void drop_offdevice(const BlockHash& key);
/* A restore finished and the entry's blocks now live at these ids. The restore's raw
* reservations (KVManager::reserve_block) become cache-held references. */
/* A restore finished and the entry's blocks now live at these ids, one per entry_groups()
* slot. The restore's raw reservations (KVManager::reserve_block) become cache-held
* references. */
int rebind(const BlockHash& key, const std::vector<int32_t>& blocks);
@@ -404,7 +422,8 @@ public:
private:
struct Entry {
std::vector<int32_t> blocks; /* one per cached group, in groups_ order */
/* blocks_per_entry(i) per cached group, in groups_ order: entry_groups_[k] owns blocks[k] */
std::vector<int32_t> blocks;
std::vector<int32_t> tokens; /* the block's token ids, compared on hit */
/* On the LRU exactly while the cache holds the blocks; `lru` is valid only then. An
* off-device entry owns no block, so eviction must not reach it. */
@@ -438,14 +457,19 @@ private:
int64_t n_blocks) const;
void touch(const BlockHash& h, uint64_t now_ns) const;
/* trim(), leaving the entries in `spare` (when given) where they are. */
int64_t trim_sparing(int64_t n_blocks,
int64_t trim_sparing(int64_t n_entries,
const std::unordered_set<BlockHash, BlockHashHash>* spare);
/* A live sequence also holds one of this entry's blocks, so releasing it frees nothing. */
bool shared_with_live(const Entry& e) const;
/* Whether `e` holds the block_size_ token ids at `src`, so a hash collision is a miss. */
bool same_tokens(const Entry& e, const int32_t* src) const;
/* Gives the entry's block in every group back to the KV manager. */
/* Gives the entry's blocks in every group back to the KV manager. */
void release_blocks(const Entry& e);
/* Takes the cache's reference on the blocks of entry `b` of a sequence's tables `bt` (one per
* cached group) into `out`, entry_groups_ order; on a refusal releases exactly what it took
* and returns false. */
bool retain_entry(const std::vector<std::vector<int32_t>>& bt, int64_t b,
std::vector<int32_t>* out);
/* Retire one snapshot: free its slot and tell the tiers. The session index is left to the
* caller. */
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
@@ -474,6 +498,8 @@ private:
int64_t interval_ = 0;
std::vector<int32_t> groups_; /* paged groups this cache indexes */
bool demotable_ = false; /* the host tier can hold every group in an entry */
std::vector<int32_t> per_; /* blocks of groups_[i] an entry holds */
std::vector<int32_t> entry_groups_; /* the group of each of an entry's blocks */
bool has_linear_ = false;
mutable std::unordered_map<BlockHash, Entry, BlockHashHash> map_;
+11
View File
@@ -5,6 +5,7 @@
#include "rad_internal.h"
#include <algorithm>
#include <cstdio>
#include <cstring>
#ifdef RAD_HAVE_FFMPEG
@@ -26,6 +27,8 @@ namespace mm {
bool decoder_available() { return false; }
std::string decoder_version() { return "absent (built without libav*)"; }
static int no_decoder(std::string* why) {
if (why) *why = "this build has no media decoder: it was configured without libavformat / "
"libavcodec / libswscale (RAD_WITH_FFMPEG)";
@@ -57,6 +60,14 @@ int decode_audio(const uint8_t*, size_t, int32_t, int64_t, std::vector<float>*,
bool decoder_available() { return true; }
std::string decoder_version() {
const unsigned v = avformat_version();
char b[48];
std::snprintf(b, sizeof(b), "libavformat %u.%u.%u", AV_VERSION_MAJOR(v), AV_VERSION_MINOR(v),
AV_VERSION_MICRO(v));
return b;
}
namespace {
/* The only demuxers a request may reach. A format that can name another file (a playlist, a
+5
View File
@@ -36,6 +36,11 @@ struct FrameRGBA {
/* Whether this build has a decoder. */
bool decoder_available();
/* "libavformat <version>" when the decoder is built in, "absent (built without libav*)"
* when it is not: one string for the startup report and /diagnostics, so a media 500 can be
* read off the report instead of bisected. */
std::string decoder_version();
/* The first frame of an image (or of anything with a video stream). Refuses a source over
* `max_pixels`, which bounds what a request can make the server allocate before any resize. */
int decode_image(const uint8_t* data, size_t n, int64_t max_pixels, Frame* out, std::string* why);
+7 -1
View File
@@ -22,6 +22,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
tier_.assign(n, Tier::VRAM);
busy_.assign(n, 0u);
movable_.assign(n, 0u);
pinned_.assign(n, 0u);
layer_of_.assign(n, -1);
bytes_.assign(n, 0);
ever_.assign(n, 0u);
@@ -61,6 +62,7 @@ int HeatEngine::init(const Plan& plan, const HeatParams& params) {
layer_of_[u] = mu.layer;
bytes_[u] = mu.bytes;
movable_[u] = mu.movable ? 1u : 0u;
pinned_[u] = mu.pinned ? 1u : 0u;
if (mu.movable) ++movable;
if (mu.layer < 0) {
if (mu.movable) other[(size_t)n_layer_].push_back((int32_t)u);
@@ -280,7 +282,9 @@ void HeatEngine::set_busy(int32_t unit, bool busy) {
void HeatEngine::set_place(int32_t unit) {
const size_t u = (size_t)unit, p = (size_t)pos_[u];
const bool vram = tier_[u] == Tier::VRAM;
rank_as_[p] = (!movable_[u] || busy_[u]) ? 0u : vram ? 2u : 1u;
/* A pinned resident is never a candidate to leave the card: it ranks as off-device only, so a
* promotion can still target it but a demotion cannot. */
rank_as_[p] = (!movable_[u] || busy_[u] || (pinned_[u] && vram)) ? 0u : vram ? 2u : 1u;
routed_as_[p] = vram ? 2u : 1u;
miss_bytes_[p] = vram ? 0 : bytes_[u];
}
@@ -330,6 +334,8 @@ bool HeatEngine::pick(Swap* out) const {
const int32_t rc = l >= 0 ? res_count_[(size_t)l] : 0;
const float h = heat_[(size_t)pos_[i]];
if (tier_[i] == Tier::VRAM) {
/* A pinned resident never leaves the card, whatever its heat. */
if (pinned_[i]) continue;
/* Colder wins; on a tie, take from the layer holding the most resident units. */
if (cold[c] < 0 || h < cold_h[c] || (h == cold_h[c] && rc > cold_res[c])) {
cold[c] = (int32_t)i; cold_h[c] = h; cold_res[c] = rc;
+3
View File
@@ -210,6 +210,9 @@ private:
std::vector<Tier> tier_;
std::vector<uint8_t> busy_;
std::vector<uint8_t> movable_;
/* --expert-pin-top: a decode-hot resident the planner marked unmovable is never a demotion
* candidate, even where a later pass made its unit movable again. */
std::vector<uint8_t> pinned_;
std::vector<int32_t> layer_of_;
/* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */
std::vector<uint8_t> ever_;
+138 -6
View File
@@ -12,6 +12,7 @@
#include "planner.h"
#include <algorithm>
#include <cmath>
#include <cstring>
#include <map>
#include <set>
@@ -103,6 +104,21 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
}
/* A draft head's routed experts, pinned in the host pool before any strategy runs, leave the trunk
* the whole of `host_room`. The card then holds only the trunk's floor against that room. The
* drafter's units share the trunk's slab classes, so the spare the trunk's floor already reserves
* covers them; with no trunk experts the drafter is the whole plane and pinning it leaves the card
* nothing to hold. */
int64_t expert_vram_floor_draft_hosted(const WeightFootprint& wf, int64_t host_room) {
if (wf.draft_experts <= 0) return expert_vram_floor(wf, host_room);
const int64_t trunk = wf.experts - wf.draft_experts;
if (trunk <= 0) return 0;
WeightFootprint t = wf;
t.experts = trunk;
t.draft_experts = 0;
return expert_vram_floor(t, host_room);
}
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
if (p.vram_budget == pool_bytes) return RAD_OK;
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
@@ -226,6 +242,14 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
layer_experts[mu.layer] += b;
out->expert_unit_max = std::max(out->expert_unit_max, b);
expert_strides.insert(b);
/* A draft head's routed experts: layers at meta.n_layers and above, and only when the
* program declares a drafter. The trunk's own layers stay in the elastic plane a
* strategy places; --draft-expert-placement host takes this part out of it. */
if (prog.drafter.kind != RAD_DRAFT_NONE && prog.meta.n_layers > 0 &&
mu.layer >= (int32_t)prog.meta.n_layers) {
out->draft_experts += b;
out->draft_unit_max = std::max(out->draft_unit_max, b);
}
}
else out->statics += b;
if (mu.layer >= 0 && !mu.mapped) out->layer_unit_max = std::max(out->layer_unit_max, b);
@@ -667,7 +691,7 @@ int Planner::assign_expert_tiered(Plan* p) {
Cost k;
for (int32_t ui : order) {
MoveUnit& mu = p->units[(size_t)ui];
if (mu.access != RAD_ACCESS_CONDITIONAL) continue;
if (mu.access != RAD_ACCESS_CONDITIONAL || mu.preplaced()) continue;
mu.tier = Tier::VRAM;
mu.site = Site::Device;
mu.reason = "fits in vram";
@@ -679,7 +703,7 @@ int Planner::assign_expert_tiered(Plan* p) {
for (int32_t ui : order) {
MoveUnit& mu = p->units[(size_t)ui];
if (mu.access != RAD_ACCESS_CONDITIONAL) continue;
if (mu.access != RAD_ACCESS_CONDITIONAL || mu.preplaced()) continue;
if (k.residents < cap && k.used + mu.slot_bytes <= room) {
k.used += mu.slot_bytes;
++k.residents;
@@ -1027,6 +1051,100 @@ int Planner::pin_towers(const Config& cfg, Plan* p) const {
return RAD_OK;
}
/* --draft-expert-placement host: a draft head's routed experts (layers at meta.n_layers and above,
* and only when the program declares a drafter) go to the pinned host pool before any strategy
* runs. The card reads them in place at the DeviceZeroCopy site, the same way it reads a pooled
* expert, so a drafter's experts fit beside a trunk that already fills the card instead of the
* strategy having to make room for them on it. They are not movable: heat never promotes a draft
* expert onto the card and into the trunk's slab. */
int Planner::pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const {
if (cfg.draft_expert_placement != "host") return RAD_OK;
if (prog.drafter.kind == RAD_DRAFT_NONE || prog.meta.n_layers == 0) {
if (cfg.draft_expert_placement_given) {
RAD_ERR("placement: --draft-expert-placement host: this model declares no draft head");
p->notes.push_back("--draft-expert-placement host: no draft head to place");
return RAD_E_INVAL;
}
return RAD_OK;
}
const int32_t trunk = (int32_t)prog.meta.n_layers;
auto draft = [&](const MoveUnit& mu) {
return mu.expert >= 0 && mu.layer >= trunk && mu.tier != Tier::Mapped && !mu.host_forced;
};
int64_t need = 0, n = 0, widest = 0;
for (const MoveUnit& mu : p->units)
if (draft(mu)) { need += mu.slot_bytes; widest = std::max(widest, mu.slot_bytes); ++n; }
if (!n) {
RAD_ERR("placement: --draft-expert-placement host: the draft head declares no routed "
"experts");
p->notes.push_back("--draft-expert-placement host: no drafter experts to place");
return RAD_E_STATE;
}
if (need > p->host_budget) {
RAD_ERR("placement: --draft-expert-placement host: the drafter's experts need %s of the "
"pinned host pool and %s of it is left%s", humanb(need).c_str(),
humanb(p->host_budget).c_str(),
p->file_stage_reserve ? " after the file tier's staging" : "");
p->notes.push_back(fmt("--draft-expert-placement host: the drafter's experts (%s) do not "
"fit the host pool", humanb(need).c_str()));
return RAD_E_NOMEM;
}
for (MoveUnit& mu : p->units) {
if (!draft(mu)) continue;
p->host_budget -= mu.slot_bytes;
p->draft_host_bytes += mu.slot_bytes;
mu.tier = Tier::HostPinned;
mu.site = Site::DeviceZeroCopy;
mu.movable = false;
mu.host_forced = true;
mu.reason = "--draft-expert-placement host; read over the link in place";
}
RAD_INFO("placement: the drafter's experts, %lld units (%s, widest %s), in the pinned host "
"pool, read in place (--draft-expert-placement host)", (long long)n,
humanb(need).c_str(), humanb(widest).c_str());
return RAD_OK;
}
/* --expert-pin-top F: the hottest fraction of the routed experts, ranked by the profile the planner
* was given (the container's, or --expert-profile's decode counts), stay resident. They are marked
* unmovable, so the heat engine never demotes them and the decode-hot set stops paying the host
* pool's PCIe read. The cut keeps the hottest ceil(F * n), and a tie at the cut stays movable: the
* threshold is the share just below the hot set, and only a share strictly above it pins. Runs
* after the strategy, which has already put the hot set in VRAM; a hot unit the strategy had to
* leave on the host is left there and counted, since pinning it would need VRAM the card does not
* have. */
void Planner::pin_hot(const Config& cfg, Plan* p) const {
if (cfg.expert_pin_top <= 0.0f) return;
std::vector<float> shares;
for (const MoveUnit& mu : p->units)
if (mu.expert >= 0 && mu.tier != Tier::Mapped) shares.push_back(mu.profile_share);
if (shares.empty()) return;
std::sort(shares.begin(), shares.end());
/* The cut sits after the coldest (1 - F) of the plane, so the hottest F are pinned. A tie at
* the cut stays movable: the threshold is the share just below the hot set, and only a share
* strictly above it pins. */
const double keep = (double)cfg.expert_pin_top * (double)shares.size();
const size_t hot = keep <= 0.0 ? 0 : std::min(shares.size(), (size_t)std::ceil(keep));
const float threshold = hot == 0 ? shares.back() + 1.0f
: shares[shares.size() - hot] - 1.0f;
p->pin_threshold = threshold;
p->profile_units = (int64_t)shares.size();
int64_t pinned = 0, left = 0;
for (MoveUnit& mu : p->units) {
if (mu.expert < 0 || mu.tier == Tier::Mapped || mu.host_forced) continue;
if (mu.profile_share <= threshold) continue;
if (mu.tier != Tier::VRAM) { ++left; continue; }
mu.pinned = true;
mu.movable = false;
++pinned;
}
p->pinned_units = pinned;
RAD_INFO("placement: --expert-pin-top %.4g pins %lld of %lld routed experts resident (share "
"above %.4g); %lld of the hot set had no VRAM slot and stay where the strategy put "
"them", (double)cfg.expert_pin_top, (long long)pinned, (long long)shares.size(),
(double)threshold, (long long)left);
}
/* ------------------------------------------------------------------ plan */
int Planner::plan(Plan* out) {
if (!out || !in_.program || !in_.config) return RAD_E_INVAL;
@@ -1055,6 +1173,13 @@ int Planner::plan(Plan* out) {
pin_mapped(prog, out);
build_classes(out);
/* After build_classes: a unit's slot_bytes is its class's stride, and the pins below charge
* the host pool that. Before it the charge would be zero and the pool would not hold them. */
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
if (hrc >= 0) hrc = pin_draft_experts(prog, cfg, out);
/* Charge the file tier's staging pool (RAD_PLACE_FILE_STAGE_SLOTS) before anything is placed
* in the host pool, or the fill could exhaust it and the mover refuse the plan. Sized from the
* widest class carrying a layer unit, the only kind either offload strategy spills; this
@@ -1087,14 +1212,14 @@ int Planner::plan(Plan* out) {
}
}
/* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
int hrc = pin_embedding(prog, cfg, out);
const int trc = pin_towers(cfg, out);
if (hrc >= 0) hrc = trc;
/* Not RAD_TRY: a refusal still leaves `out` filled in far enough to print. The pins ran above,
* once slot_bytes was known. */
int rc = assign(out);
enforce_op_site_agreement(prog, out);
schedule_prefetch(out);
/* After the strategy: it has put the hot set in VRAM, and pinning marks those resident. */
pin_hot(cfg, out);
finish(prog, out);
return hrc < 0 ? hrc : rc;
}
@@ -1222,6 +1347,13 @@ std::string Plan::report(const Program& prog) const {
if (tower_host_bytes)
s += fmt(" encoder tower %12s %12s (--vision-tower-placement ram, pinned, read in place)\n",
"-", humanb(tower_host_bytes).c_str());
if (draft_host_bytes)
s += fmt(" drafter %12s %12s (--draft-expert-placement host, pinned, read in place)\n",
"-", humanb(draft_host_bytes).c_str());
if (pinned_units)
s += fmt(" pinned hot %12s %12lld (--expert-pin-top: resident, heat never demotes them, "
"share above %.4g of %lld)\n", "-", (long long)pinned_units, (double)pin_threshold,
(long long)profile_units);
if (ngram_copy_bytes)
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n",
"-", humanb(ngram_copy_bytes).c_str(),
+22 -2
View File
@@ -79,8 +79,9 @@ struct MoveUnit {
Site site = Site::Device;
int32_t slab_slot = -1;
bool movable = false; /* may the heat engine relocate it after load */
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's
* or the encoder tower's */
bool pinned = false; /* a decode-hot resident --expert-pin-top kept: heat never demotes it */
bool host_forced = false; /* a placement flag put it in the pinned pool: the embedding's,
* the encoder tower's or the draft head's experts' */
/* Placed before any strategy runs, so every assignment pass skips it and no VRAM total counts
* it: the mapped tier, --embedding-placement ram and --vision-tower-placement ram. */
@@ -227,7 +228,14 @@ public:
* both flags' weight bytes, as the tier totals count them; the pooled figures exclude it. */
int64_t embedding_host_bytes = 0;
int64_t tower_host_bytes = 0;
int64_t draft_host_bytes = 0;
int64_t forced_host_used = 0;
/* --expert-profile and --expert-pin-top: the profile's units the planner pinned resident and the
* share threshold it derived from the fraction. Reported so the window can see what the decode
* set costs the card. */
int64_t pinned_units = 0;
int64_t profile_units = 0;
float pin_threshold = 0.0f;
/* --ngram-placement ram: RAM for the n-gram tables the load phase copies out of the mapping.
* Every pool still sees them on the mapped tier. `ngram_copy_card` selects pinned memory a
* device kernel reads over the link; otherwise locked memory the host gather reads. */
@@ -314,6 +322,8 @@ private:
void pin_mapped(const Program& prog, Plan* p);
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
int pin_towers(const Config& cfg, Plan* p) const;
int pin_draft_experts(const Program& prog, const Config& cfg, Plan* p) const;
void pin_hot(const Config& cfg, Plan* p) const;
void build_classes(Plan* p);
void rank_units(Plan* p, std::vector<int32_t>* order) const;
int assign(Plan* p);
@@ -349,6 +359,11 @@ struct WeightFootprint {
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
int64_t expert_unit_max = 0; /* the largest expert unit's slot */
/* A draft head's routed experts (layers at meta.n_layers and above, when the program has a
* drafter): the part of `experts` a host-pinned --draft-expert-placement takes out of the host
* pool's room for the trunk, and the largest such unit. */
int64_t draft_experts = 0;
int64_t draft_unit_max = 0;
/* Upper bound on an expert-tiered plan's spare slab: per expert slab class, the shadow slots,
* staging ring and tail pad (Planner::assign_expert_tiered). Same weight budget as residents. */
int64_t expert_spare = 0;
@@ -400,6 +415,11 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
* the host pool. */
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
/* The same floor once --draft-expert-placement host has taken the drafter's experts out of the
* plane the strategy places: the trunk's floor against the whole host room. The drafter's units
* share the trunk's slab classes, so no spare is added. With no drafter it is expert_vram_floor. */
int64_t expert_vram_floor_draft_hosted(const WeightFootprint& wf, int64_t host_room);
/* Checks that the plan and this rank's weights pool used the same split: Plan::vram_budget must
* equal the pool Pools::configure allocated, or the slab and the pool disagree silently. Returns
* RAD_E_STATE, logging the rank and both sizes, when they differ. */
+66
View File
@@ -479,4 +479,70 @@ void ExpertStats::stop() {
ExpertStats::~ExpertStats() { stop(); }
/* ------------------------------------------------------------------ --expert-profile */
int xs_profile_load(const std::string& path, std::vector<RadFileProfile>* out, int32_t* n_trunk) {
if (!out) return RAD_E_INVAL;
out->clear();
if (n_trunk) *n_trunk = -1;
FILE* f = std::fopen(path.c_str(), "r");
if (!f) {
RAD_ERR("--expert-profile: cannot read %s: %s", path.c_str(), std::strerror(errno));
return RAD_E_IO;
}
std::string text;
char buf[1 << 16];
while (const size_t n = std::fread(buf, 1, sizeof buf, f)) text.append(buf, n);
const bool bad = std::ferror(f) != 0;
std::fclose(f);
if (bad) {
RAD_ERR("--expert-profile: reading %s failed", path.c_str());
return RAD_E_IO;
}
nlohmann::json j;
try { j = nlohmann::json::parse(text); }
catch (const nlohmann::json::exception& e) {
RAD_ERR("--expert-profile: %s is not JSON: %s", path.c_str(), e.what());
return RAD_E_INVAL;
}
if (!j.is_object() || j.value("format", "") != "radiance-expert-stats/1" ||
!j.contains("counts") || !j["counts"].contains("decode") ||
!j["counts"]["decode"].is_array()) {
RAD_ERR("--expert-profile: %s is not a radiance-expert-stats/1 file with decode counts",
path.c_str());
return RAD_E_INVAL;
}
if (n_trunk && j.contains("n_trunk_layers") && j["n_trunk_layers"].is_number_integer())
*n_trunk = j["n_trunk_layers"].get<int32_t>();
const auto& rows = j["counts"]["decode"];
int64_t kept = 0;
for (size_t l = 0; l < rows.size(); ++l) {
if (!rows[l].is_array()) continue;
uint64_t sum = 0;
for (const auto& c : rows[l])
if (c.is_number_unsigned() || c.is_number_integer())
sum += c.get<uint64_t>();
if (sum == 0) continue;
for (size_t e = 0; e < rows[l].size(); ++e) {
const auto& c = rows[l][e];
if (!(c.is_number_unsigned() || c.is_number_integer())) continue;
const uint64_t n = c.get<uint64_t>();
if (n == 0) continue;
RadFileProfile p{};
p.layer = (int32_t)l;
p.expert = (int32_t)e;
p.share = (float)((double)n / (double)sum);
out->push_back(p);
++kept;
}
}
if (kept == 0)
RAD_WARN("--expert-profile: %s has no decode selections; the planner ranks from the "
"container's profile", path.c_str());
else
RAD_INFO("--expert-profile: %lld decode-hot entries over %zu layers from %s",
(long long)kept, rows.size(), path.c_str());
return RAD_OK;
}
} /* namespace rad */
+7
View File
@@ -210,4 +210,11 @@ private:
std::mutex file_mu_; /* one write at a time */
};
/* --expert-profile FILE: the planner's ranking, from a radiance-expert-stats JSON's `decode`
* counts. One entry per (layer, expert) with a positive count, its share that count over the
* layer's decode selections, so a layer's hottest expert ranks above another layer's merely busy
* one. `n_trunk` is the file's trunk layer count, or -1 where it names none. Returns RAD_E_IO on a
* missing or unreadable file and RAD_E_INVAL on one that is not this format. */
int xs_profile_load(const std::string& path, std::vector<RadFileProfile>* out, int32_t* n_trunk);
} /* namespace rad */
+23
View File
@@ -907,6 +907,14 @@ struct Config {
* store is opened (checkpoint_slots_auto in core/mem/prefix.h). */
int64_t checkpoint_slots = -1;
bool prefix_cache = true;
/* --prefix-resume exact|nearest. Exact (the default) resumes a prefix hit only on the grid an
* idle server's cold prefill chunks the same prompt on (ChunkGeometry::grid), and takes a
* prompt's tail snapshot where its last chunk starts: the hit recomputes the cold run's own
* chunks, so its output is the cold run's bit for bit, where a kernel rounds a row differently
* at another chunk length. Nearest resumes at the deepest snapshot or block, a prompt's tail
* snapshot at its last quantum boundary: up to a chunk less re-prefilled a turn, and a hit that
* can differ from a cold run in the last bits (a near-tie in greedy text). */
bool prefix_exact = true;
/* geometric-backoff | tip-only | keep-all. §19.1 records the default as unmeasured;
* core/mem/prefix.h ships the two extremes so they can be compared. */
std::string checkpoint_policy = "geometric-backoff";
@@ -1079,6 +1087,21 @@ struct Config {
/* --expert-stats FILE: count the routed experts every layer selects, by step kind, and write
* the counts to FILE as JSON every 30 s and at shutdown (place/xstats.h). Empty is off. */
std::string expert_stats;
/* --expert-profile FILE: a radiance-expert-stats JSON (place/xstats.h) whose `decode` counts
* rank the expert plane, instead of the container's activation profile. Empty serves the
* container's profile. */
std::string expert_profile;
bool expert_profile_given = false;
/* --expert-pin-top F: pin the hottest F of the routed experts (0 < F <= 1) by the profile's
* share, keeping them resident: heat never demotes them. 0 is off. */
float expert_pin_top = 0.0f;
bool expert_pin_top_given = false;
/* --draft-expert-placement auto|host: a draft head's (MTP/DSpark) routed experts are pinned in
* the host pool before any strategy runs, streamed in place like a pooled expert. `auto` (the
* default) leaves them to the strategy. `host` is what lets a drafter's experts fit beside a
* trunk that already fills the card. */
std::string draft_expert_placement = "auto";
bool draft_expert_placement_given = false;
/* --live: the live view (spec §16). Off by default like everything else in that section. */
bool live_view = false;
+14 -4
View File
@@ -87,11 +87,20 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
verify_ = std::getenv("RADIANCE_DEBUG_TIER_VERIFY") != nullptr;
verify_rep_ = verify_ && !leader_ && rep_bytes_ > 0;
/* A group whose blocks are shorter than an entry is listed once per block it holds there. */
size_t n_groups = 0;
for (size_t i = 0; i < gi_.size(); ++i) {
bool seen = false;
for (size_t j = 0; j < i && !seen; ++j) seen = gi_[j].g == gi_[i].g;
if (!seen) ++n_groups;
}
const std::string blocks =
n_groups != gi_.size() ? fmt(" in %zu blocks", gi_.size()) : std::string();
char buf[400];
std::snprintf(buf, sizeof buf,
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s, batches of %d through "
"gather_rows/scatter_rows at u8",
gi_.size(), humanb(entry_bytes_).c_str(),
"kv tier transfer: %zu paged group(s), %s an entry%s%s%s%s, batches of %d "
"through gather_rows/scatter_rows at u8",
n_groups, humanb(entry_bytes_).c_str(), blocks.c_str(),
rep_bytes_ > 0 ? " (" : "",
rep_bytes_ > 0 ? humanb(rep_bytes_).c_str() : "",
rep_bytes_ > 0 ? " of it replicated on every rank and held once a slot)" : "",
@@ -143,7 +152,8 @@ int TierExec::slot_layout(const std::vector<const KVManager*>& ranks,
return RAD_E_STATE;
}
L.rep_bytes += p0->bytes_per_block;
L.replicated.push_back(p0->name);
if (std::find(L.replicated.begin(), L.replicated.end(), p0->name) == L.replicated.end())
L.replicated.push_back(p0->name);
}
int64_t slot = L.rep_bytes;
for (size_t i = 0; i < ranks.size(); ++i) {
+3 -2
View File
@@ -46,8 +46,9 @@ namespace rad {
class TierExec {
public:
~TierExec();
/* `groups` is PrefixCache::cached_groups(): the paged groups an entry holds a block in, in the
* order of the entry's `blocks` vector. The staging layout is derived from them here only.
/* `groups` is PrefixCache::entry_groups(): the group of each block an entry holds, in the
* order of the entry's `blocks` vector (a group with blocks shorter than the entry is listed
* once per block). The staging layout is derived from them here only.
* `max_batch` is the staging buffer in entries, `max_copy` the most entries per copy out and
* `max_chain` the longest restore chain; the index buffers are sized from the last two. */
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers,
+37 -15
View File
@@ -391,7 +391,10 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
* by a repetition count (upstream's cap of 2000 rejects ordinary schemas such as
* `maxLength: 8000`). It is linear in the count, and nothing after the parse is worse than
* linear in the rules; the mask plan gives every link past the longest token one class. So
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`. */
* `[^"]{0,8000}` costs about a megabyte and yields the same plan as `[^"]{0,1999}`.
*
* S'(x) depends only on S and x, so the links are shared: every bounded repetition of the same
* operand points into one chain (rep_links_), and S{0,2000} after S{0,4000} builds nothing. */
auto handle_repetitions = [&](uint64_t min_times, uint64_t max_times) {
const bool no_max = max_times == UINT64_MAX;
if (last_sym_start == rule.size())
@@ -407,17 +410,30 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
/* A refusal names the repetition the client wrote. */
try {
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
/* A bounded repetition's chain of links for this operand, shared with every earlier
* bounded repetition of it; only the links it lacks are built. */
std::vector<uint32_t>* links = nullptr;
uint64_t n_new = n_opt;
if (!no_max && n_opt > 0) {
std::vector<std::pair<uint32_t, uint32_t>> key;
key.reserve(prev_rule.size());
for (const auto& e : prev_rule) key.emplace_back((uint32_t)e.type, e.value);
links = &rep_links_[std::move(key)];
n_new = n_opt > links->size() ? n_opt - links->size() : 0;
}
/* Charge the copies up front: the operand once per required count beyond the first,
* and once per optional rule plus its reference, ALT and END. Counts reach 2^64 - 2,
* so overflow saturates and is refused before the loops run. Each generated rule's
* name and slot are charged again in generate_symbol_id. */
* and once per optional rule built plus its reference, ALT and END. Counts reach
* 2^64 - 2, so overflow saturates and is refused before the loops run. Each generated
* rule's name and slot are charged again in generate_symbol_id. */
{
const uint64_t w = prev_rule.size();
const uint64_t n_rest = no_max ? 1 : max_times - min_times;
uint64_t req = 0, opt = 0, copies = 0, bytes = 0;
const bool wraps =
__builtin_mul_overflow(min_times > 1 ? min_times - 1 : 0, w, &req) ||
__builtin_mul_overflow(n_rest, w + 3, &opt) ||
__builtin_mul_overflow(n_new, w + 3, &opt) ||
__builtin_add_overflow(req, opt, &copies) ||
__builtin_mul_overflow(copies, (uint64_t)sizeof(GbnfElement), &bytes);
charge(wraps ? UINT64_MAX : bytes);
@@ -430,21 +446,26 @@ const char* GbnfParser::parse_sequence(const char* src, const std::string& rule_
rule.insert(rule.end(), prev_rule.begin(), prev_rule.end());
}
uint32_t last_rec_rule_id = 0;
const uint64_t n_opt = no_max ? 1 : max_times - min_times;
GbnfRule rec_rule(prev_rule);
for (uint64_t i = 0; i < n_opt; i++) {
rec_rule.resize(prev_rule.size());
if (no_max) {
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (i > 0 || no_max)
rec_rule.push_back({ GRE_RULE_REF, no_max ? rec_rule_id : last_rec_rule_id });
rec_rule.push_back({ GRE_RULE_REF, rec_rule_id });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
last_rec_rule_id = rec_rule_id;
rule.push_back({ GRE_RULE_REF, rec_rule_id });
} else if (n_opt > 0) {
while (links->size() < n_opt) {
rec_rule.resize(prev_rule.size());
const uint32_t rec_rule_id = generate_symbol_id(rule_name);
if (!links->empty()) rec_rule.push_back({ GRE_RULE_REF, links->back() });
rec_rule.push_back({ GRE_ALT, 0 });
rec_rule.push_back({ GRE_END, 0 });
add_rule(rec_rule_id, rec_rule);
links->push_back(rec_rule_id);
}
rule.push_back({ GRE_RULE_REF, (*links)[n_opt - 1] });
}
if (n_opt > 0) rule.push_back({ GRE_RULE_REF, last_rec_rule_id });
} catch (const std::runtime_error& ex) {
throw std::runtime_error("the repetition {" + std::to_string(min_times) + "," +
(no_max ? std::string() : std::to_string(max_times)) + "}: " +
@@ -580,6 +601,7 @@ const char* GbnfParser::parse_rule(const char* src) {
int GbnfParser::parse(const char* src, std::string* err) {
if (!src) return RAD_E_INVAL;
budget_used_ = 0;
rep_links_.clear();
depth_ = 0;
try {
const char* pos = parse_space(src, true);
+7
View File
@@ -146,6 +146,13 @@ private:
uint32_t depth_ = 0;
void charge(uint64_t bytes);
/* The optional links of bounded repetitions, keyed by the repeated operand's elements:
* links[k - 1] is S'(k) ::= S S'(k-1) |, so every S{m,n} over the same S shares one chain and
* builds only the links past the longest it has (handle_repetitions). A JSON schema's
* `maxLength` bounds all repeat `char`, so a schema with many of them costs its longest bound
* once instead of the sum of them. */
std::map<std::vector<std::pair<uint32_t, uint32_t>>, std::vector<uint32_t>> rep_links_;
uint32_t get_symbol_id(const char* src, size_t len);
uint32_t generate_symbol_id(const std::string& base);
void add_rule(uint32_t id, const GbnfRule& rule);
+43 -2
View File
@@ -143,15 +143,49 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
* checkpoints land wherever a step ends (§7.3). */
g.min_max_tok = g.quantum;
*out = g;
if (cfg.max_tok < g.min_max_tok) {
*out = g;
RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least "
"%lld, so a chunk can end on a linear-state boundary: %s",
(long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
return RAD_E_INVAL;
}
/* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A
* prefill alone in its step takes the budget, rounded down to the quantum, and stops at every
* interval boundary it reaches where chunks split at the interval (linear state, or periodic
* window snapshots); a span carries h intervals from the second one on. An interval past the
* budget must then be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the grid every cold run cuts: rounded up, as the quantum rounds it, since a longer
* interval costs only retention. */
const int64_t I0 = g.checkpoint_interval;
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
const int64_t budget_chunk = cfg.max_tok / g.quantum * g.quantum;
g.exact = cfg.prefix_exact && cfg.prefix_cache;
if (g.exact && splits && I0 > budget_chunk && I0 % budget_chunk != 0) {
g.checkpoint_interval = align_up(I0, budget_chunk);
RAD_WARN("--checkpoint-interval %lld resolves to %lld: --prefix-resume exact needs it a "
"multiple of the %lld-token prefill chunk (--max-num-batched-tokens %lld) so "
"every checkpoint is where a cold prefill's chunk ends; give a multiple of %lld, "
"or --prefix-resume nearest to keep %lld", (long long)cfg.checkpoint_interval,
(long long)g.checkpoint_interval, (long long)budget_chunk, (long long)cfg.max_tok,
(long long)budget_chunk, (long long)I0);
}
if (g.exact) {
const int64_t I = g.checkpoint_interval;
if (splits && I <= budget_chunk) {
const int64_t h = g.span > 1 ? std::max<int64_t>(1, std::min(g.span, cfg.max_tok / I))
: 1;
g.grid = h * I;
g.grid_origin = h > 1 ? I : 0;
} else {
g.grid = budget_chunk;
g.grid_origin = 0;
}
}
*out = g;
/* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
* when the interval is below --max-num-batched-tokens, raising the budget does not change the
* chunk; the log line makes that visible. tip-only window snapshots do not
@@ -167,6 +201,13 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
eff >= cfg.max_tok ? ""
: g.span > 1 ? " (the checkpoint interval times the span, not the budget)"
: " (the checkpoint interval, not the budget)");
if (g.exact)
RAD_INFO("prefix resume: exact -- a hit resumes only where an idle server's cold prefill "
"of the same prompt starts a chunk (every %lld tokens%s) and a prompt's tail "
"snapshot is taken where its last chunk starts, so the hit recomputes the cold "
"run's own chunks and answers bit-identically; a turn re-prefills up to one chunk "
"more than --prefix-resume nearest", (long long)g.grid,
g.grid_origin > 0 ? fmt(" from %lld", (long long)g.grid_origin).c_str() : "");
if (cfg.prefill_span > 1) {
/* What the span does here, said once: the intervals the budget holds can be fewer than
* the flag asks for, and a model without an interval grid spans nothing. */
+22
View File
@@ -60,7 +60,29 @@ struct ChunkGeometry {
* tip-only, which keeps the tail alone and so splits no chunk at the interval. */
bool window_periodic = false;
/* --prefix-resume exact (Config::prefix_exact): a prefix hit resumes only where a cold prefill
* of the same prompt starts a chunk, so the tokens a hit recomputes are cut into the chunks a
* cold run cuts them into. A kernel may round a row differently at another chunk length (a
* split-K count chosen from M, a small-M path); computed in the same chunks, the hit's output
* is the cold run's, bit for bit, on an idle server. The grid is where an idle server's prefill
* chunks start: 0, then grid_origin + k * grid. `grid` is the checkpoint interval where chunks
* split at it and it fits the budget, times the span from the second interval on (origin = the
* interval), and otherwise --max-num-batched-tokens rounded down to the quantum (the interval
* is then rounded up to a multiple of it). Zero when not exact. */
bool exact = false;
int64_t grid = 0;
int64_t grid_origin = 0;
bool checkpoints() const { return checkpoint_interval > 0; }
/* The deepest grid position at or below `pos`; `pos` itself when not exact. */
int64_t grid_floor(int64_t pos) const {
if (pos <= 0) return 0;
if (!exact || grid <= 0) return pos;
if (pos < grid_origin) return 0;
return grid_origin + (pos - grid_origin) / grid * grid;
}
bool on_grid(int64_t pos) const { return grid_floor(pos) == pos; }
};
/* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration
+6 -4
View File
@@ -172,7 +172,7 @@ struct IPrefixCache {
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
* `blocks_out` receives block ids per cached group, in cached_groups() order, for
* IKVManager::adopt. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `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;
@@ -187,10 +187,12 @@ struct IPrefixCache {
/* Release the least recently used entries and their KV references. The scheduler tries this
* before preempting a running request. */
virtual int64_t evict(int64_t n_entries) = 0;
/* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike
/* Free up to `n_entries` for the reserve without losing anything a later turn needs. Unlike
* evict(), it skips entries a live sequence still holds (no block would be freed) and entries
* whose only copy is in VRAM. Returns the number of blocks freed. */
virtual int64_t trim(int64_t n_blocks) = 0;
* whose only copy is in VRAM. An entry is one block in each cached group, or more in a group
* whose blocks are shorter than the entry (PrefixCache::blocks_per_entry). Returns the number
* of entries freed. */
virtual int64_t trim(int64_t n_entries) = 0;
/* Drop every entry in every tier. Implementations with idle tiers must override this: there,
* evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */
+96 -19
View File
@@ -10,6 +10,7 @@
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <numeric>
namespace rad {
@@ -97,9 +98,9 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
if (kv->block_tokens((int32_t)i) <= 0) continue;
++n_paged;
const auto& cg = pc->cached_groups();
/* Snapshots are taken only where the trunk has a window to snapshot too
* (ChunkGeometry::window_ckpt); without them no drafter window rides in one. */
if (cfg.prefix_cache && geo_.window_ckpt && kv->window_snapshot((int32_t)i) &&
/* Snapshots are taken only on a checkpoint grid (ChunkGeometry::checkpoints()), the
* window's alone or beside linear state; without one no window rides in a slot. */
if (cfg.prefix_cache && geo_.checkpoints() && kv->window_snapshot((int32_t)i) &&
std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end())
++n_snap;
}
@@ -110,19 +111,27 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
}
/* The trunk's share: a paged group a trunk layer reads (a bound layer below the trunk's layer
* count; a drafter borrows from base_layer up) that the cache does not index. Recomputing the
* tail cannot repair that hole; see scheduler.h. */
* tail cannot repair that hole; see scheduler.h. A windowed group is restored by a hit that
* resumes at a window snapshot (a checkpoint slot carries the trunk's window, with or without
* linear state beside it); any other such group refuses every hit. */
hit_holes_trunk_ = false;
hit_needs_window_ = false;
for (size_t i = 0; i < prog.kv_groups.size(); ++i) {
if (kv->block_tokens((int32_t)i) <= 0) continue;
bool trunk = false;
for (int l : prog.kv_groups[i].layers) if (l < prog.meta.n_layers) { trunk = true; break; }
if (!trunk) continue;
const std::vector<int32_t>& cg = pc->cached_groups();
if (std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) { hit_holes_trunk_ = true; break; }
if (std::find(cg.begin(), cg.end(), (int32_t)i) != cg.end()) continue;
if (prog.kv_groups[i].decl.kind == RAD_KV_WINDOW) hit_needs_window_ = true;
else hit_holes_trunk_ = true;
}
if (hit_holes_trunk_ && cfg.prefix_cache)
RAD_INFO("prefix cache: a trunk layer's paged group is neither prefix-cached nor carried "
"by a checkpoint slot -- a hit re-prefills");
else if (hit_needs_window_ && cfg.prefix_cache)
RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit "
"resumes from a window snapshot (a checkpoint slot) or re-prefills");
"resumes from a window snapshot (a checkpoint slot)");
if (cfg.prefill_interleave > 0)
RAD_INFO("scheduler: --prefill-interleave %lld: after a prefill chunk that leaves its "
"prompt unfinished while other sequences decode, the next %lld steps carry "
@@ -470,14 +479,26 @@ void Scheduler::trim_prefix_cache() {
if (!pc_ || !cfg_.prefix_cache) return;
const std::vector<int32_t>& cg = pc_->cached_groups();
if (cg.empty()) return;
const int32_t g = cg[0];
const int64_t total = kv_->total_blocks(g);
if (total <= 0) return;
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
/* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded by
* the live mark, so a pool that returned its unused top would read as nearly full and the
* trim would drain the cache for room the pool can grow back into. */
const int64_t short_by = reserve - (total - kv_->held_blocks(g));
/* An entry covers the lcm of the cached groups' blocks and holds that over a group's block of
* its blocks (PrefixCache::blocks_per_entry); the trim asks for entries, as many as the group
* furthest short needs. */
int64_t entry = 0;
for (int32_t g : cg) {
const int64_t bs = kvgeom_.g[(size_t)g].block_size;
if (bs > 0) entry = entry > 0 ? std::lcm(entry, bs) : bs;
}
int64_t short_by = 0;
for (int32_t g : cg) {
const int64_t total = kv_->total_blocks(g), bs = kvgeom_.g[(size_t)g].block_size;
if (total <= 0 || bs <= 0) continue;
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
/* Free against the carve, not free_blocks(): on an elastic pool free_blocks() is bounded
* by the live mark, so a pool that returned its unused top would read as nearly full and
* the trim would drain the cache for room the pool can grow back into. */
const int64_t blocks = reserve - (total - kv_->held_blocks(g));
const int64_t per = std::max<int64_t>(entry / bs, 1);
if (blocks > 0) short_by = std::max(short_by, (blocks + per - 1) / per);
}
if (short_by > 0) (void)pc_->trim(short_by);
}
@@ -850,7 +871,38 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
int64_t want = remaining < budget ? remaining : budget;
if (geo_.checkpoints()) {
if (geo_.checkpoints() && geo_.exact) {
/* --prefix-resume exact: checkpoints only where an idle cold prefill of this prompt starts
* a chunk (ChunkGeometry::grid), so a hit that resumes at one recomputes the cold run's
* own chunks. Splits as below at the interval and a span's end; the tail snapshot is at
* the start of the prompt's last chunk (tail_checkpoint), a boundary an idle chunk already
* ends on, so it costs a copy and no step. A step that shares the budget (another
* request, decode rows) may straddle it, and is split there. */
const int64_t I = geo_.checkpoint_interval;
const bool periodic = !geo_.window_ckpt || geo_.window_periodic;
const int64_t next = periodic ? ((n_computed / I) + 1) * I : INT64_MAX;
int64_t far = next;
if (geo_.span > 1 && span_now_ && n_computed >= I && n_computed % I == 0)
far = n_computed + geo_.span * I;
if (n_computed + want > far)
want = far - n_computed;
else if (n_computed + want > next && n_computed + want < n_target)
want = (n_computed + want) / I * I - n_computed;
const int64_t tail = tail_checkpoint(n_target);
if (tail > n_computed && n_computed + want >= tail) {
want = tail - n_computed;
if (checkpoint_pos) *checkpoint_pos = tail;
} else if (periodic && (n_computed + want) % I == 0 && geo_.on_grid(n_computed + want)) {
if (checkpoint_pos) *checkpoint_pos = n_computed + want;
}
/* A request's own checkpoint (Request::checkpoint_at) as below, wherever it falls: the
* head the request shares with others resumes there by design. */
const int64_t keep = keep_at / geo_.quantum * geo_.quantum;
if (keep > n_computed && keep <= n_computed + want && keep <= n_target) {
want = keep - n_computed;
if (checkpoint_pos) *checkpoint_pos = keep;
}
} else if (geo_.checkpoints()) {
const int64_t I = geo_.checkpoint_interval;
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
if (geo_.window_ckpt && !geo_.window_periodic) {
@@ -934,6 +986,16 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
int64_t Scheduler::tail_checkpoint(int64_t target) const {
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
if (I <= 0 || Q <= 0) return -1;
if (geo_.exact) {
/* --prefix-resume exact: where the prompt's last chunk starts on the resume grid, so an
* exact repeat re-prefills that chunk as the cold run did, and an appended turn that chunk
* and what it added. A window snapshot keeps its margin below (next comment): the grid
* point under the end less a block. Past the first interval, as below. */
const int64_t margin = geo_.window_ckpt ? std::max<int64_t>(Q, 16) : 1;
const int64_t t = geo_.grid_floor(target - margin);
if (geo_.window_ckpt) return t >= I ? t : -1;
return t > I ? t : -1;
}
const int64_t tail = target / Q * Q;
/* A window snapshot is taken at the tail of any prompt of an interval or more, a block short
* of the end: the next turn re-renders the last few tokens (the generation prompt is replaced
@@ -1136,6 +1198,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
if (reuse > last) reuse = last;
if (reuse < 0) reuse = 0;
/* --prefix-resume exact: resume only on the grid an idle cold prefill chunks this prompt
* on (ChunkGeometry::grid), so the tokens recomputed below are cut into the cold run's own
* chunks. A snapshot is already on it (plan_chunk writes none off it, but for a request's
* own Request::checkpoint_at); a hit at a block (no snapshot needed) steps back to it. */
if (geo_.exact && reuse > 0 &&
!(geo_.checkpoints() && h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens)) {
const int32_t g = (int32_t)geo_.grid_floor(reuse);
if (g < reuse)
RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at %lld, on the "
"%lld-token chunk grid (--prefix-resume exact)", (unsigned long long)r.id,
(long long)reuse, (long long)g, (long long)geo_.grid);
reuse = g;
}
/* A hit on a hybrid model needs a checkpoint. The adopted blocks cover the paged
* attention groups, but nothing covers a recurrent group, whose state lives in a
* per-sequence slot; skipping tokens also requires restoring that state (`ckpt_src`,
@@ -1158,9 +1234,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
(unsigned long long)r.id, (long long)h.n_attn_tokens, (long long)reuse);
}
/* A window snapshot covers the trunk's windowed groups at the checkpoint only. The lookup
* clamped the hit to it (a window counts as state there), so a hit with a slot is exactly
* at a snapshot; one without is no hit. */
const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 &&
* clamped the hit to it (a window counts as state there, and linear state beside it
* resumes there too), so a hit with a slot is exactly at a snapshot; one without is no
* hit. */
const bool win_hit = geo_.checkpoints() && kv_->has_window_snapshot() && reuse > 0 &&
h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens;
/* Windowed-group clamp: the trunk's own KV includes a paged group the cache does not
@@ -1173,7 +1250,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
*
* A drafter's own group (bound at base_layer and above) is not this clamp's business:
* draft refill caps the hit so the recompute covers the drafter's window. */
if (reuse > 0 && hit_holes_trunk_ && !win_hit) {
if (reuse > 0 && (hit_holes_trunk_ || (hit_needs_window_ && !win_hit))) {
reuse = 0;
s.hit_cut = SchedReq::HitCut::Window;
RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not "
+6 -2
View File
@@ -491,12 +491,16 @@ private:
* place. */
bool hit_holes_draft_ = true;
/* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index and
* no checkpoint slot carries? Unlike a drafter hole, recomputing the tail cannot repair it;
* every hit is refused (admit_one). */
bool hit_holes_trunk_ = false;
/* The end-of-generation ids, sorted and unique (set_eog), and a lookup in them. */
std::vector<int32_t> eog_;
bool is_eog(int32_t id) const;
/* A windowed trunk group, which the cache does not index: a hit stands only where it resumes
* at a window snapshot (IKVManager::has_window_snapshot), which restores the window. */
bool hit_needs_window_ = false;
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
* not declare one, in which case admission and commit are exactly as before. A sequence with
+19 -1
View File
@@ -38,7 +38,8 @@
* first steps run at `size` divided by it and the latent is enlarged to `size` for the last
* `upscale_refine_steps` (the model's default when absent; abi/rad_builder.h, RadVideoGenDecl).
* The video object of an upscaled video says how it was made: the factor, the refine steps and the
* small size (`upscale_from`).
* small size (`upscale_from`). Keyframes ride it: each is prepared at both sizes and pinned at the
* one the steps run at.
*
* The prompt is the model's template with `{prompt}` filled; the template is tokenised with its
* special tokens and the prompt without, so a caller cannot write control tokens into it.
@@ -742,6 +743,23 @@ HttpResponse Server::handle_video_create(const HttpRequest& req) {
&canvas[i], &why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why);
pixels(m, { canvas[i] });
/* A latent upscale's first steps pin it at their own size, prepared the same way. */
if (r->upscale > 1.0) {
RadVideoGenDecl geo{}; /* video_small_size reads the size multiple only */
geo.size_multiple = info.size_multiple;
int32_t sw = 0, sh = 0;
gen::video_small_size(geo, r->width, r->height, r->upscale, &sw, &sh);
mm::Frame small;
if (deps_.mm->encoder_image_canvas((const uint8_t*)m.data.data(), m.data.size(),
sw, sh,
m.kind == gen::VideoRefMedia::LAST_FRAME ||
first_center,
&small, &why) < 0)
return bad(m.name.c_str(), "'" + m.name + "' could not be decoded: " + why);
m.small_h = small.h;
m.small_w = small.w;
m.small_pixels.assign(small.rgb.begin(), small.rgb.end());
}
}
}
+6
View File
@@ -320,6 +320,12 @@ int parse_tokenizer_json(const char* path, VocabBuild& out);
/* Same, from an in-memory buffer, for a tokenizer.json that arrived some other way. */
int parse_tokenizer_json_buf(std::string_view json, const char* origin, VocabBuild& out);
/* Read a standalone chat template file into out.chat_template, trailing newlines stripped.
* A release that ships no template (DeepSeek's does not) needs one from elsewhere; the caller
* passes the file. An unreadable or empty file is an error, never a silent skip. Returns
* RAD_OK, or RAD_E_IO when the file cannot be read. */
int read_chat_template_path(const char* path, VocabBuild& out);
/* Build a VocabBuild from a GGUF's tokenizer.ggml.* metadata.
*
* GGUF has no declared chain, only `tokenizer.ggml.pre`, a name llama.cpp derived by hashing the
+21
View File
@@ -638,6 +638,27 @@ void read_config(const std::string& dir, VocabBuild& out) {
} /* namespace */
int read_chat_template_path(const char* path, VocabBuild& out) {
if (!path) return RAD_E_INVAL;
std::ifstream f(path);
if (!f) {
RAD_ERR("tokenizer: cannot read chat template %s", path);
return RAD_E_IO;
}
std::ostringstream ss;
ss << f.rdbuf();
std::string t = ss.str();
while (!t.empty() && (t.back() == '\n' || t.back() == '\r')) t.pop_back();
if (t.empty()) {
RAD_ERR("tokenizer: chat template %s is empty", path);
return RAD_E_IO;
}
RAD_INFO("tokenizer: chat template from %s (%zu bytes), overriding the checkpoint's",
path, t.size());
out.chat_template = std::move(t);
return RAD_OK;
}
/* ================================================================== parse_tokenizer_json */
namespace {
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""engram_tables.py -- the Engram's derived tables of a DeepSeek-V4.1 release, for `rad-convert --add`.
The release ships the Engram's embedding tables but not the hash constants inference/engram.py
computes at load: the compressed token map (the tokenizer's normalisers over every token's decode),
the n-gram hash multipliers (numpy PCG64 streams) and the per-head bucket moduli (primes) with their
offsets into the joined table. This tool computes them in Radiance's own terms -- no llama.cpp
converter, no transformers: the token map is built from the release's tokenizer.json by reimplementing
HuggingFace's ByteLevel decode and the normaliser sequence, and the multipliers from numpy's PCG64.
It writes the four arrays as a small safetensors with the GGUF's element types (token map I32; the
rest U64 in the GGUF, which the core reads as I64):
engram.token_map I32 [vocab]
engram.layer_multipliers I64 [n_engram_layers * max_ngram]
engram.head_vocab_sizes I64 [n_engram_layers * (max_ngram - 1) * n_heads]
engram.head_offsets I64 [same] (absolute row offsets into the joined table)
The deepseek41 plugin reads them under these names when the checkpoint is the release
(arch/deepseek41 ckpt_name). Reads config.json and tokenizer.json only (small).
usage: python3 data/engram_tables.py RELEASE_DIR OUT.safetensors
"""
import argparse
import json
import math
import struct
import sys
import unicodedata
from pathlib import Path
import numpy as np
SENTINEL = "\ue000"
def _is_prime(n: int) -> bool:
if n < 2 or n % 2 == 0:
return n == 2
return all(n % d for d in range(3, math.isqrt(n) + 1, 2))
def engram_primes(n_layers: int, max_ngram_size: int, n_heads: int, vocab_size: int) -> list[list[list[int]]]:
"""EngramLayout.from_args: [layer][ngram order 2..max][head] bucket moduli, never reused across layers."""
seen: set[int] = set()
out: list[list[list[int]]] = []
for _ in range(n_layers):
per_ngram = []
for _ in range(max_ngram_size - 1):
sizes, cur = [], vocab_size - 1
for _ in range(n_heads):
cand = cur + 1
while not _is_prime(cand) or cand in seen:
cand += 1
seen.add(cand)
sizes.append(cand)
cur = cand
per_ngram.append(sizes)
out.append(per_ngram)
return out
def engram_multipliers(layer_ids: list[int], max_ngram_size: int, compressed_vocab_size: int) -> list[list[int]]:
"""compute_hash_multipliers: odd, bounded so that token_id * multiplier cannot overflow int64."""
bound = max(1, (np.iinfo(np.int64).max // compressed_vocab_size) // 2)
rows = []
for layer_id in layer_ids:
rng = np.random.default_rng(10007 * layer_id)
values = rng.integers(low=0, high=bound, size=(max_ngram_size,), dtype=np.int64)
rows.append([int(v) * 2 + 1 for v in values])
return rows
def _bytes_to_unicode() -> dict[int, str]:
"""GPT-2's byte-level alphabet: the printable bytes map to themselves, the rest to U+0100+."""
bs = list(range(33, 127)) + list(range(161, 173)) + list(range(174, 256))
cs = bs[:]
n = 0
for b in range(256):
if b not in bs:
bs.append(b)
cs.append(256 + n)
n += 1
return dict(zip(bs, [chr(c) for c in cs]))
_byte_dec = {v: k for k, v in _bytes_to_unicode().items()}
def _byte_level_decode(token: str) -> str:
"""ByteLevel: the token's characters are the byte alphabet; join the bytes, decode UTF-8."""
raw = bytes(_byte_dec[c] for c in token)
return raw.decode("utf-8", errors="replace")
def _normalize(text: str) -> str:
"""The converter's normaliser sequence, step for step: NFKC, NFD, strip accents, lowercase,
collapse whitespace runs, trim, and keep a lone space as a sentinel."""
text = unicodedata.normalize("NFKC", text)
text = unicodedata.normalize("NFD", text)
text = "".join(c for c in text if not unicodedata.category(c).startswith("M"))
text = "".join(c.lower() if c.isupper() else c for c in text)
out, prev_space = [], False
for c in text:
if c in " \t\r\n":
if not prev_space:
out.append(" ")
prev_space = True
else:
out.append(c)
prev_space = False
text = "".join(out)
sentinel = False
if text == " ":
text, sentinel = SENTINEL, True
stripped = text.strip()
if sentinel:
return " " if stripped == SENTINEL else stripped.replace(SENTINEL, " ")
return stripped
def engram_compressed_token_map(release_dir: Path) -> tuple[list[int], int]:
"""token id -> compressed id (tokens that normalize alike collapse)."""
tok = json.load(open(Path(release_dir) / "tokenizer.json"))
vocab = tok["model"]["vocab"] # token string -> id
added = tok.get("added_tokens") or []
id_str: dict[int, str] = {i: s for s, i in vocab.items()}
for a in added:
id_str[a["id"]] = a["content"]
added_ids = {a["id"] for a in added}
key_to_new: dict[str, int] = {}
lookup = [0] * (max(id_str) + 1)
for token_id in range(max(id_str) + 1):
token = id_str.get(token_id)
if token is None:
lookup[token_id] = key_to_new.setdefault(f"<missing {token_id}>", len(key_to_new))
continue
if token_id in added_ids:
text = token
else:
text = _byte_level_decode(token)
if "\ufffd" in text:
key = token
else:
normalized = _normalize(text)
key = normalized if normalized else text
lookup[token_id] = key_to_new.setdefault(key, len(key_to_new))
return lookup, len(key_to_new)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("release")
ap.add_argument("out")
a = ap.parse_args()
cfg = json.load(open(Path(a.release) / "config.json"))
hp = {**cfg, **cfg.get("text_config", {})}
layer_ids = list(hp.get("engram_layer_ids") or [])
if not layer_ids:
sys.exit("the release has no Engram layers; nothing to write")
max_ngram, n_heads = hp["engram_max_ngram_size"], hp["engram_n_heads"]
primes = engram_primes(len(layer_ids), max_ngram, n_heads, hp["engram_vocab_size"])
for li, layer_primes in enumerate(primes):
if sum(p for per in layer_primes for p in per) != hp["engram_num_embeddings"][li]:
sys.exit(f"engram layer {layer_ids[li]}: prime sum != num_embeddings")
token_map, cvocab = engram_compressed_token_map(Path(a.release))
if cvocab != hp["engram_compressed_vocab_size"] or len(token_map) != hp["vocab_size"]:
sys.exit(f"compressed token map ({len(token_map)} -> {cvocab}) does not match the config")
sizes = [p for layer in primes for per in layer for p in per]
offsets = [sum(sizes[:i]) for i in range(len(sizes))]
mults = [m for row in engram_multipliers(layer_ids, max_ngram, cvocab) for m in row]
tensors = [("engram.token_map", "I32", "<i", token_map),
("engram.layer_multipliers", "I64", "<q", mults),
("engram.head_vocab_sizes", "I64", "<q", sizes),
("engram.head_offsets", "I64", "<q", offsets)]
header, blobs, off = {}, [], 0
for name, dt, fmt, vals in tensors:
b = struct.pack(f"<{len(vals)}{fmt[1]}", *vals)
header[name] = {"dtype": dt, "shape": [len(vals)], "data_offsets": [off, off + len(b)]}
blobs.append(b)
off += len(b)
header["__metadata__"] = {"format": "pt", "source": "radiance data/engram_tables.py"}
h = json.dumps(header, separators=(",", ":")).encode()
h += b" " * (-len(h) % 8)
with open(a.out, "wb") as f:
f.write(struct.pack("<Q", len(h)))
f.write(h)
for b in blobs:
f.write(b)
print(f"{a.out}: token_map {len(token_map)} -> {cvocab}; {len(layer_ids)} Engram layers {layer_ids}; "
f"{len(mults)} multipliers, {len(sizes)} heads, rows {sum(sizes)}")
if __name__ == "__main__":
main()
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""imatrix_merge.py -- add the fused gate_up entries an HF release needs to an imatrix.
DeepSeek-V4.1's release stores routed experts per expert and its shared expert as separate gate/up
weights, so the release's own imatrix (llama.cpp's collector output, run on the original checkpoint)
holds `<stem>.ffn_gate_exps` and `<stem>.ffn_up_exps`. Radiance's recipe fuses them
(`ffn_gate_up_exps.*`, `ffn_gate_up_shexp`), and the quantiser looks the importance up by the fused
name. This tool reads the imatrix, sums the two halves (the fused weight's input columns are the
gate's and the up's: llama.cpp sums them for fused tensors too), and writes a new imatrix with those
entries added. Everything else is carried through unchanged.
usage: python3 data/imatrix_merge.py IMATRIX IN OUT
"""
import sys
import numpy as np
import gguf
def load(path):
r = gguf.GGUFReader(path)
tensors = {}
for t in r.tensors:
tensors[t.name] = np.array(t.data, dtype=np.float32, copy=True) if t.tensor_type == 0 else None
return r, tensors
def base_parts(name):
if name.endswith(".in_sum2"):
return name[:-8]
if name.endswith(".counts"):
return name[:-7]
return None
def main() -> None:
im, out = sys.argv[1], sys.argv[3]
r, tensors = load(im)
if any(v is None for v in tensors.values()):
sys.exit("every imatrix tensor must be f32")
pairs = {}
for name in tensors:
base = base_parts(name)
if not base or not base.endswith(".weight"):
continue
stem_name = base[: -len(".weight")]
for suf, key in ((".ffn_gate_exps", "gate"), (".ffn_up_exps", "up"),
(".ffn_gate_shexp", "gate_sh"), (".ffn_up_shexp", "up_sh")):
if stem_name.endswith(suf):
stem = stem_name[: -len(suf)]
pairs.setdefault(stem, {})[key] = base
added = {}
for stem, p in pairs.items():
if "gate" in p and "up" in p:
g2, u2 = tensors[p["gate"] + ".in_sum2"], tensors[p["up"] + ".in_sum2"]
gc, uc = tensors[p["gate"] + ".counts"], tensors[p["up"] + ".counts"]
if g2.shape != u2.shape:
sys.exit(f"{stem}: gate {g2.shape} != up {u2.shape}")
added[f"{stem}.ffn_gate_up_exps.weight.in_sum2"] = g2 + u2
added[f"{stem}.ffn_gate_up_exps.weight.counts"] = gc + uc
if "gate_sh" in p and "up_sh" in p:
g2, u2 = tensors[p["gate_sh"] + ".in_sum2"], tensors[p["up_sh"] + ".in_sum2"]
gc, uc = tensors[p["gate_sh"] + ".counts"], tensors[p["up_sh"] + ".counts"]
if g2.shape != u2.shape:
sys.exit(f"{stem}: shexp gate {g2.shape} != up {u2.shape}")
added[f"{stem}.ffn_gate_up_shexp.weight.in_sum2"] = g2 + u2
added[f"{stem}.ffn_gate_up_shexp.weight.counts"] = gc + uc
n_layers = len({k.split(".")[1] for k in pairs})
w = gguf.GGUFWriter(out, "imatrix")
w.add_int32("imatrix.version", 2)
for name, v in tensors.items():
w.add_tensor(name, v, raw_shape=v.shape, raw_dtype=gguf.GGMLQuantizationType.F32)
for name, v in added.items():
w.add_tensor(name, v, raw_shape=v.shape, raw_dtype=gguf.GGMLQuantizationType.F32)
w.write_header_to_file()
w.write_kv_data_to_file()
w.write_tensors_to_file()
w.close()
print(f"{out}: {len(tensors)} carried, {len(added)} fused gate_up entries for {n_layers} layers")
if __name__ == "__main__":
main()
@@ -0,0 +1,36 @@
# Kernel rows a replay of this fixture reaches (rad-kbench --coverage).
# A row listed here and not reached fails the replay; regenerate with
# --coverage-write when a row is added or deliberately retired.
add_bf16
attn_paged_fp8_decode
cast_bf16_bf16
dflash_select_bf16
gated_quant_fp8_bf16
gather_rows_bf16
gemm_nt_bf16_m16
gemm_nt_bf16_tiled
gemm_nt_q_fp8a8_m16
gemm_nt_q_fp8a8_tiled
gemm_nt_q_gated_fp8a8
kv_store_fp8
layernorm_bf16
quant_act_fp8_bf16
quant_act_i8_bf16
rmsnorm_bf16
rmsnorm_quant_fp8_bf16
rope_bf16
row_topk_bf16
sample_argmax_f32
sample_dry_f32
sample_logprobs_f32
sample_mask_f32
sample_minp_f32
sample_penalties_f32
sample_pick_f32
sample_temp_f32
sample_topk_f32
sample_topp_f32
sample_typical_f32
sample_xtc_f32
scatter_rows_bf16
silu_mul_bf16
File diff suppressed because it is too large. Load diff
+54 -2
View File
@@ -52,6 +52,7 @@ driver. [`DOCKER.md`](DOCKER.md) covers it, with compose files per model.
| Optional | ROCm with `hipcc`, for AMD device kernels; without it you get the host backend. Set `ROCM_PATH` if ROCm is not at `/opt/rocm` |
| With a card | Resizable BAR on (Above 4G Decoding and Resizable BAR in the firmware setup). The host writes every dispatch's arguments into VRAM there. On a card whose BAR is smaller than its VRAM they stay in pinned host memory and every dispatch reads them over the link: on R9700s, Qwen3.8-27B fp8 decode steps take 0.4-1.8% longer at `--tp 1` and 2 than with the arguments in VRAM. Peer access needs the large BAR too, so at `--tp 2` and above such a card takes the collectives through host memory (§4.7) |
| Optional | OpenMP, used by the host kernel libraries if present |
| Optional | `libavformat-dev libavcodec-dev libavutil-dev libswscale-dev libswresample-dev` (ffmpeg 6+), for image, video and audio input. The probe is `RAD_WITH_FFMPEG` (`ON` fatal, `OFF` off, default `AUTO`): built without them the engine boots normal, serves text, and refuses every image/video/audio part with HTTP 500 — the configure log is the only warning (`radiance: no libavformat ...`). `GET /diagnostics` shows `media decoders` |
| Optional | `clang++` (or ROCm's), for `tests/r4d_emu` when the C++ compiler is g++; CMake 3.25+ for `CMakePresets.json` |
| Shell harnesses | `curl` and `jq` |
@@ -92,6 +93,27 @@ cmake --build build -j
ctest --test-dir build -L fast -j8 --output-on-failure
```
A ROCm SDK installed outside `/opt/rocm` — a userspace SDK tree under a virtualenv, a core-only
system install — needs more than `ROCM_PATH`: hipcc is found, then device compilation dies inside
`cuda_wrappers/cmath` with `Could not find standard C++ header 'cmath'`, because ROCm's clang
does not pick up the distro gcc's libstdc++ headers on its own. The flags that make it work:
```sh
ROCM=/path/to/_rocm_sdk_devel # the SDK root (the venv's site-packages/_rocm_sdk_devel)
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
-DRAD_HIPCC=$ROCM/bin/hipcc \
-DCMAKE_HIP_COMPILER=$ROCM/llvm/bin/clang++ \
-DCMAKE_HIP_COMPILER_ROCM_ROOT=$ROCM \
-DCMAKE_HIP_FLAGS="--rocm-path=$ROCM --rocm-device-lib-path=$ROCM/lib/llvm/amdgcn/bitcode --gcc-install-dir=/usr/lib/gcc/x86_64-linux-gnu/15"
export LD_LIBRARY_PATH=$ROCM/lib:$LD_LIBRARY_PATH
```
`--gcc-install-dir` takes the distro gcc's directory (the installed gcc-15's; after a distro gcc
upgrade it must be repointed, and the configure cached in `build/CMakeCache.txt` reset with
`-c`). The device-lib path is where the SDK tree keeps `amdgcn/bitcode` (under `lib/llvm/` in a
userspace SDK, `$ROCM/amdgcn/bitcode` in a core system install). The flags are not needed for a
full `/opt/rocm` install, and `DOCKER.md`'s container sidesteps them.
### 1.3 Check that it works
The tests are grouped into tiers by label, and `CMakePresets.json` names the usual runs. A preset
@@ -498,6 +520,7 @@ dequantisation where the architecture's kernels read another form, and NVFP4 alw
| `compressed-tensors` with an `nvfp4-pack-quantized` config group (`weights`: 4-bit float, group 16) | `fp4_e2m1*f32[1x16]` | the packed e2m1 codes beside an f32 scale per 16 of K, `weight_scale / weight_global_scale`: the global scale is a divisor, as compressed-tensors' dequantise and vLLM read it. Each piece keeps its own global, so a fused gate\|up reads both exactly. No kernel serves NVFP4, so every NVFP4 weight takes a recipe rule (`data/recipes/q38-27b-nvfp4-df2.recipe` makes it MXFP4) |
| `compressed-tensors` whose config groups are all `float-quantized` with 8-bit `float` weights | `fp8_e4m3*<scale>[1x*]` or `[RxC]` | nothing is imported: each `X.weight` reads stock as FP8 with `X.weight_scale` beside it, one scale a row (`[N, 1]` or `[N]`, the channel strategy) or a block plane; a per-tensor scale (`[1]`) is written once a row, so it is imported rather than byte for byte. The quantisation is still the tool's, so the family's quantised plugin serves it |
| `modelopt` (NVIDIA ModelOpt) with `quant_algo` `NVFP4`, `FP8`, or `MIXED_PRECISION` whose `quantized_layers` are each NVFP4 (group 16) or FP8 (e.g. ukisai's Swift 1.5 27B NVFP4) | NVFP4: `fp4_e2m1*f32[1x16]`; FP8: `fp8_e4m3*f32[1x*]` | NVFP4: `X.weight` (U8 `[N, K/2]`, the even k in the low nibble) beside an f32 scale per 16 of K, `float(X.weight_scale) * X.weight_scale_2`: ModelOpt's second level multiplies, where compressed-tensors' global scale divides. FP8: `X.weight` E4M3 with its one f32 `X.weight_scale`, written once a row. `X.input_scale` (a static activation scale) is not read: activations are quantised from their own values. Any other algorithm is refused by name. No kernel serves NVFP4, and none an FP8 scale per tensor, so both take recipe rules (`data/recipes/q38-27b-modelopt-nvfp4.recipe`) |
| GGUF `Q8_0`, `Q4_K` and `Q6_K` tensors (a GGUF file, not a `quantization_config`) | `i8*f16[1x32]`, `affine:codes=u4[1x1],scale=u6[1x32],scale.1=f16[1x256],min=u6[1x32],min.1=f16[1x256]` and `i6*i8[1x16]*f16[1x256]` | the blocks split into their planes, bit for bit; a rule re-quantises from the exact dequantisation. Not served as they stand: the loader refuses them with the hint to serve the container `rad-convert` writes |
The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
A mixed-precision release (NVFP4 MLPs beside FP8 or bf16 linears, the usual NVFP4 layout) reads
@@ -1170,6 +1193,31 @@ snapshot lets it skip at least 256 tokens of that head, the request takes one wh
ends, at the cost of one chunk split, and the requests after it resume there. A conversation's
next turn has only its own earlier turn past that point, so it splits nothing extra.
A prefix hit answers exactly as the same prompt prefilled cold, by default
(`--prefix-resume exact`). A kernel can round a row differently at another chunk
length (the fp8 GEMM's split-K count is chosen from `M`, spec §17), so a hit that
recomputes its tail in other chunks than a cold prefill can flip a near-tie in
greedy text. The hit therefore resumes only where an idle server's cold prefill of
that prompt starts a chunk: every `--max-num-batched-tokens` tokens (rounded down
to the chunk quantum), or every `--checkpoint-interval` when that is smaller. A
prompt's tail snapshot is taken where its last chunk starts, a boundary the chunk
already ends on, so it costs a copy and no step. An exact repeat re-prefills the
cold run's last chunk; an appended turn, that chunk and what the turn added: up to
one chunk more than `--prefix-resume nearest`, which resumes at the deepest
snapshot or block and splits a prompt's last chunk at its last quantum boundary.
The interval must be a multiple of the chunk when it is larger; otherwise it is
rounded up, and startup says so:
```
--checkpoint-interval 6144 resolves to 8192: --prefix-resume exact needs it a multiple of the
4096-token prefill chunk (--max-num-batched-tokens 4096) ...
```
It is an idle-server property, as greedy batching is: a prefill that shares its
steps with other requests or decode rows (`--busy-prefill-chunk`,
`--prefill-interleave`) is cut differently, and a request's own checkpoint
(`/v1/systemone`'s shared head) resumes where it was asked.
**One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built
from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk with the
fused fp8 junctions, a step of at least 1024 tokens that carries one prefill sequence and nothing
@@ -1924,6 +1972,7 @@ by 0.002-0.003 nats.
| `--prefill-span N` | 1 | checkpoint intervals one step may carry of a prefill alone in its step, from the prompt's second interval on; needs `--max-num-batched-tokens` of N intervals. Every other step is planned at the budget less the extra intervals, and the checkpoints inside a span are not written (§4.5) |
| `--checkpoint-slots N` | auto | linear-state (hybrid) or sliding-window snapshots the server may hold at once, in total, not per sequence. They live in pinned host memory, allocated at startup: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`, 144 MiB on Qwen3.8-27B; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`). `auto` gives each of `--max-num-seqs` what `--checkpoint-policy` keeps for a `--max-model-len` session plus one (10 at 200K tokens under geometric backoff), within an eighth of host memory and what the host can pin; the startup line and the report say what it chose and why (§4.8). A full store retires its least recently used snapshot. A count is taken as given: a store the host memory cannot hold or pin stops the start, and a table placed in host memory leaves room for it; `0` serves with none, every prefix hit then prefilling from the start |
| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
| `--prefix-resume MODE` | exact | `exact`: a prefix hit resumes only where an idle server's cold prefill of the prompt starts a chunk, and a prompt's tail snapshot is taken where its last chunk starts, so a hit answers bit-identically to a cold run; an interval past the chunk is rounded up to a multiple of it. `nearest`: the deepest snapshot or block, up to a chunk less re-prefilled a turn |
| `--no-prefix-cache` | prefix cache on | disable prefix caching |
**Parallel**
@@ -3118,7 +3167,8 @@ workflow, and is otherwise read off the parts:
- **Keyframes**: a `first_frame` (`i2va`), a `last_frame` (`l2va`) or both (`fl2va`), each an image
pinned at that end of the video. The first frame is stretched to the video's size, or, with
`"first_frame_mode": "center"`, scaled to cover it and cropped at the centre; the last frame is
always cropped. A keyframe request takes no `latent_upscale`: the pins are on the video's own grid.
always cropped. With `latent_upscale` each keyframe is prepared at both sizes and pinned on the
grid the steps run on (below).
- **Reference media** (`ref2va`): `ref_image_1` .. `ref_image_9`, `ref_video_1` .. `ref_video_3`, each
video with an optional soundtrack `ref_video_audio_N` of its own number, and `ref_audio_1` ..
`ref_audio_3`, numbered from 1 without gaps. Pictures and video frames are fitted into 256 x 256
@@ -3157,7 +3207,9 @@ upscaler, re-noised, and the last **`upscale_refine_steps`** run at the full siz
and 12 of the base model's 49 by default). The steps at the small size cost a fraction of a
full-size step's, so most of the time goes to the refinement. The video object of an upscaled
video carries `latent_upscale`, the `upscale_refine_steps` it ran and `upscale_from`, the small
size. Reference media ride it unchanged; keyframes do not (above).
size. Reference media ride it unchanged. Keyframes ride it too: each is encoded at the small size
before the prompt and again at the full size after the upscale, into the same slot, so every step
pins it on its own grid.
```sh
curl -s http://localhost:8000/v1/videos -H 'Content-Type: application/json' -d '{
+3 -3
View File
@@ -21,7 +21,7 @@ pass reached; the Rows nothing ran section lists the rest.
| library | version | domain | rows | run | ops | graph | cases | pass | fail | worst rel_l2 | median us |
|---|---|---|---|---|---|---|---|---|---|---|---|
| `libavx` | 0.1.0 | host | 100 | 42 of 100 | 100 of 147 | 43 of 43 | 734 | 734 | 0 | 9.01e-04 | 78.91 |
| `libr4d` | 0.5.0 | device | 287 | 48 of 287 | 142 of 147 | 43 of 43 | 734 | 734 | 0 | 4.27e-03 | 12.78 |
| `libr4d` | 0.5.0 | device | 291 | 48 of 291 | 142 of 147 | 43 of 43 | 734 | 734 | 0 | 4.27e-03 | 12.78 |
| `libref` (oracle) | 0.1.0 | host | 123 | 42 of 123 | 123 of 147 | 43 of 43 | 734 | 734 | 0 | 0.00e+00 | - |
Rows declaring an optional hook (tuning, fusion, weight layout):
@@ -34,7 +34,7 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
## Rows nothing ran
132 of 510 declared row(s) were reached by a case in this pass.
132 of 514 declared row(s) were reached by a case in this pass.
`libavx`: 58 row(s) not reached:
@@ -99,7 +99,7 @@ Rows declaring an optional hook (tuning, fusion, weight layout):
| `avx_silu` | `silu` |
| `avx_softmax` | `softmax` |
`libr4d`: 239 row(s) not reached:
`libr4d`: 243 row(s) not reached:
| kernel | op |
|---|---|
+4 -2
View File
@@ -191,8 +191,10 @@ drops blocks.
## Checking
There is deliberately no switch that forces dense attention above the bound, where it is not the
model the checkpoint was trained as. libref implements only `qsa_block_key` of the QSA ops, so
there is no whole-subsystem reference comparison. Changes are checked with:
model the checkpoint was trained as. libref implements all five QSA ops — `ref_qsa_block_key`,
`ref_qsa_score`, `ref_qsa_select`, `ref_qsa_tail_store`, `ref_qsa_work` (`libref/ref_qsa.cpp`) — so
each device kernel has a row to compare against; what no oracle gives is the whole-subsystem
comparison, a dense run against a sparse one above the bound. Changes are checked with:
- **`r4d_selftest` oracles**: `qsa_block_key` and `qsa_score` against f64 evaluations,
`qsa_work` and `qsa_tail_store` against a host walk of the batch, `qsa_select` against a host
+9
View File
@@ -9,6 +9,15 @@ All numbers: paired within-session windows, bar ≥0.5% + sign test, geometry
`--prefill-span 2 --tp-wire wht6 --placement all_vram` iq4r MoE unless stated.
Every "dead" row is a *measured* dead — the mechanism, not a guess.
Shorthand used in the table and the prose (glossed once, used everywhere):
`pp` prefill; `c1/c2/c8/c16` concurrency (live streams) 1/2/8/16; `M` rows in a collective
(batch tokens at a step, rows in a MoE launch); `I` `--checkpoint-interval`; `T` tokens
(`T<=25` at most 25 tokens); `ti8` the int8 peer wire (`--tp-wire wht6`'s coding); `FK` the
MoE fast band; `W4` the 4-bit weight format; `iq4r` the shipped MoE quantisation; `hc_write`
the fused all-reduce + residual-write row; `pp64K` a 64 K-token prefill; `QSA` the sparse
indexer (docs/QSA.md); `L0..L3` kill levels, defined under *Kill levels*; `W#`/`R#` the
experiment rows of this table.
## The table
| # | Element | What we tried | Result (measured) | Status / PR |
+46
View File
@@ -0,0 +1,46 @@
# DeepSeek-V4.1-Flash: a .rad straight from the release (no GGUF converter)
The official DeepSeek-V4.1-Flash release converts with `rad-convert` alone: no llama.cpp GGUF is
built as an intermediate, and no separate drafter directory is grafted. The pieces are in the tree:
- `data/engram_tables.py` builds the Engram hash tables from the release's own `tokenizer.json` and
`config.json`, reimplementing the tokenizer's ByteLevel decode and the normaliser sequence
(NFKC, NFD, strip marks, lowercase, collapse spaces, sentinel) and the PCG64 multipliers and
prime buckets. Validated against HF `tokenizers`: 0 mismatched token ids of 129280, compressed
vocab 99092, the release's two Engram layers [1, 14]. It writes `engram-tables.safetensors`.
- `data/imatrix_merge.py` fuses the imatrix entries llama.cpp's converter writes split
(`ffn_gate_exps`, `ffn_up_exps`) into the plugin's fused `ffn_gate_up_*`, summing the two halves
(and `shexp`): 1184 entries carried through, 160 fused for 40 layers. IQ1_S refuses a fused
weight without one.
- `data/recipes/deepseek41-ud-iq1s.recipe` is the UD-IQ1_S per-tensor mix, as rules for libquant's
`ggml` quantiser, so the release converts to the same encodings the GGUF gives.
- `rad-convert --chat-template FILE` bakes a template into the container's vocab section. The
release carries no `chat_template.jinja` and its `tokenizer_config.json` names none, so without
this flag an HF-direct container answers `/v1/chat/completions` with 501. Trailing newlines are
stripped as for a sibling template, and an unreadable or empty file is refused, not skipped.
## The three steps
```
# 1. the Engram tables, from the release's tokenizer (not a GGUF)
python3 data/engram_tables.py <HF release dir> engram-tables.safetensors
# 2. fuse the imatrix's split gate/up entries
python3 data/imatrix_merge.py imatrix_unsloth.gguf_file imatrix-merged.gguf
# 3. convert; the template is the model's own, baked into the container
rad-convert <HF release dir> --add engram-tables.safetensors \
--recipe data/recipes/deepseek41-ud-iq1s.recipe \
--imatrix imatrix-merged.gguf --tokenizer <HF release dir>/tokenizer.json \
--chat-template chat_template.jinja -o deepseek-v4.1-flash-ud-iq1s.rad
```
Measured on the release (DeepSeek-V4.1-Flash-1017, fp8 with e8m0 per 32×32 blocks, MXFP4 experts):
plan 32701 weights / **251.07 GiB**, conversion **251.13 GiB in 2h11m** on this host, and the
container serves on 4× R9700 at TP4 with its DSpark metadata (block 5, 128 experts, targets
37/38/39) and Engram baked. Quality of the converted container, greedy, thinking off: HE 154/164 =
.939 (the native UD-IQ1_S reference .963, McNemar p = .125), GSM 194/200 = .970 (reference .960).
Serving: nothing else is needed now that the template is baked. A container built before this flag
needed `--override-chat-template FILE` at serve time; the file has to be a Radiance-renderable
template (the release's own is; llama.cpp-only jinja such as `dict()` in a GGUF's template is not).
@@ -54,8 +54,7 @@ and at least 256, an aspect of at most 4:1 and an area of at most 1344x768, so 7
console. Every task takes every size.
`latent_upscale` (advanced) runs the early steps at half or a quarter of the size and the rest
at full size, with a container converted with the latent upscaler. The keyframe tasks do not take
it.
at full size, with a container converted with the latent upscaler. Every task takes it.
## Outputs
@@ -347,8 +347,7 @@ class RadianceMiniMax(io.ComfyNode):
io.Combo.Input("latent_upscale", options=["off", "2", "4"], default="off",
advanced=True,
tooltip="run the early steps at 1/2 or 1/4 of the size, with a "
"container that has the latent upscaler; not with "
"keyframes"),
"container that has the latent upscaler"),
*images, *videos, *tracks, *audios,
io.Int.Input("timeout", default=1800, min=30, max=7200, step=30, advanced=True,
tooltip="seconds to wait for the job"),
+150
View File
@@ -0,0 +1,150 @@
# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on
# instructions RDNA3 has: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and
# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family is
# a re-tile of the dot2 lane map, not a drop-in) or gfx12-only instructions such as
# global_load_tr_b128, and they decode every quantised weight in software: the lane map, not a
# missing instruction, is the reason.
#
# A build targeting other cards skips libr3d. The engine then has no device kernel library for that
# card and refuses ops only a reference library implements, unless
# --debug-accept-reference-kernels is passed (spec §17). The supported fix is a kernel library for
# that card; libr4d is that library for gfx12 and libr3d is it for gfx11.
#
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S libr3d -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`, naming the HIP compiler as for
# the tree); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libr3d LANGUAGES CXX HIP)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
# `^gfx11` is the family, not a chip: gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151 and the
# family target `gfx11-generic` all take these kernels, exactly as `^gfx12` covers RDNA4 for libr4d.
# The RDNA3 cards differ in CU count and clock, never in the instructions these kernels issue, so
# one code object per family serves the lot; a build that lists both a chip and the family gets
# both, and the engine picks the chip's object first (docs/PLUGIN.md §10).
rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")
if(NOT R3D_GPU_TARGETS)
message(STATUS
"libr3d: RDNA3 (gfx11xx) only, and this build targets ${RAD_GPU_TARGETS} -- not built")
return()
endif()
# R3D_UNITS is the definitive list of libr3d's device translation units, as "unit|extra flags".
#
# Every unit is compiled -ffp-contract=off, which rad_hipify puts on all HIP sources. It is not a
# style preference: libref accumulates in f32 with no FMA and no reassociation (ref_common.h), and
# a contracted device kernel disagrees with the oracle it is checked against. It also keeps the
# instruction counts quoted in kernel comments true.
# Kernels and libr3d's declaration (row table, operand descriptions) share one directory. There is
# no launch adapter: every entry point takes `(const RadArgs*, RadStream)` and sits beside its
# kernel. The plugin links rad_abi only, like one written out of tree.
set(R3D_UNITS
# The model's small ops, one workgroup per row: rmsnorm, layernorm, the binary and unary element
# ops, the activations, cast, softmax, embed_lookup, gather_rows and scatter_rows, rope and
# kv_store. This is the set the engine refuses on a card with no device kernel library.
"r3d_model_bf16|"
# The sampler's pre-filters: penalties, DRY, the n-gram ban, the bitmask, and the logprobs
# summary, which reads the logits plane once where the reference reads it three.
"r3d_sample_pre_f32|"
# The speculative decoder's accept step: a walk over the draft block's candidate lattice, which is
# a gather out of two codebooks rather than arithmetic.
"r3d_dflash_f32|"
# The gated MLP band: GEMM, gate and output quantiser in one launch, so the [M,N] intermediate the
# unfused chain writes and re-reads never exists.
"r3d_gemm_fp8a8_gated|"
# The vocab projection at decode: U2 codes, int8 activations, a joined scale+zero operand.
"r3d_gemm_nt_q_w2a8|"
# The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it.
"r3d_vocab_bf16|"
# The quantised GEMM at prefill heights: the 176 bands a forward pass ran on the CPU.
"r3d_gemm_fp8a8_tiled|"
# The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale
# per 32 of K, the block's partials scaled at the block boundary.
"r3d_gemm_mxfp4a8|"
"r3d_gemm_inta8|"
# Paged attention at head_dim 128: the decode leg (one head group a workgroup, 16-token tiles,
# split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3
# cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes.
"r3d_attn_paged_h128|"
# The sampler's spine: the row's top-R in one scan, and the stages that turn the candidate plane
# the top-R produces into one token -- argmax, temp, top-k, the draw, and the four narrowings.
"r3d_sample_f32|"
# Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that
# quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights.
"r3d_quant_fp8|"
# The skinny bf16 GEMM, M <= 16: one output element a lane, k ascending, so the accumulation order
# is libref's. The decode GEMM -- the op a token is made of.
"r3d_gemm_bf16_nt_m16|"
# The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits
# and three mantissa bits are a subset of f16's), and over int8 codes.
"r3d_gemm_fp8a16_nt_m1|"
# Landing next, in the same shape as libr4d's: the prefill GEMM (an 8x8 tile a wave over LDS, the
# same dot2 inner product), paged causal attention (the decode leg split-KV, the prefill leg a
# query tile a workgroup, bf16 or fp8 KV), the vocab (logits as a GEMM over the embedding, the row
# top-k, the cross-rank top-1) and the sampler's stages. Their rows are not in r3d_rows.cpp yet,
# because a row naming an entry point that is not in the library is an undefined symbol and the
# plugin would fail to load, taking every other row with it.
)
set(R3D_SRC "")
foreach(u ${R3D_UNITS})
string(REPLACE "|" ";" parts "${u}")
list(GET parts 0 unit)
list(LENGTH parts n)
set(extra "")
if(n GREATER 1)
list(GET parts 1 extra)
endif()
set(src "${CMAKE_CURRENT_SOURCE_DIR}/${unit}.hip")
if(NOT EXISTS "${src}")
message(FATAL_ERROR "libr3d unit ${unit}.hip is missing from ${CMAKE_CURRENT_SOURCE_DIR}")
endif()
if(extra)
set_source_files_properties("${src}" PROPERTIES COMPILE_OPTIONS "${extra}")
endif()
list(APPEND R3D_SRC "${src}")
endforeach()
# The host sources are declaration only: the row table, the operand descriptions and the fusion
# claims. They are pure host C++ that includes neither r3d.h nor hip_runtime.h, so these tables
# compile and can be inspected without ROCm. libr3d has no layout source: nothing it serves is
# repacked, because a dot2 GEMM reads a weight in the order it is stored (see r3d_rows.cpp).
# r3d_fuse.cpp joins the list with the first fused row: a `replaces` chain with no row naming it
# would be dead code, and the fused rmsnorm-then-quant kernel is the first one worth its bytes.
set(R3D_DECLARATION r3d_rows.cpp r3d_shapes.cpp)
rad_add_plugin(libr3d kernels
SOURCES ${R3D_DECLARATION}
HIP_SOURCES ${R3D_SRC}
GPU_TARGETS ${R3D_GPU_TARGETS}
INCLUDES ${CMAKE_CURRENT_SOURCE_DIR})
# rad_plugin_info's build_target is this build's own target list, spelled as the device reports its
# arch, because the loader warns when a plugin claims a card the running device is not
# (core/plugin/loader.cpp, target_covers). A library built for two archs says two.
string(REPLACE ";" " " R3D_BUILD_TARGET "${R3D_GPU_TARGETS}")
target_compile_definitions(libr3d PRIVATE R3D_BUILD_TARGET="${R3D_BUILD_TARGET}")
# Catalogue dump: prints every row and, on a card, calls each launch with a minimal valid input, to
# catch transcription errors in the constraint table. It dlopens the plugin so an undefined symbol
# in the .so is caught too.
add_executable(r3d_selftest ${CMAKE_CURRENT_SOURCE_DIR}/r3d_selftest.cpp)
# Links the HIP runtime to allocate the device buffers it feeds the kernels.
target_link_libraries(r3d_selftest PRIVATE radiance::abi ${CMAKE_DL_LIBS} ${RAD_HIP_RUNTIME})
target_include_directories(r3d_selftest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
# The device phase of the selftest -- the per-row launch -- is built only when the HIP runtime is
# there, which in this plugin's build it always is.
target_compile_definitions(r3d_selftest PRIVATE RAD_HAVE_HIP)
set_target_properties(r3d_selftest PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Installed beside the tools, so the image can run the rows' own card checks without a build tree:
# r3d_selftest <home>/kernels/libr3d.so [--case <row>]
install(TARGETS r3d_selftest RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
# C++17, the standard every radiance plugin builds device code at: it is what the tree's kernels are
# written against and what the cost figures assume.
set_target_properties(libr3d PROPERTIES HIP_STANDARD 17 HIP_STANDARD_REQUIRED ON)
+1211
View File
File diff suppressed because it is too large. Load diff
+387
View File
@@ -0,0 +1,387 @@
/* r3d.h -- the entry points libr3d exports, and the launchers behind them.
*
* Two layers, in every unit, as in libr4d:
*
* The launcher (`r3d_<op>(...)`, this header) takes pointers as longs, a geometry as ints and a
* stream as a long, checks what a `__global__` cannot (nulls, non-positive extents, a pitch that
* does not describe the operand), computes the grid, and issues one kernel with
* hipLaunchKernelGGL on the stream it was handed. It returns 0, or a negative launcher code:
* -1 a null pointer, -2 a bad extent, -3 a bad pitch, -4 the HIP launch failed. It allocates
* nothing and synchronises on nothing.
*
* The shim (`r3d_rad_<op>(const RadArgs*, RadStream)`, declared in the unit) is the RadLaunchFn
* the row table names. It reads the operands with r3d_args.h, takes the dtype from the tensor and
* not from the `dtype` parameter, takes the row count from the operand and not from `M` (which is
* the band's upper bound), checks strides, translates the ABI dtypes to the codes below, and
* returns a RAD status.
*
* A launcher is declared here and defined beside its kernel, in the same translation unit as the
* shim that calls it: there is no adapter, and an out-of-tree author reading one unit sees the whole
* path from RadArgs to the grid.
*
* Streams: a RadStream is the engine's queue, usable with hipLaunchKernel (and so <<<>>>),
* hipMemcpyAsync, hipMemcpy2DAsync and hipMemsetAsync and with nothing else in HIP
* (docs/PLUGIN.md §5). libr3d passes it to the launch and nowhere else.
*/
#ifndef RAD_R3D_H
#define RAD_R3D_H
#include "r3d_plugin.h"
extern "C" {
/* ================================================================== r3d_model_bf16.hip
*
* One workgroup per row. Every launcher takes a row pitch in elements for each operand that can be
* a slice (a column slice of a fused projection is the usual case), 0 meaning "dense, so n".
*/
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wdt` is R3D_DT_BF16 or R3D_DT_F32 for a
* gain, R3D_DT_N for none (the gain is then 1, and wadd is refused by the shim, as libref does). */
int r3d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
int x_ld, int y_ld, int wdt, long stream);
/* The same at f32 activations, for an f32 checkpoint's residual stream: the row is the op's, the
* store narrows nothing. `wdt` is the gain's dtype code, R3D_DT_N for none. */
int r3d_rmsnorm_f32(long x, long w, long y, int M, int n, float eps, float wadd, float mult,
int x_ld, int y_ld, int wdt, long stream);
/* y = (x - mean) / sqrt(var + eps) * w + b, the mean and variance both taken in the reference's
* two passes. `b` may be 0 (no bias). */
int r3d_layernorm_bf16(long x, long w, long b, long y, int M, int n, float eps,
int x_ld, int y_ld, long stream);
/* y = a + b, and y = a * b. `bcast` says b carries n elements and rides every row. `div` is the
* `add` op's optional divisor, 0 meaning none: with it, y = rd(rd(a + b) / div). */
int r3d_add_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
int bcast, long stream);
int r3d_add_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, float div,
int bcast, long stream);
int r3d_mul_bf16(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast,
long stream);
int r3d_mul_f32(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, int bcast,
long stream);
/* y = x, one dtype to another, over M rows of n at the given pitches. The dtypes are R3D_DT_*;
* an integer pair goes straight through (ids above 2^24 survive an i64 -> i32 copy), everything
* else widens to f32 and narrows once on the way out. */
int r3d_cast(long x, long y, int M, int n, int x_ld, int y_ld, int from_dt, int to_dt, long stream);
/* The unary activations, f32 in, narrowed once by the store: y = x*sigmoid(x), 0.5x(1+erf(x/sqrt2))
* and 1/(1+exp(-x)) respectively. */
int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
int r3d_silu_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
/* y = act(gate) * up, `act` R3D_ACT_SILU, R3D_ACT_GELU (the exact erf form) or R3D_ACT_SIGMOID.
* The two inputs are the halves of a fused [M, 2n] projection, so their pitches are separate. */
int r3d_act_mul_bf16(long gate, long up, long y, int M, int n, int g_ld, int u_ld, int y_ld,
int act, long stream);
/* y[i] = silu(gate_up[i]) * gate_up[n + i]: the llama MLP's gated product over one fused plane,
* the gate the FIRST half, which is the order rad-convert fuses gate and up in. The activation is
* not narrowed before the product: that is `act_mul`'s order, over two operands, and it stands for
* the unfused pair that stored the activation. `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the
* output's; 0 takes each one's dense width. 0, -1, -2, -3, -4. */
int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, long stream);
/* Row-wise softmax over f32, maximum subtracted, the denominator summed in ascending order. */
int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
/* y = x * s, where `s` is the op's [1] weight plane, in device memory, of dtype `s_dt`
* (R3D_DT_BF16 or R3D_DT_F32). The scalar is read by the kernel, not by the launcher: a launch may
* not copy device memory to the host, and the reference reads the same one value on the host because
* its operands are host planes. Every lane loads the same address, which is one uniform load per
* block; `s` is 0 only for a call the shim has already refused.
*
* y = v (fill) is the other scalar-carried op, and its value is a parameter, so it is by value. */
int r3d_scale_bf16(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
int r3d_scale_f32(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, long stream);
int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream);
/* In-place rotary on a fused qkv row: q, then k, then v untouched. `mode` is R3D_ROPE_NEOX or
* R3D_ROPE_GPTJ; `rot` the rotary width (<= head_dim, even). `scale` is the position divisor: the
* angle of pair i is (pos / scale) * theta^-i, which is libref's proportional ladder at a factor
* other than 1 (ref_rope's `scale` divides the position, and YaRN's magnitude is carried by
* `yarn_factor`, which this kernel does not implement). `pos` is M i32 positions, one a row. */
int r3d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_head, int n_head_kv, float theta,
float scale, int mode, int rot, int qkv_ld, long stream);
/* K and V into a paged cache, at slot_mapping's slots. The cache is [blocks, kv_heads, block_size,
* 2*head_dim] with the strides the shim read off the operand and passes as sb/sh/so/sd; a negative
* slot is skipped, and so is one at or past `slot_max` = n_blocks * block_size, which the launcher
* computes from M and block_size exactly as `r3d_shape_kv_store` sizes the cache. The reference
* *refuses* such a slot on the host, where it can see the block count; a launch cannot refuse a
* slot it has not read, and writing past the cache is the one failure mode worse than a value
* dropped, so the bound is the kernel's and the divergence is a slot lost rather than a step lost. `kv_dt` R3D_DT_BF16 stores the values, R3D_DT_U8 encodes them as E4M3 with the
* reciprocal of k_scale / v_scale, R3D_DT_F16 as f16. */
int r3d_kv_store(long k, long v, long sm, long kv, int M, int head_dim, int n_head_kv,
int block_size, int kv_dt, float k_scale, float v_scale, int k_ld, int v_ld,
long long slot_max, long sb, long sh, long so, long sd, long stream);
/* x[r] = wte[ids[r] - vocab_offset] * wscale, narrowed once. A row whose id is out of the table's
* range is zeroed, as libref does. */
int r3d_embed_lookup(long ids, long wte, long x, int M, int n_embd, int n_vocab, int vocab_offset,
float wscale, float mult, int x_ld, int w_ld, int dt, long stream);
/* y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n elements.
*
* `src_rows` and `dst_rows` are the plane's own row count. Only the shim can supply it -- it has the
* operand's numel, the launcher has a pointer -- and the kernel needs it, because the reference
* reads the index plane on the host and refuses an index outside the row count, while a launch
* cannot refuse an index it has not read. So the bound travels to the kernel and the kernel acts on
* it: a gather at idx >= src_rows takes the padding path (the zero row libref's padding form
* writes), a scatter at idx >= dst_rows drops the row, which is the same refusal seen from inside a
* launch. The worst failure here is a read or a write past the plane, and a dropped row is what
* stands between this card and it. 0 means unchecked: the shim's bug to avoid, not a caller's to
* supply. */
int r3d_gather_rows(long x, long idx, long y, int M, int n, int x_ld, int y_ld, int dt,
long long src_rows, long stream);
int r3d_scatter_rows(long v, long idx, long x, int M, int n, int v_ld, int x_ld, int dt,
long long dst_rows, long stream);
/* ================================================================== r3d_quant_fp8.hip
*
* All three quantisers write a plain row-major code plane and one f32 scale per (row, group); no
* fragment permutation, because a dot2 GEMM reads codes in order.
*/
/* Per-(row, group) symmetric quantisation. scale = amax * (1/top) with top 448 for E4M3 and 127
* for int8, the codes v * (1/scale) clamped to +-top and rounded by the codec. An all-zero group
* gets scale 1. */
int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld, int s_ld,
long stream);
int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group, int x_ld, int s_ld,
long stream);
/* quant_act_i8g: the same code at `group` granularity -- amax / 127 per (row, group), 1 for an
* all-zero group -- stored row-major. This is the plane libr3d's i8a8 GEMM reads; `quant_act_i8`
* above is the per-row plane the WMMA-ordered ops read, and the two are not interchangeable.
* 0, -1, -2, -3, -4. */
int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
long long x_ld, long long s_ld, long stream);
/* The gated form: gate_up is [M, 2n] (gate in the first n, up in the second), and what is
* quantised is act(gate) * up. `q`/`s` carry that product's codes and scales; `out_bf16`, when
* present, also receives the product in bf16. */
int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n, int group,
int act, long stream);
/* The residual add, the RMS norm and the E4M3 quantiser in one pass, so the normalised row never
* goes back to VRAM. `res` is the residual plane, INOUT, and 0 when the op has no residual: with it
* the sum is STORED, narrowed to bf16, BEFORE the variance reads it, so the norm is over the bf16
* sum -- the `add` + `rmsnorm` pair, not `rmsnorm_add`, which normalises the unrounded sum. `ob`,
* when present, receives exactly the bf16 values the codes were taken over. Pitches are in elements
* of their own operand, `s_ld` in scales, so a dense scale plane is n/group. `group` must divide n:
* a partial group is the standalone quantiser's zero-padded store, which this pass does not have.
* 0, -1, -2, -3, -4. */
int r3d_rmsnorm_quant_fp8(long x, long res, long w, long q, long s, long ob, int M, int n,
int group, float eps, float wadd, int x_ld, int res_ld, int ob_ld,
int q_ld, int s_ld, int wdt, long stream);
/* y = code * scale, the read of a container's own quantised weight: group-wide f32 scales, E4M3 or
* int8 codes. */
int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld, int y_ld,
long stream);
/* ================================================================== r3d_gemm_*.hip
*
* y[M,N] = a[M,K] @ b[N,K]^T. One output element a lane, k ascending, f32 accumulate, the sum
* narrowed once by the store. Split-K (sk > 0) writes partials to `scratch` and reduces them in a
* second kernel on the same stream; the row's scratch hook sizes the arena for the largest sk the
* band allows.
*/
/* bf16 (and f16) operands. `nt` 1 streams the weight with non-temporal loads. */
int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk,
int wv, int nt, long scratch, long stream);
int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld, int y_ld, int sk,
int kb, int nt, long scratch, long stream);
/* A block-scaled fp8 weight: b is E4M3 codes, b_scale one scale per (pb1 rows of N, pb2 of K)
* block, pb1/pb2 the block sizes the container states (absent, both default to `group`). The
* scale plane is **bf16** in the container's quantised family -- `gemm_q_shape` writes
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` -- and f32 only under the separate dtype `fp8a8f32`.
* a is bf16 (fp8a16, no a_scale) or E4M3 codes with per-(row, group) f32 a_scale (fp8a8). */
int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
long scratch, long stream);
/* The same kernel with the scale plane's dtype named, which the 17-argument entry above cannot
* state: it forwards RAD_F32, and the container's quantised weights carry bf16 block scales. Land
* new callers on this one; the older entry is kept for callers written against its RAD_F32
* behaviour. bs_dt is the plane's RadDataType: RAD_BF16 reads bf16, anything else -- 0 included --
* reads f32. */
int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K,
int group, int pb1, int pb2, int a_ld, int y_ld, int sk, int nt,
long scratch, int bs_dt, long stream);
/* The int8 weight twin, with the optional a_sum / b_ref row sums an int8 GEMM with a zero point
* needs (libquant's symmetric form leaves them null). */
int r3d_gemm_nt_q_i8(long a, long a_scale, long b, long b_scale, long a_sum, long b_ref, long y,
int M, int N, int K, int group, int a_ld, int y_ld, int sk, int nt,
long scratch, long stream);
/* ================================================================== r3d_attn_paged_h128.hip
*
* Paged causal attention. `kv` is the cache the shim read its strides from; `bt` a
* [num_seqs, blocks] block table; `seqused` per-sequence lengths; cu_seqlens, when present, the
* ragged query layout; k_descale / v_descale the per-(seq, head) fp8 cache descales.
*/
int r3d_attn_decode_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc,
long cu, long out, int num_seqs, int q_len, int head_dim, int gqa,
int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs,
int max_ctx, int window, int causal,
float scale, int kv_dt, long q_ld, long out_ld, int splits, long scratch,
long stream);
int r3d_attn_prefill_h128(long q, long kv, long bt, long seqused, long k_desc, long v_desc,
long cu, long out, int num_seqs, int q_len, int head_dim, int gqa,
int n_head, int block_size, int bt_cols, int bt_rs, int bt_cs,
int max_ctx, int window, int causal,
float scale, int kv_dt, long q_ld, long out_ld, long scratch,
long stream);
/* ================================================================== r3d_gemm_fp8a8_tiled.hip
*
* The quantised GEMM at prefill heights. b_row/bs_row are the container's row strides, 0 meaning
* dense; `group` is the scale block, 128 on every band this checkpoint declares. The scales arrive
* as the container's two planes behind one operand, which is what the row's layout hook presents;
* the plain two-tensor form is the same entry with bs_row dense.
*/
int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N,
int K, int group, int a_ld, long long b_row, int as_ld, long long bs_row,
int y_ld, int nt, long stream);
/* ================================================================== r3d_gemm_mxfp4a8.hip
*
* The quantised GEMM at dtype=mxfp4a8: an OCP-MXFP4 weight against the fp8 activation. `b` is the
* e2m1 codes, two per byte, [N, K/2] u8; `b_scale` the e8m0 scale, one per 32 of K, [N, K/32] u8;
* `a` E4M3 with `a_scale` f32 per (row, 128 of K); `y` bf16. b_row/e8_row are the row strides in
* bytes, 0 meaning dense. There is no zero point: the scale is symmetric, and a reserved e8 (0,
* 255) is refused. M <= 16 takes the m16 launcher, M >= 17 the tiled one.
*/
int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int group, int a_ld, int y_ld, long long e8_row, long stream);
int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M,
int N, int K, int group, int a_ld, long long b_row, int as_ld,
long long e8_row, int y_ld, int nt, long stream);
/* ================================================================== r3d_gemm_inta8.hip
*
* The quantised GEMM at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight grids at decode
* heights. `b` is the signed codes (I4, two a byte, or I8, one a byte), [N, K]; `b_scale` the f16
* scale, one per (row, 128 of K), [N, K/128]; `a` int8 in the step order with `a_scale` f32 per
* row; `y` bf16. b_rb and sb_rb are the row strides (bytes / elements), 0 meaning dense.
* There is no zero point:
* the dequant is code times scale. M <= 16 only; the prefill band is the tiled rows' and the
* 8-bit grid at prefill heights is declared out of this unit.
*/
int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream);
int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int a_ld, int y_ld, long long b_rb, long long sb_rb, long stream);
/* ================================================================== r3d_vocab_bf16.hip
*
* The vocab-sharded logits and the top-k that follows them.
*/
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T: the decode heights (M <= 16) on
* the decode arm, a prefill arm above them, over a vocabulary-wide N. */
int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd, int x_ld,
int y_ld, int sk, int nt, long scratch, long stream);
/* Per-row top-R of a [M, N] logits row: idx (i32) and val (f32), descending, ties to the lower
* index. `pairs`, when present, also receives the (index, value) dwords a cross-rank merge reads. */
int r3d_row_topk_bf16(long x, long idx, long val, long pairs, int M, int N, int R, int vocab_off,
int x_ld, int rc, int nch, long scratch, long stream);
/* The cross-rank top-1: one id and one value a row, out of [M, n] candidate pairs. */
int r3d_pair_argmax(long pairs, long idx, long val, int M, int n, long stream);
/* ================================================================== r3d_sample_f32.hip
* The sampler, and the vocabulary row it starts from.
*
* The shapes are libref's, operand for operand, and so is the `params` plane:
* one `RadSampleParams` a row, 96 bytes of f32 words, which every stage reads by field. `logits` is
* f32 and the candidate planes are word-typed -- `cand_idx` i32, `cand_val` f32, the pair planes
* i32 holding an id's bits beside a logit -- because that is what the reference writes.
*
* The stages over the full vocabulary (argmax, temp, topk, logprobs, penalties, dry, ngram_ban) are
* one block a row and are bound by the plane: at the band MiniCPM5-2B asks for, 2048 rows of 130560
* f32, the logits are 1.02 GiB and one pass is the floor. The stages over the candidate set (the
* four narrowings and pick) are one block a row of `n_cand` and are bound by the arithmetic, which
* is why `pick` keeps the reference's double `exp`: the law is `(float)std::exp((double)x)`, and a
* hardware `v_exp_f32` two ulp away moves a draw whenever a true probability lands within an ulp of
* the `u < cum` boundary.
*
* M comes off the operand, never off the band: the band's `M` is a range's bound and a step's row
* count is what the planes hold. 0, -1 null pointer, -2 bad extent, -3 pitch, -4 launch failed.
*/
int r3d_row_topk(long x, long idx, long val, long pairs, int M, int N, int R, int x_dt,
long long x_ld, long long idx_ld, long long val_ld, long long pairs_ld,
int vocab_off, long stream);
int r3d_sample_argmax(long lg, long tok, int M, int n_vocab, long long lg_ld, long stream);
int r3d_sample_temp(long lg, long params, int M, int n_vocab, long long lg_ld, long stream);
int r3d_sample_topk(long lg, long params, long ci, long cv, long pairs, int M, int n_vocab,
int n_cand, long long lg_ld, long long ci_ld, long long cv_ld,
long long pairs_ld, int vocab_off, long stream);
int r3d_sample_pick(long ci, long cv, long params, long tok, int M, int n_cand,
long long ci_ld, long long cv_ld, long stream);
/* The four narrowing stages: one shape, `cand_idx` and `cand_val` in place, one predicate each --
* top-p a prefix rule in candidate order, min-p a floor under the best candidate's probability,
* typical the band around the set's entropy, XTC the exclusion-the-model-would-not-choose cut. */
int r3d_sample_topp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
long long cv_ld, long stream);
int r3d_sample_minp(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
long long cv_ld, long stream);
int r3d_sample_typical(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
long long cv_ld, long stream);
int r3d_sample_xtc(long ci, long cv, long params, int M, int n_cand, long long ci_ld,
long long cv_ld, long stream);
/* The pre-filters over the logits row. `hist` is the row's history of global token ids, i32
* [M, max_hist]; its window, and the rule that a token is penalised at its first occurrence in the
* window, are libref's (`hist_window`), and the window is placed inside the params plane by the
* descriptor's `fill_chunk`. `vocab_off` shifts the ids a stage reports, for a split vocabulary. */
int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab, long long lg_ld,
long long hist_ld, int vocab_off, long stream);
int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab,
long long lg_ld, long long hist_ld, int vocab_off, long stream);
int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist, int M,
int n_vocab, long long lg_ld, long long hist_ld, int vocab_off,
long stream);
int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab, long long lg_ld,
int mask_rows, long stream);
/* The gated MLP band: b is E4M3 codes of N = 2n rows (gate rows [0,n), up rows [n,N)), b_scale one
* scale per (group, group) block, bf16 as the container writes it. The row is narrowed to bf16 as
* the unfused pair leaves it, gated (act: R3D_ACT_SILU | R3D_ACT_SIGMOID), narrowed again, and coded
* per group of `group` columns: q is the codes [M,n], scale the per-(row, group) amax scales, and
* out_bf16 the narrowed gated tensor when the caller wants it (y_ld is its row pitch, n when the
* plane is absent). M <= 64, sk == 1; no scratch, because the row never leaves the registers. */
int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch, long stream);
/* The same kernel naming the scale plane's dtype. The entry above forwards RAD_BF16, which is the
* container's form for this op; f32 is accepted and equal bit for bit. */
int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
int bs_dt, long stream);
/* DFlash2's greedy walk over the candidate lattice. `hp` may be 0: the plane of ones the reference
* computes when the operand is absent. The rows of cand, unary and tokens are (sequence, step),
* M * steps of them; `anchor` is a row of M * anchor_stride ids. */
int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ,
long tokens, int M, int steps, int top_k, int rank, int n_vocab,
int anchor_stride, long long cand_ld, long long un_ld, long long hp_ld,
long long pred_ld, long long succ_ld, long long tok_ld, long stream);
int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k,
long long lg_ld, long long stats_ld, int vocab_off, long stream);
} /* extern "C" */
#endif /* RAD_R3D_H */
+310
View File
@@ -0,0 +1,310 @@
/* r3d_args.h -- how a libr3d entry point reads its arguments.
*
* There is no adapter layer. An entry point takes `(const RadArgs*, RadStream)` and returns a
* status, the same RadLaunchFn contract every other plugin implements; an out-of-tree author can
* write the same kernel without an adapter they could not reach.
*
* This header holds the shared helpers: reading a parameter, finding an operand, testing
* contiguity. Most are one line over rad_abi.h.
*
* Nothing here includes r3d.h or HIP: host translation units (the row table, the shape hooks)
* include it too, so those tables compile and can be checked without ROCm.
*/
#ifndef R3D_ARGS_H
#define R3D_ARGS_H
#include "rad_abi.h"
#include "rad_plugin.h"
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
/* ================================================================== parameter access
*
* Forwards to rad_abi.h's static inline helpers, the ones a third-party plugin gets, keeping
* libr3d's spelling at its call sites. */
static inline int r3d_geti(const RadArgs* a, const char* k, long long* out) {
return rad_args_geti(a, k, out);
}
static inline long long r3d_geti_or(const RadArgs* a, const char* k, long long dflt) {
return rad_args_geti_or(a, k, dflt);
}
static inline const char* r3d_gets(const RadArgs* a, const char* k) {
return rad_args_gets(a, k);
}
/* A float parameter is RAD_P_F64 (rad_types.h, docs/OPS.md "The four rules"), so `dval` arrives
* and the step path runs no strtod. Deliberately laxer than rad_args_getf_or: string and integer
* spellings are still read, because a tool or selftest may call a launch directly with no declare
* to enforce the type. */
static inline double r3d_getf(const RadArgs* a, const char* k, double dflt) {
if (!a || !k) return dflt;
for (int i = 0; i < a->n_p; ++i) {
if (!a->p[i].key || std::strcmp(a->p[i].key, k) != 0) continue;
if (a->p[i].kind == RAD_P_F64) return a->p[i].dval;
if (a->p[i].kind == RAD_P_INT) return (double)a->p[i].ival;
if (a->p[i].kind == RAD_P_STR && a->p[i].sval && a->p[i].sval[0]) {
char* end = nullptr;
const double v = std::strtod(a->p[i].sval, &end);
return (end && end != a->p[i].sval) ? v : dflt;
}
return dflt;
}
return dflt;
}
/* An enumerated parameter: `act` is "silu" or "sigmoid", not 0 or 1, so a --debug-graph dump says
* what runs; the mapping to libr3d's integer lives in the shim. Returns -1 for an unknown name,
* which every caller turns into RAD_E_INVAL. `alt` is libr3d's own integer spelling of the same
* key, consulted only when the name is absent. */
static inline int r3d_act_code(const RadArgs* a, const char* key, const char* alt, int dflt) {
if (const char* s = r3d_gets(a, key)) {
if (!std::strcmp(s, "silu") || !std::strcmp(s, "swish")) return 0;
if (!std::strcmp(s, "sigmoid")) return 1;
return -1;
}
long long v = 0;
if (alt && r3d_geti(a, alt, &v)) return (v == 0 || v == 1) ? (int)v : -1;
return dflt;
}
/* Same, off a bare RadParam list (init() and the layout hooks); forwards to rad_plugin.h's
* rad_param_*. */
static inline long long r3d_pgeti_or(const RadParam* p, int n_p, const char* k, long long dflt) {
return rad_param_geti(p, n_p, k, dflt);
}
static inline const char* r3d_pgets(const RadParam* p, int n_p, const char* k) {
return rad_param_gets(p, n_p, k, nullptr);
}
/* ================================================================== operand access
*
* An absent optional operand is a null RadTensor.data (rad_abi.h). r3d_opt() returns null both
* past the end and for a present-but-null operand, so an optional test is one pointer test. For a
* required operand the caller turns null into RAD_E_INVAL: it is a bug in the issue, not a shape
* the kernel declines.
*/
static inline const RadTensor* r3d_opt(const RadArgs* a, int i) { return rad_arg_in(a, i); }
/* An optional operand the plan carries a slot for, with no bytes behind it, is ABSENT -- it is not a
* dtype problem. The engine hands the slots of an op's optional operands as descriptors with a null
* `data` when the graph did not bind one, and a shim that dtype-checks such a descriptor would refuse
* a band the op never reads -- `rmsnorm_quant_fp8` answering E_DTYPE to a band whose dtype is fine,
* for an empty `out_bf16` slot. Every test of an optional operand goes through here; a bare `if (t)`
* is the bug. */
static inline bool r3d_has(const RadTensor* t) { return t && t->data; }
static inline const void* r3d_p(const RadTensor* t) { return t ? t->data : nullptr; }
/* The same for an operand a kernel writes, so an output cast reads as one rather than as a pointer
* laundered through `long`. */
static inline void* r3d_wp(const RadTensor* t) { return t ? t->data : nullptr; }
static inline long r3d_addr(const RadTensor* t) { return t ? (long)(uintptr_t)t->data : 0L; }
static inline long long r3d_dim(const RadTensor* t, int i) {
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
return t->shape[i];
}
static inline long long r3d_stride(const RadTensor* t, int i) {
if (!t || i < 0 || (uint32_t)i >= t->rank) return 0;
return t->stride[i];
}
static inline long long r3d_numel(const RadTensor* t) { return rad_tensor_numel(t); }
/* [rows..., K] flattened to (M, K). Every per-row kernel in libr3d owns whole rows (one workgroup
* per row), so the leading axes are only a row count. The GEMM makes the same fold explicitly. */
static inline int r3d_rows_of(const RadTensor* t, long long* M, long long* K) {
if (!t || t->rank < 1) return RAD_E_SHAPE;
*K = t->shape[t->rank - 1];
*M = 1;
for (uint32_t i = 0; i + 1 < t->rank; ++i) *M *= t->shape[i];
return (*M >= 1 && *K >= 1) ? RAD_OK : RAD_E_SHAPE;
}
/* Dense row-major over the whole tensor. libr3d's entry points take at most one pitch, so
* everything else must be tight, and the shim checks it. This is the "necessary condition only"
* boundary of spec §2.1: the constraint table settles geometry, contiguity is a property of the
* call. */
static inline int r3d_contig(const RadTensor* t) { return rad_tensor_is_contiguous(t); }
/* Contiguous in every axis but the leading one, whose stride is the row pitch libr3d takes as an
* explicit argument (`x_ld`, `a_stride`, ...). Returns the pitch in elements, or -1. */
static inline long long r3d_row_pitch(const RadTensor* t) {
if (!t || t->rank == 0) return -1;
if (t->rank == 1) return 1;
long long acc = 1;
for (int i = (int)t->rank - 1; i >= 1; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) return -1;
acc *= t->shape[i];
}
return t->stride[0];
}
/* [rows..., n] read as (rows, n): the leading axes are a row count and only the last is
* structural. Returns the pitch in elements, or -1.
*
* A column slice must refuse. k out of a fused [tok, 2*kv_dim] projection, read as
* [tok*n_head_kv, head_dim] for a per-head norm, has rows `n` apart within a token and a buffer row
* apart between tokens; no single pitch describes that, and the leading stride would make the
* consumer read most heads from garbage. So the trailing axes must cover the whole row. */
static inline long long r3d_rows_pitch(const RadTensor* t, long long n, long long* rows) {
if (!t || t->rank < 1 || n <= 0) return -1;
const long long nel = rad_tensor_numel(t);
if (nel % n) return -1;
*rows = nel / n;
if (t->rank == 1) return n;
if (t->shape[t->rank - 1] == n) {
if (t->stride[t->rank - 1] != 1) return -1;
return t->rank >= 2 ? t->stride[t->rank - 2] : n;
}
if (rad_tensor_is_contiguous(t)) return n;
long long trail = 1;
for (int i = 1; i < (int)t->rank; ++i) trail *= t->shape[i];
return trail == n ? r3d_row_pitch(t) : -1;
}
/* An attention operand, [tokens, heads * head_dim] over its trailing axes: the token count, head
* count and row pitch in elements. False when the trailing axes are not whole heads or no single
* pitch describes the rows. */
static inline bool r3d_head_rows(const RadTensor* t, long long head_dim, long long* n_tok,
long long* n_head, long long* ld) {
long long width = 1;
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
if (t->rank < 2 || width % head_dim) return false;
*n_head = width / head_dim;
*ld = r3d_rows_pitch(t, width, n_tok);
return *ld >= 0;
}
/* 16-byte alignment, needed by every kernel that loads a dword pair per lane. The kernels do not
* check it, so the shim does. */
static inline int r3d_aligned(const void* p, unsigned bytes) {
return p ? (((uintptr_t)p & (uintptr_t)(bytes - 1)) == 0) : 1;
}
/* ================================================================== which check refused
*
* A shim refuses in many places with the same few codes, so the engine's report names the kernel
* and geometry but not the failing condition. R3D_NO() wraps a refusal and prints its own line when
* RAD_R3D_TRACE is set; otherwise it is the bare return plus one cached-flag load on a path that is
* failing anyway. */
static inline int r3d_trace_on(void) {
static int on = -1;
if (on < 0) { const char* e = std::getenv("RAD_R3D_TRACE"); on = (e && *e && *e != '0'); }
return on;
}
static inline int r3d_refused(int code, const char* file, int line) {
if (r3d_trace_on()) std::fprintf(stderr, "[r3d] %s:%d refused -> %d\n", file, line, code);
return code;
}
#define R3D_NO(code) r3d_refused((code), __FILE__, __LINE__)
/* The descriptor we were handed, printed when we decline one. A stride refusal that names no stride
* is a refusal the reader has to reproduce, and reproducing it costs a probe cycle: the engine binds
* rank, shape and strides in ELEMENTS, and the shape it binds is the step's, not the band's. */
static inline void r3d_trace_desc(const char* what, const RadTensor* t) {
if (!r3d_trace_on()) return;
if (!t) { std::fprintf(stderr, "[r3d] %s: (absent)\n", what); return; }
std::fprintf(stderr, "[r3d] %s: dtype %u rank %u shape [", what, t->dtype, t->rank);
for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->shape[i]);
std::fprintf(stderr, "] stride [");
for (int i = 0; i < (int)t->rank; ++i) std::fprintf(stderr, "%s%lld", i ? "," : "", (long long)t->stride[i]);
std::fprintf(stderr, "] data %p\n", t->data);
}
#define R3D_STR(why, a1, v1, a2, v2) \
do { \
if (r3d_trace_on()) \
std::fprintf(stderr, "[r3d] %s:%d stride refusal: %s, %s %lld, %s %lld\n",\
__FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \
(long long)(v2)); \
return R3D_NO(RAD_E_STRIDE); \
} while (0)
/* ================================================================== dtype helpers
*
* A row's `dtype` constraint is a necessary condition on the geometry, not a promise about the
* tensors: the shim reads the dtype off the operand, and these are the tests it reads it with. */
static inline int r3d_is_bf16(const RadTensor* t) { return t && t->dtype == RAD_BF16; }
static inline int r3d_is_f16(const RadTensor* t) { return t && t->dtype == RAD_F16; }
static inline int r3d_is_f32(const RadTensor* t) { return t && t->dtype == RAD_F32; }
static inline int r3d_is_i32(const RadTensor* t) { return t && t->dtype == RAD_I32; }
static inline int r3d_is_i64(const RadTensor* t) { return t && t->dtype == RAD_I64; }
static inline int r3d_is_fp8(const RadTensor* t) {
return t && (t->dtype == RAD_F8E4M3 || t->dtype == RAD_F8E5M2);
}
static inline int r3d_is_e4m3(const RadTensor* t) { return t && t->dtype == RAD_F8E4M3; }
static inline int r3d_is_i8(const RadTensor* t) { return t && t->dtype == RAD_I8; }
static inline int r3d_is_u8(const RadTensor* t) { return t && t->dtype == RAD_U8; }
/* The dtype name a row's constraint table carries, for a shim that must match a string parameter
* against an operand. */
static inline int r3d_dt_named(uint32_t dt, const char* name) {
if (!name) return 0;
if (!std::strcmp(name, "bf16")) return dt == RAD_BF16;
if (!std::strcmp(name, "f16") || !std::strcmp(name, "fp16")) return dt == RAD_F16;
if (!std::strcmp(name, "f32") || !std::strcmp(name, "fp32")) return dt == RAD_F32;
if (!std::strcmp(name, "fp8_e4m3") || !std::strcmp(name, "e4m3")) return dt == RAD_F8E4M3;
if (!std::strcmp(name, "fp8_e5m2") || !std::strcmp(name, "e5m2")) return dt == RAD_F8E5M2;
if (!std::strcmp(name, "i8") || !std::strcmp(name, "int8")) return dt == RAD_I8;
return 0;
}
/* ================================================================== libr3d's constants
*
* Restated here because r3d_rows.cpp and r3d_shapes.cpp are host code built without ROCm and cannot
* include r3d.h, and because a .rad container records them in its layout tag. */
enum {
R3D_WAVE = 32,
/* The activation quantiser's group: the width a scale covers along n. 128 is the WEIGHT
* scale's block width and therefore a property of the checkpoint, not a knob. */
R3D_ACT_GROUP = 128,
/* Block-scaled fp8, on both axes: the checkpoint's `quantization_config.weight_block_size`,
* which the bytes on disk follow. The entry points reject a mismatch. */
R3D_FP8_BLOCK = 128,
/* The int8 weight group, the same 128 the checkpoint's scales use. */
R3D_W8_GROUP = 128,
/* The largest N a dot2 GEMM's per-lane accumulator grid spans in one wave. */
R3D_NTILE = 16,
/* The operand count of `gemm_nt_q` (a, a_scale, b, b_scale, y, a_sum, b_ref). The shape hook
* builds the whole list at once and needs a name for its length; the schema in r3d_rows.cpp is
* the authority, and rad-kbench checks the two against each other. */
R3D_GEMM_Q_NOPERAND = 7
};
/* ================================================================== libr3d's tunables
*
* The knobs the row table declares, exposed so `rad-tune` can walk them and `--debug-graph` can
* name the pick (spec §15). The chosen point comes back appended to RadArgs::p, so a launch reads
* it with r3d_geti_or like any other parameter; these structs are how a launch reads several at
* once, with the row's defaults where a caller supplied none.
*
* sk == 0 means "choose the largest legal split count at issue". Split-K requires
* K % (sk * group) == 0, so no fixed default is legal at every shape, and an illegal default would
* make an untuned install fail rather than run slowly. The sentinel is resolved in one place, in
* the GEMM unit.
*/
struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */
struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */
struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk width in columns */
extern "C" {
/* -- the tuned configuration (r3d_rows.cpp) --
*
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*);
void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*);
void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*);
} /* extern "C" */
#endif /* R3D_ARGS_H */
File diff suppressed because it is too large. Load diff
+359
View File
@@ -0,0 +1,359 @@
/* r3d_codecs.h -- the numeric codecs, in the one spelling every libr3d unit and the host use.
*
* These define what a result is, so they are stated once: rad_plugin.h's bf16 / f16 / fp8 / int8
* rounders, restated so a device kernel can call them. rad_plugin.h's are `static inline` host
* functions, which a `__global__` cannot reach, and libref -- the oracle every libr3d row is
* checked against at kbench -- is built out of them. The mirror is therefore not a style choice,
* and r3d_selftest.cpp compares the two over the whole fp8 code space, the whole bf16 code space
* and 2^20 random f32s, so a drift of one ulp is a test failure here and not a tolerance argument
* at kbench.
*
* The contract, from ref_common.h and rad_plugin.h: f32 accumulation, IEEE round-to-nearest-ties-
* to-even narrowing, no fused multiply-add and no reassociation, subnormals kept. Widening is
* exact. `-ffp-contract=off` is a correctness flag, and rad_hipify puts it on every HIP source.
*
* R3D_HD is `__host__ __device__` in a HIP translation unit and nothing in a host one, which is how
* the same header serves a kernel and r3d_selftest.cpp. The pieces that want a GPU instruction are
* behind __HIP_DEVICE_COMPILE__ and have a plain-C++ twin a device build never takes.
*/
#ifndef R3D_CODECS_H
#define R3D_CODECS_H
#include <cstdint>
#include <cstring>
/* HIP first, and before R3D_HD: `__forceinline__` is a macro of hip_runtime.h's, so a unit that
* includes this header without including the runtime first -- r3d_common.h includes the codecs
* before it -- would read `__forceinline__` as a type name. The runtime declares no
* `__host__ __device__` memcpy, which is why the bitcasts below go through bits_of and float_of.
* A host translation unit -- the row table, the operand descriptions, r3d_selftest.cpp -- takes the
* #else and pulls in no ROCm header at all. */
#if defined(__HIPCC__)
#include <hip/hip_runtime.h>
#endif
#if defined(__HIPCC__)
#define R3D_HD __device__ __host__ __forceinline__
#else
#define R3D_HD inline
#endif
/* The bit cast, in one place. Device code cannot call `memcpy` and the HIP headers do not declare a
* `__host__ __device__` one on every release, so the device path is the compiler's bit cast; the
* host path keeps memcpy, which the optimiser folds to a move, because GCC only grew
* `__builtin_bit_cast` in C++20 mode and r3d_selftest.cpp is built at C++17 by the tree's host
* compiler. */
R3D_HD uint32_t bits_of(float f) {
#if defined(__HIPCC__)
return __builtin_bit_cast(uint32_t, f);
#else
uint32_t u;
std::memcpy(&u, &f, sizeof u);
return u;
#endif
}
R3D_HD float float_of(uint32_t u) {
#if defined(__HIPCC__)
return __builtin_bit_cast(float, u);
#else
float f;
std::memcpy(&f, &u, sizeof f);
return f;
#endif
}
/* ================================================================== bf16
*
* bf16 is f32's top half: widening is a shift, narrowing one add and a shift.
*
* `(u >> 16) & 1` is the tie-break -- it adds one more than the halfway point when the surviving
* bit is odd, so ties go to even. Overflow carries into the bf16 infinity; a NaN is forced quiet so
* it cannot round into an infinity, which is what rad_f32_to_bf16 does and what libref does. */
R3D_HD float bf16_to_f32(uint16_t h) {
const uint32_t u = (uint32_t)h << 16;
return float_of(u);
}
R3D_HD uint16_t f32_to_bf16(float f) {
const uint32_t u = bits_of(f);
if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t)((u >> 16) | 0x0040u);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
/* The same rounding, stopped one shift short: the rounded value sitting in a word's high half, the
* form a packed store wants. gfx11 in this ROCm has no v_cvt_pk_bf16_f32 (llvm-mc rejects it on
* gfx1100, gfx1102 and gfx1151), so a bf16 pair is two of these and one byte permute. */
R3D_HD uint32_t bf16_hi_rne(float f) {
const uint32_t u = bits_of(f);
return u + 0x7fffu + ((u >> 16) & 1u);
}
/* Two such words as one bf16 pair, `lo`'s half in the low half of the result: one v_perm_b32. */
R3D_HD uint32_t bf16_pack_hi(uint32_t lo, uint32_t hi) {
#if defined(__HIP_DEVICE_COMPILE__)
return __builtin_amdgcn_perm(hi, lo, 0x07060302u);
#else
return ((lo >> 16) & 0xffffu) | (hi & 0xffff0000u);
#endif
}
R3D_HD uint32_t bf16x2_rne(float lo, float hi) {
return bf16_pack_hi(bf16_hi_rne(lo), bf16_hi_rne(hi));
}
/* A bf16 pair word's two values as floats: a shift and a mask, no conversion. */
R3D_HD float bf16w_lo(uint32_t w) {
const uint32_t u = w << 16;
return float_of(u);
}
R3D_HD float bf16w_hi(uint32_t w) {
const uint32_t u = w & 0xffff0000u;
return float_of(u);
}
/* ================================================================== f16
*
* RTNE both ways with subnormals kept, as rad_f16_to_f32 and rad_f32_to_f16 do -- not the hardware
* convert, whose rounding mode a caller could have changed and which flushes subnormal halves. */
R3D_HD float f16_to_f32(uint16_t h) {
const uint32_t s = (uint32_t)(h >> 15) << 31;
const uint32_t e = (uint32_t)(h >> 10) & 0x1fu;
uint32_t m = (uint32_t)h & 0x3ffu;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0; /* subnormal: renormalise into f32's range */
while (!(m & 0x400u)) { m <<= 1; ++sh; }
m &= 0x3ffu;
u = s | ((uint32_t)(127 - 15 - sh + 1) << 23) | (m << 13);
}
} else if (e == 0x1fu) {
u = s | 0x7f800000u | (m << 13);
} else {
u = s | ((e - 15u + 127u) << 23) | (m << 13);
}
return float_of(u);
}
R3D_HD uint16_t f32_to_f16(float f) {
const uint32_t u = bits_of(f);
const uint32_t s = (u >> 16) & 0x8000u;
const uint32_t a = u & 0x7fffffffu;
if (a >= 0x7f800000u) /* inf or nan */
return (uint16_t)(s | 0x7c00u | (a > 0x7f800000u ? ((a >> 13) & 0x3ffu) | 0x200u : 0u));
if (a >= 0x47800000u) return (uint16_t)(s | 0x7c00u); /* overflow -> inf */
if (a < 0x33000000u) return (uint16_t)s; /* underflow -> zero */
const int e = (int)(a >> 23) - 127;
uint32_t m = a & 0x7fffffu;
if (e < -14) { /* subnormal half */
const int sh = -14 - e + 13;
m |= 0x800000u;
const uint32_t lo = m & ((1u << sh) - 1u);
uint32_t q = m >> sh;
const uint32_t half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint16_t)(s | q);
}
uint32_t q = m >> 13;
const uint32_t lo = m & 0x1fffu;
uint32_t he = (uint32_t)(e + 15);
if (lo > 0x1000u || (lo == 0x1000u && (q & 1u))) ++q;
if (q == 0x400u) { q = 0; ++he; } /* rounding carried into the exp */
if (he >= 0x1fu) return (uint16_t)(s | 0x7c00u);
return (uint16_t)(s | (he << 10) | q);
}
/* Two f32 as one dword of two f16, `lo` in the low half.
*
* v_cvt_pkrtz_f16_f32 rounds toward zero, which is not RTNE, so this is only ever called with
* values f16 represents exactly: a bf16 widened (seven mantissa bits into ten) or an E4M3 code
* (three into three). For those the two spellings give the same bits and the instruction is free. */
R3D_HD uint32_t f16x2_pack(float lo, float hi) {
#if defined(__HIP_DEVICE_COMPILE__)
/* The builtin answers as a pair of __fp16; the bits are the dword the dot2 reads. */
return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pkrtz(lo, hi));
#else
return (uint32_t)f32_to_f16(lo) | ((uint32_t)f32_to_f16(hi) << 16);
#endif
}
/* A dword of two bf16 as a dword of two f16.
*
* Exact over f16's normal range, and that is what makes the dot2 path sound: a bf16 has seven
* mantissa bits and an f16 ten, so within [2^-14, 65504] a widening costs no rounding and a dot
* product over widened bf16 accumulates the sums libref forms over its bf16 operands.
*
* Outside it the widening is not exact, and the two edges behave differently. Above 65504 a
* magnitude becomes an infinity (the packing instruction saturates, which is the kinder of the two
* answers). Below 2^-14 the operand is an f16 subnormal, whose grid is a power of two coarser than
* bf16's at the same magnitude, so a widening truncates toward zero -- and below 2^-24 it flushes.
* The truncation is what the packing instruction does, `v_cvt_pkrtz_f16_f32` rounding toward zero.
*
* The low edge costs a served model nothing: an activation below 2^-14 times a weight of a
* hundredth is 1e-18, against an accumulator of order one, so it is not a term the sum can see;
* and a scale-reduced operand is scaled back up before it is used, which is why the quantised rows
* put the scale on the block, not the element. What would be visible is a weight stream whose
* magnitudes live below 2^-14, and no checkpoint's do. The rows whose band can reach 65504 say so
* in their `shape` text. */
R3D_HD uint32_t bf16x2_to_f16x2(uint32_t w) {
return f16x2_pack(bf16w_lo(w), bf16w_hi(w));
}
/* ================================================================== fp8 e4m3 ("e4m3fn")
*
* 1-4-3, bias 7, no infinity, S1111111 the only NaN, 448 the largest finite. The KV-cache and
* block-scaled weight format, so the attention oracle and every fp8 row depend on its rounding.
*
* RDNA3 has no instruction for it: v_cvt_pk_fp8_f32 and v_cvt_pk_f32_fp8 need the fp8 feature,
* which RDNA3 does not have. The builtins are *declared* for gfx11 -- so `__has_builtin` is true
* here, which is the trap a `__has_builtin` guard falls into, and libr4d's guards are exactly that
* -- and rejected at instruction selection. Both directions are bit maths, about eleven VALU an
* encode and six a decode. */
R3D_HD float e4m3_to_f32(uint8_t b) {
const uint32_t s = (uint32_t)(b >> 7) << 31;
const uint32_t e = (uint32_t)(b >> 3) & 0xfu;
uint32_t m = (uint32_t)b & 0x7u;
uint32_t u;
if (e == 0u) {
if (m == 0u) {
u = s;
} else {
int sh = 0; /* subnormal: 2^-9 * m/8 */
while (!(m & 0x8u)) { m <<= 1; ++sh; }
m &= 0x7u;
u = s | ((uint32_t)(127 - 6 - sh) << 23) | (m << 20);
}
} else if (e == 0xfu && m == 0x7u) {
u = s | 0x7fc00000u; /* the single NaN encoding */
} else {
u = s | ((e - 7u + 127u) << 23) | (m << 20);
}
return float_of(u);
}
/* Saturates at 448 rather than overflowing: a NaN from one large activation spreads through the
* whole row, and every fp8 cast in this project clamps for that reason. The clamp is inside the
* codec here because there is no instruction to clamp in front of. */
R3D_HD uint8_t f32_to_e4m3(float f) {
const uint32_t u = bits_of(f);
const uint8_t s = (uint8_t)((u >> 24) & 0x80u);
const uint32_t a = u & 0x7fffffffu;
if (a > 0x7f800000u) return (uint8_t)(s | 0x7fu); /* nan */
if (a >= 0x43e00000u) return (uint8_t)(s | 0x7eu); /* >= 448: the largest finite */
const int e = (int)(a >> 23) - 127;
uint32_t m = a & 0x7fffffu;
/* The smallest subnormal is 2^-9, so everything below half of it (exponent -11 and below)
* rounds to zero. Exponent -10 is [2^-10, 2^-9): its tie point 2^-10 rounds to the even zero
* and the rest up to 2^-9, which the subnormal branch does with a 24-bit shift. */
if (e < -10) return s;
if (e < -6) { /* subnormal fp8 */
const int sh = -6 - e + 20;
m |= 0x800000u;
const uint32_t lo = m & ((1u << sh) - 1u);
uint32_t q = m >> sh;
const uint32_t half = 1u << (sh - 1);
if (lo > half || (lo == half && (q & 1u))) ++q;
return (uint8_t)(s | q);
}
uint32_t q = m >> 20;
const uint32_t lo = m & 0xfffffu;
int ee = e + 7;
if (lo > 0x80000u || (lo == 0x80000u && (q & 1u))) ++q;
if (q == 0x8u) { q = 0; ++ee; }
if (ee > 15 || (ee == 15 && q >= 7u)) return (uint8_t)(s | 0x7eu);
return (uint8_t)(s | ((uint32_t)ee << 3) | q);
}
/* Two codes in one dword, the low element in the low byte: the store a wave's lane does. */
R3D_HD uint32_t e4m3x2_pack(float lo, float hi) {
return (uint32_t)f32_to_e4m3(lo) | ((uint32_t)f32_to_e4m3(hi) << 8);
}
/* A dword of two E4M3 codes as a dword of two f16.
*
* Exact -- e4m3 has four exponent and three mantissa bits, f16 five and ten -- and this is the fp8
* matrix path: a code becomes the f16 the checkpoint means, dot2 multiplies it, and the block
* scale is applied once per block. RDNA3 has no fp8 hardware, so the decode is VALU, and it is
* paid where the weight bytes are being read anyway. */
R3D_HD uint32_t e4m3x2_to_f16x2(uint32_t w) {
return f16x2_pack(e4m3_to_f32((uint8_t)(w & 0xffu)), e4m3_to_f32((uint8_t)(w >> 8)));
}
/* ================================================================== int8
*
* The symmetric int8 twin: amax/127, RTNE, saturating. f16 holds every int8 exactly, so widening
* into a dot product is exact and the scale is the only float in the path. */
R3D_HD int8_t f32_to_i8_rtne(float f) {
if (!(f == f)) return 0;
/* Round to nearest, ties to even, in integer arithmetic. A tie at the top of the range would
* round to a code that does not exist (+128), so the clamp is applied after the rounding, not
* as an early return: 127.5 goes to the even 128 and then clamps to 127, which is what
* rad_round_even_sat gives. */
const float fl = __builtin_floorf(f);
const float frac = f - fl;
int32_t q = (int32_t)fl;
if (frac > 0.5f) ++q;
else if (frac == 0.5f && (q & 1)) ++q;
if (q > 127) q = 127;
if (q < -128) q = -128;
return (int8_t)q;
}
R3D_HD uint32_t i8x2_pack(float lo, float hi) {
return (uint32_t)(uint8_t)f32_to_i8_rtne(lo) | ((uint32_t)(uint8_t)f32_to_i8_rtne(hi) << 8);
}
R3D_HD uint32_t i8x2_to_f16x2(uint32_t w) {
return f16x2_pack((float)(int8_t)(uint8_t)(w & 0xffu), (float)(int8_t)(uint8_t)(w >> 8));
}
/* ================================================================== the dot product
*
* Two f16 products into an f32 accumulator, one instruction: v_dot2acc_f32_f16, which
* __builtin_amdgcn_fdot2 lowers to on every gfx11 target (checked by reading the emitted asm on
* gfx1100, gfx1102 and gfx1151). RDNA3 pairs it as v_dual_dot2acc_f32_f16 where the scheduler can,
* which is how libr3d's inner loops reach the matrix unit's absence without noticing.
*
* The selector is FALSE, always. RDNA3 has no bf16 dot2, and this compiler accepts the bf16
* selector and emits the f16 instruction anyway: a bf16 pair passed with sel=true is read as two
* f16s and the products are nonsense, silently, on every gfx11 target. bf16 operands are widened
* with bf16x2_to_f16x2, which is exact.
*
* The two products go into `acc` in the order written, and a kernel that walks k ascending
* reproduces libref's summand-for-summand: the reference loop is `s += a[k]*b[k]` with
* -ffp-contract=off. The match is not bit-exact and cannot be: `v_dot2acc_f32_f16` folds the two
* products and the accumulator with guard bits and rounds once, where the reference rounds each
* product and each sum. The difference is under an f32 ulp a pair, a random walk of about
* sqrt(K/2) ulps over a K-long dot, which is a thousandth of the bf16 the store narrows to -- so it
* sits inside what `rad-kbench` measures, exactly as libr4d's WMMA accumulation does. What is
* required, and what every loop here keeps, is that the *order* of the summands be the reference's:
* k ascending, one accumulator per output element, no reassociation across lanes.
*
* The host path below is the same arithmetic with each product rounded first, which is what a test
* needs it to be. It is not the hardware's rounding. */
R3D_HD float dot2_f16x2(uint32_t a, uint32_t b, float acc) {
#if defined(__HIP_DEVICE_COMPILE__)
typedef __fp16 v2h __attribute__((ext_vector_type(2)));
return __builtin_amdgcn_fdot2(__builtin_bit_cast(v2h, a), __builtin_bit_cast(v2h, b), acc,
false);
#else
const uint32_t alo = a & 0xffffu, ahi = a >> 16;
const uint32_t blo = b & 0xffffu, bhi = b >> 16;
return acc + f16_to_f32((uint16_t)alo) * f16_to_f32((uint16_t)blo)
+ f16_to_f32((uint16_t)ahi) * f16_to_f32((uint16_t)bhi);
#endif
}
/* Four f16 products into one accumulator: the step every libr3d matmul runs. The two dot2s are a
* dependency chain of two; a kernel keeps four of these chains in flight. */
R3D_HD float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1, float acc) {
return dot2_f16x2(a1, b1, dot2_f16x2(a0, b0, acc));
}
#endif /* R3D_CODECS_H */
+256
View File
@@ -0,0 +1,256 @@
/* r3d_common.h -- the RDNA3 seams a kernel needs: the wave's lane maths, the loads, the block
* reduce, the occupancy and LDS conventions.
*
* What RDNA3 gives, measured on the ROCm this tree builds against (AMD clang 24; `__has_builtin`
* off --offload-device-only, and llvm-mc -show-encoding per target). The codecs are in r3d_codecs.h;
* this header is what is left.
*
* v_dot2acc_f32_f16 yes, every gfx11 target, from __builtin_amdgcn_fdot2, and RDNA3 pairs
* it as v_dual_dot2acc_f32_f16 where the scheduler can. The matrix work.
* v_dot2 with bf16 no, and the builtin's bf16 selector is accepted and ignored -- the f16
* instruction is emitted -- so bf16 is widened, never asserted.
* WMMA the mnemonic is unreachable -- every v_wmma_* is rejected by the
* assembler on gfx1100, gfx1102, gfx1151 and gfx1201 alike, and inline
* asm dies in amdgcn-link -- but the builtin is not:
* __builtin_amdgcn_wmma_f32_16x16x16_f16_w32 compiles for the three gfx11
* targets and emits a real tile instruction. Measured here against dot2 at
* four occupancies, 1.99 against 1.97 TFLOP/s: RDNA3's AI accelerator is a
* 2x f16-rate feature and a paired dot2 is already at that rate, so the
* tile buys a fragment layout and a block-alignment requirement and no
* throughput. No fragment layouts here, so no repacked weights, so no
* layout hook: a dot2 GEMM reads a weight in the order it is stored.
* fp8 convert no (needs the fp8 feature); the builtins are declared and die at
* instruction selection, which is why the codecs are software.
* v_cvt_pkrtz_f16_f32 yes. Used only where it is exact.
* v_cvt_pk_bf16_f32 no on gfx1100/1102/1151 in this build, so bf16 packs are software.
* DPP16, v_permlanex16 yes, RDNA1 onward. The lane maths below is libr4d's, unchanged: the
* encodings are the same silicon, and they were verified on hardware.
* ballot_w32, readlane,
* readfirstlane, ds_bpermute,
* v_perm_b32, exp2f, rcpf,
* s_barrier, fence,
* sched_group_barrier yes.
* transposed loads no: neither global_load_tr_b128 (RDNA4) nor ds_read_b64_tr_b16 (dropped
* by RDNA4, kept here as a fact about gfx11 -- this ROCm's assembler
* rejects it too). A transpose is done in registers.
*
* Wave32 is gfx11's default and every kernel here is written for it; the guard below fires if a
* build asks for wave64, because that computes garbage rather than running slower.
*
* The register file is the one number that is NOT the same as RDNA4's: a gfx11 SIMD has 1024 VGPRs
* for a wave32, allocated in groups of 8, against gfx1201's 1536. R3D_WAVES is stated per kernel,
* and a kernel's budget is computed against 1024.
*/
#ifndef R3D_COMMON_H
#define R3D_COMMON_H
#include "r3d_codecs.h"
#include <hip/hip_runtime.h>
#include <cstdint>
#if defined(__HIP_DEVICE_COMPILE__) && defined(__AMDGCN_WAVEFRONT_SIZE)
#if __AMDGCN_WAVEFRONT_SIZE != 32
#error "libr3d kernels are written for wave32, gfx11's default; a wave64 build computes garbage"
#endif
#endif
enum : int { kWave = 32 };
/* A 16-byte staging register as a native vector. HIP's uint4 is a class template wrapping a union,
* and an array of them carried across a loop is kept in scratch by LLVM 22 and 24; an
* ext_vector_type array is promoted to registers. Loaded and stored whole only. */
typedef unsigned int r3d_u32x4 __attribute__((ext_vector_type(4)));
typedef unsigned int r3d_u32x2 __attribute__((ext_vector_type(2)));
/* ================================================================== the occupancy a kernel is
* built for
*
* Fixes the waves per SIMD the compiler schedules for. Left unstated, the scheduler picks the
* target itself and the choice moves between compiler releases. gfx11's budget is 1024 VGPRs a
* SIMD at wave32, in granules of 8: a kernel asking for 5 waves has 204 registers to spend. */
#define R3D_WAVES(n) __attribute__((amdgpu_waves_per_eu((n), (n))))
/* ================================================================== exp2
*
* The hardware transcendental. libr4d's rule applies: exp2f, powf and sincosf are the accurate
* forms, not the __ approximations -- rope positions reach 262144, past __sincosf's argument
* reduction, and libref uses libm. exp2f itself is the one place the hardware op is exactly what
* the reference computes, because both sides round the same result once. */
__device__ __forceinline__ float ex2(float x) {
return __builtin_amdgcn_exp2f(x);
}
__device__ __forceinline__ float rcp(float x) { return __builtin_amdgcn_rcpf(x); }
/* ================================================================== one element, one register
*
* A 16-bit element of global memory, zero-extended into a whole register (global_load_u16). Read as
* `uint16_t` it lands in a register half (global_load_d16_b16) whose other half the waitcnt pass
* then waits for; through a generic pointer it is also a flat load. The pointer must address global
* memory, which every caller's operand is.
*
* libr4d notes that LLVM 24 gives gfx12 real 16-bit registers and the packability that follows;
* gfx11 does not have them, so keeping bf16 in whole registers from load to store is the plain
* reading as well as the portable one. */
typedef const uint16_t __attribute__((address_space(1))) *r3d_gu16;
__device__ __forceinline__ uint32_t ldg_u16(const uint16_t* p) { return *(r3d_gu16)p; }
__device__ __forceinline__ uint32_t ldg_u32(const uint32_t* p) { return *(const __attribute__((address_space(1))) uint32_t*)p; }
__device__ __forceinline__ float ldg_f32(const float* p) {
return *(const __attribute__((address_space(1))) float*)p;
}
/* ================================================================== lane maths
*
* A wave is 32 lanes, two rows of sixteen. Reductions are XOR butterflies, in the order a
* __shfl_xor loop runs in, so the result is bit-identical to that loop -- which is what libref
* sums, since the reference sums a row in ascending index order and a wave of lanes maps to
* consecutive elements.
*
* `__shfl_xor` lowers to ds_bpermute_b32 plus s_wait_dscnt, an LDS round trip that dominates a
* dependency chain. DPP16's ROW_XMASK (control 0x160 | N) makes the partner read a modifier on the
* consuming VALU op, and N = 16 crosses the two rows of a wave32 with v_permlanex16, still one VALU
* op. Row and bank masks are all-ones because every lane participates; bound_ctrl is moot because
* every lane has a partner. These are libr4d's encodings, verified on hardware. */
template <int N>
__device__ __forceinline__ uint32_t r3d_xor_lane_u32(uint32_t v) {
static_assert(N >= 1 && N <= 16 && (N & (N - 1)) == 0, "a lane xor within the wave");
if constexpr (N < 16)
return (uint32_t)__builtin_amdgcn_update_dpp(0, (int)v, 0x160 | N, 0xf, 0xf, true);
else
return (uint32_t)__builtin_amdgcn_permlanex16((int)v, (int)v, 0x76543210u, 0xFEDCBA98u,
false, false);
}
template <int N>
__device__ __forceinline__ float r3d_xor_lane(float v) {
return __uint_as_float(r3d_xor_lane_u32<N>(__float_as_uint(v)));
}
/* A 64-bit value's partner: the halves exchanged separately, as a 64-bit shuffle does. */
template <int N>
__device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long long v) {
const uint32_t lo = r3d_xor_lane_u32<N>((uint32_t)v);
const uint32_t hi = r3d_xor_lane_u32<N>((uint32_t)(v >> 32));
return ((unsigned long long)hi << 32) | lo;
}
/* v_permlanex16 swaps only with identity selectors (each 4-bit field names the source lane in the
* other half; sel0 covers lanes 0-7, sel1 lanes 8-15); zero selectors silently broadcast lane 0. */
__device__ __forceinline__ float swap16(float x) { return r3d_xor_lane<16>(x); }
/* v + the partner's v, the partner read by DPP so the add carries it. */
template <int CTRL>
__device__ __forceinline__ float r3d_dpp_xor_add(float v) {
return v + __uint_as_float(__builtin_amdgcn_update_dpp(0, __float_as_uint(v), CTRL, 0xF, 0xF,
true));
}
__device__ __forceinline__ float wave_sum(float v) {
v += swap16(v); /* xor 16 -- crosses the two rows of sixteen */
v = r3d_dpp_xor_add<0x168>(v); /* xor 8 -- row_xmask from here down */
v = r3d_dpp_xor_add<0x164>(v); /* xor 4 */
v = r3d_dpp_xor_add<0x162>(v); /* xor 2 */
v = r3d_dpp_xor_add<0x161>(v); /* xor 1 */
return v;
}
__device__ __forceinline__ float wave_max(float v) {
v = fmaxf(v, r3d_xor_lane<16>(v));
v = fmaxf(v, r3d_xor_lane<8>(v));
v = fmaxf(v, r3d_xor_lane<4>(v));
v = fmaxf(v, r3d_xor_lane<2>(v));
v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
/* The same butterflies over a group of W lanes (a power of two up to the wave), in the order
* `for (o = W/2; o; o >>= 1) v = op(v, __shfl_xor(v, o))` runs them, so bit-identical to it. A row
* of sixteen lanes -- the sixteen columns a lane owns in a bf16 pair layout -- uses W = 16. */
template <int W>
__device__ __forceinline__ float r3d_xor_sum(float v) {
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
if constexpr (W >= 32) v += r3d_xor_lane<16>(v);
if constexpr (W >= 16) v += r3d_xor_lane<8>(v);
if constexpr (W >= 8) v += r3d_xor_lane<4>(v);
if constexpr (W >= 4) v += r3d_xor_lane<2>(v);
if constexpr (W >= 2) v += r3d_xor_lane<1>(v);
return v;
}
template <int W>
__device__ __forceinline__ float r3d_xor_max(float v) {
static_assert(W >= 1 && W <= 32 && (W & (W - 1)) == 0, "a power-of-two group within the wave");
if constexpr (W >= 32) v = fmaxf(v, r3d_xor_lane<16>(v));
if constexpr (W >= 16) v = fmaxf(v, r3d_xor_lane<8>(v));
if constexpr (W >= 8) v = fmaxf(v, r3d_xor_lane<4>(v));
if constexpr (W >= 4) v = fmaxf(v, r3d_xor_lane<2>(v));
if constexpr (W >= 2) v = fmaxf(v, r3d_xor_lane<1>(v));
return v;
}
/* A wave's inclusive prefix sum in registers: row_shr 1, 2, 4 and 8 within each row of sixteen,
* then the other row's total from one readlane. Lane L ends with the sum over lanes 0..L. Replaces
* an LDS step-doubling scan, which costs two barriers a round. Integer, so combine order is free.
* Every lane must be active. */
__device__ __forceinline__ uint32_t wave_prefix_u32(uint32_t x, int lane) {
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x111, 0xF, 0xF, true); /* row_shr:1 */
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x112, 0xF, 0xF, true); /* row_shr:2 */
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x114, 0xF, 0xF, true); /* row_shr:4 */
x += (uint32_t)__builtin_amdgcn_update_dpp(0, (int)x, 0x118, 0xF, 0xF, true); /* row_shr:8 */
const uint32_t lo = (uint32_t)__builtin_amdgcn_readlane((int)x, 15);
return lane >= 16 ? x + lo : x;
}
/* ================================================================== a block's sum
*
* Wave sum, one LDS round trip, then every thread adds the wave partials in wave order. The order
* is the contract: libref sums a row in ascending index order, the waves cover consecutive
* elements, and adding the partials in wave order is the same bracketing at any thread count.
* `lds` holds NWAVES floats. */
template <int NTHREADS>
__device__ __forceinline__ float block_sum(float v, float* lds) {
constexpr int NWAVES = NTHREADS / kWave;
const uint32_t lane = threadIdx.x & (kWave - 1);
const uint32_t w = threadIdx.x / kWave;
v = wave_sum(v);
if (lane == 0) lds[w] = v;
__syncthreads();
if constexpr (NWAVES == 1) return lds[0];
float t = lds[0];
#pragma unroll
for (int i = 1; i < NWAVES; ++i) t += lds[i];
return t;
}
/* ================================================================== scheduling
*
* LLVM single-buffers LDS and drains before every dependent read unless told otherwise; on gfx11
* the matrix unit is absent so there is nothing to overlap a load with, and the barrier the
* kernels need is the plain one. */
__device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); }
__device__ __forceinline__ void group_barrier() { __syncthreads(); }
/* ================================================================== the geometry constants
*
* A gfx11 GPU's wave slots: a CU has 4 SIMDs, a SIMD holds 16 wave32s, so 64 slots a CU. HIP's
* multiProcessorCount reports CUs on gfx11 (it reports WGPs on gfx12, which is where libr4d's 2048
* comes from), and a launch whose grid passes 64 * multiProcessorCount waves has more work than
* slots: the tail waves start after another wave retires. A row-per-block kernel with one wave a
* block is exactly that cliff, and its row count is where the cliff is.
*
* A launcher's question, so a host function: this HIP declares no device-side hipGetDevice or
* hipDeviceGetAttribute, and a __device__ body does not compile at all. */
static inline int wave_slot_count() {
int dev = 0, cu = 0;
(void)hipGetDevice(&dev);
(void)hipDeviceGetAttribute(&cu, hipDeviceAttributeMultiprocessorCount, dev);
return 64 * cu;
}
/* The LDS a workgroup gets is 64 KiB, the same figure RDNA4 gives, and no kernel in libr3d needs
* more. There is no hipFuncSetAttribute opt-in: 64 KiB of dynamic shared memory is available as
* soon as it is asked for. */
enum : int { kLdsCap = 64 * 1024 };
#endif /* R3D_COMMON_H */
+309
View File
@@ -0,0 +1,309 @@
/* r3d_dflash_f32.hip -- DFlash2's candidate walk, `dflash_select`, on the card.
*
* A block-diffusion drafter proposes every position of a block in one backbone pass, so position
* l+1 is not conditioned on what the drafter chose at l. This op restores that dependence: it walks
* the `steps` positions in order and, at each, picks the candidate that maximises
*
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
*
* where pid(0) is the anchor -- the token the target just committed, read at
* `anchor[m * anchor_stride]` -- and pid(l) is the walk's own previous pick, `cand[l-1, chosen]`.
* `hp` absent is a plane of ones, which drops the trilinear form to a low-rank bigram (DSpark's
* Markov head). libref's `ref_dflash_select` is the law, and this file transcribes its arithmetic
* and its order.
*
* ============================== why it is a kernel and not a GEMM ==============================
*
* The walk is serial in l: the predecessor of step l is not known until step l-1 has been decided,
* so the [steps, K, K] edge tensor cannot be scored in advance -- scoring it computes K times the
* edges that are ever read. What is parallel is the sequences (M of them) and, inside a step, the K
* candidates. So a block takes `256 / top_k` sequences and gives each lane one (sequence,
* candidate) pair: the lane runs the rank sum for its own edge, in the reference's order, and one
* lane per sequence scans the K scores and takes the pick. The loop over `steps` stays serial, with
* the two LDS round trips per step (the scores out, the pick back) that the dependence requires.
*
* The rank sum is the whole cost: at the band (steps=7, top_k=16, rank=256, M=256) a walk is
* 7 * 16 * 256 = 28672 fused terms, and the bytes it touches are the K successor rows a step reads,
* 16 * 512 B of bf16, so the op is a gather over `succ` [n_vocab, rank] -- 66.8 MiB of codebook at
* the band, of which the walk reads M * steps * K = 28672 rows, about 14.7 MiB, plus one
* predecessor row a step. There is no arithmetic to hide that behind, which is why the sum is a
* plain ascending chain and not a tree: a tree buys nothing here and costs the agreement.
*
* ============================== agreement, and where this file declines ==============================
*
* Bit-exact by construction, not by tolerance:
*
* - the rank sum is `sc = unary; for (i = 0; i < rank; ++i) sc += ax[i] * succ[i];` -- ascending
* in r, one accumulator, no reduction, no tree, with `-ffp-contract=off` so no FMA fusion
* changes the rounding of a term;
* - `ax[i] = pred[pid][i] * hp[l][i]` is rounded to f32 before it meets `succ`, because the
* reference writes it into a float array first (and with `hp` absent it is `pred * 1.0f`, which
* is the same value);
* - the argmax is a strict `>` over c ascending, so the earliest candidate wins a tie and a NaN
* never displaces the incumbent -- the reference's loop, statement for statement;
* - a predecessor outside the vocabulary contributes zero, and a candidate outside it is scored
* by `unary` alone: both are the reference's tests (`pid >= 0 && pid < nv`, `tok >= 0 &&
* tok < nv`), and both are why padding rows -- a shard's unused rows, a block shorter than
* `steps` -- are legal inputs;
* - the pick of step l is written to `tokens[m, l]` and becomes pid(l+1) unchanged, including
* when it is out of range for the codebooks.
*
* Declines, all of them the shim's, none reachable from a row that carries the constraints its row
* states: a codebook (`pred`, `succ`, `hp`) that is not bf16, because this is the bf16
* instantiation -- the band's `dtype` is the codebooks' width and a row asks for bf16 (RAD_E_DTYPE);
* `unary` that is not f32, `cand`/`anchor`/`tokens` that are not i32, exactly as the schema's
* operand list types them (RAD_E_DTYPE); a codebook whose rows are not contiguous -- the gather is
* `token * rank + r` and a row stride inside the row is not that (RAD_E_STRIDE); `top_k` above 256,
* which is one lane a candidate and no more candidates than lanes (RAD_E_UNSUPPORTED); and a `cand`
* plane that describes more sequences than the band's `M`, which is `band_rows` refusing and is
* RAD_E_SHAPE, not a truncation.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_codecs.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <rad_types.h>
namespace {
constexpr uint32_t kThr = 256; /* 8 waves: the block's (sequence, candidate) lanes */
constexpr uint32_t kKMax = kThr; /* one lane a candidate, so top_k <= 256 */
/* Whole-register loads of the planes the walk gathers through. bf16 is a 16-bit load and the
* library's codec, which is the same decode libref's `ldt` performs. */
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
return (int32_t)ldg_u32((const uint32_t*)p);
}
__device__ __forceinline__ float ldg_f32(const float* p) { return *(const float*)p; }
__device__ __forceinline__ uint16_t ldg_u16(const uint16_t* p) { return *(const uint16_t*)p; }
/* ------------------------------------------------------------------ the walk
* `per` sequences per block, `K` candidates per sequence, so lane (s, c) owns the edge
* (sequence s, candidate c) of the step in hand. `hp` may be null: then the `hp` factor is 1.0f,
* exactly as the reference's `(hp ? ldt(hp, ...) : 1.0f)` writes it. */
__global__ __launch_bounds__(kThr) void dflash_select_kernel(
const int32_t* __restrict__ cand, const float* __restrict__ un,
const uint16_t* __restrict__ hp, const int32_t* __restrict__ anc,
const uint16_t* __restrict__ pred, const uint16_t* __restrict__ succ,
int32_t* __restrict__ out, uint32_t M, uint32_t steps, uint32_t K, uint32_t R, uint32_t nv,
uint32_t astr, long long cand_ld, long long un_ld, long long hp_ld, long long pred_ld,
long long succ_ld, long long tok_ld, uint32_t per) {
__shared__ int32_t s_pid[kThr]; /* the walk's predecessor, one per sequence */
__shared__ float s_sc[kThr]; /* this step's K scores, one per lane */
const uint32_t s = threadIdx.x / K; /* the sequence this lane walks for */
const uint32_t c = threadIdx.x - s * K; /* the candidate this lane scores */
const uint32_t seq0 = blockIdx.x * per + s;
/* A block of 256 lanes holds ceil(256 / K) sequences and the last group can be partial. A lane
* with no sequence replays the last real one: it reaches every __syncthreads() and its stores
* are suppressed, and the loads it performs are in range because the sequence it replays is. */
const uint32_t seq = seq0 < M ? seq0 : M - 1;
const bool mine = seq0 < M;
/* pid(0): the anchor, at `m * anchor_stride` in a flat plane. The reference reads it through
* `ld_int`, so a negative id is a legal "no predecessor" and not an error. */
int32_t pid = ldg_i32(anc + (size_t)seq * (size_t)astr);
const bool has_hp = (hp != nullptr);
for (uint32_t l = 0; l < steps; ++l) {
const uint32_t r = seq * steps + l; /* cand/unary/hp are one row per (m, l) */
const size_t cb = (size_t)r * (size_t)cand_ld;
const int32_t tok = ldg_i32(cand + cb + c);
float sc = ldg_f32(un + (size_t)r * (size_t)un_ld + c);
/* A predecessor outside the vocabulary contributes nothing; a candidate outside it is
* scored by `unary` alone. Both tests are the reference's, and both are why a shard's
* padding rows and a block shorter than `steps` are legal inputs. */
const bool have_p = pid >= 0 && (uint32_t)pid < nv;
const bool have_s = tok >= 0 && (uint32_t)tok < nv;
if (have_s) {
const uint16_t* pp = pred + (size_t)(have_p ? pid : 0) * (size_t)pred_ld;
const uint16_t* sp = succ + (size_t)tok * (size_t)succ_ld;
const uint16_t* hpb = hp + (size_t)r * (size_t)hp_ld;
for (uint32_t i = 0; i < R; ++i) {
/* ax[i], rounded to f32 where the reference writes it into its float array, and
* then the ascending chain. 1.0f for a missing hp is the reference's own factor. */
const float ax = have_p
? bf16_to_f32(ldg_u16(pp + i)) * (has_hp ? bf16_to_f32(ldg_u16(hpb + i)) : 1.0f)
: 0.0f;
sc += ax * bf16_to_f32(ldg_u16(sp + i));
}
}
s_sc[threadIdx.x] = sc; /* == s_sc[s * K + c] */
__syncthreads();
if (c == 0) {
/* The reference's argmax: strict `>`, c ascending, so the earliest candidate wins a
* tie and a NaN never takes the lead from a number. */
uint32_t best_c = 0;
float best_s = -INFINITY;
for (uint32_t j = 0; j < K; ++j) {
const float v = s_sc[s * K + j];
if (v > best_s) { best_s = v; best_c = j; }
}
const int32_t pick = ldg_i32(cand + cb + best_c);
if (mine) out[(size_t)seq * (size_t)tok_ld + l] = pick;
s_pid[s] = pick; /* pid(l+1), out-of-range included */
}
__syncthreads();
pid = s_pid[s];
}
}
/* ------------------------------------------------------------------ shim helpers */
/* The plane's row pitch, from the plane: `rows` is its row count and `ld` the pitch a row's
* elements start at, K apart. A rank-1 plane is a run of rows K apart, which is what the
* reference's rowoff does for one. */
static inline int rows_pitch(const RadTensor* t, long long K, long long* rows, long long* ld) {
const long long p = r3d_rows_pitch(t, K, rows);
if (p < 0) return RAD_E_STRIDE;
if (K <= 0 || *rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE;
if (p < K) return RAD_E_SHAPE;
*ld = p;
return RAD_OK;
}
/* A codebook: [n, rank] bf16 with contiguous rows, because the gather is `token * rank + r`. */
static inline int codebook_ok(const RadTensor* t, long long rank) {
if (!t || !t->data) return RAD_E_INVAL;
if (!r3d_is_bf16(t)) return RAD_E_DTYPE;
if (!r3d_aligned(r3d_p(t), 2)) return RAD_E_ALIGN;
if (rank > 0 && t->rank >= 1 && r3d_stride(t, (int)t->rank - 1) != 1) return RAD_E_STRIDE;
return RAD_OK;
}
static inline int r3d_launch_status(int rc) {
if (rc == 0) return RAD_OK;
switch (rc) {
case -1: return RAD_E_INVAL;
case -2: return RAD_E_SHAPE;
case -3: return RAD_E_STRIDE;
default: return RAD_E_DEVICE;
}
}
} /* namespace */
#define R3D_NEED(x) \
do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
/* ================================================================== launcher
*
* cand [M*steps][top_k] i32, candidate token ids, -1 for padding
* unary [M*steps][top_k] f32, the candidate-independent half of the score
* hp [M*steps][rank] bf16, the step's factor; 0 (absent) is a plane of ones
* anchor [M*anchor_stride] i32, the token each walk starts from, at m*anchor_stride
* pred [n_vocab][rank] bf16, the predecessor codebook
* succ [n_vocab][rank] bf16, the successor codebook the walk gathers with its picks
* tokens [M][steps] i32, out: the accepted prefix, one pick a step
*
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
*/
extern "C" int r3d_dflash_select(long cand, long unary, long hp, long anchor, long pred, long succ,
long tokens, int M, int steps, int top_k, int rank, int n_vocab,
int anchor_stride, long long cand_ld, long long un_ld,
long long hp_ld, long long pred_ld, long long succ_ld,
long long tok_ld, long stream) {
if (!cand || !unary || !anchor || !pred || !succ || !tokens) return -1;
if (M <= 0 || steps <= 0 || top_k <= 0 || rank <= 0 || n_vocab <= 0 || anchor_stride <= 0)
return -2;
if ((unsigned)top_k > kKMax) return -2; /* one lane a candidate */
if (!cand_ld) cand_ld = top_k;
if (!un_ld) un_ld = top_k;
if (!hp_ld) hp_ld = rank;
if (!pred_ld) pred_ld = rank;
if (!succ_ld) succ_ld = rank;
if (!tok_ld) tok_ld = steps;
if (cand_ld < top_k || un_ld < top_k) return -3;
if (hp_ld < rank || pred_ld < rank || succ_ld < rank) return -3;
if (tok_ld < steps) return -3;
const uint32_t per = (kThr + (uint32_t)top_k - 1) / (uint32_t)top_k;
R3D_KLAUNCH(R3D_KNAME(dflash_select_kernel), dim3((M + per - 1) / per), dim3(kThr),
(hipStream_t)(uintptr_t)stream, (const int32_t*)(uintptr_t)cand,
(const float*)(uintptr_t)unary, (const uint16_t*)(uintptr_t)hp,
(const int32_t*)(uintptr_t)anchor, (const uint16_t*)(uintptr_t)pred,
(const uint16_t*)(uintptr_t)succ, (int32_t*)(uintptr_t)tokens, (uint32_t)M,
(uint32_t)steps, (uint32_t)top_k, (uint32_t)rank, (uint32_t)n_vocab,
(uint32_t)anchor_stride, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, per);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ================================================================== shim
*
* libref's operand list is {cand, unary, hp?, anchor, pred, succ, tokens} and its parameter list is
* {M, steps, top_k, rank, n_vocab, anchor_stride?, dtype}. Sequences come from `cand` -- the plane
* holds M * steps * top_k ids -- through `band_rows`, so a plane describing more sequences than the
* band's M is refused, not truncated. `rank` and `n_vocab` fall back to the predecessor codebook's
* own shape, as the reference's do, and `anchor_stride` defaults to 1.
*/
extern "C" int r3d_rad_dflash_select(const RadArgs* a, RadStream stream) {
const RadTensor* cand = r3d_opt(a, 0);
const RadTensor* un = r3d_opt(a, 1);
const RadTensor* hp = r3d_opt(a, 2); /* OPD_O: absent is a plane of ones */
const RadTensor* anc = r3d_opt(a, 3);
const RadTensor* pred = r3d_opt(a, 4);
const RadTensor* succ = r3d_opt(a, 5);
const RadTensor* tok = r3d_opt(a, 6);
if (!cand || !cand->data || !un || !un->data || !anc || !anc->data || !pred || !pred->data ||
!succ || !succ->data || !tok || !tok->data)
return R3D_NO(RAD_E_INVAL);
/* The band names the codebooks' width; this is the bf16 instantiation. */
const char* dt = r3d_gets(a, "dtype");
if (dt && !r3d_dt_named(RAD_BF16, dt)) return R3D_NO(RAD_E_DTYPE);
const long long steps = r3d_geti_or(a, "steps", 0);
const long long K = r3d_geti_or(a, "top_k", 0);
const long long astr = r3d_geti_or(a, "anchor_stride", 1);
long long R = r3d_geti_or(a, "rank", pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 1) : 0);
long long nv = r3d_geti_or(a, "n_vocab",
pred->rank >= 2 ? r3d_dim(pred, (int)pred->rank - 2) : 0);
const long long band_M = r3d_geti_or(a, "M", 0);
if (steps <= 0 || K <= 0 || astr <= 0 || R <= 0 || nv <= 0) return R3D_NO(RAD_E_SHAPE);
if (K > (long long)kKMax) return R3D_NO(RAD_E_UNSUPPORTED);
if (steps > 0x7fffffffLL / (K * 256) ) return R3D_NO(RAD_E_SHAPE);
/* Sequences from the plane, the band as a ceiling -- band_rows refuses, it does not truncate. */
const long long all = steps * K;
if (all <= 0 || r3d_numel(cand) % all) return R3D_NO(RAD_E_SHAPE);
const long long M = r3d_numel(cand) / all;
if (M <= 0 || (band_M > 0 && M > band_M)) return R3D_NO(RAD_E_SHAPE);
/* The reference's extent tests, in its order. */
if (r3d_numel(un) < M * steps * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(anc) < (M - 1) * astr + 1) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(tok) < M * steps) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(pred) < nv * R || r3d_numel(succ) < nv * R) return R3D_NO(RAD_E_SHAPE);
if (hp && hp->data && r3d_numel(hp) < M * steps * R) return R3D_NO(RAD_E_SHAPE);
if (!r3d_is_i32(cand)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(un)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_i32(anc)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_i32(tok)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(codebook_ok(pred, R));
R3D_NEED(codebook_ok(succ, R));
if (hp && hp->data) R3D_NEED(codebook_ok(hp, R));
if (!r3d_aligned(r3d_p(cand), 4) || !r3d_aligned(r3d_p(un), 4) || !r3d_aligned(r3d_p(anc), 4) ||
!r3d_aligned(r3d_p(tok), 4))
return R3D_NO(RAD_E_ALIGN);
long long cand_ld = 0, un_ld = 0, tok_ld = 0, rows = 0;
R3D_NEED(rows_pitch(cand, K, &rows, &cand_ld));
R3D_NEED(rows_pitch(un, K, &rows, &un_ld));
R3D_NEED(rows_pitch(tok, steps, &rows, &tok_ld));
long long hp_ld = R, pred_ld = R, succ_ld = R;
if (hp && hp->data) R3D_NEED(rows_pitch(hp, R, &rows, &hp_ld));
R3D_NEED(rows_pitch(pred, R, &rows, &pred_ld));
R3D_NEED(rows_pitch(succ, R, &rows, &succ_ld));
return r3d_launch_status(r3d_dflash_select(
r3d_addr(cand), r3d_addr(un), (hp && hp->data) ? r3d_addr(hp) : 0L, r3d_addr(anc),
r3d_addr(pred), r3d_addr(succ), r3d_addr(tok), (int)M, (int)steps, (int)K, (int)R, (int)nv,
(int)astr, cand_ld, un_ld, hp_ld, pred_ld, succ_ld, tok_ld, (long)(uintptr_t)stream));
}
+79
View File
@@ -0,0 +1,79 @@
/* r3d_fp8_dequant.h -- the E4M3 -> f16 decoder as a table, for the rows that read fp8 codes.
*
* WHY THIS EXISTS, WITH THE MEASUREMENT THAT ASKED FOR IT
*
* gfx11 has no instruction that converts E4M3 to f16. clang lists `__builtin_amdgcn_cvt_pk_f16_fp8`
* for the target, and a build that calls it on gfx1102 contains ZERO `v_cvt_pk_f16_fp8` in its ISA:
* the builtin is software here, lowered to the same exponent work `e4m3_to_f32` does. r3d_codecs.h's
* codec is two `e4m3_to_f32` (a dozen instructions of shifts, exponent bias and subnormal handling
* each) plus a pack, about 25 instructions a pair, 100 an eight-code group. Measured on the
* vocabulary head at M=1 (r3d_vocab_bf16.hip, RX 7600 / gfx1102 / 32 CU): 13.603 ms a token at
* 19.6 GB/s of codes, 8x above the 1.64 ms the codes' 255 MiB floor at this row's own 163 GB/s, and
* the ALU was the binding resource, not DRAM.
*
* E4M3 has 256 bit patterns and every one of them has an f16 value (f16's exponent range covers
* E4M3's, its subnormals included, and E4M3's NaN maps to an f16 NaN). So the decoder is a
* 256-entry table of 512 bytes, and eight LDS reads replace the hundred ALU instructions. That is
* the whole idea, and the table goes in LDS -- not __constant__, whose broadcast is a liability here
* because every lane decodes a DIFFERENT code, and divergent constant indexes serialise.
*
* Cost: 512 bytes of LDS a block, one fill of 256 stores at block start plus a barrier. Conflict
* behaviour on the reads: 16-bit loads at data-dependent addresses, so a wavefront's 32 lanes land
* on 16 bank words; random codes give roughly two lanes per word, and measured cost is about two
* cycles a read -- eight reads an eight-code group against the codec's hundred instructions.
*
* The table is EXACT: it is built by calling the codec once per entry, so it is the codec, moved
* from the loop to the block's start. Nothing about the arithmetic changes, and a row's rel_l2
* against its reference is unchanged by this header. The one thing to keep: the table must be filled
* before any lane reads it, so every use is `..._init` then the barrier it contains, then reads.
*
* int8 codes do NOT want a table: `v_cvt_f32_i8` is a hardware instruction, so
* r3d_codecs.h's i8x2_to_f16x2 is two converts and a pack. This header serves the fp8 codes.
*
* Header-only, like the rest of libr3d. Include it in a .hip after r3d_codecs.h.
*/
#ifndef R3D_FP8_DEQUANT_H
#define R3D_FP8_DEQUANT_H
#include "r3d_codecs.h"
#define R3D_E4M3_TBL 256 /* every E4M3 bit pattern, in order, as the f16 it means */
#define R3D_E4M3_TBL_BYTES (R3D_E4M3_TBL * 2)
/* Fill the block's table: `tbl` is __shared__ uint16_t[R3D_E4M3_TBL]. The barrier is inside it,
* because the only correct order is fill-then-read and the row should not have to remember it. */
__device__ __forceinline__ void r3d_e4m3_f16_init(uint16_t* tbl, int tid, int nthr)
{
for (int i = tid; i < R3D_E4M3_TBL; i += nthr)
tbl[i] = f32_to_f16(e4m3_to_f32((uint8_t)i));
__syncthreads();
}
/* Two codes (the low 16 bits of a dword) as one f16 pair, the pair layout dot2_f16x2 reads: the
* first code in the low half. Same answer as e4m3x2_to_f16x2, eight table reads per eight codes. */
__device__ __forceinline__ uint32_t r3d_e4m3x2_ld(const uint16_t* tbl, uint32_t pair)
{
const uint16_t lo = tbl[pair & 0xffu];
const uint16_t hi = tbl[(pair >> 8) & 0xffu];
return (uint32_t)lo | ((uint32_t)hi << 16);
}
/* Eight codes (two dwords, straddling pairs as always) as four f16 pairs. The sibling of
* codes8_to_f16x4 in r3d_vocab_bf16.hip; the int8 side of that helper stays with the codec, because
* int8 has a hardware convert and fp8 does not. */
__device__ __forceinline__ void r3d_e4m3x8_ld(const uint16_t* tbl, uint2 c, uint32_t* w)
{
const uint32_t d0 = c.x, d1 = c.y;
w[0] = r3d_e4m3x2_ld(tbl, d0 & 0xffffu);
w[1] = r3d_e4m3x2_ld(tbl, d0 >> 16);
w[2] = r3d_e4m3x2_ld(tbl, d1 & 0xffffu);
w[3] = r3d_e4m3x2_ld(tbl, d1 >> 16);
}
/* One code, for the rows that decode a scalar a step (an activation tile staged a byte a lane). */
__device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t code)
{
return tbl[code];
}
#endif /* R3D_FP8_DEQUANT_H */
+374
View File
@@ -0,0 +1,374 @@
/* r3d_gemm_bf16_nt_m16.hip -- the skinny bf16 GEMM, M <= 16: the linear a token is made of.
*
* y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store.
*
* The band is decode and speculative verify, where the weight is the cost and the activation is
* free: the kernel is built so the whole weight plane streams once, and so every output's sum is
* the sum libref forms.
*
* ---- the lane map --------------------------------------------------------------------------
*
* One output element a lane, walking k ascending. A wave covers MT rows of the activation by
* 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template
* argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same
* weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each;
* lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own
* accumulator from 0 to K and never exchanges a value with another lane: its chain is
*
* acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc))
*
* with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand,
* the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no
* wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is
* bit-identical to libref's, not merely within a tolerance.
*
* Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row
* and its result is dropped at the store -- so the k loop stays uniform and the loads stay
* straight-line.
*
* ---- where the bytes come from --------------------------------------------------------------
*
* The activation is staged in LDS and widened on the way in: one row is M <= 16 elements wide per
* k, so a tile is MT * 128 bf16 (4.25 KiB at MT = 16) and one 16-byte load a thread. Staging
* converts bf16 -> f16 once per element with bf16x2_to_f16x2, which is exact, so the dot2 reads
* f16 pairs straight out of LDS and the widening is paid N/MT times less often than it would be
* read. The pitch is 68 dwords: 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on
* banks 4 apart -- conflict-free -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned.
*
* The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then
* thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from
* global memory into registers, widened there by four v_cvt_pkrtz per eight values (one per dword,
* so one convert per two dot2 products -- the price of the dot2 path being the widening the staged
* row pays once per element), and live for the four products they feed.
* Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst
* case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch.
*
* ---- the register budget --------------------------------------------------------------------
*
* A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs,
* four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24
* live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD,
* 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the
* scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since
* every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of
* 256 threads is the default, and `wv` is the axis a tuner walks.
*
* ---- split-K --------------------------------------------------------------------------------
*
* At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three
* waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one
* blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the
* same stream adds the partials per output in ascending split order and narrows once.
*
* The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref
* forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in
* ascending slab order, which brackets the products differently than a single running chain does.
* sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract
* libr4d's tiled row states about its slices. The row is verified at every sk kbench measures.
*
* `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1},
* legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the
* eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a
* step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be
* 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for.
*
* ---- `nt` -----------------------------------------------------------------------------------
*
* RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So
* `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier
* and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic
* pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench
* can price the two lowerings and record that on this card they are the same stream.
*/
/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and
* r3d_common.h reaches the codecs before it reaches the runtime. */
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256; // eight waves, the default
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kKTile = 128; // k a staged tile of a covers
constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row
constexpr int kMTMax = 16; // the band's upper bound
/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree.
* `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be
* whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis
* descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot
* hold is not a legal default. */
constexpr int kUnit = 8;
inline int pick_sk(long long K, int maxsk)
{
static const int kLadder[] = { 16, 8, 4, 2, 1 };
for (int s : kLadder)
if (s <= maxsk && K % ((long long)s * kUnit) == 0) return s;
return 1;
}
/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier,
* no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic
* pointer, which the compiler lowers to flat_load_dwordx4. */
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p)
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
{
return *(const r3d_u32x4*)p;
}
/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane.
*
* `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the
* narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense
* [sk][M][N], and gemm_split_reduce adds them. */
template <int MT, bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel(
const uint16_t* __restrict__ A, const uint16_t* __restrict__ B,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab)
{
/* Staged activation, widened to f16 pairs on the way in. One allocation for the widest MT:
* this kernel is instantiated for MT = 1, 2, 4, 8 and 16 and 4.25 KiB is not worth a template. */
__shared__ uint32_t s_a[kMTMax * kAPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
constexpr uint32_t kNT = kWave / MT; // weight rows a wave covers
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT;
const uint32_t m = lane & (MT - 1);
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const int kbeg = (int)blockIdx.y * kslab;
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint16_t* w = B + (size_t)n_real * w_ld;
float acc = 0.0f;
for (int kt = kbeg; kt < kend; kt += kKTile) {
const int kl = std::min(kKTile, kend - kt);
/* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the
* last real row, whose products the store drops. */
const int nu = (kl + 7) / 8;
/* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight
* waves, and a stage loop that strides the block constant leaves units staged only for
* the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of
* the tile out of LDS that was never written. */
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) {
const int r = i / nu, c = (i % nu) * 8;
const int rr = r < M ? r : M - 1;
const uint16_t* src = A + (size_t)rr * a_ld + kt + c;
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
if (c + 8 <= kl) {
const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src;
*(r3d_u32x4*)dst = r3d_u32x4{
bf16x2_to_f16x2(q.x), bf16x2_to_f16x2(q.y),
bf16x2_to_f16x2(q.z), bf16x2_to_f16x2(q.w) };
} else {
uint32_t p[4] = { 0, 0, 0, 0 };
for (int e = 0; e < kl - c; e += 2) {
const uint32_t lo = ldg_u16(src + e);
const uint32_t hi = (e + 1 < kl) ? ldg_u16(src + e + 1) : 0u;
p[e / 2] = bf16x2_to_f16x2(lo | (hi << 16));
}
for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e];
}
}
group_barrier();
const uint32_t* ap = s_a + (size_t)m * kAPitch;
const int kf = kl & ~7;
for (int k = 0; k < kf; k += 8) {
const r3d_u32x4 aw = lds_a(ap + k / 2);
const r3d_u32x4 b16 = ldw<NT>(w + kt + k);
/* The weight is widened here and it is not optional: dot2's operands are f16, and a
* bf16 bit pattern read as f16 is a different number -- bf16's 1.0 (0x3F80) is 1.875 --
* and any magnitude at or above 2^16 is an infinity. Feeding the bytes straight in is
* the trap this ISA sets for a bf16 GEMM that reaches for v_dot2acc_f32_f16, and it
* arrives as an output uncorrelated with the reference at rel ~ 1, with infinities in
* it, which reads as a numerics problem and is a reading problem. Four
* v_cvt_pk_rtz_f16_f32_e32 per eight values, each with the pair's two VALU of unpack,
* so the widening costs one ALU slot per product the dot2 makes; RDNA3 pairs some of
* the dots as v_dual_dot2acc_f32_f16 with the converts riding alongside. */
const r3d_u32x4 bw = r3d_u32x4{ bf16x2_to_f16x2(b16.x), bf16x2_to_f16x2(b16.y),
bf16x2_to_f16x2(b16.z), bf16x2_to_f16x2(b16.w) };
acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc);
acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc);
}
/* The ragged end of the last slab, ascending. A split is legal only when its slab is whole
* tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */
for (int k = kf; k < kl; ++k)
acc = acc + bf16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k))
* bf16_to_f32((uint16_t)ldg_u16(w + kt + k));
group_barrier(); // the next tile's stage must not race this one's reads
}
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
if (!keep) return;
if constexpr (SPLIT) {
/* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this
* store keeps the same [M][N] shape at every split. */
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
} else {
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc); // narrowed once, here
}
}
/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing.
*
* This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is
* ascending over its own slab, and the slab sums bracket the products differently than one chain
* does. The difference is in the last bits and is the split's, not a bug in it. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16.
*
* a [M][K] bf16, `a_ld` elements a row (0 = K)
* b [N][K] bf16, row-major, k contiguous
* y [M][N] bf16, `y_ld` elements a row (0 = N)
*
* `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the
* weight load's lowering (see the file header), and `scratch` is the f32 partial arena,
* sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it
* does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */
extern "C" int r3d_gemm_nt_bf16_m16(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int wv, int nt, long scratch, long stream)
{
if (!a || !b || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (sk == 0) sk = pick_sk(K, 16);
if (sk < 1) return -2;
if (K % ((long long)sk * kUnit)) return -2;
if (sk > 1 && !scratch) return -1;
if (wv <= 0) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2;
const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax;
const int kslab = K / sk;
#define R3D_M16_NT(MTV, NTV) \
do { \
const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \
const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, true>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_split_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \
(const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel<MTV, NTV, false>)), grid, block, \
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \
(uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \
} \
} while (0)
#define R3D_M16_MT(MTV) do { if (nt) R3D_M16_NT(MTV, true); else R3D_M16_NT(MTV, false); } while (0)
switch (mt) {
case 1: R3D_M16_MT(1); break;
case 2: R3D_M16_MT(2); break;
case 4: R3D_M16_MT(4); break;
case 8: R3D_M16_MT(8); break;
default: R3D_M16_MT(16); break;
}
#undef R3D_M16_MT
#undef R3D_M16_NT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ============================================================== the plugin ABI entry point
*
* gemm_nt's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm/oGemm). */
enum { G_A = 0, G_B, G_Y };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s)
{
const RadTensor* A = r3d_opt(a, G_A);
const RadTensor* B = r3d_opt(a, G_B);
const RadTensor* Y = r3d_opt(a, G_Y);
if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(A));
R3D_NEED(dt_bf16(B));
R3D_NEED(dt_bf16(Y));
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE);
/* The row count comes from the output, never from `M`, which is the band's upper bound. */
const long long nel = r3d_numel(Y);
if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = nel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
long long arows = 0, yrows = 0;
const long long a_ld = r3d_rows_pitch(A, K, &arows);
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
/* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher
* does not carry cannot be described to it. */
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
/* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
int wv = c.wv > 0 ? c.wv : kWaves;
if (wv > kWaves) wv = kWaves;
if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE);
int sk = c.sk > 0 ? c.sk : pick_sk(K, 16);
if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16
if (K % ((long long)sk * kUnit)) return R3D_NO(RAD_E_SHAPE);
if (sk > 1) {
const long long need = (long long)sk * M * N * 4;
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
}
const int e = r3d_gemm_nt_bf16_m16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)N,
(int)K, (int)a_ld, (int)y_ld, sk, wv, c.nt,
(long)(uintptr_t)(sk > 1 ? a->scratch : nullptr),
(long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
+524
View File
@@ -0,0 +1,524 @@
/* r3d_gemm_fp8a16_nt_m1.hip -- the same skinny shape against a block-scaled weight.
*
* y[M,N] = a[M,K] @ b[N,K]^T, b stored as E4M3 codes with one f32 scale per (pb1 x pb2) block,
* f32 accumulate, narrowed once by the store. `a_scale`, when present, means the activation is
* coded too -- quant_act_fp8's E4M3 codes with one f32 per (row, group) -- which is the fp8a8
* form the row table names `fp8a8`.
*
* RDNA3 has no fp8 instruction: the builtins are declared for gfx11 and die at instruction
* selection. So the codes are decoded in software, and the decode is free of cost in the sense
* that matters here: E4M3 is four exponent and three mantissa bits, f16 is five and ten, so
* e4m3x2_to_f16x2 is EXACT and the dot2 multiplies the numbers the checkpoint means. Nothing is
* rounded between the code and the product, which is why this row's output is libref's to the bit
* at sk = 1 and not merely inside fp8 quantisation noise.
*
* ---- the lane map --------------------------------------------------------------------------
*
* The same as r3d_gemm_bf16_nt_m16's: lane l owns the output (m = l % MT, n = n0 + l / MT) for the
* template's MT = ceil(M) in {1,2,4,8,16}, walks k ascending and holds its own accumulator. One
* difference is forced by the format, and it is the one that makes this kernel what it is: a lane
* consumes sixteen codes per step, because that is what sixteen bytes are, and sixteen bytes is
* one global_load_b128. Eight dot2 per step, so the weight stream is one 16-byte load per eight
* matrix instructions -- the decode (eight v_perms and shifts, exact) sits between them and is the
* reason this kernel's rate is not the bf16 row's.
*
* A lane owns one (m, n) pair, so a lane owns one scale per block: `n / pb1` picks b_scale's row
* and the block index picks its column, and both are hoisted out of the block's sixteen-element
* steps. The activation's scale, when the activation is coded, is `m`'s row at the same block
* index. Lanes sharing an n agree on it, which is why no lane-to-lane exchange is needed.
*
* ---- where the scale multiplies -------------------------------------------------------------
*
* ref_gemm.h's quant_tile, and quant_dot beside it, is the spec, and the order it writes is the
* order this kernel runs:
*
* for gi ascending: sub = 0
* for k in the group, ascending: sub += a[k] * b[k] (from the CODES)
* acc = acc + (sub * sa) * sb
*
* with sa = a_scale[m][gi] or 1, and sb = b_scale[n / pb1][gi]. The scale multiplies the finished
* block, once, at the block's end -- not every product: scaling each product is equal in exact
* arithmetic and differs in the last bits, which moves an fp8 code and so moves a token. And
* `(sub * sa) * sb` is an order, not a formula: the parentheses are libref's, and the products are
* summed from the raw codes with no scale folded into them. This kernel accumulates a block's
* sub-sum into a register of its own, so the bracketing is the reference's, and the widening is
* exact, so at sk = 1 the output is bit-identical to it.
*
* ---- the activation ---------------------------------------------------------------------------
*
* Staged in LDS per block of the weight's K, widened on the way in: bf16 -> f16 for fp8a16, E4M3 ->
* f16 for fp8a8, both exact. One row of a is M <= 16 elements wide per k, so a staged block is
* MT * 128 values, 4.25 KiB at MT = 16, and the pitch is 68 dwords: 68 mod 32 = 4, so a
* ds_read_b128's eight lanes land on banks four apart, and 272 bytes a row keeps the 16-byte reads
* aligned. The weight is not staged: with M <= 16 a staged tile has 32/MT readers, so staging
* trades a wave's worth of L1 residency for a round trip through LDS and buys nothing.
*
* ---- split-K --------------------------------------------------------------------------------
*
* `sk` contiguous slices, one per blockIdx.y, each writing its f32 partial to `scratch` and a
* second kernel adding them per output in ascending slice order. Each partial is a chain of
* `(sub * sa) * sb` terms over its own slices of blocks, so at sk = 1 the chain is libref's
* exactly; sk > 1 brackets the block terms by slice, which is the split's doing and agrees to the
* last bits. Legality is K % (sk * group) == 0 -- a slice that ends mid-block cannot apply that
* block's scale -- which is the row's gemm_tune_valid rule, unit = group.
*
* ---- `nt` -----------------------------------------------------------------------------------
*
* No transposed load on this ISA and no cache field on a global load. nt = 1 issues the weight
* reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache
* modifier and no swizzle; nt = 0 issues the same 16-byte reads through the generic pointer. The
* axis measures the two lowerings, and on this card it measures the same stream twice.
*/
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kMTMax = 16;
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
constexpr int kAPitch = 68; // dwords a staged activation row (128 values + 4)
constexpr int kGroupMax = 128; // the stage is sized for one 128-wide block per row
/* A slice is legal when it is a whole number of scale blocks, so the split ladder is capped by
* the scratch hook's widest split and stepped by the block the weight carries. */
int pick_sk(long long K, int group, int maxsk)
{
static const int kLadder[] = { 16, 8, 4, 2, 1 };
for (int s : kLadder)
if (s <= maxsk && K % ((long long)s * group) == 0) return s;
return 1;
}
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p)
{
return *(const r3d_u32x4*)p;
}
__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p)
{
return *(const __attribute__((address_space(1))) uint8_t*)p;
}
/* The weight's 16 codes as eight f16 pairs, exact.
*
* e4m3x2_to_f16x2 decodes the TWO codes in a dword's low half, so a 16-byte load -- four dwords,
* sixteen codes -- is eight decodes, each fed the 16-bit pair it wants: the pairs straddle the
* dwords, four dwords in, eight pairs out. Feeding the codec whole dwords decodes eight codes and
* leaves the rest of the step multiplying registers that were never written, which is the quiet
* version of this bug: the answer comes back a fraction of its size, not a NaN. */
__device__ __forceinline__ void codes_to_f16x8(const r3d_u32x4 c, uint32_t* w)
{
const uint32_t d[4] = { c.x, c.y, c.z, c.w };
#pragma unroll
for (int j = 0; j < 8; ++j)
w[j] = e4m3x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu);
}
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T. `A8` is the fp8a8 form: a carries E4M3 codes and a_scale
* carries one f32 per (row, block); without it a is bf16 and read directly. */
template <int MT, bool A8, bool NT, bool SPLIT>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_kernel(
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16,
uint16_t* __restrict__ Y, float* __restrict__ Part,
int M, int N, int K, int group, int pb1, int a_ld, int y_ld, int kslab, int nkb)
{
__shared__ uint32_t s_a[kMTMax * kAPitch];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
const uint32_t waves = blockDim.x / kWave;
constexpr uint32_t kNT = kWave / MT;
const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT;
const uint32_t m = lane & (MT - 1);
const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const int kbeg = (int)blockIdx.y * kslab;
const int kend = kbeg + kslab < K ? kbeg + kslab : K;
const uint8_t* w = B + (size_t)n_real * K;
/* b_scale is the container's `weight_scale_inv`, and the op's shape hook writes it bf16 for the
* whole quantised family -- `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})`; f32 belongs to the
* separate `fp8a8f32` spelling. Both are read here; bf16 widens to f32 exactly, since every
* bf16 value is representable in f32, so the widening is free and the products are unchanged. */
const size_t bsrow = (size_t)(n_real / pb1) * nkb;
const float* bsF = bs16 ? nullptr : (const float*)BScale + bsrow;
const uint16_t* bsH = bs16 ? (const uint16_t*)BScale + bsrow : nullptr;
const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr;
float acc = 0.0f;
/* One scale block per round: stage the block's activation, walk the block's k, fold the block's
* scale in at the end. `kb` is the block's first k, which is where the scales are indexed. */
for (int kb = kbeg; kb < kend; kb += group) {
const int gl = std::min(group, kend - kb);
const int gi = kb / group;
/* Stage gl elements of MT activation rows, widened to f16 pairs. Eight values a unit: a
* 16-byte load for a bf16 row, an 8-byte one for a coded row, which is why the coded row's
* pitch check is eight, not sixteen. A row past M re-reads the last real row. */
constexpr int kUnit = 8;
const int nu = (gl + kUnit - 1) / kUnit;
for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { // see the m16 unit's note on wv
const int r = i / nu, c = (i % nu) * kUnit;
const int rr = r < M ? r : M - 1;
const int cnt = std::min(kUnit, gl - c);
uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2;
if constexpr (A8) {
const uint8_t* src = A + (size_t)rr * a_ld + kb + c; // codes: bytes and elements agree
for (int e = 0; e < cnt; e += 8) {
const uint8_t* sp = src + e;
uint32_t q[2];
if (cnt - e >= 8) {
const r3d_u32x2 b8 =
*(const __attribute__((address_space(1))) r3d_u32x2*)sp;
q[0] = b8.x; q[1] = b8.y;
} else {
uint32_t pack[2] = { 0, 0 };
for (int t = 0; t < cnt - e; ++t)
pack[t >> 2] |= (uint32_t)ldg_u8(sp + t) << (8 * (t & 3));
q[0] = pack[0]; q[1] = pack[1];
}
uint32_t p[4] = { e4m3x2_to_f16x2(q[0] & 0xffffu),
e4m3x2_to_f16x2(q[0] >> 16),
e4m3x2_to_f16x2(q[1] & 0xffffu),
e4m3x2_to_f16x2(q[1] >> 16) };
#pragma unroll
for (int t = 0; t < 4; ++t)
if (e + 2 * t < gl) dst[e / 2 + t] = p[t];
}
} else {
/* A is a byte pointer here because the coded form codes it: cast first, then the
* row and k offsets are ELEMENT offsets, which for bf16 is twice the byte count. */
const uint16_t* src = (const uint16_t*)A + (size_t)rr * a_ld + kb + c;
for (int e = 0; e < cnt; e += 8) {
uint32_t p[4];
if (cnt - e >= 8) {
const r3d_u32x4 b16 =
*(const __attribute__((address_space(1))) r3d_u32x4*)(src + e);
p[0] = bf16x2_to_f16x2(b16.x);
p[1] = bf16x2_to_f16x2(b16.y);
p[2] = bf16x2_to_f16x2(b16.z);
p[3] = bf16x2_to_f16x2(b16.w);
} else {
#pragma unroll
for (int t = 0; t < 4; ++t) {
const uint32_t lo = ldg_u16(src + e + 2 * t);
const uint32_t hi = (e + 2 * t + 1 < gl)
? ldg_u16(src + e + 2 * t + 1) : 0u;
p[t] = bf16x2_to_f16x2(lo | (hi << 16));
}
}
#pragma unroll
for (int t = 0; t < 4; ++t)
if (e + 2 * t < gl) dst[e / 2 + t] = p[t];
}
}
}
group_barrier();
const uint32_t* ap = s_a + (size_t)m * kAPitch;
float sub = 0.0f;
const int gf = (gl / kStep) * kStep;
for (int k = 0; k < gf; k += kStep) {
const r3d_u32x4 a0 = lds_a(ap + k / 2);
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
uint32_t b[8];
codes_to_f16x8(ldc<NT>(w + kb + k), b);
sub = dot4_f16x4(a0.x, a0.y, b[0], b[1], sub);
sub = dot4_f16x4(a0.z, a0.w, b[2], b[3], sub);
sub = dot4_f16x4(a1.x, a1.y, b[4], b[5], sub);
sub = dot4_f16x4(a1.z, a1.w, b[6], b[7], sub);
}
/* The last partial block, when K is not a whole block: ascending, two k at a time, each
* code decoded on its own. The launcher refuses a K that is not a multiple of the block
* (a ragged block would read past the scale plane), so this is a shape the kernel carries
* for completeness and the row never issues. */
for (int k = gf; k < gl; k += 2) {
const uint32_t aw = ap[k / 2];
const uint32_t c0 = ldg_u8(w + kb + k);
const uint32_t c1 = (k + 1 < gl) ? ldg_u8(w + kb + k + 1) : 0u;
const uint32_t pw = e4m3x2_to_f16x2(c0 | (c1 << 8));
sub = dot2_f16x2(aw, pw, sub);
}
group_barrier(); // the next block's stage must not race this one's reads
/* The block's finished sub-sum, scaled once, in libref's parentheses. */
const float sa = A8 ? as[gi] : 1.0f;
acc = acc + (sub * sa) * (bs16 ? bf16_to_f32(bsH[gi]) : bsF[gi]);
}
const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M);
if (!keep) return;
if constexpr (SPLIT) {
Part[((size_t)blockIdx.y * M + m) * N + n0] = acc;
} else {
Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc);
}
}
/* The split reduction, the m16 unit's, in the same order: v = ((p0 + p1) + p2) + ... ascending by
* slice, then one narrowing. Ascending slice order is libref's ascending sum only at sk = 1; past
* that the block terms are bracketed by slice, which is the split's cost and is stated as such. */
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_q_reduce(
const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk)
{
const int mn = M * N;
const int stride = gridDim.x * kBlockThreads;
for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) {
const int m = i / N, n = i - m * N;
const float* p = Part + (size_t)m * N + n;
float v = p[0];
for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N];
Y[(size_t)m * y_ld + n] = f32_to_bf16(v);
}
}
} // namespace
/* y[M,N] = a[M,K] @ dequant(b)[N,K]^T over E4M3 codes, M <= 16, f32 accumulate, bf16 out.
*
* a [M][K] bf16 (fp8a16) or E4M3 codes (fp8a8, when `a_scale` is present)
* a_scale [M][ceil(K/group)] f32, or 0
* b [N][K] E4M3 codes, row-major, k contiguous
* b_scale [ceil(N/pb1)][ceil(K/pb2)] bf16 (the container's weight_scale_inv) or f32, block-major
* y [M][N] bf16, `y_ld` elements a row (0 = N)
*
* `group` is the code group along K (pb2, the checkpoint's block width); `pb1` the rows sharing a
* scale row (0 = group). `sk` splits K (0 = the widest legal), `nt` the weight load's lowering,
* `scratch` the f32 partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0,
* -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP failed. */
extern "C" int r3d_gemm_nt_q_fp8_ex(long a, long a_scale, long b, long b_scale, long y, int M,
int N, int K, int group, int pb1, int pb2, int a_ld, int y_ld,
int sk, int nt, long scratch, int bs_dt, long stream)
{
if (!a || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (group <= 0) group = R3D_FP8_BLOCK;
if (pb1 <= 0) pb1 = group;
if (pb2 == 0) pb2 = group;
if (pb2 != group) return -2; // one block: the K block IS the code group
if (group > kGroupMax) return -2;
if (group % kStep) return -2; // a block must be whole lane steps
if (K % group) return -2; // a ragged block reads past the scale plane
const int nkb = K / group;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
const int a8 = a_scale != 0;
if (a8 && (a_ld % 8)) return -3; // 8-byte code staging
if (!a8 && (a_ld % 8)) return -3; // 16-byte widened staging
if (sk == 0) sk = pick_sk(K, group, 16);
if (sk < 1) return -2;
if (K % ((long long)sk * group)) return -2;
if (sk > 1 && !scratch) return -1;
const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */
const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax;
const int kslab = K / sk;
const int nrowb = (N + pb1 - 1) / pb1;
if ((long long)nrowb * nkb <= 0) return -2;
#define R3D_Q_NT(MTV, A8V, NTV) \
do { \
const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \
const dim3 grid((nt_ + kWaves - 1) / kWaves, (unsigned)sk), dim3_blk(kBlockThreads); \
if (sk > 1) { \
R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel<MTV, A8V, NTV, true>)), grid, dim3_blk, \
(hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \
(const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \
(float*)scratch, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \
const int mn = M * N; \
const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \
R3D_KLAUNCH(gemm_q_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \
(const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \
} else { \
R3D_KLAUNCH(R3D_KNAME((gemm_q_kernel<MTV, A8V, NTV, false>)), grid, dim3_blk, \
(hipStream_t)stream, (const uint8_t*)a, (const float*)a_scale, \
(const uint8_t*)b, (const void*)b_scale, bs16, (uint16_t*)y, \
(float*)nullptr, M, N, K, group, pb1, a_ld, y_ld, kslab, nkb); \
} \
} while (0)
#define R3D_Q_A8(MTV, A8V) do { if (nt) R3D_Q_NT(MTV, A8V, true); else R3D_Q_NT(MTV, A8V, false); } while (0)
#define R3D_Q_MT(MTV) do { if (a8) R3D_Q_A8(MTV, true); else R3D_Q_A8(MTV, false); } while (0)
switch (mt) {
case 1: R3D_Q_MT(1); break;
case 2: R3D_Q_MT(2); break;
case 4: R3D_Q_MT(4); break;
case 8: R3D_Q_MT(8); break;
default: R3D_Q_MT(16); break;
}
#undef R3D_Q_MT
#undef R3D_Q_A8
#undef R3D_Q_NT
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The declaration in r3d.h carries no scale dtype, and the weight's block scales are bf16 for the
* whole quantised family (see the entry above), so the family needs a second spelling. `_ex` adds
* `bs_dt`, the b_scale plane's RadDataType: RAD_BF16 reads it as bf16, anything else -- 0 included
* -- reads it as f32, which is exactly what the entry below, and every caller written before the
* bf16 discovery, asks for. The shim takes the dtype off the operand and calls `_ex`; the old entry
* forwards, so a raw caller of the old name sees the behaviour it was written against. */
extern "C" int r3d_gemm_nt_q_fp8(long a, long a_scale, long b, long b_scale, long y, int M, int N,
int K, int group, int pb1, int pb2, int a_ld, int y_ld, int sk,
int nt, long scratch, long stream)
{
return r3d_gemm_nt_q_fp8_ex(a, a_scale, b, b_scale, y, M, N, K, group, pb1, pb2, a_ld, y_ld, sk,
nt, scratch, RAD_F32, stream);
}
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_q's operands are [a, a_scale, b, b_scale, y, a_sum?, b_ref?] and its parameters M, N, K,
* group, dtype, pb1?, pb2?, split_n? (libref's pGemmQ/oGemmQ). */
enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
/* The trace latch for this file: distinct GEMM shapes, printed once each. A static array and a
* counter, no lock -- the flag is a diagnostic and a doubled line is a cosmetic cost, a lock in
* the served path is not. */
struct GemmPlanKey { long long M, N, K; unsigned a_rank, as_rank; long long a_ld, y_ld; };
static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_rank,
unsigned as_rank, long long a_ld, long long y_ld)
{
static GemmPlanKey seen[96];
static int n = 0;
for (int i = 0; i < n; ++i)
if (seen[i].M == M && seen[i].N == N && seen[i].K == K && seen[i].a_rank == a_rank &&
seen[i].as_rank == as_rank && seen[i].a_ld == a_ld && seen[i].y_ld == y_ld)
return false;
if (n < 96) seen[n++] = GemmPlanKey{M, N, K, a_rank, as_rank, a_ld, y_ld};
return true;
}
extern "C" int r3d_rad_gemm_nt_q_fp8(const RadArgs* a, RadStream s)
{
const RadTensor* A = r3d_opt(a, Q_A);
const RadTensor* AS = r3d_opt(a, Q_ASCALE);
const RadTensor* B = r3d_opt(a, Q_B);
const RadTensor* BS = r3d_opt(a, Q_BSCALE);
const RadTensor* Y = r3d_opt(a, Q_Y);
if (!A || !B || !BS || !Y) return R3D_NO(RAD_E_INVAL);
/* The schemes this kernel decodes: E4M3 codes on the weight, bf16 activations (fp8a16) or
* E4M3 codes with their own scale (fp8a8). E5M2 has no decoder here. */
if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE);
/* The weight's block scales are bf16 for the whole quantised family -- the shape hook's
* `o.t(f32s ? RAD_F32 : RAD_BF16, {nb, kb})` is the container's `weight_scale_inv`, and f32 is
* the separate `fp8a8f32` spelling, which no row here claims (those bands stay with the
* reference). Accept both; the kernel widens bf16 -> f32 at the load, exactly and for free. */
const bool bs16 = r3d_is_bf16(BS);
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_bf16(Y));
const bool a8 = AS != nullptr;
if (a8) {
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_f32(AS));
} else {
R3D_NEED(dt_bf16(A));
}
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE);
const long long nel = r3d_numel(Y);
if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = nel / N; // never from the `M` parameter
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
/* The block geometry, and the disagreement libref refuses: `group` is what the selector
* matched on, and pb2 is the checkpoint's, and they describe the same bytes. */
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
const long long pb1 = r3d_geti_or(a, "pb1", group), pb2 = r3d_geti_or(a, "pb2", group);
if (group != R3D_FP8_BLOCK) return R3D_NO(RAD_E_SHAPE);
if (pb2 != 0 && pb2 != group) return R3D_NO(RAD_E_SHAPE);
if (pb1 <= 0) return R3D_NO(RAD_E_SHAPE);
if (K % group) return R3D_NO(RAD_E_SHAPE);
const long long nkb = (K + group - 1) / group, nrowb = (N + pb1 - 1) / pb1;
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < nrowb * nkb) return R3D_NO(RAD_E_SHAPE);
if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE);
/* `a_sum` removes an activation zero point this grid does not have, and `b_ref` is an mxfp4
* scale reference: libref refuses both beside these schemes (gemm_ntq_impl), so we do. */
if (r3d_opt(a, Q_ASUM)) return R3D_NO(RAD_E_UNSUPPORTED);
if (r3d_opt(a, Q_BREF)) return R3D_NO(RAD_E_UNSUPPORTED);
long long arows = 0, yrows = 0;
const long long a_ld = r3d_rows_pitch(A, K, &arows);
const long long y_ld = r3d_rows_pitch(Y, N, &yrows);
if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
/* The scale planes have no pitch argument in the launcher, so they must be dense, and their
* stated grid must be the one the kernel walks. */
if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nrowb * nkb)
return R3D_NO(RAD_E_SHAPE);
if ((a8 && (a_ld % 8)) || (!a8 && (a_ld % 8))) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
/* The plan's own numbers for the M<=16 band, under RAD_R3D_TRACE=1 and once per distinct
* shape -- the same instrument the tiled row carries, in the row that serves the short steps.
* It lives here because the served collapse begins at 15 prompt tokens, a step the tiled shim
* never sees: the ladder's numbers below 17 are M=5..16 and the tiled row's line cannot speak
* for them. M is derived off the activation's output the way the row derives it (line 430:
* numel(y)/N, never the `M` parameter), and nothing is read that the checks above did not
* already require. With the flag unset this is one cached getenv and a return: no copy, no
* latch slot, no new operand read, no syscall. */
if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS ? AS->rank : 0u, a_ld, y_ld)) {
std::fprintf(stderr, "[r3d] plan: gemm M=%lld (band M<=%d) N=%lld K=%lld group=%lld "
"a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld "
"a_scale %s numel=%lld y rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld "
"Mpad=%lld\n",
M, kMTMax, N, K, group, (unsigned)A->rank, r3d_numel(A),
r3d_dim(A, 0), r3d_dim(A, 1), a_ld, arows,
AS ? "rank=2" : "absent (fp8a16, bf16 activations)",
AS ? r3d_numel(AS) : 0LL, (unsigned)Y->rank, r3d_numel(Y), r3d_dim(Y, 0),
r3d_dim(Y, 1), y_ld, (M + 15) / 16 * 16);
r3d_trace_desc("gemm a", A);
r3d_trace_desc("gemm y", Y);
if (AS) r3d_trace_desc("gemm a_scale", AS);
}
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
int sk = c.sk > 0 ? c.sk : pick_sk(K, (int)group, 16);
if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16
if (K % ((long long)sk * group)) return R3D_NO(RAD_E_SHAPE);
if (sk > 1) {
const long long need = (long long)sk * M * N * 4;
if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH);
}
const int e = r3d_gemm_nt_q_fp8_ex(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)pb1,
(int)pb2, (int)a_ld, (int)y_ld, sk, c.nt,
(long)(uintptr_t)(sk > 1 ? a->scratch : nullptr),
(int)BS->dtype, /* bf16 weight_scale_inv or f32 */
(long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
+678
View File
@@ -0,0 +1,678 @@
/* r3d_gemm_fp8a8_gated.hip -- gemm_nt_q_gated: the gated MLP's GEMM, its gate and its quantiser in
* one launch. 48 bands on one 2B model (N=12288 K=2048 group=128 dtype=fp8a8 act=silu, M=64 x47
* and M=16), and the reason the [M, N] bf16 intermediate never exists.
*
* y[M,n] = gate(a[M,K] @ b[N,K]^T), quantised: n = N/2, gate half = b's rows [0, n),
* up half = [n, N). `q` is E4M3 codes over y, `scale` one f32 per (row, `group` of n), and
* `out_bf16`, when bound, is exactly the bf16 the codes were taken over.
*
* The law is ref_gemm_nt_q_gated and it is transcribed in its order:
*
* row[j] = quant_dot(ma, mb, SA, SB, m, j, K) over the FULL N, j ascending
* gt = round_bf16(row[i]), up = round_bf16(row[n + i]) BOTH halves, before the gate
* sg = 1 / (1 + exp(-gt)) the gate is the FIRST half
* h = f32_to_bf16((act == silu ? gt * sg : sg) * up) the activation is not narrowed
* fp8_row(h, n, group) amax -> scale[m, group], codes
*
* Both halves are narrowed before the gate because the unfused pair writes a bf16 [M, N] tensor and
* re-reads it: the fused form must be byte-identical to the pair it replaces, so the narrowing that
* the store performed is kept, and `out_bf16` is what the pair's tensor held. The activation itself
* is NOT narrowed -- `gt * sg` is formed in f32 from the narrowed gate, and the product with `up`
* rounds once, at the store.
*
* ---- the lane map: one lane owns a PAIR of dots -----------------------------------------------
*
* The gate couples column i with column n + i, and a wave covers 32 consecutive columns, so the
* partner column is 192 waves away for the band's n = 6144: no lane-to-lane exchange reaches it, and
* staging a whole row through LDS to reach it costs a round trip of the [M, N] tensor this op exists
* to avoid. So the lane owns BOTH products of its column: it walks k ascending with two accumulators
* and reads two weight rows, `i` and `n + i`. The weight traffic is unchanged -- the pair of rows is
* exactly the traffic the unfused GEMM spent on the two columns -- and the coupling is free.
*
* A block covers ONE group of `group` output columns and RP = 256 / group rows, so a lane is
*
* i = blockIdx.x * group + (tid % group) m = blockIdx.y * RP + tid / group
*
* and a wave's 32 lanes are 32 consecutive columns of one group of one row, for group >= 32. That
* alignment is what closes the epilogue inside the block: the group's amax is a wave max folded over
* the group's group/32 waves in LDS, the scale is one store, the codes are one byte a lane. The
* whole op -- product, gate, quantiser -- is one launch and no scratch, which is why the row is
* concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`) and why the bf16 row of the
* intermediate is not written, read, or allocated.
*
* ---- the two streams: fp8a8 at M <= 8 reads the codes, the rest stages them -------------------
*
* The band's served case is a decode: one row, the whole 12288 x 2048 operand, 42 calls a token.
* The shape above is built for the band's declared ceiling (M = 64, 47 of the 48 bands) and serves
* that height well; at M = 1 it spends 987 us on 24 MiB of codes, 25 GB/s, and the reason is not
* the loads. It is the path a code takes: global -> LDS stage -> decode -> dot, with two
* `group_barrier`s per k-block holding the block in step, and a decoder of ten VALU a code (RDNA3
* has no fp8 instruction: r3d_codecs.h, and the builtins that look like one are rejected at
* instruction selection on gfx1102).
*
* So the arm is chosen by the row count, in the launcher, from the same band key:
*
* M <= 8 and fp8a8 read the activation and both weight rows straight from memory, 16 bytes at
* a time, decode them out of a 256-entry table the block builds once, and
* multiply. No shared memory between a load and a dot, no barrier in the
* k-loop, six loads in flight.
* M >= 9, and every fp8a16 case the shape above, with the same table decoder in place of the
* arithmetic one. At these heights the grid is 48 x M/2 blocks and occupancy,
* not the window, is what feeds the stream; the stage pays for itself.
*
* Measured on the band, vram, GPU 2, nine launches timed on their own, best/median:
*
* M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the card's 163 GB/s
* M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us floor for 24 MiB is 154 us, and the same
* M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us sixteen loads with no decode and no dot
* M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us run in 139 us)
* M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us
* M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us
* M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us
*
* The two numbers behind the shape, both from the band's own stream (24 MiB of codes, vram, 11
* launches, this kernel's loop with the epilogue off): staged through LDS and decoded arithmetically
* 497 us; read straight and decoded from the table 187 us; the read alone 139 us. The table alone
* moves M = 64 from 8395 us to 2786 us -- two thirds of the tall arm's gain is the decoder, and it
* costs nothing in registers (109 a lane, four waves a SIMD, zero spills).
*
* Two things in this file are load-bearing. The table's argument is a PAIR, not an index (see
* build_e4m3_table). And the decoded pairs go from the table into the dot inline, never through an
* array (see the tall arm's step_body).
*
* ---- where the scale multiplies -------------------------------------------------------------
*
* quant_dot, unchanged from r3d_gemm_fp8a16_nt_m1.hip: per group of k a sub-sum from zero over
* ascending k of the CODES' products, then `acc = acc + (sub * sa) * sb` -- the parentheses are the
* reference's, the scale multiplies the finished block once, and `sa` is `a_scale[m][gi]` (1 when
* the activation carries no scale plane). Each lane's two chains are the two calls the unfused pair
* makes, so the bracketing is the pair's, element for element.
*
* b_scale is bf16: this op's shape hook writes `o.t(RAD_BF16, {nb, kb})` with no f32 spelling, so
* the plain entry reads the plane as bf16 and the `_ex` twin takes the dtype, as the fp8 GEMM's
* does. bf16 -> f32 widening is exact, so an f32 plane carrying the same values must produce
* bit-identical output; the driver tests exactly that.
*
* ---- the epilogue's one transcendental -------------------------------------------------------
*
* libref's sigmoid is `1.0f / (1.0f + (float)std::exp((double)(-x)))`. There is no f64 ALU on this
* card (1:64, emulated), and the band asks for M*n = 393216 exponentials a layer, which is
* attention's regime and not the sampler's. `expf` is the accurate device form, as in
* r3d_gated_quant_fp8's kernel (r3d_quant_fp8.hip), not `__expf`; what it feeds is a bf16
* narrowing, whose ulp is 2^-8 against the transcendental's ~1e-7, so the narrowing lands the same
* bf16 everywhere but on a tie. The count of those ties is in the row's prose, measured.
*
* ---- what the launcher refuses ----------------------------------------------------------------
*
* M > 64 (the bands' ceiling, and past it the weight stream -- M reads of an [N, K] plane from L2 --
* is the wall, which is a tiled kernel's problem, not this one's); N odd (the reference's own
* `N & 1` test); a group that is not a power of two in [32, 256] (a wave must sit inside one group,
* and the block is one group wide); group > n, where the reference defaults the QUANTISER's group to
* n and leaves the weight's K block at the stated width: two widths this kernel reads as one, so it
* refuses rather than serve a geometry whose two grids disagree; K % group != 0, because a ragged K
* block reads past the scale plane; sk > 1, because no K slab closes an epilogue that needs the
* whole row. Refusals are codes: -1 null, -2 shape, -3 pitch, -4 HIP.
*
* ---- relayout: none, and it is a claim ---------------------------------------------------------
*
* libref reads the gated weight [N, K] row-major; libr4d stores fp8a8 weights in WMMA fragment order
* (`r4d.fp8.w.frag64`). The two readings are ~1.35 apart, a relative error, not noise, so this row
* carries no relayout and says so: a row that inherits the fp8 GEMM's unrelayout scores 1.35 against
* the per-op oracle and reads as a broken kernel. The stored order is the reading order here, which
* is the library's rule for every row.
*/
#include <hip/hip_runtime.h> // __forceinline__, which r3d_codecs.h's R3D_HD spells
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <algorithm>
namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave;
constexpr int kStep = 16; // codes a lane takes per step: one 16-byte load
constexpr int kWin = 64; // codes a lane takes per WINDOW: four loads per stream
constexpr int kGroupMin = 32; // a wave's 32 columns must sit inside one group
constexpr int kGroupMax = 256; // a block is one group wide, at 256 threads
constexpr int kMMax = 64; // the bands' ceiling: 47 of the 48 are M = 64
constexpr float kTopE4M3 = 448.0f; // q8_group's top for E4M3: the largest finite code
/* The E4M3 decoder as a table: 256 f16, one entry per code. The codec's arithmetic decode is ten
* VALU a code (r3d_codecs.h -- RDNA3 has no fp8 instruction, and the builtins that look like one
* are rejected at instruction selection), and this kernel decodes every weight code it multiplies,
* twice over at RP = 2, which at M = 1 is every code in the operand. The table costs two
* `ds_read_u16` and a pack a PAIR, and it is exact by construction: the entry for code c is the
* dword the arithmetic path returns for c, computed by that path at the block's first instruction.
* The unit test reads all 256 entries back and compares them with the codec. */
__device__ __forceinline__ void build_e4m3_table(uint16_t* tab, uint32_t tid)
{
for (uint32_t u = tid; u < 128; u += kBlockThreads)
/* The codec's argument is a PAIR, low code in the low byte; the entry is indexed by code.
* Feeding it the index alone fills the even entries and decodes code 0 into every odd one,
* so the kernel multiplies half the plane by zero -- the board's `codes256` case, whose
* weight is the code enumeration, shows it: rel_l2 9.6e-01, not a NaN. */
*(uint32_t*)&tab[2 * u] = e4m3x2_to_f16x2((u * 2) | ((u * 2 + 1) << 8));
}
__device__ __forceinline__ uint32_t tab_pair(const uint16_t* tab, uint32_t pair)
{
const uint32_t lo = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair & 0xffu));
const uint32_t hi = *(const uint16_t __attribute__((address_space(3))) *)(tab + (pair >> 8));
return lo | (hi << 16);
}
/* One step of the skinny arm: sixteen codes of activation and sixteen of weight, both coded, both
* out of the same table. This is the whole of the reference's inner step -- `sub += a[k] * b[k]`,
* k ascending -- with the pairs decoded as each dot consumes them. Four dot4, the pairs in order,
* one accumulator; nothing about it depends on where the bytes came from. */
__device__ __forceinline__ float dot_coded_step(const uint16_t* tab, const r3d_u32x4 a,
const r3d_u32x4 c, float sub)
{
sub = dot4_f16x4(tab_pair(tab, a.x & 0xffffu), tab_pair(tab, a.x >> 16),
tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub);
sub = dot4_f16x4(tab_pair(tab, a.y & 0xffffu), tab_pair(tab, a.y >> 16),
tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub);
sub = dot4_f16x4(tab_pair(tab, a.z & 0xffffu), tab_pair(tab, a.z >> 16),
tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub);
sub = dot4_f16x4(tab_pair(tab, a.w & 0xffffu), tab_pair(tab, a.w >> 16),
tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub);
return sub;
}
/* One step's sixteen codes into the accumulator: four dot4, the pairs decoded out of the table as
* each dot consumes them. Materialising the eight pairs first and feeding the dots from the array
* is what the register file cannot afford here: the scheduler hoists the sixteen table reads, so
* all eight decoded pairs are live at once on top of the window's loads. Consuming a pair in the
* dot that wants it keeps two registers live where the array keeps eight -- which is the
* difference between this arm compiling at zero spills and spilling 374 bytes against the
* 128-register budget a 256-thread block gets at four waves a SIMD. The order is unchanged: the
* pairs ascend, four dot4 a step, into one accumulator. */
__device__ __forceinline__ float dot_step(const uint16_t* tab, const r3d_u32x4 c,
const r3d_u32x4 a0, const r3d_u32x4 a1, float sub)
{
sub = dot4_f16x4(a0.x, a0.y, tab_pair(tab, c.x & 0xffffu), tab_pair(tab, c.x >> 16), sub);
sub = dot4_f16x4(a0.z, a0.w, tab_pair(tab, c.y & 0xffffu), tab_pair(tab, c.y >> 16), sub);
sub = dot4_f16x4(a1.x, a1.y, tab_pair(tab, c.z & 0xffffu), tab_pair(tab, c.z >> 16), sub);
sub = dot4_f16x4(a1.z, a1.w, tab_pair(tab, c.w & 0xffffu), tab_pair(tab, c.w >> 16), sub);
return sub;
}
template <bool NT>
__device__ __forceinline__ r3d_u32x4 ldc(const uint8_t* p) // 16 codes
{
if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p;
else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p);
}
__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) { return *(const r3d_u32x4*)p; }
/* q8_group's clamp, with q8_group's comparisons: fminf/fmaxf replace a NaN with the bound, and a NaN
* activation is a value the reference encodes as the format's NaN, not as +-top. */
__device__ __forceinline__ float clamp_top(float c)
{
if (c > kTopE4M3) c = kTopE4M3;
if (c < -kTopE4M3) c = -kTopE4M3;
return c;
}
/* y[M,n] = gate(a @ b^T), with the quantiser. GROUP is the block's width in output columns AND the
* weight's K block AND the quantiser's group: one `group` parameter, three grids, which is what the
* op states: kb, nb and ng are derived from the one key. ACT is the gate, A8 the coded activation,
* NT the weight load's lowering.
*
* The activation is staged in LDS per K block, widened to f16 pairs on the way in -- E4M3 -> f16 and
* bf16 -> f16 are both exact over f16's normal range. A block stages RP * GROUP values, 512 bytes at
* every supported GROUP, and a wave reads its row's 16 values per step as one broadcast ds_read: all
* 32 lanes of a wave own the same m, so all 32 read the same address. The weight is not staged: a
* lane streams two rows of it and no other lane reads them with it. */
template <int GROUP, int ACT, bool A8, bool NT, bool WIN>
__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(WIN ? 3 : 8) void gated_kernel(
const uint8_t* __restrict__ A, const float* __restrict__ AScale,
const uint8_t* __restrict__ B, const void* __restrict__ BScale, int bs16,
uint8_t* __restrict__ Q, float* __restrict__ S, uint16_t* __restrict__ Y,
int M, int N, int K, int a_ld, int q_ld, int y_ld, int nkb, int ng)
{
constexpr int RP = kBlockThreads / GROUP; // rows a block carries
constexpr int AP = GROUP / 2; // dwords a staged activation row (f16 pairs)
constexpr int WPG = GROUP / kWave; // waves covering one group of columns
static_assert(RP >= 1 && WPG >= 1 && RP * WPG == kWaves, "a block is one group wide");
__shared__ uint32_t s_a[RP * AP];
__shared__ float s_mx[kWaves];
__shared__ uint16_t s_tab[256];
const uint32_t tid = threadIdx.x;
const uint32_t lane = tid & (kWave - 1);
const uint32_t wave = tid / kWave;
/* The block's decoder, filled before any lane reads it: 128 dwords, one per pair of codes, by
* the codec's own arithmetic. The cost is 128 decodes a block -- at the band's M = 64 that is
* 0.02% of the block's decodes, and at M = 1 it is paid once per block for 128 codes x 16 k
* blocks of table reads. */
build_e4m3_table(s_tab, tid);
group_barrier();
const uint32_t gidx = blockIdx.x; // the group of output columns
const uint32_t mloc = tid / GROUP; // this lane's row within the block
const uint32_t i = gidx * GROUP + (tid % GROUP); // the fused column
const uint32_t m = (uint32_t)blockIdx.y * RP + mloc;
const int n = N / 2;
/* A ragged last group runs past n: the pair's rows are clamped, so no lane reads past the weight
* plane, and its stores are guarded below. A row past M re-reads the last real row. */
const int i_real = (int)(i < (uint32_t)n ? i : (uint32_t)(n - 1));
const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1));
const uint8_t* wg = B + (size_t)i_real * K; // the gate's row
const uint8_t* wu = B + (size_t)(n + i_real) * K; // the up's row, n rows further on
/* b_scale is [ceil(N/group)][ceil(K/group)]: make_scales gives rblk = group (fewer scale rows
* than operand rows is a block grid), so a row's scale row is its row index over the block. */
const size_t bsg = (size_t)((uint32_t)i_real / GROUP) * (size_t)nkb;
const size_t bsu = (size_t)((uint32_t)(n + i_real) / GROUP) * (size_t)nkb;
const float* bsF = bs16 ? nullptr : (const float*)BScale;
const uint16_t* bsH = bs16 ? (const uint16_t*)BScale : nullptr;
const float* as = A8 ? AScale + (size_t)m_real * nkb : nullptr;
float acc_g = 0.0f, acc_u = 0.0f;
/* One scale block per round, `nkb` of them: stage the block's activation, walk the block's k
* with two chains, fold the block's two scales in at the block's end. K is a multiple of GROUP,
* which the launcher requires, so every block is whole and the staging loop has no tail. */
/* The skinny arm's activation pointer: the row, in bytes. */
const uint8_t* ar = (A8 && WIN) ? (const uint8_t*)A + (size_t)m_real * a_ld : nullptr;
for (int kb = 0; kb < K; kb += GROUP) {
const int gi = kb / GROUP;
/* The staged round, and the barrier around it, belong to the tall arms. At the skinny height
* -- M <= 8, the threshold `R3D_GT_G` selects on, 16 KiB of activation at the band's K --
* the whole activation is M*K bytes and the 48 column groups of a row all
* read the same slice of it, so it lives in L1 from the first k-block on and staging it
* through shared memory buys nothing but a barrier a block a k-block. The numbers: the
* same stream read straight from memory 187 us, the same stream staged through LDS 497 us,
* at 48 blocks, 24 MiB of codes, on a part of this family. */
if constexpr (!WIN) {
constexpr int kUnit = 8; // codes (fp8a8) or elements (bf16) a unit
constexpr int nu = GROUP / kUnit;
#pragma unroll
for (int u = (int)tid; u < RP * nu; u += kBlockThreads) {
const int r = u / nu, c = (u % nu) * kUnit;
const int rm = (int)((uint32_t)blockIdx.y * RP + (uint32_t)r);
const int rr = rm < M ? rm : M - 1;
uint32_t* dst = s_a + (size_t)r * AP + c / 2;
if constexpr (A8) {
const r3d_u32x2 b8 = *(const __attribute__((address_space(1))) r3d_u32x2*)(
A + (size_t)rr * a_ld + kb + c);
dst[0] = e4m3x2_to_f16x2(b8.x & 0xffffu);
dst[1] = e4m3x2_to_f16x2(b8.x >> 16);
dst[2] = e4m3x2_to_f16x2(b8.y & 0xffffu);
dst[3] = e4m3x2_to_f16x2(b8.y >> 16);
} else {
/* Cast to the element pointer FIRST: the row and k offsets are ELEMENT offsets,
* which for bf16 is twice the byte count (r3d_gemm_fp8a16_nt_m1.hip). */
const r3d_u32x4 b16 = *(const __attribute__((address_space(1))) r3d_u32x4*)(
(const uint16_t*)A + (size_t)rr * a_ld + kb + c);
dst[0] = bf16x2_to_f16x2(b16.x);
dst[1] = bf16x2_to_f16x2(b16.y);
dst[2] = bf16x2_to_f16x2(b16.z);
dst[3] = bf16x2_to_f16x2(b16.w);
}
}
group_barrier();
}
const uint32_t* ap = s_a + (size_t)mloc * AP;
/* One chain at a time. The gate's product, k ascending into `sub_g`, then the up's into
* `sub_u` -- the two chains are the two calls the unfused pair makes, they share nothing,
* and each one's bracketing is that call's, element for element.
*
* Sequencing them, rather than interleaving them step by step, is what the register file
* asks for. The window is eight 16-byte loads a stream; holding both streams' windows
* live at once is 64 registers of loads on top of the decode's temporaries, the staged
* activation's reads, the two accumulators and the block's pointers, and at 256 threads
* (four waves a SIMD, 128 registers a lane) it spills 365 bytes. One chain's window is
* 32 registers, and the arm compiles clean.
*
* On the band's stream -- 24 MiB of codes, vram, 11 launches, GPU 2, this kernel's loop
* with the epilogue off: 16-byte step with the arithmetic decoder 584 us; table decoder,
* same step 453 us; table, window 64 283 us; table, window 128 187 us; the same sixteen
* loads with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
float sub_g, sub_u;
if constexpr (WIN) {
/* The skinny arm, M <= 8 (the threshold `R3D_GT_G` selects on): read the codes, decode
* them out of the block's table, multiply
* them. No shared memory between the load and the dot, and no barrier in the k-loop --
* the two chains, gate then up, k ascending inside each, the scales folded at the block's
* end, the epilogue below untouched.
*
* Three loads a step, sixteen bytes each: the activation's sixteen codes, the gate's,
* the up's. Six of them are in flight at the depth below, against the 163 GB/s the card
* does; the tall arms feed the same stream with occupancy, at 32 waves a CU.
*
* On this band's stream (24 MiB of codes, vram, 11 launches, GPU 2, epilogue off):
* the staged shape 497 us; the same codes read straight 187 us; the same sixteen loads
* with no decode and no dot 139 us. The op without the table decoder and the window
* spends 1474 us a call. */
constexpr int kNS = GROUP / kStep; // steps a block
constexpr int kD = 2; // loads a chain in flight
auto chain = [&](const uint8_t* w, float sub) {
auto ld = [&](int st) {
return ldc<NT>(w + kb + (st < kNS ? st : kNS - 1) * kStep);
};
/* Named registers, not an array: an array indexed across a round -- even with the
* round count constant and the loop marked for unrolling -- puts the codes in the
* private segment, 572 bytes a lane, and every code crosses scratch on its way from
* the load to the dot. Two named dwords-in-four, prefetched two steps ahead, keep
* the same six loads in flight and the frame at zero. */
r3d_u32x4 c0 = ld(0), c1 = ld(1);
#pragma unroll
for (int st = 0; st < kNS; st += kD) {
__builtin_amdgcn_sched_barrier(0);
const r3d_u32x4 a0 = ldc<NT>(ar + kb + (st + 0) * kStep);
const r3d_u32x4 a1 = ldc<NT>(ar + kb + (st + 1) * kStep);
const r3d_u32x4 n0 = ld(st + kD + 0), n1 = ld(st + kD + 1);
sub = dot_coded_step(s_tab, a0, c0, sub);
sub = dot_coded_step(s_tab, a1, c1, sub);
c0 = n0;
c1 = n1;
}
return sub;
};
sub_g = chain(wg, 0.0f);
sub_u = chain(wu, 0.0f);
} else {
/* The tall arms: one 16-code step a round, both streams in the same round.
* At M >= 8 the block grid is 48 x M/2 blocks, the wave slots are full, and the stream
* is fed by occupancy -- 109 registers a lane, four waves a SIMD, 32 waves a CU. The
* window is a skinny-arm fix: it buys its loads per lane at 32 registers, which on
* this arm is a fifth wave a SIMD given up, and on the 47 bands at M = 64 that is the
* whole op. Measured: windowed at M = 64 costs more than it saves. */
sub_g = 0.0f;
sub_u = 0.0f;
/* The round's unroll depth is a register decision, and at group = 32 it is the whole
* decision: the block is two steps wide, so `unroll 2` is a full unroll, the scheduler
* takes all thirty-two table reads of the two chains and hoists them above the dots,
* and the arm lands at 128 registers with 12 spilled (the same arm at group >= 64, in
* the same file, is 106 to 112 with none). Left as a loop the body is one step. */
/* Inline, from the table into the dot, on purpose. Materialising the eight decoded
* pairs into an array on the way -- the shape the arithmetic decoder above feeds --
* puts the plane about a third away from the reference at every tall height (M = 7:
* rel_l2 6.6e-01; M = 64: -nan), with the table itself exact on the device, entry by
* entry and pair by pair. The array form is the one that miscomputes here; do not
* restore it as a tidy-up. */
auto step_body = [&](int k) {
const r3d_u32x4 a0 = lds_a(ap + k / 2);
const r3d_u32x4 a1 = lds_a(ap + k / 2 + 4);
sub_g = dot_step(s_tab, ldc<NT>(wg + kb + k), a0, a1, sub_g);
sub_u = dot_step(s_tab, ldc<NT>(wu + kb + k), a0, a1, sub_u);
};
if constexpr (GROUP <= 32) {
#pragma unroll 1
for (int k = 0; k < GROUP; k += kStep) step_body(k);
} else {
#pragma unroll 2
for (int k = 0; k < GROUP; k += kStep) step_body(k);
}
}
if constexpr (!WIN)
group_barrier(); // the next block's stage must not race this one's reads
/* The two finished sub-sums, each scaled once, in libref's parentheses. */
const float sa = A8 ? as[gi] : 1.0f;
acc_g = acc_g + (sub_g * sa) * (bs16 ? bf16_to_f32(bsH[bsg + gi]) : bsF[bsg + gi]);
acc_u = acc_u + (sub_u * sa) * (bs16 ? bf16_to_f32(bsH[bsu + gi]) : bsF[bsu + gi]);
}
/* ---- the epilogue: narrow both halves, gate, quantise the group -------------------------- */
const float gt = bf16_to_f32(f32_to_bf16(acc_g));
const float up = bf16_to_f32(f32_to_bf16(acc_u));
const float sg = 1.0f / (1.0f + expf(-gt));
const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up);
const bool keep = (i < (uint32_t)n) && (m < (uint32_t)M);
if (keep && Y) Y[(size_t)m * y_ld + i] = h;
/* A column past n, and a row past M, contribute 0.0f: padding takes no part in the amax and
* takes no store, which is quant_act_fp8's rule for a ragged row. */
const float am = keep ? fabsf(bf16_to_f32(h)) : 0.0f;
float mx = wave_max(am); // fmaxf skips a NaN, as `if (m > amax)` does
if (lane == 0) s_mx[wave] = mx;
group_barrier();
mx = s_mx[mloc * WPG];
#pragma unroll
for (int w = 1; w < WPG; ++w) mx = fmaxf(mx, s_mx[mloc * WPG + w]);
const float sc = mx > 0.0f ? mx * (1.0f / kTopE4M3) : 1.0f;
/* One store per (row, group): the group's WPG waves all hold the same max, so the first writes
* and the rest stand down. `scale` is dense -- the launcher takes no pitch for it -- so a row is
* `ng` scales and the group index is the block's. */
if (keep && lane == 0 && (wave % WPG) == 0) S[(size_t)m * ng + gidx] = sc;
if (keep) {
const float inv = 1.0f / sc;
Q[(size_t)m * q_ld + i] = f32_to_e4m3(clamp_top(bf16_to_f32(h) * inv));
}
}
} // namespace
/* y[M,n] = gate(a[M,K] @ dequant(b)[N,K]^T), E4M3 codes out, n = N/2 inside.
*
* a [M][K] E4M3 codes (fp8a8, with `a_scale`) or bf16 (fp8a16)
* a_scale [M][ceil(K/group)] f32, dense, or 0
* b [N][K] E4M3 codes, row-major, k contiguous: gate rows [0,n), up rows
* [n,N)
* b_scale [ceil(N/group)][ceil(K/group)] bf16 (the op's stated dtype) or f32, block-major
* q [M][n] E4M3 codes, `q_ld` elements a row (0 = n)
* scale [M][ceil(n/group)] f32, DENSE (no pitch is taken)
* out_bf16 [M][n] bf16, `y_ld` elements a row (0 = n), optional: the pre-gate...
* the gated bf16 tensor the codes were taken over
*
* `group` is the weight's K block, the weight's row block and the output quantiser's group at once,
* which is what the op's single key states; 0 takes the checkpoint's 128. `act` is R3D_ACT_SILU
* (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). `sk` is accepted as 0/1 and
* refused above it: the epilogue needs a whole row. `nt` selects the weight load's lowering.
* `scratch` is unused -- the op needs no arena, which is what keeps the row concurrent.
*
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 HIP
* failed. */
extern "C" int r3d_gemm_nt_q_gated_ex(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
int bs_dt, long stream)
{
if (!a || !b || !b_scale || !q || !scale) return -1;
if (M < 1 || N < 2 || (N & 1) || K < 1) return -2;
if (M > kMMax) return -2;
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2;
const int n = N / 2;
if (group <= 0) group = R3D_FP8_BLOCK;
if (group > n) return -2; // two grids, one key: see the header
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return -2;
if (K % group) return -2; // a ragged block reads past the scales
const int nkb = K / group, ng = (n + group - 1) / group;
if (!a_ld) a_ld = K;
if (!q_ld) q_ld = n;
if (!y_ld) y_ld = n;
if (a_ld % 8) return -3; // 8-code (and 8-element) staging
if (sk == 0) sk = 1;
if (sk > 1) return -2; // no K slab closes this epilogue
(void)scratch;
const int bs16 = (bs_dt == RAD_BF16); /* anything else, 0 included, reads the plane as f32 */
const int a8 = a_scale != 0;
const int rp = kBlockThreads / group;
const dim3 grid((unsigned)ng, (unsigned)((M + rp - 1) / rp)), blk(kBlockThreads);
/* The skinny arms -- the decode's height -- take the windowed stream; the tall arms keep
* the step. One number, two kernels, and the band key that names them is the same one.
*
* M <= 8 is the shipped threshold and it is a tunable, not a fact. With the table decoder in both
* arms, N=12288 K=2048 group=128 vram: at M=8 skinny 402 against staged 754, at M=16 skinny 955
* against staged 1030 -- so the crossover is above 16; M=9..15 is unmeasured. Decode lives at M=1
* and a draft's verify at M<=8, which is what the threshold is chosen for; a prefill at 9..16 rows
* would take the skinny arm on the M=16 numbers, for about 7%. */
#define R3D_GT_G(G, A, A8, NTV) \
do { \
if (A8 && M <= 8) R3D_GT_W(G, A, A8, NTV, true); \
else R3D_GT_W(G, A, A8, NTV, false); \
} while (0)
#define R3D_GT_W(G, A, A8, NTV, WV) \
R3D_KLAUNCH(R3D_KNAME((gated_kernel<G, A, A8, NTV, WV>)), grid, blk, (hipStream_t)stream, \
(const uint8_t*)a, (const float*)a_scale, (const uint8_t*)b, \
(const void*)b_scale, bs16, (uint8_t*)q, (float*)scale, (uint16_t*)out_bf16, \
M, N, K, a_ld, q_ld, y_ld, nkb, ng)
#define R3D_GT_NT(G, A, A8) do { if (nt) R3D_GT_G(G, A, A8, true); else R3D_GT_G(G, A, A8, false); } while (0)
#define R3D_GT_A8(G, A) do { if (a8) R3D_GT_NT(G, A, true); else R3D_GT_NT(G, A, false); } while (0)
#define R3D_GT_ACT(G) do { if (act == R3D_ACT_SILU) R3D_GT_A8(G, R3D_ACT_SILU); \
else R3D_GT_A8(G, R3D_ACT_SIGMOID); } while (0)
#define R3D_GT(G) do { switch (group) { case G: R3D_GT_ACT(G); break; default: break; } } while (0)
R3D_GT(32);
R3D_GT(64);
R3D_GT(128);
R3D_GT(256);
#undef R3D_GT
#undef R3D_GT_ACT
#undef R3D_GT_A8
#undef R3D_GT_NT
#undef R3D_GT_W
#undef R3D_GT_G
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The declaration in r3d.h carries no scale dtype, and this op's shape hook states bf16 -- the hook
* has no f32 spelling at all -- so the plain entry reads bf16 and the `_ex` twin above carries the
* key. A caller with an f32 scale plane (the `fp8a8f32` reading of the unfused GEMM) lands on `_ex`
* with RAD_F32; the kernel widens bf16 -> f32 exactly, so the two agree to the bit. */
extern "C" int r3d_gemm_nt_q_gated(long a, long a_scale, long b, long b_scale, long q, long scale,
long out_bf16, int M, int N, int K, int group, int act,
int a_ld, int q_ld, int y_ld, int sk, int nt, long scratch,
long stream)
{
return r3d_gemm_nt_q_gated_ex(a, a_scale, b, b_scale, q, scale, out_bf16, M, N, K, group, act,
a_ld, q_ld, y_ld, sk, nt, scratch, RAD_BF16, stream);
}
/* ============================================================== the plugin ABI entry point
*
* gemm_nt_q_gated's operands are [a, a_scale, b, b_scale, q, scale, out_bf16?] and its parameters
* M, N, K, group, dtype, act (libref's pGemmQGated/oGemmQGated: `act` REQUIRED, `a_scale` REQUIRED,
* `out_bf16` optional). The shape hook declines every scheme but fp8a8, so the row binds fp8a8 and
* the shim reads the coded activation off the operands. */
enum { G_A = 0, G_ASCALE, G_B, G_BSCALE, G_Q, G_SCALE, G_OB };
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
static int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
static int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
static int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; }
extern "C" int r3d_rad_gemm_nt_q_gated(const RadArgs* a, RadStream s)
{
const RadTensor* A = r3d_opt(a, G_A);
const RadTensor* AS = r3d_opt(a, G_ASCALE);
const RadTensor* B = r3d_opt(a, G_B);
const RadTensor* BS = r3d_opt(a, G_BSCALE);
const RadTensor* Q = r3d_opt(a, G_Q);
const RadTensor* SC = r3d_opt(a, G_SCALE);
const RadTensor* OB = r3d_opt(a, G_OB);
if (!A || !B || !BS || !Q || !SC) return R3D_NO(RAD_E_INVAL);
if (!r3d_is_e4m3(B)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_e4m3(Q));
R3D_NEED(dt_f32(SC));
if (OB) R3D_NEED(dt_bf16(OB));
/* The activation: E4M3 codes with a per-(row, group) f32 scale (fp8a8, the scheme this op's
* shape hook and every band states), or bf16 with no scale (fp8a16, which the hook declines, so
* no band arrives: the kernel carries the path because the launcher does, and the shim accepts
* it on the operands). E5M2 has no decoder here. */
const bool a8 = AS != nullptr;
if (a8) {
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_f32(AS));
} else {
R3D_NEED(dt_bf16(A));
}
/* b_scale is bf16 -- `o.t(RAD_BF16, {nb, kb})` is this op's own line in the hook, and the
* container's `weight_scale_inv` for the whole quantised family. f32 is accepted because the
* widening is exact and the kernel reads both: the driver's bf16/f32 pair must agree element
* for element. */
const bool bs16 = r3d_is_bf16(BS);
if (!bs16 && !r3d_is_f32(BS)) return R3D_NO(RAD_E_DTYPE);
/* `act` is required by the schema (P_STR, not P_STRO): an implementation may compile one gate,
* and an optional parameter would let the row resolve for the other. libref's default is -1 and
* it refuses it; so does this shim, with no `mode` integer spelling to fall back on. */
const int act = r3d_act_code(a, "act", nullptr, -1);
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return R3D_NO(RAD_E_INVAL);
const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1));
const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2));
if (K < 1 || N < 2 || (N & 1)) return R3D_NO(RAD_E_SHAPE);
const long long n = N / 2;
/* Rows come from `q`, never from the `M` parameter, which is the band's upper bound. libref
* reads numel(q) / n; on a plane whose pitch exceeds n that counts the padding, so the shape's
* own row count clamps it. A dense plane -- every case the fixture draws -- reads the same
* number either way. */
const long long qnel = r3d_numel(Q);
if (qnel < n || qnel % n) return R3D_NO(RAD_E_SHAPE);
long long M = qnel / n;
if (Q->rank >= 2 && r3d_dim(Q, (int)Q->rank - 2) < M) M = r3d_dim(Q, (int)Q->rank - 2);
if (M < 1 || M > kMMax) return R3D_NO(RAD_E_SHAPE);
/* The group: the weight's K block, the weight's row block and the quantiser's group, from the
* one key the op states. The reference defaults 0 to `group`-as-stated for the grids and
* `g > n` to n for the quantiser alone; this kernel reads one width, so a group wider than the
* fused width is refused rather than served on a grid the two sides do not share. */
const long long group = r3d_geti_or(a, "group", R3D_FP8_BLOCK);
if (group < kGroupMin || group > kGroupMax || (group & (group - 1))) return R3D_NO(RAD_E_SHAPE);
if (group > n) return R3D_NO(RAD_E_SHAPE);
if (K % group) return R3D_NO(RAD_E_SHAPE);
const long long nkb = K / group, nb = (N + group - 1) / group, ng = (n + group - 1) / group;
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < nb * nkb) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(SC) < M * ng) return R3D_NO(RAD_E_SHAPE);
if (AS && r3d_numel(AS) < M * nkb) return R3D_NO(RAD_E_SHAPE);
if (OB && r3d_numel(OB) < M * n) return R3D_NO(RAD_E_SHAPE);
long long arows = 0, qrows = 0, srows = 0, yrows = 0;
const long long a_ld = r3d_rows_pitch(A, K, &arows);
const long long q_ld = r3d_rows_pitch(Q, n, &qrows);
const long long y_ld = OB ? r3d_rows_pitch(OB, n, &yrows) : n;
if (a_ld < 0 || q_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
/* `yrows` is only a promise when the plane is there. `r3d_rows_pitch` leaves the count at zero
* for a null operand, and an absent optional output is a null operand by contract (r3d_args.h),
* so testing `yrows` unconditionally reads "the row is missing" from "the caller asked for no
* bf16 mirror". */
if (arows < M || qrows < M || (OB && yrows < M)) return R3D_NO(RAD_E_SHAPE);
if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); // 8-code / 8-element staging
/* The scale planes travel without a pitch argument, so they must be dense, and `scale`'s grid
* must be the one the kernel walks: `ng` scales a row. */
if (!r3d_contig(B) || !r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
if (AS && !r3d_contig(AS)) return R3D_NO(RAD_E_STRIDE);
if (r3d_rows_pitch(SC, ng, &srows) != ng) return R3D_NO(RAD_E_STRIDE);
if (srows < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_dim(BS, 1) != 0 && BS->shape[BS->rank - 1] != nkb && r3d_numel(BS) != nb * nkb)
return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN);
R3dGemmCfg c;
r3d_cfg_gemm(a, &c);
/* Split-K is the axis this kernel cannot honour: a K slab produces a partial product, and the
* epilogue needs the finished row -- its bf16 narrowing, the gate's partner column, the group's
* amax. A caller that states sk > 1 is refused here, at the row, not answered slowly. */
if (c.sk > 1) return R3D_NO(RAD_E_SHAPE);
const int e = r3d_gemm_nt_q_gated_ex(
r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Q), r3d_addr(SC),
r3d_addr(OB), (int)M, (int)N, (int)K, (int)group, act, (int)a_ld, (int)q_ld, (int)y_ld, 1,
c.nt, 0L, (int)BS->dtype, (long)(uintptr_t)s);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
File diff suppressed because it is too large. Load diff
+431
View File
@@ -0,0 +1,431 @@
/* r3d_gemm_inta8.hip -- gemm_nt_q at dtype=w4a8 and w8a8: the symmetric int4 and int8 weight
* grids at decode heights, one kernel per grid.
*
* The grids, libref's descriptions: int8 activations in quant_act_i8's step order against
* signed weight codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row, 128 of
* K), an f32 activation scale per row, and no zero point -- the dequant is code times scale,
* so there is no a_sum to carry and no bias to take off. The group sub-sum is formed on the
* integer grid and scaled once per group, the reference's order:
*
* sub = sum over the group of a * code, an exact integer
* acc += (sub * a_scale[m]) * scale[n, g]
*
* ---- exactness, and why the dots may run in f16 --------------------------------------------------
*
* A lane's 64 products are |a * code| <= 127 * 7 (w4a8) or 127 * 127 (w8a8), and the group's
* 128 of them sum to 113,792 (w4a8) or 2,064,512 (w8a8): both under 2^24, the f32 mantissa, so
* the lane partial and the pair fold are exact, and the group terms land in the accumulator
* in the reference's ascending order. The codes widen to f16 through a sign extension, which
* is exact for both grids; the activations widen through the i8 codec the w2a8 arm uses.
*
* The activation is the step order: within each sixteen-byte step the middle two dwords are
* exchanged, so the staging reads through the same position map the w2a8 arm does, and a
* weight row's codes are plain row-major, two a byte at I4 and one a byte at I8.
*
* ---- the tile --------------------------------------------------------------------------------------
*
* One workgroup serves kWaves weight rows; a wavefront takes one row, lane l owns rows
* l & (MT-1) and k-lane l / MT, and the chunk is 2048 / MT codes: a multiple of the 128
* group at every MT, so a chunk carries CG = 16 / MT whole groups and the group's scale is
* one read. The lane's 64 codes are 32 bytes at I4, two 16-byte loads, and 64 at I8, four.
* The lane's 64 sit in the group's two halves the w2a8 arm folds with one shfl_xor(MT), and
* the group's term -- scaled by the activation's row scale and the weight's group scale --
* goes to shared, where the row's owner lane sums the chunk's groups in ascending order.
*
* M > 16 is the tiled row's; the w2a8 arm serves the 2- and 4-bit container grids there, and
* the 8-bit grid at prefill heights is declared out of this unit.
*
* ---- refusals --------------------------------------------------------------------------------------
*
* Every structural violation is a refusal, in the shim: the dtypes of all five operands,
* K % 128, the band's M, the b row pitch's 16-byte alignment, the a and y pitches. There is
* no data that is a refusal: both grids have no reserved value.
*/
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
#include "r3d_args.h"
namespace {
constexpr int kWave = 32;
constexpr int kWaves = 8;
constexpr int kBlockThreads = kWaves * kWave;
constexpr int kMTMax = 16;
constexpr int kGroup = 128;
constexpr int kTileQuads = 512; /* MT rows x CHUNK/4 f16, constant over MT */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse.
* Applied to the four columns of one dword it leaves them four contiguous bytes and turns
* the map on the DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a
* 16-byte step exchanged. */
__device__ __forceinline__ int64_t dword_pos(int64_t d)
{
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
/* The LDS swizzle, at the granularity the tile is touched: a quad of four f16, two dwords,
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low
* four bits with bits 4..7 -- a bijection on 16-quad groups. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
{
lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu));
hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu),
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
}
/* Four signed int4 codes (two bytes, the low code in the low nibble) -> two f16x2 dwords.
* Exact: the sign extension lands on an integer, and f16 steps by 1/8 at exponent 2^-3.
* A nibble n is the value (n & 7) - (n & 8): 0..7 pass through and 8..15 land on -8..-1.
* The gfx1102 backend folds the bias-8 spelling ((n ^ 8) - 8) to n ^ 16 once it has proven
* the nibble range, so the sign is kept as a bit term. */
__device__ __forceinline__ void i4x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
{
const uint32_t n0 = w & 0xFu;
const uint32_t n1 = (w >> 4) & 0xFu;
const uint32_t n2 = (w >> 8) & 0xFu;
const uint32_t n3 = (w >> 12) & 0xFu;
const int32_t c0 = (int32_t)((n0 & 7u) - (n0 & 8u));
const int32_t c1 = (int32_t)((n1 & 7u) - (n1 & 8u));
const int32_t c2 = (int32_t)((n2 & 7u) - (n2 & 8u));
const int32_t c3 = (int32_t)((n3 & 7u) - (n3 & 8u));
lo = f16x2_pack((float)c0, (float)c1);
hi = f16x2_pack((float)c2, (float)c3);
}
__device__ __forceinline__ float dot4_f16x4(uint32_t a0, uint32_t a1, uint32_t b0, uint32_t b1,
float acc)
{
const _Float16* fa = (const _Float16*)&a0;
const _Float16* fb = (const _Float16*)&b0;
acc = fmaf(fa[0], fb[0], acc);
acc = fmaf(fa[1], fb[1], acc);
const _Float16* fa1 = (const _Float16*)&a1;
const _Float16* fb1 = (const _Float16*)&b1;
acc = fmaf(fa1[0], fb1[0], acc);
acc = fmaf(fa1[1], fb1[1], acc);
return acc;
}
template <int MT, int CDT>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_inta8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa,
const uint8_t* __restrict__ b, int b_rb, const uint16_t* __restrict__ sb,
int sb_rb, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
int a_pitch, int y_pitch)
{
constexpr int KL = kWave / MT; /* k-lanes per activation row */
constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk: 16 / MT */
constexpr int CL = 64; /* codes per lane per chunk */
constexpr int NLOAD = (CL * CDT) / 128; /* 16-byte loads: the lane's window */
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/4 f16, swizzled */
__shared__ float sT[kWaves * 16]; /* warp*16 + m*CG + j */
__shared__ float sSa[MT];
const int lane = threadIdx.x & (kWave - 1);
const int warp = (int)(threadIdx.x / kWave);
const int n = blockIdx.x * kWaves + warp;
const bool live = n < N;
if ((int)blockIdx.x * kWaves >= N) return;
const int m = lane & (MT - 1);
const int kl = lane / MT;
const int row_bytes = b_rb; /* the codes' byte pitch, from the shim */
const int cq = (CDT == 4) ? (chunk >> 1) : chunk; /* the chunk's code bytes */
const int nchunk = K / chunk;
if (lane < MT) sSa[lane] = lane < M ? sa[lane] : 0.0f;
__syncthreads();
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells
* are four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t w = 0;
if (r < M)
w = *(const uint32_t*)(a + (long long)r * a_pitch +
dword_pos((int64_t)ch * (chunk >> 2) + c));
const int q = r * (chunk >> 2) + c;
uint32_t lo, hi;
i8x4_to_f16x2(w, lo, hi);
sA[p_ix(q)] = make_uint2(lo, hi);
}
__syncthreads();
if (live) {
/* 64 codes: 32 bytes at I4, 64 at I8. The lane's codes are kl * 64 within the
* chunk, and the row pitch keeps every 16-byte load aligned. */
const uint8_t* bp = b + (long long)n * row_bytes + (int64_t)ch * cq +
kl * (CL / 2) * (CDT / 4);
uint4 qw[NLOAD];
#pragma unroll
for (int L = 0; L < NLOAD; ++L)
__builtin_memcpy(&qw[L], bp + 16 * L, 16);
/* One value per quad: I4 the two-byte window as a 16-bit element, I8 the dword.
* The I4 window is taken as a half at its own address; shifting a dword array by
* a byte amount miscompiles on the gfx1102 backend. */
uint32_t wd[(CL >> 2)];
if (CDT == 4) {
uint16_t wq[CL / 2];
#pragma unroll
for (int L = 0; L < NLOAD; ++L)
__builtin_memcpy(&wq[8 * L], &qw[L], 16);
#pragma unroll
for (int v = 0; v < (CL >> 2); ++v)
wd[v] = wq[v];
} else {
#pragma unroll
for (int L = 0; L < NLOAD; ++L)
{ wd[4 * L + 0] = qw[L].x; wd[4 * L + 1] = qw[L].y;
wd[4 * L + 2] = qw[L].z; wd[4 * L + 3] = qw[L].w; }
}
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
/* 16 quads, decoded before the dot. */
uint32_t cb[(CL >> 2)][2];
#pragma unroll
for (int v = 0; v < (CL >> 2); ++v) {
if (CDT == 4) i4x4_to_f16x2(wd[v] & 0xFFFFu, cb[v][0], cb[v][1]);
else i8x4_to_f16x2(wd[v], cb[v][0], cb[v][1]);
}
float p = 0.0f; /* the lane's half-group, an exact integer */
#pragma unroll
for (int v = 0; v < (CL >> 2); ++v) {
const uint2 av = sA[p_ix(qb + v)];
p = dot4_f16x4(av.x, av.y, cb[v][0], cb[v][1], p);
}
/* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */
const float isg = p + __shfl_xor(p, MT);
const int g = ch * CG + (kl >> 1);
const float sc = f16_to_f32(sb[(long long)n * sb_rb + g]);
const float term = (isg * sSa[m]) * sc; /* the reference's parentheses */
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT. The group's two
* half-lanes write the same value, which is what the pair fold above is for. */
sT[warp * 16 + m * CG + (kl >> 1)] = term;
}
__syncthreads();
/* The chunk's groups, in ascending order, into the lane that owns the row's answer:
* the reference walks g in ascending order and f32 adds are not associative, so the
* order is part of the answer, not a detail. */
if (live && kl == 0) {
#pragma unroll
for (int j = 0; j < CG; ++j)
if (m < M) acc += sT[warp * 16 + m * CG + j];
}
__syncthreads();
}
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
}
int mt_for(int M)
{
int mt = 1;
while (mt < M && mt < kMTMax) mt *= 2;
return mt;
}
#define R3D_INTA8_LAUNCH(MT, CDT) \
do { \
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \
R3D_KLAUNCH(R3D_KNAME((gemm_inta8_kernel<MT, CDT>)), grid, block, (hipStream_t)stream, \
(const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, (const uint16_t*)b_scale, \
(int)sb_rb, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \
} while (0)
extern "C" int r3d_gemm_nt_q_w4a8_m16(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int a_ld, int y_ld, long long b_rb,
long long sb_rb, long stream)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (K % kGroup) return -2;
const int mt = mt_for(M);
const int chunk = 2048 / mt;
if (K % chunk) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3;
if (y_ld < N) return -3;
if (!b_rb) b_rb = K / 2;
if (b_rb < K / 2) return -3;
if (b_rb & 15) return -5;
if (!sb_rb) sb_rb = K / kGroup;
if (sb_rb < K / kGroup) return -3;
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
switch (mt) {
case 1: R3D_INTA8_LAUNCH(1, 4); break;
case 2: R3D_INTA8_LAUNCH(2, 4); break;
case 4: R3D_INTA8_LAUNCH(4, 4); break;
case 8: R3D_INTA8_LAUNCH(8, 4); break;
default: R3D_INTA8_LAUNCH(16, 4); break;
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_gemm_nt_q_w8a8_m16(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int a_ld, int y_ld, long long b_rb,
long long sb_rb, long stream)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (K % kGroup) return -2;
const int mt = mt_for(M);
const int chunk = 2048 / mt;
if (K % chunk) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3;
if (y_ld < N) return -3;
if (!b_rb) b_rb = K;
if (b_rb < K) return -3;
if (b_rb & 15) return -5;
if (!sb_rb) sb_rb = K / kGroup;
if (sb_rb < K / kGroup) return -3;
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
switch (mt) {
case 1: R3D_INTA8_LAUNCH(1, 8); break;
case 2: R3D_INTA8_LAUNCH(2, 8); break;
case 4: R3D_INTA8_LAUNCH(4, 8); break;
case 8: R3D_INTA8_LAUNCH(8, 8); break;
default: R3D_INTA8_LAUNCH(16, 8); break;
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#undef R3D_INTA8_LAUNCH
/* ================================================================== the shims
*
* gemm_nt_q's slots, as the two shims take them: 0 a (I8, step order), 1 a_scale (f32, one
* per row), 2 b (I4 or I8 codes), 3 b_scale (f16, one per (row, 128 of K)), 4 y (bf16),
* 5 a_sum (absent: symmetric), 6 b_ref (absent).
*/
extern "C" int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "w4a8") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
const RadTensor* BREF = r3d_opt(a, 6);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE); /* symmetric: nothing to remove */
if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_I4) return R3D_NO(RAD_E_DTYPE);
if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
const long long bbr = r3d_row_pitch(B) / 2; /* I4 counts elements, two a byte */
const int rc = r3d_gemm_nt_q_w4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
bbr, (long long)r3d_row_pitch(BS), (long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
extern "C" int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "w8a8") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
const RadTensor* BREF = r3d_opt(a, 6);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE);
if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
const int rc = r3d_gemm_nt_q_w8a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp,
(long long)r3d_row_pitch(B), (long long)r3d_row_pitch(BS),
(long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
} // namespace
+738
View File
@@ -0,0 +1,738 @@
/* r3d_gemm_mxfp4a8.hip -- gemm_nt_q at dtype=mxfp4a8: an OCP-MXFP4 weight against an fp8
* activation, at both heights.
*
* y[M,N] = a[M,K] @ b[N,K]^T, a in E4M3 with one f32 scale per (row, 128 of K), b in e2m1
* with one e8m0 scale per (row, 32 of K). f32 accumulate, one bf16 narrowing at the store.
* There is no zero point: the scale is symmetric.
*
* ---- the format, and the fold it gives ----------------------------------------------------------------
*
* OCP MXFP4 stores a weight row as e2m1 codes, two per byte, element 2j in the LOW nibble of
* byte j, with one e8m0 exponent per 32 K elements: a u8 plane [N, K/32] behind the u8 codes
* plane [N, K/2]. e8m0 value e means the factor 2^(e-127); e = 0 and e = 255 are reserved
* (zero, NaN) and a plane carrying either is refused, the reference's answer for the same
* bytes.
*
* The fold this kernel runs, per 32-block:
*
* 1. the code for element k is e4m3(mag) at d = 0 -- the e2m1 magnitude is EXACT in e4m3,
* because all eight magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} are e4m3 grid points. The
* unpack is a 4-bit lookup on the nibble through the eight e4m3 magnitude bytes
* {0x00, 0x30, 0x38, 0x3C, 0x40, 0x44, 0x48, 0x4C}, the sign bit of the code on the
* sign bit of the byte.
* 2. the code products run on dot2_f16x2. A product is at most 6 x 448 = 2688, in f16's
* range (65504), and an eight-term partial is under 21504, in f16's grid: the dot's
* only rounding is the instruction's own.
* 3. the per-block factor 2^(e-127) is applied in the epilogue: the 32-block partial, an
* f32, is multiplied by the factor -- a power of two, exact in f32 short of the
* under/overflow edge -- and added to the running f32 sum. One multiply and one add per
* block per output element, no per-element scale traffic.
* 4. the store narrows once, to bf16.
*
* The e2m1 magnitude is exact, the products are exact, and the two roundings a block sees are
* the dot's fused rounding and the store: the row's distance from the reference is the store's
* ulp, nothing else.
*
* The RDNA4 sibling folds the e8 into the table through a d-indexed row, because its WMMA
* path needs one scale per row; this library's dot2 path folds per block in the epilogue, and
* the table is the eight fixed magnitude bytes, no index.
*
* ---- the tiled row (M >= 17) -------------------------------------------------------------------------
*
* The 128x128 tile, 8x8 f32 accumulators a lane, k ascending in 32-code chunks. The chunk IS
* the OCP 32-block: the lane's e8 bytes for its eight tile columns enter as one byte per row
* at staging, through LDS, and the chunk's partials flush at the chunk's end:
*
* total[i][j] += acc[i][j] * 2^(e8[n_c + j][blk] - 127); acc[i][j] = 0;
*
* `acc` is the 32-block partial, `total` the running f32 sum over blocks in ascending k. The
* activation stages exactly as the fp8a8 tiled row's: E4M3 through the LDS table, the f32
* scale per (row, 128 of K) folded at staging; 32 divides 128, so a chunk sits inside one
* group and never straddles one.
*
* ---- the m16 row (M <= 16) ----------------------------------------------------------------------------
*
* One wave per weight row, the w2a8 row's shape: lane l owns row m = l % MT and k-lane
* kl = l / MT, a chunk is CHUNK = 2048/MT codes, and every lane takes 64 of them -- two OCP
* 32-blocks, the lane's blocks 2*kl and 2*kl+1 of the chunk. Each lane sums its two blocks in
* k, scales each by the block's e8, and the group's four block terms are formed in ascending
* block order by one shfl_xor pair and written to LDS, where the kl == 0 lane adds them to the
* accumulator in ascending block order: the reference's ascending-k accumulation, at the
* 32-block granularity the format fixes.
*
* ---- refusals -----------------------------------------------------------------------------------------
*
* Every structural violation is a refusal, in the shim: the dtypes of all seven operands (the
* codes as fp4_e2m1 or raw bytes, the e8 plane as e8m0 or u8, `b_ref` the e8 plane again and
* ignored), K % 32 and K % 128, the codes plane's extent and 16-byte row alignment, the e8
* plane's [N, K/32] extent, the pitches, the band's M. A reserved e8 (0, 255) is a data
* violation, and it is refused where the data is readable: the shim scans the e8 plane once
* per (pointer, size) pair, on a plane the host can see, and answers E_INVAL. A plane the
* host cannot see is not scanned, and the kernel's e8 guard -- reserved values take the scale
* zero -- keeps its output finite.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_fp8_dequant.h"
#include "r3d_tiling.h"
#include "r3d_launch.h"
#include <cstring>
#include <cstdio>
#include <cstdlib>
namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = 8;
constexpr int kTM = 128; /* rows a tile */
constexpr int kTN = 128; /* columns a tile */
constexpr int kKC = 32; /* k a chunk: one OCP 32-block */
constexpr int kMX = 32; /* K per e8m0 exponent: the OCP MX block */
constexpr int kGroup = 128; /* the activation's scale group */
constexpr int kMMin = 17; /* the tiled row's floor: the m16 row's ceiling plus one */
constexpr int kMTMax = 16;
constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 2048 codes, 4 KiB of f16 */
/* The eight e2m1 magnitudes, as e4m3 bytes: 0, .5, 1, 1.5 in the low word, 2, 3, 4, 6 in the
* high. Every one is exact, which is the whole point of the fold. */
#define R3D_MXFP4_MAG_LO 0x3c383000u
#define R3D_MXFP4_MAG_HI 0x4c484440u
/* Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) as eight e4m3
* bytes in k order (word 0 = elements 0..3, word 1 = 4..7). Even and odd nibbles each run
* through the magnitude bytes by a v_perm_b32 on the 3-bit magnitude, bit 3 of the code shifts
* onto the e4m3 sign, and two more v_perm_b32 interleave the halves. The table is the fixed
* d = 0 row: no index, because the per-block factor is applied in the epilogue, not folded
* here. */
__device__ __forceinline__ void mxfp4_unpack8(uint32_t wv, uint32_t* lo, uint32_t* hi)
{
const uint32_t ev = wv & 0x0F0F0F0Fu; /* low nibble of each byte -> even elements */
const uint32_t od = (wv >> 4) & 0x0F0F0F0Fu; /* high nibble -> odd elements */
const uint32_t be = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, ev & 0x07070707u)
| ((ev & 0x08080808u) << 4);
const uint32_t bo = __builtin_amdgcn_perm(R3D_MXFP4_MAG_HI, R3D_MXFP4_MAG_LO, od & 0x07070707u)
| ((od & 0x08080808u) << 4);
*lo = __builtin_amdgcn_perm(bo, be, 0x05010400u);
*hi = __builtin_amdgcn_perm(bo, be, 0x07030602u);
}
/* The e8m0 factor: 2^(e-127). The reserved values take the scale zero -- e = 0 is the
* format's zero, e = 255 its NaN -- so a plane that carries one computes a zero block and
* stays finite; the refusal for such a plane is the shim's, where the bytes are readable. */
__device__ __forceinline__ float e8_scale(uint8_t e)
{
return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127);
}
/* Four e4m3 bytes (one dword, low byte first) as two f16x2, through the block's table. The
* table entries are f16 bit patterns, so the words are moves, not conversions. */
__device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w, uint32_t* o)
{
o[0] = (uint32_t)tbl[w & 0xffu] | ((uint32_t)tbl[(w >> 8) & 0xffu] << 16);
o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16);
}
/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT
* f16x2_pack, which truncates. */
__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc)
{
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
const _Float16 s = (_Float16)sc;
const _Float16 rl = a * s, rh = b * s;
return (uint32_t)__builtin_bit_cast(uint16_t, rl)
| ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
}
/* Eight codes -> eight f16, through the table. gfx11 has no E4M3 convert, so the 256-entry
* f16 table stands in for the instruction. */
__device__ __forceinline__ void codes8(const uint2 c, const uint16_t* tbl, uint32_t* w)
{
r3d_e4m3x8_ld(tbl, c, w);
}
template <int NT>
__device__ __forceinline__ uint2 loadc8s(const uint8_t* p)
{
typedef uint32_t __attribute__((ext_vector_type(2))) u8v;
u8v v;
if (NT) v = __builtin_nontemporal_load((const u8v*)p);
else __builtin_memcpy(&v, p, 8);
uint2 r;
__builtin_memcpy(&r, &v, 8);
return r;
}
/* ================================================================== the tiled row */
struct ActQ {
const float* scale; /* a_scale, f32: [M][ceil(K/group)] */
long long row; /* elements a row */
int gmode; /* 1: one scale per (row, group) */
};
struct MxWQ {
const uint8_t* codes; /* e2m1, two per byte, [N][K/2] */
const uint8_t* e8; /* e8m0, one per 32, [N][K/32] */
long long code_row; /* bytes a codes row */
long long e8_row; /* bytes an e8 row */
};
/*
* The tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a
* lane -- 64 f32 accumulators a lane for the 32-block partials, 64 more for the running
* sum, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; the activation arrives as
* E4M3 codes, decodes through the block's table and leaves staging as f16 with its scale
* folded in, and the weight arrives as e2m1 nibbles, unpacks to e4m3 and leaves staging as
* f16 UNSIGNED by the block: its scale is the e8, and the e8 is applied at the chunk's end,
* where the chunk's partials meet it.
*/
template <int NT>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __restrict__ y,
int M, int N, int K, int a_ld, int y_ld)
{
__shared__ __align__(16) uint16_t sA[kTM * kKC];
__shared__ __align__(16) uint16_t sB[kTN * kKC];
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
__shared__ uint8_t sE8[kTN]; /* the chunk's e8, one per tile row */
const int tid = (int)threadIdx.x;
r3d_e4m3_f16_init(sTbl, tid, kBlockThreads);
const int m0 = (int)blockIdx.y * kTM;
const int n0 = (int)blockIdx.x * kTN;
const int rg = tid >> 4, cg = tid & 15;
float acc[8][8];
float total[8][8];
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) { acc[i][j] = 0.0f; total[i][j] = 0.0f; }
const int m_r = m0 + rg * 8, n_c = n0 + cg * 8;
for (int k0 = 0; k0 < K; k0 += kKC) {
const int g = k0 / kGroup;
const int blk = k0 / kMX; /* the chunk is one 32-block */
#pragma unroll
for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) {
const int mm = j / (kKC / 8), c8 = j % (kKC / 8);
const int m = m0 + mm, k = k0 + c8 * 8;
uint4 staged = make_uint4(0, 0, 0, 0);
if (m < M) {
const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)];
uint32_t w[4];
codes8(loadc8s<NT>(a + (long long)m * a_ld + k), sTbl, w);
staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa),
fold_pair(w[2], sa), fold_pair(w[3], sa));
}
*(uint4*)&sA[srow(mm, c8, kKC)] = staged;
}
for (int nn = tid; nn < kTN; nn += kBlockThreads) {
const int n = n0 + nn;
uint4 st[4] = { make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0),
make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) };
/* The e8 for the column, written even past N: a row the tile does not serve keeps
* the scale zero, so the flush multiplies a staged zero by a defined value. */
sE8[nn] = (n < N) ? h.e8[(long long)n * h.e8_row + blk] : 0;
if (n < N) {
/* 32 codes, 16 bytes, one load: k0 is a multiple of 32, the row a multiple of
* 64 bytes, so the load is aligned. */
uint4 cv;
__builtin_memcpy(&cv, h.codes + (long long)n * h.code_row + (k0 >> 1), 16);
const uint32_t d[4] = { cv.x, cv.y, cv.z, cv.w };
uint32_t w[16];
#pragma unroll
for (int q = 0; q < 4; ++q) {
uint32_t lo, hi;
mxfp4_unpack8(d[q], &lo, &hi);
e4m3x4_to_f16x2(sTbl, lo, w + 4 * q);
e4m3x4_to_f16x2(sTbl, hi, w + 4 * q + 2);
}
st[0] = make_uint4(w[0], w[1], w[2], w[3]);
st[1] = make_uint4(w[4], w[5], w[6], w[7]);
st[2] = make_uint4(w[8], w[9], w[10], w[11]);
st[3] = make_uint4(w[12], w[13], w[14], w[15]);
}
#pragma unroll
for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q];
}
__syncthreads();
/* The chunk's e8 for the lane's eight columns, held in registers: the flush reads it
* and nothing else does. The index is tile-local -- sE8 is this tile's 128 rows, and a
* global column index reads past it on every tile past the first. */
float e8s[8];
#pragma unroll
for (int j = 0; j < 8; ++j) e8s[j] = e8_scale(sE8[cg * 8 + j]);
#pragma unroll
for (int kc = 0; kc < kKC; kc += 2) {
uint32_t af[8], bf[8];
#pragma unroll
for (int i = 0; i < 8; ++i)
af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)];
#pragma unroll
for (int j = 0; j < 8; ++j)
bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)];
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
}
/* The 32-block boundary: the partial scales by the block's factor, the sum keeps the
* blocks in ascending k, and the partial resets for the next block. */
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) {
total[i][j] += acc[i][j] * e8s[j];
acc[i][j] = 0.0f;
}
__syncthreads();
}
/* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = m_r + i;
if (m >= M) break;
uint16_t* row = (uint16_t*)y + (long long)m * y_ld;
if (n_c + 8 <= N) {
uint32_t p[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
p[j] = (uint32_t)f32_to_bf16(total[i][2 * j]) |
((uint32_t)f32_to_bf16(total[i][2 * j + 1]) << 16);
*(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]);
} else {
#pragma unroll
for (int j = 0; j < 8; ++j)
if (n_c + j < N) row[n_c + j] = f32_to_bf16(total[i][j]);
}
}
}
/* ================================================================== the m16 row */
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords,
* moved as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four
* bits with bits 4..7 -- a bijection on 16-quad groups. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
template <int MT>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride,
const uint8_t* __restrict__ b, const uint8_t* __restrict__ e8,
int e8_row, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
int a_pitch, int y_pitch)
{
constexpr int KL = kWave / MT; /* k-lanes per activation row */
constexpr int CL = 64; /* codes per lane per chunk: two 32-blocks */
constexpr int BPR = (2048 / MT) / kMX; /* 32-blocks a row of the chunk: 64/MT */
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
__shared__ float sB[kWaves * 64]; /* the chunk's block terms: warp*64 + m*BPR + bl */
const int lane = threadIdx.x & (kWave - 1);
const int warp = (int)(threadIdx.x / kWave);
const int n = blockIdx.x * kWaves + warp;
const bool live = n < N;
if ((int)blockIdx.x * kWaves >= N) return;
const int m = lane & (MT - 1);
const int kl = lane / MT;
const int nchunk = K / chunk;
r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads);
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
__syncthreads();
/* The chunk's activation rows, decoded and scaled on the way in. Cells are four codes:
* MT * CHUNK/4 = 512 of them at every MT, two per thread. The scale is per (row, 128
* of K); a cell's four codes sit in one group, so one scalar a cell. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t lo = 0, hi = 0;
if (r < M) {
const int64_t k0 = (int64_t)ch * (chunk >> 2) * 4 + c * 4;
const uint32_t w = *(const uint32_t*)(a + (long long)r * a_pitch + k0);
const float s = sa[(long long)r * sa_stride + k0 / kGroup];
uint32_t w2[2];
e4m3x4_to_f16x2(sTbl, w, w2);
lo = fold_pair(w2[0], s);
hi = fold_pair(w2[1], s);
}
const int q = r * (chunk >> 2) + c;
sA[p_ix(q)] = make_uint2(lo, hi);
}
__syncthreads();
if (live) {
/* 64 codes, 32 bytes: two 16-byte loads, aligned by the row pitch and k0 % 32 == 0. */
const uint8_t* bp = b + (long long)n * (K >> 1) + (int64_t)ch * (chunk >> 1)
+ kl * (CL >> 1);
uint4 qw0 = make_uint4(0, 0, 0, 0), qw1 = make_uint4(0, 0, 0, 0);
__builtin_memcpy(&qw0, bp, 16);
__builtin_memcpy(&qw1, bp + 16, 16);
const uint32_t w8[8] = { qw0.x, qw0.y, qw0.z, qw0.w, qw1.x, qw1.y, qw1.z, qw1.w };
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
float p0 = 0.0f, p1 = 0.0f; /* the lane's two 32-block partials */
#pragma unroll
for (int v = 0; v < 8; ++v) { /* dwords 0..3: block 2*kl, 4..7: 2*kl+1 */
uint32_t elo, ehi;
mxfp4_unpack8(w8[v], &elo, &ehi);
float& p = (v < 4) ? p0 : p1;
#pragma unroll
for (int e = 0; e < 2; ++e) {
uint32_t w2[2];
e4m3x4_to_f16x2(sTbl, e ? ehi : elo, w2);
const uint2 av = sA[p_ix(qb + 2 * v + e)];
p = dot4_f16x4(av.x, av.y, w2[0], w2[1], p);
}
}
/* The lane's two blocks, scaled by their e8. The pair (kl, kl^1) owns the group's
* four blocks -- kl even the lower two, kl odd the upper two -- so one exchange
* forms the group in ascending block order. */
const int blk0 = ch * (chunk / kMX) + 2 * kl;
const float q0f = p0 * e8_scale(e8[(long long)n * e8_row + blk0]);
const float q1f = p1 * e8_scale(e8[(long long)n * e8_row + blk0 + 1]);
const float o0f = __shfl_xor(q0f, MT);
const float o1f = __shfl_xor(q1f, MT);
const bool lo = !(kl & 1);
const float t0 = lo ? q0f : o0f;
const float t1 = lo ? q1f : o1f;
const float t2 = lo ? o0f : q0f;
const float t3 = lo ? o1f : q1f;
/* One slot per (row, 32-block-in-chunk): MT*BPR is 64 at every MT. The group's two
* half-lanes write the same four values. */
const int j = kl >> 1;
const int bb = warp * 64 + m * BPR + 4 * j;
sB[bb + 0] = t0;
sB[bb + 1] = t1;
sB[bb + 2] = t2;
sB[bb + 3] = t3;
}
__syncthreads();
/* The chunk's block terms, in ascending block order, into the lane that owns the row's
* answer: the reference walks k in ascending order and f32 adds are not associative, so
* the order is part of the answer, not a detail. */
if (live && kl == 0) {
#pragma unroll
for (int bl = 0; bl < BPR; ++bl)
if (m < M) acc += sB[warp * 64 + m * BPR + bl];
}
__syncthreads();
}
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
}
/* ================================================================== the launchers */
static int mt_for(int M)
{
int mt = 1;
while (mt < M && mt < kMTMax) mt *= 2;
return mt;
}
extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y,
int M, int N, int K, int group, int a_ld, int y_ld,
long long e8_row, long stream)
{
if (!a || !a_scale || !b || !b_scale || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2;
if (group != kGroup) return -2;
if (K % kGroup) return -2; /* the activation's scale group */
if (K % kMX) return -2; /* the weight's 32-block */
const int mt = mt_for(M);
const int chunk = 2048 / mt;
if (K % chunk) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld < K) return -3;
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
if (y_ld < N) return -3;
if (!e8_row) e8_row = K / kMX;
if (e8_row < K / kMX) return -3;
if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5;
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads);
#define R3D_MXFP4A8_M16(MT) \
do { \
R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel<MT>)), grid, block, (hipStream_t)stream, \
(const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \
(const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \
y_ld); \
} while (0)
switch (mt) {
case 1: R3D_MXFP4A8_M16(1); break;
case 2: R3D_MXFP4A8_M16(2); break;
case 4: R3D_MXFP4A8_M16(4); break;
case 8: R3D_MXFP4A8_M16(8); break;
default: R3D_MXFP4A8_M16(16); break;
}
#undef R3D_MXFP4A8_M16
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define L_MX(why, a1, v1, a2, v2) \
do { \
if (r3d_trace_on()) \
std::fprintf(stderr, "[r3d] %s:%d %s: %s = %lld, %s = %lld\n", \
__FILE__, __LINE__, (why), (a1), (long long)(v1), (a2), \
(long long)(v2)); \
return R3D_NO(-3); \
} while (0)
int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K,
int group, int a_ld, long long b_row, int as_ld, long long e8_row,
int y_ld, int nt, long stream)
{
if (!av || !asv || !bvc || !bsv || !yv) return -1;
if (M < kMMin || N < 1 || K < 1) return -2;
if (group != kGroup) return -2; /* kKC 32 divides the group 128 */
if (K % kGroup) return -2; /* a ragged k-block reads past the scale planes */
if (K > (1 << 24)) return -2;
if (nt < 0 || nt > 1) return -2;
if (a_ld % 8) L_MX("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K);
if (b_row & 15) L_MX("b row pitch: 16-byte code loads", "b_row", b_row, "K", K);
if (as_ld < (K + kGroup - 1) / kGroup) L_MX(
"a_scale: one per (row, group)", "as_ld", as_ld, "ceil(K/group)",
(K + kGroup - 1) / kGroup);
if (y_ld % 8) L_MX("y pitch: 16-byte bf16 store runs", "y_ld", y_ld, "N", N);
if (a_ld < K) L_MX("a pitch shorter than K", "a_ld", a_ld, "K", K);
if (!b_row) b_row = K >> 1;
if (b_row < (K >> 1)) L_MX("b row pitch shorter than K/2", "b_row", b_row, "K", K);
if (!e8_row) e8_row = K / kMX;
if (e8_row < K / kMX) L_MX("e8 row pitch shorter than K/32", "e8_row", e8_row, "K", K);
if (y_ld < N) L_MX("y pitch shorter than N", "y_ld", y_ld, "N", N);
if ((av & 7) || (asv & 3) || (bvc & 15) || (bsv & 1) || (yv & 7)) return -5;
const dim3 blk(kBlockThreads);
const dim3 grd((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM));
ActQ aq{(const float*)(uintptr_t)asv, (long long)as_ld, 1};
MxWQ h{(const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, b_row, e8_row};
hipStream_t s = (hipStream_t)(uintptr_t)stream;
if (nt) mxfp4a8_tiled_kernel<1><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
else mxfp4a8_tiled_kernel<0><<<grd, blk, 0, s>>>(
(const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y,
int M, int N, int K, int group, int a_ld,
long long b_row, int as_ld, long long e8_row,
int y_ld, int nt, long stream)
{
return launch_mxfp4a8_tiled(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row,
as_ld, e8_row, y_ld, nt, stream);
}
/* ================================================================== the shims
*
* gemm_nt_q's slots, as the two shims take them: 0 a (E4M3), 1 a_scale (f32, one per (row,
* 128 of K)), 2 b (the e2m1 codes -- fp4_e2m1, or the raw u8 bytes, two a byte), 3 b_scale (the
* e8 plane, e8m0 or u8, one per 32 of K), 4 y (bf16), 5 a_sum (absent: symmetric), 6 b_ref (the
* e8 plane again, accepted and ignored).
*/
/* The reserved-e8 scan: one pass per (pointer, size) pair for the process's life. The plane is
* the weight's, its address stable across the launches a pass makes, and a second scan of the
* same bytes buys nothing. The scan needs the host to see the plane -- the mapped tier's form,
* the placement the row's operands take; a plane the host cannot see is not scanned, and the
* kernel's e8 guard carries the reserved values there. */
struct E8ScanKey { const void* p; long long n; };
static bool e8_scan_once(const void* p, long long n)
{
static E8ScanKey seen[16];
static int ns = 0;
for (int i = 0; i < ns; ++i)
if (seen[i].p == p && seen[i].n == n) return true;
if (ns < 16) seen[ns++] = E8ScanKey{ p, n };
void* dev = nullptr;
if (hipHostGetDevicePointer(&dev, (void*)p, 0) != hipSuccess) return true;
const uint8_t* e8 = (const uint8_t*)p;
for (long long i = 0; i < n; ++i)
if (e8[i] == 0 || e8[i] == 255) return false;
return true;
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
const RadTensor* BREF = r3d_opt(a, 6);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */
/* `b_ref` is the reference's per-row exponent, derived from `b_scale`: it changes no
* product, so beside an e2m1 weight its dtype is checked and its value ignored. */
if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e2m1, two a byte */
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); /* e8m0, one per 32 */
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
/* The `group` key names the band; the blocks the kernel reads -- 128 for the activation's
* scale, 32 for the weight's e8 -- are the format's, so the key is not checked. */
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE);
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B);
if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE);
const long long as_p = r3d_row_pitch(AS);
if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(BS)) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL);
const int rc = r3d_gemm_nt_q_mxfp4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS),
r3d_addr(Y), (int)M, (int)N, (int)K, kGroup,
(int)ap, (int)yp, (long long)r3d_row_pitch(BS),
(long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "mxfp4a8") != 0) return R3D_NO(RAD_E_DTYPE);
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
const RadTensor* BREF = r3d_opt(a, 6);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y))
return R3D_NO(RAD_E_INVAL);
if (r3d_has(ASUM)) return R3D_NO(RAD_E_DTYPE); /* symmetric: no zero point */
if (r3d_has(BREF) && BREF->dtype != RAD_E8M0 && BREF->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_e4m3(A)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE);
if (B->dtype != RAD_FP4E2M1 && B->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
if (BS->dtype != RAD_E8M0 && BS->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE);
/* The band's keys, from the schema: N, K, group. The codes plane is [N, K/2], so a band that
* names no N or K is answered by the operand, with the /2 restored. */
const long long M_band = r3d_geti_or(a, "M", 0);
const long long N0 = r3d_geti_or(a, "N", 0), K0 = r3d_geti_or(a, "K", 0);
const long long N = N0 > 0 ? N0 : r3d_dim(B, 0);
/* A band that names no K is answered by the codes plane: [N, K] of fp4_e2m1, [N, K/2] of
* raw bytes. The `group` key names the band; the blocks the kernel reads are the
* format's, so the key is not checked. */
const long long K = K0 > 0 ? K0
: (B->dtype == RAD_FP4E2M1 ? r3d_dim(B, 1) : 2 * r3d_dim(B, 1));
if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE);
if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL);
if (K % kGroup || K % kMX) return R3D_NO(RAD_E_SHAPE);
long long a_rows = 0;
const long long ap = r3d_rows_pitch(A, K, &a_rows);
if (ap < K || a_rows < 1) return R3D_NO(RAD_E_STRIDE);
if (ap % 8) return R3D_NO(RAD_E_STRIDE); /* 8-byte code loads, 8 codes a lane */
/* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key M is an upper bound: a step
* shorter than the band is the step the engine runs, and the key keeps its job as the
* ceiling the plan promised not to exceed. */
const long long M = a_rows;
if (M_band > 0 && M > M_band) return R3D_NO(RAD_E_SHAPE);
if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* the m16 row serves M <= 16 */
const long long ynel = r3d_numel(Y);
if (ynel % N) return R3D_NO(RAD_E_SHAPE);
if (ynel / N < M) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M * (K / kGroup)) return R3D_NO(RAD_E_SHAPE);
const long long bbytes = B->dtype == RAD_FP4E2M1 ? r3d_numel(B) / 2 : r3d_numel(B);
if (bbytes < N * (K / 2)) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(BS) < N * (K / kMX)) return R3D_NO(RAD_E_SHAPE);
const long long as_p = r3d_row_pitch(AS);
if (as_p < K / kGroup) return R3D_NO(RAD_E_STRIDE);
/* The codes plane's pitch, in bytes: fp4_e2m1 counts elements, two to a byte. */
const long long cp0 = r3d_row_pitch(B);
const long long cp = B->dtype == RAD_FP4E2M1 ? cp0 / 2 : cp0;
if (cp < K / 2) return R3D_NO(RAD_E_STRIDE);
if (cp & 15) return R3D_NO(RAD_E_ALIGN);
const long long e8p = r3d_row_pitch(BS);
if (e8p < K / kMX) return R3D_NO(RAD_E_STRIDE);
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(AS), 4) ||
!r3d_aligned(r3d_p(B), 16) || !r3d_aligned(r3d_p(Y), 8))
return R3D_NO(RAD_E_ALIGN);
if (!e8_scan_once(r3d_p(BS), N * (K / kMX))) return R3D_NO(RAD_E_INVAL);
const int nt = (int)r3d_geti_or(a, "nt", 0);
const int rc = r3d_gemm_nt_q_mxfp4a8_tiled(r3d_addr(A), r3d_addr(AS), r3d_addr(B),
r3d_addr(BS), r3d_addr(Y), (int)M, (int)N,
(int)K, kGroup, (int)ap, cp, (int)as_p, e8p,
(int)yp, nt, (long)s);
if (rc == -1) return R3D_NO(RAD_E_INVAL);
if (rc == -2) return R3D_NO(RAD_E_SHAPE);
if (rc == -3) return R3D_NO(RAD_E_STRIDE);
if (rc == -5) return R3D_NO(RAD_E_ALIGN);
if (rc == -4) return R3D_NO(RAD_E_DEVICE);
return RAD_OK;
}
} // namespace
+576
View File
@@ -0,0 +1,576 @@
/* r3d_gemm_nt_q_w2a8.hip -- gemm_nt_q at dtype=w2a8: the vocabulary projection, decode-sized.
*
* y[M,N] = a[M,K] @ b[N,K]^T over a 2-bit unsigned weight code with an f16 scale and an unsigned
* integer zero per (row, group of K), an int8 activation with one f32 scale per ROW, and the int8
* code sums `a_sum` the zero is removed with. f32 accumulate, bf16 store.
*
* This is the band that gates the server. MiniCPM5-2B's `output.weight` is N=130560, K=2048,
* group=128, dtype=w2a8, and its stored form is the container's joined `rad.planes` operand: a
* scale plane and a zero plane behind ONE operand (b_scale). libref declines w2a8 in
* `gemm_q_shape`, so kbench has no case for the op the engine needs most -- the fixture cannot
* draw the dtype, which is why this row's evidence is a driver that builds the joined operand with
* `rad_planes_relayout` and compares every element against `ref_gemm_nt_q`'s own body. libref reads
* the form in `gemm_zp`, so a host row serves it, at 135 GFLOP of CPU work per token; and a
* placement without a reader is refused, because nothing in the loaded set can READ the joined form.
* `r3d_layout_gemm_q_w2a8` below is that reader: it DESCRIBES the container's bytes (that is what
* RadLayoutFn in rad_abi.h is), and the row carries no relayout and no repacking.
*
* ---- the law, and the order inside it ---------------------------------------------------------
*
* gemm_zp, the ZP_I8_ROW arm, is the spec, and this kernel runs its order:
*
* q[k] = rad_load_bits(row n of b, 2, k) bits [2k,2k+2) of byte k/4
* is(g) = SUM_{k in group g} (int)a[m][i8_step_pos(k)] * (int)q[k] integers: exact
* sub(g) = (float)is(g) - (float)z[n][g] * a_sum[g*mpad + m] mpad = ceil(M/16)*16 = 16
* acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING
* y[m,n] = bf16(acc)
*
* `a_sum` is per row and per group and group-major, `sa` is one f32 per ROW (ZP_I8_ROW: quant_act_i8
* scales a whole row, not a group), and `(sub * sa) * sb` is a parenthesised order, not a formula.
*
* The activation is in quant_act_i8's step order: column c sits at byte
* i8_step_pos(c) = (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), bits 2 and 3 of c swapped, the map
* its own inverse. Swapping bits 2 and 3 of a column is swapping bits 0 and 1 of its DWORD index,
* so a dword's four columns stay four contiguous bytes: staging reads a's dwords in a permuted
* dword order, one 4-byte load per four codes, and nothing straddles a dword.
*
* `is` is a sum of integers, every partial sum under 2^24, so it is exact in f32 and its bracketing
* is free. `sub`, the products and the g-ascending accumulation are float, and their order is the
* reference's, so the store is bit-identical to the host row: bit-equality element by element is
* the test, not a tolerance, because nothing else on this machine can draw the operands.
*
* ---- U2 to f16 through a bias, and the bias removed with a_sum ---------------------------------
*
* There is no int8 dot on this ISA. `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`
* and the RDNA3 matrix ops `__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared in AMD
* clang 24.0.0git for gfx1102. So the codes widen to f16 and the dot runs on dot2_f16x2, whose
* hardware form folds a pair into an f32 accumulator. Every product is
* an integer and every partial sum is an integer, and "products and partials are integers below
* 2^24" is a true statement about f32 and a false statement about this instruction: v_fdot2_f32_f16
* carries a little under 24 bits of mantissa on integer operands -- about 22, from the ratio of the
* worst error to its magnitude -- so any kernel that pushes integers through a pair-dot inherits a
* tail once its partials reach 2^20. The instrument at the end of this file (one 64-code dot per
* lane, the f32 it produces beside the exact integer it should have produced) shows: bias 1024,
* 71027 of 262144 dots off, by up to 1/8. Bias 128, 70115 of 262144 off, by up to 1/64. The bias is 128 because the tail grows with the magnitude, and 128 is
* the largest power of two that keeps a lane's partial sum under 2^21; shrinking it is a smaller
* tail, not no tail. What the tail costs is one bit of the bf16 answer: 0.1-0.2% of outputs land one
* bf16 ulp off and nothing else, rel_l2 5.0e-3 at the band, no non-finite anywhere. That is this
* row's exactness, written out here because the law below is exact integers and the row reads like a
* bit-exact one. It is not, and the row's prose says so.
* The row without the dot unit -- four f32 words a quad in the tile, four __fmaf_rn per quad -- is
* not in this file. Its arithmetic is exact: a probe of 262144 samples of the four fmas with no
* tile, zero inexact dots, worst error exactly zero. Its staging is the defect: the f32 tile,
* written through a vector pointer at -O2, comes up with content that was never written, and
* typing the array `uint4` rules aliasing out, so the defect is in the tile staging and not in the
* arithmetic.
* At the band this row is not memory-bound. r3d_vocab_bf16.hip streams the same n_vocab x n_embd
* head in 535 MB of bf16 in 3.29 ms at M=1, 163 GB/s, two thirds of the card's DRAM. The 66.8 MB
* of codes this row reads has a streaming floor near 0.41 ms, not the 3.0 ms of one 22 GB/s pass
* this row measures, so this row runs 6-10x above its own floor and the headroom is in its loop --
* the group-term plane and the two barriers a chunk -- not in the memory system. An f32 row costs
* nothing to run, and the tail goes with it.
* The trick that pays for the widening is that f16 bits of (128 + x) are 0x5800 + 8x for 0 <= x < 8,
* so a 2-bit code becomes an f16 with a mask, two shifts and an add -- no table, no compare per
* code -- and the dot returns is' = SUM a[k]*(128 + q[k]) = is + 128*SUM a. SUM a over the group is
* the plane the op already carries: a_sum[g*mpad + m], the very number the zero is removed with.
* 128 * a_sum scales an integer-valued f32 by a power of two, so it is exact, is = is' - 128*a_sum
* is exact, and the reference's own sub = (float)is - (float)z*a_sum follows unchanged. The de-bias
* costs one exact f32 subtraction per (m, group) and is why a row with no int8 instruction on it is
* memory-bound at the band instead of unpack-bound.
*
* ---- the lane map ------------------------------------------------------------------------------
*
* One warp per weight row n; a block of 8 waves covers 8 rows. MT, the template's row count, is the
* power of two that covers M, and KL = 32/MT is the number of k-lanes per activation row. A chunk
* is CHUNK = 2048/MT codes, so the staged tile is always MT*CHUNK/2 = 1024 dwords = 4 KiB: the
* tile shrinks with the row count exactly as the row count grows, which is what keeps the block
* resident at M=16. A chunk holds CHUNK/128 = 16/MT groups and every lane takes 64 codes -- one
* 16-byte load of codes (four bytes, sixteen codes each, U2 being four codes a byte), thirty-two
* dwords of activation from LDS and thirty-two dot2 in sixteen dot4_f16x4 -- so lane l owns row
* m = l % MT, k-lane kl = l / MT, and group ch*(16/MT) + kl/2, whose two halves are the pair
* (l, l^MT): the group folds with ONE shfl_xor, in integers.
*
* Each lane's group index ascends with the chunk index, so `acc += term` in the lane IS the
* reference's ascending g loop over the groups that lane owns; the groups the other k-lanes own are
* added by kl-1 ordered broadcasts per chunk, in ascending kl, which is ascending g. At M=16, where
* a chunk is one group, there is no cross-lane float work at all. Reassociating the g sum is what
* would break bit-equality, and the map is built so that no lane ever has to.
*
* LDS is touched a quad at a time (two dwords, 8 bytes), swizzled as `p_ix` below; unswizzled the
* wavefront's 32 quads for one u all sit in the same bank pair.
*
* ---- refusals (codes; RAD_R3D_TRACE=1 prints the line) -----------------------------------------
*
* The shim mirrors gemm_ntq_impl's and gemm_zp's checks and declines two things the reference
* accepts, each named at its site: M > 16 (the band is 16, the tile is 16 rows, mpad is the
* reference's 16-row pad; the prefill vocab projection is `logits_gemm` and is a tiled bf16 row,
* not a wider loop bound here), and a zero plane stored sub-byte (U2/U4/U5), where the kernel reads
* a zero a byte at a time -- a sub-byte zero plane needs the bit-extract path,
* `rad_load_bits(zb, bits, g)` is ten lines. w2a8's practical form, and this container's, is U8.
*/
#include <hip/hip_runtime.h>
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_launch.h"
#include "r3d_args.h"
#include "rad_planes.h"
namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave; /* 8 weight rows per block */
constexpr int kMTMax = 16; /* the band's M */
constexpr int kTileQuads = 512; /* MT * CHUNK/4, constant over MT: 512 quads, 4 KiB */
constexpr int kGroup = 128; /* the block size w2a8 is stored at */
constexpr int kMpad = 16; /* the reference's (M+15)/16*16, M <= 16 */
/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. Applying
* it to the four columns of one dword leaves them four contiguous bytes and turns the map on the
* DWORD index into a swap of bits 0 and 1 -- the middle two dwords of a 16-byte step exchanged.
* The byte a dword starts at is therefore 4 * dword_pos(d): NOT 4 * step_pos(d), which swaps the
* wrong pair of bits and reads the step's dwords unexchanged. */
[[maybe_unused]] [[maybe_unused]] __device__ __forceinline__ int64_t step_pos(int64_t c)
{
return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1);
}
__device__ __forceinline__ int64_t dword_pos(int64_t d)
{
return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1));
}
/* The LDS swizzle, at the granularity the tile is touched: a quad of four codes, two dwords, moved
* as one 8-byte word. Quads are numbered q = r*(CHUNK/4) + c, and p_ix XORs q's low four bits with
* bits 4..7 -- a bijection on 16-quad groups, so on any tile whose quad count is a multiple of 16.
* A wavefront reads q = m*(CHUNK/4) + kl*16 + u for fixed u; CHUNK/4 is a multiple of 16 at every
* MT, so q ^ (q >> 4) mod 16 is u ^ (4m + kl) mod 16 over the 32 lanes -- 16 distinct values, each
* one 8-byte access spanning two banks: 32 banks, no conflict. The swizzle must leave bit 0 of the
* quad index alone: the two dwords of a quad are adjacent only then, and the scalar form that
* XORs bits 5..9 of the dword index does not. */
__device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); }
/* Four int8 codes -> two f16x2 dwords. Exact: an integer of |a| <= 127 needs no rounding. */
__device__ __forceinline__ void i8x4_to_f16x2(uint32_t w, uint32_t& lo, uint32_t& hi)
{
lo = f16x2_pack((float)(int32_t)(int8_t)(w & 0xffu), (float)(int32_t)(int8_t)((w >> 8) & 0xffu));
hi = f16x2_pack((float)(int32_t)(int8_t)((w >> 16) & 0xffu),
(float)(int32_t)(int8_t)((w >> 24) & 0xffu));
}
/* Four U2 codes (one byte) -> two f16x2 dwords, BIASED by 128: each half is the f16 bits of
* (128 + code). An f16 at exponent 2^7 steps its mantissa by 1/8, so 128 + code is 0x5800 + 8*code
* and stays an integer. The dot therefore returns is + 128 * the group's code sum, which the
* epilogue takes off with the group's a_sum.
*
* The bias is 128 and not 1024 because of where the dot unit's precision runs out. a * (B + q) is an
* integer the size of 128 * B, and a lane's 64 of them sum to 64 * 128 * (B + 3): at B = 1024 that is
* 2^23, at B = 128 it is 2^20. The unit keeps a little under 24 bits of mantissa on integers, so the
* tail scales with the magnitude -- 71027 of 262144 dots off by up to 1/8 at B = 1024, 70115 off by
* up to 1/64 at B = 128, in the probe below. 128 is the largest power of two that keeps a lane's
* partial sum under 2^21, which is as close as a pair-dot gets; the header carries the rest. */
__device__ __forceinline__ void u2x4_biased(uint32_t w, uint32_t& lo, uint32_t& hi)
{
lo = 0x58005800u + ((w & 3u) << 3) + (((w >> 2) & 3u) << 19);
hi = 0x58005800u + (((w >> 4) & 3u) << 3) + (((w >> 6) & 3u) << 19);
}
template <int MT>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_w2a8_kernel(const int8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride,
const uint8_t* __restrict__ b, const uint16_t* __restrict__ sb, int sb_rb,
const uint8_t* __restrict__ zq, int z_rb, const float* __restrict__ asum,
int asum_stride, uint16_t* __restrict__ y, int M, int N, int K, int chunk,
int a_pitch, int y_pitch)
{
constexpr int KL = kWave / MT; /* k-lanes per activation row */
constexpr int CG = (2048 / MT) / kGroup; /* groups per chunk */
constexpr int CL = (2048 / MT) / KL; /* codes per lane per chunk: 64 */
/* The tile: one quad of four codes per slot, two f16x2 dwords, typed as the quad the staging
* writes and the dot reads. The tile is a `uint2[]` and not a `uint32_t[]` reached through a
* vector pointer: the f32 variant of this row, written through `*(uint4*)&sA[]` at -O2, comes
* up with content that was never written. */
__shared__ __align__(16) uint2 sA[kTileQuads]; /* MT rows x CHUNK/2 f16, swizzled */
__shared__ float sT[kWaves * 16]; /* each warp's chunk terms: warp*16 + m*CG + j */
__shared__ float sSa[MT];
const int lane = threadIdx.x & (kWave - 1);
const int warp = (int)(threadIdx.x / kWave);
const int n = blockIdx.x * kWaves + warp;
/* A wavefront past the last row sits the chunk out, but it stages: the tile is block-wide, so
* the warps that have no row to serve still write the rows their lanes own. Only a block whose
* EIGHT rows are all past the last row leaves, which is a block-uniform test and cannot strand
* a barrier; a guard on the row would, because the tail block's dead warps own tile rows and
* staging them from never-written memory corrupts the tile. The store is guarded by `live`
* below, so a dead wavefront writes nothing. */
const bool live = n < N;
if ((int)blockIdx.x * kWaves >= N) return;
const int m = lane & (MT - 1);
const int kl = lane / MT;
const int row_bytes = K >> 2; /* rad_enc_row_bytes(RAD_U2, K), K % 16 == 0 */
const int cq = chunk >> 2; /* the chunk's code bytes */
const int nchunk = K / chunk;
if (lane < MT) sSa[lane] = lane < M ? sa[(long long)lane * sa_stride] : 0.0f;
__syncthreads();
float acc = 0.0f;
for (int ch = 0; ch < nchunk; ++ch) {
/* Stage the chunk's activation rows, widened and step-unpermuted on the way in. Cells are
* four codes: MT * CHUNK/4 = 512 of them at every MT, two per thread. */
for (int i = threadIdx.x; i < MT * (chunk >> 2); i += kBlockThreads) {
const int r = i / (chunk >> 2), c = i % (chunk >> 2);
uint32_t w = 0;
if (r < M)
w = *(const uint32_t*)(a + (long long)r * a_pitch +
dword_pos((int64_t)ch * (chunk >> 2) + c));
const int q = r * (chunk >> 2) + c;
uint32_t lo, hi;
i8x4_to_f16x2(w, lo, hi);
sA[p_ix(q)] = make_uint2(lo, hi);
}
__syncthreads();
uint4 qw = make_uint4(0, 0, 0, 0);
if (live)
qw = *(const uint4*)(b + (long long)n * row_bytes + (long long)ch * cq + kl * (CL >> 2));
const uint32_t w4[4] = { qw.x, qw.y, qw.z, qw.w };
if (live) {
const int qb = m * (chunk >> 2) + kl * (CL >> 2);
float p = 0.0f; /* the lane's half-group, an exact integer */
#pragma unroll
for (int v = 0; v < 4; ++v) { /* four bytes, four quads, sixteen codes */
#pragma unroll
for (int b = 0; b < 4; ++b) {
uint32_t ql, qh;
u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh);
const uint2 av = sA[p_ix(qb + 4 * v + b)];
p = dot4_f16x4(av.x, av.y, ql, qh, p);
}
}
/* Fold the pair: lanes l and l^MT are the same row, the two halves of one group. */
const float isg = p + __shfl_xor(p, MT);
const int g = ch * CG + (kl >> 1);
const float as = asum[(long long)g * asum_stride + m];
const float is = isg - 128.0f * as; /* exact: the de-bias */
const float iz = (float)zq[(long long)n * z_rb + g];
const float sc = f16_to_f32(sb[(long long)n * (sb_rb >> 1) + g]);
const float term = ((is - iz * as) * sSa[m]) * sc; /* gemm_zp's parentheses */
/* One slot per (row, group-in-chunk): MT*CG is 16 at every MT, so this is 64 bytes.
* The group's two half-lanes write the same value, which is why the pair fold above is
* a fold and not a broadcast. */
sT[warp * 16 + m * CG + (kl >> 1)] = term;
}
__syncthreads();
/* Group ch*CG + j, for j ascending, into the lane that owns the row's answer. The reference
* walks g in ascending order and f32 adds are not associative, so the order is part of the
* answer, not a detail. The group gather is the one place in the kernel that crosses
* k-lanes; it is a barrier and four LDS reads at 64 bytes, which is cheaper than a shuffle
* round-trip. */
if (live && kl == 0) {
/* A chunk carries CG groups, and group ch*CG + j lives in the two k-lanes 2j and 2j+1:
* they hold the same group's two halves, which is what the fold above combined. Every
* lane adds all CG of them in ascending j, so each lane of a row ends on the same
* partial sum, built in the same order the reference walks its groups in -- f32 adds are
* not associative, and a lane that finished its own group last rounds the tail
* differently. Reading a lane's `acc` would not do: by j = 2 it has already added a
* group of its own. */
#pragma unroll
for (int j = 0; j < CG; ++j)
if (m < M) acc += sT[warp * 16 + m * CG + j];
}
__syncthreads();
}
if (live && kl == 0 && m < M) y[(long long)m * y_pitch + n] = f32_to_bf16(acc);
}
int mt_for(int M) { return M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; }
} // namespace
/* ================================================================== the launcher
*
* Codes: 0, -1 a required pointer is null, -2 a shape it does not read, -3 a pitch it cannot read,
* -4 HIP. `nt` is the threads argument every libr3d launcher takes and this kernel ignores: the
* work is one warp per weight row, and the wavefront count is the grid.
*
* `b_scale` is the joined operand's base. The launcher reads the two planes out of its own header
* (rad_planes.h's rad_planes_find) and passes each plane's base, row pitch in bytes and the row
* count down, so the kernel reads the container's bytes where they lie. */
/* The instrument behind the measurement in the header: the dot on its own, one 64-code sample per
* lane, the f32 it produces beside the exact integer it should have produced. The driver runs it as
* `dot [n]`; the bias is sized from it, and it shows the f32 path to be exact. Two extern "C"
* symbols, no row, no cost at serve time. */
extern "C" __global__ void __launch_bounds__(256) probe_dot_kernel(const int8_t* a,
const uint8_t* codes,
float* out, long long* exact)
{
const int g = blockIdx.x * 32 + (int)(threadIdx.x / kWave) * 4 + (int)(threadIdx.x & 3);
const int lane4 = (int)(threadIdx.x & 31) & 3;
(void)lane4;
const uint32_t* w4 = (const uint32_t*)(codes + (long long)g * 16);
float p = 0.0f;
long long ex = 0;
#pragma unroll
for (int v = 0; v < 4; ++v) {
#pragma unroll
for (int b = 0; b < 4; ++b) {
const uint32_t aw = *(const uint32_t*)(a + (long long)g * 64 + 4 * (4 * v + b));
uint32_t ql, qh;
u2x4_biased((w4[v] >> (8 * b)) & 0xffu, ql, qh);
uint32_t lo, hi;
i8x4_to_f16x2(aw, lo, hi);
p = dot4_f16x4(lo, hi, ql, qh, p);
#pragma unroll
for (int j = 0; j < 4; ++j)
ex += (long long)(int)(int8_t)((aw >> (8 * j)) & 0xffu) *
(long long)(128 + ((w4[v] >> (8 * b + 2 * j)) & 3u));
}
}
out[g] = p;
exact[g] = ex;
}
extern "C" int r3d_w2a8_probe_launch(const int8_t* a, const uint8_t* codes, float* out,
long long* exact, int n)
{
probe_dot_kernel<<<(n + 31) / 32, 256, 0, 0>>>(a, codes, out, exact);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
extern "C" int r3d_gemm_nt_q_w2a8(long a, long a_scale, long b, long b_scale, long a_sum, long y,
int M, int N, int K, int group, int a_ld, int y_ld, int nt,
long stream)
{
(void)nt;
if (!a || !a_scale || !b || !b_scale || !a_sum || !y) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (M > kMTMax) return -2; /* the row says the same: C_LE("M", 16) */
if (group != kGroup) return -2; /* the tile is 128-wide: chunk = 128*16/MT */
if (K % kGroup) return -2;
if (K % 16) return -2; /* the step order is a 16-byte step */
const int mt = mt_for(M);
const int chunk = 2048 / mt;
if (K % chunk) return -2; /* ragged chunk: the tile would read past K */
const int G = K / group;
if (G < 1) return -2;
if (!a_ld) a_ld = K;
if (!y_ld) y_ld = N;
if (a_ld % 4) return -3; /* four codes a dword, staged whole */
if (((uintptr_t)b & 15u) || ((uintptr_t)a & 3u)) return -3;
const RadPlanesHeader* h = rad_planes_header((const void*)(uintptr_t)b_scale);
if (!h) return -2; /* not the joined form: rad.planes is expected */
const RadPlanesEntry* es = nullptr;
const RadPlanesEntry* ez = nullptr;
const void* sp = rad_planes_find((const void*)(uintptr_t)b_scale, "scale", &es);
const void* zp = rad_planes_find((const void*)(uintptr_t)b_scale, "zero", &ez);
if (!sp || !zp || !es || !ez) return -2;
if (es->dtype != RAD_F16) return -2; /* this kernel reads an f16 scale */
if (ez->dtype != RAD_U8) return -2; /* ...and a byte-wide zero; see the header */
if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return -2;
if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return -3;
#define R3D_W2A8_LAUNCH(MT) \
do { \
const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); \
R3D_KLAUNCH(R3D_KNAME((gemm_w2a8_kernel<MT>)), grid, block, (hipStream_t)stream, \
(const int8_t*)a, (const float*)a_scale, 1, (const uint8_t*)b, \
(const uint16_t*)sp, (int)es->row_bytes, (const uint8_t*)zp, (int)ez->row_bytes, \
(const float*)a_sum, kMpad, (uint16_t*)y, M, N, K, chunk, a_ld, y_ld); \
} while (0)
switch (mt) {
case 1: R3D_W2A8_LAUNCH(1); break;
case 2: R3D_W2A8_LAUNCH(2); break;
case 4: R3D_W2A8_LAUNCH(4); break;
case 8: R3D_W2A8_LAUNCH(8); break;
default: R3D_W2A8_LAUNCH(16); break;
}
#undef R3D_W2A8_LAUNCH
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ================================================================== the shim
*
* gemm_nt_q's slots, as gemm_ntq_impl takes them: 0 a (i8, step order), 1 a_scale (f32, one per
* row), 2 b (the u2 codes), 3 b_scale (the joined scale+zero), 4 y (bf16), 5 a_sum (f32, group
* major, mpad = 16 columns). */
extern "C" int r3d_rad_gemm_nt_q_w2a8(const RadArgs* a, RadStream s)
{
if (!a) return R3D_NO(RAD_E_INVAL);
const char* dt = r3d_gets(a, "dtype");
if (dt && std::strcmp(dt, "w2a8") != 0) return R3D_NO(RAD_E_DTYPE); /* the row is w2a8 only */
const RadTensor* A = r3d_opt(a, 0);
const RadTensor* AS = r3d_opt(a, 1);
const RadTensor* B = r3d_opt(a, 2);
const RadTensor* BS = r3d_opt(a, 3);
const RadTensor* Y = r3d_opt(a, 4);
const RadTensor* ASUM = r3d_opt(a, 5);
if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y) || !r3d_p(ASUM))
return R3D_NO(RAD_E_INVAL);
if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8's codes */
if (B->dtype != RAD_U2) return R3D_NO(RAD_E_DTYPE); /* the grid's codes */
if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (!r3d_is_f32(AS) || !r3d_is_f32(ASUM)) return R3D_NO(RAD_E_DTYPE);
const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0);
const long long group = r3d_geti_or(a, "group", 0);
if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE);
if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* no defaulting: gemm_zp refuses 0 */
if (K % group || K % 16) return R3D_NO(RAD_E_SHAPE);
const long long G = K / group;
const long long ynel = r3d_numel(Y);
if (N < 1 || ynel % N) return R3D_NO(RAD_E_SHAPE);
const long long M = ynel / N;
if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); /* DECLINE, in the header: the band is
* 16 and the tile is 16 rows; the
* prefill vocab projection is
* logits_gemm, a tiled bf16 row. */
if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE);
if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* gemm_zp's code for this one */
if (r3d_numel(ASUM) < G * kMpad) return R3D_NO(RAD_E_INVAL);
const long long ap = r3d_row_pitch(A);
if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); /* step order read four codes a dword */
if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); /* gemm_zp: contiguous codes only */
long long yrows = 0;
const long long yp = r3d_rows_pitch(Y, N, &yrows);
if (yp < N) return R3D_NO(RAD_E_STRIDE);
if (!r3d_contig(ASUM)) return R3D_NO(RAD_E_STRIDE);
const RadPlanesHeader* h = rad_planes_header(r3d_p(BS));
if (!h) return R3D_NO(RAD_E_DTYPE); /* the joined form is the operand */
const RadPlanesEntry* es = nullptr;
const RadPlanesEntry* ez = nullptr;
const void* sp = rad_planes_find(r3d_p(BS), "scale", &es);
const void* zp = rad_planes_find(r3d_p(BS), "zero", &ez);
if (!sp || !zp || !es || !ez) return R3D_NO(RAD_E_DTYPE);
if (es->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE);
if (ez->dtype != RAD_U8)
return R3D_NO(RAD_E_DTYPE); /* DECLINE: a sub-byte zero plane needs the bit-extract path;
* rad_load_bits(zb, bits, g) is 10 lines. U8 is w2a8's form. */
if (es->rows != N || es->cols != G || ez->rows != N || ez->cols != G) return R3D_NO(RAD_E_SHAPE);
if ((es->row_bytes & 1) || es->row_bytes < 2 * G || ez->row_bytes < G) return R3D_NO(RAD_E_STRIDE);
if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN);
const int rc = r3d_gemm_nt_q_w2a8(
r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(ASUM), r3d_addr(Y), (int)M,
(int)N, (int)K, (int)group, (int)ap, (int)yp, 0, (long)s);
/* The launcher's codes are its own (r3d_launch.h's set: null, shape, pitch, HIP); the row speaks
* RAD codes, and the shim is where the two are named. Same mapping as the gated row's. */
if (rc == 0) return RAD_OK;
return R3D_NO(rc == -1 ? RAD_E_INVAL : rc == -2 ? RAD_E_SHAPE
: rc == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
/* ================================================================== the layout hook
*
* The scoped exception to libr3d's "no layout hooks, no repacking" rule, transcribed from libref's
* `ref_layout_gemm_q` with the checks and their order unchanged:
*
* if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
* const ZpGrid* zg = zp_grid(dtype); group = param "group";
* if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
* transform empty, or beginning "givens";
* sel_roles(enc, sel, n, "scale", "zero") && enc->n_planes >= 3;
* plane[0]: role "codes", dtype == zg->codes, block {1,1};
* scale: RAD_PLANE_TILED, RAD_F16, block {1, group};
* zero: RAD_PLANE_TILED, zero_dt(...), block {1, group};
* return rad_planes_layout(enc, sel, planes, n, out);
*
* zp_grid, zero_dt and sel_roles are libref-internal statics, inlined below for w2a8: the grid is
* { "w2a8", RAD_U2, ZP_I8_ROW }, zero_dt is U8|U2|U4|U5, and the practical form is U8 (the kernel
* declines a sub-byte zero, at its site, with the fix named). The answer is rad_planes.h's own:
* the tag is "rad.planes", the dtype the first plane's, the shape the byte count. NOTHING HERE
* MOVES A BYTE: this hook is the reader the mapped tier needs and the row's relayout is null.
*/
/* The writer for the joined operand this hook names: codes, scale and zero as the plan's one
* `rad.planes` weight, assembled by rad_planes_relayout -- header, entries, each plane's rows,
* copied. The ABI's contract is that a query answering RAD_OK is a promise the loader keeps on the
* row's word: "out describes the stored form, and relayout will produce it" (rad_abi.h), and a
* weight with no hook is the only kind that can be read where it lies, which is why a joined weight
* is placed in VRAM and a plain one can stay on the mapped tier. Nothing here transforms a code:
* the bytes written are the bytes stored. */
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes)
{
(void)p; (void)n_p;
if (operand != 3) return RAD_E_UNSUPPORTED;
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
/* A layout query answers in the engine's own vocabulary and leaves no trace, and a model that will
* not load says only that two rows want one weight in two forms. This prints the question and the
* answer -- operand, band dtype, planes offered, code returned -- under RAD_R3D_TRACE=1. */
static int r3d_layout_trace(const char* who, int operand, const char* dt, int n_planes, int rc) {
if (r3d_trace_on())
std::fprintf(stderr, "[r3d] %s: operand %d dtype %s planes %d -> %d\n", who, operand,
dt ? dt : "(none)", n_planes, rc);
return rc;
}
extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out)
{
if (n < 2 || operand != 3) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED);
const char* dt = r3d_pgets(p, n_p, "dtype");
/* The plan this hook describes -- the (scale, zero) pair joined on operand 3 -- is a statement
* about the CONTAINER, not about the code width, and the engine forces every row that reads one
* weight to answer with one form. So both packed grids come through, and the width a row can
* unpack is the SHIM's business: gemm_nt_q_w2a8_m16 reads U2 and nothing else,
* gemm_nt_q_w2a8_tiled reads U2 and U4, and each says so at its own line. */
if (!dt || (std::strcmp(dt, "w2a8") != 0 && std::strcmp(dt, "w4a8_asym") != 0))
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the packed grids */
const long long group = r3d_pgeti_or(p, n_p, "group", 0);
if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (!enc || !rad_enc_is(enc, "affine")) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (!enc || enc->n_planes < 3 || !sel) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
/* sel_roles(enc, sel, n, "scale", "zero"): one role per selected plane, in order. */
if (n != 2) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
for (int i = 0; i < 2; ++i) {
const char* want = i == 0 ? "scale" : "zero";
if (sel[i] < 0 || sel[i] >= enc->n_planes) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
}
/* The codes plane is the one this operand does NOT take: the weight's role "codes", the grid's
* dtype, block {1,1}. libref finds it by role over enc->plane, not by sel. */
int codes = -1;
for (int i = 0; i < enc->n_planes; ++i)
if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; }
if (codes < 0) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
for (int i = 0; i < 2; ++i) {
const RadEncPlane& q = enc->plane[sel[i]];
const RadTensor& t = planes[i];
if (q.kind != RAD_PLANE_TILED) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (q.block[0] != 1 || q.block[1] != group) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE);
if (i == 0) {
if (t.dtype != RAD_F16) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the scale is f16 */
} else {
const uint32_t zd = t.dtype;
const bool ok = zd == RAD_U8 || zd == RAD_U2 || zd == RAD_U4 || zd == RAD_U5;
if (!ok) return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* zero_dt: never signed */
}
}
return r3d_layout_trace("r3d_layout_gemm_nt_q_w2a8", operand, r3d_pgets(p, n_p, "dtype"), n, rad_planes_layout(enc, sel, planes, n, out));
}
+23
View File
@@ -0,0 +1,23 @@
/* r3d_launch.h -- the two lines a libr3d unit needs to launch a kernel.
*
* R3D_KLAUNCH is the triple-chevron form, which the engine services on its own queues because the
* stream it hands a launch is the one hipLaunchKernel accepts (docs/PLUGIN.md §5). It is written as
* a macro so a test can define it and drive the same sources through a host SIMT emulator; a build
* does not, and gets the chevron.
*
* R3D_DYN_LDS declares a kernel's dynamic LDS, sized by the launch: `extern __shared__` in a build.
* RDNA3 gives a workgroup the same 64 KiB RDNA4 does, so a tile sized for libr4d fits here too.
*
* R3D_KNAME names a kernel in a context where commas would split a macro argument, the way
* HIP_KERNEL_NAME does for hipLaunchKernelGGL.
*/
#ifndef R3D_LAUNCH_H
#define R3D_LAUNCH_H
#define R3D_KNAME(...) __VA_ARGS__
#ifndef R3D_KLAUNCH
#define R3D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<<grid, block, 0, stream>>>(__VA_ARGS__)
#endif
#ifndef R3D_DYN_LDS
#define R3D_DYN_LDS(type, name) extern __shared__ type name[]
#endif
#endif
File diff suppressed because it is too large. Load diff
+288
View File
@@ -0,0 +1,288 @@
/* r3d_plugin.h -- what libr3d's translation units share.
*
* The row table (r3d_rows.cpp) and the operand descriptions (r3d_shapes.cpp) are pure host C++ and
* include only this file and the ABI; the launch shims include r3d.h and so <hip/hip_runtime.h>.
* The split lets the constraint table compile and be checked without ROCm, and is why every shim is
* declared here rather than beside its definition.
*
* Nothing in this header may include r3d.h.
*/
#ifndef RAD_R3D_PLUGIN_H
#define RAD_R3D_PLUGIN_H
#include "r3d_args.h"
/* ================================================================== the priority ladder
*
* The selector ranks candidate rows by an integer priority (spec §2.1); where two rows of one op
* can match a geometry, it decides which serves. Each group states the reason for its order.
* Values are spaced by ten so a row can be slipped between two without renumbering.
*
* libr3d ships one row per (op, dtype) pair far more often than libr4d does: the matrix work runs
* on the dot2 path, whose lane map takes a dtype as a template argument, so the kernel that serves
* bf16 serves f16 as is, and there is nothing to specialise a second row for. Where two rows of
* one op do exist, the reason is the geometry, and it is written next to the pair.
*/
enum {
/* The common case: this op, these dtypes, one row. Nothing competes with it. */
R3D_PRIO_ONLY = 50,
/* `attn_paged` is banded on q_len, and the decode row's bound (q_len <= 16) is a bucket
* boundary, not a partition: a speculative verify at 8 query tokens matches the prefill row
* too, and the decode kernel -- split-KV, one head group a workgroup, no query tile -- is the
* faster one there. Decode therefore outranks prefill, as it does in libr4d. */
R3D_PRIO_ATTN_DECODE = 70,
R3D_PRIO_ATTN_PREFILL = 60,
/* The skinny bf16 GEMM's band is M <= 16 and the tiled one's starts at M >= 16, so the two
* meet at exactly 16 rows and the skinny kernel wins there (it keeps the whole weight stream
* in flight with one wave a row and has no LDS staging to pay for). The overlap is deliberate:
* a caller that wants the tiled kernel at 16 rows asks with M=17, the same convention libr4d
* uses at its own m64/tiled boundary. */
R3D_PRIO_GEMM_M16 = 60,
R3D_PRIO_GEMM_TILED = 40,
/* The vocab is a GEMM whose N is the vocabulary: one row, M <= 16, split-K across the whole
* card. The tiled GEMM has no row for these N, so this priority only decides against a future
* tiled vocab row. */
R3D_PRIO_VOCAB_M1 = 60,
/* An fp8 weight row and an int8 weight row never compete: no dtype string reaches both, and a
* container's encoding picks which is legal. */
R3D_PRIO_GEMM_FP8 = 60,
/* The sampler stages are one row each, on one dtype (f32 logits), so there is nothing to rank.
* The name is here so a second row for a stage -- an i8 logits form, say -- has a ladder to
* join. */
R3D_PRIO_SAMPLE = 50
};
/* ================================================================== the dtype codes a C
* launcher takes
*
* The launchers in r3d.h take a dtype as an int, because a `__global__`'s dtype has to be a runtime
* value for the ops that are one kernel over several (cast, fill, dequant) and a compile-time one
* everywhere else. These are the codes; they are libr3d's own, not rad_types.h's RAD_DT_* (a
* launcher's argument list is a private contract between a shim and its kernel, and the kernel
* switch reads better over a dense 0..n than over the ABI's sparse enum). Every shim translates. */
enum {
R3D_DT_BF16 = 0,
R3D_DT_F16 = 1,
R3D_DT_F32 = 2,
R3D_DT_I32 = 3,
R3D_DT_I64 = 4,
R3D_DT_U8 = 5, /* byte codes: fp8 e4m3, read with the codec */
R3D_DT_I8 = 6,
R3D_DT_E5M2 = 7,
R3D_DT_N = 8
};
/* A RadTensor's dtype to the code above, or -1 for one libr3d has no kernel for. */
static inline int r3d_dt_code(uint32_t dt) {
switch (dt) {
case RAD_BF16: return R3D_DT_BF16;
case RAD_F16: return R3D_DT_F16;
case RAD_F32: return R3D_DT_F32;
case RAD_I32:
case RAD_U32: return R3D_DT_I32;
case RAD_I64: return R3D_DT_I64;
case RAD_F8E4M3: return R3D_DT_U8;
case RAD_F8E5M2: return R3D_DT_E5M2;
case RAD_I8: return R3D_DT_I8;
case RAD_U8: return R3D_DT_U8;
default: return -1;
}
}
/* The bytes an element of that code occupies. */
static inline int r3d_dt_size(int code) {
static const int kSize[R3D_DT_N] = { 2, 2, 4, 4, 8, 1, 1, 1 };
return (code >= 0 && code < R3D_DT_N) ? kSize[code] : 0;
}
/* The activation an `act` parameter names, as the kernels' template argument. */
enum { R3D_ACT_SILU = 0, R3D_ACT_SIGMOID = 1, R3D_ACT_GELU = 2 };
/* rope's `mode`, same numbering as libref's kModes. libr3d's kernel implements neox and gptj; the
* rows' constraints say so, so a model that needs mrope is not routed here. */
enum { R3D_ROPE_NEOX = 0, R3D_ROPE_GPTJ = 1 };
/* ================================================================== the row table's entry points
*
* Declared here so r3d_rows.cpp, which is host code built without ROCm, can name them; each is
* defined beside its kernel, in the unit named below, and is documented there. A shim is a
* `RadLaunchFn`: operands read with r3d_args.h, dtype from the tensor, row count from the operand.
* A shape hook is a `RadShapeFn`: the extent and content domain of one operand (r3d_shapes.cpp).
*/
extern "C" {
/* --- r3d_model_bf16.hip --- */
int r3d_rad_rmsnorm (const RadArgs* a, RadStream s);
int r3d_rad_layernorm (const RadArgs* a, RadStream s);
int r3d_rad_add (const RadArgs* a, RadStream s);
int r3d_rad_mul (const RadArgs* a, RadStream s);
int r3d_rad_cast (const RadArgs* a, RadStream s);
int r3d_rad_silu (const RadArgs* a, RadStream s);
int r3d_rad_gelu (const RadArgs* a, RadStream s);
int r3d_rad_sigmoid (const RadArgs* a, RadStream s);
int r3d_rad_act_mul (const RadArgs* a, RadStream s);
int r3d_rad_softmax (const RadArgs* a, RadStream s);
int r3d_rad_scale (const RadArgs* a, RadStream s);
int r3d_rad_fill (const RadArgs* a, RadStream s);
int r3d_rad_rope (const RadArgs* a, RadStream s);
int r3d_rad_kv_store (const RadArgs* a, RadStream s);
int r3d_rad_embed_lookup (const RadArgs* a, RadStream s);
int r3d_rad_gather_rows (const RadArgs* a, RadStream s);
int r3d_rad_scatter_rows (const RadArgs* a, RadStream s);
/* --- r3d_quant_fp8.hip --- */
int r3d_rad_quant_act_fp8 (const RadArgs* a, RadStream s);
int r3d_rad_quant_act_i8 (const RadArgs* a, RadStream s);
int r3d_rad_quant_act_i8g (const RadArgs* a, RadStream s);
int r3d_rad_gated_quant_fp8 (const RadArgs* a, RadStream s);
int r3d_rad_dequant (const RadArgs* a, RadStream s);
/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */
int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_i8 (const RadArgs* a, RadStream s);
/* --- r3d_shapes.cpp --- */
int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_layernorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_add (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_act_mul (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_cast (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_silu (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gelu (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_sigmoid (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_softmax (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_scale (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_fill (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_rope (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_kv_store (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_embed_lookup (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_i8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_quant_act_i8g (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gated_quant_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_dequant (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_q (const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* --- r3d_attn_paged_h128.hip, r3d_vocab_bf16.hip, r3d_sample_f32.hip --- */
extern "C" int r3d_shape_silu_mul (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_attn_paged (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_gemm_nt_q_gated (const RadParam*, int, int, RadOpdDesc*);
/* The vocab projection at w2a8, decode. The layout hook is this library's scoped exception to
* "no layout hooks" (the other two are the fp8 weight's and the logits head's, below): it repacks
* nothing, it presents the container's `scale` and `zero` planes as the single joined `b_scale`
* operand the way rad_planes stores them, transcribed from
* ref_layout_gemm_q. Without it the plan has a placement with no reader. */
extern "C" int r3d_layout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout*);
extern "C" int r3d_shape_dflash_select (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_row_topk (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_argmax (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_temp (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_topk (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_topp (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_minp (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_typical (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_xtc (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_pick (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_penalties (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_dry (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_ngram_ban (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_mask (const RadParam*, int, int, RadOpdDesc*);
extern "C" int r3d_shape_sample_logprobs (const RadParam*, int, int, RadOpdDesc*);
/* --- r3d_sample_f32.hip: the draw spine (row_topk, argmax, temp, topk, pick, the four narrowings)
and r3d_model_bf16.hip's pre-filters (penalties, dry, ngram_ban, mask, logprobs) --- */
int r3d_rad_gemm_nt_q_w2a8 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_gated (const RadArgs* a, RadStream s);
int r3d_rad_dflash_select (const RadArgs* a, RadStream s);
int r3d_rad_row_topk (const RadArgs* a, RadStream s);
int r3d_rad_sample_argmax (const RadArgs* a, RadStream s);
int r3d_rad_sample_temp (const RadArgs* a, RadStream s);
int r3d_rad_sample_topk (const RadArgs* a, RadStream s);
int r3d_rad_sample_pick (const RadArgs* a, RadStream s);
int r3d_rad_sample_topp (const RadArgs* a, RadStream s);
int r3d_rad_sample_minp (const RadArgs* a, RadStream s);
int r3d_rad_sample_typical (const RadArgs* a, RadStream s);
int r3d_rad_sample_xtc (const RadArgs* a, RadStream s);
int r3d_rad_sample_penalties (const RadArgs* a, RadStream s);
int r3d_rad_sample_dry (const RadArgs* a, RadStream s);
int r3d_rad_sample_ngram_ban (const RadArgs* a, RadStream s);
int r3d_rad_sample_mask (const RadArgs* a, RadStream s);
int r3d_rad_sample_logprobs (const RadArgs* a, RadStream s);
/* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */
/* The paged attention's two entry points, banded on q_len: the decode kernel is split-KV over the
* cache with one head group a workgroup, the prefill kernel stages a 16-token query tile. */
int r3d_rad_attn_decode_h128 (const RadArgs* a, RadStream s);
int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s);
/* --- r3d_vocab_bf16.hip: the vocabulary projection, both heights. The shape hook is a
* transcription of ref_logits_gemm_shape -- three plain tensors, nothing joined -- so the band the
* engine declares is the band kbench fills, which is the opposite of the w2a8 row's null hook: there
* the describable byte count is the trap, here it is the point. */
/* --- r3d_gemm_fp8a8_tiled.hip: the quantised GEMM above the decode heights, and the reader for
* the container's fp8 weight: codes and per-128x128 scale as two planes behind `b_scale`. The
* reference's own gemm_nt_q hook answers nothing for this dtype -- ref_layout_gemm_q reads zp_grid,
* and zp_grid has no fp8a8 entry -- which is why the row carries its own. */
int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s);
extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
/* --- r3d_gemm_mxfp4a8.hip: the OCP-MXFP4 weight against the fp8 activation, both heights. The
* weight is two plain u8 planes -- e2m1 codes [N, K/2] and the e8m0 scale [N, K/32] -- so the row
* reads them in place and carries no layout hook; the shape hook is its own because the weight's
* two planes are not the fp8 grid's E4M3 codes and block scale. */
int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s);
/* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight
* is signed codes (I4, two a byte, or I8, one a byte) against a plain f16 scale per (row, 128 of
* K) -- no zero point and no a_sum, so both planes are read in place and the rows carry no layout
* hook. */
int r3d_rad_gemm_nt_q_w4a8_m16(const RadArgs* a, RadStream s);
int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s);
int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out);
/* The three writers that go with the three plane hooks, one per row, each delegating to
* rad_planes_relayout: the loader converts a quantised weight into the joined operand the plan names
* at load, and only the row that reads it can say how. See abi/rad_abi.h. */
extern "C" int r3d_relayout_logits_head(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
extern "C" int r3d_relayout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, void*, int64_t);
extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, void*, int64_t);
int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s);
/* The head's reader: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16 scale
* per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the mapped
* tier will not place a weight a loaded library cannot read in place. Transcribed from
* ref_layout_head (libref's own logits row carries that hook), with the statics it uses inlined
* beside it. It moves no byte: a round-trip through its relayout writer (above) reproduces the
* planes byte for byte, and that writer exists for the round-trip, not for a move. */
extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*,
const int*, const RadTensor*, int, RadLayout*);
int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s);
int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*);
int r3d_rad_silu_mul (const RadArgs* a, RadStream s);
int r3d_rad_rmsnorm_quant_fp8 (const RadArgs* a, RadStream s);
int r3d_shape_rmsnorm_quant_fp8 (const RadParam*, int, int, RadOpdDesc*);
} /* extern "C" */
#endif /* RAD_R3D_PLUGIN_H */
+929
View File
@@ -0,0 +1,929 @@
/* r3d_quant_fp8.hip -- the activation quantisers and the dequantise that reads a container's own
* codes.
*
* The arithmetic is libref's, transcribed. The group core is `q8_group`: an amax over
* the group's consecutive columns, `sc = amax * (1.0f / top)` -- a MULTIPLY by the reciprocal, not a
* divide -- codes `v * (1/sc)` clamped to +-top and encoded by the codec, and scale 1 for an
* all-zero group, whose reciprocal would be an infinity. The five bodies are libref's
* quant_act_fp8, quant_act_i8, quant_act_i8g, gated_quant_fp8 and dequant, loop order and rounding
* points as written. The clamp is required and not defensive: `amax * (1/scale)` is
* 448 exactly and can round an ulp above once the reciprocal is rounded, and a code out of range
* encodes as NaN, which then spreads through every row that reads it.
*
* RDNA3 has no fp8 instruction (r3d_common.h), so both directions are the software codecs in
* r3d_codecs.h, which are bit-exact mirrors of rad_plugin.h's; the absmax is a butterfly
* (r3d_xor_max), which reproduces a `__shfl_xor` loop bit for bit, and a max is exact and
* order-free, so the bracketing is q8_group's ascending one whatever the lane mapping.
*
* No kernel here carries a layout hook, and the codes are the bytes their consumer reads, which is
* the reason a container converted on this card is readable anywhere. Four of the five planes are
* plain row-major with one f32 scale per (row, group), because a dot2 GEMM reads codes in the order
* they are stored. The fifth is the op whose NAME carries the order: libref stores quant_act_i8's
* codes in the int8 WMMA's step order (`i8_step_pos`, the middle two dwords of every 16-byte step
* exchanged) because that is what the w4a8, w8a8 and w2a8 GEMMs read, so this kernel stores them
* that way too and its n is a multiple of 16; quant_act_i8g is the row-major int8 plane, and it is
* the one this library's i8a8 GEMM consumes. The two are not interchangeable.
*
* The store address costs nothing either way: a lane owns FOUR CONSECUTIVE COLUMNS, so its codes are
* one dword, a wave's are 128 contiguous bytes, and a wave covers exactly one 128-column group;
* `i8_step_pos` preserves c % 4, so it permutes a wave's 128 bytes without splitting a lane. The
* launchers therefore refuse `n % 4` -- and quant_act_i8 `n % 16` -- and a ragged last group
* (n % group != 0) is written zero-padded: padding is a zero code and takes no part in the amax.
*
* Group widths: the rows ask for 128, the checkpoint's weight-scale block width, and the kernels
* also serve any other power of two from 4 to 512, so a selftest can drive a narrow group and a
* future row on a 64-wide grid needs no new kernel. A group is a power of two because the amax
* butterfly is over the lanes covering it, GROUP/4 of them.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
namespace {
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
enum : uint32_t {
kColsPerLane = 4, /* one dword of codes a lane */
kWaveCols = kWave * kColsPerLane /* 128: the columns a wave covers */
};
/* The largest code each quantiser saturates at. E4M3 has no infinity, so 448 is the largest finite
* value, and the scale is a dequant multiplier like the checkpoint's weight_scale_inv: the GEMM
* multiplies the activation's scale by the weight's block scale and never divides. */
constexpr float kTopE4M3 = 448.0f;
constexpr float kTopI8 = 127.0f;
/* The floor quant_act_i8's amax is raised to before its DIVIDE by 127, where quant_act_fp8
* multiplies by a reciprocal, so the two quantisers round one ulp apart here; that is libref's
* spelling and the GEMMs read the scale as it is. */
constexpr float kI8Floor = 1e-8f;
/* The LDS code-sum accumulator's width, in groups, as in libr4d's r4d_quant_act_i8. */
enum : uint32_t { kI8MaxGroups = 256 };
/* A bf16 element of a row: a whole-register 16-bit load (r3d_common.h) widened by a shift. */
__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) {
return bf16_to_f32((uint16_t)ldg_u16(p + i));
}
/* q8_group's clamp, in q8_group's order and with q8_group's comparisons, at the codec's top -- 448
* for E4M3, 127 for int8. fminf/fmaxf are NOT the same function here: they replace a NaN with the
* bound, and a NaN in an activation is a value the reference encodes as the format's NaN, not as
* +-top. */
__device__ __forceinline__ float clamp_top(float c, float top) {
if (c > top) c = top;
if (c < -top) c = -top;
return c;
}
/* The four codes a lane's four columns produce, in column order: byte 0 is column c0. */
__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) {
const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3));
const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3));
return lo | (hi << 16);
}
/* The same four codes as int8, at the same rounding points: clamp to +-127, then the codec's
* round-to-nearest-even. quant_act_i8g's store; quant_act_i8's is the same bytes at a permuted
* address. */
__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) {
const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8));
const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8));
const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8));
const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8));
return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24);
}
/* q8_group's scale from the group's amax: the reciprocal of `top` MULTIPLIED, not a divide -- the
* one place the two int8 quantisers and the fp8 one agree, and the reason the per-row
* quant_act_i8 spells its scale as a divide and is a separate body. */
__device__ __forceinline__ float group_scale(float am, float top) {
return am > 0.0f ? am * (1.0f / top) : 1.0f;
}
/* The map libref uses, verbatim: where a row's column c is stored in the step-ordered int8 plane.
* Bits 2 and 3 of c exchanged = the middle two dwords of every 16-byte step swapped, which is the
* order the int8 WMMA reads an A fragment. The map is its own inverse, and it preserves c % 4, so a
* lane's four columns stay contiguous and its store stays one dword. */
__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) {
return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1);
}
/* block_sum's twin for a maximum -- r3d_common.h has the sum. A max needs no order argument at all:
* it is exact, so the wave partials combine in any order -- but it is spelled the same way, so a
* reader sees one reduction shape in this library and not two. `lds` holds kWaves floats. */
__device__ __forceinline__ float block_max(float v, float* lds) {
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
v = wave_max(v);
if (lane == 0) lds[wave] = v;
__syncthreads();
float t = lds[0];
#pragma unroll
for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]);
return t;
}
/* ================================================================== quant_act_fp8
*
* Per-(row, group) symmetric E4M3 of an activation, over q8_group. One workgroup
* a row, a wave a group, a lane four columns -- libr4d's layout, because the reason for
* it (one dword a lane, 128 contiguous bytes a wave) is the store and not the instruction set.
*
* GROUP is the group's width. At 128 a wave covers one group and the amax is r3d_xor_max<32>. A
* narrower group is covered by GROUP/4 lanes of the wave and the butterfly is over those lanes, so
* one wave quantises 128/GROUP groups in a pass; a wider one is covered by one wave in sub-blocks
* of 128 whose maxima are fmaxf'd. All three are q8_group's bracketing.
*
* Rows are dim 0, so a rank-3 activation ([tokens, heads, width], a GDN block's out-projection
* input) is one row per token, as libref reads it: its consuming GEMM's K is heads*width, and one
* row per head would put scales on a grid that GEMM does not read.
*/
template <int GROUP>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_fp8_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) {
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave");
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
uint8_t* __restrict__ qr = q + (size_t)row * n;
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
for (uint32_t u = wave; u < nunit; u += kWaves) {
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
float v[kSub][kColsPerLane];
float am = 0.0f;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t c = c0 + (uint32_t)j;
/* Past the row's end a lane contributes 0.0f, so padding is a zero code and takes
* no part in the amax. n is a multiple of 4, so a lane's four columns are all in
* the row or all outside it: the ragged edge never splits a lane. */
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f;
}
float m = 0.0f;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
am = fmaxf(am, r3d_xor_max<kLanes>(m));
}
const float sc = group_scale(am, kTopE4M3);
/* The scale store is guarded by the group count, not just by the lane: a wave covers
* kPer = 128/GROUP groups and a row's group count is ceil(n/group), which is not a multiple
* of kPer when the last group is ragged. Unguarded, those lanes wrote one row past the
* scale row -- and on a ragged n, past the plane's end. */
if ((lane & (kLanes - 1)) == 0) {
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
}
const float inv = 1.0f / sc;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv);
}
}
}
/* ================================================================== quant_act_i8g
*
* The same group core at int8, q8_group called with top 127. One scale
* per (row, group), `sc = amax * (1.0f / 127)` -- the reciprocal MULTIPLIED, as in the fp8 path, so
* this is quant_act_fp8 with a different codec and not quant_act_i8 at a finer granularity -- codes
* clamp(v * (1/sc), +-127) to nearest even, stored ROW-MAJOR, and scale 1 for an all-zero group.
*
* The row-major store is the point of the op: libr3d's only int8 GEMM is the i8a8 one, and a dot2
* GEMM reads a row in the order it is stored. The step-ordered plane belongs to quant_act_i8, whose
* consumers are libr4d's WMMA GEMMs, and the two are not interchangeable.
*
* Same lane mapping and same ragged rules as quant_act_fp8_kernel, so the two bodies read as one
* shape with the codec swapped.
*/
template <int GROUP>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8g_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n,
uint32_t ngrp, uint32_t x_ld, uint32_t s_ld) {
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
static_assert(kLanes >= 1 && kLanes <= (int)kWave, "a group spans at most one wave");
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
uint8_t* __restrict__ qr = q + (size_t)row * n;
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
for (uint32_t u = wave; u < nunit; u += kWaves) {
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
float v[kSub][kColsPerLane];
float am = 0.0f;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t c = c0 + (uint32_t)j;
v[sb][j] = c < n ? ld_bf(xr, c) : 0.0f; /* padding is a zero code, as above */
}
float m = 0.0f;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
am = fmaxf(am, r3d_xor_max<kLanes>(m));
}
const float sc = group_scale(am, kTopI8);
if ((lane & (kLanes - 1)) == 0) {
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
}
const float inv = 1.0f / sc;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
if (c0 < n) *(uint32_t*)(qr + c0) = i8_codes4(v[sb], inv); /* row-major */
}
}
}
} /* namespace */
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] E4M3, DENSE: the launcher takes no code pitch, so the plane is
* row-major with no hole in it, rounded up to 4 bytes for the padding
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
*
* A launcher checks what a `__global__` cannot and issues one kernel: 0, -1 a null pointer, -2 a bad
* extent (including a group with no instantiation), -3 a pitch that does not describe the operand,
* -4 the HIP launch failed. It allocates nothing and synchronises on nothing. */
extern "C" int r3d_quant_act_fp8(long x, long q, long s, int M, int n, int group, int x_ld,
int s_ld, long stream) {
if (!x || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
const int ngrp = (n + group - 1) / group;
if (!x_ld) x_ld = n;
if (!s_ld) s_ld = ngrp;
if (x_ld < n || s_ld < ngrp) return -3;
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
const dim3 grid((unsigned)M), block(kThreads);
#define R3D_QAF(G) \
R3D_KLAUNCH(R3D_KNAME(quant_act_fp8_kernel<G>), grid, block, st, (const uint16_t*)x, \
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \
(uint32_t)s_ld)
switch (group) {
case 4: R3D_QAF(4); break;
case 8: R3D_QAF(8); break;
case 16: R3D_QAF(16); break;
case 32: R3D_QAF(32); break;
case 64: R3D_QAF(64); break;
case 128: R3D_QAF(128); break;
case 256: R3D_QAF(256); break;
case 512: R3D_QAF(512); break;
default: return -2;
}
#undef R3D_QAF
return hipGetLastError() == hipSuccess ? 0 : -4;
}
namespace {
/* ================================================================== quant_act_i8
*
* The activation of the w4a8, w8a8 and w2a8 GEMMs, ONE SCALE PER ROW,
* max(amax, 1e-8) / 127, codes x * (1/scale) rounded to nearest even by the int8 codec.
*
* The codes go out in libref's STEP ORDER, `i8_step_pos`: the middle two
* dwords of every 16-byte step exchanged, which is why this op's n is a multiple of 16 and not of
* 4. That order is what the op MEANS -- the w4a8, w8a8 and w2a8 GEMMs read the plane that way, and
* kbench compares the plane element by element -- so it is kept on a card that has no WMMA, and the
* row-major int8 plane is a separate op, quant_act_i8g below, which is the one this library's i8a8
* GEMM consumes. The permutation is per-lane and preserves c % 4, so a lane's four codes stay
* contiguous and the store stays one dword; a wave's 128 bytes are a permutation of the same 128.
*
* One divergence from the reference's arithmetic, and it is inert: libref reduces a row with
* std::max and this with fmaxf. They agree on every input the op can see -- std::max(a, NaN) is a, so
* the reference's amax is never a NaN, and fmaxf drops the NaN the same way; an all-NaN row has amax
* 0 in both and scale 1e-8/127.
*
* ASUM, when present, also takes each row's code sums per `group` columns, group-major
* [n/group][Mpad] with Mpad = ceil(M/16)*16: an asymmetric weight grid needs sum_k a_k to subtract
* z_g * sum_k a_k from a group's dot product once instead of N times, and it reads whole 16-row
* tiles. The sums are integers, so the LDS accumulator's atomic adds are exact and their order is
* free. Rows M..Mpad-1 are not written; the caller zeroes them, as libref does.
*/
template <bool ASUM>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void quant_act_i8_kernel(
const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s,
float* __restrict__ asum, uint32_t n, uint32_t group, uint32_t x_ld, uint32_t s_ld,
uint32_t mpad) {
__shared__ float red[kWaves];
__shared__ int gs[kI8MaxGroups];
const uint32_t row = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)row * x_ld;
uint8_t* __restrict__ qr = q + (size_t)row * n;
const uint32_t ngrp = ASUM ? n / group : 0;
float am = 0.0f;
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t cc = c + (uint32_t)j;
if (cc < n) am = fmaxf(am, fabsf(ld_bf(xr, cc)));
}
}
const float scale = fmaxf(block_max(am, red), kI8Floor) / kTopI8;
const float inv = 1.0f / scale;
if (threadIdx.x == 0) s[(size_t)row * s_ld] = scale;
if (ASUM) {
for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads) gs[g] = 0;
__syncthreads(); /* the zeroing has to land before the atomics */
}
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
uint32_t w = 0;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t cc = c + (uint32_t)j;
const int8_t code = (cc < n) ? f32_to_i8_rtne(ld_bf(xr, cc) * inv) : (int8_t)0;
w |= (uint32_t)(uint8_t)code << (8 * j);
/* n % group == 0 and group % 4 == 0, so a lane's four columns are in one group. The
* sum is over column order, and the map is its own inverse, so summing the codes of
* columns [gi*group, (gi+1)*group) here is libref reading qr[i8_step_pos(i)] --
* same bytes, same groups. */
if (ASUM && cc < n) atomicAdd(&gs[cc / group], (int)code);
}
*(uint32_t*)(qr + i8_step_pos(c)) = w; /* the step order, one dword a lane */
}
if (ASUM) {
__syncthreads();
for (uint32_t g = threadIdx.x; g < ngrp; g += kThreads)
asum[(size_t)g * mpad + row] = (float)gs[g];
}
}
} /* namespace */
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] i8, DENSE, in libref's STEP ORDER (i8_step_pos: bits 2 and 3 of the
* column exchanged), so n is a multiple of 16, not of 4
* s [M] f32, ONE scale a row, written at element pitch `s_ld` (0 = 1). A
* plane with more room than rows is legal and filled in libref's flat
* order -- the row's scale at s[r], the tail the caller's -- because
* that is what libref does with whatever capacity it is handed, and a
* byte comparison of the tail then agrees.
* asum [n/group][Mpad] f32, optional, group-major, Mpad = ceil(M/16)*16
*
* `group` sizes asum and is ignored without it, as libref ignores it: it is the width of the code
* sums, not the granularity of the scale, which is the whole row. */
extern "C" int r3d_quant_act_i8(long x, long q, long s, long asum, int M, int n, int group,
int x_ld, int s_ld, long stream) {
if (!x || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % 16) return -3; /* a whole 16-byte step; see i8_step_pos */
uint32_t mpad = 0;
if (asum) {
if (group < (int)kColsPerLane || group % (int)kColsPerLane || n % group) return -2;
if (n / group > (int)kI8MaxGroups) return -2;
mpad = (uint32_t)((M + 15) / 16 * 16);
} else {
group = n;
}
if (!x_ld) x_ld = n;
if (!s_ld) s_ld = 1;
if (x_ld < n || s_ld < 1) return -3;
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
const dim3 grid((unsigned)M), block(kThreads);
if (asum)
R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel<true>), grid, block, st, (const uint16_t*)x,
(uint8_t*)q, (float*)s, (float*)asum, (uint32_t)n, (uint32_t)group,
(uint32_t)x_ld, (uint32_t)s_ld, mpad);
else
R3D_KLAUNCH(R3D_KNAME(quant_act_i8_kernel<false>), grid, block, st, (const uint16_t*)x,
(uint8_t*)q, (float*)s, (float*)nullptr, (uint32_t)n, (uint32_t)group,
(uint32_t)x_ld, (uint32_t)s_ld, mpad);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* x [M][n] bf16, `x_ld` elements a row (0 = n)
* q [M][n] i8, DENSE and ROW-MAJOR: the plane this library's i8a8 GEMM reads
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
*
* `group` is the scale's width and is clamped to n when absent, as libref clamps it: `group >= n`
* and `group` absent are both one scale a row. Codes clamp to +-127 before
* the codec, in q8_group's order. 0, -1, -2 a bad extent or an uninstantiated group, -3 a pitch
* that does not describe the operand, -4 the HIP launch failed. */
extern "C" int r3d_quant_act_i8g(const void* x, void* q, void* s, int M, int n, int group,
long long x_ld, long long s_ld, long stream) {
if (!x || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % (int)kColsPerLane) return -3; /* a lane owns four columns; see the kernel */
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
const int ngrp = (n + group - 1) / group;
if (!x_ld) x_ld = n;
if (!s_ld) s_ld = ngrp;
if (x_ld < n || s_ld < ngrp) return -3;
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
const dim3 grid((unsigned)M), block(kThreads);
#define R3D_QAI8G(G) \
R3D_KLAUNCH(R3D_KNAME(quant_act_i8g_kernel<G>), grid, block, st, (const uint16_t*)x, \
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, (uint32_t)x_ld, \
(uint32_t)s_ld)
switch (group) {
case 4: R3D_QAI8G(4); break;
case 8: R3D_QAI8G(8); break;
case 16: R3D_QAI8G(16); break;
case 32: R3D_QAI8G(32); break;
case 64: R3D_QAI8G(64); break;
case 128: R3D_QAI8G(128); break;
case 256: R3D_QAI8G(256); break;
case 512: R3D_QAI8G(512); break;
default: return -2;
}
#undef R3D_QAI8G
return hipGetLastError() == hipSuccess ? 0 : -4;
}
namespace {
/* ================================================================== gated_quant_fp8
*
* act(gate) * up, then quant_act_fp8's quantiser, in one pass. `gate_up` is
* [M, 2n], gate in the first n and up in the second, which is what a fused gate_up projection
* writes; the product is what gets quantised, and `out_bf16`, when bound, receives it.
*
* The product is narrowed to bf16 and read back before the absmax. That is the op and not an
* optimisation: the unfused pair writes a bf16 [M, n] tensor and quantises those bytes, so the
* codes are taken over the narrowed value and out_bf16 holds exactly the value they came from.
* Within the product the rounding points are libref's: sg = 1/(1+exp(-gate)) in f32, then
* (gate*sg) for silu -- MULTIPLIED, not divided, which is a different f32 -- then * up, then one
* bf16 narrowing. `expf` is the accurate form and not __expf (r3d_common.h); it is the one value in
* this unit the reference evaluates in double, so a code can move by one where the bf16 narrowing
* lands on a tie. Every other number here is bit-for-bit.
*
* No row reduction, so no first pass and no barrier: a wave a group, a lane four columns.
*/
template <int GROUP, int ACT>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void gated_quant_fp8_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint8_t* __restrict__ q,
float* __restrict__ s, uint32_t n, uint32_t ngrp, uint32_t s_ld) {
constexpr int kSub = GROUP >= (int)kWaveCols ? GROUP / (int)kWaveCols : 1;
constexpr int kPer = GROUP < (int)kWaveCols ? (int)kWaveCols / GROUP : 1;
constexpr int kLanes = GROUP < (int)kWaveCols ? (int)(GROUP / kColsPerLane) : (int)kWave;
const uint32_t row = blockIdx.x;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint16_t* __restrict__ gr = gu + (size_t)row * (2 * n);
uint16_t* __restrict__ yr = y ? y + (size_t)row * n : nullptr;
uint8_t* __restrict__ qr = q + (size_t)row * n;
const uint32_t nunit = (ngrp + kPer - 1) / kPer;
for (uint32_t u = wave; u < nunit; u += kWaves) {
const uint32_t g0 = u * kPer, cbase = g0 * GROUP;
float v[kSub][kColsPerLane];
float am = 0.0f;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) {
const uint32_t c = c0 + (uint32_t)j;
if (c < n) {
const float gt = ld_bf(gr, c);
const float up = ld_bf(gr, n + c);
const float sg = 1.0f / (1.0f + expf(-gt));
const uint16_t h = f32_to_bf16((ACT == R3D_ACT_SILU ? gt * sg : sg) * up);
if (yr) yr[c] = h;
v[sb][j] = bf16_to_f32(h);
} else {
v[sb][j] = 0.0f; /* padding: see quant_act_fp8_kernel */
}
}
float m = 0.0f;
#pragma unroll
for (int j = 0; j < kColsPerLane; ++j) m = fmaxf(m, fabsf(v[sb][j]));
am = fmaxf(am, r3d_xor_max<kLanes>(m));
}
const float sc = group_scale(am, kTopE4M3);
if ((lane & (kLanes - 1)) == 0) { /* the ragged guard, as above */
const uint32_t gi = (kSub > 1) ? g0 : g0 + lane / kLanes;
if (gi < ngrp) s[(size_t)row * s_ld + gi] = sc;
}
const float inv = 1.0f / sc;
#pragma unroll
for (int sb = 0; sb < kSub; ++sb) {
const uint32_t c0 = cbase + (uint32_t)sb * kWaveCols + lane * kColsPerLane;
if (c0 < n) *(uint32_t*)(qr + c0) = e4m3_codes4(v[sb], inv);
}
}
}
} /* namespace */
/* gu [M][2n] bf16, gate first then up, DENSE (the launcher takes no pitch)
* y [M][n] bf16, the product, optional, dense
* q [M][n] E4M3, dense
* s [M][ceil(n/group)] f32, dense
*
* `act` is R3D_ACT_SILU (down_proj's input) or R3D_ACT_SIGMOID (a gated attention o_proj's). */
extern "C" int r3d_gated_quant_fp8(long gate_up, long q, long s, long out_bf16, int M, int n,
int group, int act, long stream) {
if (!gate_up || !q || !s) return -1;
if (M <= 0 || n <= 0) return -2;
if (n % (int)kColsPerLane) return -3;
if (act != R3D_ACT_SILU && act != R3D_ACT_SIGMOID) return -2;
if (group < 4 || group > 512 || (group & (group - 1))) return -2;
const int ngrp = (n + group - 1) / group;
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
const dim3 grid((unsigned)M), block(kThreads);
#define R3D_GQ(G, A) \
R3D_KLAUNCH(R3D_KNAME(gated_quant_fp8_kernel<G, A>), grid, block, st, (const uint16_t*)gate_up, \
(uint16_t*)out_bf16, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)ngrp, \
(uint32_t)ngrp)
#define R3D_GQ_ACT(A) \
switch (group) { \
case 4: R3D_GQ(4, A); break; \
case 8: R3D_GQ(8, A); break; \
case 16: R3D_GQ(16, A); break; \
case 32: R3D_GQ(32, A); break; \
case 64: R3D_GQ(64, A); break; \
case 128: R3D_GQ(128, A); break; \
case 256: R3D_GQ(256, A); break; \
case 512: R3D_GQ(512, A); break; \
default: return -2; \
}
/* The gate is a template argument, so the multiply below is one instruction and not a branch in
* the inner loop; the switch is over the group widths, each with its own lane mapping. */
if (act == R3D_ACT_SILU) { R3D_GQ_ACT(R3D_ACT_SILU); }
else { R3D_GQ_ACT(R3D_ACT_SIGMOID); }
#undef R3D_GQ_ACT
#undef R3D_GQ
return hipGetLastError() == hipSuccess ? 0 : -4;
}
namespace {
/* ================================================================== dequant
*
* y = code * scale, the read of a container's own quantised weight. Elementwise,
* so there is no reduction and no order to match; the code decodes exactly (E4M3's four exponent
* bits and three mantissa bits are a subset of f16's, and of f32's; E5M2 is f16's top byte,
* rad_plugin.h; int8 is exact in f32), the product is one f32 multiply per element, and the
* store narrows it to bf16 -- the width every consumer of a dequantised weight on this card reads,
* which is why the launcher names the codes' dtype and not the output's.
*
* The scale stream is [M, ceil(n/group)] and the shim requires it to carry every group, so the
* clamp below never fires on a well-formed call; libref clamps a short stream's index to its last
* scale instead of reading off the end, and a kernel row refuses that geometry instead.
*/
template <int QDT>
__device__ __forceinline__ float code_value(uint8_t b) {
if (QDT == R3D_DT_U8) return e4m3_to_f32(b);
if (QDT == R3D_DT_E5M2) return f16_to_f32((uint16_t)b << 8);
return (float)(int8_t)b;
}
template <int QDT>
__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void dequant_kernel(
const uint8_t* __restrict__ q, const float* __restrict__ s, uint16_t* __restrict__ y,
uint32_t n, uint32_t group, uint32_t ngrp, uint32_t s_ld, uint32_t y_ld) {
const uint32_t row = blockIdx.x;
const uint8_t* __restrict__ qr = q + (size_t)row * n;
const float* __restrict__ sr = s + (size_t)row * s_ld;
uint16_t* __restrict__ yr = y + (size_t)row * y_ld;
for (uint32_t c = threadIdx.x * kColsPerLane; c < n; c += kThreads * kColsPerLane) {
const uint32_t gi = min(c / group, ngrp - 1u);
const float sc = ldg_f32(sr + gi);
/* n is a multiple of 4 and the plane is dense, so a lane's four codes are one dword. */
const uint32_t w = ldg_u32((const uint32_t*)(qr + c));
/* One 8-byte store a lane: bf16x2_rne is software RTNE, because gfx11 has no
* v_cvt_pk_bf16_f32 (r3d_common.h), and the narrowing is the store's single round. */
uint32_t* yp = (uint32_t*)(yr + c);
yp[0] = bf16x2_rne(code_value<QDT>((uint8_t)(w & 0xffu)) * sc,
code_value<QDT>((uint8_t)(w >> 8)) * sc);
yp[1] = bf16x2_rne(code_value<QDT>((uint8_t)(w >> 16)) * sc,
code_value<QDT>((uint8_t)(w >> 24)) * sc);
}
}
} /* namespace */
/* q [M][n] codes, DENSE: E4M3, E5M2 or i8, one byte apiece
* s [M][ceil(n/group)] f32, `s_ld` elements a row (0 = ceil(n/group))
* y [M][n] bf16, `y_ld` elements a row (0 = n)
*
* `y` is bf16: the launcher describes the codes' dtype and not the output's, because a dequantised
* weight here is read by a bf16 dot2 GEMM, which is the same reason r3d.h gives this launcher one
* dtype argument. An f32 plane is r3d_cast's, which carries two. */
extern "C" int r3d_dequant(long q, long s, long y, int M, int n, int group, int q_dt, int s_ld,
int y_ld, long stream) {
if (!q || !s || !y) return -1;
if (M <= 0 || n <= 0 || group < 1) return -2;
if (n % (int)kColsPerLane) return -3;
if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8) return -2;
const int ngrp = (n + group - 1) / group;
if (!s_ld) s_ld = ngrp;
if (!y_ld) y_ld = n;
if (s_ld < ngrp || y_ld < n) return -3;
const hipStream_t st = (hipStream_t)(uintptr_t)stream;
const dim3 grid((unsigned)M), block(kThreads);
#define R3D_DQ(D) \
R3D_KLAUNCH(R3D_KNAME(dequant_kernel<D>), grid, block, st, (const uint8_t*)q, (const float*)s, \
(uint16_t*)y, (uint32_t)n, (uint32_t)group, (uint32_t)ngrp, (uint32_t)s_ld, \
(uint32_t)y_ld)
switch (q_dt) {
case R3D_DT_U8: R3D_DQ(R3D_DT_U8); break;
case R3D_DT_E5M2: R3D_DQ(R3D_DT_E5M2); break;
case R3D_DT_I8: R3D_DQ(R3D_DT_I8); break;
default: return -2;
}
#undef R3D_DQ
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ================================================================== the plugin ABI entry points
*
* Three things every shim here reads off the operands and not off the parameters:
*
* * the dtype. A row's `dtype` constraint is a necessary condition on the geometry, not a promise
* about the tensors, and an f32 activation read as bf16 is a value that passes every other
* check.
* * the row count. `M` is the band's upper bound, so the args carry a bound and the operand
* carries the call.
* * the pitch. r3d_rows_pitch() answers in elements, or -1 for an inner axis that is strided.
*
* The code planes are dense: none of the four launchers takes a code pitch, because a dot2 GEMM
* reads codes row-major and the engine hands them over in the order it stores them. A plane with a
* hole in it is a stride refusal and not a slow path. */
/* bf16 is the only activation width these kernels read. An f32 activation is r3d_cast's problem,
* which takes the dtypes as arguments; a quantiser with a dtype switch in its inner loop is the
* wrong shape for an op whose whole point is the store. */
static inline int dt_bf16(const RadTensor* t) { return r3d_is_bf16(t) ? RAD_OK : RAD_E_DTYPE; }
static inline int dt_f32(const RadTensor* t) { return r3d_is_f32(t) ? RAD_OK : RAD_E_DTYPE; }
/* The codes' dtype picks the codec, so it is checked exactly and never as "some byte". */
static inline int dt_e4m3(const RadTensor* t) { return r3d_is_e4m3(t) ? RAD_OK : RAD_E_DTYPE; }
static inline int dt_i8(const RadTensor* t) { return r3d_is_i8(t) ? RAD_OK : RAD_E_DTYPE; }
#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
/* A launcher checked the geometry and answered with a code; translate it to a RAD status. */
static inline int r3d_launch_status(int e) {
switch (e) {
case 0: return RAD_OK;
case -1: return RAD_E_INVAL;
case -2: return RAD_E_SHAPE;
case -3: return RAD_E_STRIDE;
default: return RAD_E_DEVICE;
}
}
/* The group must be a power of two from 4 to 512: the amax butterfly is over the lanes covering a
* group, GROUP/4 of them, and the kernels are instantiated for those widths. libref clamps
* `group <= 0 || group > n` to n, so "one scale a row" arrives as 0 and leaves as n;
* a width with no instantiation is refused and not rounded, because a rounded group would quantise
* on a grid the weight's scales are not on. */
static inline int r3d_group_of(long long g, long long n) {
if (g <= 0 || g > n) g = n;
return (g >= 4 && g <= 512 && (g & (g - 1)) == 0) ? (int)g : 0;
}
/* ------------------------------------------------------------------ quant_act_fp8 */
enum { QAF_X = 0, QAF_Q, QAF_S };
extern "C" int r3d_rad_quant_act_fp8(const RadArgs* a, RadStream stream) {
const RadTensor* x = r3d_opt(a, QAF_X);
const RadTensor* q = r3d_opt(a, QAF_Q);
const RadTensor* sc = r3d_opt(a, QAF_S);
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(x));
R3D_NEED(dt_e4m3(q));
R3D_NEED(dt_f32(sc));
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n);
if (!group) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
long long rows = 0, qrows = 0, srows = 0;
const long long x_ld = r3d_rows_pitch(x, n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
return r3d_launch_status(r3d_quant_act_fp8(r3d_addr(x), r3d_addr(q), r3d_addr(sc), (int)rows,
(int)n, group, (int)x_ld, (int)s_ld,
(long)(uintptr_t)stream));
}
/* ------------------------------------------------------------------ quant_act_i8 */
enum { QAI_X = 0, QAI_Q, QAI_S, QAI_ASUM };
extern "C" int r3d_rad_quant_act_i8(const RadArgs* a, RadStream stream) {
const RadTensor* x = r3d_opt(a, QAI_X);
const RadTensor* q = r3d_opt(a, QAI_Q);
const RadTensor* sc = r3d_opt(a, QAI_S);
const RadTensor* as = r3d_opt(a, QAI_ASUM); /* the asymmetric grid's code sums */
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(x));
R3D_NEED(dt_i8(q));
R3D_NEED(dt_f32(sc));
if (r3d_has(as)) R3D_NEED(dt_f32(as)); /* a slot with no bytes is the operand being absent */
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); /* a whole 16-byte step: see i8_step_pos */
/* One scale a row: this op's scale granularity IS the row (the amax runs over the whole row,
* and the store is `stt(s, rowoff(s, r, 1), scale)`, a FLAT stream at element pitch 1), and
* libref lists `group` as the width of the row SUMS, not of the scale. A plane with more
* elements than rows is therefore accepted and filled in libref's order: the row's scale
* lands at s[r], the plane's first M elements, and the rest of it stays the caller's. That
* is exactly the plane the row's operand description gives --
* [M, ceil(n/group)], quant_act_i8g's width, of which this op writes the first column -- and
* refusing it would be the shim tightening its own row past the reference: libref requires
* numel(s) >= rows and nothing more, and the bytes it never touches compare equal. */
long long rows = 0, qrows = 0, srows = 0;
const long long x_ld = r3d_rows_pitch(x, n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
const long long s_ld = r3d_rows_pitch(sc, 1, &srows);
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
if (srows < rows || r3d_numel(sc) < rows) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
/* `group` sizes asum only, and is not read without it. n % group == 0, because a sum is over
* whole columns of a row, and the LDS accumulator is 256 groups wide. */
int group = 0;
if (as) {
group = (int)r3d_geti_or(a, "group", R3D_W8_GROUP);
if (group < (int)kColsPerLane || group % kColsPerLane || n % group)
return R3D_NO(RAD_E_SHAPE);
if (n / group > (long long)kI8MaxGroups) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(as)) return R3D_NO(RAD_E_STRIDE);
const long long mpad = ((rows + 15) / 16) * 16;
if (r3d_numel(as) < (n / group) * mpad) return R3D_NO(RAD_E_SHAPE);
}
return r3d_launch_status(r3d_quant_act_i8(
r3d_addr(x), r3d_addr(q), r3d_addr(sc), r3d_addr(as), (int)rows, (int)n, group, (int)x_ld,
(int)s_ld, (long)(uintptr_t)stream));
}
/* ------------------------------------------------------------------ quant_act_i8g */
/* The int8 plane at group granularity, and the one this library's i8a8 GEMM reads. Operands are
* libref's oQuantFp8 shape -- {x, q, scale} -- with the int8 codes' dtype. */
enum { QAG_X = 0, QAG_Q, QAG_S };
extern "C" int r3d_rad_quant_act_i8g(const RadArgs* a, RadStream stream) {
const RadTensor* x = r3d_opt(a, QAG_X);
const RadTensor* q = r3d_opt(a, QAG_Q);
const RadTensor* sc = r3d_opt(a, QAG_S);
if (!x || !q || !sc) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(x));
R3D_NEED(dt_i8(q));
R3D_NEED(dt_f32(sc));
const long long n = r3d_geti_or(a, "n", r3d_dim(x, (int)x->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
/* libref's clamp of `group`: absent, zero or wider than the row is one
* scale a row, so the default here is 0 and the clamp turns it into n. A width the kernels have
* no instantiation for is refused, not rounded to one. */
const int group = r3d_group_of(r3d_geti_or(a, "group", 0), n);
if (!group) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
long long rows = 0, qrows = 0, srows = 0;
const long long x_ld = r3d_rows_pitch(x, n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
if (x_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
if (srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
return r3d_launch_status(r3d_quant_act_i8g(x->data, q->data, sc->data, (int)rows, (int)n, group,
x_ld, s_ld, (long)(uintptr_t)stream));
}
/* ------------------------------------------------------------------ gated_quant_fp8 */
enum { GQT_GU = 0, GQT_Q, GQT_S, GQT_Y };
extern "C" int r3d_rad_gated_quant_fp8(const RadArgs* a, RadStream stream) {
const RadTensor* gu = r3d_opt(a, GQT_GU);
const RadTensor* q = r3d_opt(a, GQT_Q);
const RadTensor* sc = r3d_opt(a, GQT_S);
const RadTensor* y = r3d_opt(a, GQT_Y); /* the product, for a bf16 consumer */
if (!gu || !q || !sc) return R3D_NO(RAD_E_INVAL);
R3D_NEED(dt_bf16(gu));
R3D_NEED(dt_e4m3(q));
R3D_NEED(dt_f32(sc));
if (r3d_has(y)) R3D_NEED(dt_bf16(y)); /* the same: an empty slot is no operand at all */
/* "silu" (down_proj's input) or "sigmoid" (a gated attention o_proj's), `mode` the integer
* spelling of the same choice, `act` winning where both are given. libref's `act` enumerates
* those two, so a gelu-gated feed-forward is not this row's: it asks for a gate the oracle has
* no definition for here. */
const int act = r3d_act_code(a, "act", "mode", R3D_ACT_SILU);
if (act < 0) return R3D_NO(RAD_E_UNSUPPORTED);
const long long n = r3d_geti_or(a, "n", r3d_dim(q, (int)q->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
const int group = r3d_group_of(r3d_geti_or(a, "group", R3D_ACT_GROUP), n);
if (!group) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
/* The fused gate_up projection writes the plane dense, gate half first, [M, 2n] with no hole: a
* sliced gate is r3d_act_mul_bf16's, which takes the two pitches. */
long long rows = 0, qrows = 0, srows = 0, yrows = 0;
const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
const long long y_ld = y ? r3d_rows_pitch(y, n, &yrows) : n;
if (gu_ld < 0 || q_ld < 0 || s_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (gu_ld != 2 * n) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
if (s_ld != ngrp || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
if (y && (y_ld != n || yrows < rows || r3d_numel(y) < rows * n)) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4)) return R3D_NO(RAD_E_ALIGN);
return r3d_launch_status(r3d_gated_quant_fp8(
r3d_addr(gu), r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n, group, act,
(long)(uintptr_t)stream));
}
/* ------------------------------------------------------------------ dequant */
enum { DQT_Q = 0, DQT_S, DQT_Y };
extern "C" int r3d_rad_dequant(const RadArgs* a, RadStream stream) {
const RadTensor* q = r3d_opt(a, DQT_Q);
const RadTensor* sc = r3d_opt(a, DQT_S);
const RadTensor* y = r3d_opt(a, DQT_Y);
if (!q || !sc || !y) return R3D_NO(RAD_E_INVAL);
/* The codes' dtype IS the encoding, so it is read off the tensor: E4M3 and E5M2 are one byte
* apiece and nothing in the bytes tells them apart. A plain u8 plane carries no encoding, so it
* is not accepted under the E4M3 code. */
if (q->dtype == RAD_U8) return R3D_NO(RAD_E_DTYPE);
const int q_dt = r3d_dt_code(q->dtype);
if (q_dt != R3D_DT_U8 && q_dt != R3D_DT_E5M2 && q_dt != R3D_DT_I8)
return R3D_NO(RAD_E_DTYPE);
R3D_NEED(dt_f32(sc));
R3D_NEED(dt_bf16(y)); /* the launcher has no output dtype; see above */
const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1));
if (n <= 0 || n % kColsPerLane) return R3D_NO(RAD_E_SHAPE);
/* Rows come off `y`, as in ref_dequant: `y` is the plane the consumer reads. */
long long rows = 0, qrows = 0, srows = 0;
const long long y_ld = r3d_rows_pitch(y, n, &rows);
const long long q_ld = r3d_rows_pitch(q, n, &qrows);
if (y_ld < 0 || q_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (rows <= 0 || rows > 0x7fffffffLL || n > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
if (q_ld != n || qrows < rows || r3d_numel(q) < rows * n) return R3D_NO(RAD_E_SHAPE);
/* The scale stream's extent gives the group count and `group` each group's width, as libref
* reads them; with no `group`, the stream is taken as one scale per group of ceil(n/ngrp). */
const long long ngrp_param = r3d_numel(sc) / rows > 0 ? r3d_numel(sc) / rows : 1;
long long group = r3d_geti_or(a, "group", 0);
if (group <= 0) group = (n + ngrp_param - 1) / ngrp_param;
if (group < 1 || group > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE);
const long long ngrp = (n + group - 1) / group;
const long long s_ld = r3d_rows_pitch(sc, ngrp, &srows);
if (s_ld < 0 || srows < rows || r3d_numel(sc) < rows * ngrp) return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(q), 4) || !r3d_aligned(r3d_p(sc), 4) || !r3d_aligned(r3d_p(y), 8))
return R3D_NO(RAD_E_ALIGN);
return r3d_launch_status(r3d_dequant(r3d_addr(q), r3d_addr(sc), r3d_addr(y), (int)rows, (int)n,
(int)group, q_dt, (int)s_ld, (int)y_ld,
(long)(uintptr_t)stream));
}
+1839
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+932
View File
@@ -0,0 +1,932 @@
/* r3d_sample_pre_f32.hip -- the sampler's pre-filters: the five stages that edit the logits row
* before the candidate set is built. `sample_logprobs`, `sample_penalties`, `sample_dry`,
* `sample_ngram_ban` and `sample_mask`; the draw spine -- argmax, temp, top-k, the narrowings and
* the pick -- is `r3d_sample_f32.hip`, and the only things shared are statics.
*
* The arithmetic is libref's, transcribed: the reference's sampler is the law, and
* `abi/rad_sample.h` is the wire format for every scalar, one 96-byte row per sampled position. The order of the
* arithmetic is transcription where the order can be seen, and there is a lot of it here: the
* penalties law (sign-dependent repetition, the count times the frequency, presence once per
* distinct token, all of it at the token's FIRST occurrence in the window), DRY's longest-suffix
* repeat per continuation token with its repeated-multiplication penalty, the n-gram ban's
* windowed prefix search and its whitelist exemption, and the mask's bit-per-token rule.
*
* ============================== what each stage reads, and why the shapes differ ==============
*
* The row is 130560 f32 at the band and there are 2048 of them: the logits plane is 1.02 GiB and
* one pass over it is ~3.6 ms on this card (RX 7600, 16 CUs). That number sorts the five into two
* shapes, and the shape is decided by how many of the row's columns the stage touches -- which is
* what the reference touches, not what it could:
*
* HISTORY STAGES -- penalties, dry, ngram_ban. A row's window is 64 tokens, so a row has at most
* 64 columns to touch. libref touches exactly those, and so does this file: one block a row of 64
* threads, each position a thread, the window read straight from L2 (4096 integer reads a row,
* which is why the quadratic scans are free and why there is no LDS copy of the history). These
* kernels move kilobytes a row. Micro-optimising the scans would be optimising the part that is
* not the cost.
*
* ROW STAGES -- mask, logprobs. A mask writes every disallowed column of the row and logprobs
* summarises every column of it, so these read and write the plane and are the bandwidth rows of
* the unit: 256 threads a row, a thread a run of columns, so each lane's traffic is one
* contiguous segment.
*
* `sample_logprobs` is where the pass count is the whole argument. libref reads the row three
* times -- a max, then a sum of `exp(v - max)`, then a third scan to insert every element into a
* k-list -- so at the band it reads 3.06 GiB where one pass reads 1.02. One pass cannot know the
* row's max before it has seen the row, so each lane keeps a running max and a running DOUBLE sum
* of `exp(v - its own max)`, rescaling its sum when its max rises (one double multiply per rise,
* a handful per lane), and the butterfly merges pairs of (max, sum) by
*
* m = max(a, b); sum = a.sum * exp(a.mx - m) + b.sum * exp(b.mx - m)
*
* which is the reference's sum shifted by a constant per lane. Each term is the reference's term
* to a fraction of an f64 ulp, the merged sum lands on the reference's to ~1e-15 relative, and the
* stored value is f32 -- 6e-8 is the granularity of what the plane holds, so the rescaling is
* below the store's own rounding. The lane shuffles carry the max (32-bit) and the k-list (one
* 8-byte pattern an entry at a time); the sum is merged in LDS, by wave and then across waves, and
* the reason is in sample_logprobs_kernel's comment: a double can cross lanes soundly only by
* moving bits, never by value. `r3d_lanes_check` at the end of the file is the control that keeps
* that true, and `r3d_selftest.cpp` runs it. The `exp`
* is `exp(double)`, the reference's own width: libref's sum adds double exps and the row is the
* logit distribution, so this is the file's one fp64-heavy kernel and it is the slow path by law,
* not by oversight -- consumer RDNA3 is 1:64 on doubles. At the band (M=2048,
* n_vocab=130560, k=21) the plane's one read is 3.6 ms at 266 GiB/s, a read that also sums
* `exp(double)` is 30.4 ms, this kernel is 38.9 ms, and libref's three reads of that plane are
* 2.988 GiB against this kernel's 0.996.
*
* The k-list is per lane too, k deep, kept in the reference's order -- descending by value, ties
* to the LOWER column, which is `topk_next`'s total order and the narrowing stages' -- and merged
* pairwise in the same butterfly, so the block's list is the reference's list. `k` at the band is
* 21; the pool is 64 deep, and a request above that is refused rather than silently truncated.
*
* ============================== agreement, and where this file declines ==============================
*
* Maxima are strict `>` with the max as the first argument, which is `std::max`'s law and is how a
* NaN is kept out of the row's max: a NaN never compares greater, so it is never adopted, at the
* first element or anywhere later. A NaN in the sum propagates, because the reference's
* `exp(NaN - mx)` is NaN and it is added.
*
* A row whose parameters turn the stage off is left bit for bit as it was -- the flag test is the
* reference's, and for penalties the identity test (rep 1, freq 0, pres 0) is too.
*
* Declines, all of them RAD_E_UNSUPPORTED from the shim and none of them reachable from a row that
* carries the constraints its rows do: a history plane wider than 2^31/8 columns is not a plane;
* `k` above 64 for logprobs (the pool's depth, and far above any k the engine requests); and for
* ngram_ban a `whitelist` plane, which the kernel implements -- the whitelist is exempted before
* the -inf writes, as the reference removes it from the banned set -- so the only decline is the
* `ngram` plane's dtype and the mask and whitelist's, which must be 32-bit words.
*/
#include "r3d.h"
#include "r3d_args.h"
#include "r3d_common.h"
#include "r3d_launch.h"
#include <rad_sample.h>
#include <cfloat>
/* ================================================================== shared helpers (statics)
*
* The headers are frozen, so a unit that needs a helper carries its own copy and keeps it static: a
* non-static one collides at link with the same helper in another unit and takes the library down.
*/
namespace {
constexpr uint32_t kThreads = 256; /* 8 waves: the row stages */
constexpr uint32_t kPre = 64; /* 2 waves: the history stages, a position a thread */
constexpr uint32_t kWave = 32;
constexpr uint32_t kWaves = kThreads / kWave;
constexpr int kKMax = 64; /* the k-list pool's depth, per lane */
/* The row's summary accumulates `exp` in DOUBLE, because that is where the reference's sum lives.
* The width is a switch, because the width is the cost: at the band the double exp is 30 ms of the
* kernel's 38 ms against a 3.7 ms plane read, and an f32 exp widened to double --
* `expf`, terms accurate to an f32 ulp, summed in double -- lands the row's sum on the reference's
* to ~1e-10 relative against a stored f32 granularity of 6e-8. Define R3D_LP_EXP_F32 to build the
* fast exp; the default is the reference's arithmetic. */
#ifdef R3D_LP_EXP_F32
__device__ __forceinline__ double dexp(double x) { return (double)expf((float)x); }
#else
__device__ __forceinline__ double dexp(double x) { return exp(x); }
#endif
/* A whole-register load of an index plane: the history, the n-gram pair, the bitmask words. */
__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) {
return (int32_t)ldg_u32((const uint32_t*)p);
}
__device__ __forceinline__ uint32_t ldg_u8(const uint8_t* p) { return *(const uint8_t*)p; }
/* Lane partners of the accumulator's pieces. */
template <int N>
__device__ __forceinline__ int32_t xor_i32(int32_t v) {
return (int32_t)r3d_xor_lane_u32<N>((uint32_t)v);
}
/* There is no 64-bit lane shuffle here on purpose: see sample_logprobs_kernel. */
/* The law, verbatim. The window both history stages read, clamped to the row's own row
* of the plane; `last_n` 0 disables the stage, a negative keeps the whole span, a positive keeps
* its TAIL. The window law IS the history law: the window, and the rule that a token is penalised
* at its first occurrence in it. */
__device__ __forceinline__ bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax,
int64_t* ho_out, int64_t* hl_out) {
if (last_n == 0) return false;
int64_t hl = sp.hist_len;
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
if (ho > hmax) ho = hmax;
if (hl > hmax - ho) hl = hmax - ho;
if (last_n > 0 && hl > last_n) {
ho += hl - last_n;
hl = last_n;
}
*ho_out = ho;
*hl_out = hl;
return hl > 0;
}
/* The law, verbatim, including the stop short of overflow: repeated multiplication, so
* every implementation lands on the same float. */
__device__ __forceinline__ float dry_penalty(float multiplier, float base, int64_t e) {
float pen = multiplier;
if (base == 1.0f) return pen;
const float lim = FLT_MAX / base;
for (int64_t i = 0; i < e; ++i) {
if (pen > lim) break;
pen *= base;
}
return pen;
}
/* The k-list's order: descending by value, ties to the lower column. `above(x, y)` is "x comes
* first", the reference's comparator and `topk_next`'s chain. */
struct Cand { float v; int32_t i; };
__device__ __forceinline__ bool above(Cand x, Cand y) {
return x.v > y.v || (x.v == y.v && x.i < y.i);
}
/* ================================================================== sample_logprobs
*
* The law. The row's summary: its max, the sum of exp(v - max) in double, and the k
* largest as (id, logit) pairs descending, ids as floats with `vocab_off` added, an unfilled slot
* id -1 and logit -infinity. Rows without RAD_SP_LOGPROBS are not written at all.
*
* One pass over the row, per the file's header: the max, the sum and the k-list are three
* independent accumulations of the same read, and the sum is rescaled into the row's final max at
* the merge, which is a per-lane shift of the reference's terms.
*/
struct Acc {
float mx;
double sum;
Cand c[kKMax];
int n;
};
/* A lane's running state over its own elements. A new maximum rescales the sum it has so far; the
* reference never rescales (it knows the max up front) and the rescale is the price of the read. */
__device__ __forceinline__ void acc_push(Acc& a, int k, uint32_t col, float v) {
if (v > a.mx) {
if (a.mx != -INFINITY) a.sum *= dexp((double)a.mx - (double)v);
a.mx = v;
}
a.sum += dexp((double)v - (double)a.mx);
/* The reference's insertion: an element that is not above the k-th is dropped, and the insert
* point is the first slot the element beats (with a NaN, no slot, so the tail: insert, then the
* pop leaves the list exactly as it was). */
if (a.n == k && !above(Cand{ v, (int32_t)col }, a.c[a.n - 1])) return;
int pos = 0;
while (pos < a.n && !above(Cand{ v, (int32_t)col }, a.c[pos])) ++pos;
if (pos >= k) return;
for (int j = (a.n < k ? a.n : k - 1); j > pos; --j) a.c[j] = a.c[j - 1];
a.c[pos] = Cand{ v, (int32_t)col };
if (a.n < k) ++a.n;
}
/* The butterfly's merge of two lanes' states: the max is strict, the sum is the two shifted sums,
* and the lists merge on the same order. Ties in the merge (two equal values at equal columns
* cannot happen -- the column is the lane's -- and a NaN is not above anything, so a NaN list
* entry stays in the lane that read it). */
__device__ __forceinline__ Acc acc_merge(const Acc& a, const Acc& b, int k) {
Acc r;
r.mx = a.mx > b.mx ? a.mx : b.mx;
r.sum = (a.mx == -INFINITY ? 0.0 : a.sum * dexp((double)a.mx - (double)r.mx)) +
(b.mx == -INFINITY ? 0.0 : b.sum * dexp((double)b.mx - (double)r.mx));
int i = 0, j = 0;
r.n = 0;
while (r.n < k && (i < a.n || j < b.n)) {
const bool take_b = (i >= a.n) || (j < b.n && above(b.c[j], a.c[i]));
r.c[r.n++] = take_b ? b.c[j++] : a.c[i++];
}
return r;
}
template <int THR>
__global__ __launch_bounds__(THR) void sample_logprobs_kernel(
const float* __restrict__ lg, const RadSampleParams* __restrict__ pr,
float* __restrict__ st, uint32_t n, uint32_t k, uint32_t lg_ld, uint32_t st_ld,
int32_t voff) {
const uint32_t row = blockIdx.x;
if (!(pr[row].flags & RAD_SP_LOGPROBS)) return;
Acc a;
a.mx = -INFINITY;
a.sum = 0.0;
a.n = 0;
const float* __restrict__ lr = lg + (size_t)row * lg_ld;
for (uint32_t c = threadIdx.x; c < n; c += THR) acc_push(a, (int)k, c, ldg_f32(lr + c));
/* The k-list and the max meet their partners in the wave's 32-bit lane shuffles, five rounds.
*
* The participation mask of a 64-bit shuffle on this ROCm is an `unsigned long long`, and on
* wave32 it is `0xFFFFFFFFull`: `~0ull` names lanes 32..63, which a wave of 32 does not have.
* `r3d_lanes_check` at the end of this file is the control that proves the lane helpers, and
* `r3d_selftest.cpp` runs it and checks every lane of every wave.
*
* The SUM does not go through a lane shuffle: it meets its partners in LDS, the machinery
* `block_sum` already trusts. A double can cross lanes soundly -- lanes_check_kernel below is
* exact in all 256 lanes of all 8 waves for three forms of it -- but only by moving the value's
* *bits*, never by value: a cast to an integer type converts by value, so
*
* d += (double)r3d_xor_lane_u64<N>((unsigned long long)d);
*
* truncates the partner's term to its integer part, and a wave of fractions then sums to 1, the
* largest term's integer part -- a 40% loss of the row's mass at the band's width, the shape a
* hardware fault takes. The k-list, whose entries are bit patterns by construction (a float's
* pattern and an int in one 8-byte value), crosses lanes as that pattern in one shuffle; the sum,
* which is a number, does not cross lanes at all. */
#define R3D_ACC_XOR(M) \
{ \
Acc b; \
b.mx = r3d_xor_lane<M>(a.mx); \
b.n = xor_i32<M>((int32_t)a.n); \
for (int j = 0; j < k; ++j) { \
/* One list entry is one 8-byte value -- a float's pattern and a column -- and it
* crosses lanes as that pattern, in one shuffle. Assembling it from the two halves on
* the far side would need each half shuffled and then reassembled by value, which is
* the shape that turns a bit pattern into a number. */ \
const unsigned long long packed = \
(unsigned long long)__float_as_uint(a.c[j].v) | \
((unsigned long long)(uint32_t)a.c[j].i << 32); \
const unsigned long long got = __shfl_xor_sync(0xFFFFFFFFull, packed, M); \
b.c[j] = Cand{ __uint_as_float((uint32_t)got), (int32_t)(uint32_t)(got >> 32) }; \
} \
b.sum = 0.0; \
const float mx = a.mx > b.mx ? a.mx : b.mx; /* no lane's max is a NaN: a NaN is never \
adopted by the strict test above */ \
a = acc_merge(a, b, (int)k); \
a.mx = mx; \
}
R3D_ACC_XOR(16)
R3D_ACC_XOR(8)
R3D_ACC_XOR(4)
R3D_ACC_XOR(2)
R3D_ACC_XOR(1)
#undef R3D_ACC_XOR
/* The wave's sum, in LDS: the wave's max first, then every lane's sum shifted into it, in lane
* order. An empty lane (a row narrower than the block) has max -infinity and sum 0 and
* contributes nothing, which is the reference's own arithmetic on an empty span. */
__shared__ float s_mx[kThreads];
__shared__ double s_sum[kThreads];
__shared__ float w_mx[kWaves];
__shared__ double w_sum[kWaves];
__shared__ int w_n[kWaves];
__shared__ Cand w_c[kWaves][kKMax];
s_mx[threadIdx.x] = a.mx;
s_sum[threadIdx.x] = a.sum;
__syncthreads();
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
if (lane == 0) {
const uint32_t b = wave * kWave;
float m = s_mx[b];
for (uint32_t l = 1; l < kWave; ++l)
if (s_mx[b + l] > m) m = s_mx[b + l];
double s = 0.0;
for (uint32_t l = 0; l < kWave; ++l)
s += s_mx[b + l] == -INFINITY ? 0.0
: s_sum[b + l] * dexp((double)s_mx[b + l] - (double)m);
w_mx[wave] = m;
w_sum[wave] = s;
w_n[wave] = a.n;
for (int j = 0; j < k; ++j) w_c[wave][j] = a.c[j];
}
__syncthreads();
if (threadIdx.x != 0) return;
/* The eight wave partials, in wave order: the row's max, the row's sum, the row's k-list. */
float m = w_mx[0];
double s = w_sum[0];
int n_list = w_n[0];
Cand list[kKMax];
for (int j = 0; j < k; ++j) list[j] = w_c[0][j];
for (uint32_t w = 1; w < kWaves; ++w) {
const float mm = w_mx[w] > m ? w_mx[w] : m;
s = (m == -INFINITY ? 0.0 : s * dexp((double)m - (double)mm)) +
(w_mx[w] == -INFINITY ? 0.0 : w_sum[w] * dexp((double)w_mx[w] - (double)mm));
m = mm;
Acc x, y;
x.mx = m; x.sum = 0.0; x.n = n_list;
for (int j = 0; j < k; ++j) x.c[j] = list[j];
y.mx = w_mx[w]; y.sum = 0.0; y.n = w_n[w];
for (int j = 0; j < k; ++j) y.c[j] = w_c[w][j];
const Acc t = acc_merge(x, y, (int)k);
n_list = t.n;
for (int j = 0; j < k; ++j) list[j] = t.c[j];
}
float* __restrict__ sr = st + (size_t)row * st_ld;
sr[0] = m;
sr[1] = (float)s;
for (uint32_t j = 0; j < k; ++j) {
const bool have_j = j < (uint32_t)n_list;
sr[2 + 2 * j] = have_j ? (float)(list[j].i + voff) : -1.0f;
sr[3 + 2 * j] = have_j ? list[j].v : -INFINITY;
}
}
/* ================================================================== sample_penalties
*
* The law. llama.cpp's ordering, at the token's first occurrence in the window:
*
* repetition logit = logit > 0 ? logit / rep : logit * rep
* frequency logit -= count * freq
* presence logit -= pres
*
* The repetition penalty is sign-dependent because dividing a negative logit would raise it. The
* count carries the multiplicity, which is why the update runs once per distinct token, and the
* scan for it is the reference's own: walk the window from the front, stop at an earlier
* occurrence, count the ones from here on.
*
* Columns are global ids less `vocab_off`, so a token on another rank's shard is skipped here and
* penalised there. Each distinct token is one column and one thread, so the writes cannot race.
*/
__global__ __launch_bounds__(kPre) void sample_penalties_kernel(
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
const uint32_t row = blockIdx.x;
const RadSampleParams& sp = pr[row];
if (!(sp.flags & RAD_SP_PENALTY)) return;
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.penalty_last_n, (int64_t)hmax, &ho, &hl)) return;
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
float* __restrict__ lr = lg + (size_t)row * lg_ld;
for (uint32_t i = threadIdx.x; i < (uint32_t)hl; i += kPre) {
const int32_t tok = ldg_i32(hr + i);
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= n) continue;
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
if (ldg_i32(hr + j) != tok) continue;
if (j < (int64_t)i) { first = false; break; }
++count;
}
if (!first) continue;
float v = lr[col];
v = v > 0.0f ? v / rep : v * rep;
v -= (float)count * freq;
v -= pres;
lr[col] = v;
}
}
/* ================================================================== sample_dry
*
* The law, DRY's rule (llama.cpp's llama_sampler_dry_apply): for every earlier position
* j, n_j is how long a suffix of the window also ends at j, capped at the breaker limit; the token
* at j+1 would extend that repeat and is penalised by multiplier * base^(n - allowed), once, by the
* LONGEST repeat it follows. A token that is itself a whole-sequence breaker is never penalised,
* and only lengths at or above `allowed` count.
*
* A thread a position, the window read from L2. The map the reference keeps is here a maximum over
* the threads that share a token, applied by the thread holding the token's first occurrence, so
* one column is written once.
*/
__global__ __launch_bounds__(kPre) void sample_dry_kernel(
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
const uint8_t* __restrict__ brk, uint32_t n, uint32_t lg_ld, uint32_t hmax, int32_t voff) {
const uint32_t row = blockIdx.x;
const RadSampleParams& sp = pr[row];
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) return;
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.dry_penalty_last_n, (int64_t)hmax, &ho, &hl)) return;
if (hl <= allowed) return;
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
if (cap < allowed) return;
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
const uint8_t* __restrict__ br = brk ? brk + (size_t)row * hmax + ho : nullptr;
float* __restrict__ lr = lg + (size_t)row * lg_ld;
const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); };
const auto exempt = [&](int64_t i) { return br && ldg_u8(br + i) != 0u; };
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
for (uint32_t j = threadIdx.x; j + 1u < (uint32_t)hl; j += kPre) {
const int64_t lim = ((int64_t)j + 1 < cap) ? (int64_t)j + 1 : cap;
int64_t m = 0;
while (m < lim && tok_at(j - m) == tok_at(hl - 1 - m)) ++m;
if (m < allowed || exempt((int64_t)j + 1)) continue;
const int32_t tok = tok_at((int64_t)j + 1);
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= n) continue;
/* The longest repeat any position attributes to this token, and the first thread that
* carries it pays for it. Equal tokens at equal lengths: the lowest j, so one writer. */
int64_t longest = m;
bool first = true;
for (int64_t q = 0; q + 1 < hl; ++q) {
if (tok_at(q + 1) != tok) continue;
const int64_t limq = (q + 1 < cap) ? q + 1 : cap;
int64_t mq = 0;
while (mq < limq && tok_at(q - mq) == tok_at(hl - 1 - mq)) ++mq;
if (mq < allowed || exempt(q + 1)) continue;
if (mq > longest) longest = mq;
if (q < (int64_t)j) { first = false; break; }
}
if (!first) continue;
const float v = lr[col];
lr[col] = v - dry_penalty(sp.dry_multiplier, base, longest - allowed);
}
}
/* ================================================================== sample_ngram_ban
*
* The law, the windowed no-repeat-ngram ban. With the row's window s[0, hl):
*
* search_start = max(0, hl - w); search_end = hl - n + 1; prefix = s[hl - n + 1, hl)
* for idx in [search_start, search_end): s[idx, idx + n - 1) == prefix => ban s[idx + n - 1]
*
* The window is on the START index, so the n-gram that straddles the window's edge is searched. A
* banned token's logit becomes -infinity, and the whitelist is removed from the banned set before
* any -inf is written, so a whitelisted column is never touched. n == 1 bans every token in the
* window, the prefix being empty. A row whose n is 0 is left bit for bit as it was.
*
* A thread a search index. Several indices can ban the same token; the write is the same -infinity
* from every one of them, so the race writes one value.
*/
__global__ __launch_bounds__(kPre) void sample_ngram_ban_kernel(
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ hist,
const int32_t* __restrict__ ngram, const int32_t* __restrict__ wl, uint32_t n, uint32_t lg_ld,
uint32_t hmax, uint32_t words, int32_t voff) {
const uint32_t row = blockIdx.x;
const RadSampleParams& sp = pr[row];
const int32_t* __restrict__ nr = ngram + (size_t)row * 2;
const int64_t nn = ldg_i32(nr);
const int64_t win_req = ldg_i32(nr + 1);
if (nn <= 0) return;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, -1, (int64_t)hmax, &ho, &hl)) return; /* the whole staged span */
if (hl < nn) return;
const int64_t win = (win_req > 0 && win_req < hl) ? win_req : hl;
const int64_t search_start = hl - win;
const int64_t search_end = hl - nn + 1;
if (search_end <= search_start) return;
const int32_t* __restrict__ hr = hist + (size_t)row * hmax + ho;
const int32_t* __restrict__ wr = wl ? wl + (size_t)row * words : nullptr;
float* __restrict__ lr = lg + (size_t)row * lg_ld;
const auto tok_at = [&](int64_t i) { return ldg_i32(hr + i); };
const auto exempt = [&](int64_t col) {
if (!wr) return false;
const uint32_t word = (uint32_t)ldg_i32(wr + col / 32);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = nn - 1, p0 = hl - plen;
for (uint32_t idx = search_start + threadIdx.x; idx < (uint32_t)search_end; idx += kPre) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (tok_at((int64_t)idx + j) != tok_at(p0 + j)) { match = false; break; }
}
if (!match) continue;
const int32_t tok = tok_at((int64_t)idx + plen);
const int64_t col = (int64_t)tok - voff;
if (tok < 0 || col < 0 || col >= n) continue;
if (exempt(col)) continue;
lr[col] = -INFINITY;
}
}
/* ================================================================== sample_mask
*
* The law. A set bit means allowed; an unset column's logit becomes -infinity. This is
* the dense row stage: a row of 130560 columns and a bitmask of 4080 words, so a thread takes a
* word and the 32 columns under it, which is one contiguous 128-byte segment a lane. A word that
* is all ones is skipped whole, and a word that is all zeros is a run of eight 16-byte stores;
* either way the row is written in the order the plane is laid out.
*
* `mask_row` is the row's own row of the bitmask plane, and the reference skips a row index
* outside the plane, -1 included (the shape hook caps `idx_max` at M so a fixture draws a real
* row); the shim bounds the plane to at least M rows, which is the same test at the geometry the
* op's descriptor describes.
*/
__global__ __launch_bounds__(kThreads) void sample_mask_kernel(
float* __restrict__ lg, const RadSampleParams* __restrict__ pr, const int32_t* __restrict__ bm,
uint32_t n, uint32_t lg_ld, uint32_t words, uint32_t mask_rows) {
const uint32_t row = blockIdx.x;
const RadSampleParams& sp = pr[row];
if (!(sp.flags & RAD_SP_MASK)) return;
const int64_t mrow = sp.mask_row;
if (mrow < 0 || (uint64_t)mrow >= mask_rows) return;
const int32_t* __restrict__ br = bm + (size_t)mrow * words;
float* __restrict__ lr = lg + (size_t)row * lg_ld;
for (uint32_t w = threadIdx.x; w < words; w += kThreads) {
const uint32_t bits = (uint32_t)ldg_i32(br + w);
if (bits == 0xffffffffu) continue; /* nothing banned in these 32 */
const uint32_t c0 = 32u * w;
const uint32_t cnt = n - c0 < 32u ? n - c0 : 32u; /* the row's last word is partial */
if (bits == 0u) {
for (uint32_t c = 0; c < cnt; ++c) lr[c0 + c] = -INFINITY;
continue;
}
for (uint32_t c = 0; c < cnt; ++c)
if (((bits >> c) & 1u) == 0u) lr[c0 + c] = -INFINITY;
}
}
/* ------------------------------------------------------------------ shim helpers */
static inline int sp_is_word(const RadTensor* t) {
return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32);
}
/* The params plane: [M, 24] words. The dtype test is not decoration -- a 16-bit view of the plane
* passes a byte-count check and then misreads every row, sampling with the top half of one row's
* temp and the bottom of the next. */
static inline int params_ok(const RadTensor* t, long long M) {
if (!t || !t->data) return RAD_E_INVAL;
if (!sp_is_word(t)) return RAD_E_DTYPE;
if (r3d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return RAD_E_SHAPE;
if (!r3d_contig(t)) return RAD_E_STRIDE;
if (!r3d_aligned(r3d_p(t), 8)) return RAD_E_ALIGN; /* seed and pos are 8-byte fields */
return RAD_OK;
}
static inline int logits_ok(const RadTensor* t) {
if (!t || !t->data) return RAD_E_INVAL;
if (!r3d_is_f32(t)) return RAD_E_DTYPE;
if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN;
return RAD_OK;
}
/* The history plane: i32 [M, max_hist], contiguous, its width the reference's `hmax`. */
static inline int hist_ok(const RadTensor* t, long long M, long long* hmax) {
if (!t || !t->data) return RAD_E_INVAL;
if (!r3d_is_i32(t)) return RAD_E_DTYPE;
if (!r3d_contig(t)) return RAD_E_STRIDE;
if (!r3d_aligned(r3d_p(t), 4)) return RAD_E_ALIGN;
const long long w = r3d_numel(t) / M;
if (w <= 0 || w > 0x7fffffffLL) return RAD_E_SHAPE;
*hmax = w;
return RAD_OK;
}
static inline int r3d_launch_status(int rc) {
if (rc == 0) return RAD_OK;
switch (rc) {
case -1: return RAD_E_INVAL;
case -2: return RAD_E_SHAPE;
case -3: return RAD_E_STRIDE;
default: return RAD_E_DEVICE;
}
}
/* The logits row count, from the plane and never from the band's M. */
static inline int logits_rows(const RadArgs* a, const RadTensor* lg, long long* n_vocab,
long long* rows, long long* lg_ld) {
/* The reference reads the width off the band, falling back to the plane's last dimension, and
* a rank-1 plane has no last dimension to read: the width is absent, which is E_SHAPE. */
*n_vocab = r3d_geti_or(a, "n_vocab",
lg->rank >= 2 ? r3d_dim(lg, (int)lg->rank - 1) : 0);
if (*n_vocab <= 0 || *n_vocab > 0x7fffffffLL) return RAD_E_SHAPE;
*lg_ld = r3d_rows_pitch(lg, *n_vocab, rows);
if (*lg_ld < 0) return RAD_E_STRIDE;
if (*rows <= 0 || *rows > 0x7fffffffLL) return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
#define R3D_NEED(x) \
do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0)
/* ================================================================== launchers
*
* lg [M][n_vocab] f32, INOUT for the four editing stages, read-only for logprobs
* params [M] 24 words a row, the per-row scalars
* hist [M][max_hist] i32, global token ids, `hist_off`/`hist_len` windowing it
* stats [M][2 + 2k] f32
* bitmask [rows][(n_vocab+31)/32] i32, a set bit meaning allowed
*
* 0, -1 null, -2 bad extent, -3 pitch, -4 the HIP launch failed. No allocation, no synchronisation.
*/
extern "C" int r3d_sample_logprobs(long lg, long params, long stats, int M, int n_vocab, int k,
long long lg_ld, long long stats_ld, int vocab_off,
long stream) {
if (!lg || !params || !stats) return -1;
if (M <= 0 || n_vocab <= 0 || k <= 0) return -2;
if (k > kKMax) return -2;
if (!lg_ld) lg_ld = n_vocab;
if (!stats_ld) stats_ld = 2 + 2 * (long long)k;
if (lg_ld < n_vocab || stats_ld < 2 + 2 * (long long)k) return -3;
R3D_KLAUNCH(R3D_KNAME(sample_logprobs_kernel<kThreads>), dim3((uint32_t)M), dim3(kThreads),
(hipStream_t)(uintptr_t)stream, (const float*)(uintptr_t)lg,
(const RadSampleParams*)(uintptr_t)params, (float*)(uintptr_t)stats,
(uint32_t)n_vocab, (uint32_t)k, (uint32_t)lg_ld, (uint32_t)stats_ld,
(int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_sample_penalties(long lg, long params, long hist, int M, int n_vocab,
long long lg_ld, long long hist_ld, int vocab_off,
long stream) {
if (!lg || !params || !hist) return -1;
if (M <= 0 || n_vocab <= 0) return -2;
if (!lg_ld) lg_ld = n_vocab;
if (!hist_ld) return -2; /* the window is clamped to the plane's width */
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
R3D_KLAUNCH(R3D_KNAME(sample_penalties_kernel), dim3((uint32_t)M), dim3(kPre),
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_sample_dry(long lg, long params, long hist, long breakers, int M, int n_vocab,
long long lg_ld, long long hist_ld, int vocab_off, long stream) {
if (!lg || !params || !hist) return -1;
if (M <= 0 || n_vocab <= 0) return -2;
if (!lg_ld) lg_ld = n_vocab;
if (!hist_ld) return -2;
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
R3D_KLAUNCH(R3D_KNAME(sample_dry_kernel), dim3((uint32_t)M), dim3(kPre),
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
(const uint8_t*)(uintptr_t)breakers, (uint32_t)n_vocab, (uint32_t)lg_ld,
(uint32_t)hist_ld, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_sample_ngram_ban(long lg, long params, long hist, long ngram, long whitelist,
int M, int n_vocab, long long lg_ld, long long hist_ld,
int vocab_off, long stream) {
if (!lg || !params || !hist || !ngram) return -1;
if (M <= 0 || n_vocab <= 0) return -2;
if (!lg_ld) lg_ld = n_vocab;
if (!hist_ld) return -2;
if (lg_ld < n_vocab || hist_ld <= 0) return -3;
const uint32_t words = (uint32_t)((n_vocab + 31) / 32);
R3D_KLAUNCH(R3D_KNAME(sample_ngram_ban_kernel), dim3((uint32_t)M), dim3(kPre),
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)hist,
(const int32_t*)(uintptr_t)ngram, (const int32_t*)(uintptr_t)whitelist,
(uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hist_ld, words, (int32_t)vocab_off);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r3d_sample_mask(long lg, long params, long bitmask, int M, int n_vocab,
long long lg_ld, int mask_rows, long stream) {
if (!lg || !params || !bitmask) return -1;
if (M <= 0 || n_vocab <= 0) return -2;
if (!lg_ld) lg_ld = n_vocab;
if (lg_ld < n_vocab) return -3;
if (mask_rows < M) return -3; /* a plane that cannot address row M-1 is not that plane */
const uint32_t words = (uint32_t)((n_vocab + 31) / 32);
/* mask_rows is the bitmask plane's own row count, which is what the reference compares
* mask_row against, and the shim reads it off the operand. It is M at the geometry the shape
* hook draws and the engine builds, and larger when a caller hands a plane of its own, in which
* case a row addressing past M is masked, as the reference masks it. The grid stays M: rows
* past the logits plane's row count have no logits to mask. */
R3D_KLAUNCH(R3D_KNAME(sample_mask_kernel), dim3((uint32_t)M), dim3(kThreads),
(hipStream_t)(uintptr_t)stream, (float*)(uintptr_t)lg,
(const RadSampleParams*)(uintptr_t)params, (const int32_t*)(uintptr_t)bitmask,
(uint32_t)n_vocab, (uint32_t)lg_ld, words, (uint32_t)mask_rows);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* ================================================================== shims
*
* libref's operand lists: {logits, params, history[, breakers]} for the history stages,
* {logits, params, ngram, whitelist?} for the ban, {logits, params, bitmask} for the mask and
* {logits, params, stats} for logprobs. M is the logits plane's row count.
*/
extern "C" int r3d_rad_sample_logprobs(const RadArgs* a, RadStream stream) {
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* pr = r3d_opt(a, 1);
const RadTensor* st = r3d_opt(a, 2);
R3D_NEED(logits_ok(lg));
const long long k = r3d_geti_or(a, "k", 0);
if (k <= 0) return R3D_NO(RAD_E_SHAPE);
/* The pool is 64 deep per lane, which is above every k the engine requests. A row carrying
* C_LE("k", 64) is what keeps a request above it out of the band. */
if (k > kKMax) return R3D_NO(RAD_E_UNSUPPORTED);
long long n_vocab = 0, rows = 0, lg_ld = 0;
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
R3D_NEED(params_ok(pr, rows));
if (!st || !st->data) return R3D_NO(RAD_E_INVAL);
if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE);
long long srows = 0;
const long long st_ld = r3d_rows_pitch(st, 2 + 2 * k, &srows);
if (st_ld < 0) return R3D_NO(RAD_E_STRIDE);
if (srows < rows) return R3D_NO(RAD_E_SHAPE);
return r3d_launch_status(r3d_sample_logprobs(
r3d_addr(lg), r3d_addr(pr), r3d_addr(st), (int)rows, (int)n_vocab, (int)k, lg_ld, st_ld,
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
}
extern "C" int r3d_rad_sample_penalties(const RadArgs* a, RadStream stream) {
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* pr = r3d_opt(a, 1);
const RadTensor* hi = r3d_opt(a, 2);
R3D_NEED(logits_ok(lg));
long long n_vocab = 0, rows = 0, lg_ld = 0;
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
R3D_NEED(params_ok(pr, rows));
long long hmax = 0;
R3D_NEED(hist_ok(hi, rows, &hmax));
return r3d_launch_status(r3d_sample_penalties(
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), (int)rows, (int)n_vocab, lg_ld, hmax,
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
}
extern "C" int r3d_rad_sample_dry(const RadArgs* a, RadStream stream) {
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* pr = r3d_opt(a, 1);
const RadTensor* hi = r3d_opt(a, 2);
const RadTensor* brk = r3d_opt(a, 3);
R3D_NEED(logits_ok(lg));
long long n_vocab = 0, rows = 0, lg_ld = 0;
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
R3D_NEED(params_ok(pr, rows));
long long hmax = 0;
R3D_NEED(hist_ok(hi, rows, &hmax));
long long baddr = 0;
if (brk && brk->data) {
/* One byte a history position, the exemption matching the history position for position. */
if (!r3d_is_u8(brk)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(brk)) return R3D_NO(RAD_E_STRIDE);
if (r3d_numel(brk) < rows * hmax) return R3D_NO(RAD_E_SHAPE);
baddr = r3d_addr(brk);
}
return r3d_launch_status(r3d_sample_dry(
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), baddr, (int)rows, (int)n_vocab, lg_ld, hmax,
(int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
}
extern "C" int r3d_rad_sample_ngram_ban(const RadArgs* a, RadStream stream) {
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* pr = r3d_opt(a, 1);
const RadTensor* hi = r3d_opt(a, 2);
const RadTensor* ng = r3d_opt(a, 3);
const RadTensor* wl = r3d_opt(a, 4);
R3D_NEED(logits_ok(lg));
long long n_vocab = 0, rows = 0, lg_ld = 0;
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
R3D_NEED(params_ok(pr, rows));
long long hmax = 0;
R3D_NEED(hist_ok(hi, rows, &hmax));
if (!ng || !ng->data) return R3D_NO(RAD_E_INVAL);
if (!r3d_is_i32(ng)) return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(ng) || r3d_numel(ng) < 2 * rows) return R3D_NO(RAD_E_SHAPE);
const long long words = (n_vocab + 31) / 32;
long long waddr = 0;
if (wl && wl->data) {
if (wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(wl)) return R3D_NO(RAD_E_STRIDE);
if (r3d_numel(wl) < rows * words) return R3D_NO(RAD_E_SHAPE);
waddr = r3d_addr(wl);
}
return r3d_launch_status(r3d_sample_ngram_ban(
r3d_addr(lg), r3d_addr(pr), r3d_addr(hi), r3d_addr(ng), waddr, (int)rows, (int)n_vocab,
lg_ld, hmax, (int)r3d_geti_or(a, "vocab_off", 0), (long)(uintptr_t)stream));
}
extern "C" int r3d_rad_sample_mask(const RadArgs* a, RadStream stream) {
const RadTensor* lg = r3d_opt(a, 0);
const RadTensor* pr = r3d_opt(a, 1);
const RadTensor* bm = r3d_opt(a, 2);
R3D_NEED(logits_ok(lg));
long long n_vocab = 0, rows = 0, lg_ld = 0;
R3D_NEED(logits_rows(a, lg, &n_vocab, &rows, &lg_ld));
R3D_NEED(params_ok(pr, rows));
if (!bm || !bm->data) return R3D_NO(RAD_E_INVAL);
if (bm->dtype != RAD_I32 && bm->dtype != RAD_U32) return R3D_NO(RAD_E_DTYPE);
if (!r3d_contig(bm)) return R3D_NO(RAD_E_STRIDE);
const long long words = (n_vocab + 31) / 32;
if (words <= 0 || r3d_numel(bm) < rows * words) return R3D_NO(RAD_E_SHAPE);
/* The plane's own row count is the bound the reference tests, and the plane may be longer than
* the logits: a caller that hands a plane of its own gets its rows. */
const long long mask_rows = r3d_numel(bm) / words;
return r3d_launch_status(r3d_sample_mask(r3d_addr(lg), r3d_addr(pr), r3d_addr(bm), (int)rows,
(int)n_vocab, lg_ld, (int)mask_rows,
(long)(uintptr_t)stream));
}
/* ================================================================== the lane helpers, proved
*
* Every wave-sum in libr3d is a butterfly over lane shuffles, and the arithmetic that rides on a
* lane shuffle is invisible to a codec sweep: a helper that hands back a stale half of a 64-bit
* value reads as a few percent of a perplexity, in a model nobody suspects. This file
* has one of the shapes in it -- the logprobs k-list crosses lanes as 8-byte values -- so it also
* carries the control that checks the helpers, on the card, one entry per lane per wave.
*
* On this box (gfx1102, -O2 and -O3, wave32) the control is exact in **all 256 lanes of all 8
* waves**: seeds at wave-local lanes 6, 9, 19 and 25, five butterfly rounds, and every form of the
* 64-bit exchange -- `r3d_xor_lane_u64` (two 32-bit shuffles of the halves), the same shape written
* as a `__shfl_xor_sync` per half, and one shuffle of the 64-bit value -- with the lane's value
* derived from `threadIdx.x`, loaded from a plane, and accumulated in a grid-stride loop.
* `r3d_xor_lane_u64` is sound; the form it must not be written in converts by value:
*
* d += (double)r3d_xor_lane_u64<N>((unsigned long long)d); // WRONG
*
* `(unsigned long long)d` converts a double to an integer **by value** and `(double)` converts back
* by value, so the partner's term arrives truncated to its integer part. A wave of fractions then
* sums to 1 -- the largest term's integer part -- a 40% loss of the row's mass at the band's width,
* and a loss that vanishes when the terms are integers: an integer survives the round trip. Nothing
* about the lane shuffle is involved, and a codec sweep cannot see it, because the expression is not
* a codec. The correct form moves bits, not values (`bits_of` / `d_from_bits` below), which is what
* the k-list's shuffle does.
*
* The two traps of this shape are the whole content of the warning: summing a
* float's IEEE pattern as an integer, and converting a float's pattern to a value. The control
* catches both, in both directions, on the card, in every lane.
*/
__device__ __forceinline__ double d_from_bits(unsigned long long b) {
double d;
__builtin_memcpy(&d, &b, sizeof d);
return d;
}
__device__ __forceinline__ unsigned long long bits_of(double d) {
unsigned long long b;
__builtin_memcpy(&b, &d, sizeof b);
return b;
}
__global__ __launch_bounds__(256) void lanes_check_kernel(double* __restrict__ out) {
/* kThreads and kWave are this file's anonymous-namespace names and are ambiguous out here, so
* the control spells its own geometry. */
constexpr uint32_t kLWave = 32, kLBlock = 256;
/* Seeds at wave-local lanes 6, 9, 19, 25: a wave with four non-zero lanes and an expected sum
* of 0.08945 + 1 + 0.5971 + 0.9768, in the butterfly's own order. Every wave carries them, so
* every wave is checked. */
const uint32_t lane = threadIdx.x & (kLWave - 1);
const double seed = (lane == 6) ? 0.08945 : (lane == 9) ? 1.0 : (lane == 19) ? 0.5971
: (lane == 25) ? 0.9768 : 0.0;
__shared__ double s_d[kLBlock];
__shared__ float s_f[kLBlock];
s_d[threadIdx.x] = seed;
s_f[threadIdx.x] = (float)seed;
__syncthreads();
/* Form 0: the 32-bit butterfly every wave-sum in the library is built from, over a value read
* out of LDS so it is a memory operand and not a constant. */
float f = s_f[threadIdx.x];
f += r3d_xor_lane<16>(f);
f += r3d_xor_lane<8>(f);
f += r3d_xor_lane<4>(f);
f += r3d_xor_lane<2>(f);
f += r3d_xor_lane<1>(f);
out[0 * kLBlock + threadIdx.x] = (double)f;
/* Form 1: the halves form over a value derived from the lane index. The pattern goes to the
* helper and back through bits_of/d_from_bits: a cast between double and an integer type
* converts the value, which is what this control guards against. */
double d = seed;
#define R3D_L64(N) d += d_from_bits(r3d_xor_lane_u64<N>(bits_of(d)));
R3D_L64(16) R3D_L64(8) R3D_L64(4) R3D_L64(2) R3D_L64(1)
#undef R3D_L64
out[1 * kLBlock + threadIdx.x] = d;
/* Form 2: the same halves form over a value loaded from LDS, the shape an accumulator has. */
d = s_d[threadIdx.x];
#define R3D_L64B(N) d += d_from_bits(r3d_xor_lane_u64<N>(bits_of(d)));
R3D_L64B(16) R3D_L64B(8) R3D_L64B(4) R3D_L64B(2) R3D_L64B(1)
#undef R3D_L64B
out[2 * kLBlock + threadIdx.x] = d;
/* Form 3: one shuffle of the 64-bit pattern, the form this file's k-list uses. The mask is
* 0xFFFFFFFFull, the 32 lanes a wave32 wave has. */
d = s_d[threadIdx.x];
#define R3D_S64(N) d += d_from_bits(__shfl_xor_sync(0xFFFFFFFFull, bits_of(d), N));
R3D_S64(16) R3D_S64(8) R3D_S64(4) R3D_S64(2) R3D_S64(1)
#undef R3D_S64
out[3 * kLBlock + threadIdx.x] = d;
}
/* Four forms x 256 lanes of doubles (8 KiB, which the caller owns: this launcher allocates nothing,
* as every launcher in this file does). 0, -1 null, -4 the launch failed. r3d_selftest.cpp dlsyms
* this by name and compares every lane against a host emulation of the same five rounds. */
extern "C" int r3d_lanes_check(long out, long stream) {
if (!out) return -1;
R3D_KLAUNCH(R3D_KNAME(lanes_check_kernel), dim3(1), dim3(256),
(hipStream_t)(uintptr_t)stream, (double*)(uintptr_t)out);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
File diff suppressed because it is too large. Load diff
+836
View File
@@ -0,0 +1,836 @@
/* r3d_shapes.cpp -- the extent and content domain of each operand of an op at a geometry.
*
* This is libr3d's side of the `RadShapeFn` hook: the component that reads an operand is the one
* that knows its extent. The hand-written table in `tools/` describes the ops it was written
* against; a row that exists only here is invisible to it, and a tool that cannot size an operand
* cannot call the op cold. So correctness checks, benchmarks and the coverage census reach these
* rows through this hook.
*
* The authority for every extent is the shim, not the prose or the row table. Each `r3d_rad_*`
* entry point unpacks `RadArgs.t[i]` into extents and pitches; if a shim passes `x->shape[1]` as
* `n`, that is what the operand is. Each group names its unit, and a change to a shim's contract
* must be mirrored here.
*
* Content matters as much as size. A token id gathers a row of a codebook, a KV slot indexes
* n_blocks * block_size positions, a block-table entry indexes n_blocks. Drawn from the wrong
* range, such an operand tests the kernel's out-of-range handling instead of its arithmetic, and a
* scatter whose indices collide is a race the parallel rerun rightly reports as a failure.
* `RAD_FILL_INDEX` with an explicit `idx_max` states each range, and `RAD_OPD_F_IDX_UNIQUE` marks
* the scatters that need distinct destinations.
*
* ============================================================ rows with no description
*
* A decline is a real answer: the caller skips and counts the case, where an invented extent
* yields a meaningless pass. These rows carry a null `opd_shape`:
*
* gemm_nt_q at a quantised `a` whose scale plane the row does not name
* Not present in libr3d: both quantised rows state their activation dtype in `dtype`, so
* `a` is bf16 against an fp8 weight (fp8a16) or i8 against an i8 weight (i8a8), and both are
* described below. The case is listed here because it is the one libr4d declines, and a
* reader comparing the two files will look for the difference.
*
* rope at a multi-component mode
* mrope, imrope and axial take one position per component, component-major, and the
* component count comes from the `sections` string. libr3d's kernel implements neox and gptj
* and its row's constraints say so, so a geometry with `sections` set is never routed here.
*
* No tuned axis is read here: this plugin's axes (split counts, wave counts, the streaming mode)
* change how a kernel walks its operands, not their extents. An axis that did would be read from
* `p`, where the core appends the chosen point.
*
* Pure host code (no r3d.h, no HIP), like r3d_rows.cpp, so the tables compile and can be read
* without ROCm.
*/
#include <cstdint>
#include <cstring>
#include "r3d_plugin.h"
namespace {
/* ==================================================================== building a description
*
* Each op builds its whole operand list in schema order and hands out the one asked for, so the
* count can be checked by eye against the schema in r3d_rows.cpp (the tool also checks it against
* `RadOpSchema::n_operands`).
*/
/* A plain operand of up to four extents. A trailing 0 ends the shape; zero is never a legal
* extent (`pick` refuses one), so it cannot be mistaken for a real one. */
RadOpdDesc opd(uint32_t dt, int64_t d0, int64_t d1 = 0, int64_t d2 = 0, int64_t d3 = 0) {
RadOpdDesc d{};
d.dtype = dt;
d.fill = RAD_FILL_NORMAL;
/* -1 is "draw"; set explicitly though the caller pre-initialises it. */
d.idx_const = -1;
const int64_t e[4] = { d0, d1, d2, d3 };
for (int i = 0; i < 4 && e[i] != 0; ++i) d.shape[d.rank++] = e[i];
return d;
}
/* An index operand. `idx_max` is the exclusive upper bound of the draw; 0 means the previous
* operand's leading extent (the ABI default, right for a gather from the operand before it).
* `konst >= 0` fills every element with that value. Always i32: every index libr3d reads is signed
* 32-bit. */
RadOpdDesc opd_idx(int64_t d0, int64_t idx_max, int64_t konst = -1, uint32_t flags = 0,
int64_t d1 = 0) {
RadOpdDesc d = opd((uint32_t)RAD_I32, d0, d1);
d.fill = RAD_FILL_INDEX;
d.idx_max = idx_max;
d.idx_const = konst;
d.flags = flags;
return d;
}
/* An optional operand this description does not pass. One entry per schema operand is still
* emitted, so absence needs a spelling; to the ABI it means a null RadTensor. */
RadOpdDesc opd_none() {
RadOpdDesc d{};
d.idx_const = -1;
d.flags = RAD_OPD_F_ABSENT;
return d;
}
/* Restricts the fill to (0, 1); `RAD_FILL_SIGMOID` is the ABI's only such draw. A scale plane drawn
* from a normal is as likely to be negative as positive, and a negative descale inverts the sign of
* an entire quantised block. */
RadOpdDesc in_unit(RadOpdDesc d) { d.fill = RAD_FILL_SIGMOID; return d; }
/* Hands out operand `operand` of a list after checking the whole list, so a geometry missing a
* parameter declines every operand rather than describing a few and declining the rest. A
* non-positive extent means a needed parameter was absent or zero: RAD_E_UNSUPPORTED, not
* RAD_E_SHAPE, which would read as a tool bug. An index outside the list is a bug here or in the
* schema, reported as RAD_E_SHAPE. */
int pick(RadOpdDesc* out, int operand, const RadOpdDesc* list, int n) {
if (!out || !list || n <= 0) return RAD_E_INVAL;
for (int i = 0; i < n; ++i) {
if (list[i].flags & RAD_OPD_F_ABSENT) continue;
if (list[i].rank == 0 || list[i].rank > RAD_MAX_RANK) return RAD_E_UNSUPPORTED;
for (uint32_t d = 0; d < list[i].rank; ++d)
if (list[i].shape[d] <= 0) return RAD_E_UNSUPPORTED;
}
if (operand < 0 || operand >= n) return RAD_E_SHAPE;
*out = list[operand];
return RAD_OK;
}
#define R3D_PICK(list) return pick(out, operand, (list), (int)(sizeof(list) / sizeof((list)[0])))
/* ==================================================================== parameters
*
* `M` and the other ranged parameters read as the band's bound, not any one step's row count (as
* in every shim here): buffers must hold the whole band the kernel was selected for.
*
* Not r3d_pgeti_or(): that reads RAD_P_INT only, which suits a launch (every range has collapsed
* by then), but this hook can see ranges still open. rad_param_getdim (ABI, shared with libr4d)
* reads a RAD_P_RANGE as its high bound.
*/
int64_t gi(const RadParam* p, int n_p, const char* k, int64_t dflt) {
return rad_param_getdim(p, n_p, k, dflt);
}
const char* gs(const RadParam* p, int n_p, const char* k) {
return rad_param_gets(p, n_p, k, nullptr);
}
/* The activation dtype, from `dtype` and its attention spellings; bf16 when the geometry names
* none. A quantisation-scheme string ("fp8a16", "w8a16") is not a dtype and lands on bf16, which
* is what the quantised rows use it to mean: the scheme picks the weight's dtype, the row states
* the activation's. */
uint32_t act_dt(const RadParam* p, int n_p) {
const char* s = gs(p, n_p, "dtype");
if (!s) s = gs(p, n_p, "q_dtype");
const uint32_t dt = rad_dtype_parse(s);
return dt == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : dt;
}
/* The scale-stream group count, matching the quantisers' launches: `group` <= 0 or wider than the
* row is one scale per row, otherwise ceil(n / group). */
int64_t scale_groups(int64_t n, int64_t group) {
int64_t g = group;
if (g <= 0 || g > n) g = n;
return g > 0 ? (n + g - 1) / g : 0;
}
/* ==================================================================== elementwise and norms
* r3d_model_bf16.hip
*/
} /* namespace */
extern "C" {
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. The gain is described at its full width; the
* form with no gain at all is a hand case, since a null optional operand is not a fill domain. */
int r3d_shape_rmsnorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, M, n) }; /* x, w, y */
R3D_PICK(list);
}
/* The two-pass form. `b` is optional and passed: the biased form covers strictly more code, and a
* null optional operand is not a fill domain a tool can draw. */
int r3d_shape_layernorm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, n), opd(D, n), opd(D, M, n) }; /* x,w,b,y */
R3D_PICK(list);
}
/* add / mul share a schema and a description. `b` is described at full extent; the row-broadcast
* form is not described, since a buffer of n elements against M rows cannot be told from a shape
* bug by a tool that sizes by shape alone. */
static int binary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, M, n) }; /* a, b, y */
return pick(out, operand, list, 3);
}
int r3d_shape_add(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return binary_shape(p, n_p, operand, out);
}
int r3d_shape_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return binary_shape(p, n_p, operand, out);
}
/* y = act(gate) * up over two [M, n] operands. The fused [M, 2n] form is the one the model
* issues; describing it here would be a second spelling of a geometry the row's `n` is about, so
* the two halves are described as the kernel sees them. */
int r3d_shape_act_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return binary_shape(p, n_p, operand, out);
}
/* x -> y, one dtype to another. Operand dtypes come from `from` and `to`; an unparseable spelling
* falls back to f32, the widest it could mean. */
int r3d_shape_cast(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
uint32_t from = rad_dtype_parse(gs(p, n_p, "from"));
uint32_t to = rad_dtype_parse(gs(p, n_p, "to"));
if (from == (uint32_t)RAD_DT_INVALID) from = (uint32_t)RAD_F32;
if (to == (uint32_t)RAD_DT_INVALID) to = (uint32_t)RAD_F32;
const RadOpdDesc list[] = { opd(from, M, n), opd(to, M, n) }; /* x, y */
R3D_PICK(list);
}
/* The unary activations and softmax: x and y at the same extent. */
static int unary_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n) }; /* x, y */
return pick(out, operand, list, 2);
}
int r3d_shape_silu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, out);
}
int r3d_shape_gelu(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, out);
}
int r3d_shape_sigmoid(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, out);
}
int r3d_shape_softmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
return unary_shape(p, n_p, operand, out);
}
/* y = x * s. `s` is one element, broadcast over everything; a row of them would be a different op. */
int r3d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) }; /* x, s, y */
R3D_PICK(list);
}
/* y = value. The only operand is the output, so a case's whole content is the kernel's. */
int r3d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, n) };
R3D_PICK(list);
}
/* ==================================================================== the model's odds and ends
* r3d_model_bf16.hip
*/
/* In-place rotary over a fused qkv row: n_head q heads, then n_head_kv each of k and v. The
* positions are drawn over the row count, which for a single step is its own positions; a step
* crossing a context boundary is a hand case, since a fill cannot spell "contiguous from an
* arbitrary start". */
int r3d_shape_rope(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t nh = gi(p, n_p, "n_head", 0);
const int64_t nkv = gi(p, n_p, "n_head_kv", nh);
if (M <= 0 || hd <= 0 || nh <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_BF16, M, (nh + 2 * nkv) * hd), /* qkv, INOUT */
opd_idx(M, 0) /* positions */
};
R3D_PICK(list);
}
/* K and V into a paged cache. Two blocks of slack over the tokens, so the slot mapping is not a
* dense prefix and the block index matters. Only the cache takes `kv_dtype`: k and v are bf16
* activations whatever the cache stores. */
int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t kvh = gi(p, n_p, "n_head_kv", 0);
const int64_t bs = gi(p, n_p, "block_size", 0);
if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0) return RAD_E_UNSUPPORTED;
const int64_t nb = (M + bs - 1) / bs + 2;
const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_BF16 : kv;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_BF16, M, kvh, hd), /* k */
opd((uint32_t)RAD_BF16, M, kvh, hd), /* v */
opd_idx(M, nb * bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping */
opd(KV, nb, kvh, bs, 2 * hd) /* kv_cache, INOUT */
};
R3D_PICK(list);
}
/* x[r] = wte[ids[r] - vocab_offset]. Ids are global, so the draw's bound is `vocab_offset + n_vocab`:
* under a shard the draw crosses the slice boundary and exercises the zero-row path. */
int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t ne = gi(p, n_p, "n_embd", 0);
const int64_t nv = gi(p, n_p, "n_vocab", 0);
const int64_t vo = gi(p, n_p, "vocab_offset", 0);
if (M <= 0 || ne <= 0 || nv <= 0 || vo < 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const RadOpdDesc list[] = {
opd_idx(M, vo + nv), /* tokens */
opd(D, nv, ne), /* wte */
opd(D, M, ne) /* x */
};
R3D_PICK(list);
}
/* The source is 4x the gathered height so the gather is not the identity, which would pass while
* broken; `idx` draws over those 4M rows. */
int r3d_shape_gather_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, 4 * M, n), opd_idx(M, 0), opd(D, M, n) }; /* x, idx, y */
R3D_PICK(list);
}
/* Onto exactly M rows a scatter is a permutation, which a kernel ignoring `idx` could pass, so the
* destination is 4x the scattered height and unnamed rows must come back unchanged. The indices are
* distinct: two rows drawing one destination is a race. */
int r3d_shape_scatter_rows(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = {
opd(D, M, n), opd_idx(M, 4 * M, -1, RAD_OPD_F_IDX_UNIQUE), opd(D, 4 * M, n)
}; /* v, idx, x (INOUT) */
R3D_PICK(list);
}
/* ================================================================== quantisation
* r3d_quant_fp8.hip
*/
/* Codes row-major at [M, n], one f32 scale per (row, `group` of n). `dtype` names the input; the
* output's dtype is in the op name. */
int r3d_shape_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = {
opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng)
}; /* x, q, scale */
R3D_PICK(list);
}
/* The int8 twin, with the optional row-sum plane beside it. `asum` is described whenever `group`
* divides n, so a case checks the row sums as well; it is group-major, the layout libref's
* quant_act_i8 writes. */
/* The per-row int8: one scale per row, in a [M, 1] plane (the reference writes it at pitch 1, so a
* plane with more room is legal and this states the tightest one), and the optional `asum` described
* whenever `group` divides n, so a case exercises the row sums too. `q` is in the step order --
* described by its extent, because a description states a plane's size and content domain, not a
* permutation; the row's `shape` prose names the order. */
int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0), g = gi(p, n_p, "group", 0);
const RadOpdDesc list[] = {
opd(D, M, n),
opd((uint32_t)RAD_I8, M, n),
opd((uint32_t)RAD_F32, M, 1),
(g > 0 && n % g == 0) ? opd((uint32_t)RAD_F32, n / g, (M + 15) / 16 * 16) : opd_none()
}; /* x, q, scale, asum */
R3D_PICK(list);
}
/* The per-group int8, the activation the i8a8 GEMM reads: the fp8 quantiser's extents at int8 codes
* and a 127 denominator. */
int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = {
opd(D, M, n), opd((uint32_t)RAD_I8, M, n), opd((uint32_t)RAD_F32, M, ng)
}; /* x, q, scale */
R3D_PICK(list);
}
/* The gated form: gate_up is [M, 2n] with the gate first, and what is quantised is
* act(gate) * up over n columns. */
int r3d_shape_gated_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = {
opd(D, M, 2 * n),
opd((uint32_t)RAD_F8E4M3, M, n),
opd((uint32_t)RAD_F32, M, ng),
opd((uint32_t)RAD_BF16, M, n)
}; /* gate_up, q, scale, out_bf16 */
R3D_PICK(list);
}
/* y = code * scale. `dtype` names the code: E4M3 and E5M2 are the checkpoint's fp8, i8 the int8
* twin. The scale is a dequant multiplier, so its draw is restricted to (0, 1) -- a normal draw is
* as likely to be negative, and a negative scale inverts a whole block. */
int r3d_shape_dequant(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t g = gi(p, n_p, "group", 0);
const uint32_t qd = rad_dtype_parse(gs(p, n_p, "dtype"));
const uint32_t Q = qd == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_I8 : qd;
const RadOpdDesc list[] = {
opd(Q, M, n), in_unit(opd((uint32_t)RAD_F32, M, scale_groups(n, g))),
opd((uint32_t)RAD_BF16, M, n)
}; /* q, scale, y */
R3D_PICK(list);
}
/* ================================================================== gemm
* r3d_gemm_bf16_nt_m16.hip, r3d_gemm_bf16_nt_tiled.hip, r3d_gemm_fp8a16_nt_m1.hip
*/
/* y[M,N] = a[M,K] @ b[N,K]^T. Both operands are k-contiguous, which is what the transposed spelling
* in the op's name means and why neither is described as [K, N]. */
int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
const RadOpdDesc list[] = { opd(D, M, K), opd(D, N, K), opd(D, M, N) }; /* a, b, y */
R3D_PICK(list);
}
/* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head
* [n_vocab, n_embd] in the activation's dtype, the logits in f32 -- the dtype the schema states, not
* the one a GEMM would narrow to, because every sampler stage downstream reads f32 and a prefill
* band's plane is 1.07 GB of it at M=2048. The reference's own logits row answers a placement
* question (`ref_layout_head`: where the head lives) and so carries a layout hook; this row has
* nothing to place, it reads the head where it is stored, which is why the hook it declares is the
* shape and nothing else. A hook is the right thing to write *because* all three operands are
* describable: the extents the hook names are the ones that get filled, which is the opposite of
* the joined w2a8 plane, where a describable byte count is a container header waiting to be filled
* with random bytes. */
int r3d_shape_logits_gemm_bf16(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), nv = gi(p, n_p, "n_vocab", 0), ne = gi(p, n_p, "n_embd", 0);
if (M <= 0 || nv <= 0 || ne <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const RadOpdDesc list[] = { opd(D, M, ne), opd(D, nv, ne), opd(RAD_F32, M, nv) };
R3D_PICK(list); /* x, lm_head, logits */
}
/* The quantised GEMM. `dtype` names the scheme, and the scheme fixes which operands are coded:
*
* fp8a16 a bf16, b the checkpoint's E4M3 [N][K], b_scale one f32 per 128x128 block (the
* container's `weight_scale_inv`, whose dtype the container states: f32 at fp8a8f32,
* bf16 as DeepSeek's own scales are).
* fp8a8 a E4M3 against a_scale, one f32 per (row, `group` of K) -- quant_act_fp8's output
* feeding the GEMM, which is the reason the two rows state the same group.
* i8a8 i8 codes on both axes with an f32 scale per (row, `group`).
*
* `b_scale`'s plane is block-major [ceil(N/pb), ceil(K/pb)] for fp8 and row-major [N, ceil(K/group)]
* for i8: the two checkpoints spell it differently and both are the bytes on disk. */
int r3d_shape_gemm_nt_q(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
int64_t group = gi(p, n_p, "group", 0);
if (group <= 0) group = R3D_FP8_BLOCK; /* the block every block-scaled checkpoint uses */
const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group;
const char* q = gs(p, n_p, "dtype");
const bool i8a8 = q && !std::strcmp(q, "i8a8");
const bool a8 = q && (!std::strcmp(q, "fp8a8") || i8a8);
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
list[0] = opd(i8a8 ? (uint32_t)RAD_I8 : (a8 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16),
M, K); /* a */
list[1] = a8 ? in_unit(opd((uint32_t)RAD_F32, M, kb)) : opd_none(); /* a_scale */
list[2] = opd(i8a8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3, N, K); /* b */
list[3] = in_unit(opd((uint32_t)RAD_F32, i8a8 ? N : nb, kb)); /* b_scale */
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
list[5] = opd_none(); /* a_sum */
list[6] = opd_none(); /* b_ref */
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
}
/* The OCP-MXFP4 grid, libref's description for the dtype: the weight is e2m1, two a byte, with
* one e8m0 exponent per 32 of K, so the weight's planes are [N, K] of fp4_e2m1 and [N, K/32] of
* e8m0; `b_ref` is the same exponent plane, accepted beside an e2m1 weight and ignored. The
* activation is the fp8a8 row's -- E4M3 against one f32 per (row, 128 of K), drawn in (0, 1) as
* a quantiser's is. Both zero-point operands are absent: the scale is symmetric. */
int r3d_shape_gemm_nt_q_mxfp4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
if (K % 128) return RAD_E_UNSUPPORTED; /* the activation's scale group and the 32-block */
const char* q = gs(p, n_p, "dtype");
if (!q || std::strcmp(q, "mxfp4a8") != 0) return RAD_E_UNSUPPORTED;
const int64_t kb = K / 128;
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
list[0] = opd((uint32_t)RAD_F8E4M3, M, K); /* a */
RadOpdDesc as = opd((uint32_t)RAD_F32, M, kb); /* a_scale */
as.fill = RAD_FILL_SIGMOID; /* a quantiser's (0, 1) */
list[1] = as;
list[2] = opd((uint32_t)RAD_FP4E2M1, N, K); /* b: e2m1, two a byte */
/* The e8m0 scale, filled with 127: the factor 2^0. A normal draw of the u8 grid is an exponent
* as high as 227, a factor 2^100, and the plane would scale the output past the finiteness
* bound the run checks; 127 is the checkpoint's own cluster and no reserved value. */
RadOpdDesc e8 = opd((uint32_t)RAD_E8M0, N, K / 32); /* b_scale: e8m0 */
e8.fill = RAD_FILL_INDEX;
e8.idx_const = 127;
list[3] = e8;
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
list[5] = opd_none(); /* a_sum */
list[6] = e8; /* b_ref: the e8 plane */
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
}
/* The symmetric int4 / int8 weight grids, libref's descriptions: int8 activations in the step
* order against signed codes (I4, two a byte, or I8, one a byte) with one f16 scale per (row,
* 128 of K) and one f32 activation scale per row, drawn in (0, 1) as a quantiser's is. There is
* no zero point and no a_sum: the dequant is code times scale. */
static int shape_inta8(const RadParam* p, int n_p, int operand, RadOpdDesc* out, const char* q,
uint32_t bdt)
{
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), K = gi(p, n_p, "K", 0);
if (M <= 0 || N <= 0 || K <= 0) return RAD_E_UNSUPPORTED;
if (K % 128) return RAD_E_UNSUPPORTED; /* the weight's scale group */
const char* d = gs(p, n_p, "dtype");
if (!d || std::strcmp(d, q) != 0) return RAD_E_UNSUPPORTED;
const int64_t kb = K / 128;
RadOpdDesc list[R3D_GEMM_Q_NOPERAND];
list[0] = opd((uint32_t)RAD_I8, M, K); /* a, step order */
RadOpdDesc as = opd((uint32_t)RAD_F32, M, 1); /* a_scale, per row */
as.fill = RAD_FILL_SIGMOID;
list[1] = as;
list[2] = opd(bdt, N, K); /* b: the signed codes */
list[3] = opd((uint32_t)RAD_F16, N, kb); /* b_scale */
list[4] = opd((uint32_t)RAD_BF16, M, N); /* y */
list[5] = opd_none(); /* a_sum */
list[6] = opd_none(); /* b_ref */
return pick(out, operand, list, R3D_GEMM_Q_NOPERAND);
}
int r3d_shape_gemm_nt_q_w4a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
{
return shape_inta8(p, n_p, operand, out, "w4a8", (uint32_t)RAD_I4);
}
int r3d_shape_gemm_nt_q_w8a8(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
{
return shape_inta8(p, n_p, operand, out, "w8a8", (uint32_t)RAD_I8);
}
} /* extern "C" */
/* ==================================================================== r3d_sample_f32.hip, r3d_attn_paged_h128.hip
*
* The vocabulary and the sampler. The schemas in r3d_rows.cpp are transcribed from libref and
* checked against it, and these are the other half of that transcription. Every extent, dtype,
* fill domain and flag below is libref's: a description that differs from libref's is a case
* kbench skips, with one line saying so, and a row that is never exercised is a row that is not
* tested.
*
* The sampler's `params` operand is one plane with one fill domain, `RAD_FILL_SAMPLE_PARAMS`: the
* ABI's `RadSampleParams`, 96 bytes, 24 f32 words a row, whose fields the stages read by name. The
* history window and the mask-row count are placed *inside* that plane by `fill_chunk` and
* `idx_max`, so the draw produces a window that fits the plane and a `mask_row` that is a row of
* the bitmask plane (or -1, the unconstrained row sharing a short plane). Both are the stage's
* parameters to obey, not this file's invention.
*/
/* The sampler's parameter plane: [M, 24] f32, one RadSampleParams a row. */
RadOpdDesc opd_params(int64_t M, int64_t hist, int64_t mask_rows) {
RadOpdDesc d = opd((uint32_t)RAD_F32, M, 24);
d.fill = (uint32_t)RAD_FILL_SAMPLE_PARAMS;
d.fill_chunk = hist;
d.idx_max = mask_rows;
return d;
}
/* The widths libref's shapes choose, and the reasons it gives for them: the history window is what
* a deployment sizes the plane to, 64 is plausible; the candidate width is narrower than the
* vocabulary and wide enough for the narrowing stages. */
enum { kHist = 64, kCand = 64 };
/* `n_vocab` rows of f32 logits, and the parameter plane, the pair every vocabulary-width stage
* opens with. */
int sample_vocab(const RadParam* p, int n_p, int64_t* M, int64_t* nv) {
*M = gi(p, n_p, "M", 0);
*nv = gi(p, n_p, "n_vocab", 0);
return (*M > 0 && *nv > 0) ? RAD_OK : RAD_E_UNSUPPORTED;
}
/* silu(gate) * up over one fused projection: the operand is [M, 2n] and the output [M, n]. */
int r3d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const RadOpdDesc list[] = { opd(D, M, 2 * n), opd(D, M, n) }; /* gate_up (gate first), y */
R3D_PICK(list);
}
/* The fused add + norm + quantiser. `residual` is INOUT and the sum it holds is the bf16 one the
* variance reads, so x and residual are the same shape by the op's meaning, not by convenience;
* `out_bf16`, optional, is what the codes were taken over, and it exists so a test can read the
* value the quantiser saw. */
int r3d_shape_rmsnorm_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const uint32_t D = act_dt(p, n_p);
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0));
const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, n),
opd((uint32_t)RAD_F8E4M3, M, n), opd((uint32_t)RAD_F32, M, ng),
opd((uint32_t)RAD_BF16, M, n) };
R3D_PICK(list); /* x, residual, w, q, scale, out_bf16 */
}
/* Paged attention. The context is deeper than the query: one sequence whose context is its query
* length is the smallest geometry, and the one that exercises nothing -- no deep paging, no KV
* split, no window -- so `ctx`, when a harness passes it, wins, and is never below the query.
* `q_len` is the ranged parameter; a decode row and a 2048-token prefill chunk are different
* kernels (docs/OPS.md). */
int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "q_len", 0);
const int64_t hd = gi(p, n_p, "head_dim", 0);
const int64_t bs = gi(p, n_p, "block_size", 16);
const int64_t gqa = gi(p, n_p, "gqa", 1);
const int64_t nh = gi(p, n_p, "n_head", gqa);
if (M <= 0 || hd <= 0 || bs <= 0 || gqa <= 0 || nh <= 0 || nh % gqa) return RAD_E_UNSUPPORTED;
const int64_t kvh = nh / gqa;
const int64_t S = 1;
/* `ctx`, as the reference spells it -- and it is NOT the band's `max_ctx`, which is why a
* geometry that wants a context deeper than its query chunk has to name `ctx`. When no case
* names it, the context is the query chunk. */
int64_t ctx = gi(p, n_p, "ctx", 0);
if (ctx < M) ctx = M;
const int64_t max_blocks = (ctx + bs - 1) / bs;
const uint32_t Q = act_dt(p, n_p);
const uint32_t kv = rad_dtype_parse(gs(p, n_p, "kv_dtype"));
const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? Q : kv;
const RadOpdDesc list[] = {
opd(Q, S * M, nh, hd), /* q */
opd(KV, max_blocks, kvh, bs, 2 * hd), /* kv_cache */
opd_idx(S, max_blocks, -1, 0, max_blocks), /* block_table: indexes blocks,
may repeat -- a page table */
opd_idx(S, 0, ctx), /* seqused: a constant, not a draw */
opd_none(), /* k_descale: no per-(seq,head) */
opd_none(), /* v_descale */
opd_none(), /* cu_seqlens: the rectangular
reading at one sequence */
opd(Q, S * M, nh, hd) /* out */
};
R3D_PICK(list);
}
/* Exact per-row top-R. `pairs` is described because its packing is checked: an int32 id's bits in
* the first slot beside its value, so the plane is f32 to hold the value. */
int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0), N = gi(p, n_p, "N", 0), R = gi(p, n_p, "R", 0);
if (M <= 0 || N <= 0 || R <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
const RadOpdDesc list[] = {
opd(D, M, N), opd((uint32_t)RAD_I32, M, R), opd((uint32_t)RAD_F32, M, R),
opd((uint32_t)RAD_F32, M, R, 2)
}; /* x, idx, val, pairs */
R3D_PICK(list);
}
int r3d_shape_sample_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M)
}; /* logits, params, token */
R3D_PICK(list);
}
int r3d_shape_sample_temp(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0) };
R3D_PICK(list); /* logits INOUT, params */
}
/* DFlash2's candidate walk, slot for slot from libref's shape hook. `cand` and `anchor` hold token
* ids bounded by n_vocab so the codebook gather stays inside the plane, and cand/unary/hp carry one
* row per (sequence, step), M * steps. */
/* The gated MLP band, slot for slot from libref's shape hook: n = N/2, the weight's scales per
* (ceil(N/group), ceil(K/group)) in **bf16** (the container's `weight_scale_inv`, which writes
* `o.t(RAD_BF16, {nb, kb})`), the output's codes per (M, n) and its scales per (M, ceil(n/group)).
* The row's set is fp8a8 only, group a power of two in [32, 256], no wider than n, and K a whole
* number of groups -- a hook that describes a shape the kernel refuses is the bug class this file
* exists to prevent. */
int r3d_shape_gemm_nt_q_gated(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t N = gi(p, n_p, "N", 0);
const int64_t K = gi(p, n_p, "K", 0);
const int64_t group = gi(p, n_p, "group", 0);
const char* q = gs(p, n_p, "dtype");
if (!q || std::strcmp(q, "fp8a8") != 0) return RAD_E_UNSUPPORTED;
const int64_t n = N / 2;
if (M <= 0 || M > 64 || N <= 1 || (N & 1) || K <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
if (group != 32 && group != 64 && group != 128 && group != 256) return RAD_E_UNSUPPORTED;
if (group > n || (K % group)) return RAD_E_UNSUPPORTED;
const int64_t kb = (K + group - 1) / group, nb = (N + group - 1) / group;
const int64_t ng = (n + group - 1) / group;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F8E4M3, M, K), /* a */
opd((uint32_t)RAD_F32, M, kb), /* a_scale */
opd((uint32_t)RAD_F8E4M3, N, K), /* b: gate rows [0,n), up rows [n,N) */
opd((uint32_t)RAD_BF16, nb, kb), /* b_scale: the container's form */
opd((uint32_t)RAD_F8E4M3, M, n), /* q */
opd((uint32_t)RAD_F32, M, ng), /* scale */
opd((uint32_t)RAD_BF16, M, n), /* out_bf16, optional */
};
R3D_PICK(list);
}
int r3d_shape_dflash_select(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t steps = gi(p, n_p, "steps", 0);
const int64_t K = gi(p, n_p, "top_k", 0);
const int64_t R = gi(p, n_p, "rank", 0);
const int64_t nv = gi(p, n_p, "n_vocab", 0);
const int64_t astr = gi(p, n_p, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_UNSUPPORTED;
const int64_t rows = M * steps;
const RadOpdDesc list[] = {
opd_idx(rows, nv, -1, 0, K), /* cand: drawn over the vocab */
opd((uint32_t)RAD_F32, rows, K), /* unary */
opd((uint32_t)RAD_BF16, rows, R), /* hp, absent is a plane of ones */
opd_idx(M * astr, nv), /* anchor */
opd((uint32_t)RAD_BF16, nv, R), /* pred */
opd((uint32_t)RAD_BF16, nv, R), /* succ */
opd_idx(M, nv, -1, 0, steps), /* tokens */
};
R3D_PICK(list);
}
int r3d_shape_sample_mask(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
/* mask_rows is M: one bitmask row a sequence is the widest the plane gets, and an
* unconstrained row shares it with mask_row -1. A set bit is an allowed token. */
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, M),
opd((uint32_t)RAD_I32, M, (nv + 31) / 32) };
R3D_PICK(list);
}
int r3d_shape_sample_logprobs(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const int64_t k = gi(p, n_p, "k", 0);
if (k <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0),
opd((uint32_t)RAD_F32, M, 2 + 2 * k) };
R3D_PICK(list); /* logits, params, stats [M, 2+2k] */
}
int r3d_shape_sample_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const int64_t nc = nv < (int64_t)kCand ? nv : (int64_t)kCand;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F32, M, nv), opd_params(M, 0, 0),
opd((uint32_t)RAD_I32, M, nc), opd((uint32_t)RAD_F32, M, nc),
opd((uint32_t)RAD_I32, M, 2 * nc)
}; /* logits, params, cand_idx, cand_val (logits, not probs), pairs */
R3D_PICK(list);
}
/* The four narrowing stages -- top-p, min-p, typical, XTC -- in place over the candidate set.
* The set is drawn, not sorted: the ABI has no descending fill domain, and top-p is a prefix rule
* in candidate order, which applies equally to a random order. An implementation that sorted
* internally would genuinely disagree with the schema. */
int r3d_shape_narrow(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t nc = gi(p, n_p, "n_cand", 0);
if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc),
opd_params(M, 0, 0) };
R3D_PICK(list); /* cand_idx INOUT, cand_val INOUT, params */
}
int r3d_shape_sample_pick(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t nc = gi(p, n_p, "n_cand", 0);
if (M <= 0 || nc <= 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = { opd_idx(M, nc, -1, 0, nc), opd((uint32_t)RAD_F32, M, nc),
opd_params(M, 0, 0), opd((uint32_t)RAD_I32, M) };
R3D_PICK(list); /* cand_idx, cand_val, params (seed and pos), token */
}
/* Penalties and DRY: logits, params with a history window inside it, and the history itself -- real
* token ids that repeat as text repeats. DRY's breaker plane marks about half its positions, so the
* exemption runs as well as the penalty. */
int r3d_shape_sample_penalties(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist)
};
R3D_PICK(list);
}
int r3d_shape_sample_dry(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc brk = opd_idx(M, 2, -1, 0, kHist);
const_cast<RadOpdDesc&>(brk).dtype = (uint32_t)RAD_U8;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist), brk
};
R3D_PICK(list);
}
/* The windowed n-gram ban adds a {n, window} pair a row and an optional exemption bitmask. */
int r3d_shape_sample_ngram_ban(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
int64_t M = 0, nv = 0;
if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED;
const RadOpdDesc list[] = {
opd((uint32_t)RAD_F32, M, nv), opd_params(M, kHist, 0),
opd_idx(M, nv, -1, RAD_OPD_F_IDX_HISTORY, kHist),
opd_idx(M, 64, -1, 0, 2),
opd((uint32_t)RAD_I32, M, (nv + 31) / 32)
};
R3D_PICK(list);
}
/* The four narrowing stages share the description above; the op names which predicate the kernel
* applies, and the schema they share says the operands are the same. */
int r3d_shape_sample_topp(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
return r3d_shape_narrow(p, n_p, o, out);
}
int r3d_shape_sample_minp(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
return r3d_shape_narrow(p, n_p, o, out);
}
int r3d_shape_sample_typical(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
return r3d_shape_narrow(p, n_p, o, out);
}
int r3d_shape_sample_xtc(const RadParam* p, int n_p, int o, RadOpdDesc* out) {
return r3d_shape_narrow(p, n_p, o, out);
}
+57
View File
@@ -0,0 +1,57 @@
/* r3d_tiling.h -- the tiled rows' LDS row law, in one place.
*
* Every tiled row in libr3d stages an [rows x pitch] f16 tile in LDS and then reads it back two
* elements at a time for dot2_f16x2. Two functions spell that out and they must agree exactly, so
* they live here and the rows include this file.
*
* srow(row, c8, pitch) the element offset of the c8-th run of EIGHT elements of `row`
* srow_pair(row, kc, pitch) the element offset of the pair (kc, kc+1) of `row`, kc even
*
* The law, and why it is shaped like this:
*
* - Granularity is EIGHT elements (16 bytes at f16): staging writes a uint4 a step, so the XOR has
* to move whole uint4s and never split one. A swizzle at pair granularity would make the store
* unaligned and the compiler would say so in bytes of spill.
* - The XOR is with (row & 7), so eight consecutive rows rotate the runs by one slot each. That is
* what kills the dot loop's bank conflict: a wavefront reads 32 rows at the same kc, and with the
* rotation the 32 reads land on 32 distinct 16-byte slots instead of the four a plain row-major
* tile puts them on.
* - The mask (pitch / 8 - 1) keeps the rotated index INSIDE the row. pitch is in elements, so a
* row has pitch/8 runs, and pitch/8 is a power of two for every tile in the library (32, 128).
* Without the mask a rotated index leaves the row and reads a neighbour's, which is the bug this
* header exists to prevent: it is silent, it is data-dependent, and it measures 30x off.
* - srow_pair takes the pair index kc>>3 -- the run the pair lives in -- and adds (kc & 7), the
* element inside the run. Reading pairs through srow is what keeps the store, the load and the
* swizzle one statement each.
*
* Measured law, in the family's numbers: a row that stages through srow and reads through
* srow_pair, with dot2_f16x2 accumulating into f32, lands at rel_l2 1.7e-03 against
* ref_gemm_nt_q's body at a bf16 output (the store's ulp binding, not the fold's) with 83% of
* outputs bit-exact. A row that gets the swizzle wrong, in either direction, lands at rel_l2 3e+01.
*
* Header-only, like the rest of libr3d. Include it in a .hip at file scope, before the kernels; the
* definitions are in an unnamed namespace, so each translation unit gets its own copy -- which is
* what the rows had before this header existed, spelled the same way, so the host pass does not see
* an unused static and the inliner sees the same function it always did.
*/
#ifndef R3D_TILING_H
#define R3D_TILING_H
namespace {
/* The element offset of run `c8` of `row`. pitch is a row's element count, a power of two. */
__device__ __forceinline__ int srow(int row, int c8, int pitch)
{
return row * pitch + (((c8 ^ (row & 7)) & (pitch / 8 - 1)) << 3);
}
/* The element offset of the f16 pair (kc, kc+1), kc even: the run the pair lives in, plus the
* element's place inside that run. */
__device__ __forceinline__ int srow_pair(int row, int kc, int pitch)
{
return srow(row, kc >> 3, pitch) + (kc & 7);
}
} // namespace
#endif /* R3D_TILING_H */
+926
View File
@@ -0,0 +1,926 @@
/* r3d_vocab_bf16.hip -- the lm_head projection: `logits_gemm`, and the same tiling under `gemm_nt`
* at prefill sizes.
*
* y[M,N] = x[M,K] @ w[N,K]^T, f32 accumulate, k ascending.
*
* `logits_gemm` spells N and K as n_vocab and n_embd and its y is **f32**: the schema says so
* (`ref_logits_gemm_shape` writes `o.t(RAD_F32, {M, nv})`, "f32 logits, as every sampler stage reads
* them"), and none of those stages wants a bf16 logit. `gemm_nt` is the same arithmetic with a bf16
* y, narrowed once by the store. Both entries are the same two kernels; `YF32` is the only
* difference in the code and the only difference in what the board has to report.
*
* ---- why this row exists ------------------------------------------------------------------------
*
* The probe of the served checkpoint refuses exactly one op: `logits_gemm`. libref's
* `ref_logits_gemm` is
* `gemm_nt_impl(a, false, "n_vocab", "n_embd")` on 32 OpenMP threads: 1.1 TFLOP for the band's shape
* (M=2048, n_vocab=130560, n_embd=2048), which this card does in about a second and the CPU in
* tens. For decode it is the 535 MB vocabulary head read once a token -- one call per token, the
* head the model cannot answer without. This row is not a speed decision. It is
* a read of the container's own form, and the head is stored in two of them: bf16 plain, with
* `layout`, `relayout` and `unrelayout` all null; and E4M3 codes with a bf16 scale per 128x128 block
* as two planes of one `rad.planes` container, which is the form the served checkpoint ships and
* which is answered by `r3d_layout_logits_head`, this file's transcription of `ref_layout_head`.
* Nothing is repacked in either case, and no operand description is declined.
*
* ---- the prefill arm (M > 16) -------------------------------------------------------------------
*
* A block is TM x TN = 128 x 128 outputs, 256 threads, eight waves, eight outputs a side a lane: 64
* f32 accumulators a lane, grid (N/TN) x (M/TM). Lane `tid` owns rows m0 + (tid/16)*8 .. +7 by
* columns n0 + (tid%16)*8 .. +7, so its 64 outputs are one 8x8 square of the tile and its stores are
* 32-byte runs of f32 (16-byte runs of bf16).
*
* k is walked in KC = 32 code chunks. Both tiles are stored row-major in f16 -- a row is the 32
* k-values of one m, 64 bytes -- because the global load that fills them is 8 contiguous k of one
* row: one `uint4` a thread, sixteen bytes, widened on the way in by four `bf16x2_to_f16x2`, which
* is exact for everything f16 can hold (bf16 has eight mantissa bits, f16 ten) and arrives as an inf
* for what it cannot, which the board counts rather than assumes away. The compute then reads those
* 64-byte rows in f16x2 pairs: eight activation pairs and eight weight pairs per two codes,
* sixty-four `fdot2` per two codes -- one pair-dot per output per two codes, 16 LDS reads against
* 64 dots.
*
* The tile pitch is KC elements and the rows are XOR-swizzled in eight-element units, which is the
* only arrangement that satisfies both ends at once. The staging store is a `uint4`, so a row's
* chunk offset has to stay a multiple of eight elements; an unswizzled 64-byte row stride puts all
* eight rows a lane reads on the same bank, 32-way. `srow` moves whole eight-element chunks by
* `row & 7`, which preserves the 16-byte alignment and brings the compute reads to two-way. Two-way
* and not conflict-free: the eight rows a lane owns sit at stride eight, so a period-8 swizzle
* repeats inside a lane's own set. The cost is 512 LDS cycles a block-chunk against 2048 of
* dots, a quarter, which is what the vectorised staging store buys.
*
* At the band, M=2048 n_vocab=130560 n_embd=2048, 16 x 1020 blocks of 256 threads:
* 272.24 ms = 4023 GFLOP/s, which is 37% of the 10.8 TFLOP/s this card's 32 CUs do dense f16 with
* f32 accumulate. At M=46 -- one tile row, 1020 blocks -- the same kernel does 16.64 ms =
* 1478 GFLOP/s, and the shortfall is the shape, not the kernel: 46 rows against a 128-row tile
* leaves 5/8 of every block's arithmetic idle. The host row for this op is `ref_logits_gemm`: 1.1
* TFLOP per forward pass across the whole vocabulary, on OpenMP threads; this row is the card's
* answer to that comparison.
*
* ---- the decode arm (M <= 16) -------------------------------------------------------------------
*
* The prefill tile reads the head M/TM times; at M=1 it would read 127/128 of it for nothing. At
* M <= 16 the block is the decode shape `r3d_gemm_bf16_nt_m16.hip` uses: a wave is MT activation
* rows by 32/MT weight rows, lane l owns (m = l % MT, n = n0 + l / MT), one accumulator a lane from
* k=0 to K, and no wave reduction anywhere -- so each output's sum is the reference's ascending
* chain, summand for summand, in the pair-dot's grouping. The activation arrives in 128-code chunks
* and stays in LDS for the chunk (MT x 128 f16, 4 KiB at MT=16, the same eight-element swizzle at
* the wider pitch); the weight goes straight from global to registers in 16-byte loads, eight codes
* at a time, widened where it lands. A wave keeps 32/MT weight rows in flight -- 4 KiB at MT=1 --
* which is what makes 16-byte strided reads across rows cost what they fetch. `nt=1` asks for
* non-temporal head loads, the honest hint for bytes read once a token; on this card it is worth
* nothing: 3.316 ms against 3.290 ms at M=1, 0.8% the other way. It is implemented
* because the ABI names it, and left off by default because the number says to.
*
* At n_vocab = 130560, n_embd = 2048 the arm is M = 1 in 3.226 ms = 166 GB/s of head, and M = 16 in
* 8.151 ms = 1050 GFLOP/s, 66 GB/s of bytes. The w2a8 row's 22 GB/s is not this arm's bound: it is
* that kernel's own limit -- an ALU-bound pair-dot with one 16-byte weight load per 64 codes -- and
* the card's DRAM is 256 GB/s. This arm is the streaming shape, 16 bytes a lane a step with the
* activation in LDS, and it runs at two thirds of the card.
*
* So the bf16 head costs 3.23 ms per decode token, and M = 16 (a speculative verify) costs 0.51 ms
* a token. The quantised head is the same op in half the bytes: the codes are 130560 x 2048 =
* 267,386,880 bytes (255.0 MiB) and the scales 1020 x 16 bf16 = 32,640 bytes (31.9 KiB), so a decode
* reads 255.03 MiB where the bf16 head reads 510.0 MiB. At the 163 GB/s this row's bf16 arm runs at
* the floor that is 1.64 ms a token, and at the card's 256 GB/s, 1.04 ms. (The 66.8 MB figure is the
* w2a8 row's 2-bit grid, a different head form.) Every number below says which of the three
* placements the bytes were in, because the placement is worth more than anything in the kernel, and
* all three are on this page so the choice between the head's forms is made on measurement.
*
* ---- the accumulation, and what it is exact against ---------------------------------------------
*
* libref's law per output is `acc += a*b` over ascending k from zero, and for this op with no bias.
* One accumulator per output, k ascending, no reassociation across lanes, in both arms. The pair-dot
* folds two products into the accumulator per step (`acc + a0*b0 + a1*b1` in one rounding) where the
* reference rounds each product in, so the sums agree closely and are not bit-equal. f32 output,
* K = 2048: rel_l2 1.77e-06 against the reference's law, identical -- 1.77e-06, to the
* digits -- against the same law with the operands widened to f16 first, so the widening
* contributes nothing and the fusion is the whole of it. 1.77e-06 is about 30
* f32 ulps on a sum of 2048 terms, and a random walk of one rounding per 1024 steps predicts
* sqrt(1024) * 6e-8 = 1e-6, which is where it lands. At K = 320 it is 2.0e-07, which scales the same
* way. What it means for the sampler: the head's bf16 values carry 4.9e-4 of quantisation each, so
* this is 300x finer than the input, and a top-k decision flips only on a tie tighter than 1e-6.
*
* Nothing here is integer arithmetic, so the v_fdot2_f32_f16 mantissa rule that bounds
* r3d_gemm_nt_q_w2a8.hip does not bite: the products are not integers, so there is no 2^20 wall, and
* the board's tail is ordinary rounding, counted with the plane pre-filled at 0x7fc0 -- no non-finite
* output at any size, including the 268-million-output band.
*
* ---- the head's stored form, and who answers it ---------------------------------------------------
*
* The band's `dtype=bf16` is the ACTIVATION's dtype. The head is quantised: the graph reads
* 'output.weight' as two planes of fp8_e4m3 * bf16[128x128], and the mapped tier reads the
* container where it lies, and its stored form is not the container's (rad.planes). The placement
* needs a reader for the head's stored form, and a layout hook is what a reader is. So:
*
* r3d_layout_logits_head (operand 1 -- `ref_layout_head` is `layout_scaled(operand, 1, -1, ...)`)
* tag `rad.planes`; codes E4M3 (libref's `scaled_rows` also admits int8) with a float scale --
* bf16, f16 or f32 -- on a block of {128, 128} (`R3D_FP8_BLOCK`); ends in `rad_planes_layout`.
* It moves no byte and `relayout` stays null. `ref_layout_head` is libref-internal-static, so
* its body, and `layout_scaled`'s, and `enc_scaled_rows`' and `float_scale_dt`' with it, are
* transcribed here as the w2a8 hook transcribed `ref_layout_gemm_q`: checks and their order,
* unchanged. Two fields are worth naming: `rad_enc_is`
* compares `scheme`, and `transform` is the optional pre-transform. The
* encoding is affine with an EMPTY transform; a fixture that writes "affine" into `transform`
* makes the hook decline every head.
*
* The law. `ScaledRows::at(r, c) = codes.at(r, c) * scale.cover(r, c)`: the code widened exactly,
* multiplied by the scale covering it, one f32 rounding, then the plain ascending-k GEMM in f32.
* The widening is exact both ways -- E4M3 is 4 exponent and 3 mantissa bits, f16 is 5 and 10, and
* int8 lands in f16 whole -- so the codes reach the dot as the numbers the checkpoint means, and
* the only divergence stays the dot's fused rounding: rel_l2 2.77e-04 at M=1, K=2048,
* which is one f16 ulp's worth (2^-12 = 2.44e-04) and is the fold, not the dot; against the fold
* law, below, it is 4.5e-06, and `<=2 ulps` is 1.000 with `>6 ulps` 0 at every size,
* 268-million-output band included. y stays f32: logits are f32 and the reference's store is f32.
*
* The fold, and the hardware rule it obeys. The reference dequantises each element into f32; the
* tile is f16, so the scale enters as a f16 multiply at staging -- the tiled arm once per staged
* 8-column group, the decode arm once per 128-code chunk, and a chunk of 32 sits inside one
* 128-column block (128 % 32 == 0, 128 % 128 == 0), so one scale per staged row. That costs no
* registers: the prefill arm is the register file's at 237 VGPRs, and per-k-block partials would
* need 64 more accumulators and spill. The multiply must be a hardware f16 multiply
* (`v_mul_f16`, round to nearest, subnormals kept), not `f16x2_pack`: that builtin is
* `v_cvt_pkrtz_f16_f32`, ROUNDS TOWARD ZERO, and r3d_codecs.h says so and says to call it only
* with values f16 already represents exactly. A folded weight is not one of those -- code 431 by
* a scale of 4.5e-5 is eleven significant bits -- and a toward-zero packer biases every product
* toward zero and flushes the subnormal end: rel_l2 2.8e-04 against the fold law with only 0.53 of
* outputs within 2 ulps. The f16 multiply is one rounding in the right direction and one
* instruction: 4.5e-06 and 1.000. The number and the verdict: 2.77e-04 against the reference's
* exact law is the fold's cost, 250x finer than the E4M3 code's own quantum (2^-4 = 6.25e-2), so
* the fold does not move the logits by anything the quantisation did not already move. An f32
* scale plane costs one more rounding (the scale to f16, 1.75e-04 against a model that folds
* after the multiply); the shipped form's bf16 scale is f16-exact and pays nothing.
*
* With the head's bytes where the engine would put them (VRAM, with the header page
* read by the shim on the host): prefill M=2048 in 325.06 ms = 3369 GFLOP/s against the bf16 head's
* 269.31 ms = 4067 -- 17% slower, all of it staging, and the case for the quantised head at prefill
* is the 255 MiB of weight traffic, not the FLOPs. M=46: 22.43 ms = 0.488 ms a token against
* 0.361. Decode M=1: 13.603 ms a token, 19.7 GB/s of codes, 8x above the 1.64 ms floor, and the
* cause is the E4M3 decoder. `__builtin_amdgcn_cvt_pk_f16_fp8` exists in clang and expands
* to software on gfx1102 -- zero `v_cvt_pk_f16_fp8` in the ISA -- so eight codes cost
* ~100 instructions of `e4m3_to_f32` against the bf16 arm's four, and the arm is ALU-bound. The
* fix has a size: a 256-entry f16 table in LDS is 512 bytes, 8 LDS reads a staged group against
* ~100 ALU, which puts the arm back near its floor; that is a tiling pass, not this row's work.
* The speculation block is where the form already pays: M=8 (7 drafts + 1) reads the head ONCE and
* costs 21.67 ms = 2.708 ms a token, 5x cheaper per token than M=1 on the same kernel.
*
* Where the bytes live, on this box, at M=1: in VRAM 13.6 ms; on the mapped tier
* (hipHostMalloc, read over PCIe by 8-byte strided loads) 643 ms a token; managed and left alone
* 2071 ms a token, 122 MB/s, because managed pages do not migrate for a read-mostly device access
* on this ROCm and the kernel faults page by page. The head is placed on
* the mapped tier. A hook makes that placement legal; it does not make it fast, and these three
* numbers are the argument for uploading the head. The board takes the timed number after
* `hipMemPrefetchAsync` and says so on every line.
*
* Both forms are served, chosen by the header: `rad_planes_header(w)` at the shim's head branch
* dispatches on it, and a plain bf16 operand goes down the bf16 path untouched. The choice is
* the container's, not the row's. The shim reads the container's header
* (which is why the operand's bytes must be host-readable: `scaled_rows()` does the same host read,
* so this is the engine's convention, not this row's invention); the kernel reads the same bytes on
* the card, so the fixture is hipMallocManaged + prefetch, or hipHostMalloc, never plain malloc --
* plain malloc faults 700 on the kernel's first read.
*
* ---- the decoder is a table, and what the table moved --------------------------------------------
*
* r3d_fp8_dequant.h replaces the E4M3 codec with a 256-entry f16 table in LDS (512 bytes, eight
* reads an eight-code group) because clang lists __builtin_amdgcn_cvt_pk_f16_fp8 for gfx1102 and a
* build that calls it contains ZERO v_cvt_pk_f16_fp8: the builtin is software here. The A/B is one
* source built twice (-DR3D_NO_E4M3_TBL selects the codec), same fixture, same seed:
*
* M=8 speculation 2.500 -> 0.924 ms/token (20.002 -> 7.395 ms) 2.70x THE WIN
* M=2048 prefill 323.978 -> 322.661 ms (3380 -> 3394 GFLOP/s) flat, -0.4%
* M=1 decode 12.999 -> 13.293 ms/token (20.6 -> 20.2 GB/s) NOT moved, 2.3% worse
* M=46 prefill 21.603 -> 21.792 ms (1139 -> 1129 GFLOP/s) flat
*
* The table is exact by construction -- the codec, evaluated once per bit pattern at block start --
* and rel_l2 is bit-identical between the two binaries (2.770e-04 vs the fold law / 4.452e-06 vs the
* fold model at prefill; 2.758e-04 / 4.559e-06 at M=1), which is the check that the swap moved work
* and not arithmetic. It is a 2.70x win where the decoder was the binding resource (MT=8: four
* decodes and four folds a lane per eight codes, no memory wall in reach) and a NAMED NON-RESULT at
* M=1: 13 ms at 20 GB/s of codes is 8x off the 1.64 ms floor this row's own 163 GB/s implies, and
* removing ~100 ALU instructions an eight-code group does not move it. The suspect at M=1 is the
* load width -- eight codes a lane through an 8-byte load, where the bf16 arm takes sixteen bytes a
* lane and streams at 163 GB/s -- so the shape to try there is a 16-byte code load (16 codes, eight
* pairs, half the wavefronts), not more ALU. 44 kernels, all vgpr_spill_count: 0, both builds.
*
* ---- what is refused, and where ------------------------------------------------------------------
*
* sk > 1: the grid is vocab-wide at every M -- 1020 blocks in x at the band for the prefill arm,
* 8160 for the decode arm at MT=16 -- so no shape this row serves is short of parallelism, and a
* split would buy a second kernel and a documented order change for nothing. kb: KC = 32 only; a
* tile pitched at anything else is a different swizzle, not a knob, and the launcher enumerates the
* values it accepts and refuses the rest. K not a multiple of KC, an x pitch not a multiple of 8, a
* y pitch not a multiple of 4 (f32) or 8 (bf16), a weight that is not contiguous, and quantised
* heads that are not this form. The head branch, in its order:
* a quantised head on the bf16-y row -- logits are f32; the tiled row keeps a bf16 head
* a `zero` plane on the head -- codes+scale+zero is gemm_nt_q's asymmetric grid, and the row
* that reads it is r3d_gemm_nt_q_w2a8.hip; that is w2a8's grid, not this op
* a joined operand that is not two planes
* a joined head whose planes are not codes + scale (a `table`, a `bias`: names it)
* codes tiled by anything but one code a cell
* sub-byte codes (4-bit: w4a16's ground, and the row that reads it is w2a8's neighbour)
* e5m2 and every other code dtype: no decoder here
* a scale plane that is a table, not a tiling
* an integer scale: not float_scale_dt's set
* a scale block that is not 128x128 -- per-(row, group) scales are gemm_nt_q's grid, and a
* per-row scale is a different indexing of the plane than ScaledRows::cover is
* a plane that does not cover the band (codes must be N x K, scales ceil(N/128) x
* ceil(K/128)); a plane whose row_bytes is shorter than its row
* and the bf16 branch's: a plain head that is not bf16, x and y dtypes,
* no axes, pitches, the head's numel and contiguity, absurd shapes,
* alignment, sk > 1. The launcher's own: a head with a null plane, a dtype
* outside the served set, a row pitch a vector load cannot walk (a 16-bit scale row is 2
* bytes a column, so K = 320 -- 3 scale columns, 6 bytes -- is legal), addresses.
* 24 refusals, 24 as stated, and the hook's two served encodings answer RAD_OK with
* tag `rad.planes` and the codes' dtype.
*/
#include <hip/hip_runtime.h>
#include "r3d.h"
#include "r3d_common.h"
#include "r3d_codecs.h"
#include "r3d_fp8_dequant.h" /* the E4M3 -> f16 table: 512 bytes of LDS for ~100 ALU a group */
#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */
#include "r3d_args.h"
#include "r3d_launch.h"
#include "rad_planes.h"
namespace {
constexpr int kBlockThreads = 256;
constexpr int kWaves = kBlockThreads / kWave; /* 8 */
constexpr int kTM = 128; /* activation rows a block */
constexpr int kTN = 128; /* weight rows a block */
constexpr int kKC = 32; /* codes a tile step */
constexpr int kSkinnyMax = 16; /* the MT ceiling of the decode arm */
constexpr int kChunkK = 128; /* the decode arm's activation chunk */
#if defined(__has_builtin)
# if __has_builtin(__builtin_nontemporal_load)
# define R3D_HAS_NT 1
# endif
#endif
#ifndef R3D_HAS_NT
# define R3D_HAS_NT 0
#endif
/* The tile address, in f16 elements: `pitch`-wide rows whose eight-element chunks are XORed by the
* row's low bits. Multiples of eight in, so a uint4 store and an f16x2 read are both aligned by
* construction, at both pitches this file uses (32 and 128). */
/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */
/* Eight bf16 -> eight f16, exact for every value f16 can hold. */
__device__ __forceinline__ uint4 widen8(uint4 w)
{
return make_uint4(bf16x2_to_f16x2(w.x), bf16x2_to_f16x2(w.y), bf16x2_to_f16x2(w.z),
bf16x2_to_f16x2(w.w));
}
constexpr int kFp8Block = 128; /* the head's scale block: R3D_FP8_BLOCK, llama_dense_fp8 */
/* The head as the container stores it: E4M3 codes with one float scale per (128 x 128) block.
* Passed by value; every pointer in it is a device address, resolved by the shim out of the joined
* bytes (rad_planes_find), which is what a layout hook's absence asks of a kernel -- the container's
* own form, read where it lies, no byte moved. */
struct HeadQ {
const uint8_t* codes; /* [N][K] */
const uint8_t* scale; /* [ceil(N/128)][ceil(K/128)] */
long long code_row; /* bytes a codes row: the plane's row_bytes, not K's element count */
long long scale_row; /* bytes a scale row */
int sdt; /* the scale's dtype: 0 bf16, 1 f16, 2 f32 (float_scale_dt's set) */
int cdt; /* the codes' dtype: 0 E4M3, 1 int8 */
};
/* The scale covering logical (n, k): `scale.cover` from the reference's ScaledRows, one scalar load a
* row a chunk. The plane is 32 KiB at the band, so it is in cache from the first block that touches
* a row and the load is not the traffic; the codes are. */
__device__ __forceinline__ float scale_at(const HeadQ h, int n, int k)
{
const uint8_t* p = h.scale + (long long)(n >> 7) * h.scale_row
+ (long long)(k >> 7) * (h.sdt == 2 ? 4 : 2);
if (h.sdt == 2) { float f; __builtin_memcpy(&f, p, 4); return f; }
const uint16_t u = *(const uint16_t*)p;
return h.sdt == 1 ? f16_to_f32(u) : bf16_to_f32(u);
}
/* Eight codes -> eight f16, exact. E4M3 is four exponent and three mantissa bits and f16 is five and
* ten, and int8 lands in f16 whole, so the decoder is a widening, not a rounding: the numbers the
* checkpoint means are the numbers multiplied (r3d_gemm_fp8a16_nt_m1.hip says the same about the
* same codec). e4m3x2_to_f16x2 decodes the two codes in a dword's LOW half, so the pairs straddle
* dwords: two dwords in, four pairs out. Feeding it whole dwords decodes eight codes and leaves the
* rest of the step multiplying registers that were never written -- the shape the sibling unit
* documents, and the reason this helper takes the pair the way it does. */
#if defined(__has_builtin)
# if __has_builtin(__builtin_amdgcn_cvt_pk_f16_fp8)
# define R3D_HAS_FP8CVT 1 /* gfx11+: v_cvt_pk_f16_fp8, two codes to two f16, one instruction */
# endif
#endif
#ifndef R3D_HAS_FP8CVT
# define R3D_HAS_FP8CVT 0
#endif
__device__ __forceinline__ uint32_t cvt_pk_f16_fp8(uint32_t b)
{
#if R3D_HAS_FP8CVT
return __builtin_bit_cast(uint32_t, __builtin_amdgcn_cvt_pk_f16_fp8(b));
#else
return f16x2_pack(e4m3_to_f32((uint8_t)(b & 0xffu)), e4m3_to_f32((uint8_t)((b >> 8) & 0xffu)));
#endif
}
__device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const uint16_t* tbl,
uint32_t* w)
{
const uint32_t d[2] = { c.x, c.y };
if (tbl && !cdt) {
/* The table: eight LDS reads for eight codes. Exact by construction -- the table is built
* from the codec below, one entry per bit pattern -- so a row's numbers do not move; what
* moves is where the work happens. r3d_fp8_dequant.h carries the reason and the measurement.
* Passing null tbl asks for the codec, which is how the board A/Bs the two in one binary. */
r3d_e4m3x8_ld(tbl, c, w);
return;
}
if (!cdt) {
/* The instruction this wants: two codes to two f16, one op. clang has the builtin on this
* target's list and gfx1102 does not have the instruction: the ISA of this build contains
* zero v_cvt_pk_f16_fp8, so the builtin expands to the software decode below and
* eight codes cost ~100 instructions of exponent work. At M=1: 19.7 GB/s of codes,
* 8x above the 1.64 ms floor, ALU-bound. The builtin stays because it says what the operation
* is and a card with the instruction gets it for free; the fix for THIS card is a 256-entry
* f16 table in LDS, 512 bytes, 8 LDS reads where the ~100 ALU are, which is a tiling pass. */
w[0] = cvt_pk_f16_fp8(d[0]);
w[1] = cvt_pk_f16_fp8(d[0] >> 16);
w[2] = cvt_pk_f16_fp8(d[1]);
w[3] = cvt_pk_f16_fp8(d[1] >> 16);
return;
}
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint32_t pair = (d[j >> 1] >> (16 * (j & 1))) & 0xffffu;
w[j] = i8x2_to_f16x2(pair);
}
}
/* The fold: the decoded code times the scale covering it, in f16 pairs.
*
* The reference dequantises per element into f32 (`ScaledRows::at` = code * scale, one rounding) and
* then multiplies. Folding into the staged f16 costs one f16 rounding per weight -- half an ulp,
* 2.4e-4 relative, on a code whose own quantum is 2^-4 = 6.3e-2, a factor of 250. It buys the whole
* structure: the tile stays f16, the dot loop is untouched, the accumulators do not double, and the
* register file, which is the tightest thing in the prefill arm at 237 VGPRs, does not move. The
* alternative -- a per-block partial summed separately and scaled -- needs 64 more accumulators and
* spills. The number the board prints is this fold's. */
__device__ __forceinline__ uint32_t scale_pair(uint32_t w, float sc)
{
#if defined(__HIP_DEVICE_COMPILE__)
/* One f16 multiply, hardware, round-to-nearest.
*
* It is NOT f16x2_pack of an f32 product: that builtin is v_cvt_pkrtz_f16_f32, rounds toward
* zero, and r3d_codecs.h says out loud to call it only with values f16 already represents
* exactly. A folded weight is not one of those -- code 431 times a scale of 4.5e-5 is a product
* with eleven significant bits -- so the packer truncates, and truncation is a bias: every
* product moves toward zero, and it shows as rel_l2 2.8e-04 (half an f16 ulp, the
* whole of it) with the subnormal end flushed to zero on top. F16 arithmetic is one v_mul_f16
* an element and rounds the way the reference's f32 multiply rounds.
*/
const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16);
const _Float16 a = __builtin_bit_cast(_Float16, lo16);
const _Float16 b = __builtin_bit_cast(_Float16, hi16);
const _Float16 s = (_Float16)sc; /* f32 -> f16, round to nearest even */
const _Float16 rl = a * s, rh = b * s; /* v_mul_f16: one rounding, subnormals kept */
return (uint32_t)__builtin_bit_cast(uint16_t, rl) |
((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16);
#else
return (uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w & 0xffffu)) * sc) |
((uint32_t)f32_to_f16(f16_to_f32((uint16_t)(w >> 16)) * sc) << 16);
#endif
}
/* The head's 16-byte load, ordinary or streamed-once. */
template <int NT>
__device__ __forceinline__ uint4 loadw8(const uint16_t* p)
{
#if R3D_HAS_NT
if (NT) {
/* The builtin wants a native vector, not HIP's class: four unsigned ints, bit-cast. */
typedef unsigned int v4u __attribute__((ext_vector_type(4)));
const v4u t = __builtin_nontemporal_load((const v4u*)p);
uint4 r;
__builtin_memcpy(&r, &t, 16);
return r;
}
#else
(void)NT;
#endif
return *(const uint4*)p;
}
/* Eight codes, the quantised head's 8-byte load, ordinary or streamed-once: the same builtin
* requirement as the 16-byte one, a native vector. Half the bytes of the bf16 head is the whole
* point of the form, and it is the load that changes. */
template <int NT>
__device__ __forceinline__ uint2 loadc8(const uint8_t* p)
{
#if R3D_HAS_NT
if (NT) {
typedef unsigned int v2u __attribute__((ext_vector_type(2)));
const v2u t = __builtin_nontemporal_load((const v2u*)p);
uint2 r;
__builtin_memcpy(&r, &t, 8);
return r;
}
#else
(void)NT;
#endif
return *(const uint2*)p;
}
/* ============================================================ the prefill arm, M > 16
*
* y is f32 for logits_gemm and bf16 for gemm_nt; `YF32` is that choice, and it is the only one.
*/
template <bool YF32, bool WQ>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2)
gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, HeadQ h,
void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld)
{
(void)b; /* the plain head; WQ reads the container through h */
__shared__ __align__(16) uint16_t sA[kTM * kKC]; /* f16, TM rows x KC, swizzled */
__shared__ __align__(16) uint16_t sB[kTN * kKC]; /* f16, TN rows x KC, swizzled */
const int tid = (int)threadIdx.x;
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */
#ifndef R3D_NO_E4M3_TBL
if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then the barrier it holds */
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
#else
(void)sTbl; /* the board's A/B: the codec, unbuilt */
const uint16_t* const r3d_tbl = (const uint16_t*)nullptr;
#endif
const int m0 = (int)blockIdx.y * kTM;
const int n0 = (int)blockIdx.x * kTN;
const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */
float acc[8][8];
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) acc[i][j] = 0.0f;
const int m_r = m0 + rg * 8, n_c = n0 + cg * 8;
for (int k0 = 0; k0 < K; k0 += kKC) {
/* Stage 128 rows x 4 chunks of eight a side: one uint4 a thread a side, two a side. Rows
* past M and codes past K stage as zeros, which is the clamping a ragged tail needs, keeps
* the loads straight-line and contributes nothing to a sum. */
#pragma unroll
for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) {
const int mm = j / (kKC / 8), c8 = j % (kKC / 8);
const int m = m0 + mm, k = k0 + c8 * 8;
uint4 w = make_uint4(0, 0, 0, 0);
if (m < M && k < K) w = *(const uint4*)(a + (long long)m * a_ld + k);
*(uint4*)&sA[srow(mm, c8, kKC)] = widen8(w);
}
#pragma unroll
for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) {
const int nn = j / (kKC / 8), c8 = j % (kKC / 8);
const int n = n0 + nn, k = k0 + c8 * 8;
uint4 staged = make_uint4(0, 0, 0, 0);
if (n < N && k < K) {
if (WQ) {
/* Eight codes, one scale: a group of 8 sits inside one 128-column block, so
* the whole staged run shares the scale, and the tile's 32-code chunk sits
* inside one block too (128 % 32 == 0). The scale indexes the tile's row, not
* the lane's: the plane is (n-block, k-block), and this row is n. */
const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k);
uint32_t w[4];
codes8_to_f16x4(c, h.cdt, r3d_tbl, w);
const float sc = scale_at(h, n, k);
staged = make_uint4(scale_pair(w[0], sc), scale_pair(w[1], sc),
scale_pair(w[2], sc), scale_pair(w[3], sc));
} else {
staged = widen8(*(const uint4*)(b + (long long)n * K + k));
}
}
*(uint4*)&sB[srow(nn, c8, kKC)] = staged;
}
__syncthreads();
#pragma unroll
for (int kc = 0; kc < kKC; kc += 2) {
uint32_t af[8], bf[8];
#pragma unroll
for (int i = 0; i < 8; ++i)
af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)];
#pragma unroll
for (int j = 0; j < 8; ++j)
bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)];
#pragma unroll
for (int i = 0; i < 8; ++i)
#pragma unroll
for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]);
}
__syncthreads();
}
/* The store, eight columns at a time: 32 bytes of f32, 16 of bf16. Guarded row by row, so a
* ragged M writes nothing and a ragged N writes whole runs of columns it owns. */
#pragma unroll
for (int i = 0; i < 8; ++i) {
const int m = m_r + i;
if (m >= M) break;
if (n_c + 8 <= N) {
if (YF32) {
float* row = (float*)y + (long long)m * y_ld;
#pragma unroll
for (int j = 0; j < 8; j += 4)
*(uint4*)(row + n_c + j) =
make_uint4(__float_as_uint(acc[i][j]), __float_as_uint(acc[i][j + 1]),
__float_as_uint(acc[i][j + 2]), __float_as_uint(acc[i][j + 3]));
} else {
uint16_t* row = (uint16_t*)y + (long long)m * y_ld;
uint32_t p[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
p[j] = (uint32_t)f32_to_bf16(acc[i][2 * j]) |
((uint32_t)f32_to_bf16(acc[i][2 * j + 1]) << 16);
*(uint4*)(row + n_c) = make_uint4(p[0], p[1], p[2], p[3]);
}
} else {
/* The ragged N tail, unrolled: a dynamic index into acc would put the 64 accumulators
* in local memory, and the compiler says so -- 80 KiB of spill against a 64 KiB limit. */
#pragma unroll
for (int j = 0; j < 8; ++j) {
if (n_c + j < N) {
if (YF32) ((float*)y)[(long long)m * y_ld + n_c + j] = acc[i][j];
else ((uint16_t*)y)[(long long)m * y_ld + n_c + j] = f32_to_bf16(acc[i][j]);
}
}
}
}
}
/* ============================================================ the decode arm, M <= 16
*
* A wave is MT activation rows by KLW = 32/MT weight rows, one accumulator a lane, the whole of k in
* ascending order. The activation tile is block-wide, so every wave stages it -- a wave whose row is
* past the vocabulary stages too and simply does not read, which is the rule that keeps a tile from
* coming up with holes.
*/
template <int MT, bool YF32, int NT, bool WQ>
__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4)
logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, HeadQ h,
void* __restrict__ y, int M, int N, int K, int x_ld, int y_ld)
{
constexpr int KLW = kWave / MT;
constexpr int STEPS = MT * (kChunkK / 8); /* uint4 staging steps a chunk */
__shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */
__shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL];
#ifndef R3D_NO_E4M3_TBL
if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads);
const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr;
#else
(void)sTbl;
const uint16_t* const r3d_tbl = (const uint16_t*)nullptr;
#endif
const int lane = (int)threadIdx.x & (kWave - 1);
const int warp = (int)threadIdx.x / kWave;
const int m = lane & (MT - 1);
const int n = (int)blockIdx.x * (kWaves * KLW) + warp * KLW + lane / MT;
const bool live = n < N;
/* A dead lane reads row N-1, a row that exists: the loads stay uniform and nothing is read out
* of bounds; its result is dropped at the store. */
const uint16_t* wrow = w + (long long)(live ? n : N - 1) * K;
const int nsteps = M < MT ? M : MT;
float acc = 0.0f;
for (int k0 = 0; k0 < K; k0 += kChunkK) {
for (int j = (int)threadIdx.x; j < STEPS; j += kBlockThreads) {
const int r = j / (kChunkK / 8), c8 = j % (kChunkK / 8);
const int k = k0 + c8 * 8;
uint4 v = make_uint4(0, 0, 0, 0);
if (r < nsteps && k < K) v = *(const uint4*)(x + (long long)r * x_ld + k);
*(uint4*)&sX[srow(r, c8, kChunkK)] = widen8(v);
}
__syncthreads();
if (live) {
const uint16_t* wp = wrow + k0;
const uint8_t* cp = h.codes + (long long)(live ? n : N - 1) * h.code_row + k0;
/* One scale a chunk: kChunkK is the scale block, so the lane's 128 codes are inside a
* single (n-block, k-block) and the load is one scalar per 128 codes. */
const float sc = WQ ? scale_at(h, live ? n : N - 1, k0) : 0.0f;
const int kend = K - k0 < kChunkK ? K - k0 : kChunkK; /* a multiple of 8: the
* launcher takes K % 8 == 0 */
for (int kc = 0; kc < kend; kc += 8) {
uint32_t w0, w1, w2, w3;
if (WQ) {
uint32_t q[4];
codes8_to_f16x4(loadc8<NT>(cp + kc), h.cdt, r3d_tbl, q);
w0 = scale_pair(q[0], sc); w1 = scale_pair(q[1], sc);
w2 = scale_pair(q[2], sc); w3 = scale_pair(q[3], sc);
} else {
const uint4 wv = loadw8<NT>(wp + kc);
w0 = bf16x2_to_f16x2(wv.x); w1 = bf16x2_to_f16x2(wv.y);
w2 = bf16x2_to_f16x2(wv.z); w3 = bf16x2_to_f16x2(wv.w);
}
const int s = srow_pair(m, kc, kChunkK);
acc = dot2_f16x2(*(const uint32_t*)&sX[s], w0, acc);
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 2], w1, acc);
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 4], w2, acc);
acc = dot2_f16x2(*(const uint32_t*)&sX[s + 6], w3, acc);
}
}
__syncthreads();
}
if (live && m < M) {
if (YF32) ((float*)y)[(long long)m * y_ld + n] = acc;
else ((uint16_t*)y)[(long long)m * y_ld + n] = f32_to_bf16(acc);
}
}
/* ------------------------------------------------------------------ the shared launcher
*
* Returns 0, -1 a null pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP
* launch failed, -5 an address it cannot read at 16 bytes.
*/
template <bool YF32>
int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ld, int sk, int kb,
int nt, long stream, const HeadQ* hq = nullptr)
{
if (!xv || !wv || !yv) return -1;
if (M < 1 || N < 1 || K < 1) return -2;
if (sk > 1) return -2; /* the grid is vocab-wide at every M, see header */
if (kb == 0) kb = kKC;
if (kb != kKC) return -2; /* 32 is the tile's k-chunk and the only one */
if (nt < 0 || nt > 1) return -2;
if (K % kKC) return -2; /* the tile's chunk; 2048 at the band */
if (K % 8) return -3; /* 16-byte weight loads */
if (!x_ld) x_ld = K;
if (!y_ld) y_ld = N;
if (x_ld % 8) return -3; /* 16-byte activation loads (bf16) */
if (y_ld % (YF32 ? 4 : 8)) return -3; /* 16-byte store runs (f32: 4, bf16: 8) */
if (x_ld < K || y_ld < N) return -3;
if ((xv & 15) || (wv & 15) || (yv & 15)) return -5;
const uint16_t* x = (const uint16_t*)(uintptr_t)xv;
const uint16_t* w = (const uint16_t*)(uintptr_t)wv;
void* y = (void*)(uintptr_t)yv;
hipStream_t s = (hipStream_t)(uintptr_t)stream;
/* The head's form is the shim's answer, resolved out of the container before the launch; this
* is where its pointers are checked as pointers. The declared entries pass null and get the
* plain bf16 head, which is what r3d.h's signature for them describes. */
HeadQ h;
std::memset(&h, 0, sizeof h);
const int wq = hq != nullptr;
if (hq) {
h = *hq;
if (!h.codes || !h.scale) return -1;
if (h.sdt < 0 || h.sdt > 2 || h.cdt < 0 || h.cdt > 1) return -2;
if (h.code_row & 7) return -3; /* 8-byte code loads, one row a stride */
if (h.scale_row & (h.sdt == 2 ? 3 : 1))
return -3; /* a scale row is 4 bytes a column for f32, 2 for
* bf16/f16: a plane of 3 columns is 6 bytes and the
* loads land on even addresses. K = 320 is legal. */
if (((long long)(uintptr_t)h.codes & 7) || ((long long)(uintptr_t)h.scale & 3)) return -5;
}
if (M <= kSkinnyMax) {
#define R3D_SKINNY(MTV, NTV, WQV) \
do { \
const int klw = kWave / (MTV); \
const int per = kWaves * klw; \
const dim3 grid((unsigned)((N + per - 1) / per)), block(kBlockThreads); \
R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel<MTV, YF32, NTV, WQV>)), grid, block, s, x, w, \
h, y, M, N, K, x_ld, y_ld); \
} while (0)
#define R3D_SKINNY_MT(MTV) \
do { \
if (wq) { if (nt) R3D_SKINNY(MTV, 1, 1); else R3D_SKINNY(MTV, 0, 1); } \
else { if (nt) R3D_SKINNY(MTV, 1, 0); else R3D_SKINNY(MTV, 0, 0); } \
} while (0)
if (M == 1) R3D_SKINNY_MT(1);
else if (M <= 2) R3D_SKINNY_MT(2);
else if (M <= 4) R3D_SKINNY_MT(4);
else if (M <= 8) R3D_SKINNY_MT(8);
else R3D_SKINNY_MT(16);
#undef R3D_SKINNY_MT
#undef R3D_SKINNY
} else {
const dim3 grid((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM));
const dim3 block(kBlockThreads);
if (wq)
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, true>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
else
R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel<YF32, false>)), grid, block, s, x, w, h, y, M,
N, K, x_ld, y_ld);
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The shim's shared body: the checks the two ops agree on, then the launch. `y_is_f32` is the op's
* schema (logits are f32 because every sampler stage reads f32; gemm_nt's y is bf16), nkey/kkey the
* axis names libref spells them with ("n_vocab"/"n_embd" and "N"/"K" -- ref_logits_gemm is
* gemm_nt_impl with the axes renamed, so this body is shared by construction, not by imitation). */
int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey)
{
if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data)
return R3D_NO(RAD_E_INVAL);
const RadTensor* x = &a->t[0];
const RadTensor* w = &a->t[1];
const RadTensor* y = &a->t[2];
const RadPlanesEntry* ce = nullptr;
const RadPlanesEntry* se = nullptr;
HeadQ h;
std::memset(&h, 0, sizeof h);
int joined = 0;
/* ---- the head's stored form ---------------------------------------------------------------
* The band's `dtype` key is the ACTIVATION's dtype: on this graph `dtype=bf16` with the head
* stored as E4M3 codes and a bf16 scale per 128x128 block, in two planes of one container. The
* stored form is answered by a layout hook -- `ref_layout_head`, transcribed below as
* r3d_layout_logits_head, the way the w2a8 hook transcribed ref_layout_gemm_q -- and this is
* its launch-side twin: read the header, read the two planes, dispatch on what they are. The
* checks and their order are the reference's `scaled_rows`: the roles, then the dtypes and
* blocks, then the coverage (which needs N and K, so it sits below, where the reference has
* them already).
*
* The bf16 head is served as is: the container's header, not the row's preference, picks
* the form. Two forms, one row, chosen by the bytes.
*/
const RadPlanesHeader* ph = rad_planes_header(r3d_p(w));
if (ph) {
if (!y_is_f32) return R3D_NO(RAD_E_DTYPE); /* logits are f32; the bf16-y row keeps a bf16 head */
if (rad_planes_find(r3d_p(w), "zero", nullptr))
return R3D_NO(RAD_E_DTYPE); /* codes+scale+zero is gemm_nt_q's asymmetric grid: w2a8 */
if (ph->n_planes != 2) return R3D_NO(RAD_E_DTYPE);
const uint8_t* cb = (const uint8_t*)rad_planes_find(r3d_p(w), "codes", &ce);
const uint8_t* sb = (const uint8_t*)rad_planes_find(r3d_p(w), "scale", &se);
if (!cb || !sb || !ce || !se)
return R3D_NO(RAD_E_DTYPE); /* a joined head that is not codes + one scale */
if (ce->kind != RAD_PLANE_TILED || ce->block[0] != 1 || ce->block[1] != 1)
return R3D_NO(RAD_E_DTYPE); /* codes must be one code an element, tiled plain */
if (ce->dtype != RAD_F8E4M3 && ce->dtype != RAD_I8) {
if (rad_dtype_bytes(ce->dtype, 8) < 8)
return R3D_NO(RAD_E_DTYPE); /* sub-byte codes: w4a16's ground, not this form */
return R3D_NO(RAD_E_DTYPE); /* e5m2 and the rest: no decoder here */
}
if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE);
if (se->dtype == RAD_BF16) h.sdt = 0;
else if (se->dtype == RAD_F16) h.sdt = 1;
else if (se->dtype == RAD_F32) h.sdt = 2;
else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not a float_scale_dt */
if (se->block[0] != kFp8Block || se->block[1] != kFp8Block)
return R3D_NO(RAD_E_SHAPE); /* per-(row,group) scales are gemm_nt_q's grid; per-row
* is not the indexing this kernel does */
h.codes = cb; h.scale = sb; h.code_row = ce->row_bytes; h.scale_row = se->row_bytes;
h.cdt = ce->dtype == RAD_I8 ? 1 : 0;
joined = 1;
} else if (w->dtype != RAD_BF16) {
return R3D_NO(RAD_E_DTYPE);
}
if (x->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE);
if (y->dtype != (y_is_f32 ? (uint32_t)RAD_F32 : (uint32_t)RAD_BF16)) return R3D_NO(RAD_E_DTYPE);
long long N = r3d_geti_or(a, nkey, 0);
long long K = r3d_geti_or(a, kkey, 0);
if (N <= 0) N = r3d_dim(w, 0);
if (K <= 0) K = r3d_dim(w, 1);
if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE);
long long M = 0, x_rows = 0;
const long long y_pitch = r3d_rows_pitch(y, N, &M); /* M = numel(y)/N, the reference's fold */
if (y_pitch < N || M <= 0) return R3D_NO(RAD_E_STRIDE);
const long long x_pitch = r3d_rows_pitch(x, K, &x_rows);
if (x_pitch < K || x_rows < M) return R3D_NO(RAD_E_STRIDE);
if (r3d_numel(w) < N * K) return R3D_NO(RAD_E_SHAPE);
if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); /* N rows of K contiguous codes */
if (joined) {
/* The coverage checks, `scaled_rows`' last block: the planes must cover the band, and the
* scale plane covers it by blocks -- ceil, so a ragged vocabulary is fine (131 rows need 2
* scale rows) and a plane one row short is not. */
const long long sb_r = (N + kFp8Block - 1) / kFp8Block;
const long long sb_c = (K + kFp8Block - 1) / kFp8Block;
if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE);
if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE);
if (ce->row_bytes < ce->cols || se->row_bytes < se->cols * (h.sdt == 2 ? 4 : 2))
return R3D_NO(RAD_E_STRIDE);
}
if (M > (long long)1 << 24 || N > (long long)1 << 28 || K > (long long)1 << 28)
return R3D_NO(RAD_E_SHAPE);
if (!r3d_aligned(r3d_p(x), 16) || !r3d_aligned(r3d_p(w), 16) || !r3d_aligned(r3d_p(y), 16))
return R3D_NO(RAD_E_ALIGN);
const int sk = (int)r3d_geti_or(a, "sk", 1);
if (sk > 1) return R3D_NO(RAD_E_SHAPE); /* the grid is vocab-wide at every M, see the header */
const int kb = (int)r3d_geti_or(a, "kb", 0);
const int nt = (int)r3d_geti_or(a, "nt", 0);
const HeadQ* hp = joined ? &h : nullptr;
const int e = y_is_f32
? gemm_launch<true>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp)
: gemm_launch<false>(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K,
(int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp);
if (e == 0) return RAD_OK;
return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE
: e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE);
}
/* The reference's `enc_scaled_rows` and `float_scale_dt`, inlined: libref keeps them static inline in
* its own header, so a plugin that transcribes ref_layout_head transcribes them with it. Checks and
* order are its, unchanged: affine, untransformed, two planes, the roles in order, codes tiled with
* block {1,1} and a code dtype it admits, the scale tiled with a float dtype. */
bool float_scale_dt(uint32_t dt)
{
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
}
bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n)
{
if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false;
if (n != 2 || !sel) return false; /* sel_roles(enc, sel, n, "codes", "scale") */
const char* want[2] = { "codes", "scale" };
for (int i = 0; i < 2; ++i) {
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0) return false;
}
const RadEncPlane& c = enc->plane[sel[0]];
const RadEncPlane& sc = enc->plane[sel[1]];
return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 &&
(c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED &&
float_scale_dt(sc.dtype);
}
} // namespace
/* logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the declared entry (r3d.h's
* r3d_vocab_bf16.hip section). M <= 16 takes the decode arm, above it the prefill tile. */
extern "C" int r3d_logits_gemm_bf16(long x, long lm, long y, int M, int n_vocab, int n_embd,
int x_ld, int y_ld, int sk, int nt, long scratch, long stream)
{
(void)scratch; /* no split, so no partials: see the header */
return gemm_launch<true>(x, lm, y, M, n_vocab, n_embd, x_ld, y_ld, sk, kKC, nt, stream);
}
/* The same tiling with a bf16 y, for gemm_nt at prefill sizes (M >= 17; M <= 16 is the m16 row). */
extern "C" int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int K, int a_ld,
int y_ld, int sk, int kb, int nt, long scratch, long stream)
{
(void)scratch;
return gemm_launch<false>(a, b, y, M, N, K, a_ld, y_ld, sk, kb, nt, stream);
}
extern "C" int r3d_rad_logits_gemm_bf16(const RadArgs* a, RadStream s)
{
return rad_gemm_run(a, s, 1, "n_vocab", "n_embd");
}
extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s)
{
return rad_gemm_run(a, s, 0, "N", "K");
}
/* The head's layout hook, `ref::ref_layout_head` transcribed: operand 1 of
* logits_gemm, two planes, codes and one scale, untransformed -- and the answer is the container's
* own form. It moves no byte, and its `relayout` writer (below) exists for the round-trip: this is
* a reader, which is what
* the mapped tier asks for when a weight's stored form is not the container's. Operand 0 (the
* activations) and a one-plane selection are declined as `layout_scaled` declines them, and so is
* every other encoding: a silent no-op on a head is the worst failure a row can have. */
/* The head's WRITER. A layout query that answers RAD_OK is a promise the ABI makes to the loader --
* "out describes the stored form, and relayout will produce it" (rad_abi.h) -- and the load step
* holds the row to it. The container stores the quantiser's pair; the plan wants one operand; the
* row that owns the band assembles it, losslessly, with rad_planes_relayout: the header, the
* entries and each plane's rows, copied.
* No code is transformed and no number is derived -- a kernel doing arithmetic
* here would make the served numbers depend on which library loaded the container (rad_abi.h).
* The query and the writer share the plan through rad_planes_plan, so they cannot disagree. The
* operand guard is the hook's own rule repeated: a call routed to the wrong slot writes nothing. */
extern "C" int r3d_relayout_logits_head(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n_planes, void* dst,
int64_t dst_bytes)
{
(void)p; (void)n_p;
if (operand != 1) return R3D_NO(RAD_E_UNSUPPORTED);
return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
extern "C" int r3d_layout_logits_head(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out)
{
(void)p; (void)n_p; /* layout_scaled ignores both */
if (n < 2 || operand != 1) return RAD_E_UNSUPPORTED; /* layout_scaled(operand, 1, -1, ...) */
if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
+2 -2
View File
@@ -31,10 +31,10 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
| `attn_decode_h256_gqa6_fp8kv` / `..._bf16kv` | the same geometry, split-KV, `q_len * gqa` ≤ 64 |
| `attn_decode_h256_gqa6_scratch_bytes` / `attn_decode_h128_gqa4_scratch_bytes` | bytes of split-KV scratch a launch needs; ask before allocating, since the split count is chosen from the geometry |
| `attn_vit_h72_bf16` | dense non-causal vision-encoder attention, head_dim 72 native, varlen over images |
| `gdn_conv_prep_w4_h128_bf16` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum |
| `gdn_conv_prep_w4_h128_bf16` / `..._f32wgt` | the GDN prefill preamble in one kernel: causal conv (width 4, silu, with its state cache), q/k/v split, qk l2norm, gating and the per-chunk gate cumsum |
| `gdn_kkt_solve_k128_c64_bf16` | `A = (I + strict_lower(diag(beta) K K^T e^dg))^-1` per chunk of 64: the gram and its triangular inverse, without the fp32 gram reaching memory |
| `gdn_chunk_scan_k128_v128_c64_bf16` | gated-delta-net chunked scan: WY recompute, state recurrence and output in one kernel; head_k 128, head_v 128, chunk 64 |
| `gdn_conv_update_w4_h128_bf16` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly |
| `gdn_conv_update_w4_h128_bf16` / `..._f32wgt` | the same convolution for a decode step: a rolling speculative window over the conv state cache, writing q/k/v directly |
| `gdn_recurrent_update_k128_v128_bf16_fp32state` | the decode-time recurrent delta-rule update against the paged fp32 state cache, gating and qk l2norm included |
| `gdn_gated_rmsnorm_h128_bf16` | gated RMS norm over a 128-channel row, `out = rms(x) . w . act(z)` |
| `ar_oneshot_2rank_exact` | one-shot push all-reduce over P2P, exactly 2 ranks, exact bf16/fp16/fp32 |
+24 -2
View File
@@ -220,6 +220,16 @@ int r4d_gdn_conv_prep_w4_h128_bf16(
const void* A_log, const void* dt_bias, void* q, void* k, void* v, void* g, void* beta,
const void* cu, int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr,
void* stream);
// The same with an f32 `wgt`, as a GGUF stores ssm_conv1d. Every other operand is as above, and
// a bf16-representable weight gives the same bytes.
int r4d_gdn_conv_prep_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16,
const void* A_log, const void* dt_bias, void* q, void* k, void* v, void* g, void* beta,
const void* cu, int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr,
void* stream);
// The same convolution for a decode step over a speculative window. The state cache is a rolling
// buffer of width-1 + num_spec entries read at the slot the last accepted token left; q / k / v
@@ -229,6 +239,12 @@ int r4d_gdn_conv_update_w4_h128_bf16(
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream);
// The same with an f32 `wgt`, as for the prefill convolution.
int r4d_gdn_conv_update_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream);
// The gated RMS norm on the layer's output: out = rms(x) . w . act(z), one row per (token, head).
// Replaces FLA's rmsnorm_fn. act: 0 = silu/swish, 1 = sigmoid. Prefill only; the decode kernel
@@ -685,6 +701,12 @@ void r4d_moe_gemm_pin_down_dec(int pin);
// (refused likewise, and below 512 rows, whose scratch is not sized for their weight planes).
// All bit-identical; r4d_selftest compares their bytes.
void r4d_hc_read_pin_prefill(int form);
// Test hook: pins the gated residual read's decode kernels. 0 is the launcher's rule (kernels A and
// B as one grid at one to seven rows where the per-stream counters exist, the tiled up-mix's K
// passes pipelined from eight rows), 1 the kernels the rule replaced (A, then the up-mix in a second
// launch; the tiled up-mix's passes in sequence). Bit-identical; r4d_selftest compares their bytes
// and --perfhc times both.
void r4d_hc_read_pin_decode(int form);
// Test hook: pins the MLA matrix row's key load. 0 is the launcher's rule (sixteen-byte vectors
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
// Bit-identical; r4d_selftest compares them and --perfmla times both.
@@ -791,8 +813,8 @@ int r4d_gate_quant_fp8(long g, long x, long y, long q, long s, int M, int n, in
// on the norm's load. IPC arguments are r4d_ar_oneshot_2rank_exact's; `nblocks` is clamped to M
// because a block owns whole rows, and `x` takes no pitch because it is also the message. Like the
// int8 twin r4d_ar_ln_had_quant_i8 it has two wires: `wire` 0 is the exact bf16 payload, 6 the
// rotated 6-bit one. Wire 6 needs `n` to be a multiple of r4d_ar_rmsnorm_quant_fp8_chunk_elems()
// so a chunk never straddles a row.
// rotated 6-bit one. Wire 6 needs `n` to be a multiple of 64 (a group never straddles a row); a
// row that is not whole r4d_ar_rmsnorm_quant_fp8_chunk_elems() chunks pads its last one with zeros.
int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flags, long my_flags,
long seq_ctrs, long slot_stride16,
long x, long res, long w, long y, long q, long s,
+14 -5
View File
@@ -351,11 +351,13 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
sq = r4d_ar_ipc_alloc(kSeqWords(maxb) * 4, 0, handle, &hlen));
/* This rank's own packed copy, for the rotated 6-bit wire only: the reduce must fold exactly
* the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the scales 1/64, so half
* the message plus a thirty-second plus a page is ample. */
* the bytes it sent. The 6-bit payload is 3/8 of the bf16 message and the f32 scales 1/32 of
* it, laid out from half the slot; a row padded to whole 512-element chunks
* (ar_rmsnorm_quant_fp8) adds up to 7 groups' scales a row, so the scales get a sixteenth
* (enough for any row of 512 or more) plus a page. ar_rmsnorm_quant checks the fit. */
if (in->dtype != 2) {
R4D_TRY("ar_ipc_alloc(locpack)",
lp = r4d_ar_ipc_alloc(in->slot_bytes / 2 + in->slot_bytes / 32 + 4096, 0,
lp = r4d_ar_ipc_alloc(in->slot_bytes / 2 + in->slot_bytes / 16 + 4096, 0,
handle, &hlen));
}
@@ -1353,11 +1355,18 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
if (wire != 0 && wire != 6) return RAD_E_INVAL;
if (wire == 6) {
const int ce = r4d_ar_rmsnorm_quant_fp8_chunk_elems();
if (ce <= 0 || K % ce) return RAD_E_SHAPE;
/* Whole 64-element groups a row; the last 512-element chunk may be partial (padded). */
if (ce <= 0 || K % 64) return RAD_E_SHAPE;
/* This rank's packed-half side buffer exists for every bf16 instance; missing means a
* broken init. */
if (!in->locpack) return RAD_E_STATE;
if (wpo) return RAD_E_UNSUPPORTED; // the post-norm is the exact wire's only
/* The padded message must fit: payload (3/4 byte an element) in the peer slot's half and
* in locpack's, the bf16 scales in the slot's other half, the f32 ones in locpack after
* half the slot (its allocation: a sixteenth of the slot plus a page). */
const long long chunks = M * ((K + ce - 1) / ce), groups = chunks * (ce / 64);
if (chunks * (ce * 6 / 8) > in->slot_bytes / 2 || groups * 2 > in->slot_bytes / 2 ||
groups * 4 > in->slot_bytes / 16 + 4096)
return RAD_E_SHAPE;
}
R4dArCfg cfgv;
+54 -18
View File
@@ -310,6 +310,10 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
// Rotation and amax close over a 64-element group, so the bytes are identical; the chunk size only
// sets ownership. A chunk may not straddle a row (both ranks must agree on a block's bytes), and a
// wave owns a whole chunk, so a smaller chunk employs more waves (see r4d_ar_ln_had_quant_i8.hip).
// A row of whole 64-element groups that is not whole chunks (TranslateGemma's 5376 = 10.5 chunks)
// ends in a partial chunk: its missing groups go out as zeros and are not stored back. Every real
// group is the same 64 elements as in the flat message, so its bytes, and the sum, are the
// standalone wire's; with whole chunks the mapping is the flat one.
//
// The reduced row goes back to global `x`, not LDS: unlike the int8 twin this norm needs no
// in-place rotation, and pass two re-reads the row L1-hot as the standalone norm does.
@@ -372,11 +376,16 @@ __device__ __forceinline__ unsigned int arq_load_acq(const unsigned int* p) {
// POST: a sandwich-norm junction (Gemma 3): the reduced sum is post-normed against `wp` before the
// residual add, `v = bf16(sum * s1 * (wp + wadd))` with s1 the sum's own rms, as rmsnorm_quant_i8's
// POST computes it. `x` still receives the reduced sum. Exact wire and a residual only.
// POST computes it. `x` still receives the reduced sum. Either wire (the compressed one has already
// stored the sum into `x`); a residual only.
//
// HI8: ar_rmsnorm_had_quant_i8g, pass two in norm_quant_row's rotated int8 form. The reduction and
// the norm are untouched, so `x`, the residual and `y` are ar_rmsnorm_quant_fp8's bytes.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false>
// PAD (wire 6 only): the row is whole 64-element groups but not whole chunks, so its last chunk is
// padded and a chunk's elements are found by (row, chunk in row). Without it the flat index is the
// element offset, the code a row of whole chunks has always run.
template <bool WF32, bool RES, uint32_t THR, int WIRE, bool POST = false, bool HI8 = false,
bool PAD = false>
__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w,
const void* __restrict__ wp,
@@ -393,7 +402,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb);
/* Chunks per row and this block's window into the global chunk numbering, derived identically
* on both ranks from (M, nb, n). */
const int cpr = WIRE ? (int)(n / ARQ_CE) : 0;
const int cpr = WIRE ? (int)(PAD ? (n + ARQ_CE - 1) / ARQ_CE : n / ARQ_CE) : 0;
const int gpr = (int)(n / ARQ_GROUP); /* the real groups a row has; the rest of its last chunk pads */
(void)gpr;
const int c00 = r0 * cpr, cpb = (r1 - r0) * cpr;
const uint32_t lane = tid & (ARQ_WV - 1), wave = tid / ARQ_WV;
const int lig = (int)(lane & (ARQ_LPG - 1)), gw = (int)(lane / ARQ_LPG);
@@ -430,8 +441,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
} else {
/* Rotate, amax, quantise and pack straight into the peer's slot. A wave owns whole chunks,
* so every lane emits ARQ_NWORD dwords per chunk and the flush is lane-uniform. No group is
* partial (n is whole chunks, a block owns whole rows), so the standalone kernel's `live`
* guard is unnecessary and every cross-lane stage is fully active. */
* partial (n is whole groups, a block owns whole rows), so every cross-lane stage is fully
* active; a group past the row's end (a partial last chunk) packs zeros. */
for (int ci = (int)wave; ci < cpb; ci += (int)(THR / ARQ_WV)) {
const int c = c00 + ci;
unsigned int acc[ARQ_NWORD];
@@ -440,10 +451,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
#pragma unroll
for (int t = 0; t < ARQ_ITERS; ++t) {
const int g = c * ARQ_CG + t * ARQ_GPW + gw;
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
float v[ARQ_EPL];
if constexpr (PAD) {
const int cr = c / cpr, gr = (c - cr * cpr) * ARQ_CG + t * ARQ_GPW + gw;
const bool live = gr < gpr;
const long off = (long)cr * n + (long)gr * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) v[i] = bf2f(x[off + i]);
for (int i = 0; i < ARQ_EPL; ++i) v[i] = live ? bf2f(x[off + i]) : 0.0f;
} else {
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) v[i] = bf2f(x[off + i]);
}
arq_wht(v, lig);
float a = 0.0f;
#pragma unroll
@@ -590,9 +609,18 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
+ (float)((int)(lsy & ARQ_MASK) + ARQ_QMIN) * lsc;
}
arq_wht(v, lig);
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
if constexpr (PAD) {
const int cr = c / cpr, gr = (c - cr * cpr) * ARQ_CG + gl;
if (gr < gpr) {
const long off = (long)cr * n + (long)gr * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
}
} else {
const long off = (long)g * ARQ_GROUP + (long)lig * ARQ_EPL;
#pragma unroll
for (int i = 0; i < ARQ_EPL; ++i) x[off + i] = f2bf(v[i]);
}
}
}
/* Pass two reads all of `x`'s row; each wave wrote only its own chunks. */
@@ -610,13 +638,14 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
(void)pr;
float ss = 0.0f;
if constexpr (POST && WIRE == 0 && RES) {
if constexpr (POST && RES) {
/* Pass one reduces and takes the sum's sum of squares; pass two post-norms it, adds it
* into the stream and takes the stream's. Each thread reads back only its own columns. */
float s1s = 0.0f;
for (uint32_t i = tid; i < n; i += THR) {
const uint16_t a = f2bf(bf2f(xr[i]) + bf2f(pr[i]));
xr[i] = a;
uint16_t a;
if constexpr (WIRE == 0) { a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a; }
else { a = xr[i]; }
const float av = bf2f(a);
s1s += av * av;
}
@@ -862,7 +891,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
int nblocks, int nthreads, int drain, int acq, int wire,
long loc_pack, long loc_scale_off, long wp, bool hi8) {
if (!x || !w || !q || !s) return -1;
if (wp && (!res || wire != 0)) return -10; // a post-norm needs the stream and the exact wire
if (wp && !res) return -10; // a post-norm needs the stream
if (hi8 && wp) return -11;
if (hi8 && (n % (int)kGroup)) return -12;
if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1;
@@ -871,8 +900,9 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
// four columns (see norm_quant_row).
if (n % 8) return -5;
if (wire != 0 && wire != 6) return -7;
// A chunk may not straddle a row, or the ranks would disagree about a block's bytes.
if (wire == 6 && (n % ARQ_CE)) return -8;
// A group may not straddle a row, or the ranks would disagree about a block's bytes; a row's
// last chunk may be partial (its missing groups go out as zeros).
if (wire == 6 && (n % ARQ_GROUP)) return -8;
if (wire == 6 && (!loc_pack || loc_scale_off <= 0)) return -9;
if (!r_ld) r_ld = n;
if (!y_ld) y_ld = n;
@@ -887,8 +917,9 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
// The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order).
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
if (thr != 256 && thr != 512 && thr != 1024) return -6;
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H>), dim3((uint32_t)nb), \
const bool pad = wire == 6 && (n % ARQ_CE) != 0;
#define R4D_ARQ_HP(wf, rs, T, W, PO, H, PD) \
hipLaunchKernelGGL((ar_rmsnorm_quant_fp8_kernel<wf, rs, T, W, PO, H, PD>), dim3((uint32_t)nb), \
dim3(T), 0, \
(hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, (const void*)w, \
(const void*)wp, \
@@ -898,12 +929,16 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
(long)loc_scale_off, M, (uint32_t)n, \
(uint32_t)nkb, eps, wadd, (uint32_t)r_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
(uint32_t)s_ld, (int)slot_stride16, drain, acq, (unsigned)nbw)
#define R4D_ARQ_H(wf, rs, T, W, PO, H) \
do { if (pad) R4D_ARQ_HP(wf, rs, T, W, PO, H, (W == 6)); \
else R4D_ARQ_HP(wf, rs, T, W, PO, H, false); } while (0)
#define R4D_ARQ_P(wf, rs, T, W, PO) R4D_ARQ_H(wf, rs, T, W, PO, false)
#define R4D_ARQ_T(wf, rs, T, W) \
do { if (hi8) R4D_ARQ_H(wf, rs, T, W, false, true); \
else R4D_ARQ_P(wf, rs, T, W, false); } while (0)
#define R4D_ARQ_W(wf, rs, T) \
do { if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
do { if (wire == 6 && rs && wp) R4D_ARQ_P(wf, rs, T, 6, true); \
else if (wire == 6) R4D_ARQ_T(wf, rs, T, 6); \
else if (rs && wp) R4D_ARQ_P(wf, rs, T, 0, true); \
else R4D_ARQ_T(wf, rs, T, 0); } while (0)
#define R4D_ARQ(wf, rs) \
@@ -917,6 +952,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
#undef R4D_ARQ_T
#undef R4D_ARQ_P
#undef R4D_ARQ_H
#undef R4D_ARQ_HP
return hipGetLastError() == hipSuccess ? 0 : -4;
}
+1 -1
View File
@@ -10,7 +10,7 @@
/* Every `const void*` libr4d takes has one element type, cast inside the kernel (e.g.
* r4d_gdn_conv_prep_w4_h128_bf16 reads `wgt` as bf16 and `A_log` as f32); the signature does not
* say so. A plugin declaring `ssm_conv1d.weight` or the `gdn_kkt` buffer as f32 would be read as
* say so. A plugin declaring the `gdn_kkt` buffer as f32 would be read as
* bf16 on the device, while libref (which honours each operand's dtype) stays correct, so the bug
* would show only on the device path. The shim therefore checks dtypes by name (spec §2.1). */
static inline int r4d_dt(const RadTensor* t, uint32_t want) {
+13
View File
@@ -4,9 +4,22 @@
// A single definition keeps the fold byte-identical to the standalone path: the reciprocal form
// below changes the last bit of some bf16 outputs.
#pragma once
#include "r4d_gdn_wmma.h"
#define R4D_GDN_CONV_W 4 // conv width; the state holds R4D_GDN_CONV_W - 1 taps of history
// The weight is bf16 from a checkpoint and f32 from a GGUF, which keeps ssm_conv1d unquantised.
// cp_taps is a channel's taps as one vector load; cp_tap widens one tap to f32, exactly for
// either type.
template <typename WT> struct cp_vec4;
template <> struct cp_vec4<unsigned short> { using T = ushort4; };
template <> struct cp_vec4<float> { using T = float4; };
template <typename WT> using cp_taps = typename cp_vec4<WT>::T;
static_assert(R4D_GDN_CONV_W == 4, "cp_taps holds a channel's taps in one four-wide vector");
__device__ __forceinline__ float cp_tap(unsigned short w) { return bf2f(w); }
__device__ __forceinline__ float cp_tap(float w) { return w; }
// The result is rounded to bf16 immediately, so an IEEE-exact divide buys nothing: v_rcp_f32 is
// 1 ULP (~1e-7 relative) against bf16's 2^-8 quantum. The exact form is ~10 dependent instructions
// (v_div_scale, v_rcp, Newton, v_div_fmas, v_div_fixup); this is two. The conv update runs four
+80 -22
View File
@@ -72,10 +72,10 @@ __device__ __forceinline__ bool r4d_has_init(const void* p, int i32, int n) {
return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0;
}
template <int HPB, int ABF16>
template <int HPB, int ABF16, typename WT>
__global__ __launch_bounds__(HPB * 32)
void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
const unsigned short* __restrict__ wgt,
const WT* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long cs_seq, long cs_dim, long cs_tok,
@@ -150,7 +150,7 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
#pragma unroll
for (int c = 0; c < CP_DPL; ++c) {
#pragma unroll
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(wgt[(size_t)(d0 + c) * CP_W + i]);
for (int i = 0; i < CP_W; ++i) wt[i][c] = cp_tap(wgt[(size_t)(d0 + c) * CP_W + i]);
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
}
@@ -241,7 +241,8 @@ void r4d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long xpitch,
}
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
template <typename WT>
static int cp_prep_launch(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
@@ -256,8 +257,8 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
const int nchunk_ub = (T + CP_BT - 1) / CP_BT + N;
dim3 grid(nchunk_ub, units / hpb), blk(hpb * 32);
#define CP_LAUNCH(P, AB) \
hipLaunchKernelGGL((r4d_gdn_conv_prep_kernel<P, AB>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
hipLaunchKernelGGL((r4d_gdn_conv_prep_kernel<P, AB, WT>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const WT*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, \
cs_seq, cs_dim, cs_tok, (const int*)cache_idx, ci_stride, \
has_init, hi_i32, a, b, ab_stride, \
@@ -277,16 +278,44 @@ extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
return (int)hipGetLastError();
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log,
const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu,
int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream)
{
return cp_prep_launch<unsigned short>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
cache_idx, ci_stride, has_init, hi_i32, a, b, ab_stride,
ab_is_bf16, A_log, dt_bias, q, k, v, g, beta, cu, N, T, H,
Hg, K, V, width, softplus_thr, stream);
}
extern "C" int r4d_gdn_conv_prep_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, const void* cache_idx, long ci_stride,
const void* has_init, int hi_i32,
const void* a, const void* b, long ab_stride, int ab_is_bf16, const void* A_log,
const void* dt_bias, void* q, void* k, void* v, void* g, void* beta, const void* cu,
int N, int T, int H, int Hg, int K, int V, int width, float softplus_thr, void* stream)
{
return cp_prep_launch<float>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok, cache_idx,
ci_stride, has_init, hi_i32, a, b, ab_stride, ab_is_bf16, A_log,
dt_bias, q, k, v, g, beta, cu, N, T, H, Hg, K, V, width,
softplus_thr, stream);
}
// ---------------------------------------------------------------------------------------------
// Decode-time convolution. Same filter, but a step's tokens are a speculative window and the
// state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting
// at the slot the last accepted token left, and rewrites the buffer shifted by one. Writes q, k
// and v in their own layouts (no torch.cat for the recurrent kernel).
// ---------------------------------------------------------------------------------------------
template <int HPB>
template <int HPB, typename WT>
__global__ __launch_bounds__(HPB * 32)
void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitch,
const unsigned short* __restrict__ wgt,
const WT* __restrict__ wgt,
const unsigned short* __restrict__ bias,
unsigned short* __restrict__ cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max,
@@ -312,15 +341,14 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
const int unit = blockIdx.y * HPB + warp;
const int d0 = unit * CP_HD + lane * CP_DPL;
// A channel's weights are CP_W contiguous shorts: one vector load per channel.
static_assert(CP_W == 4, "the weight load reads a channel's taps as one ushort4");
// A channel's weights are CP_W contiguous elements: one vector load per channel.
float wt[CP_W][CP_DPL], bs[CP_DPL];
#pragma unroll
for (int c = 0; c < CP_DPL; ++c) {
const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * CP_W);
const unsigned short* ws = (const unsigned short*)&w4;
const cp_taps<WT> w4 = *(const cp_taps<WT>*)(wgt + (size_t)(d0 + c) * CP_W);
const WT* ws = (const WT*)&w4;
#pragma unroll
for (int i = 0; i < CP_W; ++i) wt[i][c] = bf2f(ws[i]);
for (int i = 0; i < CP_W; ++i) wt[i][c] = cp_tap(ws[i]);
bs[c] = bias ? bf2f(bias[d0 + c]) : 0.0f;
}
@@ -428,7 +456,8 @@ void r4d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long xpitc
#undef CU_TOKEN_BODY
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
template <typename WT>
static int cu_update_launch(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
@@ -443,8 +472,8 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1;
dim3 grid(N, units / hpb), blk(hpb * 32);
#define CU_LAUNCH(P) \
hipLaunchKernelGGL((r4d_gdn_conv_update_kernel<P>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const unsigned short*)wgt, \
hipLaunchKernelGGL((r4d_gdn_conv_update_kernel<P, WT>), grid, blk, 0, (hipStream_t)stream, \
(const unsigned short*)x, xpitch, (const WT*)wgt, \
(const unsigned short*)bias, (unsigned short*)cstate, cs_seq, cs_dim, \
cs_tok, state_len_max, (const int*)cache_idx, ci_stride, \
(const int*)num_accepted, (unsigned short*)q, (unsigned short*)k, \
@@ -459,6 +488,28 @@ extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
return (int)hipGetLastError();
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream)
{
return cu_update_launch<unsigned short>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
state_len_max, cache_idx, ci_stride, num_accepted, q,
k, v, cu, N, H, Hg, K, V, width, max_query_len, stream);
}
extern "C" int r4d_gdn_conv_update_w4_h128_bf16_f32wgt(
const void* x, long xpitch, const void* wgt, const void* bias, void* cstate,
long cs_seq, long cs_dim, long cs_tok, int state_len_max, const void* cache_idx,
long ci_stride, const void* num_accepted, void* q, void* k, void* v, const void* cu,
int N, int H, int Hg, int K, int V, int width, int max_query_len, void* stream)
{
return cu_update_launch<float>(x, xpitch, wgt, bias, cstate, cs_seq, cs_dim, cs_tok,
state_len_max, cache_idx, ci_stride, num_accepted, q, k, v, cu,
N, H, Hg, K, V, width, max_query_len, stream);
}
// ============================================================== the plugin ABI entry points
// Shared operand helpers: r4d_gdn_args.h. Operand enums use an OPD_ prefix because CP_W and CP_ST
// are already kernel constants in this unit.
@@ -535,12 +586,16 @@ extern "C" int r4d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) {
if (tb->dtype != ta->dtype) return R4D_NO(RAD_E_DTYPE);
if (!ab_is_bf16 && ta->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
/* bf16 x, weights, conv state and q/k/v; fp32 A_log, dt_bias, g and beta. */
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
/* bf16 x, conv state and q/k/v; bf16 or f32 weights (r4d_gdn_conv_tap.h); fp32 A_log,
* dt_bias, g and beta. */
R4D_DT(x, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(g, RAD_F32); R4D_DT(beta, RAD_F32);
if (w->dtype != RAD_BF16 && w->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const auto prep = w->dtype == RAD_F32 ? r4d_gdn_conv_prep_w4_h128_bf16_f32wgt
: r4d_gdn_conv_prep_w4_h128_bf16;
return R4D_RAW(r4d_gdn_conv_prep_w4_h128_bf16(
return R4D_RAW(prep(
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
cidx->data, (long)cidx->stride[0], hin ? hin->data : nullptr,
@@ -588,9 +643,12 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
if (H == 0 || Hg == 0 || H % Hg) return R4D_NO(RAD_E_SHAPE);
if (v->shape[0] != T || k->shape[0] != T) return R4D_NO(RAD_E_SHAPE);
/* bf16 x, weights, conv state and q/k/v, as in the prefill conv. */
R4D_DT(x, RAD_BF16); R4D_DT(w, RAD_BF16); R4D_DT(cst, RAD_BF16);
/* bf16 x, conv state and q/k/v, bf16 or f32 weights, as in the prefill conv. */
R4D_DT(x, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(q, RAD_BF16); R4D_DT(k, RAD_BF16); R4D_DT(v, RAD_BF16);
if (w->dtype != RAD_BF16 && w->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
const auto update = w->dtype == RAD_F32 ? r4d_gdn_conv_update_w4_h128_bf16_f32wgt
: r4d_gdn_conv_update_w4_h128_bf16;
const int width = (int)r4d_geti_or(a, "conv_width", 4);
/* state_len_max and max_query_len describe one window, so only one is free. The state cache
@@ -606,7 +664,7 @@ extern "C" int r4d_rad_gdn_conv_update(const RadArgs* a, RadStream s) {
const long long mql = state_len_max - (width - 2);
if (width < 2 || mql < 1) return R4D_NO(RAD_E_SHAPE);
return R4D_RAW(r4d_gdn_conv_update_w4_h128_bf16(
return R4D_RAW(update(
x->data, (long)xpitch, w->data, b ? b->data : nullptr, cst->data,
(long)cst->stride[0], (long)cst->stride[1], (long)cst->stride[2],
(int)state_len_max, sidx->data, (long)sidx->stride[0],
@@ -37,6 +37,7 @@
#include <cstring>
#include <map>
#include <mutex>
#include <type_traits>
#include <utility>
#define RU_K 128 // head_k
@@ -187,9 +188,11 @@ __device__ __forceinline__ float ru_act(float z, int kind) {
// channels and resets the counter (no waiting). A value head's v channels have one reader and are
// rewritten by it. Two launches sharing a counter block must not overlap; blocks are keyed on
// (stream, output), as split_ctr in r4d_gemm_fp8a8.hip.
//
// CV is also the weight's type: 1 bf16, 2 f32, read as gdn_conv_update reads it.
struct RuConv {
const unsigned short* x; long xpitch; // the projection's [q | k | v] columns, row pitch
const unsigned short* w; // [conv_dim, R4D_GDN_CONV_W]
const void* w; // [conv_dim, R4D_GDN_CONV_W], bf16 or f32 (CV)
const unsigned short* b; // [conv_dim] or null
unsigned short* cs; // the conv state cache
long cs_seq, cs_dim, cs_tok;
@@ -293,13 +296,15 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
const int off = naccept ? naccept[n] - 1 : 0;
const int ca = tid < RU_K ? hk * RU_K + tid : (Hg + hk) * RU_K + (tid - RU_K);
const int cb = (2 * Hg + hv) * RU_V + tid;
using CWT = std::conditional_t<CV == 2, float, unsigned short>;
const CWT* const cw = (const CWT*)cv.w;
const unsigned short* xr = cv.x + (size_t)bos * cv.xpitch;
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
if (t < T) cxa[t] = xr[(size_t)t * cv.xpitch + ca];
{
const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)ca * CW);
cwa[0] = bf2f(w4.x); cwa[1] = bf2f(w4.y); cwa[2] = bf2f(w4.z); cwa[3] = bf2f(w4.w);
const cp_taps<CWT> w4 = *(const cp_taps<CWT>*)(cw + (size_t)ca * CW);
cwa[0] = cp_tap(w4.x); cwa[1] = cp_tap(w4.y); cwa[2] = cp_tap(w4.z); cwa[3] = cp_tap(w4.w);
if (cv.b) cba = bf2f(cv.b[ca]);
}
spa = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)ca * cv.cs_dim;
@@ -309,8 +314,8 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
#pragma unroll
for (int t = 0; t < RU_CVT; ++t)
if (t < T) cxb[t] = xr[(size_t)t * cv.xpitch + cb];
const ushort4 w4 = *(const ushort4*)(cv.w + (size_t)cb * CW);
cwb[0] = bf2f(w4.x); cwb[1] = bf2f(w4.y); cwb[2] = bf2f(w4.z); cwb[3] = bf2f(w4.w);
const cp_taps<CWT> w4 = *(const cp_taps<CWT>*)(cw + (size_t)cb * CW);
cwb[0] = cp_tap(w4.x); cwb[1] = cp_tap(w4.y); cwb[2] = cp_tap(w4.z); cwb[3] = cp_tap(w4.w);
if (cv.b) cbb = bf2f(cv.b[cb]);
spb = cv.cs + (size_t)cslot * cv.cs_seq + (size_t)cb * cv.cs_dim;
#pragma unroll
@@ -864,7 +869,7 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row
// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and
// factor-block bounds are as in ru_update_launch.
// factor-block bounds are as in ru_update_launch. `w_f32` is the conv weight's type.
static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride,
const void* A_log, const void* dt_bias, void* state,
long st_slot, long st_head, void* o, void* oq, void* os,
@@ -872,7 +877,7 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
long sidx_stride, const void* nacc, const void* z,
long z_pitch, const void* nw, float neps, int nact, int N,
int H, int Hg, float scale, float thr, int state_fp16,
RadStream stream, int oq_i8, bool anc) {
RadStream stream, int oq_i8, bool anc, bool w_f32) {
if (anc && sidx_stride < 6) return RAD_E_SHAPE;
if (anc && sidx_stride * RU_FSTR > st_head) return RAD_E_SHAPE;
const int sdt = state_fp16 ? 1 : 0;
@@ -880,11 +885,11 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
const long flood = (long)N * slots_written * st_slot * (sdt ? 2 : 4);
const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024;
const dim3 grid(N, H, 1), blk(RU_V * 2);
#define RC_LAUNCH(NTC, ANCC, SDTC) \
do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC); else RC_LAUNCH_NM(1, NTC, ANCC, SDTC); } \
while (0)
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, 1>), \
#define RC_LAUNCH(NTC, ANCC, SDTC, CVC) \
do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \
else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0)
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC, CVC) \
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \
grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \
ab_stride, (const float*)A_log, (const float*)dt_bias, \
(ru_state<SDTC>::T*)state, st_slot, st_head, (unsigned short*)o, \
@@ -892,11 +897,14 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
(const int*)sidx, sidx_stride, (const int*)nacc, \
(const unsigned short*)z, z_pitch, (const float*)nw, neps, nact, H, Hg, \
scale, thr, cv)
#define RC_PICKNT(ANCC, SDTC) \
do { if (nt) RC_LAUNCH(1, ANCC, SDTC); else RC_LAUNCH(0, ANCC, SDTC); } while (0)
#define RC_PICKANC(SDTC) \
do { if (anc) RC_PICKNT(1, SDTC); else RC_PICKNT(0, SDTC); } while (0)
if (sdt) RC_PICKANC(1); else RC_PICKANC(0);
#define RC_PICKNT(ANCC, SDTC, CVC) \
do { if (nt) RC_LAUNCH(1, ANCC, SDTC, CVC); else RC_LAUNCH(0, ANCC, SDTC, CVC); } while (0)
#define RC_PICKANC(SDTC, CVC) \
do { if (anc) RC_PICKNT(1, SDTC, CVC); else RC_PICKNT(0, SDTC, CVC); } while (0)
#define RC_PICKSDT(CVC) \
do { if (sdt) RC_PICKANC(1, CVC); else RC_PICKANC(0, CVC); } while (0)
if (w_f32) RC_PICKSDT(2); else RC_PICKSDT(1);
#undef RC_PICKSDT
#undef RC_PICKANC
#undef RC_PICKNT
#undef RC_LAUNCH
@@ -1082,9 +1090,10 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
const long long ab_stride = r4d_row_pitch(ta);
if (ab_stride < 0 || r4d_row_pitch(tb) != ab_stride) return R4D_NO(RAD_E_STRIDE);
R4D_DT(x, RAD_BF16); R4D_DT(cw, RAD_BF16); R4D_DT(cb, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(x, RAD_BF16); R4D_DT(cb, RAD_BF16); R4D_DT(cst, RAD_BF16);
R4D_DT(ta, RAD_BF16); R4D_DT(tb, RAD_BF16); R4D_DT(o, RAD_BF16); R4D_DT(z, RAD_BF16);
R4D_DT(alog, RAD_F32); R4D_DT(dtb, RAD_F32); R4D_DT(nw, RAD_F32);
if (cw->dtype != RAD_BF16 && cw->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (state->dtype != RAD_F32 && state->dtype != RAD_F16) return R4D_NO(RAD_E_DTYPE);
if (oq) {
if (oq->dtype != RAD_F8E4M3 && oq->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
@@ -1113,7 +1122,7 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
RuConv cv{};
cv.x = (const unsigned short*)x->data; cv.xpitch = (long)xpitch;
cv.w = (const unsigned short*)cw->data; cv.b = cb ? (const unsigned short*)cb->data : nullptr;
cv.w = cw->data; cv.b = cb ? (const unsigned short*)cb->data : nullptr;
cv.cs = (unsigned short*)cst->data;
cv.cs_seq = (long)cst->stride[0]; cv.cs_dim = (long)cst->stride[1];
cv.cs_tok = (long)cst->stride[2];
@@ -1128,5 +1137,5 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
os ? (long)r4d_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0],
nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H,
(int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s,
oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0);
oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0, cw->dtype == RAD_F32);
}
+138 -33
View File
@@ -151,19 +151,30 @@ constexpr uint32_t kSplitThinCap = 64u;
* tuned at (the NT accumulators and K-step unroll are sized against it), so a compiler release
* cannot change occupancy. Shapes with one or two waves per block are LDS-bound and use that
* count. */
constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bool i8) {
constexpr uint32_t f8_waves(bool full, uint32_t nt, uint32_t mw, uint32_t fk, bool i8,
bool gated = false) {
if (mw == 1u) return nt == 1u ? 8u : nt == 2u ? 4u : nt == 3u ? 3u : 2u;
if (mw == 2u) return nt == 1u ? 12u : nt == 2u ? 8u : nt == 3u ? 5u : 4u;
if (!i8) {
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 16u : 12u) : nt == 3u ? 10u
: (full && mw >= 8u) ? 10u : 9u;
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? 9u : mw == 4u ? 7u : 8u;
/* The gated three-tile form at 8, not 9. At 9 waves' 168 registers its epilogue spilled
* 57 at the full tile (48 rows), which ran gate_up 51 % slower than 56 rows, and 10 below
* it, 70 with the LDS-staged scales. 8 waves leave 192, where it spills 9 and 10. The gated
* form is always MW 16, four waves a SIMD a block, so 8 and 9 both hold two blocks a WGP:
* no occupancy is lost. */
return nt == 1u ? 12u : nt == 2u ? 10u : nt == 3u ? (gated ? 8u : 9u)
: mw == 4u ? 7u : 8u;
}
if (fk == 128u)
return nt == 1u ? 16u : nt == 2u ? (full ? 10u : 12u) : nt == 3u ? (full ? 9u : 10u)
: full ? 7u : 9u;
if (nt == 1u) return 12u;
/* 10, not 12. The fold's LDS-staged scales (gemm_fp8a8_kernel) need a few more
* registers than 12 waves' 120 leave, and spilled. gfx12 allocates registers 24 at a time, so
* 11 waves leave 120 as well and 10 is the next step (144). No decode shape puts more than 8 of
* these waves on a SIMD, so the lower pin costs no occupancy. */
if (nt == 1u) return 10u;
if (nt == 2u) return full ? 9u : mw == 4u ? 9u : 10u;
if (nt == 3u) return full ? (mw == 16u ? 8u : 7u) : (mw == 4u ? 8u : 9u);
return full ? (mw == 4u ? 5u : 6u) : (mw == 4u ? 7u : 8u);
@@ -252,10 +263,6 @@ __device__ __forceinline__ void gemm_fp8a8_body(
const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg;
// The B rows this lane owns, one per N tile (column `frag_c` of each of its NT accumulators,
// 16 apart). A per-B-row scale must be looked up for each, not just the first.
const uint32_t brow0 = n0 + wn + frag_c(lane);
const uint8_t* bsrc = Bp + (size_t)(n0 + sn) * b_ld + sk;
// A as fragments: a wave owns one 16-row weight tile, so its A operand for 64 k is this lane's
// 32 bytes. `ksuper` is the plane's tile stride; `arow` is out of range only when N is not a
@@ -287,12 +294,76 @@ __device__ __forceinline__ void gemm_fp8a8_body(
afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes, alive && st < ksuper);
}
/* The fold's scales are staged through LDS a K tile ahead, beside the B tile. The
* fold loaded them itself, after the next tile's prefetch had been issued; loads return in
* order, so each fold waited for that whole prefetch, twice a tile at FK = 256, and the "one
* tile ahead" overlapped nothing. Now the block's threads each load one weight-scale dword and
* one activation scale of tile c0+FK with its B prefetch (a few each only in the selftest's
* one- and two-wave pins) and store them at the top of the next pass with the B tile, so a fold
* reads LDS. Two registers a thread: holding a tile's scales a lane (8 + 2*NT registers)
* spilled at the decode shapes' register pins. Same values as before: bit-identical. A dead
* wave's fp8 block scale reads as 0 instead of the plane row past the end it used to read; its
* rows are never stored.
*
* A tile holds kFolds = FK / kBlock scale blocks, and the fold at `ks` uses block ks / kBlock
* of its tile. s_ws: I8, each wave's 16 bf16 row scales a block, [MW][kFolds][8] dwords
* (r4d_fp8_layout.cpp's tile-major plane); fp8, each wave's one bf16 block scale,
* [MW][kFolds]. s_as: each B row's f32 scale a block, [kFolds][FN]. */
constexpr uint32_t kFolds = (FK + kBlock - 1) / kBlock;
constexpr uint32_t kWS = I8 ? MW * kFolds * 8u : MW * kFolds;
constexpr uint32_t kAS = kFolds * FN;
constexpr uint32_t kWSPer = (kWS + MW * kWave - 1) / (MW * kWave);
constexpr uint32_t kASPer = (kAS + MW * kWave - 1) / (MW * kWave);
__shared__ __attribute__((aligned(16))) uint32_t s_ws[kWS];
__shared__ float s_as[kAS];
const uint32_t nkb8 = (cols + kBlock - 1) / kBlock;
auto load_ws = [&](uint32_t c, uint32_t i) -> uint32_t {
if (i >= kWS) return 0u;
if constexpr (I8) {
const uint32_t tr = (m0 + (i / (kFolds * 8u)) * 16u) / 16u;
const uint32_t kb = c / kBlock + (i / 8u) % kFolds;
return ((Full || tr * 16u < rows) && kb < nkb8)
? ((const uint32_t*)Sa)[((size_t)tr * nkb8 + kb) * 8u + i % 8u] : 0u;
} else {
const uint32_t w = i / kFolds, kb = c / kBlock + i % kFolds;
const uint32_t wr = GATED ? ((w < kGHalf ? 0u : rows / 2u) + blockIdx.x * (FM / 2u)
+ (w % kGHalf) * 16u)
: (m0 + w * 16u);
return ((Full || wr < rows) && kb < nkb8)
? (uint32_t)((const uint16_t*)Sa)[(size_t)(wr / kBlock) * sa_ld + kb] : 0u;
}
};
auto load_as = [&](uint32_t c, uint32_t i) -> float {
if (i >= kAS) return 0.0f;
const uint32_t tok = n0 + i % FN, kb = c / kBlock + i / FN;
return ((Full || tok < nb) && kb < nkb8) ? ((const float*)Sb)[(size_t)tok * sb_ld + kb]
: 0.0f;
};
uint32_t qws[kWSPer];
float qas[kASPer];
auto load_q = [&](uint32_t c) {
#pragma unroll
for (uint32_t r = 0; r < kWSPer; ++r) qws[r] = load_ws(c, tid + r * MW * kWave);
#pragma unroll
for (uint32_t r = 0; r < kASPer; ++r) qas[r] = load_as(c, tid + r * MW * kWave);
};
load_q(kbeg);
// The B rows this lane owns within the tile, one per N tile (column `frag_c` of each of its NT
// accumulators, 16 apart). A per-B-row scale must be looked up for each, not just the first.
const uint32_t bl0 = wn + frag_c(lane);
for (uint32_t c0 = kbeg; c0 < kend; c0 += FK) {
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r < FN) stage8_store<FK>(s_b, r, sk, pb[p]);
}
#pragma unroll
for (uint32_t r = 0; r < kWSPer; ++r)
if (tid + r * MW * kWave < kWS) s_ws[tid + r * MW * kWave] = qws[r];
#pragma unroll
for (uint32_t r = 0; r < kASPer; ++r)
if (tid + r * MW * kWave < kAS) s_as[tid + r * MW * kWave] = qas[r];
__syncthreads();
const uint32_t c1 = c0 + FK;
if (c1 < kend) {
@@ -311,6 +382,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
afrag + (size_t)(arow * ksuper + st) * r4d_fp8::kTileBytes,
alive && st < ksuper);
}
load_q(c1);
}
#pragma unroll
@@ -332,19 +404,16 @@ __device__ __forceinline__ void gemm_fp8a8_body(
// Gating it at the compile-time-known positions is legal and byte-identical but raises
// the register live range of the fold; see libr4d/isa/README.md.
if ((c0 + ks + kK) % kBlock == 0 || c0 + ks + kK >= kend) {
const uint32_t kb = (c0 + ks) / kBlock;
/* This tile's scale block for `ks`, staged with the tile. */
const uint32_t f = ks / kBlock < kFolds ? ks / kBlock : kFolds - 1u;
if constexpr (I8) {
// A is the int8 weight with a bf16 scale per row. A lane's eight accumulator
// slots are eight consecutive rows of one 16-row tile, adjacent in the
// tile-major [N/16][K/128][16] plane: one 16-byte load. B is the activation.
const uint32_t nkb8 = (cols + kBlock - 1) / kBlock;
float wsr[8];
{
const uint32_t tr = wrow0 / 16u;
uint4 w8 = make_uint4(0u, 0u, 0u, 0u);
if (Full || tr * 16u < rows)
w8 = *(const uint4*)((const uint16_t*)Sa +
((size_t)tr * nkb8 + kb) * 16u + (lane >> 4) * 8u);
const uint4 w8 =
*(const uint4*)&s_ws[(wave * kFolds + f) * 8u + (lane >> 4) * 4u];
const uint32_t d[4] = { w8.x, w8.y, w8.z, w8.w };
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
@@ -352,9 +421,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
}
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t tok = brow0 + j * 16;
const float s = (Full || tok < nb)
? ((const float*)Sb)[(size_t)tok * sb_ld + kb] : 0.0f;
const float s = s_as[f * FN + bl0 + j * 16u];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += acc_val<I8>(raw[j][t]) * (wsr[t] * s);
@@ -365,14 +432,10 @@ __device__ __forceinline__ void gemm_fp8a8_body(
// A is the weight: one bf16 scale for this wave's 16 rows, which sit in one
// scale row. B is the activation: one f32 scale per (token, 128-column block),
// one per lane per tile.
const float ws =
bscale(((const uint16_t*)Sa)[(size_t)(wrow0 / kBlock) * sa_ld + kb]);
const float ws = bscale((uint16_t)s_ws[wave * kFolds + f]);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t tok = brow0 + j * 16;
const float s = ws * ((Full || tok < nb)
? ((const float*)Sb)[(size_t)tok * sb_ld + kb]
: 0.0f);
const float s = ws * s_as[f * FN + bl0 + j * 16u];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += raw[j][t] * s;
@@ -382,8 +445,8 @@ __device__ __forceinline__ void gemm_fp8a8_body(
}
}
}
// Wait until every wave has finished reading before the tile is overwritten. The
// prefetched fragments become current.
// Wait until every wave has finished reading before the tile and its scales are
// overwritten. The prefetched fragments become current.
#pragma unroll
for (uint32_t p = 0; p < kAF; ++p) pf[p] = pfn[p];
__syncthreads();
@@ -583,12 +646,54 @@ __device__ __forceinline__ void gemm_fp8a8_body(
const uint32_t rlo = m0, rhi = min(m0 + FM, rows);
const float* const w0 = (const float*)Y;
uint16_t* const cy = (uint16_t*)C;
for (uint32_t idx = tid; idx < (rhi - rlo) * nb; idx += MW * kWave) {
const uint32_t r = rlo + idx / nb, col = idx % nb;
const size_t o = (size_t)col * rows + r;
float acc = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[(size_t)z * rows * nb + o];
cy[o] = f32_to_bf16(acc);
/* Consecutive threads take consecutive weight rows, which are adjacent in a
* partial plane ([nb][rows]), four rows a thread as one 16-byte load and kFinU quads in
* flight at each z. The loop walked the token index fastest, `rows` floats apart, one
* element a thread at a time: a cache line a load and a round trip each, which at
* N = 512, M = 64 (four columns of blocks finishing 8,192 elements over four planes)
* was most of a 45 us call. Each element is still summed from 0.0f in ascending z:
* bit-identical. */
const uint32_t nr = rhi - rlo;
const size_t zs = (size_t)rows * nb;
if ((rows & 3u) == 0u && (nr & 3u) == 0u && ((uintptr_t)C & 7u) == 0u
&& ((uintptr_t)Y & 15u) == 0u) {
constexpr uint32_t kFinU = 4;
const uint32_t nq = nr / 4u, total = nq * nb;
for (uint32_t b = tid; b < total; b += kFinU * MW * kWave) {
size_t o[kFinU];
float4 acc[kFinU];
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
const uint32_t idx = b + u * MW * kWave;
o[u] = idx < total ? (size_t)(idx / nq) * rows + rlo + (idx % nq) * 4u : 0u;
acc[u] = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
}
for (uint32_t z = 0; z < gridDim.z; ++z) {
float4 v[kFinU];
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u)
v[u] = b + u * MW * kWave < total ? *(const float4*)(w0 + z * zs + o[u])
: make_float4(0.0f, 0.0f, 0.0f, 0.0f);
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
acc[u].x += v[u].x; acc[u].y += v[u].y;
acc[u].z += v[u].z; acc[u].w += v[u].w;
}
}
#pragma unroll
for (uint32_t u = 0; u < kFinU; ++u) {
if (b + u * MW * kWave >= total) continue;
*(uint2*)(cy + o[u]) = make_uint2(bf16x2_rne(acc[u].x, acc[u].y),
bf16x2_rne(acc[u].z, acc[u].w));
}
}
} else {
for (uint32_t idx = tid; idx < nr * nb; idx += MW * kWave) {
const size_t o = (size_t)(idx / nr) * rows + rlo + idx % nr;
float acc = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[z * zs + o];
cy[o] = f32_to_bf16(acc);
}
}
}
}
@@ -598,7 +703,7 @@ __device__ __forceinline__ void gemm_fp8a8_body(
Sc, Yb, q_ld, s_ld, y_ld, Bias, c_ld
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8, GATED))
void gemm_fp8a8_kernel(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
@@ -613,7 +718,7 @@ void gemm_fp8a8_kernel(
}
template <bool Full, uint32_t NT, uint32_t MW, uint32_t FK,
bool GATED = false, bool I8 = false, bool BIAS = false>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8))
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(f8_waves(Full, NT, MW, FK, I8, GATED))
void r4dchain_gemm_fp8a8(
const uint8_t* __restrict__ Ap, const void* __restrict__ Sa,
const uint8_t* __restrict__ Bp, const void* __restrict__ Sb,
+1287 -196
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -365,6 +365,7 @@ int w4_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W4_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
const bool asym = w4_asym(p, n_p);
const bool ok = asym ? (r4d_enc::affine(enc, RAD_U4, RAD_F16, 1, g.group, RAD_U8) ||
@@ -474,6 +475,7 @@ int w5_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W4_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W4_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W4_KPB) return RAD_E_SHAPE;
if (!w5_enc(enc, g.group)) return RAD_E_DTYPE;
if (gout) *gout = g;
@@ -676,6 +678,7 @@ int w8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W8_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W8_GROUP) return RAD_E_DTYPE;
if (g.K % R4D_W8_KPB) return RAD_E_SHAPE;
if (!r4d_enc::affine(enc, RAD_I8, RAD_F16, 1, g.group)) return RAD_E_DTYPE;
if (gout) *gout = g;
@@ -760,6 +763,7 @@ int w2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
WGeom g;
int rc = wgeom(p, n_p, R4D_W2_GROUP, &g);
if (rc != RAD_OK) return rc;
if (g.group != R4D_W2_GROUP) return RAD_E_DTYPE;
if (g.K % 128) return RAD_E_SHAPE;
if (!(r4d_enc::affine(enc, RAD_U2, RAD_F16, 1, g.group, RAD_U8) ||
r4d_enc::affine(enc, RAD_U2, RAD_F16, 1, g.group, RAD_U4))) return RAD_E_DTYPE;
+35 -21
View File
@@ -1448,7 +1448,7 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = {
};
/* ar_rmsnorm_post_quant_fp8: the same with a sandwich post-norm of the reduced sum before the add
* (Gemma 3's junction, arch/gemma3), exact wire only. Its own op: an optional seventh operand on
* (Gemma 3's junction, arch/gemma3), on either wire. Its own op: an optional seventh operand on
* ar_rmsnorm_quant_fp8 would break every plugin that issues that op's six. */
static const RadOperandSpec oArRmsNormPostQuantFp8[] = {
{ "x", RAD_OPD_INOUT, 0 },
@@ -3542,7 +3542,7 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("ar_rmsnorm_post_quant_fp8", pArRmsNormQuantFp8, oArRmsNormPostQuantFp8,
"ar_rmsnorm_quant_fp8 with a post-norm of the reduced sum against w_post before the "
"residual add (a sandwich-norm junction), exact wire only, byte-identical to all_reduce, "
"residual add (a sandwich-norm junction), either wire, byte-identical to all_reduce, "
"rmsnorm, rmsnorm_quant_fp8."),
SCHEMA("ar_rmsnorm_quant_fp8", pArRmsNormQuantFp8, oArRmsNormQuantFp8,
"the two-rank all-reduce and the residual add, RMS norm and block-scaled fp8 "
@@ -4704,30 +4704,39 @@ static const RadConstraint cGemmNt64[] = {
static const RadConstraint cGemmNtTiled[] = {
C_GE("M", 65), C_LE("M", 65536), C_GE("N", 128), C_DIV("K", 64), C_IN("dtype", "bf16"),
};
/* The dense integer kernels take their group from a build constant and read no `group` argument.
* A declaration at another group gets no kernel rather than a silent 128. */
static const RadConstraint cGemmNtW4[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a16"),
};
/* w5a16 serves any M: the dispatcher takes rows past 64 as chunks of 64. */
static const RadConstraint cGemmNtW5[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a16"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w5a16"),
};
static const RadConstraint cGemmNtW4Asym[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a16_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a16_asym"),
};
static const RadConstraint cGemmNtW4A8I8[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8i8_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8i8_asym"),
};
static const RadConstraint cGemmNtW5A8I8[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w5a8i8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w5a8i8"),
};
static const RadConstraint cGemmNtW2A8[] = {
C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w2a8"),
C_DIV("K", 128), C_DIV("N", 16), C_EQ("group", R4D_W2_GROUP), C_IN("dtype", "w2a8"),
};
static const RadConstraint cGemmNtW8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w8a16"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a16"),
};
static const RadConstraint cGemmNtW4A8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w4a8 w4a8_asym"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8 w4a8_asym"),
};
static const RadConstraint cGemmNtMxfp4A8[] = {
C_LE("M", 64), C_DIV("K", 32), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
@@ -5053,11 +5062,13 @@ static const RadConstraint cDequantW4Bf16[] = {
* K % (SK*group)). Its MAX_M of 32768 is not structural; as a skinny kernel with a tiled sibling
* above 64, it takes the w4a8 row's band. */
static const RadConstraint cGemmNtW8A8[] = {
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16), C_IN("dtype", "w8a8"),
C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 16),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a8"),
};
/* r4d_gemm_w4a8_tiled / _asym_tiled. Entry point: N % 256, K % group, M >= 1. */
static const RadConstraint cGemmW4A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8 w4a8_asym"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W4_GROUP), 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
@@ -5108,13 +5119,15 @@ static const RadConstraint cGemmM2xfp4A8Tiled[] = {
/* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so
* `w8a8_asym` is absent from the dtype set. */
static const RadConstraint cGemmW8A8Tiled[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w8a8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W8_GROUP), C_IN("dtype", "w8a8"),
};
/* r4d_gemm_w4a8_prefill. Entry point: N % BN and K % group, BN being the variant's block width
* (256 except for the two 1024-thread arms). N % 256 is the default's condition; the shim refuses
* a variant whose BN does not divide N (the per-call half of spec §2.1). */
static const RadConstraint cGemmW4A8Prefill[] = {
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256), C_IN("dtype", "w4a8"),
C_GE("M", 1), C_DIV("K", 128), C_DIV("N", 256),
C_EQ("group", R4D_W4_GROUP), C_IN("dtype", "w4a8"),
};
/* =================================================================================== tunables
@@ -7272,7 +7285,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"gdn prefill preamble: causal conv + qkv split + qk l2norm + gating + per-chunk cumsum "
"[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]",
"conv width 4, head_k/head_v 128, chunk 64, varlen, conv state read and rewritten in place",
"bf16 x / weights / conv state / q,k,v out, fp32 a,b and gate/beta out",
"bf16 x / conv state / q,k,v out, bf16 or f32 weights, fp32 a,b and gate/beta out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvPrep), NOTUNE,
nullptr, nullptr, r4d_rad_gdn_conv_prep },
@@ -7282,7 +7295,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"gdn decode conv: rolling speculative window over the conv state cache, writes q/k/v "
"[UNVALIDATED: DPP row_xmask rewrite never correctness-gated]",
"conv width 4, head_k/head_v 128, state cache width-1 + num_spec, read at accepted offset",
"bf16 x / weights / conv state / q,k,v out",
"bf16 x / conv state / q,k,v out, bf16 or f32 weights",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvUpdate), NOTUNE,
nullptr, nullptr, r4d_rad_gdn_conv_update },
@@ -7311,7 +7324,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"workgroup convolves its key head's q and k and its value head's v into LDS, and the last "
"workgroup of a key head to arrive rewrites that head's conv state",
"head_k/head_v 128, conv width 4, a sequence's window at most 8 tokens, the fused row norm",
"bf16 x / conv weights / conv state / a,b / out; the state cache is f32 or f16. "
"bf16 x / conv state / a,b / out, bf16 or f32 conv weights; the state cache is f32 or f16. "
"Byte-identical to gdn_conv_update followed by gdn_recurrent_update",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGdnConvRecurrentUpdate), NOTUNE,
@@ -8779,7 +8792,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"exactly 2 ranks; n a multiple of 8 and x unpitched, because x is the message and a block pushes "
"its rows as 16B words; group 128; a block owns whole ROWS, so the block count is clamped to M; "
"either wire, chosen by `wire` -- the rotated 6-bit payload additionally needs n to be a "
"multiple of 512, so that a chunk never straddles a row; residual and out_bf16 may be null",
"multiple of 64, so that a group never straddles a row (a row's last 512-element chunk may be partial); residual and out_bf16 may be null",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; codes "
"taken over the BF16-ROUNDED norm output, and the reduced sum rounded to bf16 exactly as the "
"standalone all-reduce of the SAME wire stores it -- byte-identical to the pair it replaces",
@@ -8796,7 +8809,7 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
"back",
"exactly 2 ranks; n a multiple of 128 (a rotation block cannot straddle a row) and x unpitched; "
"group 128; a block owns whole ROWS, so the block count is clamped to M; either wire, chosen by "
"`wire` -- the rotated 6-bit payload additionally needs n to be a multiple of 512; residual and "
"`wire` -- the rotated 6-bit payload pads a row's partial last 512-element chunk; residual and "
"out_bf16 may be null",
"bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out of the "
"UNROTATED norm output; x and the residual are ar_rmsnorm_quant_fp8's bytes, and the codes "
@@ -8809,8 +8822,9 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
{ "ar_rmsnorm_post_quant_fp8", "ar_rmsnorm_post_quant_fp8", "quant",
"the two-rank all-reduce, a post-norm of the reduced sum, the residual add, RMS norm and "
"block-scaled fp8 quantisation in one kernel: a sandwich-norm junction (Gemma 3)",
"exactly 2 ranks, the exact wire; n a multiple of 8 and x unpitched; group 128; a block owns whole "
"rows; the residual is required",
"exactly 2 ranks, either wire chosen by `wire` (the rotated 6-bit payload needs n a multiple of 64; "
"a row's last 512-element chunk may be partial); n a multiple of 8 and x unpitched; group 128; a "
"block owns whole rows; the residual is required",
"bf16 in, E4M3 out with an f32 scale per (row, 128 columns); x receives the reduced sum",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cArRmsNormQuantFp8), ROW(tAr), nullptr,
+388 -12
View File
@@ -142,6 +142,7 @@ struct Plugin {
void (*pin_gather)(int) = nullptr;
void (*pin_ddec)(int) = nullptr;
void (*pin_hc)(int) = nullptr;
void (*pin_hc_dec)(int) = nullptr;
void (*pin_qsel)(int) = nullptr;
void (*pin_mla)(int) = nullptr;
void (*mla_stats)(unsigned long long*) = nullptr;
@@ -212,6 +213,7 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "r4d_moe_gather_pin_form", &pl->pin_gather);
okall &= sym(pl->h, "r4d_moe_gemm_pin_down_dec", &pl->pin_ddec);
okall &= sym(pl->h, "r4d_hc_read_pin_prefill", &pl->pin_hc);
okall &= sym(pl->h, "r4d_hc_read_pin_decode", &pl->pin_hc_dec);
okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel);
okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla);
okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats);
@@ -4146,9 +4148,10 @@ static int64_t i8_code_misses(const uint16_t* x, int64_t x_ld, const int8_t* q,
*
* The key heads' conv state must have moved, so the check is sensitive. The anchor form runs in a
* child process, as in gdn_recurrent_anchor. `i8` runs both at int8 codes and also holds the pair's
* codes to quant_act_i8g over its `o`. */
* codes to quant_act_i8g over its `o`. `f32w` hands the fold the conv weight in f32, as a GGUF
* stores it, and leaves the pair's in bf16: the values are bf16's, so the bytes must not change. */
static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form,
bool i8 = false) {
bool i8 = false, bool f32w = false) {
const RadKernelInfo* rf = find(pl, "gdn_conv_recurrent_update_k128_v128_bf16");
const RadKernelInfo* rc = find(pl, "gdn_conv_update_w4_h128_bf16");
const RadKernelInfo* rr = find(pl, "gdn_recurrent_update_k128_v128_bf16_fp32state");
@@ -4175,7 +4178,8 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
const std::vector<uint16_t> hw = bf((size_t)(conv_dim * W), 0.5f);
const std::vector<uint16_t> hcs = bf((size_t)(CSLOTS * conv_dim * SL), 1.0f);
std::vector<float> hst((size_t)(SSLOTS * H * V * K)), halog((size_t)H), hdtb((size_t)H),
hnw((size_t)V);
hnw((size_t)V), hwf(hw.size());
for (size_t i = 0; i < hw.size(); ++i) hwf[i] = h_bf16(hw[i]);
for (auto& e : hst) e = 0.1f * rnd();
for (int64_t h = 0; h < H; ++h) { halog[(size_t)h] = -2.0f + 0.25f * (float)h;
hdtb[(size_t)h] = -1.0f + 0.5f * (float)h; }
@@ -4196,6 +4200,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
void* d_in = dev(nullptr, in_b);
void* d_ab = dev(nullptr, (size_t)(Td * 2 * H) * 2);
void* d_w = dev(hw.data(), hw.size() * 2);
void* d_wf = dev(hwf.data(), hwf.size() * 4);
void* d_alog = dev(halog.data(), halog.size() * 4);
void* d_dtb = dev(hdtb.data(), hdtb.size() * 4);
void* d_nw = dev(hnw.data(), hnw.size() * 4);
@@ -4224,6 +4229,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
const RadTensor ta = view(d_ab, RAD_BF16, Td, H, 2 * H, 0);
const RadTensor tb = view(d_ab, RAD_BF16, Td, H, 2 * H, H);
const RadTensor tw = T(d_w, RAD_BF16, { conv_dim, W });
const RadTensor tfw = f32w ? T(d_wf, RAD_F32, { conv_dim, W }) : tw;
const RadTensor tal = T(d_alog, RAD_F32, { H }), tdt = T(d_dtb, RAD_F32, { H });
const RadTensor tnw = T(d_nw, RAD_F32, { V });
const RadTensor tci = T(d_cidx, RAD_I32, { N }), tsi = T(d_sidx, RAD_I32, { N, COLS });
@@ -4269,7 +4275,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
e = run(rr, { tq, tk, tv, ta, tb, tal, tdt, st(0), tsi, tna, tcu, tz, tnw, to(0),
toq(0), tos(0) }, pr);
if (e != RAD_OK) { why = "pair rc=" + std::to_string(e); break; }
e = run(rf, { tx, tw, none, cs(1), tci, ta, tb, tal, tdt, st(1), tsi, tna, tcu, tz, tnw,
e = run(rf, { tx, tfw, none, cs(1), tci, ta, tb, tal, tdt, st(1), tsi, tna, tcu, tz, tnw,
to(1), toq(1), tos(1) }, pf);
if (e != RAD_OK) { why = "fold rc=" + std::to_string(e); break; }
@@ -4316,6 +4322,8 @@ static void gdn_conv_fold(const Plugin& pl) {
const char* row = "gdn_conv_recurrent_update_k128_v128_bf16";
const char* nmp = "gdn_conv_recurrent_update is byte-identical to the pair, per_candidate";
const char* nma = "gdn_conv_recurrent_update is byte-identical to the pair, anchor";
const char* nmf = "gdn_conv_recurrent_update over an f32 conv weight is byte-identical to the "
"pair over its bf16 twin, per_candidate";
if (sel(row)) {
gdn_conv_fold_run(pl, nmp, "per_candidate");
gdn_conv_fold_run(pl, "gdn_conv_recurrent_update is byte-identical to the pair at int8 "
@@ -4323,6 +4331,174 @@ static void gdn_conv_fold(const Plugin& pl) {
"per_candidate", true);
}
if (sel(row) || sel(nma)) gdn_conv_fold_run(pl, nma, "anchor");
if (sel(row) || sel(nmf)) gdn_conv_fold_run(pl, nmf, "per_candidate", false, true);
}
/* gdn_conv_prep and gdn_conv_update over an f32 weight, as a GGUF stores ssm_conv1d, against the
* same weight in bf16.
*
* The weight's values are bf16's, so both forms widen to the same taps and every byte a row writes
* must match: q, k and v, g and beta at prefill, and the conv state. Both runs start from identical
* copies of the cache and from outputs poisoned with 0xFF, so an element the f32 instance never
* writes is caught even where the bf16 one misses it as well. Prefill has two sequences seeded
* from their cached history, one over two chunks, and a one-token sequence without; decode has
* uneven windows and read offsets, sequence 1 at slot 0. The cache must have moved, and an f16
* weight is refused. */
static void gdn_conv_f32_weight(const Plugin& pl) {
const struct { const char* row; const char* nm; bool prep; } forms[] = {
{ "gdn_conv_prep_w4_h128_bf16",
"gdn_conv_prep over an f32 weight is byte-identical to its bf16 twin", true },
{ "gdn_conv_update_w4_h128_bf16",
"gdn_conv_update over an f32 weight is byte-identical to its bf16 twin", false },
};
for (const auto& f : forms) {
if (!sel(f.row) && !sel(f.nm)) continue;
const RadKernelInfo* r = find(pl, f.row);
if (!r) { ok(f.nm, false, "row absent"); continue; }
const int64_t K = 128, V = 128, H = 4, Hg = 2, N = 3, W = 4, MQ = 4, CSLOTS = 3;
const int64_t xdim = 2 * Hg * K + H * V;
/* Prefill reads W - 1 taps of history from a W-deep slot; decode rolls a W - 2 + MQ one. */
const int64_t SL = f.prep ? W : W - 2 + MQ;
const int32_t plen[N] = { 70, 1, 57 }, dlen[N] = { 4, 1, 3 };
const int32_t slot[N] = { 2, 0, 1 }, nacc[N] = { 2, 1, 3 };
const uint8_t init[N] = { 1, 0, 1 };
int64_t Tn = 0;
std::vector<int32_t> cu(1, 0);
for (int64_t n = 0; n < N; ++n) {
Tn += f.prep ? plen[n] : dlen[n];
cu.push_back((int32_t)Tn);
}
uint32_t seed = 0x2f37c0d5u;
auto rnd = [&seed]() {
seed = st_mix32(seed + 0x9e3779b9u);
return (float)(seed & 0xFFFFu) * (1.0f / 32768.0f) - 1.0f;
};
auto bf = [&](size_t n, float s) {
std::vector<uint16_t> v(n);
for (auto& e : v) e = h_to_bf16(s * rnd());
return v;
};
const std::vector<uint16_t> hw = bf((size_t)(xdim * W), 0.5f), hb = bf((size_t)xdim, 0.25f);
const std::vector<uint16_t> hx = bf((size_t)(Tn * xdim), 1.0f);
const std::vector<uint16_t> hab = bf((size_t)(Tn * 2 * H), 1.0f);
const std::vector<uint16_t> hcs = bf((size_t)(CSLOTS * xdim * SL), 1.0f);
std::vector<float> hwf(hw.size()), halog((size_t)H), hdtb((size_t)H);
for (size_t i = 0; i < hw.size(); ++i) hwf[i] = h_bf16(hw[i]);
for (int64_t h = 0; h < H; ++h) { halog[(size_t)h] = -2.0f + 0.25f * (float)h;
hdtb[(size_t)h] = -1.0f + 0.5f * (float)h; }
auto dev = [](const void* h, size_t bytes) {
void* d = dalloc(bytes);
if (d && h) st_memcpy(d, h, bytes, hipMemcpyHostToDevice);
return d;
};
const size_t cs_b = hcs.size() * 2, qk_b = (size_t)(Tn * Hg * K) * 2,
v_b = (size_t)(Tn * H * V) * 2, g_b = (size_t)(Tn * H) * 4;
void* d_x = dev(hx.data(), hx.size() * 2);
void* d_ab = dev(hab.data(), hab.size() * 2);
void* d_b = dev(hb.data(), hb.size() * 2);
void* d_w[2] = { dev(hw.data(), hw.size() * 2), dev(hwf.data(), hwf.size() * 4) };
void* d_alog = dev(halog.data(), halog.size() * 4);
void* d_dtb = dev(hdtb.data(), hdtb.size() * 4);
void* d_slot = dev(slot, sizeof(slot));
void* d_nacc = dev(nacc, sizeof(nacc));
void* d_init = dev(init, sizeof(init));
void* d_cu = dev(cu.data(), cu.size() * 4);
void* d_cs[2]; void* d_q[2]; void* d_k[2]; void* d_v[2]; void* d_g[2]; void* d_beta[2];
for (int i = 0; i < 2; ++i) {
d_cs[i] = dev(hcs.data(), cs_b);
d_q[i] = dev(nullptr, qk_b); d_k[i] = dev(nullptr, qk_b); d_v[i] = dev(nullptr, v_b);
d_g[i] = dev(nullptr, g_b); d_beta[i] = dev(nullptr, g_b);
}
if (!d_x || !d_cu || !d_cs[1] || !d_beta[1]) { ok(f.nm, false, "hipMalloc"); continue; }
for (int i = 0; i < 2; ++i) {
st_memset(d_q[i], 0xFF, qk_b); st_memset(d_k[i], 0xFF, qk_b);
st_memset(d_v[i], 0xFF, v_b); st_memset(d_g[i], 0xFF, g_b);
st_memset(d_beta[i], 0xFF, g_b);
}
/* a and b_gate are column views of one [Tn, 2H] row, as the block lays them out. */
auto view = [](void* base, int64_t rows, int64_t cols, int64_t pitch, int64_t col0) {
RadTensor t = T((char*)base + (size_t)col0 * 2, RAD_BF16, { rows, cols });
t.stride[0] = pitch;
return t;
};
auto ops = [&](int i, uint32_t wdt) {
const RadTensor tx = T(d_x, RAD_BF16, { Tn, xdim }), tb = T(d_b, RAD_BF16, { xdim });
const RadTensor tw = T(d_w[i], wdt, { xdim, W });
const RadTensor tcs = T(d_cs[i], RAD_BF16, { CSLOTS, xdim, SL });
const RadTensor tcu = T(d_cu, RAD_I32, { N + 1 }), tsl = T(d_slot, RAD_I32, { N });
const RadTensor tq = T(d_q[i], RAD_BF16, { Tn, Hg, K }),
tk = T(d_k[i], RAD_BF16, { Tn, Hg, K }),
tv = T(d_v[i], RAD_BF16, { Tn, H, V });
if (!f.prep)
return std::vector<RadTensor>{ tx, tw, tb, tcs, tsl, T(d_nacc, RAD_I32, { N }), tcu,
tq, tk, tv };
return std::vector<RadTensor>{
tx, tw, tb, T(d_alog, RAD_F32, { H }), T(d_dtb, RAD_F32, { H }), tcs, tcu,
view(d_ab, Tn, H, 2 * H, 0), view(d_ab, Tn, H, 2 * H, H), tsl,
T(d_init, RAD_U8, { N }), tq, tk, tv, T(d_g[i], RAD_F32, { Tn, H }),
T(d_beta[i], RAD_F32, { Tn, H }) };
};
std::vector<RadParam> ps = f.prep
? std::vector<RadParam>{ PI("M", Tn), PI("head_k", K), PI("head_v", V),
PI("chunk", 64), PI("conv_width", W) }
: std::vector<RadParam>{ PI("q_len", MQ), PI("head_k", K), PI("head_v", V),
PI("conv_width", W) };
auto run = [&](std::vector<RadTensor> ts) {
RadArgs a; std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
const int rc_ = r->launch(&a, (RadStream) nullptr);
return rc_ != RAD_OK ? rc_ : (st_stream_sync(nullptr) != hipSuccess ? -1000 : RAD_OK);
};
auto fetch = [](void* d, size_t b) {
std::vector<uint8_t> h(b);
st_memcpy(h.data(), d, b, hipMemcpyDeviceToHost);
return h;
};
std::string why;
for (int i = 0; i < 2 && why.empty(); ++i) {
const int e = run(ops(i, i ? RAD_F32 : RAD_BF16));
if (e != RAD_OK) why = std::string(i ? "f32" : "bf16") + " rc=" + std::to_string(e);
}
struct Out { const char* what; void* a; void* b; size_t n; size_t es; };
std::vector<Out> outs = { { "q", d_q[0], d_q[1], qk_b, 2 },
{ "k", d_k[0], d_k[1], qk_b, 2 },
{ "v", d_v[0], d_v[1], v_b, 2 },
{ "conv_state", d_cs[0], d_cs[1], cs_b, 2 } };
if (f.prep) {
outs.push_back({ "g", d_g[0], d_g[1], g_b, 4 });
outs.push_back({ "beta", d_beta[0], d_beta[1], g_b, 4 });
}
for (const Out& o : outs) {
if (!why.empty()) break;
const std::vector<uint8_t> A = fetch(o.a, o.n), B = fetch(o.b, o.n);
size_t diff = 0, poisoned = 0;
for (size_t j = 0; j < o.n; ++j) diff += A[j] != B[j];
for (size_t j = 0; j < o.n; j += o.es) {
size_t ff = 0;
for (size_t e = 0; e < o.es; ++e) ff += B[j + e] == 0xFF;
poisoned += ff == o.es;
}
if (diff)
why = std::string(o.what) + " differs in " + std::to_string(diff) + " of " +
std::to_string(o.n) + " bytes";
else if (poisoned)
why = std::string(o.what) + ": " + std::to_string(poisoned) + " elements unwritten";
}
if (why.empty() && fetch(d_cs[1], cs_b) == std::vector<uint8_t>(
(const uint8_t*)hcs.data(), (const uint8_t*)hcs.data() + cs_b))
why = "the conv state never moved";
if (why.empty()) {
const int e = run(ops(1, RAD_F16));
if (e != RAD_E_DTYPE) why = "an f16 weight gave rc=" + std::to_string(e);
}
ok(f.nm, why.empty(), why);
}
}
/* The gated norm's gate as a column slice, which one pitch cannot describe.
@@ -17914,6 +18090,129 @@ static void hc_read_i8(const Plugin& pl, int64_t M, bool real_stream, int form)
: "the int8 run changed" + bad);
}
/* The gated residual's read at its decode kernels, byte for byte: the launcher's rule (kernels A and
* B as one grid at one to seven rows, the tiled up-mix pipelined from eight) against the kernels it
* replaced, pinned through r4d_hc_read_pin_decode(1). E4M3 or int8 codes, on a real stream (the
* one-grid form keys its counters on it). The two forms must dispatch different kernels, so a pin
* that is ignored cannot pass by comparing a form with itself. */
static void hc_decode_forms(const Plugin& pl, int64_t M, bool i8) {
const std::string nm = fmt("hc_read_e4m3 decode kernels at M=%lld, %s codes: the rule "
"byte-identical to the previous kernels", (long long)M,
i8 ? "int8" : "E4M3");
const RadKernelInfo* r = find(pl, "hc_read_e4m3");
if (!r) { skip(nm.c_str(), "row absent"); return; }
if (!pl.pin_hc_dec || !pl.record) { skip(nm.c_str(), "no r4d_hc_read_pin_decode"); return; }
const int64_t n = 2560, hc = 4, lr = 320, HN = hc * n, grp = 128, nkb = n / grp;
const int64_t dld = r4d_hc8::row_bytes(HN, r4d_hc8::down_group(HN));
const int64_t uld = r4d_hc8::row_bytes(lr, r4d_hc8::up_group(lr));
uint64_t rs = 0xD1B54A32D192ED03ull ^ (uint64_t)M;
auto rnd = [&]() { rs ^= rs << 13; rs ^= rs >> 7; rs ^= rs << 17; return rs; };
std::vector<uint16_t> hh((size_t)(M * HN));
for (auto& v : hh) v = h_to_bf16((float)((int)(rnd() % 2001) - 1000) / 400.0f);
std::vector<float> wg((size_t)HN);
for (auto& v : wg) v = (float)((int)(rnd() % 201) - 100) / 1000.0f;
auto plane = [&](int64_t rows, int64_t K, int64_t G, int64_t ld) {
std::vector<uint8_t> b((size_t)(rows * ld), 0);
for (int64_t r0 = 0; r0 < rows; ++r0) {
uint8_t* row = b.data() + r0 * ld;
for (int64_t k = 0; k < K; ++k) row[k] = (uint8_t)(8 + rnd() % 111) | ((rnd() & 1) ? 0x80u : 0u);
float* sc = (float*)(row + K);
for (int64_t g = 0; g < K / G; ++g) sc[g] = 0.002f + 0.004f * (float)(rnd() % 1000) / 1000.0f;
}
return b;
};
std::vector<uint8_t> down = plane(lr, HN, r4d_hc8::down_group(HN), dld);
std::vector<uint8_t> up = plane(HN, lr, r4d_hc8::up_group(lr), uld);
std::vector<uint16_t> injw((size_t)(hc * HN));
for (auto& v : injw) v = h_to_bf16((float)((int)(rnd() % 201) - 100) / 50000.0f);
const size_t xb = (size_t)(M * n * 2), ib = (size_t)(M * hc * 2), qb = (size_t)(M * n),
sb = (size_t)(M * nkb * 4);
void* d_h = dalloc(hh.size() * 2);
void* d_w = dalloc(wg.size() * 4);
void* d_dn = dalloc(down.size());
void* d_up = dalloc(up.size());
void* d_iw = dalloc(injw.size() * 2);
void* d_x = dalloc(xb);
void* d_inj = dalloc(ib);
void* d_q = dalloc(qb);
void* d_qs = dalloc(sb);
void* d_rq = dalloc(qb);
void* d_rs = dalloc(sb);
if (!d_h || !d_w || !d_dn || !d_up || !d_iw || !d_x || !d_inj || !d_q || !d_qs || !d_rq || !d_rs) {
ok(nm.c_str(), false, "hipMalloc failed");
return;
}
st_memcpy(d_h, hh.data(), hh.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_w, wg.data(), wg.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_dn, down.data(), down.size(), hipMemcpyHostToDevice);
st_memcpy(d_up, up.data(), up.size(), hipMemcpyHostToDevice);
st_memcpy(d_iw, injw.data(), injw.size() * 2, hipMemcpyHostToDevice);
hipStream_t hs = nullptr;
if (hipStreamCreate(&hs) != hipSuccess) { ok(nm.c_str(), false, "stream"); return; }
const uint32_t qdt = i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
std::vector<RadTensor> ts = {
T(d_h, RAD_BF16, { M, HN }), T(d_w, RAD_F32, { HN }),
T(d_dn, RAD_F8E4M3, { lr, HN }), T(d_up, RAD_F8E4M3, { HN, lr }),
T(d_iw, RAD_BF16, { hc, HN }), T(d_x, RAD_BF16, { M, n }),
T(d_inj, RAD_BF16, { M, hc }), T(d_q, qdt, { M, n }),
T(d_qs, RAD_F32, { M, nkb }), T(d_rq, RAD_F8E4M3, { M, n }),
T(d_rs, RAD_F32, { M, nkb }),
};
std::vector<RadParam> ps = {
PI("M", M), PI("n", n), PI("hc", hc), PI("lowrank", lr), PF("eps", 1e-6),
PS("dtype", "bf16"), PF("wadd", 1.0), PI("inject", 1), PI("group", grp),
PI("rotate", 1), PS("mix", "e4m3"),
};
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();
if (r->scratch) {
const int64_t need = r->scratch(&a);
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
}
struct Out { std::vector<uint8_t> x, inj, q, qs, rq, rs; std::vector<const void*> fns; };
Out out[2];
for (int form = 0; form < 2; ++form) {
pl.pin_hc_dec(form);
st_memset(d_x, 0, xb); st_memset(d_q, 0, qb); st_memset(d_qs, 0, sb);
st_memset(d_rq, 0, qb); st_memset(d_rs, 0, sb); st_memset(d_inj, 0, ib);
const void* fns[16] = {};
pl.record(fns, 16);
const int rc = r->launch(&a, (RadStream)hs);
const int nd = pl.record(nullptr, 0);
if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) {
ok(nm.c_str(), false, fmt("%s rc=%d", form ? "the previous kernels" : "the rule", rc));
pl.pin_hc_dec(0);
(void)hipStreamDestroy(hs);
return;
}
out[form].fns.assign(fns, fns + (nd < 16 ? nd : 16));
auto get = [&](std::vector<uint8_t>& v, void* d, size_t b) {
v.resize(b); st_memcpy(v.data(), d, b, hipMemcpyDeviceToHost);
};
get(out[form].x, d_x, xb); get(out[form].inj, d_inj, ib); get(out[form].q, d_q, qb);
get(out[form].qs, d_qs, sb); get(out[form].rq, d_rq, qb); get(out[form].rs, d_rs, sb);
}
pl.pin_hc_dec(0);
(void)hipStreamDestroy(hs);
std::string bad;
if (out[0].x != out[1].x) bad += " x";
if (out[0].inj != out[1].inj) bad += " inj";
if (out[0].q != out[1].q) bad += " q";
if (out[0].qs != out[1].qs) bad += " qs";
if (out[0].rq != out[1].rq) bad += " rq";
if (out[0].rs != out[1].rs) bad += " rs";
int64_t nz = 0;
for (uint8_t v : out[0].q) nz += v != 0;
const bool distinct = out[0].fns != out[1].fns;
ok(nm.c_str(), bad.empty() && nz > (int64_t)qb / 2 && distinct,
!bad.empty() ? "differs in" + bad
: !distinct ? std::string("both forms dispatched the same kernels")
: fmt("%lld of %zu codes non-zero; %zu and %zu launches", (long long)nz, qb,
out[0].fns.size(), out[1].fns.size()));
}
/* The gated residual's read at a prefill chunk: hc_read_e4m3 at Qwen3.8-Flash-Next's shape (n
* 2560, four streams, lowrank 320, inject gains, the fp8 twin and its rotated twin). Several
* launches at prefill, so also a harness for libr4d/isa/trace.sh. Random codes, small positive
@@ -18024,11 +18323,20 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
static const char* const kForm[] = { "the launcher's rule", "the decode tiles' kernels",
"the wide kernels", "the PF2 kernels" };
std::vector<Out> outs;
std::vector<int> ran; /* the form each of `outs` came from */
for (int form = f_lo; form <= f_hi; ++form) {
if (pl.pin_hc) pl.pin_hc(form);
st_memset(d_x, 0, xb); st_memset(d_inj, 0, ib); st_memset(d_q, 0, qb);
st_memset(d_qs, 0, sb); st_memset(d_rq, 0, qb); st_memset(d_rs, 0, sb);
const int rc = r->launch(&a, rst);
/* A pinned form refusing the shape is not a failure: the wide kernels serve only the wide
* row tile, so from 8 rows up to it --perfhc times the decode tiles' kernels alone. The
* first form (the decode tiles') must serve. */
if (rc == RAD_E_SHAPE && pl.pin_hc && form > f_lo) {
skip(fmt("%s prefill form '%s' at M=%lld", rn, kForm[form], (long long)M).c_str(),
"not served at this row count");
continue;
}
if (rc != RAD_OK || st_stream_sync(hs) != hipSuccess) {
ok(fmt("%s prefill form '%s' at M=%lld is served", rn, kForm[form],
(long long)M).c_str(), false, fmt("rc=%d", rc));
@@ -18043,6 +18351,7 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
get(o.x, d_x, xb); get(o.inj, d_inj, ib); get(o.q, d_q, qb);
get(o.qs, d_qs, sb); get(o.rq, d_rq, qb); get(o.rs, d_rs, sb);
outs.push_back(std::move(o));
ran.push_back(form);
}
/* Form f against the decode tiles' kernels, outs[0]. */
auto same = [&](size_t f, const char* what) {
@@ -18061,11 +18370,10 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
bad.empty() && nz > qb / 2, bad.empty() ? fmt("%zu of %zu codes non-zero", nz, qb)
: "differs in" + bad);
};
for (size_t f = 1; f < outs.size(); ++f) same(f, kForm[f_lo + (int)f]);
for (size_t f = 1; f < outs.size(); ++f) same(f, kForm[ran[f]]);
if (timed) {
for (int form = f_lo; form <= f_hi; ++form) {
if (pl.pin_hc) pl.pin_hc(form);
auto time_now = [&](const char* label) {
hipEvent_t w0, w1;
st_ev_create(&w0); st_ev_create(&w1);
st_ev_record(w0, hs);
@@ -18081,8 +18389,21 @@ static void hc_prefill(const Plugin& pl, int64_t M, int iters, bool timed, bool
const double flop = 2.0 * (double)M * (double)HN * (double)(2 * lr + hc);
std::printf("%s at M=%lld (n %lld, hc %lld, lowrank %lld, inject, fp8 twin + "
"rotated), %s: %.1f us a call, %.1f TFLOP/s\n", rn, (long long)M,
(long long)n, (long long)hc, (long long)lr, kForm[form], us,
(long long)n, (long long)hc, (long long)lr, label, us,
flop / (us * 1e6));
};
for (const int form : ran) {
if (pl.pin_hc) pl.pin_hc(form);
time_now(kForm[form]);
}
/* The decode kernels against the ones they replaced (r4d_hc_read_pin_decode), under the
* launcher's prefill rule. */
if (pl.pin_hc_dec && f8) {
if (pl.pin_hc) pl.pin_hc(0);
pl.pin_hc_dec(1);
time_now("the previous decode kernels");
pl.pin_hc_dec(0);
time_now("the launcher's rule");
}
}
if (pl.pin_hc) pl.pin_hc(0);
@@ -20254,6 +20575,27 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter
};
perf_row(pl, "gemm_fp8a8_nt_m16", ts, ps, d_w, wbytes, copies, bytes, iters);
perf_row(pl, "gemm_fp8a8_tiled", ts, ps, d_w, wbytes, copies, bytes, iters);
/* The gated row, at a gate_up shape: N is the gate and up rows together, as the engine
* fuses them, and the output is their quantised SiLU product, N / 2 wide. It refuses a
* shape the split rule would split. */
if (N % 256 == 0 && K % 256 == 0 && M <= 64) {
const int64_t nout = N / 2, gkb = nout / 128;
void* d_gq = dalloc((size_t)M * nout);
void* d_gs = dalloc((size_t)M * gkb * 4);
void* d_gy = dalloc((size_t)M * nout * 2);
if (!d_gq || !d_gs || !d_gy) {
std::printf(" %-22s hipMalloc failed\n", "gemm_fp8a8_gated_nt_m16");
} else {
perf_row(pl, "gemm_fp8a8_gated_nt_m16",
{ T(d_q, RAD_F8E4M3, { M, K }), T(d_qs, RAD_F32, { M, sk }),
T(d_w, RAD_F8E4M3, { N, K }), T(d_s, RAD_BF16, { sn, sk }),
T(d_gq, RAD_F8E4M3, { M, nout }), T(d_gs, RAD_F32, { M, gkb }),
T(d_gy, RAD_BF16, { M, nout }) },
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
PS("dtype", "fp8a8"), PS("act", "silu") },
d_w, wbytes, copies, bytes, iters);
}
}
}
/* The lm head, a decode GEMM too. Its weight is [N][K + 2*nkb] E4M3 with each row's bf16
@@ -25142,6 +25484,23 @@ struct ArThread {
int64_t spitch = 0;
};
/* Whether every rank device a collective case is about to use can reach every other directly.
* The engine carries this fact (device.p2p, RAD_FACT_P2P) and selects around its absence; a card
* count is not enough. hipDeviceCanAccessPeer answers it without a kernel: on a box with the IOMMU
* off the peer path is absent, the enable call throws `enable_peer: invalid device ordinal`, and
* init returns RAD_E_DEVICE — a skip line, like the card-count gates, not a failure. */
static bool ar_peer_path_ok(const std::vector<int>& devs, int world) {
if (world < 2 || (int)devs.size() < world) return false;
for (int a = 0; a < world; ++a)
for (int b = 0; b < world; ++b) {
if (a == b) continue;
int can = 0;
if (hipDeviceCanAccessPeer(&can, devs[a], devs[b]) != hipSuccess) return false;
if (!can) return false;
}
return true;
}
static void ar_worker(ArThread* t) {
if (st_set_device(t->dev) != hipSuccess) { t->rc_init = RAD_E_DEVICE; return; }
std::vector<RadParam> ps = {
@@ -25179,6 +25538,7 @@ static void ar_two_rank(const Plugin& pl, const std::vector<int>& devs, const ch
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; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* 8192 fp32 elements: whole 16-byte pushes, small enough to exercise the handshake rather
* than the link. */
@@ -25290,6 +25650,7 @@ static void ar_two_rank_sweep(const Plugin& pl, const std::vector<int>& devs, co
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; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); 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();
@@ -25314,6 +25675,7 @@ static void ar_two_rank_late(const Plugin& pl, const std::vector<int>& devs, con
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; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
pl.pin_late_push(1);
ArSweep a{ row, 0, devs[0] }, b{ row, 1, devs[1] };
std::thread ta(ar_sweep_worker, &a), tb(ar_sweep_worker, &b);
@@ -25402,6 +25764,7 @@ static void gather_two_rank(const Plugin& pl, const std::vector<int>& devs, cons
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; }
if (!ar_peer_path_ok(devs, 2)) { skip(name, "no peer path between the cards (device.p2p)"); 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 };
@@ -25493,6 +25856,7 @@ static void ar_wide_rank(const Plugin& pl, const std::vector<int>& devs, const c
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
const int64_t numel = 8192;
const std::string w = std::to_string(world);
std::vector<ArThread> t;
@@ -25787,6 +26151,7 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector<int>& devs, cons
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
using Run = ArPatternRun;
/* The three-rank list walks the UNEVEN split (words % 3 of 0, 1 and 2); the four- and
* eight-rank rows cannot be given one -- cArTsExact4/cArTsExact8/cArTi8Ts4 constrain numel so
@@ -25869,6 +26234,7 @@ static void ar_wide_weighted(const Plugin& pl, const std::vector<int>& devs, con
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if ((int)devs.size() < W) { skip(name, "needs 8 gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, W)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* bf16: 72 elements are 9 words, 8 are one; 8256 is 1032 words, 4196352 is 524544. Without
* weights the words must divide by eight. */
const std::vector<ArPatternRun> uneven = {
@@ -26476,6 +26842,7 @@ static void ar_lane_forms(const Plugin& pl, const std::vector<int>& devs, const
const RadKernelInfo* row = find(pl, name);
if (!row) { ok(name, false, "row absent"); return; }
if ((int)devs.size() < 4) { skip(name, "needs 4 gfx1201 cards"); return; }
if (!ar_peer_path_ok(devs, 4)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
struct Run { bool coded; int pat; const char* dtype; std::vector<int64_t> sizes; int oop; };
/* 1024: one wave a shard; 1055744: 1031 waves, an odd split over the blocks; 524352: bf16
* outside the coded form; 46137344: the feed-forward reduce at an 8192-token chunk. */
@@ -26610,6 +26977,7 @@ static void ar_wide_ti8(const Plugin& pl, const std::vector<int>& devs, const ch
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* 32768 is under the 128 KiB floor and 65544 is not whole groups (at four ranks, not whole
* SHARD groups -- the 4-rank wire tiles numel by 128): both exact. The rest are
* lossy: 65536 sits ON the floor (2048 groups, % 3 = 2), then 2048 x 2048 / 2049 / 2050 rows
@@ -26980,6 +27348,7 @@ static void ar_hc_write_case(const Plugin& pl, const std::vector<int>& devs, con
skip(name, (std::string("needs ") + std::to_string(world) + " gfx1201 cards").c_str());
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
struct Shape { int64_t M, n, hc, top_k; const char* act; bool scratch; };
std::vector<Shape> shapes;
if (!want_gather) {
@@ -27279,6 +27648,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector<in
skip(name, world == 4 ? "needs 4 gfx1201 cards" : "needs 2 gfx1201 cards");
return;
}
if (!ar_peer_path_ok(devs, world)) { skip(name, "no peer path between the cards (device.p2p)"); return; }
/* Only the four-rank P2P row ends the engine's link hold; the host twin and the two-rank rows
* leave it alone. */
const bool releases = world == 4 && !nm_ends_with(name, "_host");
@@ -29518,6 +29888,7 @@ static void device_phase(const Plugin& pl) {
}
gdn_recurrent_anchor(pl);
gdn_conv_fold(pl);
gdn_conv_f32_weight(pl);
if (sel("gdn_gated_rmsnorm_h128_bf16")) {
const RadKernelInfo* r = find(pl, "gdn_gated_rmsnorm_h128_bf16");
if (!r) ok("gdn_gated_rmsnorm_h128_bf16", false, "row absent");
@@ -30734,6 +31105,10 @@ static void device_phase(const Plugin& pl) {
for (int form : { 1, 2 }) hc_read_i8(pl, m, true, form);
for (int64_t m : { 700, 2048 }) hc_read_i8(pl, m, true, 3);
}
/* The decode kernels against the ones they replaced: each one-grid instantiation (1 to 7
* rows) and the tiled up-mix at both of its row tiles. */
for (int64_t m : { 1, 2, 3, 4, 5, 6, 7, 8, 16, 32, 33, 64 })
for (bool i8 : { false, true }) hc_decode_forms(pl, m, i8);
}
if (sel("hc_read_bf16")) {
if (!g_case) std::printf("\nthe gated residual's read over bf16 mixing matrices at the "
@@ -31179,8 +31554,8 @@ static void usage(void) {
" given byte offsets in a safetensors file, compared with a host\n"
" reference over the same bytes. An offset is 8 + <header length, a\n"
" u64 at byte 0> + the tensor's own data_offsets[0].\n"
" --perf N K M [iters]: time the fp8 decode GEMMs at one shape and print the\n"
" weight bandwidth each reaches.\n"
" --perf N K M [iters]: time the fp8 decode GEMMs at one shape (the gated row with\n"
" N a gate_up's width) and print the weight bandwidth each reaches.\n"
" --perfwpa N K M [iters] [pb1]: the int5 and int4 x int8 tiled GEMMs (gemm_w5a8i8_tiled,\n"
" gemm_w4a8i8_tiled), warmed, min / median time and a hash of the output.\n"
" --perfmxd N K M [iters]: the dense MXFP4 GEMM rows (gemv, decode, skinny, tiled) at\n"
@@ -31197,8 +31572,9 @@ static void usage(void) {
" rows -- at one shape, each with its TFLOP/s.\n"
" --perfw2 N K M [iters]: the int2 DFlash2 draft head at every variant it has.\n"
" --perfhc M [iters]: hc_read_e4m3 at Qwen3.8-Flash-Next's shape and M rows, every\n"
" prefill-tile form (PF2 from M=512) compared byte for byte and timed\n"
" as one op each;\n"
" prefill-tile form that serves M (the wide kernels at the wide tile,\n"
" PF2 from M=512) compared byte for byte and timed as one op each,\n"
" then the previous decode kernels against the launcher's rule;\n"
" run it under libr4d/isa/trace.sh for its launches.\n"
" --cold MIB: with a --perf mode, time cold: read MIB through the caches before\n"
" every timed launch (256 empties this card's L2 and last level) and\n"
+24 -2
View File
@@ -659,6 +659,10 @@ same path runs. Trivial means served as stored:
`fp4_e2m1*e8m0[1x32]`, byte for byte;
- GGUF `F32`, `F16` and `BF16`.
A GGUF `Q8_0`, `Q4_K` or `Q6_K` tensor is not trivial, because its blocks interleave what the planes
of §4.1 hold apart. `rad-convert` imports it without a recipe as those planes, bit for bit, and the
loader refuses it with that hint. Other GGUF block types are dequantised for a recipe or refused.
**A torch.save file beside the safetensors is read as data** (`core/format/torch_zip.h`), for a
model part that ships only that way (Fish Audio drama-3's `codec.pth`): its tensors join the
namespace under `<stem>.`. The zip's stored entries are mapped, and its pickle is read by a machine
@@ -697,7 +701,9 @@ A rule names an algorithm (`rtn`, `gptq`, `cast`); its options name the grid (`c
`group` or `block`, `scale`, a second level `scale2`, `zero`, `rule`) and the transform
(`transform=fwht128`) (§4.5). First match wins, so a protected expert's `cast` rule sits above the
rule every other expert takes. A quantiser that declines a weight (`rtn` declines a rank-1 tensor)
leaves it to the checkpoint's encoding, so a broad pattern need not exclude every norm.
leaves it to the checkpoint's encoding, so a broad pattern need not exclude every norm. A GGUF block
tensor is the exception: a rule that declines it is an error, since keeping its planes would hide
that the rule did not apply.
`--recipe FILE` names a file and `--quant 'PATTERN=QUANTISER:k=v,...'` adds rules ahead of it.
`$NAME` in an option is read from the environment.
@@ -1054,6 +1060,21 @@ token when it sits at `i * block_size`. This engine changes two things:
On a model with sliding-window attention and no linear state, a checkpoint snapshots the window
behind a prompt's tail instead, and chunks are not split at the interval.
**Exact resume.** A hit recomputes the tokens past where it resumes, and a kernel can round a row
differently at another chunk length (§17), so a hit is bit-identical to a cold run of the same
prompt only if it recomputes the cold run's own chunks. With `--prefix-resume exact` (the default)
a hit resumes only on the grid an idle server's cold prefill chunks on: the budget's chunk
(`--max-num-batched-tokens` rounded down to the quantum), or the interval where chunks split at it
and it is the smaller, times the span from the second interval on. Every snapshot the scheduler
writes is on that grid: interval checkpoints (the interval, when past the chunk, is rounded up to a
multiple of it), and the prompt's tail snapshot, which is taken where its last chunk starts rather
than at its last quantum boundary. That boundary is one the cold chunk already ends on, so the tail
snapshot costs no extra step; an exact repeat re-prefills the last chunk, an appended turn that
chunk and its own tokens, up to one chunk more than `--prefix-resume nearest` (the deepest snapshot
or block). A hit with no snapshot to resume from (full attention) steps back to the grid. The
property holds for a prefill alone in its steps; one sharing its steps with other work is cut
differently, as greedy text under batching already differs (§17).
Snapshots are large (at a 2048-token interval a 128K session on Qwen3.5-27B is 64 checkpoints,
about 9 GiB), so retention is budgeted. Retention keeps the session tip, which an appending agent
transcript resumes from, and any snapshot a lookup resumed from since the tip was written, which a
@@ -1642,7 +1663,8 @@ It does not give bit-exactness. The fp8 GEMM's split-K finisher sums in index or
repeats, but the split count is chosen from `M`, so a row computed at `M = 1` and at `M = 8` can
differ in the last bits. A speculative decode can therefore diverge from a non-speculative one on a
near-tie, and a request at a different batch position can take a different reduction order. Nothing
pins it (§19.7).
pins it (§19.7). A prefix hit is held to the cold run's chunks (§7.3, exact resume), so on an idle
server it repeats the cold run's output.
---
+13
View File
@@ -604,6 +604,19 @@ set_tests_properties(ops_doc PROPERTIES
TIMEOUT ${RAD_TEST_TIMEOUT}
ENVIRONMENT "ROCR_VISIBLE_DEVICES=99")
# docs/KERNELS.md is generated by rad-kbench and merged by hand; a partial merge leaves a
# library's "rows not reached" header from one run above a table from another (v1.13.0: 239
# against 243 rows). The counts must agree with each other and with the headline; cheap.
if(EXISTS ${CMAKE_SOURCE_DIR}/docs/KERNELS.md)
add_test(NAME kernel_report_check
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/kernel_report_check.sh
${CMAKE_SOURCE_DIR}/docs/KERNELS.md)
set_tests_properties(kernel_report_check PROPERTIES
LABELS "fast;unit"
SKIP_RETURN_CODE 77
TIMEOUT ${RAD_TEST_TIMEOUT})
endif()
# tools/rad-export. Its standard-library checks always run; the merge arithmetic runs where torch
# and safetensors import, and the PEFT comparison where peft and transformers do too.
find_program(RAD_PYTHON3 NAMES python3)
+28 -5
View File
@@ -8226,10 +8226,12 @@ TEST(gemma3_without_fused_junctions_every_linear_quantises_into_what_it_reads) {
CHECK(quant >= 2 * (int)m.layers.size());
}
/* Under a lossy --tp-wire the fused all-reduce junctions, which send the exact wire only, still
* serve the steps whose message goes out exact anyway: a decode step's few rows fold every
* junction's all-reduce in, while a prefill chunk above --tp-wire-min-kb keeps the lossy
* all-reduce, unfused. Both families: the MXFP4 trunk's fp8 junction and a w4a8 trunk's int8 one. */
/* Under a lossy --tp-wire a decode step's few rows, whose message goes out exact, fold every
* junction's all-reduce in. On the MXFP4 trunk a lossy step up to kAr6MaxRows (24) does too,
* through the fp8 junction's lossy twin (ar_rmsnorm_post_quant_fp8 at wire 6; TranslateGemma's
* 5376-wide row is whole 64-element groups, its last 512-element chunk padded); a taller one, like a
* prefill chunk, keeps the lossy all-reduce, unfused. A w4a8 trunk's int8 junction sends the exact
* wire only. Both families: the MXFP4 trunk's fp8 junction and a w4a8 trunk's int8 one. */
TEST(gemma3_under_a_lossy_wire_small_steps_keep_the_fused_junction) {
MetaKV mk = gemma3_meta();
const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP);
@@ -8244,7 +8246,7 @@ TEST(gemma3_under_a_lossy_wire_small_steps_keep_the_fused_junction) {
ctx.tp_wire_min_bytes = 128 * 1024;
REQUIRE_EQ(gemma3::declare(&b, mk.meta(), &ctx), RAD_OK);
const gemma3::Model& m = gemma3::g_model[rank];
if (is_mx) CHECK(m.fuse_mx && m.fuse_mx_ar);
if (is_mx) CHECK(m.fuse_mx && m.fuse_mx_ar && m.fuse_mx_ar6);
else CHECK(!m.fuse_mx && m.fuse && m.fuse_ar);
auto issued = [&](const RadCtx& c, std::initializer_list<const char*> names) {
int n = 0;
@@ -8263,6 +8265,27 @@ TEST(gemma3_under_a_lossy_wire_small_steps_keep_the_fused_junction) {
CHECK_EQ(fused_pre, 0);
/* Every junction the decode step fused is an all-reduce the prefill step issues alone. */
CHECK_EQ(issued(*v[1], { "all_reduce" }), issued(*v[0], { "all_reduce" }) + fused_dec);
/* 24 rows (24 x 5376 x 2 bytes, above the floor): the MXFP4 trunk fuses the same junctions
* through the lossy twin, other op instances than the decode step's; the int8 one cannot. */
const auto mid = kit(b, {}, { 24 });
const auto vm = run_passes(b, gemma3::step, { mid.get() }, rank, 2);
CHECK_PASSES(b, vm);
const int fused_mid = issued(*vm[0], { "ar_rmsnorm_quant_i8", "ar_rmsnorm_post_quant_fp8" });
if (is_mx) {
CHECK_EQ(fused_mid, fused_dec);
CHECK_EQ(issued(*vm[0], { "all_reduce" }), issued(*v[0], { "all_reduce" }));
std::vector<int> dec_ids;
for (const RecIssue& i : v[0]->issues)
if (const RecOp* o = b.op_of(i.op); o && o->op == "ar_rmsnorm_post_quant_fp8")
dec_ids.push_back((int)i.op);
int shared = 0;
for (const RecIssue& i : vm[0]->issues)
if (const RecOp* o = b.op_of(i.op); o && o->op == "ar_rmsnorm_post_quant_fp8")
shared += std::find(dec_ids.begin(), dec_ids.end(), (int)i.op) != dec_ids.end();
CHECK_EQ(shared, 0);
} else {
CHECK_EQ(fused_mid, 0);
}
}
}
+211 -54
View File
@@ -7,6 +7,7 @@
* back.
*/
#include "rad_test.h"
#include "gguf_writer.h"
#include "format/checkpoint.h"
#include "format/encoding.h"
#include "rad_plugin.h"
@@ -2054,60 +2055,9 @@ TEST(a_concat_declared_in_pieces_joins_every_piece_in_order) {
* shape everything else uses; the legacy and Q4_K/Q6_K block types decode by their definitions. */
namespace {
struct GKv {
std::string key;
uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings */
double num = 0;
std::vector<std::string> strs;
};
struct GTensor { std::string name; uint32_t type; std::vector<uint64_t> ne; std::vector<uint8_t> bytes; };
void put_bytes(std::string* b, const void* p, size_t n) { b->append((const char*)p, n); }
void put_str(std::string* b, const std::string& s) {
const uint64_t n = s.size();
put_bytes(b, &n, 8);
b->append(s);
}
/* A GGUF v3 file of `kvs` and `ts`, every tensor at a 32-byte aligned offset. */
void write_gguf(const std::string& path, const std::vector<GKv>& kvs, const std::vector<GTensor>& ts) {
std::string b = "GGUF";
const uint32_t ver = 3;
const uint64_t nt = ts.size(), nk = kvs.size();
put_bytes(&b, &ver, 4);
put_bytes(&b, &nt, 8);
put_bytes(&b, &nk, 8);
for (const GKv& kv : kvs) {
put_str(&b, kv.key);
put_bytes(&b, &kv.type, 4);
if (kv.type == 4) { const uint32_t v = (uint32_t)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 6) { const float v = (float)kv.num; put_bytes(&b, &v, 4); }
else if (kv.type == 8) put_str(&b, kv.strs.at(0));
else {
const uint32_t et = 8;
const uint64_t n = kv.strs.size();
put_bytes(&b, &et, 4);
put_bytes(&b, &n, 8);
for (const std::string& s : kv.strs) put_str(&b, s);
}
}
uint64_t off = 0;
for (const GTensor& t : ts) {
put_str(&b, t.name);
const uint32_t nd = (uint32_t)t.ne.size();
put_bytes(&b, &nd, 4);
for (uint64_t d : t.ne) put_bytes(&b, &d, 8);
put_bytes(&b, &t.type, 4);
put_bytes(&b, &off, 8);
off += (t.bytes.size() + 31) / 32 * 32;
}
while (b.size() % 32) b.push_back('\0');
for (const GTensor& t : ts) {
b.append((const char*)t.bytes.data(), t.bytes.size());
while (b.size() % 32) b.push_back('\0');
}
write_file(path, b);
}
using ggufw::GKv;
using ggufw::GTensor;
using ggufw::write_gguf;
uint16_t h16(float v) { return rad_f32_to_f16(v); }
@@ -2308,6 +2258,213 @@ TEST(a_gguf_tensor_is_row_major_and_its_legacy_blocks_decode_by_definition) {
}
}
namespace {
/* `rows` x `cols` blocks of Q4_K (type 12) or Q6_K (type 14) with arbitrary quants and scales and
* finite f16 super-scales: random bits there would make NaNs, which equal nothing. */
GTensor k_blocks(const char* name, uint32_t type, int64_t rows, int64_t cols, uint32_t seed) {
GTensor t{ name, type, { (uint64_t)cols, (uint64_t)rows }, {} };
uint32_t x = seed;
auto fill = [&](int n) {
for (int i = 0; i < n; ++i) {
x = x * 1664525u + 1013904223u;
t.bytes.push_back((uint8_t)(x >> 24));
}
};
auto push16 = [&](float v) {
const uint16_t h = h16(v);
t.bytes.push_back((uint8_t)h);
t.bytes.push_back((uint8_t)(h >> 8));
};
for (int64_t b = 0; b < rows * cols / 256; ++b) {
const float d = 0.0625f * (float)(1 + (b + seed) % 7);
if (type == 12) {
push16(d);
push16(d / 2);
fill(12 + 128);
} else {
fill(128 + 64 + 16);
push16(d);
}
}
return t;
}
/* Every plane of `w` through ckpt_plane_rows, and the weight those planes decode to. */
void read_planes(const CkptWeight& w, std::vector<std::vector<uint8_t>>* planes,
std::vector<float>* values) {
std::string why;
planes->assign((size_t)w.enc.n_planes, {});
const void* data[RAD_ENC_MAX_PLANES] = { nullptr };
for (int k = 0; k < w.enc.n_planes; ++k) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
(*planes)[(size_t)k].resize((size_t)(pr * rad_enc_row_bytes(w.enc.plane[k].dtype, pc)));
CHECK_EQ(ckpt_plane_rows(w, k, 0, pr, (*planes)[(size_t)k].data(), &why), (int)RAD_OK);
data[k] = (*planes)[(size_t)k].data();
}
EncodedView v;
enc_view(w.enc, w.rows, w.cols, data, &v);
values->assign((size_t)(w.rows * w.cols), 0.0f);
CHECK_EQ(enc_decode_rows(v, 0, w.rows, values->data(), &why), (int)RAD_OK);
}
/* The planes of `w` decode to exactly what the block definition gives (ckpt_rows_f32). */
void check_planes_decode_by_definition(const CkptWeight& w) {
std::vector<std::vector<uint8_t>> planes;
std::vector<float> got, want((size_t)(w.rows * w.cols));
std::string why;
read_planes(w, &planes, &got);
REQUIRE_EQ(ckpt_rows_f32(w, 0, w.rows, want.data(), &why), (int)RAD_OK);
int bad = 0, nonzero = 0;
for (size_t i = 0; i < want.size(); ++i) {
bad += !(got[i] == want[i]);
nonzero += want[i] != 0.0f;
}
if (bad) std::fprintf(stderr, " %d of %zu value(s) differ\n", bad, want.size());
CHECK_EQ(bad, 0);
CHECK(nonzero > (int)want.size() / 2);
}
} /* namespace */
TEST(a_gguf_q8_0_q4_k_or_q6_k_tensor_is_imported_as_its_planes) {
const std::string path = fresh_dir() + "/m.gguf";
std::vector<float> w8;
const GTensor q8 = legacy_blocks("t.q8_0", 8, &w8);
const GTensor g = k_blocks("g", 12, 2, 512, 1), u = k_blocks("u", 12, 3, 512, 2);
const GTensor s = k_blocks("s", 12, 2, 256, 3), k6 = k_blocks("k6", 14, 2, 256, 4);
const GTensor q5{ "t.q5_k", 13, { 256, 1 }, std::vector<uint8_t>(176, 0) };
write_gguf(path, llama_kvs(15), { q8, g, u, s, k6, q5 });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
Program prog;
prog.name_map.push_back(map("t.q8_0", RAD_MAP_COPY, { "t.q8_0" }));
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "g", "u" }));
prog.name_map.push_back(map("s", RAD_MAP_COPY, { "s" }));
prog.name_map.push_back(map("k6", RAD_MAP_COPY, { "k6" }));
prog.name_map.push_back(map("mix", RAD_MAP_CONCAT, { "s", "k6" }));
prog.name_map.push_back(map("across", RAD_MAP_CONCAT, { "g", "s" }, {}, 1));
prog.name_map.push_back(map("t.q5_k", RAD_MAP_COPY, { "t.q5_k" }));
std::string why;
/* Q8_0: the codes plane is each block's quants and the scale plane its d, byte for byte. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q8_0", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
CHECK(has(w.why, "GGUF"));
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 2);
std::vector<std::vector<uint8_t>> planes;
std::vector<float> f;
read_planes(w, &planes, &f);
REQUIRE_EQ(planes[0].size(), (size_t)(8 * 32));
REQUIRE_EQ(planes[1].size(), (size_t)(8 * 2));
int bad = 0;
for (int b = 0; b < 8; ++b) {
bad += std::memcmp(planes[0].data() + 32 * b, q8.bytes.data() + 34 * b + 2, 32) != 0;
bad += std::memcmp(planes[1].data() + 2 * b, q8.bytes.data() + 34 * b, 2) != 0;
}
CHECK_EQ(bad, 0);
int differ = 0;
for (size_t i = 0; i < w8.size(); ++i) differ += f[i] != w8[i];
CHECK_EQ(differ, 0);
}
/* Q4_K, gate and up joined along rows: the planes decode to the block definition, and a
* range that starts in the first piece and ends in the second is the same bytes. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
CHECK_EQ(w.rows, (int64_t)5);
CHECK_EQ(w.cols, (int64_t)512);
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 5);
check_planes_decode_by_definition(w);
std::vector<std::vector<uint8_t>> planes;
std::vector<float> f;
read_planes(w, &planes, &f);
for (int k = 0; k < w.enc.n_planes; ++k) {
int64_t pr = 0, pc = 0;
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
const int64_t rb = rad_enc_row_bytes(w.enc.plane[k].dtype, pc);
std::vector<uint8_t> part((size_t)(3 * rb));
REQUIRE_EQ(ckpt_plane_rows(w, k, 1, 3, part.data(), &why), RAD_OK);
CHECK_EQ(std::memcmp(part.data(), planes[(size_t)k].data() + rb, part.size()), 0);
}
}
/* A row of one block ends its 6-bit planes mid-word. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "s", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
check_planes_decode_by_definition(w);
}
/* Q6_K. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "k6", false, &w, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK(!w.trivial);
REQUIRE(rad_enc_valid(&w.enc));
REQUIRE_EQ(w.enc.n_planes, 3);
check_planes_decode_by_definition(w);
}
/* What it does not import keeps the GGUF reason. */
{
CkptWeight w;
REQUIRE_EQ(ckpt_resolve(ck, prog, "mix", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "different block types"));
REQUIRE_EQ(ckpt_resolve(ck, prog, "across", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "joined along a column"));
REQUIRE_EQ(ckpt_resolve(ck, prog, "t.q5_k", false, &w, &why), RAD_OK);
CHECK(!w.imported && !w.ggml_blocks && !w.trivial);
CHECK(has(w.why, "GGUF"));
}
}
/* llama.cpp stacks an MoE's experts in one rank-3 tensor of blocks, and an expert's gate|up is two
* dim-0 slices joined along rows: their planes are those of the same blocks stored on their own. */
TEST(a_slice_of_a_stacked_gguf_block_tensor_is_imported_as_its_planes) {
const std::string path = fresh_dir() + "/m.gguf";
const int64_t E = 4, N = 3, K = 512;
GTensor gate = k_blocks("gate_exps", 12, E * N, K, 5);
GTensor up = k_blocks("up_exps", 12, E * N, K, 6);
gate.ne = up.ne = { (uint64_t)K, (uint64_t)N, (uint64_t)E };
const size_t eb = gate.bytes.size() / E;
GTensor own{ "gu2", 12, { (uint64_t)K, (uint64_t)(2 * N) }, {} };
own.bytes.assign(gate.bytes.begin() + 2 * eb, gate.bytes.begin() + 3 * eb);
own.bytes.insert(own.bytes.end(), up.bytes.begin() + 2 * eb, up.bytes.begin() + 3 * eb);
write_gguf(path, llama_kvs(15), { gate, up, own });
Checkpoint ck;
REQUIRE_EQ(ck.open(path), RAD_OK);
Program prog;
prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "gate_exps", "up_exps" }, { 2, 2 }));
prog.name_map.push_back(map("gu2", RAD_MAP_COPY, { "gu2" }));
std::string why;
CkptWeight w, o;
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK);
REQUIRE_EQ(ckpt_resolve(ck, prog, "gu2", false, &o, &why), RAD_OK);
CHECK(w.imported && w.ggml_blocks);
CHECK_EQ(w.rows, 2 * N);
CHECK_EQ(w.cols, K);
REQUIRE(rad_enc_equal(&w.enc, &o.enc));
std::vector<std::vector<uint8_t>> got, want;
std::vector<float> fg, fo;
read_planes(w, &got, &fg);
read_planes(o, &want, &fo);
for (int k = 0; k < w.enc.n_planes; ++k) CHECK(got[(size_t)k] == want[(size_t)k]);
}
TEST(hyv3_gguf_metadata_normalizes_architecture_and_config_fields) {
const std::string path = fresh_dir() + "/hyv3.gguf";
const std::vector<GKv> kvs = {
+17
View File
@@ -437,6 +437,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } },
{ "--prefill-span", { "2" } },
{ "--checkpoint-slots", { "4" } }, { "--checkpoint-policy", { "tip-only" } },
{ "--prefix-resume", { "nearest" } },
{ "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } },
{ "--draft-coupling", { "on" } },
{ "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } },
@@ -466,6 +467,8 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--video-max-frame-tokens", { "70" } }, { "--image-tokens", { "280" } },
{ "--max-source-pixels", { "1000000" } },
{ "--expert-stats", { "/s/experts.json" } },
{ "--expert-profile", { "/p.json" } }, { "--expert-pin-top", { "0.2" } },
{ "--draft-expert-placement", { "host" } },
{ "--kld-record", { "/r", "--kld-corpus", "/c.jsonl" } }, { "--kld-ref", { "/r" } },
{ "--kld-corpus", { "/c.jsonl", "--kld-record", "/r" } },
{ "--kld-out", { "/o.json", "--kld-ref", "/r" } },
@@ -863,6 +866,20 @@ TEST(expert_stats_is_off_until_it_names_a_file) {
CHECK(parse_fresh({ "--expert-stats" }) < 0);
}
/* A prefix hit resumes on the cold run's chunk grid unless the operator trades that for a shorter
* re-prefill; any other word is refused. */
TEST(prefix_resume_is_exact_unless_nearest_is_asked_for) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.prefix_exact);
Config c;
CHECK_EQ(parse({ "--prefix-resume", "nearest" }, &c), RAD_OK);
CHECK(!c.prefix_exact);
CHECK_EQ(parse({ "--prefix-resume", "exact" }, &c), RAD_OK);
CHECK(c.prefix_exact);
CHECK_EQ(parse({ "--prefix-resume", "deepest" }, &c), RAD_E_INVAL);
}
/* --checkpoint-slots is auto by default, resolved by the engine once a snapshot's size is known;
* a count is taken as given, 0 included, and the report shows which. */
TEST(the_checkpoint_slots_are_auto_or_a_count) {
+68
View File
@@ -6,11 +6,13 @@
* checkpoint holds them, so one conversion writes a quantised and a copied weight of every kind.
*/
#include "rad_test.h"
#include "gguf_writer.h"
#include "tiny_model.h"
#include "format/encoding.h"
#include "format/radfile.h"
#include "gen_config.h"
#include "text/tokenizer.h"
#include <sys/stat.h>
@@ -756,6 +758,49 @@ TEST(a_recipe_or_flag_that_cannot_be_honoured_is_refused_before_writing) {
}
}
/* A rule that declines a GGUF block tensor stops the run rather than keep the tensor's planes: the
* tiny LLaMA as a GGUF with its first attn_norm in Q8_0, under an `rtn` rule, which declines a
* rank-1 tensor. */
TEST(a_rule_that_declines_a_gguf_block_tensor_is_an_error) {
World& w = world();
REQUIRE(w.ok);
tiny::TempDir d("convert_gguf");
const tiny::Llama s;
const std::vector<ggufw::GKv> kvs = {
{ "general.architecture", 8, 0, { "llama" } },
{ "llama.block_count", 4, (double)s.layers, {} },
{ "llama.embedding_length", 4, (double)s.hidden, {} },
{ "llama.attention.head_count", 4, (double)s.heads, {} },
{ "llama.attention.head_count_kv", 4, (double)s.kv_heads, {} },
{ "llama.attention.key_length", 4, (double)s.head_dim, {} },
{ "llama.feed_forward_length", 4, (double)s.ffn, {} },
{ "llama.context_length", 4, (double)s.ctx, {} },
{ "llama.vocab_size", 4, (double)s.vocab, {} },
};
std::vector<ggufw::GTensor> ts;
for (const auto& [name, t] : w.src) {
ggufw::GTensor g{ name, t.dtype == "F32" ? 0u : 30u, {}, t.bytes };
g.ne.assign(t.shape.rbegin(), t.shape.rend());
if (name == "model.layers.0.input_layernorm.weight") {
g.type = 8;
g.bytes.clear();
for (uint64_t b = 0; b < g.ne[0] / 32; ++b) {
g.bytes.insert(g.bytes.end(), { 0x00, 0x3C }); /* d = 1 in f16 */
g.bytes.insert(g.bytes.end(), 32, 1);
}
}
ts.push_back(std::move(g));
}
REQUIRE(ggufw::write_gguf(d / "llama.gguf", kvs, ts));
std::string log;
CHECK(convert(d / "llama.gguf",
{ "-o", d / "g.rad", "--recipe", w.recipe, "--quant",
"blk.0.attn_norm.weight=rtn:codes=i8,group=32,scale=bf16" },
&log) != 0);
CHECK(has(log, "(rtn) refuses it"));
CHECK(!exists(d / "g.rad"));
}
/* ================================================================== an int4 release */
namespace {
@@ -923,4 +968,27 @@ TEST(an_fp8_kv_cache_declares) {
CHECK(exists(d / "k.rad"));
}
/* --chat-template bakes a template into the container's vocab section, for a release that ships
* none (DeepSeek's). Without the flag the container carries what the checkpoint carried. A missing
* file is refused, not silently skipped. */
TEST(chat_template_flag_bakes_the_template) {
World& w = world();
REQUIRE(w.ok);
tiny::TempDir d("convert_ct");
const std::string tmpl = d / "chat_template.jinja";
REQUIRE(tiny::write_text(tmpl, "{%- raw %}{{ messages }}{%- endraw %}\n\n"));
std::string log;
REQUIRE_EQ(convert(w.ckpt, { "-o", d / "with.rad", "--recipe", w.recipe,
"--chat-template", tmpl }, &log), 0);
RadFile f;
REQUIRE_EQ(f.open((d / "with.rad").c_str()), RAD_OK);
VocabBuild vb;
REQUIRE_EQ(vocab_deserialize(f.base(), (uint64_t)f.size(), f.vocab().h, vb), RAD_OK);
CHECK_EQ(vb.chat_template, std::string("{%- raw %}{{ messages }}{%- endraw %}"));
std::string bad;
CHECK_EQ(convert(w.ckpt, { "-o", d / "bad.rad", "--recipe", w.recipe,
"--chat-template", d / "absent.jinja" }, &bad), 1);
}
RAD_TEST_MAIN()
+39
View File
@@ -1433,6 +1433,45 @@ TEST(gbnf_a_length_bound_past_two_thousand_is_held_exactly) {
}
}
/* Bounded repetitions of one operand share one chain of links, so a schema's many length bounds
* cost its longest once rather than their sum. 200 properties at `maxLength: 4000` were 200 chains,
* past the compile budget (a tool schema like that is refused in full); shared, they compile, and
* every bound, short or long, string or array, is still held exactly. */
TEST(gbnf_bounds_over_one_operand_share_their_links) {
auto bv = bpe_like(59, 1500);
std::string props = R"("a":{"type":"string","maxLength":4000},"b":{"type":"string","maxLength":7},)"
R"("c":{"type":"array","items":{"type":"string","maxLength":5},"maxItems":3})";
for (int i = 0; i < 200; ++i)
props += ",\"f" + std::to_string(i) + "\":{\"type\":\"string\",\"maxLength\":4000}";
std::string gbnf, err;
CHECK_OK(grammar_from_json_schema("{\"type\":\"object\",\"properties\":{" + props +
"},\"required\":[\"a\",\"b\",\"c\"]}",
"root", &gbnf, &err));
std::unique_ptr<GbnfGrammar> g;
CHECK_OK(GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err));
auto whole = [&](const std::string& text) {
std::unique_ptr<GbnfGrammar> h;
std::string e;
if (GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &h, &e) < 0) return false;
return h->accept_str(text) >= 0 && h->complete();
};
auto doc = [](size_t a, size_t b, std::vector<size_t> c, size_t f7) {
std::string s = "{\"a\":\"" + std::string(a, 'x') + "\",\"b\":\"" + std::string(b, 'y') +
"\",\"c\":[";
for (size_t i = 0; i < c.size(); ++i) s += (i ? ",\"" : "\"") + std::string(c[i], 'z') + "\"";
s += "]";
if (f7) s += ",\"f7\":\"" + std::string(f7, 'w') + "\"";
return s + "}";
};
CHECK(whole(doc(4000, 7, { 5, 0, 5 }, 4000)));
CHECK(whole(doc(0, 0, {}, 0)));
CHECK(!whole(doc(4001, 7, { 5 }, 0)));
CHECK(!whole(doc(10, 8, { 5 }, 0)));
CHECK(!whole(doc(10, 7, { 6 }, 0)));
CHECK(!whole(doc(10, 7, { 1, 1, 1, 1 }, 0)));
CHECK(!whole(doc(10, 7, { 1 }, 4001)));
}
/* Identical clauses across tools are one clause to the plan. A tool-calling template writes the
* same undeclared-parameter clause, free-text value and closing tags as separate rules per tool;
* the plan hash-conses rules by body, so its size and the compile's vocabulary walks do not grow
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more