From cce687bf2c79699c858f39ef91733acee4a6207a Mon Sep 17 00:00:00 2001 From: C_Tamas Date: Sat, 24 Oct 2026 19:19:19 +0700 Subject: [PATCH] device and plugin boundary: kv_resolve, the streamed store rows, ABI 30 --- abi/rad_abi.h | 46 +- abi/rad_runtime.h | 67 +++ core/device/aql.cpp | 49 +- core/device/device.h | 22 +- core/device/dispatch.cpp | 9 +- core/device/host.cpp | 1 + core/runtime/ctx.cpp | 20 +- core/runtime/ctx.h | 58 ++- core/runtime/issue.cpp | 15 +- core/runtime/kvbind.cpp | 10 +- core/runtime/tierexec.cpp | 15 +- core/runtime/xprefetch.cpp | 2 +- docs/KERNELS.md | 6 + docs/OPS.md | 192 +++++++- libavx/CMakeLists.txt | 1 + libavx/avx_attn.cpp | 96 ++++ libavx/avx_cases.cpp | 41 ++ libavx/avx_check_hand.cpp | 477 ++++++++++++++++++ libavx/avx_isa.h | 2 +- libavx/avx_kvstream.cpp | 403 +++++++++++++++ libavx/avx_registry.cpp | 42 ++ libr4d/CMakeLists.txt | 1 + libr4d/r4d_fuse.cpp | 37 ++ libr4d/r4d_kv_resolve.hip | 814 +++++++++++++++++++++++++++++++ libr4d/r4d_model_bf16.hip | 152 ++++++ libr4d/r4d_plugin.h | 10 + libr4d/r4d_qk_norm_rope_gate.hip | 135 ++++- libr4d/r4d_rows.cpp | 188 +++++++ libr4d/r4d_shapes.cpp | 84 ++++ libref/ref_attn.cpp | 120 +++++ libref/ref_kvstream.cpp | 453 +++++++++++++++++ libref/ref_ops.h | 6 + libref/ref_registry.cpp | 42 ++ libref/ref_shapes.cpp | 56 +++ 34 files changed, 3643 insertions(+), 29 deletions(-) create mode 100644 libavx/avx_kvstream.cpp create mode 100644 libr4d/r4d_kv_resolve.hip create mode 100644 libref/ref_kvstream.cpp diff --git a/abi/rad_abi.h b/abi/rad_abi.h index fe7d8223..7399a732 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -14,11 +14,47 @@ extern "C" { /* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h, * rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or - * rad_spechub.h. Every - * kind of plugin reports it, and a plugin that does not report exactly this version is refused at - * load with both versions printed. A new optional export (e.g. rad_plugin_reference) is not a - * change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 27u + * rad_spechub.h. Every kind of plugin reports it, and a plugin that does not report exactly this + * version is refused at load with both versions printed. A new optional export (e.g. + * rad_plugin_reference) is not a + * change of shape: a plugin without it gets the default. + * + * 26: RadKVGroupBatch grows one trailing, zero-defaulted field (`stream`, a RadKVStream) so a + * plugin can see a streamed KV group's ring, residency map and host mirror, and RadBuildCtx grows + * `kv_resident_blocks` and `kv_stream_ok` (--kv-resident and the architecture's capability). Every + * earlier field keeps its offset, but the structs are larger, so out-of-tree plugins must be + * rebuilt against 26. + * + * 27: RadBuildCtx grows `cvec`, a rank's control-vector direction table (control vectors). Trailing + * and zero-defaulted as above, so a plugin built against 26 keeps every offset. + * + * 28: RadArchProbe grows two trailing, zero-defaulted fields that met in the same merge: + * `chain_pays` (the plugin measured its speculative step faster with chained launches) and + * `kv_stream_ok` (the architecture can move a KV group between host memory and a resident ring). + * Both are additions a 27 plugin never reads; a plugin that does set them must be built against + * 28, since 27's struct ends where these begin. + * + * 29: radiance 1.11.0's Unlimited-OCR and control-vector work meets KV streaming. RadBuildCtx + * grows `attn_prefill_fp8` (--attn-prefill-fp8, the prefill attention's products accepted in + * e4m3); it fills the four padding bytes ABI 28 already had after `kv_quant`, so no field moves. + * RadArchProbe grows `control_vector_ok` after ABI 28's `kv_stream_ok`: upstream 1.11.0 had it at + * the offset `kv_stream_ok` took in 28, so it moves to 80 and the struct grows, which is why this + * is a bump. Both trailing fields are zero-defaulted, but a plugin that sets either must be built + * against 29. + * + * 30: radiance 1.12.0 meets KV streaming. Upstream spent 27 on its own additions and this tree had + * already spent it, so the merge takes the next number for both: upstream's `RadBuildCtx` grows + * `tp_attn_rows`, `state_dtype` (--state-cache-dtype f16) and `draft_coupling`, and gains + * `rad_lane1_window_begin/end` and `rad_drafter_short_block`; `RadArchProbe` grows + * `tp_attn_rows_ok` and `state_f16_ok`; `RadAudioGenBatch` grows `prev_slot`/`prev_pos`/ + * `prev_used` and the reference prompt's `n_ref`/`ref_samples`/`ref_audio`/`ref_cu`/`ref_cu_h`/ + * `ref_frame`/`ref_frame_h`; `RadAudioGenDecl` grows `branches`, `input_special` and the + * `tmpl_ref`/`ref_*` reference template; and the plugin ABI gains `rad_spechub.h` (a whole new + * header) with the per-row `rad_kernel_reference` override. Every upstream field is trailing and + * zero-defaulted, and `RadKVStream` loses our never-read `scratch` (80 -> 72 bytes), so a plugin + * built against 26-29 keeps the offsets it reads only if it is rebuilt; the loss of a middle + * pointer in `RadKVStream` is why this is a bump even before upstream's additions. */ +#define RAD_ABI_VERSION 30u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index aa684371..07488d31 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -22,6 +22,56 @@ typedef struct RadCtx RadCtx; * scheduler and the run phase the bounds without a device read. */ enum { RAD_PHASE_PREFILL = 0, RAD_PHASE_DECODE = 1, RAD_PHASE_MIXED = 2 }; +/* ================================================================== KV streaming */ +/* A streamed KV group keeps its whole context in pinned host memory and only a ring of blocks on + * the card (docs/KV-STREAMING.md §3.2, §3.6, §4.2). The step batch carries this view of that + * group; a group whose KV is fully resident has none. + * + * Why one pointer to a struct rather than fields inside RadKVGroupBatch: the data is per group + * and fixed at bring-up, while the batch is rebuilt per step for every rank, so copying its + * pointers and geometry per group into every step's batch would be work that never changes. One + * trailing pointer also keeps a group's own layout as it was for every plugin that does not + * stream: the field is zero-defaulted, and a null `stream` means the group is fully resident and + * has no ring, no map and no host copy. + * + * The layout mirrors the pool, layer by layer: a layer's mirror is a dense run of `blocks` rows + * of `block_bytes`, and `host_layer_stride` is `blocks * block_bytes`. So layer l's row for block + * b is at `host + l * host_layer_stride + b * block_bytes`, and `block_bytes` is both the row + * pitch `kv_resolve` reads the mirror at and the length of every copy into the ring. + * + * `res`, `slot_block`, `slot_state` and `ctl` are device memory: a resolve launch reads and + * rewrites them every step, so a host round trip per lookup would cost the link latency the ring + * exists to avoid. Nothing here changes address for the engine's life, which is what lets a + * recorded pass replay a resolve. */ +typedef struct RadKVStream { + /* The group's mirror, pinned host memory, RAD_MEM_HOST_MAPPED so a device kernel reads it over + * the link in place. `blocks * bytes_per_block` bytes, all layers, zeroed at bring-up: a block + * no store has written yet reads as zeros rather than as whatever the page held. */ + uint8_t* host; + /* Residency, both directions, ONE SLICE A LAYER: `res` is block -> ring slot or -1 (device, + * `n_layers * blocks` entries, layer l at `res + l * blocks`), `slot_block` is slot -> block or + * -1 (`n_layers * slots`), `slot_state` is `n_layers * slots * 2`: the epoch of a slot's last + * use and its CLOCK reference bit. A block is resident per layer because the resolve copies one + * layer's bytes; a group-wide map would call a block resident for a layer that was never + * copied. `ctl` is shared: its counters and overflow latch are the group's. */ + int32_t* res; + int32_t* slot_block; + int32_t* slot_state; + /* The control block: epoch, clock hand, the last launch's miss count, the overflow latch, and + * the cumulative misses/lookups/calls counters (docs/OPS.md "kv_resolve"). */ + int32_t* ctl; + /* Bytes one block of ONE layer occupies: the mirror's row pitch and the ring's slot pitch. */ + int64_t block_bytes; + /* Bytes one layer of the mirror occupies, i.e. the distance between layer l and layer l+1. */ + int64_t host_layer_stride; + /* Ring depth in blocks: the group's device pool is `slots` blocks deep while a selection names + * block ids over the group's whole context. */ + int64_t slots; + /* Bytes the host mirror occupies, all layers (`blocks * block_bytes * n_layers`), so a caller + * that only has this view can report or check the off-card tier. */ + int64_t host_bytes; +} RadKVStream; + typedef struct RadKVGroupBatch { rad_kvgroup group; int32_t* slot_mapping; /* [n_tok] flat slot index per token, device */ @@ -36,6 +86,10 @@ typedef struct RadKVGroupBatch { int64_t state_index_pitch; int64_t block_size; int64_t max_blocks; + /* Null unless this group's KV streams: the mirror, the residency map and the ring's geometry + * (RadKVStream above). Trailing and zero-defaulted, so a plugin built against ABI 25 reads + * every field it knows at the same offset and simply never sees the ring. */ + const RadKVStream* stream; } RadKVGroupBatch; typedef struct RadBatch { @@ -721,6 +775,19 @@ int rad_step_fail(RadCtx* c, const char* what); /* ================================================================== run-phase queries */ const RadBatch* rad_batch(RadCtx* c); +/* The position of absolute model layer `layer` in the cache `group` holds, or -1 when this rank + * has no pool for it or the group does not hold that layer. It is the same lookup a RAD_KV operand + * makes (KVPoolBinding::layer_slot), and the index a streamed group's host mirror is laid out by: + * layer `i` of the group is at `stream->host + i * stream->host_layer_stride`. A group's bound + * layers need not be contiguous, so this is never `layer` itself. */ +int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer); +/* Prefill staging (docs/KV-STREAMING.md §4.1). When the group's pass selected the one-layer stage + * view, copy this layer's whole host-mirror row into it, on the compute stream, after the layer's + * store and before its attention; returns 1 and the caller must not resolve. Returns 0 when the + * group has no stage view (a resident group, or the parity configuration's context-sized ring) and + * the caller proceeds normally. The ordering rule is in core/kvstream/stage.h. */ +int rad_kv_stage_layer(RadCtx* c, rad_kvgroup group, const RadKVGroupBatch* kvb, + int layer); int rad_rank(RadCtx* c); int rad_world_size(RadCtx* c); RadStream rad_stream(RadCtx* c); diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 748d74bd..046d1de5 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -2668,9 +2668,10 @@ int64_t a_gate_room(RadStream rs) { /* Waits for the mark, then for the card's link gate if a collective has ever held it (under TP * the all-reduce shares the link and the step waits on it, not on these copies), copies, writes - * `done`, then the list's number. */ + * `done`, then the list's number. RAD_XP_NO_YIELD skips the gate: a list the compute stream waits on + * cannot outlast a hold whose release is behind that wait (core/kvstream/stage.cpp). */ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, - uint32_t* done, uint32_t done_val) { + uint32_t* done, uint32_t done_val, unsigned flags) { DmaQueue* dq = xp_queue(ord); if (!dq) return RAD_E_UNSUPPORTED; Sig* in = (Sig*)mark; @@ -2684,7 +2685,8 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d 10u /* interval */ | (0xfffu << 16) /* retry forever */ }; rc = dma_put(dq, poll, 6); } - if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle) { + if (rc == RAD_OK && n > 0 && lane && lane->ever_held && lane->gate.handle && + !(flags & RAD_XP_NO_YIELD)) { const uint64_t ga = (uint64_t)lane->gate.handle + offsetof(amd_signal_t, value); const uint32_t gate[6] = { kSdmaPoll | (3u << 28) /* equal */ | (1u << 31) /* memory */, (uint32_t)ga, (uint32_t)(ga >> 32), 0u, 1u /* the low bit */, @@ -2719,6 +2721,34 @@ int a_xp_list(int ord, void* mark, int n, const uint64_t* src, const uint64_t* d return rc; } +/* An event the DMA engine completes (rad_event_dma): a fresh completion word for the event, which + * a rad_xp_list writes 0 to as its `done` once its bytes have landed, so a stream that waits on the + * event stops until the copy is done. + * + * The word comes back at 0 and the *caller* arms it with a write of 1 on the stream, because the arm + * must be ordered: a host store here would land ahead of a wait still queued for the group's previous + * copy (which would then block on this 1 and never see its 0), and an event record would not do + * either -- a record completes by decrementing its signal to 0, which is the value the wait is + * looking for. A fresh signal each time keeps two uses of one word from overlapping at all. */ +int a_event_dma(RadEvent re, RadStream rs, uint32_t** word) { + if (!word) { device_set_error("rad_event_dma: null word"); return RAD_E_INVAL; } + if (capturing()) { + device_set_error("rad_event_dma: a tape cannot record a DMA list; the caller must re-run " + "this call with the tape paused"); + return RAD_E_STATE; + } + Event* e = ev_of(re); + Stream* s = ours(rs); + if (!e || !s) { device_set_error("rad_event_dma: null or foreign argument"); return RAD_E_INVAL; } + Sig* g = sig_get(e->host); + if (!g) { device_set_error("rad_event_dma: no signal could be made"); return RAD_E_DEVICE; } + hsa_signal_silent_store_relaxed(g->h, 0); + g->agent = s->agent; + record_adopt(e, g); + *word = (uint32_t*)(uintptr_t)sig_value_addr(g); + return RAD_OK; +} + int64_t a_xp_behind(int ord) { DmaQueue* dq = (ord >= 0 && ord < kMaxDevices) ? &g_dma_xp[ord] : nullptr; if (!dq || !dq->tried.load(std::memory_order_acquire) || !dq->ok) return 0; @@ -3376,9 +3406,17 @@ void* pin_pieces(int64_t bytes) { char* const p = (char*)at; prefer_numa_node(p, len, current_card_numa_node()); + /* RADIANCE_NO_HUGE_PAGES asks for small pages, before the pin faults them in: the KV mirror's + * scattered 2 KiB reads are the case page size is supposed to matter for, and this is how that + * is measured rather than assumed (core/kvstream/mirror.cpp). Not a supported mode. */ + const bool small_pages = std::getenv("RADIANCE_NO_HUGE_PAGES") != nullptr; if (len >= ((int64_t)2 << 20)) { - ::madvise(p, (size_t)len, MADV_HUGEPAGE); - warn_if_no_huge_pages(); + if (small_pages) { + ::madvise(p, (size_t)len, MADV_NOHUGEPAGE); + } else { + ::madvise(p, (size_t)len, MADV_HUGEPAGE); + warn_if_no_huge_pages(); + } } (void)::madvise(p, (size_t)len, MADV_DONTFORK); @@ -3604,6 +3642,7 @@ const DeviceBackend* aql_backend_if_present(void) { g_aql.stream_gate = a_stream_gate; g_aql.gate_open = a_gate_open; g_aql.gate_room = a_gate_room; + g_aql.event_dma = a_event_dma; return &g_aql; }(); return b; diff --git a/core/device/device.h b/core/device/device.h index 0d9655ce..16f99d1e 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -113,13 +113,27 @@ extern "C" void* rad_link_gate(RadStream s); * counts lists handed over and not yet finished. The prefetch ring is uncached device memory * (rad_dev_alloc_uncached): the engine writes it and kernels read it, so no cache may hold a * slot's previous contents. */ +/* An event the DMA engine completes instead of a dispatch: it is recorded on `s` (a write of 1 to + * its completion word, in stream order) and `*word` returns that word for `rad_xp_list` to write 0 + * to as the list's `done`, once the list's bytes have landed. `rad_event_wait(s, ev)` then stops `s` + * until the copy is done, device-side: no host round trip on the step path. The caller waits for + * the group's previous copy before arming the next, so the word's older 0 cannot release a later + * wait. RAD_E_STATE while a tape is recording: a list is not a queue packet, so a recorded pass + * must re-run the call with the tape paused (core/kvstream/stage.cpp). */ +extern "C" int rad_event_dma(RadEvent ev, RadStream s, uint32_t** word); extern "C" int rad_xp_supported(int device); extern "C" int rad_xp_stream_create(RadStream* out); extern "C" int rad_ride(RadStream s, void** token); extern "C" int rad_ride_wait(RadStream s, void* token); extern "C" void rad_ride_release(void* token, RadStream after, int64_t packets); +/* `flags` RAD_XP_NO_YIELD: the list does not give way to a link a stream of this card holds. A copy + * the compute stream itself waits on must set it -- a yield it cannot outlast is a deadlock (the + * hold's release is behind the wait) -- at the cost of taking its share of the link in one piece + * (core/kvstream/stage.cpp). The expert prefetch passes 0: nothing waits for it. */ +#define RAD_XP_NO_YIELD 1u extern "C" int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, - const uint64_t* bytes, uint32_t* done, uint32_t done_val); + const uint64_t* bytes, uint32_t* done, uint32_t done_val, + unsigned flags); extern "C" int64_t rad_xp_behind(int device); extern "C" void* rad_dev_alloc_uncached(int64_t bytes); extern "C" void rad_dev_free_uncached(void* p); @@ -316,7 +330,7 @@ struct DeviceBackend { int (*ride_wait)(RadStream s, void* token); void (*ride_release)(void* token, RadStream after, int64_t packets); int (*xp_list)(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, - const uint64_t* bytes, uint32_t* done, uint32_t done_val); + const uint64_t* bytes, uint32_t* done, uint32_t done_val, unsigned flags); int64_t (*xp_behind)(int device); void* (*alloc_uncached)(int64_t bytes); void (*free_uncached)(void* p); @@ -325,6 +339,10 @@ struct DeviceBackend { int (*stream_gate)(RadStream s, void** gate); int (*gate_open)(void* gate); int64_t (*gate_room)(RadStream s); + + /* ---- an event a DMA list completes: see rad_event_dma. Null (unsupported) on a backend with + * no DMA queue that writes a completion word. */ + int (*event_dma)(RadEvent e, RadStream s, uint32_t** word); }; diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index cf075dd6..16b20d6f 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -549,6 +549,11 @@ void rad_event_destroy(RadEvent e) { dev()->event_destroy(e); } int rad_event_record(RadEvent e, RadStream s) { return dev()->event_record(e, s); } +int rad_event_dma(RadEvent e, RadStream s, uint32_t** w) { + if (const auto f = dev()->event_dma) return f(e, s, w); + rad::device_set_error("rad_event_dma: the device backend has no DMA queue to complete an event"); + return RAD_E_UNSUPPORTED; +} int rad_event_wait(RadStream s, RadEvent e) { return dev()->event_wait(s, e); } int rad_event_query(RadEvent e) { return dev()->event_query(e); } int rad_event_sync(RadEvent e) { @@ -630,8 +635,8 @@ void rad_ride_release(void* token, RadStream after, int64_t packets) { if (const auto f = dev()->ride_release) f(token, after, packets); } int rad_xp_list(int device, void* mark, int n, const uint64_t* src, const uint64_t* dst, const uint64_t* bytes, - uint32_t* done, uint32_t done_val) { - if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val); + uint32_t* done, uint32_t done_val, unsigned flags) { + if (const auto f = dev()->xp_list) return f(device, mark, n, src, dst, bytes, done, done_val, flags); return RAD_E_UNSUPPORTED; } int64_t rad_xp_behind(int device) { diff --git a/core/device/host.cpp b/core/device/host.cpp index d404a2bb..d66be6e4 100644 --- a/core/device/host.cpp +++ b/core/device/host.cpp @@ -816,6 +816,7 @@ const DeviceBackend g_host = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, h_stream_gate, h_gate_open, h_gate_room, + nullptr, /* no DMA queue, so no event it could complete */ }; } /* namespace */ diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index ca8e322b..2db02d28 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -3,6 +3,8 @@ */ #include #include "ctx.h" +#include "kvstream/bind.h" +#include "kvstream/stage.h" #include "xp_state.h" #include "../device/device.h" @@ -921,7 +923,7 @@ int Ctx::lane_join(int from, int to) { * (below). */ static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); -static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72, +static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 80, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); uint64_t Ctx::pass_key(const RadBatch* b) const { @@ -957,6 +959,11 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table); mix((uint64_t)k.block_table_pitch); ptr(k.seqused); ptr(k.state_index); mix((uint64_t)k.state_index_pitch); mix((uint64_t)k.block_size); mix((uint64_t)k.max_blocks); + /* Null on a fully resident group, a fixed set of addresses on a streamed one. Two groups + * that differ here hand a kernel different memory, so they are different passes -- and the + * view's *address* must not enter the key: the builder's Out slot rotates every step, which + * would make every streamed pass a new one (kvstream/bind.h, kvstream_view_key). */ + mix(kvstream_view_key(k.stream)); } mix((uint64_t)level_); mix(dense_epoch_); @@ -1229,6 +1236,12 @@ int Ctx::play_pass(PassTape& t) { rc = xp_ ? xp_step_run(st.a) : RAD_OK; lane_ = l0; break; + case kTapeKvStage: + case kTapeKvStageAfter: + lane_ = st.lane; + rc = kvstage_run(this, st.a, st.b, st.kind == kTapeKvStageAfter); + lane_ = l0; + break; } if (rc < 0) { if (step_status_ >= 0) step_status_ = rc; @@ -1254,7 +1267,8 @@ int Ctx::run_pass(const RadBatch* b) { /* A pass the stager armed for is issued live: see runtime/stager.h. */ if (!tape_on_ || staging_) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } const uint64_t key = pass_key(b); - if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); return RAD_OK; } + if (key == 0) { bump(pc_unkeyed_); arch_step_(this, b); + return RAD_OK; } if (std::find(tape_refused_.begin(), tape_refused_.end(), key) != tape_refused_.end()) { bump(pc_refused_); arch_step_(this, b); @@ -1320,7 +1334,6 @@ int Ctx::run_pass(const RadBatch* b) { } int Ctx::run_step(const RadBatch* b) { - if (!b) return RAD_E_INVAL; if (!arch_step_) { RAD_WARN("Ctx::run_step: no architecture step function was installed"); @@ -1337,6 +1350,7 @@ int Ctx::run_step(const RadBatch* b) { step_status_ = RAD_OK; step_fail_.clear(); prof_n_ = 0; + kvstream_enter(this, b); { const int rc = run_pass(b); if (rc < 0 && step_status_ >= 0) step_status_ = rc; diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index 303cfaa3..3a52cddf 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -141,6 +141,18 @@ struct RouteSlot { * LINEAR [n_states, n_head_kv, state_dim[0], state_dim[1]] * CONV [n_states, n_head_kv * head_dim, conv_slots] channel-major, then time */ +/* One of the two views a streamed group's allocation is addressed through. `depth` is the number + * of layer stripes the view presents: the ring keeps the group's `n_layers`, the stage presents + * one and every layer aliases offset 0. The field is a depth and NOT a rewritten `layer_slot`: + * that table is also the host mirror's row (rad_kv_layer_index), so collapsing it would write all + * layers into one mirror row (docs/KV-STREAMING.md §3.5.1). */ +struct KVViewState { + int64_t layer_stride = 0; + int64_t bytes = 0; + int64_t depth = 0; /* 0: n_layers; 1: every layer at offset 0 */ + int64_t shape0 = 0; /* the operand's [blocks] extent for this view */ +}; + struct KVPoolBinding { void* base = nullptr; int64_t layer_stride = 0; /* bytes between one layer's cache and the next */ @@ -152,8 +164,26 @@ struct KVPoolBinding { std::vector layer_slot; uint32_t rank = 0; /* 0 when the group has no plan: the operand stays a flat span */ int64_t shape[RAD_MAX_RANK] = {0}; + /* The active view's stripe count: 0 is n_layers, 1 is the one-layer prefill stage. */ + int64_t depth = 0; + /* Both fixed views over the group's one allocation. The ring is always present; the stage only + * for a group whose plan depth is 1 (its ring is smaller than its context). The active fields + * above are set from one of these before each pass (kvstream_enter), so a recorded pass that + * used a view replays against it: the pass key already carries the phase, which selects it. */ + KVViewState ring; + KVViewState stage; + bool has_stage = false; + /* Bytes of one layer's mirror row a staged pass must copy, from the block manager's highest + * held block (kvstream/stage.h). 0 copies the whole row, which is always correct and is what a + * caller with no manager (a test, a harness) leaves it at. Set once per step, before the pass, + * because the bound grows as a prefill appends blocks. */ + int64_t stage_live_bytes = 0; }; +/* The KV stage's driver, run again where a recorded pass made it (kvstream/stage.cpp). `after` is + * the call the architecture makes after a layer's attention instead of before it. */ +int kvstage_run(Ctx* c, int group, int layer, bool after); + struct CtxDesc { Program* program = nullptr; int rank = 0; @@ -213,6 +243,20 @@ public: int rank() const { return rank_; } /* Whether repeated passes are recorded and played back (prepare() says when they are not). */ bool records_passes() const { return tape_on_; } + /* Whether the pass being issued is being recorded. Work a tape cannot record -- a DMA + * submission -- must be re-run where the pass made it instead (tape_kv_stage). */ + bool recording() const { return rec_ != nullptr; } + /* While recording: a KV stage call becomes a host step that re-runs at every play, because the + * DMA list it hands the engine and the stream wait on the list's completion word are neither of + * them queue packets (kvstream/stage.cpp; xprefetch.cpp does the same for the prefetch). */ + int tape_kv_stage(bool after, int group, int layer) { + TapeStep st; + st.kind = (uint8_t)(after ? kTapeKvStageAfter : kTapeKvStage); + st.a = group; + st.b = layer; + return tape_host(st, [&] { return kvstage_run(this, group, layer, after); }); + } /* This rank's device ordinal, for the calls that name a card rather than a stream. */ + int device() const { return device_; } int world_size() const { return world_size_; } RadStream stream() const { return stream_; } Program* program() const { return program_; } @@ -230,6 +274,17 @@ public: void* weight_ptr(rad_weight w); void* buf_ptr(rad_buf b); + /* The group-local position of absolute model layer `layer` in the binding's layer_slot, or -1. + * rad_kv_layer_index (rad_runtime.h) exposes it to a plugin, which needs it for the host + * mirror: that is laid out by the group's layers, not by model layer numbers. */ + int64_t kv_layer_index(rad_kvgroup g, int layer) const; + /* The group's pool binding, for the view switch and the stage copy. */ + const KVPoolBinding* kv_binding(rad_kvgroup g) const { + return g < kv_.size() ? &kv_[(size_t)g] : nullptr; + } + KVPoolBinding* kv_binding(rad_kvgroup g) { + return g < kv_.size() ? &kv_[(size_t)g] : nullptr; + } /* ---------------------------------------------------------- routing (spec §5.5) */ int route_report(int layer, const RadRouting* r); @@ -435,7 +490,8 @@ private: * issue. A difference means the key misses a dependency; the step fails, naming the first * differing dispatch. */ enum TapeKind : uint8_t { kTapePlay = 0, kTapeTable = 1, kTapeHost = 2, kTapeRoute = 3, - kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6 }; + kTapeXp = 4, kTapeXpMark = 5, kTapeXpStep = 6, + kTapeKvStage = 7, kTapeKvStageAfter = 8 }; /* A prefetch call (Ctx::xp_predict), run again where the pass made it. */ struct TapeXp { RadPrefetchNext next{}; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index a8e7f245..5baf187c 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -19,6 +19,7 @@ #include #include "ctx.h" #include "device/device.h" +#include "kvstream/bind.h" #include "wtab.h" #include @@ -802,7 +803,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { const int64_t layer = (o.offset >= 0 && (size_t)o.offset < b.layer_slot.size()) ? b.layer_slot[(size_t)o.offset] : -1; - const int64_t off = layer * b.layer_stride; + const int64_t off = kv_binding_offset(b, layer); if (layer < 0 || (b.bytes && off + b.layer_stride > b.bytes)) return abort_step_msg(h, RAD_E_INVAL, fmt("operand %d asks KV group %u for layer %lld, which is " @@ -1044,6 +1045,7 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { g_iss_lau_p = g_iss_lau; } } else { + /* The launch alone, split from the band scan and operand resolution `own` covers above. */ s = ip.launch(la, cur_stream()); } if (hold) { @@ -1251,6 +1253,17 @@ int rad_step_fail(RadCtx* c, const char* what) { } const RadBatch* rad_batch(RadCtx* c) { return c ? static_cast(c)->batch() : nullptr; } + +int64_t rad::Ctx::kv_layer_index(rad_kvgroup g, int layer) const { + if (g >= kv_.size() || !kv_[g].base || layer < 0) return -1; + const std::vector& ls = kv_[g].layer_slot; + if ((size_t)layer >= ls.size()) return -1; + return ls[(size_t)layer]; +} + +int rad_kv_layer_index(RadCtx* c, rad_kvgroup group, int layer) { + return c ? (int)static_cast(c)->kv_layer_index(group, layer) : -1; +} int rad_rank(RadCtx* c) { return c ? static_cast(c)->rank() : 0; } int rad_world_size(RadCtx* c) { return c ? static_cast(c)->world_size() : 1; } RadStream rad_stream(RadCtx* c) { return c ? static_cast(c)->stream() : nullptr; } diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp index 44f57716..bb734863 100644 --- a/core/runtime/kvbind.cpp +++ b/core/runtime/kvbind.cpp @@ -1,6 +1,7 @@ /* kvbind.cpp -- see kvbind.h. */ #include "kvbind.h" +#include "kvstream/bind.h" #include "mem/kv.h" namespace rad { @@ -12,6 +13,8 @@ void bind_kv_pools(const Program& p, const std::functionbase; b.layer_stride = gp->layer_stride(); b.bytes = gp->pool_bytes; @@ -34,10 +37,15 @@ void bind_kv_pools(const Program& p, const std::functionn_blocks; + /* `shape[0]` follows the view and is filled by kv_bind_views below: the resident + * window's depth for the ring, the group's context for the prefill stage + * (docs/KV-STREAMING.md §3.1, §4.1). */ + b.shape[0] = gp->pool_blocks(); b.shape[1] = d.n_head_kv; b.shape[2] = gp->block_size; b.shape[3] = 2 * d.head_dim; + /* Both fixed views over the group's one allocation, with the ring active. */ + kv_bind_views(*gp, &b); break; case RAD_KV_LINEAR: b.rank = 4; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 2c36c329..075407c3 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -1,6 +1,7 @@ #include "runtime/tierexec.h" #include "rad_internal.h" +#include "kvstream/plan.h" #include #include @@ -31,12 +32,18 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, for (int32_t g : groups) { const KVGroupPlan* p = kv->plan(g); if (!p || !p->paged()) continue; + /* A streamed group's pool is one layer of its context, so a gather of layer L would copy + * the last staged layer n_layers times. Its mirror is the tier and the residency map + * restores a block on the next resolve (docs/KV-STREAMING.md §4.1). */ + if (!kv_tier_cached(*p)) continue; GroupInfo gi; gi.g = g; gi.n_layers = p->n_layers; gi.frag = p->layer_bytes_per_block(); gi.layer_stride = p->layer_stride(); - gi.n_blocks = p->n_blocks; + /* The pool's depth: a streamed group backs fewer blocks than it addresses, and the tier + * gathers fragments of the blocks that are here (docs/KV-STREAMING.md §3.1). */ + gi.n_blocks = p->pool_blocks(); gi.base = p->base; gi.replicated = p->replicated; if (p->zero) { @@ -109,6 +116,12 @@ int TierExec::slot_layout(const std::vector& ranks, for (int32_t g : groups) { const KVGroupPlan* p0 = ranks[0]->plan(g); if (!p0 || !p0->paged()) continue; + /* A streamed group is not part of a tier entry: its pool is one layer deep, so a gather + * of layer L would copy the last staged layer n_layers times, and its host mirror is the + * tier (docs/KV-STREAMING.md §4.1). TierExec::stage skips the same groups, so this + * arithmetic and its gather offsets agree. A streamed group is never replicated, so + * leaving it out of the replicated window too is the safe rule. */ + if (!kv_tier_cached(*p0)) continue; bool replicated = false; for (size_t i = 0; i < ranks.size(); ++i) { const KVGroupPlan* p = ranks[i]->plan(g); diff --git a/core/runtime/xprefetch.cpp b/core/runtime/xprefetch.cpp index 30198a14..0a2c4bbd 100644 --- a/core/runtime/xprefetch.cpp +++ b/core/runtime/xprefetch.cpp @@ -202,7 +202,7 @@ void Ctx::xp_serve(XpState& x) { if (r.mark) rad_ride_release(r.mark, r.ms, kXpMarkHold); continue; } - if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq) == RAD_OK) { + if (rad_xp_list(x.device, r.mark, n, src, dst, bytes, x.done + r.g, r.seq, 0) == RAD_OK) { ++x.lists; if (r.mark) x.marks.emplace_back(r.mark, x.lists); } else { diff --git a/docs/KERNELS.md b/docs/KERNELS.md index 54f765ab..e6c3c96e 100644 --- a/docs/KERNELS.md +++ b/docs/KERNELS.md @@ -280,6 +280,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout): | `hc_write_bf16` | `hc_write` | | `join_add_scale_bf16` | `join_add_scale` | | `kv_store_bf16` | `kv_store` | +| `kv_store_streamed_bf16` | `kv_store_streamed` | +| `kv_store_streamed_fp8` | `kv_store_streamed` | | `l2norm_chan_bf16` | `l2norm_chan` | | `lane_gather_w32` | `lane_gather` | | `lane_store_w32` | `lane_store` | @@ -313,6 +315,8 @@ Rows declaring an optional hook (tuning, fusion, weight layout): | `qk_norm_rope_gate` | `qk_norm_rope_gate` | | `qk_norm_rope_gate_kv_store_bf16` | `qk_norm_rope_gate_kv_store` | | `qk_norm_rope_gate_kv_store_fp8` | `qk_norm_rope_gate_kv_store` | +| `qk_norm_rope_gate_kv_store_streamed_fp8` | `qk_norm_rope_gate_kv_store_streamed` | +| `qk_norm_rope_gate_kv_store_streamed_bf16` | `qk_norm_rope_gate_kv_store_streamed` | | `qkv_norm_rope_bf16` | `qkv_norm_rope` | | `qsa_block_key_bf16` | `qsa_block_key` | | `qsa_score_bf16` | `qsa_score` | @@ -507,6 +511,7 @@ on a marked row is a hole this model falls into. | `hc_write` | | host | device | host | | `join_add_scale` | | - | device | - | | `kv_store` | yes | host | device | host | +| `kv_store_streamed` | | host | device | host | | `l2norm_chan` | | - | device | host | | `lane_gather` | | - | device | host | | `lane_store` | | - | device | host | @@ -534,6 +539,7 @@ on a marked row is a hole this model falls into. | `qk_norm_rope` | | host | device | host | | `qk_norm_rope_gate` | | - | device | - | | `qk_norm_rope_gate_kv_store` | | - | device | - | +| `qk_norm_rope_gate_kv_store_streamed` | | - | device | - | | `qkv_norm_rope` | | - | device | - | | `qsa_block_key` | | host | device | host | | `qsa_score` | | - | device | host | diff --git a/docs/OPS.md b/docs/OPS.md index 0b851db2..19db01f8 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -851,6 +851,7 @@ as the weight's GEMM stored them and claims no form. It changes no value. | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | | `sam_attn` | `M`(range) `head_dim` `n_head` `grid_h` `grid_w` `window` `scale`:f64 `dtype` | `q`, `k`, `v`, `cu_seqlens`, `out`, `rel_pos_h`w, `rel_pos_w`w | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | +| `kv_store_streamed` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout | | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | @@ -1033,6 +1034,21 @@ declares bound it lower. `RadKVGroupBatch` carries the slot mapping, the block table and the sequence lengths, but the pool base belongs to the block manager, not the batch. +**When the group streams, the pool is a ring and the operand is its layer.** The device pool then +holds `slots` blocks and the sequence's block table still names up to `blocks` ids, so the sparse +path needs one indirection: `kv_resolve` (in "Sparse attention (QSA)") rewrites the selected ids as +ring slots and copies a block in from the pinned host mirror on a miss. Every other op reads the +cache exactly as before, because it is handed a resolved table. + +Such a group is written by `kv_store_streamed` instead of `kv_store`: the token's k and v go into +the host mirror ALWAYS and into the ring slot only when the residency map says the block is +resident. The mirror is the truth; the ring is a cache of it. The order a layer keeps is **store, +then resolve, then attention**, because a block this step writes may not be in the ring yet and the +resolve copies such a block whole out of the mirror. The residency test belongs in the writer, not +only in the resolve: at decode the block a step writes is usually the block the previous step made +resident, so a mirror-only writer would leave the ring's copy of it missing this step's tokens and +the resolve, seeing the block resident, would not copy it. + **`kv_dtype` `fp8_v4` and `k6_v4`** (device-only) are the quantised layouts of `--kv-cache-dtype` (`RadBuildCtx::kv_quant`). A head's dims are grouped by 32, each group with an f16 scale (its absmax over the largest code, clamped so every code decodes finite in f16), @@ -1056,7 +1072,39 @@ ratios over 4-token pages: `attn_{prefill,decode,decode_gq}_h256_gqa12_{fp8v4,k6 gate and quantiser in the split-KV merge. `r4d_selftest` holds the stores to an exactly representable set and the attention rows to its inline oracle. -### `qk_norm_rope_gate` (device-only) +### `kv_store_streamed` + +`kv_store` for a group whose KV streams: one scatter into the group's two copies instead of one. + +- **`k`, `v`, `slot_mapping`** — as `kv_store`: bf16 activations, an i32 flat slot per token, a + negative slot skipped. `slot / block_size` is the block and `slot % block_size` the position in + it. +- **`host`** — bytes, `[blocks, row]`, inout. The layer's authoritative mirror, one block a row, + the identity layout the design note gives it (`[block, kv_heads, block_size, 2 * head_dim]`, + K then V in a slot). **Written for every token with a slot, always.** +- **`kv_cache`** — the ring, the same `RAD_KV(group, layer)` operand `attn_paged`, `kv_store` and + `kv_resolve` take. **Written at `res[block]` only when that is >= 0.** +- **`res`** — `i32 [blocks]`, in. The residency map `kv_resolve` maintains. Read, never written: + residency is the resolve's decision, so the store cannot move the map under a selection that has + already been resolved. + +Both planes are dense rows of the same byte pitch, so one offset addresses the same element of the +same block in either and the two copies cannot disagree. The conversion follows the cache's dtype: +`kv_store_fp8`'s for E4M3 (divided by the reader's descales) and `kv_store_bf16`'s for bf16 (the +value itself, no descales; every offset is two bytes wide). The rows are `kv_store_streamed_fp8` +and `kv_store_streamed_bf16`, so the default `--kv-cache-dtype bf16` streams as well as fp8; a +packed fp8_v4/k6_v4 group has no streamed row and the engine refuses to stream it rather than leave +it without a writer. + +The caller's order, per layer, is **store → resolve → attention**. A block the current step writes +may not be in the ring at all (a block's first tokens, or a block a previous resolve evicted); the +resolve then copies the whole block out of the mirror, so the store must have written it. A block +that is resident takes the token in both copies, so the ring never holds a stale block and the +resolve never needs to re-copy a resident one. A map entry outside `[-1, slots)` is a state fault +that libref refuses; the device kernel treats it as not resident, which writes the mirror and lets +the resolve refuse the step. + + | op | params | operands | |---|---|---| @@ -1078,6 +1126,7 @@ rank-2 view can express, which would otherwise take `heads` `rmsnorm` launches p | op | params | operands | |---|---|---| | `qk_norm_rope_gate_kv_store` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout | +| `qk_norm_rope_gate_kv_store_streamed` | `M` `head_dim` `n_head` `n_head_kv` `rot` `q_dtype` `eps`:f64/opt `wadd`:f64/opt `cs_f32`/opt `pos_i64`/opt `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `q_gate`?, `k`, `cos_sin`, `positions`, `q_w`w?, `k_w`w → `q_out`?, `k_out`, `gate_out`?; `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout | **`qk_norm_rope_gate_kv_store`** is the prologue followed by `kv_store` in one launch: each k head's block already holds its token's rotated k one element a lane, so it also writes that element and @@ -1094,6 +1143,25 @@ accepts, but a rotated element is a difference of two products, so where those n ULP becomes a few percent and the transcript moves within a few dozen steps. The kernel reproduces the reference's fold exactly: widths above the head dim contribute zeros, and adding 0.0f is exact. +**`qk_norm_rope_gate_kv_store_streamed`** is that fold for a group whose KV streams: the store is +`kv_store_streamed` instead of `kv_store`, so it takes the residency map and the group's host +mirror as its last two operands. The token's rotated k and its v go into the mirror's block row for +every token with a slot, and into `kv_cache[res[block]]` only where the map calls the block +resident; a negative or out-of-range slot stores nothing, and a map entry outside `[-1, slots)` is +treated as not resident (libref refuses it as a state fault, and the resolve then refuses the +step). Both planes are the same dense row of the same paged layout, and the rotated k is the value +`k_out` receives, so the bytes are exactly `qk_norm_rope_gate` then `kv_store_streamed`'s. It has +an E4M3 row (`_fp8`) and a bf16 row (`_bf16`, the default cache dtype; the two planes hold the +rotated k and v themselves, two bytes wide). It +exists because the pair costs a launch a layer on the decode path: one launch where the unfused +prologue and the store were two, and one fewer hop between store, resolve and attention. + +The caller's order is unchanged -- **store, then resolve, then attention** -- and a staged pass +keeps the stage-copy wait before the store, which is now the prologue's own write. The folded path +takes the same guards as the hosted one: `T` at or below the fused rows and a pass at one rotary +component per token (no mixed media positions). Where the row is absent, or a pass declines it, the +layer runs `qk_norm_rope_gate` plus a separate store exactly as before. + ## Image generation The ops a diffusion image generator declares (`rad_declare_generator`, `abi/rad_builder.h`): a @@ -2673,13 +2741,15 @@ order, not a slow one. | `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` | | `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` | | `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` `signed`/opt | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` | +| `kv_resolve` | `M`(range) `blocks` `slots` `sel_pitch` `block_bytes` | `sel`:inout, `nsel`, `res`:inout, `slot_block`:inout, `slot_state`:inout, `ctl`:inout, `host`, `kv_cache`:inout | | `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` | | `qsa_work` | `M`(range) `n` `ratio` `ring` `seqs` `work` `dtype` | `k`, `pos`, `cu`, `state`, `sidx`, `bt`, `rope`? → `stage`, `page`, `bpos`, `nc` | Five ops decompose one indexer, which scores blocks of key history against the query and hands `attn_paged` a shorter block table. `docs/QSA.md` describes the decomposition and `arch/common/rad_qsa.h` issues all five. libref implements all five (the oracle for libr4d's -kernels), and libavx all five for the host path. +kernels), and libavx all five for the host path. `kv_resolve` sits between the last of them and the +attention when the group's KV streams; it is described below, after `qsa_select`. ### `qsa_block_key` @@ -2808,6 +2878,124 @@ because a chunk's local top-k contains every global top-k member of that chunk, output layout too: the attention sums the selected pages in table order and float addition is not associative. Without scratch, or above 32 rows, one workgroup per query walks the whole list. +### `kv_resolve` + +Turns `qsa_select`'s block ids into the ring slots that hold them, and copies a block in when it is +not resident. It is the one op a streamed KV group needs: `sel` is the only place the sparse path +names KV storage, because `qsa_select` already writes `tb[b]`, the group's pool page id, and +`attn_paged` uses each entry as a raw pool index. When the group streams, the device pool is +`slots` blocks deep and the id space is `blocks`, so an id is no longer an address; after this op +every entry is a slot of `kv_cache` and the attention is unchanged. + +The layouts, which the schema cannot state (the maps are one format, and the two block planes are +bytes, so the op is the same code at every cache layout). The shape given is the operand's extent: + +- **`sel`** — `i32 [M, sel_pitch]`, inout. In: block ids. Out: the ring slot holding each block, for + the entries below `nsel[q]`; the -1 padding of `qsa_select` past them is untouched. +- **`nsel`** — `i32 [M]`, in. The valid entries of each row, as `qsa_select` wrote them. +- **`res`** — `i32 [blocks]`, inout. Block id -> slot, or -1 absent; -2 is a claim this call has made + and never leaves it behind. +- **`slot_block`** — `i32 [slots]`, inout. Slot -> block id, or -1 free. +- **`slot_state`** — `i32 [slots, 2]`, inout. Column 0 is the epoch that last used the slot, column 1 + a two-bit **heat counter** in `[0, 3]`: bumped by one, clamped at 3, on every use (a hit or a + placement, once a slot a call), and halved when the sweep passes the slot. 31 bits of the i32 are + unused, so the policy needs no new field and no ABI change. +- **`ctl`** — `i32 [16]`, inout. `[0]` epoch, `[1]` clock hand, `[2]` blocks placed by the last call, + `[3]` overflow (latched), then `u64` misses, lookups and calls from `[4]`, 8-byte aligned, then + `[10]` the largest selection union one call has seen (distinct blocks, hits plus misses), `[11]` + the largest number of blocks one call has placed, and `[12]` the largest number of distinct + blocks one call has claimed — the depth its miss list had to hold. The maxima are the measurement + a ring and a claim list are sized from: `[10]` against the ring's depth says whether one launch + can overflow it, `[12]` against `max_seqs * sel_pitch` says whether a claim list is wide enough. +- **`host`** — bytes, `[blocks, block_bytes]`, in. The layer's authoritative mirror, identity block + layout: block `b` at `b * block_bytes`, exactly as the design note lays it out. +- **`kv_cache`** — bytes, `[slots, block_bytes]`, inout. The layer's ring, the same operand + `attn_paged` and `kv_store` take as `RAD_KV(group, layer)`. + +One call, in order: bump the epoch, one lookup per distinct block, one victim per miss, re-point +both maps, copy each missed block, rewrite every valid selection entry. What each step owes: + +- **One call is one epoch.** The epoch is bumped first; a resident block takes the new epoch and + bumps its heat counter, so the sweep can tell what this call has already touched from what it may + take. +- **One lookup per distinct block, and the map is its own set.** A miss is claimed once, `-1` to + `-2`, so a block named by several rows is claimed by the first of them. `sel` entries past + `nsel[q]` are `-1` padding and are not touched; `nsel[q]` above `sel_pitch` is refused rather than + steered into the neighbouring row. +- **The miss list is in ascending block id, and that is part of the contract.** First-appearance + order would let the row that claimed a block first decide which slot it lands in, so two + implementations of one contract would produce different tables. Ascending is a fact about the + claim set, not about the map: a device launch sorts the claims it made, or — above the shared + claim list — collects the smallest `slots` of them a window of the id space at a time, both over + the selection's entries. `blocks` is the id space (`max_seqs * ceil(max_ctx / block_size)`, 102 400 + at the parity shape) and never the size of one launch, so nothing here walks it. +- **The claim list's depth is derived, not a constant.** One claim is one distinct absent block a + selection entry names, so a launch makes at most `M * sel_pitch` of them (and at most `lookups`, + which is `sum_q nsel[q]`). The device kernel sizes its shared list at + `next_pow2(min(M * sel_pitch, the workgroup's LDS room))`, so any `--max-num-seqs` follows from the + operands: `max_seqs * 513` is 2052 at four sequences, 4104 at eight. There is no cap to raise and + none to fall off, and `ctl[12]` reports the largest count a launch has made. +- **The victim rule is the block's own slot if it is free, then a free slot, then CLOCK, from a hand + that ends just past the last slot taken, with second chance.** A miss whose id is inside the ring + and whose own slot is free goes to slot `b`, so while the context is shorter than the ring the map + is `res[b] = b` and adjacent block ids land in adjacent slots of one layer's stripe, which is the + order the attention's gather reads them in. That is placement only: it takes a slot only when + that slot is free and it does not move the hand, so it never evicts, and a miss it cannot place + falls through to the walk below from the hand it would always have seen -- at depth, where most ids + are past `slots`, the same blocks land in the same slots as before. A free slot holds no block, so + taking it costs nothing and it is claimed before any resident block is considered; the ring's empty + region fills before an eviction. + A slot this call already used (a hit's, or a miss's already claimed) is passed and keeps its + heat counter, free or not; when a whole turn finds no free slot, the sweep halves the counter of a + warm slot (`old >> 1`) and passes it, and takes a cold one (counter 0). The hand still **picks** + the victim -- a per-visit decision, not a search -- so the policy costs no reduction, no barrier + and no extra traffic: an add-and-clamp in place of a constant store and a shift in place of a + zero. That is why it is affordable where an exact LRU is not: the epoch-ordered minimum needs a + collective reduction per miss, which costs more than the choice is worth. The free scan halves no + counter and leaves the hand alone when it finds nothing, so a ring with no free slot takes exactly + the victim the sweep names. Every write clamps the counter to 3, + so two passes halve any value to 0 and the third places the miss: a sweep visits at most + `3 * slots` slots. The counter is the same decayed-use-count mechanism the streamed experts + already replace by (`core/place/heat.*`), at ring granularity. +- **The ring must hold the union of one call's selection.** A hit holds a slot and a miss needs + another, so `hits + misses <= slots` is the sizing rule. What that union is depends on the launch: + a decode step takes the ring and a prefill step takes the one-layer stage, and a decode step issues + one row a sequence (`1 + n_spec` rows a sequence under speculation), so at most + `max_seqs * (1 + n_spec) * (topk + 1)` blocks -- which is the ceiling `--kv-resident` is held to at + startup, and `ctl[10]` is what says at run time that the bound held. Overflow is not silent: an unplaced miss reverts to `-1` (so a later call may claim it) + and its selection entries are rewritten to slot 0 -- a defined address inside the ring, because a + block id is an address past it that the attention dereferences unchecked -- with `ctl[3]` latched. + A caller that finds `ctl[3]` set must discard the step: those entries do not name their blocks, so + the launch's output is wrong by construction and is never served. +- **The copied bytes are the mirror's bytes.** One `memcpy` per placed miss, `block_bytes` long, + nothing converted, so a streamed block is bit-identical to what the writer put in the mirror. + That is why `block_size` is not a parameter and `block_bytes` is: the op never reads an element, + and a `block_size` key would make it a KV group's consumer, taking the block size the block + manager reads away from the resolved attention kernel. +- **`slots` is the operand's, not only the parameter's.** `slot_block`'s extent is the ring a call + may address, exactly as `sel`'s extent states `M` and its row pitch states `sel_pitch`; the declared + parameter is the ceiling a call may not pass. The pool is planned after the program is built, so a + ring the engine sized smaller (`--kv-resident`, when it streams at all) reaches the op as a + shorter operand. The declared ceiling is the ring the deployment carves -- `--kv-resident` in + tokens rounded up to whole blocks, clamped to the group's context (`RadBuildCtx:: + kv_resident_blocks`) -- and not the block-id space `blocks`, so the geometry an engine reports for + this op is the ring it is issued with; with nothing streaming the two are equal. The ceiling also + sizes the row's scratch. +- **The miss list is scratch, not an operand.** It is one launch's temporary; a device row declares + `next_pow2(slots) + slots` i32s through its scratch hook (the miss list, then the slots it pairs + with) and the reference needs none. The claim list before the sort is dynamic LDS, not scratch, + while it fits: the sort reads every element from every thread, so it belongs in the workgroup, and + the row sizes that launch's LDS from the bound above. A launch too wide for that room sorts the + list in the scratch's first plane, which is why it is padded to a power of two. +- **The op is stateful, and therefore not concurrent.** epoch, hand, heat counters and counters + live between launches, so the row must not carry `rad_kernel_concurrent` + (`abi/rad_abi.h:493`); without the promise the engine orders the launch behind everything before + it, which is what the map needs. It is still recordable: the maps, the ring and the mirror are + fixed-size from the group's declaration, so addresses and pitches never move and a replay is + valid. +- **The caller brings the state up.** `res` and `slot_block` filled with `-1`, `slot_state` and + `ctl` zeroed. There is no reset op: a residency map lives as long as its pool. + ### `qsa_tail_store` Parks the raw index keys of the tokens that have not completed a block yet: diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 7fa41a55..34b7b2de 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -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 diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index c6bd6598..2c8b4b32 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.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 diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e2293ae8..84bf99b6 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -429,6 +429,22 @@ std::vector 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 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 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), diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index 06bfd340..5ff8adb3 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -57,6 +57,11 @@ struct Hand { int oracle_opd = -1; std::vector 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 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 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& 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 sel, std::vector nsel, + std::vector res, std::vector sblk, std::vector sst, + std::vector 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& 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 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((size_t)4096, -1), std::vector((size_t)8, -1), + std::vector((size_t)16, 0), std::vector(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 res_ok = { -1, -1, -1, -1, -1, -1, -1, -1 }; + const std::vector sblk_ok = { -1, -1, -1, -1 }; + const std::vector sst_ok = { 0, 0, 0, 0, 0, 0, 0, 0 }; + const std::vector 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 sm, std::vector 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& 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 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; diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index becab33c..a2f88f41 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -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) \ diff --git a/libavx/avx_kvstream.cpp b/libavx/avx_kvstream.cpp new file mode 100644 index 00000000..7533dd35 --- /dev/null +++ b/libavx/avx_kvstream.cpp @@ -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 + +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; +} diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index aaaf5884..174246fc 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -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)), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 96ed0e97..f9d305af 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -160,6 +160,7 @@ set(R4D_UNITS "r4d_qsa_block_key_bf16|" "r4d_qsa_score_bf16|" "r4d_qsa_select_bf16|" + "r4d_kv_resolve|" "r4d_qsa_tail_store_bf16|" "r4d_qsa_work_bf16|" "r4d_sample_chain_f32|" diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index dfa95d2a..447d76b6 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -586,6 +586,43 @@ extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam* p, int n_p, u } } +/* ========================================================================================== + * qk_norm_rope_gate_kv_store_streamed -- the same prologue with the STREAMED store folded on. + * (row: qk_norm_rope_gate_kv_store_streamed_fp8; kernel: r4d_qk_norm_rope_gate.hip under + * QK_KV_STREAMED) + * + * Operands: [0] q_gate? [1] k [2] cos_sin [3] positions [4] q_w? [5] k_w [6] q_out? + * [7] k_out [8] gate_out? [9] v [10] slot_mapping [11] kv_cache + * [12] res [13] host + * + * The store is `kv_store_streamed`, whose `k` is the prologue's own `k_out`. */ +extern "C" int r4d_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p, + uint64_t present, int step, + RadFuseStep* out) { + if (!out) return RAD_E_INVAL; + auto opt = [present](int i) { return opt_opd(present, i); }; + switch (step) { + case 0: { + Step s(out, "qk_norm_rope_gate"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head") + .mirror(p, n_p, "n_head_kv").mirror(p, n_p, "rot").mirror(p, n_p, "q_dtype") + .mirror_opt(p, n_p, "eps").mirror_opt(p, n_p, "wadd").mirror_opt(p, n_p, "cs_f32") + .mirror_opt(p, n_p, "pos_i64"); + return s.wire({ opt(0), 1, 2, 3, opt(4), 5, opt(6), 7, opt(8) }); + } + case 1: { + Step s(out, "kv_store_streamed"); + s.mirror(p, n_p, "M").mirror(p, n_p, "head_dim").mirror(p, n_p, "n_head_kv") + .mirror(p, n_p, "block_size").mirror(p, n_p, "kv_dtype") + .mirror_opt(p, n_p, "k_scale").mirror_opt(p, n_p, "v_scale"); + /* k_out, v, slot_mapping, kv_cache, res, host */ + return s.wire({ 7, 9, 10, 11, 12, 13 }); + } + default: + return RAD_E_NOTFOUND; + } +} + /* ========================================================================================== * qkv_norm_rope_kv_store -- qkv_norm_rope, then kv_store of its finished k and v. * (rows: qkv_norm_rope_kv_store_fp8 and _bf16; kernel: libr4d/r4d_qkv_norm_rope.hip, diff --git a/libr4d/r4d_kv_resolve.hip b/libr4d/r4d_kv_resolve.hip new file mode 100644 index 00000000..b741ba54 --- /dev/null +++ b/libr4d/r4d_kv_resolve.hip @@ -0,0 +1,814 @@ +// kv_resolve: turn a streamed KV group's selected block ids into the ring slots that hold them, +// copy a block in from the pinned host mirror when it is not resident, and rewrite the selection +// in place (docs/OPS.md "kv_resolve", docs/KV-STREAMING.md §3.4 and §4.2). +// +// `qsa_select` already writes the group's pool page id into `sel`, and `attn_paged` reads every +// entry as a raw pool index. A streamed group's device pool is `slots` blocks deep while the id +// space is `blocks`, so an id is no longer an address; after this op each entry is a slot of +// `kv_cache` and the attention is unchanged. `sel` is the only place the sparse path names KV +// storage, which is why one op between select and attention suffices. +// +// The order is the contract (libref/ref_kvstream.cpp), because two implementations must place the +// same blocks in the same slots and so produce the same table: +// +// 1. bump the epoch (ctl[0] + 1); +// 2. one lookup per entry below nsel[q]: a hit takes the epoch and, the first time this call +// stamps that slot, bumps its two-bit heat counter by one (clamped at 3) -- one bump a slot a +// call, not one an entry, so a block many rows name gains one step of heat, the same as one a +// single row names. A miss claims its map entry once (-1 -> -2, atomicCAS), so the map is its +// own set. That CAS is also the distinct-claim count: it succeeds exactly once per block, +// which is the +// `s_distinct` step 3 would otherwise have to scan the map for. The value read is kept, one +// int an entry, for step 7 below; +// 3. compact the claimed blocks out of `res` in ASCENDING block id. The claims are made by +// whichever thread reaches them first, but this scan is what fixes the miss order, so +// atomic claim order never reaches the placement. A thread owns one contiguous chunk of the +// map and reads it four ids at a time, so the list is still ascending by construction. Only +// taken when the call claimed something: with no claim there is no `-2` and nothing to +// place (step 2's count says so); +// 4. one victim per miss, in the hand order from ctl[1]: a FREE slot (slot_block < 0) first, so +// no resident block is evicted while the ring has room (the free count is taken in parallel +// once per call); only a call with no free slot falls back to CLOCK's second chance, where a +// slot stamped with this call's epoch is passed and keeps its counter, a warm slot (counter +// non-zero) has its counter HALVED and is passed, and a cold slot (counter 0) is taken. The +// hand PICKS the victim: this is a per-visit decision, so the policy costs no reduction, no +// barrier and no extra traffic -- an add-and-clamp and a shift where a constant store and a +// zero store would do. An exact LRU would need the minimum over the ring per miss, a +// collective reduction that pays more than the choice is worth. The hand ends just past the +// last slot taken; the sweep visits at most 3*slots, because every write clamps the counter +// to 3 and two halvings take any value to 0; +// 5. re-point both maps as each victim is taken (`res[old] = -1`, then slot -> b and b -> slot, +// with the slot's counter bumped by one as a use: the victim's is 0 by construction, so it is +// 1 in the common case, and the clamp keeps a slot taken by identity or from the free region +// inside [0, 3]); +// 6. copy `block_bytes` of host[b] into kv_cache[s] for each placed miss, as bytes, in this one +// launch; +// 7. rewrite every entry below nsel[q] whose block is resident as its slot; entries past nsel[q] +// keep qsa_select's -1 padding. An entry step 2 saw resident uses the slot it read there, so +// `res` is read once a selection entry, not twice (see "THE ENTRY CACHE"). +// +// OVERFLOW. The ring must hold the union of the call's selection (`hits + misses <= slots`). When it +// does not, the sweep cannot place every miss: the unplaced claims are reverted to -1 (so a later +// call may claim them again), ctl[3] is latched to 1, and their selection entries are rewritten to +// SLOT 0 rather than left holding the block id. The id would be an address past the ring, which +// attn_paged dereferences with no bounds check, so an overflow would fault or read another layer; +// slot 0 is defined memory, wrong numbers the caller discards on ctl[3]. +// +// STATE. The epoch, the hand, the two-bit heat counters and the counters live between launches, so +// this row is not concurrent (r4d_rows.cpp's kStateful[]): two launches must never overlap, and the +// engine orders them. It is still recordable: the maps, the ring and the mirror are fixed-size +// from the group's declaration, so addresses and pitches never move. +// +// COST. A decode step issues this once per QSA layer -- twelve launches, in a step whose whole +// budget is ~33 ms -- so a launch's own cost is the miss path, not the dispatch: ~20 to ~60 misses +// a launch at 16k-160k of history. Everything that path touches is therefore sized from the call's +// own entries and not from `blocks`: +// +// - the claim list comes out of the lookup pass, which already sees every claim, so no pass walks +// `res` over `blocks`; +// - the union is a metric (`ctl[10]`), counted on the first stamp per slot, so no pass walks +// `slot_state` over `slots`: a ring is sized by misses and not by slots, and a ring larger than +// the history does not cost more than a small one; +// - the copies are independent, so each miss has a warp of its own and every miss's read is in +// flight at once. +// +// What is left is the host read itself: a miss copies 2 KiB from a pinned mirror page the card has +// not touched, so it is PCIe transactions with a page walk behind them, and no arrangement of the +// copy loop changes that. The CLOCK sweep is not the cost either: each launch halves the counters +// of the slots it passes, so the ring arrives at the next launch mostly cold and a sweep visits +// about one slot a miss. The free-slot scan ahead of it costs a visit per slot it passes, and the +// count that says whether to scan at all (phase 3b) is one coalesced pass over the two slot maps per +// call, so a ring with no free slot -- where every eviction is unavoidable -- pays neither a full +// turn of scanning per miss nor one serial scan per launch. +// +// SCRATCH. `next_pow2(slots)` block ids then `slots` slots (the row's scratch hook sizes it). The +// miss list is a per-call temporary and would cost the arena planner, the recorded pass and the +// tape key bytes nothing outside this launch reads. The claim list is dynamic LDS (`cap` ids) while +// it fits -- the sort reads every element from every thread, so it wants shared memory -- and the +// scratch's first plane when it does not, which is why that plane is padded to a power of two. The +// entry cache is dynamic LDS too, after the claim list, and absent when it does not fit. +// +// THE CLAIM LIST'S SIZE IS DERIVED, NOT WRITTEN DOWN. A claim is a distinct absent block the +// selection names, so one call makes at most `M * sel_pitch` of them -- and at most `lookups = +// sum_q nsel[q]` in fact -- which is a fact about the call and not about the cache: `blocks` is the +// id space, `max_seqs * ceil(max_ctx / block_size)` and never the size of a launch. So the +// launcher sizes the list at `next_pow2(min(M * sel_pitch, the room a workgroup has))`, and for +// `--max-num-seqs 4` at `sel_pitch` 513 that is 4096 ids, where a constant would have to be chosen +// for the largest configuration or hand that one the map walk below. Nothing here mentions +// `max_seqs`: the engine declares `sel_pitch` and launches `M` rows, and any --max-num-seqs follows +// from those two. `ctl[12]` records the largest claim count one call has made, so a list that is +// ever too shallow is visible in the counters rather than only in the launch's time. +// +// Only the first `slots` claimed blocks are needed: the sweep cannot place more than `slots`, and +// every claim past that is still reverted to -1 by the final pass, so a capped list changes no +// placement. +// +// ABOVE THE LIST. A launch wider than the list -- 28 or more rows at `sel_pitch` 513, since a +// workgroup has tens of thousands of ids of room -- gathers its claims from the selection into the +// scratch and sorts them there (phase 3). The walk is over the call's entries, `lookups` of them, +// never over `blocks`: the map is only the set that says whether an id is a claim and that keeps a +// block four rows name out of the list four times. Same ids, same ascending order, same placements +// as the fast path. The one call this cannot serve is one claiming more blocks than the ring holds: +// no structure there can hold the whole claim set, so that call -- which has overflowed and whose +// step the caller discards -- keeps the map walk that puts the smallest `slots` claims in order. +// +// THE ENTRY CACHE. Step 2 and step 7 each read `res[b]` for every selection entry, and those reads +// are scattered over `blocks` i32: at decode that is two 513-load waves over a map the launch has +// already touched once. But step 7's answer for a HIT is step 2's +// answer: the only thing that clears a `res` entry in a call is an eviction, and the sweep never +// takes a slot stamped with this call's epoch (the `slot_state` test in both the free scan and the +// CLOCK sweep), which is exactly the stamp step 2 puts on every hit's slot. So a hit's slot cannot move, and only an entry step 2 saw absent can +// change -- a claimed block becomes its placed slot, or stays -1 when the sweep could not place it +// (step 6a's revert), or in the above-the-list path passes through -3 and back. Step 2 therefore +// stores the value it read, one int an entry, and step 7 uses it when it is >= 0 and reads the map +// only otherwise: the same slots, the same `sel`, one scattered wave instead of two. +// +// The cache is `M * sel_pitch` ints of dynamic LDS, the launch's whole entry count, and only while +// the workgroup has that room beside the claim list; a prefill-shaped launch that has not gets +// zero and step 7 reads the map instead. Nothing outside the launch sees it: no operand, +// no scratch, no contract. Entries whose block id is out of range are skipped in both steps and +// never reach the cache, and the read is by `sel`'s entry index, which is the same index -- and the +// same thread -- in both steps, so no barrier is needed between them. +// +// STATE FAULTS. libref refuses a `res` entry outside [-1, slots), a `slot_block` outside +// [-1, blocks), a hand outside [0, slots) and a selection entry outside [0, blocks) before it +// writes anything. A device launch cannot return a host status from inside its kernel, so this +// kernel guards instead: an out-of-range hand starts at 0, a map value outside its domain is not +// used to address memory, an out-of-range block id is left in `sel`, and nsel is clamped to +// `sel_pitch` so a bad count cannot steer a row into its neighbour. Those paths are the state +// fault libref refuses; a legal call never takes them and is bit-identical to the reference. +// +// The shape checks (ranks, dtypes, pitches, byte extent per block) belong to the shim below. Like +// every step-sized kernel it takes the launch's row count and row pitch from `sel`'s own extent, +// not from the ranged `M`/`sel_pitch` parameters: `M` arrives as the band's ceiling, so a one-row +// decode and a 625-token prefill would otherwise be refused (arch/common/rad_arch.h's "step-sized +// operands"). `M` is still checked as the ceiling it is, so a genuinely over-wide launch is refused. +// The ring depth is the operand's for the same reason: `slot_block`'s extent is the ring this call +// may address, and the declared `slots` is the ceiling it may not pass -- the pool is planned after +// declare, so a ring the engine sized smaller (--kv-resident) arrives shorter. +// It reads the two byte planes by row pitch in bytes, as libref does, so the same kernel serves +// every cache layout (`fp8`, `fp8_v4`, `k6_v4`, `bf16`) and the copy converts nothing. +// +// Returns a RAD status rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. + +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_launch.h" + +#include +#include + +namespace { + +constexpr int kThreads = 1024; + +/* A 16-byte vector as a builtin type, not `uint4`: the class copies through a memcpy call, and the + * miss copy needs its four loads to stay four loads (phase 6). */ +typedef unsigned int kv_v16 __attribute__((ext_vector_type(4))); + +/* The next power of two at or above `n`, clamped to what an i32 can index: the sort pads to one and + * the row's scratch is sized from the same expression. */ +static long long kv_pow2ceil(long long n) { + long long p = 1; + while (p < n && p <= (1LL << 30)) p <<= 1; + return p; +} + +/* The claim list's capacity, in ids, from the launch's own operands and the device's LDS room (the + * header above, "the claim list's size is derived"). `0` means a workgroup has no room at all, which + * the shim refuses. `*room_out` is the dynamic LDS room in ints, so the entry cache can take what the + * claim list leaves (header, "the entry cache"). */ +static int kv_claim_cap(long long M, long long pitch, int* room_out) { + /* Static LDS: the two reduction arrays and the scalars. Everything else is dynamic. */ + const size_t stat = (size_t)kThreads * 2 * sizeof(int) + 64; + static const int room = [] { + int dev = 0; + if (hipGetDevice(&dev) != hipSuccess) return 0; + hipDeviceProp_t pr{}; + if (hipGetDeviceProperties(&pr, dev) != hipSuccess) return 0; + if (pr.sharedMemPerBlock <= stat) return 0; + size_t r = (pr.sharedMemPerBlock - stat) / sizeof(int); + size_t p = 1; + while (p * 2 <= r) p *= 2; /* a power of two: the sort pads to one, and must not pad + * past the buffer */ + return (int)p; + }(); + *room_out = room; + if (room < 1) return 0; + /* The largest power of two the room holds: `cap` is always one, because the sort pads the list + * to a power of two and must not pad past the buffer. */ + int top = 1; + while (top <= room / 2) top *= 2; + const long long bound = M * pitch; /* the call's claim ceiling */ + int p = 1; + while ((long long)p < bound && p < top) p <<= 1; + return p; +} + +/* 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 rather than surviving every pass. */ +__device__ __forceinline__ int kv_heat_up(int h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); } +__device__ __forceinline__ int kv_heat_down(int h) { return h > 0 ? (h >> 1) : 0; } + +/* Ascending order of `n` distinct claim ids in the claim list, padded to a power of two with + * INT32_MAX, which sorts past every block id. A caller's buffer, because both paths sort: the whole + * claim set when it fits the list and one window of the id space when it does not. Block ids are + * distinct, so no equal pair decides anything. */ +__device__ __forceinline__ void kv_sort_claims(int* list, int n, int tid) { + int n2 = 1; + while (n2 < n) n2 <<= 1; + for (int i = n + tid; i < n2; i += kThreads) list[i] = INT32_MAX; + __syncthreads(); + for (int k = 2; k <= n2; k <<= 1) { + for (int j = k >> 1; j > 0; j >>= 1) { + for (int i = tid; i < n2; i += kThreads) { + const int ixj = i ^ j; + if (ixj > i) { + const int a = list[i], b = list[ixj]; + /* Ascending overall: a pair whose lower index sits in the first half of a + * k-block sorts up, the other half sorts down (bitonic). */ + const bool up = (i & k) == 0; + if (up ? a > b : a < b) { list[i] = b; list[ixj] = a; } + } + } + __syncthreads(); + } + } +} + +__global__ __launch_bounds__(kThreads) void kv_resolve_kernel( + int32_t* __restrict__ sel, const int32_t* __restrict__ nsel, + int32_t* __restrict__ res, int32_t* __restrict__ slot_block, + int32_t* __restrict__ slot_state, int32_t* __restrict__ ctl, + const uint8_t* __restrict__ host, uint8_t* __restrict__ cache, + int32_t* __restrict__ miss_block, int32_t* __restrict__ miss_slot, + int M, int blocks, int slots, int pitch, int bbytes, int sst_ld, int cap, int ecache) { + + __shared__ int s_epoch, s_lookups, s_nmiss, s_distinct, s_placed, s_overflow, s_claims, s_hits; + __shared__ int s_free; + __shared__ int s_cnt[kThreads], s_off[kThreads]; + /* The claim list, before the sort, `cap` ids of dynamic LDS (kv_claim_cap). Shared rather than + * the row's scratch because the sort reads every element from every thread; the scratch still + * holds the placed miss list, which is what the row declares and what the sweep and the copies + * walk in order. `ecache` ints follow it: the value this call's lookup read for each selection + * entry, which step 7 reuses (header, "the entry cache"). */ + R4D_DYN_LDS(int, s_dyn); + int* const s_list = s_dyn; + int* const s_ent = s_dyn + cap; + /* The claim gather's fill counter. */ + __shared__ int s_wc; + + const int tid = (int)threadIdx.x; + + /* ---- 1. the epoch ---- */ + if (tid == 0) { + s_epoch = ctl[0] + 1; + s_lookups = 0; + s_claims = 0; + s_hits = 0; + s_distinct = 0; + s_nmiss = 0; + s_placed = 0; + s_overflow = 0; + s_free = 0; + /* This call's miss count. A call that claims nothing returns it as zero below without + * reaching the sweep, so it is cleared here rather than left as the last call's. */ + ctl[2] = 0; + } + __syncthreads(); + const int epoch = s_epoch; + + /* ---- 2. one lookup per entry; the map is its own set ---- */ + int lookups = 0, hits = 0; + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + lookups += n; + for (int i = tid; i < n; i += kThreads) { + const size_t e = (size_t)q * pitch + i; + const int b = sel[e]; + if ((unsigned)b >= (unsigned)blocks) continue; + const int s = res[b]; + /* The value this lookup saw, for step 7: a hit's slot cannot move in this call (the + * sweep passes every slot this pass stamps with the epoch), so only an entry that was + * absent here needs the map read again. Header, "the entry cache". */ + if (ecache > 0) s_ent[e] = s; + if (s >= 0 && s < slots) { + /* The stamp is this call's mark on the slot and the union's counter at once: the + * exchange says whether this thread was the first to stamp it, so the ring is + * counted here instead of walked after the fact. */ + if (atomicExch(&slot_state[(size_t)s * sst_ld], epoch) != epoch) { + /* One bump a slot a call: the exchange says this thread was the first to stamp + * it, so a block twenty rows name gains one step of heat, not twenty. */ + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_up(slot_state[(size_t)s * sst_ld + 1]); + ++hits; + } + } else if (s == -1) { + /* One CAS wins per block, so this is the distinct-claim count, and the claim list + * needs no walk over `res` to find them. */ + if (atomicCAS(&res[b], -1, -2) == -1) { + const int k = atomicAdd(&s_claims, 1); + if (k < cap) s_list[k] = b; + } + } + } + } + /* The launch's hit count: a per-thread total, then the same warp-first reduction the union + * ends with. */ + s_cnt[tid] = hits; + __syncthreads(); + if (tid < 32) { + int t = 0; + for (int i = tid; i < kThreads; i += 32) t += s_cnt[i]; + s_off[tid] = t; + } + __syncthreads(); + if (tid == 0) { + int used = 0; + for (int t = 0; t < 32; ++t) used += s_off[t]; + s_hits = used; + s_lookups = lookups; + s_distinct = s_claims; + } + __syncthreads(); + + /* ---- 3. the canonical miss order: ascending block id ---- */ + const int claims = s_distinct; + const int want = claims < slots ? claims : slots; + if (claims > 0) { + if (claims <= cap) { + /* The list holds every claim, so sorting it says exactly what walking `res` said -- + * ascending block id -- over `claims` elements instead of `blocks`. */ + kv_sort_claims(s_list, claims, tid); + for (int i = tid; i < want; i += kThreads) miss_block[i] = s_list[i]; + } else { + /* Above the list: the launch is wide enough that `M * sel_pitch` -- the claim ceiling + * it declares -- passes the workgroup's LDS room, so the list is not held in shared + * memory. The claims are gathered from the selection into the row's scratch instead and + * sorted there, over `lookups` entries: the same ids, the same ascending order, and + * still nothing about `blocks` in the cost. Only a call that fits its ring takes this + * path; a call with more claims than the ring has slots cannot be listed at all and + * keeps the map walk below, because a sorted list of the smallest `slots` claims has to + * come from the whole claim set. */ + if (claims <= slots) { + if (tid == 0) s_wc = 0; + __syncthreads(); + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + /* One claim per distinct block: the map is the set, so a block four rows + * name enters the list once. -3 is "collected", restored below. */ + if (atomicCAS(&res[b], -2, -3) == -2) { + const int k = atomicAdd(&s_wc, 1); + if (k < slots) miss_block[k] = b; + } + } + } + __syncthreads(); + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + if (res[b] == -3) res[b] = -2; + } + } + __syncthreads(); + /* `claims` ids, padded to a power of two: the row's scratch is sized for exactly + * that (r4d_rad_kv_resolve_scratch). */ + kv_sort_claims(miss_block, claims, tid); + } else { + /* More claims than the ring can hold: this call has overflowed whatever it places, + * so the sweep stops at its first unplaceable miss and `ctl[3]` latches. The list + * here is `blocks`-wide because the ascending order of the WHOLE claim set is the + * contract, and with no structure able to hold it the map is where it lives. A legal + * call -- one the ring can hold -- never reaches this. */ + const int chunk = (blocks + kThreads - 1) / kThreads; + const int lo = (int)((long long)tid * chunk); + const int hi = lo + chunk < blocks ? lo + chunk : blocks; + const bool vec4 = (lo & 3) == 0 && (hi & 3) == 0 && ((uintptr_t)res & 15u) == 0; + int c = 0; + if (vec4) { + const int4* const r4 = (const int4*)res; + for (int i = lo / 4; i < hi / 4; ++i) { + const int4 v = r4[i]; + c += (v.x == -2) + (v.y == -2) + (v.z == -2) + (v.w == -2); + } + } else { + for (int b = lo; b < hi; ++b) c += (res[b] == -2); + } + s_cnt[tid] = c; + s_off[tid] = c; + __syncthreads(); + for (int step = 1; step < kThreads; step <<= 1) { + const int v = tid >= step ? s_off[tid - step] : 0; + __syncthreads(); + s_off[tid] += v; + __syncthreads(); + } + __syncthreads(); + int pos = s_off[tid] - s_cnt[tid]; + if (vec4) { + const int4* const r4 = (const int4*)res; + for (int i = lo / 4; i < hi / 4; ++i) { + const int4 v = r4[i]; + if (v.x == -2 && pos < slots) miss_block[pos++] = 4 * i; + if (v.y == -2 && pos < slots) miss_block[pos++] = 4 * i + 1; + if (v.z == -2 && pos < slots) miss_block[pos++] = 4 * i + 2; + if (v.w == -2 && pos < slots) miss_block[pos++] = 4 * i + 3; + } + } else { + for (int b = lo; b < hi; ++b) + if (res[b] == -2 && pos < slots) miss_block[pos++] = b; + } + __syncthreads(); + } + } + if (tid == 0) { + /* The list is the first `want` claims in ascending order whichever path built it. */ + s_nmiss = want; + s_overflow = claims > slots; + s_placed = 0; + } + __syncthreads(); + } + + /* ---- 3b. how many slots are free ---- */ + /* A free slot is claimed before any resident block is evicted (phase 4), and this is what says + * whether there is one to claim: a call whose ring is full -- where every slot holds a block -- + * must not pay a turn of scanning per miss to discover it, and above that a full ring never + * becomes free again during the call. Counting in parallel costs one coalesced pass over the + * two slot maps; the sweep then reads the count and, when it is zero, goes straight to CLOCK. + * A slot this call stamped is not free whatever it holds: it is the call's own. */ + if (claims > 0) { + int nf = 0; + for (int s = tid; s < slots; s += kThreads) + if (slot_block[s] < 0 && slot_state[(size_t)s * sst_ld] != epoch) ++nf; + if (nf != 0) atomicAdd(&s_free, nf); + } + __syncthreads(); + + /* ---- 4. one victim per miss: the block's own slot first, else a free slot, else CLOCK ---- */ + /* Identity first: a block whose id fits the ring and whose own slot is free goes there, so + * res[b] = b for a context shorter than the ring. The attention's gather is a long run of + * adjacent block ids, and a layer's slots are 2 KiB apart inside one stripe, so identity turns + * that run into a sequential walk of one stripe instead of the order the blocks entered the + * selection. + * + * It is only a placement preference, never a replacement one: it takes a slot only when that + * slot is free, and it does not move the hand, so a ring that cannot give identity the slot + * falls through to the walk below with the hand exactly where it was. The fallback is free slot + * first, then CLOCK, so a depth where most ids are past `slots` places the same blocks in the + * same slots. + * + * A free slot (nothing resident in it) is not a victim at all: taking it costs no block, so + * every free slot is claimed before a live one is even considered. CLOCK's second chance over + * the heat counter is what a ring with no free slot falls back to, and the free scan has no + * side effect when it finds nothing (it halves no counter and leaves the hand where it + * started), so a full ring takes exactly the victim the sweep below names. + * + * `free_left` is the call's free-slot count from phase 3b, decremented as the sweep fills one. + * Once it is zero nothing can free a slot -- a placement makes a free slot live and an eviction + * re-points a live one -- so a full ring pays the count once, not a scan per miss. */ + if (tid == 0 && claims > 0) { + int hand = ctl[1]; + /* A hand outside the ring is a state fault libref refuses; start at the beginning + * rather than address outside it. */ + if (hand < 0 || hand >= slots) hand = 0; + int placed = 0; + bool overflow = s_overflow; + int free_left = s_free; + const int nmiss = s_nmiss; + for (int k = 0; k < nmiss; ++k) { + const int b = miss_block[k]; + int victim = -1; + /* Identity: the block's own slot, if the id fits the ring and the slot is free (or + * already holds it). Leaving the hand alone is what keeps the fallback identical. */ + if (b < slots) { + const int want = b; + if (slot_state[(size_t)want * sst_ld] != epoch && + (slot_block[want] < 0 || slot_block[want] == b)) + victim = want; + } + /* Free first, in the same hand order CLOCK walks, so a ring with frees to give + * places every miss identically in both implementations. A stamp of this call's epoch + * is never taken, free or not: it is a slot the call itself already uses. */ + if (victim < 0 && free_left > 0) { + int h = hand; + for (int scanned = 0; scanned < slots; ++scanned) { + const int s = h; + h = h + 1 == slots ? 0 : h + 1; + if (slot_state[(size_t)s * sst_ld] == epoch) continue; /* used by this call */ + if (slot_block[s] >= 0) continue; /* holds a block */ + victim = s; + hand = h; + break; + } + if (victim < 0) free_left = 0; + } + if (victim < 0) { + for (long long scanned = 0; scanned < 3LL * slots; ++scanned) { + const int s = hand; + hand = hand + 1 == slots ? 0 : hand + 1; + if (slot_state[(size_t)s * sst_ld] == epoch) continue; /* used by this call */ + const int old = slot_block[s]; + if (old >= 0 && old < blocks && + slot_state[(size_t)s * sst_ld + 1] > 0) { /* second chance */ + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_down(slot_state[(size_t)s * sst_ld + 1]); + continue; + } + victim = s; + break; + } + } + if (victim < 0) { overflow = true; break; } + /* ---- 5. re-point both maps ---- */ + const int s = victim; + const int old = slot_block[s]; + if (old < 0 && free_left > 0) --free_left; /* a free slot the sweep just filled */ + if (old >= 0 && old < blocks) res[old] = -1; + slot_block[s] = b; + slot_state[(size_t)s * sst_ld] = epoch; + slot_state[(size_t)s * sst_ld + 1] = + kv_heat_up(slot_state[(size_t)s * sst_ld + 1]); + res[b] = s; + miss_slot[k] = s; + ++placed; + } + ctl[1] = hand; + ctl[2] = placed; + if (overflow) ctl[3] = 1; + s_placed = placed; + } + __syncthreads(); + + /* A miss the sweep could not place is not resident: undo every remaining claim, so the next + * call may claim them again. A `res` entry still -2 here is by definition such a claim (a + * placed one holds its slot), and every claim is named by at least one selection entry, so the + * selection reaches all of them: `lookups` entries instead of `blocks` map entries, and the + * write is idempotent, so an entry repeating a block is harmless. The list is the shorter pass + * when it holds every claim, which is the normal case. */ + if (claims > 0) { + if (s_distinct <= slots) { + for (int k = tid; k < s_distinct; k += kThreads) + if (res[miss_block[k]] == -2) res[miss_block[k]] = -1; + } else { + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const int b = sel[(size_t)q * pitch + i]; + if ((unsigned)b >= (unsigned)blocks) continue; + if (res[b] == -2) res[b] = -1; + } + } + } + } + __syncthreads(); + + /* ---- 6. the copies, one block each, in miss order, in this launch ---- */ + /* One warp a miss, so every miss's host read is in flight at once and each warp's lanes are + * independent. One 2 KiB copy out of the host mirror is PCIe transactions at ~1 us of latency + * each, and a decode launch takes tens of them: a loop that waits out one miss at a time, or a + * flattened loop that re-reads `miss_block`/`miss_slot` from the scratch for every lane, spends + * the launch waiting. The copies are independent -- each writes its own slot -- so the order + * between them is the miss order only for the record. + * + * Four loads per thread, issued before any of them is stored from. A wave issues in order and a + * store waits on its load, so `dst[i] = src[i]` at a stride of 32 makes the next iteration's load + * wait behind the previous iteration's store and the 2 KiB copy pays the mirror's read latency + * four times over instead of once (the trip count is `block_bytes`, a runtime value, so the + * compiler cannot unroll it). Loading the four vectors of one thread's quarter of the block + * first puts four requests in flight, and a block is + * a whole number of them at the declared geometry (2 KiB = 128 vectors = one full turn of the + * group), so the common path never takes the tail. Four more VGPRs: the kernel goes 32 -> 36 + * with no spill, and it runs one workgroup by design. + * + * The vectors are `kv_v16`, not `uint4`: that class's assignment is a 16-byte memcpy call, and a + * memcpy is a load and a store that are adjacent by construction however the four are written in + * the source, which is the serialised shape this loop exists to avoid. Builtin vectors leave the + * four as four loads and four stores, which is what the scheduler needs. Same bytes either way. */ + const int placed = s_placed; + const int lane = tid & 31; + if (bbytes >= 16 && bbytes % 16 == 0) { + const int vec = bbytes / 16; + for (int k = tid >> 5; k < placed; k += kThreads / 32) { + const kv_v16* __restrict__ const src = + (const kv_v16*)host + (size_t)miss_block[k] * vec; + kv_v16* __restrict__ const dst = (kv_v16*)cache + (size_t)miss_slot[k] * vec; + int i = lane; + for (; i + 96 < vec; i += 128) { + const kv_v16 a = src[i], b = src[i + 32], c = src[i + 64], d = src[i + 96]; + dst[i] = a; + dst[i + 32] = b; + dst[i + 64] = c; + dst[i + 96] = d; + } + /* A block that is not a whole number of four-wide turns -- `block_bytes` not a multiple + * of 2048 -- finishes at the original one-vector stride, so every lane sequence is + * covered exactly once whatever the pitch. */ + for (; i < vec; i += 32) dst[i] = src[i]; + } + } else { + for (int k = tid >> 5; k < placed; k += kThreads / 32) { + const uint8_t* src = host + (size_t)miss_block[k] * bbytes; + uint8_t* const dst = cache + (size_t)miss_slot[k] * bbytes; + for (int i = lane; i < bbytes; i += 32) dst[i] = src[i]; + } + } + + /* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */ + for (int q = 0; q < M; ++q) { + int n = nsel[q]; + if (n < 0) n = 0; + if (n > pitch) n = pitch; + for (int i = tid; i < n; i += kThreads) { + const size_t e = (size_t)q * pitch + i; + const int b = sel[e]; + if ((unsigned)b >= (unsigned)blocks) continue; + /* A hit's slot is the one step 2 read; anything absent then (-1, -2, -3) only the map + * knows where the sweep placed it. Same index, same thread, so no barrier is needed. */ + int s = ecache > 0 ? s_ent[e] : -1; + if (s < 0) s = res[b]; + sel[e] = s >= 0 ? s : 0; + } + } + + /* The distinct blocks this call touched, for the union the caller reports: the slots this call + * hit or filled (counted in phase 2 and by the sweep) plus the claims it could not place. Both + * halves are known by now -- distinct hit slots and distinct claimed blocks -- and an entry + * count would overcount them, because many of a launch's rows share swaths of the history. + * Nothing walks the ring for it. */ + if (tid == 0) { + const int placed = s_placed; + const int uni = s_hits + s_distinct; + if (uni > ctl[10]) ctl[10] = uni; + if (placed > ctl[11]) ctl[11] = placed; + /* The depth the claim list had to hold, which is what the next size of it is derived from. */ + if (s_distinct > ctl[12]) ctl[12] = s_distinct; + uint64_t* const ctr = (uint64_t*)(ctl + 4); + ctr[0] += (uint64_t)placed; + ctr[1] += (uint64_t)s_lookups; + ctr[2] += 1u; + ctl[0] = epoch; + } +} + +} // namespace + +/* `sel` [M][sel_pitch] i32, block ids in, ring slots out + * `nsel` [M] i32, valid entries of each row + * `res` [blocks] i32, block -> slot, -1 absent, -2 claimed by this call + * `slot_block` [slots] i32, slot -> block, -1 free + * `slot_state` [slots][sst_ld] i32, [s][0] epoch of last use, [s][1] two-bit heat counter + * `ctl` [16] i32, [0] epoch, [1] hand, [2] placed, [3] overflow, u64 from [4] + * `host` [blocks][bbytes] u8, the layer's host mirror + * `cache` [slots][bbytes] u8, the layer's device ring + * `miss_block`, `miss_slot` the row scratch, `next_pow2(slots)` ids then `slots` slots + * `cap` the claim list's capacity, from kv_claim_cap + * `ecache` the entry cache's capacity in ints: `M * sel_pitch`, or 0 when + * the claim list leaves no room for it (header, "the entry cache") + * + * The two planes are addressed by `bbytes` alone, so the shim has already checked that each + * block's row pitch in bytes is exactly `block_bytes` and that its trailing extents fill it. */ +static int r4d_kv_resolve_emit(long sel, long nsel, long res, long slot_block, long slot_state, + long ctl, long host, long cache, long miss_block, long miss_slot, + int M, int blocks, int slots, int pitch, int bbytes, int sst_ld, + RadStream stream) { + if (!sel || !nsel || !res || !slot_block || !slot_state || !ctl || !host || !cache || + !miss_block || !miss_slot) + return R4D_NO(RAD_E_INVAL); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0 || sst_ld < 2) + return R4D_NO(RAD_E_SHAPE); + /* The list is sized from this launch's own operands. A workgroup with no LDS room for even one + * id cannot run the op at all, which is a shape the caller cannot satisfy rather than a slow + * launch: refuse it. */ + int room = 0; + const int cap = kv_claim_cap(M, pitch, &room); + if (cap < 1) return R4D_NO(RAD_E_SHAPE); + /* One int a selection entry for the entry cache (the header), while the room the claim list + * leaves holds them all: a decode launch caches its 513, a prefill this wide does not and step 7 + * reads the map again. */ + const long long entries = (long long)M * pitch; + const int ecache = entries <= (long long)(room - cap) ? (int)entries : 0; + return R4D_EMIT(stream, kv_resolve_kernel, dim3(1), dim3(kThreads), + (uint32_t)(cap + ecache) * sizeof(int), + (int32_t*)sel, (const int32_t*)nsel, (int32_t*)res, (int32_t*)slot_block, + (int32_t*)slot_state, (int32_t*)ctl, (const uint8_t*)host, (uint8_t*)cache, + (int32_t*)miss_block, (int32_t*)miss_slot, M, blocks, slots, pitch, + bbytes, sst_ld, cap, ecache); +} + +/* ============================================================== the plugin ABI entry point */ + +enum { KR_SEL = 0, KR_NSEL = 1, KR_RES = 2, KR_SBLK = 3, KR_SST = 4, KR_CTL = 5, KR_HOST = 6, + KR_CACHE = 7 }; + +/* Fan a byte extent into the shape's trailing elements: one block a row, dense, so the row pitch + * in bytes and the product of the trailing extents' element bytes both equal `block_bytes`. */ +static int r4d_kv_block_row_bytes(const RadTensor* t, long long* out) { + long long acc = 1; + for (unsigned d = 1; d < t->rank; ++d) acc *= t->shape[d]; + *out = acc * (long long)rad_dtype_bytes(t->dtype, 1); + return t->stride[0] * (long long)rad_dtype_bytes(t->dtype, 1) == *out ? RAD_OK : RAD_E_STRIDE; +} + +extern "C" int r4d_rad_kv_resolve(const RadArgs* a, RadStream stream) { + const RadTensor* se = r4d_opt(a, KR_SEL); + const RadTensor* ns = r4d_opt(a, KR_NSEL); + const RadTensor* re = r4d_opt(a, KR_RES); + const RadTensor* sb = r4d_opt(a, KR_SBLK); + const RadTensor* st = r4d_opt(a, KR_SST); + const RadTensor* ct = r4d_opt(a, KR_CTL); + const RadTensor* ho = r4d_opt(a, KR_HOST); + const RadTensor* ca = r4d_opt(a, KR_CACHE); + if (!se || !ns || !re || !sb || !st || !ct || !ho || !ca) + return R4D_NO(RAD_E_INVAL); + + /* `M` is a RANGED parameter, so the resolved geometry carries the band's ceiling (max_tok), + * not this launch's rows: a 625-token prefill and a one-row decode both arrive with 2048 here. + * The operand names the call, as arch/common/rad_arch.h's "step-sized operands" rule says, so + * the row count is `sel`'s own extent and the parameter is only the ceiling it may not pass. */ + const long long band = r4d_geti_or(a, "M", 0); + const long long M = se->shape[0]; + const long long blocks = r4d_geti_or(a, "blocks", 0); + /* The ring depth is the operand's, for the same reason: the pool is planned after declare, so + * the declared `slots` is the context bound and a ring the engine sized smaller + * (--kv-resident) arrives as a shorter `slot_block`. The parameter is the ceiling a + * call may not pass (libref/ref_kvstream.cpp, "The parameters"). */ + const long long slots_decl = r4d_geti_or(a, "slots", 0); + const long long slots = sb->shape[0]; + /* The row pitch is the operand's too. Reading it from `sel_pitch` would let a view whose rows + * are wider or narrower than its declared geometry be rewritten into its neighbour. */ + const long long declared_pitch = r4d_geti_or(a, "sel_pitch", 0); + const long long pitch = r4d_row_pitch(se); + const long long bbytes = r4d_geti_or(a, "block_bytes", 0); + if (M <= 0 || blocks <= 0 || slots <= 0 || slots > slots_decl || pitch <= 0 || bbytes <= 0) + return R4D_NO(RAD_E_SHAPE); + if (M > INT32_MAX || blocks > INT32_MAX || slots > INT32_MAX || pitch > INT32_MAX || + bbytes > INT32_MAX) + return R4D_NO(RAD_E_SHAPE); + /* A launch above the band was resolved against constraints it does not satisfy. */ + if (band > 0 && M > band) return R4D_NO(RAD_E_SHAPE); + if (declared_pitch > 0 && pitch != declared_pitch) return R4D_NO(RAD_E_STRIDE); + + /* The map and the counts are one format, written by one op and read by the writer and the + * sweep: i32, dense. */ + const RadTensor* state[] = { se, ns, re, sb, st, ct }; + for (const RadTensor* t : state) + if (t->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (se->rank != 2 || st->rank != 2) return R4D_NO(RAD_E_SHAPE); + if (se->stride[1] != 1) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(ns) < M || ns->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(re) < blocks || re->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (sb->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (st->shape[0] < slots || st->stride[1] != 1 || st->stride[0] < 2) + return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(ct) < 16 || ct->stride[0] != 1) return R4D_NO(RAD_E_SHAPE); + if (ho->rank < 2 || ca->rank < 2) return R4D_NO(RAD_E_SHAPE); + if (ho->shape[0] < blocks || ca->shape[0] < slots) return R4D_NO(RAD_E_SHAPE); + + /* One block of one layer: the mirror's row and the pool's slot are the same bytes, and the + * copy length `block_bytes` is both pitches. The pool arrives as a KV group's cache, so its + * dtype is the cache layout's, not u8; only the byte pitch is fixed. */ + long long hdense = 0, pdense = 0; + if (r4d_kv_block_row_bytes(ho, &hdense) != RAD_OK || hdense != bbytes) + return R4D_NO(RAD_E_STRIDE); + if (r4d_kv_block_row_bytes(ca, &pdense) != RAD_OK || pdense != bbytes) + return R4D_NO(RAD_E_STRIDE); + /* The counters are read as u64 in an i32 block. */ + if (((uintptr_t)ct->data & 7u) != 0) return R4D_NO(RAD_E_STRIDE); + + /* The row's scratch: `nlist` ids (the miss list, padded to a power of two when a wide launch + * sorts it there), then `slots` slots. */ + const int64_t nlist = kv_pow2ceil(slots); + const long long need = (nlist + slots) * 4; + if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_INVAL); + int32_t* const miss_block = (int32_t*)a->scratch; + int32_t* const miss_slot = (int32_t*)((char*)a->scratch + nlist * 4); + + return r4d_kv_resolve_emit(r4d_addr(se), r4d_addr(ns), r4d_addr(re), r4d_addr(sb), + r4d_addr(st), r4d_addr(ct), r4d_addr(ho), r4d_addr(ca), + (long)(uintptr_t)miss_block, (long)(uintptr_t)miss_slot, + (int)M, (int)blocks, (int)slots, (int)pitch, (int)bbytes, + (int)st->stride[0], stream); +} + +/* The miss list -- `next_pow2(slots)` block ids, because a launch too wide for the shared claim list + * sorts the list in this scratch -- then `slots` slots (the header above). */ +extern "C" int64_t r4d_rad_kv_resolve_scratch(const RadArgs* a) { + const long long slots = r4d_geti_or(a, "slots", 0); + if (slots <= 0 || slots > INT32_MAX) return 0; + return (kv_pow2ceil(slots) + slots) * 4; +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 74355602..0a67c3d6 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -688,6 +688,94 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel( } } +// The store of a streamed KV group: `kv_store_fp8` into the group's two copies. +// +// A streamed group's ring is `slots` blocks deep while its block-id space is `blocks`, so a block's +// id is not an address. Its host mirror is: +// +// host[blocks, kv_heads, block_size, 2 * head_dim] one block a row, identity layout +// +// and this kernel writes a token's k and v into the mirror's block `slot / block_size` ALWAYS, and +// into the ring at `res[block]` only when the map says the block is resident. Both planes have the +// same row pitch, so one offset serves both and the two copies cannot disagree. +// +// The residency test is here, not in the resolve, because the block a decode step writes is +// usually the one the previous step already made resident: a mirror-only writer would leave the +// ring's copy of that block short of this step's tokens, and the resolve does not re-copy a +// resident block. The caller orders store, then resolve, then attention, so a block that is NOT +// resident yet gets this step's bytes through the mirror and is copied in whole by the resolve. +// +// STATE FAULTS. libref refuses a slot naming a block past the id space and a map entry outside +// [-1, slots) before writing anything. A device launch cannot return a host status, so this kernel +// guards: a token whose block is out of range stores nothing, and a map entry outside its domain +// reads as not resident (the mirror is still written, and the resolve refuses the step). A legal +// call never takes either path and is bit-identical to the reference. +template +__global__ __launch_bounds__(kThreads) void kv_store_streamed_kernel( + const uint16_t* __restrict__ k, const uint16_t* __restrict__ v, + const int32_t* __restrict__ slot, uint8_t* __restrict__ kv, + const int32_t* __restrict__ res, uint8_t* __restrict__ host, + uint32_t head_dim, uint32_t kv_heads, uint32_t block_size, uint32_t blocks, uint32_t slots, + uint32_t k_ld, uint32_t v_ld, float k_inv, float v_inv) { + const uint32_t t = blockIdx.x; + const int32_t s = slot[t]; + if (s < 0) return; + const uint32_t blk = (uint32_t)s / block_size, off = (uint32_t)s % block_size; + if (blk >= blocks) return; + /* Both planes are byte planes of the same paged layout; a bf16 element is two bytes, so every + * offset and pitch doubles while the row arithmetic stays one expression. */ + const size_t EB = BF16 ? 2 : 1; + const size_t row = (size_t)kv_heads * block_size * 2 * head_dim * EB; + const size_t so = (size_t)off * 2 * head_dim * EB; + uint8_t* const m = host + (size_t)blk * row + so; + const int32_t sl = res[blk]; + /* A map entry outside [-1, slots) is not an address: treat it as absent. */ + uint8_t* const c = (sl >= 0 && (uint32_t)sl < slots) ? kv + (size_t)sl * row + so : nullptr; + const size_t head_step = (size_t)block_size * 2 * head_dim * EB; + + for (uint32_t j = threadIdx.x * 4u; j < kv_heads * head_dim; j += kThreads * 4u) { + const uint32_t h = j / head_dim, d = j % head_dim; + uint8_t* const mrow = m + (size_t)h * head_step; + uint8_t* const crow = c ? c + (size_t)h * head_step : nullptr; + float kf[4], vf[4]; +#pragma unroll + for (int e = 0; e < 4; ++e) { + kf[e] = bf16_to_f32(k[(size_t)t * k_ld + j + (uint32_t)e]) * k_inv; + vf[e] = bf16_to_f32(v[(size_t)t * v_ld + j + (uint32_t)e]) * v_inv; + } + if constexpr (BF16) { + /* kv_store_bf16's bytes: the value itself, no descales (k_inv/v_inv are 1). */ + uint16_t* const mk = (uint16_t*)mrow; + uint16_t* const mv = (uint16_t*)(mrow + (size_t)head_dim * 2); + uint16_t* const ck = crow ? (uint16_t*)crow : nullptr; + uint16_t* const cv = crow ? (uint16_t*)(crow + (size_t)head_dim * 2) : nullptr; +#pragma unroll + for (int e = 0; e < 4; ++e) { + const uint16_t kb = f32_to_bf16(kf[e]), vb = f32_to_bf16(vf[e]); + mk[d + e] = kb; + mv[d + e] = vb; + if (ck) { ck[d + e] = kb; cv[d + e] = vb; } + } + } else { + int pk = 0, pv = 0; + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[0], -448.0f), 448.0f), + fminf(fmaxf(kf[1], -448.0f), 448.0f), pk, false); + pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf[2], -448.0f), 448.0f), + fminf(fmaxf(kf[3], -448.0f), 448.0f), pk, true); + pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf[0], -448.0f), 448.0f), + fminf(fmaxf(vf[1], -448.0f), 448.0f), pv, false); + pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf[2], -448.0f), 448.0f), + fminf(fmaxf(vf[3], -448.0f), 448.0f), pv, true); + *(uint32_t*)(mrow + d) = (uint32_t)pk; + *(uint32_t*)(mrow + head_dim + d) = (uint32_t)pv; + if (crow) { + *(uint32_t*)(crow + d) = (uint32_t)pk; + *(uint32_t*)(crow + head_dim + d) = (uint32_t)pv; + } + } + } +} + // The fp8_v4 store: K as kv_store_fp8 writes it, V as int4 in groups of 32 with an f16 scale // (absmax / 7). Four columns a thread as above, so a group of 32 is 8 lanes; head_dim is a multiple // of 32, so a group never straddles two heads. A token's row is `row` bytes. K6 is the k6_v4 store: @@ -2220,6 +2308,70 @@ static int kv_store_q4(const RadArgs* a, RadStream stream, int k6) { extern "C" int r4d_rad_kv_store_fp8v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 0); } extern "C" int r4d_rad_kv_store_k6v4(const RadArgs* a, RadStream stream) { return kv_store_q4(a, stream, 1); } +/* The store of a streamed group: `kv_store`'s geometry and E4M3 conversion, plus the group's + * residency map (`res`) and its host mirror (`host`). The mirror is the truth and is written for + * every token with a slot; the ring is written only when `res[block] >= 0`. Both are one block a + * row of the same byte pitch, so the row arithmetic is the cache's, unchanged. + * + * `res` is read, never written: residency is the resolve's decision, and this op must not move the + * map under a selection the indexer already resolved. A block id past the mirror's extent or a map + * entry outside [-1, slots) is a state fault that libref refuses; the kernel guards instead (see + * kv_store_streamed_kernel), since a device launch cannot return a host status. + * + * The cache is E4M3 or bf16. Streaming is dtype-agnostic beyond the two writers: the mirror and the + * ring are byte planes of one paged layout whose pitch is `block_bytes`, so a bf16 group doubles + * every offset and stores the values kv_store_bf16 stores. */ +extern "C" int r4d_rad_kv_store_streamed(const RadArgs* a, RadStream stream) { + KvStoreGeom g{}; + const int rc = kv_store_geom(a, &g); + if (rc != RAD_OK) return rc; + if (g.kv->dtype != RAD_F8E4M3 && g.kv->dtype != RAD_BF16) + return R4D_NO(RAD_E_UNSUPPORTED); + /* Four columns per thread, so a head must be whole groups. */ + if (g.head_dim % 4) return R4D_NO(RAD_E_SHAPE); + + const RadTensor* res = r4d_opt(a, 4); + const RadTensor* host = r4d_opt(a, 5); + if (!res || !host) return R4D_NO(RAD_E_INVAL); + if (res->dtype != RAD_I32 || !r4d_contig(res)) return R4D_NO(RAD_E_STRIDE); + if (host->dtype != RAD_U8 || !r4d_contig(host) || host->rank != 2) + return R4D_NO(RAD_E_STRIDE); + + const long long row = g.kv_heads * g.block_size * 2 * g.head_dim * + (g.kv->dtype == RAD_BF16 ? 2 : 1); + const long long blocks = host->shape[0], slots = g.kv->shape[0]; + if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE); + /* Both planes are dense rows of one block, so the same offset addresses the same element. */ + if (host->shape[1] != row || host->stride[0] != row) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE); + + const double ks = r4d_getf(a, "k_scale", 1.0); + const double vs = r4d_getf(a, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + + const long long k_ld = g.k_ld ? g.k_ld : g.kv_heads * g.head_dim; + const long long v_ld = g.v_ld ? g.v_ld : g.kv_heads * g.head_dim; + const bool bf16 = g.kv->dtype == RAD_BF16; + /* kv_store_bf16 stores the value itself, so a bf16 group uses no descales. */ + const float k_inv = bf16 ? 1.0f : (float)(1.0 / ks); + const float v_inv = bf16 ? 1.0f : (float)(1.0 / vs); + if (bf16) + return R4D_EMIT(stream, kv_store_streamed_kernel<1>, dim3((uint32_t)g.T), dim3(kThreads), + 0, (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (const int32_t*)r4d_addr(res), (uint8_t*)r4d_addr(host), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)blocks, (uint32_t)slots, (uint32_t)k_ld, (uint32_t)v_ld, + k_inv, v_inv) == RAD_OK ? RAD_OK : RAD_E_DEVICE; + return R4D_EMIT(stream, kv_store_streamed_kernel<0>, dim3((uint32_t)g.T), dim3(kThreads), 0, + (const uint16_t*)r4d_addr(g.k), (const uint16_t*)r4d_addr(g.v), + (const int32_t*)r4d_addr(g.sm), (uint8_t*)r4d_addr(g.kv), + (const int32_t*)r4d_addr(res), (uint8_t*)r4d_addr(host), + (uint32_t)g.head_dim, (uint32_t)g.kv_heads, (uint32_t)g.block_size, + (uint32_t)blocks, (uint32_t)slots, (uint32_t)k_ld, (uint32_t)v_ld, + k_inv, v_inv) == RAD_OK ? RAD_OK : RAD_E_DEVICE; +} + /* ------------------------------------------------------------------ logits_gemm * * gemm_nt's arithmetic with `n_vocab`/`n_embd` for N/K, but writing f32 (see the kernel above). diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 87d99131..61da0830 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -521,6 +521,7 @@ int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gdn_gated_norm_hq_i8 (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate (const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs*, RadStream); +int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store_fp8v4(const RadArgs*, RadStream); int r4d_rad_qk_norm_rope_gate_kv_store_k6v4(const RadArgs*, RadStream); int r4d_rad_rope_table (const RadArgs*, RadStream); @@ -557,6 +558,9 @@ int r4d_rad_qsa_block_key (const RadArgs*, RadStream); int r4d_rad_qsa_score (const RadArgs*, RadStream); int r4d_rad_qsa_select (const RadArgs*, RadStream); int64_t r4d_rad_qsa_select_scratch(const RadArgs*); +int r4d_rad_kv_resolve (const RadArgs*, RadStream); +int64_t r4d_rad_kv_resolve_scratch(const RadArgs*); +int r4d_rad_kv_store_streamed(const RadArgs*, RadStream); int r4d_rad_qsa_tail_store (const RadArgs*, RadStream); int r4d_rad_qsa_work (const RadArgs*, RadStream); int r4d_rad_sample_chain (const RadArgs*, RadStream); @@ -819,6 +823,7 @@ int r4d_shape_fill (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_silu_mul (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_rope (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_kv_store (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_kv_store_streamed (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_logits_gemm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_sample_penalties (const RadParam*, int, int operand, RadOpdDesc*); @@ -839,6 +844,8 @@ int r4d_shape_qk_norm_rope_gate_kv_store(const RadParam*, int, int operand, RadO int r4d_shape_qkv_norm_rope (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qkv_norm_rope_kv_store(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_add_rmsnorm(const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_qk_norm_rope_gate_kv_store_streamed(const RadParam*, int, int operand, + RadOpdDesc*); int r4d_shape_rope_table (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gdn_gated_rmsnorm (const RadParam*, int, int operand, RadOpdDesc*); @@ -884,6 +891,7 @@ int r4d_shape_gram_accum (const RadParam*, int, int operand, RadOpdDesc* int r4d_shape_qsa_block_key (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_score (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_select (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_kv_resolve (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_tail_store (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_qsa_work (const RadParam*, int, int operand, RadOpdDesc*); @@ -913,6 +921,8 @@ int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadF int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_add_rmsnorm(const RadParam*, int, uint64_t, int, RadFuseStep*); +int r4d_fuse_qk_norm_rope_gate_kv_store_streamed(const RadParam*, int, uint64_t, int, + RadFuseStep*); int r4d_fuse_ar_rmsnorm_quant_fp8(const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_ar_gather_hc_write (const RadParam*, int, uint64_t, int, RadFuseStep*); int r4d_fuse_attn_paged_gate_quant(const RadParam*, int, uint64_t, int, RadFuseStep*); diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 9274a31f..43598c1e 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -50,10 +50,18 @@ struct QkKvStore { int v_pitch, block_size, n_blocks; float k_inv, v_inv; int row; /* fp8_v4 / k6_v4: a token's bytes in a page, 25 or 22 * HD / 16 */ + /* QK_KV_STREAMED only: the group's host mirror and per-layer residency map, as + * kv_store_streamed takes them (libr4d/r4d_model_bf16.hip). `blocks` is the mirror's block + * count (the id space) while `n_blocks` stays the ring depth. */ + const int32_t* res; + void* host; + int blocks; }; -/* The cache forms KV selects. */ -enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4 }; +/* The cache forms KV selects. The two STREAMED forms are the same store with two destination + * planes: E4M3 (the fp8 QSA family) and bf16 (the default cache dtype). */ +enum { QK_KV_NONE = 0, QK_KV_FP8 = 1, QK_KV_BF16 = 2, QK_KV_F8V4 = 3, QK_KV_K6V4 = 4, + QK_KV_STREAMED = 5, QK_KV_STREAMED_BF16 = 6 }; /* KV folds kv_store in: a k head's block, holding the token's rotated k one element per lane, also * writes that element and the head's v element into the cache at the token's slot, as E4M3 with @@ -151,7 +159,56 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( if constexpr (KV != QK_KV_NONE) { if (isk && t < HD) { const int32_t sl = kvs.slot[tok]; - if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) { + /* A streamed group's cache is the ring and its truth is the host mirror: the token goes to + * the mirror's block row ALWAYS and to the ring slot only where the residency map says the + * block is resident, exactly as kv_store_streamed writes it (libref/ref_attn.cpp states why + * the test belongs in the writer). The block id bounds the mirror, the map bounds the ring, + * and a slot names a ring block only through `res`. */ + if constexpr (KV == QK_KV_STREAMED || KV == QK_KV_STREAMED_BF16) { + if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.blocks) { + const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size; + const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size; + /* One element of each plane. The mirror and the ring are byte planes of the same paged + * layout and `block_bytes` is their pitch, so a bf16 element is two bytes at twice the + * fp8 offset. */ + const size_t EB = KV == QK_KV_STREAMED_BF16 ? 2 : 1; + const size_t rowb = (size_t)(2 * HD) * EB; + const size_t at = ((size_t)blk * nkv * kvs.block_size + off) * rowb + + (size_t)lh * kvs.block_size * rowb; + const __hip_bfloat16 kb = __float2bfloat16(res); + const __hip_bfloat16 vb = kvs.v[(size_t)tok * kvs.v_pitch + (size_t)lh * HD + t]; + const int32_t rs = kvs.res[blk]; + unsigned char* const m = (unsigned char*)kvs.host + at; + unsigned char* const c = + (rs >= 0 && (uint32_t)rs < (uint32_t)kvs.n_blocks) + ? (unsigned char*)kvs.cache + + (((size_t)rs * nkv * kvs.block_size + off) * rowb + + (size_t)lh * kvs.block_size * rowb) + : nullptr; + if constexpr (KV == QK_KV_STREAMED_BF16) { + /* kv_store_bf16 writes the values themselves: no descales. */ + *(__hip_bfloat16*)(m + EB * t) = kb; + *(__hip_bfloat16*)(m + EB * (HD + t)) = vb; + if (c) { + *(__hip_bfloat16*)(c + EB * t) = kb; + *(__hip_bfloat16*)(c + EB * (HD + t)) = vb; + } + } else { + const float kf = __bfloat162float(kb) * kvs.k_inv; + const float vf = __bfloat162float(vb) * kvs.v_inv; + const int pk = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(kf, -448.0f), 448.0f), 0.0f, + 0, false); + const int pv = __builtin_amdgcn_cvt_pk_fp8_f32(fminf(fmaxf(vf, -448.0f), 448.0f), 0.0f, + 0, false); + m[t] = (unsigned char)(pk & 0xFF); + m[HD + t] = (unsigned char)(pv & 0xFF); + if (c) { + c[t] = (unsigned char)(pk & 0xFF); + c[HD + t] = (unsigned char)(pv & 0xFF); + } + } + } + } else if (sl >= 0 && (uint32_t)sl / (uint32_t)kvs.block_size < (uint32_t)kvs.n_blocks) { const uint32_t blk = (uint32_t)sl / (uint32_t)kvs.block_size; const uint32_t off = (uint32_t)sl % (uint32_t)kvs.block_size; const size_t rowb = (KV == QK_KV_F8V4 || KV == QK_KV_K6V4) ? (size_t)kvs.row : (size_t)(2 * HD); @@ -261,7 +318,7 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel( // The two launches, as the plugin ABI's RadLaunchFn. See the note at the head of // r4d_quant_act_i8.hip on the argument list and status return. enum { QK_QGATE = 0, QK_K, QK_COSSIN, QK_POS, QK_WQ, QK_WK, QK_QOUT, QK_KOUT, QK_GOUT, - QK_V, QK_SLOT, QK_CACHE }; + QK_V, QK_SLOT, QK_CACHE, QK_RES, QK_HOST }; /* The body of both forms; KVF is the kv_store fold and `kvs` its cache, already checked. */ template @@ -386,6 +443,76 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream : qk_body(args, stream, kvs); } +/* The prologue with the STREAMED store folded in: a streamed group's cache is a ring of + * `n_blocks` slots over a `blocks`-wide block-id space, and its truth is the pinned host mirror. + * Each token's rotated k and its v go to the mirror's block row ALWAYS and to `kv_cache[res[block]]` + * only when the residency map calls the block resident (docs/OPS.md "kv_store_streamed"), so this + * row replaces `qk_norm_rope_gate` + `kv_store_streamed` with one launch a layer and one chain + * between store, resolve and attention. + * + * The bytes are the pair's exactly: `k_out`'s bf16 value is the one the E4M3 conversion reads, and + * both planes are the same dense rows of the same paged layout, so the folded write and the split + * write are the same arithmetic. The cache is E4M3 (the fp8 QSA family) or bf16 (the default + * `--kv-cache-dtype`, where both planes are the value itself, as kv_store_bf16 writes it). */ +extern "C" int r4d_rad_qk_norm_rope_gate_kv_store_streamed(const RadArgs* args, RadStream stream) { + const RadTensor* k = r4d_opt(args, QK_K); + const RadTensor* qg = r4d_opt(args, QK_QGATE); + const RadTensor* v = r4d_opt(args, QK_V); + const RadTensor* sm = r4d_opt(args, QK_SLOT); + const RadTensor* kv = r4d_opt(args, QK_CACHE); + const RadTensor* res = r4d_opt(args, QK_RES); + const RadTensor* ho = r4d_opt(args, QK_HOST); + if (!k || !v || !sm || !kv || !res || !ho) return R4D_NO(RAD_E_INVAL); + const char* kvd = r4d_gets(args, "kv_dtype"); + const uint32_t want = kvd ? rad_dtype_parse(kvd) : (uint32_t)RAD_DT_INVALID; + if (v->dtype != RAD_BF16 || sm->dtype != RAD_I32 || kv->dtype != want || + (kv->dtype != RAD_F8E4M3 && kv->dtype != RAD_BF16) || res->dtype != RAD_I32 || + ho->dtype != RAD_U8) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(sm) || !r4d_contig(kv) || !r4d_contig(res) || !r4d_contig(ho) || + ho->rank != 2) + return R4D_NO(RAD_E_STRIDE); + + const long long hd = r4d_geti_or(args, "head_dim", 0); + const long long nkv = r4d_geti_or(args, "n_head_kv", 0); + const long long bs = r4d_geti_or(args, "block_size", 0); + if (hd <= 0 || nkv <= 0 || bs <= 0) return R4D_NO(RAD_E_SHAPE); + if (kv->rank != 4 || kv->shape[1] != nkv || kv->shape[2] != bs || kv->shape[3] != 2 * hd) + return R4D_NO(RAD_E_SHAPE); + const long long M = qg ? qg->shape[0] : k->shape[0]; + long long Mv = 0; + const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); + if (v_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (Mv < M || r4d_numel(sm) != M) return R4D_NO(RAD_E_SHAPE); + + /* One block of one layer: the mirror's row pitch and the ring's slot pitch are the same bytes, + * so the store addresses both with one row arithmetic. */ + const long long row = nkv * bs * 2 * hd * (kv->dtype == RAD_BF16 ? 2 : 1); + const long long blocks = ho->shape[0], slots = kv->shape[0]; + if (blocks <= 0 || slots <= 0 || row <= 0) return R4D_NO(RAD_E_SHAPE); + if (ho->shape[1] != row || ho->stride[0] != row) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(res) < blocks) return R4D_NO(RAD_E_SHAPE); + + const double ks = r4d_getf(args, "k_scale", 1.0); + const double vs = r4d_getf(args, "v_scale", 1.0); + if (!(ks > 0.0) || !(vs > 0.0)) return R4D_NO(RAD_E_INVAL); + + QkKvStore kvs{}; + kvs.v = (const __hip_bfloat16*)r4d_p(v); + kvs.slot = (const int32_t*)r4d_p(sm); + kvs.cache = r4d_wp(kv); + kvs.v_pitch = (int)v_ld; + kvs.block_size = (int)bs; + kvs.n_blocks = (int)slots; + kvs.k_inv = 1.0f / (float)ks; + kvs.v_inv = 1.0f / (float)vs; + kvs.res = (const int32_t*)r4d_p(res); + kvs.host = r4d_wp(ho); + kvs.blocks = (int)blocks; + return kv->dtype == RAD_BF16 ? qk_body(args, stream, kvs) + : qk_body(args, stream, kvs); +} + /* The fp8_v4 and k6_v4 forms: the same operands, the cache [n_blocks, kv_heads, block_size, * 25 or 22 * HD / 16] E4M3-typed bytes (fp8_v4: E4M3 K; k6_v4: int6 K; both int4 V, f16 scales). */ static int qk_kv_q4(const RadArgs* args, RadStream stream, int k6) { diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index be3ca727..5e611270 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -291,6 +291,25 @@ static const RadOperandSpec oQkNormRopeGateKv[] = { { "slot_mapping", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, }; +/* The prologue with a streamed group's store folded in: the same parameters and operands, then the + * residency map and the layer's host mirror, which the store needs and the ring does not. The cache + * is E4M3 only (streaming ships for the fp8 QSA family). */ +static const RadOperandSpec oQkNormRopeGateKvStreamed[] = { + { "q_gate", RAD_OPD_IN, 1 }, + { "k", RAD_OPD_IN, 0 }, + { "cos_sin", RAD_OPD_IN, 0 }, + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 1 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, + { "q_out", RAD_OPD_OUT, 1 }, + { "k_out", RAD_OPD_OUT, 0 }, + { "gate_out", RAD_OPD_OUT, 1 }, + { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, + { "res", RAD_OPD_IN, 0 }, + { "host", RAD_OPD_INOUT, 0 }, +}; /* Builds the cos/sin table the fused prologue reads, each position at its own row of a * [max_ctx, rot] plane. `rot`, `theta` and `scale` are spelled as `rope`'s, since both must compute * the same angles. */ @@ -1332,6 +1351,32 @@ static const RadOperandSpec oQsaSelect[] = { { "seqused", RAD_OPD_OUT, 0 }, }; +/* `kv_resolve`, a new op whose schema this plugin fixes: the residency map of a streamed KV + * group, between `qsa_select` and the attention. `sel` is block ids in and ring slots out; + * `res`, `slot_block`, `slot_state` and `ctl` are the state it keeps between calls, so its row is + * not concurrent. The miss list is the row's scratch, not an operand: nothing outside the launch + * reads it. `block_bytes` is a byte extent, not `block_size`: the op only moves bytes, and a + * `block_size` key would make it the KV group's consumer, taking the block size the resolved + * attention kernel must read. */ +static const RadParamSpec pKvResolve[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "blocks", RAD_P_INT, RAD_REQUIRED }, + { "slots", RAD_P_INT, RAD_REQUIRED }, + { "sel_pitch", RAD_P_INT, RAD_REQUIRED }, + { "block_bytes", RAD_P_INT, RAD_REQUIRED }, +}; +static const RadOperandSpec oKvResolve[] = { + { "sel", RAD_OPD_INOUT, 0 }, + { "nsel", RAD_OPD_IN, 0 }, + { "res", RAD_OPD_INOUT, 0 }, + { "slot_block", RAD_OPD_INOUT, 0 }, + { "slot_state", RAD_OPD_INOUT, 0 }, + { "ctl", RAD_OPD_INOUT, 0 }, + { "host", RAD_OPD_IN, 0 }, + /* The group's ring, the same RAD_KV operand `attn_paged` and `kv_store` take. */ + { "kv_cache", RAD_OPD_INOUT, 0 }, +}; + /* `qsa_score`, a new op whose schema this plugin fixes: the indexer's score of each compressed * block of key history for one query. * @@ -2041,6 +2086,27 @@ static const RadOperandSpec oKvStore[] = { { "slot_mapping", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, }; +/* `kv_store` for a streamed group. `host` is the group's authoritative mirror and is always + * written, `res` is the residency map that says whether the block is in the ring (the ring slot is + * written only when `res[block] >= 0`). The parameters are kv_store's: the layout and the E4M3 + * conversion are the same, only the destination set differs. */ +static const RadParamSpec pKvStoreStreamed[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + { "block_size", RAD_P_INT, RAD_REQUIRED }, + { "kv_dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("k_scale"), + P_F64O("v_scale"), +}; +static const RadOperandSpec oKvStoreStreamed[] = { + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "slot_mapping", RAD_OPD_IN, 0 }, + { "kv_cache", RAD_OPD_INOUT, 0 }, + { "res", RAD_OPD_IN, 0 }, + { "host", RAD_OPD_INOUT, 0 }, +}; static const RadParamSpec pEmbed[] = { { "M", RAD_P_INT, RAD_REQUIRED }, @@ -2913,6 +2979,13 @@ static const RadOpSchema kSchemas[] = { SCHEMA("kv_store", pKvStore, oKvStore, "scatter k and v into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim] -- K at " "[.., d] and V at [.., head_dim + d]. A negative slot stores nothing."), + SCHEMA("kv_store_streamed", pKvStoreStreamed, oKvStoreStreamed, + "kv_store for a streamed group: the token's k and v into the group's host mirror at the " + "BLOCK's identity row always, and into kv_cache[res[block]] only when the residency map " + "says the block is resident. The mirror is the truth and a block absent from the ring is " + "copied in whole by kv_resolve, so the caller orders store, then resolve, then " + "attention. A negative slot stores nothing; a map entry outside [-1, slots) is treated " + "as not resident, which libref refuses as a state fault."), SCHEMA("embed_lookup", pEmbedM, oEmbed, "the embedding gather. A negative token id writes a zero row, and so does one outside " "[vocab_offset, vocab_offset + n_vocab) -- which is what makes the table shardable " @@ -3046,6 +3119,13 @@ static const RadOpSchema kSchemas[] = { "qk_norm_rope_gate followed by kv_store, in one launch: each k head's block also writes " "its rotated k and its v into the paged cache at the token's slot. The `k` kv_store " "reads is `k_out`, so the tail adds only `v`, `slot_mapping` and `kv_cache`."), + SCHEMA("qk_norm_rope_gate_kv_store_streamed", pQkNormRopeGateKv, oQkNormRopeGateKvStreamed, + "qk_norm_rope_gate followed by kv_store_streamed, in one launch: the token's rotated k " + "and its v into the group's host mirror at the BLOCK's identity row always, and into " + "kv_cache[res[block]] only when the residency map says the block is resident. The " + "mirror is the truth and a block absent from the ring is copied in whole by kv_resolve, " + "so the caller keeps store, then resolve, then attention. Replaces the prologue plus a " + "separate streamed store, one launch a layer. E4M3 caches only."), SCHEMA("rope_table", pRopeTable, oRopeTable, "the cos/sin `qk_norm_rope_gate` reads, written at each position's OWN row of a " "[max_ctx, rot] plane: rot values a row, cos for the first half and sin for the second. " @@ -3344,6 +3424,20 @@ static const RadOpSchema kSchemas[] = { "nowhere else, so the effective query position is (nsel-1)*ratio + pos%ratio. Ties " "break to the LOWER block index through a prefix count, never through atomic order. " "`signed` 1 ranks signed finite scores; absent or 0 ranks max(score, 0)."), + SCHEMA("kv_resolve", pKvResolve, oKvResolve, + "make every block the selections name resident and rewrite them as ring slots: bump " + "the epoch, take a hit or make a single claim (-1 -> -2) per distinct block, compact " + "the claimed blocks in ASCENDING block id, take a free slot before any resident one and " + "otherwise one CLOCK second-chance victim per miss from ctl[1] -- a warm slot (two-bit " + "heat counter) is halved and passed, a cold one is taken, and a slot this call already " + "uses is never taken -- re-point both maps, copy " + "each missed block from the host mirror into its slot, then replace every entry below " + "nsel with the slot holding its block. nsel and 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], reverts the unplaced claims to -1 and leaves those entries naming " + "blocks, never a fabricated slot, so the caller must refuse the step. The maps, the " + "epoch, the hand and the heat counters keep state across launches, so the row is not " + "concurrent; the miss list is the row's scratch (2 * slots i32), not an operand."), SCHEMA("qsa_score", pQsaScore, oQsaScore, "score[m][b] = (sum over heads of relu(q[m][h] . bk[bt[m][b]])) / sqrt(n). THE RELU IS " "PER (BLOCK, HEAD) AND THE SUM IS OVER HEADS, in that order -- four independent votes, " @@ -4609,6 +4703,12 @@ static const RadConstraint cQsaTailStore[] = { /* No dtype: every operand is f32 or i32. */ static const RadConstraint cQsaSelect[] = { C_GE("blocks", 1), C_GE("topk", 1), C_GE("ratio", 1) }; +/* The two byte planes are read by pitch, so only positivity is fixed: any block extent and any + * ring depth the device can address. */ +static const RadConstraint cKvResolve[] = { + C_GE("blocks", 1), C_GE("slots", 1), C_GE("sel_pitch", 1), C_GE("block_bytes", 1), +}; + /* A lane owns n/32 dims of both operands, so n is a wave multiple, at most eight of them. The * head bound is the register file: the query stays resident across the block loop. */ static const RadConstraint cQsaScore[] = { @@ -4785,6 +4885,14 @@ static const RadConstraint cQkNormRopeGateKv[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), }; +static const RadConstraint cQkNormRopeGateKvStreamed[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cQkNormRopeGateKvStreamedBf16[] = { + C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), + C_GE("block_size", 1), C_IN("kv_dtype", "bf16"), +}; static const RadConstraint cQkNormRopeGateKvFp8v4[] = { C_IN("q_dtype", "bf16"), C_LE("head_dim", 256), C_DIV("head_dim", 32), C_GE("block_size", 1), C_IN("kv_dtype", "fp8_v4"), @@ -5135,6 +5243,15 @@ static const RadConstraint cCausalConv[] = { C_IN("dtype", "bf16"), C_GE("width" C_LE("width", 8) }; static const RadConstraint cKvStore[] = { C_GE("block_size", 1), C_IN("kv_dtype", "bf16") }; static const RadConstraint cKvStoreFp8[] = { C_GE("block_size", 1), C_IN("kv_dtype", "fp8_e4m3") }; +/* The streamed store converts as the fp8 row does and requires the same divisible head. */ +static const RadConstraint cKvStoreStreamedFp8[] = { C_GE("block_size", 1), + C_IN("kv_dtype", "fp8_e4m3"), + C_DIV("head_dim", 4) }; +/* The same store into a bf16 cache: the mirror and the ring are the value itself, as kv_store_bf16 + * writes it. Head_dim needs only the four-column grouping. */ +static const RadConstraint cKvStoreStreamedBf16[] = { C_GE("block_size", 1), + C_IN("kv_dtype", "bf16"), + C_DIV("head_dim", 4) }; static const RadConstraint cKvStoreFp8v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), C_IN("kv_dtype", "fp8_v4") }; static const RadConstraint cKvStoreK6v4[] = { C_GE("block_size", 1), C_DIV("head_dim", 32), @@ -5842,6 +5959,31 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_kv_store_k6v4, nullptr, nullptr, nullptr, nullptr }, +/* The store of a streamed KV group: the host mirror always, the ring slot when resident. One + * workgroup a token, two destinations; the mirror's row pitch is the block's, so a token's bytes + * land at the same offsets in both planes. */ +{ "kv_store_streamed_fp8", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the ring slot the residency map names", + "cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror [blocks, the same row pitch]; " + "head_dim a multiple of 4; a negative slot stores nothing", + "bf16 k / v, E4M3 mirror and ring, i32 slot mapping and residency map, scalar descales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreStreamedFp8), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_kv_store_streamed }, + +/* The same store into a bf16 cache: the mirror and the ring hold the values themselves, as + * kv_store_bf16 writes them, and every plane offset is two bytes wide. */ +{ "kv_store_streamed_bf16", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the ring slot the residency map names", + "cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror [blocks, the same row pitch as " + "bytes]; head_dim a multiple of 4; a negative slot stores nothing", + "bf16 k / v, bf16 mirror and ring, i32 slot mapping and residency map", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvStoreStreamedBf16), NOTUNE, + nullptr, nullptr, r4d_rad_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_kv_store_streamed }, + { "logits_gemm_bf16", "logits_gemm", "vocab", "the lm_head projection: C[M, n_vocab] f32 = x[M, n_embd] @ lm_head[n_vocab, n_embd]^T", "any M and any vocabulary; n_embd a multiple of 8. One workgroup a vocabulary column", @@ -8018,6 +8160,21 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_qsa_select, r4d_rad_qsa_select_scratch, nullptr, nullptr, r4d_shape_qsa_select }, +/* The residency map of a streamed KV group. One workgroup: the CLOCK hand is serial state, and the + * phases are barriers over the entries, the block-id space and the ring. The copy is the same + * launch, so one step is one dispatch rather than one per claim. */ +{ "kv_resolve_i32", "kv_resolve", "attn", + "turn selected KV block ids into ring slots, evict by CLOCK and copy misses in from the host", + "any block count, ring depth and block byte extent; the mirror and the ring are read by byte " + "pitch, so every cache layout is the same launch", + "i32 selection and residency maps, u8 host mirror, the group's KV cache; the selection and both " + "maps are rewritten in place. A call that needs more distinct blocks than slots latches " + "ctl[3] and leaves those entries naming blocks, never a fabricated slot", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cKvResolve), NOTUNE, + nullptr, nullptr, r4d_rad_kv_resolve, r4d_rad_kv_resolve_scratch, nullptr, nullptr, + r4d_shape_kv_resolve }, + /* The indexer's score. One workgroup per query, one wave per block: a lane owns n/32 consecutive * dims of the query heads and the block key, so a head's dot product is one wave reduction and the * block key is read once for all heads (the head loop is inside the block loop). */ @@ -8491,6 +8648,35 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store, nullptr, nullptr, nullptr, r4d_shape_qk_norm_rope_gate_kv_store, nullptr, r4d_fuse_qk_norm_rope_gate_kv_store }, +/* The prologue and the STREAMED cache store in one launch: the mirror for every token, the ring + * only where the residency map says the block is resident. The operands are the pair's, plus the + * map and the mirror. */ +{ "qk_norm_rope_gate_kv_store_streamed_fp8", "qk_norm_rope_gate_kv_store_streamed", "attn", + "qk_norm_rope_gate, and kv_store_streamed (host mirror always, resident ring slot too) from the " + "same launch", + "qk_norm_rope_gate's shapes; cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror " + "[blocks, the same row pitch], one slot a row; a negative slot stores nothing", + "bf16 in and out, E4M3 mirror and ring, i32 slot mapping and residency map, scalar descales", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvStreamed), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_qk_norm_rope_gate_kv_store_streamed, nullptr, + r4d_fuse_qk_norm_rope_gate_kv_store_streamed }, + +/* The same fold into a bf16 streamed group: the default `--kv-cache-dtype`, where both planes hold + * the rotated k and v themselves, as kv_store_streamed_bf16 writes them. */ +{ "qk_norm_rope_gate_kv_store_streamed_bf16", "qk_norm_rope_gate_kv_store_streamed", "attn", + "qk_norm_rope_gate, and kv_store_streamed (host mirror always, resident ring slot too) from the " + "same launch", + "qk_norm_rope_gate's shapes; cache exactly [slots, kv_heads, block_size, 2*head_dim], mirror " + "[blocks, the same row pitch as bytes], one slot a row; a negative slot stores nothing", + "bf16 in and out, bf16 mirror and ring, i32 slot mapping and residency map", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkNormRopeGateKvStreamedBf16), NOTUNE, + nullptr, nullptr, r4d_rad_qk_norm_rope_gate_kv_store_streamed, nullptr, nullptr, nullptr, + r4d_shape_qk_norm_rope_gate_kv_store_streamed, nullptr, + r4d_fuse_qk_norm_rope_gate_kv_store_streamed }, + /* The fold into an fp8_v4 cache: E4M3 K, int4 V in groups of 32 (a wave) with f16 scales. */ { "qk_norm_rope_gate_kv_store_fp8v4", "qk_norm_rope_gate_kv_store", "attn", "qk_norm_rope_gate, and kv_store into an fp8_v4 paged cache from the same launch", @@ -9533,6 +9719,8 @@ extern "C" int rad_kernel_concurrent(int i) { if (k->family && std::strcmp(k->family, "ar") == 0) return 0; static const char* const kStateful[] = { "hc_", "mtp_enter", "ar_", "gemm_w4a8_tiled", "gemm_w8a8_tiled", "lora_", + /* The residency map's epoch, hand, heat counters and counters live across launches. */ + "kv_resolve", }; for (const char* p : kStateful) if (std::strncmp(k->name, p, std::strlen(p)) == 0) return 0; diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 35d281e5..ec9c509b 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -754,6 +754,33 @@ extern "C" int r4d_shape_kv_store(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* The streamed store: kv_store's geometry with the group's two copies beside the ring. One block + * and one ring slot, with every token on its own position of that block: the draw vocabulary cannot + * express an injective residency map, and two blocks drawing one slot would be a race between two + * tokens on one ring byte. The partly resident map and the mirror-only step are built by hand. */ +extern "C" int r4d_shape_kv_store_streamed(const RadParam* p, int n_p, int operand, + RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + /* E4M3 or bf16: the mirror and the ring are byte planes of the same paged layout, and the + * mirror's row pitch doubles for a two-byte element. */ + if (KV != (uint32_t)RAD_F8E4M3 && KV != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + const RadOpdDesc l[] = { + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd_idx(M, 0, bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping, one block */ + opd(KV, 1, kvh, bs, 2 * hd), /* kv_cache -- the ring */ + opd_idx(1, 0, 1, 0), /* res -- the block, resident in slot 0 */ + opd((uint32_t)RAD_U8, 1, row), /* host -- the layer's mirror */ + }; + R4D_PICK(l); +} + /* logits_gemm at bf16. The fp8 row is not described; see the file header. */ extern "C" int r4d_shape_logits_gemm(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1133,6 +1160,35 @@ extern "C" int r4d_shape_qkv_norm_rope_kv_store(const RadParam* p, int n_p, int R4D_PICK(l); } +/* qk_norm_rope_gate_kv_store_streamed -- the prologue's operands, then the streamed store's: `v`, + * `slot_mapping`, the ring, the residency map and the layer's mirror. One block, one ring slot and + * every token on its own position of it, exactly as kv_store_streamed's shape says (the draw + * vocabulary cannot express an injective block -> slot map, and two blocks in one slot would race). + * E4M3 or bf16: both planes are byte planes whose pitch is one block, so a bf16 mirror row is twice + * the fp8 row. */ +extern "C" int r4d_shape_qk_norm_rope_gate_kv_store_streamed(const RadParam* p, int n_p, + int operand, RadOpdDesc* out) { + if (operand < 9) return r4d_shape_qk_norm_rope_gate(p, n_p, operand, out); + const int64_t M = pi(p, n_p, "M"); + const int64_t hd = pi(p, n_p, "head_dim"); + const int64_t kvh = pi(p, n_p, "n_head_kv"); + const int64_t bs = pi(p, n_p, "block_size"); + const uint32_t KV = dt_act(p, n_p, "kv_dtype"); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + if (KV != (uint32_t)RAD_F8E4M3 && KV != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + const RadOpdDesc l[] = { + opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), opd_none(), + opd_none(), opd_none(), + opd((uint32_t)RAD_BF16, M, kvh, hd), + opd_idx(M, 0, bs, -1, RAD_OPD_F_IDX_UNIQUE), /* slot_mapping, one block */ + opd(KV, 1, kvh, bs, 2 * hd), /* kv_cache -- the ring */ + opd_idx(1, 0, 1, 0), /* res -- the block, resident in slot 0 */ + opd((uint32_t)RAD_U8, 1, row), /* host -- the layer's mirror */ + }; + R4D_PICK(l); +} + /* rope_table -- the cos/sin plane the fused prologue reads (shim in r4d_qk_norm_rope_gate.hip). */ extern "C" int r4d_shape_rope_table(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { @@ -1869,6 +1925,34 @@ extern "C" int r4d_shape_qsa_select(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* The residency map and the two byte planes. `sel` is described as block ids, which is what + * `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch. + * + * A described residency map can only be an all-resident one: the description vocabulary draws an + * index in [0, idx_max) or a constant, and a cold entry is -1, which no draw expresses. So a tool + * that calls this op cold sees every map entry at 0, which exercises the epoch, the rewrite and + * the bookkeeping but never a miss, an eviction or a copy. The service-shaped cases are built by + * hand in tests/ref_test.cpp and in this plugin's selftest, against libref. */ +extern "C" int r4d_shape_kv_resolve(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + + const int64_t M = pi(p, n_p, "M"), blocks = pi(p, n_p, "blocks"); + const int64_t slots = pi(p, n_p, "slots"), pitch = pi(p, n_p, "sel_pitch"); + const int64_t bbytes = pi(p, n_p, "block_bytes"); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0) + return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = { + opd_idx(M, pitch, blocks), /* sel -- one block id an entry */ + opd_idx(M, 0, pitch + 1), /* nsel -- 0 .. sel_pitch */ + opd_idx(blocks, 0, slots, 0), /* res -- an all-resident map, no -2 */ + opd_idx(slots, 0, blocks, 0), /* slot_block -- the reverse map */ + opd_idx(slots, 2, 2, 0), /* slot_state -- cold: epoch 0, no reference */ + opd_idx(16, 0, 2, 0), /* ctl -- cold: epoch 0, hand 0 */ + opd((uint32_t)RAD_U8, blocks, bbytes), /* host -- the layer's mirror, a block a row */ + opd((uint32_t)RAD_U8, slots, bbytes), /* kv_cache -- the layer's ring, a block a row */ + }; + R4D_PICK(l); +} + /* The QSA block score. The block-key store's height is the KV pool's page count, which the * runtime decides, so `blocks` gives the widest a table entry can address: a bound, not the plan. * Table entries are page ids. */ diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index d5c0ccd4..932ac33a 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -565,6 +565,126 @@ int ref_kv_store(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ kv_store_streamed */ +/* The store of a streamed group: the host mirror is the truth, the device pool is a cache of it. + * + * A streamed group's ring is `slots` blocks deep while the block-id space is `blocks`, and a block + * may be absent from it. This op is `kv_store` with the two copies the group keeps: + * + * host[b] is written ALWAYS, at the block's identity row, whatever the map says; + * kv_cache[res[b]] is written only when `res[b] >= 0`, i.e. the block is resident now. + * + * The residency test belongs in the writer rather than in the resolve, and this is the case that + * decides it: at decode the block this step's tokens land in is the block the last step already + * made resident (a block is `ratio` tokens of one sequence), so a writer that only wrote the + * mirror would leave the ring holding that block's first tokens and every later token missing - + * and the resolve, seeing the block resident, would not copy it. Writing the ring when resident + * and the mirror always means a host block is never stale and a slot never holds a block the + * mirror disagrees with, which is the property the resolve's copy relies on. + * + * The order the caller must keep is store, then resolve, then attention (arch/common/ + * rad_block_attn_gated_fp8.h): the block the current step writes may be absent from the ring, and + * the resolve then copies whole blocks out of the mirror, so it must see this step's bytes. + * + * The two planes are the same bytes in the same paged layout + * (`[notional block, kv_heads, block_size, 2 * head_dim]`, K then V in a slot), so one conversion + * writes both: the mirror is described as an E4M3 plane over the same row pitch and the loop + * stores into `host` and, when resident, `kv_cache`. + * + * `res` is read, not written: residency is the resolve's decision (libref/ref_kvstream.cpp). A + * `res` entry outside [-1, slots) for a block this call touches, or a slot naming a block past the + * id space, is a state fault and is refused before anything is written. */ +int ref_kv_store_streamed(const RadArgs* a, RadStream) { + if (!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). Streaming is dtype-agnostic + * beyond the writer: both planes are byte planes of the same paged layout whose pitch is one + * block, so a bf16 group doubles every offset and stores the value itself, as kv_store_bf16 + * does. A packed fp8_v4/k6_v4 group has no streamed row and is refused. */ + const bool fp8 = kv->dtype == RAD_F8E4M3; + if (!fp8 && kv->dtype != RAD_BF16) return RAD_E_UNSUPPORTED; + if (kv->rank != 4) return RAD_E_SHAPE; + if (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: a padded mirror row would copy a + * block's bytes over its neighbour's, and the two copies must address the same offsets. */ + 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); + /* kv_store_bf16 stores the value itself; only the E4M3 row divides by the reader's descales. */ + 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; + + /* Everything that can refuse is checked before the first write: a half-written mirror would + * make the next step's copies plausible and wrong. */ + const int32_t* const R = (int32_t*)res->data; + for (int64_t t = 0; t < M; ++t) { + const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t)); + if (s < 0) continue; /* padded row, no cache slot */ + const int64_t blk = s / block_size; + if (blk >= blocks) return RAD_E_SHAPE; + if (R[blk] < -1 || R[blk] >= slots) return RAD_E_INVAL; + } + + /* The mirror, seen as the plane it holds (E4M3 or bf16): same bytes, same writer, so the two + * copies cannot round differently. */ + RadTensor hkv = *host; + hkv.dtype = kv->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); + + REF_PAR_FOR(M * kv_heads * head_dim * 2) + for (int64_t t = 0; t < M; ++t) { + const int64_t s = ld_int(sm->dtype, sm->data, offlin(sm, t)); + if (s < 0) continue; + const int64_t blk = s / block_size, off = s % block_size; + const int64_t hb = blk * hv.sb + off * hv.so; + /* A resident block keeps its slot current; a non-resident one is written to the mirror + * alone and the resolve copies the whole block in when it selects it. */ + 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; +} + /* ------------------------------------------------------------------ rope */ namespace { diff --git a/libref/ref_kvstream.cpp b/libref/ref_kvstream.cpp new file mode 100644 index 00000000..ef122f2b --- /dev/null +++ b/libref/ref_kvstream.cpp @@ -0,0 +1,453 @@ +/* ref_kvstream.cpp -- kv_resolve: the residency map between a streamed KV group's block ids and + * the ring slots its device pool actually holds (docs/KV-STREAMING.md §3.4 and §4.3, docs/OPS.md + * "Sparse attention (QSA)"). + * + * ============================== What it sits between ============================== + * + * `qsa_select` already dereferences the attention group's block table: it writes + * `sel[q][i] = tb[b]`, the group's POOL PAGE ID (`r4d_qsa_select_bf16.hip:254`, `:686`), and + * `attn_paged` uses each entry as a raw pool page index with no indirection + * (`r4d_attn_decode_h256_gqa6.hip:268`, `:322`; `r4d_attn_paged_gqa8.hip`). When the group's KV + * streams, the device pool is `slots` blocks deep and the block-id space is `blocks`, so a block id + * is no longer an address: `blk * kv_block_stride` would walk out of the layer and silently read + * another layer's bytes. `kv_resolve` turns every selected block id into the ring slot holding it, + * copies the block in from the pinned host mirror when it is not resident, and rewrites `sel` in + * place. Nothing below the rewrite changes: `sel` is the only place the sparse path names KV + * storage, so `attn_paged` reads a resolved table exactly as it reads a fully resident one. + * + * `nsel` and `seqused` stay what `qsa_select` wrote them: the attention's length over the table is + * a token count inside the blocks, not an address, so the rewrite leaves both alone. + * + * ============================== The operands, exactly ============================== + * + * # name role dtype shape what it is + * 0 sel inout i32 [M, sel_pitch] block ids in, ring slots out + * 1 nsel in i32 [M] valid entries of each row + * 2 res inout i32 [blocks] block -> slot, or -1; -2 in flight + * 3 slot_block inout i32 [slots] slot -> block, or -1 free + * 4 slot_state inout i32 [slots, 2] [s,0] epoch of last use, [s,1] heat + * 5 ctl inout i32 [16] the control block (below) + * 6 host in u8 [blocks, block_bytes] the layer's host mirror, identity layout + * 7 kv_cache inout bytes [slots, block_bytes] the layer's ring, as RAD_KV(group, layer) + * + * Order follows the read order of the algorithm, with the cache last as in `kv_store`. `sel` and + * `nsel` keep `qsa_select`'s positions 5 and 6 relative to each other, so the pair reads the same + * way in both ops. + * + * **The miss list is not an operand.** It is a per-call temporary, and a temporary is the row's + * scratch in this codebase (`qsa_select`'s split workspace, docs/OPS.md "qsa_select"): an operand + * would enter the arena planner, the recorded pass's ranges and the tape key for bytes nothing + * outside one launch reads. A device row that needs one declares + * `(next_pow2(slots) + slots) * 4` bytes through `RadKernelInfo::scratch`, laid out + * `int32 miss_block[next_pow2(slots)]` -- the ascending miss list, padded because a launch too wide + * for the kernel's shared claim list sorts it here -- then `int32 miss_slot[slots]`; this reference + * sorts locally and needs none. + * + * ============================== The parameters ============================== + * + * M query rows to resolve; ranged, since a prefill chunk and a decode step differ + * blocks the group's logical block count (the id space, `res`'s extent) + * slots the ring depth (the device pool's extent, `slot_block`'s extent) + * sel_pitch the selection's row pitch in entries (topk + 1); also the bound `nsel` may not pass + * block_bytes bytes one block of ONE layer occupies: the host mirror's row pitch, the pool's slot + * pitch, and the length of every copy + * + * `block_bytes` rather than `block_size` (the block's token count) because the op moves bytes and + * never reads an element: it is the same code at every cache layout (`fp8`, `fp8_v4`, `k6_v4`, + * `bf16`), and it is the number a vectorised copy has to constrain (a block is a whole number of + * 16-byte lanes). It is deliberately NOT a `block_size` key: `Builder::find_kv_consumer` binds a KV + * group to the first unclaimed op after it that carries `block_size`, and the group's block size + * must keep coming off the resolved attention kernel, not off the op that only copies its pages. + * + * `sel_pitch` and `block_bytes` are also pitches the operands carry (`sel.stride[0]`, + * `host.stride[0]`), and this reference requires them to agree: a resolve that read one pitch and + * wrote another would rewrite a row into its neighbour. Stating them in the schema puts them in the + * resolved geometry, where a kernel may constrain them, and in the shape hook, which needs them to + * size `sel` and the two planes. + * + * `slots` is the ring depth, and the OPERAND states it, exactly as `sel`'s extent states `M` and + * its row pitch states `sel_pitch`: `slot_block`'s extent is the ring the call may address and the + * parameter is the ceiling the caller declared. Declare cannot know the ring -- the pool is planned + * after the program is built, and a plugin sees only the context bound -- so the declared `slots` is + * the context and a ring the engine sized smaller (--kv-resident) arrives as a shorter + * operand. A call may never address more than the declaration: `slots > slots_declared` is refused. + * + * ============================== The control block ============================== + * + * `ctl` is 16 int32s, the same [0..9] layout the reference design uses + * (`Strata-main/include/strata/kernels/kv_stream.hpp:78`), 8-byte aligned so the counters can be + * read as u64: + * + * [0] epoch the value the last call used (0 in a fresh block, so the first call is 1) + * [1] hand the CLOCK hand, in [0, slots) + * [2] misses blocks placed by the last call + * [3] overflow 1 once a call could not place every miss; latched, never cleared here + * [4..5] u64 misses every block ever placed + * [6..7] u64 lookups every selection entry ever resolved + * [8..9] u64 calls + * [10] maximum union the largest number of DISTINCT blocks one call has selected + * (hits + misses), so a ring's depth can be sized from measurement + * [11] maximum misses the largest number of blocks one call has placed + * [12] maximum claims the largest number of DISTINCT absent blocks one call has claimed: the + * length of the sorted miss list, so it is what a claim-list capacity has + * to hold. One call's claims are bounded by its lookups, `sum_q nsel[q] <= + * M * sel_pitch` (every claim is a selection entry), and the engine's + * worst case is `max_seqs * sel_pitch`; a device kernel sizes its list from + * those operands rather than a constant (libr4d/r4d_kv_resolve.hip), and + * this is the counter that says whether it did. + * [13..15] zero, reserved + * + * `res`, `slot_block` and `slot_state` are state as well, and the caller brings them up: `res` and + * `slot_block` FILLED WITH -1, `slot_state` and `ctl` ZEROED (one `fill` each, or the group's + * bring-up). That is the reset: there is no separate reset op, because a residency map is fixed at + * bring-up and lives as long as the pool does. Entering a call with any `res` entry of -2, a + * `slot_block` outside [-1, blocks), a `res` outside [-1, slots) or a hand outside [0, slots) is a + * state fault and is refused rather than guessed at. The epoch is a wrap-around i32 counter, only + * ever compared for equality; it would take 2^31 calls - over two years of decoding - for a stale + * stamp to read as a fresh one, and `slot_state[s,1]` would still be the sweep's second chance. + * + * `slot_state[s,1]` is a **two-bit heat counter in [0, 3]** inside an i32 (31 bits unused, so the + * policy needs no new field, no extra per-slot memory and no ABI change). It is bumped by one, and + * clamped at 3, on every use of the slot -- a hit or a placement -- once a slot a call, and halved + * when the sweep passes the slot. Zeroed at bring-up and written nowhere else, so a fresh ring + * starts cold and a negative value is not reachable from a legal state; a reader treats it as cold + * rather than letting a fault strand the sweep. + * + * ============================== The semantics, in order ============================== + * + * 1. **epoch bump.** epoch = ctl[0] + 1. + * 2. **one lookup per distinct block.** For row q ascending, then entry i ascending, over + * i in [0, nsel[q]) (entries at or past nsel[q] are `qsa_select`'s -1 padding and are not + * touched): b = sel[q][i]. + * res[b] >= 0 -> a hit: slot_state[res[b],0] = epoch and, the first time this call stamps + * that slot, slot_state[res[b],1] = min(old + 1, 3). One bump a SLOT a + * call, not one an entry: a block twenty rows name gains one step of heat, + * the same as one a single row names, so the counter measures the calls + * that wanted the block and not the width of the selection. + * res[b] == -1 -> a miss, claimed once: res[b] = -2 and b appended to the miss list. + * res[b] == -2 -> already claimed by an earlier entry; nothing. This is what makes the pass + * one lookup per block without a second structure: the map is its own set. + * 3. **the miss list is ascending block id.** Not first-appearance order: a block claimed by row 3 + * must not evict a different slot from a block claimed by row 0 depending on which thread got + * there first, or two implementations of one contract would place the same blocks in different + * slots and `sel` would differ. Ascending is a fact about the claim set, not about the map, so + * a device implementation orders the claim list itself (a sort of at most `M * sel_pitch` ids); + * nothing here needs a pass over `blocks`, which is the id space and not the call's size. + * 4. **one victim per miss, in that order: identity, a free slot, then a CLOCK (second chance) + * sweep.** For each missed b in ascending order, if `b < slots` and slot b is available -- + * `slot_state[b,0] != epoch` and `slot_block[b]` is either -1 or b itself -- the victim is slot + * b, and the hand does not move. This is a placement preference only: it takes a slot only when + * that slot is free, so it can never evict, and leaving the hand alone means a miss it cannot + * place falls through to exactly the walk below, from exactly the hand it would have seen. Two + * things make it worth having: it maps a block's id to its own slot while the context is + * shorter than the ring, and adjacent block ids then sit in adjacent slots of one layer's + * stripe, which is the order the attention's gather reads them in. Otherwise, visit slots from + * the hand, one at a time, wrapping. A FREE slot -- slot_block[s] == -1 -- is taken before any + * resident block is considered: evicting costs a copy on the next call and a free slot costs + * nothing, so the ring fills its empty region first. A slot with slot_state[s,0] == epoch was + * claimed or hit by this call and is passed, free or not, and keeps its heat counter; this is + * the "never take a slot this call itself uses" rule. When a whole turn finds no free slot, the + * same walk is the CLOCK sweep, with the two-bit heat counter in place of the one-bit + * reference: + * - a slot holding a block whose counter is non-zero: halve it (old >> 1) and pass it. A + * saturated 3 survives exactly two passes (3 -> 1 -> 0), a freshly used 1 exactly one, + * and a slot nothing has wanted for two sweeps is the victim on the next visit. + * - otherwise (a block, counter 0): take it. + * The hand still PICKS the victim -- this is a per-visit decision, not a search -- so the + * policy needs no reduction, no barrier and no extra traffic: an add-and-clamp where a + * constant store was, and a shift where a zero was. That is the whole reason it is affordable + * where an exact LRU is not: the epoch-ordered minimum costs a collective reduction per miss. + * The hand advances one slot per visit, so it ends just past the last slot taken. How many + * slots are free is counted before the sweep; a placement into a free slot makes it live and an + * eviction re-points a live one, so the count only falls to zero and a full ring goes straight + * to CLOCK. The free + * scan is side-effect free when it finds nothing -- it halves no counter and leaves the hand + * where it started -- so a full ring's victim is the sweep's alone. A free slot is taken + * without regard to its stale counter. The CLOCK sweep may + * visit at most 3 * slots slots; every write clamps the counter to 3, so two passes halve any + * value to 0 (docs/KV-STREAMING.md §3.4) and the third places the miss. + * 5. **re-point both maps** as each victim is taken: if the slot held block `old`, res[old] = -1; + * slot_block[s] = b, slot_state[s] = {epoch, min(old + 1, 3)}, res[b] = s. A placement is a + * use, so it carries the same bump a hit does; the victim's counter is 0 by construction (the + * sweep only takes a cold slot), so this is 1 in the common case, and the `min` is what keeps + * the two-bit range true for a slot taken by identity or from the free region. + * 6. **copy**: for each placed (b, s), block_bytes from host[b] into the pool's slot s. A copy is + * a byte copy; nothing is converted, so a streamed block is bit-identical to the block the + * writer put in the mirror. + * 7. **rewrite**: for every entry in [0, nsel[q]), sel[q][i] = res[b] when that is >= 0. Entries + * at or past nsel[q] keep their -1. + * + * `ctl[2] = placed`, `ctl[0] = epoch`, `ctl[1] = hand`, and the counters grow by `placed`, the + * number of entries read (one a lookup, as phase 2 defines a lookup: per entry, not per distinct + * block) and one. The three maxima are the sizes this op exists to measure: `ctl[10]` is the + * largest union one call has selected -- the number a ring must hold -- `ctl[11]` the largest number + * of blocks one call has placed, i.e. how much of that union was not already resident, and + * `ctl[12]` the largest number of claims one call has made, which is the depth the miss list had to + * hold. + * + * ============================== Overflow ============================== + * + * The ring must hold every DISTINCT block one call selects: a hit holds a slot and a miss needs + * another, so the condition is `hits + misses <= slots`. What that union is depends on the launch: + * at decode it is at most `max_seqs * (sel_pitch - 1)`, while above `qsa_exact_to` prefill issues a + * row per query and a launch's union can be a chunk's worth of the history, which is why the engine + * measures it (ctl[10]) instead of assuming a bound. + * + * It is not silent when it does: a miss left unplaced by the sweep reverts to `res[b] = -1`, and + * `ctl[3]` is latched to 1 with `ctl[2]` counting only what was placed. The selection rewrite then + * writes SLOT 0 for every entry whose block is not resident -- a safe address inside the ring, not + * the block's slot. The entry cannot be left holding the block id: on device that value is an + * address past the ring which `attn_paged` dereferences without a bounds check, so a step whose + * resolve overflowed would fault or read another layer's bytes. Slot 0 is defined memory holding a + * real block's KV, so the step produces wrong numbers rather than a fault -- and a caller that finds + * `ctl[3]` set must DISCARD the step, which is the only reading that keeps the engine honest: it + * never serves output computed against a table whose entries do not name their blocks. + * + * ============================== Statefulness ============================== + * + * The op keeps state across calls - the epoch, the hand, the heat counters and its counters - so it + * is not concurrent: two of its launches must never overlap, and the engine must not reorder one + * against another. That is the `rad_kernel_concurrent` promise (`abi/rad_abi.h:493`), which is + * given per row; a plugin's row list lives beside it, and libr4d's is the `kStateful[]` prefix + * table inside `rad_kernel_concurrent` (`libr4d/r4d_rows.cpp:8748-8770`, "A new row with + * stream-ordered state belongs in the list above"). Both kernel rows for this op therefore stay + * out of that list. The absence of the promise is always safe: without it the engine orders the + * launch behind everything before it, which is exactly what the map needs. + * + * Being stateful is not the same as being unrecordable. The op is a pure function of + * device-resident state whose addresses and pitches never change after bring-up (the maps, the + * ring and the mirror are fixed-size from the group's declaration), so a recorded pass replays it + * correctly; rewriting contents is fine, changing a pitch would force a re-record (docs/ + * KV-STREAMING.md §3.4, core/runtime/ctx.cpp's pass key). + * + * ============================== Why this file is the oracle ============================== + * + * It is the obvious serial form of the contract above: one pass over the entries, one sorted miss + * list, one second-chance walk of the slots, one memcpy per miss, one rewrite. Two device + * implementations compared against it must agree on which slot every block lands in, which is the + * part a fast parallel sweep could get right on hits and wrong on victims. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include +#include + +using namespace ref; + +namespace { + +/* The heat counter's two writes, the same function in all three implementations: 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 rather than letting it survive every pass. */ +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; } + +/* `ctl`'s size, and the index of its first counter (three 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 + * exactly `bytes` densely. Both the mirror and the pool are one block a row; a padded row would + * copy a block's bytes over its neighbour's. */ +int64_t 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); +} + +} /* namespace */ + +int ref_kv_resolve(const RadArgs* a, RadStream) { + if (!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* 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; the parameter is the ceiling it may not pass (see "The + * parameters"). */ + 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 the + * copy length `block_bytes` is both pitches. */ + int64_t hdense = 0, pdense = 0; + if (row_bytes(host, &hdense) != bbytes || hdense * rad_dtype_bytes(host->dtype, 1) != bbytes) + return RAD_E_STRIDE; + if (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 int64_t stp = sst->stride[0]; + /* The counters are read and written as u64 in an i32 block. */ + if (((uintptr_t)C & 7u) != 0) return RAD_E_STRIDE; + + /* ---- everything that can refuse, before anything is written; the selection is read once and + * kept, so phase 7 writes values it did not have to re-read ---- */ + std::vector off, ent; + for (int64_t q = 0; q < M; ++q) { + const int64_t n = ld_int(nsel->dtype, nsel->data, q); + if (n < 0 || n > pitch) return RAD_E_SHAPE; + for (int64_t i = 0; i < n; ++i) { + const int64_t b = ld_int(sel->dtype, sel->data, q * pitch + i); + if (b < 0 || b >= blocks) return RAD_E_INVAL; + off.push_back(q * pitch + i); + ent.push_back(b); + } + } + 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) ---- */ + std::vector 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 (see "The semantics", step 2). */ + if (ST[s * stp] != epoch) { + ST[s * stp] = epoch; + ST[s * stp + 1] = heat_up(ST[s * stp + 1]); + } + } else if (s == -1) { + R[b] = -2; + miss.push_back(b); + } + } + const int64_t lookups = (int64_t)ent.size(); + + /* ---- 3. the canonical miss order ---- */ + std::sort(miss.begin(), miss.end()); + + /* ---- 4. one victim per miss: identity, a free slot, then CLOCK, from the hand, never a slot + * this call uses ---- */ + /* Identity first (see "The semantics", step 4): a missed block whose id fits the ring and whose + * own slot is free takes that slot and leaves the hand alone, so the fallback below runs from + * the hand it would always have run from. A free slot is not a victim (see step 4): the ring's + * empty region fills before any resident block is evicted. The free scan halves no counter + * and does not move the hand when it finds nothing, so a full ring takes the CLOCK victim it + * always took. The count below is what lets a full ring go straight to CLOCK: no placement + * frees a slot and no eviction does either, so a count of zero 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; + bool overflow = false; + for (size_t k = 0; k < miss.size(); ++k) { + const int32_t b = miss[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] = heat_down(ST[s * stp + 1]); + continue; + } + victim = s; + break; + } + } + if (victim < 0) { 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] = heat_up(ST[victim * stp + 1]); + R[b] = (int32_t)victim; + ++placed; + } + /* A miss the sweep could not place is not resident: undo the claim, so the next call may claim + * it again, and leave its selection entries naming the block (see "Overflow"). */ + for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1; + + /* ---- 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) { + const int32_t b = miss[(size_t)k]; + std::memcpy(pb + (int64_t)R[b] * bbytes, hb + (int64_t)b * bbytes, (size_t)bbytes); + } + + /* ---- 7. the rewrite: every valid entry becomes the slot holding its block ---- */ + for (size_t e = 0; e < ent.size(); ++e) { + const int32_t s = R[ent[e]]; + /* An entry of a miss the sweep could not place names slot 0, not its block id: the id is + * an address outside the ring (see "Overflow"). ctl[3] is what says the table is unusable. */ + st_int(sel->dtype, sel->data, off[e], s >= 0 ? s : 0); + } + + /* ---- the bookkeeping ---- */ + /* The union is over DISTINCT blocks, so it is counted from the slots this call stamped (every + * block it hit or placed leaves the call's epoch there) plus the misses it could not place: + * entries repeat, a selection names one block per row and many rows share swaths of history. */ + int64_t used = 0; + for (int64_t s = 0; s < slots; ++s) + if (ST[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; + /* The sizes the counters report: the union this call selected and the part of it that had to + * be copied in. + * A ring sized for the largest union a launch selects is the whole answer to "how large does the + * ring have to be" (docs/KV-STREAMING.md §3.4). */ + 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 + kKvCtlMisses); + ctr[0] += (uint64_t)placed; + ctr[1] += (uint64_t)lookups; + ctr[2] += 1u; + return RAD_OK; +} diff --git a/libref/ref_ops.h b/libref/ref_ops.h index b652f7d1..ccf6f1d2 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -153,6 +153,8 @@ int ref_chan_stats (const RadArgs*, RadStream); /* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */ int ref_sam_attn (const RadArgs*, RadStream); int ref_kv_store (const RadArgs*, RadStream); +/* the store of a streamed group: the host mirror always, the ring slot when the block is resident */ +int ref_kv_store_streamed (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); int ref_qk_norm_rope (const RadArgs*, RadStream); @@ -242,6 +244,8 @@ int ref_qsa_score (const RadArgs*, RadStream); int ref_qsa_select (const RadArgs*, RadStream); int ref_qsa_tail_store (const RadArgs*, RadStream); int ref_qsa_work (const RadArgs*, RadStream); +/* the residency map between a streamed group's block ids and its ring slots (ref_kvstream.cpp) */ +int ref_kv_resolve (const RadArgs*, RadStream); int ref_dflash_conv (const RadArgs*, RadStream); /* ---- mixture of experts */ @@ -406,6 +410,7 @@ REF_SHAPE_FN(ref_mix_rows); REF_SHAPE_FN(ref_chan_stats); REF_SHAPE_FN(ref_sam_attn); REF_SHAPE_FN(ref_kv_store); +REF_SHAPE_FN(ref_kv_store_streamed); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); REF_SHAPE_FN(ref_qk_norm_rope); @@ -487,6 +492,7 @@ REF_SHAPE_FN(ref_qsa_score); REF_SHAPE_FN(ref_qsa_select); REF_SHAPE_FN(ref_qsa_tail_store); REF_SHAPE_FN(ref_qsa_work); +REF_SHAPE_FN(ref_kv_resolve); REF_SHAPE_FN(ref_dflash_conv); REF_SHAPE_FN(ref_router_topk); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 7d9ed170..07c7db77 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -403,6 +403,17 @@ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n 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` with the group's two copies: `host` is the authoritative mirror + * (always written) and `res` is the residency map that says whether the block is in the ring. The + * parameters are kv_store's, because the layout and the conversion are the same; `res` is read, + * never written, since residency is `kv_resolve`'s decision. */ +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") }; 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"), @@ -457,6 +468,17 @@ static const RadParamSpec pQsaWork[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), static const RadOperandSpec oQsaWork[] = { OPD("k"), OPD("pos"), OPD("cu"), OPD("state"), OPD("sidx"), OPD("bt"), OPD_O("rope"), OUT("stage"), OUT("page"), OUT("bpos"), OUT("nc") }; +/* The residency map of a streamed group (ref_kvstream.cpp, docs/KV-STREAMING.md §3.4). No + * `block_size`: the op moves whole blocks by the byte and never reads an element, and a + * `block_size` key would make it a KV group's consumer, taking the binding away from the resolved + * attention kernel (Builder::find_kv_consumer). `sel_pitch` and `block_bytes` are the selection's + * row pitch and one block of one layer's byte extent. The miss list is the row's scratch, not an + * operand. */ +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") }; /* DFlash2's grouped convolution, libr4d's schema exactly. */ static const RadParamSpec pDflashConv[] = { P_INT("T"), P_INT("hidden_size"), P_INT("taps"), @@ -1383,6 +1405,11 @@ static const RadOpSchema kSchemas[] = { { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, +{ "kv_store_streamed", ARR(pKvStoreStreamed), ARR(oKvStoreStreamed), + "kv_store for a streamed group: writes the token's k and v into the group's 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; a block absent from the ring " + "is copied in whole by kv_resolve." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: " "rot values a row, cos for the first half and sin for the second. The angles are `rope`'s " @@ -1409,6 +1436,15 @@ static const RadOpSchema kSchemas[] = { "The blocks completing in this batch: per block its `ratio` raw keys (this step's rows, or the " "tail's at q % ring) staged contiguously, its block-key page and its first-token position; slots " "past the count get page -1. nc is each sequence's complete-block count." }, +{ "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." }, { "dflash_conv", ARR(pDflashConv), ARR(oDflashConv), "DFlash2's grouped dynamic depthwise convolution: out[t][h] = sum over taps j, j == 0 or " "t % block_size >= j, of (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]." }, @@ -2234,6 +2270,9 @@ SIMPLE("ref_sam_attn", "sam_attn", "attn", ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_kv_store, nullptr), +ROW("ref_kv_store_streamed", "kv_store_streamed", "attn", + "scatter k and v into the host mirror always and into the resident ring slot", DT_ANY, + nullptr, 0, nullptr, nullptr, ref_kv_store_streamed, nullptr), SIMPLE("ref_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, ref_rope), SIMPLE("ref_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding", DT_FLOAT, ref_qk_norm_rope), @@ -2276,6 +2315,9 @@ SIMPLE("ref_qsa_tail_store", "qsa_tail_store", "attn", ref_qsa_tail_store), SIMPLE("ref_qsa_work", "qsa_work", "attn", "QSA work list: completing blocks' keys, pages and positions", DT_FLOAT, ref_qsa_work), +SIMPLE("ref_kv_resolve", "kv_resolve", "attn", + "streamed KV residency map: selected block ids become ring slots, misses copied in", + "i32 maps, u8 block planes", ref_kv_resolve), SIMPLE("ref_dflash_conv", "dflash_conv", "draft", "DFlash2 grouped dynamic depthwise convolution", DT_FLOAT, ref_dflash_conv), SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk), diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 9cfc2d9d..a2527135 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1455,6 +1455,36 @@ int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("kv_store", operand, out); } +/* The streamed store. Same geometry as `kv_store`, with the mirror and the residency map beside + * the ring: the mirror is one block a row of the same byte pitch. + * + * The described call touches ONE block, resident in ring slot 0. The draw vocabulary cannot express + * an injective residency map (block -> slot is a permutation, and a draw is a free choice per + * entry), and two blocks drawing one slot would make two tokens write the same ring byte -- a race + * the parallel rerun rightly reports. So the generated case exercises the conversion, the positions + * within a block, the mirror write and the resident ring write; a partly resident map and the + * mirror-only step are built by hand in tests/ref_test.cpp and libavx's hand cases. `M <= block_size` + * keeps every token on its own position of that one block. */ +int ref_kv_store_streamed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t kvh = gi(p, n_p, "n_head_kv", 0); + const int64_t bs = gi(p, n_p, "block_size", 0); + if (M <= 0 || hd <= 0 || kvh <= 0 || bs <= 0 || M > bs) return RAD_E_UNSUPPORTED; + const uint32_t kv = dt_parse(gs(p, n_p, "kv_dtype")); + const uint32_t KV = kv == (uint32_t)RAD_DT_INVALID ? (uint32_t)RAD_F8E4M3 : kv; + const int64_t row = kvh * bs * 2 * hd * (KV == (uint32_t)RAD_BF16 ? 2 : 1); + + Opd o; + o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* k */ + o.t((uint32_t)RAD_BF16, { M, kvh, hd }); /* v */ + o.t_idx({ M }, bs, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* slot_mapping, one block */ + o.t(KV, { 1, kvh, bs, 2 * hd }); /* kv_cache, INOUT */ + o.t_idx({ 1 }, 1, -1, 0); /* res -- resident in slot 0 */ + o.t((uint32_t)RAD_U8, { 1, row }); /* host, INOUT */ + return o.finish("kv_store_streamed", operand, out); +} + int ref_rope_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -1644,6 +1674,32 @@ int ref_qsa_work_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("qsa_work", operand, out); } +/* The residency map and the two byte planes. `sel` is described as block ids, which is what + * `qsa_select` leaves there; past `nsel` it is -1 padding the op does not touch. + * + * A described residency map can only be an all-resident one: the description vocabulary draws an + * index in [0, idx_max) or a non-negative constant, and a cold entry is -1 (`res[b] == -1`, an + * absent block), which no draw expresses. So a tool that calls this op cold sees every block + * resident, which exercises the epoch, the rewrite and the bookkeeping but never a miss, an + * eviction or a copy. The service-shaped cases (a partly resident pool, a second chance, an + * eviction, an overflow) are built by hand in tests/ref_test.cpp and in libavx's hand cases. */ +int ref_kv_resolve_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), blocks = gi(p, n_p, "blocks", 0); + const int64_t slots = gi(p, n_p, "slots", 0), pitch = gi(p, n_p, "sel_pitch", 0); + const int64_t bbytes = gi(p, n_p, "block_bytes", 0); + if (M <= 0 || blocks <= 0 || slots <= 0 || pitch <= 0 || bbytes <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t_idx({ M, pitch }, blocks, -1, 0); /* sel -- one block id an entry */ + o.t_idx({ M }, pitch + 1, -1, 0); /* nsel -- 0 .. sel_pitch */ + o.t_idx({ blocks }, slots, -1, 0); /* res -- every block resident, no -2 */ + o.t_idx({ slots }, blocks, -1, 0); /* slot_block -- the reverse map */ + o.t_idx({ slots, 2 }, 2, 0, 0); /* slot_state -- cold: epoch 0, no reference */ + o.t_idx({ 16 }, 2, 0, 0); /* ctl -- cold: epoch 0, hand 0 */ + o.t((uint32_t)RAD_U8, { blocks, bbytes }); /* host -- the layer's mirror, a block a row */ + o.t((uint32_t)RAD_U8, { slots, bbytes }); /* kv_cache -- the layer's ring, a block a row */ + return o.finish("kv_resolve", operand, out); +} + /* `delta` is described as the whole [T, 2 * taps * NG] coefficient projection, of which the op * reads the first taps * NG columns at the row pitch: the form the architecture issues, and the * pitch libr4d requires. */