Archived
device and plugin boundary: kv_resolve, the streamed store rows, ABI 30
This commit is contained in:
1 parent
5a9ce4912b
commit
cce687bf2c
34 files changed
+3643
-29
No files matched your search
@@ -46,6 +46,7 @@ set(AVX_KERNEL_SRC
|
||||
avx_planes.cpp
|
||||
avx_lora.cpp
|
||||
avx_attn.cpp
|
||||
avx_kvstream.cpp
|
||||
avx_sam_attn.cpp
|
||||
avx_qsa.cpp
|
||||
avx_moe.cpp
|
||||
|
||||
@@ -1060,6 +1060,102 @@ AVX_KERNEL(kv_store) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ kv_store_streamed */
|
||||
/* kv_store for a group whose KV streams: the host mirror is authoritative and the ring is a cache
|
||||
* of it. `host` is written ALWAYS, at the block's identity row; `kv_cache[res[block]]` only when
|
||||
* the residency map says the block is resident. libref/ref_attn.cpp (ref_kv_store_streamed) states
|
||||
* why the residency test belongs in the writer and not in the resolve: at decode the block a step
|
||||
* writes is usually already resident, so a mirror-only writer would leave the ring's copy of it
|
||||
* short of this step's tokens and the resolve would not re-copy a resident block.
|
||||
*
|
||||
* The two planes are the same bytes in the same paged layout, so one conversion writes both: the
|
||||
* mirror is a view of the same `[block, kv_heads, block_size, 2 * head_dim]` shape whose dtype is
|
||||
* the cache's, so the two copies cannot round differently. E4M3 converts as kv_store_fp8 does;
|
||||
* bf16 stores the value itself, as kv_store_bf16 does. `res` is read, never written. */
|
||||
AVX_KERNEL(kv_store_streamed) {
|
||||
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
|
||||
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
|
||||
const RadTensor *res = &a->t[4], *host = &a->t[5];
|
||||
|
||||
const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0);
|
||||
const int64_t block_size = p_int(a, "block_size", 0);
|
||||
const int64_t kv_heads = p_int(a, "n_head_kv", 0);
|
||||
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
|
||||
if (k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (sm->dtype != RAD_I32 || res->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (host->dtype != RAD_U8) return RAD_E_DTYPE;
|
||||
/* E4M3 (the fp8 QSA family) or bf16 (the default cache dtype); a packed fp8_v4/k6_v4 group has
|
||||
* no streamed row. */
|
||||
const bool fp8 = kv->dtype == RAD_F8E4M3;
|
||||
if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED;
|
||||
if (kv->rank != 4 || kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
|
||||
kv->shape[3] != 2 * head_dim) return RAD_E_SHAPE;
|
||||
if (host->rank != 2) return RAD_E_SHAPE;
|
||||
|
||||
/* One block of one layer: both planes are dense rows of it, so the same offsets address the
|
||||
* same element of the same block in either. */
|
||||
const int64_t EB = fp8 ? 1 : 2;
|
||||
const int64_t row = kv_heads * block_size * 2 * head_dim * EB;
|
||||
const int64_t slots = kv->shape[0], blocks = host->shape[0];
|
||||
if (host->shape[1] != row ||
|
||||
host->stride[0] * rad_dtype_bytes(host->dtype, 1) != row) return RAD_E_STRIDE;
|
||||
if (kv->stride[0] * rad_dtype_bytes(kv->dtype, 1) != row) return RAD_E_STRIDE;
|
||||
if (slots <= 0 || blocks <= 0) return RAD_E_SHAPE;
|
||||
if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE;
|
||||
|
||||
const int64_t M = numel(sm);
|
||||
if (M <= 0 || numel(k) < M * kv_heads * head_dim ||
|
||||
numel(v) < M * kv_heads * head_dim) return RAD_E_SHAPE;
|
||||
|
||||
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
|
||||
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
|
||||
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
|
||||
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
|
||||
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
|
||||
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
|
||||
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
|
||||
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
|
||||
|
||||
/* Refused before the first write, exactly as libref refuses it: a half-written mirror makes
|
||||
* the next step's copies plausible and wrong. (The device row cannot return a host status from
|
||||
* inside its kernel and guards these instead; a legal call never takes either path.) */
|
||||
const int32_t* const R = (const int32_t*)res->data;
|
||||
for (int64_t t = 0; t < M; ++t) {
|
||||
const int64_t slot = ldi(sm, offlin(sm, t));
|
||||
if (slot < 0) continue;
|
||||
const int64_t blk = slot / block_size;
|
||||
if (blk >= blocks) return RAD_E_SHAPE;
|
||||
if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RadTensor hkv = *host;
|
||||
hkv.dtype = kv->dtype; /* the same bytes, seen as the cache's dtype */
|
||||
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
|
||||
const KVView hv = kv_view(&hkv, head_dim, block_size, kv_heads);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * kv_heads * head_dim >= AVX_PAR_MIN)
|
||||
for (int64_t t = 0; t < M; ++t) {
|
||||
const int64_t slot = ldi(sm, offlin(sm, t));
|
||||
if (slot < 0) continue;
|
||||
const int64_t blk = slot / block_size, off = slot % block_size;
|
||||
const int64_t hb = blk * hv.sb + off * hv.so;
|
||||
const int64_t cb = R[blk] >= 0 ? R[blk] * kvv.sb + off * kvv.so : -1;
|
||||
for (int64_t h = 0; h < kv_heads; ++h) {
|
||||
for (int64_t d = 0; d < head_dim; ++d) {
|
||||
const float xk = ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks;
|
||||
const float xv = ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs;
|
||||
stt(&hkv, hb + h * hv.sh + d * hv.sd, xk);
|
||||
stt(&hkv, hb + h * hv.sh + (head_dim + d) * hv.sd, xv);
|
||||
if (cb >= 0) {
|
||||
stt(kv, cb + h * kvv.sh + d * kvv.sd, xk);
|
||||
stt(kv, cb + h * kvv.sh + (head_dim + d) * kvv.sd, xv);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== rotary
|
||||
*
|
||||
* NeoX pairs element i with i + rotary_dim/2; GPT-J ("interleaved") pairs 2i with 2i+1. The style
|
||||
|
||||
@@ -429,6 +429,22 @@ std::vector<Case> build_cases() {
|
||||
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 16), HS("kv_dtype", "fp8_e4m3"), HF("k_scale", ks),
|
||||
HF("v_scale", 1.0 / ks) });
|
||||
/* The streamed store, on one block and one ring slot (see ref_shapes.cpp: a described map
|
||||
* cannot be an injective permutation, so a multi-block call could draw two blocks one slot).
|
||||
* The resident/mirror-only split is built by hand in avx_check_hand.cpp. */
|
||||
for (double ks : { 1.0, 0.5 })
|
||||
add("kv_store_streamed", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 32), HS("kv_dtype", "fp8_e4m3"),
|
||||
HF("k_scale", ks), HF("v_scale", 1.0 / ks) });
|
||||
add("kv_store_streamed", { HI("M", 3), HI("head_dim", 32), HI("n_head_kv", 1),
|
||||
HI("block_size", 4), HS("kv_dtype", "fp8_e4m3") });
|
||||
/* The same store into a bf16 cache: both planes are the values themselves, two bytes wide. */
|
||||
for (double ks : { 1.0, 0.5 })
|
||||
add("kv_store_streamed", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
|
||||
HI("block_size", 32), HS("kv_dtype", "bf16"),
|
||||
HF("k_scale", ks), HF("v_scale", 1.0 / ks) });
|
||||
add("kv_store_streamed", { HI("M", 3), HI("head_dim", 32), HI("n_head_kv", 1),
|
||||
HI("block_size", 4), HS("kv_dtype", "bf16") });
|
||||
for (const char* mode : { "neox", "gptj" }) {
|
||||
add("rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 10000.0), HF("scale", 1.0), HS("mode", mode),
|
||||
@@ -528,6 +544,22 @@ std::vector<Case> build_cases() {
|
||||
HS("dtype", "f32") });
|
||||
add("qsa_work", { HI("M", 3), HI("n", 40), HI("ratio", 2), HI("ring", 3), HI("seqs", 3),
|
||||
HI("work", 3), HS("dtype", "f32") });
|
||||
/* The streamed group's residency map at a decode step's geometry and at the edges a check can
|
||||
* describe: a ring shallower than the id space and deeper than it, one query row, a pitch of
|
||||
* one, and a `block_bytes` that is not a multiple of a vector (a block is a whole number of
|
||||
* 16-byte lanes in practice, but nothing in the schema says so and the copy's tail must still
|
||||
* be right). libref describes the map as every block resident (ref_shapes.cpp), so these cases
|
||||
* exercise the epoch, the hit stamp, the rewrite and the bookkeeping; a miss, an eviction, a
|
||||
* second chance and an overflow need a cold map, which no description draws, and are built by
|
||||
* hand in avx_check_hand.cpp. */
|
||||
add("kv_resolve", { HI("M", 4), HI("blocks", 300), HI("slots", 96), HI("sel_pitch", 33),
|
||||
HI("block_bytes", 256) });
|
||||
add("kv_resolve", { HI("M", 6), HI("blocks", 64), HI("slots", 128), HI("sel_pitch", 17),
|
||||
HI("block_bytes", 24) });
|
||||
add("kv_resolve", { HI("M", 1), HI("blocks", 8), HI("slots", 4), HI("sel_pitch", 1),
|
||||
HI("block_bytes", 8) });
|
||||
add("kv_resolve", { HI("M", 3), HI("blocks", 1), HI("slots", 1), HI("sel_pitch", 513),
|
||||
HI("block_bytes", 4096) });
|
||||
/* The proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the
|
||||
* frequency denominator is head_dim. */
|
||||
for (const char* mode : { "neox", "gptj" }) {
|
||||
@@ -1232,6 +1264,15 @@ std::vector<Case> build_cases() {
|
||||
(double)M * blocks * 8, 0);
|
||||
speed("qsa_select", { HI("M", 2048), HI("blocks", 16384), HI("topk", 512), HI("ratio", 4),
|
||||
HI("seqs", 1) }, 2048.0 * 16384 * 8, 0);
|
||||
/* The residency map at a decode step: an 8K-block id space over a 2048-slot ring (a group at
|
||||
* depth 3 with 256-token blocks), one query row and a four-row verify window, 512 selected
|
||||
* blocks a row. libref describes the map all-resident, so this times the two selection passes,
|
||||
* the compaction of the claim list, the rewrite and the bookkeeping; the block copies are one
|
||||
* per miss, and which blocks miss is a cache state the geometry does not carry. */
|
||||
for (const int64_t M : { 1, 4 })
|
||||
speed("kv_resolve", { HI("M", M), HI("blocks", 8192), HI("slots", 2048),
|
||||
HI("sel_pitch", 513), HI("block_bytes", 2048) },
|
||||
(double)M * 513 * 8, 0);
|
||||
/* The tail and the work list: four decoding sequences, and a prefill chunk's volume (512
|
||||
* sequences of four rows each completing a block, 2048 key rows staged). */
|
||||
speed("qsa_tail_store", { HI("M", 4), HI("n", 128), HI("ratio", 4), HI("ring", 7),
|
||||
|
||||
@@ -57,6 +57,11 @@ struct Hand {
|
||||
int oracle_opd = -1;
|
||||
std::vector<float> oracle;
|
||||
double oracle_tol = 0;
|
||||
/* An answer neither library computes: operand `oracle_opd`'s whole buffer must hold these
|
||||
* bytes on both sides. For a case whose bytes follow from the layout by hand, so a store that
|
||||
* writes the right values to the wrong place fails even when both libraries agree. */
|
||||
int want_raw_opd = -1;
|
||||
std::vector<uint8_t> want_raw;
|
||||
|
||||
Hand(const char* n, const char* o, double t) : name(n), op(o), tol(t) {}
|
||||
|
||||
@@ -159,6 +164,13 @@ struct Hand {
|
||||
return *this;
|
||||
}
|
||||
|
||||
/* Operand `opd` (an output) must hold `bytes` verbatim on both sides. */
|
||||
Hand& expect_bytes(int opd, std::vector<uint8_t> bytes) {
|
||||
want_raw_opd = opd;
|
||||
want_raw = std::move(bytes);
|
||||
return *this;
|
||||
}
|
||||
|
||||
enum Result { PASS, FAIL, ABSENT };
|
||||
|
||||
Result fail(const std::string& why) {
|
||||
@@ -275,6 +287,26 @@ struct Hand {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (want_raw_opd >= 0) {
|
||||
const Buf& bf = bufs[(size_t)buf_of[(size_t)want_raw_opd]];
|
||||
if (want_raw.size() != bf.orig.size()) {
|
||||
fail("the expected bytes are " + std::to_string(want_raw.size()) + ", the operand " +
|
||||
std::to_string(bf.orig.size()));
|
||||
ok = false;
|
||||
} else {
|
||||
for (int side = 0; side < 2; ++side) {
|
||||
const uint8_t* d = side ? bf.b.data() : bf.a.data();
|
||||
size_t at = 0;
|
||||
while (at < want_raw.size() && d[at] == want_raw[at]) ++at;
|
||||
if (at != want_raw.size()) {
|
||||
std::printf(" FAIL %-20s %s\n %s byte %zu is 0x%02x, expected 0x%02x\n",
|
||||
op.c_str(), name.c_str(), side ? who : "libref", at, d[at],
|
||||
want_raw[at]);
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
double core_rel = -1;
|
||||
if (oracle_opd >= 0 && !oracle.empty()) {
|
||||
const Buf& bf = bufs[(size_t)buf_of[(size_t)oracle_opd]];
|
||||
@@ -3136,6 +3168,449 @@ void qsa_cases(std::vector<Hand>& hs) {
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the streamed KV residency map
|
||||
*
|
||||
* `kv_resolve`'s service shapes: a partly resident pool, an eviction, a second chance over the
|
||||
* two-bit heat counter (including the cases where it must differ from a one-bit CLOCK), an
|
||||
* overflow, one claim for a block several rows name, a copy whose length is not a vector multiple,
|
||||
* and the state faults it refuses. libref's description can only draw an all-resident map (a cold
|
||||
* entry is -1, which no index draw expresses), so every case below is one the table cannot reach.
|
||||
*
|
||||
* The pool starts as the maps say it is: a slot holding block `b` carries b's bytes and a free
|
||||
* slot carries 0xEE, the marker tests/ref_test.cpp uses. Then the copies are visible element by
|
||||
* element, and both libraries are compared over the whole of every map, the mirror's bytes and the
|
||||
* ring. */
|
||||
namespace kvhand {
|
||||
|
||||
enum { kNOB = 0xEE };
|
||||
|
||||
/* The bytes block `b`, element `i` of its block: a pattern under 256 whose block digit is
|
||||
* recoverable, so a copy that landed in the wrong slot shows. */
|
||||
float block_byte(int64_t b, int64_t i) { return (float)((29 * b + i) & 0xff); }
|
||||
|
||||
/* A pool with its operands in the contract's order. `sel` and `sst` are flat, shaped here. */
|
||||
Hand pool(const char* name, int64_t M, int64_t blocks, int64_t slots, int64_t pitch,
|
||||
int64_t bbytes, std::vector<int64_t> sel, std::vector<int64_t> nsel,
|
||||
std::vector<int64_t> res, std::vector<int64_t> sblk, std::vector<int64_t> sst,
|
||||
std::vector<int64_t> ctl) {
|
||||
Hand h(name, "kv_resolve", 0.0);
|
||||
h.dense(RAD_I32, { M, pitch },
|
||||
[sel](int64_t i) { return (float)sel[(size_t)i]; }, true)
|
||||
.idx(nsel)
|
||||
.idx(res, true)
|
||||
.idx(sblk, true)
|
||||
.dense(RAD_I32, { slots, 2 },
|
||||
[sst](int64_t i) { return (float)sst[(size_t)i]; }, true)
|
||||
.idx(ctl, true)
|
||||
.dense(RAD_U8, { blocks, bbytes },
|
||||
[bbytes](int64_t i) { return block_byte(i / bbytes, i % bbytes); })
|
||||
/* A slot's contents are the block `slot_block` says it holds; a free slot is the marker. */
|
||||
.dense(RAD_U8, { slots, bbytes },
|
||||
[sblk, bbytes](int64_t i) {
|
||||
const int64_t b = sblk[(size_t)(i / bbytes)];
|
||||
return b < 0 ? (float)kNOB : block_byte(b, i % bbytes);
|
||||
},
|
||||
true)
|
||||
.pi("M", M).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch)
|
||||
.pi("block_bytes", bbytes);
|
||||
return h;
|
||||
}
|
||||
|
||||
} /* namespace kvhand */
|
||||
|
||||
void kv_cases(std::vector<Hand>& hs) {
|
||||
using namespace kvhand;
|
||||
|
||||
/* Blocks 2 and 5 are resident; the selection names them, then 6 and 4. The epoch reaches both
|
||||
* hit slots, the misses are claimed once each and placed in ascending block order (4 then 6),
|
||||
* not in the order the rows name them. Pinned to the rule, so both libraries are held to it
|
||||
* and not only to each other. */
|
||||
{
|
||||
Hand h = pool("hits take the epoch, misses land in block order", 2, 8, 4, 4, 8,
|
||||
{ 2, 5, 6, -1, 2, 4, -1, -1 }, { 3, 2 },
|
||||
{ -1, -1, 0, -1, -1, 3, -1, -1 }, { 2, -1, -1, 5 },
|
||||
{ 0, 1, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 0, 3, 2, -1, 0, 1, -1, -1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* An unreferenced resident slot is the victim and the block it held leaves the map; the hand
|
||||
* starts on it, so the sweep takes it first. */
|
||||
{
|
||||
Hand h = pool("an unreferenced slot is the victim and its block is unmapped", 1, 8, 4, 1,
|
||||
4, { 0 }, { 1 }, { -1, 0, 1, 2, 3, -1, -1, -1 }, { 1, 2, 3, 4 },
|
||||
{ 0, 1, 0, 0, 0, 1, 0, 0 }, { 0, 1, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A free slot is taken before an unreferenced resident slot, even when the hand starts on the
|
||||
* resident one: the empty region is not a victim and the block in that slot stays. */
|
||||
{
|
||||
Hand h = pool("a free slot is taken before an unreferenced one", 1, 8, 4, 1, 4, { 0 }, { 1 },
|
||||
{ -1, -1, -1, 0, -1, -1, -1, -1 }, { 3, -1, -1, -1 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* Second chance: every slot is referenced, so a full turn clears every bit and the miss takes
|
||||
* the slot the hand started on. The bits the sweep passed stay cleared. */
|
||||
{
|
||||
Hand h = pool("a referenced slot gets a second chance", 1, 8, 4, 2, 4, { 0, 1 }, { 2 },
|
||||
{ -1, -1, -1, -1, 0, 1, 2, 3 }, { 4, 5, 6, 7 },
|
||||
{ 0, 1, 0, 1, 0, 1, 0, 1 }, { 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 0, 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The heat counter, and the three shapes that separate it from a one-bit CLOCK. Slot 0 was hit
|
||||
* on two earlier calls (counter 2), slots 1 and 2 once each: a CLOCK sweep clears all three bits
|
||||
* and evicts slot 0 on its second pass, while 2 -> 1 -> 0 leaves slot 0 resident and takes slot
|
||||
* 1. Pinned to the victim, so both libraries are held to the rule and not only to each other. */
|
||||
{
|
||||
Hand h = pool("a slot hit twice survives two sweep passes", 1, 32, 3, 1, 8, { 20 }, { 1 },
|
||||
{ -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 },
|
||||
{ 10, 11, 12 }, { 0, 2, 0, 1, 0, 1 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The halving is only visible in `slot_state`, not in the victim (a cold slot 1 is taken either
|
||||
* way), so this case pins the counter: a saturated 3 is 1 after one pass, not the 0 a one-bit
|
||||
* CLOCK would leave. */
|
||||
{
|
||||
Hand h = pool("a saturated counter halves 3 -> 1 on one pass", 1, 32, 3, 1, 8, { 20 }, { 1 },
|
||||
{ -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 },
|
||||
{ 10, 11, 12 }, { 0, 3, 0, 0, 0, 0 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(4, { 0, 1, 1, 1, 0, 0 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A saturated counter (3) against three slots placed on the previous call (1 each): the sweep
|
||||
* walks two full laps, spends the fresh counters first, and takes slot 1. CLOCK, for which all
|
||||
* four are "referenced", takes slot 0 -- the hottest block in the ring. */
|
||||
{
|
||||
Hand h = pool("a saturated counter outlasts a fresh placement", 1, 32, 4, 1, 8, { 20 },
|
||||
{ 1 },
|
||||
{ -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 },
|
||||
{ 10, 11, 12, 13 }, { 0, 3, 0, 1, 0, 1, 0, 1 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* One bump a slot a call: block 10 is resident and named by both entries, so its counter goes
|
||||
* 1 -> 2. A per-entry bump would leave 3, which is the disagreement this case exists for. */
|
||||
{
|
||||
Hand h = pool("a block two rows name gains one step of heat", 1, 32, 3, 2, 8, { 10, 10 },
|
||||
{ 2 },
|
||||
{ -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 },
|
||||
{ 10, 11, 12 }, { 0, 1, 0, 0, 0, 0 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(4, { 1, 2, 0, 0, 0, 0 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
|
||||
/* 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 stamped with this call's epoch - so it reverts to -1 and its entry keeps the
|
||||
* block id, a value that is not a slot. */
|
||||
{
|
||||
Hand h = pool("an unplaceable miss latches overflow, never a used slot", 1, 8, 4, 5, 4,
|
||||
{ 6, 7, 0, 1, 2 }, { 5 }, { 0, 1, 2, -1, -1, -1, -1, -1 }, { 0, 1, 2, -1 },
|
||||
{ 0, 1, 0, 1, 0, 1, 0, 0 }, { 0, 3, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 3, 0, 0, 1, 2 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A block two rows name is claimed once, the list is ascending, a row of zero entries resolves
|
||||
* nothing, and `block_bytes` 24 leaves the copy a tail shorter than a vector lane group.
|
||||
* Placement: 4 fits the ring and takes slot 4, while 9 and 15 are past `slots` and take the
|
||||
* first free slots from the hand (0 then 1). */
|
||||
{
|
||||
Hand h = pool("one claim per block, a 24-byte copy, an empty row", 3, 16, 6, 4, 24,
|
||||
{ 9, 4, -1, -1, 9, 15, -1, -1, -1, -1, -1, -1 }, { 2, 2, 0 },
|
||||
{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 },
|
||||
{ -1, -1, -1, -1, -1, -1 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
|
||||
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 0, 4, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* An epoch is only ever compared for equality (docs/OPS.md), so a stamp that happens to equal
|
||||
* the epoch this call takes reads as this call's own: the sweep passes that slot and takes the
|
||||
* next. Nothing is validated about a stamp, and both implementations must read it the same
|
||||
* way. */
|
||||
{
|
||||
Hand h = pool("a stamp equal to the new epoch is passed", 1, 8, 4, 2, 4, { 0 }, { 1 },
|
||||
{ -1, -1, -1, -1, -1, -1, -1, -1 }, { 3, -1, -1, -1 },
|
||||
{ 2, 1, 0, 0, 0, 0, 2, 0 }, { 1, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.expect(0, { 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
|
||||
/* 2052 claims -- four rows of 513, which is what `--max-num-seqs 4` selects, and eight more than
|
||||
* the largest fixed list can hold. Every slot is free, so all 2052 are placed: ids 100..2099
|
||||
* take their own slot and the 52 past the ring (2100..2151) take the first free slots from the
|
||||
* hand, which are 0..51. Pinned, so both libraries are held to the placement and not only to
|
||||
* each other. The claim list is gathered from the selection, so the id space (`blocks`) is not
|
||||
* in the cost. */
|
||||
{
|
||||
const int64_t M = 4, blocks = 4096, slots = 2100, pitch = 513, bbytes = 8, first = 100;
|
||||
std::vector<int64_t> sel, nsel((size_t)M, 513), res((size_t)blocks, -1),
|
||||
sblk((size_t)slots, -1), sst((size_t)(slots * 2), 0), ctl(16, 0),
|
||||
want((size_t)slots, -1);
|
||||
for (int64_t q = 0; q < M; ++q)
|
||||
for (int64_t i = 0; i < 513; ++i) sel.push_back(first + q * 513 + i);
|
||||
for (int64_t k = 0; k < 2052; ++k) {
|
||||
const int64_t b = first + k;
|
||||
want[(size_t)(b < slots ? b : b - slots)] = b;
|
||||
}
|
||||
Hand h = pool("2052 claims: identity below the ring, the rest from the hand", M, blocks,
|
||||
slots, pitch, bbytes, sel, nsel, res, sblk, sst, ctl);
|
||||
h.expect(3, want);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* More claims than the ring, and more than a fixed list holds: 12 distinct blocks and 8 slots,
|
||||
* so the eight smallest ids are placed and the four largest revert to -1 with the
|
||||
* overflow latched. 1, 2, 3, 5 and 7 fit the ring and take their own slots; 9, 11 and 100 are
|
||||
* past it and take the first free slots from the hand, 0, then past the identity slots, 4 and
|
||||
* 6. The claim list cannot be clipped at the ring's depth -- the order the sweep takes is the
|
||||
* ascending order of the whole claim set. */
|
||||
{
|
||||
Hand h = pool("12 claims in 8 slots place the eight smallest", 1, 4096, 8, 12, 8,
|
||||
{ 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 }, { 12 },
|
||||
std::vector<int64_t>((size_t)4096, -1), std::vector<int64_t>((size_t)8, -1),
|
||||
std::vector<int64_t>((size_t)16, 0), std::vector<int64_t>(16, 0));
|
||||
h.expect(3, { 9, 1, 2, 3, 11, 5, 100, 7 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
|
||||
/* ---- the refusals: state faults and a selection that does not fit, before any write ---- */
|
||||
const std::vector<int64_t> res_ok = { -1, -1, -1, -1, -1, -1, -1, -1 };
|
||||
const std::vector<int64_t> sblk_ok = { -1, -1, -1, -1 };
|
||||
const std::vector<int64_t> sst_ok = { 0, 0, 0, 0, 0, 0, 0, 0 };
|
||||
const std::vector<int64_t> ctl_ok = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
|
||||
{
|
||||
Hand h = pool("a block id past the id space is refused", 1, 8, 4, 2, 4, { 8, -1 }, { 1 },
|
||||
res_ok, sblk_ok, sst_ok, ctl_ok);
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = pool("more entries than the row holds is refused", 1, 8, 4, 2, 4, { 1, 1 }, { 3 },
|
||||
res_ok, sblk_ok, sst_ok, ctl_ok);
|
||||
h.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = pool("a claim in flight on entry is a state fault", 1, 8, 4, 2, 4, { 1, -1 }, { 1 },
|
||||
{ -1, -2, -1, -1, -1, -1, -1, -1 }, sblk_ok, sst_ok, ctl_ok);
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = pool("a hand past the ring is a state fault", 1, 8, 4, 2, 4, { 1, -1 }, { 1 },
|
||||
res_ok, sblk_ok, sst_ok,
|
||||
{ 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = pool("a slot_block past the id space is a state fault", 1, 8, 4, 2, 4, { 1, -1 },
|
||||
{ 1 }, res_ok, { 8, -1, -1, -1 }, sst_ok, ctl_ok);
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The mirror's row pitch is not `block_bytes`: a copy would move a block over its neighbour. */
|
||||
{
|
||||
const int64_t blocks = 8, slots = 4, pitch = 2, bbytes = 4, stride = bbytes + 4;
|
||||
Hand h("a mirror row pitch that is not block_bytes is refused", "kv_resolve", 0.0);
|
||||
h.dense(RAD_I32, { 1, pitch }, [](int64_t i) { return i == 0 ? 1.0f : -1.0f; }, true)
|
||||
.idx({ 1 })
|
||||
.idx(res_ok, true).idx(sblk_ok, true)
|
||||
.dense(RAD_I32, { slots, 2 }, [](int64_t) { return 0.0f; }, true)
|
||||
.idx(ctl_ok, true)
|
||||
.view(RAD_U8, { blocks, bbytes }, { stride, 1 }, blocks * stride,
|
||||
[bbytes](int64_t i) { return (float)((29 * (i / stride) + i % bbytes) & 0xff); })
|
||||
.dense(RAD_U8, { slots, bbytes }, [](int64_t) { return (float)kNOB; }, true)
|
||||
.pi("M", 1).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch)
|
||||
.pi("block_bytes", bbytes)
|
||||
.refuses(RAD_E_STRIDE);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A ring shallower than `slots` blocks is refused before the sweep could walk past it. */
|
||||
{
|
||||
const int64_t blocks = 8, slots = 4, pitch = 2, bbytes = 4;
|
||||
Hand h("a ring with fewer blocks than slots is refused", "kv_resolve", 0.0);
|
||||
h.dense(RAD_I32, { 1, pitch }, [](int64_t i) { return i == 0 ? 1.0f : -1.0f; }, true)
|
||||
.idx({ 1 })
|
||||
.idx(res_ok, true).idx(sblk_ok, true)
|
||||
.dense(RAD_I32, { slots, 2 }, [](int64_t) { return 0.0f; }, true)
|
||||
.idx(ctl_ok, true)
|
||||
.dense(RAD_U8, { blocks, bbytes }, [bbytes](int64_t i) { return block_byte(i / bbytes,
|
||||
i % bbytes); })
|
||||
.dense(RAD_U8, { slots - 1, bbytes }, [](int64_t) { return (float)kNOB; }, true)
|
||||
.pi("M", 1).pi("blocks", blocks).pi("slots", slots).pi("sel_pitch", pitch)
|
||||
.pi("block_bytes", bbytes)
|
||||
.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== the streamed KV store
|
||||
*
|
||||
* `kv_store_streamed` has two destinations, and the cases worth pinning are the ones a description
|
||||
* cannot draw: a block absent from the ring beside one resident, a step that writes the mirror
|
||||
* alone (every token of a block's first step), a negative slot, and the state faults libref
|
||||
* refuses before its first write. Both libraries are compared over both planes -- the ring and the
|
||||
* mirror -- and `k` / `v` are the engine's rank-2 column slices over a row stride twice the view's
|
||||
* width, so a store that derives its pitch from the shape writes the previous token's rows.
|
||||
*/
|
||||
namespace kvstream {
|
||||
|
||||
Hand store(const char* name, int64_t blocks, int64_t slots, int64_t bs, int64_t kvh, int64_t hd,
|
||||
std::vector<int64_t> sm, std::vector<int64_t> res) {
|
||||
const int64_t M = (int64_t)sm.size();
|
||||
const int64_t lane = kvh * hd;
|
||||
const int64_t row = kvh * bs * 2 * hd;
|
||||
const int64_t span = M * 2 * lane;
|
||||
Hand h(name, "kv_store_streamed", 0.0);
|
||||
h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[](int64_t i) { return (float)((int)(i % 31) - 15) * 0.5f; }) /* k */
|
||||
.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[](int64_t i) { return (float)((int)(i % 13) - 6) * 0.25f; }) /* v */
|
||||
.idx(sm)
|
||||
.dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd },
|
||||
[](int64_t i) { return (float)((int)(i % 5) + 1); }, true) /* the ring */
|
||||
.idx(res)
|
||||
.dense(RAD_U8, { blocks, row },
|
||||
[](int64_t i) { return (float)(int)((i * 37) % 251); }, true) /* the mirror */
|
||||
.pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs)
|
||||
.ps("kv_dtype", "fp8_e4m3");
|
||||
return h;
|
||||
}
|
||||
|
||||
} /* namespace kvstream */
|
||||
|
||||
void kvstream_cases(std::vector<Hand>& hs) {
|
||||
using namespace kvstream;
|
||||
/* Block 0 absent, block 1 resident in slot 0, block 2 absent, block 3 resident in slot 1. */
|
||||
{
|
||||
Hand h = store("the mirror always, the resident slot too", 4, 2, 2, 2, 4,
|
||||
{ 1, 3, 6, 2 }, { -1, 0, -1, 1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* Nothing resident: the ring must come out untouched and the mirror must hold every row. */
|
||||
{
|
||||
Hand h = store("a cold ring takes the mirror alone", 4, 2, 2, 2, 4,
|
||||
{ 0, 5, 6, 7 }, { -1, -1, -1, -1 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A negative slot is a padded row: neither plane is written. */
|
||||
{
|
||||
Hand h = store("a negative slot stores nothing", 2, 1, 2, 1, 2, { -1, 3 }, { -1, 0 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The parity configuration's identity map: the ring slot is the block, so the two planes hold
|
||||
* the same bytes at every mapped position. */
|
||||
{
|
||||
Hand h = store("an identity map writes both planes alike", 3, 3, 2, 1, 2,
|
||||
{ 0, 3, 5 }, { 0, 1, 2 });
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The mirror's exact bytes, laid out by hand: four tokens fill both blocks at both offsets
|
||||
* with constants, so the paged layout [kv_heads][block_size][2 * head_dim] and the E4M3
|
||||
* encoding are pinned against an answer no library computes. Agreement alone cannot catch a
|
||||
* store that writes the right values at the wrong address or with the wrong scale. */
|
||||
{
|
||||
const int64_t blocks = 2, slots = 2, bs = 2, kvh = 1, hd = 2, M = 4;
|
||||
const int64_t lane = kvh * hd, row = kvh * bs * 2 * hd, span = M * 2 * lane;
|
||||
const float kd[M][2] = { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } };
|
||||
const float vd[M][2] = { { -1, -2 }, { -3, -4 }, { -5, -6 }, { -7, -8 } };
|
||||
Hand h("the mirror's bytes, block-id addressing and E4M3", "kv_store_streamed", 0.0);
|
||||
h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[&](int64_t i) { return i % 4 < 2 ? kd[i / 4][i % 4] : 0.0f; })
|
||||
.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[&](int64_t i) { return i % 4 < 2 ? vd[i / 4][i % 4] : 0.0f; })
|
||||
.idx({ 0, 1, 2, 3 })
|
||||
.dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd }, [](int64_t) { return 0.0f; }, true)
|
||||
.idx({ 0, 1 })
|
||||
.dense(RAD_U8, { blocks, row }, [](int64_t) { return 0.0f; }, true) /* the mirror */
|
||||
.pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs)
|
||||
.ps("kv_dtype", "fp8_e4m3");
|
||||
std::vector<uint8_t> want((size_t)(blocks * row), 0);
|
||||
for (int64_t t = 0; t < M; ++t) {
|
||||
const float pair[2 * hd] = { kd[t][0], kd[t][1], vd[t][0], vd[t][1] };
|
||||
uint8_t enc[2 * hd] = {};
|
||||
h_narrow(pair, RAD_F8E4M3, 2 * hd, enc);
|
||||
const int64_t blk = t / bs, off = t % bs;
|
||||
for (int64_t j = 0; j < 2 * hd; ++j)
|
||||
want[(size_t)(blk * row + off * 2 * hd + j)] = enc[j];
|
||||
}
|
||||
h.expect_bytes(5, want);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* The default cache dtype: both planes hold the values themselves, two bytes an element. */
|
||||
{
|
||||
const int64_t blocks = 4, slots = 2, bs = 2, kvh = 2, hd = 4, M = 4;
|
||||
const int64_t lane = kvh * hd, row = kvh * bs * 2 * hd * 2, span = M * 2 * lane;
|
||||
Hand h("bf16: the mirror always, the resident slot too", "kv_store_streamed", 0.0);
|
||||
h.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[](int64_t i) { return (float)((int)(i % 31) - 15) * 0.5f; })
|
||||
.view(RAD_BF16, { M, lane }, { 2 * lane, 1 }, span,
|
||||
[](int64_t i) { return (float)((int)(i % 13) - 6) * 0.25f; })
|
||||
.idx({ 1, 3, 6, 2 })
|
||||
.dense(RAD_BF16, { slots, kvh, bs, 2 * hd },
|
||||
[](int64_t i) { return (float)((int)(i % 5) + 1); }, true)
|
||||
.idx({ -1, 0, -1, 1 })
|
||||
.dense(RAD_U8, { blocks, row },
|
||||
[](int64_t i) { return (float)(int)((i * 37) % 251); }, true)
|
||||
.pi("M", M).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs)
|
||||
.ps("kv_dtype", "bf16");
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* ---- the refusals, before any write ---- */
|
||||
{
|
||||
Hand h = store("a map entry past the ring is refused", 2, 1, 2, 1, 2, { 0, 1 }, { 1, 0 });
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = store("a claim in flight is a state fault", 2, 1, 2, 1, 2, { 0, 1 }, { -2, 0 });
|
||||
h.refuses(RAD_E_INVAL);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
{
|
||||
Hand h = store("a slot past the mirror is refused", 2, 1, 2, 1, 2, { 4, 1 }, { -1, 0 });
|
||||
h.refuses(RAD_E_SHAPE);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
/* A mirror row that is not the block's pitch: a write would spill into the next block. */
|
||||
{
|
||||
const int64_t blocks = 2, slots = 1, bs = 2, kvh = 1, hd = 2, row = 8;
|
||||
Hand h("a padded mirror row is refused", "kv_store_streamed", 0.0);
|
||||
h.view(RAD_BF16, { 2, 2 }, { 4, 1 }, 8,
|
||||
[](int64_t i) { return (float)((int)(i % 7) - 3); })
|
||||
.view(RAD_BF16, { 2, 2 }, { 4, 1 }, 8,
|
||||
[](int64_t i) { return (float)((int)(i % 5) - 2); })
|
||||
.idx({ 0, 1 })
|
||||
.dense(RAD_F8E4M3, { slots, kvh, bs, 2 * hd }, [](int64_t) { return 1.0f; }, true)
|
||||
.idx({ -1, -1 })
|
||||
.view(RAD_U8, { blocks, row }, { row + 4, 1 }, blocks * (row + 4),
|
||||
[](int64_t i) { return (float)(int)(i % 251); }, true)
|
||||
.pi("M", 2).pi("head_dim", hd).pi("n_head_kv", kvh).pi("block_size", bs)
|
||||
.ps("kv_dtype", "fp8_e4m3")
|
||||
.refuses(RAD_E_STRIDE);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================================================== weights of several planes
|
||||
*
|
||||
* A weight declared over several planes of one stored tensor reaches a host row joined
|
||||
@@ -4333,6 +4808,8 @@ bool hand_cases(const Check& ck) {
|
||||
upscaler_cases(hs);
|
||||
vsa_cases(hs);
|
||||
qsa_cases(hs);
|
||||
kv_cases(hs);
|
||||
kvstream_cases(hs);
|
||||
encoder_cases(hs);
|
||||
audio_cases(hs);
|
||||
Broken broken;
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ int avx_par_force(int threads);
|
||||
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
|
||||
X(lora_shrink) X(lora_expand) X(lora_expand_mm) \
|
||||
/* ---- attention */ \
|
||||
X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \
|
||||
X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(kv_store_streamed) X(kv_resolve) X(rope) \
|
||||
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
|
||||
X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \
|
||||
X(sam_attn) \
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
/* avx_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and
|
||||
* the ring slots its pool holds (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4).
|
||||
*
|
||||
* libref/ref_kvstream.cpp is the contract, and this file follows it line by line: the same
|
||||
* refusals in the same order, the same epoch, the same ascending miss order, the same victim from
|
||||
* the same CLOCK sweep over the same two-bit heat counter, so the same blocks land in the
|
||||
* same slots. That is the part a residency
|
||||
* map cannot get "close" on: `sel` becomes the attention's addressing, and two implementations
|
||||
* that agreed on residency but disagreed on a victim would read different KV for the same query.
|
||||
*
|
||||
* Why its own file rather than a section of avx_qsa.cpp: the op sits beside `qsa_select` in
|
||||
* docs/OPS.md but is not part of the indexer -- it walks no scores and rotates nothing, it moves
|
||||
* bytes and owns state across calls (epoch, hand, heat counters). libref keeps the same split
|
||||
* (ref_qsa.cpp / ref_kvstream.cpp), so the two libraries' files diff against each other.
|
||||
*
|
||||
* ============================== what is and is not vector work ==============================
|
||||
*
|
||||
* The phases that can run wide do: the rewrite of a `sel` row (a gather of `res[b]` with the
|
||||
* negative results left in place) and the block copy (one block is a whole number of 16-byte lanes
|
||||
* at every cache layout, docs/OPS.md). The passes that cannot are the lookup/claim pass, the claim
|
||||
* gather and the CLOCK sweep, and none of them is a missed opportunity:
|
||||
*
|
||||
* the map is its own set (phase 2). Two lanes of one vector naming the same absent block would
|
||||
* both read -1 and both claim it, which is exactly the double claim -2 exists to prevent, and
|
||||
* two lanes naming the same resident slot would race on its epoch. The pass is one load and one
|
||||
* store per entry and is bounded by the selection, not by the cache. The claim gather and the
|
||||
* revert are the same pass twice more (`lookups` entries each) for the same reason: the list is a
|
||||
* fact about the selection, and the whole point of this form is that `blocks` -- the id space --
|
||||
* never enters a launch's cost.
|
||||
*
|
||||
* the sweep is a serial second-chance walk with a moving hand whose result is the placement
|
||||
* itself. Its cost is one pass over the slots per miss, and a miss is a cold block: the copies
|
||||
* dominate.
|
||||
*
|
||||
* No OpenMP anywhere: the op carries state from call to call (ctl's epoch, hand and counters), so
|
||||
* two of its launches must never overlap and one launch is a single serial unit of work. This is
|
||||
* why its row is absent from libr4d's concurrent prefix table; libavx's rows make no concurrency
|
||||
* promise at all.
|
||||
*
|
||||
* Scratch is the arena the other kernels use (avx_common.h), not RadArgs::scratch: the miss list
|
||||
* and the claim list are per-call temporaries, and the arena is already the plugin's answer for
|
||||
* one. The layout is `int32 miss_block[slots]`, `int32 miss_slot[slots]` -- what a device row
|
||||
* declares through RadKernelInfo::scratch -- followed by `int32 claim[lookups]`, the gathered claim
|
||||
* set this file needs only because it has no workgroup to sort in.
|
||||
*/
|
||||
#include "avx_common.h"
|
||||
#include "avx_vec.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
using namespace avx;
|
||||
|
||||
namespace {
|
||||
|
||||
/* The heat counter's two writes, the same function in all three implementations (libref's
|
||||
* heat_up/heat_down): a use bumps by one and saturates at 3, a sweep pass halves, and a negative
|
||||
* value -- never written by a legal call -- reads as cold. */
|
||||
int32_t kv_heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
|
||||
int32_t kv_heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; }
|
||||
|
||||
/* `ctl`'s size and the index of its first u64 counter (three consecutive u64s from [4]). */
|
||||
enum { kKvCtlInts = 16, kKvCtlMisses = 4, kKvCtlLookups = 6, kKvCtlCalls = 8 };
|
||||
static_assert(kKvCtlLookups == kKvCtlMisses + 2 && kKvCtlCalls == kKvCtlMisses + 4,
|
||||
"the three counters are consecutive u64s from ctl[4]");
|
||||
|
||||
/* The byte pitch of a rank-2-or-deeper operand's rows, and whether its trailing extents fill that
|
||||
* pitch densely (libref's row_bytes). Both planes are one block a row: a padded row would copy a
|
||||
* block's bytes over its neighbour's. */
|
||||
int64_t kv_row_bytes(const RadTensor* t, int64_t* dense) {
|
||||
int64_t acc = 1;
|
||||
for (int i = (int)t->rank - 1; i >= 1; --i) acc *= t->shape[i];
|
||||
*dense = acc;
|
||||
return t->stride[0] * rad_dtype_bytes(t->dtype, 1);
|
||||
}
|
||||
|
||||
/* `block_bytes` of the mirror into a slot of the pool. A copy is a byte copy at every cache
|
||||
* layout (the op never reads an element), so the width is the ISA's, not the block's dtype. */
|
||||
void kv_copy_block(uint8_t* dst, const uint8_t* src, int64_t n) {
|
||||
int64_t i = 0;
|
||||
#if AVX_LEVEL >= 3
|
||||
for (; i + 64 <= n; i += 64)
|
||||
_mm512_storeu_si512((void*)(dst + i), _mm512_loadu_si512((const void*)(src + i)));
|
||||
#elif AVX_LEVEL >= 2
|
||||
for (; i + 32 <= n; i += 32)
|
||||
_mm256_storeu_si256((__m256i*)(dst + i),
|
||||
_mm256_loadu_si256((const __m256i*)(src + i)));
|
||||
#elif AVX_LEVEL >= 1
|
||||
for (; i + 16 <= n; i += 16)
|
||||
_mm_storeu_si128((__m128i*)(dst + i), _mm_loadu_si128((const __m128i*)(src + i)));
|
||||
#endif
|
||||
if (i < n) std::memcpy(dst + i, src + i, (size_t)(n - i));
|
||||
}
|
||||
|
||||
/* The claim list: every distinct block the selection claims, in block-id order. A claim exists only
|
||||
* where an entry names a block -- the lookup pass left it `-2` -- so the list is gathered from the
|
||||
* SELECTION, whose length is `lookups = sum_q nsel[q]`: a property of the call. It is deliberately
|
||||
* not a walk of `res` over `blocks`, which is the group's whole id space and says nothing about how
|
||||
* big one launch is. The map stays the dedup set: the first entry naming a claim marks it `-3`, so a
|
||||
* block several rows name enters the list once, and the marks are restored before the sweep sees the
|
||||
* map.
|
||||
*
|
||||
* The caller sorts the list; `cap` is the buffer's length and is `lookups` at least, because a
|
||||
* distinct claim costs at least one entry, so every claim is written. The contract needs the first
|
||||
* `slots` of that ascending order and nothing past them. */
|
||||
int64_t kv_claims(int32_t* res, int32_t* out, int64_t cap,
|
||||
const int32_t* sel, const int32_t* nsel, int64_t M, int64_t pitch) {
|
||||
int64_t n = 0;
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
const int32_t* const row = sel + q * pitch;
|
||||
for (int64_t i = 0; i < nsel[q]; ++i) {
|
||||
const int32_t b = row[i];
|
||||
if (res[b] != -2) continue; /* a hit, or taken by an earlier entry */
|
||||
res[b] = -3;
|
||||
if (n < cap) out[n++] = b;
|
||||
}
|
||||
}
|
||||
for (int64_t k = 0; k < n; ++k) res[out[k]] = -2;
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Every claim the sweep could not place goes back to -1: the block is not resident, and the next
|
||||
* call may claim it again. A `res` entry still -2 here is by definition such a claim (a placed one
|
||||
* holds its slot), and it is named by at least one selection entry, so one pass over the selection
|
||||
* reaches all of them -- `lookups` entries instead of `blocks` map entries. The write is idempotent,
|
||||
* so entries that repeat a block are harmless. */
|
||||
void kv_relax_claims(int32_t* res, const int32_t* sel, const int32_t* nsel, int64_t M,
|
||||
int64_t pitch) {
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
const int32_t* const row = sel + q * pitch;
|
||||
for (int64_t i = 0; i < nsel[q]; ++i)
|
||||
if (res[row[i]] == -2) res[row[i]] = -1;
|
||||
}
|
||||
}
|
||||
|
||||
/* The rewrite: entry i becomes the slot holding its block, and an entry whose block could not be
|
||||
* placed becomes slot 0 -- a defined address inside the ring, because leaving the block id would
|
||||
* make the attention dereference past it. ctl[3] is what marks the table unusable ("Overflow" in
|
||||
* docs/OPS.md).
|
||||
*
|
||||
* The gather is safe by construction: the validation pass refused any entry outside [0, blocks)
|
||||
* before a byte was written. An entry at or past nsel[q] is never passed in, so `qsa_select`'s -1
|
||||
* padding survives. */
|
||||
void kv_rewrite_row(int32_t* row, int64_t n, const int32_t* res) {
|
||||
int64_t i = 0;
|
||||
#if AVX_LEVEL >= 3
|
||||
const __m512i zero = _mm512_setzero_si512();
|
||||
for (; i + 16 <= n; i += 16) {
|
||||
const __m512i b = _mm512_loadu_si512((const void*)(row + i));
|
||||
const __m512i s = _mm512_mask_i32gather_epi32(zero, (__mmask16)0xFFFF, b,
|
||||
(const void*)res, 4);
|
||||
/* A gather that lands on a negative is a block this call could not place (-1) or one it
|
||||
* just claimed (-2): slot 0, not the id, exactly as the scalar tail writes it. Clamping
|
||||
* says that for the whole vector; masking the store instead would leave the id in place. */
|
||||
_mm512_storeu_si512((void*)(row + i), _mm512_max_epi32(s, zero));
|
||||
}
|
||||
#elif AVX_LEVEL >= 2
|
||||
const __m256i all = _mm256_set1_epi32(-1);
|
||||
const __m256i zero = _mm256_setzero_si256();
|
||||
for (; i + 8 <= n; i += 8) {
|
||||
const __m256i b = _mm256_loadu_si256((const __m256i*)(row + i));
|
||||
const __m256i s = _mm256_mask_i32gather_epi32(zero, res, b, all, 4);
|
||||
/* s > -1 is s >= 0; a negative lane becomes 0 ("Overflow"), never the block id it holds. */
|
||||
const __m256i ok = _mm256_cmpgt_epi32(s, all);
|
||||
_mm256_storeu_si256((__m256i*)(row + i), _mm256_blendv_epi8(zero, s, ok));
|
||||
}
|
||||
#endif
|
||||
for (; i < n; ++i) {
|
||||
const int32_t s = res[row[i]];
|
||||
row[i] = s >= 0 ? s : 0;
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ------------------------------------------------------------------ kv_resolve */
|
||||
/* One call: bump the epoch; one lookup per distinct block (a hit stamps the slot with the epoch and
|
||||
* bumps its heat counter, an absent block becomes a claim and joins the miss list once); place one
|
||||
* victim per miss -- the block's own slot when its id fits the ring and that slot is free (a
|
||||
* context shorter than the ring maps block id to slot), otherwise a free slot first, then CLOCK from
|
||||
* the hand over the two-bit heat counter, which never takes a slot this call has stamped; re-point
|
||||
* both maps; copy each missed block from the mirror; rewrite every valid entry. `nsel` and the
|
||||
* attention's length are untouched:
|
||||
* a selection entry is an address, not a count.
|
||||
*
|
||||
* `kv_cache` is the RAD_KV operand the attention and `kv_store` take, and it is INOUT rather than
|
||||
* OUT: only the slots a miss lands in are written and every other slot of the ring must survive
|
||||
* for the blocks still resident there.
|
||||
*
|
||||
* An entry of a miss the sweep could not place is rewritten to slot 0, not left holding its block
|
||||
* id: on device the id is an address past the ring that `attn_paged` dereferences unchecked, and a
|
||||
* measured overflow must produce wrong numbers the caller discards (ctl[3]), not a fault. */
|
||||
AVX_KERNEL(kv_resolve) {
|
||||
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
|
||||
const RadTensor *sel = &a->t[0], *nsel = &a->t[1], *res = &a->t[2], *sblk = &a->t[3];
|
||||
const RadTensor *sst = &a->t[4], *ctl = &a->t[5], *host = &a->t[6], *pool = &a->t[7];
|
||||
const int64_t M = p_int(a, "M", 0), blocks = p_int(a, "blocks", 0);
|
||||
const int64_t slots_decl = p_int(a, "slots", 0), pitch = p_int(a, "sel_pitch", 0);
|
||||
const int64_t bbytes = p_int(a, "block_bytes", 0);
|
||||
/* Zero rows is not a call (docs/OPS.md). */
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
if (blocks <= 0 || slots_decl <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_SHAPE;
|
||||
|
||||
/* The map and the counts are one format, written by one op and read by the writer and the
|
||||
* sweep: i32, dense. */
|
||||
const RadTensor* const state[] = { sel, nsel, res, sblk, sst, ctl };
|
||||
for (const RadTensor* t : state)
|
||||
if (t->dtype != RAD_I32) return RAD_E_DTYPE;
|
||||
if (sel->rank != 2 || sst->rank != 2) return RAD_E_SHAPE;
|
||||
if (sel->shape[0] < M || sel->shape[1] < pitch) return RAD_E_SHAPE;
|
||||
if (sel->stride[1] != 1 || sel->stride[0] != pitch) return RAD_E_STRIDE;
|
||||
if (numel(nsel) < M || nsel->stride[0] != 1) return RAD_E_SHAPE;
|
||||
if (numel(res) < blocks || res->stride[0] != 1) return RAD_E_SHAPE;
|
||||
/* The operand states the ring and the parameter is its declared ceiling, as `sel` states `M`
|
||||
* (libref/ref_kvstream.cpp, "The parameters"): the pool is planned after declare, so a ring the
|
||||
* engine sized smaller (--kv-resident) arrives as a shorter `slot_block`. */
|
||||
const int64_t slots = numel(sblk);
|
||||
if (slots < 1 || slots > slots_decl || sblk->stride[0] != 1) return RAD_E_SHAPE;
|
||||
if (sst->shape[0] < slots || sst->stride[1] != 1 || sst->stride[0] < 2) return RAD_E_STRIDE;
|
||||
if (numel(ctl) < kKvCtlInts || ctl->stride[0] != 1) return RAD_E_SHAPE;
|
||||
if (host->rank < 2 || pool->rank < 2) return RAD_E_SHAPE;
|
||||
if (host->shape[0] < blocks || pool->shape[0] < slots) return RAD_E_SHAPE;
|
||||
|
||||
/* One block of one layer: the mirror's row and the pool's slot are the same bytes, and
|
||||
* `block_bytes` is both pitches -- the length of every copy. */
|
||||
int64_t hdense = 0, pdense = 0;
|
||||
if (kv_row_bytes(host, &hdense) != bbytes ||
|
||||
hdense * rad_dtype_bytes(host->dtype, 1) != bbytes)
|
||||
return RAD_E_STRIDE;
|
||||
if (kv_row_bytes(pool, &pdense) != bbytes ||
|
||||
pdense * rad_dtype_bytes(pool->dtype, 1) != bbytes)
|
||||
return RAD_E_STRIDE;
|
||||
|
||||
int32_t* const R = (int32_t*)res->data;
|
||||
int32_t* const SB = (int32_t*)sblk->data;
|
||||
int32_t* const ST = (int32_t*)sst->data;
|
||||
int32_t* const C = (int32_t*)ctl->data;
|
||||
const int32_t* const NS = (const int32_t*)nsel->data;
|
||||
int32_t* const SE = (int32_t*)sel->data;
|
||||
const int64_t stp = sst->stride[0];
|
||||
/* The counters are read and written as u64 inside an i32 block. */
|
||||
if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE;
|
||||
|
||||
/* ---- everything that can refuse, before anything is written; the entry count is summed here
|
||||
* so the counter and the claim list's length need no second look at `nsel` ---- */
|
||||
int64_t lookups = 0;
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
const int64_t n = NS[q];
|
||||
if (n < 0 || n > pitch) return RAD_E_SHAPE;
|
||||
const int32_t* const row = SE + q * pitch;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
if (row[i] < 0 || row[i] >= blocks) return RAD_E_INVAL;
|
||||
lookups += n;
|
||||
}
|
||||
/* The map's own domain, over the whole of it. This is a state fault the contract refuses
|
||||
* (`-2` is never left by a call; a slot index outside the ring would address past it), not a
|
||||
* fallback: an entry the map holds and no selection entry names can only be found by looking
|
||||
* at the map, so this pass is `blocks` long in the reference and here alike. Everything that
|
||||
* acts on a claim is bounded by the selection, as above. */
|
||||
for (int64_t b = 0; b < blocks; ++b)
|
||||
if (R[b] < -1 || R[b] >= slots) return RAD_E_INVAL; /* -2 is never left by a call */
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (SB[s] < -1 || SB[s] >= blocks) return RAD_E_INVAL;
|
||||
if (C[1] < 0 || C[1] >= slots) return RAD_E_INVAL;
|
||||
|
||||
/* ---- 1. the epoch ---- */
|
||||
const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u);
|
||||
|
||||
/* ---- 2. hits, and one claim per distinct miss (the map is its own set) ---- */
|
||||
for (int64_t q = 0; q < M; ++q) {
|
||||
const int64_t n = NS[q];
|
||||
const int32_t* const row = SE + q * pitch;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int32_t b = row[i];
|
||||
const int32_t s = R[b];
|
||||
if (s >= 0) {
|
||||
/* The epoch stamps the slot; the heat counter gains one step, once a slot a call
|
||||
* (libref's step 2), so the counter measures calls that wanted the block. */
|
||||
if (ST[s * stp] != epoch) {
|
||||
ST[s * stp] = epoch;
|
||||
ST[s * stp + 1] = kv_heat_up(ST[s * stp + 1]);
|
||||
}
|
||||
} else if (s == -1) {
|
||||
R[b] = -2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 3. the canonical miss order ---- */
|
||||
int32_t* const miss_block = (int32_t*)scratch_raw((size_t)(2 * slots + lookups) * sizeof(int32_t));
|
||||
int32_t* const miss_slot = miss_block + slots;
|
||||
int32_t* const claim = miss_slot + slots;
|
||||
const int64_t nclaims = kv_claims(R, claim, lookups, SE, NS, M, pitch);
|
||||
std::sort(claim, claim + nclaims);
|
||||
const int64_t nmiss = nclaims < slots ? nclaims : slots;
|
||||
for (int64_t k = 0; k < nmiss; ++k) miss_block[k] = claim[k];
|
||||
|
||||
/* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot
|
||||
* this call uses ---- */
|
||||
/* Identity first: a block whose id fits the ring and whose own slot is free goes there, so a
|
||||
* context shorter than the ring gets res[b] = b and the attention's run of adjacent ids reads
|
||||
* adjacent slots of one layer's stripe (libref's step 4; +2.07% at 16k, §26). It takes only a
|
||||
* free slot and does not move the hand, so it never evicts and the fallback below is the old
|
||||
* policy exactly, from the hand it would always have seen.
|
||||
*
|
||||
* Free before live: the ring's empty region fills before any resident block is evicted (see
|
||||
* libref's step 4). The free scan has no side effect when it finds nothing, so a full ring
|
||||
* takes the same CLOCK victim it always took. The count is what keeps a full ring from paying
|
||||
* that scan per miss: a placement makes a free slot live and an eviction re-points a live one,
|
||||
* so a zero count holds for the rest of the call. */
|
||||
int64_t free_left = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (SB[s] < 0 && ST[s * stp] != epoch) ++free_left;
|
||||
int64_t hand = C[1];
|
||||
int64_t placed = 0;
|
||||
/* More claims than the ring can hold means some miss was left unplaced by construction -- the
|
||||
* list here is the first `slots` of the claim set, so the sweep cannot discover it by running
|
||||
* out of misses -- and libref latches exactly that. */
|
||||
bool overflow = nclaims > slots;
|
||||
for (int64_t k = 0; k < nmiss; ++k) {
|
||||
const int32_t b = miss_block[k];
|
||||
int64_t victim = -1;
|
||||
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[s * stp] == epoch) continue; /* used by this call */
|
||||
if (SB[s] >= 0) continue; /* holds a block */
|
||||
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[s * stp] == epoch) continue; /* used by this call */
|
||||
if (SB[s] >= 0 && ST[s * stp + 1] > 0) { /* second chance */
|
||||
ST[s * stp + 1] = kv_heat_down(ST[s * stp + 1]);
|
||||
continue;
|
||||
}
|
||||
victim = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (victim < 0) {
|
||||
/* Every slot of the ring is stamped with this call's epoch: nothing left to take, and
|
||||
* taking a slot this call filled would break the table it is about to hand out. */
|
||||
overflow = true;
|
||||
break;
|
||||
}
|
||||
/* ---- 5. re-point both maps ---- */
|
||||
if (SB[victim] < 0 && free_left > 0) --free_left; /* a free slot just filled */
|
||||
if (SB[victim] >= 0) R[SB[victim]] = -1;
|
||||
SB[victim] = b;
|
||||
ST[victim * stp] = epoch;
|
||||
ST[victim * stp + 1] = kv_heat_up(ST[victim * stp + 1]);
|
||||
R[b] = (int32_t)victim;
|
||||
miss_slot[k] = (int32_t)victim;
|
||||
++placed;
|
||||
}
|
||||
kv_relax_claims(R, SE, NS, M, pitch);
|
||||
|
||||
/* ---- 6. the copies, one block each, in miss order ---- */
|
||||
const uint8_t* const hb = (const uint8_t*)host->data;
|
||||
uint8_t* const pb = (uint8_t*)pool->data;
|
||||
for (int64_t k = 0; k < placed; ++k)
|
||||
kv_copy_block(pb + (int64_t)miss_slot[k] * bbytes,
|
||||
hb + (int64_t)miss_block[k] * bbytes, bbytes);
|
||||
|
||||
/* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */
|
||||
for (int64_t q = 0; q < M; ++q) kv_rewrite_row(SE + q * pitch, NS[q], R);
|
||||
|
||||
/* ---- the bookkeeping ---- */
|
||||
/* Distinct blocks, counted from the slots this call stamped: a hit or a placed miss leaves the
|
||||
* call's epoch in its slot, and the misses it could not place are the rest of the union. Entry
|
||||
* counts would overcount, because many of a launch's rows share swaths of the history. */
|
||||
int64_t used = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (ST[s * stp] == epoch) ++used;
|
||||
/* The union is over DISTINCT blocks, so it is the slots this call stamped plus the claims it
|
||||
* could not place -- exactly libref's count, and now that the whole claim set is known rather
|
||||
* than a list clipped at `slots`, an overflow reports the union it selected too. */
|
||||
const int64_t uni = used + nclaims - placed;
|
||||
C[0] = epoch;
|
||||
C[1] = (int32_t)hand;
|
||||
C[2] = (int32_t)placed;
|
||||
if (overflow) C[3] = 1;
|
||||
/* The measured sizes: this call's selection union, the part of it that had to be copied in, and
|
||||
* the depth of its claim list. */
|
||||
if (uni > C[10]) C[10] = (int32_t)uni;
|
||||
if (placed > C[11]) C[11] = (int32_t)placed;
|
||||
if (nclaims > C[12]) C[12] = (int32_t)nclaims;
|
||||
uint64_t* const ctr = (uint64_t*)(C + kKvCtlMisses);
|
||||
ctr[0] += (uint64_t)placed;
|
||||
ctr[1] += (uint64_t)lookups;
|
||||
ctr[2] += 1u;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -324,6 +324,28 @@ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT(
|
||||
P_F64O("k_scale"), P_F64O("v_scale") };
|
||||
static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping"),
|
||||
INOUT("kv_cache") };
|
||||
/* The streamed store: kv_store's parameters and the group's two copies beside the ring. `host` is
|
||||
* the authoritative mirror and is always written; `res` is the residency map and is read only. */
|
||||
static const RadParamSpec pKvStoreStreamed[] = {
|
||||
P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"),
|
||||
P_F64O("k_scale"), P_F64O("v_scale")
|
||||
};
|
||||
static const RadOperandSpec oKvStoreStreamed[] = { OPD("k"), OPD("v"), OPD("slot_mapping"),
|
||||
INOUT("kv_cache"), OPD("res"),
|
||||
INOUT("host") };
|
||||
|
||||
/* The residency map of a streamed group. Every operand is i32 state or a byte plane, so no dtype
|
||||
* parameter: the op is the same code at every cache layout. `kv_cache` is the same RAD_KV operand
|
||||
* (docs/OPS.md, `kv_resolve`) the attention and kv_store take, INOUT for the same reason kv_store's
|
||||
* is -- only the slots a miss lands in are written. No constraint either: `block_size` is
|
||||
* deliberately not a parameter here, because `Builder::find_kv_consumer` binds a KV group to the
|
||||
* first unclaimed op after it carrying `block_size`, and that must stay the resolved attention
|
||||
* kernel, not the op that only copies its pages. */
|
||||
static const RadParamSpec pKvResolve[] = { P_INT("M"), P_INT("blocks"), P_INT("slots"),
|
||||
P_INT("sel_pitch"), P_INT("block_bytes") };
|
||||
static const RadOperandSpec oKvResolve[] = { INOUT("sel"), OPD("nsel"), INOUT("res"),
|
||||
INOUT("slot_block"), INOUT("slot_state"),
|
||||
INOUT("ctl"), OPD("host"), INOUT("kv_cache") };
|
||||
|
||||
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
|
||||
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
|
||||
@@ -1026,6 +1048,20 @@ static const RadOpSchema kSchemas[] = {
|
||||
"each tile to all of its rows. logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w] over the head's "
|
||||
"whole head_dim, softmax in f32 with the max subtracted, out = sum p*v, pad rows dropped." },
|
||||
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
|
||||
{ "kv_store_streamed", ARR(pKvStoreStreamed), ARR(oKvStoreStreamed),
|
||||
"kv_store for a streamed group: writes k and v into the host mirror always, at the block's "
|
||||
"identity row, and into the ring slot only when the residency map says the block is resident. A "
|
||||
"negative slot is skipped; the mirror is the truth and a block absent from the ring is copied in "
|
||||
"whole by kv_resolve." },
|
||||
{ "kv_resolve", ARR(pKvResolve), ARR(oKvResolve),
|
||||
"Makes every block the selections name resident and rewrites them as ring slots: an epoch bump, "
|
||||
"a hit or a single claim per distinct block, a free slot before any resident one and otherwise "
|
||||
"one CLOCK (second-chance) victim per miss - never a slot this call uses - the two maps "
|
||||
"re-pointed, each missed block copied from the host mirror "
|
||||
"into its slot, then every valid sel entry replaced by the slot holding its block. nsel, and so "
|
||||
"the attention's length, are unchanged. The ring must hold the call's distinct blocks; a call "
|
||||
"that cannot place every miss latches ctl[3] and leaves those entries naming blocks, never a "
|
||||
"fabricated slot." },
|
||||
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
|
||||
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
|
||||
"QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with "
|
||||
@@ -1601,6 +1637,12 @@ SIMPLE("avx_sam_attn", "sam_attn", "attn",
|
||||
L(sam_attn)),
|
||||
ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY,
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)),
|
||||
ROW("avx_kv_store_streamed", "kv_store_streamed", "attn",
|
||||
"scatter k and v into the host mirror always and into the resident ring slot", DT_ANY,
|
||||
cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store_streamed)),
|
||||
SIMPLE("avx_kv_resolve", "kv_resolve", "attn",
|
||||
"streamed KV residency map: selected block ids become ring slots, misses copied in",
|
||||
"i32 maps, u8 block planes", L(kv_resolve)),
|
||||
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
|
||||
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
|
||||
L(rope_table)),
|
||||
|
||||
Reference in new issue
Block a user