tests: the emulator fixtures, the mem/ref suites and the kv_resolve self-test

This commit is contained in:
C_Tamas committed 2026-10-24 19:19:19 +07:00
1 parent c2219fccb0
commit 5b415b2ef8
7 files changed
+2678 -11

No files matched your search

+713
View File
@@ -20520,6 +20520,351 @@ static void sample_argmax_case(const Plugin& pl) {
" agree=" + (agree ? "1" : "0"));
}
/* kv_resolve, on the card, against libref's serial oracle (libref/ref_kvstream.cpp).
*
* Each call is applied twice from the same pre-call bytes: once by libref on host tensors, once by
* this kernel on device tensors. All eight operands are then compared byte for byte -- both maps,
* the selection, ctl (epoch, hand, placed, overflow and the u64 counters) and the copied blocks --
* so a different victim, a stale epoch, an invented slot, a missed copy or a drifted counter all
* fail. The cases are the ones tests/ref_test.cpp pins: all-hit, misses placed in ascending block
* id, an unreferenced victim, a second chance, and the overflow latch; the last one also repeats
* three calls so the epoch, the hand and the heat counters are checked across launches.
*
* The state faults libref refuses before writing cannot return a host status from a device launch,
* so the kernel guards them; those checks are asserted here separately and are not byte-compared.
*/
static void kv_resolve_case(const Plugin& pl) {
const char* what = "kv_resolve vs libref: hits, misses, CLOCK, second chance, overflow";
const RadKernelInfo* r = find(pl, "kv_resolve_i32");
if (!r) { ok(what, false, "row absent"); return; }
if (!g_plugin) { ok(what, false, "plugin path absent"); return; }
std::string rpath(g_plugin);
rpath = rpath.substr(0, rpath.find_last_of('/') + 1) + "libref.so";
void* ref = dlopen(rpath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!ref) { ok(what, false, "reference plugin unavailable"); return; }
auto rcount = (int (*)(void))dlsym(ref, "rad_kernel_count");
auto rat = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at");
const RadKernelInfo* oracle = nullptr;
if (rcount && rat)
for (int i = 0; i < rcount(); ++i)
if (std::strcmp(rat(i)->op, "kv_resolve") == 0) { oracle = rat(i); break; }
if (!oracle) { ok(what, false, "reference operation unavailable"); dlclose(ref); return; }
struct State {
int64_t M, blocks, slots, pitch, bbytes;
std::vector<int32_t> sel, nsel, res, sblk, sst, ctl;
std::vector<uint8_t> host, pool;
};
auto seed = [](State& c, int64_t M, int64_t blocks, int64_t slots, int64_t pitch,
int64_t bbytes) {
c.M = M; c.blocks = blocks; c.slots = slots; c.pitch = pitch; c.bbytes = bbytes;
c.sel.assign((size_t)(M * pitch), -1);
c.nsel.assign((size_t)M, 0);
c.res.assign((size_t)blocks, -1);
c.sblk.assign((size_t)slots, -1);
c.sst.assign((size_t)(slots * 2), 0);
c.ctl.assign(16, 0);
c.host.assign((size_t)(blocks * bbytes), 0);
c.pool.assign((size_t)(slots * bbytes), (uint8_t)0xEE);
for (int64_t b = 0; b < blocks; ++b)
for (int64_t i = 0; i < bbytes; ++i)
c.host[(size_t)(b * bbytes + i)] = (uint8_t)(10 * b + i);
};
auto put = [](State& c, int64_t s, int64_t b) {
for (int64_t i = 0; i < c.bbytes; ++i)
c.pool[(size_t)(s * c.bbytes + i)] = (uint8_t)(10 * b + i);
};
/* Both runs start from `c.sel`/`c.nsel` of each step; `c` keeps the state across steps.
*
* `band` is what the geometry's RANGED `M` parameter holds, which is the band's ceiling, not
* this call's rows: the device must read its row count from `sel`'s extent while libref is
* handed the call's real width. `band < 0` means the two agree. `want_kernel` lets a case
* assert the device's refusal (a launch above the band) while libref, which has no band,
* still accepts. */
auto run = [&](const char* label, State& c,
const std::vector<std::vector<int32_t>>& sels,
const std::vector<std::vector<int32_t>>& nsels,
int64_t band = -1, int want_kernel = RAD_OK) {
std::vector<void*> d(8, nullptr);
const size_t bytes[8] = { (size_t)(c.M * c.pitch) * 4, (size_t)c.M * 4,
(size_t)c.blocks * 4, (size_t)c.slots * 4,
(size_t)(c.slots * 2) * 4, (size_t)16 * 4,
(size_t)(c.blocks * c.bbytes), (size_t)(c.slots * c.bbytes) };
for (int i = 0; i < 8; ++i) {
d[(size_t)i] = dalloc(bytes[i]);
if (!d[(size_t)i]) { ok(label, false, "allocation failed"); return; }
}
const std::vector<std::vector<int64_t>> shapes = {
{ c.M, c.pitch }, { c.M }, { c.blocks }, { c.slots }, { c.slots, 2 }, { 16 },
{ c.blocks, c.bbytes }, { c.slots, c.bbytes } };
const uint32_t dts[8] = { RAD_I32, RAD_I32, RAD_I32, RAD_I32, RAD_I32, RAD_I32,
RAD_U8, RAD_U8 };
/* libref reads the counters as u64 from ctl+4 and refuses a ctl that is not 8-byte
* aligned, which a vector<int32_t> is not guaranteed to be. */
alignas(8) int32_t ctl_host[16] = {};
std::vector<RadTensor> th, td;
for (int i = 0; i < 8; ++i) {
void* hp = i == 0 ? (void*)c.sel.data() : i == 1 ? (void*)c.nsel.data()
: i == 2 ? (void*)c.res.data() : i == 3 ? (void*)c.sblk.data()
: i == 4 ? (void*)c.sst.data() : i == 5 ? (void*)ctl_host
: i == 6 ? (void*)c.host.data() : (void*)c.pool.data();
th.push_back(T(hp, dts[i], shapes[(size_t)i]));
td.push_back(T(d[(size_t)i], dts[i], shapes[(size_t)i]));
}
std::vector<RadParam> ps = { PI("M", c.M), PI("blocks", c.blocks), PI("slots", c.slots),
PI("sel_pitch", c.pitch), PI("block_bytes", c.bbytes) };
std::vector<RadParam> pd = ps;
if (band > 0) pd[0] = PI("M", band);
RadArgs ah{}, ad{};
ah.t = th.data(); ah.n_t = 8; ah.p = ps.data(); ah.n_p = 5; ah.world_size = 1;
ad.t = td.data(); ad.n_t = 8; ad.p = pd.data(); ad.n_p = 5; ad.world_size = 1;
const int64_t need = r->scratch ? r->scratch(&ad) : 0;
if (need < 0) { ok(label, false, "scratch hook refused"); return; }
ad.scratch_bytes = need;
if (need > 0) ad.scratch = dalloc((size_t)need);
bool pass = true;
std::string why;
for (size_t k = 0; k < sels.size() && pass; ++k) {
std::copy(sels[k].begin(), sels[k].end(), c.sel.begin());
std::copy(nsels[k].begin(), nsels[k].end(), c.nsel.begin());
std::memcpy(ctl_host, c.ctl.data(), sizeof ctl_host);
const void* const hp[8] = { c.sel.data(), c.nsel.data(), c.res.data(),
c.sblk.data(), c.sst.data(), ctl_host, c.host.data(),
c.pool.data() };
for (int i = 0; i < 8; ++i)
st_memcpy(d[(size_t)i], hp[i], bytes[i], hipMemcpyHostToDevice);
const int rr = oracle->launch(&ah, nullptr);
std::memcpy(c.ctl.data(), ctl_host, sizeof ctl_host);
const int rc = r->launch(&ad, nullptr);
st_stream_sync(nullptr);
if (rr != RAD_OK || rc != want_kernel) {
pass = false;
why = fmt("call %zu: libref rc=%d kernel rc=%d (wanted %d)", k, rr, rc,
want_kernel);
break;
}
/* A refusal case has nothing to compare: the device wrote nothing. */
if (want_kernel != RAD_OK) break;
for (int i = 0; i < 8 && pass; ++i) {
std::vector<uint8_t> got(bytes[i]);
st_memcpy(got.data(), d[(size_t)i], bytes[i], hipMemcpyDeviceToHost);
for (size_t j = 0; j < bytes[i]; ++j)
if (got[j] != ((const uint8_t*)hp[i])[j]) {
pass = false;
why = fmt("call %zu operand %d byte %zu: kernel %u, libref %u", k, i, j,
(unsigned)got[j], (unsigned)((const uint8_t*)hp[i])[j]);
break;
}
}
}
ok(label, pass, why);
};
/* All hits: the epoch reaches every slot, every counter goes to 1, nothing is copied. */
{
State c; seed(c, 2, 8, 4, 4, 8);
c.res = { 0, 1, 2, 3, -1, -1, -1, -1 };
c.sblk = { 0, 1, 2, 3 };
for (int64_t s = 0; s < 4; ++s) put(c, s, s);
run("kv_resolve all-hit", c, { { 0, 1, 2, 3, 0, 2, -1, -1 } }, { { 4, 2 } });
}
/* ref_test's first case: hits, then two misses placed in ascending block id, not row order. */
{
State c; seed(c, 2, 8, 4, 4, 8);
put(c, 0, 2); put(c, 3, 5);
c.res = { -1, -1, 0, -1, -1, 3, -1, -1 };
c.sblk = { 2, -1, -1, 5 };
c.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
run("kv_resolve misses in ascending block order", c,
{ { 2, 5, 6, -1, 2, 4, -1, -1 } }, { { 3, 2 } });
}
/* ref_test's eviction: slot 1's block is unreferenced, so the hand takes it and unmaps block 2. */
{
State c; seed(c, 1, 8, 4, 1, 4);
for (int64_t s = 0; s < 4; ++s) put(c, s, s + 1);
c.res = { -1, 0, 1, 2, 3, -1, -1, -1 };
c.sblk = { 1, 2, 3, 4 };
c.sst = { 0, 1, 0, 0, 0, 1, 0, 0 };
c.ctl[1] = 1;
run("kv_resolve evicts an unreferenced slot", c, { { 0 } }, { { 1 } });
}
/* ref_test's free-first policy: slot 0 holds an unreferenced block and the hand starts on it,
* so the CLOCK sweep would evict it -- a free slot must be claimed instead, and block 3 must
* stay resident and mapped. */
{
State c; seed(c, 1, 8, 4, 1, 4);
put(c, 0, 3);
c.res = { -1, -1, -1, 0, -1, -1, -1, -1 };
c.sblk = { 3, -1, -1, -1 };
run("kv_resolve free slot before a live one", c, { { 0 } }, { { 1 } });
}
/* ref_test's second chance: every counter is 1, so the hand halves all four and comes back. */
{
State c; seed(c, 1, 8, 4, 2, 4);
for (int64_t s = 0; s < 4; ++s) put(c, s, s + 4);
c.res = { -1, -1, -1, -1, 0, 1, 2, 3 };
c.sblk = { 4, 5, 6, 7 };
c.sst = { 0, 1, 0, 1, 0, 1, 0, 1 };
run("kv_resolve second chance", c, { { 0, 1 } }, { { 2 } });
}
/* ref_test's overflow: three hits hold slots 0..2, one slot is free and two misses want it. The
* second must not take the slot the first just filled; ctl[3] latches and block 7 stays in sel. */
{
State c; seed(c, 1, 8, 4, 5, 4);
for (int64_t s = 0; s < 3; ++s) put(c, s, s);
c.res = { 0, 1, 2, -1, -1, -1, -1, -1 };
c.sblk = { 0, 1, 2, -1 };
c.sst = { 0, 1, 0, 1, 0, 1, 0, 0 };
c.ctl[1] = 3;
run("kv_resolve overflow latches", c, { { 6, 7, 0, 1, 2 } }, { { 5 } });
}
/* ref_test's heat case: slot 0 was hit twice (counter 2) and slots 1 and 2 once each. A one-bit
* CLOCK would evict slot 0 on the second pass; the counter halves 2 -> 1 -> 0, so slot 0 stays
* resident and slot 1 is the victim. Same state, a different victim, so this is the case that
* says the kernel runs the counter and not a bit. */
{
State c; seed(c, 1, 32, 3, 1, 8);
for (int64_t s = 0; s < 3; ++s) put(c, s, 10 + s);
c.res.assign(32, -1); c.res[10] = 0; c.res[11] = 1; c.res[12] = 2;
c.sblk = { 10, 11, 12 };
c.sst = { 0, 2, 0, 1, 0, 1 };
run("kv_resolve heat: a slot hit twice survives two passes", c, { { 20 } }, { { 1 } });
}
/* The claim list's depth, above the fixed 2048 ids it used to sort: four rows of 513 -- what
* `--max-num-seqs 4` selects -- claim 2052 distinct blocks, all with every slot free, so block
* `first + k` lands in slot k. A device launch derives the list's size from its own operands
* (libr4d/r4d_kv_resolve.hip, kv_claim_cap), and this case is the one that says so: with a
* constant 2048 the launch above it took the map walk and ctl[12] still had to read 2052. */
{
State c; seed(c, 4, 4096, 2100, 513, 8);
std::vector<int32_t> sel((size_t)(4 * 513)), nsel((size_t)4, 513);
for (int64_t q = 0; q < 4; ++q)
for (int64_t i = 0; i < 513; ++i) sel[(size_t)(q * 513 + i)] = (int32_t)(100 + q * 513 + i);
run("kv_resolve 2052 claims", c, { sel }, { nsel });
}
/* Three calls in a row: the epoch, the hand and the heat counters carry, and a call evicts
* only after halving every warm slot it passes. */
{
State c; seed(c, 2, 16, 6, 4, 16);
run("kv_resolve across calls", c,
{ { 0, 1, 2, -1, 3, 4, -1, -1 },
{ 5, 6, 7, -1, 1, 8, -1, -1 },
{ 0, 2, 4, -1, 5, 6, -1, -1 } },
{ { 3, 2 }, { 3, 2 }, { 3, 2 } });
}
/* The deployment's own block: 2 KiB across 32 lanes is 128 vectors, one full four-wide group per
* thread with nothing left over, and 2064 bytes is that group plus one vector of tail. Both are
* the copy phase 6 exists for -- four loads in flight -- and both are compared against libref's
* memcpy byte for byte, including the slot's last byte. */
for (int64_t bb : { 2048, 2064 }) {
State c; seed(c, 2, 8, 4, 4, bb);
put(c, 0, 0); put(c, 3, 3);
c.res = { 0, -1, -1, 3, -1, -1, -1, -1 };
c.sblk = { 0, -1, -1, 3 };
const std::string name =
fmt("kv_resolve copies a whole block byte for byte (%lld bytes)", (long long)bb);
run(name.c_str(), c, { { 0, 3, 1, 2 } }, { { 4 } });
}
/* The launch widths the geometry's band hid: `M` arrives as the band ceiling (2048) while the
* selection's own extent is one row, a 625-token prefill, or the whole band. The row count and
* pitch must come from `sel`, and the result must be byte-identical to libref at that width. */
{
State c; seed(c, 1, 8, 4, 2, 4);
put(c, 0, 2);
c.res = { -1, -1, 0, -1, -1, -1, -1, -1 };
c.sblk = { 2, -1, -1, -1 };
run("kv_resolve at one query row (band 2048)", c, { { 2, 5 } }, { { 2 } }, 2048);
}
{
const int64_t M = 625, pitch = 4;
State c; seed(c, M, 8, 4, pitch, 8);
put(c, 0, 2); put(c, 1, 5);
c.res = { -1, -1, 0, -1, -1, 1, -1, -1 };
c.sblk = { 2, 5, -1, -1 };
std::vector<int32_t> sel((size_t)(M * pitch), -1), ns((size_t)M, 2);
for (int64_t q = 0; q < M; ++q) {
sel[(size_t)(q * pitch)] = 2;
sel[(size_t)(q * pitch + 1)] = 5;
}
run("kv_resolve at 625 query rows (band 2048)", c, { sel }, { ns }, 2048);
}
{
const int64_t M = 2048, pitch = 4;
State c; seed(c, M, 8, 4, pitch, 8);
put(c, 0, 2); put(c, 1, 5);
c.res = { -1, -1, 0, -1, -1, 1, -1, -1 };
c.sblk = { 2, 5, -1, -1 };
std::vector<int32_t> sel((size_t)(M * pitch), -1), ns((size_t)M, 2);
for (int64_t q = 0; q < M; ++q) {
sel[(size_t)(q * pitch)] = 2;
sel[(size_t)(q * pitch + 1)] = 5;
}
run("kv_resolve at the band bound (2048 rows)", c, { sel }, { ns }, 2048);
}
/* The ceiling still refuses: five operand rows against a four-row band is a caller bug. */
{
State c; seed(c, 5, 8, 4, 2, 4);
c.res = { -1, -1, -1, -1, -1, -1, -1, -1 };
c.sblk = { -1, -1, -1, -1 };
run("kv_resolve refuses a launch wider than its band", c, { { 0, 1 } }, { { 2 } }, 4,
RAD_E_SHAPE);
}
/* The state faults, guarded on device. A pitch that disagrees with sel_pitch is refused; a row
* that asks for more entries than it holds is clamped to its own row, and an out-of-range block
* id is left in sel and in the map. */
{
State c; seed(c, 2, 8, 4, 2, 4);
void* d[8];
const size_t bytes[8] = { (size_t)(c.M * c.pitch) * 4, (size_t)c.M * 4,
(size_t)c.blocks * 4, (size_t)c.slots * 4,
(size_t)(c.slots * 2) * 4, (size_t)16 * 4,
(size_t)(c.blocks * c.bbytes), (size_t)(c.slots * c.bbytes) };
const void* const hp[8] = { c.sel.data(), c.nsel.data(), c.res.data(), c.sblk.data(),
c.sst.data(), c.ctl.data(), c.host.data(), c.pool.data() };
for (int i = 0; i < 8; ++i) d[i] = dalloc(bytes[i]);
std::vector<RadTensor> ts = {
T(d[0], RAD_I32, { c.M, c.pitch }), T(d[1], RAD_I32, { c.M }),
T(d[2], RAD_I32, { c.blocks }), T(d[3], RAD_I32, { c.slots }),
T(d[4], RAD_I32, { c.slots, 2 }), T(d[5], RAD_I32, { 16 }),
T(d[6], RAD_U8, { c.blocks, c.bbytes }), T(d[7], RAD_U8, { c.slots, c.bbytes }) };
std::vector<RadParam> ps = { PI("M", c.M), PI("blocks", c.blocks), PI("slots", c.slots),
PI("sel_pitch", c.pitch), PI("block_bytes", c.bbytes) };
RadArgs a{};
a.t = ts.data(); a.n_t = 8; a.p = ps.data(); a.n_p = 5; a.world_size = 1;
const int64_t need = r->scratch(&a);
a.scratch = dalloc((size_t)need); a.scratch_bytes = need;
for (int i = 0; i < 8; ++i) st_memcpy(d[i], hp[i], bytes[i], hipMemcpyHostToDevice);
ts[0].stride[0] = c.pitch + 1;
ok("kv_resolve refuses a sel row pitch that is not sel_pitch",
r->launch(&a, nullptr) == RAD_E_STRIDE);
ts[0].stride[0] = c.pitch;
/* Row 0 asks for five entries of a two-wide row; row 1 must keep its sentinels. */
const int32_t sel[4] = { 1, 1, 77, 77 };
const int32_t ns[2] = { 5, 0 };
st_memcpy(d[0], sel, sizeof sel, hipMemcpyHostToDevice);
st_memcpy(d[1], ns, sizeof ns, hipMemcpyHostToDevice);
const int rc = r->launch(&a, nullptr);
int32_t got[4] = {};
st_memcpy(got, d[0], sizeof got, hipMemcpyDeviceToHost);
ok("kv_resolve clamps nsel to its own row", rc == RAD_OK && got[2] == 77 && got[3] == 77,
fmt("rc=%d row1=%d,%d", rc, got[2], got[3]));
/* A block id outside the map is left alone rather than turned into a slot. */
const int32_t bad[4] = { 99, -1, 77, 77 };
const int32_t nb[2] = { 1, 0 };
st_memcpy(d[0], bad, sizeof bad, hipMemcpyHostToDevice);
st_memcpy(d[1], nb, sizeof nb, hipMemcpyHostToDevice);
const int rc2 = r->launch(&a, nullptr);
st_memcpy(got, d[0], sizeof got, hipMemcpyDeviceToHost);
ok("kv_resolve leaves an out-of-range block id alone", rc2 == RAD_OK && got[0] == 99,
fmt("rc=%d sel0=%d", rc2, got[0]));
}
dlclose(ref);
}
/* sample_ngram_ban, against a host port of the reference processor.
*
* The oracle is modeling_unlimitedocr.py:353-383's SlidingWindowNoRepeatNgramProcessor, restated
@@ -21014,6 +21359,346 @@ static void qsa_select_case(const Plugin& pl, int signed_scores = 0) {
" su=" + (su_ok ? "1" : "0") + " det=" + (det ? "1" : "0"));
}
/* kv_store_streamed, on the card, against libref's oracle: the store of a group whose KV streams.
*
* Both sides start from the same bytes; libref runs on host tensors and this kernel on device ones,
* and all six operands are compared byte for byte afterwards -- the mirror, the ring, and the four
* inputs, which must be unchanged. The conversion is E4M3 on both sides, so a status only one side
* rounds differently, or a block written to the wrong plane, fails here.
*
* The cases are the ones that decide the design: a block absent from the ring beside one resident
* (the resident token must reach both copies, the absent one the mirror only), a step with nothing
* resident (the ring untouched), the parity configuration's identity map (both planes alike), and a
* padded batch row. libref refuses the state faults before writing them; this kernel guards the same
* paths instead, since a launch cannot return a host status, so they are not byte-compared.
*/
static void kv_store_streamed_case(const Plugin& pl, const char* row, const char* kvd,
uint32_t kdt, int64_t eb) {
const std::string whats =
fmt("kv_store_streamed %s vs libref: mirror always, resident slot too", kvd);
const char* what = whats.c_str();
const RadKernelInfo* r = find(pl, row);
if (!r) { ok(what, false, "row absent"); return; }
if (!g_plugin) { ok(what, false, "plugin path absent"); return; }
std::string rpath(g_plugin);
rpath = rpath.substr(0, rpath.find_last_of('/') + 1) + "libref.so";
void* ref = dlopen(rpath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!ref) { ok(what, false, "reference plugin unavailable"); return; }
auto rcount = (int (*)(void))dlsym(ref, "rad_kernel_count");
auto rat = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at");
const RadKernelInfo* oracle = nullptr;
if (rcount && rat)
for (int i = 0; i < rcount(); ++i)
if (std::strcmp(rat(i)->op, "kv_store_streamed") == 0) { oracle = rat(i); break; }
if (!oracle) { ok(what, false, "reference operation unavailable"); dlclose(ref); return; }
struct State {
int64_t M, blocks, slots, bs, kvh, hd, row;
std::vector<uint16_t> k, v;
std::vector<int32_t> sm, res;
std::vector<uint8_t> host, ring;
};
auto seed = [eb](State& c, int64_t M, int64_t blocks, int64_t slots, int64_t bs, int64_t kvh,
int64_t hd, std::vector<int32_t> sm, std::vector<int32_t> res) {
c.M = M; c.blocks = blocks; c.slots = slots; c.bs = bs; c.kvh = kvh; c.hd = hd;
c.row = kvh * bs * 2 * hd * eb;
c.sm = std::move(sm);
c.res = std::move(res);
c.k.resize((size_t)(M * kvh * hd));
c.v.resize((size_t)(M * kvh * hd));
for (int64_t i = 0; i < M * kvh * hd; ++i) {
c.k[(size_t)i] = h_to_bf16((float)((i * 5 + 3) % 29 - 14) * 0.5f);
c.v[(size_t)i] = h_to_bf16((float)((i * 11 + 1) % 17 - 8) * 0.25f);
}
c.host.assign((size_t)(blocks * c.row), 0);
c.ring.assign((size_t)(slots * c.row), 0);
};
/* `mapped_host`: the mirror is pinned HOST memory, mapped into the device's address space, not
* a device allocation. That is what the engine hands the op -- a streamed group's mirror is
* RAD_MEM_HOST_MAPPED, one address on every card -- so the store's second destination is system
* RAM written by a kernel, the first in-place device write of that kind here (docs/
* KV-STREAMING.md §6.2). The kernel gets the device view of it; the comparison reads the host
* pointer, which is the same bytes by construction. */
auto run = [&](const char* label, State& c, int want_kernel = RAD_OK,
bool mapped_host = false) {
void* d[6] = {};
const size_t bytes[6] = {
c.k.size() * 2, c.v.size() * 2, c.sm.size() * 4,
c.ring.size(), (size_t)c.res.size() * 4, c.host.size() };
void* host_mapped = nullptr; /* operand 5's host pointer, when it is host memory */
for (int i = 0; i < 6; ++i) {
if (i == 5 && mapped_host) {
if (hipHostMalloc(&host_mapped, bytes[5], hipHostMallocMapped) != hipSuccess ||
!host_mapped) {
ok(label, false, "host-mapped allocation failed");
return;
}
if (hipHostGetDevicePointer(&d[5], host_mapped, 0) != hipSuccess || !d[5]) {
ok(label, false, "host-mapped allocation has no device view");
st_free(host_mapped);
return;
}
continue;
}
d[i] = dalloc(bytes[i]);
if (!d[i]) { ok(label, false, "allocation failed"); return; }
}
const std::vector<std::vector<int64_t>> shapes = {
{ c.M, c.kvh, c.hd }, { c.M, c.kvh, c.hd }, { c.M },
{ c.slots, c.kvh, c.bs, 2 * c.hd }, { c.blocks }, { c.blocks, c.row } };
const uint32_t dts[6] = { RAD_BF16, RAD_BF16, RAD_I32, kdt, RAD_I32, RAD_U8 };
const void* hp[6] = { c.k.data(), c.v.data(), c.sm.data(), c.ring.data(), c.res.data(),
c.host.data() };
std::vector<RadTensor> th, td;
for (int i = 0; i < 6; ++i) {
th.push_back(T((void*)hp[i], dts[i], shapes[(size_t)i]));
td.push_back(T(d[i], dts[i], shapes[(size_t)i]));
if (i == 5 && mapped_host) std::memcpy(host_mapped, hp[5], bytes[5]);
else st_memcpy(d[i], hp[i], bytes[i], hipMemcpyHostToDevice);
}
std::vector<RadParam> ps = { PI("M", c.M), PI("head_dim", c.hd),
PI("n_head_kv", c.kvh), PI("block_size", c.bs),
{ "kv_dtype", RAD_P_STR, 0, 0, kvd, 0 } };
RadArgs ah{}, ad{};
ah.t = th.data(); ah.n_t = 6; ah.p = ps.data(); ah.n_p = 5; ah.world_size = 1;
ad.t = td.data(); ad.n_t = 6; ad.p = ps.data(); ad.n_p = 5; ad.world_size = 1;
const int rr = oracle->launch(&ah, nullptr);
const int rc = r->launch(&ad, nullptr);
st_stream_sync(nullptr);
bool pass = rr == RAD_OK && rc == want_kernel;
std::string why;
if (!pass) why = fmt("libref rc=%d kernel rc=%d (wanted %d)", rr, rc, want_kernel);
if (pass && want_kernel == RAD_OK) {
for (int i = 0; i < 6 && pass; ++i) {
std::vector<uint8_t> got(bytes[i]);
if (i == 5 && mapped_host)
std::memcpy(got.data(), host_mapped, bytes[i]);
else
st_memcpy(got.data(), d[i], bytes[i], hipMemcpyDeviceToHost);
for (size_t j = 0; j < bytes[i]; ++j)
if (got[j] != ((const uint8_t*)hp[i])[j]) {
pass = false;
why = fmt("operand %d byte %zu: kernel %u, libref %u", i, j,
(unsigned)got[j], (unsigned)((const uint8_t*)hp[i])[j]);
break;
}
}
}
if (host_mapped) (void)hip_ck(hipHostFree(host_mapped), "hipHostFree", __LINE__);
ok(label, pass, why);
};
/* Block 0 absent, block 1 resident in slot 0, block 2 absent: one token in each. */
{
State c; seed(c, 3, 4, 2, 2, 2, 4, { 1, 3, 6 }, { -1, 0, -1, -1 });
run("kv_store_streamed mirror always, resident slot too", c);
}
/* Nothing resident: the ring must come out untouched. */
{
State c; seed(c, 2, 4, 2, 2, 2, 4, { 0, 5 }, { -1, -1, -1, -1 });
run("kv_store_streamed a cold ring takes the mirror alone", c);
}
/* The parity configuration's identity map: both planes hold the same bytes. */
{
State c; seed(c, 4, 3, 3, 2, 2, 4, { 0, 3, 5, 2 }, { 0, 1, 2 });
run("kv_store_streamed an identity map writes both planes alike", c);
}
/* A padded batch row stores nothing in either plane. */
{
State c; seed(c, 2, 2, 1, 2, 1, 8, { -1, 3 }, { -1, 0 });
run("kv_store_streamed a negative slot stores nothing", c);
}
/* The engine's own configuration: the mirror is pinned host memory the kernel writes. */
{
State c; seed(c, 3, 4, 2, 2, 2, 4, { 1, 3, 6 }, { -1, 0, -1, -1 });
run("kv_store_streamed into a host-mapped mirror", c, RAD_OK, true);
}
}
/* qk_norm_rope_gate_kv_store_streamed, on the card, against the pair it replaces: the device
* prologue (the row the fold is byte-identical to) plus libref's `kv_store_streamed` oracle for the
* store half -- the mirror for every token, the ring slot only where the residency map says the
* block is resident. All four outputs are compared byte for byte (q, the rotated k, the mirror and
* the ring), as are the inputs that must not change.
*
* The cases that decide the design are the same ones the streamed store has: a partly resident map
* beside absent blocks, a cold ring, the parity configuration's identity map, and a padded row
* whose negative slot writes neither plane. The inputs span E4M3's clamp, as the hosted fold does.
*/
static void qk_kv_fold_streamed_case(const Plugin& pl, const char* row, const char* kvd,
uint32_t kdt, int64_t eb) {
if (!sel(row)) return;
const std::string whats =
fmt("qk_norm_rope_gate_kv_store_streamed %s vs prologue + libref kv_store_streamed", kvd);
const char* what = whats.c_str();
const RadKernelInfo* rk = find(pl, row);
const RadKernelInfo* rf = find(pl, "qk_norm_rope_gate");
const RadKernelInfo* rt = find(pl, "rope_table_f32");
if (!rk || !rf || !rt) { ok(what, false, "row absent"); return; }
if (!g_plugin) { ok(what, false, "plugin path absent"); return; }
std::string rpath(g_plugin);
rpath = rpath.substr(0, rpath.find_last_of('/') + 1) + "libref.so";
void* ref = dlopen(rpath.c_str(), RTLD_NOW | RTLD_LOCAL);
if (!ref) { ok(what, false, "reference plugin unavailable"); return; }
auto rcount = (int (*)(void))dlsym(ref, "rad_kernel_count");
auto rat = (const RadKernelInfo* (*)(int))dlsym(ref, "rad_kernel_at");
const RadKernelInfo* oracle = nullptr;
if (rcount && rat)
for (int i = 0; i < rcount(); ++i)
if (std::strcmp(rat(i)->op, "kv_store_streamed") == 0) { oracle = rat(i); break; }
if (!oracle) { ok(what, false, "reference operation unavailable"); dlclose(ref); return; }
const int64_t M = 12, nq = 4, nkv = 2, hd = 64, rot = 64, ctx = 1024, bs = 8;
const int64_t blocks = 4, slots = 3;
const int64_t rowb = nkv * bs * 2 * hd * eb; /* one block of one layer, bytes */
const size_t qb = (size_t)M * nq * hd * 2, kb = (size_t)M * nkv * hd * 2;
const size_t hb = (size_t)(blocks * rowb), cb = (size_t)(slots * rowb);
uint32_t st = 0x1234567u;
auto rnd = [&](float span) {
st = st * 1664525u + 1013904223u;
return ((float)(st >> 8) / 16777216.0f * 2.0f - 1.0f) * span;
};
std::vector<int32_t> pos((size_t)M), slot((size_t)M);
for (int64_t t = 0; t < M; ++t) {
pos[(size_t)t] = (int32_t)((t * 97 + 5) % ctx);
slot[(size_t)t] = (int32_t)((t * 3 + 1) % (blocks * bs)); /* blocks 0..3, 3 coprime with 8 */
}
slot[2] = -1; /* a pad row */
std::vector<uint16_t> hqg((size_t)M * nq * 2 * hd), hk((size_t)M * nkv * hd),
hv((size_t)M * nkv * hd);
for (auto& x : hqg) x = h_to_bf16(rnd(4.0f));
for (auto& x : hk) x = h_to_bf16(rnd(4.0f));
for (auto& x : hv) x = h_to_bf16(rnd(2000.0f));
std::vector<float> fwq((size_t)hd), fwk((size_t)hd);
for (int64_t d = 0; d < hd; ++d) { fwq[(size_t)d] = rnd(0.5f); fwk[(size_t)d] = rnd(0.5f); }
void* d_qg = dalloc((size_t)M * nq * 2 * hd * 2);
void* d_k = dalloc(kb); /* the prologue's rotated k, reused as the fold's k_out check */
void* d_v = dalloc(kb);
void* d_wq = dalloc((size_t)hd * 4); void* d_wk = dalloc((size_t)hd * 4);
void* d_p = dalloc((size_t)M * 4); void* d_sl = dalloc((size_t)M * 4);
void* d_cs = dalloc((size_t)ctx * rot * 4);
void* d_qA = dalloc(qb); void* d_qB = dalloc(qb);
void* d_kA = dalloc(kb); void* d_kB = dalloc(kb);
void* d_hA = dalloc(hb); void* d_hB = dalloc(hb);
void* d_cA = dalloc(cb); void* d_cB = dalloc(cb);
void* d_res = dalloc((size_t)blocks * 4);
if (!d_qg || !d_k || !d_v || !d_wq || !d_wk || !d_p || !d_sl || !d_cs || !d_qA || !d_qB ||
!d_kA || !d_kB || !d_hA || !d_hB || !d_cA || !d_cB || !d_res) {
ok(what, false, "hipMalloc failed"); dlclose(ref); return;
}
st_memcpy(d_qg, hqg.data(), hqg.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_v, hv.data(), hv.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_k, hk.data(), hk.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_wq, fwq.data(), (size_t)hd * 4, hipMemcpyHostToDevice);
st_memcpy(d_wk, fwk.data(), (size_t)hd * 4, hipMemcpyHostToDevice);
st_memcpy(d_p, pos.data(), (size_t)M * 4, hipMemcpyHostToDevice);
st_memcpy(d_sl, slot.data(), (size_t)M * 4, hipMemcpyHostToDevice);
st_memset(d_cs, 0, (size_t)ctx * rot * 4);
{
std::vector<RadTensor> ts = { T(d_p, RAD_I32, { M }), T(d_cs, RAD_F32, { ctx, rot }) };
std::vector<RadParam> ps = { PI("M", M), PI("rot", rot), PF("theta", 1e7),
PF("scale", 1.0), PS("dtype", "f32") };
run_case(rt, ts, ps);
}
const std::vector<RadParam> pq = { PI("M", M), PI("head_dim", hd), PI("n_head", nq),
PI("n_head_kv", nkv), PI("rot", rot),
PS("q_dtype", "bf16"), PF("eps", 1e-6), PF("wadd", 1.0),
PI("cs_f32", 1) };
/* The prologue's own output is the reference for q and k, and the oracle's input for k. */
{
std::vector<RadTensor> ts = { T(d_qg, RAD_BF16, { M, nq * 2 * hd }),
T(d_k, RAD_BF16, { M, nkv * hd }),
T(d_cs, RAD_F32, { ctx, rot }), T(d_p, RAD_I32, { M }),
T(d_wq, RAD_F32, { hd }), T(d_wk, RAD_F32, { hd }),
T(d_qA, RAD_BF16, { M, nq * hd }),
T(d_kA, RAD_BF16, { M, nkv * hd }), RadTensor{} };
std::vector<RadParam> ps = pq;
run_case(rf, ts, ps);
}
std::vector<uint16_t> hkout((size_t)M * nkv * hd);
st_memcpy(hkout.data(), d_kA, kb, hipMemcpyDeviceToHost);
/* A map, a ring and a mirror: `res` and `slots` are the call's, the rest start from bytes the
* kernel must not mistake for its own. */
auto one = [&](const char* label, std::vector<int32_t> res) {
std::vector<uint8_t> hh(hb), hc(cb);
for (auto& x : hh) x = (uint8_t)(rnd(128.0f) + 128.0f);
for (auto& x : hc) x = (uint8_t)(rnd(128.0f) + 128.0f);
std::vector<uint8_t> ref_h = hh, ref_c = hc;
st_memcpy(d_hA, hh.data(), hb, hipMemcpyHostToDevice);
st_memcpy(d_cA, hc.data(), cb, hipMemcpyHostToDevice);
st_memcpy(d_hB, hh.data(), hb, hipMemcpyHostToDevice);
st_memcpy(d_cB, hc.data(), cb, hipMemcpyHostToDevice);
st_memcpy(d_res, res.data(), (size_t)blocks * 4, hipMemcpyHostToDevice);
/* The oracle on host memory: the same k_out, v, slots, ring, map and mirror. */
std::vector<RadTensor> th = {
T(hkout.data(), RAD_BF16, { M, nkv, hd }),
T(hv.data(), RAD_BF16, { M, nkv, hd }), T(slot.data(), RAD_I32, { M }),
T(ref_c.data(), kdt, { slots, nkv, bs, 2 * hd }),
T(res.data(), RAD_I32, { blocks }), T(ref_h.data(), RAD_U8, { blocks, rowb }) };
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", hd), PI("n_head_kv", nkv),
PI("block_size", bs), PS("kv_dtype", kvd) };
RadArgs ah{};
ah.t = th.data(); ah.n_t = (int)th.size(); ah.p = ps.data(); ah.n_p = (int)ps.size();
ah.world_size = 1;
const int rr = oracle->launch(&ah, nullptr);
std::vector<RadTensor> ts = { T(d_qg, RAD_BF16, { M, nq * 2 * hd }),
T(d_k, RAD_BF16, { M, nkv * hd }),
T(d_cs, RAD_F32, { ctx, rot }), T(d_p, RAD_I32, { M }),
T(d_wq, RAD_F32, { hd }), T(d_wk, RAD_F32, { hd }),
T(d_qB, RAD_BF16, { M, nq * hd }),
T(d_kB, RAD_BF16, { M, nkv * hd }), RadTensor{},
T(d_v, RAD_BF16, { M, nkv * hd }), T(d_sl, RAD_I32, { M }),
T(d_cB, kdt, { slots, nkv, bs, 2 * hd }),
T(d_res, RAD_I32, { blocks }),
T(d_hB, RAD_U8, { blocks, rowb }) };
std::vector<RadParam> pf = pq;
pf.push_back(PI("block_size", bs));
pf.push_back(PS("kv_dtype", kvd));
RadArgs af{};
af.t = ts.data(); af.n_t = (int)ts.size(); af.p = pf.data(); af.n_p = (int)pf.size();
af.world_size = 1;
const int rc = rk->launch(&af, nullptr);
st_stream_sync(nullptr);
std::vector<uint8_t> qa(qb), qbv(qb), ka(kb), kbv(kb), hkv(hb), ckv(cb);
st_memcpy(qa.data(), d_qA, qb, hipMemcpyDeviceToHost);
st_memcpy(qbv.data(), d_qB, qb, hipMemcpyDeviceToHost);
st_memcpy(ka.data(), d_kA, kb, hipMemcpyDeviceToHost);
st_memcpy(kbv.data(), d_kB, kb, hipMemcpyDeviceToHost);
st_memcpy(hkv.data(), d_hB, hb, hipMemcpyDeviceToHost);
st_memcpy(ckv.data(), d_cB, cb, hipMemcpyDeviceToHost);
auto ndiff = [](const uint8_t* a, const uint8_t* b, size_t n) {
int64_t k = 0;
for (size_t i = 0; i < n; ++i) k += a[i] != b[i];
return k;
};
const int64_t dq = ndiff(qa.data(), qbv.data(), qb);
const int64_t dk = ndiff(ka.data(), kbv.data(), kb);
/* The kernel's two planes against the oracle's, byte for byte. */
const int64_t dh = ndiff(hkv.data(), ref_h.data(), hb);
const int64_t dc = ndiff(ckv.data(), ref_c.data(), cb);
const bool touched = ndiff(ref_h.data(), hh.data(), hb) + ndiff(ref_c.data(), hc.data(), cb) > 0;
bool pass = rr == RAD_OK && rc == RAD_OK && dq == 0 && dk == 0 && dh == 0 && dc == 0;
std::string why = fmt("libref rc=%d kernel rc=%d; q %lld, k %lld, mirror %lld, ring %lld "
"differ", rr, rc, (long long)dq, (long long)dk, (long long)dh,
(long long)dc);
if (pass && !touched) { pass = false; why = "the store wrote neither plane"; }
ok(label, pass, why);
};
one("qk_norm_rope_gate_kv_store_streamed a partly resident map writes both planes",
{ -1, 0, 2, -1 }); /* block 1 -> slot 0, block 2 -> slot 2, blocks 0 and 3 absent */
one("qk_norm_rope_gate_kv_store_streamed a cold ring takes the mirror alone",
{ -1, -1, -1, -1 });
one("qk_norm_rope_gate_kv_store_streamed an identity map writes both planes alike",
{ 0, 1, 2, -1 });
dlclose(ref);
}
/* qsa_select at prefill: many queries over one history, each bounded by its own position.
*
* At decode the sequence's complete-block count equals the query's and `bt[nc]` is -1. Mid-chunk,
@@ -27499,6 +28184,34 @@ static void device_phase(const Plugin& pl) {
qsa_select_few_live_case(pl);
}
if (sel("kv_resolve_i32")) {
if (!g_case) std::printf("\nthe streamed-KV residency map, against libref\n");
kv_resolve_case(pl);
}
if (sel("kv_store_streamed_fp8")) {
if (!g_case) std::printf("\nthe streamed-KV store, against libref\n");
kv_store_streamed_case(pl, "kv_store_streamed_fp8", "fp8_e4m3", RAD_F8E4M3, 1);
}
if (sel("kv_store_streamed_bf16")) {
if (!g_case) std::printf("\nthe streamed-KV store, bf16, against libref\n");
kv_store_streamed_case(pl, "kv_store_streamed_bf16", "bf16", RAD_BF16, 2);
}
if (sel("qk_norm_rope_gate_kv_store_streamed_fp8")) {
if (!g_case)
std::printf("\nthe folded streamed store, against the prologue and libref's store\n");
qk_kv_fold_streamed_case(pl, "qk_norm_rope_gate_kv_store_streamed_fp8", "fp8_e4m3",
RAD_F8E4M3, 1);
}
if (sel("qk_norm_rope_gate_kv_store_streamed_bf16")) {
if (!g_case)
std::printf("\nthe folded streamed store, bf16, against the prologue and libref's "
"store\n");
qk_kv_fold_streamed_case(pl, "qk_norm_rope_gate_kv_store_streamed_bf16", "bf16",
RAD_BF16, 2);
}
if (sel("qsa_score_bf16")) {
if (!g_case) std::printf("\nthe QSA block score, against the formula it implements\n");
/* Every form of the row: the launcher picks by shape, and another model's shape may get
+8 -5
View File
@@ -425,8 +425,9 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip
${R4D_DIR}/r4d_dsa.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip)
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres
dsa)
set(R4D_EMU_BUILT OFF)
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
# No fiber switch for this ISA.
@@ -465,7 +466,8 @@ else()
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_dsa.cpp)
${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp
${R4D_EMU}/test_dsa.cpp)
get_filename_component(stem ${src} NAME_WE)
set(lang "")
if(src MATCHES "\\.hip$")
@@ -502,7 +504,7 @@ else()
endif()
endif()
if(R4D_EMU_BUILT)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse dsa)
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse kvres dsa)
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
endforeach()
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
@@ -574,7 +576,8 @@ if(RAD_HIP_FOUND AND TARGET libr4d)
endif()
add_test(NAME oot_plugins
COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP})
${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot ${RAD_OOT_HIP}
${CMAKE_CXX_COMPILER})
# RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do.
set_tests_properties(oot_plugins PROPERTIES
LABELS "oot"
+840
View File
@@ -7,6 +7,9 @@
#include "rad_test.h"
#include "mem/kv.h"
#include "kvstream/bringup.h"
#include "kvstream/bind.h"
#include "kvstream/plan.h"
#include "mem/pools.h"
#include "mem/prefix.h"
#include "mem/vram_budget.h"
@@ -116,6 +119,52 @@ struct Fixture {
}
};
/* The streamed path an architecture plugin declares for `g`, as the builder records it: one
* kv_resolve stating the group's per-layer block pitch and the blocks one selection row can name,
* and one kv_store_streamed stating the group's page. `with_resolve`/`with_store` build the model
* that declares neither (or only one) -- which is what the tree's DSA-index models actually do,
* so --kv-resident must be ignored rather than started on them.
*
* `store_resolved` is the third state, and the one easiest to get wrong: the op is *declared* and the
* kernel table has no row for it. The builder records the op anyway and synthesises one band
* with both domains null and a miss reason (core/build/rad_builder.cpp, resolve_bands), so the op
* is present in prog.ops and only its handle is null -- which is exactly the packed-cache shape
* (`fp8_v4` / `k6_v4`, no streamed-store row). A resolved band is a bound row in a domain, which is
* what kvstream_ops reads (kvstream_ops; the same test as Builder::op_resolved). */
static KernelRow& a_resolved_row() {
/* Static, as a plugin table's rows are: a Resolved points at one. Nothing in this test issues
* the op, so the row carries no kernel. */
static KernelRow row;
return row;
}
static Program stream_program(const KVGroupInfo& g, int64_t sel_pitch, bool with_resolve = true,
bool with_store = true, bool store_resolved = true) {
Program p;
p.meta.arch_id = "test-arch";
const int64_t n_bound = g.layers.empty() ? 1 : (int64_t)g.layers.size();
const int64_t layer_bytes = g.bytes_per_block > 0 ? g.bytes_per_block / n_bound : 0;
if (with_resolve) {
OpInfo oi;
oi.op = "kv_resolve";
oi.bands.resize(1); /* resolved: the builder records one band per domain */
oi.bands[0].dom[RAD_DOMAIN_DEVICE].row = &a_resolved_row();
oi.base.set_i("block_bytes", layer_bytes);
oi.base.set_i("sel_pitch", sel_pitch);
p.ops.push_back(std::move(oi));
}
if (with_store) {
OpInfo oi;
oi.op = "kv_store_streamed";
oi.bands.resize(1);
if (store_resolved) oi.bands[0].dom[RAD_DOMAIN_DEVICE].row = &a_resolved_row();
else oi.bands[0].miss[RAD_DOMAIN_DEVICE] = "kv_dtype in {fp8_e4m3}, have fp8_v4";
oi.base.set_i("block_size", g.block_size);
p.ops.push_back(std::move(oi));
}
return p;
}
static std::vector<int32_t> tok_run(int32_t base, int n) {
std::vector<int32_t> v;
for (int i = 0; i < n; ++i) v.push_back(base + i);
@@ -776,6 +825,56 @@ static KVGroupInfo paged_group(const char* name, int kind, int64_t heads, int64_
return k;
}
/* Which group --kv-resident streams is a rule, not the widest paged FULL group: a group is a
* candidate only when the program states a streamed path for it, and an indexer-style dense-read
* group never is. GLM-5.3's two FULL groups make the difference visible: kv_latent (49 152 B) is
* the geometry the feature wants, kv_dsa_index (1 632 B) is read over the whole history every
* step and must stay resident. Width then decides only between groups that are wired. */
TEST(kv_stream_group_picks_a_wired_full_group_not_merely_the_widest) {
std::vector<KVGroupInfo> g;
g.push_back(null_group());
const std::vector<int32_t> full_layers = { 3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 45 };
KVGroupInfo latent = paged_group("kv_latent", RAD_KV_FULL, 1, 4, full_layers);
latent.decl.dtype = RAD_BF16;
latent.decl.head_dim = 256;
latent.bytes_per_block = 49152; /* 12 layers x 4 tokens x 256 x bf16 */
KVGroupInfo index = paged_group("kv_dsa_index", RAD_KV_FULL, 1, 4, full_layers);
index.decl.dtype = RAD_U8;
index.decl.head_dim = 17;
index.bytes_per_block = 1632; /* 12 layers x 4 tokens x 17 x u8 */
g.push_back(latent);
g.push_back(index);
auto check_pick = [&](const Program& p, int32_t want) {
Program prog = p;
prog.kv_groups = g; /* index-aligned, as Engine's program is */
CHECK_EQ(kv_stream_group(g, &prog), want);
/* The cap probe and the carve must agree, so the plans overload takes the same rule. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 4096;
f.cfg.max_seqs = 2;
CHECK_OK(f.kv.plan_groups(g, f.cfg));
CHECK_EQ(kv_stream_group(f.kv, &prog), want);
};
/* Wired latent, narrower: it is picked. */
check_pick(stream_program(g[1], 513), 1);
/* The index group made wider is still not picked: it is not wired. This is the width
* coincidence the rule removes. */
g[2].bytes_per_block = 65536;
check_pick(stream_program(g[1], 513), 1);
g[2].bytes_per_block = 1632;
/* A resolve that states the index group's pitch (136 B a layer) is the only wired path, so
* the narrower group is the one that streams. */
check_pick(stream_program(g[2], 513), 2);
/* A dense-read group is never a candidate, even when its own path is declared. Nothing else
* is wired here, so nothing streams. */
g[2].dense_read = true;
check_pick(stream_program(g[2], 513), -1);
g[2].dense_read = false;
}
/* A windowed group is capped at its window on both ranks, and the cap shifts the freed bytes to
* the other groups, a kink in paged_split the inverse must cross exactly. The dear rank's count is
* past the window, so the window group holds max_seqs x window_blocks on both ranks. */
@@ -846,6 +945,655 @@ TEST(an_uneven_worlds_cheaper_rank_gives_its_saved_kv_to_its_weights_up_to_all_r
CHECK_EQ(s.kv_mib, (int64_t)800);
}
TEST(a_streamed_group_is_refused_at_carve_without_its_host_copy) {
/* The failure this prevents: the manager hands out block ids over the context, the pool backs
* four of them, and a kv_store for block 40 writes forty blocks past the layer stride. So a
* streamed plan is refused unless something owns the blocks the pool does not. Each variant
* removes one of the three pieces the carve requires. */
for (int variant = 0; variant < 3; ++variant) {
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024; /* the context the group will address, in host RAM */
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64);
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
/* How many blocks the group has is decided at carve; the host copy has to be there first,
* so size it from the context the carve will compute: every sequence at full length. */
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
const int64_t page = f.kv.plan(G_FULL)->bytes_per_block;
const int64_t need = ctx_blocks * page;
std::vector<char> host((size_t)need, 0);
std::vector<int32_t> res((size_t)ctx_blocks, -1);
KVManager::StreamMap m;
m.host = variant == 0 ? nullptr : (uint8_t*)host.data(); /* 0: no copy at all */
m.host_bytes = variant == 1 ? need - 1 : need; /* 1: a copy too small */
m.res = variant == 2 ? nullptr : res.data(); /* 2: no map */
f.kv.set_stream_map(G_FULL, m);
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_INVAL);
}
}
TEST(a_streamed_group_addresses_its_context_but_backs_only_the_resident_window) {
/* kv streaming (docs/KV-STREAMING.md): a paged group keeps allocating block ids over its whole
* context -- the block table, the refcounts, the prefix cache and every `id < n_blocks` guard
* count in those -- while the device pool backs only `--kv-resident` of them and a residency
* map says which. The two numbers differ only where addressing happens, so this pins the four
* places that multiply by one of them: the carve, the stride between layers, the operand shape
* a kernel is handed, and the loan. Getting one wrong is not a crash: it is a kernel writing
* one layer's block into the next, which produces fluent wrong text.
*
* The split is decided at carve, not at plan: how many blocks the group has is a function of
* the pool's budget, which only the carve knows. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024; /* the context the group addresses */
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
/* Both numbers come from the carve: the context from --max-model-len and --max-num-seqs, the
* window from --kv-resident. The host copy must already cover the context. */
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
const int64_t page = f.kv.plan(G_FULL)->bytes_per_block;
CHECK(ctx_blocks > 4); /* the pool holds more than the window */
std::vector<char> host((size_t)(ctx_blocks * page), 0);
std::vector<int32_t> res((size_t)ctx_blocks, -1);
KVManager::StreamMap sm_in;
sm_in.host = (uint8_t*)host.data();
sm_in.res = res.data();
sm_in.host_bytes = (int64_t)host.size();
f.kv.set_stream_map(G_FULL, sm_in);
const KVManager::StreamMap* sm = f.kv.stream_map(G_FULL);
CHECK(sm != nullptr && sm->host == (uint8_t*)host.data() && sm->res == res.data() &&
sm->host_bytes >= ctx_blocks * page);
CHECK_OK(f.kv.carve(f.pools.kv()));
const KVGroupPlan* p = f.kv.plan(G_FULL);
CHECK_EQ(p->n_blocks, ctx_blocks);
CHECK_EQ(p->n_slots, 4);
CHECK(p->streamed());
CHECK_EQ(p->pool_blocks(), 4);
CHECK_EQ(p->layer_stride(), 4 * p->layer_bytes_per_block());
/* The carve is one reservation of max(ring, stage): the ring's four blocks of every layer, or
* the whole context one layer deep. Here the context's one layer is the larger, so the pool is
* a stage and the ring fits inside it (docs/KV-STREAMING.md §4.1). */
CHECK_EQ(f.kv.pool_bytes_carved(G_FULL),
std::max(4 * page, ctx_blocks * p->layer_bytes_per_block()));
CHECK_EQ(rad::kv_ceiling_bytes(*p, ctx_blocks, 4), ctx_blocks * p->layer_bytes_per_block());
/* The startup report must not read as a pool that holds the whole context. */
CHECK(f.kv.report().find("streaming:") != std::string::npos);
/* Not lendable: the window is what a residency map reads, and a block lent to the expert slab
* is one the attention has nowhere to put. */
CHECK(!f.kv.lendable(G_FULL));
/* The linear group next to it is untouched. */
CHECK_EQ(f.kv.plan(G_GDN)->n_slots, 0);
CHECK(!f.kv.plan(G_GDN)->streamed());
/* Block ids still run over the context. A sequence longer than the window asks for more ids
* than the pool backs and gets them, because its table names logical blocks -- which is exactly
* why a streamed plan may not be carved without somewhere for them to live. */
CHECK_OK(f.kv.add_sequence(1));
CHECK_OK(f.kv.ensure(1, 16 * 8)); /* eight blocks, twice the window */
const std::vector<int32_t>& bt = f.kv.block_table(1, G_FULL);
CHECK(bt.size() >= 8);
int32_t hi = 0;
for (int32_t b : bt) hi = std::max(hi, b);
CHECK(hi >= 4); /* an id past the window */
/* And a server that does not stream carves exactly what it did before the split: nothing
* moves for a group with no cap_resident_tokens(). */
Fixture plain;
plain.cfg.checkpoint_slots = 0;
CHECK_OK(plain.build());
const KVGroupPlan* q = plain.kv.plan(G_FULL);
CHECK(q->n_blocks > 0);
CHECK_EQ(q->n_slots, q->n_blocks);
CHECK(!q->streamed());
CHECK_EQ(plain.kv.pool_bytes_carved(G_FULL), q->n_blocks * q->bytes_per_block);
}
TEST(a_resident_window_that_does_not_fit_vram_kv_is_refused_by_its_own_flag) {
/* --kv-resident is what sizes the window, so a window wider than the pool has to be refused by
* the carve. Left to the split, it would leave the other groups zero blocks and the operator
* would be told to raise --host-pool-mib -- a term that is not the one that is too large. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 100000); /* 6250 blocks against a 1 MiB pool */
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
/* The host copy is the right size for the context; the window is what does not fit. */
const int64_t ctx_blocks = f.cfg.max_seqs * (f.cfg.max_ctx / 16);
std::vector<char> host((size_t)(ctx_blocks * f.kv.plan(G_FULL)->bytes_per_block), 0);
std::vector<int32_t> res((size_t)ctx_blocks, -1);
KVManager::StreamMap sm_in;
sm_in.host = (uint8_t*)host.data();
sm_in.res = res.data();
sm_in.host_bytes = (int64_t)host.size();
f.kv.set_stream_map(G_FULL, sm_in);
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_NOMEM);
}
TEST(a_streamed_window_group_is_refused_by_name) {
/* A window group already bounds its own history, so the ids it allocates are its window's,
* while a streamed group's ids are its whole context. Streaming one would give it a table of
* the other shape, so it is refused instead of carved with ids nothing can resolve. */
auto groups = hybrid_groups();
groups[G_FULL].decl.kind = RAD_KV_WINDOW;
groups[G_FULL].decl.window = 128; /* window_blocks = 128/16 + 1 */
Fixture f;
f.cfg.checkpoint_slots = 0;
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64);
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
CHECK_EQ(f.kv.carve(f.pools.kv()), RAD_E_INVAL);
}
/* The residency maps are device memory (abi/rad_runtime.h, RadKVStream: a resolve launch reads and
* rewrites them every step, so a host round trip per lookup would pay the link latency the ring
* exists to avoid). On a card the KV pool is an elastic VRAM range mapped into the address space,
* and a host load of it faults -- which is the card-only segfault this helper exists to keep out of
* the suite. The engine drains the same arrays the same way (core/engine.cpp reads `ctl` with
* rad_memcpy_async), so a check of their contents copies them back on a stream first. The counts
* are the ABI's: `res` is `n_layers * blocks`, `slot_block` is `n_layers * slots`, and
* `slot_state` is `n_layers * slots * 2`. */
struct StreamMapsHost {
std::vector<int32_t> res, slot_block, slot_state, ctl;
};
static int read_stream_maps(const KVManager::StreamMap& m, const KVGroupPlan& p, RadStream st,
StreamMapsHost* out) {
const int64_t layers = p.n_layers > 0 ? p.n_layers : 1;
out->res.assign((size_t)(layers * p.n_blocks), 0);
out->slot_block.assign((size_t)(layers * m.slots), 0);
out->slot_state.assign((size_t)(layers * m.slots * 2), 0);
out->ctl.assign(16, 0);
auto copy = [&](std::vector<int32_t>& dst, const int32_t* src) {
return rad_memcpy_async(dst.data(), src,
(int64_t)dst.size() * (int64_t)sizeof(int32_t), st);
};
int rc = copy(out->res, m.res);
if (rc == RAD_OK) rc = copy(out->slot_block, m.slot_block);
if (rc == RAD_OK) rc = copy(out->slot_state, m.slot_state);
if (rc == RAD_OK) rc = copy(out->ctl, m.ctl);
if (rc == RAD_OK) rc = rad_stream_sync(st);
return rc;
}
TEST(a_streamed_plan_allocates_reports_and_frees_its_mirror) {
/* The host mirror and the ring's maps, end to end: what stream_cost() promises is what
* alloc_stream() takes, the mirror is zeroed (a block nothing wrote yet must read as zeros, not
* as a page's leftovers), the maps come out of the KV pool and hold the reset state a resolve
* launch expects, the report shows both tiers, and free_stream() releases the mirror and is
* safe to call twice. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
const KVManager::StreamCost cost = f.kv.stream_cost();
CHECK_EQ(cost.groups, (int64_t)1);
CHECK_EQ(cost.host_bytes, f.cfg.max_seqs * (f.cfg.max_ctx / 16) *
f.kv.plan(G_FULL)->bytes_per_block);
CHECK(cost.map_bytes > 0);
const int64_t pool_used = f.pools.kv().used();
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
/* Every map byte is a reservation in the KV pool, so the paged split sees it. */
CHECK_EQ(f.pools.kv().used() - pool_used, cost.map_bytes);
const KVManager::StreamMap* m = f.kv.stream_map(G_FULL);
REQUIRE(m != nullptr);
CHECK(m->host != nullptr && m->res != nullptr && m->ctl != nullptr);
CHECK_EQ(m->host_bytes, cost.host_bytes);
CHECK_EQ(m->block_bytes, f.kv.plan(G_FULL)->layer_bytes_per_block());
CHECK_EQ(m->host_layer_stride, (f.cfg.max_seqs * (f.cfg.max_ctx / 16)) * m->block_bytes);
/* Zeroed at allocation: a miss copies these bytes to the ring before attention reads them. */
int64_t nonzero = 0;
for (int64_t i = 0; i < m->host_bytes; ++i) nonzero += m->host[i] != 0;
CHECK_EQ(nonzero, (int64_t)0);
CHECK_OK(f.kv.carve(f.pools.kv()));
RadStream st = nullptr;
REQUIRE_EQ(rad_stream_create(&st, 0), RAD_OK);
CHECK_OK(f.kv.init_stream(st));
CHECK_OK(rad_stream_sync(st));
/* The reset the reference contract states: both maps -1, state and control zero, in every
* layer's slice (the maps are device memory; read_stream_maps copies them back). */
const KVGroupPlan* p = f.kv.plan(G_FULL);
StreamMapsHost got;
CHECK_OK(read_stream_maps(*m, *p, st, &got));
rad_stream_destroy(st);
int64_t wrong = 0;
for (int64_t b = 0; b < (int64_t)got.res.size(); ++b) wrong += got.res[(size_t)b] != -1;
for (int64_t s = 0; s < (int64_t)got.slot_block.size(); ++s)
wrong += got.slot_block[(size_t)s] != -1;
for (int64_t i = 0; i < (int64_t)got.slot_state.size(); ++i)
wrong += got.slot_state[(size_t)i] != 0;
CHECK_EQ(wrong, (int64_t)0);
for (int i = 0; i < 16; ++i) CHECK_EQ(got.ctl[(size_t)i], 0);
CHECK_EQ(m->slots, p->pool_blocks());
CHECK(f.kv.stream_view(G_FULL) == m);
const KVManager::StreamStats stats = f.kv.stream_stats();
CHECK_EQ(stats.resident_blocks, p->pool_blocks());
/* Both tiers in one line, and the ring placed in the pool it was carved from. */
CHECK(f.kv.report().find("streaming:") != std::string::npos);
CHECK(f.kv.report().find("vram_kv") != std::string::npos);
CHECK(f.kv.report().find("pinned host memory") != std::string::npos);
f.kv.free_stream(rad_malloc_allocator());
CHECK(f.kv.stream_view(G_FULL) == nullptr);
CHECK(f.kv.stream_map(G_FULL) == nullptr || f.kv.stream_map(G_FULL)->host == nullptr);
f.kv.free_stream(rad_malloc_allocator()); /* teardown after a partial bring-up */
}
TEST(a_streamed_plans_maps_are_device_memory_read_back_on_its_stream) {
/* The maps are device memory (abi/rad_runtime.h, RadKVStream), and this case's job is to keep
* that rule visible: they are carved from the KV pool, so on a card the pool's elastic range is
* VRAM mapped into the address space and a host load of `res`, `slot_block`, `slot_state` or
* `ctl` faults -- the card-only segfault this suite used to have. The mirror is the only one of
* the four the host may read with a load. Their reset contents are
* `a_streamed_groups_maps_are_charged_before_the_pool_is_sized`'s job. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
CHECK_OK(configure_pools(f.pools, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64);
CHECK_OK(f.kv.plan_groups(hybrid_groups(), f.cfg));
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_OK(f.kv.carve(f.pools.kv()));
const KVManager::StreamMap* m = f.kv.stream_map(G_FULL);
REQUIRE(m != nullptr);
/* Every map array is a reservation of this pool, and the pool is what the card backs: the
* mirror is the only thing here the host may read with a load. */
const char* lo = (const char*)f.pools.kv().base();
const char* hi = lo + f.pools.kv().bytes();
CHECK((const char*)m->res >= lo && (const char*)m->res < hi);
CHECK(m->host < (const uint8_t*)lo || m->host >= (const uint8_t*)hi);
if (!device_is_host()) CHECK(rad_dev_host_ptr(m->res) == nullptr);
f.kv.free_stream(rad_malloc_allocator());
}
TEST(a_plan_that_does_not_stream_allocates_and_reports_nothing) {
/* The inert case every existing server runs: no cap_resident_tokens(), so stream_cost() is
* zero, alloc_stream() takes nothing, the ABI view is null (every group fully resident) and
* the report has no streaming line. */
Fixture f;
CHECK_OK(f.build());
const KVManager::StreamCost cost = f.kv.stream_cost();
CHECK_EQ(cost.groups, (int64_t)0);
CHECK_EQ(cost.host_bytes, (int64_t)0);
CHECK_EQ(cost.map_bytes, (int64_t)0);
const int64_t pool_used = f.pools.kv().used();
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_EQ(f.pools.kv().used(), pool_used);
CHECK(f.kv.stream_view(G_FULL) == nullptr);
CHECK(f.kv.stream_map(G_FULL) == nullptr);
const KVManager::StreamStats stats = f.kv.stream_stats();
CHECK_EQ(stats.resident_blocks, (int64_t)0);
CHECK(f.kv.report().find("streaming:") == std::string::npos);
f.kv.free_stream(rad_malloc_allocator());
CHECK_EQ(f.pools.kv().used(), pool_used);
}
TEST(a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing) {
/* --kv-resident is the whole switch (docs/KV-STREAMING.md §5 Phase 4): absent or 0 and nothing
* streams, and a ring that covers the group's context streams nothing either -- the ring is
* sized from --max-num-seqs and --max-model-len at startup, so such a group keeps the base
* engine's path exactly. Not "cheap": no mirror, no residency maps, no stage view and a null
* RadKVStream, so the batch hands the arch no stream and no kv_resolve can be issued (the
* issue sites test `kvb->stream`, arch/common/rad_block_attn_gated_fp8.h). */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2; /* context: 2 sequences x 1024 tokens */
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 128 B, as declare sets it */
const int64_t ctx_blocks = 2 * (1024 / 16); /* 128 blocks of 16 tokens */
/* A ring that covers the context. The group is bf16 here on purpose: a configuration that fits
* is never refused for a cache the streamed store has no row for, because nothing streams. */
f.cfg.kv_resident = 1024 * 2;
KVStreamSetup s;
CHECK_OK(kvstream_configure(f.cfg, 1024, groups, stream_program(groups[G_FULL], 513), &s));
CHECK_EQ(s.group, -1);
CHECK_EQ(s.asked_tokens, (int64_t)2048);
CHECK_EQ(s.ctx_blocks, ctx_blocks);
CHECK_EQ(s.ring_blocks, ctx_blocks);
CHECK_EQ(s.stage_blocks, (int64_t)0); /* no stage view is declared */
CHECK_EQ(s.group_name, std::string("full"));
/* And the engine applies that decision: configure_kv caps only a group that streams, so the
* manager is never told about a window, alloc_stream() takes nothing and the carve is the
* ordinary one-view pool. */
CHECK_OK(configure_pools(f.pools, f.cfg));
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
const KVManager::StreamCost cost = f.kv.stream_cost();
CHECK_EQ(cost.groups, (int64_t)0);
CHECK_EQ(cost.host_bytes, (int64_t)0);
CHECK_EQ(cost.map_bytes, (int64_t)0);
const int64_t pool_used = f.pools.kv().used();
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_EQ(f.pools.kv().used(), pool_used); /* no mirror and no maps were taken */
CHECK_OK(f.kv.carve(f.pools.kv()));
const KVGroupPlan* p = f.kv.plan(G_FULL);
CHECK_EQ(p->n_slots, p->n_blocks); /* every block has its own slot */
CHECK(!p->streamed());
CHECK_EQ(p->depth, (int64_t)0); /* the arch sees no stage view */
CHECK_EQ(f.kv.pool_bytes_carved(G_FULL), p->n_blocks * p->bytes_per_block);
CHECK(f.kv.stream_view(G_FULL) == nullptr); /* so no kv_resolve can be issued */
CHECK(f.kv.stream_map(G_FULL) == nullptr);
CHECK(f.kv.report().find("streaming:") == std::string::npos);
f.kv.free_stream(rad_malloc_allocator());
/* Absent (the parser's default) and 0 are the same: nothing is asked for, nothing is decided,
* nothing is capped. */
{
Fixture g;
g.cfg.checkpoint_slots = 0;
g.cfg.max_ctx = 1024;
g.cfg.max_seqs = 2;
g.cfg.kv_resident = 0;
KVStreamSetup o;
CHECK_OK(kvstream_configure(g.cfg, 1024, groups, stream_program(groups[G_FULL], 513), &o));
CHECK_EQ(o.group, -1);
CHECK_EQ(o.asked_tokens, (int64_t)0);
CHECK_EQ(o.ring_blocks, (int64_t)0);
CHECK_EQ(o.stage_blocks, (int64_t)0);
CHECK_OK(g.build_groups(groups));
CHECK_EQ(g.kv.stream_cost().groups, (int64_t)0);
CHECK(g.kv.stream_view(G_FULL) == nullptr);
CHECK(!g.kv.plan(G_FULL)->streamed());
CHECK_EQ(g.kv.plan(G_FULL)->depth, (int64_t)0);
}
}
TEST(a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring) {
/* The serial drafter's history pass is RAD_PHASE_DECODE, but after a prefill chunk it carries
* the chunk's tokens of every sequence: more rows a sequence than a decode step can select for
* (1 + n_spec). Its selection is the union of the histories it spans, not one row a selection,
* so it reads the one-layer stage -- identity-addressed over the whole context -- and cannot
* overflow the ring. A verify or a history pass over the verified window stays on the ring:
* routing those to the stage would stage every decode step. */
using rad::KVView;
CHECK(kv_pass_view(RAD_PHASE_PREFILL, 2048, 4, 3) == KVView::Stage);
CHECK(kv_pass_view(RAD_PHASE_MIXED, 900, 3, 3) == KVView::Stage);
/* The ring's passes: a verify step (4 rows a sequence with n_spec 3), one row a sequence, and
* the history pass that redoes the verified positions. */
CHECK(kv_pass_view(RAD_PHASE_DECODE, 16, 4, 3) == KVView::Ring);
CHECK(kv_pass_view(RAD_PHASE_DECODE, 4, 4, 3) == KVView::Ring);
CHECK(kv_pass_view(RAD_PHASE_DECODE, 12, 3, 3) == KVView::Ring);
CHECK(kv_pass_view(RAD_PHASE_DECODE, 4, 4, 0) == KVView::Ring);
/* The history pass over a prefill chunk, and every prefill-shaped decode pass. */
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2048, 4, 3) == KVView::Stage);
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2039, 3, 3) == KVView::Stage);
CHECK(kv_pass_view(RAD_PHASE_DECODE, 2048, 4, 0) == KVView::Stage);
}
TEST(a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling) {
/* Anything under the computed amount is ignored and pulled up to it. A within-(1 + n_spec)
* decode step takes the ring, not the stage (`kv_pass_view`), and issues one selection a row:
* max_seqs x (1 + n_spec) rows of at most `sel_pitch` blocks. A ring under that union is not a
* slower configuration but a request served from a selection table that no longer addresses
* the pool -- and the engine computes the union itself, so the flag takes it: one warning
* naming what was asked, what it became and why, and startup proceeds. The effective ring is
* the ceiling, which is what the carve must take. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2;
f.cfg.n_spec = 0;
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* the streamed store's one row */
groups[G_FULL].bytes_per_block = 2048; /* as declare sets it */
const int64_t sel_pitch = 8; /* a synthetic indexer's topk + 1 */
const int64_t ctx_blocks = 2 * (1024 / 16); /* 128 blocks of 16 tokens */
const Program prog = stream_program(groups[G_FULL], sel_pitch);
CHECK_OK(configure_pools(f.pools, f.cfg));
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
/* The ceiling is 2 sequences x 1 row x sel_pitch = 16 blocks = 256 tokens. */
f.cfg.kv_resident = 128; /* 8 blocks: half of it */
KVStreamSetup s;
const std::string log = stderr_of([&] {
/* The budget probe prices the ring the carve will take, both of them raised. */
CHECK_OK(kvstream_cap_probe(f.kv, f.cfg, prog, 1024));
CHECK_OK(kvstream_configure(f.cfg, 1024, groups, prog, &s));
});
CHECK(has(log, "--kv-resident 128 raised to 256 tokens"));
CHECK(has(log, "a decode step can name 16 blocks of 16 blocks each"));
CHECK(has(log, "(--max-num-seqs 2 x 1 for speculation x 8)"));
/* Raised, not refused: the flag is as the operator left it and the plan is the ceiling. */
CHECK_EQ(f.cfg.kv_resident, (int64_t)128);
CHECK_EQ(s.group, (int32_t)G_FULL);
CHECK_EQ(s.asked_tokens, (int64_t)128);
CHECK_EQ(s.raised_tokens, (int64_t)256);
CHECK_EQ(s.ring_blocks, (int64_t)16);
CHECK_EQ(s.ring_tokens, (int64_t)256);
CHECK_EQ(s.ctx_blocks, ctx_blocks);
CHECK_EQ(s.stage_blocks, ctx_blocks); /* one layer, the whole context */
/* The carve takes the ceiling, not the flag's 8 blocks: cap_resident_tokens is handed the
* raised ring, and the residency map, the pool and the resolve's slot ceiling are that depth. */
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_OK(f.kv.carve(f.pools.kv()));
const KVGroupPlan* p = f.kv.plan(G_FULL);
CHECK(p->streamed());
CHECK_EQ(p->n_blocks, ctx_blocks);
CHECK_EQ(p->n_slots, (int64_t)16); /* the ceiling */
CHECK_EQ(p->n_slots, s.ring_blocks);
CHECK_EQ(f.kv.stream_map(G_FULL)->slots, (int64_t)16);
CHECK_EQ(f.kv.stream_stats().resident_blocks, (int64_t)16);
/* And the startup report says so in the ring's own line, not only in the warning: the ring is
* no longer what the operator typed, and the report is what people read afterwards. */
KVStreamHostUse use;
kvstream_host_add(&use, f.kv);
const std::string rep = stderr_of([&] { kvstream_report(s, use, 1); });
CHECK(has(rep, "--kv-resident 128 became 256 tokens"));
CHECK(has(rep, "(8 -> 16 blocks of 16 tokens each)"));
CHECK(has(rep, "ring 16 blocks")); /* the staging line quotes the ring */
f.kv.free_stream(rad_malloc_allocator());
/* Under speculation a verify step runs the drafts beside the accepted position, so the rows --
* and the ceiling -- scale by 1 + n_spec: 2 x 4 x 8 = 64 blocks = 1024 tokens. */
{
Fixture g;
g.cfg.checkpoint_slots = 0;
g.cfg.max_ctx = 1024;
g.cfg.max_seqs = 2;
g.cfg.n_spec = 3;
g.cfg.kv_resident = 512; /* 32 blocks: enough without speculation */
KVStreamSetup o;
const std::string l = stderr_of([&] {
CHECK_OK(kvstream_configure(g.cfg, 1024, groups, prog, &o));
});
CHECK(has(l, "--kv-resident 512 raised to 1024 tokens"));
CHECK(has(l, "(--max-num-seqs 2 x 4 for speculation x 8)"));
CHECK_EQ(o.group, (int32_t)G_FULL);
CHECK_EQ(o.ring_blocks, (int64_t)64);
CHECK_EQ(o.raised_tokens, (int64_t)1024);
}
/* At the ceiling nothing is raised and the ring is the flag's own number. */
{
Fixture g;
g.cfg.checkpoint_slots = 0;
g.cfg.max_ctx = 1024;
g.cfg.max_seqs = 2;
g.cfg.n_spec = 3;
g.cfg.kv_resident = 1024; /* exactly 2 x 4 x 8 blocks of 16 */
KVStreamSetup o;
const std::string l = stderr_of([&] {
CHECK_OK(kvstream_configure(g.cfg, 1024, groups, prog, &o));
});
CHECK(!has(l, "raised"));
CHECK_EQ(o.raised_tokens, (int64_t)0);
CHECK_EQ(o.ring_blocks, (int64_t)64);
CHECK_EQ(o.ring_tokens, (int64_t)1024);
}
}
TEST(a_model_whose_architecture_declares_no_streamed_ops_ignores_the_flag) {
/* Fail safe (docs/KV-STREAMING.md §5 Phase 4): --kv-resident is only usable where the
* architecture plugin actually declared the streamed path. A streamed group's attention reads
* `sel`, which kv_resolve rewrites from block ids into ring slots; a plugin that never issues
* the resolve leaves block ids in `sel` while the attention treats them as pool pages -- past
* the ring, which is a fault or silent corruption rather than a slow path -- and without the
* streamed store nothing writes the host mirror, so a miss would read zeros. So the flag is
* ignored with one line, and the server runs exactly as if it had not been given. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2;
f.cfg.kv_resident = 256; /* 16 blocks against a 128-block context */
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].bytes_per_block = 2048; /* 16 tokens x 2 kv heads x 8 x 2 B x 2 layers */
const Program none =
stream_program(groups[G_FULL], 8, /*with_resolve=*/false, /*with_store=*/false);
KVStreamSetup s;
int st = RAD_OK;
const std::string log = stderr_of([&] { st = kvstream_configure(f.cfg, 1024, groups, none, &s); });
CHECK_OK(st); /* ignored, not refused */
CHECK_EQ(s.group, -1);
CHECK_EQ(s.asked_tokens, (int64_t)0); /* nothing is claimed, so nothing is reported */
CHECK_EQ(s.ring_blocks, (int64_t)0);
CHECK_EQ(s.stage_blocks, (int64_t)0);
CHECK(has(log, "ignored"));
CHECK(has(log, "test-arch")); /* the architecture, not just the group */
CHECK(has(log, "kv_resolve")); /* the op that is missing, by name */
CHECK(!has(log, "raised to")); /* that is the other message: this model cannot stream at all */
/* Half a path is no path: the resolve with no streamed store would leave the mirror unwritten
* and the miss list meaningless, so the warning names that op instead. */
KVStreamSetup half;
const std::string log2 = stderr_of([&] {
CHECK_OK(kvstream_configure(f.cfg, 1024, groups,
stream_program(groups[G_FULL], 8, true, false), &half));
});
CHECK_EQ(half.group, -1);
CHECK(has(log2, "kv_store_streamed"));
/* And the fail-safe never turns a working architecture off: the same configuration with both
* ops declared streams the ring it was sized for. */
KVStreamSetup ok;
CHECK_OK(kvstream_configure(f.cfg, 1024, groups, stream_program(groups[G_FULL], 8), &ok));
CHECK_EQ(ok.group, (int32_t)G_FULL);
CHECK_EQ(ok.ring_blocks, (int64_t)16);
CHECK_EQ(ok.stage_blocks, ok.ctx_blocks);
}
TEST(a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path) {
/* The other half of the fail-safe: "declared but unresolved" is not
* "absent". The builder always leaves at least one band -- resolve_bands synthesises a miss band
* with both domains null -- and records the op whether or not a row matched, so a declaration
* with no kernel is present in prog.ops and only its handle is null. Counting it as a streamed
* path would stream a group whose store never runs: the host mirror stays empty and a miss
* copies zeros out of it. Modelled the way the builder produces it: one band, no domain bound. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2;
f.cfg.kv_resident = 256; /* 16 blocks against a 128-block context */
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].decl.dtype = RAD_F8E4M3;
groups[G_FULL].bytes_per_block = 2048;
/* The resolve resolves; the store is declared with no row (both domains null). */
const Program unresolved = stream_program(groups[G_FULL], 8, true, true, /*store_resolved=*/false);
REQUIRE_EQ(unresolved.ops.size(), (size_t)2);
REQUIRE_EQ(unresolved.ops[1].bands.size(), (size_t)1);
CHECK(unresolved.ops[1].bands[0].dom[RAD_DOMAIN_DEVICE].row == nullptr);
const KVStreamOps ops = kvstream_ops(unresolved, &groups[G_FULL]);
CHECK(ops.resolve);
CHECK(!ops.store);
CHECK(!ops.folded);
CHECK(!ops.streams()); /* no writer, so no streamed path */
KVStreamSetup s;
int st = RAD_OK;
const std::string log =
stderr_of([&] { st = kvstream_configure(f.cfg, 1024, groups, unresolved, &s); });
CHECK_OK(st); /* ignored, not carved */
CHECK_EQ(s.group, -1);
CHECK_EQ(s.asked_tokens, (int64_t)0);
CHECK_EQ(s.ring_blocks, (int64_t)0);
CHECK_EQ(s.stage_blocks, (int64_t)0);
CHECK(has(log, "ignored"));
CHECK(has(log, "kv_store_streamed")); /* the op that is missing, by name */
}
TEST(a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed) {
/* --kv-cache-dtype fp8_v4 / k6_v4: the architecture declares the resolve and no streamed store,
* because libr4d's streamed rows are E4M3 and bf16 and a packed cache has base-store rows only
* (arch/common/rad_block_attn_gated_fp8.h). The group is declared to the core as plain E4M3, so
* no dtype gate downstream can see the layout: the operator has to be told the *layout* has no
* writer, not that the architecture cannot stream -- and the group must run the base path.
* Before this the op was declared against a table with no row for it, which is a weightless
* device hole: startup refused with or without --kv-resident, naming a kernel band and never the
* flag. */
for (const char* dtype : { "fp8_v4", "k6_v4" }) {
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2;
f.cfg.kv_resident = 256; /* 16 blocks against a 128-block context */
f.cfg.kv_cache_dtype = dtype;
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].decl.dtype = RAD_F8E4M3; /* what declare gives the core, packed or not */
groups[G_FULL].bytes_per_block = 2048;
/* What the gated plugin emits for a packed cache: the layout-blind resolve, no store. */
const Program packed = stream_program(groups[G_FULL], 8, true, /*with_store=*/false);
KVStreamSetup s;
int st = RAD_OK;
const std::string log = stderr_of([&] {
st = kvstream_configure(f.cfg, 1024, groups, packed, &s);
});
CHECK_OK(st); /* started, not refused */
CHECK_EQ(s.group, -1);
CHECK_EQ(s.asked_tokens, (int64_t)0);
CHECK_EQ(s.stage_blocks, (int64_t)0);
CHECK(has(log, "ignored"));
CHECK(has(log, std::string("group 'full' has a ") + dtype + " cache"));
CHECK(has(log, "has no writer for that layout (E4M3 and bf16 only)"));
CHECK(!has(log, "declares no")); /* not that sentence: the arch declared it */
CHECK(!has(log, "raised to")); /* and not the ring's */
}
}
TEST(a_resolve_declared_for_another_group_does_not_enable_streaming) {
/* The check is per group, not per program: the resolve states the layer-bytes pitch of the
* group it was emitted for, so one declared for a narrower full group cannot make streaming
* of the widest group look wired. That is the difference between "some group resolves" and
* "the group the plan streams resolves", and only the second is safe. */
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_ctx = 1024;
f.cfg.max_seqs = 2;
f.cfg.kv_resident = 256;
std::vector<KVGroupInfo> groups = hybrid_groups();
groups[G_FULL].bytes_per_block = 2048; /* 1024 B a layer */
Program other = stream_program(groups[G_FULL], 8);
other.ops[0].base.set_i("block_bytes", 4096); /* a wider group's pitch, not this one's */
KVStreamSetup s;
int st = RAD_OK;
const std::string log = stderr_of([&] { st = kvstream_configure(f.cfg, 1024, groups, other, &s); });
CHECK_OK(st);
CHECK_EQ(s.group, -1);
CHECK(has(log, "kv_resolve"));
}
TEST(kv_refuses_a_group_with_no_block_size) {
/* Block size comes from the resolved attention kernel; zero means it did not resolve, and the
* manager refuses rather than inventing one. */
@@ -6669,4 +7417,96 @@ TEST(a_tier_transfer_gives_back_every_event_and_device_byte) {
CHECK_EQ(vram1, vram0);
}
/* The streamed group's residency maps are reserved from the KV pool before the carve, so the
* budget probe must charge them before it sizes the pool. Left out, the pool it names is short by
* their bytes and the group that stays resident is carved below one full-length conversation --
* the target shape's `kv_qsa_bkey` at 47 185 of the 51 200 blocks it needed (188 740 tokens
* against --max-model-len 204800). The probe has no pool and cannot reserve them; the carve has
* already taken them. paged_split() charges them and carve_into() adds back what was reserved, so
* both paths see the same bytes (kvstream/carve.h). */
TEST(a_streamed_groups_maps_are_charged_before_the_pool_is_sized) {
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_seqs = 4;
f.cfg.max_ctx = 65536; /* the maps are more than the MiB rounding */
std::vector<KVGroupInfo> groups = hybrid_groups();
groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 4, { 6, 7 }));
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 256);
REQUIRE(need > 0);
f.cfg.vram_kv_mib = need;
CHECK_OK(configure_pools(f.pools, f.cfg));
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_OK(f.kv.carve(f.pools.kv()));
/* The group that stays resident holds one whole conversation, not the pool's remainder. */
const KVGroupPlan* bkey = f.kv.plan(3);
REQUIRE(bkey != nullptr);
CHECK(!bkey->streamed());
CHECK(bkey->n_blocks * bkey->block_size >= f.cfg.max_ctx);
}
/* A dense-read group is read over its whole live history every decode step, so it cannot stream.
* While a sibling does, its carve is a floor of max_seqs full contexts: the host mirror next to it
* is sized for max_seqs sequences, and an indexer funded for one makes the advertised capacity a
* promise the engine cannot keep. The probe sizes the pool for the floor before the carve spends
* it (kvstream/carve.h). */
TEST(a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams) {
Fixture f;
f.cfg.checkpoint_slots = 0;
f.cfg.max_seqs = 4;
f.cfg.max_ctx = 65536;
std::vector<KVGroupInfo> groups = hybrid_groups();
groups.push_back(paged_group("bkey", RAD_KV_FULL, 2, 4, { 6, 7 }));
groups.back().dense_read = true;
CHECK_OK(f.kv.plan_groups(groups, f.cfg));
f.kv.cap_resident_tokens(G_FULL, 64); /* four blocks of 16 tokens */
const int64_t need = f.kv.pool_mib_for_tokens(f.cfg.max_ctx, 512);
REQUIRE(need > 0);
f.cfg.vram_kv_mib = need;
CHECK_OK(configure_pools(f.pools, f.cfg));
CHECK_OK(f.kv.alloc_stream(rad_malloc_allocator(), f.pools.kv()));
CHECK_OK(f.kv.carve(f.pools.kv()));
const KVGroupPlan* bkey = f.kv.plan(3);
REQUIRE(bkey != nullptr);
CHECK(!bkey->streamed());
CHECK_EQ(bkey->n_blocks, f.cfg.max_seqs * ((f.cfg.max_ctx + 3) / 4));
CHECK_EQ(bkey->n_slots, bkey->n_blocks);
}
RAD_TEST_MAIN()
/* A streamed-only op exists only when the architecture's capability table says it can stream AND
* the deployment asked for a ring (core/kvstream/bringup.cpp, consulted from rad_op_declared). One
* binary serves both runs, so this is the only place the two questions meet; no model file carries
* the flag, and an architecture that cannot stream keeps the graph it had before streaming existed. */
TEST(a_streamed_op_exists_only_for_a_capable_architecture_and_a_ring) {
RadBuildCtx ctx{};
ctx.kv_stream_ok = 1;
ctx.kv_resident_blocks = 32768;
/* capable and asked: the ops declare as they always did */
CHECK(!kvstream_op_gated(ctx, "kv_store_streamed"));
CHECK(!kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store_streamed"));
CHECK(!kvstream_op_gated(ctx, "kv_resolve"));
/* nothing that works without a ring is ever gated */
CHECK(!kvstream_op_gated(ctx, "kv_store"));
CHECK(!kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store"));
CHECK(!kvstream_op_gated(ctx, "attn_paged"));
CHECK(!kvstream_op_gated(ctx, "qsa_select"));
CHECK(!kvstream_op_gated(ctx, nullptr));
/* no flag: the ops that exist only for a ring are gone */
ctx.kv_resident_blocks = 0;
CHECK(kvstream_op_gated(ctx, "kv_store_streamed"));
CHECK(kvstream_op_gated(ctx, "kv_resolve"));
CHECK(!kvstream_op_gated(ctx, "kv_store"));
/* an architecture with no streamed path declares none even when the flag asks */
ctx.kv_resident_blocks = 32768;
ctx.kv_stream_ok = 0;
CHECK(kvstream_op_gated(ctx, "kv_store_streamed"));
CHECK(kvstream_op_gated(ctx, "qk_norm_rope_gate_kv_store_streamed"));
CHECK(kvstream_op_gated(ctx, "kv_resolve"));
CHECK(!kvstream_op_gated(ctx, "kv_store"));
CHECK(!kvstream_op_gated(ctx, "attn_paged"));
}
+8 -4
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE]]
# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER]]]
#
# THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is
# installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers,
@@ -26,7 +26,11 @@
# has already checked what the out-of-tree build produced.
set -eu
B=$1; S=$2; W=$3
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}
HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}
# The tree's own C++ compiler, so the out-of-tree build does not depend on the host's default
# (`c++` may be a different GCC than the one the installed ABI headers require).
CCXX=""
[ -n "$CXXC" ] && CCXX="-DCMAKE_CXX_COMPILER=$CXXC"
GEN=${CMAKE_GENERATOR:-Ninja}
J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)}
@@ -64,8 +68,8 @@ is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; }
for d in $dirs; do
n=$(basename "$d")
say "building $d against the installed package"
extra=""
is_dev "$n" && extra="-DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
extra="$CCXX"
is_dev "$n" && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT
-DRAD_HIP_VOPD_REPEATABLE=$VOPD"
# A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's
# HIP compiler as a third party would pass theirs.
+2
View File
@@ -124,6 +124,8 @@ template <class T>
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
template <class T>
inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; }
template <class T>
inline T atomicExch(T* p, T v) { const T o = *p; *p = v; return o; }
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
typedef short emu_v8s __attribute__((ext_vector_type(8)));
+510
View File
@@ -0,0 +1,510 @@
/* tests/r4d_emu: kv_resolve (libr4d/r4d_kv_resolve.hip) on the host SIMT emulator, every operand
* held to a port of libref's ref_kv_resolve (libref/ref_kvstream.cpp) byte for byte: the rewritten
* selection, both residency maps, the slot epochs and heat counters, the control block, the mirror
* (untouched) and every byte of the ring.
*
* The fixtures are the shapes the claim list has to survive:
*
* - a partly resident pool, an eviction, a second chance: the ordinary decode call;
* - identity placement and its two exits: ids that fit the ring and take their own slot, an id
* whose slot is occupied by a different block (a clash, which walks from the hand without
* evicting), ids past the ring, and a full ring of clashes (which is CLOCK, unchanged);
* - 2052 claims (four rows of 513, what `--max-num-seqs 4` selects) and 8000 claims at a launch
* wide enough to derive a list of 8192 ids -- both above the fixed 2048-id list the kernel used
* to sort, so the claim path is what places them;
* - 12 claims into 8 slots: more claims than the ring holds, so the unplaceable ones revert
* through the selection and the overflow latch is set;
* - the two-bit heat counter: a slot hit twice surviving two sweep passes where the one-bit
* CLOCK would evict it, a saturated counter halving 3 -> 1 on a pass, and a saturated counter
* outlasting a slot that was only placed last call;
* - one bump a slot a call however many rows name it, which is the one place the device's
* `atomicExch` and a per-entry reference would part company;
* - 8200 claims at a launch whose bound (32 rows x 513) exceeds the workgroup's LDS room, so the
* list is narrower than the claim set and the kernel collects the smallest `slots` a window of
* the id space at a time. That is the path that replaced the `blocks`-sized map walk, and the
* slots must still be the same ones libref computes.
*
* A claim count is bounded by the launch's entries, `sum_q nsel[q] <= M * sel_pitch`, so every
* fixture's claim count is a number the kernel derives rather than one it assumes. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream);
namespace {
enum { kNOB = 0xEE };
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
t.shape[i] = shape[i];
t.stride[i] = st;
st *= shape[i];
}
return t;
}
/* Block `b`'s bytes: a pattern whose block digit is recoverable, so a copy that landed in the wrong
* slot shows up in the ring's bytes. */
uint8_t block_byte(int64_t b, int64_t i) { return (uint8_t)((29 * b + i) & 0xff); }
struct Fix {
int64_t M = 1, blocks = 1, slots = 1, pitch = 1, bbytes = 8;
std::vector<int32_t> sel, nsel, res, sblk, sst, ctl;
std::vector<uint8_t> host, pool;
/* A fresh pool: the maps say what is resident, a free slot holds the marker. */
void shape(int64_t M_, int64_t blocks_, int64_t slots_, int64_t pitch_, int64_t bbytes_) {
M = M_; blocks = blocks_; slots = slots_; pitch = pitch_; bbytes = bbytes_;
sel.assign((size_t)(M * pitch), -1);
nsel.assign((size_t)M, 0);
res.assign((size_t)blocks, -1);
sblk.assign((size_t)slots, -1);
sst.assign((size_t)(slots * 2), 0);
ctl.assign(16, 0);
host.assign((size_t)(blocks * bbytes), 0);
pool.assign((size_t)(slots * bbytes), (uint8_t)kNOB);
for (int64_t b = 0; b < blocks; ++b)
for (int64_t i = 0; i < bbytes; ++i) host[(size_t)(b * bbytes + i)] = block_byte(b, i);
}
/* Make slot `s` hold block `b`: the map and the bytes, as a resident block leaves them. */
void resident(int64_t s, int64_t b) {
sblk[(size_t)s] = (int32_t)b;
res[(size_t)b] = (int32_t)s;
for (int64_t i = 0; i < bbytes; ++i) pool[(size_t)(s * bbytes + i)] = block_byte(b, i);
}
};
/* The heat counter's two writes, copied from libref: a use bumps by one and saturates at 3, a
* sweep pass halves, and a negative value reads as cold. */
int32_t heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
int32_t heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; }
/* libref's ref_kv_resolve over a fixture, step for step (libref/ref_kvstream.cpp): the same epoch,
* the same one claim per distinct block, the same sorted miss list, the same free-slot-then-CLOCK
* sweep over the same two-bit heat counter, the same revert of what it could not place, the same
* copies and rewrite. The fixtures are legal calls, so the refusals are not repeated here. */
void ref_resolve(Fix& f) {
const int64_t M = f.M, blocks = f.blocks, slots = f.slots, pitch = f.pitch, bbytes = f.bbytes;
int32_t* const R = f.res.data();
int32_t* const SB = f.sblk.data();
int32_t* const ST = f.sst.data();
int32_t* const C = f.ctl.data();
const int64_t stp = 2;
std::vector<int64_t> off, ent;
for (int64_t q = 0; q < M; ++q)
for (int64_t i = 0; i < f.nsel[(size_t)q]; ++i) {
off.push_back(q * pitch + i);
ent.push_back(f.sel[(size_t)(q * pitch + i)]);
}
const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u);
std::vector<int32_t> miss;
for (size_t e = 0; e < ent.size(); ++e) {
const int32_t b = (int32_t)ent[e];
const int32_t s = R[b];
if (s >= 0) {
/* One bump a slot a call, not one an entry (libref's step 2). */
if (ST[(size_t)s * stp] != epoch) {
ST[(size_t)s * stp] = epoch;
ST[(size_t)s * stp + 1] = heat_up(ST[(size_t)s * stp + 1]);
}
} else if (s == -1) {
R[b] = -2;
miss.push_back(b);
}
}
const int64_t lookups = (int64_t)ent.size();
std::sort(miss.begin(), miss.end());
int64_t free_left = 0;
for (int64_t s = 0; s < slots; ++s)
if (SB[s] < 0 && ST[(size_t)s * stp] != epoch) ++free_left;
int64_t hand = C[1];
int64_t placed = 0;
bool overflow = false;
for (size_t k = 0; k < miss.size(); ++k) {
const int32_t b = miss[k];
int64_t victim = -1;
/* Identity first: the block's own slot if the id fits the ring and that slot is free (or
* already holds it), hand untouched (libref's step 4). */
if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b))
victim = b;
if (victim < 0 && free_left > 0) {
int64_t h = hand;
for (int64_t scanned = 0; scanned < slots; ++scanned) {
const int64_t s = h;
h = h + 1 == slots ? 0 : h + 1;
if (ST[(size_t)s * stp] == epoch) continue;
if (SB[s] >= 0) continue;
victim = s;
hand = h;
break;
}
if (victim < 0) free_left = 0;
}
if (victim < 0) {
for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) {
const int64_t s = hand;
hand = hand + 1 == slots ? 0 : hand + 1;
if (ST[(size_t)s * stp] == epoch) continue;
if (SB[s] >= 0 && ST[(size_t)s * stp + 1] > 0) {
ST[(size_t)s * stp + 1] = heat_down(ST[(size_t)s * stp + 1]);
continue;
}
victim = s;
break;
}
}
if (victim < 0) { overflow = true; break; }
if (SB[victim] < 0 && free_left > 0) --free_left;
if (SB[victim] >= 0) R[SB[victim]] = -1;
SB[victim] = b;
ST[(size_t)victim * stp] = epoch;
ST[(size_t)victim * stp + 1] = heat_up(ST[(size_t)victim * stp + 1]);
R[b] = (int32_t)victim;
++placed;
}
for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1;
for (int64_t k = 0; k < placed; ++k) {
const int32_t b = miss[(size_t)k];
std::memcpy(f.pool.data() + (int64_t)R[b] * bbytes, f.host.data() + (int64_t)b * bbytes,
(size_t)bbytes);
}
for (size_t e = 0; e < ent.size(); ++e) {
const int32_t s = R[ent[e]];
f.sel[(size_t)off[e]] = s >= 0 ? s : 0;
}
int64_t used = 0;
for (int64_t s = 0; s < slots; ++s)
if (ST[(size_t)s * stp] == epoch) ++used;
const int64_t uni = used + (int64_t)miss.size() - placed;
C[0] = epoch;
C[1] = (int32_t)hand;
C[2] = (int32_t)placed;
if (overflow) C[3] = 1;
if (uni > C[10]) C[10] = (int32_t)uni;
if (placed > C[11]) C[11] = (int32_t)placed;
if ((int64_t)miss.size() > C[12]) C[12] = (int32_t)miss.size();
uint64_t* const ctr = (uint64_t*)(C + 4);
ctr[0] += (uint64_t)placed;
ctr[1] += (uint64_t)lookups;
ctr[2] += 1u;
}
/* The device entry point over a fixture. Its scratch is the row's `next_pow2(slots)` miss-list ids
* (the list is sorted there when a launch is too wide for the shared claim list) then `slots`
* slots. */
int dev_resolve(Fix& f) {
int64_t nlist = 1;
while (nlist < f.slots) nlist <<= 1;
std::vector<int32_t> scratch((size_t)(nlist + f.slots), 0);
RadTensor t[8] = { tens(f.sel.data(), RAD_I32, { f.M, f.pitch }),
tens(f.nsel.data(), RAD_I32, { f.M }),
tens(f.res.data(), RAD_I32, { f.blocks }),
tens(f.sblk.data(), RAD_I32, { f.slots }),
tens(f.sst.data(), RAD_I32, { f.slots, 2 }),
tens(f.ctl.data(), RAD_I32, { 16 }),
tens(f.host.data(), RAD_U8, { f.blocks, f.bbytes }),
tens(f.pool.data(), RAD_U8, { f.slots, f.bbytes }) };
RadParam p[5]{};
p[0] = { "M", RAD_P_INT, f.M };
p[1] = { "blocks", RAD_P_INT, f.blocks };
p[2] = { "slots", RAD_P_INT, f.slots };
p[3] = { "sel_pitch", RAD_P_INT, f.pitch };
p[4] = { "block_bytes", RAD_P_INT, f.bbytes };
RadArgs a{};
a.t = t;
a.n_t = 8;
a.p = p;
a.n_p = 5;
a.scratch = scratch.data();
a.scratch_bytes = (int64_t)scratch.size() * 4;
return r4d_rad_kv_resolve(&a, nullptr);
}
size_t mismatch(const std::vector<int32_t>& a, const std::vector<int32_t>& b, const char* what,
const char* name) {
size_t bad = 0;
for (size_t i = 0; i < a.size(); ++i)
if (a[i] != b[i]) {
if (!bad)
std::printf(" FAIL %-42s %s[%zu]: %d, libref %d\n", name, what, i, a[i], b[i]);
++bad;
}
return bad;
}
size_t mismatch_bytes(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b,
const char* what, const char* name) {
size_t bad = 0;
for (size_t i = 0; i < a.size(); ++i)
if (a[i] != b[i]) {
if (!bad)
std::printf(" FAIL %-42s %s[%zu]: %u, libref %u\n", name, what, i, a[i], b[i]);
++bad;
}
return bad;
}
/* One fixture, both ways, every operand compared. */
int check(const char* name, Fix f) {
std::printf(" .. %s\n", name);
std::fflush(stdout);
Fix ref = f;
ref_resolve(ref);
const int rc = dev_resolve(f);
if (rc != RAD_OK) {
std::printf(" FAIL %-42s refused (%d)\n", name, rc);
return 1;
}
size_t bad = 0;
bad += mismatch(f.sel, ref.sel, "sel", name);
bad += mismatch(f.res, ref.res, "res", name);
bad += mismatch(f.sblk, ref.sblk, "slot_block", name);
bad += mismatch(f.sst, ref.sst, "slot_state", name);
bad += mismatch(f.ctl, ref.ctl, "ctl", name);
bad += mismatch_bytes(f.pool, ref.pool, "kv_cache", name);
bad += mismatch_bytes(f.host, ref.host, "host", name);
if (bad) return 1;
std::printf(" ok %-42s %lld claims, %lld placed\n", name, (long long)ref.ctl[12],
(long long)ref.ctl[2]);
return 0;
}
/* `n` distinct block ids across `M` rows of `pitch` entries, contiguously from `first`. Each row
* declares exactly the entries this fills, since `nsel` is what says an entry is valid -- and a
* declared entry holding -1 is a state fault, not padding. */
void fill_claims(Fix& f, int64_t first, int64_t n, int64_t per_row) {
int64_t k = 0;
for (int64_t q = 0; q < f.M; ++q) {
int64_t take = per_row;
if (take > n - k) take = n - k;
if (take < 0) take = 0;
f.nsel[(size_t)q] = (int32_t)take;
for (int64_t i = 0; i < take; ++i, ++k) f.sel[(size_t)(q * f.pitch + i)] = (int32_t)(first + k);
}
}
int run_all() {
int fails = 0, cases = 0;
++cases;
{
Fix f;
f.shape(2, 8, 4, 4, 8);
f.resident(0, 2);
f.resident(3, 5);
f.sel = { 2, 5, 6, -1, 2, 4, -1, -1 };
f.nsel = { 3, 2 };
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
fails += check("a decode call: two hits, two misses, ascending", f);
}
++cases;
{
/* Every slot resident and referenced: the sweep clears four bits and takes the slot the
* hand started on, one full turn later. */
Fix f;
f.shape(1, 8, 4, 2, 4);
for (int64_t s = 0; s < 4; ++s) f.resident(s, s + 4);
f.sel = { 0, 1 };
f.nsel = { 2 };
f.sst = { 0, 1, 0, 1, 0, 1, 0, 1 };
fails += check("second chance: a full ring clears and wraps", f);
}
++cases;
{
/* 2052 claims, the four-sequence decode shape, over the old 2048-claim list. */
Fix f;
f.shape(4, 4096, 2100, 513, 8);
fill_claims(f, 100, 2052, 513);
fails += check("2052 claims, every slot free", f);
}
++cases;
{
/* A launch wide enough that the list is 8192 ids (32 x 513 = 16416 is past the workgroup's
* LDS room), with 8000 claims: still inside the list, and far past 2048. */
Fix f;
f.shape(32, 12000, 8100, 513, 8);
fill_claims(f, 200, 8000, 250);
fails += check("8000 claims inside a derived 8192-id list", f);
}
++cases;
{
/* More claims than the ring: the eight smallest ids take the eight free slots, the rest
* revert through the selection and the overflow latches. */
Fix f;
f.shape(1, 4096, 8, 12, 8);
f.sel = { 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 };
f.nsel = { 12 };
fails += check("12 claims into 8 slots: the smallest eight", f);
}
++cases;
{
/* 8200 claims against a list of 8192: the launch's bound is past the workgroup's LDS room, so
* the kernel gathers the claims from the selection into the row's scratch and sorts them
* there. Same slots as libref's sort of all 8200, and no walk of `blocks`. */
Fix f;
f.shape(32, 12000, 8300, 513, 8);
fill_claims(f, 0, 8200, 257);
fails += check("8200 claims: sorted in the scratch above the list", f);
}
++cases;
{
/* Identity's two ways out in one call. Block 1's own slot holds block 6, so it is a clash
* and takes the first free slot after the hand (0) -- never an eviction. Block 2's slot is
* free, so it takes slot 2 even though the hand has moved to 1. */
Fix f;
f.shape(1, 12, 4, 4, 8);
f.resident(1, 6);
f.sel = { 1, 2, 8, -1 };
f.nsel = { 3 };
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
fails += check("identity clash falls back to a free slot, then identity again", f);
}
++cases;
{
/* Ids past the ring, the depth case: nothing can be identity, every miss walks from the
* hand exactly as before. */
Fix f;
f.shape(1, 16, 4, 5, 8);
f.sel = { 9, 10, 11, 12, 13 };
f.nsel = { 5 };
fails += check("ids past the ring: the old free-slot walk, unchanged", f);
}
++cases;
{
/* A full ring of clashing slots: identity has nowhere to go and CLOCK picks the victim the
* hand walks to, halving one counter on the way. */
Fix f;
f.shape(1, 12, 3, 2, 8);
f.resident(0, 5);
f.resident(1, 6);
f.resident(2, 7);
f.sel = { 0, 1 };
f.nsel = { 2 };
f.sst = { 0, 1, 0, 1, 0, 1 };
fails += check("identity clash on a full ring: CLOCK, unchanged", f);
}
++cases;
{
/* A ring wider than one thread's chunk with its free slots far from the hand: the sweep
* walks the chunk summaries (2100 slots is 3 a thread) and must still name the first free
* slot from the hand. Slots 0..2048 hold blocks, 2049 and 2050 are free, and the misses
* are ids past the ring, so identity cannot place them. */
Fix f;
f.shape(1, 6000, 2100, 3, 8);
for (int64_t s = 0; s < 2049; ++s) f.resident(s, s);
f.sel = { 4000, 4001, 4002 };
f.nsel = { 3 };
fails += check("free slots in the last chunk, hand at 0", f);
}
++cases;
{
/* The same ring with the hand past the free region: the walk wraps through the chunk
* summaries to slots 0 and 1, in that order, and leaves the hand at 2. */
Fix f;
f.shape(1, 6000, 2100, 3, 8);
for (int64_t s = 2; s < 2100; ++s) f.resident(s, s);
f.sel = { 4000, 4001, 4002 };
f.nsel = { 3 };
f.ctl[1] = 2099;
fails += check("free slots at slot 0, hand at the end: the walk wraps", f);
}
++cases;
{
/* Heat, the discriminating case: slot 0 was hit twice (counter 2), slots 1 and 2 once each.
* A one-bit CLOCK clears all three and evicts slot 0 on the second pass; the counter halves
* 2 -> 1 -> 0, so slot 0 survives two passes and slot 1 is the victim. Same inputs, a
* different slot -- which is exactly what this fixture exists to pin. */
Fix f;
f.shape(1, 32, 3, 1, 8);
f.resident(0, 10);
f.resident(1, 11);
f.resident(2, 12);
f.sst = { 0, 2, 0, 1, 0, 1 };
f.sel = { 20 };
f.nsel = { 1 };
fails += check("heat: a slot hit twice survives two passes, CLOCK would take it", f);
}
++cases;
{
/* The halving: a saturated 3 is 1 after one pass, not 0, and the cold slot behind it is the
* victim. A one-bit CLOCK clears slot 0 and evicts it. */
Fix f;
f.shape(1, 32, 3, 1, 8);
f.resident(0, 10);
f.resident(1, 11);
f.resident(2, 12);
f.sst = { 0, 3, 0, 0, 0, 0 };
f.sel = { 20 };
f.nsel = { 1 };
fails += check("heat: a saturated counter halves 3 -> 1 on one pass", f);
}
++cases;
{
/* A saturated counter outlasts a slot that was only placed last call: {3,1,1,1} walks two
* full laps, leaving the 3 at 1 then 0, and takes slot 1 (counter 1 -> 0 -> victim). Earning
* the same state from placements is what test/kvstream's multi-call case does. */
Fix f;
f.shape(1, 32, 4, 1, 8);
for (int64_t s = 0; s < 4; ++s) f.resident(s, 10 + s);
f.sst = { 0, 3, 0, 1, 0, 1, 0, 1 };
f.sel = { 20 };
f.nsel = { 1 };
fails += check("heat: a saturated counter outlasts a fresh placement", f);
}
++cases;
{
/* One bump a slot a call: block 10 is resident and named by both entries, so its counter
* gains one step (1 -> 2), not two. The device's first-stamp `atomicExch` and a per-entry
* reference would disagree here, which is why the fixture exists. */
Fix f;
f.shape(1, 32, 3, 2, 8);
f.resident(0, 10);
f.resident(1, 11);
f.resident(2, 12);
f.sst = { 0, 1, 0, 0, 0, 0 };
f.sel = { 10, 10 };
f.nsel = { 2 };
fails += check("heat: a block two entries name gains one step, not two", f);
}
++cases;
{
/* Every miss takes its own slot with a hit and a hand that is not at 0 in play: the
* identity fast path must leave the hand exactly where it was and still stamp its slots,
* because the fallback never runs. */
Fix f;
f.shape(1, 12, 8, 6, 8);
f.resident(3, 9); /* a resident block the selection does not name */
f.ctl[1] = 5;
f.sel = { 0, 2, 4, 6, 7 };
f.nsel = { 5 };
fails += check("identity for every miss, hand untouched", f);
}
std::printf("%d of %d fixtures match libref\n", cases - fails, cases);
return fails ? 1 : 0;
}
} /* namespace */
int main() {
const int fails = run_all();
return fails;
}
+597 -2
View File
@@ -987,10 +987,11 @@ TEST(op_vocabulary) {
/* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */
"lora_shrink", "lora_expand", "lora_expand_mm",
"grid_embed_aa",
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key",
"attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table",
"qk_norm_rope", "qsa_block_key",
/* The rest of the QSA indexer and DFlash2's convolution: not fusions, so a model that
* issues them has no other host path. */
"qsa_score", "qsa_select", "qsa_tail_store", "qsa_work", "dflash_conv",
"qsa_score", "qsa_select", "qsa_tail_store", "qsa_work", "kv_resolve", "dflash_conv",
"router_topk", "moe_scatter", "router_topk_scatter", "router_gemm_topk_scatter",
"moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather",
"row_topk",
@@ -3489,6 +3490,148 @@ TEST(op_kv_store_reads_the_row_stride_and_not_the_shape) {
CHECK_EQ(kv.at(12), 0.0f); CHECK_EQ(kv.at(15), 0.0f);
}
/* The E4M3 byte a value stores as. The mirror is a byte plane, so `T::at` on it reads the byte and
* not the value; comparing a mirror byte to a ring element needs the byte both sides are. */
static int e4m3_byte(float x) {
T t(RAD_F8E4M3, {1});
t.f({ x });
return (int)(uint8_t)t.mem[0];
}
/* kv_store_streamed: the group's host mirror is written for every token with a slot, and the ring
* slot only when the residency map says the block is resident. The two planes are the same paged
* layout, so a token's bytes land at the same offset in either.
*
* The case that decides the design: block 0 is NOT resident and block 1 is, and one token lands in
* each. Block 1's token must reach both copies (the ring's copy of a resident block would otherwise
* fall behind, and the resolve does not re-copy a resident block); block 0's must reach the mirror
* only, leaving the ring untouched until a resolve copies the whole block in. */
TEST(op_kv_store_streamed_writes_the_mirror_always_and_the_ring_when_resident) {
/* head_dim 2, one kv head, block_size 2: a block row is [kv_heads, block_size, 2 * head_dim]
* = 8 bytes, K then V inside a position. */
T k(RAD_BF16, {2, 1, 2}); k.f({ 1, 2, 5, 6 });
T v(RAD_BF16, {2, 1, 2}); v.f({ 3, 4, 7, 8 });
T sm(RAD_I32, {2}); sm.n({ 0, 3 }); /* block 0 offset 0, block 1 offset 1 */
T res(RAD_I32, {2}); res.n({ -1, 0 }); /* block 0 absent, block 1 in ring slot 0 */
T host(RAD_U8, {2, 8});
T kv(RAD_F8E4M3, {1, 1, 2, 4}); /* one ring slot, one block deep */
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 2).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "fp8_e4m3");
CHECK_OK(run("kv_store_streamed", a));
/* Token 0, block 0, position 0: K then V, mirror only. */
CHECK_EQ((int)host.at(0), e4m3_byte(1.0f)); CHECK_EQ((int)host.at(1), e4m3_byte(2.0f));
CHECK_EQ((int)host.at(2), e4m3_byte(3.0f)); CHECK_EQ((int)host.at(3), e4m3_byte(4.0f));
/* Token 1, block 1, position 1: both planes, at the same in-block offset, so the same bytes. */
CHECK_EQ((int)host.at(12), e4m3_byte(5.0f)); CHECK_EQ((int)host.at(13), e4m3_byte(6.0f));
CHECK_EQ((int)host.at(14), e4m3_byte(7.0f)); CHECK_EQ((int)host.at(15), e4m3_byte(8.0f));
CHECK_EQ((int)host.at(12), e4m3_byte(kv.at(4)));
CHECK_EQ((int)host.at(13), e4m3_byte(kv.at(5)));
CHECK_EQ((int)host.at(14), e4m3_byte(kv.at(6)));
CHECK_EQ((int)host.at(15), e4m3_byte(kv.at(7)));
/* Nothing else: block 0 has no slot, so its ring stays as it was, and block 1's position 0 is
* another token's. */
for (int i = 0; i < 4; ++i) CHECK_EQ(kv.at(i), 0.0f);
for (int i = 4; i < 12; ++i) CHECK_EQ(host.at(i), 0.0f);
}
/* The bf16 streamed store: both planes hold the values themselves, two bytes an element, exactly
* as kv_store_bf16 writes them. The descales are fp8-only, so a bf16 call with a non-1 k_scale
* still stores the value (this is the difference from the E4M3 row, and the reason the fused bf16
* fold passes the prologue's bf16 bytes straight through). */
TEST(op_kv_store_streamed_bf16_writes_the_values_into_both_planes) {
T k(RAD_BF16, {2, 1, 2}); k.f({ 1, 2, 5, 6 });
T v(RAD_BF16, {2, 1, 2}); v.f({ 3, 4, 7, 8 });
T sm(RAD_I32, {2}); sm.n({ 0, 3 }); /* block 0 offset 0, block 1 offset 1 */
T res(RAD_I32, {2}); res.n({ -1, 0 }); /* block 0 absent, block 1 in ring slot 0 */
T host(RAD_U8, {2, 16}); /* 1 kv head, 2 positions, 2*hd=4, bf16 */
T kv(RAD_BF16, {1, 1, 2, 4}); /* one ring slot, one block deep */
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 2).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "bf16").d("k_scale", 0.5).d("v_scale", 2.0);
CHECK_OK(run("kv_store_streamed", a));
auto at16 = [](const std::vector<uint8_t>& m, size_t i) {
return (unsigned)((unsigned)m[i] | ((unsigned)m[i + 1] << 8));
};
/* Token 0, block 0: mirror only, the values themselves. */
CHECK_EQ(at16(host.mem, 0), (unsigned)f32_to_bf16(1.0f));
CHECK_EQ(at16(host.mem, 2), (unsigned)f32_to_bf16(2.0f));
CHECK_EQ(at16(host.mem, 4), (unsigned)f32_to_bf16(3.0f));
CHECK_EQ(at16(host.mem, 6), (unsigned)f32_to_bf16(4.0f));
/* Token 1, block 1 position 1: both planes at the same in-block offset. */
CHECK_EQ(at16(host.mem, 24), (unsigned)f32_to_bf16(5.0f));
CHECK_EQ(at16(host.mem, 26), (unsigned)f32_to_bf16(6.0f));
CHECK_EQ(at16(host.mem, 28), (unsigned)f32_to_bf16(7.0f));
CHECK_EQ(at16(host.mem, 30), (unsigned)f32_to_bf16(8.0f));
for (size_t i = 0; i < 8; ++i) CHECK_EQ(kv.mem[i], 0); /* block 0 wrote no slot */
for (size_t i = 0; i < 8; ++i) CHECK_EQ((int)kv.mem[8 + i], (int)host.mem[24 + i]);
}
/* A block absent from the ring is written to the mirror alone, whatever the map holds: this is the
* state every token of a block's first step is in, and the resolve copies the whole block in. */
TEST(op_kv_store_streamed_a_block_with_no_slot_reaches_only_the_mirror) {
T k(RAD_BF16, {1, 1, 2}); k.f({ 2, 4 });
T v(RAD_BF16, {1, 1, 2}); v.f({ 6, 8 });
T sm(RAD_I32, {1}); sm.n({ 3 }); /* block 1, position 1 */
T res(RAD_I32, {2}); res.n({ -1, -1 });
T host(RAD_U8, {2, 8});
T kv(RAD_F8E4M3, {1, 1, 2, 4});
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "fp8_e4m3").
d("k_scale", 0.5).d("v_scale", 2.0); /* the store divides by the reader's descal */
CHECK_OK(run("kv_store_streamed", a));
CHECK_EQ((int)host.at(12), e4m3_byte(4.0f)); CHECK_EQ((int)host.at(13), e4m3_byte(8.0f));
CHECK_EQ((int)host.at(14), e4m3_byte(3.0f)); CHECK_EQ((int)host.at(15), e4m3_byte(4.0f));
for (int i = 0; i < 4; ++i) CHECK_EQ(kv.at(i), 0.0f); /* the ring is untouched */
}
/* The refusals libref makes before its first write: a slot naming a block past the mirror, a
* residency entry outside [-1, slots), and a mirror row wider than the block. Nothing is written on
* any of them - a half-written mirror is what the next step's copies would believe. */
TEST(op_kv_store_streamed_refuses_a_state_fault_before_writing) {
T k(RAD_BF16, {1, 1, 2}); k.f({ 1, 2 });
T v(RAD_BF16, {1, 1, 2}); v.f({ 3, 4 });
/* A map entry naming a slot the ring does not have. */
{
T sm(RAD_I32, {1}); sm.n({ 0 });
T res(RAD_I32, {2}); res.n({ 1, -1 }); /* slot 1 of a one-slot ring */
T host(RAD_U8, {2, 8});
T kv(RAD_F8E4M3, {1, 1, 2, 4});
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "fp8_e4m3");
CHECK_EQ(run("kv_store_streamed", a), RAD_E_INVAL);
for (int i = 0; i < 8; ++i) CHECK_EQ(host.at(i), 0.0f);
}
/* A slot naming a block past the mirror's extent. */
{
T sm(RAD_I32, {1}); sm.n({ 4 }); /* block 2 of a two-block mirror */
T res(RAD_I32, {2}); res.n({ -1, -1 });
T host(RAD_U8, {2, 8});
T kv(RAD_F8E4M3, {1, 1, 2, 4});
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "fp8_e4m3");
CHECK_EQ(run("kv_store_streamed", a), RAD_E_SHAPE);
for (int i = 0; i < 8; ++i) CHECK_EQ(host.at(i), 0.0f);
}
/* A mirror row that is not the block's byte pitch: a copy into it would spill over the next
* block. */
{
T sm(RAD_I32, {1}); sm.n({ 0 });
T res(RAD_I32, {2}); res.n({ -1, -1 });
T host(RAD_U8, {2, 8});
host.t.stride[0] = 12; /* a padded row */
T kv(RAD_F8E4M3, {1, 1, 2, 4});
A a; a.t(k).t(v).t(sm).t(kv).t(res).t(host)
.i("M", 1).i("head_dim", 2).i("n_head_kv", 1).i("block_size", 2)
.s("kv_dtype", "fp8_e4m3");
CHECK_EQ(run("kv_store_streamed", a), RAD_E_STRIDE);
}
}
TEST(op_rope) {
/* head_dim 2 means one rotary pair with inv_freq 1, so the angle is the position itself. */
T qkv(RAD_F32, {1, 6}); qkv.f({1, 0, 1, 0, 9, 9}); /* q, k, v */
@@ -7625,6 +7768,453 @@ TEST(qsa_select_orders_above_then_ties_and_appends_the_partial_page) {
CHECK_EQ(r.su[0], 1LL * 4 + 3 + 1);
}
/* ================================================================== kv_resolve
* The residency map of a streamed group: selected block ids in, ring slots out, a block copied in
* from the host mirror when it is not resident (docs/OPS.md "kv_resolve",
* docs/KV-STREAMING.md §3.4). */
namespace {
/* One pool's worth of state. A block's bytes in the mirror are `10 * b + i` for i < block_bytes, so
* a copied block is recognisable byte by byte; a slot nothing wrote holds NOB (a marker, not a
* block's bytes). */
enum { kKvNob = 0xEE };
struct KVF {
const int64_t M, blocks, slots, pitch, bbytes;
T sel, nsel, res, sblk, sst, ctl, host, pool;
KVF(int64_t M_, int64_t blocks_, int64_t slots_, int64_t pitch_, int64_t bbytes_)
: M(M_), blocks(blocks_), slots(slots_), pitch(pitch_), bbytes(bbytes_),
sel(RAD_I32, {M, pitch}), nsel(RAD_I32, {M}), res(RAD_I32, {blocks_}),
sblk(RAD_I32, {slots_}), sst(RAD_I32, {slots_, 2}), ctl(RAD_I32, {16}),
host(RAD_U8, {blocks_, bbytes_}), pool(RAD_U8, {slots_, bbytes_}) {}
void fill_host() {
for (int64_t b = 0; b < blocks; ++b)
for (int64_t i = 0; i < bbytes; ++i)
host.mem[(size_t)(b * bbytes + i)] = (uint8_t)(10 * b + i);
}
/* The pool as a resident block leaves it, and a slot no block occupies. */
void put(int64_t s, int64_t b) {
for (int64_t i = 0; i < bbytes; ++i)
pool.mem[(size_t)(s * bbytes + i)] = (uint8_t)(10 * b + i);
}
void clear_slot(int64_t s) {
for (int64_t i = 0; i < bbytes; ++i) pool.mem[(size_t)(s * bbytes + i)] = (uint8_t)kKvNob;
}
int call() {
A a; a.t(sel).t(nsel).t(res).t(sblk).t(sst).t(ctl).t(host).t(pool)
.i("M", M).i("blocks", blocks).i("slots", slots).i("sel_pitch", pitch)
.i("block_bytes", bbytes);
return run("kv_resolve", a);
}
int64_t slot(int64_t s, int64_t i) const { return pool.mem[(size_t)(s * bbytes + i)]; }
};
/* A slot's bytes are block b's, from the mirror. */
#define CHECK_SLOT_HOLDS(F, S, B) \
for (int64_t i_ = 0; i_ < (F).bbytes; ++i_) \
CHECK_EQ((F).slot((S), i_), (int64_t)(uint8_t)(10 * (B) + i_))
/* A whole int operand, element by element, against the values on paper. */
#define CHECK_ENTRIES(T, ...) \
do { \
const std::vector<int64_t> want_ = { __VA_ARGS__ }; \
REQUIRE_EQ((int64_t)want_.size(), numel(&(T).t)); \
for (size_t i_ = 0; i_ < want_.size(); ++i_) CHECK_EQ((T).iat((int64_t)i_), want_[i_]); \
} while (0)
} /* namespace */
/* Blocks 2 and 5 are resident; the selection names them (hits), then 6 and 4 (misses). The epoch
* reaches the hit slots, the two misses are claimed once each and placed in ascending block order
* (4 then 6) - not the order the rows name them - and the copies land in the mirror's bytes. */
TEST(kv_resolve_hits_take_the_epoch_and_misses_are_placed_in_block_order) {
KVF f(2, 8, 4, 4, 8);
f.fill_host();
f.put(0, 2); f.put(3, 5); f.clear_slot(1); f.clear_slot(2);
f.res.n({ -1, -1, 0, -1, -1, 3, -1, -1 });
f.sblk.n({ 2, -1, -1, 5 });
f.sst.n({ 0, 1, 0, 0, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 2, 5, 6, -1, 2, 4, -1, -1 });
f.nsel.n({ 3, 2 });
REQUIRE_EQ(f.call(), RAD_OK);
/* Block 6 came after block 4 in the selection, and still lands after it: ascending block id. */
CHECK_ENTRIES(f.res, -1, -1, 0, -1, 1, 3, 2, -1);
CHECK_ENTRIES(f.sblk, 2, 4, 6, 5);
/* Slot 0 was referenced already (counter 1), so its use takes it to 2; slot 3's block was
* resident but cold, as the two placements are, so they land at 1. That is the counter doing
* its job on a normal decode call. */
CHECK_ENTRIES(f.sst, 1, 2, 1, 1, 1, 1, 1, 1);
CHECK_ENTRIES(f.sel, 0, 3, 2, -1, 0, 1, -1, -1);
CHECK_SLOT_HOLDS(f, 0, 2);
CHECK_SLOT_HOLDS(f, 1, 4);
CHECK_SLOT_HOLDS(f, 2, 6);
CHECK_SLOT_HOLDS(f, 3, 5);
CHECK_EQ(f.ctl.iat(0), 1); /* epoch */
CHECK_EQ(f.ctl.iat(1), 3); /* hand, just past the last slot taken */
CHECK_EQ(f.ctl.iat(2), 2); /* placed */
CHECK_EQ(f.ctl.iat(3), 0); /* no overflow */
CHECK_EQ(f.ctl.iat(4), 2); /* u64 misses */
CHECK_EQ(f.ctl.iat(6), 5); /* u64 lookups: 3 + 2 entries, one each */
CHECK_EQ(f.ctl.iat(8), 1); /* u64 calls */
}
/* An unreferenced resident slot is the victim, and the block it held leaves the map: the sweep
* re-points both maps, so a block that is no longer anywhere resident reads as -1. */
TEST(kv_resolve_evicts_an_unreferenced_slot_and_unmaps_its_block) {
KVF f(1, 8, 4, 1, 4);
f.fill_host();
for (int64_t s = 0; s < 4; ++s) f.put(s, s + 1);
f.res.n({ -1, 0, 1, 2, 3, -1, -1, -1 });
f.sblk.n({ 1, 2, 3, 4 });
f.sst.n({ 0, 1, 0, 0, 0, 1, 0, 0 }); /* slot 1's block is unreferenced */
f.ctl.n({ 0, 1, 0, 0 }); /* the hand starts on slot 1 */
f.sel.n({ 0 });
f.nsel.n({ 1 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, 1, 0, -1, 2, 3, -1, -1, -1);
CHECK_ENTRIES(f.sblk, 1, 0, 3, 4);
CHECK_ENTRIES(f.sst, 0, 1, 1, 1, 0, 1, 0, 0);
CHECK_ENTRIES(f.sel, 1);
CHECK_SLOT_HOLDS(f, 1, 0);
CHECK_EQ(f.ctl.iat(1), 2);
CHECK_EQ(f.ctl.iat(2), 1);
}
/* A free slot is claimed before any live block is evicted, even when the hand starts on an
* unreferenced resident slot: the ring's empty region is not a victim. The block in that slot
* stays resident, its map entry and its heat counter untouched. */
TEST(kv_resolve_takes_a_free_slot_before_an_unreferenced_one) {
KVF f(1, 8, 4, 1, 4);
f.fill_host();
f.put(0, 3);
f.res.n({ -1, -1, -1, 0, -1, -1, -1, -1 });
f.sblk.n({ 3, -1, -1, -1 });
f.sst.n({ 0, 0, 0, 0, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 }); /* the hand starts on the resident slot */
f.sel.n({ 0 });
f.nsel.n({ 1 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, 1, -1, -1, 0, -1, -1, -1, -1);
CHECK_ENTRIES(f.sblk, 3, 0, -1, -1);
CHECK_ENTRIES(f.sst, 0, 0, 1, 1, 0, 0, 0, 0); /* slot 0 never went through CLOCK */
CHECK_ENTRIES(f.sel, 1);
CHECK_SLOT_HOLDS(f, 1, 0);
CHECK_SLOT_HOLDS(f, 0, 3); /* block 3 was not evicted */
CHECK_EQ(f.ctl.iat(1), 2); /* hand just past the slot taken */
CHECK_EQ(f.ctl.iat(2), 1);
}
/* A block whose id fits the ring and whose own slot is free takes that slot, not the hand's: the
* map stays res[b] = b while the context is shorter than the ring, which is the layout that makes
* the attention's gather of adjacent ids sequential inside one layer's stripe. Identity does not
* move the hand, so ctl[1] is still where the call found it. */
TEST(kv_resolve_places_a_block_in_its_own_slot_when_that_slot_is_free) {
KVF f(1, 12, 8, 4, 4);
f.fill_host();
f.res.n({ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 });
f.sblk.n({ -1, -1, -1, -1, -1, -1, -1, -1 });
f.sst.n({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 6, 3, 7, 3 });
f.nsel.n({ 4 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, -1, -1, -1, 3, -1, -1, 6, 7, -1, -1, -1, -1);
CHECK_ENTRIES(f.sblk, -1, -1, -1, 3, -1, -1, 6, 7);
CHECK_ENTRIES(f.sel, 6, 3, 7, 3);
CHECK_SLOT_HOLDS(f, 3, 3);
CHECK_SLOT_HOLDS(f, 6, 6);
CHECK_SLOT_HOLDS(f, 7, 7);
CHECK_EQ(f.ctl.iat(1), 0); /* identity never moves the hand */
CHECK_EQ(f.ctl.iat(2), 3);
}
/* A clash is not an eviction. Block 3's own slot holds block 5, so the placement is the ordinary
* free-slot walk from the hand -- slot 0 here -- and block 5 stays resident and referenced. Block
* 4's slot is free and takes it even though the hand has moved past it. */
TEST(kv_resolve_own_slot_occupied_falls_back_to_a_free_slot) {
KVF f(1, 12, 8, 3, 4);
f.fill_host();
f.put(3, 5);
f.res.n({ -1, -1, -1, -1, -1, 3, -1, -1, -1, -1, -1, -1 });
f.sblk.n({ -1, -1, -1, 5, -1, -1, -1, -1 });
f.sst.n({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 3, 4, -1 });
f.nsel.n({ 2 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, -1, -1, -1, 0, 4, 3, -1, -1, -1, -1, -1, -1);
CHECK_ENTRIES(f.sblk, 3, -1, -1, 5, 4, -1, -1, -1);
CHECK_ENTRIES(f.sel, 0, 4, -1);
CHECK_SLOT_HOLDS(f, 0, 3);
CHECK_SLOT_HOLDS(f, 4, 4);
CHECK_SLOT_HOLDS(f, 3, 5);
CHECK_EQ(f.ctl.iat(1), 1); /* only the fallback moved it */
CHECK_EQ(f.ctl.iat(2), 2);
}
/* Second chance: every slot is referenced, so the hand clears all four bits and the miss takes the
* slot it started on, one full turn later. The bit it passed stays cleared. */
TEST(kv_resolve_gives_a_referenced_slot_a_second_chance) {
KVF f(1, 8, 4, 2, 4);
f.fill_host();
for (int64_t s = 0; s < 4; ++s) f.put(s, s + 4);
f.res.n({ -1, -1, -1, -1, 0, 1, 2, 3 });
f.sblk.n({ 4, 5, 6, 7 });
f.sst.n({ 0, 1, 0, 1, 0, 1, 0, 1 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 0, 1 });
f.nsel.n({ 2 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, 0, 1, -1, -1, -1, -1, 2, 3);
CHECK_ENTRIES(f.sblk, 0, 1, 6, 7);
CHECK_ENTRIES(f.sst, 1, 1, 1, 1, 0, 0, 0, 0); /* 2 and 3 lost their second chance */
CHECK_ENTRIES(f.sel, 0, 1);
CHECK_SLOT_HOLDS(f, 0, 0);
CHECK_SLOT_HOLDS(f, 1, 1);
CHECK_SLOT_HOLDS(f, 2, 6); /* untouched: still block 6 */
CHECK_EQ(f.ctl.iat(1), 2);
}
/* The heat counter is what makes this different from a one-bit CLOCK: slot 0 was hit on two
* earlier calls (counter 2), slots 1 and 2 once each. A CLOCK sweep would clear all three bits and
* evict slot 0 on the second pass; the counter halves 2 -> 1 -> 0, so slot 0 survives two passes and
* slot 1, whose single step of heat the first pass spends, is the victim. Same inputs, a different
* slot: the fixture is here to pin the policy and not only agreement between two implementations. */
TEST(kv_resolve_a_slot_hit_twice_survives_two_sweep_passes) {
KVF f(1, 32, 3, 1, 8);
f.fill_host();
for (int64_t s = 0; s < 3; ++s) f.put(s, 10 + s);
f.res.n({-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1});
f.sblk.n({ 10, 11, 12 });
f.sst.n({ 0, 2, 0, 1, 0, 1 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 20 });
f.nsel.n({ 1 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.sblk, 10, 20, 12); /* slot 0, the hot one, was not the victim */
/* The sweep writes only the counter; the epoch column is what a hit or a placement stamps, so
* slots 0 and 2 keep the 0 they entered with. */
CHECK_ENTRIES(f.sst, 0, 0, 1, 1, 0, 0);
CHECK_ENTRIES(f.sel, 1);
CHECK_EQ(f.ctl.iat(1), 2);
CHECK_EQ(f.ctl.iat(2), 1);
}
/* The halving sequence, across three calls, with the hand put back on slot 0 so each call passes
* the hot slot once -- the same visits a hand that wraps once gives it. A saturated 3 is 1 after one
* pass (a one-bit CLOCK would have cleared it to 0, and the next call would evict it), 1 is 0 after
* the second, and only the third pass takes the slot. Each step is checked, because the whole of the
* policy is the difference between 1 and 0 here. */
TEST(kv_resolve_halves_a_saturated_counter_three_to_one_to_zero) {
KVF f(1, 32, 3, 1, 8);
f.fill_host();
for (int64_t s = 0; s < 3; ++s) f.put(s, 10 + s);
f.res.n({-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1});
f.sblk.n({ 10, 11, 12 });
f.sst.n({ 0, 3, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 20 });
f.nsel.n({ 1 });
REQUIRE_EQ(f.call(), RAD_OK);
/* 3 -> 1: the pass cost it one halving, not the whole counter. Slot 1 (cold) was the victim. */
CHECK_ENTRIES(f.sblk, 10, 20, 12);
CHECK_ENTRIES(f.sst, 0, 1, 1, 1, 0, 0);
f.sel.n({ 21 });
((int32_t*)f.ctl.t.data)[1] = 0; /* the hand back on slot 0, the epoch untouched */
REQUIRE_EQ(f.call(), RAD_OK);
/* 1 -> 0: slot 0 passed again and is still resident; slot 2 (cold) is the victim. */
CHECK_ENTRIES(f.sblk, 10, 20, 21);
CHECK_ENTRIES(f.sst, 0, 0, 1, 0, 2, 1);
f.sel.n({ 22 });
((int32_t*)f.ctl.t.data)[1] = 0;
REQUIRE_EQ(f.call(), RAD_OK);
/* 0: the third visit takes it. */
CHECK_ENTRIES(f.sblk, 22, 20, 21);
CHECK_ENTRIES(f.sst, 3, 1, 1, 0, 2, 1);
CHECK_EQ(f.res.iat(10), -1); /* evicted on the third pass */
CHECK_EQ(f.res.iat(20), 1);
CHECK_EQ(f.res.iat(21), 2);
CHECK_EQ(f.res.iat(22), 0);
}
/* A saturated counter and a slot placed on the previous call differ by two steps of heat, and the
* sweep spends the fresh one first: {3,1,1,1} walks two full laps, leaving the 3 at 1 then 0 and
* taking slot 1. A one-bit CLOCK, for which all four are "referenced", evicts slot 0 -- the hottest
* block in the ring. */
TEST(kv_resolve_a_saturated_counter_outlasts_a_fresh_placement) {
KVF f(1, 32, 4, 1, 8);
f.fill_host();
for (int64_t s = 0; s < 4; ++s) f.put(s, 10 + s);
f.res.n({-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1});
f.sblk.n({ 10, 11, 12, 13 });
f.sst.n({ 0, 3, 0, 1, 0, 1, 0, 1 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 20 });
f.nsel.n({ 1 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.sblk, 10, 20, 12, 13);
CHECK_ENTRIES(f.sst, 0, 0, 1, 1, 0, 0, 0, 0);
CHECK_EQ(f.ctl.iat(1), 2);
}
/* One bump a slot a call, not one an entry: block 10 is resident and named by both entries, so its
* counter goes 1 -> 2 rather than 1 -> 3. The device kernel counts the first thread to stamp a slot
* (`atomicExch`), so a per-entry bump in the reference would be a real disagreement, not a detail. */
TEST(kv_resolve_counts_one_bump_a_slot_a_call) {
KVF f(1, 32, 3, 2, 8);
f.fill_host();
for (int64_t s = 0; s < 3; ++s) f.put(s, 10 + s);
f.res.n({-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1});
f.sblk.n({ 10, 11, 12 });
f.sst.n({ 0, 1, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 10, 10 });
f.nsel.n({ 2 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.sst, 1, 2, 0, 0, 0, 0);
CHECK_ENTRIES(f.sel, 0, 0);
CHECK_EQ(f.ctl.iat(2), 0);
}
/* Overflow: three hits hold slots 0..2 and two misses want the one slot left. The first is placed,
* the second has nowhere and must NOT steal the slot the first took (every slot of the ring is
* marked with this call's epoch, so the sweep passes it), nor any hit's. ctl[3] latches, the
* unplaced block reverts to -1, and its selection entry is rewritten to slot 0: leaving the block id
* would make a device attention dereference an address past the ring, and ctl[3] is what says the
* table is unusable. */
TEST(kv_resolve_overflow_latches_instead_of_taking_a_slot_it_just_filled) {
KVF f(1, 8, 4, 5, 4);
f.fill_host();
for (int64_t s = 0; s < 3; ++s) f.put(s, s);
f.clear_slot(3);
f.res.n({ 0, 1, 2, -1, -1, -1, -1, -1 });
f.sblk.n({ 0, 1, 2, -1 });
f.sst.n({ 0, 1, 0, 1, 0, 1, 0, 0 });
f.ctl.n({ 0, 3, 0, 0 }); /* the hand starts on the one free slot */
f.sel.n({ 6, 7, 0, 1, 2 });
f.nsel.n({ 5 });
REQUIRE_EQ(f.call(), RAD_OK);
CHECK_ENTRIES(f.res, 0, 1, 2, -1, -1, -1, 3, -1);
CHECK_ENTRIES(f.sblk, 0, 1, 2, 6);
CHECK_ENTRIES(f.sst, 1, 2, 1, 2, 1, 2, 1, 1); /* three hits on referenced slots, one placement */
/* Entry 1 is block 7, unplaced: it names slot 0, a defined address inside the ring, and ctl[3]
* below is what marks the table unusable. */
CHECK_ENTRIES(f.sel, 3, 0, 0, 1, 2);
CHECK_SLOT_HOLDS(f, 3, 6); /* the second miss did not overwrite the first */
CHECK_SLOT_HOLDS(f, 0, 0);
CHECK_EQ(f.ctl.iat(2), 1);
CHECK_EQ(f.ctl.iat(3), 1); /* overflow, latched */
CHECK_EQ(f.ctl.iat(4), 1);
CHECK_EQ(f.ctl.iat(6), 5);
}
/* A launch's claim count is derived from its own operands, never a constant: one claim is one
* distinct absent block a selection entry names, so a launch makes at most `M * sel_pitch` of them
* -- 2052 for four rows of 513, which is what `--max-num-seqs 4` selects -- and the miss list has to
* hold every one of them. This runs the same fixture at 2048 and at 2052 claims and holds the wider
* launch to the narrower one's placement: every block the two share lands in the same slot, so the
* launch above the old fixed list is not a different placement, and ctl[12] reports the depth the
* list had to hold. */
TEST(kv_resolve_places_2052_claims_exactly_as_it_places_2048) {
const int64_t bbytes = 8, blocks = 4096, pitch = 513, M = 4, slots = 2100, first = 100;
/* Every slot free: ids below the ring take their own slot, and the ids past it walk the free
* slots from the hand. */
auto launch = [&](int64_t per_row) {
KVF f(M, blocks, slots, pitch, bbytes);
f.fill_host();
std::vector<int64_t> sel((size_t)(M * pitch), -1), nsel((size_t)M, per_row);
for (int64_t q = 0; q < M; ++q)
for (int64_t i = 0; i < per_row; ++i)
sel[(size_t)(q * pitch + i)] = first + q * per_row + i;
f.sel.n(sel);
f.nsel.n(nsel);
f.res.n(std::vector<int64_t>((size_t)blocks, -1));
f.sblk.n(std::vector<int64_t>((size_t)slots, -1));
f.sst.n(std::vector<int64_t>((size_t)(slots * 2), 0));
f.ctl.n(std::vector<int64_t>(16, 0));
CHECK_EQ(f.call(), RAD_OK);
return f;
};
KVF small = launch(512); /* 4 x 512 = 2048 claims */
KVF large = launch(513); /* 4 x 513 = 2052 claims */
/* 2052 claims are all placed, ascending from the first, and the counters say so. Identity
* covers every id below the ring: block `first + k` takes slot `first + k`. The 52 ids past
* `slots` (2100..2151) fall back to the first free slots after the hand, which is still 0. */
for (int64_t k = 0; k < 2000; ++k) { /* ids first .. slots - 1 */
CHECK_EQ(large.res.iat(first + k), first + k);
CHECK_EQ(large.sblk.iat(first + k), first + k);
}
for (int64_t j = 0; j < 52; ++j) { /* ids slots .. first + 2051 */
CHECK_EQ(large.res.iat(slots + j), j);
CHECK_EQ(large.sblk.iat(j), slots + j);
}
CHECK_EQ(large.ctl.iat(12), 2052); /* the claim list's depth */
CHECK_EQ(large.ctl.iat(10), 2052); /* every claim is a miss: no block was resident */
CHECK_EQ(large.ctl.iat(2), 2052);
CHECK_EQ(large.ctl.iat(1), 52); /* identity never moves the hand: 52 fallbacks did */
CHECK_EQ(large.ctl.iat(3), 0);
CHECK_SLOT_HOLDS(large, 0, slots);
CHECK_SLOT_HOLDS(large, 51, first + 2051);
CHECK_SLOT_HOLDS(large, 2051, first + 1951);
/* The 2048-claim launch places its own blocks in exactly those slots. The four blocks only the
* wider launch names (2148..2151) are the sole difference, so they are skipped. */
for (int64_t s = 0; s < slots; ++s)
if (large.sblk.iat(s) < first + 2048)
CHECK_EQ(small.sblk.iat(s), large.sblk.iat(s));
for (int64_t k = 0; k < 2048; ++k)
CHECK_EQ(small.res.iat(first + k), large.res.iat(first + k));
CHECK_EQ(small.ctl.iat(12), 2048);
CHECK_EQ(small.ctl.iat(2), 2048);
/* The rewrite: every valid entry names the slot of its block, and the padding past nsel[q] is
* -1 (the 2048-claim launch has one such entry a row). */
for (int64_t q = 0; q < M; ++q)
for (int64_t i = 0; i < pitch; ++i) {
const int64_t e = q * pitch + i;
/* The block's own id while it fits the ring, then the slot it fell back to. The wider
* launch packs 513 a row, the narrower one 512. */
const int64_t bl = first + q * pitch + i;
const int64_t bs = first + q * 512 + i;
CHECK_EQ(large.sel.iat(e), bl < slots ? bl : bl - slots);
if (i < 512) CHECK_EQ(small.sel.iat(e), bs < slots ? bs : bs - slots);
else CHECK_EQ(small.sel.iat(e), -1);
}
}
TEST(kv_resolve_refuses_a_selection_that_does_not_fit_the_maps) {
KVF f(1, 8, 4, 2, 4);
f.fill_host();
f.res.n({ -1, -1, -1, -1, -1, -1, -1, -1 });
f.sblk.n({ -1, -1, -1, -1 });
f.sst.n({ 0, 0, 0, 0, 0, 0, 0, 0 });
f.ctl.n({ 0, 0, 0, 0 });
f.sel.n({ 8, -1 }); /* block 8 is outside [0, blocks) */
f.nsel.n({ 1 });
CHECK_EQ(f.call(), RAD_E_INVAL);
CHECK_EQ(f.sel.iat(0), 8); /* nothing rewritten */
CHECK_ENTRIES(f.res, -1, -1, -1, -1, -1, -1, -1, -1);
CHECK_ENTRIES(f.sel, 8, -1);
CHECK_EQ(f.ctl.iat(0), 0); /* no epoch bump either */
f.sel.n({ 1, 1 });
f.nsel.n({ 3 }); /* more entries than the row holds */
CHECK_EQ(f.call(), RAD_E_SHAPE);
CHECK_EQ(f.ctl.iat(0), 0);
}
/* qsa_tail_store: only the last `ring` tokens of a sequence write, to row pos % ring of the
* sequence's slot; a sequence with no slot and every untargeted row are left alone. */
TEST(qsa_tail_store_writes_the_last_ring_tokens_into_the_sequences_slot) {
@@ -8503,6 +9093,9 @@ std::vector<Geo> geometries() {
.d("scale", 0.3535533905932738).s("dtype", "bf16")),
G("kv_store", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head_kv", 2).i("block_size", 4)
.s("kv_dtype", "f32")),
G("kv_store_streamed", "M", 3,
a.i("M", R).i("head_dim", 8).i("n_head_kv", 2).i("block_size", 8)
.s("kv_dtype", "fp8_e4m3")),
G("rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1)
.d("theta", 1e4).d("scale", 1.0).s("mode", "neox")),
G("qk_norm_rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1)
@@ -8514,6 +9107,8 @@ std::vector<Geo> geometries() {
G("qsa_score", "M", 4, a.i("M", R).i("n", 32).i("heads", 2).i("blocks", 6).i("seqs", 2)
.s("dtype", "bf16")),
G("qsa_select", "M", 4, a.i("M", R).i("blocks", 6).i("topk", 3).i("ratio", 4).i("seqs", 2)),
G("kv_resolve", "M", 3, a.i("M", R).i("blocks", 8).i("slots", 6).i("sel_pitch", 4)
.i("block_bytes", 8)),
G("qsa_tail_store", "M", 4, a.i("M", R).i("n", 32).i("ratio", 4).i("ring", 6).i("seqs", 2)
.s("dtype", "bf16")),
G("qsa_work", "M", 6, a.i("M", R).i("n", 32).i("ratio", 4).i("ring", 6).i("seqs", 2)