okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Trevinkv: --kv k8v4 streams with --kv-residentfea9ff5a4

main
13.8 KiB246 linesraw
1// src/kernels/kv_stream_parity.cpp - KV streaming (kv_stream.hpp) against a fully resident pool (GPU, no model).
2//
3// Decodes a synthetic sequence twice: into a fully resident pool with the identity page table, and into a streamed
4// layer (host copy + a small VRAM slot pool that must evict constantly). Every few cells a batch of 1-8 queries
5// with selections shaped like the indexer's (whole 4-cell blocks, a partial threshold block, the tail block, half of
6// them recent) is attended in both; `kv_stream_resolve` runs before the streamed attention. Checks:
7//   1. the attention outputs are BITWISE equal (the streamed readers see exactly the resident values);
8//   2. the residency map is consistent after every call (slot_block and page_table invert each other);
9//   3. no call overflowed, and the hit/miss counters add up;
10//   4. a ring (the MTP drafter's layout) restored from the host copy reads the same values as the resident pool.
11// INT8, FP16, Q4_0 (PR #21) and hybrid K8V4 pools; K8V4's appends are the engine's folded calls (layer.cpp), its host
12// copy written through kv_hybrid_k_half / kv_hybrid_v_half.
13#include "strata/kernels/kv_q4.hpp"
14#include "strata/kernels/kv_q8.hpp"
15#include "strata/kernels/kv_stream.hpp"
16#include "strata/kernels/qsa.hpp"
17#include "strata/kernels/qsa_decode_attn.hpp"
18
19#include <cuda_runtime.h>
20
21#include <algorithm>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <set>
27#include <vector>
28
29namespace k = strata::kernels;
30
31namespace {
32int g_fail = 0;
33void ck(cudaError_t e, const char* w) {
34    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
35}
36template <typename T> T* dalloc(size_t n) {
37    T* p = nullptr;
38    ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc");
39    ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset");
40    return p;
41}
42template <typename T> T* halloc(size_t n) {   // pinned, mapped; returns the device pointer
43    void* h = nullptr;
44    void* d = nullptr;
45    ck(cudaHostAlloc(&h, n * sizeof(T) + 64, cudaHostAllocMapped), "hostalloc");
46    std::memset(h, 0, n * sizeof(T) + 64);
47    ck(cudaHostGetDevicePointer(&d, h, 0), "devptr");
48    return (T*) d;
49}
50
51struct Pools {   // one K/V pool set of `pages` pages
52    k::KvHostPools p;   // reused as a plain pointer bundle
53    void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) {
54        const size_t rows = (size_t) pages * s.n_head_kv * s.page_size;
55        if (fmt == k::kKvHybrid) {
56            const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);
57            p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
58            p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
59            p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
60        } else if (fmt == k::kKvQ4) {
61            const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);
62            p.k_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
63            p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
64        } else if (fmt == k::kKvInt8) {
65            p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
66            p.v_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
67            p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
68            p.v_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
69        } else {
70            p.k_pool = host ? halloc<uint16_t>(rows * s.head_dim) : dalloc<uint16_t>(rows * s.head_dim);
71            p.v_pool = host ? halloc<uint16_t>(rows * s.head_dim) : dalloc<uint16_t>(rows * s.head_dim);
72        }
73    }
74    k::QsaAttnPools attn(const int32_t* table) const {
75        k::QsaAttnPools a;
76        a.k_pool = p.k_pool; a.v_pool = p.v_pool; a.k_q = p.k_q; a.v_q = p.v_q; a.k_scale = p.k_scale;
77        a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table;
78        return a;
79    }
80};
81
82void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc,
83            const k::QsaShapes& s, int fmt, const k::KvHostPools* host) {
84    if (fmt == k::kKvHybrid) {   // exactly as qsa_layer: each half folded onto its own pool, host copy by halves
85        const k::KvHostPools hk = host ? k::kv_hybrid_k_half(*host) : k::KvHostPools{},
86                             hv = host ? k::kv_hybrid_v_half(*host) : k::KvHostPools{};
87        k::kv_append_q8_step(pl.p.k_q, pl.p.k_q, pl.p.k_scale, pl.p.k_scale, table, step, kc, kc, s, nullptr,
88                             host ? &hk : nullptr);
89        k::kv_append_q4_step(pl.p.v_q4, pl.p.v_q4, table, step, vc, vc, s, nullptr, host ? &hv : nullptr);
90    } else if (fmt == k::kKvQ4) k::kv_append_q4_step(pl.p.k_q4, pl.p.v_q4, table, step, kc, vc, s, nullptr, host);
91    else if (fmt == k::kKvInt8) k::kv_append_q8_step(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, step, kc, vc, s, nullptr, host);
92    else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host);
93}
94
95// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block.
96std::vector<int32_t> selection(int64_t n_kv, int64_t width, std::mt19937& rng) {
97    std::vector<int32_t> ids;
98    if (n_kv <= width) {
99        for (int64_t c = 0; c < n_kv; ++c) ids.push_back((int32_t) c);
100        return ids;
101    }
102    const int64_t n_bid = n_kv / 4, tail = n_kv - n_bid * 4;
103    std::set<int64_t> blocks;
104    const int64_t want_full = (width - tail) / 4, part = (width - tail) % 4;
105    std::uniform_int_distribution<int64_t> any(0, n_bid - 1), recent(std::max<int64_t>(0, n_bid - 2048), n_bid - 1);
106    while ((int64_t) blocks.size() < want_full + (part ? 1 : 0)) blocks.insert(rng() % 2 ? recent(rng) : any(rng));
107    int64_t partial_block = part ? *std::next(blocks.begin(), (long) (rng() % blocks.size())) : -1;
108    for (int64_t b : blocks) {
109        const int64_t take = b == partial_block ? part : 4;
110        for (int64_t i = 0; i < take; ++i) ids.push_back((int32_t) (b * 4 + i));
111    }
112    for (int64_t c = n_bid * 4; c < n_kv; ++c) ids.push_back((int32_t) c);
113    std::sort(ids.begin(), ids.end());
114    return ids;
115}
116
117bool run(int fmt) {
118    const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";
119    k::QsaShapes s = k::qsa_real_shapes();
120    const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700;   // must evict: slots < blocks
121    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8;
122    const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head;
123    std::mt19937 rng(7 + 4 * fmt);
124    std::normal_distribution<float> nd(0.f, 1.f);
125
126    Pools ref, slots, host;
127    ref.alloc(n_blocks, s, fmt, false);
128    slots.alloc(n_slots, s, fmt, false);
129    host.alloc(n_blocks, s, fmt, true);
130    int32_t* ident = dalloc<int32_t>(n_blocks);
131    {
132        std::vector<int32_t> t(n_blocks);
133        for (int64_t i = 0; i < n_blocks; ++i) t[i] = (int32_t) i;
134        ck(cudaMemcpy(ident, t.data(), n_blocks * 4, cudaMemcpyHostToDevice), "ident");
135    }
136    k::KvStreamMap m;
137    m.page_table = dalloc<int32_t>(n_blocks);
138    m.slot_block = dalloc<int32_t>(n_slots); m.slot_stamp = dalloc<int32_t>(n_slots); m.slot_ref = dalloc<int32_t>(n_slots);
139    m.miss_block = dalloc<int32_t>(n_slots); m.miss_slot = dalloc<int32_t>(n_slots);
140    m.ctl = dalloc<int32_t>(k::kKvCtlInts);
141    m.n_blocks = n_blocks; m.n_slots = n_slots;
142    k::kv_stream_reset(m, nullptr);
143
144    float* kc = dalloc<float>(H * D);
145    float* vc = dalloc<float>(H * D);
146    int32_t* step = dalloc<int32_t>(k::kStepCount);
147    int32_t* steps = dalloc<int32_t>(NQ * k::kStepCount);
148    int32_t* ids = dalloc<int32_t>(NQ * cap);
149    float* q = dalloc<float>(NQ * NH * D);
150    const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s);
151    float* scratch = dalloc<float>(NQ * scr);
152    float* out_ref = dalloc<float>(NQ * NH * D);
153    float* out_str = dalloc<float>(NQ * NH * D);
154    std::vector<float> hk(H * D), hv(H * D), hq(NQ * NH * D), a((size_t) NQ * NH * D), b2((size_t) NQ * NH * D);
155    std::vector<int32_t> pt(n_blocks), sb(n_slots);
156
157    int batches = 0, bad = 0;
158    for (int64_t pos = 0; pos < N; ++pos) {
159        for (auto& x : hk) x = nd(rng) * ((pos % 17 == 0) ? 30.f : 1.f);
160        for (auto& x : hv) x = nd(rng);
161        const int32_t st[4] = {(int32_t) pos, (int32_t) (pos + 1), (int32_t) ((pos + 1) / 4), 0};
162        ck(cudaMemcpy(kc, hk.data(), hk.size() * 4, cudaMemcpyHostToDevice), "k");
163        ck(cudaMemcpy(vc, hv.data(), hv.size() * 4, cudaMemcpyHostToDevice), "v");
164        ck(cudaMemcpy(step, st, sizeof(st), cudaMemcpyHostToDevice), "step");
165        append(ref, ident, step, kc, vc, s, fmt, nullptr);
166        append(slots, m.page_table, step, kc, vc, s, fmt, &host.p);
167        if (pos % 131 != 130 && pos != N - 1) continue;
168        // a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection
169        const int n_q = 1 + (int) (rng() % NQ);
170        std::vector<int32_t> hids((size_t) NQ * cap, 0), hst(NQ * 4, 0);
171        for (int t = 0; t < n_q; ++t) {
172            const int64_t p = std::max<int64_t>(0, pos - (n_q - 1 - t)), n_kv = p + 1;
173            const int64_t width = std::min<int64_t>(n_kv, cap);
174            const std::vector<int32_t> sel = selection(n_kv, width, rng);
175            if ((int64_t) sel.size() != width) { std::fprintf(stderr, "selection size %zu != %lld\n", sel.size(), (long long) width); return false; }
176            std::copy(sel.begin(), sel.end(), hids.begin() + (size_t) t * cap);
177            hst[t * 4 + 0] = (int32_t) p; hst[t * 4 + 1] = (int32_t) n_kv; hst[t * 4 + 2] = (int32_t) (n_kv / 4);
178            hst[t * 4 + 3] = (int32_t) width;
179        }
180        for (auto& x : hq) x = nd(rng);
181        ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids");
182        ck(cudaMemcpy(steps, hst.data(), hst.size() * 4, cudaMemcpyHostToDevice), "steps");
183        ck(cudaMemcpy(q, hq.data(), hq.size() * 4, cudaMemcpyHostToDevice), "q");
184        k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n_q, nullptr);
185        k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n_q, cap, s, nullptr);
186        k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n_q, nullptr);
187        ck(cudaDeviceSynchronize(), "batch");
188        ck(cudaMemcpy(a.data(), out_ref, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "a");
189        ck(cudaMemcpy(b2.data(), out_str, (size_t) n_q * NH * D * 4, cudaMemcpyDeviceToHost), "b");
190        if (std::memcmp(a.data(), b2.data(), (size_t) n_q * NH * D * 4) != 0) {
191            if (bad++ < 5) std::fprintf(stderr, "  %s pos %lld n_q %d: streamed attention differs\n", name, (long long) pos, n_q);
192        }
193        // the map inverts itself
194        ck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt");
195        ck(cudaMemcpy(sb.data(), m.slot_block, n_slots * 4, cudaMemcpyDeviceToHost), "sb");
196        int64_t resident = 0;
197        for (int64_t bk = 0; bk < n_blocks; ++bk) {
198            if (pt[bk] < -1 || pt[bk] >= n_slots || (pt[bk] >= 0 && sb[pt[bk]] != bk)) {
199                if (bad++ < 5) std::fprintf(stderr, "  map broken at block %lld (table %d)\n", (long long) bk, pt[bk]);
200                break;
201            }
202            resident += pt[bk] >= 0;
203        }
204        for (int64_t sl = 0; sl < n_slots; ++sl)
205            if (sb[sl] >= 0 && pt[sb[sl]] != sl) { if (bad++ < 5) std::fprintf(stderr, "  slot %lld not in the table\n", (long long) sl); break; }
206        ++batches;
207    }
208    const k::KvStreamCounters c = k::kv_stream_counters(m);
209    std::printf("  %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n",
210                name, batches, (unsigned long long) c.lookups, (unsigned long long) c.misses,
211                c.lookups ? 100.0 * (double) (c.lookups - c.misses) / (double) c.lookups : 0.0, (int) c.overflow, bad);
212    if (c.overflow || c.calls != (uint64_t) batches || c.misses == 0 || c.misses >= c.lookups) ++bad;
213
214    // 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R`
215    {
216        const int64_t R = 1500, b1 = n_blocks, b0 = b1 - R;
217        Pools ring;
218        ring.alloc(R, s, fmt, false);
219        int32_t* rt = dalloc<int32_t>(n_blocks);
220        k::kv_ring_table(rt, n_blocks, R, nullptr);
221        k::kv_ring_restore(ring.attn(rt), host.p, fmt, b0, b1, R, s, nullptr);
222        const int64_t width = cap;
223        std::vector<int32_t> hids((size_t) cap), hst = {(int32_t) (N - 1), (int32_t) N, (int32_t) (N / 4), (int32_t) width};
224        for (int64_t i = 0; i < width; ++i) hids[i] = (int32_t) (N - width + i);   // the window's last cells
225        ck(cudaMemcpy(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice), "ids");
226        ck(cudaMemcpy(steps, hst.data(), 16, cudaMemcpyHostToDevice), "steps");
227        k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, 1, nullptr);
228        k::qsa_decode_attn_batch(q, ring.attn(rt), ids, steps, cap, s, scratch, out_str, 1, nullptr);
229        ck(cudaDeviceSynchronize(), "ring");
230        ck(cudaMemcpy(a.data(), out_ref, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "a");
231        ck(cudaMemcpy(b2.data(), out_str, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "b");
232        const bool ok = std::memcmp(a.data(), b2.data(), (size_t) NH * D * 4) == 0;
233        std::printf("  %s ring restore: %s\n", name, ok ? "identical" : "DIFFERS");
234        if (!ok) ++bad;
235    }
236    return bad == 0;
237}
238}  // namespace
239
240int main() {
241    std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n");
242    const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4), d = run(k::kKvHybrid);
243    if (!a || !b || !c || !d) ++g_fail;
244    std::printf(g_fail ? "FAIL\n" : "PASS\n");
245    return g_fail ? 1 : 0;
246}