diff --git a/CMakeLists.txt b/CMakeLists.txt index e0c61046..4c422bb3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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 diff --git a/abi/rad_builder.h b/abi/rad_builder.h index d3ba826b..7d29b8b9 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -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. * diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 702d7b16..37d6975a 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -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); diff --git a/core/config.cpp b/core/config.cpp index 841335e5..89d1cd81 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -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); } }, diff --git a/core/diag/diag.h b/core/diag/diag.h index a02e2824..4f2bb217 100644 --- a/core/diag/diag.h +++ b/core/diag/diag.h @@ -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 " / "absent (built without libav*)" */ }; struct Facts { diff --git a/core/diag/report.cpp b/core/diag/report.cpp index 189b7678..a64661bc 100644 --- a/core/diag/report.cpp +++ b/core/diag/report.cpp @@ -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& config, const std::vector 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& cg = pc.cached_groups(); + * marked each resident at its new blocks. A job's blocks are one per entry slot. */ + const std::vector& cg = pc.entry_groups(); for (size_t i = 0; i < jobs.size(); ++i) { TierJob& j = jobs[i]; if (!ok[i]) { res = RestoreResult::Cut; continue; } diff --git a/core/engine.h b/core/engine.h index 7609b93b..29cee8da 100644 --- a/core/engine.h +++ b/core/engine.h @@ -241,6 +241,9 @@ private: std::vector table_copies_; std::vector card_copies_; std::vector> 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 expert_profile_; int load_weights(); int configure_kv(); /* Resolves --checkpoint-slots auto for snapshots of `slot` bytes (`what` names their kind). */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 46d25035..c28fa5a8 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -37,6 +37,7 @@ #include #include +#include #include #include #include @@ -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(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(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(room - align_up(wfs[i].draft_experts, MiB), 0)); + facts[i].experts = std::max(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& 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& 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 diff --git a/core/engine_diag.cpp b/core/engine_diag.cpp index 25f6b80a..367c3aba 100644 --- a/core/engine_diag.cpp +++ b/core/engine_diag.cpp @@ -6,6 +6,7 @@ */ #include "engine_priv.h" #include "device/device.h" +#include "mm/media.h" #include @@ -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_; diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index d976d744..9c0ae3ad 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -1,5 +1,6 @@ /* checkpoint.cpp -- see checkpoint.h. */ #include "checkpoint.h" +#include "ggml_planes.h" #include "rad_plugin.h" #include @@ -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 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. */ diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 5498f4dc..27821d4a 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -282,6 +282,9 @@ struct CkptWeight { * from `pq_meta`. */ bool paro = false; std::vector 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. */ diff --git a/core/format/ggml_planes.h b/core/format/ggml_planes.h new file mode 100644 index 00000000..78414619 --- /dev/null +++ b/core/format/ggml_planes.h @@ -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_ 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 +#include + +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 */ diff --git a/core/gen/video.h b/core/gen/video.h index 96e65474..72e9f97b 100644 --- a/core/gen/video.h +++ b/core/gen/video.h @@ -98,6 +98,10 @@ struct VideoRefMedia { std::vector 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 small_pixels; + int32_t small_h = 0, small_w = 0; }; struct VideoRequest { diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index 41f6020a..caa318ad 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -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& 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 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& 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(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(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(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; diff --git a/core/gen/video_driver.h b/core/gen/video_driver.h index cc486689..9a3f876a 100644 --- a/core/gen/video_driver.h +++ b/core/gen/video_driver.h @@ -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 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 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 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& tab, Pack* out, std::string* why) const; int32_t predicted_chunks(double log_seconds, std::string* note) const; diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index c1a3eb7a..506e44bd 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -270,12 +270,12 @@ int KVManager::plan_groups(const std::vector& 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; diff --git a/core/mem/kv.h b/core/mem/kv.h index 7786569f..2f9128d3 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -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) */ diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index cdb79a5a..a42b7530 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -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 blocks; int32_t host_slot = -1; diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index da2a2c9a..d73906c7 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -5,6 +5,7 @@ #include #include +#include #include 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& 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& 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& tokens, return hit; } +bool PrefixCache::retain_entry(const std::vector>& bt, int64_t b, + std::vector* 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& tokens, const std::vector& 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 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 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 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 PrefixCache::restorable_from(const std::vector& 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(per_[i], 1)); return std::max(0, room); } int64_t PrefixCache::trim_for(const std::vector& tokens, - const std::vector& mm, int64_t n_blocks) { + const std::vector& 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 hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_); std::unordered_set 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& 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& 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* 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; } diff --git a/core/mem/prefix.h b/core/mem/prefix.h index b0a6016a..792dc7a3 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -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& 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& 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& tokens, @@ -235,7 +250,7 @@ public: std::vector>* 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& 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 restorable_from(const std::vector& tokens, const std::vector& 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& tokens, const std::vector& 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& blocks); @@ -404,7 +422,8 @@ public: private: struct Entry { - std::vector 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 blocks; std::vector 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* 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>& bt, int64_t b, + std::vector* 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::iterator it); @@ -474,6 +498,8 @@ private: int64_t interval_ = 0; std::vector groups_; /* paged groups this cache indexes */ bool demotable_ = false; /* the host tier can hold every group in an entry */ + std::vector per_; /* blocks of groups_[i] an entry holds */ + std::vector entry_groups_; /* the group of each of an entry's blocks */ bool has_linear_ = false; mutable std::unordered_map map_; diff --git a/core/mm/media.cpp b/core/mm/media.cpp index 8eb1e048..586a2173 100644 --- a/core/mm/media.cpp +++ b/core/mm/media.cpp @@ -5,6 +5,7 @@ #include "rad_internal.h" #include +#include #include #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*, 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 diff --git a/core/mm/media.h b/core/mm/media.h index 4920bc47..f887b79e 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -36,6 +36,11 @@ struct FrameRGBA { /* Whether this build has a decoder. */ bool decoder_available(); +/* "libavformat " 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); diff --git a/core/place/heat.cpp b/core/place/heat.cpp index bde21644..301cbde0 100644 --- a/core/place/heat.cpp +++ b/core/place/heat.cpp @@ -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; diff --git a/core/place/heat.h b/core/place/heat.h index 2436e2f7..16c95adf 100644 --- a/core/place/heat.h +++ b/core/place/heat.h @@ -210,6 +210,9 @@ private: std::vector tier_; std::vector busy_; std::vector 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 pinned_; std::vector layer_of_; /* Bit 0: promoted before. Bit 1: demoted before. Feeds the readmit counters. */ std::vector ever_; diff --git a/core/place/planner.cpp b/core/place/planner.cpp index 777b7d0f..60ec2f09 100644 --- a/core/place/planner.cpp +++ b/core/place/planner.cpp @@ -12,6 +12,7 @@ #include "planner.h" #include +#include #include #include #include @@ -103,6 +104,21 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) { return std::min(all, std::max(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 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(), diff --git a/core/place/planner.h b/core/place/planner.h index 1eb08958..ffc371ca 100644 --- a/core/place/planner.h +++ b/core/place/planner.h @@ -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* 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. */ diff --git a/core/place/xstats.cpp b/core/place/xstats.cpp index 38199713..8f2b839a 100644 --- a/core/place/xstats.cpp +++ b/core/place/xstats.cpp @@ -479,4 +479,70 @@ void ExpertStats::stop() { ExpertStats::~ExpertStats() { stop(); } +/* ------------------------------------------------------------------ --expert-profile */ + +int xs_profile_load(const std::string& path, std::vector* 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(); + 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(); + 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(); + 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 */ diff --git a/core/place/xstats.h b/core/place/xstats.h index ee5b5df5..adf816c9 100644 --- a/core/place/xstats.h +++ b/core/place/xstats.h @@ -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* out, int32_t* n_trunk); + } /* namespace rad */ diff --git a/core/rad_core.h b/core/rad_core.h index 6db092a1..215f5d5c 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -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; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 12a38194..21d70712 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -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& 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) { diff --git a/core/runtime/tierexec.h b/core/runtime/tierexec.h index 40c2def2..37bffc21 100644 --- a/core/runtime/tierexec.h +++ b/core/runtime/tierexec.h @@ -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, diff --git a/core/sample/gbnf.cpp b/core/sample/gbnf.cpp index 455449d5..b4bf15f8 100644 --- a/core/sample/gbnf.cpp +++ b/core/sample/gbnf.cpp @@ -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* links = nullptr; + uint64_t n_new = n_opt; + if (!no_max && n_opt > 0) { + std::vector> 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); diff --git a/core/sample/gbnf.h b/core/sample/gbnf.h index 89b47b5d..a57ae993 100644 --- a/core/sample/gbnf.h +++ b/core/sample/gbnf.h @@ -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> 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); diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index e5dca1ca..d6af36ed 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -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(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. */ diff --git a/core/sched/geometry.h b/core/sched/geometry.h index 437b0eb5..72583964 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -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 diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index e7e329a2..fd53ac05 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -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>* blocks_out, const HitCap* cap) const = 0; virtual const std::vector& 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. */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 1664614f..4a304cc4 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -10,6 +10,7 @@ #include #include #include +#include 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& 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& 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(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(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 " diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 5efb9ee7..f33d248e 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -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 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 diff --git a/core/server/videos.cpp b/core/server/videos.cpp index 76e090c6..53ac4396 100644 --- a/core/server/videos.cpp +++ b/core/server/videos.cpp @@ -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()); + } } } diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index 96a2c822..fe0740fc 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -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 diff --git a/core/text/tokenizer_json.cpp b/core/text/tokenizer_json.cpp index 4ce100ea..79e389e4 100644 --- a/core/text/tokenizer_json.cpp +++ b/core/text/tokenizer_json.cpp @@ -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 { diff --git a/data/engram_tables.py b/data/engram_tables.py new file mode 100644 index 00000000..605d182b --- /dev/null +++ b/data/engram_tables.py @@ -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"", 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", " {cvocab}; {len(layer_ids)} Engram layers {layer_ids}; " + f"{len(mults)} multipliers, {len(sizes)} heads, rows {sum(sizes)}") + + +if __name__ == "__main__": + main() diff --git a/data/imatrix_merge.py b/data/imatrix_merge.py new file mode 100644 index 00000000..6dccbb9a --- /dev/null +++ b/data/imatrix_merge.py @@ -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 `.ffn_gate_exps` and `.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() diff --git a/data/kbench_rows/kbench_rows_kernels_libr3d.txt b/data/kbench_rows/kbench_rows_kernels_libr3d.txt new file mode 100644 index 00000000..2dd4e49b --- /dev/null +++ b/data/kbench_rows/kbench_rows_kernels_libr3d.txt @@ -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 diff --git a/data/recipes/deepseek41-ud-iq1s.recipe b/data/recipes/deepseek41-ud-iq1s.recipe new file mode 100644 index 00000000..bc8ece4a --- /dev/null +++ b/data/recipes/deepseek41-ud-iq1s.recipe @@ -0,0 +1,1299 @@ +# deepseek41-ud-iq1s.recipe -- DeepSeek-V4.1-Flash-1017 from the official release at Unsloth's UD-IQ1_S per-tensor mix: +# routed experts iq1_s / iq2_xxs (gate_up iq1_s in 34 layers and iq2_xxs in 6, down iq1_s in 20 and iq2_xxs in 20), +# attention and shared expert q6_K / q5_K / q8_0, the Engram table iq4_nl, norms and small tensors cast to their stored +# float type, the DSpark drafter's experts kept as the release's MXFP4 (no rule). The `ggml` quantiser runs its +# own searches (llama.cpp's iq1_s/iq2_xxs procedure, ported in Radiance); iq1_s and iq2_xxs need --imatrix. 251.07 GiB. +# +# data/engram_tables.py engram-tables.safetensors (the release ships none) +# rad-convert --add engram-tables.safetensors \ +# --recipe data/recipes/deepseek41-ud-iq1s.recipe --imatrix -o deepseek41-ud-iq1s.rad +# +# The imatrix is Unsloth's with entries for the fused weights added (docs/deepseek41-wip.md). One rule per weight, +# experts collapsed per layer; first match wins. +# PATTERN QUANTISER OPTIONS +dspark.enc.output_norm.weight cast dtype=f32 +dspark.fc.weight cast dtype=bf16 +dspark.markov_w1.weight cast dtype=bf16 +dspark.markov_w2.weight cast dtype=bf16 +dspark.output_norm.weight cast dtype=f32 +output.weight ggml type=q6_K +output_norm.weight cast dtype=f32 +per_layer_token_embd.weight ggml type=iq4_nl +token_embd.weight ggml type=q6_K +blk.0.attn_kv.weight ggml type=q6_K +blk.0.attn_kv_a_norm.weight cast dtype=f32 +blk.0.attn_norm.weight cast dtype=f32 +blk.0.attn_output_a.g0.weight ggml type=q6_K +blk.0.attn_output_a.g1.weight ggml type=q6_K +blk.0.attn_output_a.g2.weight ggml type=q6_K +blk.0.attn_output_a.g3.weight ggml type=q6_K +blk.0.attn_output_a.g4.weight ggml type=q6_K +blk.0.attn_output_a.g5.weight ggml type=q6_K +blk.0.attn_output_a.g6.weight ggml type=q6_K +blk.0.attn_output_a.g7.weight ggml type=q6_K +blk.0.attn_output_b.weight ggml type=q6_K +blk.0.attn_q_a.weight ggml type=q6_K +blk.0.attn_q_a_norm.weight cast dtype=f32 +blk.0.attn_q_b.weight ggml type=q6_K +blk.0.attn_sinks.weight cast dtype=f32 +blk.0.ffn_down_exps.*.weight ggml type=iq1_s +blk.0.ffn_down_shexp.weight ggml type=q6_K +blk.0.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.0.ffn_gate_up_shexp.weight ggml type=q6_K +blk.0.ffn_norm.weight cast dtype=f32 +blk.0.glm_router.correction cast dtype=f32 +blk.0.glm_router.weight cast dtype=f32 +blk.0.hc_attn_base.weight cast dtype=f32 +blk.0.hc_attn_fn.weight cast dtype=f32 +blk.0.hc_attn_scale.weight cast dtype=f32 +blk.0.hc_ffn_base.weight cast dtype=f32 +blk.0.hc_ffn_fn.weight cast dtype=f32 +blk.0.hc_ffn_scale.weight cast dtype=f32 +blk.1.attn_kv.weight ggml type=q6_K +blk.1.attn_kv_a_norm.weight cast dtype=f32 +blk.1.attn_norm.weight cast dtype=f32 +blk.1.attn_output_a.g0.weight ggml type=q6_K +blk.1.attn_output_a.g1.weight ggml type=q6_K +blk.1.attn_output_a.g2.weight ggml type=q6_K +blk.1.attn_output_a.g3.weight ggml type=q6_K +blk.1.attn_output_a.g4.weight ggml type=q6_K +blk.1.attn_output_a.g5.weight ggml type=q6_K +blk.1.attn_output_a.g6.weight ggml type=q6_K +blk.1.attn_output_a.g7.weight ggml type=q6_K +blk.1.attn_output_b.weight ggml type=q6_K +blk.1.attn_q_a.weight ggml type=q6_K +blk.1.attn_q_a_norm.weight cast dtype=f32 +blk.1.attn_q_b.weight ggml type=q6_K +blk.1.attn_sinks.weight cast dtype=f32 +blk.1.engram_gate.weight cast dtype=f32 +blk.1.engram_kv.weight ggml type=q6_K +blk.1.ffn_down_exps.*.weight ggml type=iq1_s +blk.1.ffn_down_shexp.weight ggml type=q6_K +blk.1.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.1.ffn_gate_up_shexp.weight ggml type=q6_K +blk.1.ffn_norm.weight cast dtype=f32 +blk.1.glm_router.correction cast dtype=f32 +blk.1.glm_router.weight cast dtype=f32 +blk.1.hc_attn_base.weight cast dtype=f32 +blk.1.hc_attn_fn.weight cast dtype=f32 +blk.1.hc_attn_scale.weight cast dtype=f32 +blk.1.hc_ffn_base.weight cast dtype=f32 +blk.1.hc_ffn_fn.weight cast dtype=f32 +blk.1.hc_ffn_scale.weight cast dtype=f32 +blk.2.attn_compressor_kvg.weight cast dtype=bf16 +blk.2.attn_compressor_norm.weight cast dtype=f32 +blk.2.attn_kv.weight ggml type=q6_K +blk.2.attn_kv_a_norm.weight cast dtype=f32 +blk.2.attn_norm.weight cast dtype=f32 +blk.2.attn_output_a.g0.weight ggml type=q6_K +blk.2.attn_output_a.g1.weight ggml type=q6_K +blk.2.attn_output_a.g2.weight ggml type=q6_K +blk.2.attn_output_a.g3.weight ggml type=q6_K +blk.2.attn_output_a.g4.weight ggml type=q6_K +blk.2.attn_output_a.g5.weight ggml type=q6_K +blk.2.attn_output_a.g6.weight ggml type=q6_K +blk.2.attn_output_a.g7.weight ggml type=q6_K +blk.2.attn_output_b.weight ggml type=q6_K +blk.2.attn_q_a.weight ggml type=q6_K +blk.2.attn_q_a_norm.weight cast dtype=f32 +blk.2.attn_q_b.weight ggml type=q6_K +blk.2.attn_sinks.weight cast dtype=f32 +blk.2.ffn_down_exps.*.weight ggml type=iq1_s +blk.2.ffn_down_shexp.weight ggml type=q6_K +blk.2.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.2.ffn_gate_up_shexp.weight ggml type=q6_K +blk.2.ffn_norm.weight cast dtype=f32 +blk.2.glm_router.correction cast dtype=f32 +blk.2.glm_router.weight cast dtype=f32 +blk.2.hc_attn_base.weight cast dtype=f32 +blk.2.hc_attn_fn.weight cast dtype=f32 +blk.2.hc_attn_scale.weight cast dtype=f32 +blk.2.hc_ffn_base.weight cast dtype=f32 +blk.2.hc_ffn_fn.weight cast dtype=f32 +blk.2.hc_ffn_scale.weight cast dtype=f32 +blk.2.indexer.attn_k.weight cast dtype=bf16 +blk.2.indexer.attn_q_b.weight cast dtype=bf16 +blk.2.indexer.k_norm.weight cast dtype=f32 +blk.2.indexer.proj.weight cast dtype=bf16 +blk.3.attn_kv.weight ggml type=q6_K +blk.3.attn_kv_a_norm.weight cast dtype=f32 +blk.3.attn_norm.weight cast dtype=f32 +blk.3.attn_output_a.g0.weight ggml type=q6_K +blk.3.attn_output_a.g1.weight ggml type=q6_K +blk.3.attn_output_a.g2.weight ggml type=q6_K +blk.3.attn_output_a.g3.weight ggml type=q6_K +blk.3.attn_output_a.g4.weight ggml type=q6_K +blk.3.attn_output_a.g5.weight ggml type=q6_K +blk.3.attn_output_a.g6.weight ggml type=q6_K +blk.3.attn_output_a.g7.weight ggml type=q6_K +blk.3.attn_output_b.weight ggml type=q6_K +blk.3.attn_q_a.weight ggml type=q6_K +blk.3.attn_q_a_norm.weight cast dtype=f32 +blk.3.attn_q_b.weight ggml type=q6_K +blk.3.attn_sinks.weight cast dtype=f32 +blk.3.ffn_down_exps.*.weight ggml type=iq1_s +blk.3.ffn_down_shexp.weight ggml type=q6_K +blk.3.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.3.ffn_gate_up_shexp.weight ggml type=q6_K +blk.3.ffn_norm.weight cast dtype=f32 +blk.3.glm_router.correction cast dtype=f32 +blk.3.glm_router.weight cast dtype=f32 +blk.3.hc_attn_base.weight cast dtype=f32 +blk.3.hc_attn_fn.weight cast dtype=f32 +blk.3.hc_attn_scale.weight cast dtype=f32 +blk.3.hc_ffn_base.weight cast dtype=f32 +blk.3.hc_ffn_fn.weight cast dtype=f32 +blk.3.hc_ffn_scale.weight cast dtype=f32 +blk.4.attn_kv.weight ggml type=q6_K +blk.4.attn_kv_a_norm.weight cast dtype=f32 +blk.4.attn_norm.weight cast dtype=f32 +blk.4.attn_output_a.g0.weight ggml type=q6_K +blk.4.attn_output_a.g1.weight ggml type=q6_K +blk.4.attn_output_a.g2.weight ggml type=q6_K +blk.4.attn_output_a.g3.weight ggml type=q6_K +blk.4.attn_output_a.g4.weight ggml type=q6_K +blk.4.attn_output_a.g5.weight ggml type=q6_K +blk.4.attn_output_a.g6.weight ggml type=q6_K +blk.4.attn_output_a.g7.weight ggml type=q6_K +blk.4.attn_output_b.weight ggml type=q6_K +blk.4.attn_q_a.weight ggml type=q6_K +blk.4.attn_q_a_norm.weight cast dtype=f32 +blk.4.attn_q_b.weight ggml type=q6_K +blk.4.attn_sinks.weight cast dtype=f32 +blk.4.ffn_down_exps.*.weight ggml type=iq1_s +blk.4.ffn_down_shexp.weight ggml type=q6_K +blk.4.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.4.ffn_gate_up_shexp.weight ggml type=q6_K +blk.4.ffn_norm.weight cast dtype=f32 +blk.4.glm_router.correction cast dtype=f32 +blk.4.glm_router.weight cast dtype=f32 +blk.4.hc_attn_base.weight cast dtype=f32 +blk.4.hc_attn_fn.weight cast dtype=f32 +blk.4.hc_attn_scale.weight cast dtype=f32 +blk.4.hc_ffn_base.weight cast dtype=f32 +blk.4.hc_ffn_fn.weight cast dtype=f32 +blk.4.hc_ffn_scale.weight cast dtype=f32 +blk.5.attn_kv.weight ggml type=q6_K +blk.5.attn_kv_a_norm.weight cast dtype=f32 +blk.5.attn_norm.weight cast dtype=f32 +blk.5.attn_output_a.g0.weight ggml type=q6_K +blk.5.attn_output_a.g1.weight ggml type=q6_K +blk.5.attn_output_a.g2.weight ggml type=q6_K +blk.5.attn_output_a.g3.weight ggml type=q6_K +blk.5.attn_output_a.g4.weight ggml type=q6_K +blk.5.attn_output_a.g5.weight ggml type=q6_K +blk.5.attn_output_a.g6.weight ggml type=q6_K +blk.5.attn_output_a.g7.weight ggml type=q6_K +blk.5.attn_output_b.weight ggml type=q6_K +blk.5.attn_q_a.weight ggml type=q6_K +blk.5.attn_q_a_norm.weight cast dtype=f32 +blk.5.attn_q_b.weight ggml type=q6_K +blk.5.attn_sinks.weight cast dtype=f32 +blk.5.ffn_down_exps.*.weight ggml type=iq1_s +blk.5.ffn_down_shexp.weight ggml type=q6_K +blk.5.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.5.ffn_gate_up_shexp.weight ggml type=q6_K +blk.5.ffn_norm.weight cast dtype=f32 +blk.5.glm_router.correction cast dtype=f32 +blk.5.glm_router.weight cast dtype=f32 +blk.5.hc_attn_base.weight cast dtype=f32 +blk.5.hc_attn_fn.weight cast dtype=f32 +blk.5.hc_attn_scale.weight cast dtype=f32 +blk.5.hc_ffn_base.weight cast dtype=f32 +blk.5.hc_ffn_fn.weight cast dtype=f32 +blk.5.hc_ffn_scale.weight cast dtype=f32 +blk.6.attn_kv.weight ggml type=q6_K +blk.6.attn_kv_a_norm.weight cast dtype=f32 +blk.6.attn_norm.weight cast dtype=f32 +blk.6.attn_output_a.g0.weight ggml type=q6_K +blk.6.attn_output_a.g1.weight ggml type=q6_K +blk.6.attn_output_a.g2.weight ggml type=q6_K +blk.6.attn_output_a.g3.weight ggml type=q6_K +blk.6.attn_output_a.g4.weight ggml type=q6_K +blk.6.attn_output_a.g5.weight ggml type=q6_K +blk.6.attn_output_a.g6.weight ggml type=q6_K +blk.6.attn_output_a.g7.weight ggml type=q6_K +blk.6.attn_output_b.weight ggml type=q6_K +blk.6.attn_q_a.weight ggml type=q6_K +blk.6.attn_q_a_norm.weight cast dtype=f32 +blk.6.attn_q_b.weight ggml type=q6_K +blk.6.attn_sinks.weight cast dtype=f32 +blk.6.ffn_down_exps.*.weight ggml type=iq1_s +blk.6.ffn_down_shexp.weight ggml type=q6_K +blk.6.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.6.ffn_gate_up_shexp.weight ggml type=q6_K +blk.6.ffn_norm.weight cast dtype=f32 +blk.6.glm_router.correction cast dtype=f32 +blk.6.glm_router.weight cast dtype=f32 +blk.6.hc_attn_base.weight cast dtype=f32 +blk.6.hc_attn_fn.weight cast dtype=f32 +blk.6.hc_attn_scale.weight cast dtype=f32 +blk.6.hc_ffn_base.weight cast dtype=f32 +blk.6.hc_ffn_fn.weight cast dtype=f32 +blk.6.hc_ffn_scale.weight cast dtype=f32 +blk.7.attn_kv.weight ggml type=q6_K +blk.7.attn_kv_a_norm.weight cast dtype=f32 +blk.7.attn_norm.weight cast dtype=f32 +blk.7.attn_output_a.g0.weight ggml type=q6_K +blk.7.attn_output_a.g1.weight ggml type=q6_K +blk.7.attn_output_a.g2.weight ggml type=q6_K +blk.7.attn_output_a.g3.weight ggml type=q6_K +blk.7.attn_output_a.g4.weight ggml type=q6_K +blk.7.attn_output_a.g5.weight ggml type=q6_K +blk.7.attn_output_a.g6.weight ggml type=q6_K +blk.7.attn_output_a.g7.weight ggml type=q6_K +blk.7.attn_output_b.weight ggml type=q6_K +blk.7.attn_q_a.weight ggml type=q6_K +blk.7.attn_q_a_norm.weight cast dtype=f32 +blk.7.attn_q_b.weight ggml type=q6_K +blk.7.attn_sinks.weight cast dtype=f32 +blk.7.ffn_down_exps.*.weight ggml type=iq1_s +blk.7.ffn_down_shexp.weight ggml type=q6_K +blk.7.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.7.ffn_gate_up_shexp.weight ggml type=q6_K +blk.7.ffn_norm.weight cast dtype=f32 +blk.7.glm_router.correction cast dtype=f32 +blk.7.glm_router.weight cast dtype=f32 +blk.7.hc_attn_base.weight cast dtype=f32 +blk.7.hc_attn_fn.weight cast dtype=f32 +blk.7.hc_attn_scale.weight cast dtype=f32 +blk.7.hc_ffn_base.weight cast dtype=f32 +blk.7.hc_ffn_fn.weight cast dtype=f32 +blk.7.hc_ffn_scale.weight cast dtype=f32 +blk.8.attn_compressor_kvg.weight cast dtype=bf16 +blk.8.attn_compressor_norm.weight cast dtype=f32 +blk.8.attn_kv.weight ggml type=q6_K +blk.8.attn_kv_a_norm.weight cast dtype=f32 +blk.8.attn_norm.weight cast dtype=f32 +blk.8.attn_output_a.g0.weight ggml type=q6_K +blk.8.attn_output_a.g1.weight ggml type=q6_K +blk.8.attn_output_a.g2.weight ggml type=q6_K +blk.8.attn_output_a.g3.weight ggml type=q6_K +blk.8.attn_output_a.g4.weight ggml type=q6_K +blk.8.attn_output_a.g5.weight ggml type=q6_K +blk.8.attn_output_a.g6.weight ggml type=q6_K +blk.8.attn_output_a.g7.weight ggml type=q6_K +blk.8.attn_output_b.weight ggml type=q6_K +blk.8.attn_q_a.weight ggml type=q6_K +blk.8.attn_q_a_norm.weight cast dtype=f32 +blk.8.attn_q_b.weight ggml type=q6_K +blk.8.attn_sinks.weight cast dtype=f32 +blk.8.ffn_down_exps.*.weight ggml type=iq1_s +blk.8.ffn_down_shexp.weight ggml type=q6_K +blk.8.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.8.ffn_gate_up_shexp.weight ggml type=q6_K +blk.8.ffn_norm.weight cast dtype=f32 +blk.8.glm_router.correction cast dtype=f32 +blk.8.glm_router.weight cast dtype=f32 +blk.8.hc_attn_base.weight cast dtype=f32 +blk.8.hc_attn_fn.weight cast dtype=f32 +blk.8.hc_attn_scale.weight cast dtype=f32 +blk.8.hc_ffn_base.weight cast dtype=f32 +blk.8.hc_ffn_fn.weight cast dtype=f32 +blk.8.hc_ffn_scale.weight cast dtype=f32 +blk.8.indexer.attn_k.weight cast dtype=bf16 +blk.8.indexer.attn_q_b.weight cast dtype=bf16 +blk.8.indexer.k_norm.weight cast dtype=f32 +blk.8.indexer.proj.weight cast dtype=bf16 +blk.9.attn_kv.weight ggml type=q6_K +blk.9.attn_kv_a_norm.weight cast dtype=f32 +blk.9.attn_norm.weight cast dtype=f32 +blk.9.attn_output_a.g0.weight ggml type=q6_K +blk.9.attn_output_a.g1.weight ggml type=q6_K +blk.9.attn_output_a.g2.weight ggml type=q6_K +blk.9.attn_output_a.g3.weight ggml type=q6_K +blk.9.attn_output_a.g4.weight ggml type=q6_K +blk.9.attn_output_a.g5.weight ggml type=q6_K +blk.9.attn_output_a.g6.weight ggml type=q6_K +blk.9.attn_output_a.g7.weight ggml type=q6_K +blk.9.attn_output_b.weight ggml type=q6_K +blk.9.attn_q_a.weight ggml type=q6_K +blk.9.attn_q_a_norm.weight cast dtype=f32 +blk.9.attn_q_b.weight ggml type=q6_K +blk.9.attn_sinks.weight cast dtype=f32 +blk.9.ffn_down_exps.*.weight ggml type=iq1_s +blk.9.ffn_down_shexp.weight ggml type=q6_K +blk.9.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.9.ffn_gate_up_shexp.weight ggml type=q6_K +blk.9.ffn_norm.weight cast dtype=f32 +blk.9.glm_router.correction cast dtype=f32 +blk.9.glm_router.weight cast dtype=f32 +blk.9.hc_attn_base.weight cast dtype=f32 +blk.9.hc_attn_fn.weight cast dtype=f32 +blk.9.hc_attn_scale.weight cast dtype=f32 +blk.9.hc_ffn_base.weight cast dtype=f32 +blk.9.hc_ffn_fn.weight cast dtype=f32 +blk.9.hc_ffn_scale.weight cast dtype=f32 +blk.10.attn_kv.weight ggml type=q6_K +blk.10.attn_kv_a_norm.weight cast dtype=f32 +blk.10.attn_norm.weight cast dtype=f32 +blk.10.attn_output_a.g0.weight ggml type=q6_K +blk.10.attn_output_a.g1.weight ggml type=q6_K +blk.10.attn_output_a.g2.weight ggml type=q6_K +blk.10.attn_output_a.g3.weight ggml type=q6_K +blk.10.attn_output_a.g4.weight ggml type=q6_K +blk.10.attn_output_a.g5.weight ggml type=q6_K +blk.10.attn_output_a.g6.weight ggml type=q6_K +blk.10.attn_output_a.g7.weight ggml type=q6_K +blk.10.attn_output_b.weight ggml type=q6_K +blk.10.attn_q_a.weight ggml type=q6_K +blk.10.attn_q_a_norm.weight cast dtype=f32 +blk.10.attn_q_b.weight ggml type=q6_K +blk.10.attn_sinks.weight cast dtype=f32 +blk.10.ffn_down_exps.*.weight ggml type=iq1_s +blk.10.ffn_down_shexp.weight ggml type=q6_K +blk.10.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.10.ffn_gate_up_shexp.weight ggml type=q6_K +blk.10.ffn_norm.weight cast dtype=f32 +blk.10.glm_router.correction cast dtype=f32 +blk.10.glm_router.weight cast dtype=f32 +blk.10.hc_attn_base.weight cast dtype=f32 +blk.10.hc_attn_fn.weight cast dtype=f32 +blk.10.hc_attn_scale.weight cast dtype=f32 +blk.10.hc_ffn_base.weight cast dtype=f32 +blk.10.hc_ffn_fn.weight cast dtype=f32 +blk.10.hc_ffn_scale.weight cast dtype=f32 +blk.11.attn_kv.weight ggml type=q6_K +blk.11.attn_kv_a_norm.weight cast dtype=f32 +blk.11.attn_norm.weight cast dtype=f32 +blk.11.attn_output_a.g0.weight ggml type=q6_K +blk.11.attn_output_a.g1.weight ggml type=q6_K +blk.11.attn_output_a.g2.weight ggml type=q6_K +blk.11.attn_output_a.g3.weight ggml type=q6_K +blk.11.attn_output_a.g4.weight ggml type=q6_K +blk.11.attn_output_a.g5.weight ggml type=q6_K +blk.11.attn_output_a.g6.weight ggml type=q6_K +blk.11.attn_output_a.g7.weight ggml type=q6_K +blk.11.attn_output_b.weight ggml type=q6_K +blk.11.attn_q_a.weight ggml type=q6_K +blk.11.attn_q_a_norm.weight cast dtype=f32 +blk.11.attn_q_b.weight ggml type=q6_K +blk.11.attn_sinks.weight cast dtype=f32 +blk.11.ffn_down_exps.*.weight ggml type=iq1_s +blk.11.ffn_down_shexp.weight ggml type=q6_K +blk.11.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.11.ffn_gate_up_shexp.weight ggml type=q6_K +blk.11.ffn_norm.weight cast dtype=f32 +blk.11.glm_router.correction cast dtype=f32 +blk.11.glm_router.weight cast dtype=f32 +blk.11.hc_attn_base.weight cast dtype=f32 +blk.11.hc_attn_fn.weight cast dtype=f32 +blk.11.hc_attn_scale.weight cast dtype=f32 +blk.11.hc_ffn_base.weight cast dtype=f32 +blk.11.hc_ffn_fn.weight cast dtype=f32 +blk.11.hc_ffn_scale.weight cast dtype=f32 +blk.12.attn_kv.weight ggml type=q6_K +blk.12.attn_kv_a_norm.weight cast dtype=f32 +blk.12.attn_norm.weight cast dtype=f32 +blk.12.attn_output_a.g0.weight ggml type=q6_K +blk.12.attn_output_a.g1.weight ggml type=q6_K +blk.12.attn_output_a.g2.weight ggml type=q6_K +blk.12.attn_output_a.g3.weight ggml type=q6_K +blk.12.attn_output_a.g4.weight ggml type=q6_K +blk.12.attn_output_a.g5.weight ggml type=q6_K +blk.12.attn_output_a.g6.weight ggml type=q6_K +blk.12.attn_output_a.g7.weight ggml type=q6_K +blk.12.attn_output_b.weight ggml type=q6_K +blk.12.attn_q_a.weight ggml type=q6_K +blk.12.attn_q_a_norm.weight cast dtype=f32 +blk.12.attn_q_b.weight ggml type=q6_K +blk.12.attn_sinks.weight cast dtype=f32 +blk.12.ffn_down_exps.*.weight ggml type=iq1_s +blk.12.ffn_down_shexp.weight ggml type=q6_K +blk.12.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.12.ffn_gate_up_shexp.weight ggml type=q6_K +blk.12.ffn_norm.weight cast dtype=f32 +blk.12.glm_router.correction cast dtype=f32 +blk.12.glm_router.weight cast dtype=f32 +blk.12.hc_attn_base.weight cast dtype=f32 +blk.12.hc_attn_fn.weight cast dtype=f32 +blk.12.hc_attn_scale.weight cast dtype=f32 +blk.12.hc_ffn_base.weight cast dtype=f32 +blk.12.hc_ffn_fn.weight cast dtype=f32 +blk.12.hc_ffn_scale.weight cast dtype=f32 +blk.13.attn_kv.weight ggml type=q6_K +blk.13.attn_kv_a_norm.weight cast dtype=f32 +blk.13.attn_norm.weight cast dtype=f32 +blk.13.attn_output_a.g0.weight ggml type=q6_K +blk.13.attn_output_a.g1.weight ggml type=q6_K +blk.13.attn_output_a.g2.weight ggml type=q6_K +blk.13.attn_output_a.g3.weight ggml type=q6_K +blk.13.attn_output_a.g4.weight ggml type=q6_K +blk.13.attn_output_a.g5.weight ggml type=q6_K +blk.13.attn_output_a.g6.weight ggml type=q6_K +blk.13.attn_output_a.g7.weight ggml type=q6_K +blk.13.attn_output_b.weight ggml type=q6_K +blk.13.attn_q_a.weight ggml type=q6_K +blk.13.attn_q_a_norm.weight cast dtype=f32 +blk.13.attn_q_b.weight ggml type=q6_K +blk.13.attn_sinks.weight cast dtype=f32 +blk.13.ffn_down_exps.*.weight ggml type=iq1_s +blk.13.ffn_down_shexp.weight ggml type=q6_K +blk.13.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.13.ffn_gate_up_shexp.weight ggml type=q6_K +blk.13.ffn_norm.weight cast dtype=f32 +blk.13.glm_router.correction cast dtype=f32 +blk.13.glm_router.weight cast dtype=f32 +blk.13.hc_attn_base.weight cast dtype=f32 +blk.13.hc_attn_fn.weight cast dtype=f32 +blk.13.hc_attn_scale.weight cast dtype=f32 +blk.13.hc_ffn_base.weight cast dtype=f32 +blk.13.hc_ffn_fn.weight cast dtype=f32 +blk.13.hc_ffn_scale.weight cast dtype=f32 +blk.14.attn_compressor_kvg.weight cast dtype=bf16 +blk.14.attn_compressor_norm.weight cast dtype=f32 +blk.14.attn_kv.weight ggml type=q6_K +blk.14.attn_kv_a_norm.weight cast dtype=f32 +blk.14.attn_norm.weight cast dtype=f32 +blk.14.attn_output_a.g0.weight ggml type=q6_K +blk.14.attn_output_a.g1.weight ggml type=q6_K +blk.14.attn_output_a.g2.weight ggml type=q6_K +blk.14.attn_output_a.g3.weight ggml type=q6_K +blk.14.attn_output_a.g4.weight ggml type=q6_K +blk.14.attn_output_a.g5.weight ggml type=q6_K +blk.14.attn_output_a.g6.weight ggml type=q6_K +blk.14.attn_output_a.g7.weight ggml type=q6_K +blk.14.attn_output_b.weight ggml type=q6_K +blk.14.attn_q_a.weight ggml type=q6_K +blk.14.attn_q_a_norm.weight cast dtype=f32 +blk.14.attn_q_b.weight ggml type=q6_K +blk.14.attn_sinks.weight cast dtype=f32 +blk.14.engram_gate.weight cast dtype=f32 +blk.14.engram_kv.weight ggml type=q6_K +blk.14.ffn_down_exps.*.weight ggml type=iq1_s +blk.14.ffn_down_shexp.weight ggml type=q8_0 +blk.14.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.14.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.14.ffn_norm.weight cast dtype=f32 +blk.14.glm_router.correction cast dtype=f32 +blk.14.glm_router.weight cast dtype=f32 +blk.14.hc_attn_base.weight cast dtype=f32 +blk.14.hc_attn_fn.weight cast dtype=f32 +blk.14.hc_attn_scale.weight cast dtype=f32 +blk.14.hc_ffn_base.weight cast dtype=f32 +blk.14.hc_ffn_fn.weight cast dtype=f32 +blk.14.hc_ffn_scale.weight cast dtype=f32 +blk.14.indexer.attn_k.weight cast dtype=bf16 +blk.14.indexer.attn_q_b.weight cast dtype=bf16 +blk.14.indexer.k_norm.weight cast dtype=f32 +blk.14.indexer.proj.weight cast dtype=bf16 +blk.15.attn_kv.weight ggml type=q6_K +blk.15.attn_kv_a_norm.weight cast dtype=f32 +blk.15.attn_norm.weight cast dtype=f32 +blk.15.attn_output_a.g0.weight ggml type=q6_K +blk.15.attn_output_a.g1.weight ggml type=q6_K +blk.15.attn_output_a.g2.weight ggml type=q6_K +blk.15.attn_output_a.g3.weight ggml type=q6_K +blk.15.attn_output_a.g4.weight ggml type=q6_K +blk.15.attn_output_a.g5.weight ggml type=q6_K +blk.15.attn_output_a.g6.weight ggml type=q6_K +blk.15.attn_output_a.g7.weight ggml type=q6_K +blk.15.attn_output_b.weight ggml type=q6_K +blk.15.attn_q_a.weight ggml type=q6_K +blk.15.attn_q_a_norm.weight cast dtype=f32 +blk.15.attn_q_b.weight ggml type=q6_K +blk.15.attn_sinks.weight cast dtype=f32 +blk.15.ffn_down_exps.*.weight ggml type=iq1_s +blk.15.ffn_down_shexp.weight ggml type=q8_0 +blk.15.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.15.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.15.ffn_norm.weight cast dtype=f32 +blk.15.glm_router.correction cast dtype=f32 +blk.15.glm_router.weight cast dtype=f32 +blk.15.hc_attn_base.weight cast dtype=f32 +blk.15.hc_attn_fn.weight cast dtype=f32 +blk.15.hc_attn_scale.weight cast dtype=f32 +blk.15.hc_ffn_base.weight cast dtype=f32 +blk.15.hc_ffn_fn.weight cast dtype=f32 +blk.15.hc_ffn_scale.weight cast dtype=f32 +blk.16.attn_kv.weight ggml type=q6_K +blk.16.attn_kv_a_norm.weight cast dtype=f32 +blk.16.attn_norm.weight cast dtype=f32 +blk.16.attn_output_a.g0.weight ggml type=q6_K +blk.16.attn_output_a.g1.weight ggml type=q6_K +blk.16.attn_output_a.g2.weight ggml type=q6_K +blk.16.attn_output_a.g3.weight ggml type=q6_K +blk.16.attn_output_a.g4.weight ggml type=q6_K +blk.16.attn_output_a.g5.weight ggml type=q6_K +blk.16.attn_output_a.g6.weight ggml type=q6_K +blk.16.attn_output_a.g7.weight ggml type=q6_K +blk.16.attn_output_b.weight ggml type=q6_K +blk.16.attn_q_a.weight ggml type=q6_K +blk.16.attn_q_a_norm.weight cast dtype=f32 +blk.16.attn_q_b.weight ggml type=q6_K +blk.16.attn_sinks.weight cast dtype=f32 +blk.16.ffn_down_exps.*.weight ggml type=iq1_s +blk.16.ffn_down_shexp.weight ggml type=q8_0 +blk.16.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.16.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.16.ffn_norm.weight cast dtype=f32 +blk.16.glm_router.correction cast dtype=f32 +blk.16.glm_router.weight cast dtype=f32 +blk.16.hc_attn_base.weight cast dtype=f32 +blk.16.hc_attn_fn.weight cast dtype=f32 +blk.16.hc_attn_scale.weight cast dtype=f32 +blk.16.hc_ffn_base.weight cast dtype=f32 +blk.16.hc_ffn_fn.weight cast dtype=f32 +blk.16.hc_ffn_scale.weight cast dtype=f32 +blk.17.attn_kv.weight ggml type=q6_K +blk.17.attn_kv_a_norm.weight cast dtype=f32 +blk.17.attn_norm.weight cast dtype=f32 +blk.17.attn_output_a.g0.weight ggml type=q6_K +blk.17.attn_output_a.g1.weight ggml type=q6_K +blk.17.attn_output_a.g2.weight ggml type=q6_K +blk.17.attn_output_a.g3.weight ggml type=q6_K +blk.17.attn_output_a.g4.weight ggml type=q6_K +blk.17.attn_output_a.g5.weight ggml type=q6_K +blk.17.attn_output_a.g6.weight ggml type=q6_K +blk.17.attn_output_a.g7.weight ggml type=q6_K +blk.17.attn_output_b.weight ggml type=q6_K +blk.17.attn_q_a.weight ggml type=q6_K +blk.17.attn_q_a_norm.weight cast dtype=f32 +blk.17.attn_q_b.weight ggml type=q6_K +blk.17.attn_sinks.weight cast dtype=f32 +blk.17.ffn_down_exps.*.weight ggml type=iq1_s +blk.17.ffn_down_shexp.weight ggml type=q8_0 +blk.17.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.17.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.17.ffn_norm.weight cast dtype=f32 +blk.17.glm_router.correction cast dtype=f32 +blk.17.glm_router.weight cast dtype=f32 +blk.17.hc_attn_base.weight cast dtype=f32 +blk.17.hc_attn_fn.weight cast dtype=f32 +blk.17.hc_attn_scale.weight cast dtype=f32 +blk.17.hc_ffn_base.weight cast dtype=f32 +blk.17.hc_ffn_fn.weight cast dtype=f32 +blk.17.hc_ffn_scale.weight cast dtype=f32 +blk.18.attn_kv.weight ggml type=q6_K +blk.18.attn_kv_a_norm.weight cast dtype=f32 +blk.18.attn_norm.weight cast dtype=f32 +blk.18.attn_output_a.g0.weight ggml type=q6_K +blk.18.attn_output_a.g1.weight ggml type=q6_K +blk.18.attn_output_a.g2.weight ggml type=q6_K +blk.18.attn_output_a.g3.weight ggml type=q6_K +blk.18.attn_output_a.g4.weight ggml type=q6_K +blk.18.attn_output_a.g5.weight ggml type=q6_K +blk.18.attn_output_a.g6.weight ggml type=q6_K +blk.18.attn_output_a.g7.weight ggml type=q6_K +blk.18.attn_output_b.weight ggml type=q6_K +blk.18.attn_q_a.weight ggml type=q6_K +blk.18.attn_q_a_norm.weight cast dtype=f32 +blk.18.attn_q_b.weight ggml type=q6_K +blk.18.attn_sinks.weight cast dtype=f32 +blk.18.ffn_down_exps.*.weight ggml type=iq1_s +blk.18.ffn_down_shexp.weight ggml type=q8_0 +blk.18.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.18.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.18.ffn_norm.weight cast dtype=f32 +blk.18.glm_router.correction cast dtype=f32 +blk.18.glm_router.weight cast dtype=f32 +blk.18.hc_attn_base.weight cast dtype=f32 +blk.18.hc_attn_fn.weight cast dtype=f32 +blk.18.hc_attn_scale.weight cast dtype=f32 +blk.18.hc_ffn_base.weight cast dtype=f32 +blk.18.hc_ffn_fn.weight cast dtype=f32 +blk.18.hc_ffn_scale.weight cast dtype=f32 +blk.19.attn_kv.weight ggml type=q6_K +blk.19.attn_kv_a_norm.weight cast dtype=f32 +blk.19.attn_norm.weight cast dtype=f32 +blk.19.attn_output_a.g0.weight ggml type=q6_K +blk.19.attn_output_a.g1.weight ggml type=q6_K +blk.19.attn_output_a.g2.weight ggml type=q6_K +blk.19.attn_output_a.g3.weight ggml type=q6_K +blk.19.attn_output_a.g4.weight ggml type=q6_K +blk.19.attn_output_a.g5.weight ggml type=q6_K +blk.19.attn_output_a.g6.weight ggml type=q6_K +blk.19.attn_output_a.g7.weight ggml type=q6_K +blk.19.attn_output_b.weight ggml type=q6_K +blk.19.attn_q_a.weight ggml type=q6_K +blk.19.attn_q_a_norm.weight cast dtype=f32 +blk.19.attn_q_b.weight ggml type=q6_K +blk.19.attn_sinks.weight cast dtype=f32 +blk.19.ffn_down_exps.*.weight ggml type=iq1_s +blk.19.ffn_down_shexp.weight ggml type=q8_0 +blk.19.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.19.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.19.ffn_norm.weight cast dtype=f32 +blk.19.glm_router.correction cast dtype=f32 +blk.19.glm_router.weight cast dtype=f32 +blk.19.hc_attn_base.weight cast dtype=f32 +blk.19.hc_attn_fn.weight cast dtype=f32 +blk.19.hc_attn_scale.weight cast dtype=f32 +blk.19.hc_ffn_base.weight cast dtype=f32 +blk.19.hc_ffn_fn.weight cast dtype=f32 +blk.19.hc_ffn_scale.weight cast dtype=f32 +blk.20.attn_compressor_kv.weight cast dtype=bf16 +blk.20.attn_compressor_norm.weight cast dtype=f32 +blk.20.attn_kv.weight ggml type=q6_K +blk.20.attn_kv_a_norm.weight cast dtype=f32 +blk.20.attn_norm.weight cast dtype=f32 +blk.20.attn_output_a.g0.weight ggml type=q6_K +blk.20.attn_output_a.g1.weight ggml type=q6_K +blk.20.attn_output_a.g2.weight ggml type=q6_K +blk.20.attn_output_a.g3.weight ggml type=q6_K +blk.20.attn_output_a.g4.weight ggml type=q6_K +blk.20.attn_output_a.g5.weight ggml type=q6_K +blk.20.attn_output_a.g6.weight ggml type=q6_K +blk.20.attn_output_a.g7.weight ggml type=q6_K +blk.20.attn_output_b.weight ggml type=q6_K +blk.20.attn_q_a.weight ggml type=q6_K +blk.20.attn_q_a_norm.weight cast dtype=f32 +blk.20.attn_q_b.weight ggml type=q6_K +blk.20.attn_sinks.weight cast dtype=f32 +blk.20.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.20.ffn_down_shexp.weight ggml type=q8_0 +blk.20.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.20.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.20.ffn_norm.weight cast dtype=f32 +blk.20.glm_router.correction cast dtype=f32 +blk.20.glm_router.weight cast dtype=f32 +blk.20.hc_attn_base.weight cast dtype=f32 +blk.20.hc_attn_fn.weight cast dtype=f32 +blk.20.hc_attn_scale.weight cast dtype=f32 +blk.20.hc_ffn_base.weight cast dtype=f32 +blk.20.hc_ffn_fn.weight cast dtype=f32 +blk.20.hc_ffn_scale.weight cast dtype=f32 +blk.20.indexer.attn_k.weight cast dtype=bf16 +blk.20.indexer.attn_q_b.weight cast dtype=bf16 +blk.20.indexer.k_norm.weight cast dtype=f32 +blk.20.indexer.proj.weight cast dtype=bf16 +blk.21.attn_kv.weight ggml type=q6_K +blk.21.attn_kv_a_norm.weight cast dtype=f32 +blk.21.attn_norm.weight cast dtype=f32 +blk.21.attn_output_a.g0.weight ggml type=q6_K +blk.21.attn_output_a.g1.weight ggml type=q6_K +blk.21.attn_output_a.g2.weight ggml type=q6_K +blk.21.attn_output_a.g3.weight ggml type=q6_K +blk.21.attn_output_a.g4.weight ggml type=q6_K +blk.21.attn_output_a.g5.weight ggml type=q6_K +blk.21.attn_output_a.g6.weight ggml type=q6_K +blk.21.attn_output_a.g7.weight ggml type=q6_K +blk.21.attn_output_b.weight ggml type=q6_K +blk.21.attn_q_a.weight ggml type=q6_K +blk.21.attn_q_a_norm.weight cast dtype=f32 +blk.21.attn_q_b.weight ggml type=q6_K +blk.21.attn_sinks.weight cast dtype=f32 +blk.21.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.21.ffn_down_shexp.weight ggml type=q8_0 +blk.21.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.21.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.21.ffn_norm.weight cast dtype=f32 +blk.21.glm_router.correction cast dtype=f32 +blk.21.glm_router.weight cast dtype=f32 +blk.21.hc_attn_base.weight cast dtype=f32 +blk.21.hc_attn_fn.weight cast dtype=f32 +blk.21.hc_attn_scale.weight cast dtype=f32 +blk.21.hc_ffn_base.weight cast dtype=f32 +blk.21.hc_ffn_fn.weight cast dtype=f32 +blk.21.hc_ffn_scale.weight cast dtype=f32 +blk.22.attn_kv.weight ggml type=q6_K +blk.22.attn_kv_a_norm.weight cast dtype=f32 +blk.22.attn_norm.weight cast dtype=f32 +blk.22.attn_output_a.g0.weight ggml type=q6_K +blk.22.attn_output_a.g1.weight ggml type=q6_K +blk.22.attn_output_a.g2.weight ggml type=q6_K +blk.22.attn_output_a.g3.weight ggml type=q6_K +blk.22.attn_output_a.g4.weight ggml type=q6_K +blk.22.attn_output_a.g5.weight ggml type=q6_K +blk.22.attn_output_a.g6.weight ggml type=q6_K +blk.22.attn_output_a.g7.weight ggml type=q6_K +blk.22.attn_output_b.weight ggml type=q6_K +blk.22.attn_q_a.weight ggml type=q6_K +blk.22.attn_q_a_norm.weight cast dtype=f32 +blk.22.attn_q_b.weight ggml type=q6_K +blk.22.attn_sinks.weight cast dtype=f32 +blk.22.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.22.ffn_down_shexp.weight ggml type=q8_0 +blk.22.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.22.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.22.ffn_norm.weight cast dtype=f32 +blk.22.glm_router.correction cast dtype=f32 +blk.22.glm_router.weight cast dtype=f32 +blk.22.hc_attn_base.weight cast dtype=f32 +blk.22.hc_attn_fn.weight cast dtype=f32 +blk.22.hc_attn_scale.weight cast dtype=f32 +blk.22.hc_ffn_base.weight cast dtype=f32 +blk.22.hc_ffn_fn.weight cast dtype=f32 +blk.22.hc_ffn_scale.weight cast dtype=f32 +blk.23.attn_kv.weight ggml type=q6_K +blk.23.attn_kv_a_norm.weight cast dtype=f32 +blk.23.attn_norm.weight cast dtype=f32 +blk.23.attn_output_a.g0.weight ggml type=q6_K +blk.23.attn_output_a.g1.weight ggml type=q6_K +blk.23.attn_output_a.g2.weight ggml type=q6_K +blk.23.attn_output_a.g3.weight ggml type=q6_K +blk.23.attn_output_a.g4.weight ggml type=q6_K +blk.23.attn_output_a.g5.weight ggml type=q6_K +blk.23.attn_output_a.g6.weight ggml type=q6_K +blk.23.attn_output_a.g7.weight ggml type=q6_K +blk.23.attn_output_b.weight ggml type=q6_K +blk.23.attn_q_a.weight ggml type=q6_K +blk.23.attn_q_a_norm.weight cast dtype=f32 +blk.23.attn_q_b.weight ggml type=q6_K +blk.23.attn_sinks.weight cast dtype=f32 +blk.23.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.23.ffn_down_shexp.weight ggml type=q8_0 +blk.23.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.23.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.23.ffn_norm.weight cast dtype=f32 +blk.23.glm_router.correction cast dtype=f32 +blk.23.glm_router.weight cast dtype=f32 +blk.23.hc_attn_base.weight cast dtype=f32 +blk.23.hc_attn_fn.weight cast dtype=f32 +blk.23.hc_attn_scale.weight cast dtype=f32 +blk.23.hc_ffn_base.weight cast dtype=f32 +blk.23.hc_ffn_fn.weight cast dtype=f32 +blk.23.hc_ffn_scale.weight cast dtype=f32 +blk.24.attn_kv.weight ggml type=q6_K +blk.24.attn_kv_a_norm.weight cast dtype=f32 +blk.24.attn_norm.weight cast dtype=f32 +blk.24.attn_output_a.g0.weight ggml type=q6_K +blk.24.attn_output_a.g1.weight ggml type=q6_K +blk.24.attn_output_a.g2.weight ggml type=q6_K +blk.24.attn_output_a.g3.weight ggml type=q6_K +blk.24.attn_output_a.g4.weight ggml type=q6_K +blk.24.attn_output_a.g5.weight ggml type=q6_K +blk.24.attn_output_a.g6.weight ggml type=q6_K +blk.24.attn_output_a.g7.weight ggml type=q6_K +blk.24.attn_output_b.weight ggml type=q6_K +blk.24.attn_q_a.weight ggml type=q6_K +blk.24.attn_q_a_norm.weight cast dtype=f32 +blk.24.attn_q_b.weight ggml type=q6_K +blk.24.attn_sinks.weight cast dtype=f32 +blk.24.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.24.ffn_down_shexp.weight ggml type=q8_0 +blk.24.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.24.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.24.ffn_norm.weight cast dtype=f32 +blk.24.glm_router.correction cast dtype=f32 +blk.24.glm_router.weight cast dtype=f32 +blk.24.hc_attn_base.weight cast dtype=f32 +blk.24.hc_attn_fn.weight cast dtype=f32 +blk.24.hc_attn_scale.weight cast dtype=f32 +blk.24.hc_ffn_base.weight cast dtype=f32 +blk.24.hc_ffn_fn.weight cast dtype=f32 +blk.24.hc_ffn_scale.weight cast dtype=f32 +blk.24.indexer.attn_q_b.weight cast dtype=bf16 +blk.24.indexer.proj.weight cast dtype=bf16 +blk.25.attn_kv.weight ggml type=q6_K +blk.25.attn_kv_a_norm.weight cast dtype=f32 +blk.25.attn_norm.weight cast dtype=f32 +blk.25.attn_output_a.g0.weight ggml type=q6_K +blk.25.attn_output_a.g1.weight ggml type=q6_K +blk.25.attn_output_a.g2.weight ggml type=q6_K +blk.25.attn_output_a.g3.weight ggml type=q6_K +blk.25.attn_output_a.g4.weight ggml type=q6_K +blk.25.attn_output_a.g5.weight ggml type=q6_K +blk.25.attn_output_a.g6.weight ggml type=q6_K +blk.25.attn_output_a.g7.weight ggml type=q6_K +blk.25.attn_output_b.weight ggml type=q6_K +blk.25.attn_q_a.weight ggml type=q6_K +blk.25.attn_q_a_norm.weight cast dtype=f32 +blk.25.attn_q_b.weight ggml type=q6_K +blk.25.attn_sinks.weight cast dtype=f32 +blk.25.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.25.ffn_down_shexp.weight ggml type=q8_0 +blk.25.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.25.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.25.ffn_norm.weight cast dtype=f32 +blk.25.glm_router.correction cast dtype=f32 +blk.25.glm_router.weight cast dtype=f32 +blk.25.hc_attn_base.weight cast dtype=f32 +blk.25.hc_attn_fn.weight cast dtype=f32 +blk.25.hc_attn_scale.weight cast dtype=f32 +blk.25.hc_ffn_base.weight cast dtype=f32 +blk.25.hc_ffn_fn.weight cast dtype=f32 +blk.25.hc_ffn_scale.weight cast dtype=f32 +blk.26.attn_kv.weight ggml type=q6_K +blk.26.attn_kv_a_norm.weight cast dtype=f32 +blk.26.attn_norm.weight cast dtype=f32 +blk.26.attn_output_a.g0.weight ggml type=q6_K +blk.26.attn_output_a.g1.weight ggml type=q6_K +blk.26.attn_output_a.g2.weight ggml type=q6_K +blk.26.attn_output_a.g3.weight ggml type=q6_K +blk.26.attn_output_a.g4.weight ggml type=q6_K +blk.26.attn_output_a.g5.weight ggml type=q6_K +blk.26.attn_output_a.g6.weight ggml type=q6_K +blk.26.attn_output_a.g7.weight ggml type=q6_K +blk.26.attn_output_b.weight ggml type=q6_K +blk.26.attn_q_a.weight ggml type=q6_K +blk.26.attn_q_a_norm.weight cast dtype=f32 +blk.26.attn_q_b.weight ggml type=q6_K +blk.26.attn_sinks.weight cast dtype=f32 +blk.26.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.26.ffn_down_shexp.weight ggml type=q8_0 +blk.26.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.26.ffn_gate_up_shexp.weight ggml type=q8_0 +blk.26.ffn_norm.weight cast dtype=f32 +blk.26.glm_router.correction cast dtype=f32 +blk.26.glm_router.weight cast dtype=f32 +blk.26.hc_attn_base.weight cast dtype=f32 +blk.26.hc_attn_fn.weight cast dtype=f32 +blk.26.hc_attn_scale.weight cast dtype=f32 +blk.26.hc_ffn_base.weight cast dtype=f32 +blk.26.hc_ffn_fn.weight cast dtype=f32 +blk.26.hc_ffn_scale.weight cast dtype=f32 +blk.27.attn_kv.weight ggml type=q5_K +blk.27.attn_kv_a_norm.weight cast dtype=f32 +blk.27.attn_norm.weight cast dtype=f32 +blk.27.attn_output_a.g0.weight ggml type=q5_K +blk.27.attn_output_a.g1.weight ggml type=q5_K +blk.27.attn_output_a.g2.weight ggml type=q5_K +blk.27.attn_output_a.g3.weight ggml type=q5_K +blk.27.attn_output_a.g4.weight ggml type=q5_K +blk.27.attn_output_a.g5.weight ggml type=q5_K +blk.27.attn_output_a.g6.weight ggml type=q5_K +blk.27.attn_output_a.g7.weight ggml type=q5_K +blk.27.attn_output_b.weight ggml type=q5_K +blk.27.attn_q_a.weight ggml type=q5_K +blk.27.attn_q_a_norm.weight cast dtype=f32 +blk.27.attn_q_b.weight ggml type=q5_K +blk.27.attn_sinks.weight cast dtype=f32 +blk.27.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.27.ffn_down_shexp.weight ggml type=q6_K +blk.27.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.27.ffn_gate_up_shexp.weight ggml type=q6_K +blk.27.ffn_norm.weight cast dtype=f32 +blk.27.glm_router.correction cast dtype=f32 +blk.27.glm_router.weight cast dtype=f32 +blk.27.hc_attn_base.weight cast dtype=f32 +blk.27.hc_attn_fn.weight cast dtype=f32 +blk.27.hc_attn_scale.weight cast dtype=f32 +blk.27.hc_ffn_base.weight cast dtype=f32 +blk.27.hc_ffn_fn.weight cast dtype=f32 +blk.27.hc_ffn_scale.weight cast dtype=f32 +blk.28.attn_kv.weight ggml type=q5_K +blk.28.attn_kv_a_norm.weight cast dtype=f32 +blk.28.attn_norm.weight cast dtype=f32 +blk.28.attn_output_a.g0.weight ggml type=q5_K +blk.28.attn_output_a.g1.weight ggml type=q5_K +blk.28.attn_output_a.g2.weight ggml type=q5_K +blk.28.attn_output_a.g3.weight ggml type=q5_K +blk.28.attn_output_a.g4.weight ggml type=q5_K +blk.28.attn_output_a.g5.weight ggml type=q5_K +blk.28.attn_output_a.g6.weight ggml type=q5_K +blk.28.attn_output_a.g7.weight ggml type=q5_K +blk.28.attn_output_b.weight ggml type=q5_K +blk.28.attn_q_a.weight ggml type=q5_K +blk.28.attn_q_a_norm.weight cast dtype=f32 +blk.28.attn_q_b.weight ggml type=q5_K +blk.28.attn_sinks.weight cast dtype=f32 +blk.28.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.28.ffn_down_shexp.weight ggml type=q6_K +blk.28.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.28.ffn_gate_up_shexp.weight ggml type=q6_K +blk.28.ffn_norm.weight cast dtype=f32 +blk.28.glm_router.correction cast dtype=f32 +blk.28.glm_router.weight cast dtype=f32 +blk.28.hc_attn_base.weight cast dtype=f32 +blk.28.hc_attn_fn.weight cast dtype=f32 +blk.28.hc_attn_scale.weight cast dtype=f32 +blk.28.hc_ffn_base.weight cast dtype=f32 +blk.28.hc_ffn_fn.weight cast dtype=f32 +blk.28.hc_ffn_scale.weight cast dtype=f32 +blk.28.indexer.attn_q_b.weight cast dtype=bf16 +blk.28.indexer.proj.weight cast dtype=bf16 +blk.29.attn_kv.weight ggml type=q5_K +blk.29.attn_kv_a_norm.weight cast dtype=f32 +blk.29.attn_norm.weight cast dtype=f32 +blk.29.attn_output_a.g0.weight ggml type=q5_K +blk.29.attn_output_a.g1.weight ggml type=q5_K +blk.29.attn_output_a.g2.weight ggml type=q5_K +blk.29.attn_output_a.g3.weight ggml type=q5_K +blk.29.attn_output_a.g4.weight ggml type=q5_K +blk.29.attn_output_a.g5.weight ggml type=q5_K +blk.29.attn_output_a.g6.weight ggml type=q5_K +blk.29.attn_output_a.g7.weight ggml type=q5_K +blk.29.attn_output_b.weight ggml type=q5_K +blk.29.attn_q_a.weight ggml type=q5_K +blk.29.attn_q_a_norm.weight cast dtype=f32 +blk.29.attn_q_b.weight ggml type=q5_K +blk.29.attn_sinks.weight cast dtype=f32 +blk.29.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.29.ffn_down_shexp.weight ggml type=q6_K +blk.29.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.29.ffn_gate_up_shexp.weight ggml type=q6_K +blk.29.ffn_norm.weight cast dtype=f32 +blk.29.glm_router.correction cast dtype=f32 +blk.29.glm_router.weight cast dtype=f32 +blk.29.hc_attn_base.weight cast dtype=f32 +blk.29.hc_attn_fn.weight cast dtype=f32 +blk.29.hc_attn_scale.weight cast dtype=f32 +blk.29.hc_ffn_base.weight cast dtype=f32 +blk.29.hc_ffn_fn.weight cast dtype=f32 +blk.29.hc_ffn_scale.weight cast dtype=f32 +blk.30.attn_kv.weight ggml type=q5_K +blk.30.attn_kv_a_norm.weight cast dtype=f32 +blk.30.attn_norm.weight cast dtype=f32 +blk.30.attn_output_a.g0.weight ggml type=q5_K +blk.30.attn_output_a.g1.weight ggml type=q5_K +blk.30.attn_output_a.g2.weight ggml type=q5_K +blk.30.attn_output_a.g3.weight ggml type=q5_K +blk.30.attn_output_a.g4.weight ggml type=q5_K +blk.30.attn_output_a.g5.weight ggml type=q5_K +blk.30.attn_output_a.g6.weight ggml type=q5_K +blk.30.attn_output_a.g7.weight ggml type=q5_K +blk.30.attn_output_b.weight ggml type=q5_K +blk.30.attn_q_a.weight ggml type=q5_K +blk.30.attn_q_a_norm.weight cast dtype=f32 +blk.30.attn_q_b.weight ggml type=q5_K +blk.30.attn_sinks.weight cast dtype=f32 +blk.30.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.30.ffn_down_shexp.weight ggml type=q6_K +blk.30.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.30.ffn_gate_up_shexp.weight ggml type=q6_K +blk.30.ffn_norm.weight cast dtype=f32 +blk.30.glm_router.correction cast dtype=f32 +blk.30.glm_router.weight cast dtype=f32 +blk.30.hc_attn_base.weight cast dtype=f32 +blk.30.hc_attn_fn.weight cast dtype=f32 +blk.30.hc_attn_scale.weight cast dtype=f32 +blk.30.hc_ffn_base.weight cast dtype=f32 +blk.30.hc_ffn_fn.weight cast dtype=f32 +blk.30.hc_ffn_scale.weight cast dtype=f32 +blk.31.attn_kv.weight ggml type=q5_K +blk.31.attn_kv_a_norm.weight cast dtype=f32 +blk.31.attn_norm.weight cast dtype=f32 +blk.31.attn_output_a.g0.weight ggml type=q5_K +blk.31.attn_output_a.g1.weight ggml type=q5_K +blk.31.attn_output_a.g2.weight ggml type=q5_K +blk.31.attn_output_a.g3.weight ggml type=q5_K +blk.31.attn_output_a.g4.weight ggml type=q5_K +blk.31.attn_output_a.g5.weight ggml type=q5_K +blk.31.attn_output_a.g6.weight ggml type=q5_K +blk.31.attn_output_a.g7.weight ggml type=q5_K +blk.31.attn_output_b.weight ggml type=q5_K +blk.31.attn_q_a.weight ggml type=q5_K +blk.31.attn_q_a_norm.weight cast dtype=f32 +blk.31.attn_q_b.weight ggml type=q5_K +blk.31.attn_sinks.weight cast dtype=f32 +blk.31.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.31.ffn_down_shexp.weight ggml type=q6_K +blk.31.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.31.ffn_gate_up_shexp.weight ggml type=q6_K +blk.31.ffn_norm.weight cast dtype=f32 +blk.31.glm_router.correction cast dtype=f32 +blk.31.glm_router.weight cast dtype=f32 +blk.31.hc_attn_base.weight cast dtype=f32 +blk.31.hc_attn_fn.weight cast dtype=f32 +blk.31.hc_attn_scale.weight cast dtype=f32 +blk.31.hc_ffn_base.weight cast dtype=f32 +blk.31.hc_ffn_fn.weight cast dtype=f32 +blk.31.hc_ffn_scale.weight cast dtype=f32 +blk.32.attn_kv.weight ggml type=q5_K +blk.32.attn_kv_a_norm.weight cast dtype=f32 +blk.32.attn_norm.weight cast dtype=f32 +blk.32.attn_output_a.g0.weight ggml type=q5_K +blk.32.attn_output_a.g1.weight ggml type=q5_K +blk.32.attn_output_a.g2.weight ggml type=q5_K +blk.32.attn_output_a.g3.weight ggml type=q5_K +blk.32.attn_output_a.g4.weight ggml type=q5_K +blk.32.attn_output_a.g5.weight ggml type=q5_K +blk.32.attn_output_a.g6.weight ggml type=q5_K +blk.32.attn_output_a.g7.weight ggml type=q5_K +blk.32.attn_output_b.weight ggml type=q5_K +blk.32.attn_q_a.weight ggml type=q5_K +blk.32.attn_q_a_norm.weight cast dtype=f32 +blk.32.attn_q_b.weight ggml type=q5_K +blk.32.attn_sinks.weight cast dtype=f32 +blk.32.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.32.ffn_down_shexp.weight ggml type=q6_K +blk.32.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.32.ffn_gate_up_shexp.weight ggml type=q6_K +blk.32.ffn_norm.weight cast dtype=f32 +blk.32.glm_router.correction cast dtype=f32 +blk.32.glm_router.weight cast dtype=f32 +blk.32.hc_attn_base.weight cast dtype=f32 +blk.32.hc_attn_fn.weight cast dtype=f32 +blk.32.hc_attn_scale.weight cast dtype=f32 +blk.32.hc_ffn_base.weight cast dtype=f32 +blk.32.hc_ffn_fn.weight cast dtype=f32 +blk.32.hc_ffn_scale.weight cast dtype=f32 +blk.32.indexer.attn_q_b.weight cast dtype=bf16 +blk.32.indexer.proj.weight cast dtype=bf16 +blk.33.attn_kv.weight ggml type=q5_K +blk.33.attn_kv_a_norm.weight cast dtype=f32 +blk.33.attn_norm.weight cast dtype=f32 +blk.33.attn_output_a.g0.weight ggml type=q5_K +blk.33.attn_output_a.g1.weight ggml type=q5_K +blk.33.attn_output_a.g2.weight ggml type=q5_K +blk.33.attn_output_a.g3.weight ggml type=q5_K +blk.33.attn_output_a.g4.weight ggml type=q5_K +blk.33.attn_output_a.g5.weight ggml type=q5_K +blk.33.attn_output_a.g6.weight ggml type=q5_K +blk.33.attn_output_a.g7.weight ggml type=q5_K +blk.33.attn_output_b.weight ggml type=q5_K +blk.33.attn_q_a.weight ggml type=q5_K +blk.33.attn_q_a_norm.weight cast dtype=f32 +blk.33.attn_q_b.weight ggml type=q5_K +blk.33.attn_sinks.weight cast dtype=f32 +blk.33.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.33.ffn_down_shexp.weight ggml type=q6_K +blk.33.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.33.ffn_gate_up_shexp.weight ggml type=q6_K +blk.33.ffn_norm.weight cast dtype=f32 +blk.33.glm_router.correction cast dtype=f32 +blk.33.glm_router.weight cast dtype=f32 +blk.33.hc_attn_base.weight cast dtype=f32 +blk.33.hc_attn_fn.weight cast dtype=f32 +blk.33.hc_attn_scale.weight cast dtype=f32 +blk.33.hc_ffn_base.weight cast dtype=f32 +blk.33.hc_ffn_fn.weight cast dtype=f32 +blk.33.hc_ffn_scale.weight cast dtype=f32 +blk.34.attn_kv.weight ggml type=q5_K +blk.34.attn_kv_a_norm.weight cast dtype=f32 +blk.34.attn_norm.weight cast dtype=f32 +blk.34.attn_output_a.g0.weight ggml type=q5_K +blk.34.attn_output_a.g1.weight ggml type=q5_K +blk.34.attn_output_a.g2.weight ggml type=q5_K +blk.34.attn_output_a.g3.weight ggml type=q5_K +blk.34.attn_output_a.g4.weight ggml type=q5_K +blk.34.attn_output_a.g5.weight ggml type=q5_K +blk.34.attn_output_a.g6.weight ggml type=q5_K +blk.34.attn_output_a.g7.weight ggml type=q5_K +blk.34.attn_output_b.weight ggml type=q5_K +blk.34.attn_q_a.weight ggml type=q5_K +blk.34.attn_q_a_norm.weight cast dtype=f32 +blk.34.attn_q_b.weight ggml type=q5_K +blk.34.attn_sinks.weight cast dtype=f32 +blk.34.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.34.ffn_down_shexp.weight ggml type=q6_K +blk.34.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.34.ffn_gate_up_shexp.weight ggml type=q6_K +blk.34.ffn_norm.weight cast dtype=f32 +blk.34.glm_router.correction cast dtype=f32 +blk.34.glm_router.weight cast dtype=f32 +blk.34.hc_attn_base.weight cast dtype=f32 +blk.34.hc_attn_fn.weight cast dtype=f32 +blk.34.hc_attn_scale.weight cast dtype=f32 +blk.34.hc_ffn_base.weight cast dtype=f32 +blk.34.hc_ffn_fn.weight cast dtype=f32 +blk.34.hc_ffn_scale.weight cast dtype=f32 +blk.35.attn_kv.weight ggml type=q5_K +blk.35.attn_kv_a_norm.weight cast dtype=f32 +blk.35.attn_norm.weight cast dtype=f32 +blk.35.attn_output_a.g0.weight ggml type=q5_K +blk.35.attn_output_a.g1.weight ggml type=q5_K +blk.35.attn_output_a.g2.weight ggml type=q5_K +blk.35.attn_output_a.g3.weight ggml type=q5_K +blk.35.attn_output_a.g4.weight ggml type=q5_K +blk.35.attn_output_a.g5.weight ggml type=q5_K +blk.35.attn_output_a.g6.weight ggml type=q5_K +blk.35.attn_output_a.g7.weight ggml type=q5_K +blk.35.attn_output_b.weight ggml type=q5_K +blk.35.attn_q_a.weight ggml type=q5_K +blk.35.attn_q_a_norm.weight cast dtype=f32 +blk.35.attn_q_b.weight ggml type=q5_K +blk.35.attn_sinks.weight cast dtype=f32 +blk.35.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.35.ffn_down_shexp.weight ggml type=q6_K +blk.35.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.35.ffn_gate_up_shexp.weight ggml type=q6_K +blk.35.ffn_norm.weight cast dtype=f32 +blk.35.glm_router.correction cast dtype=f32 +blk.35.glm_router.weight cast dtype=f32 +blk.35.hc_attn_base.weight cast dtype=f32 +blk.35.hc_attn_fn.weight cast dtype=f32 +blk.35.hc_attn_scale.weight cast dtype=f32 +blk.35.hc_ffn_base.weight cast dtype=f32 +blk.35.hc_ffn_fn.weight cast dtype=f32 +blk.35.hc_ffn_scale.weight cast dtype=f32 +blk.36.attn_kv.weight ggml type=q5_K +blk.36.attn_kv_a_norm.weight cast dtype=f32 +blk.36.attn_norm.weight cast dtype=f32 +blk.36.attn_output_a.g0.weight ggml type=q5_K +blk.36.attn_output_a.g1.weight ggml type=q5_K +blk.36.attn_output_a.g2.weight ggml type=q5_K +blk.36.attn_output_a.g3.weight ggml type=q5_K +blk.36.attn_output_a.g4.weight ggml type=q5_K +blk.36.attn_output_a.g5.weight ggml type=q5_K +blk.36.attn_output_a.g6.weight ggml type=q5_K +blk.36.attn_output_a.g7.weight ggml type=q5_K +blk.36.attn_output_b.weight ggml type=q5_K +blk.36.attn_q_a.weight ggml type=q5_K +blk.36.attn_q_a_norm.weight cast dtype=f32 +blk.36.attn_q_b.weight ggml type=q5_K +blk.36.attn_sinks.weight cast dtype=f32 +blk.36.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.36.ffn_down_shexp.weight ggml type=q6_K +blk.36.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.36.ffn_gate_up_shexp.weight ggml type=q6_K +blk.36.ffn_norm.weight cast dtype=f32 +blk.36.glm_router.correction cast dtype=f32 +blk.36.glm_router.weight cast dtype=f32 +blk.36.hc_attn_base.weight cast dtype=f32 +blk.36.hc_attn_fn.weight cast dtype=f32 +blk.36.hc_attn_scale.weight cast dtype=f32 +blk.36.hc_ffn_base.weight cast dtype=f32 +blk.36.hc_ffn_fn.weight cast dtype=f32 +blk.36.hc_ffn_scale.weight cast dtype=f32 +blk.36.indexer.attn_q_b.weight cast dtype=bf16 +blk.36.indexer.proj.weight cast dtype=bf16 +blk.37.attn_kv.weight ggml type=q5_K +blk.37.attn_kv_a_norm.weight cast dtype=f32 +blk.37.attn_norm.weight cast dtype=f32 +blk.37.attn_output_a.g0.weight ggml type=q5_K +blk.37.attn_output_a.g1.weight ggml type=q5_K +blk.37.attn_output_a.g2.weight ggml type=q5_K +blk.37.attn_output_a.g3.weight ggml type=q5_K +blk.37.attn_output_a.g4.weight ggml type=q5_K +blk.37.attn_output_a.g5.weight ggml type=q5_K +blk.37.attn_output_a.g6.weight ggml type=q5_K +blk.37.attn_output_a.g7.weight ggml type=q5_K +blk.37.attn_output_b.weight ggml type=q5_K +blk.37.attn_q_a.weight ggml type=q5_K +blk.37.attn_q_a_norm.weight cast dtype=f32 +blk.37.attn_q_b.weight ggml type=q5_K +blk.37.attn_sinks.weight cast dtype=f32 +blk.37.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.37.ffn_down_shexp.weight ggml type=q6_K +blk.37.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.37.ffn_gate_up_shexp.weight ggml type=q6_K +blk.37.ffn_norm.weight cast dtype=f32 +blk.37.glm_router.correction cast dtype=f32 +blk.37.glm_router.weight cast dtype=f32 +blk.37.hc_attn_base.weight cast dtype=f32 +blk.37.hc_attn_fn.weight cast dtype=f32 +blk.37.hc_attn_scale.weight cast dtype=f32 +blk.37.hc_ffn_base.weight cast dtype=f32 +blk.37.hc_ffn_fn.weight cast dtype=f32 +blk.37.hc_ffn_scale.weight cast dtype=f32 +blk.38.attn_kv.weight ggml type=q5_K +blk.38.attn_kv_a_norm.weight cast dtype=f32 +blk.38.attn_norm.weight cast dtype=f32 +blk.38.attn_output_a.g0.weight ggml type=q5_K +blk.38.attn_output_a.g1.weight ggml type=q5_K +blk.38.attn_output_a.g2.weight ggml type=q5_K +blk.38.attn_output_a.g3.weight ggml type=q5_K +blk.38.attn_output_a.g4.weight ggml type=q5_K +blk.38.attn_output_a.g5.weight ggml type=q5_K +blk.38.attn_output_a.g6.weight ggml type=q5_K +blk.38.attn_output_a.g7.weight ggml type=q5_K +blk.38.attn_output_b.weight ggml type=q5_K +blk.38.attn_q_a.weight ggml type=q5_K +blk.38.attn_q_a_norm.weight cast dtype=f32 +blk.38.attn_q_b.weight ggml type=q5_K +blk.38.attn_sinks.weight cast dtype=f32 +blk.38.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.38.ffn_down_shexp.weight ggml type=q6_K +blk.38.ffn_gate_up_exps.*.weight ggml type=iq1_s +blk.38.ffn_gate_up_shexp.weight ggml type=q6_K +blk.38.ffn_norm.weight cast dtype=f32 +blk.38.glm_router.correction cast dtype=f32 +blk.38.glm_router.weight cast dtype=f32 +blk.38.hc_attn_base.weight cast dtype=f32 +blk.38.hc_attn_fn.weight cast dtype=f32 +blk.38.hc_attn_scale.weight cast dtype=f32 +blk.38.hc_ffn_base.weight cast dtype=f32 +blk.38.hc_ffn_fn.weight cast dtype=f32 +blk.38.hc_ffn_scale.weight cast dtype=f32 +blk.39.attn_kv.weight ggml type=q5_K +blk.39.attn_kv_a_norm.weight cast dtype=f32 +blk.39.attn_norm.weight cast dtype=f32 +blk.39.attn_output_a.g0.weight ggml type=q5_K +blk.39.attn_output_a.g1.weight ggml type=q5_K +blk.39.attn_output_a.g2.weight ggml type=q5_K +blk.39.attn_output_a.g3.weight ggml type=q5_K +blk.39.attn_output_a.g4.weight ggml type=q5_K +blk.39.attn_output_a.g5.weight ggml type=q5_K +blk.39.attn_output_a.g6.weight ggml type=q5_K +blk.39.attn_output_a.g7.weight ggml type=q5_K +blk.39.attn_output_b.weight ggml type=q5_K +blk.39.attn_q_a.weight ggml type=q5_K +blk.39.attn_q_a_norm.weight cast dtype=f32 +blk.39.attn_q_b.weight ggml type=q5_K +blk.39.attn_sinks.weight cast dtype=f32 +blk.39.ffn_down_exps.*.weight ggml type=iq2_xxs +blk.39.ffn_down_shexp.weight ggml type=q6_K +blk.39.ffn_gate_up_exps.*.weight ggml type=iq2_xxs +blk.39.ffn_gate_up_shexp.weight ggml type=q6_K +blk.39.ffn_norm.weight cast dtype=f32 +blk.39.glm_router.correction cast dtype=f32 +blk.39.glm_router.weight cast dtype=f32 +blk.39.hc_attn_base.weight cast dtype=f32 +blk.39.hc_attn_fn.weight cast dtype=f32 +blk.39.hc_attn_scale.weight cast dtype=f32 +blk.39.hc_ffn_base.weight cast dtype=f32 +blk.39.hc_ffn_fn.weight cast dtype=f32 +blk.39.hc_ffn_scale.weight cast dtype=f32 +blk.40.attn_kv.weight cast dtype=bf16 +blk.40.attn_kv_a_norm.weight cast dtype=f32 +blk.40.attn_norm.weight cast dtype=f32 +blk.40.attn_output_a.g0.weight cast dtype=bf16 +blk.40.attn_output_a.g1.weight cast dtype=bf16 +blk.40.attn_output_a.g2.weight cast dtype=bf16 +blk.40.attn_output_a.g3.weight cast dtype=bf16 +blk.40.attn_output_a.g4.weight cast dtype=bf16 +blk.40.attn_output_a.g5.weight cast dtype=bf16 +blk.40.attn_output_a.g6.weight cast dtype=bf16 +blk.40.attn_output_a.g7.weight cast dtype=bf16 +blk.40.attn_output_b.weight cast dtype=bf16 +blk.40.attn_q_a.weight cast dtype=bf16 +blk.40.attn_q_a_norm.weight cast dtype=f32 +blk.40.attn_q_b.weight cast dtype=bf16 +blk.40.attn_sinks.weight cast dtype=f32 +blk.40.ffn_down_shexp.weight cast dtype=bf16 +blk.40.ffn_gate_up_shexp.weight cast dtype=bf16 +blk.40.ffn_norm.weight cast dtype=f32 +blk.40.glm_router.correction cast dtype=f32 +blk.40.glm_router.weight cast dtype=f32 +blk.40.hc_attn_base.weight cast dtype=f32 +blk.40.hc_attn_fn.weight cast dtype=f32 +blk.40.hc_attn_scale.weight cast dtype=f32 +blk.40.hc_ffn_base.weight cast dtype=f32 +blk.40.hc_ffn_fn.weight cast dtype=f32 +blk.40.hc_ffn_scale.weight cast dtype=f32 +blk.41.attn_kv.weight cast dtype=bf16 +blk.41.attn_kv_a_norm.weight cast dtype=f32 +blk.41.attn_norm.weight cast dtype=f32 +blk.41.attn_output_a.g0.weight cast dtype=bf16 +blk.41.attn_output_a.g1.weight cast dtype=bf16 +blk.41.attn_output_a.g2.weight cast dtype=bf16 +blk.41.attn_output_a.g3.weight cast dtype=bf16 +blk.41.attn_output_a.g4.weight cast dtype=bf16 +blk.41.attn_output_a.g5.weight cast dtype=bf16 +blk.41.attn_output_a.g6.weight cast dtype=bf16 +blk.41.attn_output_a.g7.weight cast dtype=bf16 +blk.41.attn_output_b.weight cast dtype=bf16 +blk.41.attn_q_a.weight cast dtype=bf16 +blk.41.attn_q_a_norm.weight cast dtype=f32 +blk.41.attn_q_b.weight cast dtype=bf16 +blk.41.attn_sinks.weight cast dtype=f32 +blk.41.ffn_down_shexp.weight cast dtype=bf16 +blk.41.ffn_gate_up_shexp.weight cast dtype=bf16 +blk.41.ffn_norm.weight cast dtype=f32 +blk.41.glm_router.correction cast dtype=f32 +blk.41.glm_router.weight cast dtype=f32 +blk.41.hc_attn_base.weight cast dtype=f32 +blk.41.hc_attn_fn.weight cast dtype=f32 +blk.41.hc_attn_scale.weight cast dtype=f32 +blk.41.hc_ffn_base.weight cast dtype=f32 +blk.41.hc_ffn_fn.weight cast dtype=f32 +blk.41.hc_ffn_scale.weight cast dtype=f32 +blk.42.attn_kv.weight cast dtype=bf16 +blk.42.attn_kv_a_norm.weight cast dtype=f32 +blk.42.attn_norm.weight cast dtype=f32 +blk.42.attn_output_a.g0.weight cast dtype=bf16 +blk.42.attn_output_a.g1.weight cast dtype=bf16 +blk.42.attn_output_a.g2.weight cast dtype=bf16 +blk.42.attn_output_a.g3.weight cast dtype=bf16 +blk.42.attn_output_a.g4.weight cast dtype=bf16 +blk.42.attn_output_a.g5.weight cast dtype=bf16 +blk.42.attn_output_a.g6.weight cast dtype=bf16 +blk.42.attn_output_a.g7.weight cast dtype=bf16 +blk.42.attn_output_b.weight cast dtype=bf16 +blk.42.attn_q_a.weight cast dtype=bf16 +blk.42.attn_q_a_norm.weight cast dtype=f32 +blk.42.attn_q_b.weight cast dtype=bf16 +blk.42.attn_sinks.weight cast dtype=f32 +blk.42.ffn_down_shexp.weight cast dtype=bf16 +blk.42.ffn_gate_up_shexp.weight cast dtype=bf16 +blk.42.ffn_norm.weight cast dtype=f32 +blk.42.glm_router.correction cast dtype=f32 +blk.42.glm_router.weight cast dtype=f32 +blk.42.hc_attn_base.weight cast dtype=f32 +blk.42.hc_attn_fn.weight cast dtype=f32 +blk.42.hc_attn_scale.weight cast dtype=f32 +blk.42.hc_ffn_base.weight cast dtype=f32 +blk.42.hc_ffn_fn.weight cast dtype=f32 +blk.42.hc_ffn_scale.weight cast dtype=f32 diff --git a/docs/GUIDE.md b/docs/GUIDE.md index f7eeb1a9..ed365498 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -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*[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 '{ diff --git a/docs/KERNELS.md b/docs/KERNELS.md index e6c3c96e..4966d301 100644 --- a/docs/KERNELS.md +++ b/docs/KERNELS.md @@ -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 | |---|---| diff --git a/docs/QSA.md b/docs/QSA.md index 07552a48..1e8374e0 100644 --- a/docs/QSA.md +++ b/docs/QSA.md @@ -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 diff --git a/docs/TP4.md b/docs/TP4.md index 1822bb50..a51caa30 100644 --- a/docs/TP4.md +++ b/docs/TP4.md @@ -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 | diff --git a/docs/deepseek41-hf-direct.md b/docs/deepseek41-hf-direct.md new file mode 100644 index 00000000..fdeecf06 --- /dev/null +++ b/docs/deepseek41-hf-direct.md @@ -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 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 --add engram-tables.safetensors \ + --recipe data/recipes/deepseek41-ud-iq1s.recipe \ + --imatrix imatrix-merged.gguf --tokenizer /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). diff --git a/integrations/comfyui/ComfyUI-Radiance-MiniMax/README.md b/integrations/comfyui/ComfyUI-Radiance-MiniMax/README.md index c7938ad7..3a0b477d 100644 --- a/integrations/comfyui/ComfyUI-Radiance-MiniMax/README.md +++ b/integrations/comfyui/ComfyUI-Radiance-MiniMax/README.md @@ -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 diff --git a/integrations/comfyui/ComfyUI-Radiance-MiniMax/radiance_node.py b/integrations/comfyui/ComfyUI-Radiance-MiniMax/radiance_node.py index 7448fab2..82dd4901 100644 --- a/integrations/comfyui/ComfyUI-Radiance-MiniMax/radiance_node.py +++ b/integrations/comfyui/ComfyUI-Radiance-MiniMax/radiance_node.py @@ -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"), diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt new file mode 100644 index 00000000..e72c7ca0 --- /dev/null +++ b/libr3d/CMakeLists.txt @@ -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=`, 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 /kernels/libr3d.so [--case ] +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) diff --git a/libr3d/README.md b/libr3d/README.md new file mode 100644 index 00000000..3d656499 --- /dev/null +++ b/libr3d/README.md @@ -0,0 +1,1211 @@ +# libr3d + +libr3d is radiance's kernel library for RDNA3 and RDNA3.5 — the gfx11xx family: +`gfx1100`, `gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, and `gfx11-generic`, +the code object for a gfx11 card a build did not name. HIP kernels behind a plain C +ABI ([`r3d.h`](r3d.h)) plus the kernel-plugin rows the engine selects from +(`r3d_rows.cpp`); `libr3d/CMakeLists.txt` names every unit and its flags. + +It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`: a card gets +one device library, picked by the rows and never by the name. The kernels are not +libr4d's ported: the matrix work runs on the dot2 path — RDNA3's 16×16 wave-matrix +family is a fragment layout these kernels' lane map does not use, and gfx11 has no +bf16 pack and no VOPD — so every arithmetic path is its own: `v_dot2acc_f32_f16` for +products, software codecs for every format, a weight read in the order the container +stores it. The contract is shared: the same op schemas (copied +slot for slot from libref, as the loader requires), the same numerics rules, the same +geometry in constraints. Family parts differ in CU count and clock, never in these +instructions, so one code object per family suffices — and every number here is quoted +with its geometry, and with the class of part where the part's size is part of the +fact. + +## Naming + +An entry point is `r3d__[_]`: +`gemm_nt_bf16_m16` serves `gemm_nt` at bf16 for M ≤ 16 and refuses a larger M; +`r3d_rope_bf16` serves bf16 QKV in place and refuses anything else. A dimension named +in a name is a compile-time constant, and the entry point rejects a mismatch instead +of running. Shared dimensions stay out of the names: wave32, the attention rows' head +size (128), and the target architecture, reported by `rad_plugin_info`'s +`build_target` — spelled as a device reports its arch, because the loader warns when a +plugin claims a card the running device is not. + +Rows are `RadKernelInfo` entries in a table the engine reads from a dlopened `.so`; +the plugin links the ABI headers and nothing of the engine's. + +**Schema equality at load:** the first library to declare an op fixes its schema, and +a second declaring it with a different schema is refused by name with every row it +carries — arguments are positional, so a mistyped operand role is not a bad row, it is +no library. + +**The tail order is the ABI's:** `init, fini, launch, scratch, layout, relayout, +opd_shape, unrelayout, replaces` — `replaces` last on purpose, because kernel tables +are positional aggregate initialisers: a field inserted mid-struct shifts every later +one, and `nullptr` converts to any function pointer, so part of the shift would +compile. + +There is no launch adapter: every entry point *is* the row's `launch`, `(const +RadArgs*, RadStream)`, spelled `r3d_rad_` in [`r3d_plugin.h`](r3d_plugin.h). + +Behind it, two layers per unit: the **launcher** (`r3d_(...)` in `r3d.h`) takes +pointers as longs, checks what a `__global__` cannot, computes the grid, issues one +kernel on the stream it was handed; the **shim**, named by the row, reads operands +with [`r3d_args.h`](r3d_args.h), takes dtype from the tensor and the row count from +the operand, checks strides, returns a RAD status. Neither allocates, neither +synchronises. The table lists a selection; `r3d_rows.cpp` and `r3d.h` hold the full +set. + +| family | rows | +| --- | --- | +| `norm` | `rmsnorm_bf16` (optional residual add and multiplier), `rmsnorm_f32`, `layernorm_bf16` | +| `elem` | `add` (with `div`, and the broadcast band) · `mul` · `silu` · `gelu` · `sigmoid` · `act_mul_{silu,gelu,sigmoid}` · `softmax` · `scale` · `fill` (bf16/f32/i32/i64) · `gather_rows` · `scatter_rows`, bf16 and f32 where the op has both, plus seven `cast` pairs and `silu_mul_bf16` | +| `attn` | `rope_bf16` (neox and gptj, in place over packed QKV), `kv_store_{bf16,f16,fp8}`, `attn_paged_{bf16,fp8}_{decode,prefill}` — head_dim 128, split-KV combined in the same launch | +| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128×128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w8a8_m16` (signed int8 weight, decode band), `gemm_nt_q_gated_fp8a8` | +| `vocab` | `logits_gemm_bf16` — the head read once a token, bf16 codes, or E4M3 codes with a bf16 scale per 128×128 block | +| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `gated_quant_fp8_bf16`, `rmsnorm_quant_fp8_bf16` (norm and quantiser in one pass), `dequant_fp8` `dequant_e5m2` `dequant_i8` | +| `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` | +| `moe` | `row_topk_{bf16,f32}` — the op's stage in the reference is `moe`, so the row's is too | +| `draft` | `dflash_select_bf16` — the drafter's accept step, a walk over the draft block's candidate lattice | + +Seventy-eight rows, 44 schemas, every schema checked against the `libref.so` beside the +plugin, slot for slot, by `r3d_selftest`. GEMM rows carry tunables (`sk`, `wv`, `nt`); +the rest have none. + +Two int8 activation rows, because the reference has two ops and they are not +interchangeable: `quant_act_i8` is one scale per row, codes in the order an int8 +matrix operand is read (`i8_step_pos`, bits 2 and 3 of the column swapped) — what +`w8a8`/`w4a8`/`w2a8` producers mean; `quant_act_i8g` is one scale per (row, group), +row-major codes — what this library's `i8a8` GEMM reads and `dequant` inverts. The +step order is the op's, not a kernel's convenience: the plane is what the oracle +compares element by element, the one place in libr3d where a store address carries a +permutation. + +## Constraints as data + +Constraints are data in the rows the engine reads — a third copy of a geometry in each +caller drifts — and `r3d_selftest` checks every constraint key against the op's +declared parameters: a key renamed in one place only is a row that matches nothing. +Three rules decide what goes in a table, all three the engine's. + +* **A constraint on a key the band does not carry does not hold.** A band carries the + parameters its graph set and nothing else, so a row constraining an optional + parameter serves only graphs that spell it out: `rotary_dim` is optional on `rope`, + and binding it resolved a row to nothing for every graph that rotates a whole head; + `pb1`/`pb2` on the quantised GEMMs did the same to a whole model's bands, which fell + to the host. The selftest's reachability phase names every row that narrows itself + this way. +* **A band's `dtype` is the activation's.** A row whose dtype lives in the weight does + not constrain it: `logits_gemm` carries no `dtype` constraint, because the head's + dtype is a property of the operand and the row answers dtype with a check on the + tensor. `gemm_nt_q` is the opposite case — there `dtype` *is* the operand scheme, so + `C_IN` filters — stated at each table. +* **A row's floor is its sibling's declared ceiling + 1.** The tiled rows begin at `M + >= 17` because `gemm_nt_bf16_m16` declares `C_LE("M", 16)`, read from the constraint + and not from the name. A floor reasoned from prose ("the decode heights") left + 17..64 unserved and 209 batched-decode bands on the host: the shape a serving card + spends most of its life in. + +What the kernel cannot read goes in the constraints, not only in the launch: `n_vocab +>= 4` is the store's granularity (rows are written in 16-byte runs); `n_cand <= 1024` +is the candidate kernels' LDS budget (five f32 arrays of `n_cand` = 20 KiB of the 64 +KiB); `K % 32` / `K % 128` are the tile's k-chunk and the container's scale block. + +## Building + +Out of tree, against an installed radiance, as a third-party plugin is built: + +``` +cmake -S libr3d -B build -G Ninja \ + -DCMAKE_PREFIX_PATH="$RADIANCE_PREFIX" \ + -DCMAKE_HIP_COMPILER=/opt/rocm/lib/llvm/bin/clang++ \ + -DRAD_GPU_TARGETS="gfx1100;gfx11-generic" +cmake --build build +``` + +`rad_plugin_gpu_targets(R3D_GPU_TARGETS "^gfx11")` filters requested targets to the +family, and the project returns without a target when the filter is empty: a build for +gfx12 machines does not produce this library, on any path. `gfx11-generic` is the +object for a gfx11 card the build did not name — why one `.so` serves the family. In +tree, `add_subdirectory(libr3d)` sits beside libr4d's under the same `RAD_HIP_FOUND` +guard. + +`R3D_UNITS` lists units as `"file|extra flags"`, each named after the entry point it +provides; the shared headers (`r3d_common.h`, `r3d_codecs.h`, `r3d_args.h`, +`r3d_launch.h`, `r3d_tiling.h`, `r3d_fp8_dequant.h`) provide no kernel. Every unit is +`-ffp-contract=off`, which `rad_hipify` puts on all HIP sources — not a style +preference (Numerics). `r3d_rows.cpp` and `r3d_shapes.cpp` include neither `r3d.h` nor +the runtime, so the tables compile without ROCm. Occupancy is per kernel: +`__launch_bounds__` and `amdgpu_waves_per_eu` (`R3D_WAVES`) are written against this +family's register file, not RDNA4's. + +## Adding a kernel + +1. Write the `.hip`, named after the entry point it provides, geometry included. +2. Declare the launcher in [`r3d.h`](r3d.h) and the shim in + [`r3d_plugin.h`](r3d_plugin.h). +3. Add the unit to `R3D_UNITS` in `libr3d/CMakeLists.txt`, with any per-unit flags. +4. Add a `RadKernelInfo` row in `r3d_rows.cpp` with its constraint table. If its + `op` is one libref declares, copy libref's schema slot for slot — names and doc + strings are free, roles are not; if the op is new, declare the schema in the + same file. +5. Add the operand description to `r3d_shapes.cpp` if the row's operands are not + the schema's plain reading, and a geometry to the selftest's list. +6. Give the row a case: the selftest walks the table, so a row is run by adding no + test code — geometry comes from its constraints. +7. Measure it: `r3d_selftest /kernels/libr3d.so --case `, then + `rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d --op `. + +A row naming an entry point that does not exist is an undefined symbol at `dlopen`, +which refuses the library and takes every row with it: a row lands in the same change +as its kernel, and a constraint array whose kernel has not landed stays out of the +table. + +## What the family gives, and what it takes + +Measured by reading emitted assembly for the gfx11 targets (`__has_builtin` off +`--offload-device-only`, `llvm-mc -show-encoding` per target) against the ROCm this +tree builds against; where a claim was taken on one chip it says which. Nothing here +changes between gfx110x and gfx115x — which is what makes the family one code object. + +**The dot2 path, and the wave-matrix instructions it does not use.** RDNA3 carries +exactly six wave-matrix instructions, all 16×16×16 wave32: f16, bf16, int8 and int4 +in, f32, f16, bf16 and i32 accumulating, and the toolchain emits them on every gfx11 +target. They are not a separate matrix unit: the ISA states the WMMA ops run over +multiple cycles and drive the DOT pipeline internally, and the MAC-core measurement +on this part confirms it (512 waves, K depth 4096, operands preloaded: f32-acc f16 +19.11, f32-acc bf16 19.24, f16-acc f16 19.44, i32-acc i8 19.29, dot2 paired as +`v_dual_dot2acc_f32_f16` 18.86 TFLOP/s — the f16/bf16/i8 tiles and the dot path sit +on the same pipe within three percent, matching the full-kernel 1.99-vs-1.97 of +r3d_common.h). The i32-acc i4 tile is the exception at 25.68 TFLOP/s, 35% above the +dot path, but that instruction takes i4 in *both* operands and the grids this +library serves pair i8 activations against i4 and i2 weights — there is no +mixed-precision integer WMMA on RDNA3, so that pipe is unreachable from the w4a8 +and w2a8 rows. The i8 tile's only edge over the current w8a8 path is a decode, and +the kernel-level measurement closes the question: the w8a8 m16 row runs 0.850 +TFLOP/s and w4a8 m16 0.789 (M=16, N=11008, K=4096, weights in device memory) -- +twenty-two times below the i8 tile's own MAC core, weight-byte-bound at the decode +band's geometry, where no re-tile of the arithmetic moves the number. These +kernels run +the dot2 path: one wave a weight row, a k-split per lane, the group's exact sub-sum +folded with one shfl. The WMMA fragment layout (lanes 0..15 replicated into 16..31, +A one row a lane, B one column a lane, the accumulator's row i at lane (i%2)·16+j +VGPR i/2) is a re-tile, not a drop-in, and no measured variant earns it. Products +go through `__builtin_amdgcn_fdot2` → `v_dot2acc_f32_f16` on every gfx11 target, +paired as `v_dual_dot2acc_f32_f16` where the scheduler can — about a quarter of +RDNA4's matrix rate. No fragment layouts, so no repacked weights, so no layout hook +except the container's own planes force. + +**No int8 dot.** `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a`, +`__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared for gfx1102, and all +four were tested. Codes widen to f16 and the dot runs on `dot2_f16x4`, paid for with a +trick: the 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, and the dot's answer comes back +carrying `128 · Σa` — the plane the op already has for the zero point, so de-bias is +one exact f32 subtraction per (row, group). + +**`v_fdot2_f32_f16` carries a little under 24 bits on integers — call it 22.** +"Products and partials are integers below 2^24, so the dot is exact" is true of f32 +and false of this instruction. Instrument: `probe_dot_kernel`, in the unit that uses +it — 32 lanes a block, one 64-code dot per lane, its f32 beside the exact integer. +Bias 1024: **71027 of 262144 dots inexact, worst |err| 0.125**, every one a dot whose +magnitude had reached 2^20; bias 128: 70115 of 262144, worst 0.015625. Worst error +over magnitude is ~2^-22, so shrinking the bias shrinks the tail and does not remove +it. The same work as four `__fmaf_rn` per quad in f32: 262144 samples, **0 inexact, +worst error exactly 0**. `gemm_nt_q` at `w2a8` ships a documented tail, not a claim. + +**`v_cvt_pk_f16_fp8` is listed by the compiler and absent from the silicon:** on +gfx1102 the ISA of a build calling it contains zero `v_cvt_pk_f16_fp8`, counted by +grep — it expands to software, ~100 instructions per 8 codes against the four that +widen bf16. `v_cvt_pk_fp8_f32` / `v_cvt_pk_f32_fp8` need `fp8-conversion-insts`, which +no gfx11 target has; their builtins are *declared* for gfx11 — the trap a +`__has_builtin` guard falls into — and die at instruction selection. Both directions +of e4m3 are bit maths in [`r3d_codecs.h`](r3d_codecs.h), mirroring `rad_plugin.h` line +for line, checked over every code. + +**No fp8 instruction means the decode is arithmetic, so the arithmetic gets a table.** +Ten VALU a code, and a weight-stationary row decodes every code it multiplies — twice +over where a lane owns two chains — which at M=1 is every code in the operand. A +256-entry f16 table in LDS, 512 bytes, built once a block by the arithmetic path +itself and therefore exact by construction, costs two `ds_read_u16` and a pack a pair +at zero register cost: the gated row's tall arm is 109 registers a lane, four waves a +SIMD, zero spills, and the table alone moves M=64 from 8395.3 us to 2786.5 us (its +band: N=12288 K=2048 group=128, codes resident, best of nine) — two thirds of that +arm's gain is the decoder. Two landmines in it, both load-bearing. The table's +argument is a **PAIR**, low code in the low byte, not an index: feeding it the index +fills the even entries and decodes code 0 into every odd one, and the code-enumeration +case names that as `rel_l2` 9.6e-01, not a NaN. And the decoded pairs +go from the table into the dot **inline**: materialising the round's eight pairs into +an array on the way — the shape this loop had, and the shape the arithmetic decoder +feeds — put 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 proven exact on the device, entry +by entry and pair by pair. The array form is the one that miscomputes; do not restore +it as a tidy-up. + +**`f16x2_pack` is `v_cvt_pkrtz_f16_f32`: rounds toward zero, flushes subnormal f16.** +Only values f16 represents exactly may go through it — bf16 widened (7 mantissa bits +into 10), E4M3 widened (3 into 3) — never a code times a scale. Folding `code * scale` +through the pack biased every product toward zero: `rel_l2` 2.8e-4 against the fold's +law, 0.53 of outputs within 2 ulps. Folding with `v_mul_f16` (round to nearest, +subnormals kept) is one rounding in the right direction and one instruction: 4.5e-06, +1.000 within 2 ulps, nothing beyond six. Every scale fold here goes through +`v_mul_f16`. + +**`v_cvt_pk_bf16_f32` does not exist** on gfx1100, gfx1102, gfx1151: a bf16 pair is +rounded by hand and packed with `v_perm_b32`. **The dot's bf16 selector is a lie** — +`__builtin_amdgcn_fdot2` takes a `sel` operand for the bf16 form, the compiler accepts +`sel = true`, emits the f16 instruction, and bf16 operands are read as f16s: nonsense +products, silently. `dot2_f16x2` passes `false`, always. f16 is the compute type: bf16 +and E4M3 widen to it exactly, with the edges in the codecs — above 65504 a widening +saturates, below 2^-14 the f16 subnormal grid is coarser than the source's and +truncates. + +**Wave32, smaller register file than RDNA4:** 1024 VGPR entries a SIMD for a wave32, +granules of 8, against RDNA4's 1536; 64 KiB of LDS a workgroup on both. Occupancy +constants do not cross the generation, so `R3D_WAVES` is per kernel. A CU is 4 SIMDs × +16 wave32s = 64 wave slots, and `multiProcessorCount` reports CUs on gfx11 (WGPs on +gfx12), so a row-per-block kernel with one wave a block passes 64 waves a CU at +exactly the row count where tail waves start waiting. A wave64 build is refused at +compile time: it computes garbage rather than running slower. + +**No vector f64:** consumer RDNA3 is 1:64 on doubles, in practice soft-float, which +sets the transcendental policy per unit — the sampler keeps the reference's +`(float)exp((double)x)` (drawing a different token than the recording is wrong at any +speed), attention cannot pay it and ships a polynomial, the gated MLP uses `expf` into +a bf16 narrowing. + +**The lane ops are libr4d's** — `update_dpp` (xor and shr controls), `permlanex16`, +`readlane`, `readfirstlane`, `ballot`, `ds_bpermute`, `v_perm_b32`, `exp2f`, `rcpf`, +`s_barrier`, `sched_group_barrier`; DPP16 and `v_permlanex16` are RDNA1 onward, and +the encodings in [`r3d_common.h`](r3d_common.h) are the ones libr4d proved on +hardware. **No transposed loads, no VOPD:** neither `global_load_tr_b128` (RDNA4) nor +`ds_read_b64_tr_b16` (rejected by this assembler), so a transpose is done in +registers; VOPD is RDNA4, and the tree's `-mllvm=-amdgpu-enable-vopd=false` comes from +the LLVM version, not from here. LLVM single-buffers LDS and drains before a dependent +read unless told, and with no matrix unit there is nothing to overlap a load with, so +the barrier needed is the plain one. + +## Weights are stored once: the hook, and the writer that goes with it + +Four rows declare a `layout` — `gemm_nt_q_w2a8_m16`, `gemm_nt_q_w2a8_tiled`, +`gemm_nt_q_fp8a8_tiled`, `logits_gemm_bf16` — and each declares the `relayout` that +produces the form it names; `r3d_selftest.cpp` enforces the pair by name (a `layout` +without a `relayout` fails the table, a `relayout` without a `layout` fails it, any +`unrelayout` fails it). + +The starting rule — *no layout hooks in this library* — came from the dot path: a dot2 +GEMM reads a weight in the order it is stored, so there is nothing to repack. It +stands in every part that carries weight: **no plugin-private dtype, no repack into a +format of this plugin's invention, no container format changed from inside a kernel +library.** + +What it got wrong is that the container's quantiser already stores weights where a +kernel cannot read them in place — codes and per-block scales as separate planes, +`fp8_e4m3 * bf16[128x128]` for a head — and the engine's answer is its own canonical +form: planes joined behind one operand, `rad.planes`, sized by `rad_planes_plan`, +written by `rad_planes_relayout`. A row that reads such a weight *describes* that form +and *produces* it; the engine does the work at load, in the loader's pool behind the +container read. Three laws came out of it. + +* **A hook that answers is a promise** — the ABI says so: *RAD_OK: out describes the + stored form, and `relayout` will produce it*. With `relayout = nullptr` the model + does not load: `could not produce '…' (rad.planes) from fp8_e4m3*bf16[128x128]: + unsupported`. +* **A weight is stored once, so the row that got there first owns its plan.** The + engine arbitrates across every row of every band reading the weight, at declare: *is + wanted in two stored forms: 'rad.planes' by row A and '(as it is)' by row B. A + weight is stored once.* A second row gets the same answer by *calling the first + row's hook*, and its kernel reads the container the builder settled — by role, not + by the arrangement it declared. +* **`RAD_E_UNSUPPORTED` means stored as is**, the only kind of weight the mapped tier + can read where it lies — the lever the placement ladder runs on. A joined weight is + a resident weight, and a band that resolves to the host drags its whole layer group + onto the tier that reads the container in place, where a norm weight needing + conversion at load refuses to live. Hence the quantised GEMM at prefill heights as a + startup failure and not a slow band: no device row for `gemm_nt_q` above the decode + band → bands resolve to host kernels → the layer's weights stay in the container's + mapping → its norms group with them → the mapped tier is asked for a widening it + cannot perform. +* **A container arrives as a tensor of `rank = 1`, `shape[0] = bytes`.** That is the + joined form's stored shape — a byte count, from `rad_planes_layout` — and not a + plane. A consumer that reads it as a plane measures a scale plane's rows against + `ceil(N/group)` and refuses with a message about a geometry the operand never had: + the fp8a8 tiled row refused the sibling decode row's settled spelling (codes plain + on `b`, scale joined behind `b_scale`) with `E_SHAPE` from a tensor geometry test on + every case of one probe and at `n_b = 0`, and with `E_STRIDE` at one band — two + codes, one expression, both naming rows and columns of a thing that was never a + plane. Decode by role, on the host, where the header lives: the tag, the entry table + and the stored dtype (the first plane's) are host-readable, so the shim reads them + once per call and hands the kernel three device pointers. In that form the row + computed the reference's answer on **192 cases, 192 agreements, worst `rel_l2` + 1.362e-03** — and the same fix carried the m16/tiled crossing to 1018 cases with no + numeric divergence, where before it the crossing never reached the joined spelling. +* **A `zero` plane is refused as `E_DTYPE`, not folded.** `w2a8` is the only scheme + here with an activation zero point, and its producer is a row of this library. + `fp8a8`'s quantiser is symmetric, so the reference's fp8a8 arm refuses `a_sum` + outright (`ref_gemm.cpp:395`, `RAD_E_UNSUPPORTED` — that arm has no grid to sum a + zero over), the shape hook skips the operand, and every served band omits it. A row + that folded a zero point would be inventing a number the oracle has no law for, so + the refusal names its own fix instead: the row that computes zeros is + `r3d_gemm_nt_q_w2a8`. + +Same law, gains: read them in the dtype the checkpoint stores (a 2048-element norm +gain in f32 is 8.00 KiB), because the row's `dtype` band names the activation, never +the weight — the fused norm's kernel grew the plain norm's `WDT` leg, a dtype +parameter on the gain, rather than ask the checkpoint to be rewritten. + +## The request: a plan's vocabulary is not its contents + +A clean graph dump means every band has a row; it does not mean a request runs. At +request time the engine hands the shim the *contents* — descriptors, strides, an +arena, a step's shape — and the refusals between a clean dump and a first generated +token were one mistake: code that read the band's vocabulary as if it were the plan's +contents. Laws of the ABI, not of any one model. + +**A band's `dtype` is the activation's; a weight's dtype comes off the operand.** The +key names the step's activations, and the head of a `dtype=bf16` band can be E4M3 +codes with a bf16 scale per 128×128 block. A shim that trusts the key refuses the +request the plan is making. + +**An optional operand with no bytes is absent.** Optional operands arrive as +descriptors with a null `data` when the graph bound none, so the test is `r3d_has(t)` +— `t && t->data`; a bare `if (t)` is the bug: dtype-checking a descriptor with no +bytes answers `E_DTYPE` to a band whose dtype was fine, which is what +`rmsnorm_quant_fp8` did at M=5 with an unbound `out_bf16`. + +**A sizing hook runs at declare, where a descriptor has a shape and no bytes** (`data` +is null for every tensor in the plan). A scratch hook opening `if (!a->t[0].data) +return 0` answers 0 for the whole run, the engine allocates an arena of 0 bytes, the +split pass finds nowhere to write — a request-time `scratch buffer absent or too +small` from a hook that looked healthy. Size off the shape (`rad_tensor_numel`) or the +parameters, as the GEMM hook does. Absence at launch means the plan asked for nothing; +absence at declare means the bytes come later. + +**A band key is a bound, not the step's value.** A plan's geometry line reads `at M=30 +[band M<=2048] geometry {N=2560 K=2048 group=128 M=2048}`: the geometry's `M` is the +**ceiling the band was built for**; the height of *this* step is what the operands +say. A GEMM asking a 30-row activation for 2048 rows, and a sampler computing `rows = +(M_hint > 0) ? *M_hint : cirows` before asking the plane to be that tall, refuse every +request that asks for logprobs. Geometry comes off the operand — `nel / N`, `qnel / +n`, `r3d_rows_pitch(y, N, &M)` — and the key stays the ceiling promised not to be +exceeded. **Exceeding it is a refusal, and it prints both numbers.** + +**The engine sizes vector operands to the step, so their geometry comes from the +tensor.** The attention shim required `numel(BT) >= n_seq * max_blocks` with +`max_blocks` from the band's `max_ctx` — a table as wide as the cache — while a +five-token prompt with nothing behind it carries `[n_seq, 1]`: one block, because one +block is what the sequence has. The reference takes geometry from the tensor +(`max_blocks` from `bt->shape[last]`, row pitch from `stride[rank-2]`, column stride +from `stride[rank-1]`, `jend = min(ctx, max_blocks * block_size)`), so a context +longer than the table has columns is truncated — by the oracle as much as by us, which +makes it truncation, not corruption. The shim derives all three from the operand and +checks the one thing required: that the last reachable index `(n_seq-1)*bt_rs + +(bt_cols-1)*bt_cs + 1` is inside the plane. Two conflated counts are named apart: +`cache_blocks` bounds a slot's byte offset, `bt_cols` bounds the walk. + +**Serve the unoptimised form when the optimisation has no room.** Split-KV's halving +loop said "down to 1, which needs none" in its comment and returned `RAD_E_SCRATCH` at +1. One slice is the whole walk in one block, the same keys in the same order: not a +degraded answer, the answer without the split. Refusing a band because an optimisation +has no arena tells the user to go away. + +**A refusal carries a code, names its own fix, and prints the descriptor it saw.** +`R3D_NO(code)` prints the site under `RAD_R3D_TRACE=1`; `R3D_STR` prints the two +numbers a stride test compared; `r3d_trace_desc` prints dtype, rank, shape and strides +— in **elements**, what the engine binds and what a reader reproducing a refusal +needs. + +**The ragged query batch is a descriptor, not a second kernel.** `cu_seqlens`, when +present, is `[n_seq + 1]` of i32, and `cu[0] == 0`, monotonicity, and `cu[n_seq] ==` +the plane's row count are the *description's* promises — the served engine keeps them, +and no row may rely on them. `seq_of` walks `while (s + 1 < n && cu[s+1] <= row) ++s`, +so rows below `cu[0]` are not excluded: they land in sequence 0 with a negative index +into its query, and the reference computes them at `pos = ctx - qlen + i`, pushed +`cu[0]` keys into the past. Nothing in the oracle says the plane starts where the +descriptor starts. So `q_len` is *per-sequence* (`q_len = cus ? 0 : rows / n_seq`), the +total row count is the plane's, and a ragged batch has no `q_len` at all. One grid +covers it because the clamp a tile needs is per sequence; the rectangular case is the +descriptor's absence (`len_s = q_len`, `start_s = s * q_len`). One mapping, one mask, +one walk, one store, both forms. + +**A descriptor carries two row counts, and the store is bounded by the second.** +`len = cu[s+1] - cu[s]` is what the positions count from; `span = cu[s+1] - start`, +with `start = (s == 0 && cu[0] > 0) ? 0 : cu[s]`, is how many rows the sequence's tiles +carry, because the grid covers the plane from 0. The tile count comes from the length; +the store bound comes from the span. Bounding the store by the length drops the last +`cu[0]` rows of an in-bounds plane, silently, with status 0 from both rows: 20 rows, +`cu = [3, 17]`, one sequence, ctx 24 left 6144 items — 3 rows × 2048 — at the `0x7fc0` +pre-fill while the 17 rows it wrote agreed to bf16 rounding (max abs 1.22e-04), and the +engine read its own `out` buffer back as attention output. The plane's `rel_l2` is +`nan` in that case only because the untouched slots are bf16 NaN, which is exactly why +a finite-output check passes it and a whole-plane read-back does not. Every other +served shape agreed — 233 cases — which is what makes `cu[0] > 0` the descriptor's own +law and not a geometry note: the reference reads the descriptor, the fixture never +draws one, and the ragged oracle builds its prefix sum from 0, so the shape +that broke the agreement is a shape no oracle upstream could generate. + +## Numerics + +f32 accumulation, IEEE round-to-nearest-even narrowing, subnormals kept, no +reassociation; the oracle is `libref`. + +**`-ffp-contract=off` on every HIP source** (`rad_hipify`, library-wide): a fused +product-sum rounds once where the reference rounds twice, and a kernel diverging by a +rounding the reference does not make will not match it; the flag also keeps the +instruction counts quoted in kernel comments true. + +**Accumulation order is part of the contract:** `v_dot2acc_f32_f16` folds two products +into the accumulator and rounds once, so the match is not bit-exact and cannot be — +under an ulp a pair, a random walk of ~`sqrt(K/2)` ulps over a K-long dot, a +thousandth of the bf16 a store narrows to and inside what `rad-kbench` measures. The +*order* must be the reference's: k ascending, one accumulator per output, no +reassociation across lanes, with lane maps built so no lane ever has to break it (a +group spanning two lanes folds in one `shfl_xor`, in integers, before any float work). + +**Reductions are the reference's tree:** a wave butterfly (`dpp_xor` at 16, 8, 4, 2, +1; the halves of a 64-lane row read through `permlanex16` first where the reference +sums a whole row), then wave partials in wave order — the same bracketing at any +thread count. Activations, rope and quantisation are the reference's formulas in its +order (`1/(1+exp(-x))`, `0.5*x*(1+erf(x*0.70710678118654752))`, amax/127 with ties to +even), from `libref/ref_common.h`. + +**The accepted divergences, and the family reason for each** — where a row is checked +against a law it implements rather than against libref's bytes, each named in the unit +that ships it. + +| divergence | why, and what it costs | +| --- | --- | +| an index at or past an operand's row count takes the padding path (zero row, no store); `kv_store` drops a slot past the cache's span | the reference validates index arrays on the host and refuses, and `kv_store` refuses such a slot with `E_SHAPE` before it starts; a kernel cannot, so the bound travels as an argument (`slot_max`). A slot lost, not a step lost. A negative index is padding too and is not clamped to zero, which would duplicate row 0 across every padding row | +| rope divides the position by `scale` and evaluates the frequency ladder in double | `scale` is the position scale (the multiplier on a rotated pair is YaRN's magnitude, and the shims refuse YaRN, so it is 1). `powf` puts the reciprocal a ulp off, and at position 262144 a ulp of a frequency is a hundredth of a radian — the one place in that kernel where f32 is not enough | +| `block_sum`'s tree | wave butterfly, then partials in wave order: the reference's bracketing at any thread count, and why kernel and reference agree at 256 threads and at 64 | +| `sample_logprobs` keeps a NaN out of the max and into the sum; `sample_mask` skips a row whose `mask_row` is negative | maxima are a strict `>`, `std::max`'s law, so a NaN is never adopted; the sum propagates it, because the reference's `exp(NaN - mx)` is NaN and is added. The k-list is per lane in the reference's order (descending by value, ties to the lower column), merged in the same butterfly; the pool is 64 deep and a bigger k is refused, not truncated. The mask bound is the reference's own test (`mask_row` is `-1` for no mask), read off the operand, not off M | +| the sampler's `exp` and `log` are `double` calls narrowed once | the draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over 2^20 points in [-100, 100] (0 differ) where `expf` differs by 1 ulp in 5.7% of them. Consumer RDNA3 is 1:64 on doubles, so this is the slow path by law: at the band, one read of the logits plane is 3.6 ms, a read that also sums double exponentials 30.4 ms, this kernel 38.9 ms. The candidate set is where it is affordable (1024 exponentials a row); attention is not | +| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid is `expf` | no vector f64, and prefill is tens of millions of exponentials a layer. Against `(float)exp((double)x)` over 1.31M points of [-100, 0]: every point within one f32 ulp, 76.1% bit-identical (the device `expf` is 94.0% identical and no better in ulps), `exp(0)` exactly 1 — the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a *function*. The MLP feeds 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 | +| `w2a8` lands with a one-ulp tail | the pair-dot carries ~22 bits on integers: 0.1–0.2% of outputs one bf16 ulp off, `rel_l2` 5.0e-3 at the band, nothing further. The row's prose says so, because the law it transcribes is exact integers and the row reads like a bit-exact one | +| the fp8 folds land in f16, not f32 | the tile is f16, so a scale enters as a f16 multiply at staging — one rounding per staged value, through `v_mul_f16`. Against the reference's exact dequantise law: `rel_l2` 2.77e-04, half an f16 ulp, 250× finer than an E4M3 code's quantum (2^-4); against a model of the fold itself: 4.5e-06, the dot's fused rounding. At a bf16 output the store's ulp (3.9e-3) binds, not the fold's: 83% of outputs bit-exact, 99.93% within fold plus one store ulp | +| the bf16 GEMM's long-K tail | the pair is folded into the accumulator by one rounding, so ~0.3% of a long-K output lands one bf16 store ulp from the reference's and none is further: 99.93% bit-exact at the 512-column twin, 100% within two ulps | + +**How a plane is proved to have been written.** Every output plane in the comparison +runs is pre-filled with the dtype's NaN (`0x7fc0` for bf16 and f16) and read back whole: a +kernel returning `RAD_OK` without launching leaves the caller's bytes behind, and the +caller's zeros are finite, so only a NaN fill says the row ran. A clean case prints +`untouched 0`, `nonfinite 0`, no output beyond six ulps of the law the kernel +implements, and a whole-plane `rel_l2` inside what the fusion costs — `2 · sqrt(K/2)` +output ulps, with room for the fixture's spread. + +Two named planes (an int8 row-sum padded to a 16-row grid, a quantiser's per-group +statistics) keep the fill in their padding legitimately, because the row writes only +the rows it was given: the report says *pad NaN of N, the reference's grid, not the +row's work*, and a NaN anywhere else is the silent no-op the fill exists to find. + +Infinities are contract, not corruption, in the sampler and row top-k: a dropped +candidate, a narrowing stage's drop, and an unfilled `row_topk` slot are all `-inf`. + +## Testing + +[`r3d_selftest.cpp`](r3d_selftest.cpp) dlopens the `.so` — so an undefined symbol is +its failure, not a link failure — and runs five gates. + +**Codecs** against the ABI's host versions in `rad_plugin.h`: bf16 and f16 over all +65536 patterns both directions; e4m3 over all 256 codes plus the encoder's saturating, +subnormal, signed-zero and NaN cases; int8 against `rad_round_even_sat` over every +tie; the widenings over the range they are exact in; the bf16 pair packer against +`rad_f32_to_bf16`. The codecs are this library's own arithmetic, so they belong to the +tests: kbench compares whole ops, where a codec's disagreement is a diffuse +percentage. + +**The table:** unique names, a launch on every row, an `init` with a `fini`, the +device domain, prose on every row, a schema for every `op`, every constraint key a +declared parameter, a tunable's default among its ascending values, the layout pair +rule. + +**Band reachability:** every constraint a row puts on an optional parameter, named — +not an error, it is how a row says *I serve the form that states the parameter*, but a +decision, and a row whose author did not make it silently will not serve. + +**The schemas against `libref.so` beside the plugin**, with the loader's own +comparison (parameter count, keys, types, requiredness; operand count, roles, +optionality): one role mistyped and the loader refuses the whole library, every row +with it, one line in a log. + +**Every row, run** on a card — buffers from the row's own `opd_shape`, filled per its +fill code, outputs checked whole, one child process per row so a GPU page fault names +its row and the run continues. No card is not a failure: the static phase is a third +of what it checks, and a build machine runs it without one. + +The numerical authority is `rad-kbench`, replaying a recorded fixture against libref: + +``` +rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d +``` + +`--all-rows` runs every row whose constraints hold, not only the one selection picks — +how a tunable arm the tuned defaults never reach gets measured. `--coverage DIR +--coverage-write` records the rows a fixture reaches, so a row that stops being +reachable fails the run; the census is +[`kbench_rows_kernels_libr3d.txt`](../data/kbench_rows/kbench_rows_kernels_libr3d.txt), +written by the same run, so census and numbers cannot disagree. + +**A fixture covers a checkpoint, not the library.** A fixture is generated from the +bands a recorded checkpoint issues, so a row can be shipped, correct, and absent from +its census: the packed 2-bit grid serves the head bands of the checkpoint it is served +on, and the base fixture has no `w2a8` band above M=16. Its gate: clean cases on both +stored arrangements, every refusal refused as stated, the writer's codes, scale and +zero regions byte-identical to the fixture's including a 73,113,920-byte head operand — +plus the fp8a8 row against the same file, 36 of 36 clean. + +A row should say which of the two vouches for it. + +The rule has a tool: `rad-kbench` records a fixture **from a model**, reading only the +tables, then widens every case into the constraints of every row under test. + +``` +rad-kbench -m /path/to/served.rad --record "$RADIANCE_HOME/kb-served.rkb" +rad-kbench --fixture "$RADIANCE_HOME/kb-served.rkb" --record-rows "$RADIANCE_HOME/kbrows.rkb" \ + --kernels libr3d,libref +rad-kbench --fixture "$RADIANCE_HOME/kbrows.rkb" --kernels libref:libr3d --all-rows \ + --no-cache --max-cases 2 --max-bytes 1024 --seed 42 +``` + +Line 1 answers the served checkpoint's own bands against the reference on the +container's real weight bytes: **975 checked, 975 passed, 0 diverged, worst `rel_l2` +1.605e-03** — the sentence worth keeping in a log is *every resolved kernel agrees +with libref on this container's bytes*. + +Lines 2–3 take each case into the M and `q_len` no container selects, the edges of a +row's constraints where its floors and ceilings get exercised: 45 cases reach 45 rows, +90 checked, 90 passed, 0 diverged, worst 9.684e-04. Rows a checkpoint's +graph never uses report `no recorded case of its op`. **Record one fixture per +checkpoint you serve:** a row green on a 27B fp8 fixture and untested at the shape +your served model walks is covered by a checkpoint, not by you. + +Against that base fixture, on a 16-CU RDNA3 part with 8 GiB, built out of tree as +above: **1153 checked, 1153 passed, 0 failed, 24 skipped for the case's own memory +budget, 0 diverged, 0 capped, worst `rel_l2` 1.362e-03** against a tolerance of 8e-03 +— the GEMMs' long-K accumulations and the fused norm-quantiser's E4M3 step. 436 cases +ran inside guarded allocations and 0 wrote outside one: the whole-plane write law, +tested on the fixture and in the hand-rolled comparisons. + +**Two proofs a tolerance cannot give.** A refactor is proved by the recorded decision +lines **bit-identical**: the same run against the build of HEAD and the build of the new +file, diffed with the timing column blanked (`6143/6144`, `2047/2048`, +`3667126/3670016`, +`4193353/4194304`). A change to an index, a scale plane or a row mapping is proved +**bit-for-bit against the same fixture**, in a mode whose whole job is that pair test: +feeding a per-row scale plane as the first M floats of the `[M][groups]` array +*passed*, because those floats are row 0's slots, so row *m* read row *m/groups*' +scale, and on data drawn from one distribution the answer is a few percent off — +inside a `rel_l2` tolerance, outside the truth. A fixture whose scales are +statistically alike cannot tell a row-indexing error from rounding; the pair test can. + +A test that cannot fail is not a test, so the comparison harness carries the control +that says so: a `selfcheck` run hands the scorer a plane rebuilt under a +known misreading and requires a DIVERGENT verdict naming it. + +The first full fixture run found three bugs a finite-output check cannot find: a cast +and a gather advancing the row base by the pitch in *bytes* where it is in *elements*; +raw bf16 patterns fed to `v_dot2acc_f32_f16` (0x3F80 is bf16 1.0 and f16 1.875); a +staging loop striding by the compile-time block size, correct at eight waves a block +and silently reading unwritten LDS at one. All three are in rows a fixture selects at +M > 1, none in a row the tuned defaults select. + +The gates prove a binary, not a tree. The box builds a *synced* tree, so a file that +never went to the box can reach the repo unmeasured, and one commit did exactly that: +it carried 567 lines of a unit's redesign where the built and measured file is 483, +and the added staged-arm and window paths use a constant — `kWin` — that is declared +nowhere, so the tree at tip did not compile while every gate above kept passing, +because not one of them builds from the commit. The check that catches it costs one +clean export: archive HEAD, build the archive on the target, and `build=0` is the only +answer. Two rules follow. A file enters the tree in the bytes that were measured — the +file an agent measured in its own snapshot is the file that lands, and its md5 is +quoted with its numbers. And unfinished work stays in a scratch directory, never in a +path a commit will sweep: the 567-line file is outside the repo now, with the constant +declared, for whoever finishes and measures it. + +## The fp8x8 GEMM by row count + +The band this family exists for is 42 layers plus a drafter at `group=128 +dtype=fp8a8` with a band ceiling of M=2048: N=12288 K=2048 ×44 (the gated MLP, two +halves of 6144), N=2560 K=2048 ×44 (qkv), N=2048 K=6144 ×44 (o-proj), N=2048 K=2048 +×44, and N=2048 K=10240 ×3 (the drafter). Three rows cover it by row count and the +boundary is read off the constraint tables, not off names: `gemm_nt_q_fp8a8_m16` +declares `C_LE("M", 16)`, so `gemm_nt_q_fp8a8_tiled` opens at `C_GE("M", 17)`, and +`gemm_nt_q_gated_fp8a8` runs M=1..64 with N even and K % 128. A floor reasoned from +prose, not from the sibling's *declared* ceiling, left 17..64 unserved and 209 +batched-decode bands on the host. The census in [Naming](#naming) is the index; the +measured floors and the placement law that prices them are in +[Measuring](#measuring). + +**The m16 row is a wave a run of columns.** One output element a lane, the weight +streamed past an activation kept in registers, no wave reduction — so a lane's chain is +the reference's chain and the row is bit-comparable at the store. Above 16 rows the same +operands want a 128×128 tile through LDS with 8×8 f32 accumulators a lane. The two +ranges are complements by construction, so neither row competes for the other's band, +and the m16 row is run against the tiled row on the same bytes, which is where a +boundary that moved would be seen. + +**The tiled row folds the scales at staging, and the fold is the arithmetic.** The tile +is f16, so both scale streams enter as f16 multiplies where the codes are staged: the +activation's `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk +— TN 128 is the scale plane's row extent, so a tile is one scale-row, and kKC 32 divides +128, so a chunk sits inside one k-block. The products are separable, +`(a*sa)*(b*sb) = (a*b)*sa*sb`, so folding each side is the same sum formed a different +way and the accumulator stays one f32 register. The reference's law is the group sub-sum +accumulated from the raw codes and scaled once per group (`ref_gemm.h`'s `quant_dot`, the +same body the m16 and gated rows carry); the fold answers to it at 2.77e-04 `rel_l2` +against a store that costs 3.9e-3, so it is invisible under the bf16 output: 1.71e-03 +overall, 83% of outputs bit-exact, 99.93% within the fold floor plus one store rounding, +nothing beyond eight fold floors and two store ulps. `|y|` is not the denominator — a sum +of 2048 random products is as often near zero as not — the scale is +`S = sqrt(sum (a_k b_k)^2)`, and the fold's measured floor is 9.8e-4 of it. + +**At the band's ceiling.** M=2048, container resident, every number on a +placement line: N=12288 K=2048 28.171 ms and 3659 GFLOP/s; N=2560 K=2048 5.911 ms and +3633; N=2048 K=6144 14.699 ms and 3506; N=2048 K=2048 4.381 ms and 3922; N=2048 K=10240 +29.798 ms and 2883, the drafter. 2883 to 3922 GFLOP/s is 27 to 36% of a part's dense f16 +rate; the bytes floor at the 163 GB/s this class streams is 0.051 to 0.257 ms a band, and +2MNK/(K+N) is ~1900 flops a byte at M=2048. Prefill is compute-bound here, as it should +be, so these numbers describe the loop and not the wire. + +**The cliff is recorded with its numbers, because it is not arithmetic.** The tiled +kernels run one block a CU at 18.4 to 18.5 us a block on every column-tile count the +graphs issue (16 and 20 measured, 4.72 and 5.911 ms over the grid); 19 tiles costs 211 us +a block, 11.4×, and 21 tiles 385 us, 20.9× — deterministic to 0.1% in two isolated +processes, clean at both. Every column-tile count the served graphs issue is even, +so no band walks into it; first try the block-index swizzle these cliffs usually answer +to, then the `nt` streaming loads. + +**What proved the crossing, and what would not have.** One `RadArgs`, the device row and +libref's host row on the same bytes, the whole `y` plane compared — pre-filled `0x7fc0` +so an unwritten element is visible, every other plane poisoned, 256-byte guards checked +after the launch. In every form the served plan hands the row (rank-1 `a_scale` of `[M]`, +the codes as a rank-3 `[M][ceil(K/128)][128]` plane, the weight as the container the +layout hook writes) at the four served bands and at M = 17, 21, 30, 45, 64, 65, 128, 258: +**832 of 1600 cases computed by both sides, 0 numeric divergences, worst `rel_l2` +1.440e-03** against a 5e-3 tolerance, 86.8% of elements bit-identical. The container form +above is what let the crossing reach the joined spelling at all: in it, 192 cases, 192 +agreements, worst 1.362e-03, and the full crossing comes to 1018 cases with 0 numeric +divergences; the same band with `b_scale=[scale,zero]` is 192 cases refused `E_DTYPE`. + +**A fixture whose scales are alike cannot tell an indexing error from rounding.** The +paired run spreads its activation by orders of magnitude a group at a time, because with +uniform random data the amax of 128 samples is statistically concentrated, every block's +scale comes out equal to bf16, and a scale-*index* bug — reading group 0's scale for +group 7 — changes nothing. The unit's own selfcheck said so: two of its eight sabotages +scored 0.00. So the crossing is proved by the paired run and not by the selftest, and +the +planted bug is the proof of the instrument: one line in the shim's launch call — the row +pitch handed to the kernel for a rank-1 activation scale becomes `kb`, a row plane read +at a group plane's pitch, checks and geometry untouched. Against the paired run, 300 +cases: +**240 divergent, worst `rel_l2` 1.389e+00**, and all 180 cases whose `a_scale` is the +served rank-1 binding diverge (9.669e-01, 43 507 of 43 520 elements differing, max abs +6.75e+01: rows 0 and 1 read real scales, every row from 2 reads the bytes past the plane +and produces zeros) while the 60 rank-2 cases are untouched and agree. In `served`, the +fixed scorer names 8 of 8 as `a_scale[m*kb+g]` — the read law, which is what the sabotage +*is*. The same bug is invisible to the row's own geometry test, which sees a rank-1 scale +of `M` rows at a stride of `groups`: a gate that cannot see a wrong scale is not a gate. + +**The gated row couples column *i* to column *n + i*,** so a lane owns both products of +its column: the partner is 192 waves away at the band's n = 6144, no lane-to-lane +exchange reaches it, and staging a whole row through LDS to get it is a round trip of the +[M, N] tensor the row exists to avoid. A lane walks k ascending with two accumulators +over two weight rows, `i` and `n + i` — exactly the traffic the unfused GEMM spent on the +two columns, so the coupling is free — and a block is one group of columns by +`256/group` rows, which closes the group's amax inside the block: a wave max folded over +the group's waves in LDS, one scale store, one code a lane. Product, gate and quantiser +in one launch with 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. Both halves are narrowed to bf16 before +the gate because the pair it replaces stored them and re-read them; the activation itself +is not — `gt * sg` is f32 from the narrowed gate and the product with `up` rounds once, at +the store. The law is `ref_quant.cpp:700` and its order is the point. + +**The gated band, both arms, best/median of nine launches, codes resident:** + +``` +M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the floor for +M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us 24 MiB at 163 GB/s is 154 us, and +M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us the same sixteen loads with no +M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us decode and no dot 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 arm is chosen by row count, in the launcher, from the same band key.** M ≤ 8 with +fp8a8 reads the activation and both weight rows straight from memory, 16 bytes at a +time, decodes them out of the block's table and multiplies: 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, stages — at those heights the grid is 48 × M/2 blocks and occupancy, not the +window, feeds the stream, and the stage pays for itself. The two numbers that chose the +shape came from the band's own stream (24 MiB of codes, resident, this 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 crossover and its gap live in +the launcher's comment, beside the `M <= 8` it selects on: with the table decoder in +**both** arms, N=12288 K=2048 group=128, codes resident, skinny 402 against staged 754 at +M=8 and skinny 955 against staged 1030 at M=16 — so the crossover is above 16 and +M=9..15 has never been measured. Decode lives at M=1 and a draft's verify at M ≤ 8, which +is what the shipped threshold is chosen for; a prefill at 9..16 rows would take the skinny +arm on the M=16 numbers, for about 7%. The window is a skinny-arm fix only: at M=64 it +buys its loads per lane at 32 registers, which is a fifth of a wave a SIMD given up on the +47 bands at the ceiling, and there it costs more than it saves. + +**No relayout on the gated row, and that is a claim.** libref reads the gated +`[N, K]` weight row-major; libr4d stores fp8a8 weights in WMMA fragment order. The two +readings are ~1.35 apart — a relative error, not noise — so this row carries no +relayout and says so in its prose: a row that inherits the fp8 GEMM's `unrelayout` +scores 1.35. The launcher refuses M > 64 (past the bands' ceiling the weight stream is +the wall, and that is a tiled kernel's problem), N odd, a group that is not a power of +two in [32, 256], `group > n` (the reference then defaults the *quantiser's* group to +n and leaves the weight's K block at the stated width: two grids this kernel reads as +one), `K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (no K +slab closes an epilogue that needs the whole row), and an absent `act`. + +**The instrument** is a paired run with two plugins dlopened, both row tables resolved +the way the engine's loader resolves them, one `RadArgs`, and a plane scored against +nine index laws with a hash beside it. It runs every stored form × the bands × the +crossing heights, the served geometry with the rank-1 activation scales the plan binds, +and the collapsed mapped and managed tier arrangements (the mirror layout, the default, +is the served one). Its numbers are the ones quoted above. + +## The paged attention, decode and prefill + +Two rows, chosen by `q_len`: the decode entry, which takes `splits`, and the prefill +entry. The served plan is n_head 16 over n_head_kv 2 at head_dim 128 — gqa 8 — with +`block_size 16` and a 4096 context, the cache `fp8_e4m3` with its descales attached. The +layout is the reference's: `kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]`, +K then V inside a slot, so a key's row is a 512-byte pair and both halves are 16-byte +aligned at every slot; `block_table[seq, j / block_size]` names the block holding key +j; a negative entry is an unmapped block and hides its key, which the allocator uses to +free a sequence by writing −1, so the kernel keeps that test even though the fixture +never sets it; `seqused[s]` is the sequence's **total** key count, this step's query +rows included, so query row *i* of a `len_s`-row step sits at the absolute position +`seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify +(q_len 7) and a prefill chunk (q_len 2048). + +**A lane owns one output row and a wave is the GQA heads of one KV head:** +`h = kh * GQA + (lane & (GQA-1))`, `tok = base + (lane >> lg GQA)` — 8 heads over 4 rows +at gqa 8 — so every lane of a wave reads the same cache row at the same moment. Every +cache read is then an LDS broadcast, one `ds_read_b128` serving the wave, and the paged +walk is a per-wave event rather than a per-lane one. 32 rows per cache read is also the +register file's ceiling, not a preference: a second output row a lane needs 2 × 64 +VGPRs of widened query plus 2 × 128 of f32 accumulator, 384, over the 256 that four +waves a SIMD allows. + +**The walk happens twice, on purpose.** The reference keeps its scores; 32 keys × 128 +dims of f32 is 512 KiB a wave against 64 KiB of LDS, so pass two recomputes them. The +recomputation is the same order over the same operands, so it is bit-identical the +second time, and the op costs half again what keeping them would. A masked key is +skipped, never scored to −inf, so the denominator gets exactly the terms the reference +has, and a row with no visible key stores zeros — the reference's `mx == -INFINITY` +case, as in every other kernel here. P·V stays f32: folding the softmax weight into V +reads every weight to 11 bits, a ~1e-4 change that survives the bf16 store on a few +percent of outputs, for a third of the instructions. `exp` is a degree-8 polynomial +because there is no vector f64: over 1.31M points of [-100, 0] every point lands within +one f32 ulp of `(float)exp((double)x)` and 76.1% land bit-identical, where the device's +`expf` is 94.0% bit-identical — neither is the reference, and `exp(0)` is exactly 1, +which is the term the row is normalised by. + +**The width of a workgroup is the only lever this op has ever given.** A row slot past +a sequence's length computes a clamped duplicate: the walk, the tile and the store all +run for it. `pick_waves` picks the narrowest workgroup that carries the step's `q_len` +(one wave to 32/GQA rows, two to 64/GQA, four above); prefill keeps four. Medians of 15 +per-launch event times, two binaries in one session so the clocks drift together — the +same session's prefill reads 44.9 for both, which is how an earlier session's 40.0 was +explained: 294.7 → 158.4 ms at 256 sequences × 7 rows over 4096 keys, 268.0 → 128.4 ms +with 4 splits, 4.33 → 2.06 ms at 8 sequences over 2048, 4.27 → 3.97 ms at one sequence +over 4096, prefill 44.95 → 44.78. The kernel issues ~15% of the SIMD's slots at the +band and 3.7% at eight sequences, so halving arithmetic on a stalling kernel "should +not" buy 46%, and it did: two waves arriving at a barrier is not twice as cheap as +four, it is four times cheaper. A measurement, not an explanation, which is why the +width is a run-time choice. + +**Measured, and not the answer.** `s_setprio` around the consume leg of the walk: |Δ| ≤ +0.7% everywhere, and the one −6.4% in a session's first pair is clock ramp — the same +band run second gives +0.26%. `R3D_WAVES(2)` to lift the scalar-register ceiling: +`sgpr_count` 107 and `sgpr_spill_count` ~98 at *both* 4 and 2 waves a SIMD, timings +unmoved — the compute-shader scalar budget is not set by waves/SIMD the way the VGPR one +is. `__noinline__` on the staging leg: spills 98 → 72, a 160-byte private frame, timings +unchanged. A two-stage pipeline: +7% prefill, +7% decode, −5% split-KV. + +**Split-KV is a rescale, and the row says which splits are bit-identical.** A slice +accumulates its own `(acc[128], sum, max)` into scratch and the reducer combines before +the single narrowing, rescaling each partial by `exp(m_s - M)`; every term then arrives +as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)` — last-bit at f32 +(~2 ulp a term, ~1 ulp on the sum), and it vanishes under the bf16 store except on +outputs sitting on a rounding boundary. The row's prose states the contract: `splits = 1` +is bit-identical to the reference, `splits > 1` is not. `splits` is a **maximum**, +resolved per sequence from its own `seqused`: `nslice = ceil(nblk / ceil(nblk / splits))` +with `nblk` the sequence's block count, so a short sequence uses fewer slices and there +is no per-sequence legality check to fail, and the reducer recomputes `nslice` from the +same two numbers, so a partial needs no header. The arena is a bound, not an error: the +launcher lowers `splits` to what the arena holds, down to 1, which needs none. + +**The split curve on the served shape** — 64 sequences, 8 KV heads, fp8 cache, 15 +launches, ms a launch, at splits 1/2/4/8/16/32/64: at ctx 1024, 8.17 / 5.51 / 9.29 / +1.50 / 2.54 / 0.39 / 0.23; at ctx 4096, 35.71 / 20.92 / 11.41 / 5.79 / 2.67 / 1.44 / +2.60. Each workgroup walks `ceil(nblk / splits)` blocks with `nblk = ceil(jcap/16)`, so +the total keys read are `jcap` at **every** split count: the cost is slices × per-slice +work plus the reduce, it falls to 32 and then rises. The clamp `splits ≤ +ceil(jcap/block_size)` is a no-op at the served shape — `ceil(1024/16)` is 64 — and +bites only where splits exceed `nblk`, where a grid built from the requested number +leaves slices with no blocks: 12 of 12 such cases agree, so the extra waves cost, they +do not corrupt. The curve declines the lever with its numbers; the launcher does not +refuse it. + +**Two counts bound the walk, and the descriptor's two counts bound the store.** +`jcap = min(max_ctx, cols * block_size)`: the block table is the window the kernel is +allowed to read, so a context longer than the table has columns is truncated — by the +oracle as much as by us, which makes it truncation, not corruption. `cache_blocks` +bounds a slot's byte offset, `bt_cols` bounds the walk, and the shim checks the one +thing required: that the last reachable index `(n_seq-1)*bt_rs + (bt_cols-1)*bt_cs + 1` +is inside the plane. In the tile walk, the descriptor's length gives the tile count and +its span gives the store bound, so a sequence whose `cu[0]` is above 0 stores every row +the grid covers: see the descriptor's two counts in +[The request](#the-request-a-plans-vocabulary-is-not-its-contents). + +**A padding row must not write a partial.** A padding row's `row` clamps to a REAL row, +so the split path needs the row-validity test *before* the partial store. Unguarded, +two lanes write the same `(row, h, slice)` — inside the declared arena, so no bounds +check sees it — and their 132-float records interleave, leaving a slot with one lane's +accumulator and the other lane's `(sum, max)`. The reducer then rescales a full slice by +the wrong maximum, the combined sum comes out thousands of times too small, and `1/sum` +hands back a power of two where a logit belongs. Measured at the sliding-window band +(one sequence, 32 heads over 8 KV heads, window 2048, fp8 cache, splits 4): q_len 4 at +ctx 8192 gives `rel_l2` 1.65e-01 with a worst item of +32.0 against a reference ++1.2e-05, and q_len 6 at the same context gives 1.23e-03 where splits 1 gives 1.09e-03. +The mechanism needs `q_len < 32/gqa`, which is why the decode band (q_len 7 at gqa 8 +fills a wave, so there are no padding rows) and a run of that geometry never +saw it, and why the failing fixture cases fail identically at three seeds: a schedule, +not a sample. The slots a padding row leaves unwritten are exactly the slots the reduce +does not read; its index runs over real rows only. + +**The instrument** is a paired run with libref and libr3d dlopened in one process, both +called with the *same* `RadArgs`, absent optional operands passed as a descriptor with +null `data` and never as a shorter `n_t`, with the fp8 cache form in the same run: 233 +served-shape cases with no divergence, the rectangular matrix, the deep contexts +512..4096, the narrow block tables (`bt cols` 1/2/3/4/8, so `jcap` 16/32/48/64/128 +under a ctx of 512), empty sequences (`cu = [0,0,5,5,17]`), split counts 1 and 4, +windows 1/3/17/64/512, causal and non-causal. It is where the descriptor law above +was found. On the fixture the row scores 87 of 87 with worst `rel_l2` 7.558e-05, the +same numbers in the base build and the work build — the pair a change has to keep. + +**The unit's own launch counts itself.** A served decode step is *played* — the recorded +pass re-issues queue packets and never calls the plugin's shim — so a print that lives in +the shim has never seen the played steps. The kernel does. Under +`RAD_R3D_TRACE` only, `attn_kernel` writes one record per launch — its launch ordinal, +the row's `ctx` off `seqused`, the whole block-id row of the table, the six operand +addresses, and FNV-1a folds of the query row and of the first and last block it walks — +into a plugin-owned `__device__` ring of 256 fixed 216-byte slots, and the shim drains +the ring to stderr on a traced call. Budget is a device global the shim writes; the +decrement is `atomicSub`, the counter `atomicAdd`, and with the flag unset the kernel +pays one scalar load and a not-taken branch on one thread. The record's emission is one +step late for played steps, and the record's own `L` and `ctx` restore the order. + +**The served channel is a buffer, not a global.** In a served process the plugin is +dlopened, and the runtime's symbol stub for a plugin-owned `__device__` global is not the +address the kernel's module writes: the shim's arm and the kernel's read are two +different memories, so the ring's budget cannot be armed and the ring drains zero. The +served channel is therefore a plain `hipMalloc`'d record slot passed as a kernel +argument — no symbol table between writer and reader, one record per launch, drained at +the launch, armed by the same flag. The ring stays the board's channel, where the two +memories are one. + +**The flag's price, stated.** A launch function serves the step and is not a place to +allocate or to synchronize. With the flag *unset* both hold: the attention launch pays +one cached flag read and nothing else. With it *set*, the traced call pays one device +synchronize (the descriptor probe reads the table on the host) and the launch one stream +synchronize (the record drain), and the first traced call allocates the record slot. +Those are the instruments working, and they are the reason the flag is a tracing +switch, not a mode. + +**The law that made it a ring:** a kernel that calls device `printf` takes an extra +implicit argument — `hidden_hostcall_buffer` — and the AQL backend does not provide it, +so such a kernel is *undispatchable by the engine* (the fixture refuses the row with +`refused a geometry its constraints accept: device error`) while the same kernel, +hipLaunched by a hand-rolled board, prints every line. A board is therefore blind to +dispatch-side problems of its own kernels: only a gate that dispatches through the +engine can see them, and for this unit that gate is the recorded fixture. + +## The sampler spine + +Thirteen rows: five pre-filters, `sample_topk` feeding `sample_pick`, and the narrowing +stages that run between them. `abi/rad_sample.h` is the wire format and it is the point +of the design: every scalar — `temp`, `top_k`, `top_p`, `min_p`, `typical_p`, the +`xtc_*` pair, `seed`, `pos`, the flags, the history window — is **data**, one 96-byte +row per sampled position, because a parameter is geometry and geometry is frozen at +declare, and two rows of one batch with different `top_p` must resolve to one kernel. +`param_rows` is that check, and it is the dtype check libref states: the plane is +32-bit words, and a 16-bit view passes a byte-count test and then misreads every row. + +**The draws must reproduce, so the summation order is transcription and not +performance.** Every max here is a strict `>`, and that is also how NaN is kept out: +libref's `if (v > mx) mx = v` over −infinity never adopts a NaN, and the butterfly +merges with the same strict comparison, so a NaN in a row of logits cannot become the +max anywhere. A sum of f32 is not order-free: the reference's sums run over the +candidates in **index order** and its CDF scan accumulates in index order, so the exps +are computed in parallel — each a separate value, order-free — and the accumulation is +serial on one lane, in index order, exactly as written. Parallel values, serial sums: +the whole design of the candidate kernels in one line. + +**The draw is a function of the ABI, not of a library, and the transcendentals are the +reference's.** splitmix64 over `seed * 0x9E3779B97F4A7C15 + pos`, the top 24 bits over +2^24, integer arithmetic so it is the same number on the device as on the host, +independent streams per purpose (the pick XORs `RAD_SAMPLE_KEY_PICK`, XTC's coin +`RAD_SAMPLE_KEY_XTC`). `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and +`(float)std::log((double)x)`, transcribed as double calls rounded once to f32: the +device's are bit-identical to the host's over 2^20 points in [-100, 100] — 0 differ — +where `expf` differs from the host's by 1 ulp in 5.7% of them, and a `u < cum` +comparison sitting on an ulp boundary changes the drawn token, which is a fixture +failure even when the distribution is right. This is where the 1:64 fp64 rate is +affordable: the widest softmax here is the candidate set, 1024 exponentials a row at +half a millisecond a step, so the switch stays off and attention, at 17M exponentials a +layer, ships the polynomial instead. + +**The top-R is one scan because the reference's R scans are a sort.** `topk_next` takes, +on each of R scans, the largest value strictly below the last pick, ties to the LOWER +column; read as a whole that is a sort by (−value, +column), and the rule +`v == *pv && i <= *pi` is exactly "the next one within a run of equal values". So one +pass keeping the best R by that order produces the same R pairs, in the same order, with +the same tie-breaks. At the band's row — M=1792, N=130560, R=16, bf16 — the reference +scans the row sixteen times, 7.0 GB; this scans it once, 468 MB. Measured 22.0 ms bf16 +and 22.4 ms f32, 21 GB/s and 42 GB/s: the same time for half the bytes, which is the +finding. The pass is bound by the accepted inserts — ~55 sifts a lane at 510 elements a +lane — not by the plane, and a lane filtering against a block-wide threshold instead of +its own tail would take ~5 sifts a lane and land near the 2 ms the bandwidth floor +allows; 22 ms is not the memory system's answer, and it is written here so nobody reads +it as one. One pass needs a per-lane list, so the list is 64 deep and a merge keeps the +best 64 of two: a lane's test against its 64th best is one comparison for almost every +element (~12% of a row clears it at 510 elements a lane), and the deep comparisons +happen only for elements that enter. Sixty-four covers R=16, the selftest's 64-wide set, +and every `top_k` a request asks for in practice; past it `r3d_sample_topk` and +`r3d_row_topk` take `ceil(k/64)` passes — the reference's own chain, so the answer is +the same at any k and only the time is the reference's. + +**The candidate plane is the contract, its width is the BUFFER's, and it carries +LOGITS.** A row's set is its `top_k` largest logits, descending, ties to the lower +token id, with `cand_idx` −1 and `cand_val` −infinity for a hole. The width is the +declare-time bound — 1024 candidates is the engine's declared buffer width, and two f32 +arrays of it is 8 KiB of the 64 KiB a workgroup gets — and the row's `top_k` only +narrows *within* it: `top_k` 40 in a 1024-wide buffer is 40 candidates and 984 holes, +and the whole buffer is written every step because a hole is a value the later stages +test for. A greedy row takes none: its token is `sample_argmax`'s and the pick must not +overwrite it. `cand_val` carries LOGITS, not probabilities — every narrowing stage takes +its own softmax over the set, which is what lets the stages compose in any order and is +why a pre-filter can be moved rather than re-derived. + +**The band key is a ceiling and the plane is the step, and reading one as the other +killed every logprobs request.** The step's rows are the operand's row count. Preferring +the key's `M` over the plane asked one row of candidates to be 256 of them — `refused op +sample_topp at M=1 [band M<=256] geometry {n_cand=1024 M=256}` — so every request that +asked for logprobs died with `shape this kernel does not serve`. It was the third unit +in one night to read a band's bound as the step's value, after the tiled GEMM at M=30 +and the block table sized to the cache, which is the reason the rule is stated as a law +and not a fix. The key keeps its job as the ceiling the plan promised not to exceed, and +the refusal that fires on a plane over it prints the descriptor it saw. + +**The spine's instrument is the fixture, not a paired run.** No comparison harness pairs +these rows with libref: the selftest builds each row's buffers from its own `opd_shape`, +fills per the fill code, runs the row, and checks the plane whole in a child process, +and kbench +drives the `sample_*` bands against libref on the served checkpoint's fixture (975 of +975 across every op the run resolves, worst 1.605e-03, in the +[Testing](#testing) tally). What a paired run would add is the part the fixture cannot +check: the seeded draw compared against a *recording*, over the parameter rows a request +actually sends. That gap is in +[What is not here yet](#what-is-not-here-yet). + +## Measuring + +**Measure the floor first and name it in the verdict.** 66.8 MB of codes at a part's +22 GB/s is a 3.0 ms floor; 255 MiB at 163 GB/s is 1.64 ms; a 73.1 MB operand is a +0.449 ms read. Against those, "13.6 ms a token" and "24.151 ms at M=64" are statements +about the loop, not the wire. A number with no floor beside it is a feeling. + +**Name the placement of every operand on every timing line.** On a part whose memory +cannot hold the head this is worth an order of magnitude, and it is a property of the +class: at M=1, one kernel, the same head in VRAM is 13.6 ms a token; on the mapped +tier (pinned host bytes read over the host link by 8-byte strided loads) 643 ms; +managed and left alone 2071 ms at 122 MB/s, because managed pages do not migrate for a +read-mostly device access and the kernel faults page by page. A layout hook makes the +mapped placement *legal*, not fast. Boards state which placement produced which +number, time after a prefetch, and note that a container operand must be host-readable +at all (the shim reads its header on the host) — hence pinned or managed, never plain +`malloc`, which faults. + +A number belongs to whoever placed the bytes: the same shape in the same binary +measured 5.911 ms as the first case of a process and 85.7 ms as the second case of a +sequence that had allocated and freed a 24 MiB managed container first — 14.5×, +deterministic, clean run both ways, and at 0.2 GB/s the slow run is reading its +weight over the host link. The row's number is 5.911 ms, because the engine ships +weights to VRAM at load and reads them 44 times. + +**`vgpr_spill_count` is a gate, not a note:** 44 kernels, all zero, both builds of an +A/B. Per-group partials scaled into the accumulator cost 64 more accumulators on an +arm already at 237 VGPRs, and a runtime index into a register array of candidates +spills the array to private memory; both are rewrites, not tunables. A scalar spill in +a compute-shader wavefront is a slow path, not a stall — the ablations below say so +with numbers — so VGPR spills gate and SGPR spills get reported. + +**Number before verdict.** Four things that look like they should work on the +attention unit were measured to not work, and the one width that did move it is +recorded with them +[in the attention section](#the-paged-attention-decode-and-prefill); the tiled rows' +grid-shape cliff is recorded +[in the GEMM section](#the-fp8x8-gemm-by-row-count). A negative result carrying its +numbers is the cheapest documentation in a library: it is the only thing that stops +the next session re-measuring it. + +**Profiled per-op times sum to more than the token, and that is the tool working.** +On the served 2B plan, 61 + 24 + 12.7 + 4.2 = 102 ms of per-op device time against a +measured 87.6 ms token: the engine overlaps its ops, and `--profile-ops` restores the +synchronisations that serialise them — the caveat the served engine prints in its own +startup diagnostics ([`core/diag/checks.cpp`](../core/diag/checks.cpp): *times every op, +which restores synchronisations … drop `--profile-ops` for anything measured*). A per-op +table taken under that flag ranks the work and does not price it, and the token rate is +the price. The pair that proves the reading: the gated row's profiled saving on that plan +was ~44 ms of the 87.6 ms token, and the token got 11.4 ms faster. Quote a served run's +shape with its served numbers — the context length it was taken at, the prompt lengths it +walked — because a ranking is a property of the shape, not of the model. + +## Notes on the kernels + +Three properties are assumed throughout and not restated per kernel: **wave32 with a +1024-entry VGPR file a SIMD**, so every lane map has a lane owning whole dwords and +every budget is computed against 1024; **64 KiB of LDS a workgroup**, which sets the +candidate kernels' `n_cand <= 1024` and the tile sizes; **the dot2 path** (the +wave-matrix fragment layout is a re-tile, not a drop-in for these lane maps), which is +why the tile is a dot loop over LDS with an 8-element XOR swizzle, shared by every +tiled row in [`r3d_tiling.h`](r3d_tiling.h) and proven byte-identical between them. + +**A staged chunk of 8 bytes against a row pitch of 512 is the 2-bit grid moving 8× the +bytes it uses** at `kKC` 32: 24.151 ms at M=64, N=130560, K=2048 against a 0.449 ms +read floor, 3.7 GB/s useful. The lever is a wider k-chunk (64 codes = 16 bytes, paid +for in LDS), not more loads in flight: leading the codes measured 0.6%, bit-identical, +and was reverted. + +**The head is the largest read in a decode step**, and the sampler reads f32 — why the +store is typed, not narrowed, and why a prefill band writes 1.07 GB. bf16 codes: 3.29 +ms a token at M=1 (163 GB/s), 0.507 ms at M=16 (the head read once for sixteen rows), +269 ms at 2048 rows (4067 GFLOP/s). E4M3 codes with a bf16 scale per 128×128 block, +read as the two container planes they are: 13.6 ms a token at M=1, 8× above the 1.64 +ms floor, cause named — the E4M3 decoder, ~100 instructions an eight-code group. The +decoder-as-a-table pass (256-entry f16 table in LDS, 512 bytes, eight reads a group, +exact by construction) is 2.70× where the decoder binds (M=8: 2.500 → 0.924 ms a +token), flat at prefill, and a **named non-result at M=1**: removing ~100 ALU +instructions did not move it. The suspect at M=1 is load width — eight codes a lane +through an 8-byte load, where the bf16 arm takes sixteen bytes a lane at 163 GB/s — so +the next experiment is a 16-byte code load, not more ALU. `rel_l2` between the two +binaries is bit-identical: the check that the swap moved work, not arithmetic. + +**A launch check that does not clear the flag first refuses a healthy step.** +`hipGetLastError()` reports the first error raised *since it was last cleared*, so a +check that does not clear attributes to this launch whatever the process raised before +it: in a served process, the op that ran last; in a comparison run, its own setup. Both +were +seen. The symptom to recognise is a whole timing mode returning the device code on +every geometry of every row, all of it vanishing under `HIP_LAUNCH_BLOCKING=1` — which +is what a synchronous launch does to a pending asynchronous error, it clears it before +the check — and a shim's own text rendering it as something about strides, because the +launcher printed a raw code and the caller appended its own sentence. Two lines fix +it: clear the flag after the arguments are staged and before the chevron, then read it +straight back; and on a refusal, name the error and print the grid, the block, the +waves, the splits and the width the launcher chose. A refusal that does not say what +it saw cost two hours, and the failure mode is a healthy step refused for a symptom a +neighbour caused — the launch is not the suspect. + +**No collective rows, and no chained forms.** The parts this family ships in are +single-GPU, and an all-reduce over the host link most of them sit on is slower than +sending the bytes through the host. Nothing here is built as a chained form, so both +optional symbols are left out — the ABI's own answer, with one less thing to keep in +step. + +## What is not here yet + +Stated as library work, so nobody looks for it in a row table. + +**The 2-bit grid's staging width.** The packed-code tile at prefill heights moves 8× +the bytes it uses at `kKC` 32; the fix is a 64-code chunk (16 bytes a lane) paid for +in LDS — the whole distance between 24.151 ms and a 0.449 ms floor at M=64, N=130560, +K=2048. + +**The skinny-load path for a one-row head.** The E4M3 decode arm loads eight codes a +lane through an 8-byte load and runs 8× above its floor at M=1; the 16-byte load (16 +codes, eight pairs, half the wavefronts) is the experiment, and the decoder table has +been shown not to be the lever. + +**The gated MLP's rows-by-column-groups pass.** The table decoder moved M=64 from +8395.3 to 2786.5 us (best of nine), which is most of the row's story at the ceiling +and none of its floor: the weight read is the wall there, and 47 of the 48 bands +declare the ceiling. Past 64 the fused row refuses and the work is four ops over a +bf16 `[M, N]` tensor — two GEMMs, the gate, the quantiser — so the pass that +amortises the weight read across rows *and* column groups is what stands between the +fused form and the pair it replaces, priced at M=64. + +**The gated row's arm threshold is a tunable.** The crossover between the skinny and +staged arms is above 16 rows and M=9..15 has never been measured; the shipped M ≤ 8 is +chosen for the decode's M=1 and a draft's verify, and the launcher's comment says so +beside the number it selects on. Nine launches a band would move the threshold, not the +kernel, and a band that lives in 9..15 is paying the staged arm for about 7%. + +**`gemm_nt_q_bias` has no row, and the gap is silent.** `gemm_nt_q` has no bias +operand: bias is its own op in the registry (`ref_registry.cpp:1361`, "gemm_nt_q with +a per-column bias"), and this library declares no row for it. So every band carrying a +bias resolves to the reference's host row — correct, slow, and invisible: no `E` line +in the coverage, because nothing refused, and no entry in the profile, because the op +never reaches a device. A model with bias'd projections runs them on the host while +the census reports a clean tree. The row is a bias load in the epilogue of the tiled +rows plus a declared schema; the gap is that nobody has to notice it. + +It is a *model-shaped* gap, not a served one, and the container says so: the checkpoint +measured here declares `draft.attention_bias` and `draft.mlp_bias` with **count 0** — +no planes, no bytes — so by the law that an optional operand with no bytes is absent, +this model carries no bias band and nothing falls. `rad-info -v | grep -i bias` +is the one-line census: a model whose bias tensors have planes is the model this row is +for, and on that model the fall is real and silent. + +**The sliding window over a partially-filled last tile diverges.** The shape is +`window` between 2 and 16, exclusive of 1 and 16, over a query plane whose last tile is +not full: 10 of 60 cases in the row's window matrix, base and work producing +byte-identical planes for all 60 — 10 divergent each, same hashes — so it is in the +shipped row, not in a session's change. The scan: rows 17 at ctx 33 agree at w = 1 and 16 and diverge at w = 2, 3 and +15; ctx 32 at w = 3 agrees where ctx 34 diverges; rows 32 at ctx 48 — two full tiles — +agree where rows 33 at ctx 49 diverge, tile 3 holding one row; rows 18..24 at ctx + 16 +diverge by two rows each. Five runs of rows 17 at ctx 33, w = 3, give the identical plane +hash (`223c70af1e9e5276`): one row of 17, 2044 of 2048 items differing, `rel_l2` +1.196e+00, status 0 from both rows, no non-finite. Served bands are full attention — all +471 `window = 0` cases agree — and the plan's windowed layers use a 2048 window over +16-wide blocks, so no served band walks into it. It is a bounded, named, reproducible +divergence in a row the plan declares, and the fix belongs in the last tile's mask, not in +the window's clamp. A dedicated comparison run reproduces it. + +**`sample_merge_topk`**, the cross-rank candidate merge: under a split vocabulary it +holds `world_size * n_cand` gathered pairs, and there is no row for it here. + +**A seeded-draw comparison for the spine.** kbench grades the `sample_*` bands against +the reference on the fixture, which covers the arithmetic and not the recording: no run +compares the *drawn token* against a captured sequence, over the parameter rows a +request actually sends. The draws are the part of this library a `rel_l2` cannot grade. + +**int8 × int8.** The constraint table is written (`i8a8`, group 128, M ≤ 16, K % 128) +and `quant_act_i8g` already produces the row-major activation it wants; the kernel is +not landed, so the row is not in the table, because a row naming an entry point that +is not in the library is an undefined symbol at `dlopen` and takes every other row +with it. + +**Chunked logits.** The head's f32 plane is written whole (1.07 GB at a 2048-row +prefill band); nothing yet emits it in chunks the sampler consumes in passes. + +**A sub-byte zero plane.** `w2a8` reads a zero point a byte at a time and refuses a +zero stored U2/U4/U5 by name; the bit-extract path is the ten lines `rad_load_bits` +already is for the codes. Written for the codes and not for the zero, and the refusal +is not an approximation. + +**Speculation that pays.** The draft head is served end to end — its bands by the +2-bit grid, its accept step by `dflash_select` — and the accepted text is identical. +The target's head read amortises over the draft block (5× cheaper per token at 8 rows +than at 1 on the same kernel), so what has to pay is the drafter's own steps, and on +the 16-CU part that measured it they did not: 87.6 → 94.4 ms/token on a 5-token +prompt, 91.6 → 187.1 on a 16-token chat band with 7 drafts. The engine's own rule +switches the drafter off for a plugin whose rows measured a gain without them, so the +work left is a draft path that costs less than the head read it saves, not a flag. diff --git a/libr3d/r3d.h b/libr3d/r3d.h new file mode 100644 index 00000000..e4dae930 --- /dev/null +++ b/libr3d/r3d.h @@ -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_(...)`, 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_(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 */ diff --git a/libr3d/r3d_args.h b/libr3d/r3d_args.h new file mode 100644 index 00000000..4738edf6 --- /dev/null +++ b/libr3d/r3d_args.h @@ -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 +#include +#include +#include + +/* ================================================================== 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 */ diff --git a/libr3d/r3d_attn_paged_h128.hip b/libr3d/r3d_attn_paged_h128.hip new file mode 100644 index 00000000..3838d965 --- /dev/null +++ b/libr3d/r3d_attn_paged_h128.hip @@ -0,0 +1,1823 @@ +/* r3d_attn_paged_h128.hip -- paged attention at head_dim 128, the two bands MiniCPM5-2B declares. + * + * out[tok, h, :] = softmax_j( scale * q[tok, h, :] . K[j, h/gqa, :] ) . V[j, h/gqa, :] + * + * over a paged cache, in libref's order. The order is the point of the file: a + * tolerance on an attention output is not where a summation-order difference hides, so this kernel + * keeps the chain the reference writes, and says out loud where it cannot. + * + * ============================== the layout ============================== + * + * kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot + * + * A slot's K is 128 elements and V the 128 after it, so a key's row is a 512-byte pair and both + * halves are 16-byte aligned at every slot. `block_table[seq, j / block_size]` names the block + * holding key j; the fixture *draws* its entries over [0, max_blocks), so ids repeat and one block + * serves several keys. A negative entry is an unmapped block and hides its key -- the engine's + * allocator frees a sequence by writing -1 into rows it is done with, so the kernel keeps the test + * even though the fixture never sets it. `seqused[seq]` is the sequence's TOTAL key count, this + * step's query rows included, so query row i of a len_s-row step sits at absolute position + * `seqused[s] - len_s + i`. One kernel serves decode (q_len 1), a speculative verify (q_len 7) and a + * prefill chunk (q_len 2048). + * + * ============================== the ragged batch ============================== + * + * A step's sequences do not have to contribute the same number of query rows. `cu_seqlens`, when + * the caller has it, is [n_seq + 1] of i32 with cu[0] == 0 and cu[n_seq] == the query plane's row + * count, and sequence s owns the rows [cu[s], cu[s+1]) -- `len_s = cu[s+1] - cu[s]` rows, whose + * positions run from `seqused[s] - len_s`. That is libref's reading and not a local invention: + * its shape hook (`cu[n_seq] == rows`, `q_len = cus ? 0 : rows / n_seq`) and its walk, where + * the row's sequence, its length and its index within the sequence come from the descriptor and the + * position from the sequence's own length. So `q_len` is a PER-SEQUENCE number in the reference and + * in this file; the total row count is the plane's, and a ragged batch has no q_len at all. + * + * One grid covers a ragged batch because the clamp the width section documents is per sequence: a + * tile is `ceil(len_s / rows_per_tile)` tiles for sequence s, and the slots of its last tile past + * `len_s` compute a duplicate that stores nothing. The rows are laid out by `map_seq`, which walks + * the descriptor once a workgroup -- a rectangular batch is the same walk with len_s = q_len and + * cu[s] = s * q_len, so there is one mapping, one mask, one walk and one store for both forms. + * The causal mask, the window, the block-table walk and the descales all key off the sequence the + * row belongs to, exactly as the reference's `s = seq_of(cus, n_seq, tok)` keys them. + * + * ============================== the mask ============================== + * + * causal = 1 key j visible when j <= pos + * causal = 0 key j visible when j < ctx + * window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, the + * two-sided reading libref's prose and libr4d's window kernel both state. + * + * A masked key is skipped, never scored to -inf: the denominator gets exactly the terms the + * reference has, and a row with no visible key stores zeros, which is libref's `mx == -INFINITY` + * case and every other kernel in the project. + * + * ============================== the tile ============================== + * + * An output row is (query row, query head): 128 dims, one f32 chain per dim. A lane owns one output + * row, exactly as the skinny GEMM rows do, and for the same reason -- a lane's chain over keys is + * the reference's chain, and no cross-lane reduction touches the denominator. A wave32 is 32 output + * rows, and they must be 32 rows that read the same KV, which fixes the mapping: + * + * kh = blockIdx.y h = kh * GQA + (lane & (GQA-1)) tok = base + (lane >> lg GQA) + * + * so a wave is the GQA query heads of one KV head over 32/GQA query rows -- 8 heads x 4 rows at + * gqa = 8. Every lane of a wave then reads the same cache row at the same moment, which makes every + * cache read in this file an LDS broadcast (one `ds_read_b128` serves the wave) and makes the paged + * walk a per-wave event rather than a per-lane one. A workgroup is WAVES waves = WAVES x 32 threads + * = WAVES x (32/GQA) query rows of one sequence, one KV head: 16 rows at gqa 8 with four waves. + * WAVES is a template parameter and the launcher picks it -- see "the width of a workgroup" below. + * + * Rows per cache read is 32. It is also the ceiling the register file sets: a lane carrying a second + * output row needs 2 x 64 VGPRs of widened query and 2 x 128 of f32 accumulator, 384, over the 256 + * that four waves a SIMD allows. So the traffic is what gqa and the register file say it is. + * + * ============================== the width of a workgroup ============================== + * + * A row slot whose row is past its sequence's length computes a clamped duplicate: the walk, the + * tile and the store all run for it and the result is dropped. At the decode band's q_len = 7 with + * gqa = 8 a four-wave workgroup carries 16 row slots for 7 rows -- twice the walk for half the + * outputs. So the launcher picks the narrowest workgroup that carries the caller's q_len (pick_waves: + * one wave to 32/GQA rows, two to 64/GQA, four above), and prefill keeps four because its q_len is the + * whole chunk. At the decode band that is two waves: 512 workgroups of 64 threads, 7 of 8 slots used. + * A ragged batch has no one q_len to pick on: the launcher picks on the average sequence + * (`ceil(rows / n_seq)`), which is a performance choice and nothing else -- the tile width moves + * duplicate rows between tiles, never a result, and no host code reads the descriptor. + * + * Measured on the card: medians of 15 per-launch event times, both widths in one session, so the + * clock drifts together (both read the prefill band at 44.9): + * + * decode 256 x 7 @4096 294.7 ms -> 158.4 ms -46% + * decode 256 x 7 @4096 sp4 268.0 ms -> 128.4 ms -52% + * decode 8 x 7 @2048 sp8 4.33 -> 2.06 ms -53% + * decode 1 x 7 @4096 sp8 4.27 -> 3.97 ms -7% + * prefill 2048 x 2048 44.95 -> 44.78 ms the path is unchanged + * + * The tile is the same 8 KiB at every width, so nothing about the cache traffic changes; the win is + * the duplicated rows, and the reason it is this large is the one the counters show: the kernel + * issues 15% of the SIMD's slots at the band (SQ_INSTS_VALU 4.5G against 30G of capacity, + * SQ_INSTS_LDS 769M) and 3.7% at eight sequences. Halving the arithmetic on a kernel that is + * stalling is not supposed to buy 46%; it does, and that says the stall is a function of how many + * waves a workgroup has to bring to a barrier -- two arriving is not twice as cheap as four, it is + * four times cheaper. The width is a run-time choice because it is the only lever on this op that + * moves the band. + * + * ============================== measured, and not the answer ============================== + * + * Four things that look like they should work, each measured to not (medians of 15 per-launch + * hipEventElapsedTime, A/B in one process), so the next reader does not spend an hour on them: + * + * s_setprio 1 around the consume leg of the walk, 0 after: |delta| <= 0.7% on the bands. The + * knob is fine -- `s_setprio` takes an immediate, not an SGPR, so `s_setprio %0` will not link -- + * but priority does not move this op. + * + * R3D_WAVES(2) to lift the scalar-register ceiling: the bf16 arms report sgpr_count 107 and + * sgpr_spill_count ~98 at BOTH 4 and 2 waves a SIMD, and the timings do not move. The + * compute-shader scalar budget is not set by waves/SIMD the way the VGPR one is, so this is not + * a lever for the spills. + * + * __noinline__ on the stage leg: the spills drop (98 -> 72) and a 160-byte private frame + * appears, timings unchanged. The spills are a load-safety matter, not a time matter: while the + * bf16 arms spill SGPRs, a kernel in this TU that also needs a private segment fails to launch + * with "the operation cannot be performed in the present state". + * + * A two-stage pipeline -- two tiles, the next block's global loads issued before the current + * block is consumed, one barrier a block instead of two: a wash on the bands. The walk's + * per-block structure is the cost, and the two legs do not overlap at all -- the workgroup's + * width is the lever. + * + * ============================== the walk ============================== + * + * block_size = 16, so keys advance 16 at a time and one step stages a block of the KV head: 16 slots + * x 128 elements, K and V, widened to f16 pairs on the way in, 4 KiB each. The four waves of a + * workgroup share the stage, so a block of cache is one global read per workgroup per pass, and the + * walk costs 8 KiB of the 64 KiB of LDS. The second pass re-reads the same blocks; a sequence's + * cache for one KV head is ctx x 256 B, which at 4096 keys is 1 MiB, so the second pass is an L2 + * hit and the card's DRAM sees each byte once. + * + * The mask sits where the geometry puts it: a wave's query rows are consecutive, so at gqa 8 its + * four positions span 3 and its diagonals lie in one 16-key block, two at a block boundary. Blocks + * entirely below the wave's minimum position are walked with no mask code at all; the one or two + * diagonal blocks test `j <= pos` per lane; blocks past the wave's maximum position are not walked. + * In a 2048-token causal prefill that is one masked block in sixty-four. + * + * ============================== the two passes ============================== + * + * The reference is two-pass: pass one every visible key's score and the maximum; pass two, ascending + * keys, `w = exp(score - max)`, `sum += w`, `acc[d] += w * v[d]`, then `acc * (1/sum)` and one + * narrowing at the store. Online softmax -- the flash form, rescaling a running accumulator by + * `exp(m_old - m_new)` -- brackets the denominator and every acc[d] differently, so it is not in + * this file. Keeping the scores as the reference does costs a workspace of jcap floats a row: 32 + * rows x 4096 keys = 512 KiB a wave against 64 KiB of LDS. So the two passes are two walks, and + * pass two recomputes the scores it needs -- same order, same operands, bit-identical the second + * time. QK is paid twice and the op costs half again what keeping the scores would; that is the + * price of the reference's parentheses. + * + * QK is 64 `v_dot2acc_f32_f16` a key a lane over widened f16 pairs, ascending d. A dot2 folds a + * pair's two products into the accumulator in one rounding where the reference rounds per product, + * so a lane's score chain brackets the reference's: the same one-ulp departure the bf16 GEMM row + * documents, on a fraction of a percent of outputs, one bf16 store ulp each. + * + * P . V is 128 f32 multiply-accumulates a key a lane, `acc[d] += w * v[d]` with -ffp-contract=off, + * which is the reference's expression with vds already folded into the staged V. dot2 cannot do this + * leg in this layout: w is a per-lane scalar and the accumulation is per dim, so the only route to + * the matrix path is to fold w into V -- and w is f32, so every weight of the sum would be read to + * 11 bits, a ~1e-4 relative change on the output that survives the bf16 store as a few percent of + * outputs moved one ulp. It is a third of the instruction count, and it is not the default; the + * numbers this unit is measured with are the f32 leg's. + * + * ============================== exp ============================== + * + * `ref_exp` is `(float)std::exp((double)x)`: the reference's exponent is correctly rounded to f32 + * through a double. RDNA3 has no vector f64 -- double is soft-float, hundreds of cycles a call, and + * a call per key per lane is the whole kernel. The device libm's `expf` is a ~1-ulp polynomial and + * `__expf` is two orders of magnitude worse. `exp_ref` is a software expf: two-term range reduction + * against a split ln2, a degree-8 polynomial, and 2^k assembled in the integer domain (no libm call + * in the hot path). It is the only place in this library where an explicit `__fmaf_rn` is allowed, + * and the rule it is an exception to is the no-FMA rule: that rule exists because libref's + * expressions contain no FMA and a contracted multiply-add changes the order of rounding in + * arithmetic we are required to reproduce. Here the thing we must reproduce is a *function* libref + * computes in double precision on hardware that has f64 and this card does not. The polynomial's + * FMA is arithmetic we chose, scoped to this helper, to get the closest legal transcription of that + * function; it contracts no expression the reference wrote. + * + * `exp(0)` is exactly 1.0: k is 0, the reduction leaves r exactly 0, and the polynomial's constant + * term passes through untouched. The argument here is always <= 0 (the max is taken over the same + * set the exponentials are taken of), so the domain that matters is x <= 0. Below -103.98 the + * result is under f32's smallest subnormal and the helper returns 0; the reference's + * `(float)exp(-100)` is a denormal of order 3.7e-44, and a term that small added to a denominator + * of order 1 is not a change of any kind, let alone one that survives a bf16 store -- which is the + * reason the flush is legal and not an approximation to defend. Between -103.98 and -87.3 the + * result is subnormal, and the helper reaches it by one hardware multiply by 2^-126, so it is + * rounded the way the hardware rounds and not by hand. + * + * ============================== split-KV ============================== + * + * The decode entry takes `splits`: a sequence's blocks are cut into slices of a whole number of + * blocks, each slice accumulating its own (acc[128], sum, max) into scratch, and a second kernel + * combines the slices before the single narrowing. Combining needs the slices' maximum, so each + * slice's partial is rescaled by `exp(m_slice - M)`: the denominator becomes + * `sum = Σ_slices sum_s * exp(m_s - M)`, ascending in slice, and every term arrives as + * `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`. Both are last-bit at the f32 + * level -- ~2 ulp per term, ~1 ulp on the sum -- and both vanish under the bf16 store except on + * outputs sitting on a rounding boundary. The row's prose says `splits > 1` is not bit-identical to + * the reference and `splits = 1` is. + * + * `splits` is a maximum, resolved per sequence from its own `seqused`: `nslice = ceil(nblk / + * ceil(nblk / splits))` with nblk the sequence's block count, so a short sequence uses fewer slices + * and there is no per-sequence legality check to fail. `nslice` is recomputed by the reducer from + * the same two numbers, so the partials need no header beyond (acc, sum, max). + * + * ============================== what the shims refuse ============================== + * + * head_dim other than 128 (`RAD_E_SHAPE`; this file is named for it); a cache dtype other than bf16 + * and fp8_e4m3 -- an f32 cache has no dot2 path, and u8/u4/int8 codes are not this cache form + * (`RAD_E_DTYPE`); a query dtype other than bf16 or f16, and an out dtype that is not the query's + * (`RAD_E_DTYPE`); gqa outside {1,2,4,8} or not dividing n_head (the wave's head split is a shift); + * block_size other than 16 (the stage is sized for one); q_len < 1 in a rectangular batch, and a + * row count < 1 in a ragged one; a row count that does not fit the plane's 32-bit row indexing + * (num_seqs * q_len, or cu[n_seq], past 2^31); a q, kv or out stride that puts a slot's halves off + * a 16-byte boundary, or a row pitch that is not a multiple of 8; a `cu_seqlens` that is not i32 + * (`RAD_E_DTYPE` -- the kernel reads int, and the fix is an i32 plane, which is what the op + * describes), is not contiguous (`RAD_E_STRIDE`), is not [n_seq + 1] (`RAD_E_SHAPE`), or is not + * 4-byte aligned (`RAD_E_ALIGN`); descales attached to a bf16 cache, which the reference ignores + * and this kernel refuses rather than drops, and an fp8 cache missing them (`RAD_E_SHAPE`); an + * output shorter than rows * n_head * head_dim; and a scratch arena too small for the partials the + * requested `splits` needs, which the launcher answers by lowering `splits` to what the arena + * holds, down to 1, which needs none. + * + * What the descriptor carries that the host cannot see is clamped, not refused, because a launcher + * reads no device memory: cu[0] == 0, monotonicity and cu[n_seq] == the plane's row count are the + * description's promises (the reference's shape hook states all three), and the kernel's answer to each + * is the reference's own. Rows past the plane are dropped (`row_ok` tests the plane's row count, so + * a descriptor that runs long cannot write outside `out`); a segment with cu[s+1] <= cu[s] has no + * tiles and contributes no rows, which is the reference's `if (qlen <= 0) return;` + * (the reference's walk); and rows under cu[0] belong to sequence 0 with a negative index into its + * query, which is what `seq_of` gives them. + */ +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +#include + +#include +#include /* size_t, in the arena indexing and the shim's scratch sizing */ +#include /* the device print, behind the budget; the shims already use std::fprintf */ +#include /* std::getenv / std::atoi, in the arming */ + +/* ================================================================== the device record ring + * + * THE LAW. A kernel that calls device `printf` is given an extra implicit argument -- + * `hidden_hostcall_buffer` -- and the engine's AQL dispatcher does not provide it, so a kernel that + * prints is UNDISPATCHABLE BY THE ENGINE: the instrument is not merely silent, the row is refused, + * and a gate that hipLaunches by hand cannot see it. The kernel therefore writes; it does not speak. + * The shim drains the ring to stderr, which is a host facility and costs the kernel nothing. + * + * Four plugin-owned device globals, and nothing else is added to the kernel: the launch parameters + * are fixed, `RadArgs` is the row's ABI and the plan builds it, so a field cannot join it (and `abi/` + * is untouched). The kernel owns these; the shim resolves them with `hipGetSymbolAddress` (once, + * cached) and, ONLY under `RAD_R3D_TRACE`, writes the budget with `hipMemcpyToSymbol`. + * + * r3d_dev_budget records left to write; 0 -- its initial value -- means record nothing + * r3d_dev_launches launches seen, incremented once per launch by the same thread that records + * r3d_dev_widx the ring's write index, bumped once per record written + * r3d_dev_ring kDevRing records, a fixed struct, 216 bytes each: 55 KiB, allocated once + * + * Why they exist: the engine's recorded pass plays a decode step by writing queue packets, and a + * play never reaches a plugin shim. The shim is not in the path of a played step. The kernel is. So + * the kernel writes down what it was handed: the step's `ctx` as the row reads it off `seqused`, the + * block ids as the walk reads them off the table, the operand addresses baked into the packet, and + * three content folds -- the query row, the K row of the FIRST block the row walks, the K row of the + * LAST one -- so a block whose BYTES move underneath a step is visible: the adopted prefix whose + * recycled block still holds the previous tenant's KV, and the address slip that serves fluent, + * plausible, wrong text. + * + * A played step's record is written on the device and printed at the NEXT shim call, so a served + * log's lines land one step behind the step they describe. The + * record's own `L` and `ctx` restore the order, and the shim's plan line quotes the same counter, so + * the gap between the two prints is the played pass, measured. + * + * Inert when the flag is unset: the budget is 0, so a launch pays one uniform scalar load of a + * global and one not-taken branch, on one thread of one workgroup, plus the atomic increment of the + * counter. The bound is decremented with `atomicSub` -- 16 CUs cannot record 16 copies of one launch + * -- and the counter is `atomicAdd` before it, so a launch counted is a launch that ran, played ones + * included. The ring is bounded (kDevRing slots): a harness that arms more than the ring holds loses + * records, never the count, and the shim says so on one line. + * + * The counter counts every `attn_kernel` launch, budget or not. It does NOT count the split-KV + * reduce: that kernel is a second launch of a step's work, not a step. */ +enum { kDevRing = 256, kDevIds = 8 }; + +/* One launch, as the launch saw it. A fixed plain-old struct: no pointers, no float, no padding the + * reader has to guess. The ids are the row's first kDevIds columns -- `block_size` 16 and a served + * ladder's 21 to 33 token contexts make that two columns, so the whole row fits -- and `idsum` folds + * every column, so a 4096-token context still has one comparable number for its row. */ +struct DevRec +{ + unsigned long long L; /* the launch's own ordinal */ + long long ctx, pos, slot0, slotL, idsum; /* the step as the row reads it, and where */ + unsigned long long qh, kh, khL; /* three content folds */ + unsigned long long kv, bt, su, cu, q, out; /* the six addresses baked into the packet */ + int dec, n_seq, rows, q_len, s, len, span, start; + int jcap, splits, waves, ncols, rowok, spare, spare2, spare3; + int b[kDevIds]; /* the row's ids; `ncols` of them are real */ +}; + +extern "C" __device__ int r3d_dev_budget = 0; +extern "C" __device__ unsigned long long r3d_dev_launches = 0ULL; +extern "C" __device__ unsigned r3d_dev_widx = 0u; +/* `= {}` is load-bearing: an uninitialised `__device__` variable emits no host-side symbol, and + * the engine's loader dlopens the plugin with the symbol live, so it stops with + * `undefined symbol: r3d_dev_ring` before a single row is declared. The zero fill is the device + * side's init, and it is what the flag-unset state is. */ +extern "C" __device__ DevRec r3d_dev_ring[kDevRing] = {}; + + +namespace { + +typedef float r3d_f32x4 __attribute__((ext_vector_type(4))); + +constexpr int kHeadDim = 128; +constexpr int kPairs = kHeadDim / 2; // f16 pairs a head: one dword is two dims +constexpr int kBlock = 16; // block_size: a step stages one of these +constexpr int kWaves = 4; // 128 threads +constexpr int kThreads = kWaves * 32; +constexpr int kPitch = kPairs; // dwords a staged row; rows are read as broadcasts +constexpr int kTileDw = kBlock * kPitch; // 1024 dwords = 4 KiB +constexpr int kPartStride = kHeadDim + 4; // acc[128], sum, max, pad -- 528 B, whole 16 B rows + +/* ------------------------------------------------------------------ exp */ + +/* exp(x) narrowed to f32, as close to `(float)std::exp((double)x)` as an ALU with no f64 gets. + * + * Measured against `(float)std::exp((double)x)` over 1.31M points of [-100, 0] and the boundary + * cases: every point is within one f32 ulp, 76.1% bit-identical (the device libm's expf is 94.0% + * identical and no better in ulps), exp(0) is exactly 1. The tail below 2^-126 -- x under about + * -87.3 -- comes out zero, not subnormal: the scaling multiply that assembles the subnormal is + * flushed by the hardware. That is invisible at the store, which is where the reference is + * compared: a weight of 1e-38 next to a maximum weight of exactly 1 cannot move an accumulator, and + * the bf16 store has no resolution at that ratio. + * + * Reduce by ln2 against a two-term constant: k = rn(x / ln2), r = x - k*LN_HI - k*LO with LN_HI the + * high 24 bits of ln2 and LO what is left. A single-term reduction is what makes the naive version + * 1.5 ulp -- k*ln2 is not representable, and the subtraction's cancellation is the whole error + * budget. |r| <= 0.35, where a degree-8 polynomial reaches ~0.55 ulp, then 2^k by exponent + * assembly. */ +__device__ __forceinline__ float exp_ref(float x) +{ + /* Above the overflow point the reference's own double path yields +inf, so this one must too; + * a NaN in, a NaN out. Both cases are outside the softmax's reach (the argument is a score + * minus the row's maximum, never positive), and are here so the function is an exp, not a + * softmax helper with an undefined edge. */ + if (!(x < 88.7228390525719f)) + return x == x ? __int_as_float(0x7f800000) : __int_as_float(0x7fc00000); + if (x < -103.9720770839916f) return 0.0f; /* under the subnormals: see header */ + const int k = (int)__float2int_rn(x * 1.4426950408889634f); + const float LN_HI = 0.693145751953125f; /* ln2, high bits, exactly a float */ + const float LN_LO = 1.42860681039557e-06f; /* ln2 - LN_HI */ + float r = x - (float)k * LN_HI; + r = r - (float)k * LN_LO; + /* e^r, |r| <= 0.35: 1 + r + r^2/2 + sum(r^i / i!), i = 3..8, Estrin over r^2. */ + const float c8 = 1.98412698412698e-04f, c7 = 1.38888888888889e-03f; + const float c6 = 8.33333333333333e-03f, c5 = 4.16666666666667e-02f; + const float c4 = 1.38888888888889e-01f, c3 = 1.66666666666667e-01f; + const float r2 = r * r; + const float p4 = __fmaf_rn(__fmaf_rn(__fmaf_rn(c8, r, c7), r, c6), r, c5); + const float p2 = __fmaf_rn(p4, r2, __fmaf_rn(c3, r, 5.0e-01f)); + const float e = __fmaf_rn(p2, r2, __fmaf_rn(r, 1.0f, 1.0f)); /* in [0.70, 1.42] */ + /* Scale by 2^k in the exponent field; x <= 0 here, so the normal case is the whole story and + * the subnormal one is a single hardware multiply. */ + const int be = __float_as_int(e); + const int field = ((be >> 23) & 0xff) + k; + if (field >= 1) return __int_as_float((be & 0x007fffff) | (field << 23)); + if (field <= -23) return 0.0f; + const float t = __int_as_float((be & 0x007fffff) | ((field + 126) << 23)); + return t * __int_as_float((127 - 126) << 23); /* one rounding, the hardware's */ +} + +/* ------------------------------------------------------------------ the kernel's view */ + +struct Args { + const uint16_t* q; /* bf16 or f16 (q16), rows x n_head x head_dim */ + const uint16_t* kv; /* bf16 cache */ + const uint8_t* kv8; /* E4M3 cache, when FP8 */ + const int* bt; /* block table, i32: the shim refuses i64 indices */ + const int* su; /* seqused, i32 */ + const int* cu; /* cu_seqlens, n_seq + 1, i32; null = q_len rows each */ + const float* kds; + const float* vds; + uint16_t* out; + float* part; /* split-KV partials */ + + /* Strides are elements, and 32-bit: a cache is blocks x kv_heads x 16 x 256 elements, a row + * pitch is n_head x head_dim, a block table pitch is max_blocks, and the launcher checks that + * each fits. Every address in this kernel is a 64-bit base plus a 32-bit product, and the + * register allocator is out of scalar registers long before it is out of vector ones -- the + * wavefront runs in compute-shader mode, where a scalar spill is not a slow path, it is a + * kernel the runtime refuses to load. */ + int sb, sh, so, sd; /* cache strides */ + int q_rs, o_rs; /* row pitches; the head stride is head_dim */ + int bt_rs; /* the block table row pitch, in entries: the tensor own stride */ + int bt_cs; /* its column stride: 1 for every dense table the engine builds */ /* block table pitch */ + int n_seq, q_len, rows, n_head, kv_heads, causal, window, jcap, splits, q16, waves; + float scale; + DevRec* trace_buf; /* one record slot, a plain hipMalloc buffer: the device + * globals are stubs in a dlopened plugin, the buffer is not */ +}; + +__device__ __forceinline__ long long ld_ix(const int* p, size_t i) { return p[i]; } + +/* ------------------------------------------------------------------ the row map + * + * One map for both batch forms. With a descriptor, sequence s owns the query rows [cu[s], cu[s+1]) + * -- `len_s` rows, the row's index within the sequence `i = row - cu[s]`, its absolute position + * `seqused[s] - len_s + i`. Without one, the same walk with len_s = q_len and cu[s] = s * q_len, + * which is the reference's own rectangular reading, not a parallel implementation + * of it. + * + * A grid row is resolved by subtracting each sequence's tile count from blockIdx.x until the + * remainder fits: n_seq int loads and n_seq subtractions, once per workgroup, against a walk of + * nblk blocks with two barriers each. The descriptor is device memory and a launcher reads none of + * it, so the grid is sized on the bound in `launch` and a grid row past the batch's last tile comes + * back with tile < 0 and leaves, having staged nothing. + * + * `start` is the sequence's first dense row and `i0` the row its positions count from. They differ + * only when cu[0] > 0: the reference's `seq_of` hands rows under cu[0] to sequence + * 0 with a negative index into its query, and that is transcribed rather than refused because a + * descriptor that does not start at 0 is a caller's arithmetic slip, not a geometry this kernel has + * to be wider than. Both are 32-bit: they index rows of a plane whose element offsets the launcher + * has already checked fit in 31 bits. */ +struct RowMap { int s, tile, start, i0, len, span; }; + +__device__ __forceinline__ RowMap map_seq(const Args& A, const int tpb, int g) +{ + const int n = A.n_seq; + for (int s = 0; s < n; ++s) { + const int c0 = A.cu ? (int)ld_ix(A.cu, (size_t)s) : s * A.q_len; + const int c1 = A.cu ? (int)ld_ix(A.cu, (size_t)(s + 1)) : c0 + A.q_len; + const int start = (s == 0 && c0 > 0) ? 0 : c0; + const int nr = c1 - start; + const int nt = nr > 0 ? (nr + tpb - 1) / tpb : 0; /* tpb is a template constant */ + /* TWO counts that are easy to conflate. `len` is the sequence's query length, + * cu[s+1] - cu[s], and it is what the positions count from (the reference: qlen, and + * pos = ctx - qlen + i). `span` is the number of rows this sequence's TILES carry, + * cu[s+1] - start, and the two differ by exactly cu[0] on sequence 0 of a descriptor that + * does not start at row 0: `start` reaches below cu[0] because seq_of hands those rows to + * sequence 0 with a negative index, so the tiles must cover `span` rows, and only `len` of + * them are inside the sequence. The store below is checked against the span and the + * positions against the length: bounding the tile slots by `len` drops the last cu[0] + * rows of the QUERY PLANE -- a silent, partial, in-bounds shortfall. */ + if (g < nt) return RowMap{ s, g, start, c0, c1 - c0, nr }; + if (s + 1 >= n) return RowMap{ s, -1, start, c0, c1 - c0, nr }; /* past the batch's tiles */ + g -= nt; + } + return RowMap{ n - 1, -1, 0, 0, 0, 0 }; +} + +/* The same walk for a row, not a tile: which sequence owns dense query row `r`. The reducer needs + * it because a partial is indexed by (row, head) and its slice count is the SEQUENCE's block count. */ +__device__ __forceinline__ int seq_of_row(const Args& A, int r) +{ + const int n = A.n_seq; + for (int s = 0; s < n; ++s) { + const int c1 = A.cu ? (int)ld_ix(A.cu, (size_t)(s + 1)) : (s + 1) * A.q_len; + if (r < c1 || s + 1 >= n) return s; + } + return n - 1; +} + +/* ------------------------------------------------------------------ staging */ + +/* Sixteen E4M3 codes -- one 16-byte load, the aligned unit a slot's 128-byte half divides into -- as + * eight f16 pairs, descaled on the way. A code is exact in f16, so a power-of-two descale (every real + * cache scale) costs a multiply and no rounding at all; a general descale is rounded once, toward + * zero by the packing instruction, where the reference keeps it in f32. The bf16 path has no descale, + * so it has no rounding to report. */ +__device__ __forceinline__ void codes16_to_f16x8(const uint8_t* p, float s, uint32_t* w) +{ + const r3d_u32x4 c = *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)p; + const uint32_t d[4] = { c.x, c.y, c.z, c.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const float a0 = e4m3_to_f32((uint8_t)(d[j] & 0xffu)) * s; + const float a1 = e4m3_to_f32((uint8_t)((d[j] >> 8) & 0xffu)) * s; + const float a2 = e4m3_to_f32((uint8_t)((d[j] >> 16) & 0xffu)) * s; + const float a3 = e4m3_to_f32((uint8_t)(d[j] >> 24)) * s; + w[j * 2] = f16x2_pack(a0, a1); + w[j * 2 + 1] = f16x2_pack(a2, a3); + } +} + +/* Stage one block of one KV head: 16 slots x 128 elements, K and V, widened to f16 pairs. + * + * A slot's halves are 512 bytes apart and each 256 of them, so a bf16 chunk of 8 elements is 16 + * bytes and lands on a 16-byte boundary; an E4M3 chunk of 16 codes is 16 bytes and lands there too. + * A chunk of 8 codes is 8 bytes and does not -- a misaligned 16-byte load on this hardware returns + * garbage, which is the whole difference between the two chunk sizes below. 128 threads, one chunk of + * K and one of V each for the cache, two each for the bf16: 256 chunks of 16 bytes a half, 8 KiB of + * tile, two loads and two stores a thread. + * + * Every offset is 32-bit and the launcher has checked that the whole cache fits in 2^31 elements: + * the wavefront runs in compute-shader mode, where a scalar spill is not a slow path but a kernel the + * runtime refuses to load, and 64-bit index arithmetic across a loop like this one is what fills the + * scalar bank. */ +template +__device__ __forceinline__ void stage(Args const& A, uint32_t* sK, uint32_t* sV, int blk, int kh, + float kds, float vds, int tid) +{ + constexpr int kC = FP8 ? 16 : 8; /* elements a 16-byte chunk */ + constexpr int kCPH = kHeadDim / kC; /* chunks a half, a slot */ + constexpr int kChunks = kBlock * kCPH; /* 128 code chunks, 256 bf16 */ + constexpr int kIter = kChunks / NTH; /* bf16: 8, 4, 2 at a wave, two, four */ + static_assert(kIter * NTH == kChunks, "the stage must divide into whole per-thread trips: " + "a bounds check inside the unrolled loop keeps the " + "loop from unrolling, and the loop-invariant operands " + "then get hoisted into scalar registers"); + const int base = blk * A.sb + kh * A.sh; /* this head's block, elements */ + +#pragma unroll + for (int u = 0; u < kIter; ++u) { + const int t = tid + u * NTH; + const int slot = t / kCPH; + const int c = (t % kCPH) * kC; /* element offset in the half */ + const int k0 = base + slot * A.so + c; + const int v0 = k0 + kHeadDim; + uint32_t* dk = sK + slot * kPitch + c / 2; + uint32_t* dv = sV + slot * kPitch + c / 2; + if constexpr (FP8) { /* codes: element and byte agree */ + codes16_to_f16x8(A.kv8 + k0, kds, dk); + codes16_to_f16x8(A.kv8 + v0, vds, dv); + } else { + const r3d_u32x4 ka = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(A.kv + k0); + const r3d_u32x4 va = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(A.kv + v0); + const uint32_t kd[4] = { ka.x, ka.y, ka.z, ka.w }; + const uint32_t vd[4] = { va.x, va.y, va.z, va.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) { + dk[j] = bf16x2_to_f16x2(kd[j]); + dv[j] = bf16x2_to_f16x2(vd[j]); + } + } + } +} + +/* ------------------------------------------------------------------ the walks */ + +/* The keys a lane may see: j is a candidate for the wave, the predicate is per lane. */ +__device__ __forceinline__ bool visible(int j, long long pos, int causal, int window) +{ + if (causal && (long long)j > pos) return false; + if (window > 0) { + const long long d = pos - j; + if (causal ? (d >= window) : (d >= window || d <= -window)) return false; + } + return true; +} + +__device__ __forceinline__ float score_of(const uint32_t* qf, const uint32_t* kp, float scale) +{ + float dot = 0.0f; +#pragma unroll + for (int p = 0; p < kPairs; ++p) dot = dot2_f16x2(qf[p], kp[p], dot); + return dot * scale; +} + +/* ------------------------------------------------------------------ the launch's own voice + * + * Two content folds and one line, printed from ONE thread of ONE workgroup of a launch. + * + * `fold64` is FNV-1a over 64-bit words -- multiply, xor, per word; no float arithmetic, no + * reduction that a compiler could contract. The spelling is exact and the board's host-side fold + * copies it byte for byte, because a hash the driver cannot recompute is a number nobody can check. + * It is order-sensitive by construction (a permuted row is a different hash), which is the property + * that makes the layer-major addressing slip visible: the same 128 elements read at a layer-major + * offset fold to something else. + * + * The words are the row's OWN bytes, read as the walk reads them: the query row at + * `q + row * q_rs` for head 0 -- head 0 is the first head of kv-head 0, and 128 bf16 elements are + * the 32 words -- and the K row of the block the walk names FIRST, at `blk * sb + kh * sh + + * slot * so`, the same arithmetic `stage()` uses (this file has no `slot_of` helper; `slot_k_off` + * spells it out here so the print prints it). 128 elements are 16 words of E4M3 codes and 32 of + * bf16. Both rows are 16-byte aligned: the shim checks a 16-aligned cache, query and output base + * and a row pitch that is a multiple of 8 elements, and the header's layout note puts a slot's K on + * a 16-byte boundary at every slot. + */ +__device__ __forceinline__ unsigned long long fold64(const void* p, int words) +{ + const unsigned long long* w = (const unsigned long long*)p; + unsigned long long h = 14695981039346656037ULL; /* FNV-1a 64 offset basis */ + for (int i = 0; i < words; ++i) h = (h * 1099511628211ULL) ^ w[i]; + return h; +} + +__device__ __forceinline__ long long slot_k_off(const Args& A, int blk, int kh, int slot) +{ + return (long long)blk * A.sb + (long long)kh * A.sh + (long long)slot * A.so; +} + +/* One record per launch, from block (0,0,0), thread 0, into the ring. `noinline` on purpose: the + * walk's register budget is the scarcest thing in this file (see the stride note on Args -- a scalar + * spill is a kernel the runtime refuses to load), and a writer that a traced run runs once a launch + * must not be inlined into the middle of the mapping code that every launch runs. + * + * This function reads memory, so its bounds are the subject. THREE reads, three bounds: + * + * the query row bound: the PLANE's row count `A.rows`, the same bound the kernel checks + * before it stores (`M.start + tok < A.rows`, in the caller). `row` is the + * caller's clamped row index: the grid is sized on a bound, so a tile can name + * rows the plane does not have, and `row_ok` says whether this one is real. A + * band key (`q_len`) and the sequence's length are bounds on the SHAPE the shim + * accepted, not on the plane, and the clamp exists because the grid exceeds + * them; reading through a band key is the out-of-bounds this guard kills. A tile + * the batch has no rows for records `qh=0, rowok=0` -- the record says it did + * not read, and `L` still counts the launch. + * the table's row bound: the columns the WALK can name, ceil(jcap / block_size), where + * jcap = min(ctx, bt_cols * block_size), so a column under it is a column the + * shim proved when it sized the table from the tensor (row pitch plus bt_cols + * columns fit, at the table's own pitches), and the row is `M.s * bt_rs` with + * `M.s` a sequence index the mapping clamped. + * the cache bound: a block id is one the table names, and the shim insists every index + * the walk can reach is inside the cache's plane (`0 <= id < num_blocks`, plus + * the dense-stride requirement). The fold reads the slot-0 K row of kv-head 0 at + * the offset `stage()` computes, kHeadDim elements: 256 bytes of bf16, 128 of + * fp8, both inside a slot's 2*kHeadDim. A negative id -- an unmapped slot prints + * -1 -- folds to 0 and is not dereferenced. */ +template +__device__ __noinline__ void dev_record(const Args& A, const RowMap& M, long long row, bool row_ok, + long long ctx, int jend_all, long long pos) +{ + /* A launch that runs is a launch that is counted, budget or not: this is the number that stops + * the decode steps of a request being inferred from shim lines. */ + const unsigned long long n = atomicAdd(&r3d_dev_launches, 1ULL) + 1ULL; + /* The bound, decremented atomically, so 16 CUs cannot record 16 copies of one launch. A caller + * that armed 3 gets 3 records, wherever in the run they fall. The buffer channel bypasses the + * bound: it is one slot per launch, drained at the launch, and the budget is a device global + * that the engine process cannot arm. */ + if (!A.trace_buf && atomicSub(&r3d_dev_budget, 1) <= 0) return; + + DevRec r; + r.L = n; + r.dec = A.rows == 1 ? 1 : 0; + r.n_seq = A.n_seq; r.rows = A.rows; r.q_len = A.q_len; + r.s = M.s; r.len = M.len; r.span = M.span; r.start = M.start; + r.ctx = ctx; r.pos = pos; r.jcap = jend_all; r.splits = A.splits; r.waves = A.waves; + r.kv = (unsigned long long)(uintptr_t)(FP8 ? (const void*)A.kv8 : (const void*)A.kv); + r.bt = (unsigned long long)(uintptr_t)A.bt; + r.su = (unsigned long long)(uintptr_t)A.su; + r.cu = (unsigned long long)(uintptr_t)A.cu; + r.q = (unsigned long long)(uintptr_t)A.q; + r.out = (unsigned long long)(uintptr_t)A.out; + + const int cols = (A.jcap + kBlock - 1) / kBlock; /* <= bt_cols, by jcap's bound */ + const long long r0 = (long long)M.s * A.bt_rs; + r.ncols = cols; + unsigned long long is = 14695981039346656037ULL; /* the fold64 basis, so a sum of ids is a + * fold of them, spelled the same way */ + for (int c = 0; c < cols; ++c) { + const int b = (int)ld_ix(A.bt, (size_t)r0 + (size_t)c * (size_t)A.bt_cs); + is = (is * 1099511628211ULL) ^ (unsigned long long)(unsigned int)b; + if (c < kDevIds) r.b[c] = b; + } + for (int c = cols; c < kDevIds; ++c) r.b[c] = -2; /* a column the row does not have. -2 is + * not -1, which is an unmapped block */ + r.idsum = (long long)is; + + /* The query row, under the plane's bound, named above. */ + const bool q_ok = row_ok && row >= 0 && row < A.rows; + r.rowok = q_ok ? 1 : 0; + r.qh = q_ok ? fold64(A.q + row * (long long)A.q_rs, kHeadDim / 4) : 0ULL; + + /* The head K row of the first block the row WALKS, and of the last block it walks. The walk's + * extent is `jend_all = min(ctx, A.jcap)` keys, so the blocks it visits are `ceil(jend_all / + * kBlock)` — NOT the table's `cols`: the table row is the plane's full capacity (64 columns at + * a 4096 cap) and its far columns are `-1` for a short context, a fold of which is a fold of + * nothing. `ncols` and `idsum` keep the whole table row — that is the census — while `kh`, + * `khL`, `slot0`, `slotL` and `bL` are the walk's two ends: the head of an adopted prefix and + * the tail the step is writing, where a recycled block shows up. */ + const int walk_cols = (jend_all + kBlock - 1) / kBlock; + const int b0 = walk_cols > 0 ? r.b[0] : -2; + const int blast = walk_cols > 0 + ? (int)ld_ix(A.bt, (size_t)r0 + (size_t)(walk_cols - 1) * (size_t)A.bt_cs) + : -2; + const long long k0 = b0 >= 0 ? slot_k_off(A, b0, 0, 0) : 0; + const long long kL = blast >= 0 ? slot_k_off(A, blast, 0, 0) : 0; + r.slot0 = k0; r.slotL = kL; + r.kh = b0 < 0 ? 0ULL : (FP8 ? fold64(A.kv8 + k0, kHeadDim / 8) : fold64(A.kv + k0, kHeadDim / 4)); + r.khL = (kL == 0) ? 0ULL + : (FP8 ? fold64(A.kv8 + kL, kHeadDim / 8) : fold64(A.kv + kL, kHeadDim / 4)); + r.spare = blast; /* the id the last fold is of, printed */ + r.spare2 = cols; r.spare3 = 0; + + /* One slot, claimed by one atomic. Past the ring's end a record is counted and dropped: the + * counter keeps the truth, and the shim prints one line saying how many were lost. The struct is + * filled in a local and copied in one statement so the writer is one block of stores; a drain + * runs at a shim call, after the engine has synced the step, so it reads slots that are written + * whole. */ + const unsigned w = atomicAdd(&r3d_dev_widx, 1u); + if (w < (unsigned)kDevRing) r3d_dev_ring[w] = r; + if (A.trace_buf) A.trace_buf[0] = r; /* the engine-process channel: no symbol between us */ +} + +/* One wave's work: GQA heads x 32/GQA rows, over its slice of one sequence's blocks, for one KV + * head. CAUSAL and SPLIT are template parameters because both change the loop, not just a flag. */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) +void attn_kernel(const Args A) +{ + __shared__ uint32_t sK[kTileDw]; + __shared__ uint32_t sV[kTileDw]; + + constexpr int TOKS = 32 / GQA; /* query rows a wave carries */ + constexpr int kNThr = WAVES * 32; /* 32, 64, 128 threads */ + constexpr int ROWSB = WAVES * TOKS; /* rows a workgroup carries */ + constexpr int LG = (GQA == 1) ? 0 : (GQA == 2) ? 1 : (GQA == 4) ? 2 : 3; + + const int tid = (int)threadIdx.x; + const int wave = tid >> 5, lane = tid & 31; + const RowMap M = map_seq(A, ROWSB, (int)blockIdx.x); + /* A grid row the batch has no tiles for (the grid is sized on a bound), and a sequence with no + * rows (cu[s+1] <= cu[s], the reference's `qlen <= 0`), stage nothing and store nothing. A + * sequence that starts past the query plane -- a descriptor running beyond the operand -- is + * nobody's rows: the plane's row count is the bound the store is checked against below. */ + if (M.tile < 0 || M.len <= 0 || M.start >= A.rows) return; + const int s = M.s; + const int tile = M.tile; + const int kh = (int)blockIdx.y; + const int slice = SPLIT ? (int)blockIdx.z : 0; + + const int h = kh * GQA + (lane & (GQA - 1)); + const int tb = tile * ROWSB + wave * TOKS; /* the wave's first row of the sequence */ + const int tok = tb + (lane >> LG); /* this lane's, counted inside the sequence */ + /* A row the operands do not have: past the rows this sequence's tiles carry (the last tile of + * any sequence, and every tile of a short one in a ragged step), or past the query plane (a + * descriptor that runs long). Both are the clamp the width section documents. The bound is the + * SPAN, not the length: with cu[0] > 0 the span reaches below cu[0], and the rows there are + * the reference's rows too (seq_of gives them to sequence 0), so they are stored. */ + const bool row_ok = tok < M.span && M.start + tok < A.rows; + /* The clamp target is a row that EXISTS: the wave's first row if the sequence has one, else its + * last, and never past the plane. An idle lane loads a real query row so the walk stays + * branch-free; it never stores. */ + int tclamp = tb < M.span ? tb : M.span - 1; + if (M.start + tclamp >= A.rows) tclamp = A.rows - 1 - M.start; + const long long row = (long long)M.start + (row_ok ? tok : tclamp); + + const long long ctx = ld_ix(A.su, (size_t)s); + const int jend_all = (int)(ctx < A.jcap ? ctx : A.jcap); + /* `ib` is 0 for every descriptor the description allows (cu[0] == 0); it is the negative index + * into sequence 0's query that libref's seq_of gives rows under cu[0]. */ + const long long ib = (long long)M.start - M.i0; + const long long pos = ctx - M.len + tok + ib; + + /* THE LAUNCH WRITES. The shim is not in the path of a played step -- a play writes queue + * packets and never calls `rad_arch_step` (the recorded pass's packet path) -- and this kernel + * is, so the row writes down what the row was + * handed: `ctx` off `seqused`, the block ids off the table at the table's own pitches, the six + * operand addresses baked into the packet, and three content folds. ONE thread of ONE workgroup + * (`blockIdx.z` is the split-KV slice: one launch, not `splits` of them), gated on a global the + * shim writes only under `RAD_R3D_TRACE`. With the flag unset the gate is one load of a zero + * global and a not-taken branch, and the launch records nothing. It does not printf: a kernel + * that does takes the implicit `hidden_hostcall_buffer`, which the AQL backend does not supply, + * and the row stops being dispatchable at all (see the ring's header). + * + * Placed HERE, before the query is widened and long before the walk, so the record covers the + * launch even when the walk's rows are all clamped -- which is why the writer's own read of the + * query row is bounded by the PLANE's rows and not by the band key, and why a clamped tile + * records `qh=0 rowok=0` -- and so the writer's registers are live over the fewest live values + * in the kernel. */ + if (blockIdx.x == 0 && blockIdx.y == 0 && blockIdx.z == 0 && threadIdx.x == 0) + dev_record(A, M, row, row_ok, ctx, jend_all, pos); + + /* The WORKGROUP's bounds, not the wave's. The stage is one tile shared by the four waves, so + * every wave of a workgroup must walk exactly the same blocks: a range narrowed to a wave's own + * four positions makes the waves stage different blocks over the same LDS, and the last writer + * per 16-byte chunk wins -- a corrupted tile that looks like a numerical error. The positions of + * a workgroup's 4 x TOKS consecutive rows span 4 x TOKS - 1, and keys past the last are nobody's; + * a window cuts the front off as well. The mask that this widens past is per lane and free. */ + const int gb = tile * ROWSB; + const long long wmin = ctx - M.len + gb + ib; + const long long wmax = wmin + ROWSB - 1; + int jlo = 0, jhi = jend_all; + if (CAUSAL) { + if (wmax + 1 < jhi) jhi = (int)(wmax + 1); + } + if (A.window > 0) { + const long long lo = wmin - A.window + 1; + if (lo > jlo) jlo = (int)(lo > 0 ? lo : 0); + if (!CAUSAL) { + const long long hi = wmax + A.window; + if (hi < jhi) jhi = (int)(hi > 0 ? hi : 0); + } + } + const int nblk = (jend_all + kBlock - 1) / kBlock; + int b0 = jlo / kBlock, b1 = (jhi + kBlock - 1) / kBlock; + if (SPLIT) { + const int tps = (nblk + A.splits - 1) / A.splits; + const int s0 = slice * tps; + const int s1 = s0 + tps < nblk ? s0 + tps : nblk; + if (b0 < s0) b0 = s0; + if (b1 > s1) b1 = s1; + } + + const float kds = A.kds ? A.kds[(size_t)s * A.kv_heads + kh] : 1.0f; + const float vds = A.vds ? A.vds[(size_t)s * A.kv_heads + kh] : 1.0f; + + /* The query row, widened once and kept for both walks: 64 dwords, the lane's own 256 bytes, the + * eight heads of a token contiguous in memory. An idle lane loads its wave's first row so the + * registers hold something and the walk stays branch-free; it never stores. */ + uint32_t qf[kPairs]; + { + const uint16_t* qp = A.q + row * (long long)A.q_rs + h * kHeadDim; +#pragma unroll + for (int u = 0; u < kPairs / 4; ++u) { /* eight elements a 16-byte load */ + const r3d_u32x4 raw = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(qp + u * 8); + const uint32_t d[4] = { raw.x, raw.y, raw.z, raw.w }; +#pragma unroll + for (int j = 0; j < 4; ++j) qf[u * 4 + j] = A.q16 ? d[j] : bf16x2_to_f16x2(d[j]); + } + } + + float acc[kHeadDim]; +#pragma unroll + for (int d = 0; d < kHeadDim; ++d) acc[d] = 0.0f; + float sum = 0.0f, mx = -INFINITY; + + /* Walk one: the scores' maximum. Blocks entirely behind every row of the workgroup need no + * mask, and the ones straddling a row's position mask per lane. */ + for (int b = b0; b < b1; ++b) { + const int blk = (int)ld_ix(A.bt, (size_t)s * (size_t)A.bt_rs + (size_t)b * (size_t)A.bt_cs); + group_barrier(); + if (blk >= 0) stage(A, sK, sV, blk, kh, kds, vds, tid); + group_barrier(); + if (blk < 0) continue; + const int j0 = b * kBlock; + const int nu = j0 + kBlock <= jhi ? kBlock : (jhi > j0 ? jhi - j0 : 0); + const bool nomask = !CAUSAL && A.window <= 0; + if (nomask) { + for (int u = 0; u < nu; ++u) { + const float sc = score_of(qf, sK + u * kPitch, A.scale); + if (sc > mx) mx = sc; + } + } else { + for (int u = 0; u < nu; ++u) { + if (!visible(j0 + u, pos, CAUSAL, A.window)) continue; + const float sc = score_of(qf, sK + u * kPitch, A.scale); + if (sc > mx) mx = sc; + } + } + } + + /* Walk two: the same scores, exponentiated against the maximum, accumulated ascending. */ + if (mx > -INFINITY) { + for (int b = b0; b < b1; ++b) { + const int blk = (int)ld_ix(A.bt, (size_t)s * (size_t)A.bt_rs + (size_t)b * (size_t)A.bt_cs); + group_barrier(); + if (blk >= 0) stage(A, sK, sV, blk, kh, kds, vds, tid); + group_barrier(); + if (blk < 0) continue; + const int j0 = b * kBlock; + const int nu = j0 + kBlock <= jhi ? kBlock : (jhi > j0 ? jhi - j0 : 0); + const bool nomask = !CAUSAL && A.window <= 0; + for (int u = 0; u < nu; ++u) { + if (!nomask && !visible(j0 + u, pos, CAUSAL, A.window)) continue; + const float w = exp_ref(score_of(qf, sK + u * kPitch, A.scale) - mx); + sum += w; + const uint32_t* vp = sV + u * kPitch; +#pragma unroll + for (int p = 0; p < kPairs; ++p) { + const uint32_t q2 = vp[p]; + const int d = 2 * p; + acc[d] = acc[d] + w * f16_to_f32((uint16_t)(q2 & 0xffffu)); + acc[d + 1] = acc[d + 1] + w * f16_to_f32((uint16_t)(q2 >> 16)); + } + } + } + } + + /* A row slot past its sequence's length, or past the query plane, is a clamped duplicate: it + * computed a walk, and it stores nothing -- the partial store included, which needs the same + * test BEFORE it. A padding row's `row` clamps to a REAL row, so an unguarded partial store + * puts a second writer into (row, h, slice) -- inside the declared arena, so no bounds check + * sees it -- and the two writers' 132-float records interleave: a slot can end with one lane's + * acc and another lane's (sum, max). The reduce then rescales a full slice's accumulator by + * the other lane's maximum, the combined sum comes out thousands of times too small, and + * `1/sum` hands back a power of two where a logit belongs. The mechanism needs a padding row + * -- q_len < 32/gqa -- so a band that fills its waves (q_len 7 at gqa 8) has none. The slots a + * padding row leaves unwritten are exactly the slots the reduce does not read: its index runs + * to `nrows * n_head`, over real rows only. */ + if (!row_ok) return; + + if (SPLIT) { + float* pp = A.part + ((size_t)row * A.n_head + h) * ((size_t)A.splits * kPartStride) + + (size_t)slice * kPartStride; +#pragma unroll + for (int u = 0; u < kHeadDim / 8; ++u) { + const r3d_f32x4 v = { acc[8 * u], acc[8 * u + 1], acc[8 * u + 2], acc[8 * u + 3] }; + const r3d_f32x4 w = { acc[8 * u + 4], acc[8 * u + 5], acc[8 * u + 6], acc[8 * u + 7] }; + *(r3d_f32x4*)(pp + 8 * u) = v; + *(r3d_f32x4*)(pp + 8 * u + 4) = w; + } + pp[kHeadDim] = sum; + pp[kHeadDim + 1] = mx; + return; + } + + uint16_t* op = A.out + row * (long long)A.o_rs + h * kHeadDim; + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; /* no visible key: a zero row */ +#pragma unroll + for (int u = 0; u < kHeadDim / 8; ++u) { + uint32_t q4[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) { + const int d = 8 * u + 2 * j; + q4[j] = bf16x2_rne(acc[d] * inv, acc[d + 1] * inv); + } + *(r3d_u32x4*)(void*)(op + 8 * u) = r3d_u32x4{ q4[0], q4[1], q4[2], q4[3] }; + } +} + +/* ------------------------------------------------------------------ split-KV reduce + * + * A wave per (query row, head): 32 lanes x 4 dims. The slices combine ascending, each rescaled by + * exp(m_slice - M) with M the slices' maximum, which is where split-KV leaves the reference's + * parentheses; see the header. */ +__global__ __launch_bounds__(128) R3D_WAVES(4) +void attn_reduce(const Args A, long long nrows) +{ + const int w = (int)threadIdx.x >> 5, lane = (int)threadIdx.x & 31; + const long long idx = (long long)blockIdx.x * 4 + w; + const long long total = nrows * A.n_head; + if (idx >= total) return; + const long long row = idx / A.n_head, h = idx - row * A.n_head; + const int s = seq_of_row(A, (int)row); /* row / q_len with a null descriptor */ + const long long ctx = ld_ix(A.su, (size_t)s); + const int jend_all = (int)(ctx < A.jcap ? ctx : A.jcap); + const int nblk = (jend_all + kBlock - 1) / kBlock; + const int tps = (nblk + A.splits - 1) / A.splits; + const int nslice = tps > 0 ? (nblk + tps - 1) / tps : 0; + + float* pp = A.part + (size_t)idx * ((size_t)A.splits * kPartStride); + float M = -INFINITY; + for (int u = 0; u < nslice; ++u) { + const float m = pp[(size_t)u * kPartStride + kHeadDim + 1]; + if (m > M) M = m; + } + uint16_t* o = A.out + row * (long long)A.o_rs + h * kHeadDim; + const int d0 = lane * 4; + float a[4] = { 0.0f, 0.0f, 0.0f, 0.0f }; + float sum = 0.0f; + if (M > -INFINITY) { + for (int sl = 0; sl < nslice; ++sl) { + const float* q = pp + (size_t)sl * kPartStride; + const float f = exp_ref(q[kHeadDim + 1] - M); + sum += q[kHeadDim] * f; + a[0] += q[d0 + 0] * f; + a[1] += q[d0 + 1] * f; + a[2] += q[d0 + 2] * f; + a[3] += q[d0 + 3] * f; + } + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + *(r3d_u32x2*)(void*)(o + d0) = r3d_u32x2{ bf16x2_rne(a[0] * inv, a[1] * inv), + bf16x2_rne(a[2] * inv, a[3] * inv) }; +} + +} // namespace + +/* ================================================================== launchers + * + * Both entries take raw addresses and extents, in the library's style, and both assume the dense + * layouts the shim has just checked: the cache at [blocks, kv_heads, 16, 256], a block table whose + * row pitch is exactly ceil(max_ctx / block_size), seqused one i32 a sequence. That is what the + * signatures carry, so the shims refuse anything they cannot describe with it -- a strided cache, a + * wider block table, an i64 index plane. + * + * `cu` is the ragged query descriptor, and with it `q_len` changes meaning: it is the query PLANE's + * row count, the total, which the descriptor's cu[num_seqs] states and libref reads off the tensor + * (`rows = numel(q) / (q_heads * head_dim)`, `cu[n_seq] == rows`). Absent, it + * keeps its per-sequence meaning and the total is num_seqs * q_len. No entry reads the plane: the + * grid is sized on a bound, and the kernel does the walking. + */ +#define R3D_NEED(cond) do { if (!(cond)) return R3D_NO(RAD_E_SHAPE); } while (0) + +namespace { + +int fill(Args& A, long q, long kv, long bt, long seqused, long k_desc, long v_desc, long cu, + long rows, 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, int waves) +{ + A = Args{}; + if (head_dim != kHeadDim) return -2; /* RAD_E_SHAPE */ + if (num_seqs <= 0 || n_head <= 0) return -2; + /* A rectangular batch is counted per sequence; a ragged one has no per-sequence length, and its + * `rows` is the query plane's row count. Both have to be at least one row. */ + if (cu) { if (rows < 1 || rows > 2147483000LL) return -2; } + else if (q_len < 1 || (long long)num_seqs * q_len > 2147483000LL) return -2; + if (block_size != kBlock) return -2; + if (gqa != 1 && gqa != 2 && gqa != 4 && gqa != 8) return -2; /* the wave split is a shift */ + if (n_head % gqa) return -2; + if (window < 0 || max_ctx < 1) return -2; + if (kv_dt != RAD_BF16 && kv_dt != RAD_F8E4M3) return -1; /* RAD_E_DTYPE */ + if (!q || !kv || !bt || !seqused) return -1; + + const int kv_heads = n_head / gqa; + /* Two counts that must not be conflated. The CACHE holds + * ceil(max_ctx / block_size) blocks, which bounds the byte offset of a slot address. The TABLE + * has `bt_cols` columns, and the engine sizes it to the step: a five-token prompt with nothing + * behind it is one block, a table of [n_seq, 1]. The walk is bounded by the TABLE -- + * the reference takes max_blocks from `bt->shape[last]`, the row pitch from + * `stride[rank-2]` and the column stride from `stride[rank-1]`, and jend = min(ctx, max_blocks * + * block_size) -- so a context longer than the table has columns is truncated by the reference, + * which is the oracle, and by us, to the same keys. */ + const int cache_blocks = (max_ctx + block_size - 1) / block_size; + if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) return -2; /* RAD_E_STRIDE, said where the shim sees it */ + + A.q = (const uint16_t*)(uintptr_t)q; + A.kv = kv_dt == RAD_BF16 ? (const uint16_t*)(uintptr_t)kv : nullptr; + A.kv8 = kv_dt == RAD_F8E4M3 ? (const uint8_t*)(uintptr_t)kv : nullptr; + A.bt = (const int*)(uintptr_t)bt; + A.su = (const int*)(uintptr_t)seqused; + A.cu = (const int*)(uintptr_t)cu; + A.kds = (const float*)(uintptr_t)k_desc; + A.vds = (const float*)(uintptr_t)v_desc; + /* The dense cache: a slot's K is 128 elements, V the 128 after it. Every stride has to fit the + * 32-bit form the kernel's addressing uses. */ + A.so = 2 * kHeadDim; + A.sh = block_size * A.so; + A.sb = kv_heads * A.sh; + A.sd = 1; + if ((long long)A.sb * cache_blocks > 2147483000LL) return -2; + if (q_ld > 2147483000LL || out_ld > 2147483000LL) return -2; + A.q_rs = (int)q_ld; + A.o_rs = (int)out_ld; + A.bt_rs = bt_rs; + A.bt_cs = bt_cs; + A.n_seq = num_seqs; A.q_len = cu ? 0 : q_len; + A.rows = cu ? (int)rows : num_seqs * q_len; + A.n_head = n_head; A.kv_heads = kv_heads; + A.causal = causal ? 1 : 0; A.window = window; + A.jcap = max_ctx; + if ((long long)bt_cols * block_size < max_ctx) A.jcap = bt_cols * block_size; + if (r3d_trace_on()) /* the walk's reach is a number the shim can print: a context that + * comes back short is a table narrower than the sequence, and + * that is a plan fact, not a kernel fact */ + std::fprintf(stderr, "[r3d] attn: q_len %d rows %ld n_seq %d bs %d bt cols %d pitch %d " + "cstride %d max_ctx %d -> jcap %d\n", q_len, rows, num_seqs, + block_size, bt_cols, bt_rs, bt_cs, max_ctx, A.jcap); + { /* the record's slot, for the engine process: a plain buffer the kernel can write and the + * shim can read back, no symbol table between them. Inert when the flag is unset. */ + static void* g_trace_buf = nullptr; + A.trace_buf = nullptr; + if (r3d_trace_on() && !g_trace_buf) + (void)hipMalloc(&g_trace_buf, sizeof(DevRec)); + if (g_trace_buf) A.trace_buf = (DevRec*)g_trace_buf; + } + if (r3d_trace_on()) /* the device's own view, at the launch: the table row, the + * seqused, the KV base, and the first block's bytes -- the + * four things a wrong answer can come from, spoken together. + * The sync is the price: the staging may ride the engine's + * stream, and a read on the default stream is unordered to it. */ + { + (void)hipDeviceSynchronize(); + const char* kvb = A.kv8 ? (const char*)A.kv8 : (const char*)A.kv; + for (int s = 0; s < (int)num_seqs && s < 4; ++s) { + int row[16]; + if (hipMemcpy(row, (const char*)A.bt + (size_t)s * (size_t)bt_rs * sizeof(int), + 16 * sizeof(int), hipMemcpyDeviceToHost) == hipSuccess) { + std::fprintf(stderr, "[r3d] devstate s=%d bt=", s); + for (int c = 0; c < 16; ++c) std::fprintf(stderr, "%s%d", c ? " " : "", row[c]); + std::fprintf(stderr, "\n"); + } + int su = -1; + if (A.su && + hipMemcpy(&su, (const char*)A.su + (size_t)s * sizeof(int), sizeof(int), + hipMemcpyDeviceToHost) == hipSuccess) + std::fprintf(stderr, "[r3d] devstate s=%d seqused=%d kvbase=%p\n", s, su, + (const void*)kvb); + } + int first = -1; + if (kvb && + hipMemcpy(&first, (const char*)A.bt, sizeof(int), hipMemcpyDeviceToHost) == hipSuccess && + first >= 0) { + /* The block's bytes are spoken by address only: a D2H of the cache base page faults + * the engine process where the kernel's own read is fine, so the content check stays + * with the board, and the table + base are what the served run speaks. */ + std::fprintf(stderr, "[r3d] devstate first_block=%d (content not read: see the board)\n", + first); + } + } + /* The table bounds the walk, as in the reference: a context with more blocks than the + * table has columns stops at the table, which is what the reference does and therefore + * what the fixture and the served numbers say. */ + A.scale = scale > 0.0f ? scale : 1.0f / std::sqrt((float)kHeadDim); + A.splits = splits > 0 ? splits : 1; + A.waves = waves; + A.part = A.splits > 1 ? (float*)(uintptr_t)scratch : nullptr; + if (A.splits > 1 && !scratch) return -5; /* RAD_E_SCRATCH */ + return 0; +} + +/* The narrowest workgroup that carries the caller's q_len. A wave carries 32 / gqa query rows, and + * a row slot whose row is past q_len computes a clamped duplicate: at the decode band's q_len = 7 + * with gqa = 8 a four-wave workgroup spends 9 of its 16 row slots on duplicates, twice the walk for + * half the outputs. The tile is the same 8 KiB at every width -- 16 tokens a block, staged once per + * workgroup -- so a narrower workgroup is the same cache read spread over more workgroups, and + * 512 -> 1024 of them is the fill the counters say the op is short of (15% issue at the band, + * 3.7% at eight sequences, where splits=8 buys 3.6x). Prefill keeps four waves: its q_len is the + * whole chunk, every slot is used, and a smaller workgroup would only re-read the cache. + * The accumulation order does not depend on the width: the softmax sum is over keys, ascending, + * inside one lane, and the rows a wave holds are the same rows shifted by wave * TOKS. */ +int pick_waves(int q_len, int gqa) +{ + const int rows = 32 / (gqa > 0 ? gqa : 1); + const int w = (q_len + rows - 1) / rows; + return w <= 1 ? 1 : (w <= 2 ? 2 : 4); /* the ladder the grid is cut on: 1, 2, 4 */ +} + +/* The rows one sequence of a batch contributes, as well as a host can know them: the plane's row + * count over the sequence count, rounded up. With a descriptor the true lengths are device memory + * and a launcher reads none of it, so this is what the width and the split count are picked on for a + * ragged step. Both choices move duplicated row slots and grid blocks; neither can move a result, + * which is why the average is legal as a proxy and a per-sequence length is not needed. */ +int avg_rows(int rows, int num_seqs) { return num_seqs > 0 ? (rows + num_seqs - 1) / num_seqs : rows; } + +/* Every width the ladder can return, at every gqa, must be instantiated and dispatched: pick_waves + * is `ceil(q_len / (32/gqa))` clamped to the ladder, so gqa = 4 asks for W = 4 at q_len > 16, + * gqa = 2 at q_len > 32, gqa = 1 at q_len > 64 -- and the prefill entry passes kWaves = 4 + * unconditionally. The launcher dispatches through `if constexpr (waves_ok<...>::value)`, so a + * missing instantiation compiles the kernel call out: the entry returns RAD_OK, hipGetLastError() + * is clean, and the output plane keeps what the caller put there. A silent no-op is the worst + * failure a kernel row can have: the engine reads its own input back as the attention output. The + * gate therefore asserts the whole ladder, at every gqa -- every width it admits is a width some + * q_len can ask for. */ +template struct waves_ok { + static const bool value = (W == 1) || (W == 2) || (W == 4); +}; + +int tok_per_block(int gqa, int waves) { return waves * (32 / (gqa > 0 ? gqa : 1)); } + +/* The decode entry's `splits`, when the caller asked for the widest legal: enough workgroups to + * fill the card (16 CUs x two workgroups at four waves a SIMD) and no more, on a doubling ladder. */ +int pick_splits(int tiles, int num_seqs, int kv_heads) +{ + const long long blocks = (long long)tiles * num_seqs * kv_heads; + int sp = 1; + while (sp < 8 && blocks * sp < 32) sp *= 2; + return sp; +} + +static void dev_speak(const DevRec& r); /* the record, spoken; defined with the ring below */ + +int launch(const Args& A, long out, long stream) +{ + Args B = A; + B.out = (uint16_t*)(uintptr_t)out; + const int gqa = A.n_head / A.kv_heads; + const int waves = A.waves > 0 ? A.waves : kWaves; + const int tpb = tok_per_block(gqa, waves); + /* The grid's row count. Rectangular: every sequence has the same tile count, so the product is + * exact and is the grid. Ragged: the tile count is + * sum_s ceil(len_s / tpb), which lives in device memory, so the launch uses the bound + * sum_s ceil(len_s / tpb) <= ceil(rows / tpb) + n_seq - 1 + * (ceil(x) + ceil(y) <= ceil(x + y) + 1, inducted over the sequences), and `map_seq` sends a grid + * row past the last tile straight home. The slack is at most n_seq - 1 empty workgroups, and an + * empty one stages nothing: it reads n_seq descriptor entries and returns. */ + const int tiles = A.cu ? (A.rows + tpb - 1) / tpb + A.n_seq - 1 + : (A.q_len + tpb - 1) / tpb * A.n_seq; + dim3 grid((unsigned)tiles, (unsigned)A.kv_heads, + (unsigned)(A.splits > 1 ? A.splits : 1)); + const bool fp8 = A.kv8 != nullptr; + const bool causal = A.causal != 0; + hipStream_t st = (hipStream_t)(uintptr_t)stream; + +#define R3D_ATTN(FP8V, CAUSALV, SPLITV, GQAV, WAVESV) \ + R3D_KLAUNCH((attn_kernel), grid, \ + dim3(WAVESV * 32), st, B) + +#define R3D_ATTN_SEL(GQAV, WAVESV) \ + do { \ + if constexpr (waves_ok::value) { \ + /* `sel` is three bits, and all eight combinations are reachable: a single-sequence \ + * causal decode picks splits 4 on its own (pick_splits(1, 1, 8) = 4), so sel 6 and 7 \ + * are the engine's most common split shape. Each combination needs its own arm: a \ + * causal-with-splits launch routed into the non-causal instantiation takes its maximum \ + * over keys the row must not see, the softmax loses its top weight to a future key, \ + * and the reduce amplifies the loss into a 1/sum of the wrong size. All eight arms \ + * exist. */ \ + if (sel == 0) R3D_ATTN(false, false, false, GQAV, WAVESV); \ + else if (sel == 1) R3D_ATTN(true, false, false, GQAV, WAVESV); \ + else if (sel == 2) R3D_ATTN(false, true, false, GQAV, WAVESV); \ + else if (sel == 3) R3D_ATTN(true, true, false, GQAV, WAVESV); \ + else if (sel == 4) R3D_ATTN(false, false, true, GQAV, WAVESV); \ + else if (sel == 5) R3D_ATTN(true, false, true, GQAV, WAVESV); \ + else if (sel == 6) R3D_ATTN(false, true, true, GQAV, WAVESV); \ + else R3D_ATTN(true, true, true, GQAV, WAVESV); \ + } \ + } while (0) + +#define R3D_ATTN_GQA(GQAV) \ + do { \ + if (waves == 1) R3D_ATTN_SEL(GQAV, 1); \ + else if (waves == 2) R3D_ATTN_SEL(GQAV, 2); \ + else R3D_ATTN_SEL(GQAV, 4); \ + } while (0) + + const int sel = (fp8 ? 1 : 0) | (causal ? 2 : 0) | (A.splits > 1 ? 4 : 0); + /* The flag is cleared HERE, after the arguments are staged and before the chevron, and read + * straight back after it. `hipGetLastError()` reports the first error raised since it was last + * cleared, so a check that does not clear first attributes to this launch whatever the process + * raised before it: in a served process, the op that ran last. A synchronous launch clears a + * pending asynchronous error before the check, so `HIP_LAUNCH_BLOCKING=1` hides a + * misattribution of exactly this kind. A healthy step refused by a symptom it did not cause is + * the failure mode; the launch is not. */ + (void)hipGetLastError(); + switch (gqa) { + case 1: R3D_ATTN_GQA(1); break; + case 2: R3D_ATTN_GQA(2); break; + case 4: R3D_ATTN_GQA(4); break; + default: R3D_ATTN_GQA(8); break; + } +#undef R3D_ATTN_GQA +#undef R3D_ATTN_SEL +#undef R3D_ATTN + { + const hipError_t ke = hipGetLastError(); + if (ke != hipSuccess) { + /* A launch failure names what it saw: the error, the grid, the workgroup and the width + * the launcher chose. */ + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] attn: %s on the attn launch: grid (%u, %u, %u) block " + "%d waves %d gqa %d splits %d rows %d n_seq %d jcap %d\n", + hipGetErrorName(ke), grid.x, grid.y, grid.z, waves * 32, waves, gqa, + A.splits, A.rows, A.n_seq, A.jcap); + return -4; /* RAD_E_DEVICE */ + } + } + + if (B.trace_buf) { /* the record, spoken at the launch that wrote it: one sync, under the flag */ + (void)hipStreamSynchronize(st); + DevRec rec; + if (hipMemcpy(&rec, (const void*)B.trace_buf, sizeof rec, hipMemcpyDeviceToHost) == hipSuccess) + dev_speak(rec); + } + + if (A.splits > 1) { + const long long rows = A.rows; /* the plane's rows: cu[n_seq], or n_seq * q_len */ + const long long total = rows * A.n_head; + dim3 rg((unsigned)((total + 3) / 4)); + (void)hipGetLastError(); /* the same rule, the same reason */ + R3D_KLAUNCH(attn_reduce, rg, dim3(128), st, B, rows); + const hipError_t re = hipGetLastError(); + if (re != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] attn: %s on the reduce launch: grid (%u, 1, 1) block " + "128 rows %lld heads %d splits %d\n", hipGetErrorName(re), + rg.x, rows, A.n_head, A.splits); + return -4; + } + } + return 0; +} + +} // namespace + +extern "C" 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) +{ + /* `cu` is the ragged query descriptor and it is served: with it, `q_len` is the query plane's + * row count (see the launchers' header) and the rows per sequence are cu[s+1] - cu[s]. The + * width and the split count are picked on the average sequence, because the descriptor is on the + * device and this function reads no device memory -- both numbers choose how many row slots are + * duplicated, and neither touches a result. */ + if (splits < 0) return -2; + if (gqa <= 0 || n_head <= 0 || n_head % gqa) return -2; + if (cu && num_seqs <= 0) return -2; + Args A; + const int kv_heads = n_head / gqa; + const int per = cu ? avg_rows(q_len, num_seqs) : (q_len > 0 ? q_len : 1); + const int waves = pick_waves(per, gqa); + const int tpb = tok_per_block(gqa, waves); + const int tiles = per > 0 ? (per + tpb - 1) / tpb : 1; + int sp = splits > 0 ? splits : pick_splits(tiles, num_seqs, kv_heads); + const int e = fill(A, q, kv, bt, seqused, k_desc, v_desc, cu, cu ? q_len : 0, num_seqs, + cu ? 0 : q_len, head_dim, gqa, n_head, block_size, bt_cols, bt_rs, bt_cs, + max_ctx, window, causal, scale, kv_dt, q_ld, out_ld, sp, scratch, waves); + if (e) return e; + return launch(A, out, stream); +} + +extern "C" 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) +{ + (void)scratch; /* the prefill kernel has no split pass, so no partials */ + /* The width is kWaves with a descriptor or without one. A rectangular prefill's q_len is the + * whole chunk, so every slot of a four-wave workgroup is used; a ragged step's rows are laid + * out by the same workgroup, and the width that matters on a step with only a few rows in it is + * how many waves the GPU gets, not how many slots go unused. A 5-row step at gqa 8 is one + * workgroup per KV head: two waves is 2 x 2 wavefronts over 16 CUs, four waves is 2 x 4, and + * the measured 5-row launch at 2048 keys is 16.7 ms at four waves against 19.3 at two, with the + * duplicate slots costing nothing because a wave walks its tile once whatever rows it carries. + * A step whose rows are one per sequence is a decode step and goes to the decode entry, which + * picks its width on the average sequence -- that is where a narrow workgroup is the win. */ + Args A; + const int waves = kWaves; + const int e = fill(A, q, kv, bt, seqused, k_desc, v_desc, cu, cu ? q_len : 0, num_seqs, + cu ? 0 : q_len, head_dim, gqa, n_head, block_size, bt_cols, bt_rs, bt_cs, max_ctx, window, causal, + scale, kv_dt, q_ld, out_ld, 1, 0, waves); + if (e) return e; + A.splits = 1; + A.part = nullptr; + return launch(A, out, stream); +} + +/* ================================================================== shims + * + * The paged geometry as the tensors state it: n_seq from `seqused`, n_head and head_dim from the + * query, kv_heads from the cache, block_size from the cache, max_ctx from the cache's block count, + * q_len from the query's row count over n_seq. Params fill in what the tensors cannot say (gqa, + * causal, window, scale). */ +namespace { + +enum { P_Q = 0, P_KV = 1, P_BT = 2, P_SU = 3, P_KDS = 4, P_VDS = 5, P_CU = 6, P_OUT = 7 }; + +/* ---- arming the device record ring ---------------------------------------------------------- + * + * The kernel's four globals (`r3d_dev_budget`, `r3d_dev_launches`, `r3d_dev_widx`, `r3d_dev_ring`) + * are plugin-owned, at file scope, `extern "C"` so the names are the ones the code object carries. + * `RadArgs` is the row's ABI and the plan builds it, so nothing joins it; the kernel's launch + * parameters are fixed, so nothing joins them. The shim's whole instrument surface is therefore four + * symbols: + * + * hipGetSymbolAddress, once, cached -- the counter, for the plan line to quote + * hipMemcpyToSymbol of the budget, under RAD_R3D_TRACE ONLY -- 0 means the kernel records nothing + * hipMemcpy of the ring, under RAD_R3D_TRACE -- the drain: the records to stderr, host-side + * hipMemcpyToSymbol of the write index -- the drain's reset, so a record is spoken once + * + * The budget is re-written on every traced call, not once per process, and `RAD_R3D_DEV` is its + * size (default 64). Re-arming is one 4-byte copy under a flag that already does four device reads + * a line, and it buys the property the board needs: a harness can arm exactly -- arm 3, launch 10, + * count 3 -- between launches, with the kernel untouched. The last write wins, so a served ladder + * re-arms at every prefill and the budget never runs dry mid-request. + * + * The drain runs on every traced call too, BEFORE the arming: it speaks the records the kernel has + * written since the last call. For a played step there is no shim call in between, so its lines land + * at the next step's shim call, one step behind the step they describe. The record's `L` and `ctx` + * restore the order, and the plan line's `dev_launches=` quote is the counter the kernel itself ran, + * so the two prints of one step line up and the gap between them is the played pass, measured. + * + * Inert when the flag is unset: `dev_ring_drain` and `dev_trace_arm` return before the runtime call, + * the budget keeps its initial 0, and every kernel gates on it. Nothing here is on the served path + * at all: the shim calls them from inside its existing `r3d_trace_on()` arm. + */ +enum { kDevPrintDefault = 64 }; + +template +void* dev_sym(void** slot, const char* name, const T& symbol) +{ + if (*slot) return *slot; + void* p = nullptr; + const hipError_t e = hipGetSymbolAddress(&p, HIP_SYMBOL(symbol)); /* the T& overload */ + *slot = (e == hipSuccess) ? p : nullptr; + if (e != hipSuccess) + std::fprintf(stderr, "[r3d dev] %s: hipGetSymbolAddress -> %s\n", name, + hipGetErrorName(e)); + return *slot; +} + +void* g_dev_budget = nullptr; /* hipGetSymbolAddress cache, resolved once */ +void* g_dev_launches = nullptr; + +unsigned long long dev_launch_count() +{ + /* `hipMemcpyFromSymbol`, not `hipGetSymbolAddress` + `hipMemcpy`: the arming's + * `hipMemcpyToSymbol` resolves the stub the runtime owns, and in the engine process a + * `hipGetSymbolAddress` on a dlopened plugin's symbol can hand back an address the kernel's + * module does not write to -- the read is a copy of the initial value, forever. The same stub + * resolution the arming uses is the one the read must use. */ + unsigned long long n = 0; + (void)hipMemcpyFromSymbol(&n, HIP_SYMBOL(r3d_dev_launches), sizeof n); + return n; +} + +void* g_dev_widx = nullptr; +void* g_dev_ring = nullptr; + +/* One record, spoken. The format is the line the board parses: the same field names in the same + * order, `ids=` the row's columns, `kh` the fold of the FIRST block it walks and `khL` the fold of + * the LAST, `idsum` a fold of every column so a long row is one comparable number. */ +static void dev_speak(const DevRec& r) +{ + std::fprintf(stderr, "[r3d dev] L=%llu dec=%d n_seq=%d rows=%d q_len=%d s=%d len=%d span=%d " + "start=%d ctx=%lld pos=%lld jcap=%d splits=%d waves=%d kv=%p bt=%p su=%p cu=%p " + "q=%p out=%p bt0=%d bt1=%d bt2=%d slot0=%lld qh=%016llx kh=%016llx ids=", + (unsigned long long)r.L, r.dec, r.n_seq, r.rows, r.q_len, r.s, r.len, r.span, + r.start, (long long)r.ctx, (long long)r.pos, r.jcap, r.splits, r.waves, + (const void*)r.kv, (const void*)r.bt, (const void*)r.su, (const void*)r.cu, + (const void*)r.q, (const void*)r.out, r.b[0], r.b[1], r.b[2], (long long)r.slot0, + (unsigned long long)r.qh, (unsigned long long)r.kh); + for (int c = 0; c < r.ncols && c < kDevIds; ++c) + std::fprintf(stderr, "%s%d", c ? "," : "", r.b[c]); + std::fprintf(stderr, " ncols=%d bL=%d slotL=%lld khL=%016llx idsum=%lld rowok=%d\n", r.ncols, + r.spare, (long long)r.slotL, (unsigned long long)r.khL, (long long)r.idsum, + r.rowok); +} + +/* The ring, spoken. The drain is a D2H of at most kDevRing records (55 KiB) on a traced call: one + * sync per shim call, under the flag only. The index is the kernel's own, so the drain can never + * read past what the kernel wrote, and the reset is to 0, not to a moving base: a record is spoken + * exactly once, and the counter -- which the drain does not touch -- is the launch census. */ +void dev_ring_drain() +{ + if (!r3d_trace_on()) return; + /* The reads go through `hipMemcpyFromSymbol`, the same stub resolution the arming's + * `hipMemcpyToSymbol` uses (see `dev_launch_count`): in the engine process a + * `hipGetSymbolAddress` on a dlopened plugin's symbol is not the address the kernel writes. */ + unsigned w = 0; + if (hipMemcpyFromSymbol(&w, HIP_SYMBOL(r3d_dev_widx), sizeof w) != hipSuccess) return; + if (w == 0) return; + static DevRec buf[kDevRing]; + const unsigned keep = w < (unsigned)kDevRing ? w : (unsigned)kDevRing; + if (hipMemcpyFromSymbol(buf, HIP_SYMBOL(r3d_dev_ring), (size_t)keep * sizeof(DevRec)) != hipSuccess) + return; + for (unsigned i = 0; i < keep; ++i) dev_speak(buf[i]); + if (w > keep) + std::fprintf(stderr, "[r3d dev] ring: %u records written, %u kept, %u counted and dropped " + "-- the counter is the truth\n", w, keep, w - keep); + const unsigned zero = 0u; + (void)hipMemcpyToSymbol(HIP_SYMBOL(r3d_dev_widx), &zero, sizeof zero); +} + +void dev_trace_arm() +{ + if (!r3d_trace_on()) return; /* the gate: with the flag unset, nothing here */ + int want = kDevPrintDefault; + if (const char* e = std::getenv("RAD_R3D_DEV")) { + const int v = std::atoi(e); + if (v > 0) want = v; /* a harness arms exactly; 0 disables */ + else if (v == 0) want = 0; + } + static bool said = false; + const unsigned long long seen = dev_launch_count(); + if (!dev_sym(&g_dev_budget, "r3d_dev_budget", HIP_SYMBOL(r3d_dev_budget))) return; + const hipError_t e = hipMemcpyToSymbol(HIP_SYMBOL(r3d_dev_budget), &want, sizeof want); + if (!said || e != hipSuccess) { + said = true; + std::fprintf(stderr, "[r3d dev] armed: budget=%d launches_at_arm=%llu %s\n", want, + (unsigned long long)seen, e == hipSuccess ? "ok" : hipGetErrorName(e)); + } +} + + +/* ---- the plan line: the one number a launcher has never been able to read ---------------------- + * + * `cu_seqlens` is device memory -- the header's rule is that a launcher reads none of it -- and the + * walk's bound is a single value inside it: `cu[0]`. The served descriptors start at row 0. Under + * RAD_R3D_TRACE=1 this stops being an inference: the shim copies the descriptor's `n_seq + 1` i32 + * and prints them, once per shape. + * + * Inert when the flag is unset. Everything below sits behind `r3d_trace_on()`, the cached flag load + * `R3D_NO` already pays on a path that is failing anyway: no copy, no latch, no syscall, and no + * operand the served path did not already touch. + * + * The reads, all of them bounded. The descriptor's plane holds exactly `n_seq + 1` ints -- the shim + * has proved `r3d_numel(CU) == n_seq + 1` above -- and the copy is capped at `kCuPrint` of them, + * with the LAST entry taken by its own one-int read when the plane is wider, so the printed total is + * the total and nothing past the plane is touched. `seqused` is read for ONE int, its first, because + * `ctx` is `seqused[0]` and a plan line that cannot say where the walk bounds is + * half a line. A null pointer is never dereferenced: the descriptor is read only after `r3d_has(CU)` + * said it carries bytes, and `SU->data` was required at the top of the shim. `hipMemcpyDefault` is + * placement-agnostic, so the same line prints for a vram plane and for a host-mapped one. + * + * The latch is keyed on the shape -- n_seq, the plane's rows, the kernel's q_len, the table's + * columns -- because the engine calls this shim once a layer a step and 42 identical lines are + * noise. It is a plain static array with no lock: the worst a race can do here is print a shape + * twice, and nothing at all when the flag is off. */ +enum { kCuPrint = 64, kPlanShapes = 512 }; + +/* RAD_R3D_TRACE=2 is the same instrument with ctx in the shape key (see plan_once). Read once. */ +bool r3d_trace_wide() +{ + static int wide = -1; + if (wide < 0) { + const char* e = std::getenv("RAD_R3D_TRACE"); + wide = (e && e[0] == '2') ? 1 : 0; + } + return wide != 0; +} + +/* The shape key: n_seq, the plane's rows, the kernel's q_len, the table's + * columns. `ctx` rides along ONLY under RAD_R3D_TRACE=2, which is the wide form of the same + * instrument: a serving engine's requests all share the shape (rows 1, one sequence, 128 columns) + * and differ only in how deep the context has grown, so with the narrow key the block table prints + * once for the FIRST request and the requests that matter -- the ones after six blocks are in play + * -- never print. The default (=1) is the narrow key. */ +struct PlanKey { long long n_seq, rows, q_len, cols, ctx; }; + +bool plan_once(long long n_seq, long long rows, long long q_len, long long cols, long long ctx, + bool by_ctx) +{ + static PlanKey seen[kPlanShapes]; + static int n = 0; + for (int i = 0; i < n; ++i) + if (seen[i].n_seq == n_seq && seen[i].rows == rows && seen[i].q_len == q_len && + seen[i].cols == cols && (!by_ctx || seen[i].ctx == ctx)) + return false; + if (n < kPlanShapes) seen[n++] = PlanKey{n_seq, rows, q_len, cols, ctx}; + return true; +} + +void plan_line(bool decode, const RadTensor* Q, const RadTensor* KV, const RadTensor* O, + const RadTensor* CU, const RadTensor* SU, const RadTensor* BT, const void* scratch, + long long n_seq, long long rows, long long q_len, long long bt_cols, long long bt_rs, + long long bt_cs, int block_size, int max_ctx, int waves, int splits, bool by_ctx) +{ + /* The walk's bound, the same expression fill() uses: the TABLE's columns times the block, + * capped by the cache's context (jend = min(ctx, max_blocks * block_size)). */ + const long long reach = (long long)bt_cols * block_size; + const long long jcap = reach < max_ctx ? reach : (long long)max_ctx; + + long long ctx = -1; /* seqused[0], the first sequence's context */ + int ctx0 = 0; + if (r3d_p(SU) && hipMemcpy(&ctx0, r3d_p(SU), sizeof(int), hipMemcpyDefault) == hipSuccess) + ctx = ctx0; + + /* The latch lives here, after the one-int ctx read, because the wide key is keyed on it. This + * whole function is called only under the flag, so the served path pays none of it. */ + if (!plan_once(n_seq, rows, q_len, bt_cols, ctx, by_ctx)) return; + + std::fprintf(stderr, + "[r3d] plan: %s n_seq=%lld rows=%lld q_len=%lld cu rank=%u numel=%lld ctx=%lld " + "bt cols=%lld pitch=%lld max_ctx=%d -> jcap=%lld waves=%d splits=%d", + decode ? "decode" : "prefill", n_seq, rows, q_len, + r3d_has(CU) ? (unsigned)CU->rank : 0u, r3d_has(CU) ? r3d_numel(CU) : 0LL, ctx, + bt_cols, bt_rs, max_ctx, jcap, waves, splits); + + /* The ADDRESSES the launch bakes. The engine captures this step into a graph after two eager + * decode steps -- one request generating twelve tokens calls this shim for the prefill and for + * two decode steps, and for nothing after that -- and a replay re-runs the kernels with the + * ARGUMENTS frozen at capture. The planes a step reads are named by address in those arguments, + * so if a later request's plan lives at different addresses, a replay is reading the earlier + * request's planes and no per-row fixture, ladder or descriptor print can see it. `%p` of the + * five operands this step reads and the one it writes, nothing dereferenced. */ + std::fprintf(stderr, " q=%p kv=%p bt=%p cu=%p su=%p out=%p part=%p", + r3d_p(Q), r3d_p(KV), r3d_p(BT), r3d_p(CU), r3d_p(SU), r3d_p(O), scratch); + + /* The kernel's own launch counter, quoted on the shim's line so the two prints of one step line + * up: the shim sees a served request's prefill and its first two decode steps, the kernel sees + * every one, and the gap between the two numbers IS the played pass. One 8-byte device read, + * under the flag, on a line that is already reading three planes. */ + std::fprintf(stderr, " dev_launches=%llu", (unsigned long long)dev_launch_count()); + + if (!r3d_has(CU)) { /* an absent optional operand is ABSENT, not a refusal: the + rectangular step is the common case and it says so */ + std::fprintf(stderr, " cu=absent (rectangular)"); + } else { + int cuh[kCuPrint]; + const int take = (int)(n_seq + 1 < kCuPrint ? n_seq + 1 : kCuPrint); + if (hipMemcpy(cuh, r3d_p(CU), (size_t)take * sizeof(int), hipMemcpyDefault) != + hipSuccess) { + std::fprintf(stderr, " cu=copy failed"); + } else { + long long cu_last = -1; + if (n_seq + 1 <= kCuPrint) cu_last = cuh[(int)n_seq]; + else { + int last = 0; /* the plane's last int, nothing beyond it */ + if (hipMemcpy(&last, (const int*)r3d_p(CU) + n_seq, sizeof(int), + hipMemcpyDefault) == hipSuccess) + cu_last = last; + } + std::fprintf(stderr, " cu[0]=%d cu[n_seq]=%lld", cuh[0], cu_last); + if (n_seq + 1 <= 8) /* the whole descriptor, when it is short */ + for (int i = 0; i <= (int)n_seq; ++i) + std::fprintf(stderr, " cu[%d]=%d", i, cuh[i]); + } + } + + /* The block table's own entries for the row this step walks. The walk's arithmetic -- which + * block holds key j -- is the one part of the plan this file cannot check from the descriptor, + * and a reused block id inside one row, or an id the cache does not have, is invisible to every + * per-row fixture (the drivers deal their ids from a shuffled pool, so they cannot produce the + * first). Bounded three ways: at most `kCuPrint` columns of ONE row, only columns the shim has + * already proved the plane covers (the reach check above), and row 1's first entry only when + * there is a row 1. A -1 is an unmapped block and prints as -1, which is what the kernel sees. */ + if (r3d_has(BT)) { + const int take = (int)(bt_cols < kCuPrint ? bt_cols : kCuPrint); + int bth[kCuPrint]; + const int* btp = (const int*)r3d_p(BT); + bool got = true; + for (int i = 0; i < take; ++i) + if (hipMemcpy(&bth[i], btp + (long long)i * bt_cs, sizeof(int), + hipMemcpyDefault) != hipSuccess) { got = false; break; } + std::fprintf(stderr, " bt0="); + if (!got) std::fprintf(stderr, "(copy failed)"); + else { + std::fprintf(stderr, "["); + for (int i = 0; i < take; ++i) std::fprintf(stderr, "%s%d", i ? "," : "", bth[i]); + std::fprintf(stderr, "]"); + if (take < bt_cols) std::fprintf(stderr, " (%lld cols)", bt_cols); + if (n_seq >= 2) { + int r1 = 0; + if (hipMemcpy(&r1, btp + bt_rs, sizeof(int), hipMemcpyDefault) == hipSuccess) + std::fprintf(stderr, " bt1[0]=%d", r1); + } + } + } + std::fprintf(stderr, "\n"); +} + +int attn_shim(const RadArgs* a, RadStream s, bool decode) +{ + if (a->n_t < 8) return R3D_NO(RAD_E_INVAL); + const RadTensor* Q = r3d_opt(a, P_Q); + const RadTensor* KV = r3d_opt(a, P_KV); + const RadTensor* BT = r3d_opt(a, P_BT); + const RadTensor* SU = r3d_opt(a, P_SU); + const RadTensor* O = r3d_opt(a, P_OUT); + const RadTensor* KDS = r3d_opt(a, P_KDS); + const RadTensor* VDS = r3d_opt(a, P_VDS); + const RadTensor* CU = r3d_opt(a, P_CU); + if (!Q || !KV || !BT || !SU || !O) return R3D_NO(RAD_E_INVAL); + if (!Q->data || !KV->data || !BT->data || !SU->data || !O->data) return R3D_NO(RAD_E_INVAL); + /* `cu_seqlens` present is a ragged batch, and this file serves it: the row map, the positions, + * the mask and the walk all key off the sequence a row belongs to, which is what the descriptor + * says it is (see "the ragged batch" in the header). The descriptor is device memory, so what + * the shim can check here is its shape and dtype; what it cannot see -- cu[0] == 0, monotonicity, + * cu[n_seq] == the plane's row count -- the kernel clamps, exactly as libref's row loop does. */ + const bool ragged = r3d_has(CU); + + const int head_dim = (int)r3d_geti_or(a, "head_dim", r3d_dim(Q, (int)Q->rank - 1)); + if (head_dim != kHeadDim) return R3D_NO(RAD_E_SHAPE); + const int gqa = (int)r3d_geti_or(a, "gqa", 1); + if (gqa != 1 && gqa != 2 && gqa != 4 && gqa != 8) return R3D_NO(RAD_E_SHAPE); + const int causal = (int)r3d_geti_or(a, "causal", 1); + const int window = (int)r3d_geti_or(a, "window", 0); + const float scale = (float)r3d_getf(a, "scale", 0.0); + + /* The kernel's f16 query path is written -- `A.q16` makes the widening a copy -- but the + * launcher's signature carries one dtype slot, `kv_dt`, and it is the cache's, so the shim has + * no way to tell the kernel that q is f16: the flag would sit at zero and the kernel would + * widen f16 codes as bf16, a 2^9 scale error, not a rounding difference. Refused until `q_dt` + * joins the signature. A row set that widens `q_dtype` to "bf16 f16" must land with that + * parameter. */ + if (Q->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (O->dtype != Q->dtype) return R3D_NO(RAD_E_DTYPE); + if (KV->dtype != RAD_BF16 && KV->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); + if (BT->dtype != RAD_I32 || SU->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + const bool quant = KV->dtype == RAD_F8E4M3; + /* A quantised cache with no descale plane is a cache with scale 1.0, not a refused geometry. + * The reference reads the planes only when they are there: + * const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f; + * const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f; + * and says it in prose ("the scales are the reader's descales, default 1.0"). + * The op's operand description describes both planes as ABSENT, so a fixture that draws this + * op hands every implementation null descales; refusing them is refusing the case class. The + * kernel already carries the null through and widens at 1.0 (`A.kds ? ... : 1.0f`). */ + const bool kgiven = KDS && KDS->data, vgiven = VDS && VDS->data; + if (!quant && (kgiven || vgiven)) + return R3D_NO(RAD_E_SHAPE); /* a bf16 cache has no scales: the caller believes something + the op does not have, and dropping that quietly is worse */ + if (quant && kgiven && !r3d_is_f32(KDS)) return R3D_NO(RAD_E_DTYPE); + if (quant && vgiven && !r3d_is_f32(VDS)) return R3D_NO(RAD_E_DTYPE); + + const int n_head = (int)r3d_geti_or(a, "n_head", r3d_dim(Q, (int)Q->rank - 2)); + if (n_head <= 0 || n_head % gqa) return R3D_NO(RAD_E_SHAPE); + const int kv_heads = n_head / gqa; + const int block_size = (int)r3d_geti_or(a, "block_size", r3d_dim(KV, 2)); + if (block_size != kBlock) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(KV, 1) != kv_heads) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(KV, 3) < 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE); + const long long nb = r3d_dim(KV, 0); + const int max_ctx = (int)(nb * block_size); + const int max_blocks = (int)((max_ctx + block_size - 1) / block_size); + + const long long n_seq = r3d_numel(SU); + if (n_seq < 1 || n_seq > 65536) return R3D_NO(RAD_E_SHAPE); + /* The descriptor is [n_seq + 1] i32, contiguous: the kernel reads it with int indices, so an + * i64 plane is not a wider form of the same operand, it is the wrong operand, and the fix is the + * plane the op's description names. `seqused` is read the same way and is checked below. */ + if (ragged) { + if (CU->dtype != RAD_I32) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_DTYPE); } + if (!r3d_contig(CU)) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_STRIDE); } + if (r3d_numel(CU) != n_seq + 1) { r3d_trace_desc("cu_seqlens", CU); return R3D_NO(RAD_E_SHAPE); } + if (!r3d_aligned(CU->data, 4)) return R3D_NO(RAD_E_ALIGN); + } + long long qh = 0, qt = 0, qld = 0; + if (!r3d_head_rows(Q, kHeadDim, &qt, &qh, &qld) || qh != n_head) { r3d_trace_desc("q", Q); + r3d_trace_desc("out", O); return R3D_NO(RAD_E_STRIDE); } + long long oh = 0, ot = 0, old = 0; + if (!r3d_head_rows(O, kHeadDim, &ot, &oh, &old) || oh != n_head) { r3d_trace_desc("out", O); + return R3D_NO(RAD_E_STRIDE); } + if (qld % 8 || old % 8) return R3D_NO(RAD_E_STRIDE); + /* Rows per sequence: the plane's row count divided by the sequence count when the batch is + * rectangular, and nothing at all when it is ragged -- the reference's `q_len = cus ? 0 : + * rows / n_seq` (the reference's reading), with the plane's row count (its `rows`, and the number a + * descriptor's cu[n_seq] equals) carried to the launcher as the row count. A ragged batch is not + * required to divide: 5 rows over 3 sequences is the case the engine sends, and `qt % n_seq` is + * exactly the shape it arrives in. */ + if (qt < 1) return R3D_NO(RAD_E_SHAPE); + if (qt > 2147483000LL) return R3D_NO(RAD_E_SHAPE); /* the kernel's row index is 32-bit */ + if (!ragged && qt % n_seq) return R3D_NO(RAD_E_SHAPE); + const long long q_len = ragged ? qt : qt / n_seq; /* the per-sequence length, rectangular */ + const long long rows = qt; /* the plane's rows, both forms */ + if (q_len < 1) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(O) < rows * n_head * kHeadDim) return R3D_NO(RAD_E_SHAPE); + /* The descales are per (sequence, KV head), the reference's indexing: `s * kv_heads + kh`. */ + if (quant && kgiven && (r3d_numel(KDS) < n_seq * kv_heads || !r3d_contig(KDS))) + return R3D_NO(RAD_E_SHAPE); + if (quant && vgiven && (r3d_numel(VDS) < n_seq * kv_heads || !r3d_contig(VDS))) + return R3D_NO(RAD_E_SHAPE); + if (quant && (kgiven != vgiven)) return R3D_NO(RAD_E_SHAPE); /* half a pair is a caller bug */ + /* The cache is dense and the launcher assumes it: a slot's halves must land on a 16-byte + * boundary at every slot, so the cache's strides have to be the dense ones. */ + if (!r3d_contig(KV)) { r3d_trace_desc("kv", KV); return R3D_NO(RAD_E_STRIDE); } + /* The table is the engine's, sized to the step, so its geometry comes from the tensor and not + * from the band: `max_blocks` is the TABLE's columns, the row pitch is `stride[rank-2]` and the + * column stride `stride[rank-1]` (the reference's table read). A five-token prompt carries + * [n_seq, 1]: one block per sequence, because nothing is behind it. What the shim insists on is + * that every index the walk can reach is inside the plane -- the last row's pitch plus the last + * column it can name: a contiguity check asks for a table as wide as the cache and refuses a + * step the engine sends. */ + const long long bt_cols = BT->rank >= 2 ? r3d_dim(BT, (int)BT->rank - 1) : (n_seq ? r3d_numel(BT) / n_seq : 0); + const long long bt_rs = BT->rank >= 2 ? BT->stride[BT->rank - 2] : bt_cols; + const long long bt_cs = BT->rank >= 2 ? BT->stride[BT->rank - 1] : 1; + if (bt_cols < 1 || bt_rs < 1 || bt_cs < 1) { r3d_trace_desc("block_tables", BT); + return R3D_NO(RAD_E_STRIDE); } + const long long bt_reach = (n_seq - 1) * bt_rs + (bt_cols - 1) * bt_cs + 1; + if (r3d_numel(BT) < bt_reach) { r3d_trace_desc("block_tables", BT); + std::fprintf(stderr, "[r3d] block table: %lld entries, the walk reaches %lld\n", + (long long)r3d_numel(BT), bt_reach); + return R3D_NO(RAD_E_STRIDE); } + if (!r3d_contig(SU)) { r3d_trace_desc("seqused", SU); return R3D_NO(RAD_E_STRIDE); } + if (!r3d_aligned(Q->data, 16) || !r3d_aligned(KV->data, 16) || !r3d_aligned(O->data, 16)) + return R3D_NO(RAD_E_ALIGN); + + int splits = decode ? (int)r3d_geti_or(a, "splits", 0) : 1; + if (splits < 0) return R3D_NO(RAD_E_SHAPE); + /* The width the launcher will cut the grid on. A ragged batch has no per-sequence length to pick + * on -- the descriptor is on the device -- so the average sequence decides, as it does in the + * entry itself. It moves duplicated row slots between tiles and no result. */ + const long long per = ragged ? (rows + n_seq - 1) / n_seq : q_len; + const int waves = pick_waves((int)per, gqa); + const int tiles = (int)((per + tok_per_block(gqa, waves) - 1) / tok_per_block(gqa, waves)); + if (splits == 0) splits = decode ? pick_splits(tiles, (int)n_seq, kv_heads) : 1; + if (splits > 64) splits = 64; + if (splits > 1) { + /* The arena the engine offers is the bound: halve the split count until the partials fit, + * down to 1, which needs none -- and one slice is the whole walk in one block, the same + * keys in the same order, so it is not a degraded answer, it is the answer without the + * optimisation. A row that refuses a band because an optimisation has no room is a row that + * tells the user to go away; the number is the same either way. */ + for (;;) { + if (splits <= 1) { splits = 1; break; } + const long long need = qt * n_head * (long long)splits * kPartStride * 4; + if (a->scratch && a->scratch_bytes >= (size_t)need) break; + splits /= 2; + } + if (r3d_trace_on() && splits > 1) + std::fprintf(stderr, "[r3d] attn: %d slices into %zu of %zu bytes needed\n", + splits, a->scratch_bytes, (size_t)(qt * n_head * + (long long)splits * kPartStride * 4)); + } + + /* The plan line: what the descriptor actually says, once per shape, under the flag only. The + * `q_len` printed is the one the kernel is given -- 0 with a descriptor, the per-sequence length + * without one (the reference's reading) -- and `rows` is the plane's row count, which is what + * cu[n_seq] is required to equal. Printed AFTER every check: a refused step's shape is the + * refusal lines' business, not this one's. */ + /* The kernel is the one instrument that a played step runs through: its records sit in the ring + * until a shim call drains them, so drain FIRST -- the records written since the last call, the + * played steps included -- and THEN arm the budget this launch will spend, under the flag only + * (both functions gate themselves on the same cached load). */ + dev_ring_drain(); + dev_trace_arm(); + + if (r3d_trace_on()) + plan_line(decode, Q, KV, O, CU, SU, BT, splits > 1 ? (const void*)a->scratch : nullptr, + n_seq, rows, ragged ? 0LL : q_len, bt_cols, bt_rs, bt_cs, block_size, max_ctx, + waves, splits, r3d_trace_wide()); + + /* The entries take the descriptor's row count where a rectangular batch has its per-sequence + * length: `rows` is the plane's, which is what cu[n_seq] equals and what libref counts off the + * tensor, and `q_len` is the per-sequence length only when there is no descriptor. */ + const int e = decode + ? r3d_attn_decode_h128(r3d_addr(Q), r3d_addr(KV), r3d_addr(BT), r3d_addr(SU), + r3d_addr(KDS), r3d_addr(VDS), r3d_addr(CU), r3d_addr(O), (int)n_seq, + (int)(ragged ? rows : q_len), + head_dim, gqa, n_head, block_size, (int)bt_cols, (int)bt_rs, + (int)bt_cs, max_ctx, window, causal, scale, + (int)KV->dtype, qld, old, splits, + (long)(uintptr_t)(splits > 1 ? a->scratch : nullptr), + (long)(uintptr_t)s) + : r3d_attn_prefill_h128(r3d_addr(Q), r3d_addr(KV), r3d_addr(BT), r3d_addr(SU), + r3d_addr(KDS), r3d_addr(VDS), r3d_addr(CU), r3d_addr(O), (int)n_seq, + (int)(ragged ? rows : q_len), head_dim, gqa, n_head, block_size, + (int)bt_cols, (int)bt_rs, (int)bt_cs, max_ctx, window, + causal, scale, (int)KV->dtype, qld, old, + (long)(uintptr_t)nullptr, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_DTYPE : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_ALIGN : e == -4 ? RAD_E_DEVICE + : e == -5 ? RAD_E_SCRATCH : RAD_E_INVAL); +} + +} // namespace + +extern "C" int r3d_rad_attn_decode_h128(const RadArgs* a, RadStream s) +{ + return attn_shim(a, s, true); +} + +extern "C" int r3d_rad_attn_prefill_h128(const RadArgs* a, RadStream s) +{ + return attn_shim(a, s, false); +} diff --git a/libr3d/r3d_codecs.h b/libr3d/r3d_codecs.h new file mode 100644 index 00000000..485ebde2 --- /dev/null +++ b/libr3d/r3d_codecs.h @@ -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 +#include + +/* 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 +#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 */ diff --git a/libr3d/r3d_common.h b/libr3d/r3d_common.h new file mode 100644 index 00000000..ce40c8e8 --- /dev/null +++ b/libr3d/r3d_common.h @@ -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 +#include + +#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 +__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 +__device__ __forceinline__ float r3d_xor_lane(float v) { + return __uint_as_float(r3d_xor_lane_u32(__float_as_uint(v))); +} + +/* A 64-bit value's partner: the halves exchanged separately, as a 64-bit shuffle does. */ +template +__device__ __forceinline__ unsigned long long r3d_xor_lane_u64(unsigned long long v) { + const uint32_t lo = r3d_xor_lane_u32((uint32_t)v); + const uint32_t hi = r3d_xor_lane_u32((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 +__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 +__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 +__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 +__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 */ diff --git a/libr3d/r3d_dflash_f32.hip b/libr3d/r3d_dflash_f32.hip new file mode 100644 index 00000000..39904757 --- /dev/null +++ b/libr3d/r3d_dflash_f32.hip @@ -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 + +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)); +} diff --git a/libr3d/r3d_fp8_dequant.h b/libr3d/r3d_fp8_dequant.h new file mode 100644 index 00000000..4ee6dbd7 --- /dev/null +++ b/libr3d/r3d_fp8_dequant.h @@ -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 */ diff --git a/libr3d/r3d_gemm_bf16_nt_m16.hip b/libr3d/r3d_gemm_bf16_nt_m16.hip new file mode 100644 index 00000000..439e11f4 --- /dev/null +++ b/libr3d/r3d_gemm_bf16_nt_m16.hip @@ -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 + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +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 +__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 +__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(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)), 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)), 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); +} diff --git a/libr3d/r3d_gemm_fp8a16_nt_m1.hip b/libr3d/r3d_gemm_fp8a16_nt_m1.hip new file mode 100644 index 00000000..a110186d --- /dev/null +++ b/libr3d/r3d_gemm_fp8a16_nt_m1.hip @@ -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 // __forceinline__, which r3d_codecs.h's R3D_HD spells + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +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 +__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 +__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(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)), 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)), 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); +} diff --git a/libr3d/r3d_gemm_fp8a8_gated.hip b/libr3d/r3d_gemm_fp8a8_gated.hip new file mode 100644 index 00000000..9f365467 --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_gated.hip @@ -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 // __forceinline__, which r3d_codecs.h's R3D_HD spells + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +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 +__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 +__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(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(ar + kb + (st + 0) * kStep); + const r3d_u32x4 a1 = ldc(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(wg + kb + k), a0, a1, sub_g); + sub_u = dot_step(s_tab, ldc(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)), 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); +} diff --git a/libr3d/r3d_gemm_fp8a8_tiled.hip b/libr3d/r3d_gemm_fp8a8_tiled.hip new file mode 100644 index 00000000..7ec9ce39 --- /dev/null +++ b/libr3d/r3d_gemm_fp8a8_tiled.hip @@ -0,0 +1,1200 @@ +/* r3d_gemm_fp8a8_tiled.hip -- gemm_nt_q at prefill M, fp8a8, on a tiled f16 dot. + * + * ---- why this row exists ------------------------------------------------------------------------ + * + * The graph, at the vocabulary head: + * + * W placement: 'blk.0.attn_norm.weight' is grouped with a weight only a host kernel can read, so + * the whole group stays in the container's mapping + * E rank 0: 'blk.0.attn_norm.weight' was placed on the mapped tier, which reads the container + * where it lies, and its stored form is not the container's (widened at load) + * + * The chain is arithmetic, not policy: `gemm_nt_q` has no device row at prefill M, so its bands + * resolve to a host kernel, so the layer's weights stay in the container's mapping, so the layer's + * NORM weights are grouped with them, so the mapped tier is asked to perform the widening the norms' + * stored form needs, so startup stops. `--placement all_vram` is already the default and there is no + * grouping flag. The row that breaks the chain is the one the README names: the tiled + * quantised GEMM at prefill M. This file is that row. + * + * ---- the bands (42 layers + the drafter, per --debug-graph) ------------------------------------- + * + * gemm_nt_q N=12288 K= 2048 group=128 dtype=fp8a8 M=2048 x44 the gated MLP, 2 x 6144 + * gemm_nt_q N= 2560 K= 2048 group=128 dtype=fp8a8 M=2048 x44 qkv: 2048 + 2 x 256 + * gemm_nt_q N= 2048 K= 6144 group=128 dtype=fp8a8 M=2048 x44 o-proj + * gemm_nt_q N= 2048 K= 2048 group=128 dtype=fp8a8 M=2048 x44 + * gemm_nt_q N= 2048 K=10240 group=128 dtype=fp8a8 M=2048 x3 the drafter + * + * M=16 and M=1 are served, by gemm_nt_q_fp8a8_m16. The vocab prefill (N=130560 dtype=w2a8 M=1792) is + * the 2-bit grid and not this row's. Constraints bind the BAND's keys: dtype in {fp8a8}, group == + * 128, M >= 17, K % 128. Below M=17 the m16 rows are the served path and this row says so. The floor + * is `kMMin`, and it is the sibling row's declared ceiling plus one; the w2a8 arm below carries the + * same floor, with the reason for it. + * + * ---- the law, transcribed ----------------------------------------------------------------------- + * + * gemm_nt_q's law, in the registry: "The group sub-sum is accumulated from the raw codes and scaled + * once per group, which is what an int8 or fp8 WMMA kernel does." In code, the reference's + * quant_dot -- the same body r3d_gemm_fp8a8_gated.hip and r3d_gemm_fp8a16_nt_m1.hip carry: + * + * for g in groups: sub = 0 + * for k in g, ascending: sub = sub + code_a[m][k] * code_b[n][k] + * acc = acc + (sub * a_scale[m][g]) * b_scale[n/128][g] + * + * The codes are the raw E4M3 values, widened exactly into f32; the scale multiplies the finished + * block ONCE, and the parentheses are the reference's. Operands, from gemm_q_shape, in schema + * order: a E4M3 {M,K}; a_scale F32 {M, ceil(K/group)}; b E4M3 {N,K} (the checkpoint's own bytes); + * b_scale BF16 {ceil(N/group), ceil(K/group)} -- f32 at fp8a8f32; y BF16 {M,N}; a_sum ABSENT for + * fp8a8 because fp8a8 is symmetric; b_ref absent. y is bf16 with one narrowing at the store, f32 + * accumulate throughout. + * + * ---- the fold, and where it goes ---------------------------------------------------------------- + * + * The tile is f16, so the two scale streams enter as f16 multiplies at staging: the activation's + * `a_scale[m][g]` per staged row, the weight's `b_scale[nb][g]` once a chunk -- TN is 128, the scale + * plane's row extent, so a tile is one scale-row, and kKC 32 divides 128, so a chunk sits inside one + * k-block. The products are separable: (a*sa)*(b*sb) = (a*b)*sa*sb, so folding each side is the same + * sum, formed a different way, and the accumulator stays one f32 register per output -- 64 a lane. + * The alternative, a per-group partial scaled into the accumulator, needs 64 more registers on an arm + * that is at 237 VGPRs, and spills. + * + * The fold goes through v_mul_f16, never through f16x2_pack. That builtin is v_cvt_pkrtz_f16_f32, + * rounds toward zero, and r3d_codecs.h restricts it to values f16 represents exactly; a folded + * product is not one, and on the vocabulary head the truncation measured rel_l2 2.8e-04 against the + * fold law with 0.53 of outputs inside 2 ulps, where the f16 multiply gives 4.5e-06 and 1.000. + * + * Against the reference's law the fold costs the two f16 roundings of the staged values: measured + * rel_l2 2.77e-04 at the head's band, which is half an f16 ulp (2^-12 = 2.44e-04) and 250x finer than + * the E4M3 code's own quantum (2^-4). Against a model of the fold itself it is 4.5e-06 -- the dot's + * fused rounding, the pair-dot folding two products into the accumulator per step. This row's board + * reports both numbers, per band. + * + * ---- the decoder is a table, and that is measured ---------------------------------------------- + * + * gfx11 has no fp8->f16 instruction: clang lists __builtin_amdgcn_cvt_pk_f16_fp8 and a gfx1102 build + * that calls it contains zero of them in its ISA, so the builtin is software. r3d_fp8_dequant.h + * replaces the codec with a 256-entry f16 table in LDS, 512 bytes, eight reads an eight-code group. + * Measured on the vocabulary head's bands (the A/B is one source, -DR3D_NO_E4M3_TBL for the codec): + * M=8 speculation 2.500 -> 0.924 ms a token, 2.70x; M=2048 prefill 323.978 -> 322.661 ms, flat; and + * M=1 12.999 -> 13.293 ms, NOT moved: at M=1 the decoder is not the binding resource, and the + * limiting access there is the 8-byte code load, not the ALU. + * + * ---- what the board measures -------------------------------------------------------------------- + * + * Five bands, M=2048, GPU 2 (RX 7600, gfx1102, 32 CU), the container managed with its pages + * prefetched to the card, every number on a placement line: + * + * N=12288 K= 2048 28.171 ms 3659 GFLOP/s 0.0138 ms/token the gated MLP, x44 + * N= 2560 K= 2048 5.911 ms 3633 GFLOP/s 0.0029 ms/token qkv 2048 + 2 x 256 + * N= 2048 K= 6144 14.699 ms 3506 GFLOP/s 0.0072 ms/token o-proj, x44 + * N= 2048 K= 2048 4.381 ms 3922 GFLOP/s 0.0021 ms/token x44 + * N= 2048 K=10240 29.798 ms 2883 GFLOP/s 0.0145 ms/token the drafter, x3 + * + * 2883-3922 GFLOP/s is 27-36% of this card's dense f16 peak (10.8 TFLOP/s), above the vocabulary + * head's fp8 3369 and within 4% of its bf16 4067. The bytes floor is 0.051-0.257 ms a band at the + * 163 GB/s the head's row streams, and 2MNK/(K+N) is ~1900 flops a byte at M=2048: prefill is + * compute-bound here, as it should be, and these bands are the box's fp8a8 prefill numbers. + * + * The floors, as the gate uses them. The fold's is 2^-11 a staged rounding, twice, on S = + * sqrt(sum_k (a_k b_k)^2) -- the quadrature scale of the DEQUANTISED terms -- so 9.8e-4 S. The + * store's is bf16's own ulp, 3.9e-3 of the output's binade, and at a bf16 output the store is the + * binding one: rel_l2 lands at 1.71e-03 against BOTH the reference's per-group law and the fold + * model, 83% of outputs are bit-exact bf16, 99.93% are within the fold's floor plus one store ulp, + * and 0 outputs are beyond eight fold floors plus two store ulps, on every band. |y| alone is not a + * denominator: a sum of 2048 random products is as often near zero as not, and a relative test + * against it is a coin flip. S is the denominator, and it is why the per-output gate is + * fold-bound + store-ulp and not a multiple of |y|'s ulp. + * + * ---- the open item, with numbers, and what is NOT the kernel ------------------------------------- + * + * The grid is (ceil(N/128), ceil(M/128)) at one block a CU (64 f32 accumulators a lane). Measured + * per block, the fast shapes cost a constant 18.4-18.5 us a block (16 tiles: 4.72 ms/256; 20 tiles: + * 5.911/320). Column-tile counts 19 and 21 do not: at the same M and K, N=2432 (19 tiles) is + * 64.283 ms and 64.301 ms in two isolated processes (211 us a block, 11.4x) and N=2688 (21 tiles) is + * 129.383 ms (385 us a block, 20.9x). Deterministic to 0.1%, and it is a grid-shape cliff, not + * arithmetic -- the board is CLEAN at both. Every column-tile count the graph issues is even (96, 20, + * 16, 16, 16), so no band the graph runs lands on it; the first thing to try is the block-index + * swizzle that tile-count cliffs usually answer to, and `nt` streaming loads second. + * + * Separately, and named so nobody reads it as the kernel: the qkv shape measures 5.911, 5.919 and + * 6.002 ms as the FIRST case of a process and 85.669 / 85.847 ms as the SECOND case of the band + * sequence, same binary, same seed, same grid, CLEAN board both ways, 250 GFLOP/s when slow. A + * 14.5x deterministic placement artefact of a fixture that allocates and frees a 24 MiB managed + * container in the case before it; at 0.2 GB/s the slow run is reading b over PCIe, in the mapped + * tier's class, which is the placement law this file's header states. The row's number for the qkv + * band is 5.911 ms; the sequence's 85.8 ms is the fixture's, and the engine ships the weights to + * VRAM at load and reads them 44 times, which is the case the 5.911 measures. + * + * ---- where the bytes live, named on every line -------------------------------------------------- + * + * The head's bands, one kernel, three placements, measured: VRAM 13.6 ms a token; the mapped tier + * (hipHostMalloc) 643 ms; managed and left alone 2071 ms, 122 MB/s, because managed pages do not + * migrate for a read-mostly device access on this box. This row's operands are host-readable for the + * same reason the head's are -- the shim reads the container's header on the host, the kernel reads + * the same bytes on the card -- so the board allocates with hipMallocManaged and prefetches, and says + * which placement produced which number. Plain malloc faults 700. + * + * ---- what is refused, and where ----------------------------------------------------------------- + * + * The shim, at its own lines, each naming its fix: n_t < 5 (E_INVAL); a_sum present on an fp8a8 band + * (E_DTYPE -- fp8a8 is symmetric, a zero belongs to an asymmetric grid, and that is + * r3d_gemm_nt_q_w2a8.hip); a container carrying a zero plane (E_DTYPE, the same reason); planes that + * are not codes + scale, a codes plane tiled by anything but one code a cell, sub-byte codes + * (w4a16's ground), e5m2 and the rest, a scale that is a table, an integer scale (E_DTYPE, each its + * own line); a scale block that is not {group, group} (E_SHAPE); a plane that does not cover the + * band, ceil() arithmetic included (E_SHAPE); a plane whose row_bytes is shorter than its row + * (E_STRIDE); dtype of a not E4M3, a_scale not f32, b codes not E4M3, b_scale not bf16/f16/f32, y + * not bf16 (E_DTYPE); M < 17 (E_UNSUPPORTED: gemm_nt_q_fp8a8_m16 serves that); group != 128 + * (E_SHAPE: the fold indexes 128 and kKC 32 divides it); K % 128 (E_SHAPE); pitches that a vector + * load cannot walk (E_STRIDE); addresses not 16-byte aligned (E_ALIGN); absurd shapes (E_INVAL). + * The kernel's shape rule is stated here, because "shape this kernel does not serve" is a coverage + * claim, and coverage is caught by the fixture, not the board. + * The tile is 128 wide, so a ragged N is covered by ceil(): the last column tile stages the columns + * past N as zeros, writes the columns it owns and guards its stores column by column -- N needs NO + * divisibility, and `N % 128` is not a band key gemm_nt_q carries (r3d_rows.cpp's pGemmQ is M, N, + * K, group, dtype, pb1, pb2, split_n), so a check that wanted one could only ever refuse a shape + * the row advertised. M is the same in rows: ceil(M/128) row-tiles, rows past M stage zeros, write + * nothing, and M=65, 129, 258 and 512 -- the 27B fixture's geometries -- are served. + * K % 128 IS a rule, and it is the kernel's and not a coverage one: a 32-code chunk must sit inside + * one scale group (kKC 32 divides the group 128) and the scale plane is indexed by group, so a + * ragged K reads the scale plane past its columns. The scale plane is read at ceil(N/128) x + * ceil(K/128), exactly as the reference's `scaled_rows` covers it; the codes plane at rows == N, + * cols == K. Those two are equalities because that IS the reference's coverage rule, and every + * other shape test on this path is a covering one. + * + * And the keys, the same class of rule: the band's shape arrives as M, N, K -- gemm_q_shape reads + * exactly those and pGemmQ names them -- and n_vocab and n_embd are logits_gemm's keys, not this + * op's: read them and N and K are 0, the axis test fires, and a row whose constraints match the + * bands refuses them all at launch, invisible at planning, because the graph reports constraint + * matches and never asks the shim. N and K therefore fall back to r3d_dim(B, 0) and r3d_dim(B, 1) + * -- the weight IS [N, K], so when the band names no key the operand answers, and the operand is + * the authority the engine filled. + * + * The launcher's private codes are -1 a null plane, -2 a shape, -3 a pitch, -4 HIP, -5 an address, + * and the driver names them apart from the RAD codes, which collide numerically. + * + * ---- relayout: none, and it is a claim ---------------------------------------------------------- + * + * The codes plane is read row-major [N, K], the order the container stores it in and the order + * libref reads. libr4d keeps fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64, + * r3d_gemm_fp8a8_gated.hip's header): the two readings are ~1.35 apart, a relative error, not noise. + * So this row carries no relayout and no unrelayout, and the hook is a reader, not a mover -- the + * same claim the gated row makes, for the same reason. + */ + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_tiling.h" /* the LDS row law: srow, srow_pair */ +#include "r3d_launch.h" +#include "rad_planes.h" + +#include +#include +#include + +namespace { + +constexpr int kBlockThreads = 256; +constexpr int kTM = 128; /* rows a tile */ +constexpr int kTN = 128; /* columns a tile: one scale-row */ +constexpr int kKC = 32; /* k a chunk: divides the group */ +constexpr int kGroup = 128; /* R3D_FP8_BLOCK: the band's group */ +/* The complement of gemm_nt_q_fp8a8_m16's declared ceiling, read from the row table: its name + * says M <= 16, so this floor is 17 and M=17..64 is covered. M=17..64 is a batched decode step, + * the most common shape a serving card sees; a floor above it leaves those bands to the host -- + * 209 bands a pass, six of them -- and one host band is what drags the whole model into one host + * run. The tile is 128 rows, so a band of 17 computes 128: 2x wasted at M=64, 7.5x at M=17, and + * 1.8 TFLOP/s on the card is still two orders above the host loop. */ +constexpr int kMMin = 17; + +/* LDS row: 8-element granularity keeps the swizzle uint4-aligned, the rule every tiled row here + * follows (r3d_vocab_bf16.hip's srow, the same function for the same reason). */ +/* srow / srow_pair: r3d_tiling.h, the family's law in one place. */ + +/* The staged side of the same family, typed next to the row law so a kernel's staging and its + * swizzle are read together. u16v is a 16-byte streamed load -- 32 U4 codes, 16 E4M3 codes, and + * the uint4 the tile is written in -- memcpy'd in, never cast: an unaligned cast is UB and the + * compilers say so in bytes of spill. u8v, its 8-byte sibling (8 E4M3 codes, 32 U2 codes, the f32 + * pair a scale row is read in), is declared with the streamed-load helper below. + * + * The scale row, which is why the two arms read a different number of scalars a staged tile: + * fp8a8 b_scale's block is {group, group} = {128, 128}, the block the shape function names, and + * the tile is 128 columns wide, so a staged chunk of 128 rows shares ONE scale: a single + * scalar read a tile, indexed by (n0/128, k0/128). + * w2a8 the grid's block is {1, group}, the same rule that fixes the scale's dtype at f16, so + * the tile's 128 rows are 128 scale rows: 128 scalar reads a chunk, and + * the zero rides with them, 128 more. That is the decode row's pattern -- its scale_at per + * staged 8-group IS the {1, group} case -- and it is kept: the scale is read where the grid + * puts it, not where the tile would like it. A staged row's pair is (scale, zero) and the + * value it stages is (code - zero) * scale, in f16 arithmetic, one v_mul_f16 and one + * v_sub_f16 a code. */ +typedef uint32_t __attribute__((ext_vector_type(4))) u16v; /* a 16-byte streamed load */ + +/* The two operands' scale planes, read the way the container hands them. */ +struct ActQ { + const float* scale; /* a_scale, f32: [M][ceil(K/group)], or [M] with gmode 0 */ + long long row; /* elements a row: ceil(K/group) in group mode, 1 in row mode */ + int gmode; /* 1: one scale per (row, group) -- `a_scale[m][g]`; + * 0: one per ROW -- `a_scale[m]`, the ZP_I8_ROW form */ +}; + +struct WQ { + const uint8_t* codes; /* b's codes plane, [N][K] */ + const uint8_t* scale; /* b_scale's plane: the {128,128} block, or the {1,group} row */ + const uint8_t* zero; /* the asym grid's zero plane, one per (row, group); null if none */ + long long code_row; /* bytes a codes row */ + long long scale_row; /* bytes a scale row */ + long long zero_row; /* bytes a zero row */ + int sdt; /* 0 bf16, 1 f16, 2 f32 */ + int cdt; /* 0 E4M3, 1 int8, 2 U2, 3 U4 */ + int srows; /* 0: scale rows are 128-blocks (fp8a8); 1: scale rows are rows (w2a8, w4a8_asym) */ +}; + +__device__ __forceinline__ int i8_dw(int L) +{ + return (L & ~3) | ((L & 1) << 1) | ((L & 2) >> 1); +} + +/* (code - zero) * scale, in f16 arithmetic, for a sub-byte code read through the block's table: + * the table holds f16(i) for the grid's code values, so the code's decode is one LDS read, the + * scale one v_mul_f16 and the zero one v_sub_f16. This IS the reference's `sub(g) = is(g) - + * z[n][g] * a_sum[g][m]`, formed per element: sum over a group of (a * (q - z) * sb) is the + * reference's bracketed (sum a*q - z * sum a) * sb, term for term. */ +__device__ __forceinline__ uint32_t fold_pair_q(uint32_t codepair, const uint16_t* tbl, + _Float16 s, _Float16 zf, int bits) +{ + const uint32_t m = (1u << bits) - 1u; + /* The table entry is an f16 BIT PATTERN, so it is bit_cast, not converted: a converting cast + * stages 16384 for the code 0x4000, where the value is zero (the board's number was 217). The + * zero comes off BEFORE the scale -- the grid's zero is an integer code and code minus zero is + * exact in f16 for a 4-bit code and a U8 zero, so the staged value costs ONE rounding (the + * multiply) where (code*s) - (z*s) costs two and cancels. */ + const _Float16 a = (__builtin_bit_cast(_Float16, tbl[codepair & m]) - zf) * s; + const _Float16 b = (__builtin_bit_cast(_Float16, tbl[(codepair >> bits) & m]) - zf) * s; + return (uint32_t)__builtin_bit_cast(uint16_t, a) | + ((uint32_t)__builtin_bit_cast(uint16_t, b) << 16); +} + +__device__ __forceinline__ float scale_w(const WQ h, int nb, int g) +{ + const uint8_t* p = h.scale + (long long)nb * h.scale_row + (long long)g * (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); +} + +/* The scale of (row n, group g), in the grid the plane is laid out in. This one line is the whole + * difference between the two grids' scale rows, so it is written once and named for the ROWS: + * fp8a8 b_scale's rows are 128-row blocks ({group, group}) -> the tile's row n lives in block + * n>>7, one scalar serves the tile's 128 rows. + * w2a8 b_scale's rows are the weight's rows ({1, group}) -> row n, 128 scalars a staged chunk. + * The srows flag must match the grid: a scale read from the wrong row is not noise, it is a + * systematic few percent -- the head's bands at rel_l2 1.6e-02 against a fold floor of 1.8e-03 -- + * and it passes any gate set loosely enough. */ +__device__ __forceinline__ float scale_at_w(const WQ h, int n, int g) +{ + return scale_w(h, h.srows ? n : (n >> 7), g); +} + +__device__ __forceinline__ float zero_at_w(const WQ h, int n, int g) +{ + if (!h.zero) return 0.0f; + return (float)h.zero[(long long)n * h.zero_row + g]; /* U8: the plane's practical form */ +} + +/* quant_act_i8's step order: column c sits at (c & ~12) | ((c & 4) << 1) | ((c & 8) >> 1), the + * swap of bits 2 and 3, which is its own inverse. Bits 2 and 3 of a column are + * bits 0 and 1 of its DWORD index, so a dword's four codes stay four contiguous bytes and the + * staging reads a 16-code run's dwords in the order 0, 2, 1, 3. Nothing straddles a dword. */ + + +/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. NOT + * f16x2_pack, which truncates -- see the header and r3d_codecs.h. */ +__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 pairs, through the table. int8 codes take the codec's hardware convert, + * which is two v_cvt_f32_i8 and a pack; there is no such instruction for E4M3. */ +__device__ __forceinline__ void codes8(const uint2 c, int cdt, const uint16_t* tbl, uint32_t* w) +{ + if (!cdt) { r3d_e4m3x8_ld(tbl, c, w); return; } + const uint32_t d[2] = { c.x, c.y }; +#pragma unroll + for (int j = 0; j < 4; ++j) + w[j] = i8x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu); +} + +template +__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 tile: 128 rows x 128 columns of y, 256 threads, eight waves, eight outputs a side a lane -- + * 64 f32 accumulators a lane, grid (N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides + * arrive as E4M3 codes, decode through the block's table and leave staging as f16 with their scale + * folded in, so the dot loop is the vocabulary head's dot loop and nothing in it scales anything. + */ +template /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4 */ +__global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) +fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __restrict__ b, WQ 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]; + + const int tid = (int)threadIdx.x; + if (ARM == 0) { + r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16, the decoder table */ + } else { + /* The asym grid's codes are unsigned integers: U2 has 4 values, U4 has 16. The same + * 512 bytes, filled with f16(i) -- exact for every code the grid can hold. */ + for (int i = tid; i < 16; i += kBlockThreads) sTbl[i] = f32_to_f16((float)i); + __syncthreads(); + } + 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]; +#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; + const int nb = n0 / kGroup; /* TN == the scale plane's row */ + + /* The asym arm's staged row, one per thread for the whole tile: the B staging's row loop is + * `nn = tid; nn < kTN; nn += kBlockThreads`, so thread tid stages row n0+tid in every chunk. + * That is what makes the {1, group} grid's scalars cheap to read: the pair a row needs changes + * only when the k-group changes (kKC 32 divides kGroup 128, so every fourth chunk), and the + * load can be issued a chunk ahead, where its round trip overlaps the dot. + * + * At the 2-bit head's band M=64 N=12288 K=2048, the pair read inside the fold is 210.835 ms, + * 15.3 GFLOP/s; read once a group with a chunk's lead, 2.4 ms, 1344 GFLOP/s. + * The scalar is 128 a chunk -- the grid puts the scale at the row, so that is where it is read, + * and the decode row's pattern is kept -- with one row per thread there is no second load to + * overlap it with, and a round trip on the staging critical path is 64 of them a tile, paid in + * full. The values are identical either way; this is placement of a load, not arithmetic. */ + const int b_row = n0 + tid; + const bool b_has = (ARM == 1) && (tid < kTN) && (b_row < N); + _Float16 s_cur = (_Float16)0.0f, zf_cur = (_Float16)0.0f; + if (b_has) { + s_cur = (_Float16)scale_at_w(h, b_row, 0); + zf_cur = (_Float16)zero_at_w(h, b_row, 0); + } + /* NAMED NON-RESULT: the codes stream is NOT limited by loads in flight. A one-chunk lead on + * the row's codes load -- 8 bytes (U2) or 16 (U4) a row a chunk, issued before the fold -- + * measures 24.430 ms against 24.585 ms at M=64 N=130560 K=2048, 0.6%, bit-identical output. + * The scalar load is the cost because it sits on the critical path with nothing to overlap; the + * stream is not waiting for latency, it is paying sector count: kKC 32 codes a row a chunk is + * 8 bytes drawn from a 512-byte-strided plane, so every row costs a full 64-byte sector and the + * band moves 8x the bytes it uses. 3.7 GB/s useful, 30 GB/s of sectors, and the card is not + * near the sector limit: the shape is the limit. The lever is a wider k-chunk (kKC 64 = 16 bytes + * a row = 4x amplification, kKC 128 = one group a chunk = 2x), paid for in LDS and occupancy -- + * a tiling pass on this arm, not a load lead. */ + + for (int k0 = 0; k0 < K; k0 += kKC) { + const int g = k0 / kGroup; /* one group a chunk: 32 | 128 */ + const float sb = scale_w(h, nb, g); /* one scale for the whole tile */ + +#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) { + if (ARM == 0) { + /* A row's scale, once a staged run: a_scale is (row, group) and the run is + * inside one group. */ + /* The row form contributes no g: `aq.gmode` is 0 and the term is a select, so + * one scale a row costs one IADD and no branch in the staging loop. */ + const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; + uint32_t w[4]; + codes8(loadc8s(a + (long long)m * a_ld + k), 0, 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)); + } else { + /* The w2a8 activation: int8 codes in quant_act_i8's step order, read four codes + * a dword at the permuted dword address, and ONE scale per ROW (ZP_I8_ROW: + * quant_act_i8 scales a whole row, not a group). */ + const float sa = aq.scale[(long long)m * aq.row]; + const int L0 = k >> 2; + const uint8_t* ap = a + (long long)m * a_ld; + const uint32_t d0 = *(const uint32_t*)(ap + (i8_dw(L0) << 2)); + const uint32_t d1 = *(const uint32_t*)(ap + (i8_dw(L0 + 1) << 2)); + const uint32_t d[2] = { d0, d1 }; + uint32_t w[4]; +#pragma unroll + for (int q = 0; q < 4; ++q) + w[q] = i8x2_to_f16x2((d[q >> 1] >> (16 * (q & 1))) & 0xffffu); + 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; + } + if (ARM == 0) { +#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) { + uint32_t w[4]; + codes8(loadc8s(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w); + staged = make_uint4(fold_pair(w[0], sb), fold_pair(w[1], sb), + fold_pair(w[2], sb), fold_pair(w[3], sb)); + } + *(uint4*)&sB[srow(nn, c8, kKC)] = staged; + } + } else { + /* The sub-byte weight, w2a8 (U2, four codes a byte, a row is K>>2 bytes) and + * w4a8_asym (U4, two a byte, K>>1). A lane takes the whole 32-code chunk in one load: + * 8 bytes of U2, 16 of U4, k0 is a multiple of 128 so both are aligned. The scale AND + * the zero are per (row, group) -- the grid's block is {1, group} -- so every staged + * row reads its own pair of scalars: the decode row's pattern, 128 scalar reads a chunk + * where the fp8a8 arm reads one. */ + constexpr int BITS = (CDT == 2) ? 2 : 4; + constexpr int FIELD = 2 * BITS; /* bits a pair of codes occupies */ +#pragma unroll + 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) }; + if (n < N) { + const _Float16 s = s_cur, zf = zf_cur; /* the group's pair, prefetched */ + if (b_has && k0 + kKC < K && (k0 + kKC) / kGroup != g) { + const int gn = (k0 + kKC) / kGroup; + s_cur = (_Float16)scale_at_w(h, b_row, gn); + zf_cur = (_Float16)zero_at_w(h, b_row, gn); + } + uint32_t d[4] = { 0, 0, 0, 0 }; + const uint8_t* cp = h.codes + (long long)n * h.code_row + + (k0 >> (CDT == 2 ? 2 : 1)); + if (CDT == 2) { uint2 v; __builtin_memcpy(&v, cp, 8); d[0] = v.x; d[1] = v.y; } + else { u16v v; __builtin_memcpy(&v, cp, 16); + d[0] = v.x; d[1] = v.y; d[2] = v.z; d[3] = v.w; } + uint32_t w[16]; +#pragma unroll + for (int q = 0; q < 16; ++q) { + /* Pair q of the chunk sits at bit FIELD*q of the row: a 4-bit field for U2 + * (eight to a dword), an 8-bit field for U4 (four to a dword). Neither + * straddles a dword, which is why the field is read from one word. */ + const int bit = q * FIELD; + w[q] = fold_pair_q((d[bit >> 5] >> (bit & 31)) & ((1u << FIELD) - 1u), + sTbl, s, zf, BITS); + } + 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(); + +#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(); + } + + /* 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(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[i] would put the 64 + * accumulators in local memory, which is the trap this family of kernels documents. */ +#pragma unroll + for (int j = 0; j < 8; ++j) + if (n_c + j < N) row[n_c + j] = f32_to_bf16(acc[i][j]); + } + } +} + +/* ------------------------------------------------------------------ the launcher ------------------ */ +/* The launcher speaks the internal codes the shim maps (-3 stride, -4 device, -5 align), so a + * refusal here prints what it saw and returns -3, not the ABI code: the shim would translate -4 into + * E_DEVICE and the message the user reads would name the wrong thing. */ +#define L_STR(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(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 bs_row, int y_ld, int nt, long stream, + int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0) +{ + if (!av || !asv || !bvc || !bsv || !yv) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (group != kGroup) return -2; /* the fold indexes 128; kKC 32 divides it */ + if (K % kGroup) return -2; /* a ragged k-block reads past the scale plane */ + if (nt < 0 || nt > 1) return -2; + if (a_ld % 8) L_STR("a pitch: 8-byte code loads, 8 codes a lane", "a_ld", a_ld, "K", K); + if (b_row & 7) L_STR("b row pitch is not 8-aligned", "b_row", b_row, "N", N); + /* The activation's scale row, which is a DIFFERENT thing in the two arms: fp8a8 carries one + * scale per (row, group) so the row is ceil(K/group) columns; w2a8 and w4a8_asym scale the + * whole row (ZP_I8_ROW: quant_act_i8's law), so it is one column a row and as_ld 1 is the + * legal pitch, not a broken one. The check is per arm for the same reason the staging is. */ + /* The activation's scales arrive in two forms, both the reference's: one per (row, group) at + * width ceil(K/group), and one per ROW at width 1 (the ZP_I8_ROW form -- which is what a per-row + * quantiser produces, and what this checkpoint's plan binds for the served model). Row mode is + * `as_ld == 1` and the kernel drops the group term. */ + if (arm == 0 && as_ld != 1 && as_ld < (K + kGroup - 1) / kGroup) L_STR( + "a_scale: neither one per row nor one per (row, group)", "as_ld", as_ld, + "ceil(K/group)", (K + kGroup - 1) / kGroup); + if (arm == 1 && as_ld < 1) return -3; + if (y_ld % 8) L_STR("y pitch: 16-byte bf16 store runs", "y_ld", y_ld, "N", N); + if (a_ld < K) L_STR("a pitch shorter than K", "a_ld", a_ld, "K", K); + if (y_ld < N) L_STR("y pitch shorter than N", "y_ld", y_ld, "N", N); + if ((av & 7) || (bvc & 7) || (yv & 7) || (asv & 3) || (bsv & 3)) return -5; + if (bs_row & (sdt == 2 ? 3 : 1)) return -3; /* a scale row is 4 bytes a column for f32, 2 for + bf16/f16: ceil(K/128) = 3 columns is 6 bytes. */ + if (arm == 1) { + if (!(arm == 1 && (cdt == 2 || cdt == 3))) return -2; + if (!zv) return -1; /* the asym grid has no spelling without a zero */ + if (z_row < 1) return -3; + if (zv & 1) return -5; + if (cdt == 3 && (bvc & 15)) return -5; /* a 16-byte U4 load; U2 loads 8 */ + } + + 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, as_ld != 1 }; + WQ h{ (const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, + (const uint8_t*)(uintptr_t)zv, b_row, bs_row, z_row, sdt, cdt, srows }; + hipStream_t s = (hipStream_t)(uintptr_t)stream; +#define R3D_RUN(ARM, CD) \ + do { \ + if (nt) fp8a8_tiled_kernel<1, ARM, CD><<>>( \ + (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ + h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ + else fp8a8_tiled_kernel<0, ARM, CD><<>>( \ + (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ + h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ + } while (0) + if (arm == 0) { if (cdt == 1) R3D_RUN(0, 1); else R3D_RUN(0, 0); } + else { if (cdt == 3) R3D_RUN(1, 3); else R3D_RUN(1, 2); } +#undef R3D_RUN + const hipError_t le = hipGetLastError(); + if (le != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[launch] arm=%d cdt=%d nt=%d grid(%u,%u) block(%u) M=%d N=%d K=%d: %s\n", + arm, cdt, nt, grd.x, grd.y, kBlockThreads, M, N, K, hipGetErrorString(le)); + return -4; + } + return 0; +} + +/* libref's float_scale_dt and enc_scaled_rows, inlined: libref keeps them static inline in its own + * header, so a row that transcribes a layout hook transcribes its helpers with it. Checks and + * order unchanged. */ +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 + +/* ================================================================================================== + * The layout hook: b (operand 2) as codes + one scale. + * + * `ref_layout_gemm_q` is the w2a8/w4a8 grid's hook: it is `layout_scaled(operand, 3, -1, ...)` over + * `sel_roles("scale","zero")` with block {1, group}, and it reads `zp_grid(dtype)` first -- and + * zp_grid has no "fp8a8" entry (it lists w2a8, w4a8_asym, w4a16_asym, w5a16, w4a8i8_asym, w5a8i8), + * so the reference's own gemm_nt_q hook ANSWERS NOTHING for dtype=fp8a8: it returns E_DTYPE, the + * placement finds no reader, and the group stays mapped. That is the chain's first link, and it is + * why this hook is the head's class and not that one: two planes, "codes" and "scale", NO zero + * plane (fp8a8 is symmetric), codes tiled one a cell, the scale on the block the shape function + * names -- {group, group}. Body: layout_scaled(operand, 2, -1, ...) as ref_layout_head's is. + * ================================================================================================== */ +/* The writer for the layout this hook names -- the same rad_planes_relayout, the same operand guard, + * the same reason: the plan asks for the container's codes and per-block scales as one operand, and + * the loader converts at load with the row's help and nobody else's. */ +extern "C" int r3d_relayout_gemm_q_fp8_weight(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) +{ + /* The query and the writer are one plan; see r3d_layout_gemm_q_fp8_weight. */ + const char* dt = r3d_pgets(p, n_p, "dtype"); + if (dt && (std::strcmp(dt, "w2a8") == 0 || std::strcmp(dt, "w4a8_asym") == 0)) + return r3d_relayout_gemm_nt_q_w2a8(p, n_p, operand, enc, sel, planes, n_planes, dst, + dst_bytes); /* the decode row's plan, one writer */ + if (operand != 2) return R3D_NO(RAD_E_UNSUPPORTED); + return rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes); +} + +/* The grids this row reads behind operand 2, in two branches that never borrow each other's + * checks. fp8a8 is the symmetric pair (codes, scale) on {1,1} + {group,group}. w2a8 and + * w4a8_asym are the ZERO-POINT triple (codes, scale, zero) on {1,1} + {1,group} + {1,group}: + * ref_layout_gemm_q's plane rules with the codes plane riding along, because this row's plan puts + * all three behind b. The dtype names which grid, and the codes dtype follows it (zp_grid: + * w2a8 -> U2, w4a8_asym -> U4) -- a grid and a code width that disagree is a container this row + * cannot read, at its own line. */ +/* 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_q_fp8_weight(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* planes, int n, RadLayout* out) +{ + const char* dt = r3d_pgets(p, n_p, "dtype"); + if (dt && (std::strcmp(dt, "w2a8") == 0 || std::strcmp(dt, "w4a8_asym") == 0)) + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, r3d_layout_gemm_nt_q_w2a8(p, n_p, operand, enc, sel, planes, n, out)); + + if (n < 2 || operand != 2) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_UNSUPPORTED); /* b is operand 2 of gemm_nt_q */ + + /* The packed grids ask the DECODE ROW what the container looks like, and get the answer by + * calling its hook -- `r3d_layout_gemm_nt_q_w2a8`: codes plain on operand 2, the (scale, zero) + * pair joined on operand 3, the {1, group} block, the f16 scale, the unsigned zero. The engine + * settles one stored form per weight across every row of the op that reads it and says so at + * declare time -- `weight 'dspark.draft_head.scale' is wanted in two stored forms: + * 'rad.planes' by gemm_nt_q_w2a8_m16 and '(as it is)' by gemm_nt_q_w2a8_tiled. A weight is + * stored once` -- so a tile that wants the trio joined behind `b` is not a different plan, it is + * a model that will not load. Two rows describing one weight in one function cannot drift; the + * arm's board measures this arrangement as `decodeform`, 1.660e-03 against the joined fixture's + * 1.677e-03, the same law's noise. */ + + if (!enc_scaled_rows(enc, sel, n)) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); + const long long group = r3d_pgeti_or(p, n_p, "group", 0); + if (group <= 0) return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* the band names the block */ + if (enc->plane[sel[1]].block[0] != group || enc->plane[sel[1]].block[1] != group) + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, RAD_E_DTYPE); /* {group, group} */ + return r3d_layout_trace("r3d_layout_gemm_q_fp8_weight", operand, r3d_pgets(p, n_p, "dtype"), n, rad_planes_layout(enc, sel, planes, n, out)); +} + +/* ================================================================================================== + * The planes' entry: the caller has resolved the two planes and hands their addresses. The band is + * fp8a8, group 128, y bf16. Codes row-major, scales [ceil(N/128)][ceil(K/128)], read as bf16 -- + * fp8a8's stated dtype; the f32 spelling (fp8a8f32) arrives through the shim, which reads the dtype + * off the plane. b_row and bs_row of 0 mean the dense pitch. + * ================================================================================================== */ +extern "C" 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) +{ + const int st = launch(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row ? b_row : K, + as_ld, bs_row ? bs_row : (long long)((K + kGroup - 1) / kGroup) * 2, y_ld, + nt, stream, 0, 0); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +/* ================================================================================================== + * The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. The + * placement joins b and b_scale into one container, so 3 is absent and the container's header is + * read here, on the host; a caller that resolved the planes itself passes 3 and takes the plain + * path. Same kernel, same law, one branch. + * ================================================================================================== */ + +/* RadStream, the ABI's type: RadLaunchFn is int (*)(const RadArgs*, RadStream) and RadStream is + * void* (rad_abi.h, rad_types.h). A shim that takes a long runs -- same width, same convention -- + * and is a function-pointer type the row table has to be lied to about. The entry below keeps long + * because it takes addresses as longs; the cast is here, at the boundary. */ + +/* The plan line's latch: one print per distinct shape this shim sees, keyed on what the line prints + * -- M, N, K, the activation's rank, the scale's rank and the two pitches -- because the served plan + * runs this shim 176 times a forward pass and 42 copies of one line are noise. A plain static array + * with no lock: the worst a race does is print a shape twice, and the flag-off path never reaches + * it. The sibling decode row (gemm_nt_q_fp8a8_m16) has no such line: the shapes below M=17 are its + * served path, and the ones above it are what this line is for. */ +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_tiled(const RadArgs* args, RadStream s) +{ + if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* A = r3d_opt(args, 0); + const RadTensor* AS = r3d_opt(args, 1); + const RadTensor* B = r3d_opt(args, 2); + const RadTensor* BS = r3d_opt(args, 3); + const RadTensor* Y = r3d_opt(args, 4); + const RadTensor* ASUM = r3d_opt(args, 5); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + + /* The band's keys, from the schema this row is declared against: gemm_nt_q carries M, N, K, + * group, dtype (r3d_rows.cpp pGemmQ) -- NOT n_vocab/n_embd, which belong to logits_gemm. Read + * the wrong keys and N and K are 0, every launch is refused below at the shape check, the op + * resolves to a host kernel for every band, the planner puts the whole model in one host run, + * and a norm weight two tiers away refuses to load. Falling back to the weight's own dims keeps + * a caller that names no N/K working, and says which operand is the authority. */ + const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); + const long long K0 = r3d_geti_or(args, "K", 0); + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); + const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); + const long long group = r3d_geti_or(args, "group", 0); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + if (K > (1 << 24)) return R3D_NO(RAD_E_INVAL); /* absurd: a 16M-wide K is a 2 GiB code plane per row */ + if (group != kGroup) return R3D_NO(RAD_E_SHAPE); /* the fold indexes 128 */ + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + if (ASUM && r3d_p(ASUM)) + return R3D_NO(RAD_E_DTYPE); /* fp8a8 is symmetric: a_sum is an asymmetric grid's, and + r3d_gemm_nt_q_w2a8.hip reads that one */ + + /* ---- b: a container of codes + scale, or the two planes as tensors -------------------------- */ + const void* bvc = r3d_p(B); + const void* bsv = nullptr; + long long b_row = 0, bs_row = 0; + int sdt = 0, cdt = 0; + const RadPlanesHeader* ph = (const RadPlanesHeader*)rad_planes_header(bvc); + if (ph) { + /* find answers with the bytes and points into the container; no copy. */ + const RadPlanesEntry* ce = nullptr; + const RadPlanesEntry* se = nullptr; + if (rad_planes_find(bvc, "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 void* cb = rad_planes_find(bvc, "codes", &ce); + const void* sb = rad_planes_find(bvc, "scale", &se); + if (!cb || !sb) return R3D_NO(RAD_E_DTYPE); /* a joined weight that is not codes + scale */ + if (ce->kind != RAD_PLANE_TILED || ce->block[0] != 1 || ce->block[1] != 1) + return R3D_NO(RAD_E_DTYPE); /* codes: one a cell, 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 */ + 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) sdt = 0; + else if (se->dtype == RAD_F16) sdt = 1; + else if (se->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + if (se->block[0] != group || se->block[1] != group) + return R3D_NO(RAD_E_SHAPE); /* per-(row, group) is gemm_nt_q's w2a8 grid; per-row is + not cover's indexing of the plane */ + bvc = cb; bsv = sb; b_row = ce->row_bytes; bs_row = se->row_bytes; + cdt = ce->dtype == RAD_I8; + const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; + 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 < K) return R3D_NO(RAD_E_STRIDE); /* a packed row is not this form */ + if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); + } else { + if (!BS || !r3d_p(BS)) + return R3D_NO(RAD_E_DTYPE); /* a weight that is neither a container nor a scale + tensor: gemm_nt_q's shape hook names the two */ + b_row = K; + const long long sb_r = (N + group - 1) / group, sb_c = (K + group - 1) / group; + /* b_scale as a CONTAINER -- the codes plain on b, the scale joined behind b_scale. The + * sibling decode row uses that spelling for the shared weight, and + * r3d_relayout_gemm_q_fp8_weight writes it for a band whose encoding names its container at + * operand 3, so the plan can hand it here. The header is read on the host, where it lives + * (the same call b's arm makes above); the kernel gets the scale plane's BYTES and the row + * pitch off the ENTRY, which is the identical answer the two-tensor spelling gives. + * A `zero` plane stays refused: fp8a8's activation quantiser is symmetric and this arm has + * no zero to fold -- the reference refuses the grid for it outright -- so a row that + * computed through a zero plane would be inventing a number the oracle has no law for. The + * asymmetric grid is gemm_nt_q's w2a8 form and r3d_gemm_nt_q_w2a8 owns that spelling. */ + const RadPlanesHeader* sph = (const RadPlanesHeader*)rad_planes_header(r3d_p(BS)); + if (sph) { + if (rad_planes_find(r3d_p(BS), "zero", nullptr)) + return R3D_NO(RAD_E_DTYPE); /* codes + scale + zero: r3d_gemm_nt_q_w2a8's grid, + not this arm's -- nor libref's */ + const RadPlanesEntry* se = nullptr; + const void* sb = rad_planes_find(r3d_p(BS), "scale", &se); + if (!sb || !se) + return R3D_NO(RAD_E_DTYPE); /* a joined stream with no `scale` plane: + r3d_relayout_gemm_q_fp8_weight is its writer */ + if (se->kind != RAD_PLANE_TILED) return R3D_NO(RAD_E_DTYPE); + if (se->dtype == RAD_BF16) sdt = 0; + else if (se->dtype == RAD_F16) sdt = 1; + else if (se->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); /* an integer scale is not float_scale_dt */ + if (se->block[0] != group || se->block[1] != group) + return R3D_NO(RAD_E_SHAPE); /* per-row scales are the w2a8 grid; the 128x128 + quantiser writes one scale a (128 rows x 128 codes) */ + if (se->rows != sb_r || se->cols != sb_c) return R3D_NO(RAD_E_SHAPE); + if (se->row_bytes < sb_c * (sdt == 2 ? 4 : 2)) return R3D_NO(RAD_E_STRIDE); + bsv = sb; + bs_row = se->row_bytes; + } else { + bsv = r3d_p(BS); + long long bs_rows = 0; + const long long bs_pitch = r3d_rows_pitch(BS, sb_c, &bs_rows); + if (bs_pitch < 0 || bs_rows < sb_r) return R3D_NO(RAD_E_STRIDE); + if (BS->dtype == RAD_BF16) sdt = 0; + else if (BS->dtype == RAD_F16) sdt = 1; + else if (BS->dtype == RAD_F32) sdt = 2; + else return R3D_NO(RAD_E_DTYPE); + if (r3d_dim(BS, 0) < sb_r || r3d_dim(BS, 1) < sb_c) return R3D_NO(RAD_E_SHAPE); + bs_row = bs_pitch * (sdt == 2 ? 4 : 2); /* the kernel walks the plane's bytes */ + } + if (B->dtype == RAD_F8E4M3) cdt = 0; + else if (B->dtype == RAD_I8) cdt = 1; + else if (rad_dtype_bytes(B->dtype, 8) < 8) return R3D_NO(RAD_E_DTYPE); + else return R3D_NO(RAD_E_DTYPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(B, 0) != N || r3d_dim(B, 1) != K) return R3D_NO(RAD_E_SHAPE); + } + + if (A->dtype != RAD_F8E4M3) return R3D_NO(RAD_E_DTYPE); + if (AS->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + if (Y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); /* gemm_q_shape: y is bf16, one narrowing */ + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + + long long a_rows = 0; + long long a_ld = r3d_rows_pitch(A, K, &a_rows); + /* THE STEP'S M IS THE ACTIVATION'S ROW COUNT. The band key `M` is an upper bound, and the + * engine's own line says so -- its refusal names the step's M against the band's declared bound + * -- so reading the key as the value would refuse a step shorter than the band. libref derives + * M from the operands (the plane, not the plan), and the m16 row does it the same way. The key + * keeps its job as the ceiling the plan promised not to exceed. */ + if (a_ld < K || a_rows < 1) { + /* A group-quantised activation is the same row-major K codes the kernel wants, described in + * the rank the quantiser writes them in: [M][ceil(K/group)][group], contiguous, the row + * exactly K wide. `r3d_rows_pitch` asks for the width by name and a rank-3 plane whose last + * axis is the group does not answer it, so the plane is asked directly: contiguous and + * dividing by K is a plane of rows K wide. */ + if (rad_tensor_is_contiguous(A) && K > 0 && r3d_numel(A) % K == 0) { + const long long r = r3d_numel(A) / K; + if (r >= 1) { a_ld = K; a_rows = r; } + } + } + if (a_ld < K || a_rows < 1) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] a: pitch %lld rows %lld, want pitch >= %lld and at least one row\n", + a_ld, a_rows, (long long)K); + return R3D_NO(RAD_E_STRIDE); } + const long long M = a_rows; + if (M_band > 0 && M > M_band) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] a: %lld rows in a band that declared M <= %lld\n", M, M_band); + return R3D_NO(RAD_E_SHAPE); } + if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices, at the step's + * height, not the band's bound */ + if (M < kMMin) return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_fp8a8_m16 serves M <= 16, and + * this arm's floor is that declared + * ceiling + 1, read from its array */ + const long long kb = (K + group - 1) / group; + /* Two forms of the activation's scales, and the plan binds the one its quantiser produces: + * [M][ceil(K/group)] for a group quantiser, [M] for a per-row one (`a_scale[m]`, the ZP_I8_ROW + * form). `r3d_rows_pitch(AS, kb, ...)` returns -1 for the rank-1 plane -- the scales do not + * divide into rows of kb -- so the width asked for depends on the form, which the rank states; + * both forms must pass, the row form included. */ + const int as_row = (AS->rank <= 1); + const long long as_w = as_row ? 1 : kb; + long long as_rows = 0; + const long long as_ld = r3d_rows_pitch(AS, as_w, &as_rows); + if (as_ld < as_w || as_rows < M) { r3d_trace_desc("a_scale", AS); + std::fprintf(stderr, "[r3d] a_scale: want width %lld (rank %d), pitch %lld, rows %lld, M %lld\n", + as_w, AS->rank, as_ld, as_rows, M); + return R3D_NO(RAD_E_STRIDE); } + long long y_rows = 0; + const long long y_ld = r3d_rows_pitch(Y, N, &y_rows); + if (y_ld < N || y_rows < M) { r3d_trace_desc("y", Y); + std::fprintf(stderr, "[r3d] y: pitch %lld rows %lld, want pitch >= %lld rows >= %lld\n", + y_ld, y_rows, (long long)N, M); + return R3D_NO(RAD_E_STRIDE); } + if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(bvc, 8) || !r3d_aligned(r3d_p(Y), 8)) + return R3D_NO(RAD_E_ALIGN); + if (!r3d_aligned(r3d_p(AS), 4) || !r3d_aligned(bsv, 4)) return R3D_NO(RAD_E_ALIGN); + + /* ---- the plan line, the GEMM's side of the same instrument --------------------------------- + * + * The step's M, off the activation (the header's law: the band key `M` is a BOUND, the plane is + * the value), with the forms the served plan hands this row -- the codes' rank, pitch and numel, + * the scale's rank and pitch, the output's pitch. The fixture draws its descriptors from the + * shape hooks and does not cover the plan's own rank-1 `[M]` scale and rank-3 codes at a + * M >= 17 launch; this line is the instrument for that form: the step's rows against the + * arena's padding, ceil(M/16)*16, and the strides the producer and the consumer each read the + * same plane through. + * + * Inert when the flag is unset -- the cached `r3d_trace_on()` every refusal already pays, and + * the descriptors print through the existing `r3d_trace_desc`. Latched per shape, because this + * shim runs 176 times a forward pass and 42 copies of one line are noise. Printed AFTER every + * check, so a refused step stays the refusal lines' business. */ + if (r3d_trace_on() && gemm_plan_once(M, N, K, A->rank, AS->rank, a_ld, y_ld)) { + std::fprintf(stderr, + "[r3d] plan: gemm M=%lld (band M<=%lld) N=%lld K=%lld group=%lld " + "a rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld rows=%lld " + "a_scale rank=%u numel=%lld pitch=%lld form=%s " + "y rank=%u numel=%lld stride=[%lld,%lld] pitch=%lld Mpad=%lld\n", + M, M_band, N, K, group, (unsigned)A->rank, r3d_numel(A), + r3d_stride(A, 0), r3d_stride(A, 1), a_ld, a_rows, (unsigned)AS->rank, + r3d_numel(AS), as_ld, as_row ? "row[M]" : "group[M][kb]", (unsigned)Y->rank, + r3d_numel(Y), r3d_stride(Y, 0), r3d_stride(Y, 1), y_ld, (M + 15) / 16 * 16); + r3d_trace_desc("gemm a", A); + r3d_trace_desc("gemm a_scale", AS); + r3d_trace_desc("gemm y", Y); + } + + const int nt = (int)r3d_geti_or(args, "nt", 0); + const int st = launch(r3d_addr(A), r3d_addr(AS), (long)(uintptr_t)bvc, (long)(uintptr_t)bsv, + r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)a_ld, b_row, + (int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} + +/* ================================================================================================== + * The w2a8 arm's shim: gemm_nt_q at dtype=w2a8 (codes U2) and dtype=w4a8_asym (codes U4), the same + * tile above the decode heights. The band that gates start-up is N=130560 K=2048 group=128 + * dtype=w2a8 at M=1792 -- the drafter's draft head, read three times a step -- and the graph prints + * it as the last band with no device row. Below kMMin the m16 row (gemm_nt_q_w2a8_m16, + * C_LE("M", 16) in its constraint array) is the served path; above it the tile. The floor is the + * sibling's CEILING, read from its constraints, and it is 17: M=17..64 is a batched decode step, + * the shape a serving card lives in, and 1.8 TFLOP/s of 128-row waste is two orders above the host. + * + * The law is the reference's gemm_zp, ZP_I8_ROW arm, and the kernel runs it in a folded form: + * + * q[k] = the grid's code of weight row n, column k U2: bits [2k,2k+2) of k/4 + * sub(g) = SUM_{k in g} (int)a[m][i8_step_pos(k)] * ((int)q[k] - (int)z[n][g]) integers + * acc = acc + (sub(g) * sa[m]) * sb[n][g] g ASCENDING + * y[m,n] = bf16(acc) + * + * which is the reference's `sub = is - z * a_sum` term for term: sum a*(q - z) = sum a*q - z*sum a, + * exactly, over the same group. So the staged tile carries (q - z) * sb and the a-side carries + * a * sa[m], and a_sum -- which exists to take the 128 bias off an integer dot, because this ISA + * has no int8 dot (r3d_gemm_nt_q_w2a8.hip) -- has no term to take off here: the zero is + * removed per element, before the dot. a_sum is still REQUIRED of a w2a8 band (gemm_zp reads it and + * the schema carries it at slot 5; a band without it is not this band) and the refusal is this + * shim's own line, not the fp8a8 arm's, which REFUSES the same tensor: the two arms' lines are + * deliberately not shared, and the driver's board fires each at its own arm. The bracketing + * differs from the reference (a per-group bracket there, one chain here) by the fold's floor, which + * is what the board measures: rel_l2 against the transcribed body, at a bf16 output, where the + * store's own ulp is the wider of the two. + * + * The activation arrives in quant_act_i8's step order, and its scale is ONE f32 PER ROW (ZP_I8_ROW: + * quant_act_i8 scales a whole row), not per group like fp8a8's. The scale and the zero are per + * (row, group): 128 scalar reads a staged chunk where the fp8a8 arm reads one. + * ================================================================================================== */ +extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) +{ + if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL); + + const char* dt = r3d_gets(args, "dtype"); + int cdt = -1; + if (dt && std::strcmp(dt, "w2a8") == 0) cdt = 2; + else if (dt && std::strcmp(dt, "w4a8_asym") == 0) cdt = 3; + if (cdt < 0) + return R3D_NO(RAD_E_DTYPE); /* the zero-point grids on an int8 activation; w4a8i8_asym and + * w5a8i8 quantise the activation to int8 with a DIFFERENT + * trunk (ZP_I8_GROUP, no per-row scale) and this arm does not + * read them. */ + + const RadTensor* A = r3d_opt(args, 0); + const RadTensor* AS = r3d_opt(args, 1); + const RadTensor* B = r3d_opt(args, 2); + const RadTensor* BS = r3d_opt(args, 3); + const RadTensor* Y = r3d_opt(args, 4); + const RadTensor* ASUM = r3d_opt(args, 5); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + if (!r3d_p(ASUM)) + return R3D_NO(RAD_E_DTYPE); /* a w2a8 band without a_sum is not a w2a8 band: gemm_zp's + * ZP_I8_ROW arm reads it. This kernel folds the zero into the + * staged tile and never indexes it -- see the header. */ + + const long long M_band = r3d_geti_or(args, "M", 0), N0 = r3d_geti_or(args, "N", 0); + const long long K0 = r3d_geti_or(args, "K", 0); + const long long N = N0 > 0 ? N0 : r3d_dim(B, 0); /* the weight IS [N, K]: name the operand + * when the band names no key */ + const long long K = K0 > 0 ? K0 : r3d_dim(B, 1); + const long long group = r3d_geti_or(args, "group", 0); + if (N <= 0 || K <= 0) return R3D_NO(RAD_E_SHAPE); + /* The step's M, off the codes plane, exactly as in the fp8a8 shim above: the band key `M` is the + * ceiling the plan promised not to exceed, not the height of this step, and a draft pass whose + * chunk is shorter than the band it matched is refused by the bound below. */ + long long M = 0; + if (K > 0 && r3d_numel(A) % K == 0) M = r3d_numel(A) / K; + if (M < 1) M = M_band; + if (M_band > 0 && M > M_band) { r3d_trace_desc("a", A); + std::fprintf(stderr, "[r3d] w2a8 a: %lld rows in a band that declared M <= %lld\n", M, M_band); + return R3D_NO(RAD_E_SHAPE); } + if (group != kGroup) + return R3D_NO(RAD_E_SHAPE); /* the fold indexes the group as kGroup; kKC 32 divides it */ + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); /* a ragged k-chunk reads past the plane */ + if (M < kMMin) + return R3D_NO(RAD_E_UNSUPPORTED); /* gemm_nt_q_w2a8_m16's array says M <= 16; the floor of + * this arm is that ceiling + 1, read from the array */ + const long long G = (K + kGroup - 1) / kGroup; + const long long mpad = ((M + 15) / 16) * 16; /* a_sum is group-major, 16 columns min */ + + if (A->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); /* quant_act_i8'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); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_INVAL); /* one scale per ROW (ZP_I8_ROW) */ + if (r3d_numel(ASUM) < G * mpad) return R3D_NO(RAD_E_INVAL); + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (M * N > (1ll << 34)) return R3D_NO(RAD_E_INVAL); /* 32-bit tile indices */ + + /* The weight's planes. This row's plan puts codes, scale and zero behind b (operand 2), which is + * what r3d_layout_gemm_q_fp8_weight's asym branch describes. The decode row's plan puts the + * scale+zero pair behind b_scale and leaves the codes plain on b, and the builder settles ONE + * stored form per weight, so read whichever the container is and find the planes by role: a row + * that insists on the arrangement it declared will refuse the settled bytes of a weight it + * shares with the sibling. */ + const void* bbase = r3d_p(B); + const RadPlanesHeader* bh = rad_planes_header(bbase); + bool codes_joined = false; /* the codes plane inside b's container? */ + const RadPlanesEntry *ce = nullptr, *se = nullptr, *ze = nullptr; + const void* sp = nullptr; const void* zp = nullptr; + long long c_row = 0, s_row = 0, z_row = 0; + const void* sv = nullptr; const void* zv = nullptr; + if (bh) { + const long long cb = (cdt == 2) ? (K >> 2) : (K >> 1); + sp = rad_planes_find(bbase, "scale", &se); + zp = rad_planes_find(bbase, "zero", &ze); + const void* cp = rad_planes_find(bbase, "codes", &ce); + if (!cp || !sp || !zp) return R3D_NO(RAD_E_DTYPE); /* three planes or nothing */ + if (ce->dtype != (uint32_t)(cdt == 2 ? RAD_U2 : RAD_U4)) return R3D_NO(RAD_E_DTYPE); + if (ce->row_bytes < cb) return R3D_NO(RAD_E_STRIDE); + c_row = ce->row_bytes; + codes_joined = true; + } else { + if (!r3d_p(BS)) return R3D_NO(RAD_E_DTYPE); /* no zero, no plain spelling: the zero + * point has nowhere to live outside the + * container. */ + const RadPlanesHeader* h3 = rad_planes_header(r3d_p(BS)); + if (!h3) return R3D_NO(RAD_E_DTYPE); /* the decode row's arrangement: the + * scale+zero pair joined behind b_scale */ + sp = rad_planes_find(r3d_p(BS), "scale", &se); + zp = rad_planes_find(r3d_p(BS), "zero", &ze); + if (!sp || !zp) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != (uint32_t)(cdt == 2 ? RAD_U2 : RAD_U4)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + c_row = rad_dtype_bytes(B->dtype, r3d_dim(B, 1)); /* the row in BYTES, the same measure + * the container's entry carries on the + * joined side: K/4 for U2, K/2 for U4. + * A hand-rolled `K * (1) / 2` + * integer-divides the U2 case to zero + * and the kernel then reads every row + * from the start of the plane: the + * decode form comes out rel_l2 1.9. */ + (void)ce; + } + if (!se || !ze) return R3D_NO(RAD_E_DTYPE); + if (se->dtype != RAD_F16) + return R3D_NO(RAD_E_DTYPE); /* the grid's scale is f16; a bf16 or f32 + * scale plane is the fp8a8 grid's, not this one. */ + if (ze->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); /* DECLINED, at the site: a sub-byte zero plane needs the bit + * extract (rad_load_bits(zb, bits, g), ten lines) that the m16 + * row also declines. U8 is w2a8's practical form. */ + if (se->rows != N || se->cols != G || ze->rows != N || ze->cols != G) + return R3D_NO(RAD_E_SHAPE); /* {1, group}: the scale's rows are the weight's rows */ + if ((se->row_bytes & 1) || se->row_bytes < 2 * G || ze->row_bytes < G) + return R3D_NO(RAD_E_STRIDE); + if (bh) { + if (ce->rows != N || ce->cols != K) return R3D_NO(RAD_E_SHAPE); + if (ce->row_bytes < c_row) return R3D_NO(RAD_E_STRIDE); + } else if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + + long long a_rows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &a_rows); + if (a_ld < K || (a_ld & 3)) return R3D_NO(RAD_E_STRIDE); /* four codes a dword, step order */ + long long yrows = 0; + const long long y_ld = r3d_rows_pitch(Y, N, &yrows); + if (y_ld < N) return R3D_NO(RAD_E_STRIDE); + if (yrows > 0 && yrows < M) return R3D_NO(RAD_E_STRIDE); + const long long as_ld = 1; /* a_scale is rank 1: one per row */ + sv = se ? (const char*)sp : nullptr; + zv = ze ? (const char*)zp : nullptr; + s_row = se->row_bytes; z_row = ze->row_bytes; + const long long bvc = codes_joined + ? (long long)(uintptr_t)((const char*)bbase + ce->offset) /* the container's + * codes plane */ + : (long long)(uintptr_t)r3d_p(B); + + if (!r3d_aligned(r3d_p(A), 8) || !r3d_aligned(r3d_p(Y), 8) || + !r3d_aligned(sv, 2) || !r3d_aligned(zv, 1)) return R3D_NO(RAD_E_ALIGN); + + const int nt = (int)r3d_geti_or(args, "nt", 0); + const int st = launch(r3d_addr(A), r3d_addr(AS), bvc, (long)(uintptr_t)sv, r3d_addr(Y), + (int)M, (int)N, (int)K, (int)group, (int)a_ld, c_row, (int)as_ld, + s_row, (int)y_ld, nt, (long)(uintptr_t)s, /*sdt*/ 1, cdt, + (long)(uintptr_t)zv, z_row, /*srows*/ 1, /*arm*/ 1); + if (st == -1) return R3D_NO(RAD_E_INVAL); + if (st == -2) return R3D_NO(RAD_E_SHAPE); + if (st == -3) return R3D_NO(RAD_E_STRIDE); + if (st == -5) return R3D_NO(RAD_E_ALIGN); + if (st == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} diff --git a/libr3d/r3d_gemm_inta8.hip b/libr3d/r3d_gemm_inta8.hip new file mode 100644 index 00000000..27454ebc --- /dev/null +++ b/libr3d/r3d_gemm_inta8.hip @@ -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 +__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)), 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 diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip new file mode 100644 index 00000000..cb3dc181 --- /dev/null +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -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 + +#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 +#include +#include + +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 +__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 +__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(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 +__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)), 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><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + else mxfp4a8_tiled_kernel<0><<>>( + (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 diff --git a/libr3d/r3d_gemm_nt_q_w2a8.hip b/libr3d/r3d_gemm_nt_q_w2a8.hip new file mode 100644 index 00000000..524c8028 --- /dev/null +++ b/libr3d/r3d_gemm_nt_q_w2a8.hip @@ -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 + +#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 +__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)), 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)); +} diff --git a/libr3d/r3d_launch.h b/libr3d/r3d_launch.h new file mode 100644 index 00000000..bdda29e5 --- /dev/null +++ b/libr3d/r3d_launch.h @@ -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<<>>(__VA_ARGS__) +#endif +#ifndef R3D_DYN_LDS +#define R3D_DYN_LDS(type, name) extern __shared__ type name[] +#endif +#endif diff --git a/libr3d/r3d_model_bf16.hip b/libr3d/r3d_model_bf16.hip new file mode 100644 index 00000000..6f6e557c --- /dev/null +++ b/libr3d/r3d_model_bf16.hip @@ -0,0 +1,2072 @@ +/* r3d_model_bf16.hip -- the small ops the engine issues between the GEMMs: the norms, the + * elementwise arithmetic, the activations, cast, softmax, the embedding gather, gather_rows and + * scatter_rows, rope and the KV store. Every one of them needs a device launch, because the + * engine's buffers live in VRAM and `rad_issue` refuses an op with no launch for its operands' + * domain: on an RDNA3 card this unit is the difference between a model that runs and one that does + * not (R3D_CONTRACT, "What libr3d is"). + * + * The arithmetic is libref's -- the oracle every row is checked against at kbench -- and each + * kernel names the ref function it must equal, its operation order and its rounding points: + * + * * every reduction accumulates in f32 and only the store narrows, RTNE (r3d_codecs.h is + * rad_plugin.h's rounders restated for device code, bit for bit); + * * a row's sum is taken over lanes covering consecutive elements, butterflies in the order a + * `__shfl_xor` loop runs and wave partials added in wave order: `block_sum` in r3d_common.h, + * so the bracketing is the one the contract fixes and not a per-thread accident; + * * bf16 is kept in whole registers from load to store (`ldg_u16`) and a lane that owns two + * consecutive columns stores them as one dword through `bf16x2_rne` -- gfx11 has no + * v_cvt_pk_bf16_f32, so the pack is two software roundings and a v_perm_b32; + * * no FMA and no reassociation: -ffp-contract=off is on every HIP source (libr3d/CMakeLists.txt) + * and the expressions below are written in the reference's order, with the temporaries the + * reference has; + * * a negative index -- token id, gather row, KV slot -- is padding: a zero row, or no store. + * It is not clamped to zero, which would duplicate row 0 across every padding row. + * + * One deliberate divergence from ref, the same one libr4d states: ref validates its index arrays + * on the host and refuses an id at or past the row count. A kernel cannot do that without a copy + * and a sync on the step path, so a row count is an argument and an out-of-range id takes the + * padding path (zero row, no store) instead of faulting. kv_store's slot bound is the one place + * the reference has an argument the launcher does not (see below). + * + * `expf`, `powf` and `sincosf` are the accurate forms, not the `__` approximations: rope positions + * reach 262144, past __sincosf's argument reduction, and libref evaluates every transcendental in + * double and rounds once (libref's ref_exp/ref_pow/ref_sin/ref_cos/ref_erf). None of these + * paths is the step's bottleneck, so the difference between libm and a device routine -- a few + * ULP of f32, against the 1/256 of a bf16 store -- is the whole of the tolerance. + * + * No fusion: `rmsnorm_add` and the gated quantisers are separate entry points the architecture + * plugin selects (spec §2.3), and live in other units. + * + * Two layers per op, as r3d.h states: a launcher that takes pointers as longs and geometry as + * ints, checks what a `__global__` cannot, computes the grid and issues one kernel on the stream it + * was handed; and the shim the row table names, which reads the operands with r3d_args.h, takes + * the dtype from the tensor and the row count from the operand, and returns a RAD status. Neither + * allocates, neither synchronises. A launcher returns 0 or -1 (null), -2 (extent), -3 (pitch), + * -4 (the HIP launch failed); a shim maps any non-zero code to RAD_E_DEVICE. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include +#include +#include + +namespace { + +constexpr uint32_t kThreads = 256; // eight wave32s: the wide row, the hidden state +constexpr uint32_t kNarrow = 32; // one wave32: the narrow row, a head of a QK norm +constexpr uint32_t kNarrowN = 256; // a row this narrow is a wave's, eight columns a lane + +/* The workgroup a row gets: one wave for the rows a wave already covers -- an attention head, a + * KV head, a QK norm, where a 256-thread group would spend three quarters of its lanes on a + * barrier -- and 256 for everything wider. */ +static inline int row_threads(int n) { return n <= (int)kNarrowN ? (int)kNarrow : (int)kThreads; } + +/* ================================================================== the seams every kernel here + * shares + * + * A whole-register store beside r3d_common.h's whole-register load. The dword form is the pair + * store; the caller has already proved the address even, in elements, from a base alignment of 4. + * The address-space cast is r3d_common.h's own, a C-style cast to the qualified type: + * reinterpret_cast refuses to change address spaces. + */ +typedef uint32_t __attribute__((address_space(1))) *r3d_gu32; +typedef float __attribute__((address_space(1))) *r3d_gf32; +typedef int32_t __attribute__((address_space(1))) *r3d_gi32; +typedef int64_t __attribute__((address_space(1))) *r3d_gi64; + +__device__ __forceinline__ void stg_u32(uint16_t* p, uint32_t v) { *(r3d_gu32)p = v; } +__device__ __forceinline__ void stg_f32(float* p, float v) { *(r3d_gf32)p = v; } +/* A dword of four codes at a byte address: the fp8 quantiser's store. */ +__device__ __forceinline__ void stg_code4(uint8_t* p, uint32_t v) { *(r3d_gu32)p = v; } +__device__ __forceinline__ int32_t ldg_i32(const int32_t* p) { return *(r3d_gi32)(uintptr_t)p; } +__device__ __forceinline__ int64_t ldg_i64(const int64_t* p) { return *(r3d_gi64)(uintptr_t)p; } +__device__ __forceinline__ void stg_i32(int32_t* p, int32_t v) { *(r3d_gi32)p = v; } +__device__ __forceinline__ void stg_i64(int64_t* p, int64_t v) { *(r3d_gi64)p = v; } +__device__ __forceinline__ uint16_t ldg_u16_at(const uint16_t* p, uint32_t i) { return (uint16_t)ldg_u16(p + i); } + +/* The max across a workgroup, in the shape block_sum has: a wave butterfly and one LDS round trip. + * The order is free -- a max is associative, commutative and idempotent, so softmax's maximum is + * the one reduction whose bracketing cannot change the answer -- and every wave has to reach the + * LDS before any thread reads it, which is what the barrier inside is for. */ +template +__device__ __forceinline__ float block_max(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_max(v); + if (lane == 0) lds[w] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (int i = 1; i < NWAVES; ++i) t = fmaxf(t, lds[i]); + return t; +} + +/* ================================================================== one element, any dtype + * + * cast, fill, gather_rows, scatter_rows, embed_lookup and kv_store are one kernel over several + * dtypes, because their dtype is a runtime value in the launcher's argument list. These are + * the reference's ld_dt and st_dt over libr3d's dtype codes, and they are deliberately as + * expensive -- one switch per element, "the price of being generic" in ref's own words. None of + * them is a matmul; none of them reads one element per FLOP. + * + * The integer stores round to nearest even, saturate, and store NaN as 0 (sat_round, the + * reference's): wrapping an overflowing activation into a plausible small number is the failure + * this library has to catch, not hide. + */ +__device__ __forceinline__ float sat_round(float v, float lo, float hi) { + if (v != v) return 0.0f; + const float r = rintf(v); + return r < lo ? lo : (r > hi ? hi : r); +} + +__device__ __forceinline__ float ld_elem(int dt, const void* p, size_t i) { + switch (dt) { + case R3D_DT_BF16: return bf16_to_f32(ldg_u16_at((const uint16_t*)p, (uint32_t)i)); + case R3D_DT_F16: return f16_to_f32((uint16_t)ldg_u16((const uint16_t*)p + i)); + case R3D_DT_F32: return ldg_f32((const float*)p + i); + case R3D_DT_I32: return (float)ldg_i32((const int32_t*)p + i); + case R3D_DT_I64: return (float)ldg_i64((const int64_t*)p + i); + case R3D_DT_U8: return e4m3_to_f32(((const uint8_t*)p)[i]); // the container's fp8 byte + case R3D_DT_I8: return (float)((const int8_t*)p)[i]; + default: return 0.0f; // the shims refuse every other code; mirrors ref's ld_dt + } +} + +__device__ __forceinline__ void st_elem(int dt, void* p, size_t i, float v) { + switch (dt) { + case R3D_DT_BF16: ((uint16_t*)p)[i] = f32_to_bf16(v); break; + case R3D_DT_F16: ((uint16_t*)p)[i] = f32_to_f16(v); break; + case R3D_DT_F32: stg_f32((float*)p + i, v); break; + case R3D_DT_U8: ((uint8_t*)p)[i] = f32_to_e4m3(v); break; // saturating, RTNE + case R3D_DT_I8: ((int8_t*)p)[i] = (int8_t)sat_round(v, -128.0f, 127.0f); break; + case R3D_DT_I32: { + const float r = sat_round(v, -0x1p31f, 0x1p31f); + stg_i32((int32_t*)p + i, r >= 0x1p31f ? INT32_MAX : (int32_t)r); + break; + } + case R3D_DT_I64: { + const float r = sat_round(v, -0x1p63f, 0x1p63f); + stg_i64((int64_t*)p + i, r >= 0x1p63f ? INT64_MAX : (int64_t)r); + break; + } + default: break; + } +} + +/* The integer pair cast, which must not pass through f32: a token id above 2^24 does not survive + * one, and an i64 -> i32 copy of a table offset that rounds is a wrong row, not a near miss. */ +__device__ __forceinline__ int64_t ld_int(int dt, const void* p, size_t i) { + switch (dt) { + case R3D_DT_I32: return (int64_t)ldg_i32((const int32_t*)p + i); + case R3D_DT_I64: return ldg_i64((const int64_t*)p + i); + case R3D_DT_I8: return (int64_t)((const int8_t*)p)[i]; + case R3D_DT_U8: return (int64_t)((const uint8_t*)p)[i]; + default: return 0; + } +} + +__device__ __forceinline__ void st_int(int dt, void* p, size_t i, int64_t v) { + switch (dt) { + case R3D_DT_I32: stg_i32((int32_t*)p + i, (int32_t)v); break; + case R3D_DT_I64: stg_i64((int64_t*)p + i, v); break; + case R3D_DT_I8: ((int8_t*)p)[i] = (int8_t)v; break; + case R3D_DT_U8: ((uint8_t*)p)[i] = (uint8_t)v; break; + default: st_elem(dt, p, i, (float)v); break; + } +} + +__device__ __host__ __forceinline__ bool int_pair(int dt) { + return dt == R3D_DT_I32 || dt == R3D_DT_I64 || dt == R3D_DT_I8 || dt == R3D_DT_U8; +} + +/* The bytes an element of a dtype code occupies, on both sides of the launch: r3d_dt_size is a host + * inline, and the gather kernels walk rows in bytes. */ +__device__ __forceinline__ int dt_bytes(int dt) { + switch (dt) { + case R3D_DT_BF16: case R3D_DT_F16: return 2; + case R3D_DT_F32: case R3D_DT_I32: return 4; + case R3D_DT_I64: return 8; + case R3D_DT_U8: case R3D_DT_I8: return 1; + default: return 0; + } +} + +/* The activation, off libref's act_* set. The reference evaluates the transcendental in double + * and rounds once to f32 (libref's ref_exp/ref_erf); the device's accurate expf/erff are a + * few ULP of f32 away, and the store to bf16 keeps 8 mantissa bits. gelu is the exact erf form -- + * "gelu" means this in libref, and the tanh approximation has to be asked for by name. */ +template +__device__ __forceinline__ float act_of(float x) { + if constexpr (ACT == R3D_ACT_SIGMOID) return 1.0f / (1.0f + expf(-x)); + if constexpr (ACT == R3D_ACT_GELU) + return 0.5f * x * (1.0f + erff(x * 0.70710678118654752f)); + return x * (1.0f / (1.0f + expf(-x))); // silu: x * sigmoid(x), the product rounded once +} + +/* ================================================================== rmsnorm + * rms_rows: + * + * ss = sum_i x[i]^2 f32, ascending index order + * s = 1 / sqrt(ss/n + eps) + * y[i] = x[i] * s * (w ? w[i] + wadd : 1) * mult + * + * The mean is over the last n of the row and the gain rides every row. An absent gain is the + * constant 1 -- the shim refuses `wadd` without one, as ref does -- and the gain's dtype is read + * off the operand (WDT: R3D_DT_BF16, R3D_DT_F32, R3D_DT_N for none), because a checkpoint that + * stores its gains in f32 (a QK-norm's, an audio tower's) is read as it is. Forming 1+w in bf16 + * first loses 0.3% per channel, which is why `wadd` is added in f32 here. + * + * `mult` scales the normed row before its one rounding, for a residual branch weighted by a + * constant (Gemma 4's audio feed-forward uses 0.5); 1 leaves the product chain alone. + */ +template +__global__ __launch_bounds__(THR) void rmsnorm_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, + uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, int pair) { + typedef typename std::conditional::type T; + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = ld(xr, i); + ss += v * v; + } + ss = block_sum(ss, lds); + const float s = 1.0f / sqrtf(ss / (float)n + eps); + + const uint16_t* __restrict__ wr = (const uint16_t*)w; + const float* __restrict__ wf = (const float*)w; + /* One expression, the reference's order: ((x * s) * (w + wadd)) * mult. */ + const auto scaled = [&](uint32_t i) { + const float g = WDT == R3D_DT_N ? 1.0f + : (WDT == R3D_DT_F32 ? ldg_f32(wf + i) : bf16_to_f32(ldg_u16_at(wr, i))) + wadd; + return ld(xr, i) * s * g * mult; + }; + if (pair) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32((uint16_t*)yr + i, bf16x2_rne(scaled(i), scaled(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = scaled(i); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== layernorm + * Two passes -- the mean, then the squared deviations about that + * mean -- and not one pass of E[x^2] - E[x]^2, which cancels badly when the mean is large against + * the spread. Biased variance (divide by n), as transformers use. The store is the third pass: + * + * y[i] = ((x[i] - mean) * s * w[i]) + b[i] + * + * with `b` optional and the gain bf16 (the launcher has no gain dtype; libref reads w's through + * its own dtype, so an f32 gain is refused by the shim, not read as bf16). + */ +template +__global__ __launch_bounds__(THR) void layernorm_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, const uint16_t* __restrict__ b, + uint16_t* __restrict__ y, uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld, int pair) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + + float sum = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) sum += bf16_to_f32(ldg_u16_at(xr, i)); + const float mean = block_sum(sum, lds) / (float)n; + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float d = bf16_to_f32(ldg_u16_at(xr, i)) - mean; + ss += d * d; + } + const float s = 1.0f / sqrtf(block_sum(ss, lds) / (float)n + eps); + + const auto scaled = [&](uint32_t i) { + float v = (bf16_to_f32(ldg_u16_at(xr, i)) - mean) * s * bf16_to_f32(ldg_u16_at(w, i)); + if (b) v += bf16_to_f32(ldg_u16_at(b, i)); + return v; + }; + if (pair) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(scaled(i), scaled(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) + ((uint16_t*)yr)[i] = f32_to_bf16(scaled(i)); + } +} + +/* ================================================================== add / mul + * elementwise2, one rule per line: + * + * u = a[i]; v = b[i]; s = mul ? u*v : u+v; + * if (div != 1) s = round_to_y(s) / div; two roundings, y's dtype + * y[i] = round_to_y(s) + * + * `div` is the last sum of a mean taken pairwise -- (b0+b1+b2)/3, as a vocoder averages its + * residual blocks -- and the sum is narrowed before it is divided because the unfused pair stores + * it. 1 is the plain sum. + * + * The broadcast: b carrying exactly n elements rides every row (`bcast`, which the shim sets off + * the operand's element count, as ref does); nothing else broadcasts, so a shape bug cannot pass + * as a plausible number. The f32 pair narrows nothing on the way (round_dt(f32) is the identity), + * and `y` may be `a`: every element is read by the thread that writes it. + */ +template +__global__ __launch_bounds__(THR) void binary_kernel( + const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y, + uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, float div) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ ar = (const T*)a + (size_t)m * a_ld; + const T* __restrict__ br = (const T*)b + (size_t)m * b_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + const auto at = [&](uint32_t i) { + const float u = ld(ar, i), v = ld(br, i); + float s = MUL ? u * v : u + v; + if (div != 1.0f) s = F32 ? s / div : bf16_to_f32(f32_to_bf16(s)) / div; + return s; + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) { + const float lo = at(i), hi = at(i + 1); + if (F32) { + stg_f32((float*)yr + i, lo); + stg_f32((float*)yr + i + 1, hi); + } else { + stg_u32((uint16_t*)yr + i, bf16x2_rne(lo, hi)); + } + } + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = at(i); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== cast + * `from`/`to` are the selector's; the bytes are what the tensors say, + * which is what ref reads and what this kernel does. An integer pair goes straight through, so a + * token id above 2^24 survives an i64 -> i32 copy; everything else widens to f32 and narrows once + * on the way out. One switch per element: cast is a bandwidth op between stages, not a hot loop. + */ +template +__global__ __launch_bounds__(THR) void cast_kernel( + const void* __restrict__ x, void* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld, + int from_dt, int to_dt, int intp) { + const uint32_t m = blockIdx.x; + /* Both pitches are in elements of their own dtype, and the row base is in bytes. */ + const char* __restrict__ xr = (const char*)x + (size_t)m * x_ld * (size_t)dt_bytes(from_dt); + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)dt_bytes(to_dt); + for (uint32_t i = threadIdx.x; i < n; i += THR) { + if (intp) st_int(to_dt, yr, i, ld_int(from_dt, xr, i)); + else st_elem(to_dt, yr, i, ld_elem(from_dt, xr, i)); + } +} + +/* ================================================================== silu / gelu / sigmoid + * unary: one element, one activation, one narrowing by the store. + * The three are one kernel with the activation as a template argument, because libr3d's rows serve + * all three and the body differs by one expression. */ +template +__global__ __launch_bounds__(THR) void unary_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, + uint32_t y_ld) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) { + const float lo = act_of(ld(xr, i)), hi = act_of(ld(xr, i + 1)); + if (F32) { + stg_f32((float*)yr + i, lo); + stg_f32((float*)yr + i + 1, hi); + } else { + stg_u32((uint16_t*)yr + i, bf16x2_rne(lo, hi)); + } + } + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float v = act_of(ld(xr, i)); + if (F32) stg_f32((float*)yr + i, v); + else ((uint16_t*)yr)[i] = f32_to_bf16(v); + } + } +} + +/* ================================================================== act_mul + * y = act(a) * b, with the activation narrowed to y's dtype first, + * because the unfused pair stores it -- the rounding is the contract, not a detail: + * + * v = act(a[i]); y[i] = round_to_y( round_to_y(v) * b[i] ) + * + * `a` and `b` are the two halves of a fused projection, so each has its own pitch. The shims serve + * silu, gelu (the exact erf form) and sigmoid; gelu_tanh and quick_gelu are libref's other two + * kActs entries and are refused, so the row's constraints state which gated MLPs reach this card. + */ +template +__global__ __launch_bounds__(THR) void act_mul_kernel( + const uint16_t* __restrict__ g, const uint16_t* __restrict__ u, uint16_t* __restrict__ y, + uint32_t n, uint32_t g_ld, uint32_t u_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ gr = g + (size_t)m * g_ld; + const uint16_t* __restrict__ ur = u + (size_t)m * u_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + /* The activation, narrowed; then the product, narrowed by the store. */ + const auto at = [&](uint32_t i) { + const float v = bf16_to_f32(f32_to_bf16(act_of(bf16_to_f32(ldg_u16_at(gr, i))))); + return v * bf16_to_f32(ldg_u16_at(ur, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(at(i), at(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) + ((uint16_t*)yr)[i] = f32_to_bf16(at(i)); + } +} + +/* ================================================================== silu_mul + * y[i] = silu(gate_up[i]) * gate_up[n + i], over ONE fused operand: + * the gate is the first half, which is the order rad-convert fuses gate and up into one weight in. + * + * Nothing is narrowed between the activation and the product. act_mul rounds the activation to y's + * dtype first because it replaces an unfused pair that stored it; silu_mul is the fused pair, so + * its product is the f32 activation times the f32 up, rounded once by the store. + */ +template +__global__ __launch_bounds__(THR) void silu_mul_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, uint32_t n, uint32_t gu_ld, + uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + const auto at = [&](uint32_t i) { + return act_of(bf16_to_f32(ldg_u16_at(gr, i))) * + bf16_to_f32(ldg_u16_at(gr, n + i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32(yr + i, bf16x2_rne(at(i), at(i + 1))); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) ((uint16_t*)yr)[i] = f32_to_bf16(at(i)); + } +} + +/* ================================================================== rmsnorm_quant_fp8 + * The residual add, the norm, and the E4M3 quantiser of the result in one + * pass, so the normalised activation never goes back to VRAM. The arithmetic of the quantiser is + * r3d_quant_fp8.hip's, and `q8_group` before it, bit for bit: `sc = amax * (1.0f / + * 448.0f)` (the reciprocal MULTIPLIED), `inv = 1.0f / sc`, the codes `v * inv` clamped to +-448 by + * comparisons and not by fminf/fmaxf (those replace a NaN with the bound; a NaN activation encodes + * as the format's NaN), and a group whose amax is zero takes scale 1. + * + * Two properties of ref's order are load-bearing and are kept: + * the residual sum is STORED (narrowed to bf16) before the variance reads it, so the norm is over + * the bf16 sum. That is what makes this the `add` + `rmsnorm` pair and not `rmsnorm_add`, which + * normalises the unrounded sum; + * the quantiser codes the bf16 normalised value, not the f32 one -- `out_bf16`, when asked for, + * holds exactly the bytes the codes were taken over. + * + * A group is a wave at a time, four consecutive columns a lane per 128 columns, so the amax is a + * register max plus one wave butterfly (a maximum is exact in any order) and the codes leave as + * dwords. The normalised row is RECOMPUTED in the second pass from the same operands -- hot in L2, + * and it keeps the row's length out of LDS, which is what lets one workgroup take a 5120-column row. + */ +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + uint8_t* __restrict__ q, float* __restrict__ s, uint16_t* __restrict__ ob, uint32_t n, + float eps, float wadd, uint32_t x_ld, uint32_t res_ld, uint32_t ob_ld, uint32_t q_ld, + uint32_t s_ld) { + constexpr uint32_t kChunk = 128u; /* a lane's four columns per chunk */ + constexpr uint32_t kNChunk = (uint32_t)GROUP / kChunk; /* chunks a group is: 1, 2 or 4 */ + constexpr float kTopE4M3 = 448.0f; + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ rr = res ? res + (size_t)m * res_ld : nullptr; + uint8_t* __restrict__ qr = q + (size_t)m * q_ld; + float* __restrict__ sr = s + (size_t)m * s_ld; + uint16_t* __restrict__ obr = ob ? ob + (size_t)m * ob_ld : nullptr; + + /* The row the norm is taken over: the residual plane, once the sum has been written to it. */ + const auto src = [&](uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(rr ? rr + i : xr + i)); + }; + if (rr) { + for (uint32_t i = threadIdx.x; i < n; i += THR) + rr[i] = f32_to_bf16(bf16_to_f32(ldg_u16_at(xr, i)) + bf16_to_f32(ldg_u16_at(rr, i))); + } + __syncthreads(); + + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = src(i); ss += v * v; } + ss = block_sum(ss, lds); + const float rs = 1.0f / sqrtf(ss / (float)n + eps); + __syncthreads(); + + const uint32_t wave = threadIdx.x / kWave, lane = threadIdx.x & (kWave - 1); + const uint32_t ngrp = n / (uint32_t)GROUP; + for (uint32_t g = wave; g < ngrp; g += (uint32_t)(THR / kWave)) { + const uint32_t base = g * (uint32_t)GROUP + 4u * lane; + float v[kNChunk][4]; + float am = 0.0f; + for (uint32_t j = 0; j < kNChunk; ++j) { + for (uint32_t c = 0; c < 4u; ++c) { + const uint32_t i = base + j * kChunk + c; + /* The gain's dtype is the checkpoint's, read off the operand -- WDT, the plain + * rmsnorm's leg: the gains are read as stored, and the op's `dtype` names the + * ACTIVATION, never the weight. */ + const float gain = (!w ? 1.0f + : WDT == R3D_DT_F32 ? ldg_f32((const float*)w + i) + : bf16_to_f32(ldg_u16_at((const uint16_t*)w, i))) + + wadd; + /* The normalised value narrowed to bf16, which is the value ref quantises and the + * value out_bf16 holds. */ + const float h = bf16_to_f32(f32_to_bf16(src(i) * rs * gain)); + v[j][c] = h; + const float t = std::fabs(h); + if (t > am) am = t; /* ref's `if (m > amax) amax = m`: NaN is skipped */ + } + } + am = wave_max(am); + const float sc = am > 0.0f ? am * (1.0f / kTopE4M3) : 1.0f; + const float inv = 1.0f / sc; + if (lane == 0) stg_f32(sr + g, sc); + for (uint32_t j = 0; j < kNChunk; ++j) { + float c0 = v[j][0] * inv, c1 = v[j][1] * inv, c2 = v[j][2] * inv, c3 = v[j][3] * inv; + if (c0 > kTopE4M3) c0 = kTopE4M3; else if (c0 < -kTopE4M3) c0 = -kTopE4M3; + if (c1 > kTopE4M3) c1 = kTopE4M3; else if (c1 < -kTopE4M3) c1 = -kTopE4M3; + if (c2 > kTopE4M3) c2 = kTopE4M3; else if (c2 < -kTopE4M3) c2 = -kTopE4M3; + if (c3 > kTopE4M3) c3 = kTopE4M3; else if (c3 < -kTopE4M3) c3 = -kTopE4M3; + const uint32_t lo = e4m3x2_pack(c0, c1), hi = e4m3x2_pack(c2, c3); + stg_code4(qr + base + j * kChunk, lo | (hi << 16)); + if (obr) { + stg_u32(obr + base + j * kChunk, bf16x2_rne(v[j][0], v[j][1])); + stg_u32(obr + base + j * kChunk + 2u, bf16x2_rne(v[j][2], v[j][3])); + } + } + } +} + +/* ================================================================== softmax + * In f32: + * + * mx = max_i x[i] + * e = exp(x[i] - mx); y[i] = e; sum += e ascending + * inv = 1 / sum; y[i] = y[i] * inv read back from y + * + * The maximum is subtracted first (a 60-nat row overflows f32's exp otherwise); the denominator is + * the ascending sum, which is what `block_sum` brackets. The kernel keeps `e` in a register + * between the two passes, which is exact: ref reads it back from an f32 plane, and an f32 store + * and load round nothing. The shim therefore requires y to be f32 -- a bf16 y would round `e` + * before the multiply and ref would not, and libref itself casts f32 to f32 for this op. + */ +template +__global__ __launch_bounds__(THR) void softmax_kernel( + const float* __restrict__ x, float* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) { + __shared__ float lds[THR / kWave]; + const uint32_t m = blockIdx.x; + const float* __restrict__ xr = x + (size_t)m * x_ld; + float* __restrict__ yr = y + (size_t)m * y_ld; + + float mx = -INFINITY; + for (uint32_t i = threadIdx.x; i < n; i += THR) mx = fmaxf(mx, ldg_f32(xr + i)); + mx = block_max(mx, lds); + + float sum = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float e = expf(ldg_f32(xr + i) - mx); + sum += e; + stg_f32(yr + i, e); + } + const float inv = 1.0f / block_sum(sum, lds); + for (uint32_t i = threadIdx.x; i < n; i += THR) stg_f32(yr + i, ldg_f32(yr + i) * inv); +} + +/* ================================================================== scale / fill + * scale is y = x * s, s one scalar; fill is y = v over the whole + * plane, and both narrow once, at the store. + * + * scale's scalar is the op's [1] weight plane, in device memory, and the kernel reads it: a launch + * may not copy device memory to the host, and ref reads the same single value because its operands + * are host planes. Every lane loads the same address, so it is one uniform load per block; the + * product is taken in f32 and the store narrows, which is ref's `x * s` with round_dt(f32) as the + * store. + */ +template +__global__ __launch_bounds__(THR) void scale_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ sp, uint16_t* __restrict__ y, + uint32_t n, int s_dt, uint32_t x_ld, uint32_t y_ld) { + typedef typename std::conditional::type T; + const uint32_t m = blockIdx.x; + const T* __restrict__ xr = (const T*)x + (size_t)m * x_ld; + T* __restrict__ yr = (T*)y + (size_t)m * y_ld; + const float v = s_dt == R3D_DT_F32 ? ldg_f32((const float*)sp) + : bf16_to_f32(ldg_u16((const uint16_t*)sp)); + const auto ld = [](const T* p, uint32_t i) { + return F32 ? ldg_f32((const float*)p + i) : bf16_to_f32(ldg_u16_at((const uint16_t*)p, i)); + }; + if (PAIR) { + for (uint32_t i = 2u * threadIdx.x; i < n; i += 2u * THR) + stg_u32((uint16_t*)yr + i, bf16x2_rne(ld(xr, i) * v, ld(xr, i + 1) * v)); + } else { + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float r = ld(xr, i) * v; + if (F32) stg_f32((float*)yr + i, r); + else ((uint16_t*)yr)[i] = f32_to_bf16(r); + } + } +} + +template +__global__ __launch_bounds__(THR) void fill_kernel(void* __restrict__ y, uint32_t n, uint32_t y_ld, + int dt, float v) { + const uint32_t m = blockIdx.x; + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)dt_bytes(dt); + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, v); +} + +/* ================================================================== rope + * rope_freqs, rope_head, ref_rope -- in place on the fused qkv row, q heads + * then k heads then v untouched: + * + * inv[i] = 1 / pow(theta, (2i)/rot) the ladder, den == rot + * ang = (pos[m] / scale) * inv[i] + * c, s = cos(ang), sin(ang) + * i0, i1 = (i, i + rot/2) neox, (2i, 2i + 1) gptj + * h[i0] = x0*c - x1*s ; h[i1] = x0*s + x1*c each narrowed once + * + * The pair lives in one thread, so the in-place store needs no exchange. `scale` is the position + * scale and divides the position, as ref's rope_pos does (the value that multiplies the rotated + * pair is YaRN's magnitude, and the shims refuse YaRN, so the magnitude is 1). + * + * The frequency is recomputed per pair, not built in a plane: powf runs once per pair per head, + * off the step's critical path, and no scratch is allocated. nfreq == rot/2 always, so no pair + * sits past the ladder (ref zeroes inv[] past nfreq for the proportional ladder it supports and + * libr3d refuses). + */ +template +__global__ __launch_bounds__(THR) void rope_kernel( + uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t head_dim, + uint32_t n_rope_heads, uint32_t rot, float theta, float scale, uint32_t row_pitch) { + const uint32_t m = blockIdx.x; + const float div = scale != 0.0f ? scale : 1.0f; + const float p = (float)ldg_i32(pos + m) / div; + const uint32_t half = rot / 2; + const uint32_t total = n_rope_heads * half; + uint16_t* __restrict__ row = qkv + (size_t)m * row_pitch; + + for (uint32_t j = threadIdx.x; j < total; j += THR) { + const uint32_t h = j / half, i = j - h * half; + /* ref's ladder: `1.0f / ref_pow(theta, (float)(2i) / den)`, and ref_pow is the double pow + * narrowed once. powf here would put the reciprocal a ULP off, and at position 262144 a + * ULP of a frequency is a hundredth of a radian of rotation -- the ladder is the one place + * in this kernel where f32 is not enough. The angle itself stays f32, as ref's is. */ + const float inv = 1.0f / (float)std::pow((double)theta, (double)((float)(2 * i) / (float)rot)); + float s, c; + sincosf(p * inv, &s, &c); + const uint32_t i0 = h * head_dim + (GPTJ ? 2u * i : i); + const uint32_t i1 = h * head_dim + (GPTJ ? 2u * i + 1u : i + half); + const float x0 = bf16_to_f32(ldg_u16_at(row, i0)); + const float x1 = bf16_to_f32(ldg_u16_at(row, i1)); + ((uint16_t*)row)[i0] = f32_to_bf16(x0 * c - x1 * s); + ((uint16_t*)row)[i1] = f32_to_bf16(x0 * s + x1 * c); + } +} + +/* ================================================================== kv_store + * With the cache's strides read off the operand (kv_view): + * + * s = slot[t]; if (s < 0) skip; a padded row has no cache slot + * h, d = the kv head and the element; j = h*head_dim + d + * base = (s/block)*sb + h*sh + (s%block)*so + * cache[base + d*sd] = k[t*k_ld + j] * k_inv + * cache[base + (hd + d)*sd] = v[t*v_ld + j] * v_inv + * + * k and v rows are not dense: a de-interleaved projection gives [tokens, kv_heads, head_dim], and + * otherwise they are a column slice of the fused QKV plane -- 2560 wide against a 256-wide row for + * 16 heads and 2 kv heads. Deriving the stride from the shape would read every token after the + * first from the wrong rows, so the pitch is an argument. + * + * k_inv and v_inv are the reciprocal of the reader's descales and are 1 for every cache that is + * not fp8, so the multiply below is exact -- and for the fp8 cache it is the divide ref does, in + * the one place where a reciprocal costs nothing: a value times 1/scale against ref's + * `ldt(k,..) * ks` differs by at most the rounding of the reciprocal, far under the fp8 code step. + */ +template +__global__ __launch_bounds__(THR) void kv_store_kernel( + const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, const int32_t* __restrict__ sm, + void* __restrict__ kv, uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, int kv_dt, + float k_inv, float v_inv, uint32_t k_ld, uint32_t v_ld, int64_t sb, int64_t sh, int64_t so, + int64_t sd, int64_t slot_max) { + const uint32_t t = blockIdx.x; + const int32_t s = ldg_i32(sm + t); + /* A negative slot is padding and a slot at or past the cache's own span names a block the + * cache does not have: ref refuses such a launch on the host, where it can see the block + * count, and a kernel that has read the slot can only drop it. A slot lost, not a step lost. */ + if (s < 0 || (int64_t)s >= slot_max) return; + const int64_t blk = (int64_t)s / (int64_t)block_size, off = (int64_t)s % (int64_t)block_size; + + const uint32_t total = kv_heads * head_dim; + const uint16_t* __restrict__ kr = k + (size_t)t * k_ld; + const uint16_t* __restrict__ vr = v + (size_t)t * v_ld; + const int es = kv_dt == R3D_DT_BF16 ? 2 : kv_dt == R3D_DT_F16 ? 2 : 1; + char* __restrict__ plane = (char*)kv; + + for (uint32_t j = threadIdx.x; j < total; j += THR) { + const uint32_t h = j / head_dim, d = j - h * head_dim; + const int64_t cb = (blk * sb + (int64_t)h * sh + off * so) * es; + st_elem(kv_dt, plane + cb, (size_t)d * sd, bf16_to_f32(ldg_u16_at(kr, j)) * k_inv); + st_elem(kv_dt, plane + cb, (size_t)(head_dim + d) * sd, + bf16_to_f32(ldg_u16_at(vr, j)) * v_inv); + } +} + +/* ================================================================== embed_lookup + * embed_gather: + * + * id = tok[m] - vocab_offset + * x[m][i] = (0 <= id < n_vocab) ? wte[id*w_ld + i] * wscale * mult : 0 + * + * A negative id, or one at or past the table, is a zero row: padding's row, and in the + * vocab-parallel split another rank's token -- summing the ranks reconstructs x. ref validates the + * ids on the host when the table is whole and the world is one rank; a kernel cannot, so the table + * bound is an argument and an out-of-range id writes zeros. + * + * The table's dtype is the launcher's `dt`: bf16, f16, f32, or E4M3 codes with the table's one + * scale in `wscale` (embed_lookup_q's byte plane, whose scale is a parameter because quantising + * the table sees the whole table and the gather sees one row). `mult` is Gemma's sqrt(hidden), + * applied after the scale, so with wscale 1 the product is ref's single rounding. + */ +template +__global__ __launch_bounds__(THR) void embed_lookup_kernel( + const int32_t* __restrict__ ids, const void* __restrict__ wte, void* __restrict__ x, + uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, float wscale, float mult, uint32_t x_ld, + int64_t w_ld, int dt, int pair) { + const uint32_t m = blockIdx.x; + const int32_t id = ldg_i32(ids + m) - vocab_off; + char* __restrict__ xr = (char*)x + (size_t)m * x_ld * (size_t)dt_bytes(dt); + + if (id < 0 || id >= n_vocab) { + for (uint32_t i = threadIdx.x; i < n_embd; i += THR) st_elem(dt, xr, i, 0.0f); + return; + } + const char* __restrict__ wr = (const char*)wte + (int64_t)id * w_ld * (int64_t)dt_bytes(dt); + if (pair) { + uint16_t* __restrict__ xp = (uint16_t*)xr; + for (uint32_t i = 2u * threadIdx.x; i < n_embd; i += 2u * THR) + stg_u32(xp + i, bf16x2_rne(ld_elem(dt, wr, i) * wscale * mult, + ld_elem(dt, wr, i + 1) * wscale * mult)); + } else { + for (uint32_t i = threadIdx.x; i < n_embd; i += THR) + st_elem(dt, xr, i, ld_elem(dt, wr, i) * wscale * mult); + } +} + +/* ================================================================== gather_rows / scatter_rows + * y[r] = x[idx[r]] and x[idx[r]] = v[r], rows of n, and a row move + * with no arithmetic: ld_elem/st_elem is the identity for bf16, f16, f32, i32 and i64, and the + * fp8 code round trip is exact (every code decodes and re-encodes to itself). + * + * A negative index is padding: gather writes a zero row, scatter writes nothing -- an unsampled row + * of a step, a slot with no counterpart. An index at or past the operand's row count takes the + * same path, where ref refuses the launch (see the file header). + * + * scatter_rows' destination is INOUT and the write is partial: unnamed rows keep their contents, + * because the destination is often a pool other sequences are in. Its indices must be distinct -- + * RAD_OPD_F_IDX_UNIQUE says so in the schema -- since two rows landing on one destination have no + * defined winner in parallel, and an op whose oracle and kernel may disagree is not checkable. + */ +template +__global__ __launch_bounds__(THR) void gather_rows_kernel( + const void* __restrict__ x, const int32_t* __restrict__ idx, void* __restrict__ y, uint32_t n, + uint32_t x_ld, uint32_t y_ld, int dt, int32_t es, int64_t src_rows) { + const uint32_t m = blockIdx.x; + const int32_t r = ldg_i32(idx + m); + char* __restrict__ yr = (char*)y + (size_t)m * y_ld * (size_t)es; + /* A negative index is padding and an index at or past the source plane is one libref refuses on + * the host, where it can read the plane. Both take the zero row: reading x past its end is the + * failure this bound exists to stop. `src_rows` 0 says the caller had no plane count, which is a + * shim bug, not a bound. */ + if (r < 0 || (src_rows > 0 && (int64_t)r >= src_rows)) { + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, 0.0f); + return; + } + const char* __restrict__ xr = (const char*)x + (size_t)r * x_ld * (size_t)es; + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, yr, i, ld_elem(dt, xr, i)); +} + +template +__global__ __launch_bounds__(THR) void scatter_rows_kernel( + const void* __restrict__ v, const int32_t* __restrict__ idx, void* __restrict__ x, uint32_t n, + uint32_t v_ld, uint32_t x_ld, int dt, int32_t es, int64_t dst_rows) { + const uint32_t m = blockIdx.x; + const int32_t r = ldg_i32(idx + m); + /* A negative index is padding, one at or past the destination plane is libref's refused step: + * dropped, so no row of x is written outside the plane. `dst_rows` 0 is unchecked. */ + if (r < 0 || (dst_rows > 0 && (int64_t)r >= dst_rows)) return; + const char* __restrict__ vr = (const char*)v + (size_t)m * v_ld * (size_t)es; + char* __restrict__ xr = (char*)x + (size_t)r * x_ld * (size_t)es; + for (uint32_t i = threadIdx.x; i < n; i += THR) st_elem(dt, xr, i, ld_elem(dt, vr, i)); +} + +} /* namespace */ + +/* ================================================================== the launchers + * + * Pointers as longs, geometry as ints, the stream as a long. Each checks what a `__global__` + * cannot -- nulls, non-positive extents, a pitch that does not describe the operand -- takes the + * thread count from the row width, decides the pair layout from the pitches and the base + * alignments, and issues one kernel on the stream it was handed. A pitch of 0 means "dense, so n". + */ + +/* The pair layout: a lane owning two consecutive columns, its result stored as one dword. Legal + * when n, both pitches and the base are even, so every element of every row lands on an even + * element index -- 4-byte alignment at 2 bytes an element. */ +static inline int row_pair(long base, int n, int ld1, int ld2) { + return ((n & 1) == 0) && ((ld1 & 1) == 0) && ((ld2 & 1) == 0) && ((base & 3) == 0); +} + +/* One grid, one launch, per launcher: `grid` is the row count (blockIdx.x is the row), and the + * two thread counts are the template arguments the grid was sized for. */ +#define R3D_ROW2(kernel, thr, grid, stream, ...) \ + do { \ + if ((thr) == (int)kNarrow) \ + R3D_KLAUNCH(R3D_KNAME(kernel), dim3((uint32_t)(grid)), dim3(kNarrow), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__); \ + else \ + R3D_KLAUNCH(R3D_KNAME(kernel), dim3((uint32_t)(grid)), dim3(kThreads), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__); \ + } while (0) + +#define R3D_ROPE2(thr, grid, stream, ...) \ + do { \ + if ((thr) == (int)kNarrow) { \ + if (gptj) R3D_ROPE_K(kNarrow, 1, grid, stream, __VA_ARGS__); \ + else R3D_ROPE_K(kNarrow, 0, grid, stream, __VA_ARGS__); \ + } else { \ + if (gptj) R3D_ROPE_K(kThreads, 1, grid, stream, __VA_ARGS__); \ + else R3D_ROPE_K(kThreads, 0, grid, stream, __VA_ARGS__); \ + } \ + } while (0) + +#define R3D_ROPE_K(THR, GPTJ, grid, stream, ...) \ + R3D_KLAUNCH(R3D_KNAME(rope_kernel), dim3((uint32_t)(grid)), dim3(THR), \ + (hipStream_t)(uintptr_t)(stream), __VA_ARGS__) + +/* A row count a dim3 can carry and a grid-strided loop cannot be asked to exceed. */ +static inline int row_count_ok(long long M) { return M > 0 && M <= 0x7fffffffLL; } + +static int rmsnorm_launch(long x, long w, long y, int M, int n, float eps, float wadd, float mult, + int x_ld, int y_ld, int wdt, int f32, long stream) { + if (!x || !y || (wdt != R3D_DT_N && !w)) return -1; + if (M <= 0 || n <= 0) return -2; + if (wdt != R3D_DT_N && wdt != R3D_DT_BF16 && wdt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); + const uint16_t* xp = (const uint16_t*)(uintptr_t)x; + uint16_t* yp = (uint16_t*)(uintptr_t)y; + const void* wp = (const void*)(uintptr_t)w; +#define R3D_RMS(THR, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, xp, wp, yp, (uint32_t)n, eps, wadd, mult, \ + (uint32_t)x_ld, (uint32_t)y_ld, pair) + if (wdt == R3D_DT_F32) { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_F32); else R3D_RMS(kThreads, R3D_DT_F32); + } else if (wdt == R3D_DT_BF16) { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_BF16); else R3D_RMS(kThreads, R3D_DT_BF16); + } else { + if (thr == (int)kNarrow) R3D_RMS(kNarrow, R3D_DT_N); else R3D_RMS(kThreads, R3D_DT_N); + } +#undef R3D_RMS + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The f32 leg: the same two passes over an f32 row, and a store that narrows nothing. */ +extern "C" 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) { + if (!x || !y || (wdt != R3D_DT_N && !w)) return -1; + if (M <= 0 || n <= 0) return -2; + if (wdt != R3D_DT_N && wdt != R3D_DT_BF16 && wdt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; +#define R3D_RMSF(THR, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (const void*)(uintptr_t)w, (uint16_t*)(uintptr_t)y, (uint32_t)n, eps, wadd, \ + mult, (uint32_t)x_ld, (uint32_t)y_ld, 0) + if (row_threads(n) == (int)kNarrow) { + if (wdt == R3D_DT_F32) R3D_RMSF(kNarrow, R3D_DT_F32); + else if (wdt == R3D_DT_BF16) R3D_RMSF(kNarrow, R3D_DT_BF16); + else R3D_RMSF(kNarrow, R3D_DT_N); + } else { + if (wdt == R3D_DT_F32) R3D_RMSF(kThreads, R3D_DT_F32); + else if (wdt == R3D_DT_BF16) R3D_RMSF(kThreads, R3D_DT_BF16); + else R3D_RMSF(kThreads, R3D_DT_N); + } +#undef R3D_RMSF + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The bf16 entry point, in terms of the same body. */ +extern "C" 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) { + return rmsnorm_launch(x, w, y, M, n, eps, wadd, mult, x_ld, y_ld, wdt, 0, stream); +} + +/* The fused add + norm + E4M3 quantiser. `res` is the residual plane, INOUT, and 0 when the op has + * no residual; `ob` is the optional bf16 copy of exactly what was quantised. `group` is the + * quantiser's block and must divide n: a partial group needs the zero-padded store the standalone + * quantiser writes, and this row's band is a checkpoint whose block divides its hidden width. + * Pitches are in elements of their own operand; `s_ld` in scales, so a dense scale plane is n/group. + * 0, -1, -2, -3, -4. */ +extern "C" 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) { + if (!x || !w || !q || !s) return -1; + if (M <= 0 || n <= 0) return -2; + if (group != 128 && group != 256 && group != 512) return -2; + if (n % group) return -2; + if (!x_ld) x_ld = n; + if (!res_ld) res_ld = n; + if (!ob_ld) ob_ld = n; + if (!q_ld) q_ld = n; + if (!s_ld) s_ld = n / group; + if (x_ld < n || res_ld < n || ob_ld < n || q_ld < n || s_ld < n / group) return -3; + const int thr = row_threads(n); +#define R3D_RQ(THR, GROUP, WDT) \ + R3D_KLAUNCH(R3D_KNAME(rmsnorm_quant_fp8_kernel), dim3((uint32_t)M), \ + dim3(THR), (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (uint16_t*)(uintptr_t)res, (const void*)(uintptr_t)w, \ + (uint8_t*)(uintptr_t)q, (float*)(uintptr_t)s, (uint16_t*)(uintptr_t)ob, \ + (uint32_t)n, eps, wadd, (uint32_t)x_ld, (uint32_t)res_ld, (uint32_t)ob_ld, \ + (uint32_t)q_ld, (uint32_t)s_ld) +#define R3D_RQ_G(THR, WDT) \ + do { \ + if (group == 128) R3D_RQ(THR, 128, WDT); \ + else if (group == 256) R3D_RQ(THR, 256, WDT); \ + else R3D_RQ(THR, 512, WDT); \ + } while (0) +#define R3D_RQ_W(THR) \ + do { \ + if (wdt == R3D_DT_F32) R3D_RQ_G(THR, R3D_DT_F32); \ + else R3D_RQ_G(THR, R3D_DT_BF16); \ + } while (0) + if (thr == (int)kNarrow) R3D_RQ_W(kNarrow); else R3D_RQ_W(kThreads); +#undef R3D_RQ_W +#undef R3D_RQ_G +#undef R3D_RQ + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + if (!x || !w || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, x_ld, y_ld); + R3D_ROW2(layernorm_kernel, thr, M, stream, (const uint16_t*)(uintptr_t)x, + (const uint16_t*)(uintptr_t)w, (const uint16_t*)(uintptr_t)b, + (uint16_t*)(uintptr_t)y, (uint32_t)n, eps, (uint32_t)x_ld, (uint32_t)y_ld, pair); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The binary pair: one kernel over add/mul, bf16/f32 and the pair layout, with the broadcast + * expressed as b's row pitch (0 makes one row ride every row). */ +static int binary_launch(long a, long b, long y, int M, int n, int a_ld, int b_ld, int y_ld, + float div, int bcast, int mul, int f32, long stream) { + if (!a || !b || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!(div != 0.0f) || !std::isfinite(div)) return -2; + if (!a_ld) a_ld = n; + if (!y_ld) y_ld = n; + if (!bcast) { + if (!b_ld) b_ld = n; + } else { + b_ld = 0; + } + if (a_ld < n || y_ld < n || (!bcast && b_ld < n)) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, a_ld, y_ld) && (bcast || (b_ld & 1) == 0); +#define R3D_BIN(THR, MUL, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(binary_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)a, \ + (const uint16_t*)(uintptr_t)b, (uint16_t*)(uintptr_t)y, (uint32_t)n, \ + (uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, div) +#define R3D_BIN_M(THR) \ + do { \ + if (mul) { if (pair) R3D_BIN(THR, 1, 1, 0); else R3D_BIN(THR, 1, 0, 0); } \ + else { if (pair) R3D_BIN(THR, 0, 1, 0); else R3D_BIN(THR, 0, 0, 0); } \ + } while (0) +#define R3D_BIN_MF(THR) \ + do { \ + if (mul) R3D_BIN(THR, 1, 0, 1); else R3D_BIN(THR, 0, 0, 1); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_BIN_MF(kNarrow); else R3D_BIN_MF(kThreads); } + else { if (thr == (int)kNarrow) R3D_BIN_M(kNarrow); else R3D_BIN_M(kThreads); } +#undef R3D_BIN_MF +#undef R3D_BIN_M +#undef R3D_BIN + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, div, bcast, 0, 0, stream); +} + +extern "C" 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) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, div, bcast, 0, 1, stream); +} + +extern "C" 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) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, 1.0f, bcast, 1, 0, stream); +} + +extern "C" 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) { + return binary_launch(a, b, y, M, n, a_ld, b_ld, y_ld, 1.0f, bcast, 1, 1, stream); +} + +/* The cast's dtype codes: every pair of the dtypes the library moves. The shim translates the + * tensor dtypes with r3d_dt_code and checks them here, so a call from a tool with an unlisted + * pair is refused rather than run over a switch's default. */ +static int cast_pair_ok(int from, int to) { + static const int kOk[] = { R3D_DT_BF16, R3D_DT_F16, R3D_DT_F32, R3D_DT_I32, R3D_DT_I64, + R3D_DT_U8, R3D_DT_I8 }; + int okf = 0, okt = 0; + for (int i = 0; i < (int)(sizeof kOk / sizeof kOk[0]); ++i) { + okf = okf || from == kOk[i]; + okt = okt || to == kOk[i]; + } + return okf && okt; +} + +extern "C" 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) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!cast_pair_ok(from_dt, to_dt)) return -2; + const int fs = r3d_dt_size(from_dt), ts = r3d_dt_size(to_dt); + if (!fs || !ts) return -2; + /* The pitches are in elements of each operand's own dtype; 0 is dense. */ + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(cast_kernel, thr, M, stream, (const void*)(uintptr_t)x, (void*)(uintptr_t)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld, from_dt, to_dt, + int_pair(from_dt) && int_pair(to_dt) ? 1 : 0); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The unary activations: one launcher body, four template arguments. */ +static int unary_launch(long x, long y, int M, int n, int x_ld, int y_ld, int act, int f32, + long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); +#define R3D_UN(THR, ACT, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(unary_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (uint16_t*)(uintptr_t)y, (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld) +#define R3D_UN_A(THR) \ + do { \ + if (act == R3D_ACT_SILU) { if (pair) R3D_UN(THR, R3D_ACT_SILU, 1, 0); \ + else R3D_UN(THR, R3D_ACT_SILU, 0, 0); } \ + else if (act == R3D_ACT_GELU) { if (pair) R3D_UN(THR, R3D_ACT_GELU, 1, 0); \ + else R3D_UN(THR, R3D_ACT_GELU, 0, 0); } \ + else { if (pair) R3D_UN(THR, R3D_ACT_SIGMOID, 1, 0); \ + else R3D_UN(THR, R3D_ACT_SIGMOID, 0, 0); } \ + } while (0) +#define R3D_UN_AF(THR) \ + do { \ + if (act == R3D_ACT_SILU) R3D_UN(THR, R3D_ACT_SILU, 0, 1); \ + else if (act == R3D_ACT_GELU) R3D_UN(THR, R3D_ACT_GELU, 0, 1); \ + else R3D_UN(THR, R3D_ACT_SIGMOID, 0, 1); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_UN_AF(kNarrow); else R3D_UN_AF(kThreads); } + else { if (thr == (int)kNarrow) R3D_UN_A(kNarrow); else R3D_UN_A(kThreads); } +#undef R3D_UN_AF +#undef R3D_UN_A +#undef R3D_UN + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_silu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SILU, 0, stream); +} + +extern "C" int r3d_gelu_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_GELU, 0, stream); +} + +extern "C" int r3d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SIGMOID, 0, stream); +} + +extern "C" int r3d_silu_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + return unary_launch(x, y, M, n, x_ld, y_ld, R3D_ACT_SILU, 1, stream); +} + +extern "C" 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) { + if (!gate || !up || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (act != R3D_ACT_SILU && act != R3D_ACT_GELU && act != R3D_ACT_SIGMOID) return -2; + if (!g_ld) g_ld = n; + if (!u_ld) u_ld = n; + if (!y_ld) y_ld = n; + if (g_ld < n || u_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, g_ld, y_ld) && (u_ld & 1) == 0; +#define R3D_AM(THR, ACT, PAIR) \ + R3D_KLAUNCH(R3D_KNAME(act_mul_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate, \ + (const uint16_t*)(uintptr_t)up, (uint16_t*)(uintptr_t)y, (uint32_t)n, \ + (uint32_t)g_ld, (uint32_t)u_ld, (uint32_t)y_ld) +#define R3D_AM_A(THR) \ + do { \ + if (act == R3D_ACT_SILU) { if (pair) R3D_AM(THR, R3D_ACT_SILU, 1); \ + else R3D_AM(THR, R3D_ACT_SILU, 0); } \ + else if (act == R3D_ACT_GELU) { if (pair) R3D_AM(THR, R3D_ACT_GELU, 1); \ + else R3D_AM(THR, R3D_ACT_GELU, 0); } \ + else { if (pair) R3D_AM(THR, R3D_ACT_SIGMOID, 1); \ + else R3D_AM(THR, R3D_ACT_SIGMOID, 0); } \ + } while (0) + if (thr == (int)kNarrow) R3D_AM_A(kNarrow); else R3D_AM_A(kThreads); +#undef R3D_AM_A +#undef R3D_AM + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* y = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate and the up share one plane, so one pitch + * carries both halves: `gu_ld` is the FUSED row's pitch (>= 2n), `y_ld` the output's. */ +extern "C" int r3d_silu_mul_bf16(long gate_up, long y, int M, int n, int gu_ld, int y_ld, + long stream) { + if (!gate_up || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!gu_ld) gu_ld = 2 * n; + if (!y_ld) y_ld = n; + if (gu_ld < 2 * n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = row_pair(y, n, gu_ld, y_ld); /* n even puts the up half on a 2-byte boundary */ +#define R3D_SM(THR, PAIR) \ + R3D_KLAUNCH(R3D_KNAME(silu_mul_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)gate_up, \ + (uint16_t*)(uintptr_t)y, (uint32_t)n, (uint32_t)gu_ld, (uint32_t)y_ld) + if (pair) { + if (thr == (int)kNarrow) R3D_SM(kNarrow, 1); else R3D_SM(kThreads, 1); + } else { + if (thr == (int)kNarrow) R3D_SM(kNarrow, 0); else R3D_SM(kThreads, 0); + } +#undef R3D_SM + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_softmax_f32(long x, long y, int M, int n, int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(softmax_kernel, thr, M, stream, (const float*)(uintptr_t)x, (float*)(uintptr_t)y, + (uint32_t)n, (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* scale's two legs: the scalar plane's dtype is `s_dt` (bf16 or f32), the row's dtype is the + * launcher's. A null `s` is -1: the shim refuses a scale with no plane, so a call that reaches + * here without one is a caller bug, not a scale of zero. */ +static int scale_launch(long x, long s, long y, int M, int n, int s_dt, int x_ld, int y_ld, int f32, + long stream) { + if (!x || !s || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (s_dt != R3D_DT_BF16 && s_dt != R3D_DT_F32) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + const int thr = row_threads(n); + const int pair = f32 ? 0 : row_pair(y, n, x_ld, y_ld); +#define R3D_SC(THR, PAIR, F32) \ + R3D_KLAUNCH(R3D_KNAME(scale_kernel), dim3((uint32_t)M), dim3(THR), \ + (hipStream_t)(uintptr_t)stream, (const uint16_t*)(uintptr_t)x, \ + (const void*)(uintptr_t)s, (uint16_t*)(uintptr_t)y, (uint32_t)n, s_dt, \ + (uint32_t)x_ld, (uint32_t)y_ld) +#define R3D_SC_P(THR, F32) \ + do { \ + if (pair) R3D_SC(THR, 1, F32); else R3D_SC(THR, 0, F32); \ + } while (0) + if (f32) { if (thr == (int)kNarrow) R3D_SC_P(kNarrow, 1); else R3D_SC_P(kThreads, 1); } + else { if (thr == (int)kNarrow) R3D_SC_P(kNarrow, 0); else R3D_SC_P(kThreads, 0); } +#undef R3D_SC_P +#undef R3D_SC + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + return scale_launch(x, s, y, M, n, s_dt, x_ld, y_ld, 0, stream); +} + +extern "C" 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) { + return scale_launch(x, s, y, M, n, s_dt, x_ld, y_ld, 1, stream); +} + +extern "C" int r3d_fill(long y, int M, int n, int y_ld, int dt, float v, long stream) { + if (!y) return -1; + if (M <= 0 || n <= 0) return -2; + if (r3d_dt_size(dt) == 0) return -2; + if (!y_ld) y_ld = n; + if (y_ld < n) return -3; + const int thr = row_threads(n); + R3D_ROW2(fill_kernel, thr, M, stream, (void*)(uintptr_t)y, (uint32_t)n, (uint32_t)y_ld, dt, v); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + if (!qkv || !pos) return -1; + if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv < 0) return -2; + if (rot <= 0) rot = head_dim; + if (rot > head_dim || (rot & 1)) return -3; + if (mode != R3D_ROPE_NEOX && mode != R3D_ROPE_GPTJ) return -3; + if (head_dim & 1) return -3; // the two halves of a head, evenly split + if (!(theta > 0.0f) || !std::isfinite(theta)) return -2; + if (!qkv_ld) qkv_ld = (n_head + 2 * n_head_kv) * head_dim; + if (qkv_ld < (n_head + 2 * n_head_kv) * head_dim) return -3; + /* rope is a per-head-of-64-pairs op: one wave covers a token's rope heads when the head is + * narrow, and 256 threads take the wide ones. */ + const int gptj = mode == R3D_ROPE_GPTJ; + const int thr = (n_head + n_head_kv) * (rot / 2) <= 256u ? (int)kNarrow : (int)kThreads; + R3D_ROPE2(thr, M, stream, (uint16_t*)(uintptr_t)qkv, (const int32_t*)(uintptr_t)pos, + (uint32_t)head_dim, (uint32_t)(n_head + n_head_kv), (uint32_t)rot, theta, scale, + (uint32_t)qkv_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + if (!k || !v || !sm || !kv) return -1; + if (M <= 0 || head_dim <= 0 || n_head_kv <= 0 || block_size <= 0) return -2; + if (kv_dt != R3D_DT_BF16 && kv_dt != R3D_DT_F16 && kv_dt != R3D_DT_U8) return -2; + const int fp8 = kv_dt == R3D_DT_U8; + if (fp8 && !(k_scale > 0.0f && v_scale > 0.0f)) return -2; + const float k_inv = fp8 ? 1.0f / k_scale : 1.0f; + const float v_inv = fp8 ? 1.0f / v_scale : 1.0f; + if (!k_ld) k_ld = n_head_kv * head_dim; + if (!v_ld) v_ld = n_head_kv * head_dim; + if (k_ld < n_head_kv * head_dim || v_ld < n_head_kv * head_dim) return -3; + if (sb < 0 || sh < 0 || so < 0 || sd <= 0) return -3; + /* The cache's span, as r3d_shape_kv_store sizes it: M tokens need ceil(M/block_size) blocks, + * and the shape adds two so a step that resolves its slots before the next block is written + * has somewhere to put them. Keep the two formulas in step. */ + if (slot_max <= 0) + slot_max = (long long)((M + block_size - 1) / block_size + 2) * block_size; + const int thr = row_threads(n_head_kv * head_dim); + R3D_ROW2(kv_store_kernel, thr, M, stream, (const uint16_t*)(uintptr_t)k, + (const uint16_t*)(uintptr_t)v, (const int32_t*)(uintptr_t)sm, (void*)(uintptr_t)kv, + (uint32_t)head_dim, (uint32_t)n_head_kv, (uint32_t)block_size, kv_dt, k_inv, v_inv, + (uint32_t)k_ld, (uint32_t)v_ld, (int64_t)sb, (int64_t)sh, (int64_t)so, (int64_t)sd, + (int64_t)slot_max); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + if (!ids || !wte || !x) return -1; + if (M <= 0 || n_embd <= 0 || n_vocab <= 0) return -2; + if (dt != R3D_DT_BF16 && dt != R3D_DT_F16 && dt != R3D_DT_F32 && dt != R3D_DT_U8) return -2; + if (!x_ld) x_ld = n_embd; + if (!w_ld) w_ld = n_embd; + if (x_ld < n_embd || w_ld < n_embd) return -3; + const int thr = row_threads(n_embd); + const int pair = (dt == R3D_DT_BF16) ? row_pair(x, n_embd, x_ld, x_ld) : 0; + R3D_ROW2(embed_lookup_kernel, thr, M, stream, (const int32_t*)(uintptr_t)ids, + (const void*)(uintptr_t)wte, (void*)(uintptr_t)x, (uint32_t)n_embd, (int32_t)n_vocab, + (int32_t)vocab_offset, wscale, mult, (uint32_t)x_ld, (int64_t)w_ld, dt, pair); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The row moves: the pitch is in elements and the element size in bytes, both off the dtype, so + * the kernel's row base is one multiply. */ +extern "C" 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) { + if (!x || !idx || !y) return -1; + if (M <= 0 || n <= 0) return -2; + const int es = r3d_dt_size(dt); + if (!es) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + if (x_ld < n || y_ld < n) return -3; + R3D_ROW2(gather_rows_kernel, row_threads(n), M, stream, (const void*)(uintptr_t)x, + (const int32_t*)(uintptr_t)idx, (void*)(uintptr_t)y, (uint32_t)n, (uint32_t)x_ld, + (uint32_t)y_ld, dt, es, (int64_t)src_rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" 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) { + if (!v || !idx || !x) return -1; + if (M <= 0 || n <= 0) return -2; + const int es = r3d_dt_size(dt); + if (!es) return -2; + if (!v_ld) v_ld = n; + if (!x_ld) x_ld = n; + if (v_ld < n || x_ld < n) return -3; + R3D_ROW2(scatter_rows_kernel, row_threads(n), M, stream, (const void*)(uintptr_t)v, + (const int32_t*)(uintptr_t)idx, (void*)(uintptr_t)x, (uint32_t)n, (uint32_t)v_ld, + (uint32_t)x_ld, dt, es, (int64_t)dst_rows); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the plugin ABI entry points + * + * Unpacking RadArgs and deriving the pitches belongs to the kernel library (r3d_args.h). The + * kernels take raw pointers and one pitch per operand, so anything unpitched must be tight + * (spec §2.1). Before each launch a shim checks: + * + * * the dtype, off the operand: a row's `dtype` constraint is a necessary condition on the + * geometry, not a promise about the tensors, and an f32 operand read as bf16 is a value the + * geometry checks will not catch; + * * the row pitch, r3d_rows_pitch(): elements, or -1 (RAD_E_STRIDE) for a strided inner axis; + * * the row count, off the operand, never the `M` parameter: `M` is ranged, so the args carry + * the band's upper bound; + * * the parameters, with libref's defaults, and the forms the kernels cannot match -- refused + * with RAD_E_UNSUPPORTED so the row's constraints can state the band and a model that needs + * the refused form is not routed here at all. + * + * Every refusal goes through R3D_NO(), so a run with RAD_R3D_TRACE set says which line said no. + */ + +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; } +static inline int dt_i32(const RadTensor* t) { return r3d_is_i32(t) ? RAD_OK : RAD_E_DTYPE; } + +/* A bf16-or-f32 pair, so the two dtype legs of add/mul read as one test. */ +static inline int dt_same(const RadTensor* a, const RadTensor* b) { + return a && b && a->dtype == b->dtype ? 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's return: 0 is RAD_OK, anything else is a device failure -- the arguments were the + * shim's to check, and it checked them. */ +static inline int r3d_launch_ok(int rc) { return rc == 0 ? RAD_OK : R3D_NO(RAD_E_DEVICE); } + +/* ------------------------------------------------------------------ rmsnorm */ + +enum { RMS_X = 0, RMS_W, RMS_Y }; + +extern "C" int r3d_rad_rmsnorm(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, RMS_X); + const RadTensor* w = r3d_opt(a, RMS_W); + const RadTensor* y = r3d_opt(a, RMS_Y); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + /* The row's dtype band is bf16 or f32, and the two legs are the same two passes: an f32 + * checkpoint's residual stream normalizes without a store that narrows. */ + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + + const float wadd = (float)r3d_getf(a, "wadd", 0.0); + const float mult = (float)r3d_getf(a, "mult", 1.0); + const float eps = (float)r3d_getf(a, "eps", 1e-6); + /* `wadd` without a gain is refused, as ref does: 1 + wadd of a gain that does not exist is a + * constant scale wearing a norm's name. */ + if (!w && wadd != 0.0f) return R3D_NO(RAD_E_INVAL); + /* The gain's dtype comes off the gain: bf16, f32, or none. */ + int wdt = R3D_DT_N; + if (w) { + if (r3d_is_bf16(w)) wdt = R3D_DT_BF16; + else if (r3d_is_f32(w)) wdt = R3D_DT_F32; + else return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); + } + + const long long n = r3d_geti_or(a, "n", w ? r3d_dim(w, (int)w->rank - 1) + : r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long y_ld = r3d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || My < M) return R3D_NO(RAD_E_SHAPE); + if (w && r3d_numel(w) < n) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_rmsnorm_f32(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)n, eps, wadd, mult, + (int)x_ld, (int)y_ld, wdt, (long)(uintptr_t)s) + : r3d_rmsnorm_bf16(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)n, eps, wadd, mult, + (int)x_ld, (int)y_ld, wdt, (long)(uintptr_t)s); + return r3d_launch_ok(rc); +} + +/* ------------------------------------------------------------------ rmsnorm_quant_fp8 + * The residual add, the norm and the E4M3 quantiser in one launch: {x, residual?, w, q, scale, + * out_bf16?} with {M, n, eps, group, dtype, wadd?}, libref's. The row's reason to exist is the + * traffic: the normalised row is written once as codes and one bf16 copy, not written as bf16 and + * read back by a separate quantiser. + */ +extern "C" int r3d_rad_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* res = r3d_opt(a, 1); + const RadTensor* w = r3d_opt(a, 2); + const RadTensor* q = r3d_opt(a, 3); + const RadTensor* sc = r3d_opt(a, 4); + const RadTensor* ob = r3d_opt(a, 5); + if (!x || !w || !q || !sc) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + /* The gain comes in the dtype the checkpoint stores it in -- bf16 or f32, read off the operand. + * The band's `dtype` is the activation's: a checkpoint that stores its gains as f32 is read as + * it is, and a shim that dtype-checks the weight against the activation band serves one + * checkpoint and refuses the next. The kernel's WDT leg is the plain rmsnorm's. */ + int wdt = R3D_DT_N; + if (r3d_is_bf16(w)) wdt = R3D_DT_BF16; + else if (r3d_is_f32(w)) wdt = R3D_DT_F32; + else return R3D_NO(RAD_E_DTYPE); + /* `residual` is validated below, where the flag that makes it read is read. `out_bf16` is + * checked because this kernel WRITES it, so it is required of the row that asks for it (the + * reference writes it when the operand is there) and absent when the slot carries no bytes. */ + if (r3d_has(ob)) R3D_NEED(dt_bf16(ob)); /* no bytes = the plan asked for no bf16 copy */ + if (r3d_dt_code(q->dtype) != R3D_DT_U8) return R3D_NO(RAD_E_DTYPE); // E4M3 codes + R3D_NEED(dt_f32(sc)); + + const long long n = r3d_geti_or(a, "n", w->rank ? r3d_dim(w, (int)w->rank - 1) : 0); + const long long group = r3d_geti_or(a, "group", 0); + if (n <= 0 || group <= 0) return R3D_NO(RAD_E_SHAPE); + /* A wave covers a group, four columns a lane per 128 columns, and a partial group is the + * standalone quantiser's zero-padded store. A checkpoint whose block divides its hidden width + * is the band this row is for. */ + if (group != 128 && group != 256 && group != 512) return R3D_NO(RAD_E_UNSUPPORTED); + if (n % group) return R3D_NO(RAD_E_UNSUPPORTED); + const float eps = (float)r3d_getf(a, "eps", 1e-6); + const float wadd = (float)r3d_getf(a, "wadd", 0.0); + /* The reference reads `residual` under `wadd` and nowhere else, and so do we -- checked here, + * after the flag, and REQUIRED by it. The engine hands the slot a tensor even when the band + * says wadd=0, in any dtype; a row that validates an operand the op will not read is a row + * that refuses a checkpoint. */ + if (wadd != 0.0f) { + if (!r3d_has(res)) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(res)); + } + + const long long ngrp = n / group; + long long M = 0, Mres = 0, Mob = 0, Mq = 0, Ms = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long q_ld = r3d_rows_pitch(q, n, &Mq); + const long long s_ld = r3d_rows_pitch(sc, ngrp, &Ms); + if (x_ld < 0 || q_ld < 0 || s_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mq < M || Ms < M) return R3D_NO(RAD_E_SHAPE); + long long res_ld = 0, ob_ld = 0; + if (res) { res_ld = r3d_rows_pitch(res, n, &Mres); if (res_ld < 0 || Mres < M) + return Mres < 0 ? R3D_NO(RAD_E_STRIDE) : R3D_NO(RAD_E_SHAPE); } + if (ob) { ob_ld = r3d_rows_pitch(ob, n, &Mob); if (ob_ld < 0 || Mob < M) + return Mob < 0 ? R3D_NO(RAD_E_STRIDE) : R3D_NO(RAD_E_SHAPE); } + if (r3d_numel(w) < n) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_rmsnorm_quant_fp8( + r3d_addr(x), r3d_addr(res), r3d_addr(w), r3d_addr(q), r3d_addr(sc), r3d_addr(ob), (int)M, + (int)n, (int)group, eps, wadd, (int)x_ld, (int)res_ld, (int)ob_ld, (int)q_ld, (int)s_ld, + wdt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ layernorm */ + +enum { LN_X = 0, LN_W, LN_B, LN_Y }; + +extern "C" int r3d_rad_layernorm(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, LN_X); + const RadTensor* w = r3d_opt(a, LN_W); + const RadTensor* b = r3d_opt(a, LN_B); + const RadTensor* y = r3d_opt(a, LN_Y); + if (!x || !w || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(w)); + R3D_NEED(dt_bf16(y)); + if (b) { + /* libref reads a bias in any float dtype; the kernel reads bf16 (the launcher has one + * dtype for gain and bias), so an f32 bias is refused, not read wrong. */ + if (!r3d_is_bf16(b)) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_bf16(b)); + } + if (!r3d_contig(w) || (b && !r3d_contig(b))) return R3D_NO(RAD_E_STRIDE); + + const long long n = r3d_geti_or(a, "n", r3d_dim(w, (int)w->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + const float eps = (float)r3d_getf(a, "eps", 1e-5); + long long M = 0, My = 0; + const long long x_ld = r3d_rows_pitch(x, n, &M); + const long long y_ld = r3d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || My < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(w) < n || (b && r3d_numel(b) < n)) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_layernorm_bf16(r3d_addr(x), r3d_addr(w), r3d_addr(b), r3d_addr(y), + (int)M, (int)n, eps, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ add / mul + * The broadcast rule is libref's, read off the operand: a `b` of exactly n elements against more + * than one row rides every row, and nothing else broadcasts. `div` is `add`'s only (mul's schema + * has no div key), and a zero, NaN or infinity is refused -- the reference refuses it too. */ +static int binary_shim(const RadArgs* a, RadStream s, int mul) { + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* B = r3d_opt(a, 1); + const RadTensor* Y = r3d_opt(a, 2); + if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(Y); + if (f32) { + R3D_NEED(dt_f32(A)); + R3D_NEED(dt_f32(B)); + } else { + R3D_NEED(dt_bf16(A)); + R3D_NEED(dt_bf16(B)); + R3D_NEED(dt_bf16(Y)); + } + R3D_NEED(dt_same(A, Y)); + if (!mul) R3D_NEED(dt_same(A, B)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(Y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + const float div = mul ? 1.0f : (float)r3d_getf(a, "div", 1.0); + if (!(div != 0.0f) || !std::isfinite(div)) return R3D_NO(RAD_E_INVAL); + + long long M = 0, Mb = 0; + const long long y_ld = r3d_rows_pitch(Y, n, &M); + const long long a_ld = r3d_rows_pitch(A, n, &Mb); + if (y_ld < 0 || a_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mb < M) return R3D_NO(RAD_E_SHAPE); + + const bool bcast = r3d_numel(B) == n && M > 1; + long long b_ld = 0; + if (!bcast) { + b_ld = r3d_rows_pitch(B, n, &Mb); + if (b_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (Mb < M) return R3D_NO(RAD_E_SHAPE); + } + + const int rc = mul + ? (f32 ? r3d_mul_f32(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, bcast ? 1 : 0, (long)(uintptr_t)s) + : r3d_mul_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, bcast ? 1 : 0, (long)(uintptr_t)s)) + : (f32 ? r3d_add_f32(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, div, bcast ? 1 : 0, (long)(uintptr_t)s) + : r3d_add_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, (int)a_ld, + (int)b_ld, (int)y_ld, div, bcast ? 1 : 0, (long)(uintptr_t)s)); + return r3d_launch_ok(rc); +} + +extern "C" int r3d_rad_add(const RadArgs* a, RadStream s) { return binary_shim(a, s, 0); } +extern "C" int r3d_rad_mul(const RadArgs* a, RadStream s) { return binary_shim(a, s, 1); } + +/* ------------------------------------------------------------------ cast + * `from` and `to` are the selector's; the tensors' own dtypes are what the kernel moves. The + * whole op is flat, so one pitch per operand, and the row count is numel(y)/n with n the last + * dimension of y. */ +extern "C" int r3d_rad_cast(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + const int from_dt = r3d_dt_code(x->dtype), to_dt = r3d_dt_code(y->dtype); + if (from_dt < 0 || to_dt < 0) return R3D_NO(RAD_E_DTYPE); + /* f16 has no e5m2 twin in this library, and the f16 <-> integer pairs have no caller: the + * codes the kernels move are bf16, f16, f32, i32, i64, E4M3 codes and i8. */ + static const int kOk[] = { R3D_DT_BF16, R3D_DT_F16, R3D_DT_F32, R3D_DT_I32, R3D_DT_I64, + R3D_DT_U8, R3D_DT_I8 }; + bool ok = false; + for (unsigned i = 0; i < sizeof kOk / sizeof kOk[0]; ++i) + ok = ok || (from_dt == kOk[i] && (to_dt == kOk[i] || to_dt == R3D_DT_F32 || + to_dt == R3D_DT_BF16 || to_dt == R3D_DT_I32 || + to_dt == R3D_DT_I64 || to_dt == R3D_DT_F16 || + to_dt == R3D_DT_U8 || to_dt == R3D_DT_I8)); + if (!ok) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_cast(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + from_dt, to_dt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ silu / gelu / sigmoid */ + +static int unary_shim(const RadArgs* a, RadStream s, int act) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + /* Only silu has an f32 leg in r3d.h (the vocoder's f32 branch is the one that asked for it); + * an f32 gelu or sigmoid is refused, not served by the bf16 kernel. */ + if (f32 && act != R3D_ACT_SILU) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_silu_f32(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : (act == R3D_ACT_SILU + ? r3d_silu_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : act == R3D_ACT_GELU + ? r3d_gelu_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) + : r3d_sigmoid_bf16(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, (int)y_ld, + (long)(uintptr_t)s)); + return r3d_launch_ok(rc); +} + +extern "C" int r3d_rad_silu(const RadArgs* a, RadStream s) { return unary_shim(a, s, R3D_ACT_SILU); } +extern "C" int r3d_rad_gelu(const RadArgs* a, RadStream s) { return unary_shim(a, s, R3D_ACT_GELU); } +extern "C" int r3d_rad_sigmoid(const RadArgs* a, RadStream s) { + return unary_shim(a, s, R3D_ACT_SIGMOID); +} + +/* ------------------------------------------------------------------ act_mul + * libref's kActs order is silu, gelu, gelu_tanh, sigmoid, quick_gelu; libr3d's rows serve silu, + * gelu and sigmoid, and the other two are refused with RAD_E_UNSUPPORTED so the row's constraints + * state which gated MLPs reach an RDNA3 card. */ +extern "C" int r3d_rad_act_mul(const RadArgs* a, RadStream s) { + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* B = r3d_opt(a, 1); + const RadTensor* Y = r3d_opt(a, 2); + 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)); + + int act = -1; + if (const char* n = r3d_gets(a, "act")) { + if (!std::strcmp(n, "silu") || !std::strcmp(n, "swish")) act = R3D_ACT_SILU; + else if (!std::strcmp(n, "gelu")) act = R3D_ACT_GELU; + else if (!std::strcmp(n, "sigmoid")) act = R3D_ACT_SIGMOID; + else if (!std::strcmp(n, "gelu_tanh") || !std::strcmp(n, "quick_gelu")) + return R3D_NO(RAD_E_UNSUPPORTED); + else return R3D_NO(RAD_E_INVAL); + } else { + act = R3D_ACT_SILU; // libref's p_enum default: the gated MLP's activation + } + + const long long n = r3d_geti_or(a, "n", r3d_numel(Y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mg = 0, Mu = 0; + const long long y_ld = r3d_rows_pitch(Y, n, &M); + const long long g_ld = r3d_rows_pitch(A, n, &Mg); + const long long u_ld = r3d_rows_pitch(B, n, &Mu); + if (y_ld < 0 || g_ld < 0 || u_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mg < M || Mu < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_act_mul_bf16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)n, + (int)g_ld, (int)u_ld, (int)y_ld, act, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ silu_mul + * y[i] = silu(gate_up[i]) * gate_up[n + i]: libref's {gate_up, y} operands and its {M, n, dtype} + * schema. A distinct op from act_mul -- the llama MLP emits it, and act_mul takes two operands -- + * so a model asking for silu_mul is not served by the act_mul_silu row. + */ +extern "C" int r3d_rad_silu_mul(const RadArgs* a, RadStream s) { + const RadTensor* gu = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!gu || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(gu)); + R3D_NEED(dt_bf16(y)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mgu = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long gu_ld = r3d_rows_pitch(gu, 2 * n, &Mgu); /* the FUSED row is 2n wide */ + if (y_ld < 0 || gu_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mgu < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE); // ref's own bound on the plane + + return r3d_launch_ok(r3d_silu_mul_bf16(r3d_addr(gu), r3d_addr(y), (int)M, (int)n, (int)gu_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ softmax + * f32, as ref spells it: the reference casts to f32, computes, and casts back, and the intermediate + * `e` is read back from an f32 plane. A bf16 y would round that intermediate and the kernel cannot + * match ref with ref's own arithmetic, so it is refused rather than served at a tolerance. */ +extern "C" int r3d_rad_softmax(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* y = r3d_opt(a, 1); + if (!x || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_f32(x)); + R3D_NEED(dt_f32(y)); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + return r3d_launch_ok(r3d_softmax_f32(r3d_addr(x), r3d_addr(y), (int)M, (int)n, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ scale + * y = x * s. `s` is the op's [1] weight plane: the shim checks its dtype and that it has an + * element, and the kernel reads the value. The launcher cannot take the number by value, because + * reading a device plane on the host is a copy and a sync, and a row is neither. */ +extern "C" int r3d_rad_scale(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* sc = r3d_opt(a, 1); + const RadTensor* y = r3d_opt(a, 2); + if (!x || !sc || !y) return R3D_NO(RAD_E_INVAL); + const bool f32 = r3d_is_f32(x) && r3d_is_f32(y); + if (!f32) { + R3D_NEED(dt_bf16(x)); + R3D_NEED(dt_bf16(y)); + } + const int s_dt = r3d_is_f32(sc) ? R3D_DT_F32 : r3d_is_bf16(sc) ? R3D_DT_BF16 : -1; + if (s_dt < 0) return R3D_NO(RAD_E_DTYPE); + if (r3d_numel(sc) < 1) return R3D_NO(RAD_E_SHAPE); + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx < M) return R3D_NO(RAD_E_SHAPE); + + const int rc = f32 + ? r3d_scale_f32(r3d_addr(x), r3d_addr(sc), r3d_addr(y), (int)M, (int)n, s_dt, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s) + : r3d_scale_bf16(r3d_addr(x), r3d_addr(sc), r3d_addr(y), (int)M, (int)n, s_dt, (int)x_ld, + (int)y_ld, (long)(uintptr_t)s); + return r3d_launch_ok(rc); +} + +/* ------------------------------------------------------------------ fill */ + +extern "C" int r3d_rad_fill(const RadArgs* a, RadStream s) { + const RadTensor* y = r3d_opt(a, 0); + if (!y) return R3D_NO(RAD_E_INVAL); + const int dt = r3d_dt_code(y->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); // no e5m2 codec on this path + + const long long n = r3d_geti_or(a, "n", r3d_numel(y)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + if (y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M)) return R3D_NO(RAD_E_SHAPE); + + const float v = (float)r3d_getf(a, "value", 0.0); + return r3d_launch_ok(r3d_fill(r3d_addr(y), (int)M, (int)n, (int)y_ld, dt, v, + (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ rope + * In place, so operand 0 is the row's INOUT: the shim checks it is writable (the role says it is; + * a null data is the row's bug, and is RAD_E_INVAL) and that head_dim and rot are even. + * + * What the shim refuses, and why: the multi-component modes (mrope, imrope, axial) need a + * [C, M] position plane and per-section ladders; the proportional ladder (`ladder=head`) pairs + * across the whole head; YaRN and Llama 3 rescale the ladder. Each changes the angles, not the + * arithmetic, and the kernel has the plain rotary -- so each is RAD_E_UNSUPPORTED, the row's + * constraints say so, and a model that needs one is not routed to this card's row. + */ +extern "C" int r3d_rad_rope(const RadArgs* a, RadStream s) { + const RadTensor* qkv = r3d_opt(a, 0); + const RadTensor* pos = r3d_opt(a, 1); + if (!qkv || !pos) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(qkv)); + R3D_NEED(dt_i32(pos)); + if (!r3d_contig(pos)) return R3D_NO(RAD_E_STRIDE); + if (pos->rank >= 2) return R3D_NO(RAD_E_UNSUPPORTED); // multi-component positions + + const long long head_dim = r3d_geti_or(a, "head_dim", 0); + const long long n_head = r3d_geti_or(a, "n_head", 0); + const long long n_head_kv = r3d_geti_or(a, "n_head_kv", 0); + if (head_dim <= 0 || n_head <= 0 || n_head_kv < 0) return R3D_NO(RAD_E_SHAPE); + long long rot = r3d_geti_or(a, "rotary_dim", head_dim); + if (rot <= 0) rot = head_dim; + if (rot > head_dim) return R3D_NO(RAD_E_SHAPE); + if ((head_dim & 1) || (rot & 1)) return R3D_NO(RAD_E_SHAPE); /* odd halves: a shape the kernel does not serve */ + + static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" }; + int mode = -1; + if (const char* nm = r3d_gets(a, "mode")) { + for (int i = 0; i < 5; ++i) + if (!std::strcmp(nm, kModes[i])) { mode = i; break; } + } + if (mode < 0) return R3D_NO(RAD_E_UNSUPPORTED); // absent, or one of the three multi modes + if (mode > R3D_ROPE_GPTJ) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_gets(a, "sections")) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_getf(a, "yarn_factor", 0.0) != 0.0) return R3D_NO(RAD_E_UNSUPPORTED); + if (r3d_getf(a, "llama3_factor", 0.0) != 0.0) return R3D_NO(RAD_E_UNSUPPORTED); + if (const char* lad = r3d_gets(a, "ladder")) { + /* Absent and "rotary" are the ladder the kernel has: the base frequency divides by rot. */ + if (std::strcmp(lad, "rotary")) return R3D_NO(RAD_E_UNSUPPORTED); + } + + const float theta = (float)r3d_getf(a, "theta", 10000.0); + const float scale = (float)r3d_getf(a, "scale", 1.0); + + const long long width = (n_head + 2 * n_head_kv) * head_dim; + long long Mq = 0; + const long long qkv_ld = r3d_rows_pitch(qkv, width, &Mq); + if (qkv_ld < 0) return R3D_NO(RAD_E_STRIDE); + const long long Mp = r3d_numel(pos); + if (Mp <= 0 || Mq < Mp) return R3D_NO(RAD_E_SHAPE); + const long long M = Mp; // the positions drive the launch; a row past them is left alone + + return r3d_launch_ok(r3d_rope_bf16(r3d_addr(qkv), r3d_addr(pos), (int)M, (int)head_dim, + (int)n_head, (int)n_head_kv, theta, scale, mode, (int)rot, + (int)qkv_ld, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ kv_store + * The cache is INOUT: only the mapped slots are touched and every other slot must survive. Its + * strides are read off the operand (the reference's kv_view): a rank-4 cache carries them; the + * flat [blocks, kv_heads, block_size, 2*head_dim] form derives them. + * + * ref also refuses a slot naming a block past the cache (RAD_E_SHAPE), which the shim cannot do + * before the launch: the slots are in device memory. The bound travels as `slot_max`, the slot span + * of the cache the shapes hook sizes, and the kernel drops a slot at or past it -- a slot lost, + * not a step lost. + */ +extern "C" int r3d_rad_kv_store(const RadArgs* a, RadStream s) { + const RadTensor* k = r3d_opt(a, 0); + const RadTensor* v = r3d_opt(a, 1); + const RadTensor* sm = r3d_opt(a, 2); + const RadTensor* kv = r3d_opt(a, 3); + if (!k || !v || !sm || !kv) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_bf16(k)); + R3D_NEED(dt_bf16(v)); + R3D_NEED(dt_i32(sm)); + const int kv_dt = r3d_dt_code(kv->dtype); + if (kv_dt != R3D_DT_BF16 && kv_dt != R3D_DT_F16 && kv_dt != R3D_DT_U8) + return R3D_NO(RAD_E_DTYPE); + + const long long head_dim = r3d_geti_or(a, "head_dim", 0); + const long long n_head_kv = r3d_geti_or(a, "n_head_kv", 0); + const long long block_size = r3d_geti_or(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0); + if (head_dim <= 0 || n_head_kv <= 0 || block_size <= 0) return R3D_NO(RAD_E_SHAPE); + const float k_scale = (float)r3d_getf(a, "k_scale", 1.0); + const float v_scale = (float)r3d_getf(a, "v_scale", 1.0); + if (kv_dt == R3D_DT_U8 && !(k_scale > 0.0f && v_scale > 0.0f)) return R3D_NO(RAD_E_INVAL); + + long long sb = 0, sh = 0, so = 0, sd = 1; + if (kv->rank == 4) { + sb = r3d_stride(kv, 0); + sh = r3d_stride(kv, 1); + so = r3d_stride(kv, 2); + sd = r3d_stride(kv, 3); + if (sd != 1) return R3D_NO(RAD_E_UNSUPPORTED); // a strided cache element + if (r3d_dim(kv, 1) != n_head_kv || r3d_dim(kv, 2) != block_size) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(kv, 3) < 2 * head_dim) return R3D_NO(RAD_E_SHAPE); + } else { + so = 2 * head_dim; + sh = block_size * so; + sb = n_head_kv * sh; + } + + const long long width = n_head_kv * head_dim; + long long Mk = 0, Mv = 0; + const long long k_ld = r3d_rows_pitch(k, width, &Mk); + const long long v_ld = r3d_rows_pitch(v, width, &Mv); + if (k_ld < 0 || v_ld < 0) return R3D_NO(RAD_E_STRIDE); + const long long T = r3d_numel(sm); + if (T <= 0 || Mk < T || Mv < T) return R3D_NO(RAD_E_SHAPE); + if (!row_count_ok(T)) return R3D_NO(RAD_E_SHAPE); + + /* The cache's span, in slots: the pool's own plane, NOT this step's. A step that adopts a + * prefix writes its tail into the blocks the table names, and those sit at the allocator's + * GLOBAL indices -- a 4-token tail placed at block 3 is slots 48..51, past any bound built + * from T. A bound built from the step's own span is no bound for the tail's slots, so the + * pool's plane is the true bound: a slot at or past it names memory the cache does not have, + * and the kernel drops it there. */ + long long slot_max; + if (kv->rank == 4) { + slot_max = (long long)r3d_dim(kv, 0) * block_size; + } else { + long long el = 1; + for (int i = 0; i < kv->rank; ++i) el *= r3d_dim(kv, i); + slot_max = el / (2 * head_dim); + } + + if (std::getenv("RAD_R3D_TRACE")) /* the write side, spoken: where this step's KV lands. A + * tail that names slots of an adopted block writes over the + * shared prefix, and this line is the one that says so. */ + { + (void)hipDeviceSynchronize(); + int slots[8]; + if (hipMemcpy(slots, (const void*)(uintptr_t)r3d_addr(sm), 8 * sizeof(int), + hipMemcpyDeviceToHost) == hipSuccess) { + std::fprintf(stderr, "[r3d] kvstore: T=%lld kvbase=%p slots=", (long long)T, + (const void*)(uintptr_t)r3d_addr(kv)); + for (int c = 0; c < 8 && (long long)c < T; ++c) + std::fprintf(stderr, "%s%d", c ? " " : "", slots[c]); + std::fprintf(stderr, "\n"); + } + } + + return r3d_launch_ok(r3d_kv_store(r3d_addr(k), r3d_addr(v), r3d_addr(sm), r3d_addr(kv), (int)T, + (int)head_dim, (int)n_head_kv, (int)block_size, kv_dt, + k_scale, v_scale, (int)k_ld, (int)v_ld, slot_max, sb, sh, so, + sd, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ embed_lookup + * tokens are i32 (the engine's token ids), the table's dtype is the launcher's `dt`, and x is + * bf16 -- a table in any other float dtype, or an E4M3 table whose scale arrives as a tensor + * (embed_lookup_q's operand), is refused: one scale per gathered row is a device read the step + * path cannot do, which is why the op's schema carries `wscale` as a parameter. */ +extern "C" int r3d_rad_embed_lookup(const RadArgs* a, RadStream s) { + const RadTensor* tok = r3d_opt(a, 0); + const RadTensor* wte = r3d_opt(a, 1); + const RadTensor* x = r3d_opt(a, 2); + if (!tok || !wte || !x) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(tok)); + R3D_NEED(dt_bf16(x)); + if (!r3d_contig(tok) || !r3d_contig(wte)) return R3D_NO(RAD_E_STRIDE); + const int dt = r3d_dt_code(wte->dtype); + if (dt != R3D_DT_BF16 && dt != R3D_DT_F16 && dt != R3D_DT_F32 && dt != R3D_DT_U8) + return R3D_NO(RAD_E_DTYPE); + if (dt != R3D_DT_BF16 && r3d_getf(a, "wscale", 1.0) == 1.0 && dt == R3D_DT_U8) + return R3D_NO(RAD_E_INVAL); // an E4M3 table with no scale stated is a bug, not a copy + + const long long n_embd = r3d_geti_or(a, "n_embd", r3d_dim(wte, (int)wte->rank - 1)); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(wte, (int)wte->rank - 2)); + const long long voff = r3d_geti_or(a, "vocab_offset", 0); + if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(wte) < n_vocab * n_embd) return R3D_NO(RAD_E_SHAPE); + + long long Mx = 0; + const long long x_ld = r3d_rows_pitch(x, n_embd, &Mx); + if (x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(Mx) || r3d_numel(tok) < Mx) return R3D_NO(RAD_E_SHAPE); + const long long M = Mx; + + const float mult = (float)r3d_getf(a, "mult", 1.0); + const float wscale = (float)r3d_getf(a, "wscale", 1.0); + const long long w_ld = wte->rank >= 2 ? r3d_stride(wte, (int)wte->rank - 2) : n_embd; + + return r3d_launch_ok(r3d_embed_lookup(r3d_addr(tok), r3d_addr(wte), r3d_addr(x), (int)M, + (int)n_embd, (int)n_vocab, (int)voff, wscale, mult, + (int)x_ld, (int)w_ld, dt, (long)(uintptr_t)s)); +} + +/* ------------------------------------------------------------------ gather_rows / scatter_rows */ + +extern "C" int r3d_rad_gather_rows(const RadArgs* a, RadStream s) { + const RadTensor* x = r3d_opt(a, 0); + const RadTensor* idx = r3d_opt(a, 1); + const RadTensor* y = r3d_opt(a, 2); + if (!x || !idx || !y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(idx)); + const int dt = r3d_dt_code(x->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_same(x, y)); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long y_ld = r3d_rows_pitch(y, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (y_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx <= 0 || r3d_numel(idx) < M) return R3D_NO(RAD_E_SHAPE); + + /* The source plane's row count, which the shim sees in the descriptor and the kernel cannot: + * an index at or past it is libref's refused step and takes the zero row here. */ + return r3d_launch_ok(r3d_gather_rows(r3d_addr(x), r3d_addr(idx), r3d_addr(y), (int)M, (int)n, + (int)x_ld, (int)y_ld, dt, Mx, (long)(uintptr_t)s)); +} + +extern "C" int r3d_rad_scatter_rows(const RadArgs* a, RadStream s) { + const RadTensor* v = r3d_opt(a, 0); + const RadTensor* idx = r3d_opt(a, 1); + const RadTensor* x = r3d_opt(a, 2); + if (!v || !idx || !x) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_i32(idx)); + const int dt = r3d_dt_code(v->dtype); + if (dt < 0) return R3D_NO(RAD_E_DTYPE); + R3D_NEED(dt_same(v, x)); + if (dt == R3D_DT_E5M2) return R3D_NO(RAD_E_UNSUPPORTED); + + const long long n = r3d_geti_or(a, "n", r3d_dim(v, (int)v->rank - 1)); + if (n <= 0) return R3D_NO(RAD_E_SHAPE); + long long M = 0, Mx = 0; + const long long v_ld = r3d_rows_pitch(v, n, &M); + const long long x_ld = r3d_rows_pitch(x, n, &Mx); + if (v_ld < 0 || x_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (!row_count_ok(M) || Mx <= 0 || r3d_numel(idx) < M) return R3D_NO(RAD_E_SHAPE); + + /* The destination plane's row count, from the descriptor: an index at or past it writes past + * the plane, which is the one thing a scatter must not do, so the kernel drops the row. */ + return r3d_launch_ok(r3d_scatter_rows(r3d_addr(v), r3d_addr(idx), r3d_addr(x), (int)M, (int)n, + (int)v_ld, (int)x_ld, dt, Mx, (long)(uintptr_t)s)); +} diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h new file mode 100644 index 00000000..4a7c6675 --- /dev/null +++ b/libr3d/r3d_plugin.h @@ -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 . + * 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 */ diff --git a/libr3d/r3d_quant_fp8.hip b/libr3d/r3d_quant_fp8.hip new file mode 100644 index 00000000..d953ee3c --- /dev/null +++ b/libr3d/r3d_quant_fp8.hip @@ -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 +__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(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 +__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(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), 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 +__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), 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), 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), 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 +__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(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), 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 +__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 +__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((uint8_t)(w & 0xffu)) * sc, + code_value((uint8_t)(w >> 8)) * sc); + yp[1] = bf16x2_rne(code_value((uint8_t)(w >> 16)) * sc, + code_value((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), 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)); +} diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp new file mode 100644 index 00000000..58cb10e6 --- /dev/null +++ b/libr3d/r3d_rows.cpp @@ -0,0 +1,1839 @@ +/* r3d_rows.cpp -- what libr3d can compute, and for which geometry. + * + * One row per (kernel, band). A row is a `RadKernelInfo`: names, prose, the geometry it serves as + * constraints, the tuning axes, and the entry points that launch it. The engine reads this table at + * load, matches a requested op and geometry against it, and ranks the candidates by `priority`; it + * never calls a function in this file to do that, and it never looks at a kernel's name. Nothing in + * the engine, the graph, the containers or a test names libr3d's kernels: a card runs this library + * because the rows say they cover its ops, and it stops running them when they do not. + * + * ============================================================ the schema table + * + * The first plugin in hierarchy order to declare an op fixes its schema, and a plugin whose schema + * disagrees is refused at load, both plugins named (rad_abi.h, spec §2.3): arguments are positional, + * so two schemas for one op would make one call mean two things depending on which row won. libref + * declares the vocabulary in `docs/OPS.md`, so every schema below is libref's -- the same keys, the + * same types, the same requiredness, the same operand roles and optionality, in the same order. The + * prose is ours, because it states what *this* row computes; the loader's comparison + * covers the positional slots and not the documents. + * + * An op libr3d invents needs a schema here too, and libref's side of it: an op whose schema is + * declared only by a kernel plugin cannot be checked against a reference, and an op that exists in + * two kernels with two schemas breaks the rule above. That is why libr3d declares no new op: every + * row below implements an op libref declares. + * + * ============================================================ the constraint table + * + * A constraint is a necessary condition on the geometry (spec §2.1). "bf16 only" is not one: the + * dtype of an operand is a property of the call, and the shim reads the tensor. What goes here is + * what the *kernel* cannot do -- the divisibility its lane map assumes, the band its grid is sized + * for, the scheme its decoders implement -- and what the selector needs to choose between rows. + * A constraint the shim also checks costs nothing; a constraint the kernel does not actually + * enforce is a promise the tests will break. + * + * ============================================================ rows are positional + * + * `RadKernelInfo` is initialised positionally, as `rad_abi.h` requires: a field added anywhere but + * the end shifts every later initialiser, and `nullptr` converts to any function pointer, so part + * of the shift compiles. The order below is the struct's; the trailing slots a row does not use are + * left off, which aggregate initialisation zeroes. A row's entry points are, in order: init, fini, + * launch, scratch, layout, relayout, opd_shape, unrelayout, replaces. + * + * The only `layout` and `relayout` hooks in this table present the container's own planes as the + * joined operands they store -- the w2a8 row's `b_scale`, the fp8 weight's codes and scale, the + * logits head -- and repack nothing, so a container converted on this card keeps row-major codes + * against row-major scales. A dot2 GEMM reads a weight in the order it is stored; libr4d's fragment + * permutations are a WMMA fact, and RDNA3's wave-matrix instructions use a 16x16 fragment layout + * this table's dot2 kernels do not (r3d_common.h has the measurements). + * + * Pure host C++: no r3d.h, no HIP, so this table compiles and can be read and tested without ROCm. + */ + +#include "r3d_plugin.h" + +#ifndef R3D_BUILD_TARGET +#define R3D_BUILD_TARGET "gfx1100 gfx1101 gfx1102 gfx1103 gfx1150 gfx1151" +#endif + +#include +#include + +#define ROW(a) (a), (int)(sizeof(a) / sizeof((a)[0])) +#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) + +/* Parameter and constraint spellings, shared with libref's table. */ +#define P_INT(k) { (k), RAD_P_INT, RAD_REQUIRED } +#define P_INTO(k) { (k), RAD_P_INT, RAD_OPTIONAL } +#define P_INTD(k) { (k), RAD_P_INT, RAD_DERIVED } +#define P_STR(k) { (k), RAD_P_STR, RAD_REQUIRED } +#define P_STRO(k) { (k), RAD_P_STR, RAD_OPTIONAL } +#define P_F64(k) { (k), RAD_P_F64, RAD_REQUIRED } +#define P_F64O(k) { (k), RAD_P_F64, RAD_OPTIONAL } + +#define C_EQ(k, v) { (k), RAD_C_EQ, (long long)(v), nullptr } +#define C_LE(k, v) { (k), RAD_C_LE, (long long)(v), nullptr } +#define C_GE(k, v) { (k), RAD_C_GE, (long long)(v), nullptr } +#define C_DIV(k, v) { (k), RAD_C_DIV, (long long)(v), nullptr } +#define C_IN(k, s) { (k), RAD_C_IN, 0, (s) } + +/* A row with one implementation and nothing to measure. */ +#define NOTUNE nullptr, 0, nullptr + +#define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) } + +/* ================================================================== schemas + * + * Operand names are diagnostics only; roles and optionality are positional and must match. Where + * libref's array carries a name libr3d's reads differently (`b` for a gate, say) the names differ + * and the schema does not. + */ + +/* --- norms and elementwise --- */ +static const RadParamSpec pRmsNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), + P_F64O("wadd"), P_F64O("mult") }; +static const RadOperandSpec oRmsNorm[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") }; +static const RadOperandSpec oLayernorm[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "b", RAD_OPD_WEIGHT, 1 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("div") }; +static const RadParamSpec pMnDtype[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +static const RadOperandSpec oBinary[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oUnary[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; + +static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_STR("to") }; + +static const RadParamSpec pScale[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; +/* `s` is a WEIGHT, which is what the reference declares and what the core acts on: a weight operand + * has its issue resolve a handle and wait on the mover, and a scale plane comes from the container + * or from a quantiser, not from a buffer the planner allocated for this step. Declaring it IN is + * not a cosmetic difference -- the loader compares roles positionally and refuses the library that + * disagrees, every row with it. */ +static const RadOperandSpec oScale[] = { { "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; +static const RadOperandSpec oFill[] = { { "y", RAD_OPD_OUT, 0 } }; + +/* --- the model's odds and ends --- */ +static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), + P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), + P_F64O("yarn_factor"), P_F64O("yarn_low"), + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_STRO("ladder"), P_F64O("llama3_factor"), + P_F64O("llama3_low"), P_F64O("llama3_high"), + P_F64O("llama3_orig") }; +static const RadOperandSpec oRope[] = { { "qkv", RAD_OPD_INOUT, 0 }, + { "positions", RAD_OPD_IN, 0 } }; + +static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), + P_INT("block_size"), P_STR("kv_dtype"), + P_F64O("k_scale"), P_F64O("v_scale") }; +static const RadOperandSpec oKvStore[] = { { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 } }; + +static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"), + P_STR("dtype"), P_INTO("vocab_offset"), P_F64O("wscale"), + P_F64O("mult") }; +static const RadOperandSpec oEmbed[] = { { "tokens", RAD_OPD_IN, 0 }, + { "wte", RAD_OPD_WEIGHT, 0 }, + { "x", RAD_OPD_OUT, 0 } }; + +static const RadOperandSpec oGather[] = { { "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oScatter[] = { { "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, + { "x", RAD_OPD_INOUT, 0 } }; + +/* --- quantisation --- */ +static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype") }; +static const RadOperandSpec oQuantFp8[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oQuant[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "asum", RAD_OPD_OUT, 1 } }; + +static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), + P_STRO("act") }; +static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 } }; + +static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +/* --- gemm --- */ +static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") }; +static const RadOperandSpec oGemm[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"), + P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"), + P_INTO("split_n") }; +static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 1 }, + { "b", RAD_OPD_WEIGHT, 0 }, + { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, { "a_sum", RAD_OPD_IN, 1 }, + { "b_ref", RAD_OPD_WEIGHT, 1 } }; + + +/* ================================================================== the vocab and the sampler + * + * The vocab and sampler bands, transcribed from libref. A schema is inert on its own -- the loader + * matches a row to a schema, and a row naming an entry point no unit defines is an undefined symbol + * that kills `dlopen` and takes every row in the library with it -- so `r3d_selftest`'s schema phase + * compares every declared schema against libref's, slot for slot, the moment the library loads, and + * a misspelled key is refused at load, not when a row first meets it. + * + * The sampler is a law, not a shape: the candidate set, the tie-break in the top-k, the order of the + * renormalisations and the seeded draw are all observable, and libref is the oracle for all of them. + */ + +/* The gated MLP's activation, as the llama-family graphs emit it: one fused [M, 2n] projection, the + * gate's half activated and multiplied by the other. `act_mul` is the same arithmetic over two + * operands; these are different ops, and an architecture emits one or the other. */ +static const RadOperandSpec oGateUp[] = { { "gate_up", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; + +/* Paged attention. `block_size` is RAD_DERIVED here (the container's cache geometry, admitted by a + * constraint that only refuses its absence), and `n_head`, `max_seqs`, `max_ctx` and `prefill_fp8` + * are on the list because a plugin's scratch hook sizes a split-KV buffer from them and both + * libraries must agree on the parameter list -- libref ignores them. */ +/* DFlash2's candidate walk: a draft block of `steps` proposals, `top_k` candidates at each step, + * rescored against the target's rank-d codebooks. `anchor_stride` is optional and defaults to 1; + * `hp` is the optional per-edge scaling of the predecessor's codebook row, and absent it is a plane + * of ones, which is what the reference computes. */ +/* The gated MLP band: one weight of N = 2n rows (gate first, then up), the GEMM, the gate and the + * output quantiser in one launch, so the [M, N] intermediate the unfused chain writes and re-reads + * never exists. `act` is a required string: an implementation compiles one gate, and an optional + * would let a row resolve for the gate it does not have. */ +static const RadParamSpec pGemmQGated[] = { P_INT("M"), P_INT("N"), P_INT("K"), + P_INT("group"), P_STR("dtype"), P_STR("act") }; +/* The vocabulary projection's schema, slot for slot with the reference's: the geometry is the head's + * (`n_vocab` x `n_embd`), the dtype is the activation's, and `logits` is f32 -- the op exists + * separately from gemm_nt for that reason, and the row that serves it narrows nothing. */ +static const RadParamSpec pLogits[] = { P_INT("M"), P_INT("n_vocab"), P_INT("n_embd"), + P_STR("dtype") }; +static const RadOperandSpec oLogits[] = { + { "x", RAD_OPD_IN, 0 }, { "lm_head", RAD_OPD_WEIGHT, 0 }, { "logits", RAD_OPD_OUT, 0 } }; + +static const RadOperandSpec oGemmQGated[] = { + { "a", RAD_OPD_IN, 0 }, { "a_scale", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_WEIGHT, 0 }, { "b_scale", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, +}; + +static const RadParamSpec pDflashSelect[] = { P_INT("M"), P_INT("steps"), P_INT("top_k"), + P_INT("rank"), P_INT("n_vocab"), + P_INTO("anchor_stride"), P_STR("dtype") }; +static const RadOperandSpec oDflashSelect[] = { + { "cand", RAD_OPD_IN, 0 }, { "unary", RAD_OPD_IN, 0 }, + { "hp", RAD_OPD_IN, 1 }, { "anchor", RAD_OPD_IN, 0 }, + { "pred", RAD_OPD_WEIGHT, 0 },{ "succ", RAD_OPD_WEIGHT, 0 }, + { "tokens", RAD_OPD_OUT, 0 }, +}; + +static const RadParamSpec pAttnPaged[] = { + P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"), + P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"), + P_INTO("n_head"), P_INTO("max_seqs"), P_INTO("prefill_fp8") +}; +static const RadOperandSpec oAttnPaged[] = { + { "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_IN, 0 }, { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, { "k_descale", RAD_OPD_IN, 1 }, { "v_descale", RAD_OPD_IN, 1 }, + { "cu_seqlens", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 } +}; + +/* The row's top-R over a vocabulary slice, and the sampler's stages. The history stages write this + * rank's columns and read global ids, so they carry `vocab_off`; the narrowing stages work on the + * candidate set the top-k produced and need only its width. */ +static const RadParamSpec pRowTopk[] = { P_INT("M"), P_INT("N"), P_INT("R"), P_INTO("vocab_off"), + P_STR("dtype") }; +static const RadOperandSpec oRowTopk[] = { { "x", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_OUT, 0 }, + { "val", RAD_OPD_OUT, 0 }, + { "pairs", RAD_OPD_OUT, 1 } }; +static const RadParamSpec pMVocab[] = { P_INT("M"), P_INT("n_vocab") }; +static const RadParamSpec pMCand[] = { P_INT("M"), P_INT("n_cand") }; +static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; +static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; +static const RadParamSpec pLogprobs[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), + P_INTO("vocab_off") }; +static const RadOperandSpec oTemp[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oMask[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "bitmask", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oPenalties[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oDry[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 }, + { "breakers", RAD_OPD_IN, 1 } }; +static const RadOperandSpec oNgramBan[] = { { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 }, + { "ngram", RAD_OPD_IN, 0 }, + { "whitelist", RAD_OPD_IN, 1 } }; +static const RadOperandSpec oTopk[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "cand_idx", RAD_OPD_OUT, 0 }, + { "cand_val", RAD_OPD_OUT, 0 }, + { "pairs", RAD_OPD_OUT, 1 } }; +static const RadOperandSpec oArgmax[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "token", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oLogprobs[] = { { "logits", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "stats", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oNarrow[] = { { "cand_idx", RAD_OPD_INOUT, 0 }, + { "cand_val", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 } }; +static const RadOperandSpec oPick[] = { { "cand_idx", RAD_OPD_IN, 0 }, + { "cand_val", RAD_OPD_IN, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "token", RAD_OPD_OUT, 0 } }; + + +/* The fused MLP activation and the fused norm-quantiser, both from the model unit. The first takes + * one [M, 2n] operand and produces [M, n]; the second is libref's, slot for slot, with `residual` + * INOUT because the sum it stores is the one the variance reads. */ +static const RadParamSpec pRmsQuantFp8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"), + P_STR("dtype"), P_F64O("wadd") }; +/* `residual` is optional because the op has a no-residual form, which is what the launcher's `res` + * pointer being 0 means; libref spells it INOUT_O and the loader compares the flag. */ +static const RadOperandSpec oRmsQuantFp8[] = { + { "x", RAD_OPD_IN, 0 }, { "residual", RAD_OPD_INOUT, 1 }, { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 } +}; + +static const RadOpSchema kSchemas[] = { + SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, + "y = x * rsqrt(mean(x^2) + eps) * (w + wadd) * mult. `wadd` is GemmaRMSNorm's `1 +`, " + "added to the gain in f32; `mult` scales the normed row before its one rounding. No " + "gain operand at all means a gain of 1 and a `wadd` of 0."), + SCHEMA("layernorm", pLayernorm, oLayernorm, + "y = (x - mean) / sqrt(var + eps) * w + b, the mean and the variance taken in two " + "passes over the row."), + SCHEMA("add", pAdd, oBinary, + "y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts " + "along rows, and nothing else broadcasts at all. With `div`, y = rd(rd(a + b) / div)."), + SCHEMA("mul", pMnDtype, oBinary, "y = a * b, with the same one broadcast rule as `add`."), + SCHEMA("act_mul", pActMul, oBinary, + "y = act(a) * b over two [M, n] operands, `act` naming silu, gelu (the exact erf form), " + "gelu_tanh, sigmoid or quick_gelu. The feed-forward's gated middle."), + SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."), + SCHEMA("gelu", pMnDtype, oUnary, + "y = 0.5 * x * (1 + erf(x / sqrt(2))), the exact form; the tanh approximation is a " + "different op name."), + SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."), + SCHEMA("softmax", pMnDtype, oUnary, "Row-wise, f32, with the maximum subtracted."), + SCHEMA("cast", pCast, oUnary, + "y = x, from the dtype `from` to the dtype `to`, one rounding on the way. An integer " + "pair goes through without touching f32, so ids above 2^24 survive."), + SCHEMA("scale", pScale, oScale, + "y = x * s, `s` one element broadcast over the whole output. A row of scales is " + "`mul_weight`."), + SCHEMA("fill", pFill, oFill, "y = value over [M, n]. The output is the only operand."), + SCHEMA("rope", pRope, oRope, + "Rotary positions applied in place to a fused qkv row: q heads, then the key heads, the " + "value heads untouched. `mode` is neox, gptj, mrope, imrope or axial; the yarn, llama3 " + "and ladder parameters adjust the frequency ladder."), + SCHEMA("kv_store", pKvStore, oKvStore, + "K and V into a paged cache at slot_mapping's slots, converting to the cache's dtype. A " + "negative slot is skipped; the cache is [blocks, kv_heads, block_size, 2*head_dim]."), + SCHEMA("embed_lookup", pEmbed, oEmbed, + "x[r] = wte[tokens[r] - vocab_offset] * wscale * mult, the id global and the table " + "sharded by `vocab_offset`. An id outside the shard's range yields a zero row."), + SCHEMA("gather_rows", pMnDtype, oGather, "y[r] = x[idx[r]], rows of n elements."), + SCHEMA("scatter_rows", pMnDtype, oScatter, "x[idx[r]] = v[r], rows of n elements."), + SCHEMA("quant_act_fp8", pQuant, oQuantFp8, + "Symmetric per-(row, group) E4M3: scale = amax * (1/448) with the reciprocal " + "multiplied, not divided; an all-zero group gets scale 1 and the codes 0."), + SCHEMA("quant_act_i8", pQuant, oQuant, + "Symmetric int8 with ONE SCALE PER ROW, max(amax, 1e-8) / 127, codes round-to-nearest-" + "ties-to-even and saturating, stored in the STEP ORDER the int8 WMMA reads. `asum` takes " + "the group-major row sums the zero-pointed GEMMs reduce."), + SCHEMA("quant_act_i8g", pQuant, oQuantFp8, + "The same int8 code at `group` granularity: one f32 scale per (row, group), amax / 127, " + "1 for an all-zero group, codes row-major."), + SCHEMA("gated_quant_fp8", pGatedQuant, oGatedQuant, + "act(gate) * up over a fused [M, 2n] projection, quantised in the same pass: the codes " + "are taken over the rounded product, which `out_bf16` receives when present."), + SCHEMA("dequant", pQuant, oDequant, + "y = code * scale, the read of a container's own quantised weight: `group`-wide f32 " + "scales against E4M3, E5M2 or int8 codes."), + SCHEMA("gemm_nt", pGemm, oGemm, "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate."), + SCHEMA("gemm_nt_q", pGemmQ, oGemmQ, + "The same product against a quantised weight. `dtype` names the scheme: fp8a16 a bf16 " + "activation against E4M3 codes, fp8a8 quant_act_fp8's codes and scales, i8a8 int8 on " + "both axes. `group` is the activation's scale width; `pb1` and `pb2` the weight's block, " + "which the container states. `a_sum` and `b_ref` are the row sums a zero-pointed form " + "reduces."), + + SCHEMA("rmsnorm_quant_fp8", pRmsQuantFp8, oRmsQuantFp8, + "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The " + "residual add is STORED BEFORE THE VARIANCE READS IT, so the sum the norm is taken over " + "is the bf16 one and not the f32 one -- that is what makes this the `add` + `rmsnorm` " + "pair and not `rmsnorm_add`, which normalises the unrounded sum. `wadd` is added to every " + "gain in f32. `out_bf16` holds exactly the value the codes were taken over."), + + /* ---- the vocabulary and the sampler: schemas first, rows with their kernels ---- */ + SCHEMA("silu_mul", pMnDtype, oGateUp, + "y[i] = silu(gate_up[i]) * gate_up[n + i] over one fused [M, 2n] plane, the gate the " + "first half -- rad-convert's fusion order -- and the product of an activation that was " + "never narrowed. act_mul is the same arithmetic over two operands, narrowing first, " + "because the pair it replaces stored the activation."), + SCHEMA("attn_paged", pAttnPaged, oAttnPaged, + "Scaled dot-product attention over a paged KV cache: q [tokens, n_head, head_dim], the " + "cache [blocks, kv_heads, block_size, 2*head_dim], `block_table` a row's block list, " + "`seqused` its length. `gqa` is the head ratio; `causal` and `window` are the mask; " + "`scale` is 1/sqrt(head_dim) unless the graph says otherwise. k_descale and v_descale " + "come with an fp8 cache, cu_seqlens with a packed prefill."), + SCHEMA("row_topk", pRowTopk, oRowTopk, + "Exact per-row top-R, descending, ties to the lower column. `vocab_off` shifts every " + "column reported, so a rank's slice reports global ids; `pairs` is the [M, R, 2] plane an " + "all_gather moves, with id -1 for a slot the row could not fill."), + SCHEMA("sample_argmax", pMVocab, oArgmax, + "The most likely token of each row, the lowest id on a tie."), + SCHEMA("sample_temp", pMVocab, oTemp, + "logits / temperature, in place. The temperature is a row parameter, so a batch mixes " + "greedy and sampled rows."), + SCHEMA("sample_topk", pTopk, oTopk, + "The k most likely candidates a row: ids and values, descending, ties to the lower id. " + "`pairs` is the vocab-parallel form the merge reads after the all-gather."), + SCHEMA("sample_topp", pMCand, oNarrow, + "Narrow the candidate set to the smallest prefix whose probabilities reach p, in the " + "order the candidates arrive -- not in sorted order, which is a different set at a tie."), + SCHEMA("sample_minp", pMCand, oNarrow, + "Drop a candidate whose probability is under min_p times the best candidate's."), + SCHEMA("sample_typical", pMCand, oNarrow, + "Drop the candidates furthest from the set's entropy: keep those within `sigma` of the " + "mean surprise, the token set a reader would not have predicted least and most alike."), + SCHEMA("sample_xtc", pMCand, oNarrow, + "The exclusion-the-model-would-not-choose filter: drop every candidate above p, keeping " + "the last one standing when all of them are."), + SCHEMA("sample_pick", pMCand, oPick, + "The seeded inverse-CDF draw over the candidate set: the law the request's seed selects, " + "in the order the candidates arrive. A kernel that draws from the same distribution " + "differs from the reference on every token, and kbench reads that as a failure, because " + "for a sampler it is one."), + SCHEMA("sample_penalties", pPenal, oPenalties, + "Presence, frequency and repetition penalties in place, over the row's history, with the " + "DRY and penalty terms libref spells out."), + SCHEMA("sample_dry", pPenal, oDry, + "Distributed Repetition Penalty: a sequence of `last_n` that repeats a sequence of " + "`baseline` is penalised, growing with the length of the repeat. `breakers` marks the " + "positions that end a sequence and are never penalised."), + SCHEMA("sample_ngram_ban", pPenal, oNgramBan, + "Ban the n-grams of length `n` that the history shows inside `window`, to -inf. " + "`whitelist` exempts a set of ids from the ban."), + SCHEMA("sample_mask", pMVocab, oMask, + "The grammar's and the tool-caller's doing: set to -inf every id whose bit is clear in " + "the row's bitmask, addressed by the row's mask_row, which is -1 for a row with no " + "constraint and so shares a short plane."), + SCHEMA("sample_logprobs", pLogprobs, oLogprobs, + "The row's log-softmax statistics for the response: max, sum of exp, and the k best " + "(id, logit) pairs, in [M, 2 + 2k]."), + SCHEMA("logits_gemm", pLogits, oLogits, + "logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T. Separate from gemm_nt " + "because lm_head is its own access class and the sampler wants to fuse against it: the " + "head is the largest read in a decode step and the output is f32, which every sampler " + "stage downstream reads."), + SCHEMA("gemm_nt_q_gated", pGemmQGated, oGemmQGated, + "The gated MLP band in one launch: `b` is N = 2n rows, gate over up, the dot products are " + "narrowed to bf16 as the unfused pair would leave them, the gate is `gt * sigmoid(gt)`, the " + "product is narrowed, and the row is coded per group of `group` columns with the amax that " + "group's scale comes from. `out_bf16`, when asked for, is the narrowed gated tensor before " + "the coding."), + SCHEMA("dflash_select", pDflashSelect, oDflashSelect, + "DFlash2's greedy walk over a draft block: at each of `steps` steps the candidate with " + "the best `unary + pred[pid] . (hp * succ[cand])` is picked, and becomes the predecessor " + "of the next step. `cand`/`unary` have one row per (sequence, step); `anchor` is the " + "block's first predecessor, at `m * anchor_stride`."), +}; + +extern "C" int rad_kernel_schema_count(void) { + return (int)(sizeof(kSchemas) / sizeof(kSchemas[0])); +} +extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { + if (i < 0 || i >= rad_kernel_schema_count()) return nullptr; + return &kSchemas[i]; +} + +/* ================================================================== tuning + * + * The axes a kernel is instantiated along, measured on this card (`rad-tune`, spec §15). Every row + * without a matrix instruction to size a tile against has few axes: what is left to measure is how + * the work is split across the card, and how the weight stream is read. + */ + +/* Split-K. 0 is not a point in the space, it is the kernel's own law: "the largest split legal at + * this K", because no fixed default is legal at every shape and an illegal default would make an + * untuned install fail rather than run slowly. */ +static const int64_t kSk[] = { 0, 1, 2, 4, 8, 16 }; +/* Waves per block. 8 is 256 threads, which is the largest block that keeps the register budget of + * a wave-per-N-tile kernel inside gfx11's 1024 VGPRs a SIMD at four waves. */ +static const int64_t kWv[] = { 1, 2, 4, 8 }; +/* Non-temporal weight streaming: a decode GEMM reads a weight once per token, so the L2 is a + * latency cache and not a reuse cache. RDNA3 has no transposed-load instruction, so this axis + * selects the plain 128-bit stream with the cache hints off -- a knob worth measuring, not an + * instruction. */ +static const int64_t kNt[] = { 0, 1 }; +/* No `kb` axis. Only a GEMM that stages a K slab through LDS has a slab width to measure, and + * the skinny rows stream the weight through registers; the axis joins the table with the tiled + * row. */ + +static const RadTunable tGemmM16[] = { + { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, + { "wv", kWv, NELEM(kWv), 8, "waves per block" }, + { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, +}; +/* No `wv` here. The quantised kernel's launcher takes a fixed block of eight waves -- its weight + * decode, sixteen codes a lane into eight dot2, is the whole of a wave's issue budget at any block + * size -- so an axis the tuner would sweep is an axis the kernel ignores, and a tunable that changes + * nothing is worse than none: it spends the tuner on a knob and teaches the reader that the table + * lies. The axis joins the row with a launcher that takes it. */ +static const RadTunable tGemmQ[] = { + { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, + { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, +}; + +/* Cross-axis legality, in one place so the tuner, the scratch hook and the launch agree. A split's + * slice must end on a k multiple the kernel's inner loop consumes: 8 elements for a bf16 dot2 pair + * group, and one whole scale group for a quantised weight, since a slice that ends mid-block cannot + * apply its block scale. */ +static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + const long long K = rad_param_getdim(p, n_p, "K", 0); + const long long sk = rad_param_geti(c, n_c, "sk", 0); + const long long wv = rad_param_geti(c, n_c, "wv", 8); + if (K <= 0 || wv < 1 || wv > 8) return 0; + const long long unit = rad_param_getdim(p, n_p, "group", 0) > 0 + ? rad_param_getdim(p, n_p, "group", 0) + : 8; + return sk >= 0 && (sk == 0 || K % (sk * unit) == 0); +} + +/* The chosen point, read back. `TUNE` falls to the axis's default when the core appended nothing, + * so a checker with no tuned key runs what an untuned install runs. */ +static long long tune_i(const RadArgs* a, const RadTunable* t, int n, const char* key) { + if (a && a->p) + for (int i = 0; i < a->n_p; ++i) + if (a->p[i].key && !std::strcmp(a->p[i].key, key) && a->p[i].kind == RAD_P_INT) + return a->p[i].ival; + for (int i = 0; i < n; ++i) + if (!std::strcmp(t[i].key, key)) return t[i].deflt; + return 0; +} +#define TUNE(a, tab, key) ((int)tune_i((a), (tab), NELEM(tab), (key))) + +extern "C" void r3d_cfg_gemm(const RadArgs* a, R3dGemmCfg* out) { + out->wv = TUNE(a, tGemmM16, "wv"); + out->sk = TUNE(a, tGemmM16, "sk"); + out->kb = 0; + out->nt = TUNE(a, tGemmM16, "nt"); +} +extern "C" void r3d_cfg_split(const RadArgs* a, R3dSplitCfg* out) { + out->splits = TUNE(a, tGemmM16, "sk"); +} +extern "C" void r3d_cfg_topk(const RadArgs* a, R3dTopkCfg* out) { + out->rc = 0; + out->nch = 0; +} + +/* A split's partials are f32 over the output, plus one arrival counter per split. Sized at the + * band's bounds and the axis's widest split, because a scratch hook runs at declare, where the + * range may still be open: the buffer must hold any point the tuner can pick. */ +/* Split-KV's partials: one record of 128 accumulator floats plus the running max and sum -- 132 + * floats -- per (query row, head, slice). The shim takes the slice count from the bytes the engine + * offers and halves it until they fit, so this is the want, stated at the slice count the walk + * benefits from and capped at what these bands can carry: 15 MB at the decode band (1792 rows over + * 16 heads) and 17 MB at the prefill band. Attaching scratch makes the row non-concurrent, which is + * the ABI's rule (rad_kernel_concurrent is `scratch == nullptr`) and the price of the split. */ +static int64_t attn_scratch(const RadArgs* a) { + /* The size comes from the SHAPE, and a scratch hook runs at declare, where the engine has bound + * the operands' shapes and has no bytes to hand out yet -- `data` is null at declare for every + * tensor in the plan. A hook that requires bytes answers 0 for the whole run, the engine + * allocates an arena of 0 bytes, and the shim's split pass finds no partials to write. The + * sibling `gemm_scratch` sizes off `RadParam` dims for exactly this reason. */ + if (!a || a->n_t < 1 || a->t[0].rank == 0) return 0; + long long n_head = 0, head_dim = 0; + const int64_t nh = rad_args_geti(a, "n_head", &n_head) ? n_head : 0; + if (!rad_args_geti(a, "head_dim", &head_dim) || !head_dim || !nh) return 0; + const long long rows = rad_tensor_numel(&a->t[0]) / (nh * head_dim); + if (rows <= 0) return 0; + const long long want = rows * nh * 8 * 132 * (long long)sizeof(float); + const long long cap = 16LL << 20; + return want < cap ? want : cap; +} + +static int64_t gemm_scratch(const RadParam* p, int n_p) { + const long long M = rad_param_getdim(p, n_p, "M", 0), N = rad_param_getdim(p, n_p, "N", 0); + const long long sk = kSk[NELEM(kSk) - 1]; + if (M <= 0 || N <= 0) return 0; + return sk * M * N * 4 + sk * 64; +} + +/* ================================================================== constraints + * + * What the kernel cannot do, and what the selector needs. The divisibility in each is the lane map + * in the unit: a wave covering a bf16 row reads four elements a lane (two pairs), so a row of 4m + * elements needs no tail; where the kernel has a tail path the constraint says 2, not 4. + */ + +/* bf16 elementwise, norms and the GEMMs: rows of an even width, so a lane owns a pair. */ +static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cF32Row[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; +static const RadConstraint cNormBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2), + C_GE("n", 2) }; +static const RadConstraint cNormF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2), C_GE("n", 2) }; +static const RadConstraint cSoftmax[] = { C_IN("dtype", "f32"), C_GE("n", 2) }; + +/* A cast row is its pair of dtype names. */ +static const RadConstraint cCastBf16F32[] = { C_IN("from", "bf16"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastF32Bf16[] = { C_IN("from", "f32"), C_IN("to", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cCastBf16[] = { C_IN("from", "bf16"), C_IN("to", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cCastF32[] = { C_IN("from", "f32"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastI64F32[] = { C_IN("from", "i64"), C_IN("to", "f32"), + C_DIV("n", 2) }; +static const RadConstraint cCastI32I64[] = { C_IN("from", "i32"), C_IN("to", "i64"), + C_DIV("n", 2) }; +static const RadConstraint cCastI64I32[] = { C_IN("from", "i64"), C_IN("to", "i32"), + C_DIV("n", 2) }; + +/* act_mul names its activation, because a row for gelu and a row for silu are different template + * instantiations and a model asks for one of them. */ +static const RadConstraint cActSilu[] = { C_IN("act", "silu"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cActGelu[] = { C_IN("act", "gelu"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; +static const RadConstraint cActSigmoid[] = { C_IN("act", "sigmoid"), C_IN("dtype", "bf16"), + C_DIV("n", 2) }; + +/* A fill row is its dtype; the value is a parameter, and every dtype takes every value. */ +static const RadConstraint cFillBf16[] = { C_IN("dtype", "bf16") }; +static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") }; +static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") }; +static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") }; + +/* rope: the two modes this kernel implements, and a rotary width that is a whole even head. The + * yarn, llama3 and ladder parameters are absent from these rows' bands, so a geometry carrying them + * is not routed here. */ +/* `rotary_dim` is optional on the op, and a constraint on a parameter a band does not carry does + * not hold -- the engine's rule, quoted in r3d_selftest.cpp's band-reachability phase -- so it + * cannot appear here: an architecture that rotates the whole head, which is every llama-family + * graph, emits a band without the parameter and would find no row. Its evenness is the shim's to + * refuse (RAD_E_SHAPE), and `rotary_dim` absent is head_dim, which is even by the constraint above. */ +static const RadConstraint cRope[] = { C_IN("mode", "neox gptj"), C_DIV("head_dim", 2) }; + +/* The cache's dtype is the row: a bf16 cache stores the value, an E4M3 cache encodes it with the + * store's scale. head_dim even because a lane writes a pair; block_size a multiple of 16 so a + * block's slice of a row is a whole number of lanes. */ +static const RadConstraint cKvBf16[] = { C_IN("kv_dtype", "bf16"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; +static const RadConstraint cKvFp8[] = { C_IN("kv_dtype", "fp8_e4m3"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; +static const RadConstraint cKvF16[] = { C_IN("kv_dtype", "f16"), C_DIV("head_dim", 2), + C_DIV("block_size", 16) }; + +static const RadConstraint cEmbed[] = { C_IN("dtype", "bf16"), C_DIV("n_embd", 2) }; + +/* The gather's and scatter's dtype, and a row wide enough for a lane to own a pair. */ +static const RadConstraint cGatherBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cGatherF32[] = { C_IN("dtype", "f32"), C_DIV("n", 2) }; +static const RadConstraint cScatterBf16[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; + +/* The quantisers: the scale group is the checkpoint's block, 128, and a row wide enough that a + * wave's four-elements-a-lane store is whole. */ +static const RadConstraint cQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), + C_DIV("n", 4) }; +/* `quant_act_i8` is the per-row int8 whose codes the int8 WMMA reads, so its width is a whole + * 16-byte step, not a lane's four. `quant_act_i8g` is the per-group one whose codes are row-major, + * which is what a dot2 GEMM reads; it is the activation of this library's i8a8 row. */ +static const RadConstraint cQuantI8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 16) }; +static const RadConstraint cQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 4) }; +/* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's integer + * `mode` instead, and libref's own default is silu), and a band that states neither would resolve to + * nothing. The shim reads `act`, falls back to `mode`, then to silu, and refuses a gelu -- the + * activation whose kernel this unit does not carry -- with RAD_E_UNSUPPORTED. */ +static const RadConstraint cGateQuant[] = { C_IN("dtype", "bf16"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantFp8[] = { C_IN("dtype", "fp8_e4m3"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantE5[] = { C_IN("dtype", "fp8_e5m2"), + C_EQ("group", R3D_FP8_BLOCK), C_DIV("n", 4) }; +static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", R3D_W8_GROUP), + C_DIV("n", 4) }; + +/* The GEMMs. The skinny row's band is the decode and verify height: 16 rows, which is a speculative + * verify's ceiling with room to spare, and below the height where staging the activations through + * LDS starts to pay. K even, because the inner loop consumes pairs; N unconstrained, because a wave + * covering N tiles the tail. + * + * No upper bound on N: the vocabulary and the feed-forward widths are 11008, 14336, 128256 and + * whatever a given checkpoint's `intermediate_size` is, and a bound would refuse them. */ +static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 2), C_GE("N", 1) }; +/* The vocabulary projection. **No `dtype` constraint, and the reason is the engine's, not the + * kernel's**: the band this op is declared with carries the geometry (M, n_vocab, n_embd) and not a + * dtype key -- the head's dtype is a property of the weight, which is why libref's own logits row + * answers it with a `check_dtypes` hook and not with a constraint. A constraint on a key the + * geometry does not carry serves nobody: with `dtype in {bf16}` declared, the engine resolves a + * host kernel and no device one and refuses to start, so the dtype is refused where it is read, at + * the shim, naming the widening the kernel does. + * `n_embd` in 32-code chunks is the entry's own rule (K % 32), stated so a band outside it is + * refused at declare rather than at launch. `n_vocab`'s floor is the store's granularity: a row + * writes 16-byte runs, so a plane four ids wide is the narrowest it can read, and a band narrower + * than that -- a shard's padding, a 1-id test vocabulary -- is refused by the constraint and not by + * the launch. Above the floor the grid is vocab-wide at every M, so a 320-wide vocabulary and a + * 130560-wide one are the same kernel. */ +static const RadConstraint cLogitsGemm[] = { C_GE("M", 1), C_GE("n_vocab", 4), + C_DIV("n_embd", 32) }; +/* The tiled GEMM at prefill heights. M >= 17 is the complement of cGemmM16's M <= 16 by + * construction, so the two rows never compete for a band: the skinny shape (a wave a run of + * columns, the weight streamed past registers) is right up to 16 rows and wrong above it, and the + * 128x128 tile is the reverse. K % 32 is the tile's k-chunk and N >= 8 the bf16 store run, for the + * same reason cLogitsGemm states its floor: what the kernel cannot read is in the constraints. */ +/* The quantised GEMM above the decode heights. Here `dtype` IS the operand scheme -- gemm_q_shape + * switches on it -- so C_IN filters, which is the distinction from logits_gemm, where the band's + * dtype names the activation and C_IN filters nothing. M >= 17 is the complement of + * gemm_nt_q_fp8a8_m16's M <= 16 -- read from its constraint, not from its name: a higher floor + * would leave 17..64 unserved, and a 209-row batched decode is the shape a serving card spends + * most of its life in. The tile's k-chunk (32) divides the container's scale + * block (128), which is why `group` is an equality and `K` a divisibility. */ +static const RadConstraint cGemmQFP8Tiled[] = { C_IN("dtype", "fp8a8 fp8a8f32"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), + C_DIV("K", 128) }; +/* The OCP-MXFP4 rows: the weight is e2m1 with one e8m0 scale per 32 of K, the activation's + * scale per 128 -- both fixed by the format, so the `group` key carries no kernel-side meaning + * and the rows do not constrain it (the reference derives the planes from it). K dividing 128 + * carries the 32-block; the band split is the fp8a8 one, 16 at the ceiling and 17 at the floor, + * and the dtype carries the whole scheme. */ +static const RadConstraint cGemmQMxfp4a8M16[] = { C_IN("dtype", "mxfp4a8"), + C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQMxfp4a8Tiled[] = { C_IN("dtype", "mxfp4a8"), + C_GE("M", 17), + C_DIV("K", 128) }; + +/* The symmetric int4 / int8 weight grids at decode heights: the block is the weight's scale + * group (128), and the band is the m16 one -- M > 16 is the tiled rows', and the 8-bit grid at + * prefill heights is declared out. */ +static const RadConstraint cGemmQW4A8M16[] = { C_IN("dtype", "w4a8"), + C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"), + C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 128), C_GE("N", 1) }; + +static const RadConstraint cGemmNTTiled[] = { C_IN("dtype", "bf16"), C_GE("M", 17), C_DIV("K", 32), + C_GE("N", 8) }; +/* The quantised GEMM: the scheme names the row, the weight's block is the container's, and a split + * must land on a block boundary (gemm_tune_valid). */ +/* The block: `group` is required and every band names it, so the row states it. `pb1` and `pb2` are + * OPTIONAL, and a constraint on a key the band omits does not hold -- a model whose container + * declares the default block says nothing about pb1, and constraining it would make every one of + * that model's GEMM bands fall through to the reference and its host kernel -- 259 ops on one + * 2B model. The launcher defaults them to `group` (r3d_gemm_fp8a16_nt_m1.hip) and refuses a + * pb2 that is not the code group, which is the container's own invariant: the K block IS the code + * group, so a band naming pb2 unequal to group resolves to this row and is refused at launch. */ +static const RadConstraint cGemmQFp8a16[] = { C_IN("dtype", "fp8a16"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +static const RadConstraint cGemmQFp8a8[] = { C_IN("dtype", "fp8a8"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +/* The int8 GEMM's constraints are written ahead of its row: 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. */ +static const RadConstraint cGemmQI8[] = { C_IN("dtype", "i8a8"), + C_EQ("group", R3D_W8_GROUP), C_GE("M", 1), + C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; + +/* ================================================================== the rows + * + * Declaration order is the tie-break within one priority, so rows that share an op are declared + * narrowest first. + */ +/* The constraints above are written ahead of the rows that use them, for the same reason the + * schemas are: the table reads as one document. A constraint array with no row is not an error, so + * the file builds; the comment above each says which row it serves. */ + +/* ================================================================== the fused-MLP rows + * + * The two rows the llama graphs ask for that the model unit serves. `silu_mul` constrains + * nothing but the dtype and an even `n`: `act` is not in this op's parameter list (it is the fused + * form of one fixed activation), and a constraint on a key the geometry lacks does not hold, so a + * row built on the act_mul constraints would resolve to no band at all. `rmsnorm_quant_fp8` states + * the group the kernel covers with a wave and requires it to divide `n`; the standalone quantiser's + * `n % 4` would admit a band this kernel refuses, and a row that resolves at declare and fails at + * launch is the shape of bug this file exists to prevent. + */ +static const RadConstraint cSiluMul[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; +static const RadConstraint cRmsQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_FP8_BLOCK), + C_DIV("n", R3D_FP8_BLOCK) }; + +/* The sampler's pre-filters constrain `n_vocab` and nothing else. The bands an architecture emits + * for these ops carry `n_vocab` and `M` (plus `vocab_off`, and `k` for logprobs) and no `dtype` + * key, so a row that constrained a dtype would constrain a key the geometry lacks and resolve to no + * band at all. The dtype is f32; the shims check it on the tensor, which is where a dtype belongs + * when the geometry does not name it. `k <= 64` is the depth of the logprobs kernel's pool, so the + * row serves exactly the bands its launcher accepts. + */ +static const RadConstraint cSampleF32[] = { C_GE("n_vocab", 1) }; +static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) }; + +/* The attention rows bind the two dtype keys, the head width the kernel's tile is built for, and + * the q_len bucket boundary the two kernels are split at. `gqa`, `window` and `causal` are left + * free: the kernel walks the mask for any gqa the shim accepts and any window, and a constraint on + * them would only exclude bands it serves. */ +static const RadConstraint cAttnBf16Decode[] = { C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), + C_EQ("head_dim", 128), C_LE("q_len", 16) }; +static const RadConstraint cAttnBf16Prefill[] = { C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), + C_EQ("head_dim", 128), C_GE("q_len", 17) }; +static const RadConstraint cAttnFp8Decode[] = { C_IN("q_dtype", "bf16"), + C_IN("kv_dtype", "fp8_e4m3"), + C_EQ("head_dim", 128), C_LE("q_len", 16) }; +static const RadConstraint cAttnFp8Prefill[] = { C_IN("q_dtype", "bf16"), + C_IN("kv_dtype", "fp8_e4m3"), + C_EQ("head_dim", 128), C_GE("q_len", 17) }; + +/* `row_topk` is banded on dtype, so it gets two rows; the candidate stages are banded on `n_cand`, + * whose ceiling is the kernel's: five f32 arrays of n_cand in LDS is 20 KiB of the 64 KiB, and a + * wider band is refused by the shim (RAD_E_SHAPE), so the row states the ceiling and resolves for + * exactly what it serves. The vocab stages carry `n_vocab` and no dtype key, and the logits are f32 + * by the shim's check on the tensor. + */ +static const RadConstraint cRowTopkBf16[] = { C_IN("dtype", "bf16"), C_GE("N", 1), C_GE("R", 1) }; +static const RadConstraint cRowTopkF32[] = { C_IN("dtype", "f32"), C_GE("N", 1), C_GE("R", 1) }; +static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 1024) }; + +/* Every key the walk reads is required and in the band, so all of them are bound -- `top_k <= 256` + * is one lane a candidate. `anchor_stride` is deliberately NOT bound: it is optional, defaults to + * 1, and the kernel serves any value at or above 1, so a band that omits it must still resolve. */ +/* The block is one key for three things at once: the weight's K block, its row block and the + * quantiser's group. `act` is C_IN because it is a required string here, not the optional `mode` + * form. M <= 64 is the ceiling the launcher serves; 47 of MiniCPM5-2B's 48 bands are M=64. */ +/* The container's 2-bit vocab weights. `group` is one key for the weight's K block and the scale's + * block, as everywhere in this family; K must also be a multiple of the launcher's chunk + * (2048 / M-tile), which the launcher refuses and the row does not pretend to cover. */ +static const RadConstraint cGemmQW2A8[] = { C_IN("dtype", "w2a8"), C_EQ("group", R3D_FP8_BLOCK), + C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), + C_GE("N", 1) }; + +/* The packed-code grids at the heights gemm_nt_q_w2a8_m16 declines. The grid is the container's -- + * one scale and one zero per `group` of codes on a {1, group} plane -- so `group` is the block, and + * K divides by it because a staged 32-code chunk must sit inside one scale group. */ +static const RadConstraint cGemmQW2A8Tiled[] = { C_IN("dtype", "w2a8 w4a8_asym"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 17), + C_DIV("K", 128) }; + +static const RadConstraint cGemmGated[] = { C_IN("dtype", "fp8a8"), + C_IN("act", "silu sigmoid"), + C_EQ("group", R3D_FP8_BLOCK), C_GE("M", 1), + C_LE("M", 64), C_DIV("K", 128), C_DIV("N", 2), + C_GE("N", 2) }; + +static const RadConstraint cDflashSelect[] = { C_IN("dtype", "bf16"), C_GE("M", 1), + C_GE("steps", 1), C_GE("top_k", 1), + C_LE("top_k", 256), C_GE("rank", 1), + C_GE("n_vocab", 1) }; + +static const RadKernelInfo kKernels[] = { +/* ------------------------------------------------------------------ r3d_model_bf16.hip + * + * One workgroup a row. The `shape` column states the geometry the grid is built for; the + * `computes` column states the arithmetic, in the order the kernel performs it. + */ +{ "rmsnorm_bf16", "rmsnorm", "norm", + "root-mean-square norm with a gain, two passes over the row", + "any n; a workgroup a row; the sum of squares accumulates in f32 and only the store narrows", + "bf16 x and y, bf16 or f32 gain, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormBf16), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm }, + +{ "rmsnorm_f32", "rmsnorm", "norm", + "root-mean-square norm with a gain, two passes over the row", + "any n; a workgroup a row", + "f32 x, y and gain, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormF32), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm }, + +{ "layernorm_bf16", "layernorm", "norm", + "layer norm with a gain and an optional bias, mean and variance in two passes", + "any n; a workgroup a row; both passes accumulate in f32", + "bf16 x, y, gain and bias, fp32 reduction", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cNormBf16), NOTUNE, + nullptr, nullptr, r3d_rad_layernorm, nullptr, nullptr, nullptr, + r3d_shape_layernorm }, + +{ "add_bf16", "add", "elem", + "a + b, with b's row broadcast and an optional divisor", + "any n; a workgroup a row; f32 arithmetic, one narrowing at the store", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_add, nullptr, nullptr, nullptr, + r3d_shape_add }, + +{ "add_f32", "add", "elem", + "a + b, with b's row broadcast and an optional divisor", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_add, nullptr, nullptr, nullptr, + r3d_shape_add }, + +{ "mul_bf16", "mul", "elem", + "a * b, with b's row broadcast", + "any n; a workgroup a row", + "bf16 in and out, f32 product, one narrowing at the store", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_mul, nullptr, nullptr, nullptr, + r3d_shape_mul }, + +{ "mul_f32", "mul", "elem", + "a * b, with b's row broadcast", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_mul, nullptr, nullptr, nullptr, + r3d_shape_mul }, + +/* The casts, one row per pair the engine issues. bf16 to f32 and back is the residual stream's + * width change; i64 to f32 is a position table read by a rotary; the integer pairs move token ids + * between planes and must not pass through f32, which loses the low bits above 2^24. */ +{ "cast_bf16_f32", "cast", "elem", "bf16 to f32, exact", "any n; a wave 128 elements", + "bf16 in, f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastBf16F32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_f32_bf16", "cast", "elem", "f32 to bf16, one rounding", "any n; a wave 128 elements", + "f32 in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastF32Bf16), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_bf16_bf16", "cast", "elem", "bf16 to bf16, a copy", "any n; a wave 128 elements", + "bf16 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastBf16), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_f32_f32", "cast", "elem", "f32 to f32, a copy", "any n; a wave 128 elements", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastF32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i64_f32", "cast", "elem", "i64 to f32", "any n; a wave 128 elements", + "i64 in, f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI64F32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i32_i64", "cast", "elem", "i32 to i64, exact", "any n; a wave 128 elements", + "i32 in, i64 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI32I64), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "cast_i64_i32", "cast", "elem", "i64 to i32, the ids' narrowing", "any n; a wave 128 elements", + "i64 in, i32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cCastI64I32), NOTUNE, + nullptr, nullptr, r3d_rad_cast, nullptr, nullptr, nullptr, r3d_shape_cast }, + +{ "silu_bf16", "silu", "elem", "x * sigmoid(x), the sigmoid in f32", "any n; a wave 128 elements", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_silu, nullptr, nullptr, nullptr, r3d_shape_silu }, + +{ "silu_f32", "silu", "elem", "x * sigmoid(x)", "any n; a wave 128 elements", "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_silu, nullptr, nullptr, nullptr, r3d_shape_silu }, + +{ "gelu_bf16", "gelu", "elem", + "the exact erf GELU: 0.5 * x * (1 + erf(x / sqrt(2)))", + "any n; a wave 128 elements; erff, the accurate form, not the tanh approximation", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_gelu, nullptr, nullptr, nullptr, r3d_shape_gelu }, + +{ "sigmoid_bf16", "sigmoid", "elem", "1 / (1 + exp(-x))", "any n; a wave 128 elements", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_sigmoid, nullptr, nullptr, nullptr, r3d_shape_sigmoid }, + +{ "act_mul_silu_bf16", "act_mul", "elem", + "silu(gate) * up, the gated feed-forward's middle", + "any n; a workgroup a row; the gate is operand 0", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActSilu), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "act_mul_gelu_bf16", "act_mul", "elem", + "gelu(gate) * up, the exact erf form", + "any n; a workgroup a row", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActGelu), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "act_mul_sigmoid_bf16", "act_mul", "elem", "sigmoid(gate) * up", "any n; a workgroup a row", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cActSigmoid), NOTUNE, + nullptr, nullptr, r3d_rad_act_mul, nullptr, nullptr, nullptr, r3d_shape_act_mul }, + +{ "softmax_f32", "softmax", "elem", + "row softmax with the maximum subtracted, the denominator summed in ascending order", + "any n; a workgroup a row", + "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSoftmax), NOTUNE, + nullptr, nullptr, r3d_rad_softmax, nullptr, nullptr, nullptr, r3d_shape_softmax }, + +{ "scale_bf16", "scale", "elem", "x * s, one scalar over the whole output", + "any n; a wave 128 elements", "bf16 in and out, fp32 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r3d_rad_scale, nullptr, nullptr, nullptr, r3d_shape_scale }, + +{ "scale_f32", "scale", "elem", "x * s, one scalar over the whole output", + "any n; a wave 128 elements", "f32 in and out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r3d_rad_scale, nullptr, nullptr, nullptr, r3d_shape_scale }, + +{ "fill_bf16", "fill", "elem", "the value over [M, n]", "any n; a wave 128 elements", + "bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillBf16), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_f32", "fill", "elem", "the value over [M, n]", "any n; a wave 128 elements", "f32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillF32), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_i32", "fill", "elem", "the value over [M, n], the value as an integer", + "any n; a wave 128 elements", "i32 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillI32), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "fill_i64", "fill", "elem", "the value over [M, n], the value as an integer", + "any n; a wave 128 elements", "i64 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cFillI64), NOTUNE, + nullptr, nullptr, r3d_rad_fill, nullptr, nullptr, nullptr, r3d_shape_fill }, + +{ "rope_bf16", "rope", "attn", + "rotary positions applied in place to a fused qkv row, neox and gptj pair layouts", + "head_dim even; rotary_dim optional and even, defaulting to head_dim; a wave a head; the " + "angles from accurate powf and sincosf, the position divided by `scale`", + "bf16 qkv in place, i32 positions, fp32 angles", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRope), NOTUNE, + nullptr, nullptr, r3d_rad_rope, nullptr, nullptr, nullptr, r3d_shape_rope }, + +{ "kv_store_bf16", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, bf16 to bf16", + "any head_dim and block size; a wave a (token, head) pair; a negative slot skipped", + "bf16 k and v, i32 slot mapping, bf16 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvBf16), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "kv_store_f16", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, bf16 to f16", + "any head_dim and block size; a wave a (token, head) pair", + "bf16 k and v, i32 slot mapping, f16 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvF16), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "kv_store_fp8", "kv_store", "attn", + "K and V into a paged cache at the slot mapping, encoding E4M3 with the store's scale", + "any head_dim and block size; a wave a (token, head) pair; the scale divides before the encode", + "bf16 k and v, i32 slot mapping, fp8_e4m3 cache", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvFp8), NOTUNE, + nullptr, nullptr, r3d_rad_kv_store, nullptr, nullptr, nullptr, r3d_shape_kv_store }, + +{ "embed_lookup_bf16", "embed_lookup", "gemm", + "the codebook row an id names, scaled, with out-of-shard ids yielding a zero row", + "any n_embd; a workgroup a row of the table", + "bf16 table and output, i32 ids", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cEmbed), NOTUNE, + nullptr, nullptr, r3d_rad_embed_lookup, nullptr, nullptr, nullptr, r3d_shape_embed_lookup }, + +{ "gather_rows_bf16", "gather_rows", "elem", "y[r] = x[idx[r]]", + "any n; a workgroup a row", "bf16 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatherBf16), NOTUNE, + nullptr, nullptr, r3d_rad_gather_rows, nullptr, nullptr, nullptr, r3d_shape_gather_rows }, + +{ "gather_rows_f32", "gather_rows", "elem", "y[r] = x[idx[r]]", + "any n; a workgroup a row", "f32 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatherF32), NOTUNE, + nullptr, nullptr, r3d_rad_gather_rows, nullptr, nullptr, nullptr, r3d_shape_gather_rows }, + +{ "scatter_rows_bf16", "scatter_rows", "elem", "x[idx[r]] = v[r]", + "any n; a workgroup a row; distinct indices, so no two rows write one destination", + "bf16 rows, i32 indices", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cScatterBf16), NOTUNE, + nullptr, nullptr, r3d_rad_scatter_rows, nullptr, nullptr, nullptr, r3d_shape_scatter_rows }, + +/* ------------------------------------------------------------------ r3d_quant_fp8.hip + * + * Plain row-major code planes against one f32 scale per (row, group). No fragment permutation for + * the codes a dot2 GEMM reads: it reads them in the order they are stored, which is the whole + * reason a container converted on this card is readable by libref and by `rad-convert` on any other + * card. The one plane that keeps libref's permutation is `quant_act_i8`'s, whose order is part of + * what the op means -- see the row. + */ +{ "quant_act_fp8_bf16", "quant_act_fp8", "quant", + "symmetric per-(row, group) E4M3: scale = amax * (1/448), the codes the value times 1/scale", + "group 128; n a multiple of 4; a wave covers four columns a lane, so a group is a quarter-wipe", + "bf16 in, fp8_e4m3 codes, f32 scales", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_fp8, nullptr, nullptr, nullptr, + r3d_shape_quant_act_fp8 }, + +/* The per-row int8, in libref's step order. The order is the op's, not the kernel's convenience: + * the codes are the WMMA A-fragment's, and the plane is what the oracle compares, so this row keeps + * the permutation and the kernel's store address carries it. libr3d's own int8 GEMM reads the + * row-major `quant_act_i8g` plane two rows below, which is the pairing libref's comment states; a + * gfx11 card has no consumer for the step-ordered plane and serves the op so an architecture that + * emits it resolves to a kernel here rather than to the reference. */ +{ "quant_act_i8_bf16", "quant_act_i8", "quant", + "symmetric int8 with one scale per row: scale = max(amax, 1e-8) / 127, ties to even, saturating", + "n a multiple of 16, a whole WMMA step; a wave a row of the row sums; the codes stored in the " + "step order, the middle two dwords of every 16 bytes exchanged", + "bf16 in, i8 codes, f32 scale per row and the group-major row sums", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_i8, nullptr, nullptr, nullptr, + r3d_shape_quant_act_i8 }, + +{ "quant_act_i8g_bf16", "quant_act_i8g", "quant", + "symmetric per-(row, group) int8: scale = amax / 127, 1 for an all-zero group, ties to even", + "group 128; n a multiple of 4; a wave covers four columns a lane, so a lane's codes are one " + "dword and a wave's are 128 contiguous bytes", + "bf16 in, i8 codes row-major, f32 scales", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantI8g), NOTUNE, + nullptr, nullptr, r3d_rad_quant_act_i8g, nullptr, nullptr, nullptr, + r3d_shape_quant_act_i8g }, + +{ "gated_quant_fp8_bf16", "gated_quant_fp8", "quant", + "silu(gate) * up over a fused [M, 2n] projection, quantised in the same pass", + "group 128; n a multiple of 4; the product is rounded to bf16 before its amax, as every fused " + "implementation rounds it", + "bf16 gate_up in, fp8_e4m3 codes, f32 scales, optional bf16 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGateQuant), NOTUNE, + nullptr, nullptr, r3d_rad_gated_quant_fp8, nullptr, nullptr, nullptr, + r3d_shape_gated_quant_fp8 }, + +{ "dequant_fp8", "dequant", "quant", + "E4M3 code times its group's f32 scale", + "group 128; n a multiple of 4", + "fp8_e4m3 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +{ "dequant_e5m2", "dequant", "quant", + "E5M2 code times its group's f32 scale", + "group 128; n a multiple of 4", + "fp8_e5m2 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantE5), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +{ "dequant_i8", "dequant", "quant", + "int8 code times its group's f32 scale", + "group 128; n a multiple of 4", + "i8 codes and f32 scales in, bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDequantI8), NOTUNE, + nullptr, nullptr, r3d_rad_dequant, nullptr, nullptr, nullptr, r3d_shape_dequant }, + +/* ------------------------------------------------------------------ r3d_gemm_bf16_nt_m16.hip + * + * The decode GEMM: M is 1 to 16, so a wave owns a run of N columns and streams the weight's rows + * past an activation kept in registers. There is no fragment layout to fill, which is why this + * kernel reads the checkpoint's rows in order. + */ +{ "gemm_nt_bf16_m16", "gemm_nt", "gemm", + "a[M,K] @ b[N,K]^T for the decode and verify heights, f32 accumulate, one narrowing at the store", + "M <= 16; a wave a run of N columns, one output element a lane, k ascending in pairs; split-K " + "over scratch with the partials reduced in split order; a ragged K runs the scalar tail at sk=1", + "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " + "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " + "further. bf16 reaches the dot as f16, exact over f16's normal range, which every checkpoint's " + "weights and activations live inside", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_M16, + ROW(cGemmM16), tGemmM16, NELEM(tGemmM16), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_bf16_m16, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip + * + * The same shape against a block-scaled weight. The codes are E4M3, widened to f16 exactly and + * accumulated by dot2; the block scale is applied once per 128-element slab, after the slab's + * products, which is where the reference applies it. + */ +{ "gemm_nt_q_fp8a16_m16", "gemm_nt_q", "gemm", + "a[M,K] @ b[N,K]^T against E4M3 codes with a scale per 128x128 block", + "M <= 16, K a multiple of the block, group = pb2 = 128 and pb1 the rows sharing a scale row; a " + "wave a run of N columns; the codes widened to f16 exactly and the block scale applied after each " + "slab; a split ends on a block boundary (gemm_tune_valid)", + "bf16 a, fp8_e4m3 b, f32 b_scale, bf16 y, fp32 accumulation; an f32 a, a bf16 scale plane, a " + "ragged last block and the zero-point planes a_sum and b_ref are refused, not approximated", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFp8a16), tGemmQ, NELEM(tGemmQ), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_fp8a8_m16", "gemm_nt_q", "gemm", + "quant_act_fp8's codes and scales against E4M3 codes with a scale per 128x128 block", + "M <= 16, K a multiple of the block; both axes coded, so both scales apply", + "fp8_e4m3 a and b, f32 scales on both, bf16 y, fp32 accumulation", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFp8a8), tGemmQ, NELEM(tGemmQ), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_mxfp4a8_m16", "gemm_nt_q", "gemm", + "fp8 a against OCP-MXFP4 weights: e2m1 codes, two a byte, with an e8m0 scale per 32 of K, the " + "block's partials scaled and summed in ascending k", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane, the lane's two 32-blocks " + "scaled at the block boundary", + "fp8_e4m3 a with an f32 scale per (row, 128 of K), fp4_e2m1 codes with an e8m0 scale per (row, " + "32 of K) -- `b_ref`, the same exponent plane, is accepted and ignored, bf16 y, fp32 " + "accumulation; a reserved e8 (0, 255) is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQMxfp4a8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, + +{ "gemm_nt_q_w4a8_m16", "gemm_nt_q", "gemm", + "the symmetric 4-bit weight grid at decode: signed int4 codes against int8 activations, the " + "group's integer sub-sum scaled once by the activation's row scale and the weight's group scale", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane from two 16-byte loads, " + "the pair fold at the group boundary, the group terms scaled in the epilogue", + "I8 a in the step order with an f32 scale per row, I4 codes b (two a byte) with an f16 scale " + "per (row, 128 of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, " + "and the store is the only narrowing; no zero point, so no a_sum", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQW4A8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w4a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w4a8 }, + +{ "gemm_nt_q_w8a8_m16", "gemm_nt_q", "gemm", + "the symmetric 8-bit weight grid at decode: signed int8 codes against int8 activations, the " + "group's integer sub-sum scaled once by the activation's row scale and the weight's group scale", + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane from four 16-byte loads, " + "the pair fold at the group boundary, the group terms scaled in the epilogue", + "I8 a in the step order with an f32 scale per row, I8 codes b with an f16 scale per (row, 128 " + "of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, and the store is " + "the only narrowing; no zero point, so no a_sum; M > 16 is declared out", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQW8A8M16), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w8a8_m16, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w8a8 }, + + { "silu_mul_bf16", "silu_mul", "elem", + "silu(gate) * up over one fused gate_up plane, the gate the first half", + "any n; a workgroup a row; the activation is NOT narrowed before the product, as ref's is not " + "-- act_mul narrows it, over two operands, because the pair it replaces stored it", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSiluMul), NOTUNE, + nullptr, nullptr, r3d_rad_silu_mul, nullptr, nullptr, nullptr, r3d_shape_silu_mul }, + + { "rmsnorm_quant_fp8_bf16", "rmsnorm_quant_fp8", "quant", + "residual add, RMS norm and the E4M3 quantiser in one pass: a 5120-element bf16 plane a token " + "is written once and read once inside one kernel, where the pair writes it and reads it back", + "group 128 and a multiple of 128; a workgroup a row; the residual sum is stored before the " + "variance reads it, so the norm is over the bf16 sum, and the codes are taken over the bf16 " + "normalised value, which out_bf16 receives", + "bf16 x, residual, gain and optional out_bf16, fp8_e4m3 codes, f32 scales, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRmsQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm_quant_fp8, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm_quant_fp8 }, + + +/* ------------------------------------------------------------------ r3d_sample_pre_f32.hip + * + * The sampler's pre-filters: one workgroup a row over the logits plane. The history stages are + * sparse -- a row's history is a few hundred tokens against a vocabulary of 130560, so the + * reference's own shape, walk the window and not the row, is the fast shape too. + */ +{ "sample_penalties_f32", "sample_penalties", "sample", + "presence, frequency and repetition penalties from the row's history, in place", + "a workgroup a row; the count is taken from the token's FIRST occurrence forward, and the " + "repetition penalty is sign-dependent -- v > 0 divides, v < 0 multiplies -- as the reference has " + "it; a penalty of zero writes nothing", + "f32 logits, f32 params, i32 history; writes only inside the row's own n_vocab columns", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_penalties, nullptr, nullptr, nullptr, + r3d_shape_sample_penalties }, + +{ "sample_dry_f32", "sample_dry", "sample", + "the DRY penalty: a suffix of the history that repeats after a token penalises it, by its length", + "a workgroup a row; the longest repeat per token, capped at dry_allowed_length; the multiplier " + "grows by repeated multiply and stops at FLT_MAX/base, which is where an exponent would overflow; " + "one penalty per token, from its longest repeat, and the FIRST occurrence is the one written", + "f32 logits, f32 params, i32 history, u8 breakers; a breaker position ends a sequence and is " + "never penalised; a history no longer than dry_allowed_length penalises nothing", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_dry, nullptr, nullptr, nullptr, + r3d_shape_sample_dry }, + +{ "sample_ngram_ban_f32", "sample_ngram_ban", "sample", + "the n-grams the history shows inside the window are banned to -inf", + "a workgroup a row; the prefix compare over n-1 tokens, the ban landing on s[idx+n-1]; the " + "whitelist is removed from the banned set BEFORE the ban, so an exempt id survives; the window is " + "dry_penalty_last_n, and n = 0 bans nothing", + "f32 logits, f32 params, i32 history, i32 n-gram pairs, an optional i32 whitelist plane", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_ngram_ban, nullptr, nullptr, nullptr, + r3d_shape_sample_ngram_ban }, + +{ "sample_mask_f32", "sample_mask", "sample", + "the grammar's and the tool-caller's doing: every id whose bit is clear becomes -inf", + "a workgroup a row over 4080 words at this vocabulary; a word of all ones is skipped and the last " + "partial word honours n_vocab; a NEGATIVE mask_row skips the row, which is how an unconstrained " + "request ends up with no mask applied -- the descriptor calls the same thing " + "a shared row, and the body is the spec; the bound is the bitmask plane's own row count, not M, " + "so a row addressing the plane's second half is masked as the reference masks it", + "f32 logits, f32 params, i32 bitmask; a plane with fewer rows than the logits is refused " + "(RAD_E_SHAPE), the case the geometry never produces", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_mask, nullptr, nullptr, nullptr, + r3d_shape_sample_mask }, + +{ "sample_logprobs_f32", "sample_logprobs", "sample", + "the row's summary for the response: max, the sum of exp, and the k best (id, logit) pairs", + "one read of the logits plane where the reference reads it three (max, sum, k-list); the sum is " + "SUM exp(v - max) in DOUBLE, the reference's law, and a row's k-list is one insertion list in " + "registers, not an upper_bound per element; stats is [M][2 + 2k], and rows the flag leaves alone " + "are not written", + "f32 logits, f32 params, f32 stats; k <= 64 is the pool's depth and above it the shim refuses " + "(RAD_E_UNSUPPORTED); on a row that contains a NaN the reference's list freezes at the first k it " + "saw, because upper_bound over a NaN returns end and every later compare then fails -- this kernel " + "reports the row's true k-best, a divergence a plane has to be fed NaNs to reach", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleLogprobs), NOTUNE, + nullptr, nullptr, r3d_rad_sample_logprobs, nullptr, nullptr, nullptr, + r3d_shape_sample_logprobs }, + + +/* ------------------------------------------------------------------ r3d_attn_paged_h128.hip + * + * Paged attention, head_dim 128, banded on q_len. The two kernels share the block walk and differ + * in what a workgroup is: decode is one head group over 16 query rows with split-KV, prefill stages + * a 16-token query tile. The walk's block bounds are the WORKGROUP's -- a tile is staged once into + * LDS and every wave of the workgroup consumes it, and waves that narrowed the walk to their own + * query positions would stage different blocks over the same LDS, the last writer per 16-byte chunk + * winning. + */ +{ "attn_paged_bf16_decode", "attn_paged", "attn", + "paged attention over a bf16 cache: one head group a workgroup, 16-token tiles, split-KV", + "head_dim 128; q_len <= 16; two passes over the blocks -- scores are recomputed in the second so " + "the softmax sum accumulates ascending like the reference, and a masked key is never exponentiated; " + "the block bounds come from the workgroup's 16 rows, because the staged tile is shared", + "bf16 q and out, bf16 cache, i32 block_table and seqused; a descale on a bf16 cache is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_DECODE, + ROW(cAttnBf16Decode), NOTUNE, + nullptr, nullptr, r3d_rad_attn_decode_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_bf16_prefill", "attn_paged", "attn", + "the same walk over a 16-token query tile, for a chunk that is wider than the decode bucket", + "head_dim 128; q_len >= 17; a workgroup is 4 waves over 16 query rows and one KV head; the tile's " + "idle lanes clamp to the last query row instead of reading past the q plane", + "bf16 q and out, bf16 cache, i32 block_table and seqused", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, + ROW(cAttnBf16Prefill), NOTUNE, + nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_fp8_decode", "attn_paged", "attn", + "paged attention over an E4M3 cache, the descale riding the widening into the tile", + "head_dim 128; q_len <= 16; a 16-code chunk is the aligned 16-byte unit -- eight codes are 8 bytes " + "and a 16-byte load at a slot's odd half returns garbage; the descale " + "multiplies into the f16 tile, exact for a power-of-two scale inside f16's range", + "bf16 q and out, fp8_e4m3 cache, i32 block_table and seqused, f32 k_descale and v_descale " + "optional (absent is scale 1.0)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_DECODE, + ROW(cAttnFp8Decode), NOTUNE, + nullptr, nullptr, r3d_rad_attn_decode_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + +{ "attn_paged_fp8_prefill", "attn_paged", "attn", + "the E4M3 cache over a 16-token query tile", + "head_dim 128; q_len >= 17; the same staged walk as the bf16 prefill, with the codes widened as " + "they land in the tile", + "bf16 q and out, fp8_e4m3 cache, i32 block_table and seqused, f32 descales optional (absent is " + "scale 1.0)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, + ROW(cAttnFp8Prefill), NOTUNE, + nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + r3d_shape_attn_paged }, + + +/* ------------------------------------------------------------------ r3d_sample_f32.hip + * + * The sampler's spine: the row's top-R, and the stages that turn the top-R's candidate plane into + * one token. The candidate set is the contract between them -- `cand_val` carries LOGITS, so each + * narrowing stage takes its own softmax and the stages compose in any order; a dropped candidate is + * `cand_idx` -1 and `cand_val` -inf; the set is descending by value then ascending by id; and every + * stage leaves a greedy row byte-identical, because a greedy row's token is `sample_argmax`'s. + * `topk_next` is a sort by (-value, +column) wearing a loop -- the rule `v == *pv && i <= *pi` is + * "the next one in a run of equal values" -- so one pass keeping the best R returns the reference's + * R pairs, in its order, with its tie-breaks to the lower column. + */ +{ "row_topk_bf16", "row_topk", "moe", + "the row's top R, with the reference's tie-breaks, in one scan of the row", + "one pass keeps the best R in the reference's order, where the reference scans the row R times; " + "R beyond a pass's pool rescans with the chain's state carried, so the answer is the reference's " + "at any R and only the time grows; a slot a short row cannot fill is idx -1 and val -inf; a row " + "that opens with a NaN reports (0, NaN) R times, because the reference's seed takes the first " + "element it sees and nothing displaces a NaN", + "bf16 x, i32 idx [M,R], f32 val [M,R], an optional f32 pairs [M,R,2] (the id's bits and the value)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRowTopkBf16), NOTUNE, + nullptr, nullptr, r3d_rad_row_topk, nullptr, nullptr, nullptr, r3d_shape_row_topk }, + +{ "row_topk_f32", "row_topk", "moe", + "the row's top R over an f32 plane, in one scan", + "the same one-pass insertion as the bf16 row; the band's router row costs the reference 7.0 GB of " + "scans and this kernel 468 MB, and at the band it is the sifts that cost, not the bytes: the f32 " + "plane moves half again the traffic for the same 23 ms", + "f32 x, i32 idx, f32 val, optional f32 pairs", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRowTopkF32), NOTUNE, + nullptr, nullptr, r3d_rad_row_topk, nullptr, nullptr, nullptr, r3d_shape_row_topk }, + +{ "sample_argmax_f32", "sample_argmax", "sample", + "the greedy token: the row's argmax, ties to the lower id", + "a workgroup a row; the max is a strict `>`, so a NaN is never adopted -- the reference's scan " + "keeps the first element it sees, which is why a row opening with a NaN yields token 0, and a row " + "of all -inf yields 0; the stage that reads no scalar at all, so a missing params operand is not " + "a refusal: the reference describes the operand and does not read it", + "f32 logits, i32 token [M]; the params plane is described, not read", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_argmax, nullptr, nullptr, nullptr, + r3d_shape_sample_argmax }, + +{ "sample_temp_f32", "sample_temp", "sample", + "temperature, in place: every logit multiplied by the reciprocal of temp", + "a workgroup a row; a row is skipped when temp is not positive or is exactly 1; the reciprocal is " + "formed ONCE, as the reference forms it, not a divide per element -- a divide per element is a " + "different f32, and the argmax after it is only bit-exact under the transcription", + "f32 logits INOUT, f32 params; the most expensive row in the slice at 11 ms a step, and the cost " + "is the plane: 1 GiB in and 1 GiB out for one multiply an element", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_temp, nullptr, nullptr, nullptr, + r3d_shape_sample_temp }, + +{ "sample_topk_f32", "sample_topk", "sample", + "the candidate set the rest of the sampler draws from, written whole every step", + "the set's width is the BUFFER's, not the row's: top_k 40 in a 1024-wide plane is 40 candidates " + "and 984 holes, and a stale candidate left in a hole is a token the pick can draw; the row's " + "top_k only narrows inside the width, and `<= 0` or a width above it takes the whole width, as " + "the reference clamps; cand_val carries the LOGIT, which is what lets the narrowing stages " + "compose in any order; a greedy row takes none", + "f32 logits, f32 params, i32 cand_idx [M,n_cand] (local columns), f32 cand_val, an optional i32 " + "pairs [M,2*n_cand] of (global id, logit bits) with 0xffffffff for a hole; n_cand <= 1024", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleF32), NOTUNE, + nullptr, nullptr, r3d_rad_sample_topk, nullptr, nullptr, nullptr, + r3d_shape_sample_topk }, + +{ "sample_pick_f32", "sample_pick", "sample", + "the draw: one uniform over the candidate set's own softmax, in index order", + "splitmix64 over the seed and the position, the top 24 bits over 2^24, keyed by the pick's own " + "key; the exps are computed by the wave in parallel and the CDF accumulates on one lane in " + "candidate index order, because the order is the law -- parallel values, serial sums; an empty " + "set writes -1; a set whose mass falls below u falls back to the last candidate above -infinity, " + "which is why a masked tail is never the fallback", + "i32 cand_idx, f32 cand_val, f32 params (seed, pos), i32 token [M]; only token is written", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_pick, nullptr, nullptr, nullptr, + r3d_shape_sample_pick }, + +{ "sample_topp_f32", "sample_topp", "sample", + "nucleus: the shortest prefix whose cumulative probability reaches top_p", + "the stage takes its own softmax over the set (max by strict `>` over live candidates, then exp, " + "then the predicate), because the set carries logits; at least one candidate survives; it is a " + "PREFIX rule in the set's order, which is why the set's order is contract and why no stage sorts " + "it", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when top_p is out of range; a greedy row " + "and an all-holes row are left alone", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_topp, nullptr, nullptr, nullptr, + r3d_shape_sample_topp }, + +{ "sample_minp_f32", "sample_minp", "sample", + "min-p: drop what is below p times the best candidate's probability", + "the stage's own softmax again; the best always survives; a relative cut under the best, not a " + "prefix, so it composes with top-p in either order", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when min_p is out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_minp, nullptr, nullptr, nullptr, + r3d_shape_sample_minp }, + +{ "sample_typical_f32", "sample_typical", "sample", + "locally typical: drop the candidates whose surprisal is furthest from the set's entropy", + "the set's entropy from the same exps, the kept mass overshooting p by design and not depending " + "on the order, ties kept -- a stage that sorted the set would genuinely disagree with the schema", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when typical_p is out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_typical, nullptr, nullptr, nullptr, + r3d_shape_sample_typical }, + +{ "sample_xtc_f32", "sample_xtc", "sample", + "the exclusion of top candidates: a coin, then drop all but the least likely of the clearers", + "its own coin (the seed keyed by XTC) decides whether the stage fires at all; when it fires it " + "drops every candidate at or above the threshold EXCEPT the least likely of them, and does nothing " + "when fewer than two clear it -- a stage that dropped unconditionally would fire on 100% of steps", + "i32 cand_idx INOUT, f32 cand_val INOUT, f32 params; off when the probability or the threshold is " + "out of range", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cSampleCand), NOTUNE, + nullptr, nullptr, r3d_rad_sample_xtc, nullptr, nullptr, nullptr, + r3d_shape_sample_xtc }, + +/* ------------------------------------------------------------------ r3d_dflash_f32.hip + * + * The speculative decoder's accept step. It is a gather, not arithmetic: two 63.8 MiB codebooks, a + * walk gathering `M * steps * rank` elements, so the score's rank sum is one lane's serial chain -- + * there is nothing to hide the gather behind, and a tree would be a different sum for no gain. + */ +/* ------------------------------------------------------------------ r3d_gemm_nt_q_w2a8.hip + * + * `output.weight`: U2 codes, int8 activations, one f32 scale per activation ROW (ZP_I8_ROW), and a + * joined `b_scale` the container writes as two planes -- scale f16 and zero u8 -- behind one operand + * that only a layout hook can present. libref's shape hook declines the dtype for exactly that + * reason, so kbench has no case for the band: the row's opd_shape is null, which is the tool's + * named skip, and the joined plane is built with rad_planes_relayout, the same builder the driver + * uses. + * + * Exactness, measured and not assumed: `v_fdot2_f32_f16` carries ~22 bits of mantissa on integer + * operands, not 24, so an integer dot through it is inexact above 2^20 (71027 of 262144 sampled dots + * at bias 1024, worst |err| 0.125; 70115 and 0.015625 at bias 128). The bias is 128 because the + * error's ratio to the magnitude is ~2^-22 and shrinking the bias shrinks the tail. The result is + * that 0.1-0.2% of outputs land one bf16 ulp off the reference: rel_l2 5.0e-3 at the band, + * max_abs 9.8e-4, no non-finite anywhere. This row is NOT bit-exact by construction, and the dot + * probe in the unit is the check that states it. + * + * M <= 16 is decode. 46 of these per token, 135 GFLOP a token of CPU work that the host row puts on + * the card at 3.0-4.2 ms (66.8 MB of codes at the card's 22 GB/s is the floor; the warm-L2 run is + * 2.43 ms at 30 GB/s). + */ +{ "gemm_nt_q_w2a8_m16", "gemm_nt_q", "gemm", + "the vocab projection at decode: 2-bit codes, int8 activations, the zero removed with a_sum", + "a wave takes one weight row; lane l owns group l&15 and half of it, 64 codes to a 16-byte load, " + "the pair (l, l^16) folding the group in one shuffle; lanes 0..15 hold the per-group terms and " + "lane 0 sums the groups in ascending order in one accumulator, which is the reference's order. " + "The codes widen to f16 through a bias of 128, so the dot's integer answer comes back with " + "B*sum(a) on it and a_sum -- group-major, the reference's own 16-row pad -- removes it", + "U2 codes b, I8 activations a, f32 a_scale (one per row), the joined b_scale (f16 scale + u8 zero " + "as rad_planes stores them), f32 a_sum, bf16 y. fp8a8, fp8a16 and w4a8 take their own rows; a zero " + "plane stored sub-byte (U2/U4/U5) is refused, not approximated -- the bit-extract path is 10 lines " + "of rad_load_bits and is not written; M > 16 is refused, prefill's vocab is logits_gemm", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cGemmQW2A8), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8, nullptr, + r3d_layout_gemm_nt_q_w2a8, r3d_relayout_gemm_nt_q_w2a8, nullptr }, + +{ "gemm_nt_q_w2a8_tiled", "gemm_nt_q", "gemm", + "the packed-code grids at the heights the skinny row declines: 2-bit and 4-bit codes, int8 " + "activations, the batched decode and the draft head of a 2-bit vocab projection", + "the same 128x128 tile as the fp8a8 arm, with the codes unpacked on the way into LDS -- 8 codes " + "from a 4-byte load at U2, 16 from a 16-byte load at U4 -- and the epilogue folding " + "(code - zero) * scale per staged element, so the dot runs over values and no a_sum term is " + "reduced: the zero comes off term by term, which is why Σ a(q-z) needs no Σ a here while the m16 " + "row needs it to lift the integer bias off its f16-as-int dot. The row's scale and zero are one " + "per ROW on a {1, group} plane, so the staging reads 128 scalars a chunk where the fp8a8 arm reads " + "one, at the row the grid puts it; issued one chunk ahead of the fold that consumes them, because " + "a scalar load with nothing to overlap it is the whole band (210.8 ms against 2.396 ms with the " + "answer hoisted, the same output bits). r3d_tiling.h's swizzle is shared, proven byte-identical", + "M <= 16 is gemm_nt_q_w2a8_m16's by its declared C_LE(\"M\", 16); fp8a8 and fp8a16 take their own " + "rows, and the fp8a8 arm refuses a band carrying a_sum at its own line -- a row that silently " + "ignores a band operand passes a checkpoint whose a_sum is garbage. A zero plane stored sub-byte " + "(U2/U4) is refused and named, not approximated: rad_load_bits is the ten-line fix and it is " + "written for the codes, not the zero. Measured, VRAM: M=64 N=130560 K=2048 w2a8 24.151 ms, 1417 " + "GFLOP/s, 3.7 GB/s useful against a 0.449 ms read floor of the 73.1 MB operand -- at kKC=32 a " + "staged chunk draws 8 bytes from a row of pitch 512, so the band moves 8x the bytes it uses and " + "the lever is a wider k-chunk, not more loads in flight (the codes lead measured 0.6%, " + "bit-identical)", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cGemmQW2A8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w2a8_tiled, nullptr, + r3d_layout_gemm_q_fp8_weight, r3d_relayout_gemm_q_fp8_weight, r3d_shape_gemm_nt_q }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a8_gated.hip + * + * The gate couples column i to column n+i, so a lane owns both dots and the coupling costs no extra + * weight traffic; the block is one group by 256/group rows so the group's amax closes in-block, + * which is also why there is nothing to tune (the block shape is the quantiser's rule, not a knob) + * and why the row keeps its M ceiling in the prose. At the band's own numbers this is ~341 GFLOP/s + * at M=64 -- 0.7% of the card's fp8 peak, 46 of these per forward pass -- and it is still the row + * the model wants, because the alternative it replaces is the reference's host GEMM: the same 3.2 + * GFLOP per layer on the CPU, which is 135 GFLOP a token for this checkpoint. + */ +{ "gemm_nt_q_gated_fp8a8", "gemm_nt_q_gated", "gemm", + "the gated MLP band's GEMM, its gate and its output quantiser in one launch", + "a block is one 128-wide group by 256/group rows, so the group's amax closes in-block: wave max " + "then an LDS fold over the lanes that share a group. The gate couples column i to column n+i, so a " + "lane owns both dots and the coupling costs no extra weight traffic. No [M,N] bf16 intermediate " + "exists: the row is narrowed, gated and coded from registers, which is why there is no scratch and " + "no second pass. The narrowing matches the unfused chain -- both halves bf16 before the gate, the " + "activation NOT narrowed before the product, the product formed in f32 then narrowed -- so the " + "codes are the codes the chain would have written, byte for byte at the band", + "fp8_e4m3 a and b, f32 a_scale, bf16 b_scale (f32 accepted and equal bit for bit; fp8a8f32 is a " + "different dtype and takes no row here), f32 scale, E4M3 q, bf16 out_bf16 optional; f32 " + "accumulation with -ffp-contract=off; f16x4 dot pairing, the code widening exact. M > 64, N odd, K " + "% group != 0, group outside {32,64,128,256} or wider than n, sk > 1 and an absent act are refused, " + "not approximated", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmGated), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_gated, nullptr, nullptr, nullptr, + r3d_shape_gemm_nt_q_gated }, + +{ "dflash_select_bf16", "dflash_select", "draft", + "DFlash2's greedy walk over the candidate lattice, one lane a (sequence, candidate) pair", + "score[l][c] = unary[l][c] + SUM_r pred[pid(l)][r] * hp[l][r] * succ[cand[l][c]][r], the rank sum " + "ascending in r in f32 with ax[r] = pred * hp rounded to f32 BEFORE it meets succ, because the " + "reference writes it to a float array first; argmax strict `>` over c ascending, so the earliest " + "candidate wins a tie and a NaN never takes the lead; pid(0) is the anchor at m * anchor_stride " + "and pid(l) the walk's own previous pick, so the steps loop is serial with the two LDS round " + "trips its dependence requires; hp absent is a plane of ones; a predecessor outside the vocabulary " + "contributes zero and a candidate outside it is scored by unary alone, which is what makes a " + "shard's padding rows legal input", + "bf16 codebooks (pred, succ, optional hp) with contiguous rows, f32 unary, i32 cand, anchor and " + "tokens; pitched rows served on cand, unary, tokens and hp, a row stride INSIDE a codebook row " + "refused (RAD_E_STRIDE); top_k > 256 refused (RAD_E_UNSUPPORTED); a cand plane describing more " + "sequences than the band's M is refused, not truncated", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cDflashSelect), NOTUNE, + nullptr, nullptr, r3d_rad_dflash_select, nullptr, nullptr, nullptr, + r3d_shape_dflash_select }, + +/* ------------------------------------------------------------------ r3d_vocab_bf16.hip + * + * The head is the largest read in a decode step -- 510 MiB at this checkpoint's 130560 x 2048 -- and + * the sampler reads f32, which is why the store is typed rather than narrowed and why a prefill band + * writes 1.07 GB. Measured on the card: 3.29 ms a token at M=1 (163 GB/s of the head), 0.507 ms a + * token at M=16 (the head read once for sixteen rows), 269 ms for a 2048-token prefill at 4067 + * GFLOP/s. Against the reference's law the f32 plane is 1.77e-6 in rel_l2, which is ~30 f32 ulps at + * K=2048 and is the pair-dot folding two products into one rounding -- measured identical against + * the same law with the operands widened to f16 first, so the widening contributes nothing and the + * head's own bf16 quantisation (4.9e-4 an element) is 300x coarser than the row. + */ +{ "logits_gemm_bf16", "logits_gemm", "vocab", + "logits[M, n_vocab] = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T, the head read once a token", + "M <= 16: a wave a run of vocabulary columns, one output element a lane, the head's rows streamed " + "past an activation kept in registers, no wave reduction. M > 16: 128x128 tiles through LDS, 8x8 " + "f32 accumulators a lane, the head staged with an 8-element swizzle, k ascending in 32-code " + "chunks. The grid is vocab-wide at every M, so there is no split-K and no scratch", + "bf16 x, f32 logits: every sampler stage reads f32, so the narrowing the schema does not ask for " + "is not performed, and a prefill band's output plane is M x n_vocab f32. The head arrives in the " + "form the container stores and the row reads both, chosen by the operand's header, not by a " + "parameter: bf16 rows in the order they are stored, or -- what this checkpoint's output.weight " + "actually is -- E4M3 codes with a bf16 scale per 128x128 block as two container planes, which the " + "row's layout hook presents as the one operand the plan says they are, moving no byte. E4M3 and " + "int8 widen to f16 exactly, so the fold into f16 is the only arithmetic the codes pay: 2.77e-04 " + "from the reference's exact law, one f16 rounding, 250x finer than the code's own quantum. A head " + "with a zero plane is w2a8's grid and is refused at the shim's own line; so is a scale block that " + "is not 128x128, which is gemm_nt_q's grid", + RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, + ROW(cLogitsGemm), NOTUNE, + nullptr, nullptr, r3d_rad_logits_gemm_bf16, nullptr, + r3d_layout_logits_head, r3d_relayout_logits_head, r3d_shape_logits_gemm_bf16 }, + +/* ------------------------------------------------------------------ r3d_gemm_fp8a8_tiled.hip + * + * The prefill projection: this checkpoint declares 176 of these a forward pass (44 of qkv, 44 of + * the gated MLP's 12288 columns, 44 of o, 44 of the 2048-wide one, three of the drafter at + * K=10240), and the reference does their 135 GFLOP a token in a host loop. + * Measured at the graph's own bands, weights in VRAM: 28.171 ms at N=12288 K=2048 (3659 GFLOP/s), + * 14.699 at N=2048 K=6144, 5.911 at N=2560, 4.381 at N=2048 K=2048, 29.798 at N=2048 K=10240 -- + * 27 to 36% of the card's dense f16 peak against a byte floor of 0.051 to 0.257 ms. These are the + * first bands in this library where the dot, not the wire, is the limit, and it is the reason the + * E4M3 decoder is a table: at the tile's densities the decode ALU is on the critical path. + */ +{ "gemm_nt_q_fp8a8_tiled", "gemm_nt_q", "gemm", + "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the group sub-sum from the raw codes and one " + "scale per group, which is the reference's law and the reason the codes are never pre-scaled", + "128x128 tiles through LDS, 64 f32 accumulators a lane, k in 32-code chunks, the family's 8-element " + "XOR swizzle on the staged rows; both sides decode through the block's 512-byte E4M3->f16 table " + "and leave staging as f16 with their scale folded in -- a_scale per staged row, b_scale one scalar " + "per tile, because the tile's 128 columns are exactly the scale plane's row extent and 32 divides " + "128. One accumulator, no per-group partials, 237 VGPRs and no spill", + "E4M3 codes both sides, f32 a_scale per (row, group of 128), bf16 b_scale per 128x128 block -- the " + "container's own block; a {1,group} scale block is w2a8's grid and is refused, as is a zero plane " + "and an a_sum, fp8a8 being symmetric. y bf16 with one narrowing at the store, and at a bf16 output " + "the store's ulp (3.9e-3) is the binding floor, not the fold's (9.8e-4 of the quadrature scale): " + "83% of outputs are bit-exact, 99.93% land within the fold plus one store ulp, none beyond. The " + "fold is v_mul_f16, never f16x2_pack, which rounds toward zero and flushes subnormals", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQFP8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_fp8_tiled, nullptr, + r3d_layout_gemm_q_fp8_weight, r3d_relayout_gemm_q_fp8_weight, r3d_shape_gemm_nt_q }, + +{ "gemm_nt_q_mxfp4a8_tiled", "gemm_nt_q", "gemm", + "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the weight in OCP MXFP4: e2m1 codes, two a " + "byte, one e8m0 scale per 32 of K; the 32-block partial scales at the block boundary and the " + "blocks sum in ascending k", + "128x128 tiles through LDS, 64 f32 accumulators a lane for the block partials and 64 more for the " + "running sum, k in 32-code chunks -- one OCP 32-block a chunk -- the family's 8-element XOR " + "swizzle on the staged rows; the codes unpack to e4m3 through eight fixed magnitude bytes and " + "decode through the block's 512-byte table, a_scale folded per staged row, the e8 read at " + "staging and held in registers for the flush", + "E4M3 a with an f32 scale per (row, 128 of K), fp4_e2m1 codes with an e8m0 scale per (row, 32 " + "of K) -- `b_ref`, the same exponent plane, is accepted and ignored, bf16 y, fp32 accumulation. " + "The e2m1 magnitude is exact in e4m3, the code products are " + "exact in f16, the 32-block partial scales by a power of two in f32, and the store is the only " + "narrowing; a reserved e8 (0, 255) is refused", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, + ROW(cGemmQMxfp4a8Tiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_tiled, nullptr, + nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, + +/* The same tiling on gemm_nt's operands, the prefill projection the reference runs on the host: at + * M=2048 this checkpoint's q/k/v/o and the MLP's up/down are 135 GFLOP a token of f32-accumulating + * bf16, and the reference does them on the CPU. The exactness is the m16 row's, because it is the + * same dot. */ +{ "gemm_nt_bf16_tiled", "gemm_nt", "gemm", + "a[M,K] @ b[N,K]^T at prefill heights, f32 accumulate, one narrowing at the store", + "128x128 tiles through LDS, 8x8 f32 accumulators a lane, k ascending in 32-code chunks, the " + "partials closed in the tile; M <= 16 stays with gemm_nt_bf16_m16, whose wave-per-run-of-columns " + "shape is the right one there -- the two rows' M ranges are complements, so neither competes for " + "the other's band", + "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " + "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " + "further. 99.93% bit-exact measured at the 512-column twin, 100% within two ulps", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, + ROW(cGemmNTTiled), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr, + nullptr, nullptr, r3d_shape_gemm_nt }, + +}; + +/* ================================================================== the exports + * + * The two every plugin must export, the four that make a kernel library, and `rad_kernel_concurrent`. + * + * libr3d exports no `rad_kernel_chain`: chaining replaces the queue's ordering bit between two + * dependent launches with a spin in the kernel, and it pays where a wave is idle during that spin. + * Nothing here is built as a chained form, so the answer would be 0 for every row; the symbol is + * left out, which is the same answer with one less thing to keep in step (ABI, + * `rad_kernel_chain`: "without the symbol, or with 0, the engine never asks"). + * + * It exports no `rad_kernel_collective` either: there is no second rank in this plugin's world. The + * cards that run these rows are single-GPU cards, and an all-reduce over the PCIe x1 slot most of + * them sit in is slower than sending the bytes through the host. + */ +extern "C" int rad_kernel_count(void) { + return (int)(sizeof(kKernels) / sizeof(kKernels[0])); +} +extern "C" const RadKernelInfo* rad_kernel_at(int i) { + if (i < 0 || i >= rad_kernel_count()) return nullptr; + return &kKernels[i]; +} + +/* Which rows touch nothing but their operands and the scratch they were handed. + * + * The elementwise, norm, quant, cast, rope, cache and gather rows do: one launch, one pass, no + * state between launches, so two of them may run at once and the engine can start a row before an + * independent earlier one finishes. + * + * The GEMM rows do not, and the reason is the scratch, not the kernel. The scratch arena belongs to + * the op instance, so two layers' decode GEMMs launched at the same time share it: a split-K row's + * partials and arrival counters from the two launches would land on each other. With sk = 1 a GEMM + * launch has no partials and is safe, but the promise is per row and the axis is chosen per + * geometry, so the row states the worst case. When split-K is off on a given card (a tuned point of + * sk = 1 for every shape), the loss is one overlap the engine would have taken. + */ +extern "C" int rad_kernel_concurrent(int i) { + const RadKernelInfo* k = rad_kernel_at(i); + if (!k) return 0; + return k->scratch == nullptr; +} + +static const RadPluginInfo kInfo = { + RAD_PLUGIN_KERNEL, + "libr3d", + "0.1.0", + "the RDNA3 (gfx11) kernel library: the elementwise, norm, rope, cache and embedding rows, fp8 " + "and int8 activation quantisation with its dequant and gated forms, and the skinny bf16 and " + "fp8a16 GEMMs, every one of them through v_dot2acc_f32_f16 because RDNA3 has no matrix " + "instruction a compiler will emit", + /* The architectures this build's code objects run on, spelled as `RadDeviceProps::arch`. The + * loader compares a device's arch against these words and warns once when the code object it + * picked names a card this list does not (`target_covers`), so the string has to be the build's + * real targets rather than an author's guess at them. + * RAD_GPU_TARGETS reaches this source as a compile definition from CMakeLists.txt; the fallback + * is the whole family, which is what a build that did not say is claiming. */ + R3D_BUILD_TARGET, +}; + +extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; } diff --git a/libr3d/r3d_sample_f32.hip b/libr3d/r3d_sample_f32.hip new file mode 100644 index 00000000..a9e2cda1 --- /dev/null +++ b/libr3d/r3d_sample_f32.hip @@ -0,0 +1,1314 @@ +/* r3d_sample_f32.hip -- the sampler: the two full-vocabulary reductions, the candidate set, the + * seeded draw and the four narrowing stages. + * + * The arithmetic is libref's, transcribed -- the reference's sampler is the law and the ORDER of + * its passes is the point. `abi/rad_sample.h` is the wire format: every scalar (`temp`, `top_k`, + * `top_p`, `min_p`, `typical_p`, `xtc_*`, `seed`, `pos`, the flags, the history window) is DATA, one + * 96-byte row per sampled position, because a parameter is geometry and frozen at declare, and two + * rows of one batch with different top_p must resolve to one kernel. `param_rows` below is that + * check, and it is the dtype check libref states: the plane is 32-bit words, and a 16-bit view + * passes a byte-count test and then misreads every row. + * + * ============================== what has to agree, and with what ============================== + * + * The draws must REPRODUCE, so the summation order is transcription and not performance: + * + * - A MAX is order-free and every max here is a strict `>`, which is also how NaN is kept out: + * libref's `if (v > mx) mx = v` over -infinity never adopts a NaN, and the butterfly merges with + * the same strict comparison, so a NaN in a row of logits cannot become the max anywhere. + * - A SUM of f32 is not order-free. libref's `sum` (the pick, the narrowing stages) runs + * over the candidates in INDEX order, and the CDF scan below it accumulates in index order too. + * So the exps are computed in parallel -- each is a separate value, order-free -- and the + * accumulation is serial on one lane, in index order, exactly as written. That is the whole + * design of the candidate kernels: parallel values, serial sums. + * - The draw is specified in the ABI, not left to a library: splitmix64 over + * `seed * 0x9E3779B97F4A7C15 + pos`, top 24 bits over 2^24. Integer arithmetic, so it is the + * same number here as on the host. Independent draws at one position are independent streams: + * the pick XORs the seed with RAD_SAMPLE_KEY_PICK (0), XTC's firing coin with RAD_SAMPLE_KEY_XTC. + * - `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and `(float)std::log((double)x)`, and + * they are transcribed as double calls rounded once to f32. There is no fp8-style hardware + * shortcut to take: an f32 exp2 (`v_exp_f32`) is a couple of ulps away, and a `u < cum` + * comparison sitting on an ulp boundary changes the drawn token, which is a fixture failure even + * when the distribution is right. Consumer RDNA3 fp64 is 1:64, so this is the slow path and the + * candidate set is where it shows: it costs time, not agreement. The device's + * `(float)exp((double)x)` and `(float)log((double)x)` are bit-identical to glibc's over + * a million points in [-100, 100] (0 of 2^20 differ), while `expf` differs from the host's + * `expf` in 5.7% of them by 1 ulp -- the double call is not only the law, it is the only one + * of the two that reproduces the recording. + * + * This is where the law is affordable, and it is why this file and the attention unit differ. Here + * the widest softmax is the candidate set: 1024 exponentials a row, 2 per lane, and the whole op is + * half a millisecond a step at the band. Attention at the prefill band is 17 M exponentials a layer + * on the same 1:64 fp64, and there the law cannot be paid, so that unit ships a 0.5-ulp polynomial + * and says so. A sampler that draws a different token than the recording is wrong at any speed, so + * this unit keeps the double call and the switch stays off. + * + * ============================== the top-k, and why it is one pass ============================== + * + * libref selects with `topk_next`: R scans of the row, each taking the largest + * value strictly below the last pick, ties to the LOWER column. Read as a whole that is a sort by + * (-value, +column), and the rule `v == *pv && i <= *pi` is exactly "the next one within a run of + * equal values" -- so one pass that keeps the best R by that order produces the same R pairs, in the + * same order, with the same tie-breaks. At the band's row (N=130560, R=16, bf16, M=1792) the + * reference scans the row sixteen times: 7.0 GB of traffic. This file scans it once: 468 MB. + * + * At the band (M=1792, N=130560, R=16) the one pass is 22.0 ms bf16, 22.4 ms f32, i.e. 21 GB/s and + * 42 GB/s: the same time for half the bytes, so the pass is not bound by the plane, it is bound by + * the accepted inserts (~55 sifts a lane at 510 elements a lane, POOL steps each). The traffic is 15x + * lower than the reference's and the headroom is in the insert, not in the load; a lane that filtered + * against a block-wide threshold instead of its own tail would take ~5 sifts a lane and land near the + * 2 ms the bandwidth floor allows. The number is stated so it is not read as the memory system's + * answer. + * + * One pass needs a per-lane list, and a list costs comparisons, so it is 64 deep and the merge keeps + * the best 64 of two lists: a lane's test against its 64th best is ONE comparison for almost every + * element (only ~12% of a row's elements clear it at 510 elements a lane), and the deep comparisons + * happen only for the elements that enter. Sixty-four covers R=16, the selftest's 64-wide candidate + * set, and every top_k a request asks for in practice. Deeper is not free and is not silent: + * `r3d_sample_topk` and `r3d_row_topk` take ceil(k/64) passes when the row asks for more, and each + * pass is one more read of the row. That is the reference's own chain, so the answer is the same one + * at any k; only the time is the reference's. + * + * The chain's QUIRK is transcribed too, because kbench compares the plane. `topk_next` seeds its + * scan with `best_i < 0 ||`, so the first element it examines becomes the best even when it is a + * NaN, and after that `v > best_v` is false for everything: a row whose FIRST logit is NaN yields R + * identical (NaN, 0) slots, not a hole. To reproduce that the 64-deep pool is re-scanned by ONE lane + * in ascending column order with the literal chain -- the pool provably contains every element the + * chain can ever pick (a pick is in the global top-64, so it is in its own lane's top-64), and the + * chain's comparisons are only exact when the scan order is the row's. + * + * ============================== shape ============================== + * + * One block a row everywhere: at the band a row of 130560 f32 is 510 KiB and M is 2048, so the whole + * plane is 1 GiB and these are the memory-bound kernels of the library -- argmax and top-k each read + * 1 GiB, temp reads and writes 2 GiB. A row of the candidate set is 1024 f32 and the work is the + * transcendentals, so the same shape costs nothing and buys the serial order for free. The candidate + * stages keep their probabilities in LDS (2 * 1024 floats), which is what makes typical's O(n^2) + * distance scan affordable. + * + * Single rank. `vocab_off` is read where libref reads it (`row_topk`'s reported ids, `sample_topk`'s + * `pairs` plane) and the pair planes are written as the shape hooks describe them, because kbench + * fills and compares them. There is no all-gather here and no merge kernel: `sample_merge_topk` is + * declined by libref's own shape hook and rank 0 has nothing to merge. + */ + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +/* ================================================================== shared device helpers */ +namespace { + +constexpr uint32_t kThreads = 256; /* 8 waves */ +constexpr uint32_t kWave = 32; +constexpr uint32_t kWaves = kThreads / kWave; + +/* The candidate pool's depth, and the widest candidate set the narrowing stages carry in LDS. + * 1024 candidates is the engine's declared buffer width; two f32 arrays of it is 8 KiB of 64 KiB. */ +constexpr int kPool = 64; +constexpr int kCandMax = 1024; + +/* The double call and the single rounding to f32 ARE the law: libref's oracle + * is glibc's double exp and log, and the f32 result of a double-accurate implementation agrees with + * it for every input but a double-rounding tie. */ +/* The two transcendentals, and the A/B switch. The law is libref's `(float)std::exp((double)x)`, + * and on this card the device's double `exp`/`log` are BIT-IDENTICAL to glibc's (0 of 2^20 points + * in [-100, 100] differ, both functions), so the law is reproducible here and the draw is the + * recording's. `expf` is not: it moves 5.7% of inputs by 1 ulp relative to the host's, which is + * under a bit-exact fixture. -DR3D_EXP_F32 swaps both for the f32 hardware path, so the cost of the + * law can be measured in kbench; nothing in the shipped build uses it, and the flips it causes are + * reported with it. */ +#ifdef R3D_EXP_F32 +__device__ __forceinline__ float ref_exp(float x) { return expf(x); } +__device__ __forceinline__ float ref_log(float x) { return logf(x); } +#else +__device__ __forceinline__ float ref_exp(float x) { return (float)exp((double)x); } +__device__ __forceinline__ float ref_log(float x) { return (float)log((double)x); } +#endif + +/* abi/rad_sample.h's draw, verbatim: splitmix64 over (seed * golden + pos), top 24 bits as a float + * in [0, 1) -- exactly f32's mantissa, so no double anywhere. */ +__device__ __forceinline__ uint64_t splitmix64(uint64_t z) { + z += 0x9E3779B97F4A7C15ull; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); +} +__device__ __forceinline__ float uniform01(uint64_t seed, uint64_t pos) { + const uint64_t z = splitmix64(seed * 0x9E3779B97F4A7C15ull + pos); + return (float)(uint32_t)(z >> 40) * (1.0f / 16777216.0f); +} + +/* The params row, as the kernels see it. 96 bytes, a multiple of 8, so row m is 8-byte aligned in a + * plane of words and the u64 seed and pos load as one instruction. */ +struct Params { + const RadSampleParams* p; + __device__ __forceinline__ const RadSampleParams& operator[](uint32_t m) const { + return p[m]; + } +}; + +/* A block-wide maximum with a strict `>`, which is the comparison libref writes and the reason a NaN + * is never the max: a wave butterfly, then the wave partials. `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); /* a butterfly of fmaxf: drops a NaN */ + 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; +} + +/* ------------------------------------------------------------------ sample_argmax + * + * The law: the largest logit, ties to the LOWER column, because greedy and top-1 have to + * agree. The scan's rule is `bi < 0 || v > best`: strict, so the first of a run wins, and a NaN is + * never adopted -- except as the row's very first element, which the seed of the scan adopts. The + * parallel form is the same total order: take the right candidate only when it is strictly better + * (larger, or equal with a lower column), which is associative, so the butterfly and the serial scan + * agree, and a NaN in `best` is never displaced by anything. + */ +struct Best { float v; uint32_t i; }; + +/* The scan's law, made associative. `best_take(a, b)` keeps `a` unless `b` is strictly better -- + * larger, or equal with a lower column -- and `b.i == kNone` is "nothing examined yet". The + * reference's serial scan seeds with `bi < 0 ||` and then moves only on a strict `>`, which is the + * same total order, so a butterfly of this and a scan of that agree on every input. */ +__device__ __forceinline__ Best best_take(Best a, Best b) { + const bool better = (b.v > a.v) || (b.v == a.v && b.i < a.i); + return (b.i != 0xffffffffu && better) ? b : a; +} + +/* A max with a strict `>` over the block, NaN dropped: `fmaxf` is the drop, and libref's + * `if (v > mx) mx = v` from -infinity never adopts a NaN either. */ +__device__ __forceinline__ float block_max_strict(float v, float* lds) { + return block_max(v != v ? -INFINITY : v, lds); +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_argmax_kernel( + const float* __restrict__ lg, int32_t* __restrict__ tok, uint32_t n, uint32_t lg_ld) { + __shared__ float red[kWaves]; + __shared__ uint32_t redi[kWaves]; + + const uint32_t row = blockIdx.x; + const float* __restrict__ lr = lg + (size_t)row * lg_ld; + + /* Non-NaN values only, lowest column winning a tie. */ + Best b{ -INFINITY, 0xffffffffu }; + for (uint32_t c = threadIdx.x; c < n; c += kThreads) { + const float v = ldg_f32(lr + c); + if (v != v) continue; + if (b.i == 0xffffffffu || v > b.v) { b.v = v; b.i = c; } + } +#define R3D_BEST_XOR(M) \ + { \ + const Best o{ r3d_xor_lane(b.v), r3d_xor_lane_u32(b.i) }; \ + b = best_take(b, o); \ + } + R3D_BEST_XOR(16) + R3D_BEST_XOR(8) + R3D_BEST_XOR(4) + R3D_BEST_XOR(2) + R3D_BEST_XOR(1) +#undef R3D_BEST_XOR + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) { red[wave] = b.v; redi[wave] = b.i; } + __syncthreads(); + if (threadIdx.x == 0) { + Best t{ red[0], redi[0] }; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = best_take(t, Best{ red[w], redi[w] }); + /* topk_next's seed, and nothing else: the first element the reference examines becomes its + * best even when it is a NaN, and no finite value can displace a NaN afterwards, so a row + * that opens with a NaN reports column 0. Every other NaN the scan walks past. */ + const float x0 = ldg_f32(lr); + tok[row] = (int32_t)(x0 != x0 ? 0u : t.i); + } +} + +/* ------------------------------------------------------------------ sample_temp + * + * The law: `inv = 1/t` computed once per row, then every logit multiplied -- by the + * reciprocal, not divided, and only when the row is sampled at all: `!(t > 0) || t == 1` leaves the + * row exactly as it was, bit for bit, which is what makes temp 1.0 and temp 0.0 (greedy) no-ops the + * kernel has to keep. The write is in place: logits are an INOUT operand. + */ +__global__ __launch_bounds__(kThreads) R3D_WAVES(8) void sample_temp_kernel( + float* __restrict__ lg, const RadSampleParams* __restrict__ pr, uint32_t n, uint32_t lg_ld) { + const uint32_t row = blockIdx.x; + const float t = pr[row].temp; + if (!(t > 0.0f) || t == 1.0f) return; + const float inv = 1.0f / t; + float* __restrict__ lr = lg + (size_t)row * lg_ld; + for (uint32_t c = threadIdx.x; c < n; c += kThreads) { + const float v = ldg_f32(lr + c); + lr[c] = v * inv; + } +} + +} /* namespace */ + +/* lg [M][n_vocab] f32, INOUT for temp, read-only for argmax; `lg_ld` elements a row (0 = n) + * tok [M] i32 + * params [M] 24 words a row; argmax does not read it, and libref's shape hook describes + * it anyway, so the operand is there and unchecked, as libref leaves it. + * + * 0, -1 null, -2 bad extent, -3 pitch that does not describe the operand, -4 the HIP launch failed. + * No allocation, no synchronisation. */ +extern "C" int r3d_sample_argmax(long lg, long tok, int M, int n_vocab, long long lg_ld, + long stream) { + if (!lg || !tok) 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 (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(sample_argmax_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (const float*)lg, (int32_t*)tok, (uint32_t)n_vocab, (uint32_t)lg_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r3d_sample_temp(long lg, long params, int M, int n_vocab, long long lg_ld, + long stream) { + if (!lg || !params) 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 (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(sample_temp_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (float*)lg, (const RadSampleParams*)params, (uint32_t)n_vocab, (uint32_t)lg_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the top-k pool + * + * One lane's share of a row, kept as the 64 best by (value descending, column ascending) -- the + * order `topk_next` walks. Two rules make it one pass and make it exact: + * + * - the order is a STRICT total order, so a merge of two such lists is a merge of two sorted + * lists and keeps the first 64 of the union, which is what the reference's R scans converge on; + * - the list lives in registers, so insertion is a 64-step sift with STATIC indices (compare, and + * swap when the newcomer is better) and never a dynamic index, which would spill the array to + * private memory. The sift costs 64 compares per INSERTED element, and elements are inserted + * only after a single compare against the lane's 64th best -- about one element in eight at the + * band's 510 columns a lane -- so the amortised cost is a few comparisons a column. + * + * Slots the row never filled hold (-INFINITY, 0xffffffff): lower than any real value, and higher + * than any real column, so a real -infinity logit (a masked one) beats a pad and the extraction + * stops at the first pad. + */ +namespace { + +constexpr uint32_t kPadCol = 0xffffffffu; + +/* The pool's order, strict: larger value wins, equal value goes to the lower column. */ +__device__ __forceinline__ bool pool_better(float av, uint32_t ai, float bv, uint32_t bi) { + return av > bv || (av == bv && ai < bi); +} + +/* Insert (v, i) into a lane's register list. POOL is the list depth, which is the width of a pass: + * the sift is POOL steps and the merges are POOL-wide. The band asks for 16 (a router's top_k) and + * a candidate set for 64; carrying 64 through a router row costs four times the sift and returns + * the same 16 pairs. + * + * `pv`/`pi` carry the pick chain: an element at or above the last pick has been picked already, and + * within a run of equal values only columns after the last pick are still candidates -- + * `topk_next`'s two skips, in its order. */ +template +__device__ __forceinline__ void pool_insert(float v, uint32_t i, float pv, uint32_t pi, + float* lv, uint32_t* li) { + if (v != v) return; /* the scan walks past a NaN (its first element is + handled by the caller, as the reference's is) */ + if (v > pv) return; /* picked on an earlier pass */ + if (v == pv && i <= pi) return; /* the last pick, or one before it */ + if (!pool_better(v, i, lv[POOL - 1], li[POOL - 1])) return; /* the fast path: one compare */ + + float cv = v; + uint32_t ci = i; +#pragma unroll + for (int j = 0; j < POOL; ++j) { /* the sift: every index a compile-time constant */ + if (pool_better(cv, ci, lv[j], li[j])) { + const float tv = lv[j]; const uint32_t ti = li[j]; + lv[j] = cv; li[j] = ci; cv = tv; ci = ti; + } + } +} + +/* The best 64 of the union of two lists, in the pool's order. + * + * A[j] and B[j] are descending, so C[j] = the better of A[j] and B[kPool-1-j] is a bitonic sequence + * that already contains the top 64 of the union, and a bitonic sort of 64 in registers is six + * passes of 32 compare-exchanges with static strides -- no dynamic index, no spill, 448 compares. + * Both lanes of a shuffle pair compute the same result, which is what makes a butterfly of this + * operation a wave reduction. */ +template +__device__ __forceinline__ void pool_merge(const float* av, const uint32_t* ai, + const float* bv, const uint32_t* bi, + float* ov, uint32_t* oi) { +#define R3D_POOL_GET(X, J) \ + const float x##v = r3d_xor_lane(X[0]); (void)x##v +#pragma unroll + for (int j = 0; j < POOL; ++j) { + const int r = POOL - 1 - j; + if (pool_better(av[j], ai[j], bv[r], bi[r])) { ov[j] = av[j]; oi[j] = ai[j]; } + else { ov[j] = bv[r]; oi[j] = bi[r]; } + } +#undef R3D_POOL_GET +#pragma unroll + for (int k = POOL; k > 1; k >>= 1) { +#pragma unroll + for (int h = k / 2; h > 0; h >>= 1) { +#pragma unroll + for (int j = 0; j < POOL; ++j) { + const int o = j ^ h; + if (o <= j) continue; + /* Descending everywhere: the whole array is one descending run, so the direction of + * every compare-exchange is "the larger value to the lower index". */ + if (pool_better(ov[o], oi[o], ov[j], oi[j])) { + const float tv = ov[j]; const uint32_t ti = oi[j]; + ov[j] = ov[o]; oi[j] = oi[o]; ov[o] = tv; oi[o] = ti; + } + } + } + } +} + +/* One lane's pass over its columns of a row. STEP is 1 (scalar) or 4 (a vector load a step); LD + * reads one column. */ +template +__device__ __forceinline__ void pool_scan(const void* __restrict__ x, uint32_t n, uint32_t x_ld, + float pv, uint32_t pi, float* lv, uint32_t* li) { + const uint32_t tid = threadIdx.x; + if (XDT == 0) { /* bf16: four columns a 64-bit load */ + const uint16_t* __restrict__ p = (const uint16_t*)x + (size_t)blockIdx.x * x_ld; + if (STEP == 4) { + const uint32_t nw = n / 4; + for (uint32_t w = tid; w < nw; w += kThreads) { + const uint2 u = *(const uint2*)(p + (size_t)w * 4); + const uint32_t lo = u.x, hi = u.y; + pool_insert(bf16_to_f32((uint16_t)(lo & 0xffffu)), 4 * w + 0, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(lo >> 16)), 4 * w + 1, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(hi & 0xffffu)), 4 * w + 2, pv, pi, lv, li); + pool_insert(bf16_to_f32((uint16_t)(hi >> 16)), 4 * w + 3, pv, pi, lv, li); + } + for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) /* the row's odd tail, once */ + pool_insert(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li); + } else { + for (uint32_t c = tid; c < n; c += kThreads) + pool_insert(bf16_to_f32((uint16_t)ldg_u16(p + c)), c, pv, pi, lv, li); + } + } else { /* f32: four columns a 128-bit load */ + const float* __restrict__ p = (const float*)x + (size_t)blockIdx.x * x_ld; + if (STEP == 4) { + const uint32_t nw = n / 4; + for (uint32_t w = tid; w < nw; w += kThreads) { + const float4 v = *(const float4*)(p + (size_t)w * 4); + pool_insert(v.x, 4 * w + 0, pv, pi, lv, li); + pool_insert(v.y, 4 * w + 1, pv, pi, lv, li); + pool_insert(v.z, 4 * w + 2, pv, pi, lv, li); + pool_insert(v.w, 4 * w + 3, pv, pi, lv, li); + } + for (uint32_t c = nw * 4 + tid; c < n; c += kThreads) + pool_insert(ldg_f32(p + c), c, pv, pi, lv, li); + } else { + for (uint32_t c = tid; c < n; c += kThreads) + pool_insert(ldg_f32(p + c), c, pv, pi, lv, li); + } + } +} + +/* One pass over the row: every lane's list, a wave butterfly of merges, the eight wave lists in + * LDS, and the block's 64 best in LDS at [kWaves*kPool, ...). Returns how many are real (pads + * stop it). */ +/* The block's 64 best are left in LDS at [kWaves*kPool, ...): the extraction that follows walks + * them with a runtime index, and a runtime index into a register array is a spill. */ +template +__device__ __forceinline__ uint32_t pool_pass(const void* __restrict__ x, uint32_t n, + uint32_t x_ld, int xdt, int vec, + float pv, uint32_t pi, + float* lds_v, uint32_t* lds_i) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + float lv[POOL], bv[POOL], cv[POOL]; + uint32_t li[POOL], bi[POOL], ci[POOL]; +#pragma unroll + for (int j = 0; j < POOL; ++j) { lv[j] = -INFINITY; li[j] = kPadCol; } + + if (vec) { + if (xdt == 0) pool_scan<0, 4, POOL>(x, n, x_ld, pv, pi, lv, li); + else pool_scan<1, 4, POOL>(x, n, x_ld, pv, pi, lv, li); + } else { + if (xdt == 0) pool_scan<0, 1, POOL>(x, n, x_ld, pv, pi, lv, li); + else pool_scan<1, 1, POOL>(x, n, x_ld, pv, pi, lv, li); + } + +#define R3D_POOL_XOR(J) \ + { \ + _Pragma("unroll") for (int q = 0; q < POOL; ++q) { \ + bv[q] = r3d_xor_lane(lv[q]); bi[q] = r3d_xor_lane_u32(li[q]); \ + } \ + pool_merge(lv, li, bv, bi, cv, ci); \ + _Pragma("unroll") for (int q = 0; q < POOL; ++q) { lv[q] = cv[q]; li[q] = ci[q]; } \ + } + R3D_POOL_XOR(16) + R3D_POOL_XOR(8) + R3D_POOL_XOR(4) + R3D_POOL_XOR(2) + R3D_POOL_XOR(1) +#undef R3D_POOL_XOR + + if (lane == 0) { +#pragma unroll + for (int j = 0; j < POOL; ++j) { lds_v[wave * POOL + j] = lv[j]; lds_i[wave * POOL + j] = li[j]; } + } + __syncthreads(); + + uint32_t nout = 0; + if (threadIdx.x == 0) { /* the eight lists, merged with cursors */ + uint32_t cur[kWaves]; +#pragma unroll + for (int w = 0; w < kWaves; ++w) cur[w] = 0; + for (int j = 0; j < POOL; ++j) { + float bv = -INFINITY; uint32_t bi = kPadCol; int bw = -1; + for (int w = 0; w < kWaves; ++w) { + const uint32_t idx = (uint32_t)w * POOL + cur[w]; + const float v = lds_v[idx]; const uint32_t i = lds_i[idx]; + if (i == kPadCol) continue; + if (bw < 0 || pool_better(v, i, bv, bi)) { bv = v; bi = i; bw = w; } + } + if (bw < 0) break; + lds_v[kWaves * POOL + j] = bv; lds_i[kWaves * POOL + j] = bi; + cur[bw]++; nout = (uint32_t)j + 1; + } + } + __syncthreads(); + return nout; +} + +/* The pool, in LDS: the eight wave lists, then the block's. */ +} /* namespace */ + +/* ================================================================== row_topk + * + * The law: exact per-row top-R, descending, ties to the lower column, with `vocab_off` + * added to every reported id and the optional [M, R, 2] pair plane an all-gather moves (an int32 id + * in the first f32 slot, the value in the second, id -1 for a slot the row could not fill). + * + * The reference calls `topk_next` R times, a full scan each time; the pool above produces the same + * R pairs from one scan, because the pool's order IS the chain's order. A row that wants more than + * 64 costs ceil(R/64) scans and carries the chain's state across them, so the answer is the same at + * any R and only the time is the reference's. + */ +namespace { + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void row_topk_kernel( + const void* __restrict__ x, int32_t* __restrict__ idx, float* __restrict__ val, + float* __restrict__ pairs, uint32_t n, uint32_t k, int vec, int32_t vocab_off, + uint32_t x_ld, uint32_t idx_ld, uint32_t val_ld, uint32_t pairs_ld) { + __shared__ float lds_v[kWaves * kPool + kPool]; + __shared__ uint32_t lds_i[kWaves * kPool + kPool]; + __shared__ float st[4]; + __shared__ uint32_t s2[2]; + + const uint32_t row = blockIdx.x; + float* __restrict__ vr = val + (size_t)row * val_ld; + int32_t* __restrict__ ir = idx + (size_t)row * idx_ld; + float* __restrict__ pr = pairs ? pairs + (size_t)row * pairs_ld : nullptr; + + /* topk_next's seed of the scan: the first element it looks at becomes the best even as a NaN, + * and nothing displaces a NaN, so a row that opens with one reports (0, NaN) in every slot. + * Stated once, here, rather than buried in the pool's comparisons. */ + if (threadIdx.x == 0) + st[0] = XDT == 0 ? bf16_to_f32((uint16_t)ldg_u16((const uint16_t*)x + (size_t)row * x_ld)) + : ldg_f32((const float*)x + (size_t)row * x_ld); + __syncthreads(); + if (st[0] != st[0] && threadIdx.x == 0) { + for (uint32_t r = 0; r < k; ++r) { + ir[r] = (int32_t)vocab_off; + vr[r] = st[0]; + if (pr) { + int32_t bits = (int32_t)vocab_off; + float v = st[0]; + __builtin_memcpy(&pr[2 * r], &bits, 4); + pr[2 * r + 1] = v; + } + } + return; + } + + float pv = INFINITY; + uint32_t pi = 0xffffffffu; + uint32_t done = 0; + constexpr uint32_t kBlk = kWaves * POOL; /* where pool_pass leaves the block's list */ + while (done < k) { + __syncthreads(); + const uint32_t nout = pool_pass(x, n, x_ld, XDT, vec, pv, pi, lds_v, lds_i); + if (threadIdx.x == 0) { + /* Only the first `nout` entries of the block list were written this pass; what sits past + * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; + const uint32_t take = nout < room ? nout : room; + uint32_t j = 0; + for (; j < take; ++j) { + const uint32_t col = lds_i[kBlk + j]; + if (col == kPadCol) break; + const float v = lds_v[kBlk + j]; + const int32_t id = (int32_t)(col + (uint32_t)vocab_off); + ir[done + j] = id; + vr[done + j] = v; + if (pr) { __builtin_memcpy(&pr[2 * (done + j)], &id, 4); pr[2 * (done + j) + 1] = v; } + pv = v; pi = col; + } + for (; j < room; ++j) { /* holes to the end of the window */ + ir[done + j] = -1; + vr[done + j] = -INFINITY; + if (pr) { + const int32_t h = -1; + const float hinf = -INFINITY; + __builtin_memcpy(&pr[2 * (done + j)], &h, 4); + pr[2 * (done + j) + 1] = hinf; + } + } + st[1] = pv; + s2[0] = pi; + s2[1] = nout == 0 ? k : done + take; + } + __syncthreads(); +#ifdef R3D_POOL_TRACE + if (threadIdx.x == 0) + printf(" [pool] n=%u done=%u nout=%u take=%u pv=%g pi=%u -> pv=%g pi=%u done=%u\n", + n, done, nout, (uint32_t)0, pv, pi, st[1], s2[0], s2[1]); +#endif + pv = st[1]; pi = s2[0]; done = s2[1]; + } +} + +/* One row's top_k: the request's, clamped to the buffer, whole width when absent, none when the row + * is greedy (its token is sample_argmax's, and a stage that wrote it candidates would be a bug the + * pick cannot see). */ +__device__ __forceinline__ uint32_t row_k(const RadSampleParams& sp, uint32_t n_cand) { + if (sp.flags & RAD_SP_GREEDY) return 0; + const int32_t k = sp.top_k; + if (k <= 0 || (uint32_t)k > n_cand) return n_cand; + return (uint32_t)k; +} + +} /* namespace */ + +/* x [M][N] bf16 (x_dt 0) or f32 (x_dt 1), `x_ld` elements a row (0 = N) + * idx [M][R] i32, the column plus `vocab_off`, -1 for a slot the row could not fill + * val [M][R] f32, -infinity with the hole + * pairs [M][2R] f32, optional: (int32 id bits, value) as the all-gather moves it + * + * 0, -1, -2 a bad extent, -3 a pitch that does not describe the operand, -4 the launch failed. */ +extern "C" 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) { + if (!x || !idx || !val) return -1; + if (M <= 0 || N <= 0 || R <= 0) return -2; + if (x_dt != 0 && x_dt != 1) return -2; + if (!x_ld) x_ld = N; + if (!idx_ld) idx_ld = R; + if (!val_ld) val_ld = R; + if (!pairs_ld) pairs_ld = 2 * R; + if (x_ld < N || idx_ld < R || val_ld < R || (pairs && pairs_ld < 2 * R)) return -3; + if (M > 0x7fffffff || N > 0x7fffffff || R > 0x7fffffff) return -2; + + /* The vector load needs a row start that is 16 bytes (f32) or 8 bytes (bf16) aligned. Any pitch + * that is a multiple of 4 elements does it for every row; the base is the caller's to align and + * is checked here, so a slice handed in at an odd column takes the scalar path and is right. */ + const int es = x_dt == 0 ? 2 : 4; + const int vec = (x_ld % 4 == 0) && ((x % (4 * (long long)es)) == 0); + + const dim3 grid((unsigned)M), block(kThreads); + + /* The list depth is the pass width: R 16 (a router's top_k, the band's row) sifts 16 deep, a + * wide candidate set 64. Beyond 64 the row is scanned again, so the depth buys passes, not + * per-element work. */ + const int pool = R <= 16 ? 16 : (R <= 32 ? 32 : 64); +#define R3D_RTK(XDT, POOL) \ + R3D_KLAUNCH(R3D_KNAME(row_topk_kernel), grid, block, \ + (hipStream_t)(uintptr_t)stream, (const void*)x, (int32_t*)idx, (float*)val, \ + (float*)pairs, (uint32_t)N, (uint32_t)R, vec, (int32_t)vocab_off, \ + (uint32_t)x_ld, (uint32_t)idx_ld, (uint32_t)val_ld, (uint32_t)pairs_ld) + if (x_dt == 0) { + if (pool == 16) { R3D_RTK(0, 16); } + else if (pool == 32) { R3D_RTK(0, 32); } + else { R3D_RTK(0, 64); } + } else { + if (pool == 16) { R3D_RTK(1, 16); } + else if (pool == 32) { R3D_RTK(1, 32); } + else { R3D_RTK(1, 64); } + } +#undef R3D_RTK + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== sample_topk + * + * The law: the row's top_k largest logits into the fixed-width candidate set, descending, + * ties to the lower token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. Two things + * here are not in row_topk: the width is the BUFFER's (a declare-time bound), the row's top_k only + * narrows within it -- top_k 40 in a 1024-wide buffer is 40 candidates and 984 holes -- and a greedy + * row takes none, because its token is sample_argmax's and the pick must not overwrite it. + * + * `cand_val` carries LOGITS, not probabilities: every narrowing stage takes its own softmax over the + * set, which is what lets the stages compose in any order. + */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( + const float* __restrict__ lg, const RadSampleParams* __restrict__ pr, int32_t* __restrict__ ci, + float* __restrict__ cv, int32_t* __restrict__ pairs, uint32_t n_vocab, uint32_t n_cand, int vec, + int32_t vocab_off, uint32_t lg_ld, uint32_t ci_ld, uint32_t cv_ld, uint32_t pairs_ld) { + __shared__ float lds_v[kWaves * kPool + kPool]; + __shared__ uint32_t lds_i[kWaves * kPool + kPool]; + __shared__ float st[4]; + __shared__ uint32_t s2[2]; + + const uint32_t row = blockIdx.x; + const uint32_t k = row_k(pr[row], n_cand); + int32_t* __restrict__ ir = ci + (size_t)row * ci_ld; + float* __restrict__ vr = cv + (size_t)row * cv_ld; + int32_t* __restrict__ pp = pairs ? pairs + (size_t)row * pairs_ld : nullptr; + + /* The whole buffer is written every step: a hole is a value the later stages test for, and a + * stale candidate from the previous step would be drawn. */ + auto hole = [&](uint32_t r) { + ir[r] = -1; + vr[r] = -INFINITY; + if (pp) { pp[2 * r] = (int32_t)0xffffffffu; pp[2 * r + 1] = (int32_t)0xff800000; } + }; + + const float x0 = ldg_f32(lg + (size_t)row * lg_ld); + if (x0 != x0) { /* topk_next's seed, as in row_topk */ + for (uint32_t r = 0; r < n_cand; ++r) { + if (r >= k) { hole(r); continue; } + ir[r] = vocab_off; + vr[r] = x0; + if (pp) { pp[2 * r] = vocab_off; pp[2 * r + 1] = *(const int32_t*)&x0; } + } + return; + } + + float pv = INFINITY; + uint32_t pi = 0xffffffffu; + uint32_t done = 0; + constexpr uint32_t kBlk = kWaves * POOL; + while (done < k) { + __syncthreads(); + const uint32_t nout = pool_pass(lg, n_vocab, lg_ld, 1, vec, pv, pi, lds_v, lds_i); + if (threadIdx.x == 0) { + /* Only the first `nout` entries of the block list were written this pass; what sits past + * them is last pass's list, so the count, not the pad sentinel, bounds the copy. */ + const uint32_t room = (k - done < POOL) ? k - done : (uint32_t)POOL; + const uint32_t take = nout < room ? nout : room; + uint32_t j = 0; + for (; j < take; ++j) { + const uint32_t col = lds_i[kBlk + j]; + if (col == kPadCol) break; + const float v = lds_v[kBlk + j]; + const int32_t id = (int32_t)(col + (uint32_t)vocab_off); + ir[done + j] = (int32_t)col; /* cand_idx is LOCAL: it indexes this row of logits */ + vr[done + j] = v; + if (pp) { pp[2 * (done + j)] = id; pp[2 * (done + j) + 1] = *(const int32_t*)&v; } + pv = v; pi = col; + } + for (; j < room; ++j) hole(done + j); /* holes to the end of the window */ + s2[0] = pi; + s2[1] = nout == 0 ? k : done + take; + st[1] = pv; + } + __syncthreads(); + pv = st[1]; pi = s2[0]; done = s2[1]; + } + for (uint32_t r = done + threadIdx.x; r < n_cand; r += kThreads) hole(r); +} + +/* lg [M][n_vocab] f32; `lg_ld` a row (0 = n_vocab) + * params [M] 24 words a row + * ci [M][n_cand] i32, LOCAL columns, -1 for a hole + * cv [M][n_cand] f32, the LOGIT, -infinity with the hole + * pairs [M][2*n_cand] i32, optional: (global id, logit bits), 0xffffffff for a hole + * + * The candidate width is ci's last dimension, as libref takes it; the row's top_k only narrows + * inside it. 0, -1, -2, -3, -4. */ +extern "C" 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) { + if (!lg || !params || !ci || !cv) return -1; + if (M <= 0 || n_vocab <= 0 || n_cand <= 0 || n_cand > kCandMax) return -2; + if (!lg_ld) lg_ld = n_vocab; + if (!ci_ld) ci_ld = n_cand; + if (!cv_ld) cv_ld = n_cand; + if (!pairs_ld) pairs_ld = 2 * n_cand; + if (lg_ld < n_vocab || ci_ld < n_cand || cv_ld < n_cand || (pairs && pairs_ld < 2 * n_cand)) + return -3; + if (M > 0x7fffffff || n_vocab > 0x7fffffff) return -2; + const int vec = (lg_ld % 4 == 0) && ((lg % 16) == 0); + + const dim3 grid((unsigned)M), block(kThreads); + const int pool = n_cand <= 16 ? 16 : (n_cand <= 32 ? 32 : 64); +#define R3D_STK(POOL) \ + R3D_KLAUNCH(R3D_KNAME(sample_topk_kernel), grid, block, \ + (hipStream_t)(uintptr_t)stream, (const float*)lg, \ + (const RadSampleParams*)params, (int32_t*)ci, (float*)cv, (int32_t*)pairs, \ + (uint32_t)n_vocab, (uint32_t)n_cand, vec, (int32_t)vocab_off, \ + (uint32_t)lg_ld, (uint32_t)ci_ld, (uint32_t)cv_ld, (uint32_t)pairs_ld) + if (pool == 16) { R3D_STK(16); } + else if (pool == 32) { R3D_STK(32); } + else { R3D_STK(64); } +#undef R3D_STK + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================== the narrowing stages and the draw + * + * One block a row of the candidate set, the row in LDS (five arrays of n_cand f32 at the band's + * 1024 is 20 KiB of the 64 KiB), and the division of labour the arithmetic asks for: + * + * - the max is a butterfly of strict `>`: libref's `if (v > mx) mx = v` from -infinity, so a + * candidate at -infinity (a hole, or a grammar-masked token at the set's tail) is never the max + * and a NaN never is; + * - exp(v - mx) is one value per candidate, so the wave computes them all, in parallel, into LDS; + * - every SUM that follows is libref's loop, in index order, on lane 0. The normaliser, the top-p + * prefix, the entropy and the inverse-CDF scan are all order-sensitive f32 accumulations, and + * the draw is decided by the last of them. A parallel prefix sum would round differently, and a + * draw that rounds differently is a different token: this is the law, so the loop stays serial. + * It is 1024 adds, half a microsecond; the transcendentals it waits on are the cost, and they + * are already out of the loop. + * + * A greedy row is left alone by every stage, as the reference leaves it, which is the same rule + * that keeps its token the argmax's. + */ +namespace { + +enum { ST_TOPP = 0, ST_MINP = 1, ST_TYPICAL = 2, ST_XTC = 3, ST_PICK = 4 }; + +__device__ __forceinline__ void cand_load(uint32_t n_cand, const int32_t* __restrict__ ir, + const float* __restrict__ vr, int32_t* __restrict__ ci, + float* __restrict__ cv) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + ci[i] = ir[i]; + cv[i] = vr[i]; + } +} + +__device__ __forceinline__ void cand_write(uint32_t n_cand, int32_t* __restrict__ ir, + float* __restrict__ vr, const int32_t* __restrict__ ci, + const float* __restrict__ cv) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + ir[i] = ci[i]; + vr[i] = cv[i]; + } +} + +/* exp(v[i] - mx) for every live candidate, in parallel. A dropped candidate gets 0, which is what + * the reference's loops contribute for it (they skip it, and a 0 is inert in every sum below). */ +__device__ __forceinline__ void cand_exp(uint32_t n_cand, const int32_t* __restrict__ ci, + const float* __restrict__ cv, float mx, + float* __restrict__ ev) { + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + ev[i] = (ci[i] >= 0) ? ref_exp(cv[i] - mx) : 0.0f; +} + +__device__ __forceinline__ float lane0_sum(uint32_t n_cand, const float* __restrict__ ev, + uint32_t* out) { + if (threadIdx.x == 0) { + float sum = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) sum += ev[i]; + out[0] = (uint32_t)(uintptr_t)0; + ((float*)out)[0] = sum; + } + __syncthreads(); + return ((float*)out)[0]; +} + +/* A minimum to match, for typical's cut: the smallest qualifying distance. */ +__device__ __forceinline__ float block_min(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; +#define R3D_MIN_XOR(M) v = fminf(v, r3d_xor_lane(v)) + R3D_MIN_XOR(16); R3D_MIN_XOR(8); R3D_MIN_XOR(4); R3D_MIN_XOR(2); R3D_MIN_XOR(1); +#undef R3D_MIN_XOR + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fminf(t, lds[w]); + return t; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( + int32_t* __restrict__ ci_p, float* __restrict__ cv_p, const RadSampleParams* __restrict__ pr, + int32_t* __restrict__ tok, uint32_t n_cand, uint32_t ci_ld, uint32_t cv_ld) { + __shared__ int32_t s_ci[kCandMax]; + __shared__ float s_cv[kCandMax]; + __shared__ float s_ev[kCandMax]; + __shared__ float s_q[kCandMax]; + __shared__ float s_d[kCandMax]; + __shared__ float red[kWaves]; + __shared__ float st[4]; + __shared__ uint32_t su[4]; + + const uint32_t row = blockIdx.x; + const RadSampleParams& sp = pr[row]; + if (sp.flags & RAD_SP_GREEDY) return; /* the row's token is the argmax's, untouched */ + + int32_t* __restrict__ ir = ci_p + (size_t)row * ci_ld; + float* __restrict__ vr = cv_p + (size_t)row * cv_ld; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { s_ci[i] = ir[i]; s_cv[i] = vr[i]; } + __syncthreads(); + + /* mx over live candidates with a strict `>` from -infinity: a hole, a masked tail at -infinity + * and a NaN are all excluded, exactly as the reference's loop excludes them. */ + float mine = -INFINITY; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + if (s_ci[i] >= 0 && s_cv[i] > mine) mine = s_cv[i]; + const float mx = block_max(mine, red); + if (mx == -INFINITY) { + if (STAGE == ST_PICK && threadIdx.x == 0) tok[row] = -1; + return; /* an empty row: nothing to narrow, nothing to draw */ + } + + if (STAGE == ST_MINP) { + const float p = sp.min_p; + if (!(p > 0.0f)) return; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + const float v = s_cv[i]; + if (v == mx) continue; /* the max always survives */ + if (ref_exp(v - mx) < p) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + } else { + float inv = 0.0f; + /* exp(v - mx) for every live candidate, in parallel, in place in LDS. */ + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_ev[i] = (s_ci[i] >= 0) ? ref_exp(s_cv[i] - mx) : 0.0f; + __syncthreads(); + if (threadIdx.x == 0) { /* the normaliser: libref's loop, index order */ + float sum = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) sum += s_ev[i]; + st[0] = sum > 0.0f ? 1.0f / sum : 0.0f; + } + __syncthreads(); + inv = st[0]; + + if (STAGE == ST_TOPP) { + const float p = sp.top_p; + if (!(p < 1.0f) || !(p > 0.0f)) return; + if (threadIdx.x == 0) { /* the shortest prefix reaching p, at least one */ + float cum = 0.0f; + bool done = false; + for (uint32_t i = 0; i < n_cand; ++i) { + if (s_ci[i] < 0) continue; + if (done) { s_ci[i] = -1; s_cv[i] = -INFINITY; continue; } + cum += s_ev[i] * inv; + if (cum >= p) done = true; + } + } + __syncthreads(); + } else if (STAGE == ST_XTC) { + const float pq = sp.xtc_probability, th = sp.xtc_threshold; + if (!(pq > 0.0f) || !(th > 0.0f)) return; + if (threadIdx.x == 0) + su[1] = uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= pq ? 1u : 0u; + __syncthreads(); + if (su[1]) return; /* the coin says leave the set alone this step */ + float cnt = 0.0f, last = -1.0f; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + if (s_ev[i] * inv >= th) { cnt += 1.0f; last = (float)i; } + } + /* Count and last are a sum and a maximum: both order-free, which is why this stage needs + * no serial loop. Candidates above the threshold are re-tested below, from the same + * values in `s_ev`. */ + const float n_above = block_sum(cnt, red); + const float hi = block_max(last, red); + if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */ + const int32_t keep = (int32_t)hi; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0 || (int32_t)i == keep) continue; + if (s_ev[i] * inv >= th) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + __syncthreads(); + } else if (STAGE == ST_TYPICAL) { /* typical: the pick must not fall through here, + * it needs s_ev to still hold the exponentials */ + const float p = sp.typical_p; + if (!(p < 1.0f) || !(p > 0.0f)) return; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_q[i] = (s_ci[i] >= 0) ? s_ev[i] * inv : 0.0f; + __syncthreads(); + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_ev[i] = (s_q[i] > 0.0f) ? ref_log(s_q[i]) : 0.0f; /* log(q) once, used twice */ + __syncthreads(); + if (threadIdx.x == 0) { /* the entropy, in index order */ + float H = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) + if (s_q[i] > 0.0f) H -= s_q[i] * s_ev[i]; + st[1] = H; + } + __syncthreads(); + const float H = st[1]; + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) + s_d[i] = (s_q[i] > 0.0f) ? fabsf(-s_ev[i] - H) : 0.0f; + __syncthreads(); + /* The smallest distance whose mass reaches p. A lane owns one candidate's distance and + * sums the mass at or below it in index order; ties are kept, so the set may overshoot + * p and does not depend on the candidate order. */ + float cut = INFINITY; + for (uint32_t c = threadIdx.x; c < n_cand; c += kThreads) { + if (!(s_q[c] > 0.0f)) continue; + float mass = 0.0f; + for (uint32_t i = 0; i < n_cand; ++i) + if (s_q[i] > 0.0f && s_d[i] <= s_d[c]) mass += s_q[i]; + if (mass >= p && s_d[c] < cut) cut = s_d[c]; + } + const float cuth = block_min(cut, red); + if (cuth == INFINITY) return; /* no qualifying band: the reference leaves it be */ + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { + if (s_ci[i] < 0) continue; + if (!(s_q[i] > 0.0f) || s_d[i] > cuth) { s_ci[i] = -1; s_cv[i] = -INFINITY; } + } + __syncthreads(); + } + + if (STAGE == ST_PICK) { + if (threadIdx.x == 0) { /* the inverse CDF, in candidate order */ + const float u = uniform01(sp.seed ^ RAD_SAMPLE_KEY_PICK, sp.pos); + float cum = 0.0f; + int32_t chosen = -1, last = -1; + for (uint32_t i = 0; i < n_cand; ++i) { + const int32_t id = s_ci[i]; + if (id < 0) continue; + const float v = s_cv[i]; + if (v > -INFINITY) last = id; /* a masked tail is never the fallback */ + cum += s_ev[i] * inv; + if (u < cum) { chosen = id; break; } + } + tok[row] = chosen >= 0 ? chosen : last; + } + return; /* the draw writes no candidate plane */ + } + } + for (uint32_t i = threadIdx.x; i < n_cand; i += kThreads) { ir[i] = s_ci[i]; vr[i] = s_cv[i]; } +} + +} /* namespace */ + +/* ci [M][n_cand] i32, INOUT: -1 marks a dropped candidate + * cv [M][n_cand] f32, INOUT: the LOGIT, -infinity with a drop + * params [M] 24 words a row -- the stage's own scalar, the seed and the pos + * + * The set is not re-sorted: it arrives descending from sample_topk and the stages skip holes. A + * greedy row is left exactly as it was. 0, -1, -2, -3, -4. */ +namespace { +template +int narrow_launch(long ci, long cv, long params, int M, int n_cand, long long ci_ld, + long long cv_ld, long stream, long tok) { + if (!ci || !cv || !params) return -1; + if (M <= 0 || n_cand <= 0 || n_cand > kCandMax) return -2; + if (!ci_ld) ci_ld = n_cand; + if (!cv_ld) cv_ld = n_cand; + if (ci_ld < n_cand || cv_ld < n_cand) return -3; + if (M > 0x7fffffff || n_cand > 0x7fffffff) return -2; + + const dim3 grid((unsigned)M), block(kThreads); + R3D_KLAUNCH(R3D_KNAME(narrow_kernel), grid, block, (hipStream_t)(uintptr_t)stream, + (int32_t*)ci, (float*)cv, (const RadSampleParams*)params, (int32_t*)tok, + (uint32_t)n_cand, (uint32_t)ci_ld, (uint32_t)cv_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} +} /* namespace */ + +extern "C" 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) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" 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) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" 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) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} +extern "C" 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) { + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, 0); +} + +/* The inverse-CDF draw over the candidate set: the splitmix64 uniform at (seed ^ PICK, pos), the + * normaliser and the accumulation in candidate order, and the fallback to the last candidate above + * -infinity when the f32 probabilities sum to less than u. Writes `token` only. */ +extern "C" 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) { + if (!tok) return -1; + return narrow_launch(ci, cv, params, M, n_cand, ci_ld, cv_ld, stream, tok); +} + +/* ================================================================== the plugin ABI + * + * Nine shims, one per op. What a row's dtype is, the tensor says; what a row's geometry is, the + * operand says; `M` is the band's ceiling and never the row count, which is numel(x)/n_vocab. The + * params plane is checked the way libref checks it -- a 32-bit dtype and enough bytes for M rows -- + * and contiguous, because the kernels index it flat, as libref does. + */ + +#define R3D_NEED(expr) do { const int r3d_s = (expr); if (r3d_s) return R3D_NO(r3d_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; + } +} + +static inline int sp_is_word(const RadTensor* t) { + return t && (t->dtype == RAD_U32 || t->dtype == RAD_I32 || t->dtype == RAD_F32); +} + +/* param_rows: the params operand is a byte blob of [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, so a stage would sample 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; /* the 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; +} + +/* ------------------------------------------------------------------ row_topk */ + +enum { RTK_X = 0, RTK_IDX, RTK_VAL, RTK_PAIRS }; + +extern "C" int r3d_rad_row_topk(const RadArgs* a, RadStream stream) { + const RadTensor* x = r3d_opt(a, RTK_X); + const RadTensor* idx = r3d_opt(a, RTK_IDX); + const RadTensor* val = r3d_opt(a, RTK_VAL); + const RadTensor* pr = r3d_opt(a, RTK_PAIRS); + if (!x || !x->data || !idx || !idx->data || !val || !val->data) return R3D_NO(RAD_E_INVAL); + const int xdt = r3d_is_bf16(x) ? 0 : (r3d_is_f32(x) ? 1 : -1); + if (xdt < 0) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_i32(idx)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(val)) return R3D_NO(RAD_E_DTYPE); + if (pr && pr->data && !r3d_is_f32(pr)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_aligned(r3d_p(x), 4) || !r3d_aligned(r3d_p(idx), 4) || !r3d_aligned(r3d_p(val), 4)) + return R3D_NO(RAD_E_ALIGN); + + const long long N = r3d_geti_or(a, "N", r3d_dim(x, (int)x->rank - 1)); + const long long R = r3d_geti_or(a, "R", 1); + if (N <= 0 || R <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0, irows = 0, vrows = 0, prows = 0; + const long long x_ld = r3d_rows_pitch(x, N, &rows); + const long long idx_ld = r3d_rows_pitch(idx, R, &irows); + const long long val_ld = r3d_rows_pitch(val, R, &vrows); + if (x_ld < 0 || idx_ld < 0 || val_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || N > 0x7fffffffLL || R > 0x7fffffffLL) + return R3D_NO(RAD_E_SHAPE); + if (irows < rows || vrows < rows) return R3D_NO(RAD_E_SHAPE); + long long pairs = 0, pairs_ld = 0; + if (pr && pr->data) { + pairs_ld = r3d_rows_pitch(pr, 2 * R, &prows); + if (pairs_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (prows < rows || r3d_numel(pr) < rows * 2 * R) return R3D_NO(RAD_E_SHAPE); + pairs = r3d_addr(pr); + } + return r3d_launch_status(r3d_row_topk(r3d_addr(x), r3d_addr(idx), r3d_addr(val), pairs, + (int)rows, (int)N, (int)R, xdt, x_ld, idx_ld, val_ld, + pairs_ld, (int)r3d_geti_or(a, "vocab_off", 0), + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ argmax and temp */ + +enum { ARG_LG = 0, ARG_PARAMS, ARG_TOK }; + +extern "C" int r3d_rad_sample_argmax(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, ARG_LG); + const RadTensor* pr = r3d_opt(a, ARG_PARAMS); + const RadTensor* tk = r3d_opt(a, ARG_TOK); + R3D_NEED(logits_ok(lg)); + if (!tk || !tk->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(tk)) return R3D_NO(RAD_E_DTYPE); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + if (n_vocab <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + if (lg_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(tk) < rows) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(tk) || !r3d_aligned(r3d_p(tk), 4)) return R3D_NO(RAD_E_SHAPE); + /* The kernel reads no scalar from the params plane, so a missing one is not a refusal: argmax is + * the row every greedy request needs, and libref describes the operand without reading it. */ + if (pr && pr->data) R3D_NEED(params_ok(pr, rows)); + return r3d_launch_status(r3d_sample_argmax(r3d_addr(lg), r3d_addr(tk), (int)rows, (int)n_vocab, + lg_ld, (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_temp(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, ARG_LG); + const RadTensor* pr = r3d_opt(a, ARG_PARAMS); + R3D_NEED(logits_ok(lg)); + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + if (n_vocab <= 0) return R3D_NO(RAD_E_SHAPE); + long long rows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + if (lg_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + R3D_NEED(params_ok(pr, rows)); + return r3d_launch_status(r3d_sample_temp(r3d_addr(lg), r3d_addr(pr), (int)rows, (int)n_vocab, + lg_ld, (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ sample_topk */ + +enum { TK_LG = 0, TK_PARAMS, TK_CI, TK_CV, TK_PAIRS }; + +extern "C" int r3d_rad_sample_topk(const RadArgs* a, RadStream stream) { + const RadTensor* lg = r3d_opt(a, TK_LG); + const RadTensor* pr = r3d_opt(a, TK_PARAMS); + const RadTensor* ci = r3d_opt(a, TK_CI); + const RadTensor* cv = r3d_opt(a, TK_CV); + const RadTensor* pp = r3d_opt(a, TK_PAIRS); + R3D_NEED(logits_ok(lg)); + if (!ci || !ci->data || !cv || !cv->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(ci)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(cv)) return R3D_NO(RAD_E_DTYPE); + if (pp && pp->data && !r3d_is_i32(pp)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_aligned(r3d_p(ci), 4) || !r3d_aligned(r3d_p(cv), 4)) return R3D_NO(RAD_E_ALIGN); + + const long long n_vocab = r3d_geti_or(a, "n_vocab", r3d_dim(lg, (int)lg->rank - 1)); + /* The width is the buffer's, the declare-time bound: the row's top_k narrows inside it. */ + const long long n_cand = r3d_dim(ci, (int)ci->rank - 1); + if (n_vocab <= 0 || n_cand <= 0 || n_cand > kCandMax) return R3D_NO(RAD_E_SHAPE); + long long rows = 0, cirows = 0, cvrows = 0, prows = 0; + const long long lg_ld = r3d_rows_pitch(lg, n_vocab, &rows); + const long long ci_ld = r3d_rows_pitch(ci, n_cand, &cirows); + const long long cv_ld = r3d_rows_pitch(cv, n_cand, &cvrows); + if (lg_ld < 0 || ci_ld < 0 || cv_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (rows <= 0 || rows > 0x7fffffffLL || n_vocab > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + if (cirows < rows || cvrows < rows || r3d_numel(cv) < rows * n_cand) return R3D_NO(RAD_E_SHAPE); + R3D_NEED(params_ok(pr, rows)); + long long pairs = 0, pairs_ld = 0; + if (pp && pp->data) { + pairs_ld = r3d_rows_pitch(pp, 2 * n_cand, &prows); + if (pairs_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (prows < rows || r3d_numel(pp) < rows * 2 * n_cand) return R3D_NO(RAD_E_SHAPE); + pairs = r3d_addr(pp); + } + return r3d_launch_status(r3d_sample_topk(r3d_addr(lg), r3d_addr(pr), r3d_addr(ci), r3d_addr(cv), + pairs, (int)rows, (int)n_vocab, (int)n_cand, lg_ld, + ci_ld, cv_ld, pairs_ld, + (int)r3d_geti_or(a, "vocab_off", 0), + (long)(uintptr_t)stream)); +} + +/* ------------------------------------------------------------------ the narrowing stages and the draw */ + +enum { NW_CI = 0, NW_CV, NW_PARAMS, NW_TOK }; + +struct CandRow { + long long n_cand, rows, ci_ld, cv_ld; +}; + +static inline int cand_row_ok(const RadArgs* a, const RadTensor* ci, const RadTensor* cv, + const RadTensor* pr, long long* M_hint, CandRow* g) { + if (!ci || !ci->data || !cv || !cv->data) return RAD_E_INVAL; + if (!r3d_is_i32(ci)) return RAD_E_DTYPE; + if (!r3d_is_f32(cv)) return RAD_E_DTYPE; + if (!r3d_aligned(r3d_p(ci), 4) || !r3d_aligned(r3d_p(cv), 4)) return RAD_E_ALIGN; + const long long n_cand = r3d_geti_or(a, "n_cand", r3d_dim(ci, (int)ci->rank - 1)); + if (n_cand <= 0 || n_cand > kCandMax) return RAD_E_SHAPE; + long long cirows = 0, cvrows = 0; + const long long ci_ld = r3d_rows_pitch(ci, n_cand, &cirows); + const long long cv_ld = r3d_rows_pitch(cv, n_cand, &cvrows); + if (ci_ld < 0 || cv_ld < 0) return RAD_E_STRIDE; + /* The step's rows are the operand's row count. The band key `M` is the plan's ceiling, never a + * source of row count: the plane decides the rows, and `M` is checked only as the upper bound + * the plan promised not to exceed. Preferring the key over the plane would refuse a step that + * fits the band. */ + const long long rows = cirows; + if (rows <= 0 || rows > 0x7fffffffLL) { r3d_trace_desc("ci", ci); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: %lld candidate rows, n_cand %lld\n", rows, n_cand); + return RAD_E_SHAPE; } + if (M_hint && *M_hint > 0 && rows > *M_hint) { r3d_trace_desc("ci", ci); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: %lld rows in a band that declared M <= %lld\n", + rows, *M_hint); + return RAD_E_SHAPE; } + if (cvrows < rows) { r3d_trace_desc("cv", cv); + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] sample: cv has %lld rows, ci has %lld\n", cvrows, rows); + return RAD_E_SHAPE; } + if (r3d_numel(cv) < rows * n_cand) return RAD_E_SHAPE; + const int s = params_ok(pr, rows); + if (s) return s; + g->n_cand = n_cand; g->rows = rows; g->ci_ld = ci_ld; g->cv_ld = cv_ld; + return RAD_OK; +} + +static int narrow_shim(const RadArgs* a, RadStream stream, + int (*launch)(long, long, long, int, int, long long, long long, long)) { + const RadTensor* ci = r3d_opt(a, NW_CI); + const RadTensor* cv = r3d_opt(a, NW_CV); + const RadTensor* pr = r3d_opt(a, NW_PARAMS); + CandRow g{}; + long long M_hint = r3d_geti_or(a, "M", 0); + const int s = cand_row_ok(a, ci, cv, pr, &M_hint, &g); + if (s) return R3D_NO(s); + return r3d_launch_status(launch(r3d_addr(ci), r3d_addr(cv), r3d_addr(pr), (int)g.rows, + (int)g.n_cand, g.ci_ld, g.cv_ld, (long)(uintptr_t)stream)); +} + +extern "C" int r3d_rad_sample_topp(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_topp); +} +extern "C" int r3d_rad_sample_minp(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_minp); +} +extern "C" int r3d_rad_sample_typical(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_typical); +} +extern "C" int r3d_rad_sample_xtc(const RadArgs* a, RadStream s) { + return narrow_shim(a, s, r3d_sample_xtc); +} + +extern "C" int r3d_rad_sample_pick(const RadArgs* a, RadStream stream) { + const RadTensor* ci = r3d_opt(a, NW_CI); + const RadTensor* cv = r3d_opt(a, NW_CV); + const RadTensor* pr = r3d_opt(a, NW_PARAMS); + const RadTensor* tk = r3d_opt(a, NW_TOK); + if (!tk || !tk->data) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_i32(tk)) return R3D_NO(RAD_E_DTYPE); + CandRow g{}; + long long M_hint = r3d_geti_or(a, "M", 0); + const int s = cand_row_ok(a, ci, cv, pr, &M_hint, &g); + if (s) return R3D_NO(s); + if (r3d_numel(tk) < g.rows) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(tk) || !r3d_aligned(r3d_p(tk), 4)) return R3D_NO(RAD_E_SHAPE); + return r3d_launch_status(r3d_sample_pick(r3d_addr(ci), r3d_addr(cv), r3d_addr(pr), r3d_addr(tk), + (int)g.rows, (int)g.n_cand, g.ci_ld, g.cv_ld, + (long)(uintptr_t)stream)); +} diff --git a/libr3d/r3d_sample_pre_f32.hip b/libr3d/r3d_sample_pre_f32.hip new file mode 100644 index 00000000..41e46231 --- /dev/null +++ b/libr3d/r3d_sample_pre_f32.hip @@ -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 + +#include + +/* ================================================================== 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 +__device__ __forceinline__ int32_t xor_i32(int32_t v) { + return (int32_t)r3d_xor_lane_u32((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 +__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((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(a.mx); \ + b.n = xor_i32((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), 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((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(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(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; +} diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp new file mode 100644 index 00000000..b8871575 --- /dev/null +++ b/libr3d/r3d_selftest.cpp @@ -0,0 +1,1321 @@ +/* r3d_selftest -- dump the libr3d row table, cross-check it, and prove every row links and runs. + * + * A transcription error in a constraint table stays invisible until a model silently picks the + * wrong kernel, and a codec one bit out on a subnormal shows up as a percentage of a perplexity. So + * the table is printed in full and checked against itself: + * + * - every row's `op` has a schema declared by this plugin, or nothing can select it; + * - every constraint key is a declared parameter of that op. libr3d's constraints and libref's + * schemas are one vocabulary, and a key renamed in only one place yields a row that matches + * nothing; + * - names are unique, launches exist, an init has a fini, a tunable's default is one of its + * values (the loader refuses a plugin whose default it cannot launch, and it is better to hear + * it here), and no row carries a `layout`, `relayout` or `unrelayout` hook: libr3d repacks + * nothing (r3d_rows.cpp explains why, and a hook appearing means a container format only this + * plugin can read has crept in); + * - every `opd_shape` describes as many operands as its schema declares, for a spread of + * geometries, with positive extents. + * + * The codecs are checked against the ABI's own host versions in `rad_plugin.h` over every bit + * pattern where the domain is small and a sweep where it is not: bf16 and f16 over all 65536, E4M3 + * over all 256 codes and the encoder over the saturating, subnormal, signed-zero and NaN cases, + * int8 against `rad_round_even_sat` over every tie in its band. This is the check `rad-kbench` + * cannot do: it compares whole ops, so a codec's disagreement appears as a diffuse percentage. + * libr3d's codecs are software -- the lane map, not a missing instruction, is the reason, and its + * bf16 packing is `v_perm` and not `v_cvt_pk_bf16_f32` -- so they are the plugin's own + * arithmetic and belong to the tests. + * + * Then, on a device, every launch is called with a minimal valid input built from the row's own + * `opd_shape`, and every output plane is read back and checked to be finite. That catches the class + * of bug a table check cannot: a null operand the shim does not test, a stride read from the wrong + * axis, an operand index off by one, an undefined symbol, a kernel that writes where it should not. + * + * The numerical oracle is `rad-kbench`, which replays `kernels.rkb` against libref; this program + * does not duplicate it. What it adds is that the rows are reachable at all -- on this card, from + * this .so, with the geometry their constraints state. + * + * The plugin is dlopened rather than linked, so an undefined symbol in the .so is caught too. + * + * One child process per row. A bad pointer handed to a kernel is a GPU page fault, which ROCr + * reports by printing a line and aborting the process. In one process the first bad row would end + * the run, and with stdout block-buffered down a pipe the fault line can land next to the wrong + * row. So the parent runs the static phase and then re-execs itself once per row with + * `--case `; a child killed by a signal is a FAIL naming the signal, and the run continues. + * posix_spawn rather than fork, because the parent already has the HIP runtime's threads up and + * only exec resets them. + * + * `--case ` is also the reproducer: it runs one row, alone, in the foreground. + */ + +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r3d_codecs.h" +#include "rad_planes.h" /* the joined scale+zero plane, for the row no shape hook can describe */ +#include "r3d_plugin.h" /* the entry points, for the shape hooks that precede their rows */ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* posix_spawn's environment; declared here rather than relying on unistd.h's _GNU_SOURCE guard. */ +extern char** environ; + +#ifdef RAD_HAVE_HIP +#include +#endif + +#define NELEM(a) ((int)(sizeof(a) / sizeof((a)[0]))) +static int g_fail = 0; +static void* g_h = nullptr; /* the plugin, opened by main */ +static int g_skip = 0; +static const char* g_case = nullptr; +static const char* g_plugin = nullptr; + +/* The plugin's table, reached through the symbols dlopened in main. The program is not linked + * against libr3d: an undefined symbol in the .so must be this program's failure, not its own + * failure to build. */ +static int (*P_count)(void) = nullptr; +static const RadKernelInfo* (*P_at)(int) = nullptr; +static int (*P_scount)(void) = nullptr; +static const RadOpSchema* (*P_sat)(int) = nullptr; + +static int rows() { return P_count ? P_count() : 0; } +static const RadKernelInfo* row_at(int i) { return P_at ? P_at(i) : nullptr; } +static int schemas() { return P_scount ? P_scount() : 0; } +static const RadOpSchema* schema_at(int i) { return P_sat ? P_sat(i) : nullptr; } + +/* The loader's messages are built with a printf into a string; so are these, so a failure reads + * like the line the engine would have printed. */ +static std::string fmt(const char* f, ...) { + va_list ap; + va_start(ap, f); + char buf[512]; + std::vsnprintf(buf, sizeof buf, f, ap); + va_end(ap); + return std::string(buf); +} + +static void say(const char* tag, const char* fmt, va_list ap) { + std::printf(" %s ", tag); + std::vprintf(fmt, ap); + std::printf("\n"); +} +static void ok(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("ok ", fmt, ap); va_end(ap); +} +static void fail(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("FAIL", fmt, ap); va_end(ap); ++g_fail; +} +static void skip(const char* fmt, ...) { + va_list ap; va_start(ap, fmt); say("skip", fmt, ap); va_end(ap); ++g_skip; +} + +static const RadOpSchema* find_schema(const char* op) { + if (!op) return nullptr; + for (int i = 0; i < schemas(); ++i) { + const RadOpSchema* s = schema_at(i); + if (s && s->op && !std::strcmp(s->op, op)) return s; + } + return nullptr; +} + +static const RadParamSpec* find_param(const RadOpSchema* s, const char* key) { + if (!s || !key) return nullptr; + for (int i = 0; i < s->n_params; ++i) + if (s->params[i].key && !std::strcmp(s->params[i].key, key)) return &s->params[i]; + return nullptr; +} + +/* ================================================================== the table's own checks + * + * Every check here has a failure mode behind it: a constraint on a key the schema does not declare + * (the row matches nothing, silently, and the model falls back to a reference kernel), a tunable + * default outside its axis (the loader refuses the whole plugin), a row whose `op` is spelled for + * another op's schema (one call meaning two things), a description whose operand count disagrees + * with its schema (every case for that op skipped, forever). + */ +static void check_table() { + const int n = rows(); + std::printf("== rows: %d, schemas: %d\n", n, schemas()); + + for (int i = 0; i < n; ++i) { + const RadKernelInfo* k = row_at(i); + if (!k) { fail("row %d is null", i); continue; } + std::printf("%-26s %-18s %-6s %s\n", k->name ? k->name : "(null)", + k->op ? k->op : "(null)", k->family ? k->family : "-", + k->priority >= 0 ? "" : "no priority"); + + if (!k->name || !*k->name) fail("row %d has no name", i); + else + for (int j = i + 1; j < n; ++j) { + const RadKernelInfo* o = row_at(j); + if (o && o->name && !std::strcmp(o->name, k->name)) + fail("row '%s' is declared twice", k->name); + } + if (!k->launch) fail("row '%s' has no launch", k->name); + if (k->init && !k->fini) fail("row '%s' inits without a fini", k->name); + if (k->domain != RAD_DOMAIN_DEVICE) fail("row '%s' is not a device row", k->name); + /* No row repacks a weight: the kernel reads the container's stored order, which is the rule that + * stops a plugin quietly demanding its own format. The exception is a class with a name list, and + * the class is the container's quantised weight: codes and scales stored as planes behind one + * operand, which the mapped tier will not place unless a loaded library can read them in place. + * Three rows, one per grid the container uses -- w2a8's {1,group} with a zero, the fp8a8 GEMM's + * {128,128} without, and the lm_head's same form -- each transcribed from the reference's own hook, + * including the case the reference answers nothing for (ref_layout_gemm_q reads zp_grid, and zp_grid + * has no fp8a8 entry). What carries the rule is the pair: every one of these names has a `layout` + * **and** a `relayout`, no row anywhere has an `unrelayout`, and a hook that names a joined layout + * without the writer that produces it is the failure the engine prints at load. A fifth name is a + * rule change, and it should fail here. */ + const bool joined = 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16") + || 0 == std::strcmp(k->name, "logits_gemm_bf16") + || 0 == std::strcmp(k->name, "gemm_nt_q_fp8a8_tiled") + || 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_tiled"); + /* The query and the writer come as a pair, and the pair is the rule: a row with a hook must + * supply the relayout that produces the form the hook names (abi/rad_abi.h -- a query + * answering RAD_OK is a promise the loader keeps on the row's word), and no row may carry an + * unrelayout, because nothing in this library invents a format a tool would need to invert. + * A hook with a null writer is the failure the engine reports at load -- `could not produce + * 'output.weight' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported` -- and a relayout + * without a hook is a row repacking a weight nobody asked to have repacked. */ + if ((k->layout && !joined) || (k->layout && !k->relayout) || (k->relayout && !joined) + || (k->relayout && !k->layout) || k->unrelayout) + fail("row '%s' declares a layout hook; libr3d stores weights in order", k->name); + if (!k->computes || !*k->computes || !k->shape || !*k->shape || !k->dtypes || + !*k->dtypes) + fail("row '%s' is missing prose", k->name); + + const RadOpSchema* s = find_schema(k->op); + if (!s) { fail("row '%s' implements '%s', which no schema declares", k->name, k->op); } + else { + for (int c = 0; c < k->n_constraints; ++c) { + const RadConstraint& x = k->constraints[c]; + const RadParamSpec* p = find_param(s, x.key); + if (!p) { + fail("row '%s' constrains '%s', not a parameter of '%s'", k->name, + x.key ? x.key : "(null)", k->op); + continue; + } + /* The selector compares a string constraint against a string parameter and an + * integer one against an integer. A mismatch matches nothing. */ + if (x.op == RAD_C_IN && p->type != RAD_P_STR) + fail("row '%s' matches '%s' with a string list on a non-string parameter", + k->name, x.key); + if (x.op == RAD_C_EQ && p->type == RAD_P_STR && !x.sval) + fail("row '%s' equals the string parameter '%s' with no string", k->name, + x.key); + if (x.op == RAD_C_IN && p->type == RAD_P_STR && x.sval) { + /* The band must name at least one value, and no value may be empty. */ + int words = 0; + for (const char* q = x.sval; *q; ++q) + if (*q == ' ') ++words; + if (!words && !*x.sval) fail("row '%s' constrains '%s' to nothing", k->name, + x.key); + } + if (x.op == RAD_C_DIV && x.ival <= 0) + fail("row '%s' constrains '%s' to divide by %lld", k->name, x.key, + (long long)x.ival); + } + } + + for (int t = 0; t < k->n_tunables; ++t) { + const RadTunable& a = k->tunables[t]; + if (!a.key || a.n_values <= 0 || !a.values) { + fail("row '%s' axis %d is empty", k->name, t); + continue; + } + bool has_default = false; + for (int v = 0; v < a.n_values; ++v) { + if (v && a.values[v] <= a.values[v - 1]) + fail("row '%s' axis '%s' values are not ascending", k->name, a.key); + if (a.values[v] == a.deflt) has_default = true; + } + if (!has_default) + fail("row '%s' axis '%s' defaults to %lld, which is not one of its values", + k->name, a.key, (long long)a.deflt); + if (!a.doc || !*a.doc) fail("row '%s' axis '%s' has no description", k->name, a.key); + } + } +} + +/* ================================================================== the reference library + * + * The loader refuses a plugin whose schema for an op differs from the one the first declarer fixed + * (core/plugin/loader.cpp, `schema_same`), and it refuses the *whole* .so, every row with it. The + * comparison is positional and narrow: parameter count, each parameter's key, type and + * requiredness; operand count, each operand's role and optionality. Operand names and doc strings + * are free, because arguments are positional and names are for diagnostics. + * + * So a schema copied from libref with one operand's role mistyped is a plugin that loads in + * r3d_selftest -- which does not open libref -- and disappears from the engine, with one line in a + * log most people never read. This check is the loader's own comparison, run here, naming the op + * and the slot. + */ +static void check_reference_schemas() { + std::printf("== schemas against the reference\n"); + + /* The reference library beside the plugin under test, the way the engine's home holds them. */ + std::string path(g_plugin); + const size_t slash = path.find_last_of('/'); + path = (slash == std::string::npos ? std::string() : path.substr(0, slash + 1)) + "libref.so"; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { skip("no reference library at %s (%s)", path.c_str(), dlerror()); return; } + auto rc = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto ra = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!rc || !ra) { skip("%s declares no schemas", path.c_str()); return; } + + static const char* kRole[] = { "in", "out", "inout", "weight", "wtab" }; + auto role_name = [](int r) { return (r >= 0 && r <= 4) ? kRole[r] : "?"; }; + int mismatches = 0, compared = 0; + for (int i = 0; i < schemas(); ++i) { + const RadOpSchema* mine = schema_at(i); + if (!mine || !mine->op) continue; + const RadOpSchema* theirs = nullptr; + for (int j = 0; j < rc() && !theirs; ++j) { + const RadOpSchema* o = ra(j); + if (o && o->op && !std::strcmp(o->op, mine->op)) theirs = o; + } + if (!theirs) { + /* Not a refusal: an op the reference does not serve is an op with nothing to agree + * with, and it is the reason libr3d's rows for a chain libref has no oracle for are + * checked by the selftest's own arithmetic instead. */ + skip("'%s' has no schema in the reference, so nothing to compare against", mine->op); + continue; + } + ++compared; + std::string diff; + if (mine->n_params != theirs->n_params) { + diff = fmt("%d parameters vs %d", mine->n_params, theirs->n_params); + } else { + for (int q = 0; q < mine->n_params && diff.empty(); ++q) { + const RadParamSpec& x = mine->params[q]; + const RadParamSpec& y = theirs->params[q]; + if (!x.key || std::strcmp(x.key, y.key ? y.key : "")) + diff = fmt("parameter %d is '%s' vs '%s'", q, x.key ? x.key : "(null)", + y.key ? y.key : "(null)"); + else if (x.type != y.type) + diff = fmt("parameter '%s' is %s vs %s", x.key, + x.type == RAD_P_STR ? "a string" : "an int", + y.type == RAD_P_STR ? "a string" : "an int"); + else if (x.required != y.required) + diff = fmt("parameter '%s' is %s in the reference", x.key, + y.required ? "required" : "optional"); + else if (x.role != y.role) + diff = fmt("parameter '%s' has core role %d vs %d", x.key, x.role, y.role); + } + if (diff.empty() && mine->n_operands != theirs->n_operands) + diff = fmt("%d operands vs %d", mine->n_operands, theirs->n_operands); + for (int q = 0; q < mine->n_operands && diff.empty(); ++q) { + const RadOperandSpec& x = mine->operands[q]; + const RadOperandSpec& y = theirs->operands[q]; + /* The name is free; the role and the optionality are the contract. */ + if (x.role != y.role) + diff = fmt("operand %d ('%s' / '%s') has a different role: %s vs %s", q, + x.name ? x.name : "?", y.name ? y.name : "?", + role_name(x.role), role_name(y.role)); + else if (x.optional != y.optional) + diff = fmt("operand %d ('%s') is %s in the reference", q, + x.name ? x.name : "?", y.optional ? "optional" : "required"); + } + } + if (!diff.empty()) { + fail("'%s' has two schemas: the reference fixed it, libr3d disagrees (%s)", mine->op, + diff.c_str()); + ++mismatches; + } + } + if (!mismatches) + ok("%d of %d schemas match the reference, slot for slot%s", compared, schemas(), + schemas() == compared ? "" : " (the rest the reference does not declare)"); + dlclose(h); +} + +/* ================================================================== band reachability + * + * A row is chosen by matching its constraints against a band's geometry, and the engine's rule + * (core/util/rad_util.cpp, constraint_holds) is that a constraint on a key the geometry lacks does + * not hold, in its own words "a row constraining an optional parameter serves only callers that + * state it, and others get a row without it". The bands an architecture emits carry the parameters + * its graph set, and nothing else, so a row that constrains an optional parameter is a row narrowed + * to the graphs that spell that parameter out. + * + * Nothing in kbench shows this: a fixture case names every parameter the op declares, so the + * constraint is tested against a geometry that has it. A server shows all of it, at startup, as + * "N device band(s) resolved to no kernel" and a model that will not start. So the check is here: + * a constraint on an optional parameter is not an error -- it is how a row says "I serve the form + * that states the parameter" -- but it is a decision, and a row whose author did not make it is a + * row that will silently not serve. + */ +static void check_band_reach() { + std::printf("== band reachability\n"); + std::string path(g_plugin); + const size_t slash = path.find_last_of('/'); + path = (slash == std::string::npos ? std::string() : path.substr(0, slash + 1)) + "libref.so"; + void* h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (!h) { skip("no reference library at %s", path.c_str()); return; } + auto rc = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + auto ra = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!rc || !ra) { skip("%s declares no schemas", path.c_str()); return; } + + int narrowed = 0, checked = 0; + for (int i = 0; i < rows(); ++i) { + const RadKernelInfo* k = row_at(i); + if (!k || !k->op) continue; + const RadOpSchema* s = nullptr; + for (int j = 0; j < rc() && !s; ++j) { + const RadOpSchema* o = ra(j); + if (o && o->op && !std::strcmp(o->op, k->op)) s = o; + } + if (!s) continue; /* the table phase already failed this row */ + for (int ci = 0; ci < k->n_constraints; ++ci) { + const RadConstraint& c = k->constraints[ci]; + if (!c.key) continue; + ++checked; + const RadParamSpec* sp = nullptr; + for (int q = 0; q < s->n_params && !sp; ++q) + if (s->params[q].key && !std::strcmp(s->params[q].key, c.key)) sp = &s->params[q]; + if (sp && !sp->required) { + ok("row '%s' constrains '%s', optional on '%s': a band that leaves it out does not " + "resolve to this row", k->name, c.key, k->op); + ++narrowed; + } + } + } + if (!narrowed) ok("%d constraint(s) over %d rows, every one on a parameter a band always " + "carries", checked, rows()); + dlclose(h); +} + +/* ================================================================== the operand descriptions + * + * Against the schemas, for one geometry per op taken from the widths a model really has: 4096 + * hidden, 128 head, 11008 intermediate, 128256 vocabulary. A description that returns a count the + * schema disagrees with, a rank of zero, or an extent of zero is a bug in the description or in the + * schema; rad-kbench reports it as a skipped case for every geometry, which is how a broken hook + * hides for years. + */ +static void check_shapes() { + /* RadParam is { key, kind, ival, ihi, sval, dval }. */ +#define PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define PF(k, v) { (k), RAD_P_F64, 0, 0, nullptr, (double)(v) } +#define PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + struct Geom { const char* op; std::vector p; }; + const std::vector g = { + { "rmsnorm", { PI("M", 8), PI("n", 4096), PF("eps", 1e-5), PS("dtype", "bf16") } }, + { "layernorm", { PI("M", 8), PI("n", 4096), PF("eps", 1e-5), PS("dtype", "bf16") } }, + { "add", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "mul", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "act_mul", { PI("M", 8), PI("n", 11008), PS("act", "silu"), PS("dtype", "bf16") } }, + { "silu", { PI("M", 8), PI("n", 11008), PS("dtype", "bf16") } }, + { "gelu", { PI("M", 8), PI("n", 11008), PS("dtype", "bf16") } }, + { "sigmoid", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "softmax", { PI("M", 8), PI("n", 4096), PS("dtype", "f32") } }, + { "cast", { PI("M", 8), PI("n", 4096), PS("from", "bf16"), PS("to", "f32") } }, + { "scale", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "fill", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16"), PF("value", 0.0) } }, + { "rope", { PI("M", 8), PI("head_dim", 128), PI("n_head", 32), PI("n_head_kv", 8), + PF("theta", 500000.0), PF("scale", 1.0), PS("mode", "neox") } }, + { "kv_store", { PI("M", 8), PI("head_dim", 128), PI("n_head_kv", 8), PI("block_size", 32), + PS("kv_dtype", "bf16") } }, + { "embed_lookup", { PI("M", 8), PI("n_embd", 4096), PI("n_vocab", 128256), + PS("dtype", "bf16") } }, + { "gather_rows", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "scatter_rows", { PI("M", 8), PI("n", 4096), PS("dtype", "bf16") } }, + { "quant_act_fp8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "quant_act_i8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "quant_act_i8g", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "gated_quant_fp8", { PI("M", 8), PI("n", 11008), PI("group", 128), PS("dtype", "bf16"), + PS("act", "silu") } }, + { "dequant", { PI("M", 11008), PI("n", 4096), PI("group", 128), + PS("dtype", "fp8_e4m3") } }, + { "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PI("eps", 1e-5), PI("group", 128), + PS("dtype", "bf16") } }, + { "gemm_nt", { PI("M", 8), PI("N", 11008), PI("K", 4096), PS("dtype", "bf16") } }, + { "gemm_nt_q", { PI("M", 8), PI("N", 11008), PI("K", 4096), PI("group", 128), + PS("dtype", "fp8a16"), PI("pb1", 128), PI("pb2", 128) } }, + /* The rest are the bands MiniCPM5-2B asks for, in /home/sysadmin/libr3d/bands.txt: the + * model's own widths, not invented ones. The vocab is 130560, the MLP is 6144 wide, the + * head is 128 with 16 heads over 2 KV heads at 16-token blocks. */ + { "silu_mul", { PI("M", 1792), PI("n", 6144), PS("dtype", "bf16") } }, + { "attn_paged", { PI("q_len", 2048), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PI("n_head", 16), PI("max_ctx", 4096), + PI("max_seqs", 256) } }, + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("max_ctx", 4096), + PI("max_seqs", 256) } }, + /* The decode band with the context deeper than the query chunk: the walk has to cover keys + * that precede the chunk, which is the only thing in the op a q_len-sized cache cannot + * show. The second is the geometry that found the tile-sharing bug -- a window that starts + * mid-block, over an fp8 cache. */ + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 0), PI("window", 0), PS("q_dtype", "bf16"), + PS("kv_dtype", "bf16"), PI("n_head", 16), PI("ctx", 4096), + PI("max_ctx", 4096) } }, + { "attn_paged", { PI("q_len", 7), PI("head_dim", 128), PI("gqa", 8), PI("block_size", 16), + PI("causal", 1), PI("window", 37), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 16), PI("ctx", 512), + PI("max_ctx", 4096) } }, + /* The 27B's sliding-window band, in the shape the fixture draws it: the shape hook describes + * the descales as ABSENT, so this is the case where an fp8 cache has no scale plane and the + * reference reads 1.0. It is the geometry kbench caught a refusal on. */ + { "attn_paged", { PI("q_len", 1), PI("head_dim", 128), PI("gqa", 4), PI("block_size", 16), + PI("causal", 0), PI("window", 2048), PS("q_dtype", "bf16"), + PS("kv_dtype", "fp8_e4m3"), PI("n_head", 32), PI("max_seqs", 8), + PI("max_ctx", 262144) } }, + { "row_topk", { PI("M", 1792), PI("N", 130560), PI("R", 16), PS("dtype", "bf16") } }, + { "sample_argmax", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_temp", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_topk", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_topp", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_minp", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_typical", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_xtc", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_pick", { PI("M", 2048), PI("n_cand", 1024) } }, + { "sample_penalties", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_dry", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_ngram_ban", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_mask", { PI("M", 2048), PI("n_vocab", 130560) } }, + { "sample_logprobs", { PI("M", 2048), PI("n_vocab", 130560), PI("k", 21) } }, + /* The speculative decoder's band, as MiniCPM5-2B declares it: a 7-token draft block, 16 + * candidates a step, a rank-256 codebook over a 130560-token vocabulary, anchors strided 7 + * apart. The two codebooks are 63.8 MiB each, which is what the op really is. */ + { "dflash_select", { PI("M", 256), PI("steps", 7), PI("top_k", 16), PI("rank", 256), + PI("n_vocab", 130560), PI("anchor_stride", 7), PS("dtype", "bf16") } }, + }; +#undef PI +#undef PF +#undef PS + + /* The descriptions of the ops whose kernels have not landed: the schemas and the hooks are in + * the library, checked the moment it loads, so a transcription typo is found here and not on the + * day the row lands and kbench skips its cases -- "describes an output differently" is one line + * in a report, and a row nobody exercises is a row nobody tested. */ + /* By symbol name, dlsym'd from the plugin: this program links nothing from the library under + * test -- that is the point of dlopening it -- so a hook is a name and a pointer out of the + * handle, exactly as the rows are. */ + static const struct { const char* op; const char* sym; } kHooks[] = { + { "silu_mul", "r3d_shape_silu_mul" }, { "attn_paged", "r3d_shape_attn_paged" }, + { "row_topk", "r3d_shape_row_topk" }, { "sample_argmax", "r3d_shape_sample_argmax" }, + { "sample_temp", "r3d_shape_sample_temp" }, { "sample_topk", "r3d_shape_sample_topk" }, + { "sample_topp", "r3d_shape_sample_topp" }, { "sample_minp", "r3d_shape_sample_minp" }, + { "sample_typical", "r3d_shape_sample_typical" }, + { "sample_xtc", "r3d_shape_sample_xtc" }, { "sample_pick", "r3d_shape_sample_pick" }, + { "sample_penalties", "r3d_shape_sample_penalties" }, + { "sample_dry", "r3d_shape_sample_dry" }, { "sample_ngram_ban", "r3d_shape_sample_ngram_ban" }, + { "sample_mask", "r3d_shape_sample_mask" }, { "sample_logprobs", "r3d_shape_sample_logprobs" }, + }; + + for (const Geom& gm : g) { + const RadOpSchema* s = find_schema(gm.op); + if (!s) { fail("the geometry for '%s' has no schema", gm.op); continue; } + const RadKernelInfo* row = nullptr; + RadShapeFn hook = nullptr; + for (int i = 0; i < rows() && !row; ++i) { + const RadKernelInfo* k = row_at(i); + if (k && k->op && !std::strcmp(k->op, gm.op) && k->opd_shape) row = k; + } + if (row) hook = row->opd_shape; + for (size_t q = 0; q < NELEM(kHooks) && !hook; ++q) + if (!std::strcmp(kHooks[q].op, gm.op)) + hook = (int (*)(const RadParam*, int, int, RadOpdDesc*))dlsym(g_h, kHooks[q].sym); + if (!hook) { skip("no operand description for '%s' -- no row and no hook", gm.op); + continue; } + if (!row) std::printf(" -- '%s': the hook, ahead of its kernel\n", gm.op); + + bool bad = false; + for (int o = 0; o < s->n_operands && !bad; ++o) { + RadOpdDesc d{}; + const int st = hook(gm.p.data(), (int)gm.p.size(), o, &d); + if (st == RAD_E_UNSUPPORTED) { skip("'%s': the description declines this geometry", + gm.op); bad = true; break; } + if (st != RAD_OK) { fail("'%s' operand %d: the description returns %d", gm.op, o, st); + bad = true; break; } + if (d.flags & RAD_OPD_F_ABSENT) { + if (!s->operands[o].optional) + { fail("'%s' operand %d is required and described absent", gm.op, o); bad = true; } + continue; + } + if (d.rank == 0 || d.rank > RAD_MAX_RANK) + { fail("'%s' operand %d has rank %u", gm.op, o, d.rank); bad = true; break; } + for (uint32_t r = 0; r < d.rank && !bad; ++r) + if (d.shape[r] <= 0) + { fail("'%s' operand %d extent %u is %lld", gm.op, o, r, + (long long)d.shape[r]); bad = true; } + if (rad_dtype_bits(d.dtype) <= 0) + { fail("'%s' operand %d has an unparseable dtype", gm.op, o); bad = true; } + } + if (!bad) ok("'%s' described over %d operands", gm.op, s->n_operands); + } +} + +/* ================================================================== the codecs + * + * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the + * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into + * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. + */ +/* Two floats are the same when their bits are: `a == b` is false for two NaNs, and a codec that + * quiet a NaN the same way the ABI's does is a codec that agrees. */ +static bool same_float(float a, float b) { + return bits_of(a) == bits_of(b); +} + +/* ================================================================== the codecs + * + * Against the ABI's host implementations. Exactness is the claim, and it is the claim because the + * widenings are exact (seven mantissa bits into ten, four exponent and three mantissa bits into + * five and ten) and the encoders are mirrors of `rad_plugin.h`, line for line. + */ +static void check_codecs() { + std::printf("== codecs\n"); + + /* bf16: every one of the 65536 patterns, both directions. */ + int bad = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t b = (uint16_t)u; + if (!same_float(bf16_to_f32(b), rad_bf16_to_f32(b))) { ++bad; break; } + /* Encoder against encoder: a NaN's payload is quieted on the way out by both, so a + * round-trip to the original pattern is not the claim. */ + if (f32_to_bf16(bf16_to_f32(b)) != rad_f32_to_bf16(rad_bf16_to_f32(b))) { ++bad; break; } + } + if (bad) fail("bf16: the codecs disagree with rad_plugin.h"); + else ok("bf16: 65536 patterns, decode and encode, match rad_plugin.h bit for bit"); + + /* f16: the same, subnormals included -- the narrowing keeps them, which the ABI's codec does + * and a naive shift-and-round does not. */ + bad = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t h = (uint16_t)u; + const float f = f16_to_f32(h); + if (!same_float(f, rad_f16_to_f32(h))) { ++bad; break; } + if (f32_to_f16(f) != rad_f32_to_f16(rad_f16_to_f32(h))) { ++bad; break; } + } + if (bad) fail("f16: the codecs disagree with rad_plugin.h"); + else ok("f16: 65536 patterns, both directions, match rad_plugin.h (subnormals included)"); + + /* A bf16 pair widened to an f16 pair, in one register, exactly -- the reason the dot2 path is + * sound. Exact over f16's normal range [2^-14, 65504], as r3d_codecs.h states, and the sweep is + * over the patterns in it. Outside, the widening is not exact and is not claimed to be: above + * 65504 it saturates, and below 2^-14 an f16 subnormal's grid is coarser than bf16's, so the + * packing instruction truncates toward zero. Those patterns are counted and named in the + * message, because the number of them -- and the fact that they are the format's range, not a + * bug -- is the thing a reader needs. */ + bad = 0; + int inside = 0, outside = 0; + for (uint32_t u = 0; u < 0x10000 && !bad; ++u) { + const uint16_t b = (uint16_t)u; + const float v = bf16_to_f32(b); + const float av = v < 0.0f ? -v : v; + if (!(av >= 6.103515625e-05f && av <= 65504.0f)) { ++outside; continue; } /* f16 normals */ + ++inside; + const uint32_t w = ((uint32_t)(uint16_t)(b ^ 0x8000u) << 16) | b; + const uint32_t p = bf16x2_to_f16x2(w); + if (!same_float(f16_to_f32((uint16_t)(p & 0xFFFFu)), v) || + !same_float(f16_to_f32((uint16_t)(p >> 16)), -v)) { ++bad; break; } + } + if (bad) fail("bf16x2 -> f16x2 is not exact over f16's normal range"); + else ok("bf16 -> f16 exact over the %d patterns in f16's normal range (the other %d saturate " + "or truncate as the format says they must)", inside, outside); + + /* E4M3, both directions, over every code. The widening to f16 is exact for every code: e4m3 has + * four exponent and three mantissa bits, f16 five and ten, and 448 is well inside f16. */ + bad = 0; + for (uint32_t c = 0; c < 256 && !bad; ++c) { + if (!same_float(e4m3_to_f32((uint8_t)c), rad_fp8e4m3_to_f32((uint8_t)c))) { ++bad; break; } + if ((c & 0x7Fu) == 0x7Fu) continue; /* the code's one NaN */ + if (f32_to_e4m3(e4m3_to_f32((uint8_t)c)) != (uint8_t)c) { ++bad; break; } + const uint32_t p = e4m3x2_to_f16x2((c << 8) | c); + const float want = e4m3_to_f32((uint8_t)c); + if (!same_float(f16_to_f32((uint16_t)(p & 0xFFFFu)), want) || + !same_float(f16_to_f32((uint16_t)(p >> 16)), want)) { ++bad; break; } + } + if (bad) fail("e4m3: the codecs disagree with rad_plugin.h, or the widening is not exact"); + else ok("e4m3: 256 codes both ways, and the f16 widening exact, match rad_plugin.h"); + + /* The encoder over the cases that break a naive one: saturation at 448, the subnormals below + * 2^-6, the sign of zero, NaN, and the values a scale lands on. */ + bad = 0; + const float sweep[] = { 0.0f, -0.0f, 1.0f / 512, 1.0f / 1024, 1.0f / 6, 0.33f, 1.0f, 1.7f, + 2.0f, 3.0f, 447.0f, 448.0f, 449.0f, 1024.0f, 1e30f, -1e30f, + 1.0f / 0.0f, -1.0f / 0.0f, 0.0f / 0.0f, 1.0f / 448, 5.0f / 448, + 448.0f * 1.0000001f, 447.99f, -0.0f - 0.0f }; + int sbad = 0; + for (float v : sweep) + if (f32_to_e4m3(v) != rad_f32_to_fp8e4m3(v)) ++sbad; + if (sbad) fail("e4m3: %d of %d sweep values disagree with rad_plugin.h", sbad, + (int)(sizeof(sweep) / sizeof(sweep[0]))); + else ok("e4m3 encoder: saturating, subnormal, signed-zero and NaN cases match rad_plugin.h"); + (void)bad; + + /* int8: round to nearest, ties to even, saturating, over every tie and past the band. */ + bad = 0; + for (int i = -600; i <= 600 && !bad; ++i) + for (int f = 0; f < 4; ++f) { + const float v = (float)i + 0.25f * (float)f; + if (f32_to_i8_rtne(v) != (int8_t)rad_round_even_sat(v, -128.0, 127.0)) { ++bad; break; } + } + if (bad) fail("int8: the encoder disagrees with rad_round_even_sat"); + else ok("int8 encoder: 4804 values, every tie in the band, match rad_round_even_sat"); + + /* dot2's order. The device instruction folds the products with guard bits, so the host path is + * the reference's arithmetic and this checks only that the pairs are read low-then-high: the + * GEMMs' accumulation order is checked by rad-kbench against libref. */ + float acc = 0.0f; + const uint32_t a = f16x2_pack(1.5f, -2.5f), b = f16x2_pack(4.0f, 4.0f); + acc = dot2_f16x2(a, b, acc); + if (acc != 1.5f * 4.0f + -2.5f * 4.0f) fail("dot2: the pair is not read low-then-high"); + else ok("dot2: the pair is read low-then-high, into the accumulator it is handed"); + + /* The bf16 store a kernel's epilogue uses: two values, one dword, round to nearest even, the + * high half in the high half. A `v_perm` picking the wrong bytes shows up here and not in a + * kernel's output, where a swapped pair looks like a plausible tensor. */ + bad = 0; + for (int i = -500; i < 500 && !bad; ++i) { + const float lo = (float)i * 0.001f, hi = (float)i * -0.002f; + const uint32_t w = bf16x2_rne(lo, hi); + if (!same_float(bf16w_lo(w), rad_bf16_to_f32(rad_f32_to_bf16(lo))) || + !same_float(bf16w_hi(w), rad_bf16_to_f32(rad_f32_to_bf16(hi)))) { ++bad; break; } + } + if (bad) fail("bf16x2_rne: the pair is not (low, high) as rad_f32_to_bf16 rounds it"); + else ok("bf16x2_rne: a pair packs as rad_f32_to_bf16 rounds it, low half low"); +} + +/* ================================================================== a row, run + * + * Buffers from the row's own `opd_shape`, filled per the fill code the description carries, the + * launch called, the outputs read back and checked to be finite. + */ +enum { MAX_OPD = 24 }; + +struct Case { + RadTensor t[MAX_OPD]; + RadParam p[32]; + std::vector dev; + std::vector host; /* pinned operands: read on the host, read by the kernel too */ + std::vector words; /* the strings out.sval points into; reserved in make_params */ + int n_p = 0; +}; + +/* ================================================================== the lane helpers, on the card + * + * Every wave-sum in the library is five rounds of a butterfly over lane shuffles, and the + * arithmetic that rides on a shuffle is invisible to a codec sweep: `d += (double)f((unsigned long + * long)d)` moves a *value* where a bit pattern is wanted, and a wave of fractions then sums to 1 -- + * which is a bug this file's own predecessor shipped, in the logprobs sum, and which showed up as + * 40% of a row's probability mass missing at one shape. So the card runs the butterflies through + * `r3d_lanes_check` (r3d_sample_pre_f32.hip) and every lane of every wave is compared with a host + * emulation of the same five rounds, in the same order. + */ +static void check_lanes() { + std::printf("== lane helpers\n"); + auto run = (int (*)(long, long))dlsym(g_h, "r3d_lanes_check"); + if (!run) { skip("r3d_lanes_check is not in this plugin"); return; } +#ifndef RAD_HAVE_HIP + skip("built without HIP: the lane helpers are not checked"); + return; +#else + enum { NF = 4, NT = 256, NW = 32 }; + auto seed = [](int l) { + return l == 6 ? 0.08945 : l == 9 ? 1.0 : l == 19 ? 0.5971 : l == 25 ? 0.9768 : 0.0; + }; + /* The butterfly the kernel runs, emulated: five rounds, lane l meeting lane l^N. */ + double wd[NW]; + float wf[NW]; + for (int l = 0; l < NW; ++l) { wd[l] = seed(l); wf[l] = (float)seed(l); } + for (int N = NW / 2; N >= 1; N >>= 1) { + double t[NW]; + float u[NW]; + for (int l = 0; l < NW; ++l) { t[l] = wd[l ^ N]; u[l] = wf[l ^ N]; } + for (int l = 0; l < NW; ++l) { wd[l] += t[l]; wf[l] += u[l]; } + } + static const char* names[NF] = { + "f32 butterfly, the shape every wave_sum is", + "f64 halves (r3d_xor_lane_u64), lane-derived", + "f64 halves (r3d_xor_lane_u64), loaded from LDS", + "f64 one 64-bit __shfl_xor_sync, loaded from LDS", + }; + double* d = nullptr; + const size_t bytes = (size_t)NF * NT * sizeof(double); + if (hipMalloc(&d, bytes) != hipSuccess) { skip("no device for the lane helpers"); return; } + if (hipMemset(d, 0, bytes) != hipSuccess) { fail("could not clear the lane helper's plane"); + (void)hipFree(d); return; } + if (run((long)(uintptr_t)d, 0) != 0) { + fail("r3d_lanes_check refused to launch"); + (void)hipFree(d); + return; + } + if (hipDeviceSynchronize() != hipSuccess) { + fail("the lane helper kernel faulted"); + (void)hipFree(d); + return; + } + std::vector out((size_t)NF * NT, 0.0); + if (hipMemcpy(out.data(), d, bytes, hipMemcpyDeviceToHost) != hipSuccess) { + fail("reading the lane helper's plane back failed"); + (void)hipFree(d); + return; + } + (void)hipFree(d); + for (int f = 0; f < NF; ++f) { + int bad = 0, first = -1; + for (int i = 0; i < NT; ++i) { + const double w = (f == 0) ? (double)wf[i % NW] : wd[i % NW]; + uint64_t a, b; + std::memcpy(&a, &out[(size_t)f * NT + i], 8); + std::memcpy(&b, &w, 8); + if (a != b) { ++bad; if (first < 0) first = i; } + } + if (!bad) { + ok("%s: %d lanes over %d waves, every one exact (wave sums to %.6f)", names[f], NT, + NT / NW, wd[0]); + continue; + } + const double w = (f == 0) ? (double)wf[first % NW] : wd[first % NW]; + fail("%s: %d of %d lanes disagree; first is lane %d of wave %d: %.17g, want %.17g", + names[f], bad, NT, first % NW, first / NW, out[(size_t)f * NT + first], w); + } +#endif +} + +static size_t dt_bytes(uint32_t dt) { + const int bits = rad_dtype_bits(dt); + return bits > 0 ? (size_t)((bits + 7) / 8) : 1; +} + +static uint32_t xorshift(uint32_t& s) { + s ^= s << 13; s ^= s >> 17; s ^= s << 5; + return s; +} + +/* Fill a host plane per its description. "Normals" is a sum of four uniforms: a kernel's + * arithmetic is exercised by any value that is not a special case, and the special cases are what + * the hand-written cases and rad-kbench's sweeps are for. */ +static void fill_plane(const RadOpdDesc& d, uint8_t* p, size_t nel, uint32_t seed) { + uint32_t s = seed ? seed : 1u; + const size_t nbyte = d.dtype == RAD_U2 ? nel / 4 + : (d.dtype == RAD_U4 || d.dtype == RAD_I4 || d.dtype == RAD_FP4E2M1) ? nel / 2 + : nel * dt_bytes(d.dtype); + std::memset(p, 0, nbyte); + if (d.fill == RAD_FILL_INDEX) { + const long long mx = d.idx_const >= 0 ? d.idx_const + : (d.idx_max > 0 ? d.idx_max : (long long)nel); + for (size_t i = 0; i < nel; ++i) { + const long long v = d.idx_const >= 0 + ? d.idx_const + : (long long)(xorshift(s) % (uint32_t)(mx > 0 ? mx : 1)); + if (dt_bytes(d.dtype) >= 8) *(int64_t*)(p + i * dt_bytes(d.dtype)) = v; + else if (dt_bytes(d.dtype) == 4) *(int32_t*)(p + i * 4) = (int32_t)v; + else p[i] = (uint8_t)v; + } + return; + } + if (d.dtype == RAD_I4) { + /* Two signed codes a byte, the low nibble first: both grids' -7..7 draw, stored in + * two's complement, which is the low four bits. */ + for (size_t j = 0; j < nel / 2; ++j) { + double v0 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; + double v1 = ((double)xorshift(s) / 4294967296.0) * 2.0 - 1.0; + const int c0 = (int)(v0 * 7.0); + const int c1 = (int)(v1 * 7.0); + p[j] = (uint8_t)(((uint32_t)c0 & 0xFu) | (((uint32_t)c1 & 0xFu) << 4)); + } + return; + } + if (d.dtype == RAD_FP4E2M1) { + /* Two e2m1 codes a byte, drawn independently: all 16 values, so the unpack's magnitude + * and sign paths are both exercised. */ + for (size_t j = 0; j < nel / 2; ++j) { + const uint8_t lo = (uint8_t)(xorshift(s) & 0xFu); + const uint8_t hi = (uint8_t)(xorshift(s) & 0xFu); + p[j] = (uint8_t)(lo | (hi << 4)); + } + return; + } + for (size_t i = 0; i < nel; ++i) { + double v = 0.0; + for (int k = 0; k < 4; ++k) v += (double)xorshift(s) / 4294967296.0; + v = v / 4.0 * 2.0 - 1.0; /* [-1, 1) */ + if (d.fill == RAD_FILL_SIGMOID) v = 0.05 + 0.9 * (v * 0.5 + 0.5); + switch (d.dtype) { + case RAD_F32: *(float*)(p + i * 4) = (float)v; break; + case RAD_BF16: *(uint16_t*)(p + i * 2) = f32_to_bf16((float)v); break; + case RAD_F16: *(uint16_t*)(p + i * 2) = f32_to_f16((float)v); break; + case RAD_F8E4M3: p[i] = f32_to_e4m3((float)v); break; + case RAD_I8: *(int8_t*)(p + i) = (int8_t)(v * 100.0); break; + case RAD_U8: p[i] = (uint8_t)(v * 100.0 + 128.0); break; + case RAD_I32: + case RAD_U32: *(int32_t*)(p + i * 4) = (int32_t)(v * 1000.0); break; + case RAD_I64: *(int64_t*)(p + i * 8) = (int64_t)(v * 1000.0); break; + default: break; + } + } +} + +/* The geometry a row is run at: the band's bounds where the row constrains them, the widths a + * model has elsewhere. Reading the row's own constraints is what makes this a test of the + * constraint table and not of a geometry the table happens to admit. */ +static void make_params(Case& c, const RadKernelInfo* k, const RadOpSchema* s) { + c.words.reserve(32); /* more parameters than any op declares, so no string ever moves */ + for (int q = 0; q < s->n_params && c.n_p < 32; ++q) { + const RadParamSpec& sp = s->params[q]; + /* Only the parameters the geometry has to carry. The engine passes the graph's parameters + * with their ranges collapsed, and an optional parameter the graph did not set is simply + * not in the list: the kernel's own default is then the one libref's `p_*` default is. A + * selftest that filled every optional slot with a value would be testing a geometry no + * graph produces -- and for rope, whose optional `sections` string switches the position + * plane to one row per component, it would be testing a mode the row's constraints + * exclude. Constrained parameters are always passed: the constraint states the row's band, + * so its value is the row's own claim. */ + bool constrained = false; + for (int ci = 0; ci < k->n_constraints && !constrained; ++ci) + if (k->constraints[ci].key && sp.key && !std::strcmp(k->constraints[ci].key, sp.key)) + constrained = true; + if (!sp.required && !constrained) continue; + RadParam out{}; + out.key = sp.key; + out.kind = sp.type; + out.ival = 8; + out.dval = 1.0; + out.sval = "bf16"; + if (sp.key && !std::strcmp(sp.key, "eps")) out.dval = 1e-5; + if (sp.key && !std::strcmp(sp.key, "theta")) out.dval = 500000.0; + if (sp.key && !std::strcmp(sp.key, "head_dim")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "n_head")) out.ival = 8; + if (sp.key && !std::strcmp(sp.key, "n_head_kv")) out.ival = 8; + if (sp.key && !std::strcmp(sp.key, "block_size")) out.ival = 32; + if (sp.key && !std::strcmp(sp.key, "gqa")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "q_len")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "causal")) out.ival = 1; + if (sp.key && !std::strcmp(sp.key, "window")) out.ival = -1; + if (sp.key && !std::strcmp(sp.key, "n")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "N")) out.ival = 11008; + if (sp.key && !std::strcmp(sp.key, "K")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "n_embd")) out.ival = 4096; + if (sp.key && !std::strcmp(sp.key, "n_vocab")) out.ival = 128256; + if (sp.key && !std::strcmp(sp.key, "group")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "pb1")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "pb2")) out.ival = 128; + if (sp.key && !std::strcmp(sp.key, "from")) out.sval = "bf16"; + if (sp.key && !std::strcmp(sp.key, "to")) out.sval = "f32"; + if (sp.key && !std::strcmp(sp.key, "act")) out.sval = "silu"; + /* A constraint's own value wins: it is the band the row is compiled for, and C_IN spells + * the whole list. A list takes its first word. */ + for (int ci = 0; ci < k->n_constraints; ++ci) { + const RadConstraint& x = k->constraints[ci]; + if (!x.key || !sp.key || std::strcmp(x.key, sp.key)) continue; + if (x.op == RAD_C_EQ && sp.type == RAD_P_STR && x.sval) out.sval = x.sval; + if ((x.op == RAD_C_EQ || x.op == RAD_C_GE) && sp.type == RAD_P_INT) out.ival = x.ival; + if (x.op == RAD_C_IN && sp.type == RAD_P_STR && x.sval && x.sval[0]) { + /* The band's first word. The words outlive the parameter list, so they live in a + * vector that is reserved once: a string built per constraint and pointed at from + * out.sval is a pointer to storage the next constraint reuses, and a row with two + * string constraints reads the second one's value into the first's key. */ + c.words.emplace_back(x.sval); + std::string& w = c.words.back(); + const size_t sp0 = w.find(' '); + if (sp0 != std::string::npos) w.resize(sp0); + out.sval = w.c_str(); + } + } + c.p[c.n_p++] = out; + } +} + +/* ------------------------------------------------------------------ a row with no shape hook + * + * `gemm_q_shape` declines w2a8 for a good reason: the container stores the weight's scale and zero + * as two planes behind the one `b_scale` operand, and a RadOpdDesc names one dtype and one extent + * set, so it cannot describe that. A hook that named only the byte count would have the tool fill a + * container header with random bytes, and the kernel's correct refusal would be reported as a bug. + * So the row's `opd_shape` is null, kbench names the skip, and this is the row's coverage: the band + * MiniCPM5-2B asks for, with the joined plane built by rad_planes_relayout exactly as + * r3d_gemm_nt_q_w2a8_driver.cpp builds it, so the card test and the driver cannot drift apart. */ +static int build_w2a8(Case& c, const RadOpSchema* s) { +#define W_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define W_PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + const long long M = 16, N = 130560, K = 2048, group = 128, G = K / group; + if (s->n_operands != 7) { fail("w2a8: the schema has %d operands, not 7", s->n_operands); return 1; } + c.n_p = 0; /* the band, not the constraint table's minimums */ + const RadParam pp[] = { W_PI("M", M), W_PI("N", N), W_PI("K", K), W_PI("group", group), + W_PS("dtype", "w2a8") }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + RadEncoding e; + std::memset(&e, 0, sizeof e); + rad_enc_copy_str(e.scheme, "affine"); + e.n_planes = 3; + rad_enc_copy_str(e.plane[0].role, "codes"); + e.plane[0].dtype = RAD_U2; e.plane[0].kind = RAD_PLANE_TILED; + e.plane[0].block[0] = 1; e.plane[0].block[1] = 1; + rad_enc_copy_str(e.plane[1].role, "scale"); + e.plane[1].dtype = RAD_F16; e.plane[1].kind = RAD_PLANE_TILED; + e.plane[1].block[0] = 1; e.plane[1].block[1] = group; + rad_enc_copy_str(e.plane[2].role, "zero"); + e.plane[2].dtype = RAD_U8; e.plane[2].kind = RAD_PLANE_TILED; + e.plane[2].block[0] = 1; e.plane[2].block[1] = group; + const int sel[2] = { 1, 2 }; + + std::vector sc((size_t)N * G), ze((size_t)N * G); + uint32_t st = 0x1234567u; + for (size_t i = 0; i < sc.size(); ++i) { + st = st * 1664525u + 1013904223u; + sc[i] = f32_to_f16(0.001f + 0.002f * (float)((st >> 8) & 0xffffu) / 65536.0f); + ze[i] = (uint8_t)((st >> 16) & 3u); + } + RadTensor ps[2] = {}; /* zero-initialised: rad_planes_plan reads every field */ + const long long pd[2][2] = { { N, G }, { N, G } }; + const uint32_t pdt[2] = { RAD_F16, RAD_U8 }; + void* pdat[2] = { sc.data(), ze.data() }; + for (int i = 0; i < 2; ++i) { + ps[i].data = pdat[i]; ps[i].dtype = pdt[i]; ps[i].rank = 2; + ps[i].shape[0] = pd[i][0]; ps[i].shape[1] = pd[i][1]; + ps[i].stride[1] = 1; ps[i].stride[0] = pd[i][1]; + } + RadPlanesEntry en[RAD_ENC_MAX_PLANES]; + const long long jb = rad_planes_plan(&e, sel, ps, 2, en); + if (jb <= 0) { fail("w2a8: rad_planes_plan refused the joined scale+zero"); return 1; } + std::vector jbytes((size_t)jb, 0); + if (rad_planes_relayout(&e, sel, ps, 2, jbytes.data(), jb) != RAD_OK) { + fail("w2a8: rad_planes_relayout refused"); return 1; + } + + /* Slots in the schema's order: a, a_scale, b, b_scale (the joined blob), y, a_sum. y is the + * output and it is pre-filled with a bf16 NaN: a kernel that never launches leaves its status + * RAD_OK behind and the caller's bytes in the plane, and a plane of the caller's own zeros is + * finite, so only a NaN fill says the row ran. */ + /* Schema order: a, a_scale (optional), b, b_scale, y, a_sum (optional), b_ref (an absent + * weight: a null tensor is what an omitted optional means to the shim). */ + struct Slot { long long rows, cols; uint32_t dt; int nan; } q[7] = { + { M, K, RAD_I8, 0 }, { M, 1, RAD_F32, 0 }, { N, K, RAD_U2, 0 }, + { jb, 1, RAD_U8, 0 }, { M, N, RAD_BF16, 1 }, { G, 16, RAD_F32, 0 }, { 0, 0, RAD_F32, 0 } }; + for (int o = 0; o < 7; ++o) { + if (o == 6) { c.t[o] = RadTensor{}; continue; } + size_t bytes = o == 3 ? (size_t)jb + : q[o].dt == RAD_U2 ? (size_t)(q[o].rows * q[o].cols) / 4 + : (size_t)(q[o].rows * q[o].cols) * dt_bytes(q[o].dt); + std::vector h(bytes, 0); + if (o == 3) std::memcpy(h.data(), jbytes.data(), bytes); /* the blob, not a random fill */ + else for (size_t i = 0; i < bytes; ++i) { + st = st * 1664525u + 1013904223u; + h[i] = (uint8_t)(st >> 13); + } + if (o == 1 || o == 5) { /* scales and sums: small and positive */ + float* f = (float*)h.data(); + const size_t n = bytes / 4; + for (size_t i = 0; i < n; ++i) f[i] = 0.001f + 0.01f * (float)((st = st * 1664525u + + 1013904223u) >> 8 & 0xffffu) / 65536.0f; + } + if (q[o].nan) { + uint16_t* b16 = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) b16[i] = 0x7fc0u; + } + /* The joined operand stays on the host: the shim reads its header where it lies, which is + * the mapped tier the engine puts a joined weight on, and a device pointer there is a null + * header and a refused geometry. The driver hands it over the same way. The allocation is + * left standing -- this process is short-lived and one blob per run. */ + void* d = nullptr; + if (o == 3) { + /* Pinned host memory, the mapped tier's shape: the shim reads this operand's header on + * the host, the kernel reads the same bytes as a device pointer, and plain malloc is + * not device-addressable -- it faults with 700. hipHostMalloc is valid on both sides, + * which is what the engine's container mapping gives a joined weight. */ + if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { fail("w2a8: hipHostMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); + c.host.push_back(d); + std::memcpy(d, h.data(), bytes); + } else { + if (hipMalloc(&d, bytes) != hipSuccess) { fail("w2a8: hipMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); + if (hipMemcpy(d, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("w2a8: hipMemcpy in failed"); return 1; + } + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = q[o].dt; + t.rank = (o == 3) ? 1 : 2; + t.shape[0] = q[o].rows; t.shape[1] = q[o].cols; + t.stride[1] = 1; t.stride[0] = q[o].cols; + if (o == 3) { t.shape[0] = jb; t.shape[1] = 0; t.stride[0] = 1; } + } + return 0; +#undef W_PI +#undef W_PS +} + +static int run_row(int i) { + const RadKernelInfo* k = row_at(i); + if (!k) return 1; + std::printf("== %s (%s)\n", k->name, k->op); +#ifndef RAD_HAVE_HIP + (void)i; + skip("built without the HIP runtime: no device run"); + return 0; +#else + /* No card is not a failure: the static phase above is a third of what this program checks, and + * a build machine, a container and the CI job that builds the plugin all run it without one. */ + int ndev = 0; + if (hipGetDeviceCount(&ndev) != hipSuccess || ndev == 0) { + skip("no device visible"); + return 0; + } + const int hand = k->opd_shape ? 0 + : (0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16")) ? 1 : 2; + if (hand == 2) { skip("no operand description, so no buffers to build"); return 0; } + const RadOpSchema* s = find_schema(k->op); + if (!s) { fail("no schema for '%s'", k->op); return 1; } + + Case c; + make_params(c, k, s); + RadArgs a{}; + a.p = c.p; + a.n_p = c.n_p; + + if (hand) { if (build_w2a8(c, s)) return 1; goto launched; } + for (int o = 0; o < s->n_operands && o < MAX_OPD; ++o) { + RadOpdDesc d{}; + const int st = k->opd_shape(c.p, c.n_p, o, &d); + if (st != RAD_OK) { skip("operand %d: the description declines this geometry (%d)", o, st); + return 0; } + RadTensor t{}; + if (d.flags & RAD_OPD_F_ABSENT) { c.t[o] = t; continue; } + long long nel = 1; + for (uint32_t r = 0; r < d.rank; ++r) nel *= d.shape[r]; + t.dtype = d.dtype; + t.rank = d.rank; + for (uint32_t r = 0; r < d.rank; ++r) t.shape[r] = d.shape[r]; + /* Sub-byte dtypes count elements, not bytes: fp4_e2m1 packs two a byte. */ + const size_t bytes = d.dtype == RAD_U2 ? (size_t)(nel / 4) + : (d.dtype == RAD_U4 || d.dtype == RAD_I4 || d.dtype == RAD_FP4E2M1) + ? (size_t)(nel / 2) + : (size_t)nel * dt_bytes(d.dtype); + std::vector h(bytes ? bytes : 1); + fill_plane(d, h.data(), (size_t)nel, 0x9E3779B9u + (uint32_t)o * 7919u); + /* Standing to-do, measured and not shipped: filling every OUT plane with the dtype's NaN -- + * which is what says a row that returns RAD_OK without launching has left the caller's bytes + * in the plane, the failure the attention unit's third bug is -- works for 66 of the 68 rows + * and, in the forked child, kills `quant_act_i8_bf16` and `sample_logprobs_f32` on signal 11 + * while both run clean in-process (`--case`), and both write planes the reference pads. It + * is the right check, it needs the padded-plane story finished, and the hand-built geometry + * below already does it for the row whose coverage is this file. */ + void* p = nullptr; + if (hipMalloc(&p, bytes) != hipSuccess) { fail("hipMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(p); + if (hipMemcpy(p, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("hipMemcpy in failed"); return 1; + } + t.data = p; + long long acc = 1; + for (int r = (int)t.rank - 1; r >= 0; --r) { t.stride[r] = acc; acc *= t.shape[r]; } + c.t[o] = t; + } +launched: + a.t = c.t; + a.n_t = s->n_operands; + + /* The scratch the row asked for, at this geometry, if it asks for any. */ + void* scratch = nullptr; + if (k->scratch) { + const int64_t bytes = k->scratch(&a); + if (bytes > 0 && hipMalloc(&scratch, (size_t)bytes) == hipSuccess) { + (void)hipMemset(scratch, 0, (size_t)bytes); + a.scratch = scratch; + a.scratch_bytes = bytes; + } else if (bytes > 0) { + fail("the row wants %lld scratch bytes and none could be allocated", + (long long)bytes); + return 1; + } + } + + const int rc = k->launch(&a, nullptr); + const hipError_t le = hipGetLastError(); + const int sync = (int)hipDeviceSynchronize(); + int ret = 0; + if (rc == RAD_E_UNSUPPORTED || rc == RAD_E_INVAL || rc == RAD_E_SHAPE || + rc == RAD_E_DTYPE) { + skip("the shim declines this geometry (%d)", rc); + } else if (rc != RAD_OK) { + fail("launch returned %d", rc); + /* The band, spelled out: a shim's mapped code says what kind of answer it gave, not what + * it was given, and the difference between a launch that failed and a geometry nobody + * intended is in the numbers. */ + for (int i = 0; i < c.n_p; ++i) + if (c.p[i].kind == RAD_P_STR) + std::printf(" param %s = %s\n", c.p[i].key, c.p[i].sval ? c.p[i].sval : "(null)"); + else + std::printf(" param %s = %lld\n", c.p[i].key, c.p[i].ival); + for (int o = 0; o < s->n_operands; ++o) { + const RadTensor& t = c.t[o]; + std::printf(" operand %d '%s' dt=%u rank=%u data=%p", o, s->operands[o].name, + t.dtype, t.rank, t.data); + for (uint32_t r = 0; r < t.rank; ++r) std::printf(" %lld/%lld", t.shape[r], t.stride[r]); + std::printf("\n"); + } + ret = 1; + } else if (le != hipSuccess || sync != hipSuccess) { + fail("the kernel faulted (last error %d, sync %d)", (int)le, sync); + ret = 1; + } else { + int outs = 0; + for (int o = 0; o < s->n_operands && !ret; ++o) { + if (s->operands[o].role == RAD_OPD_IN) continue; + const RadTensor& t = c.t[o]; + if (!t.data) continue; + /* A joined plane lives where the mapped tier puts it: pinned host bytes the shim reads + * on the host and the kernel reads over PCIe. It is not a device buffer, so there is + * nothing to copy back, and its contents are the container's, not the row's work. */ + if (std::find(c.host.begin(), c.host.end(), t.data) != c.host.end()) continue; + ++outs; + long long nel = 1; + for (uint32_t r = 0; r < t.rank; ++r) nel *= t.shape[r]; + /* Sub-byte planes are counted in codes, not bytes: a U2 tensor of 267M codes is + * 66.8 MB on the card, and asking the runtime for 267 MB of it is an out-of-range + * copy, not a large one. */ + const size_t bytes = t.dtype == RAD_U2 ? (size_t)(nel / 4) + : (t.dtype == RAD_U4 || t.dtype == RAD_I4 || t.dtype == RAD_FP4E2M1) + ? (size_t)(nel / 2) + : (size_t)nel * dt_bytes(t.dtype); + std::vector h(bytes); + if (hipMemcpy(h.data(), t.data, bytes, hipMemcpyDeviceToHost) != hipSuccess) { + fail("hipMemcpy out failed: operand %d ('%s'), %zu bytes", o, s->operands[o].name, + bytes); ret = 1; break; + } + int nan = 0, big = 0; + for (long long e = 0; e < nel; ++e) { + float v; + switch (t.dtype) { + case RAD_F32: v = *(const float*)(h.data() + e * 4); break; + case RAD_BF16: v = bf16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F16: v = f16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F8E4M3: v = e4m3_to_f32(h.data()[e]); break; + default: continue; + } + if (v != v) ++nan; + else if (!(v > -1e31f && v < 1e31f)) ++big; + } + /* An infinity is the sampler's contract, not a broken number: a dropped candidate is + * `cand_idx` -1 and `cand_val` -inf, a narrowing stage drops by writing -inf, the mask + * and the ban write -inf into the logits, and a slot row_topk cannot fill is -inf. A + * NaN is nobody's contract, so it stays a failure everywhere. */ + const bool sentinel = (k->family && 0 == std::strcmp(k->family, "sample")) || + (k->op && 0 == std::strcmp(k->op, "row_topk")); + /* Two planes carry the reference's grid rather than the row's work: `asum`, the int8 + * activation's row sums padded to a 16-row grid, and `stats`, the quantiser's per-group + * statistics. The row writes the rows it was given and leaves the pad, and with outputs + * pre-filled NaN the pad is NaN by construction. Named planes only -- NaN anywhere else + * is exactly the silent no-op the fill exists to find. */ + const bool padded = s->operands[o].name && + (0 == std::strcmp(s->operands[o].name, "asum") || + 0 == std::strcmp(s->operands[o].name, "stats")); + if (nan && padded) { + ok("ran, %d output plane%s read back with %d pad NaN of %lld on '%s' (the " + "reference's grid, not the row's work)", outs, outs == 1 ? "" : "s", nan, nan == 1 + ? "" : "s", nel, s->operands[o].name); + } else if (nan) { fail("operand %d ('%s'): %d NaN of %lld", o, s->operands[o].name, nan, + nel); ret = 1; } + else if (big && !sentinel) { + fail("operand %d ('%s'): %d non-finite of %lld", o, s->operands[o].name, big, nel); + ret = 1; + } else if (big) { + ok("ran, %d output plane%s read back with %d sentinel%s of %lld on '%s' (the " + "contract's -inf)", outs, outs == 1 ? "" : "s", big, big == 1 ? "" : "s", nel, + s->operands[o].name); + } + } + if (!ret) ok("ran, %d output plane%s read back finite", outs, outs == 1 ? "" : "s"); + } + + if (scratch) (void)hipFree(scratch); + for (void* p : c.dev) (void)hipFree(p); + return ret; +#endif +} + +/* ================================================================== main */ +int main(int argc, char** argv) { + /* A row that dies takes the line it was printing with it, and knowing which row died is the + * whole point of the census: stdout is unbuffered, so the last line is the last thing that + * worked. Redirecting the output to a file is exactly when the buffering would hide it. */ + std::setvbuf(stdout, nullptr, _IONBF, 0); + const char* path = nullptr; + for (int i = 1; i < argc; ++i) { + if (!std::strcmp(argv[i], "--case") && i + 1 < argc) g_case = argv[++i]; + else if (!std::strcmp(argv[i], "--help")) { + std::printf("usage: r3d_selftest /libr3d.so [--case ]\n"); + return 0; + } else if (!path) path = argv[i]; + } + if (!path) { std::fprintf(stderr, "r3d_selftest: no plugin given\n"); return 2; } + g_plugin = path; + + /* dlopen, not link: an undefined symbol in the .so must be this program's failure. */ + void* h = dlopen(path, RTLD_NOW | RTLD_LOCAL); + if (!h) { std::fprintf(stderr, "r3d_selftest: %s\n", dlerror()); return 2; } + g_h = h; + P_count = (int (*)(void))dlsym(h, "rad_kernel_count"); + P_at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at"); + P_scount = (int (*)(void))dlsym(h, "rad_kernel_schema_count"); + P_sat = (const RadOpSchema* (*)(int))dlsym(h, "rad_kernel_schema_at"); + if (!P_count || !P_at || !P_scount || !P_sat) { + std::fprintf(stderr, "r3d_selftest: %s is not a kernel plugin\n", path); + return 2; + } + + if (!g_case) { + check_codecs(); + check_lanes(); + check_table(); + check_reference_schemas(); + check_band_reach(); + check_shapes(); + + const int n = rows(); + int passed = 0, failed = 0; + for (int i = 0; i < n; ++i) { + const RadKernelInfo* k = row_at(i); + if (!k || !k->name) continue; + std::vector argv2 = { argv[0], const_cast(path), + const_cast("--case"), + const_cast(k->name), nullptr }; + pid_t pid = 0; + if (posix_spawn(&pid, argv[0], nullptr, nullptr, argv2.data(), environ) != 0) { + fail("could not spawn a child for '%s': %s", k->name, std::strerror(errno)); + ++failed; + continue; + } + int status = 0; + while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {} + if (WIFEXITED(status)) { + if (WEXITSTATUS(status) == 0) ++passed; else ++failed; + } else if (WIFSIGNALED(status)) { + std::printf(" FAIL %s died on signal %d\n", k->name, WTERMSIG(status)); + ++failed; + } + } + std::printf("== %d rows ran clean, %d failed, %d skipped by the shims\n", passed, failed, + g_skip); + dlclose(h); + return (failed || g_fail) ? 1 : 0; + } + + for (int i = 0; i < rows(); ++i) { + const RadKernelInfo* k = row_at(i); + if (k && k->name && !std::strcmp(k->name, g_case)) return run_row(i); + } + std::printf(" FAIL no row named '%s'\n", g_case); + return 1; +} diff --git a/libr3d/r3d_shapes.cpp b/libr3d/r3d_shapes.cpp new file mode 100644 index 00000000..4ce8ca37 --- /dev/null +++ b/libr3d/r3d_shapes.cpp @@ -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 +#include + +#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(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); +} diff --git a/libr3d/r3d_tiling.h b/libr3d/r3d_tiling.h new file mode 100644 index 00000000..684e6e5e --- /dev/null +++ b/libr3d/r3d_tiling.h @@ -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 */ diff --git a/libr3d/r3d_vocab_bf16.hip b/libr3d/r3d_vocab_bf16.hip new file mode 100644 index 00000000..36b6d657 --- /dev/null +++ b/libr3d/r3d_vocab_bf16.hip @@ -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 + +#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 +__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 +__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 +__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 +__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(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(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 +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)), 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)), grid, block, s, x, w, h, y, M, + N, K, x_ld, y_ld); + else + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), 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(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(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(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(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); +} diff --git a/libr4d/README.md b/libr4d/README.md index 2c11b2d8..b112d79d 100644 --- a/libr4d/README.md +++ b/libr4d/README.md @@ -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 | diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 48415f5f..546973d0 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -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, diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 6faed029..471cd894 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -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; diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index 23c615d6..79d8e483 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -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 +// 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 __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), 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), 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; } diff --git a/libr4d/r4d_gdn_args.h b/libr4d/r4d_gdn_args.h index 0e3bff4a..1211510d 100644 --- a/libr4d/r4d_gdn_args.h +++ b/libr4d/r4d_gdn_args.h @@ -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) { diff --git a/libr4d/r4d_gdn_conv_tap.h b/libr4d/r4d_gdn_conv_tap.h index d7e65939..52f4c4ad 100644 --- a/libr4d/r4d_gdn_conv_tap.h +++ b/libr4d/r4d_gdn_conv_tap.h @@ -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 struct cp_vec4; +template <> struct cp_vec4 { using T = ushort4; }; +template <> struct cp_vec4 { using T = float4; }; +template using cp_taps = typename cp_vec4::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 diff --git a/libr4d/r4d_gdn_conv_w4_h128_bf16.hip b/libr4d/r4d_gdn_conv_w4_h128_bf16.hip index ab3a1c00..41c9c6dd 100644 --- a/libr4d/r4d_gdn_conv_w4_h128_bf16.hip +++ b/libr4d/r4d_gdn_conv_w4_h128_bf16.hip @@ -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 +template __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 +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), grid, blk, 0, (hipStream_t)stream, \ - (const unsigned short*)x, xpitch, (const unsigned short*)wgt, \ + hipLaunchKernelGGL((r4d_gdn_conv_prep_kernel), 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(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(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 +template __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 w4 = *(const cp_taps*)(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 +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

), grid, blk, 0, (hipStream_t)stream, \ - (const unsigned short*)x, xpitch, (const unsigned short*)wgt, \ + hipLaunchKernelGGL((r4d_gdn_conv_update_kernel), 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(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(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], diff --git a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip index 356a9340..62095b7e 100644 --- a/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip +++ b/libr4d/r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip @@ -37,6 +37,7 @@ #include #include #include +#include #include #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; + 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 w4 = *(const cp_taps*)(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 w4 = *(const cp_taps*)(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::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); } diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index a179235d..fb3a37f8 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -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(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(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 -__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 -__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, diff --git a/libr4d/r4d_hc_bf16.hip b/libr4d/r4d_hc_bf16.hip index d3ce4da3..f8cda02a 100644 --- a/libr4d/r4d_hc_bf16.hip +++ b/libr4d/r4d_hc_bf16.hip @@ -207,6 +207,61 @@ __device__ __forceinline__ float hc8_dot_down(const unsigned short* __restrict__ return acc; } +/* hc8_dot_down for two rows of W_down at once, one read of N from LDS feeding both. A + * wave owning two columns (four rows of a decode step) read the 20 KB vector once per column, and + * kernel A's dots were LDS-bound. Each row's sum is the same fmaf sequence as hc8_dot_down's. */ +__device__ __forceinline__ float hc8_dot16n(const float* nf, uint4 c) { + float wf[16]; + e4m3x8(c.x, c.y, wf); + e4m3x8(c.z, c.w, wf + 8); + float p = 0.0f; +#pragma unroll + for (int t = 0; t < 16; ++t) p = fmaf(wf[t], nf[t], p); + return p; +} + +template +__device__ __forceinline__ void hc8_dot_down2(const unsigned short* __restrict__ sv, + const unsigned char* __restrict__ wr0, + const unsigned char* __restrict__ wr1, long K, + int lane, float& out0, float& out1) { + const float* __restrict__ sr0 = (const float*)(wr0 + K); + const float* __restrict__ sr1 = (const float*)(wr1 + K); + float acc0 = 0.0f, acc1 = 0.0f; + long j = 0; + for (; j + kHc8Step * kU <= K; j += kHc8Step * kU) { + uint4 c0[kU], c1[kU]; + float s0[kU], s1[kU]; +#pragma unroll + for (int u = 0; u < kU; ++u) { + const long e = j + (long)u * kHc8Step + lane * 16; + c0[u] = *(const uint4*)(wr0 + e); + c1[u] = *(const uint4*)(wr1 + e); + s0[u] = sr0[e / r4d_hc8::kDownGroup]; + s1[u] = sr1[e / r4d_hc8::kDownGroup]; + } +#pragma unroll + for (int u = 0; u < kU; ++u) { + const long e = j + (long)u * kHc8Step + lane * 16; + float nf[16]; + bf16x8(*(const uint4*)(sv + e), nf); + bf16x8(*(const uint4*)(sv + e + 8), nf + 8); + acc0 = fmaf(hc8_dot16n(nf, c0[u]), s0[u], acc0); + acc1 = fmaf(hc8_dot16n(nf, c1[u]), s1[u], acc1); + } + } + for (; j < K; j += kHc8Step) { + const long e = j + lane * 16; + float nf[16]; + bf16x8(*(const uint4*)(sv + e), nf); + bf16x8(*(const uint4*)(sv + e + 8), nf + 8); + acc0 = fmaf(hc8_dot16n(nf, *(const uint4*)(wr0 + e)), sr0[e / r4d_hc8::kDownGroup], acc0); + acc1 = fmaf(hc8_dot16n(nf, *(const uint4*)(wr1 + e)), sr1[e / r4d_hc8::kDownGroup], acc1); + } + out0 = acc0; + out1 = acc1; +} + /* One thread's quarter of an E4M3 row of mix_up against RG rows of `d` in LDS. The quarter is the * row's scale group (r4d_hc8::up_group), so its partial sums are complete before scaling, and four * threads' sums make the row. All of a quarter's sixteen-code loads issue before the first is used @@ -247,11 +302,85 @@ __device__ __forceinline__ void hc8_dot_up(const float* __restrict__ sd, long lr } } +/* hc8_dot_up split at its loads, so a kernel can issue them before `d` exists: a + * quarter's codes and its group scale, then the same arithmetic in the same order. */ +struct Hc8UpQuarter { + uint4 c[kUpMaxQ]; + float sc; +}; +__device__ __forceinline__ void hc8_up_load(const unsigned char* __restrict__ wr, long lr, + int q4, Hc8UpQuarter& o) { + const long G = lr / 4, k0 = (long)q4 * G; + const int nq = (int)(G / 16); +#pragma unroll + for (int i = 0; i < kUpMaxQ; ++i) + if (i < nq) o.c[i] = *(const uint4*)(wr + k0 + 16 * i); + o.sc = ((const float*)(wr + lr))[q4]; +} +/* RPT rows of W_up with the same quarter against RG rows of `d`: each value of `d` read from LDS + * feeds RPT products, and `d` sits in LDS as the bf16 it is, sixteen values in two 16-byte reads + * (the quarter, its group and lr are multiples of 16 by r4d_hc8::group_ok, and the base is aligned). + * Read as floats a value at a time, the dot was a chain of LDS round trips: 7.4 of the 22.8 us at + * four rows with every byte cache-resident. Each (row, r) accumulates the same fmaf sequence on the + * same values as hc8_dot_up. */ +template +__device__ __forceinline__ void hc8_up_dot_rows(const unsigned short* __restrict__ sdh, long lr, + const Hc8UpQuarter* o, int q4, + float (*acc)[RG]) { + const long G = lr / 4, k0 = (long)q4 * G; + const int nq = (int)(G / 16); +#pragma unroll + for (int m = 0; m < RPT; ++m) +#pragma unroll + for (int r = 0; r < RG; ++r) acc[m][r] = 0.0f; +#pragma unroll + for (int i = 0; i < kUpMaxQ; ++i) { + if (i >= nq) break; + float wf[RPT][16]; +#pragma unroll + for (int m = 0; m < RPT; ++m) { + e4m3x8(o[m].c[i].x, o[m].c[i].y, wf[m]); + e4m3x8(o[m].c[i].z, o[m].c[i].w, wf[m] + 8); + } +#pragma unroll + for (int r = 0; r < RG; ++r) { + const unsigned short* dr = sdh + (long)r * lr + k0 + 16 * i; + float dv[16]; + bf8_f(*(const uint4*)dr, *(float(*)[8])dv); + bf8_f(*(const uint4*)(dr + 8), *(float(*)[8])(dv + 8)); +#pragma unroll + for (int t = 0; t < 16; ++t) { +#pragma unroll + for (int m = 0; m < RPT; ++m) acc[m][r] = fmaf(wf[m][t], dv[t], acc[m][r]); + } + } + } +#pragma unroll + for (int m = 0; m < RPT; ++m) +#pragma unroll + for (int r = 0; r < RG; ++r) { + float a = acc[m][r] * o[m].sc; + a += __shfl_xor(a, 1); + a += __shfl_xor(a, 2); + acc[m][r] = a; + } +} + /* On the VALU, not the LDS crossbar (r4d_common.h). The norm prologue reduces `hc + 1` * accumulators back to back with a runtime `hc`, so the exchanges form one long dependency chain. * Bit-identical: same lanes, same order. */ __device__ __forceinline__ float wave_sum(float v) { return r4d_wave_sum(v); } +/* A barrier that orders LDS only. __syncthreads() fences at workgroup scope, which in + * WGP mode on gfx12 waits for every outstanding global load: a load issued for the next pass of a + * K loop could not stay in flight across it, and a software-pipelined loop ran as serially as the + * plain one. Where a barrier guards only LDS tiles, this one leaves global loads in flight. */ +__device__ __forceinline__ void hc_lds_barrier() { + __builtin_amdgcn_fence(__ATOMIC_RELEASE, "workgroup", "local"); + __builtin_amdgcn_s_barrier(); + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "workgroup", "local"); +} + /* ============================================================== hc_enter * * h[c][i] = x[i] for every stream. One launch per step; its own op because the embedding lookup's @@ -747,8 +876,216 @@ constexpr long kHcReadAStaticLds = (long)(kWaves * kHcMax + kHcMax) * (long)size * grouped reduction. It is transposed per 256-element chunk; see wave_dot_swz. */ /* Waves per SIMD: nine for the E4M3 dot, as tuned. Unconstrained, LLVM 24 builds it at 120 VGPRs * for twelve waves, 11-20% slower at the 4-7 rows of a speculative decode step. The bf16 form keeps - * the full range; pinning it would change its code. */ -template + * the full range; pinning it would change its code. + * + * HCP and PER, when nonzero, are hc and n / kThreads known at compile time (4 and 10 at + * Flash-Next's shape). Thread t's elements of `h` are then t + e * kThreads for e < HCP * PER, the + * stream being e / PER, so every one of them and of the norm weight can be loaded before the first + * is used: one round trip from the cache instead of one per stream for the sums of squares and + * again for N, the ten-odd dependent latencies that set the decode step's time here (the kernel + * ran 8.3 us at one row with every byte cache-resident). The sums and N take the same values in + * the same order, so the output is bit-identical to the loops below. */ +template +__device__ __forceinline__ void hc_read_a_body(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, + long rows, long n, int hc, long lr, long ta, long hrow, long irow, + float eps, float wadd, unsigned bx, unsigned by, + unsigned xpub) { + /* 16-byte aligned, for the 16-byte LDS reads of the dots. The dynamic region starts + * after the kernel's static LDS, which in hc_read_fused_kernel is not a multiple of 16; a + * misaligned base ran the fused form's A blocks three times slower at four rows. */ + extern __shared__ __attribute__((aligned(16))) unsigned short sN[]; /* [hc * n], transposed per 256-element chunk */ + __shared__ float s_part[kWaves][kHcMax]; + __shared__ float s_scale[kHcMax]; + /* One 256-entry staging slot per wave (4 KiB); no barrier, a wave uses only its own. */ + __shared__ unsigned short s_stage[kWaves][kWave * 8]; + static_assert(sizeof(s_part) + sizeof(s_scale) + sizeof(s_stage) == kHcReadAStaticLds, + "the launcher sizes N's allocation against this kernel's static LDS"); + + constexpr long kPer = kWave * 8; + + const long r = by; + if (r >= rows) return; + const long HN = (long)hc * n; + /* The inject gains get a block of their own for load balance. With ta = kWaves every wave does + * one dot over HN; adding the gains to a column-owning block would give its waves a second + * one, and that slowest block would set the kernel's duration. So the grid is one wider and + * the last block owns no columns. */ + const bool pub = (bx == xpub); + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const unsigned short* hp = h + r * hrow; + const unsigned short* __restrict__ down = (const unsigned short*)downv; + + /* The transposed layout follows from the shape: the chunk must sit inside one sub-stream + * (n % 256) and every 16-byte group be aligned in LDS and in `h`; otherwise the plain layout, + * with the same N. The E4M3 dot reads N in natural order, so only the bf16 form transposes. */ + const bool swz = !F8 && (n % kPer == 0) && (((uintptr_t)hp & 15u) == 0u) + && (((uintptr_t)down & 15u) == 0u) + && (!injw || ((uintptr_t)injw & 15u) == 0u); + + /* ---- sums of squares, one stream at a time, straight from `h`. One stream at a time keeps + * the accumulator a scalar; an array indexed by runtime `hc` would live in scratch. + * + * This prologue is latency-bound, not traffic-bound: 20 KiB against the block's 320 KiB of + * W_down, yet 6.7 of the kernel's 18.7 us at the decode grid, because ten dependent iterations + * wait on loads with nothing else resident. Issuing kPreSs iterations' loads first turns eight + * serial latencies into one, bit-identically. Wider loads (these bytes are served from the + * 64 MB last-level cache, not DRAM), reading `h` once instead of twice, and deeper prefetch + * were all measured as no gain. */ + if constexpr (HCP > 0) { + /* The preloaded form (see the kernel's note): N stays the natural-order E4M3 layout. */ + static_assert(F8, "only the E4M3 dot reads N in natural order"); + constexpr int kE = HCP * PER; + uint32_t hv[kE]; + float wv[kE]; +#pragma unroll + for (int e = 0; e < kE; ++e) { + hv[e] = bfw(hp + tid + (long)e * kThreads); + wv[e] = w[tid + (long)e * kThreads]; + } +#pragma unroll + for (int c = 0; c < HCP; ++c) { + float acc = 0.0f; +#pragma unroll + for (int p = 0; p < PER; ++p) { const float v = bfw_f(hv[c * PER + p]); acc += v * v; } + acc = wave_sum(acc); + if (lane == 0) s_part[wave][c] = acc; + } + __syncthreads(); + if (tid < HCP) { + float ss = 0.0f; + for (int k = 0; k < kWaves; ++k) ss += s_part[k][tid]; + s_scale[tid] = __frsqrt_rn(ss / (float)n + eps); + if (pub && scaleout) scaleout[r * kHcMax + tid] = s_scale[tid]; + } + __syncthreads(); +#pragma unroll + for (int c = 0; c < HCP; ++c) { + const float sc = s_scale[c]; +#pragma unroll + for (int p = 0; p < PER; ++p) { + const int e = c * PER + p; + sN[tid + (long)e * kThreads] = f2bf(bfw_f(hv[e]) * sc * (wv[e] + wadd)); + } + } + __syncthreads(); + } else { + constexpr int kPreSs = 8; // n / kThreads is 10 a stream at this shape, and 12 spills + for (int c = 0; c < hc; ++c) { + const long cb = (long)c * n; + float acc = 0.0f; + long i = tid; + for (; i + (long)(kPreSs - 1) * kThreads < n; i += (long)kPreSs * kThreads) { + uint32_t hv[kPreSs]; +#pragma unroll + for (int p = 0; p < kPreSs; ++p) hv[p] = bfw(hp + cb + i + (long)p * kThreads); +#pragma unroll + for (int p = 0; p < kPreSs; ++p) { const float v = bfw_f(hv[p]); acc += v * v; } + } + for (; i < n; i += kThreads) { const float v = bf2f(hp[cb + i]); acc += v * v; } + acc = wave_sum(acc); + if (lane == 0) s_part[wave][c] = acc; + } + __syncthreads(); + if (tid < hc) { + float ss = 0.0f; + for (int k = 0; k < kWaves; ++k) ss += s_part[k][tid]; + s_scale[tid] = __frsqrt_rn(ss / (float)n + eps); + /* One workgroup publishes; the others compute the identical value. */ + if (pub && scaleout) scaleout[r * kHcMax + tid] = s_scale[tid]; + } + __syncthreads(); + + /* ---- N into LDS, narrowed to bf16 where the reference narrows it. Looped per stream rather + * than computing `j / n`, a 64-bit integer division per element (a software sequence here). */ + for (int c = 0; c < hc; ++c) { + const long cb = (long)c * n; + const float sc = s_scale[c]; + if (swz) { + /* A thread owns one (chunk, lane) group: logical elements `lane + 32t`, one 16-byte + * store at physical `q`. A wave covers one chunk, so `ch` is wave-uniform and the + * `h` and `w` reads stay coalesced. */ + for (long base = 0; base < n; base += (long)kThreads * 8) { + const long q = base + (long)tid * 8; + if (q >= n) break; + const long ch = cb + (q & ~(kPer - 1)); + float out[8]; +#pragma unroll + for (int t = 0; t < 8; ++t) { + const long li = ch + lane + (long)t * kWave; + out[t] = bfw_f(bfw(hp + li)) * sc * (w[li] + wadd); + } + *(uint4*)(sN + cb + q) = f2bf8(out); + } + } else { + constexpr int kPreScale = 8; + long i = tid; + for (; i + (long)(kPreScale - 1) * kThreads < n; i += (long)kPreScale * kThreads) { + float wv[kPreScale]; + uint32_t hv[kPreScale]; +#pragma unroll + for (int p = 0; p < kPreScale; ++p) { + wv[p] = w[cb + i + (long)p * kThreads]; + hv[p] = bfw(hp + cb + i + (long)p * kThreads); + } +#pragma unroll + for (int p = 0; p < kPreScale; ++p) + sN[cb + i + (long)p * kThreads] = f2bf(bfw_f(hv[p]) * sc * (wv[p] + wadd)); + } + for (; i < n; i += kThreads) + sN[cb + i] = f2bf(bf2f(hp[cb + i]) * sc * (w[cb + i] + wadd)); + } + } + __syncthreads(); + } + + /* ---- this workgroup's columns of W_down, one wave per column. */ + const float inv_hc = 1.0f / (float)hc; + const long k0 = (long)bx * ta; + for (long k = k0 + wave; k < k0 + ta && k < lr; k += kWaves) { + float acc; + if constexpr (F8) { + /* This wave's next column too, when it has one (hc8_dot_down2). */ + const long k2 = k + kWaves; + if (k2 < k0 + ta && k2 < lr) { + float acc2; + hc8_dot_down2(sN, (const unsigned char*)downv + k * dld, + (const unsigned char*)downv + k2 * dld, HN, lane, acc, acc2); + acc = wave_sum(acc); + acc2 = wave_sum(acc2); + if (lane == 0) { + dout[r * lr + k] = f2bf(siluf_(acc * inv_hc)); + dout[r * lr + k2] = f2bf(siluf_(acc2 * inv_hc)); + } + k = k2; + continue; + } + acc = hc8_dot_down(sN, (const unsigned char*)downv + k * dld, HN, lane); + } else { + const unsigned short* wr = down + k * HN; + acc = swz ? wave_dot_swz(sN, wr, HN, lane) + : wave_dot_lds(sN, wr, HN, lane, s_stage[wave]); + } + acc = wave_sum(acc); + if (lane == 0) dout[r * lr + k] = f2bf(siluf_(acc * inv_hc)); + } + + /* ---- the inject gains, on the block that owns no columns and already holds N. */ + if (pub && injw && inj) { + for (int c = wave; c < hc; c += kWaves) { + const unsigned short* wr = injw + (long)c * HN; + float acc = swz ? wave_dot_swz(sN, wr, HN, lane) + : wave_dot_lds(sN, wr, HN, lane, s_stage[wave]); + acc = wave_sum(acc); + if (lane == 0) inj[r * irow + c] = f2bf(2.0f * sigmoidf_(acc * inv_hc)); + } + } +} + +template __global__ __launch_bounds__(kThreads) __attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16))) void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, @@ -758,6 +1095,542 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr float* __restrict__ scaleout, long rows, long n, int hc, long lr, long ta, long hrow, long irow, float eps, float wadd) { + hc_read_a_body(h, w, downv, dld, injw, dout, inj, scaleout, rows, n, hc, lr, ta, + hrow, irow, eps, wadd, blockIdx.x, blockIdx.y, gridDim.x - 1u); +} + +/* ============================================================== hc_read, kernel B1 + * + * `u = sigmoid(W_up @ d)`, one wave per row of W_up. Separate from the mix for occupancy: the mix + * owns 128 channels (hc*128 rows of W_up), only twenty workgroups at width 2560 on 64 CUs, while + * this kernel runs HN/64 = 160 workgroups on the same bytes. `u` costs a 20 KiB-per-row round trip + * through scratch against 6.55 MiB of weight. + * + * RG rows share one block and one pass over the weight. With the row on blockIdx.y, a depth-3 MTP + * verify (four rows) streams W_up four times; the last-level cache absorbs most of it (1.4x, not + * 4x), but needlessly. `d` is 320 floats per row, so RG rows fit in LDS and a wave takes RG dots + * from each weight row it loads (~3% of a multi-row step, same output). RG=1 is the one-row case. + * + * At the decode grid this moves 6.55 MB in 14.9 us (440 GB/s; the part reads 621 cold). Measured + * slower: four rows in flight per wave (+16%); kUpRows 16 or 128; staging the 64-element tail as + * one wide load (+4.6%; both narrow loads hit one 128-byte line); eight consecutive rows per wave + * instead of strided (+9.9%; strided rows make a block's eight waves read one contiguous burst); + * and register-staging the tail (+13.1%; the compiler hoists the wait in front of the chunk load). + * A block-cooperative stage of the span would take 40 KiB of LDS (1 block per CU instead of 7). + * + * Bit-identical to wave_dot_lds: only the loop nest changes (rows move innermost), and `acc[]` is + * indexed by an unrolled constant so it stays in registers; a runtime `rows` bound would put it in + * scratch. */ + +/* RG rows of the LDS vector against one contiguous bf16 weight row, read once. `sv_ld` is the row + * pitch of `sv`. */ +template +__device__ __forceinline__ void wave_dot_lds_rows(const float* __restrict__ sv, long sv_ld, + const unsigned short* __restrict__ wr, long HN, + int lane, unsigned short* stage, + float* __restrict__ acc) { + constexpr long kPer = kWave * 8; +#pragma unroll + for (int r = 0; r < RG; ++r) acc[r] = 0.0f; + long j = 0; + if (((uintptr_t)wr & 15u) == 0u) { + for (; j + kPer <= HN; j += kPer) { + *(uint4*)(stage + lane * 8) = *(const uint4*)(wr + j + lane * 8); +#pragma unroll + for (int t = 0; t < 8; ++t) { + const int jj = lane + t * kWave; + const float wv = bf2f(stage[jj]); +#pragma unroll + for (int r = 0; r < RG; ++r) acc[r] += sv_at(sv, (long)r * sv_ld + j + jj) * wv; + } + } + } + for (long i = j + lane; i < HN; i += kWave) { + const float wv = bf2f(wr[i]); +#pragma unroll + for (int r = 0; r < RG; ++r) acc[r] += sv_at(sv, (long)r * sv_ld + i) * wv; + } +} + +template +__global__ __launch_bounds__(kThreads) +void hc_up_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, + unsigned short* __restrict__ ubuf, long rows, long hn, long lr) { + const unsigned short* __restrict__ up = (const unsigned short*)upv; + extern __shared__ __attribute__((aligned(16))) float sd[]; /* [RG * lr] */ + __shared__ unsigned short s_stage[kWaves][kWave * 8]; /* wave_dot_lds, one slot a wave */ + const long r0 = (long)blockIdx.y * RG; + if (r0 >= rows) return; + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + + /* A dead row of the tail group is zero-filled, so its dot is defined; its store is dropped. */ + for (long k = tid; k < (long)RG * lr; k += kThreads) { + const long r = k / lr; + sd[k] = (r0 + r < rows) ? bf2f(dbuf[(r0 + r) * lr + (k - r * lr)]) : 0.0f; + } + __syncthreads(); + + const long j0 = (long)blockIdx.x * kUpRows; + /* The E4M3 form takes a row four threads at a time, a quarter (one scale group) each, so 256 + * threads cover the block's 64 rows in one pass. */ + if constexpr (F8) { + static_assert(kUpRows * 4 == kThreads, "four threads a row of W_up"); + const int tr = tid >> 2, q4 = tid & 3; + const long j = j0 + tr; + float acc[RG]; + hc8_dot_up(sd, lr, (const unsigned char*)upv + (j < hn ? j : hn - 1) * uld, q4, acc); +#pragma unroll + for (int r = 0; r < RG; ++r) + if (q4 == 0 && j < hn && r0 + r < rows) ubuf[(r0 + r) * hn + j] = f2bf(sigmoidf_(acc[r])); + return; + } + for (long t = wave; t < kUpRows; t += kWaves) { + const long j = j0 + t; + if (j >= hn) break; + float acc[RG]; + wave_dot_lds_rows(sd, lr, up + j * lr, lr, lane, s_stage[wave], acc); +#pragma unroll + for (int r = 0; r < RG; ++r) { + const float a = wave_sum(acc[r]); + /* Narrowed as in the reference, where the sigmoid output is bf16 before the multiply. */ + if (lane == 0 && r0 + r < rows) ubuf[(r0 + r) * hn + j] = f2bf(sigmoidf_(a)); + } + } +} + +/* Rotated fp8 codes of one 128-channel group, for a consumer whose weight carries a 128-wide + * Hadamard (the w4a8h expert plane). A wave holds the group four consecutive values per lane (the + * r4d_fwht_wave<128> layout), loaded by the caller from the stored bf16, and quantises exactly as + * the rotated quant_act_fp8 kernel does (transform, absmax, scale, clamp, packing), so no separate + * launch over `x` is needed. */ +__device__ __forceinline__ void hc_rot_group(float* v, int lane, unsigned char* qg, float* sg) { + r4d_fwht_wave(v, lane); + float m = 0.0f; +#pragma unroll + for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); + m = r4d_wave_max(m); + const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; + if (lane == 0) *sg = sc; + const float inv = 1.0f / sc; + int pk = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), + fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); + *(unsigned*)(qg + lane * 4) = (unsigned)pk; +} + +/* The fused form's wait (hc_read_fused_kernel, below): its B blocks hold here until every A + * block has published `d` and the scales. */ +constexpr unsigned kHcSyncCtr = 3; /* tickets, A blocks done, B blocks past the wait */ + +__device__ __forceinline__ void hc_role_wait(unsigned int* __restrict__ sync, unsigned na, + unsigned nb_all) { + if (threadIdx.x == 0) { + const unsigned long t0 = wall_clock64(); + /* Relaxed while polling, acquired once after: an acquire load also invalidates the + * vector caches, and a poll of them would keep emptying them under the A blocks. */ + while (__hip_atomic_load(&sync[1], __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < na) { + __builtin_amdgcn_s_sleep(1); + /* 0.5 s at the 100 MHz wall clock. A blocks that never finish are a counter fault: + * trap rather than read a stale `d`, as the all-reduce handshakes do. */ + if (wall_clock64() - t0 > 50000000ull) __builtin_trap(); + } + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); + if (__hip_atomic_fetch_add(&sync[2], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) + 1u + == nb_all) { + __hip_atomic_store(&sync[0], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __hip_atomic_store(&sync[1], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __hip_atomic_store(&sync[2], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + } + } + __syncthreads(); + /* Every wave, not only thread 0's: a workgroup's waves can sit on both CUs of a WGP, each + * with its own vector cache, and `d` must be read past it. */ + __builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent"); +} + +/* ============================================================== hc_read, kernels B and B2 as one + * + * hc_up tiles the flattened index, so a channel's hc terms land in different workgroups and `u` + * round-trips through `ubuf` into hc_mix, a dependent launch that costs more than either kernel's + * work at one row. + * + * This workgroup instead owns 64 / hc channels in all hc sub-streams (the same 64 rows of W_up and + * grid, as hc runs of 64 / hc rows), so `u` stays in LDS. An arrival counter replaces the whole + * 128-channel scale group, as in hc_up_mix_tiled: the last workgroup covering a group of a row + * group quantises it from the bf16 `x` the others wrote. + * + * Bit-identical to the pair: the same per-row dots and narrowing as hc_up, the mean over c + * ascending as in hc_mix, and codes from the same bf16 values and amax. */ +/* RPT > 1 (E4M3 only) gives the workgroup RPT * 64 rows of W_up, RPT a thread with one + * quarter each (hc8_up_dot_rows), and 1 / RPT the grid (kUpRpt). WAIT is the fused form's + * (hc_read_fused_kernel): `d` and kernel A's scales are read only after hc_role_wait. */ +template +__device__ __forceinline__ void hc_up_mix_body(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd, unsigned bx, unsigned by, + unsigned int* __restrict__ sync = nullptr, unsigned na = 0, unsigned nb_all = 0) { + static_assert(RPT == 1 || F8, "several rows a thread is the E4M3 form's"); + constexpr int kBR = kUpRows * RPT; /* rows of W_up this workgroup owns */ + extern __shared__ __attribute__((aligned(16))) float sd[]; /* [RG * lr] */ + __shared__ unsigned short s_stage[kWaves][kWave * 8]; /* wave_dot_lds, one slot a wave */ + __shared__ unsigned short s_u[RG * kBR]; + const unsigned short* __restrict__ up = (const unsigned short*)upv; + const long r0 = (long)by * RG; + if (r0 >= rows) return; + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const int ipb = kBR / hc; /* channels this workgroup owns */ + const long i0 = (long)bx * ipb; + + /* Every load this kernel makes before its first barrier, issued together. At + * decode it is a chain of dependent latencies, not a stream of bytes (12 us at four rows with + * every byte cache-resident). `d` goes first, all of a thread's share at once (lr is at most + * two thread strides here), since loads return in order and `d` is what the barrier waits on; + * then this thread's quarter row of W_up, which does not depend on `d`; then, when one mix item + * a thread covers the block's (RG * ipb <= the thread count, always at hc 4), the hc values N + * of its channel from `h`, the norm gain and kernel A's scales. Same values, same order: + * bit-identical. */ + constexpr int kDStage = 2; + const bool dpre = lr <= (long)kDStage * kThreads; + unsigned short dv[RG][kDStage]; /* bf16 bits; the E4M3 dot keeps them as is */ + if (dpre && !WAIT) { +#pragma unroll + for (int r = 0; r < RG; ++r) { + const bool live = r0 + r < rows; +#pragma unroll + for (int s = 0; s < kDStage; ++s) { + const long k = tid + (long)s * kThreads; + dv[r][s] = (live && k < lr) ? dbuf[(r0 + r) * lr + k] : (unsigned short)0; + } + } + } + const int t = tid >> 2, q4 = tid & 3; + Hc8UpQuarter wq[RPT]; + if constexpr (F8) { + static_assert(kUpRows * 4 == kThreads, "four threads a row of W_up"); +#pragma unroll + for (int m = 0; m < RPT; ++m) { + const int tt = t + kUpRows * m; + const long j = (long)(tt / ipb) * n + i0 + tt % ipb; + hc8_up_load((const unsigned char*)upv + j * uld, lr, q4, wq[m]); + } + } + const bool one = RG * ipb <= kThreads; + float Npre[kHcMax]; + if constexpr (WAIT) { + /* The fused form (hc_read_fused_kernel): `h` and the gain now, kernel A's half after it. */ + float hv[kHcMax], wv[kHcMax]; + const int rl = one && tid < RG * ipb ? tid / ipb : 0, ii = tid - rl * ipb; + const long r = r0 + rl < rows ? r0 + rl : rows - 1; + if (one && tid < RG * ipb) { +#pragma unroll + for (int c = 0; c < kHcMax; ++c) { + if (c >= hc) break; + const long j = (long)c * n + i0 + ii; + hv[c] = bf2f(h[r * hrow + j]); + wv[c] = w[j]; + } + } + hc_role_wait(sync, na, nb_all); + if (dpre) { +#pragma unroll + for (int rr = 0; rr < RG; ++rr) { + const bool live = r0 + rr < rows; +#pragma unroll + for (int s2 = 0; s2 < kDStage; ++s2) { + const long k = tid + (long)s2 * kThreads; + dv[rr][s2] = (live && k < lr) ? dbuf[(r0 + rr) * lr + k] : (unsigned short)0; + } + } + } + if (one && tid < RG * ipb) { +#pragma unroll + for (int c = 0; c < kHcMax; ++c) { + if (c >= hc) break; + Npre[c] = nbf(hv[c] * scalein[r * kHcMax + c] * (wv[c] + wadd)); + } + } + } else if (one && tid < RG * ipb) { + const int rl = tid / ipb, ii = tid - rl * ipb; + const long r = r0 + rl < rows ? r0 + rl : rows - 1; + const long i = i0 + ii; +#pragma unroll + for (int c = 0; c < kHcMax; ++c) { + if (c >= hc) break; + const long j = (long)c * n + i; + Npre[c] = nbf(bf2f(h[r * hrow + j]) * scalein[r * kHcMax + c] * (w[j] + wadd)); + } + } + + /* `d` as bf16 for the E4M3 dot (hc8_up_dot_rows), as floats for the bf16 one. */ + unsigned short* const sdh = (unsigned short*)sd; + if (dpre) { +#pragma unroll + for (int r = 0; r < RG; ++r) +#pragma unroll + for (int s = 0; s < kDStage; ++s) { + const long k = tid + (long)s * kThreads; + if (k >= lr) continue; + if constexpr (F8) sdh[(long)r * lr + k] = dv[r][s]; + else sd[(long)r * lr + k] = bf2f(dv[r][s]); + } + } else { + /* Row by row rather than `k / lr`, a 64-bit division per element. */ +#pragma unroll + for (int r = 0; r < RG; ++r) { + const bool live = r0 + r < rows; + for (long k = tid; k < lr; k += kThreads) { + const unsigned short v = live ? dbuf[(r0 + r) * lr + k] : (unsigned short)0; + if constexpr (F8) sdh[(long)r * lr + k] = v; + else sd[(long)r * lr + k] = bf2f(v); + } + } + } + __syncthreads(); + + /* Row t of this workgroup's slice of W_up is sub-stream t / ipb of channel i0 + t % ipb. The + * E4M3 form takes each row four threads at a time, as in hc_up_kernel. */ + if constexpr (F8) { + float acc[RPT][RG]; + hc8_up_dot_rows(sdh, lr, wq, q4, acc); +#pragma unroll + for (int m = 0; m < RPT; ++m) +#pragma unroll + for (int r = 0; r < RG; ++r) + if (q4 == 0) s_u[r * kBR + t + kUpRows * m] = f2bf(sigmoidf_(acc[m][r])); + } else { + for (int t = wave; t < kUpRows; t += kWaves) { + const long j = (long)(t / ipb) * n + i0 + t % ipb; + float acc[RG]; + wave_dot_lds_rows(sd, lr, up + j * lr, lr, lane, s_stage[wave], acc); +#pragma unroll + for (int r = 0; r < RG; ++r) { + const float a = wave_sum(acc[r]); + if (lane == 0) s_u[r * kBR + t] = f2bf(sigmoidf_(a)); + } + } + } + __syncthreads(); + + const float inv_hc = 1.0f / (float)hc; + if (one) { + if (tid < RG * ipb) { + const int rl = tid / ipb, ii = tid - rl * ipb; + const long r = r0 + rl; + if (r < rows) { + float acc = 0.0f; +#pragma unroll + for (int c = 0; c < kHcMax; ++c) { + if (c >= hc) break; + acc += bf2f(s_u[rl * kBR + c * ipb + ii]) * Npre[c]; + } + acc *= inv_hc; + x[r * xrow + i0 + ii] = f2bf(acc); + } + } + } else + for (int idx = tid; idx < RG * ipb; idx += kThreads) { + const int rl = idx / ipb, ii = idx - rl * ipb; + const long r = r0 + rl; + if (r >= rows) continue; + const long i = i0 + ii; + float acc = 0.0f; + for (int c = 0; c < hc; ++c) { + const long j = (long)c * n + i; + const float Nv = nbf(bf2f(h[r * hrow + j]) * scalein[r * kHcMax + c] + * (w[j] + wadd)); + acc += bf2f(s_u[rl * kBR + c * ipb + ii]) * Nv; + } + acc *= inv_hc; + x[r * xrow + i] = f2bf(acc); + } + if (!q || !ctr) return; + + /* The group's last workgroup quantises it: kUpTB / ipb of them cover one group of a row group. */ + const int nb = kUpTB / ipb; + __threadfence(); + __syncthreads(); + __shared__ unsigned int s_arrived; + const unsigned slot = by * (unsigned)(n / kUpTB) + (unsigned)(i0 / kUpTB); + if (tid == 0) + s_arrived = __hip_atomic_fetch_add(&ctr[slot], 1u, __ATOMIC_ACQ_REL, + __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_arrived + 1u != (unsigned)nb) return; + if (tid == 0) + __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __threadfence(); + + /* One wave per row (RG <= wave count); a lane takes four of the group's 128 channels, one + * packed dword of codes. */ + if (wave >= RG) return; + const long r = r0 + wave; + if (r >= rows) return; + const long base = (i0 / kUpTB) * kUpTB; + const unsigned short* const xr = x + r * xrow + base; + /* A lane's four channels, read once for the amax, the codes and the rotation (it + * read the group three times, each a dependent round trip at the end of the step's chain). The + * amax is over the same 128 values and max is exact, so this is bit-identical. */ + static_assert(kUpTB == 4 * kWave, "a lane holds four channels of the group"); + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = bf2f(xr[lane * 4 + j]); + float m = fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3]))); + m = r4d_wave_max(m); + const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if (lane == 0) qs[r * srow + base / kUpTB] = sc; + const uint32_t pk = q8_pack4(v[0], v[1], v[2], v[3], inv); + *(unsigned*)(q + r * qrow + base + lane * 4) = (unsigned)pk; + if (rq) hc_rot_group(v, lane, rq + r * rqrow + base, rqs + r * rsrow + base / kUpTB); +} + +template +__global__ __launch_bounds__(kThreads) +void hc_up_mix_kernel(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd) { + hc_up_mix_body(upv, uld, dbuf, h, w, scalein, x, q, qs, rq, rqs, ctr, rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, blockIdx.x, blockIdx.y); +} + +/* ============================================================== hc_read, A and B in one grid + * + * At decode, kernel A is mostly latency (its norm prologue and the L2 round trips around + * its dots) with memory idle meanwhile, and kernel B cannot ask for W_up until A has ended. Run + * together, B's 3.4 MB of W_up is read while A's prologue waits, and B's work after it is short. + * + * Roles are handed out by ticket, not block index: a block's first act is an atomic increment of + * sync[0], and tickets below `na` run kernel A's body (then add one to sync[1]), the rest kernel + * B's. A B block loads its W_up rows, then waits for sync[1] to reach `na`. Every block holding a + * smaller ticket has already started, so the blocks it waits on are resident and finish whatever + * the waiters do: no co-residency is assumed and none can deadlock. The last B block past the + * wait clears the three counters for the next launch on this stream (stream order publishes it). + * A wait that runs past half a second traps rather than hang the card or read a stale `d`; it + * cannot happen with the counters in order. + * + * Bit-identical to the two launches: the same bodies, the same per-block work. */ +template +__global__ __launch_bounds__(kThreads) +__attribute__((amdgpu_waves_per_eu(9, 9))) +void hc_read_fused_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dbuf, unsigned short* __restrict__ inj, + float* __restrict__ scale, long ta, long irow, float eps, + const void* __restrict__ upv, long uld, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd, + unsigned int* __restrict__ sync, + unsigned na, unsigned gxa, unsigned gxb, unsigned nb_all) { + __shared__ unsigned s_ticket; + if (threadIdx.x == 0) + s_ticket = __hip_atomic_fetch_add(&sync[0], 1u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + const unsigned tk = s_ticket; + if (tk < na) { + hc_read_a_body(h, w, downv, dld, injw, dbuf, inj, scale, rows, n, hc, lr, + ta, hrow, irow, eps, wadd, tk % gxa, tk / gxa, gxa - 1u); + __threadfence(); + __syncthreads(); + if (threadIdx.x == 0) + __hip_atomic_fetch_add(&sync[1], 1u, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT); + return; + } + const unsigned b = tk - na; + hc_up_mix_body(upv, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, + rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, + wadd, b % gxb, b / gxb, sync, na, nb_all); +} + +/* Row group size: the row count, up to eight. RG is a template parameter so `acc[RG]` stays in + * registers. Every size from 1 to 8 is instantiated, so up to eight rows read the weight once + * (a five-row verify split 4 + 1 would read W_up twice). Output bytes do not depend on RG. + * + * LDS bounds it: RG rows of `d` are RG*lr floats beside 4 KiB of staging, so a wide low rank gets + * the largest group that fits rather than a launch failure. */ +static inline long hc_up_rg(long long rows, long long lr) { + constexpr long kLdsCap = 60 * 1024; /* leave the 4 KiB of staging slots room */ + long rg = rows < 8 ? (rows > 1 ? (long)rows : 1) : 8; + while (rg > 1 && (long long)rg * lr * (long long)sizeof(float) > kLdsCap) --rg; + return rg; +} + +static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const unsigned short* dbuf, + unsigned short* ubuf, long long rows, long long HN, long long lr, + RadStream stream) { + int emit_rc = RAD_OK; + const long rg = hc_up_rg(rows, lr); + const dim3 grid((unsigned)((HN + kUpRows - 1) / kUpRows), + (unsigned)((rows + rg - 1) / rg)); + const unsigned lds = (unsigned)(rg * lr * sizeof(float)); + const void* upp = up->data; +#define HC_UP1_CASE(RG_, F8_) \ + emit_rc = R4D_EMIT(stream, (hc_up_kernel), grid, dim3(kThreads), lds, upp, uld, \ + dbuf, ubuf, (long)rows, (long)HN, (long)lr) + switch (rg) { + case 8: if (f8) HC_UP1_CASE(8, true); else HC_UP1_CASE(8, false); break; + case 7: if (f8) HC_UP1_CASE(7, true); else HC_UP1_CASE(7, false); break; + case 6: if (f8) HC_UP1_CASE(6, true); else HC_UP1_CASE(6, false); break; + case 5: if (f8) HC_UP1_CASE(5, true); else HC_UP1_CASE(5, false); break; + case 4: if (f8) HC_UP1_CASE(4, true); else HC_UP1_CASE(4, false); break; + case 3: if (f8) HC_UP1_CASE(3, true); else HC_UP1_CASE(3, false); break; + case 2: if (f8) HC_UP1_CASE(2, true); else HC_UP1_CASE(2, false); break; + default: if (f8) HC_UP1_CASE(1, true); else HC_UP1_CASE(1, false); break; + } +#undef HC_UP1_CASE + return emit_rc; +} + +/* Rows of W_up a thread (hc_up_mix_kernel's RPT), where the wider workgroup's channels + * still divide a scale group and the width. Two, measured at Flash-Next's shape (rad-kbench, cold, + * the fused form at one, two and four rows): one row 18.4 / 18.9 / 20.6 us, two 17.0 / 17.8 / + * 20.4; four, before the bf16 dot, lost to two at every count (27.0 us at four rows, past the + * registers). */ +constexpr int kUpRpt = 2; +static inline int hc_up_rpt(bool f8, int hc, long n) { + int rpt = f8 ? kUpRpt : 1; + while (rpt > 1 && ((kUpRows * rpt) % hc || kUpTB % ((kUpRows * rpt) / hc) || + n % ((kUpRows * rpt) / hc))) + rpt >>= 1; + return rpt; +} + +/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of + * n / kUpTB scale groups. */ +/* ============================================================== the previous decode kernels + * + * hc_read's decode kernels as they were before the one-grid form and the pipelined tiled up-mix: + * kernel A, then the up-mix kernel in a second launch, and the tiled up-mix with its K passes in + * sequence. Kept verbatim behind r4d_hc_read_pin_decode(1) so r4d_selftest can compare the + * current forms with them byte for byte and --perfhc can time both from one build. */ +static int g_hc_decode_form = 0; + +template +__global__ __launch_bounds__(kThreads) +__attribute__((amdgpu_waves_per_eu(F8 ? 9 : 1, F8 ? 9 : 16))) +void hc_read_a_prev_kernel(const unsigned short* __restrict__ h, const float* __restrict__ w, + const void* __restrict__ downv, long dld, + const unsigned short* __restrict__ injw, + unsigned short* __restrict__ dout, unsigned short* __restrict__ inj, + float* __restrict__ scaleout, + long rows, long n, int hc, long lr, long ta, long hrow, long irow, + float eps, float wadd) { extern __shared__ unsigned short sN[]; /* [hc * n], transposed per 256-element chunk */ __shared__ float s_part[kWaves][kHcMax]; __shared__ float s_scale[kHcMax]; @@ -892,143 +1765,9 @@ void hc_read_a_kernel(const unsigned short* __restrict__ h, const float* __restr } } -/* ============================================================== hc_read, kernel B1 - * - * `u = sigmoid(W_up @ d)`, one wave per row of W_up. Separate from the mix for occupancy: the mix - * owns 128 channels (hc*128 rows of W_up), only twenty workgroups at width 2560 on 64 CUs, while - * this kernel runs HN/64 = 160 workgroups on the same bytes. `u` costs a 20 KiB-per-row round trip - * through scratch against 6.55 MiB of weight. - * - * RG rows share one block and one pass over the weight. With the row on blockIdx.y, a depth-3 MTP - * verify (four rows) streams W_up four times; the last-level cache absorbs most of it (1.4x, not - * 4x), but needlessly. `d` is 320 floats per row, so RG rows fit in LDS and a wave takes RG dots - * from each weight row it loads (~3% of a multi-row step, same output). RG=1 is the one-row case. - * - * At the decode grid this moves 6.55 MB in 14.9 us (440 GB/s; the part reads 621 cold). Measured - * slower: four rows in flight per wave (+16%); kUpRows 16 or 128; staging the 64-element tail as - * one wide load (+4.6%; both narrow loads hit one 128-byte line); eight consecutive rows per wave - * instead of strided (+9.9%; strided rows make a block's eight waves read one contiguous burst); - * and register-staging the tail (+13.1%; the compiler hoists the wait in front of the chunk load). - * A block-cooperative stage of the span would take 40 KiB of LDS (1 block per CU instead of 7). - * - * Bit-identical to wave_dot_lds: only the loop nest changes (rows move innermost), and `acc[]` is - * indexed by an unrolled constant so it stays in registers; a runtime `rows` bound would put it in - * scratch. */ - -/* RG rows of the LDS vector against one contiguous bf16 weight row, read once. `sv_ld` is the row - * pitch of `sv`. */ -template -__device__ __forceinline__ void wave_dot_lds_rows(const float* __restrict__ sv, long sv_ld, - const unsigned short* __restrict__ wr, long HN, - int lane, unsigned short* stage, - float* __restrict__ acc) { - constexpr long kPer = kWave * 8; -#pragma unroll - for (int r = 0; r < RG; ++r) acc[r] = 0.0f; - long j = 0; - if (((uintptr_t)wr & 15u) == 0u) { - for (; j + kPer <= HN; j += kPer) { - *(uint4*)(stage + lane * 8) = *(const uint4*)(wr + j + lane * 8); -#pragma unroll - for (int t = 0; t < 8; ++t) { - const int jj = lane + t * kWave; - const float wv = bf2f(stage[jj]); -#pragma unroll - for (int r = 0; r < RG; ++r) acc[r] += sv_at(sv, (long)r * sv_ld + j + jj) * wv; - } - } - } - for (long i = j + lane; i < HN; i += kWave) { - const float wv = bf2f(wr[i]); -#pragma unroll - for (int r = 0; r < RG; ++r) acc[r] += sv_at(sv, (long)r * sv_ld + i) * wv; - } -} - -template -__global__ __launch_bounds__(kThreads) -void hc_up_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, - unsigned short* __restrict__ ubuf, long rows, long hn, long lr) { - const unsigned short* __restrict__ up = (const unsigned short*)upv; - extern __shared__ float sd[]; /* [RG * lr] */ - __shared__ unsigned short s_stage[kWaves][kWave * 8]; /* wave_dot_lds, one slot a wave */ - const long r0 = (long)blockIdx.y * RG; - if (r0 >= rows) return; - const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; - - /* A dead row of the tail group is zero-filled, so its dot is defined; its store is dropped. */ - for (long k = tid; k < (long)RG * lr; k += kThreads) { - const long r = k / lr; - sd[k] = (r0 + r < rows) ? bf2f(dbuf[(r0 + r) * lr + (k - r * lr)]) : 0.0f; - } - __syncthreads(); - - const long j0 = (long)blockIdx.x * kUpRows; - /* The E4M3 form takes a row four threads at a time, a quarter (one scale group) each, so 256 - * threads cover the block's 64 rows in one pass. */ - if constexpr (F8) { - static_assert(kUpRows * 4 == kThreads, "four threads a row of W_up"); - const int tr = tid >> 2, q4 = tid & 3; - const long j = j0 + tr; - float acc[RG]; - hc8_dot_up(sd, lr, (const unsigned char*)upv + (j < hn ? j : hn - 1) * uld, q4, acc); -#pragma unroll - for (int r = 0; r < RG; ++r) - if (q4 == 0 && j < hn && r0 + r < rows) ubuf[(r0 + r) * hn + j] = f2bf(sigmoidf_(acc[r])); - return; - } - for (long t = wave; t < kUpRows; t += kWaves) { - const long j = j0 + t; - if (j >= hn) break; - float acc[RG]; - wave_dot_lds_rows(sd, lr, up + j * lr, lr, lane, s_stage[wave], acc); -#pragma unroll - for (int r = 0; r < RG; ++r) { - const float a = wave_sum(acc[r]); - /* Narrowed as in the reference, where the sigmoid output is bf16 before the multiply. */ - if (lane == 0 && r0 + r < rows) ubuf[(r0 + r) * hn + j] = f2bf(sigmoidf_(a)); - } - } -} - -/* Rotated fp8 codes of one 128-channel group, for a consumer whose weight carries a 128-wide - * Hadamard (the w4a8h expert plane). A wave holds the group four consecutive values per lane (the - * r4d_fwht_wave<128> layout), loaded by the caller from the stored bf16, and quantises exactly as - * the rotated quant_act_fp8 kernel does (transform, absmax, scale, clamp, packing), so no separate - * launch over `x` is needed. */ -__device__ __forceinline__ void hc_rot_group(float* v, int lane, unsigned char* qg, float* sg) { - r4d_fwht_wave(v, lane); - float m = 0.0f; -#pragma unroll - for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(v[j])); - m = r4d_wave_max(m); - const float sc = m > 0.0f ? m * (1.0f / 448.0f) : 1.0f; - if (lane == 0) *sg = sc; - const float inv = 1.0f / sc; - int pk = 0; - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[0] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[1] * inv, -448.0f), 448.0f), pk, false); - pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(v[2] * inv, -448.0f), 448.0f), - fminf(fmaxf(v[3] * inv, -448.0f), 448.0f), pk, true); - *(unsigned*)(qg + lane * 4) = (unsigned)pk; -} - -/* ============================================================== hc_read, kernels B and B2 as one - * - * hc_up tiles the flattened index, so a channel's hc terms land in different workgroups and `u` - * round-trips through `ubuf` into hc_mix, a dependent launch that costs more than either kernel's - * work at one row. - * - * This workgroup instead owns 64 / hc channels in all hc sub-streams (the same 64 rows of W_up and - * grid, as hc runs of 64 / hc rows), so `u` stays in LDS. An arrival counter replaces the whole - * 128-channel scale group, as in hc_up_mix_tiled: the last workgroup covering a group of a row - * group quantises it from the bf16 `x` the others wrote. - * - * Bit-identical to the pair: the same per-row dots and narrowing as hc_up, the mean over c - * ascending as in hc_mix, and codes from the same bf16 values and amax. */ template __global__ __launch_bounds__(kThreads) -void hc_up_mix_kernel(const void* __restrict__ upv, long uld, +void hc_up_mix_prev_kernel(const void* __restrict__ upv, long uld, const unsigned short* __restrict__ dbuf, const unsigned short* __restrict__ h, const float* __restrict__ w, const float* __restrict__ scalein, @@ -1138,63 +1877,22 @@ void hc_up_mix_kernel(const void* __restrict__ upv, long uld, } } -/* Row group size: the row count, up to eight. RG is a template parameter so `acc[RG]` stays in - * registers. Every size from 1 to 8 is instantiated, so up to eight rows read the weight once - * (a five-row verify split 4 + 1 would read W_up twice). Output bytes do not depend on RG. - * - * LDS bounds it: RG rows of `d` are RG*lr floats beside 4 KiB of staging, so a wide low rank gets - * the largest group that fits rather than a launch failure. */ -static inline long hc_up_rg(long long rows, long long lr) { - constexpr long kLdsCap = 60 * 1024; /* leave the 4 KiB of staging slots room */ - long rg = rows < 8 ? (rows > 1 ? (long)rows : 1) : 8; - while (rg > 1 && (long long)rg * lr * (long long)sizeof(float) > kLdsCap) --rg; - return rg; -} - -static inline int hc_up_launch(const RadTensor* up, long uld, bool f8, const unsigned short* dbuf, - unsigned short* ubuf, long long rows, long long HN, long long lr, - RadStream stream) { - int emit_rc = RAD_OK; - const long rg = hc_up_rg(rows, lr); - const dim3 grid((unsigned)((HN + kUpRows - 1) / kUpRows), - (unsigned)((rows + rg - 1) / rg)); - const unsigned lds = (unsigned)(rg * lr * sizeof(float)); - const void* upp = up->data; -#define HC_UP1_CASE(RG_, F8_) \ - emit_rc = R4D_EMIT(stream, (hc_up_kernel), grid, dim3(kThreads), lds, upp, uld, \ - dbuf, ubuf, (long)rows, (long)HN, (long)lr) - switch (rg) { - case 8: if (f8) HC_UP1_CASE(8, true); else HC_UP1_CASE(8, false); break; - case 7: if (f8) HC_UP1_CASE(7, true); else HC_UP1_CASE(7, false); break; - case 6: if (f8) HC_UP1_CASE(6, true); else HC_UP1_CASE(6, false); break; - case 5: if (f8) HC_UP1_CASE(5, true); else HC_UP1_CASE(5, false); break; - case 4: if (f8) HC_UP1_CASE(4, true); else HC_UP1_CASE(4, false); break; - case 3: if (f8) HC_UP1_CASE(3, true); else HC_UP1_CASE(3, false); break; - case 2: if (f8) HC_UP1_CASE(2, true); else HC_UP1_CASE(2, false); break; - default: if (f8) HC_UP1_CASE(1, true); else HC_UP1_CASE(1, false); break; - } -#undef HC_UP1_CASE - return emit_rc; -} - -/* hc_up_mix_kernel's launch: hc_up's row group; counter slots are (rows / rg) row groups of - * n / kUpTB scale groups. */ -static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool i8, - const unsigned short* dbuf, - const unsigned short* h, const float* w, const float* scale, - unsigned short* x, unsigned char* q, float* qs, - unsigned char* rq, float* rqs, - unsigned int* ctr, long long rows, long long n, int hc, - long long lr, long long hrow, long long xrow, long long qrow, - long long srow, long long rqrow, long long rsrow, float wadd, - RadStream stream) { +static inline int hc_up_mix_prev_launch(const RadTensor* up, long uld, bool f8, bool i8, + const unsigned short* dbuf, + const unsigned short* h, const float* w, const float* scale, + unsigned short* x, unsigned char* q, float* qs, + unsigned char* rq, float* rqs, + unsigned int* ctr, long long rows, long long n, int hc, + long long lr, long long hrow, long long xrow, long long qrow, + long long srow, long long rqrow, long long rsrow, float wadd, + RadStream stream) { int emit_rc = RAD_OK; const long rg = hc_up_rg(rows, lr); const dim3 grid((unsigned)(n / (kUpRows / hc)), (unsigned)((rows + rg - 1) / rg)); const unsigned lds = (unsigned)(rg * lr * sizeof(float)); const void* upp = up->data; #define HC_UPMIX_CASE3(RG_, F8_, I8_) \ - emit_rc = R4D_EMIT(stream, (hc_up_mix_kernel), grid, dim3(kThreads), lds, \ + emit_rc = R4D_EMIT(stream, (hc_up_mix_prev_kernel), grid, dim3(kThreads), lds, \ upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \ hc, \ (long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ @@ -1216,6 +1914,52 @@ static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool return emit_rc; } +static inline int hc_up_mix_launch(const RadTensor* up, long uld, bool f8, bool i8, + const unsigned short* dbuf, + const unsigned short* h, const float* w, const float* scale, + unsigned short* x, unsigned char* q, float* qs, + unsigned char* rq, float* rqs, + unsigned int* ctr, long long rows, long long n, int hc, + long long lr, long long hrow, long long xrow, long long qrow, + long long srow, long long rqrow, long long rsrow, float wadd, + RadStream stream) { + if (g_hc_decode_form == 1) + return hc_up_mix_prev_launch(up, uld, f8, i8, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, + rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd, + stream); + int emit_rc = RAD_OK; + const long rg = hc_up_rg(rows, lr); + const int rpt = hc_up_rpt(f8, hc, n); + const dim3 grid((unsigned)(n / (kUpRows * rpt / hc)), (unsigned)((rows + rg - 1) / rg)); + const unsigned lds = (unsigned)(rg * lr * sizeof(float)); + const void* upp = up->data; +#define HC_UPMIX_K(RG_, F8_, I8_, RPT_) \ + emit_rc = R4D_EMIT(stream, (hc_up_mix_kernel), grid, dim3(kThreads), lds, \ + upp, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, (long)rows, (long)n, \ + hc, \ + (long)lr, (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ + (long)rsrow, wadd) +#define HC_UPMIX_F8(RG_, I8_) \ + do { if (rpt == 2) HC_UPMIX_K(RG_, true, I8_, 2); else HC_UPMIX_K(RG_, true, I8_, 1); } while (0) +#define HC_UPMIX_CASE(RG_) \ + do { if (f8) { if (i8) HC_UPMIX_F8(RG_, true); else HC_UPMIX_F8(RG_, false); } \ + else if (i8) HC_UPMIX_K(RG_, false, true, 1); else HC_UPMIX_K(RG_, false, false, 1); } while (0) + switch (rg) { + case 8: HC_UPMIX_CASE(8); break; + case 7: HC_UPMIX_CASE(7); break; + case 6: HC_UPMIX_CASE(6); break; + case 5: HC_UPMIX_CASE(5); break; + case 4: HC_UPMIX_CASE(4); break; + case 3: HC_UPMIX_CASE(3); break; + case 2: HC_UPMIX_CASE(2); break; + default: HC_UPMIX_CASE(1); break; + } +#undef HC_UPMIX_CASE +#undef HC_UPMIX_F8 +#undef HC_UPMIX_K + return emit_rc; +} + /* ============================================================== hc_read, kernel B2 * * `x = mean_c( u[c] * N[c] )` for this workgroup's 128 channels, plus their fp8 codes: 128 is one @@ -1689,6 +2433,15 @@ void hc_down_wide_kernel(const unsigned short* __restrict__ h, const float* __re /* Eight elements of row j of W_up at k as staged bf16: the stored bf16, or eight E4M3 codes decoded * with their group's scale. A group is a multiple of sixteen codes, so eight aligned codes never * straddle two groups. */ +/* e4m3x8_bf16 on codes already in registers. */ +__device__ __forceinline__ uint4 e4m3x8_bf16v(uint2 c, float sc) { + float f[8]; + e4m3x8(c.x, c.y, f); +#pragma unroll + for (int e = 0; e < 8; ++e) f[e] *= sc; + return f2bf8(f); +} + template __device__ __forceinline__ uint4 hc_up_stage(const void* __restrict__ upv, long uld, long j, long k, long lr) { @@ -1822,6 +2575,283 @@ void hc_up_mix_tiled_kernel(const void* __restrict__ upv, long uld, if (tid < NT) s_j[tid] = (long)(tid % hc) * n + i0 + tid / hc; __syncthreads(); + v8f acc[AM][AN]; +#pragma unroll + for (int im = 0; im < AM; ++im) +#pragma unroll + for (int in = 0; in < AN; ++in) acc[im][in] = (v8f){0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; + + /* The WMMA of one staged pass. */ + auto mma = [&]() { +#pragma unroll + for (int im = 0; im < AM; ++im) { + const int mt = wave / WN + im * WM; + if (mt >= MT) continue; +#pragma unroll + for (int in = 0; in < AN; ++in) { + const int nt = wave % WN + in * WN; + if (nt >= NT16) continue; + acc[im][in] = gemm(sA, kTAP, mt, sB, kTAP, nt, lane, acc[im][in]); + } + } + }; + + /* At the decode tile (RT 32, E4M3, lr a whole number of passes) the K loop is + * software-pipelined: a pass issues the next pass's loads before staging its own from + * registers, and the mix's operands are loaded with the first pass, where each pass waited + * on its own loads. Addresses are computed once, nothing branches and the barriers order LDS + * only (hc_lds_barrier), so the waits stay partial. 17.8 -> 16.6 us at 32 rows (rad-kbench, + * cold): the kernel is bound less by memory than by its staging, barriers and WMMA. The staged + * values are the loop's own, in the same order: bit-identical. */ + constexpr int kAPer = RT * (kTKT / 8) / kThreads, kBPer = NT * (kTKT / 8) / kThreads; + constexpr int kNPer = RT * NT / kThreads; + constexpr bool kPipe = F8 && RT == 32 && kAPer == 1 && kBPer * kThreads == NT * (kTKT / 8) + && kNPer * kThreads == RT * NT; + const bool pipe = kPipe && lr % kTKT == 0; + float nh[kPipe ? kNPer : 1], nw[kPipe ? kNPer : 1], nsc[kPipe ? kNPer : 1]; + if constexpr (kPipe) { + if (pipe) { + const int nit = (int)(lr / kTKT), G = (int)r4d_hc8::up_group(lr); + const int rrA = tid / (kTKT / 8), k8A = (tid % (kTKT / 8)) * 8; + long rA = r0 + rrA; + if (rA >= rows) rA = rows - 1; + const unsigned short* const ap = dbuf + rA * lr + k8A; + const unsigned char* bp[kBPer]; + int k8B[kBPer], ttB[kBPer]; +#pragma unroll + for (int b = 0; b < kBPer; ++b) { + const int idx = tid + b * kThreads; + ttB[b] = idx / (kTKT / 8); + k8B[b] = (idx % (kTKT / 8)) * 8; + bp[b] = (const unsigned char*)upv + s_j[ttB[b]] * uld; + } + uint4 ca = *(const uint4*)ap; + uint2 cb[kBPer]; + float cs[kBPer]; +#pragma unroll + for (int b = 0; b < kBPer; ++b) { + cb[b] = *(const uint2*)(bp[b] + k8B[b]); + cs[b] = ((const float*)(bp[b] + lr))[k8B[b] / G]; + } +#pragma unroll + for (int q2 = 0; q2 < kNPer; ++q2) { + const int idx = tid + q2 * kThreads; + const int rl = idx / NT, rem = idx - rl * NT; + const int c = rem / ipb, ii = rem - c * ipb; + long r = r0 + rl; + if (r >= rows) r = rows - 1; + const long j = (long)c * n + i0 + ii; + nh[q2] = bf2f(h[r * hrow + j]); + nsc[q2] = scalein[r * kHcMax + c]; + nw[q2] = w[j]; + } + for (int it = 0; it < nit; ++it) { + /* The next pass's operands; after the last pass the first's again, in bounds. */ + const int kn = it + 1 < nit ? (it + 1) * kTKT : 0; + const uint4 na = *(const uint4*)(ap + kn); + uint2 nb[kBPer]; + float ns[kBPer]; +#pragma unroll + for (int b = 0; b < kBPer; ++b) { + nb[b] = *(const uint2*)(bp[b] + kn + k8B[b]); + ns[b] = ((const float*)(bp[b] + lr))[(kn + k8B[b]) / G]; + } + hc_lds_barrier(); + *(uint4*)(sA + rrA * kTAP + k8A) = ca; +#pragma unroll + for (int b = 0; b < kBPer; ++b) + *(uint4*)(sB + ttB[b] * kTAP + k8B[b]) = e4m3x8_bf16v(cb[b], cs[b]); + hc_lds_barrier(); + mma(); + ca = na; +#pragma unroll + for (int b = 0; b < kBPer; ++b) { + cb[b] = nb[b]; + cs[b] = ns[b]; + } + } + } + } + + if (!pipe) + for (long k0 = 0; k0 < lr; k0 += kTKT) { + __syncthreads(); + for (int idx = tid; idx < RT * (kTKT / 8); idx += kThreads) { + const int rr = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; + long r = r0 + rr; if (r >= rows) r = rows - 1; + const long ka = k0 + k8; + uint4 va = make_uint4(0u, 0u, 0u, 0u); + if (ka + 8 <= lr) va = *(const uint4*)(dbuf + r * lr + ka); + *(uint4*)(sA + rr * kTAP + k8) = va; + } + for (int idx = tid; idx < NT * (kTKT / 8); idx += kThreads) { + const int tt = idx / (kTKT / 8), k8 = (idx % (kTKT / 8)) * 8; + const long k = k0 + k8; + uint4 v = make_uint4(0u, 0u, 0u, 0u); + if (k + 8 <= lr) v = hc_up_stage(upv, uld, s_j[tt], k, lr); + *(uint4*)(sB + tt * kTAP + k8) = v; + } + __syncthreads(); + mma(); + } + /* N in a separate coalesced pass: in the WMMA epilogue consecutive lanes hold consecutive + * sub-streams, so reading `h` there would stride n elements per lane. Here consecutive threads + * take consecutive channels of one sub-stream, as in hc_mix. */ + if (pipe) { +#pragma unroll + for (int q2 = 0; q2 < (kPipe ? kNPer : 1); ++q2) { + const int idx = tid + q2 * kThreads; + const int rl = idx / NT, rem = idx - rl * NT; + const int c = rem / ipb, ii = rem - c * ipb; + if (r0 + rl < rows) s_N[rl * NT + ii * hc + c] = f2bf(nh[q2] * nsc[q2] * (nw[q2] + wadd)); + } + } else + for (int idx = tid; idx < RT * NT; idx += kThreads) { + const int rl = idx / NT, rem = idx - rl * NT; + const int c = rem / ipb, ii = rem - c * ipb; + const long r = r0 + rl; + if (r >= rows) continue; + const long j = (long)c * n + i0 + ii; + s_N[rl * NT + ii * hc + c] = + f2bf(bf2f(h[r * hrow + j]) * scalein[r * kHcMax + c] * (w[j] + wadd)); + } + + /* u from the accumulators. */ + const int e0 = 8 * (lane >> 4), nn = lane & 15; +#pragma unroll + for (int im = 0; im < AM; ++im) { + const int mt = wave / WN + im * WM; + if (mt >= MT) continue; +#pragma unroll + for (int in = 0; in < AN; ++in) { + const int nt = wave % WN + in * WN; + if (nt >= NT16) continue; + const int t = nt * 16 + nn; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const long r = r0 + mt * 16 + e0 + e; + if (r >= rows) continue; + s_u[(r - r0) * NT + t] = f2bf(sigmoidf_(acc[im][in][e])); + } + } + } + __syncthreads(); + + const float inv_hc = 1.0f / (float)hc; + for (int idx = tid; idx < RT * ipb; idx += kThreads) { + const int rl = idx / ipb, ii = idx - rl * ipb; + const long r = r0 + rl; + if (r >= rows) continue; + const unsigned short* const up_ = s_u + rl * NT + ii * hc; + const unsigned short* const np_ = s_N + rl * NT + ii * hc; + float a = 0.0f; + for (int c = 0; c < hc; ++c) a += bf2f(up_[c]) * bf2f(np_[c]); + x[r * xrow + i0 + ii] = f2bf(a * inv_hc); + } + if (!q || !ctr) return; + + /* The group's last workgroup quantises it; `nb` workgroups cover one 128-channel group. */ + const int nb = kUpTB / ipb; + __threadfence(); + __syncthreads(); + __shared__ unsigned int s_arrived; + const unsigned slot = blockIdx.y * (gridDim.x / nb) + (unsigned)(i0 / kUpTB); + if (tid == 0) + s_arrived = __hip_atomic_fetch_add(&ctr[slot], 1u, __ATOMIC_ACQ_REL, + __HIP_MEMORY_SCOPE_AGENT); + __syncthreads(); + if (s_arrived + 1u != (unsigned)nb) return; + if (tid == 0) + __hip_atomic_store(&ctr[slot], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT); + __threadfence(); + + /* The rotated codes need a whole wave per row, while the codes below use kThreads / RT threads + * per row, so the rotation walks the tile's rows a wave at a time first. */ + /* Both finishers below load what they read before using any of it -- the + * rotation every row of the wave's, the codes a thread's four-channel runs -- where they + * walked rows and channels a dependent load at a time; the codes' amax is over the same 128 + * values. The tail of this kernel is one block's chain, so these were its links. Bit-identical. */ + if (rq) { + const long gb = (i0 / kUpTB) * kUpTB; + constexpr int kRPW = (RT + kWaves - 1) / kWaves; /* rows a wave */ + float v[kRPW][4]; +#pragma unroll + for (int i = 0; i < kRPW; ++i) { + const long r = r0 + wave + i * kWaves; + const unsigned short* const xr = x + (r < rows ? r : rows - 1) * xrow + gb; +#pragma unroll + for (int j = 0; j < 4; ++j) v[i][j] = bf2f(xr[lane * 4 + j]); + } +#pragma unroll + for (int i = 0; i < kRPW; ++i) { + const long r = r0 + wave + i * kWaves; + if (wave + i * kWaves >= RT || r >= rows) break; + hc_rot_group(v[i], lane, rq + r * rqrow + gb, rqs + r * rsrow + gb / kUpTB); + } + } + + constexpr int kTPR = kThreads / RT; /* threads a row; RT divides kThreads */ + constexpr int kRuns = (kUpTB / 4) / kTPR; /* a thread's four-channel runs */ + const int rl = tid / kTPR, lr_ = tid % kTPR; + const long r = r0 + rl; + if (r >= rows) return; + const long base = (i0 / kUpTB) * kUpTB; + const unsigned short* const xr = x + r * xrow + base; + float xv[kRuns][4]; +#pragma unroll + for (int u = 0; u < kRuns; ++u) +#pragma unroll + for (int j = 0; j < 4; ++j) xv[u][j] = bf2f(xr[(lr_ + u * kTPR) * 4 + j]); + float m = 0.0f; +#pragma unroll + for (int u = 0; u < kRuns; ++u) +#pragma unroll + for (int j = 0; j < 4; ++j) m = fmaxf(m, fabsf(xv[u][j])); + m = r4d_xor_max(m); + const float sc = m > 0.0f ? m * (1.0f / q8_top()) : 1.0f; + const float inv = 1.0f / sc; + if (lr_ == 0) qs[r * srow + base / kUpTB] = sc; +#pragma unroll + for (int u = 0; u < kRuns; ++u) { + const int c4 = (lr_ + u * kTPR) * 4; + const uint32_t pk = q8_pack4(xv[u][0], xv[u][1], xv[u][2], xv[u][3], inv); + *(unsigned*)(q + r * qrow + base + c4) = (unsigned)pk; + } +} + +/* The tiled up-mix as it was before its K passes were pipelined (see the previous decode + * kernels above; r4d_hc_read_pin_decode(1)). */ +template +__global__ __launch_bounds__(kThreads) +void hc_up_mix_tiled_prev_kernel(const void* __restrict__ upv, long uld, + const unsigned short* __restrict__ dbuf, + const unsigned short* __restrict__ h, const float* __restrict__ w, + const float* __restrict__ scalein, + unsigned short* __restrict__ x, unsigned char* __restrict__ q, + float* __restrict__ qs, unsigned char* __restrict__ rq, + float* __restrict__ rqs, unsigned int* __restrict__ ctr, + long rows, long n, int hc, long lr, long hrow, long xrow, + long qrow, long srow, long rqrow, long rsrow, float wadd) { + __shared__ unsigned short sA[RT * kTAP]; + __shared__ unsigned short sB[NT * kTAP]; + __shared__ unsigned short s_u[RT * NT]; + __shared__ unsigned short s_N[RT * NT]; + __shared__ long s_j[NT]; + + constexpr int MT = RT / 16, NT16 = NT / 16; + constexpr int WM = (MT < kWaves) ? MT : kWaves, WN = kWaves / WM; + constexpr int AM = (MT + WM - 1) / WM, AN = (NT16 + WN - 1) / WN; + + const int tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave; + const int ipb = NT / hc; /* channels this workgroup owns */ + const long r0 = (long)blockIdx.y * RT; + const long i0 = (long)blockIdx.x * ipb; + if (r0 >= rows) return; + + /* The column map, once: tile column t is sub-stream t % hc of channel i0 + t / hc. */ + if (tid < NT) s_j[tid] = (long)(tid % hc) * n + i0 + tid / hc; + __syncthreads(); + v8f acc[AM][AN]; #pragma unroll for (int im = 0; im < AM; ++im) @@ -2186,11 +3216,12 @@ unsigned int* hc_mix_ctr(RadStream s) { if (slot[dev][i].ctr.load(std::memory_order_relaxed) == nullptr) { fi = i; break; } if (fi < 0) return nullptr; void* p = nullptr; - if (hipMalloc(&p, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess) return nullptr; + if (hipMalloc(&p, (size_t)(kMaxMixCtr + kHcSyncCtr) * sizeof(unsigned int)) != hipSuccess) + return nullptr; /* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has * finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it * runs on the null stream, which a non-blocking stream does not wait for, so wait here. */ - if (hipMemset(p, 0, (size_t)kMaxMixCtr * sizeof(unsigned int)) != hipSuccess || + if (hipMemset(p, 0, (size_t)(kMaxMixCtr + kHcSyncCtr) * sizeof(unsigned int)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) { (void)hipFree(p); return nullptr; @@ -2209,16 +3240,22 @@ static inline void hc_up_mix_tiled_launch(int rt, bool f8, bool i8, const void* long xrow, long qrow, long srow, long rqrow, long rsrow, float wadd, RadStream s) { const dim3 gm((unsigned)(n / (kTNT / hc)), (unsigned)((rows + rt - 1) / rt)); + /* Through r4d_emit, so r4d_record_dispatches sees which form ran. */ +#define HC_UM_K(K_) \ + (void)R4D_EMIT(s, K_, gm, dim3(kThreads), 0, up, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, \ + rows, n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd) #define HC_UM_CASE3(RT_, F8_, I8_) \ - hipLaunchKernelGGL((hc_up_mix_tiled_kernel), gm, dim3(kThreads), 0, \ - (hipStream_t)s, up, uld, dbuf, h, w, scale, x, q, qs, rq, rqs, ctr, rows, \ - n, hc, lr, hrow, xrow, qrow, srow, rqrow, rsrow, wadd) + do { \ + if (g_hc_decode_form == 1) HC_UM_K((hc_up_mix_tiled_prev_kernel)); \ + else HC_UM_K((hc_up_mix_tiled_kernel)); \ + } while (0) #define HC_UM_CASE(RT_, F8_) \ do { if (i8) HC_UM_CASE3(RT_, F8_, true); else HC_UM_CASE3(RT_, F8_, false); } while (0) if (f8) { if (rt == 32) HC_UM_CASE(32, true); else HC_UM_CASE(64, true); } else { if (rt == 32) HC_UM_CASE(32, false); else HC_UM_CASE(64, false); } #undef HC_UM_CASE #undef HC_UM_CASE3 +#undef HC_UM_K } /* The codes of `x` and the rotated codes, after a mix that writes only `x`: hc_quant_rows_kernel @@ -3717,14 +4754,67 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { * within 1.7 us of each other. Performance is not smooth in block count, so leave ta at 4. */ while (ta > 4 && ((lr + ta - 1) / ta) * rows < 2 * want_wg()) ta >>= 1; -#define HC_READ_A(F8_) \ - R4D_EMIT(s, hc_read_a_kernel, dim3((unsigned)((lr + ta - 1) / ta) + 1u, (unsigned)rows), \ + /* The preloaded prologue at the shape it is instantiated for (hc 4, n 2560), and + * there kernels A and B as one grid (hc_read_fused_kernel) when the row group is the whole + * step, the up-mix fuses (q's counters or none) and the per-stream counters exist. */ + const bool pre = f8 && hc == 4 && n == 10LL * kThreads && g_hc_decode_form != 1; + if (pre) { + const long rgf = hc_up_rg(rows, lr); + const int rpt = hc_up_rpt(true, (int)hc, n); + const long ipf = (long)kUpRows * rpt / hc; + const long lds = HN * 2 > rgf * lr * 4 ? HN * 2 : rgf * lr * 4; + unsigned int* fctr = (rgf >= rows && rgf <= 7 && kUpTB % ipf == 0 && n % ipf == 0 + && lds + kHcReadAStaticLds + 8 * kUpRows * 4 * 2 + 256 <= 65536) + ? hc_mix_ctr(s) : nullptr; + if (fctr) { + const unsigned gxa = (unsigned)((lr + ta - 1) / ta) + 1u; + const unsigned na = gxa * (unsigned)rows; + const unsigned gxb = (unsigned)(n / ipf); + const unsigned nbf_ = gxb; /* one row group */ +#define HC_FUSED_K(RG_, I8_, RPT_) \ + emit_rc = R4D_EMIT(s, (hc_read_fused_kernel), \ + dim3(na + nbf_), dim3(kThreads), (unsigned)lds, \ + (const unsigned short*)h->data, (const float*)w->data, (const void*)down->data, \ + (long)dld, injw ? (const unsigned short*)injw->data : nullptr, dbuf, \ + inj ? (unsigned short*)inj->data : nullptr, scale, (long)ta, (long)irow, eps, \ + (const void*)up->data, (long)uld, (unsigned short*)x->data, \ + q ? (unsigned char*)q->data : nullptr, q ? (float*)qs->data : nullptr, \ + rq ? (unsigned char*)rq->data : nullptr, rq ? (float*)rqs->data : nullptr, \ + q ? fctr : nullptr, (long)rows, (long)n, (int)hc, (long)lr, \ + (long)hrow, (long)xrow, (long)qrow, (long)srow, (long)rqrow, \ + (long)rsrow, wadd, fctr + kMaxMixCtr, na, gxa, gxb, nbf_) +#define HC_FUSED_R(RG_, I8_) \ + do { if (rpt == 2) HC_FUSED_K(RG_, I8_, 2); else HC_FUSED_K(RG_, I8_, 1); } while (0) +#define HC_FUSED_CASE(RG_) \ + do { if (i8) HC_FUSED_R(RG_, true); else HC_FUSED_R(RG_, false); } while (0) + switch (rgf) { + case 7: HC_FUSED_CASE(7); break; + case 6: HC_FUSED_CASE(6); break; + case 5: HC_FUSED_CASE(5); break; + case 4: HC_FUSED_CASE(4); break; + case 3: HC_FUSED_CASE(3); break; + case 2: HC_FUSED_CASE(2); break; + default: HC_FUSED_CASE(1); break; + } +#undef HC_FUSED_CASE +#undef HC_FUSED_R +#undef HC_FUSED_K + if (emit_rc != RAD_OK) return R4D_NO(RAD_E_DEVICE); + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); + } + } + +#define HC_READ_A(KERNEL_) \ + R4D_EMIT(s, KERNEL_, dim3((unsigned)((lr + ta - 1) / ta) + 1u, (unsigned)rows), \ dim3(kThreads), (unsigned)(HN * sizeof(unsigned short)), \ (const unsigned short*)h->data, (const float*)w->data, (const void*)down->data, \ (long)dld, injw ? (const unsigned short*)injw->data : nullptr, dbuf, \ inj ? (unsigned short*)inj->data : nullptr, scale, (long)rows, (long)n, (int)hc, \ (long)lr, (long)ta, (long)hrow, (long)irow, eps, wadd) - emit_rc = f8 ? HC_READ_A(true) : HC_READ_A(false); + if (g_hc_decode_form == 1) + emit_rc = f8 ? HC_READ_A(hc_read_a_prev_kernel) : HC_READ_A(hc_read_a_prev_kernel); + else if (pre) emit_rc = HC_READ_A((hc_read_a_kernel)); + else emit_rc = f8 ? HC_READ_A(hc_read_a_kernel) : HC_READ_A(hc_read_a_kernel); #undef HC_READ_A if (emit_rc != RAD_OK) return R4D_NO(RAD_E_DEVICE); if (hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE); @@ -3775,3 +4865,4 @@ extern "C" int r4d_rad_hc_read(const RadArgs* a, RadStream s) { } extern "C" void r4d_hc_read_pin_prefill(int form) { g_hc_prefill_form = form; } +extern "C" void r4d_hc_read_pin_decode(int form) { g_hc_decode_form = form; } diff --git a/libr4d/r4d_layout.cpp b/libr4d/r4d_layout.cpp index 69bae64c..84e1df1e 100644 --- a/libr4d/r4d_layout.cpp +++ b/libr4d/r4d_layout.cpp @@ -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; diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 9c1a3a1d..44375176 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -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, diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 419c0bb4..7ea5c5fd 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -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 hw = bf((size_t)(conv_dim * W), 0.5f); const std::vector hcs = bf((size_t)(CSLOTS * conv_dim * SL), 1.0f); std::vector 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 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 v(n); + for (auto& e : v) e = h_to_bf16(s * rnd()); + return v; + }; + const std::vector hw = bf((size_t)(xdim * W), 0.5f), hb = bf((size_t)xdim, 0.25f); + const std::vector hx = bf((size_t)(Tn * xdim), 1.0f); + const std::vector hab = bf((size_t)(Tn * 2 * H), 1.0f); + const std::vector hcs = bf((size_t)(CSLOTS * xdim * SL), 1.0f); + std::vector 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{ tx, tw, tb, tcs, tsl, T(d_nacc, RAD_I32, { N }), tcu, + tq, tk, tv }; + return std::vector{ + 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 ps = f.prep + ? std::vector{ PI("M", Tn), PI("head_k", K), PI("head_v", V), + PI("chunk", 64), PI("conv_width", W) } + : std::vector{ PI("q_len", MQ), PI("head_k", K), PI("head_v", V), + PI("conv_width", W) }; + auto run = [&](std::vector 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 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 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 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( + (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 hh((size_t)(M * HN)); + for (auto& v : hh) v = h_to_bf16((float)((int)(rnd() % 2001) - 1000) / 400.0f); + std::vector 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 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 down = plane(lr, HN, r4d_hc8::down_group(HN), dld); + std::vector up = plane(HN, lr, r4d_hc8::up_group(lr), uld); + std::vector 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 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 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 x, inj, q, qs, rq, rs; std::vector 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& 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 outs; + std::vector 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& 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 ps = { @@ -25179,6 +25538,7 @@ static void ar_two_rank(const Plugin& pl, const std::vector& 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& 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& 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& 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& 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 t; @@ -25787,6 +26151,7 @@ static void ar_wide_pattern(const Plugin& pl, const std::vector& 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& 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 uneven = { @@ -26476,6 +26842,7 @@ static void ar_lane_forms(const Plugin& pl, const std::vector& 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 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& 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& 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 shapes; if (!want_gather) { @@ -27279,6 +27648,7 @@ static void ar_rmsnorm_quant_i8_wide_case(const Plugin& pl, const std::vector + 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" diff --git a/spec.md b/spec.md index 696187e8..04f8e7cf 100644 --- a/spec.md +++ b/spec.md @@ -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 `.`. 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. --- diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index d0d967c0..e315197c 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -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) diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 91cc8a70..b79be67e 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -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 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 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); + } } } diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index d8d78bb0..cb612d21 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -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 strs; -}; -struct GTensor { std::string name; uint32_t type; std::vector ne; std::vector 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& kvs, const std::vector& 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>* planes, + std::vector* 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> planes; + std::vector 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 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(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> planes; + std::vector 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> planes; + std::vector 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 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> got, want; + std::vector 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 kvs = { diff --git a/tests/config_test.cpp b/tests/config_test.cpp index c3e91a98..c1f88a8e 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -437,6 +437,7 @@ const std::map>& 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>& 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) { diff --git a/tests/convert_test.cpp b/tests/convert_test.cpp index 4d18885b..8e2de6a8 100644 --- a/tests/convert_test.cpp +++ b/tests/convert_test.cpp @@ -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 @@ -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 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 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() diff --git a/tests/gbnf_test.cpp b/tests/gbnf_test.cpp index ac57da48..97b3744b 100644 --- a/tests/gbnf_test.cpp +++ b/tests/gbnf_test.cpp @@ -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 g; + CHECK_OK(GbnfGrammar::create(gbnf, "root", &bv->v, false, {}, {}, &g, &err)); + auto whole = [&](const std::string& text) { + std::unique_ptr 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 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 diff --git a/tests/gguf_writer.h b/tests/gguf_writer.h new file mode 100644 index 00000000..09dad778 --- /dev/null +++ b/tests/gguf_writer.h @@ -0,0 +1,76 @@ +/* gguf_writer.h -- GGUF v3 files written by tests: header keys and tensors, the tensors' bytes as + * the caller built them. */ +#pragma once + +#include +#include +#include +#include + +namespace ggufw { + +struct GKv { + std::string key; + uint32_t type; /* 4 u32, 6 f32, 8 string, 9 array of strings */ + double num = 0; + std::vector strs; +}; +struct GTensor { + std::string name; + uint32_t type; + std::vector ne; /* fastest dimension first, as GGUF stores it */ + std::vector bytes; +}; + +inline void put_bytes(std::string* b, const void* p, size_t n) { b->append((const char*)p, n); } +inline 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. */ +inline bool write_gguf(const std::string& path, const std::vector& kvs, + const std::vector& 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'); + } + FILE* f = std::fopen(path.c_str(), "wb"); + if (!f) return false; + const bool ok = std::fwrite(b.data(), 1, b.size(), f) == b.size(); + return std::fclose(f) == 0 && ok; +} + +} /* namespace ggufw */ diff --git a/tests/kernel_report_check.sh b/tests/kernel_report_check.sh new file mode 100755 index 00000000..8bdd2326 --- /dev/null +++ b/tests/kernel_report_check.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# kernel_report_check.sh -- the checked-in kernel report is internally consistent. +# +# docs/KERNELS.md is generated by `rad-kbench --report` and reviewed by hand. A hand-merged +# regeneration can carry a per-library "N row(s) not reached" header from one run and the table +# below it from another: at v1.13.0 the libr4d header says 239 while its table lists 243 rows +# (the four kv_store_streamed rows landed in 486c9331 without the count moving), so the section +# total (378) and the headline "132 of 510 declared row(s) were reached" both read four rows +# short of the tables. The generator cannot produce this from one run -- header and table come +# from one vector -- so the report is checked here, and a partially regenerated file fails. +# +# A check that cannot fail is not a check (docs/DEVLOG-decode-floor.md). +set -u +REPORT=$1 +test -f "$REPORT" || { echo "kernel_report_check: no report at $REPORT"; exit 1; } +# The counting is one python3 pass; a host without it skips, like ops_doc's skip codes. +command -v python3 >/dev/null 2>&1 || { echo " SKIP python3 not present"; exit 77; } + +python3 - "$REPORT" <<'PY' +import re, sys +lines = open(sys.argv[1]).read().split("\n") +pat = re.compile(r"`lib\w+`: (\d+) row\(s\) not reached:") +heads = [(i, m.group(1)) for i, l in enumerate(lines) if (m := pat.match(l))] +bad = 0 +for j, (a, claimed) in enumerate(heads): + # The library's table ends at the next library header or the next section header. + b = len(lines) + for i in range(a + 1, len(lines)): + if pat.match(lines[i]) or lines[i].startswith("## "): + b = i + break + rows = sum(1 for l in lines[a:b] if l.startswith("| `")) + name = re.match(r"`(\w+)`", lines[a]).group(1) + print(f" {name}: header {claimed}, table {rows}") + if int(claimed) != rows: + bad += 1 +text = "\n".join(lines) +m = re.search(r"(\d+) of (\d+) declared row\(s\) were reached", text) +if m: + ran, declared = int(m.group(1)), int(m.group(2)) + missed = sum(int(x) for x in pat.findall(text)) + if ran + missed != declared: + print(f" headline: {ran} reached + {missed} not reached != {declared} declared") + bad += 1 +if bad: + print(f"kernel_report_check: {bad} inconsistent count(s); regenerate the report from one run.") + sys.exit(1) +print("kernel_report_check: the report's counts agree.") +PY diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 41df9c91..94aa2592 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -1827,21 +1828,24 @@ TEST(kv_window_snapshot_rows_and_seed) { kv.free_sequence(2); } -/* A window is snapshotted only where a hit resumes from it: the trunk's window in a model without - * linear state. With linear state a hit on a windowed trunk re-prefills, and a drafter's window is - * recomputed by draft refill, so a window section there would be copied and never read. */ +/* A window is snapshotted only where a hit resumes from it: the trunk's window, with or without + * linear state beside it. A drafter's window is recomputed by draft refill, so a window section + * there would be copied and never read. */ TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) { KVGroupInfo w = paged_group("swa", RAD_KV_WINDOW, 2, 16, { 6 }, 64); const Config cfg = small_config(); - { /* beside linear state: the slot holds only the state */ + { /* beside linear state: the slot holds the state, then the window. Without the window a + * hit could not resume on such a model at all (the scheduler refuses a trunk hole). */ std::vector g = hybrid_groups(); g.push_back(w); Pools p; CHECK_OK(configure_pools(p, cfg)); KVManager kv; CHECK_OK(kv.configure(g, cfg, p.kv())); - CHECK(!kv.has_window_snapshot()); - CHECK_EQ(kv.checkpoint_bytes(), 16384ll); + CHECK(kv.has_window_snapshot()); + const KVGroupPlan* wp = kv.plan(3); + REQUIRE(wp && wp->win_snap); + CHECK_EQ(kv.checkpoint_bytes(), 16384ll + wp->window_blocks * wp->bytes_per_block); } { /* a drafter's own window over a full-attention trunk */ std::vector g = hybrid_groups(/*with_linear=*/false); @@ -2421,6 +2425,222 @@ TEST(checkpoint_interval_must_be_a_block_multiple) { CHECK_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_E_INVAL); } +/* ================================================================== mixed block sizes + * + * A model can keep KV at different strides: DeepSeek-V4's compressed attention stores one row per + * r tokens (a block of r) beside groups at one row a token. The cache indexes every such group at + * the lcm of their blocks, an entry holding lcm / B blocks of a B-token group, so a hit ends on a + * block of each and adopt() takes every group. Leaving the finer groups out left the trunk a hole + * the scheduler refuses every hit for. + */ +static KVGroupInfo gdn_group(std::vector layers) { + KVGroupInfo k; + k.name = "gdn"; + k.decl.kind = RAD_KV_LINEAR; + k.decl.dtype = RAD_F32; + k.decl.n_head_kv = 4; + k.decl.state_dim[0] = 16; + k.decl.state_dim[1] = 16; + k.layers = std::move(layers); + return k; +} + +/* Handles: 1 = the coarse group (`a`-token blocks), 2 = the fine one (`b`), 3 = linear state. */ +static std::vector mixed_groups(int64_t a, int64_t b, bool with_linear) { + std::vector g; + g.push_back(null_group()); + g.push_back(paged_group("coarse", RAD_KV_FULL, 2, a, { 0, 1 })); + g.push_back(paged_group("fine", RAD_KV_FULL, 1, b, { 2 })); + if (with_linear) g.push_back(gdn_group({ 3, 4 })); + return g; +} + +static std::vector head(const std::vector& v, int64_t n) { + return std::vector(v.begin(), v.begin() + std::min(n, (int64_t)v.size())); +} + +TEST(a_cache_over_mixed_block_sizes_indexes_every_group_at_their_lcm) { + for (const auto& ab : { std::pair{ 2, 1 }, { 2, 4 }, { 16, 2 } }) { + const int64_t a = ab.first, b = ab.second, L = std::lcm(a, b); + Fixture f; + REQUIRE_EQ(f.build_groups(mixed_groups(a, b, false)), RAD_OK); + REQUIRE(f.pc.enabled()); + CHECK_EQ(f.pc.block_size(), L); + CHECK(f.pc.cached_groups() == (std::vector{ 1, 2 })); + CHECK_EQ(f.pc.blocks_per_entry(0), L / a); + CHECK_EQ(f.pc.blocks_per_entry(1), L / b); + std::vector eg; + for (int64_t k = 0; k < L / a; ++k) eg.push_back(1); + for (int64_t k = 0; k < L / b; ++k) eg.push_back(2); + CHECK(f.pc.entry_groups() == eg); + /* Named once in the report, and nothing left out. */ + CHECK(f.pc.report().find("not cached") == std::string::npos); + CHECK(f.pc.report().find("blocks an entry") != std::string::npos); + const int64_t free1 = f.kv.free_blocks(1), free2 = f.kv.free_blocks(2); + + /* 101 tokens publish their whole entries: 96 or 100 of them. */ + const auto p = tok_run(300, 101); + const int64_t whole = 101 / L * L; + publish(f, 1, p, 101); + CHECK_EQ(f.pc.size(), whole / L); + const std::vector t1 = f.kv.block_table(1, 1), t2 = f.kv.block_table(1, 2); + for (int64_t k = 0; k < whole / a; ++k) CHECK_EQ(f.kv.block_refcount(1, t1[(size_t)k]), 2); + for (int64_t k = 0; k < whole / b; ++k) CHECK_EQ(f.kv.block_refcount(2, t2[(size_t)k]), 2); + /* The partial block past the last entry is the sequence's alone. */ + if ((int64_t)t2.size() > whole / b) CHECK_EQ(f.kv.block_refcount(2, t2[(size_t)(whole / b)]), 1); + + /* A longer prompt hits every published entry, with each group's own blocks. */ + auto longer = p; + for (int i = 0; i < 40; ++i) longer.push_back(900 + i); + std::vector> got; + CHECK_EQ(f.pc.lookup(longer, {}, &got).n_attn_tokens, (int32_t)whole); + REQUIRE_EQ(got.size(), 2u); + CHECK(got[0] == head(t1, whole / a)); + CHECK(got[1] == head(t2, whole / b)); + /* A full hit backs off one entry, and a divergence ends the hit on the entry below it. */ + CHECK_EQ(f.pc.lookup(head(p, whole), {}).n_attn_tokens, (int32_t)(whole - L)); + auto edited = p; + edited[37] += 5000; + CHECK_EQ(f.pc.lookup(edited, {}).n_attn_tokens, (int32_t)(37 / L * L)); + + /* The hit adopts in every group, and the blocks are shared, not copied. */ + CHECK_OK(f.kv.add_sequence(2)); + for (size_t i = 0; i < 2; ++i) + CHECK_OK(f.kv.adopt(2, f.pc.cached_groups()[i], got[i], whole)); + CHECK_OK(f.kv.ensure(2, (int64_t)longer.size())); + CHECK_EQ(f.kv.block_refcount(2, t2[0]), 3); + CHECK(head(f.kv.block_table(2, 2), whole / b) == head(t2, whole / b)); + f.kv.free_sequence(1); + f.kv.free_sequence(2); + CHECK_EQ(f.kv.block_refcount(1, t1[0]), 1); + CHECK_EQ(f.pc.unshared_tokens(), whole); + + /* Eviction takes the deepest entry: its blocks in both groups go back together. */ + const int64_t e1 = f.kv.free_blocks(1), e2 = f.kv.free_blocks(2); + CHECK_EQ(f.pc.evict_lru(1), 1ll); + CHECK_EQ(f.kv.free_blocks(1), e1 + L / a); + CHECK_EQ(f.kv.free_blocks(2), e2 + L / b); + CHECK_EQ(f.pc.lookup(longer, {}).n_attn_tokens, (int32_t)(whole - L)); + CHECK_EQ(f.pc.unshared_tokens(), whole - L); + /* trim() counts entries too. */ + CHECK_EQ(f.pc.trim(2), 2ll); + CHECK_EQ(f.kv.free_blocks(1), e1 + 3 * (L / a)); + CHECK_EQ(f.kv.free_blocks(2), e2 + 3 * (L / b)); + /* A restore's room is in entries: the group shortest of whole entries decides. */ + const int64_t room = std::min((f.kv.total_blocks(1) - f.kv.held_blocks(1)) / (L / a), + (f.kv.total_blocks(2) - f.kv.held_blocks(2)) / (L / b)); + CHECK_EQ(f.pc.restore_room(), room); + f.pc.clear(); + CHECK_EQ(f.kv.free_blocks(1), free1); + CHECK_EQ(f.kv.free_blocks(2), free2); + } +} + +/* A publish whose tables are short of an entry's blocks in one group is refused whole, and one + * that cannot take a reference in a later group gives back what it took in the earlier ones. */ +TEST(a_mixed_publish_short_of_a_groups_blocks_is_refused_and_takes_nothing) { + Fixture f; + REQUIRE_EQ(f.build_groups(mixed_groups(2, 1, false)), RAD_OK); + const auto p = tok_run(40, 32); + CHECK_OK(f.kv.add_sequence(1)); + CHECK_OK(f.kv.ensure(1, 32)); + std::vector> bt = { f.kv.block_table(1, 1), f.kv.block_table(1, 2) }; + std::vector> shorter = bt; + shorter[1].resize(31); /* 16 entries need 32 one-token blocks */ + CHECK_EQ(f.pc.insert(1, p, {}, shorter, 32), RAD_E_INVAL); + CHECK_EQ(f.pc.size(), 0ll); + /* A free block in the fine group cannot be retained: the entry is unwound. */ + std::vector> bad = bt; + int32_t loose = -1; + CHECK_OK(f.kv.reserve_block(2, &loose)); + f.kv.release_block(2, loose); /* back on the free list */ + bad[1][1] = loose; + CHECK_EQ(f.pc.insert(1, p, {}, bad, 32), RAD_E_STATE); + CHECK_EQ(f.kv.block_refcount(1, bt[0][0]), 1); + CHECK_EQ(f.kv.block_refcount(2, bt[1][0]), 1); + CHECK_OK(f.pc.insert(1, p, {}, bt, 32)); + CHECK_EQ(f.kv.block_refcount(2, bt[1][0]), 2); +} + +/* Checkpoints are keyed on the entry grid: the chain at the lcm of the blocks, as the scheduler's + * binding builds it (PCBinding::prefix_hash). A position off the grid has no key. */ +TEST(a_checkpoint_over_mixed_blocks_sits_on_the_entry_grid) { + for (const auto& ab : { std::pair{ 2, 1 }, { 2, 4 } }) { + const int64_t L = std::lcm(ab.first, ab.second); + Fixture f; + f.cfg.checkpoint_slots = 4; + REQUIRE_EQ(f.build_groups(mixed_groups(ab.first, ab.second, true)), RAD_OK); + CHECK_EQ(f.pc.checkpoint_interval(), 64ll); + const auto prompt = tok_run(7000, 202); + publish(f, 1, prompt, 202); + const std::vector hs = chain_of(prompt, (int)L); + const int64_t tail = 198 / L * L; + for (int64_t pos : { (int64_t)64, tail }) { + int32_t slot = -1; + CHECK_OK(f.pc.reserve_checkpoint(1, pos, hs[(size_t)(pos / L - 1)], &slot)); + f.pc.commit_checkpoint(hs[(size_t)(pos / L - 1)]); + } + auto longer = prompt; + for (int i = 0; i < 30; ++i) longer.push_back(80000 + i); + CacheHit h = f.pc.lookup(longer, {}); + CHECK_EQ(h.n_attn_tokens, (int32_t)(202 / L * L)); + CHECK_EQ(h.n_linear_tokens, (int32_t)tail); + CHECK(h.checkpoint_slot >= 0); + /* Diverging below the tail resumes at the interval snapshot. */ + auto edited = prompt; + edited[150] += 9; + CHECK_EQ(f.pc.lookup(edited, {}).n_linear_tokens, 64); + /* Off the grid: refused. */ + int32_t slot = -1; + CHECK_EQ(f.pc.reserve_checkpoint(1, L + 1, hs[0], &slot), RAD_E_INVAL); + + /* The scheduler's binding keys a snapshot on the same chain. */ + PCBinding bind(&f.pc); + Request r; + r.id = 5; + r.prompt = longer; + CHECK_OK(bind.reserve_checkpoint(r, 128, &slot)); + bind.commit_checkpoint(r, 128); + auto at128 = prompt; + for (size_t k = 130; k < at128.size(); ++k) at128[k] += 7; + CHECK_EQ(f.pc.lookup(at128, {}).n_linear_tokens, 128); + } +} + +/* The interval must be a multiple of an entry; the chunk quantum, which the engine rounds it to, + * is a multiple of every paged group's block and so of the lcm. */ +TEST(a_mixed_cache_refuses_an_interval_off_its_entry_grid) { + Fixture f; + f.cfg.checkpoint_interval = 66; /* a multiple of 2, not of lcm(2, 4) */ + f.cfg.checkpoint_slots = 2; + CHECK_OK(configure_pools(f.pools, f.cfg)); + CHECK_OK(f.kv.configure(mixed_groups(2, 4, true), f.cfg, f.pools.kv())); + log_set_level(Log::Error); + CHECK_EQ(f.pc.configure(f.cfg, &f.kv, f.cfg.checkpoint_interval), RAD_E_INVAL); + log_set_level(Log::Info); + CHECK_OK(f.pc.configure(f.cfg, &f.kv, 68)); + CHECK_EQ(f.pc.block_size(), 4ll); +} + +/* A model with linear state beside a trunk window and groups at two strides (DeepSeek-V4.1's + * shape): the cache indexes both full groups, and the window rides in the checkpoint slot after + * the state, so a hit resumes at a snapshot with nothing left out. */ +TEST(a_hybrid_with_a_window_and_mixed_blocks_leaves_only_the_window_to_the_slot) { + Fixture f; + f.cfg.checkpoint_slots = 4; + std::vector g = mixed_groups(2, 1, true); + g.push_back(paged_group("swa", RAD_KV_WINDOW, 2, 16, { 5 }, 64)); /* handle 4 */ + REQUIRE_EQ(f.build_groups(g), RAD_OK); + CHECK(f.kv.has_window_snapshot()); + const KVGroupPlan* w = f.kv.plan(4); + REQUIRE(w && w->win_snap); + CHECK_EQ(f.kv.checkpoint_bytes(), + f.kv.plan(3)->bytes_per_state + w->window_blocks * w->bytes_per_block); + CHECK(f.pc.cached_groups() == (std::vector{ 1, 2 })); + CHECK_EQ(f.pc.block_size(), 2ll); + CHECK(f.pc.report().find("a checkpoint slot carries its window") != std::string::npos); +} + /* ================================================================== retention */ TEST(geometric_backoff_keeps_the_tip_and_its_ancestors) { @@ -4994,24 +5214,26 @@ static void scribble(Fixture& f) { /* The number of entries whose blocks in `now` hold, in every cached group and layer, exactly what * their blocks in `was` held before the move: this rank's own bytes, and for a replicated group - * rank 0's, the one copy the slot holds. */ + * rank 0's, the one copy the slot holds. An entry is blocks_per_entry(gi) blocks of group gi. */ static int64_t same_bytes(Fixture& f, int rank, const std::vector>& was, const std::vector>& now) { const std::vector& cg = f.pc.cached_groups(); int64_t good = 0; - for (size_t k = 0; k < was[0].size(); ++k) { + const int64_t n = (int64_t)was[0].size() / f.pc.blocks_per_entry(0); + for (int64_t e = 0; e < n; ++e) { bool ok = true; for (size_t gi = 0; gi < cg.size() && ok; ++gi) { const KVGroupPlan* p = f.kv.plan(cg[gi]); if (p->zero) continue; const int r = p->replicated ? 0 : rank; - const int64_t frag = p->layer_bytes_per_block(); - for (int64_t l = 0; l < p->n_layers && ok; ++l) { - const unsigned char* row = - (const unsigned char*)p->base + l * p->layer_stride() + now[gi][k] * frag; - for (int64_t i = 0; i < frag && ok; ++i) - ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][k], i); - } + const int64_t frag = p->layer_bytes_per_block(), per = f.pc.blocks_per_entry(gi); + for (int64_t k = e * per; k < (e + 1) * per && ok; ++k) + for (int64_t l = 0; l < p->n_layers && ok; ++l) { + const unsigned char* row = (const unsigned char*)p->base + + l * p->layer_stride() + now[gi][(size_t)k] * frag; + for (int64_t i = 0; i < frag && ok; ++i) + ok = row[i] == pat(r, cg[gi] * 16 + l, was[gi][(size_t)k], i); + } } good += ok; } @@ -5059,6 +5281,9 @@ struct TransferCase { bool replicated = false; bool alike = false; bool verify = false; + /* The key cache at 8-token blocks: an entry is one attention block and two key blocks, and + * the slot, the staging entry and the jobs all go by the entry's blocks. */ + bool mixed = false; }; static void run_transfer(const TransferCase& tc) { const int world = tc.world; @@ -5085,11 +5310,14 @@ static void run_transfer(const TransferCase& tc) { * replicated attention group, which leaves that rank's own window empty. */ if (zero_last && r == world - 1) groups[tc.replicated ? 2 : 1].zero = true; if (tc.replicated) groups[1].replicated = true; + if (tc.mixed) groups[2].block_size = 8; REQUIRE_EQ(fx.back()->build_groups(groups), RAD_OK); } Fixture& f = *fx[0]; - const std::vector& cg = f.pc.cached_groups(); - REQUIRE_EQ(cg.size(), 2u); + REQUIRE_EQ(f.pc.cached_groups().size(), 2u); + /* One group per block an entry holds (PrefixCache::entry_groups), as bringup passes them. */ + const std::vector& cg = f.pc.entry_groups(); + REQUIRE_EQ(cg.size(), tc.mixed ? 3u : 2u); /* The slot as bringup lays it out: a replicated group once at the front, then each rank's own * window following the previous ones. Checked against the plain sums here. */ std::vector kvs; @@ -5146,6 +5374,7 @@ static void run_transfer(const TransferCase& tc) { REQUIRE_EQ(f.pc.lookup(prompt, {}, &hit).n_attn_tokens, 320); const std::vector> was = hit; CHECK(was[0][0] != was[1][0]); + CHECK_EQ((int64_t)was[1].size(), tc.mixed ? 40ll : 20ll); for (int r = 0; r < world; ++r) fill(*fx[(size_t)r], r, tc.alike); /* ---- out ---- */ @@ -5233,6 +5462,24 @@ TEST(each_rank_restores_its_own_window_of_a_shared_slot) { run_transfer({ 2, /*fragment=*/false }); run_transfer({ 2, /*fragment=*/true }); } +/* An entry over groups at different block sizes moves as its blocks: one attention block and two + * key-cache blocks a slot, each through its own staging window, and every byte comes back. With a + * replicated attention group beside a zero rank the windows still stay apart. */ +TEST(an_entry_over_mixed_block_sizes_moves_through_the_tiers_block_by_block) { + TransferCase tc; + tc.mixed = true; + for (int world : { 1, 2 }) + for (bool fragment : { false, true }) { + tc.world = world; + tc.fragment = fragment; + run_transfer(tc); + } + tc.world = 3; + tc.fragment = false; + tc.zero_last = true; + tc.replicated = true; + run_transfer(tc); +} TEST(a_rank_with_a_zero_group_moves_only_its_own_groups) { run_transfer({ 3, /*fragment=*/false, /*zero_last=*/true }); run_transfer({ 3, /*fragment=*/true, /*zero_last=*/true }); @@ -6413,6 +6660,81 @@ TEST(a_checkpoint_carries_the_window_page_by_page_and_skips_the_padding) { rad_stream_destroy(st); } +/* Linear state, a conv window and a trunk window in one slot, as on DeepSeek-V4.1: the state + * section first in plan order, then the window pages, and a restore puts each back where it + * belongs -- the state into the resumed sequence's slots, the pages into its seeded blocks. */ +TEST(a_checkpoint_carries_linear_state_and_the_window_together) { + if (!host_backend_or_skip("the hybrid checkpoint round trip")) return; + Fixture f; + f.cfg.checkpoint_slots = 4; + std::vector g = hybrid_conv_groups(); + g.push_back(paged_group("swa", RAD_KV_WINDOW, 2, 16, { 7, 8 }, 64)); /* handle 4 */ + REQUIRE_EQ(f.build_groups(g), RAD_OK); + const KVGroupPlan* w = f.kv.plan(4); + REQUIRE(w && w->win_snap && f.kv.has_window_snapshot()); + const int64_t state = f.kv.plan(G_GDN)->bytes_per_state + f.kv.plan(G_CV)->bytes_per_state; + const int64_t page = w->bytes_per_block, lb = w->layer_bytes_per_block(); + REQUIRE_EQ(f.kv.checkpoint_bytes(), state + w->window_blocks * page); + auto block = [&](int64_t l, int32_t b) { + return (unsigned char*)w->base + l * w->layer_stride() + b * lb; + }; + for (int64_t l = 0; l < w->n_layers; ++l) + for (int32_t b = 0; b < (int32_t)w->n_blocks; ++b) + for (int64_t i = 0; i < lb; ++i) block(l, b)[i] = pat(7, l, b, i); + + CHECK_OK(f.kv.add_sequence(1)); + CHECK_OK(f.kv.ensure(1, 400)); + const std::vector a = slots_of(f.kv, 1); + fill_states(f.kv, 0); + std::vector rows; + REQUIRE(f.kv.window_rows(1, 400, &rows)); + int32_t ck = -1; + REQUIRE_EQ(f.kv.alloc_checkpoint(&ck), RAD_OK); + unsigned char* blob = (unsigned char*)f.kv.checkpoint_ptr(ck); + std::memset(blob, 0x5A, (size_t)f.kv.checkpoint_bytes()); + RadStream st = nullptr; + REQUIRE_EQ(rad_stream_create(&st, 0), RAD_OK); + CHECK_OK(f.kv.checkpoint_save(a.data(), (int)a.size(), ck, st, &rows)); + CHECK_OK(rad_stream_sync(st)); + int64_t off = 0, wrong = 0; + for (int32_t gi : { (int32_t)G_GDN, (int32_t)G_CV }) { + const KVGroupPlan* p = f.kv.plan(gi); + const int64_t sl = p->bytes_per_state / p->n_layers; + for (int64_t l = 0; l < p->n_layers; ++l, off += sl) + for (int64_t i = 0; i < sl; ++i) wrong += blob[off + i] != pat(0, gi * 16 + l, a[(size_t)gi], i); + } + CHECK_EQ(off, state); + for (int64_t j = 0; j < w->window_blocks; ++j) + for (int64_t l = 0; l < w->n_layers; ++l) + for (int64_t i = 0; i < lb; ++i) { + const unsigned char want = rows[(size_t)j] >= 0 ? pat(7, l, rows[(size_t)j], i) : 0x5A; + wrong += blob[state + j * page + l * lb + i] != want; + } + CHECK_EQ(wrong, 0ll); + + /* Back into a fresh sequence: its state slots take A's copy 0, its seeded window the pages. */ + CHECK_OK(f.kv.add_sequence(2)); + CHECK_OK(f.kv.seed_window(2, 400)); + CHECK_OK(f.kv.ensure(2, 432, 400)); /* the chunk after the hit, as admit_one */ + const std::vector b = slots_of(f.kv, 2); + REQUIRE(b[(size_t)G_GDN] >= 0 && b[(size_t)G_CV] >= 0); + std::vector rows2; + REQUIRE(f.kv.window_rows(2, 400, &rows2)); + for (int64_t l = 0; l < w->n_layers; ++l) + for (int32_t r : rows2) if (r >= 0) std::memset(block(l, r), 0xEE, (size_t)lb); + CHECK_OK(f.kv.checkpoint_restore(b.data(), (int)b.size(), ck, st, &rows2)); + CHECK_OK(rad_stream_sync(st)); + CHECK_EQ(states_wrong(f.kv, 0, b, a), 0ll); + wrong = 0; + for (size_t j = 0; j < rows2.size(); ++j) { + if (rows2[j] < 0) continue; + for (int64_t l = 0; l < w->n_layers; ++l) + for (int64_t i = 0; i < lb; ++i) wrong += block(l, rows2[j])[i] != pat(7, l, rows[j], i); + } + CHECK_EQ(wrong, 0ll); + rad_stream_destroy(st); +} + /* ================================================================== multimodal prefix keys * * Placeholder token ids are the same for every picture, so the content key of each media span diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 77b47781..6e991c70 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -55,9 +55,11 @@ for d in "$S"/arch/*/ "$S"/plugin/*/; do [ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")" done # The device libraries: built out of tree only with the tree's HIP compiler, and left out of every -# comparison below without it. +# comparison below without it. Each declares the family it serves, so a tree built for one family +# produces one of them: libr3d returns without a target when RAD_GPU_TARGETS holds no gfx11, and the +# checks below compare the two builds of the same list, not a fixed list. devlibs="" -for d in libr4d; do +for d in libr4d libr3d; do [ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d" done [ -n "$HIPC" ] && dirs="$dirs $devlibs" diff --git a/tests/place_test.cpp b/tests/place_test.cpp index 6e290897..3d340c21 100644 --- a/tests/place_test.cpp +++ b/tests/place_test.cpp @@ -3908,4 +3908,224 @@ TEST(a_mover_gives_back_every_event_and_device_byte) { CHECK(vram1 - vram0 <= 2 * MiB + 4096); } +/* ================================================================== the two placement flags + * + * --draft-expert-placement host pins a draft head's routed experts in the host pool before any + * strategy runs, so they fit beside a trunk that already fills the card. --expert-pin-top keeps + * the hottest fraction of the routed experts resident, so heat never demotes them. */ + +/* A trunk of `trunk` routed layers and a draft head of `head` layers past it, `n` experts each. */ +void build_drafted(Fixture& f, int trunk, int head, int n, int64_t each) { + f.prog.meta.n_layers = (uint32_t)trunk; + f.prog.drafter.kind = RAD_DRAFT_BLOCK; + f.prog.drafter.depth = 5; + build_moe_layers(f, trunk + head, n, each, 0); +} + +TEST(draft_experts_pin_to_the_host_pool) { + Fixture f; + build_drafted(f, 2, 1, 4, 1 * MiB); + + Config c = base_config(); + c.placement = "expert_tiered"; + c.vram_weights_mib = 1024; + c.host_pool_mib = 64; + c.draft_expert_placement = "host"; + c.draft_expert_placement_given = true; + + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + CHECK_OK(Planner(in).plan(&p)); + + int pinned = 0, trunk_vram = 0; + for (const MoveUnit& mu : p.units) { + if (mu.expert < 0) continue; + if (mu.layer >= 2) { + CHECK(mu.host_forced); + CHECK(mu.tier == Tier::HostPinned); + CHECK(mu.site == Site::DeviceZeroCopy); + CHECK(!mu.movable); + ++pinned; + } else if (mu.tier == Tier::VRAM) { + ++trunk_vram; + } + } + /* The head's four experts, and only those, are forced into the pool. */ + CHECK_EQ(pinned, 4); + CHECK(trunk_vram > 0); + CHECK(p.draft_host_bytes >= 4 * MiB); + CHECK(p.report(f.prog).find("drafter") != std::string::npos); + + /* The footprint agrees: the head is the part of the plane the flag takes out. */ + WeightFootprint wf; + weight_footprint(f.prog, &wf, TablePlacement::Vram, TablePlacement::Disk, false, false); + CHECK(wf.draft_experts >= 4 * MiB); + CHECK(wf.draft_experts < wf.experts); +} + +TEST(draft_placement_auto_leaves_the_head_to_the_strategy) { + Fixture f; + build_drafted(f, 2, 1, 4, 1 * MiB); + + Config c = base_config(); + c.placement = "all_vram"; + c.vram_weights_mib = 1024; + + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + CHECK_OK(Planner(in).plan(&p)); + for (const MoveUnit& mu : p.units) + if (mu.expert >= 0 && mu.layer >= 2) CHECK(!mu.host_forced); + CHECK_EQ(p.draft_host_bytes, (int64_t)0); +} + +TEST(draft_placement_host_refuses_a_model_with_no_drafter) { + Fixture f; + build_moe_layers(f, 2, 4, 1 * MiB, 0); + + Config c = base_config(); + c.placement = "all_vram"; + c.vram_weights_mib = 1024; + c.host_pool_mib = 64; + c.draft_expert_placement = "host"; + c.draft_expert_placement_given = true; + + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + CHECK_EQ(Planner(in).plan(&p), RAD_E_INVAL); +} + +TEST(draft_placement_host_refuses_when_the_pool_is_short) { + Fixture f; + build_drafted(f, 1, 1, 8, 4 * MiB); + + Config c = base_config(); + c.placement = "expert_tiered"; + c.vram_weights_mib = 1024; + c.host_pool_mib = 1; + c.draft_expert_placement = "host"; + + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + CHECK_EQ(Planner(in).plan(&p), RAD_E_NOMEM); + CHECK(p.report(f.prog).find("DID NOT FIT") != std::string::npos); +} + +TEST(expert_pin_top_keeps_the_hottest_resident) { + Fixture f; + build_moe_layers(f, 2, 8, 1 * MiB, 0); + + /* Expert e of each layer takes share e + 1, so the hottest are the high indices. */ + std::vector prof; + for (int l = 0; l < 2; ++l) + for (int e = 0; e < 8; ++e) { + RadFileProfile r{}; + r.layer = l; + r.expert = e; + r.share = (float)(e + 1); + prof.push_back(r); + } + + Config c = base_config(); + c.placement = "expert_tiered"; + c.vram_weights_mib = 1024; + c.host_pool_mib = 1024; + c.expert_pin_top = 0.25f; + + PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()}; + Plan p; + CHECK_OK(Planner(in).plan(&p)); + + int pinned = 0, hot_pinned = 0; + for (const MoveUnit& mu : p.units) { + if (mu.expert < 0) continue; + if (mu.pinned) { + CHECK(mu.tier == Tier::VRAM); + CHECK(!mu.movable); + ++pinned; + if (mu.expert >= 6) ++hot_pinned; + } + } + /* The top quarter of 16 experts: the two hottest of each layer. */ + CHECK_EQ(pinned, 4); + CHECK_EQ(hot_pinned, 4); + CHECK(p.report(f.prog).find("pinned hot") != std::string::npos); +} + +TEST(expert_pin_top_zero_pins_nothing) { + Fixture f; + build_moe_layers(f, 1, 4, 1 * MiB, 0); + + Config c = base_config(); + c.placement = "all_vram"; + c.vram_weights_mib = 1024; + c.expert_pin_top = 0.0f; + + PlannerInput in{&f.prog, &c, 0, 1, nullptr, 0}; + Plan p; + CHECK_OK(Planner(in).plan(&p)); + for (const MoveUnit& mu : p.units) CHECK(!mu.pinned); + CHECK_EQ(p.pinned_units, (int64_t)0); +} + +TEST(a_pinned_resident_is_never_demoted) { + Fixture f; + build_moe_layers(f, 1, 4, 1 * MiB, 0); + + std::vector prof; + for (int e = 0; e < 4; ++e) { + RadFileProfile r{}; + r.layer = 0; + r.expert = e; + r.share = (float)(e + 1); + prof.push_back(r); + } + Config c = base_config(); + c.placement = "expert_tiered"; + c.vram_weights_mib = 1024; + c.host_pool_mib = 1024; + c.expert_pin_top = 0.5f; + + PlannerInput in{&f.prog, &c, 0, 1, prof.data(), (int64_t)prof.size()}; + Plan p; + CHECK_OK(Planner(in).plan(&p)); + + /* Force one pinned unit and one cold unit onto the host, so the engine has a swap to make, + * and heat the cold one far above the pinned one. */ + int32_t pinned_u = -1, cold_u = -1; + for (size_t u = 0; u < p.units.size(); ++u) { + if (p.units[u].pinned && pinned_u < 0) pinned_u = (int32_t)u; + if (p.units[u].expert == 0) cold_u = (int32_t)u; + } + CHECK(pinned_u >= 0 && cold_u >= 0); + p.units[(size_t)cold_u].tier = Tier::HostPinned; + p.units[(size_t)cold_u].movable = true; + + HeatEngine h; + HeatParams hp; + hp.warmup_dispatches = 0; + CHECK_OK(h.init(p, hp)); + const int32_t ids[] = {0}; + const int32_t counts[] = {1000}; + for (int i = 0; i < 8; ++i) h.observe_ids(0, ids, counts, 1); + Swap sw{}; + if (h.pick(&sw)) CHECK(sw.demote != pinned_u); +} + +TEST(the_draft_floor_charges_only_the_trunk) { + WeightFootprint wf; + wf.experts = 100; + wf.draft_experts = 30; + wf.expert_unit_max = 5; + wf.expert_spare = 10; + /* With the drafter hosted, the pool's room serves the trunk alone. */ + const int64_t hosted = expert_vram_floor_draft_hosted(wf, 80); + const int64_t plain = expert_vram_floor(wf, 80); + CHECK(hosted < plain); + CHECK(hosted <= wf.experts - wf.draft_experts + wf.expert_spare); + /* No drafter: the two floors agree. */ + wf.draft_experts = 0; + CHECK_EQ(expert_vram_floor_draft_hosted(wf, 80), expert_vram_floor(wf, 80)); +} + RAD_TEST_MAIN() diff --git a/tests/plugin_test.cpp b/tests/plugin_test.cpp index 9abe2e7b..fb2c5b06 100644 --- a/tests/plugin_test.cpp +++ b/tests/plugin_test.cpp @@ -1126,6 +1126,28 @@ TEST(libr4d_resolves_every_band_of_glm_mla_split_by_rows) { } } +/* The dense integer gemm_nt_q kernels compile their group in, so their rows take no other: at + * group 64 each dtype is a miss, at 128 it resolves. At M = 1 every skinny, tiled and prefill row + * of these dtypes is a candidate. */ +TEST(libr4d_resolves_a_dense_integer_gemm_only_at_its_group) { + const std::string so = libr4d(); + if (so.empty()) return; + Registry r; + CHECK(r.load_plugin(so, 0) >= 0); + for (const char* dtype : { "w4a16", "w5a16", "w4a16_asym", "w4a8i8_asym", "w5a8i8", "w2a8", + "w8a16", "w4a8", "w4a8_asym", "w8a8" }) { + Geometry g; + g.set_i("M", 1); + g.set_i("N", 256); + g.set_i("K", 256); + g.set_s("dtype", dtype); + g.set_i("group", 64); + CHECK_EQ(picked(r.select("gemm_nt_q", g, RAD_DOMAIN_DEVICE)), ""); + g.set_i("group", 128); + CHECK(r.select("gemm_nt_q", g, RAD_DOMAIN_DEVICE) != nullptr); + } +} + /* ================================================================== constraints that are not intervals */ namespace { std::string extra_dir() { return home() + "/testkernels/extra"; } diff --git a/tests/quant_ggml_test.cpp b/tests/quant_ggml_test.cpp index 3cd40e9d..2f5cdfbf 100644 --- a/tests/quant_ggml_test.cpp +++ b/tests/quant_ggml_test.cpp @@ -10,6 +10,7 @@ * The error bounds carry margin and catch a wrong plane layout, which decodes to noise. */ #include "quant_fixture.h" +#include "format/ggml_planes.h" #include @@ -134,6 +135,24 @@ TEST(ggml_writes_each_type_as_its_affine_planes) { } } +/* The core cannot call libquant, so a GGUF is read through its own copy of the encodings + * (core/format/ggml_planes.h); this holds every type of the copy to the quantiser's. */ +TEST(the_reader_names_the_planes_the_quantiser_writes) { + NEED_LIBQUANT(); + const RadQuantizerInfo* q = quantizer("ggml"); + REQUIRE(q != nullptr); + for (const ggml_planes::Type& t : ggml_planes::kTypes) { + Opts o; + o.s("type", gguf_dtype(t.ggml)->name); + const RadQuantWeight qw = weight_of("w", 4, 512, nullptr); + RadEncoding written, read; + REQUIRE_EQ(q->encoding(o.data(), o.n(), &qw, &written), RAD_OK); + REQUIRE(ggml_plane_encoding(t.ggml, &read)); + CHECK_EQ(enc_name(read), enc_name(written)); + CHECK(rad_enc_equal(&read, &written)); + } +} + TEST(every_type_decodes_within_its_bound) { NEED_LIBQUANT(); const int64_t C = 1024; diff --git a/tests/relayout_parity_test.cpp b/tests/relayout_parity_test.cpp index af2dd8a6..b5d08d3e 100644 --- a/tests/relayout_parity_test.cpp +++ b/tests/relayout_parity_test.cpp @@ -883,6 +883,52 @@ TEST(a_kernel_refuses_an_encoding_it_does_not_read) { } } +/* The dense integer kernels compile their group in and read no `group` argument, so a hook that + * accepted another one would hand the kernel planes it reads at 128. */ +TEST(a_dense_int_kernel_refuses_a_group_it_does_not_compute) { + NEED_LIBQUANT(); + const int64_t N = 64, K = 256; + const std::vector w = draw(N * K, 28); + auto rtn = [&](const char* codes, const char* zero, bool clamp, int64_t group) { + Opts g; + g.s("codes", codes).i("group", group).s("scale", "f16"); + if (zero) g.s("zero", zero); + if (clamp) g.s("clamp", "sym"); + Quantised q = quantise(quantizer("rtn"), g, "x", N, K, w); + CHECK_EQ(q.status, RAD_OK); + return q; + }; + auto lay = [&](RadLayoutFn f, const char* dtype, int64_t group, const Quantised& q) { + Opts kp; + kp.i("N", N).i("K", K).i("group", group).s("dtype", dtype); + Selection s = select(q, N, K, { "codes" }); + RadLayout L{}; + return f(kp.data(), kp.n(), B, &q.enc, s.sel.data(), s.t.data(), (int)s.t.size(), &L); + }; + const Quantised i4 = rtn("i4", nullptr, false, 64), u5 = rtn("u5", "u8", false, 64); + const Quantised i8 = rtn("i8", nullptr, true, 64), u2 = rtn("u2", "u8", false, 64); + CHECK_EQ(lay(r4d_rad_layout_w4, "w4a8", 64, i4), RAD_E_DTYPE); + CHECK_EQ(lay(r4d_rad_layout_w5, "w5a16", 64, u5), RAD_E_DTYPE); + CHECK_EQ(lay(r4d_rad_layout_w8a16, "w8a16", 64, i8), RAD_E_DTYPE); + CHECK_EQ(lay(r4d_rad_layout_w2a8, "w2a8", 64, u2), RAD_E_DTYPE); + + /* llama.cpp's Q8_0 is this encoding, an f16 scale per 32 i8 codes; the w8 kernels would read + * it at 128. */ + const RadQuantizerInfo* ggml = quantizer("ggml"); + REQUIRE(ggml != nullptr); + Opts o; + o.s("type", "q8_0"); + const Quantised q8 = quantise(ggml, o, "x", N, K, w); + REQUIRE_EQ(q8.status, RAD_OK); + CHECK_EQ(lay(r4d_rad_layout_w8a16, "w8a16", 32, q8), RAD_E_DTYPE); + + const Quantised i4_128 = rtn("i4", nullptr, false, 128), i8_128 = rtn("i8", nullptr, true, 128); + const Quantised u2_128 = rtn("u2", "u8", false, 128); + CHECK_EQ(lay(r4d_rad_layout_w4, "w4a8", 128, i4_128), RAD_OK); + CHECK_EQ(lay(r4d_rad_layout_w8a16, "w8a16", 128, i8_128), RAD_OK); + CHECK_EQ(lay(r4d_rad_layout_w2a8, "w2a8", 128, u2_128), RAD_OK); +} + /* ParoQuant's rotation pairs are stored as they are, and refused at load when a stage is not a * pairing within its own group's 128 columns, which the rotate kernels would index out of bounds. */ TEST(givens_pairs_are_stored_as_they_are_and_checked) { diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 0954976c..8f17f9e3 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -166,6 +166,10 @@ struct Fixture { cfg.max_ctx = max_ctx; cfg.checkpoint_interval = 256; cfg.prefix_cache = true; + /* The tests below were written for the nearest resume rule (a tail snapshot at the last + * quantum boundary, a hit at any snapshot or block); the exact rule's own tests set + * prefix_exact (--prefix-resume exact, the default). */ + cfg.prefix_exact = false; /* Config::n_spec defaults to -1 (`auto`), which engine_bringup resolves; this fixture * skips that, and DraftController::configure refuses a negative depth. Speculation tests * set their own depth. */ @@ -795,6 +799,248 @@ TEST(a_span_needs_an_interval_grid) { CHECK_EQ((int64_t)f.sch.plan().e.size(), 2ll); } +/* ================================================================== exact resume */ +/* --prefix-resume exact (the default): a hit resumes only where an idle server's cold prefill of + * the same prompt starts a chunk, and a prompt's tail snapshot is where its last chunk starts. A + * kernel may round a row differently at another chunk length (spec §17: the split-K count is + * chosen from M), so a hit is bit-identical to a cold run only when it recomputes the cold run's + * own chunks. */ + +/* The chunk ends and checkpoints an idle server plans for an `L`-token prompt from `from`. */ +struct Cut { std::vector ends, ckpts; }; +static Cut cut_from(const Scheduler& s, int64_t from, int64_t L, int64_t budget) { + Cut c; + for (int64_t pos = from; pos < L;) { + int64_t ck = -1; + const int64_t n = s.plan_chunk(pos, L, budget, &ck); + if (n <= 0) break; + pos += n; + c.ends.push_back(pos); + if (ck > 0) c.ckpts.push_back(ck); + } + return c; +} +static std::vector ends_after(const Cut& c, int64_t from) { + std::vector v; + for (int64_t e : c.ends) if (e > from) v.push_back(e); + return v; +} + +/* Which geometry: 0 the GDN hybrid at interval 256 / budget 512 (chunks split at the interval); + * 1 interval 1024 past a 512 budget; 2 a span of 2; 3 a sliding-window model with periodic + * snapshots; 4 the same, tip-only (no interval split); 5 full attention alone (no snapshots). */ +static void exact_fixture(Fixture& f, int kind) { + const bool window = kind == 3 || kind == 4, attn_only = kind == 5; + f.build(4096, 64, 512, 8192, window, !attn_only); + if (window) { + /* As the window tests above: drop the GDN hybrid's linear and conv groups and its scan. */ + f.prog.kv_groups.erase(f.prog.kv_groups.begin() + 1, f.prog.kv_groups.begin() + 3); + f.prog.ops.resize(1); + f.prog.buffers.resize(1); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.pc.groups = { 0 }; + if (kind == 4) f.cfg.checkpoint_policy = "tip-only"; + } + if (kind == 1) f.cfg.checkpoint_interval = 1024; + if (kind == 2) f.cfg.prefill_span = 2; + f.cfg.prefix_exact = true; +} + +TEST(exact_resume_grid_is_the_chunk_an_idle_prefill_cuts) { + struct Want { int kind; int64_t interval, grid, origin; }; + for (const Want w : { Want{ 0, 256, 256, 0 }, Want{ 1, 1024, 512, 0 }, Want{ 2, 256, 512, 256 }, + Want{ 3, 256, 256, 0 }, Want{ 4, 256, 512, 0 }, Want{ 5, 0, 512, 0 } }) { + Fixture f; + exact_fixture(f, w.kind); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); + CHECK(g.exact); + CHECK_EQ(g.checkpoint_interval, w.interval); + CHECK_EQ(g.grid, w.grid); + CHECK_EQ(g.grid_origin, w.origin); + } + /* Nearest, or no prefix cache: no grid, every position its own floor. */ + for (int off = 0; off < 2; ++off) { + Fixture f; + exact_fixture(f, 0); + if (off) f.cfg.prefix_cache = false; else f.cfg.prefix_exact = false; + REQUIRE_EQ(f.start(), RAD_OK); + CHECK(!f.sch.geometry().exact); + CHECK_EQ(f.sch.geometry().grid_floor(300), 300); + } + Fixture f; + exact_fixture(f, 2); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); /* 0, 256, 768, 1280, ... */ + CHECK_EQ(g.grid_floor(255), 0); + CHECK_EQ(g.grid_floor(256), 256); + CHECK_EQ(g.grid_floor(767), 256); + CHECK_EQ(g.grid_floor(1000), 768); + CHECK(!g.on_grid(512)); +} + +/* An interval past the budget that is not a multiple of the budget's chunk would put the chunk + * after every checkpoint off the cold run's grid: exact rounds it up, with a warning that names + * both ways out; nearest keeps it. */ +TEST(exact_rounds_an_interval_off_the_chunk_up_to_a_multiple_of_it) { + for (int exact = 0; exact < 2; ++exact) { + Fixture f; + f.build(); /* quantum 64 */ + f.cfg.checkpoint_interval = 768; /* past the 512 budget, not a multiple of it */ + f.cfg.prefix_exact = exact != 0; + log_set_level(Log::Error); + REQUIRE_EQ(f.start(), RAD_OK); + CHECK_EQ(f.sch.geometry().checkpoint_interval, exact ? 1024 : 768); + if (exact) CHECK_EQ(f.sch.geometry().grid, 512); + } + /* A budget off the quantum chunks at the quantum below it: 500 -> 448, and the interval goes + * to the next multiple of 448. */ + Fixture f; + f.build(4096, 64, /*max_tok=*/500); + f.cfg.checkpoint_interval = 1024; + f.cfg.prefix_exact = true; + log_set_level(Log::Error); + REQUIRE_EQ(f.start(), RAD_OK); + CHECK_EQ(f.sch.geometry().checkpoint_interval, 1344); + CHECK_EQ(f.sch.geometry().grid, 448); + int64_t ck = -1; + CHECK_EQ(f.sch.plan_chunk(0, 5000, 500, &ck), 448); + CHECK_EQ(f.sch.plan_chunk(896, 5000, 500, &ck), 448); + CHECK_EQ(ck, 1344); +} + +/* The tail snapshot is where the prompt's last chunk starts, a boundary an idle chunk already + * ends on: no extra step, and an exact repeat re-prefills that last chunk whole. */ +TEST(an_exact_tail_snapshot_is_where_the_last_chunk_starts) { + Fixture f; + exact_fixture(f, 1); /* interval 1024, chunks of 512 */ + REQUIRE_EQ(f.start(), RAD_OK); + Cut c = cut_from(f.sch, 0, 1800, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1536, 1800 })); + CHECK((c.ckpts == std::vector{ 1024, 1536 })); + /* Its last chunk starting on the interval: that checkpoint is the tail's. */ + c = cut_from(f.sch, 0, 1100, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1100 })); + CHECK((c.ckpts == std::vector{ 1024 })); + /* One ending on the grid: the last chunk is [1536, 2048), and its end is an interval. */ + c = cut_from(f.sch, 0, 2048, 512); + CHECK((c.ckpts == std::vector{ 1024, 1536, 2048 })); + /* Inside the first interval nothing (as before, cheap to prefill again). */ + c = cut_from(f.sch, 0, 900, 512); + CHECK(c.ckpts.empty()); + /* A step sharing its budget may straddle the tail: split there, the snapshot written. */ + int64_t ck = -1; + CHECK_EQ(f.sch.plan_chunk(1400, 1800, 512, &ck), 136); + CHECK_EQ(ck, 1536); + /* A budget short of a quantum boundary past it leaves it for the next chunk. */ + CHECK_EQ(f.sch.plan_chunk(1024, 1800, 100, &ck), 64); + CHECK_EQ(ck, -1); + + /* Nearest cuts the same prompt's last chunk at its last quantum boundary instead. */ + Fixture n; + n.build(); + n.cfg.checkpoint_interval = 1024; + REQUIRE_EQ(n.start(), RAD_OK); + c = cut_from(n.sch, 0, 1800, 512); + CHECK((c.ends == std::vector{ 512, 1024, 1536, 1792, 1800 })); + CHECK((c.ckpts == std::vector{ 1024, 1792 })); +} + +/* The property itself, over every geometry and many prompt lengths: every checkpoint is on the + * grid and is a chunk start of the cold run of the prompt that wrote it and of any longer prompt + * it prefixes (an agent's next turn), and from it the hit cuts exactly the cold run's chunks. */ +TEST(an_exact_hit_from_any_checkpoint_recomputes_the_cold_runs_own_chunks) { + for (int kind = 0; kind < 6; ++kind) { + Fixture f; + exact_fixture(f, kind); + REQUIRE_EQ(f.start(), RAD_OK); + const ChunkGeometry& g = f.sch.geometry(); + int checked = 0; + for (int64_t L = 100; L <= 3000; L += 37) { + const Cut cold = cut_from(f.sch, 0, L, 512); + for (int64_t c : cold.ckpts) { + CHECK(g.on_grid(c)); + if (c >= L) continue; + CHECK(std::find(cold.ends.begin(), cold.ends.end(), c) != cold.ends.end()); + CHECK(cut_from(f.sch, c, L, 512).ends == ends_after(cold, c)); + for (int64_t L2 : { L + 1, L + 300, L + 1500 }) { + const Cut cold2 = cut_from(f.sch, 0, L2, 512); + CHECK(std::find(cold2.ends.begin(), cold2.ends.end(), c) != cold2.ends.end()); + CHECK(cut_from(f.sch, c, L2, 512).ends == ends_after(cold2, c)); + } + ++checked; + } + } + CHECK(kind == 5 ? checked == 0 : checked > 20); + } + /* What nearest gives up: its tail snapshot at a 1000-token prompt's last quantum boundary + * (960) is no chunk start of the 1500-token turn after it, which a cold run cuts at 768 and + * 1024, so a hit there recomputes [960, 1024) as a chunk of its own. */ + Fixture n; + n.build(); + REQUIRE_EQ(n.start(), RAD_OK); + const Cut c1000 = cut_from(n.sch, 0, 1000, 512); + CHECK(std::find(c1000.ckpts.begin(), c1000.ckpts.end(), 960) != c1000.ckpts.end()); + const Cut c1500 = cut_from(n.sch, 0, 1500, 512); + CHECK(std::find(c1500.ends.begin(), c1500.ends.end(), 960) == c1500.ends.end()); + CHECK(std::find(c1500.ends.begin(), c1500.ends.end(), 768) != c1500.ends.end()); + CHECK_EQ(cut_from(n.sch, 960, 1500, 512).ends.front(), 1024); +} + +/* At admission: a hit at a snapshot resumes there (plan_chunk put it on the grid); a hit with no + * snapshot to resume from (full attention alone) steps back to the grid, the blocks above it + * left to the cache and recomputed in the cold run's chunk. */ +TEST(an_exact_hit_steps_back_to_the_grid_and_prefills_the_cold_chunks) { + for (int exact = 0; exact < 2; ++exact) { + Fixture f; + exact_fixture(f, 5); /* chunks of 512, no snapshots */ + f.cfg.prefix_exact = exact != 0; + REQUIRE_EQ(f.start(), RAD_OK); + f.pc.seed(784); /* 49 blocks */ + const uint64_t a = f.submit(1300, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, exact ? 512 : 784); + CHECK_EQ(b->ctx_lens[0], exact ? 512 : 784); + CHECK_EQ(b->n_tok, 512); /* [512, 1024) as the cold run, or [784, 1296) */ + CHECK_EQ((int)f.kv.block_table(a, 0).size(), exact ? 64 : 81); + CHECK_EQ(f.sch.metrics().hit_cut_tokens, exact ? 272 : 0); + } + /* With snapshots the hit is at one: kept as is, restored from its slot. */ + Fixture f; + exact_fixture(f, 1); + REQUIRE_EQ(f.start(), RAD_OK); + f.pc.seed(1600); + f.pc.lin = 1536; /* a tail snapshot, on the 512 grid */ + f.pc.src = 3; + const uint64_t a = f.submit(1800, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 1536); + CHECK_EQ(b->n_tok, 264); /* the cold run's last chunk, whole */ + CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 3); +} + +/* A cold prompt at the scheduler: the last chunk is not split at the end, and an exact repeat's + * hit at the tail snapshot is that chunk. */ +TEST(an_exact_cold_prefill_keeps_its_last_chunk_whole) { + Fixture f; + exact_fixture(f, 0); /* interval 256, chunks of 256 */ + REQUIRE_EQ(f.start(), RAD_OK); + f.submit(1000, 1); + std::vector toks, ckpts; + for (int i = 0; i < 8; ++i) { + const RadBatch* b = f.sch.step(); + if (!b) break; + toks.push_back(b->n_tok); + for (int k = 0; k < b->n_checkpoints; ++k) + ckpts.push_back(b->ctx_lens[0] + b->checkpoint_tok[k] + 1); + f.commit_plain(); + } + CHECK((toks == std::vector{ 256, 256, 256, 232 })); + CHECK((ckpts == std::vector{ 256, 512, 768 })); +} + TEST(a_chunk_ending_on_a_checkpoint_carries_it_into_the_batch) { Fixture f; f.build(); @@ -1117,6 +1363,123 @@ TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) { CHECK_EQ(m.linear_cached_tokens, 0); } +/* The same model with the trunk's window in the checkpoint slot (KVGroupPlan::win_snap beside + * linear state, as DeepSeek-V4.1's sliding layers beside its compressor state): the hit resumes at + * the snapshot, which restores the linear state and the window together, and the cached group's + * blocks are adopted. Before, a model with linear state never put its window in the slot, so this + * clamp refused every hit on it. */ +TEST(a_hit_on_a_hybrid_whose_slot_carries_the_window_resumes_at_the_snapshot) { + Fixture f; + f.build(4096, 64, 512, 4096, /*windowed=*/true); + const int32_t swa = 3; + f.kv.snap = { swa }; + f.pc.groups = { 0 }; + CHECK_OK(f.start()); + f.pc.seed(304); + f.pc.lin = 256; + f.pc.src = 3; + + const uint64_t a = f.submit(300, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 256); + CHECK_EQ(b->ctx_lens[0], 256); + CHECK_EQ(f.sch.plan().e[0].ckpt_restore, 3); + CHECK_EQ(f.kv.block_table(a, 0)[0], f.pc.seeded[0][0]); + const SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.linear_cached_tokens, 256); + CHECK_EQ(m.hit_cut_window, 0); + + /* A hit with no snapshot under it still reuses nothing: the window has nowhere to come from. */ + Fixture g; + g.build(4096, 64, 512, 4096, /*windowed=*/true); + g.kv.snap = { swa }; + g.pc.groups = { 0 }; + CHECK_OK(g.start()); + g.pc.seed(304); + g.pc.lin = 0; + g.pc.src = -1; + const uint64_t c = g.submit(300, 8); + REQUIRE(g.sch.step() != nullptr); + CHECK_EQ(g.sch.find(c)->n_computed, 0); +} + +/* A trunk group the cache does not index and no slot carries is a hole no snapshot fills: a full + * group left out (as a group at another block size was before the cache took every block size) + * refuses the hit even where the window is in the slot. */ +TEST(a_trunk_group_neither_cached_nor_in_the_slot_refuses_the_hit) { + Fixture f; + f.build(4096, 64, 512, 4096, /*windowed=*/true); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 16; + k.layers = { 3 }; + f.prog.kv_groups.push_back(k); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.kv.snap = { 3 }; + f.pc.groups = { 0 }; + CHECK_OK(f.start()); + f.pc.seed(304); + f.pc.lin = 256; + f.pc.src = 3; + const uint64_t a = f.submit(300, 8); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 0); + CHECK_EQ(f.sch.metrics().hit_cut_window, 1); +} + +/* Groups at two block sizes: a hit adopts each group's own blocks (the 8-token group twice as + * many), and the cache's reserve is asked for in entries, from the group furthest short. */ +TEST(a_hit_over_mixed_block_sizes_adopts_each_groups_own_blocks) { + Fixture f; + f.build(4096, 64); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 8; + f.prog.kv_groups.push_back(k); + const int32_t fine = 3; + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 4096, 64); + f.pc.groups = { 0, fine }; + CHECK_OK(f.start()); + CHECK_EQ(f.sch.geometry().quantum % 16, 0ll); + f.pc.seed(304); /* 19 blocks of 16, 38 of 8 */ + f.pc.lin = 256; + f.pc.src = 3; + const uint64_t a = f.submit(1000, 8); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.sch.find(a)->n_computed, 256); + const std::vector t0 = f.kv.block_table(a, 0), t1 = f.kv.block_table(a, fine); + CHECK_EQ((int)t0.size(), 32); /* 16 adopted + 16 for the 256-token chunk */ + CHECK_EQ((int)t1.size(), 64); /* 32 adopted + 32 */ + for (int i = 0; i < 16; ++i) CHECK_EQ(t0[(size_t)i], f.pc.seeded[0][(size_t)i]); + for (int i = 0; i < 32; ++i) CHECK_EQ(t1[(size_t)i], f.pc.seeded[1][(size_t)i]); +} + +TEST(the_cache_trim_over_mixed_block_sizes_asks_for_entries) { + Fixture f; + f.build(/*blocks=*/64, /*states=*/64); + KVGroupInfo k; + k.name = "fine"; + k.decl.kind = RAD_KV_FULL; + k.block_size = 8; + f.prog.kv_groups.push_back(k); + f.kv.setup(f.prog.kv_groups, f.cfg.max_ctx, 64, 64); + f.pc.groups = { 0, 3 }; + CHECK_OK(f.start()); + f.pc.evict_grant = 1 << 20; + f.submit(160, /*max_tokens=*/1); /* 10 + 20 blocks, finishes on the first commit */ + f.submit(176, /*max_tokens=*/64); /* 11 + 22 each, still running after it */ + f.submit(176, /*max_tokens=*/64); + REQUIRE(f.sch.step() != nullptr); + CHECK_EQ(f.kv.held_blocks(0), 32ll); /* 32 free against a reserve of 16 */ + CHECK_EQ(f.kv.held_blocks(3), 64ll); /* none free against 16: 8 entries of 2 */ + f.commit_plain(); + REQUIRE(f.pc.trims.size() == 1u); + CHECK_EQ(f.pc.trims[0], 8ll); +} + /* A request whose media is not encoded yet waits, and only it does: it is not admitted without * its rows, and the request behind it is asked and runs. Once its items are encoded it is * admitted where it stood. */ diff --git a/tests/text_test.cpp b/tests/text_test.cpp index ebbda93d..618f5897 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -21,6 +21,8 @@ */ #include "rad_test.h" +#include + #include "text/gguf.h" #include "text/tokenizer.h" #include "text/tokenizer_nfc.h" @@ -2240,4 +2242,29 @@ TEST(the_normal_forms_agree_with_an_independent_implementation) { CHECK(rows > 2500); } +/* A release that ships no chat template (DeepSeek's) is why --chat-template exists: the file is + * read, trailing newlines stripped exactly as the checkpoint's own file is, and an unreadable or + * empty file is refused rather than skipped. */ +TEST(read_chat_template_path_strips_newlines_and_refuses_empty) { + VocabBuild vb; + const std::string p = radtest::tmp_path("chat_template.jinja"); + { + std::ofstream f(p); + f << "{%- raw %}{{ messages }}{%- endraw %}\n\n"; + } + CHECK_OK(read_chat_template_path(p.c_str(), vb)); + CHECK_EQ(vb.chat_template, std::string("{%- raw %}{{ messages }}{%- endraw %}")); + + vb.chat_template.clear(); + { + std::ofstream f(p); + f << "\n\r\n"; + } + CHECK_EQ(read_chat_template_path(p.c_str(), vb), (int)RAD_E_IO); + CHECK(vb.chat_template.empty()); + + CHECK_EQ(read_chat_template_path(radtest::tmp_path("absent.jinja").c_str(), vb), (int)RAD_E_IO); + std::remove(p.c_str()); +} + RAD_TEST_MAIN() diff --git a/tests/video_gen_test.cpp b/tests/video_gen_test.cpp index bc49c4e8..7464572f 100644 --- a/tests/video_gen_test.cpp +++ b/tests/video_gen_test.cpp @@ -1080,8 +1080,7 @@ TEST(a_keyframe_pair_is_encoded_and_pins_both_ends) { CHECK(stepped); } -/* References ride a latent upscale, laid out again at the small size for the steps before it; a - * keyframe, pinned on the video's own grid, does not. */ +/* References ride a latent upscale, laid out again at the small size for the steps before it. */ TEST(references_are_laid_out_again_at_an_upscales_small_size) { VideoFixture f; f.build(); @@ -1120,6 +1119,53 @@ TEST(references_are_laid_out_again_at_an_upscales_small_size) { CHECK_OK(f.drv.done()); } CHECK_EQ(kinds, std::string("ECSSUSAD")); +} + +/* A keyframe rides a latent upscale pinned on the grid the steps run on: encoded at the small size + * before the prompt, and again at the full size, into the same slot, between the upscale and the + * first full-size step. Without its small picture the request is refused. */ +TEST(a_keyframe_is_encoded_again_at_the_full_size_after_an_upscale) { + VideoFixture f; + f.build(); + f.prog.video_gen.upscale_max = 4.0; + f.prog.video_gen.upscale_refine = 1; + with_tower(f, 16); + CHECK_OK(f.start_refs()); + std::string why; + auto r = f.req(1, 4); + r->width = 64; + r->height = 64; + r->upscale = 2.0; + gen::VideoRefMedia kf = picture(gen::VideoRefMedia::FIRST_FRAME, "first_frame", 1, 64, 64); + kf.small_w = 32; + kf.small_h = 32; + kf.small_pixels.assign((size_t)32 * 32 * 3, 2.0f); + r->refs.push_back(kf); + const int64_t T = (int64_t)r->tokens.size(); + CHECK_OK(f.drv.submit(std::move(r), &why)); + + /* The prompt, a keyframe's 2 rows and 60 soundtrack rows, then a video of 2 rows small, 8 full. */ + std::string kinds; + int steps = 0, encodes = 0; + for (int i = 0; i < 20; ++i) { + const RadBatch* b = f.drv.next(i); + if (!b) break; + const RadVideoGenBatch* V = b->vgen_b; + kinds += b->gen == RAD_GEN_PASS_VENCODE ? 'E' : kind_of(b->gen); + if (b->gen == RAD_GEN_PASS_VENCODE) { + const int32_t side = encodes++ == 0 ? 32 : 64; + CHECK_EQ(V->enc_kind, (int32_t)RAD_ENC_KEYFRAME); + CHECK_EQ(V->enc_slot, 1); + CHECK_EQ(V->enc_height, side); + CHECK_EQ(V->enc_width, side); + } else if (b->gen == RAD_GEN_PASS_VSTEP) { + CHECK_EQ(b->n_tok, T + 2 + 60 + (steps++ < 2 ? 2 : 8)); + CHECK_EQ(V->ref_tab[1], 1); + } + f.answer(10 * i); + CHECK_OK(f.drv.done()); + } + CHECK_EQ(kinds, std::string("ECSSUESAD")); VideoFixture g; g.build(); @@ -1132,7 +1178,7 @@ TEST(references_are_laid_out_again_at_an_upscales_small_size) { r->upscale = 2.0; r->refs.push_back(picture(gen::VideoRefMedia::FIRST_FRAME, "first_frame", 1, 64, 64)); CHECK_EQ(g.drv.submit(std::move(r), &why), (int)RAD_E_INVAL); - CHECK(has(why, "latent_upscale")); + CHECK(has(why, "small size")); } /* A reference video with its soundtrack and a standalone soundtrack: one encode pass each, the diff --git a/tests/videos_test.cpp b/tests/videos_test.cpp index 107a4386..4420553a 100644 --- a/tests/videos_test.cpp +++ b/tests/videos_test.cpp @@ -680,6 +680,49 @@ TEST(fl2va_keyframes_feed_the_tower_and_pin_the_output_ends) { CHECK(g.tokens == want); } +/* With a latent upscale each keyframe is prepared twice, the same way: at the canvas and at the + * small size the first steps pin it at. The tower still sees the canvas frame only. */ +TEST(fl2va_keyframes_are_prepared_at_an_upscales_small_size_too) { + FakeMultimodal mm; + mm.expand = { 900, 901 }; + mm.enc_frames = 5; mm.enc_side = 16; mm.enc_n = 850; + FakeVideoGen gen; + std::unique_ptr f(new Fixture(Fixture::Tweak{ [&](ServerOptions& o, Deps& d) { + d.videos = &gen; + d.mm = &mm; + o.video_model = true; + gen.inf.enc_ratio = 16; + gen.inf.max_enc_side = 512; + gen.inf.upscale_max = 4.0; + } })); + HttpRequest q; + q.method = "POST"; + q.path = "/v1/videos"; + q.form = { FormPart{ "prompt", "", "", "fox" }, + FormPart{ "size", "", "", "512x256" }, + FormPart{ "task", "", "", "fl2va" }, + FormPart{ "latent_upscale", "", "", "2" }, + FormPart{ "first_frame", "f.png", "image/png", "PF" }, + FormPart{ "last_frame", "l.png", "image/png", "PL" } }; + HttpResponse r = f->srv->router().dispatch(q); + REQUIRE_EQ(r.status, 200); + CHECK_EQ(mm.n_pframe, 2); + REQUIRE_EQ(mm.cenc_covers.size(), (size_t)4); + CHECK(!mm.cenc_covers[0]); /* first frame: stretched at both sizes */ + CHECK(!mm.cenc_covers[1]); + CHECK(mm.cenc_covers[2]); /* last frame: centre-cropped at both sizes */ + CHECK(mm.cenc_covers[3]); + const gen::VideoRequest& g = gen.last(); + REQUIRE_EQ(g.refs.size(), (size_t)2); + for (const gen::VideoRefMedia& m : g.refs) { + CHECK_EQ(m.enc_w, 512); + CHECK_EQ(m.enc_h, 256); + CHECK_EQ(m.small_w, 256); + CHECK_EQ(m.small_h, 128); + CHECK_EQ(m.small_pixels.size(), (size_t)256 * 128 * 3); + } +} + /* A last frame alone is : the number counts the pictures present, as ComfyUI's does. * fl2va (both ends) keeps first = 1, last = 2. */ TEST(l2va_presents_its_sole_frame_as_picture_1) { diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index 3eeb31cf..bd857f8d 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -205,6 +205,10 @@ void usage() { " --imatrix F llama.cpp imatrix: the expert-popularity profile, the column\n" " importances handed to each quantiser, and the weighting of the\n" " error report\n" + " --chat-template F a jinja template baked as the container's chat template,\n" + " overriding the checkpoint's own (or its absence). A release that\n" + " ships none (DeepSeek's) needs one, or /v1/chat/completions answers\n" + " 501. Trailing newlines are stripped\n" " --set K=V a metadata key, seen by declare AND written into the container,\n" " so a convert-time choice that must also hold at serve time is\n" " stated once. Repeatable\n" @@ -274,7 +278,7 @@ int for_row_pieces(int64_t n, bool parallel, std::string* why, F fn) { } /* namespace */ int main(int argc, char** argv) { - std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir; + std::string in, out, arch_override, home = rad_home(), tokjson, imat_path, draft_dir, chat_tmpl; std::string tokjson2, config_dir; std::vector add_files; std::vector hierarchy = rad_hierarchy_from_env(); @@ -318,6 +322,7 @@ int main(int argc, char** argv) { else if (a == "--add") add_files.push_back(next("--add")); else if (a == "--config") config_dir = next("--config"); else if (a == "--imatrix") imat_path = next("--imatrix"); + else if (a == "--chat-template") chat_tmpl = next("--chat-template"); else if (a == "--set") { const std::string kv = next("--set"); const size_t eq = kv.find('='); @@ -665,8 +670,10 @@ int main(int argc, char** argv) { const RadQuantWeight qw = quant_weight(L, nullptr); const int st = L.rule->q->encoding(L.rule->params.data(), (int)L.rule->params.size(), &qw, &L.enc); - if (st == RAD_E_UNSUPPORTED && (L.src.trivial || L.src.imported)) { - /* declined (e.g. a norm under a matrix pattern): keep as is */ + if (st == RAD_E_UNSUPPORTED && + (L.src.trivial || (L.src.imported && !L.src.ggml_blocks))) { + /* declined (e.g. a norm under a matrix pattern): keep as is. Not a GGUF block + * tensor: keeping its planes would hide that the rule did not apply. */ L.rule = nullptr; L.enc = L.src.enc; } else if (st != RAD_OK) { @@ -1041,6 +1048,12 @@ int main(int argc, char** argv) { w.abort(); return 1; } + /* The operator's template replaces whatever the checkpoint carried (or lacked), so a release + * that ships none still bakes a container that serves /v1/chat/completions. */ + if (!chat_tmpl.empty() && read_chat_template_path(chat_tmpl.c_str(), vb) < 0) { + w.abort(); + return 1; + } /* Serialised at section offset 0; finish() rebases once the string blob is sized. */ std::vector vocab_blob; if (vocab_serialize(vb, sink, 0, vocab_blob) < 0) { w.abort(); return 1; } diff --git a/tools/rad_kbench.cpp b/tools/rad_kbench.cpp index 0b5d154c..5b47d678 100644 --- a/tools/rad_kbench.cpp +++ b/tools/rad_kbench.cpp @@ -358,12 +358,25 @@ int write_report(const std::string& path, const std::vector& rows, std::string s; s += "# radiance kernel libraries\n\n"; - s += "Generated by `rad-kbench`. Every kernel of every loaded library ran on the same " - "inputs" + (benched ? std::string(" and each\ncase that passed was timed in the same " - "run, so correctness, completeness and speed come from " - "one run\n(the Speed section says how the times were " - "taken).\n\n") - : std::string(";\nnothing was timed (`--bench` was not given).\n\n")); + /* The header may claim only what this pass measured. The counts are the same ones the + * Rows nothing ran section prints from this data below; the sentence claiming every + * kernel ran is true only when no declared row was left unreached. */ + size_t declared_rows = 0, reached_rows = 0; + for (const LibRow& l : libs) { declared_rows += l.rows.size(); reached_rows += l.ran.size(); } + const bool all_ran = reached_rows == declared_rows; + s += "Generated by `rad-kbench`. " + + (all_ran + ? std::string("Every kernel of every loaded library ran on the same inputs") + : fmt("%zu of %zu declared kernel rows ran on the same inputs", reached_rows, + declared_rows)) + + (benched ? std::string(" and each\ncase that passed was timed in the same " + "run, so correctness, completeness and speed come from " + "one run\n(the Speed section says how the times were " + "taken).\n\n") + : std::string(";\nnothing was timed (`--bench` was not given).\n\n")); + if (!all_ran) + s += "Rows no case in this pass reached are listed under *Rows nothing ran*; a row " + "there is a gap in\ncoverage, not a failing kernel.\n\n"; s += "- " + provenance + "\n"; if (!arch_plugin.empty()) s += "- architecture plugin: `" + arch_plugin + "`\n"; s += "- libraries: `" + libraries + "`\n";