Archived
device and plugin boundary: kv_resolve, the streamed store rows, ABI 30
This commit is contained in:
1 parent
5a9ce4912b
commit
cce687bf2c
34 files changed
+3643
-29
No files matched your search
@@ -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|"
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 <hip/hip_runtime.h>
|
||||
#include <cstdint>
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -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 <int BF16>
|
||||
__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).
|
||||
|
||||
@@ -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*);
|
||||
|
||||
@@ -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 <int KVF>
|
||||
@@ -386,6 +443,76 @@ extern "C" int r4d_rad_qk_norm_rope_gate_kv_store(const RadArgs* args, RadStream
|
||||
: qk_body<QK_KV_FP8>(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<QK_KV_STREAMED_BF16>(args, stream, kvs)
|
||||
: qk_body<QK_KV_STREAMED>(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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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. */
|
||||
|
||||
Reference in new issue
Block a user