okami.mom/strata

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

Niko1221verify: a Q4_0 KV cache takes the batched verify window by default (STRATA_DF_QB_Q4=0 for the old path): the 6-token graph is 1950 nodes, not 2610, ids identical; + kv_window_parity test (#2403: a gfx1030 fault with q4_0 + KV streaming + MTP, not reproduced; cause unconfirmed)7e8485a48

main
17.8 KiB331 linesraw
1// src/kernels/kv_window_parity.cpp - the verify window's KV calls on a STREAMED layer, as the engine makes them (GPU, no model).
2//
3// kv_stream_parity appends one cell per call. The engine's verify window (and the MTP drafter's catch-up) appends n = 2..6
4// cells in ONE launch (kv_append_*_steps, a 3D grid with the host copy as a kernel argument), resolves the n selections
5// together, attends n queries in one batched launch, and does all of it inside a captured graph on a non-blocking
6// stream. This test drives exactly that sequence for each KV format on a layer that must evict, and on a ring over a host
7// copy (the drafter's layout), and checks
8//   1. the host copy equals a fully resident reference pool, byte for byte, for every cell written;
9//   2. every resident slot equals the reference block it holds (the slots never go stale);
10//   3. the streamed attention of each window equals the resident one, bitwise (n queries);
11//   4. the ring's attention (last cells, through `block % n_slots`) equals the resident one;
12//   5. nothing faulted (a stray store or load of the append / copy / attention kernels ends the run in a CUDA error).
13// Every window runs twice per format: as plain launches and replayed from a graph captured per window size. Issue #2403
14// (q4_0 KV + KV streaming + MTP) is the case this was written for.
15#include "strata/kernels/kv_q4.hpp"
16#include "strata/kernels/kv_q8.hpp"
17#include "strata/kernels/kv_stream.hpp"
18#include "strata/kernels/qsa.hpp"
19#include "strata/kernels/qsa_decode_attn.hpp"
20
21#include <cuda_runtime.h>
22
23#include <algorithm>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <random>
28#include <set>
29#include <vector>
30
31namespace k = strata::kernels;
32
33namespace {
34void ck(cudaError_t e, const char* w) {
35    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
36}
37template <typename T> T* dalloc(size_t n) {
38    T* p = nullptr;
39    ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc");
40    ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset");
41    return p;
42}
43struct HostBuf {   // pinned, mapped: `d` is what kernels get, `h` what the test reads
44    void* h = nullptr;
45    void* d = nullptr;
46};
47HostBuf halloc(size_t bytes) {
48    HostBuf b;
49    ck(cudaHostAlloc(&b.h, bytes + 64, cudaHostAllocMapped), "hostalloc");
50    std::memset(b.h, 0, bytes + 64);
51    ck(cudaHostGetDevicePointer(&b.d, b.h, 0), "devptr");
52    return b;
53}
54
55constexpr int kMaxWin = 6;   // --spec 4 windows are <= 5 tokens, the drafter's catch-up T <= 6
56
57// One KV array of a pool set: the pointer (device or host-mapped), the host-readable twin, bytes per page (block).
58struct Arr {
59    void* d = nullptr;
60    void* h = nullptr;   // non-null for host copies
61    size_t per_block = 0;
62};
63
64struct Pools {   // one pool set of `pages` pages in the layout of format `fmt`
65    k::KvHostPools p;
66    std::vector<Arr> arrs;
67    void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) {
68        const size_t rows_per_page = (size_t) s.n_head_kv * s.page_size, rows = (size_t) pages * rows_per_page;
69        auto mk = [&](size_t per_row, auto** field) {
70            using T = std::remove_pointer_t<std::remove_pointer_t<decltype(field)>>;
71            Arr a;
72            a.per_block = rows_per_page * per_row;
73            if (host) { HostBuf b = halloc(rows * per_row); a.d = b.d; a.h = b.h; }
74            else a.d = dalloc<uint8_t>(rows * per_row);
75            *field = (T*) a.d;
76            arrs.push_back(a);
77        };
78        const size_t q4 = k::kv_q4_bytes_per_head((int) s.head_dim);
79        const size_t codes = (size_t) s.head_dim, scales = (size_t) (s.head_dim / k::KV_Q8_GROUP) * 2;
80        if (fmt == k::kKvHybrid) {
81            mk(codes, &p.k_q); mk(scales, &p.k_scale); mk(q4, &p.v_q4);
82        } else if (fmt == k::kKvQ4) {
83            mk(q4, &p.k_q4); mk(q4, &p.v_q4);
84        } else {   // kKvInt8
85            mk(codes, &p.k_q); mk(codes, &p.v_q); mk(scales, &p.k_scale); mk(scales, &p.v_scale);
86        }
87    }
88    k::QsaAttnPools attn(const int32_t* table) const {
89        k::QsaAttnPools a;
90        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;
91        a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table;
92        return a;
93    }
94};
95
96// The appends of one window, as verify.cpp / mtp.cpp make them.
97void append_window(const Pools& pl, const int32_t* table, const int32_t* steps, const float* kc, const float* vc, int n,
98                   const k::QsaShapes& s, int fmt, const k::KvHostPools* host, cudaStream_t cs) {
99    const int cur = (int) (s.n_head_kv * s.head_dim);
100    if (fmt == k::kKvHybrid) {   // the unused half's lanes folded onto the used pool (layer.cpp), the host copy by halves
101        const k::KvHostPools hk = host ? k::kv_hybrid_k_half(*host) : k::KvHostPools{},
102                             hv = host ? k::kv_hybrid_v_half(*host) : k::KvHostPools{};
103        k::kv_append_q8_steps(pl.p.k_q, pl.p.k_q, pl.p.k_scale, pl.p.k_scale, table, steps, k::kStepCount, kc, kc, cur, n, s, cs,
104                              host ? &hk : nullptr);
105        k::kv_append_q4_steps(pl.p.v_q4, pl.p.v_q4, table, steps, k::kStepCount, n, vc, vc, s, cs, host ? &hv : nullptr);
106    } else if (fmt == k::kKvQ4) {
107        k::kv_append_q4_steps(pl.p.k_q4, pl.p.v_q4, table, steps, k::kStepCount, n, kc, vc, s, cs, host);
108    } else {
109        k::kv_append_q8_steps(pl.p.k_q, pl.p.v_q, pl.p.k_scale, pl.p.v_scale, table, steps, k::kStepCount, kc, vc, cur, n, s, cs,
110                              host);
111    }
112}
113
114// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block.
115std::vector<int32_t> selection(int64_t n_kv, int64_t width, std::mt19937& rng) {
116    std::vector<int32_t> ids;
117    if (n_kv <= width) {
118        for (int64_t c = 0; c < n_kv; ++c) ids.push_back((int32_t) c);
119        return ids;
120    }
121    const int64_t n_bid = n_kv / 4, tail = n_kv - n_bid * 4;
122    std::set<int64_t> blocks;
123    const int64_t want_full = (width - tail) / 4, part = (width - tail) % 4;
124    std::uniform_int_distribution<int64_t> any(0, n_bid - 1), recent(std::max<int64_t>(0, n_bid - 2048), n_bid - 1);
125    while ((int64_t) blocks.size() < want_full + (part ? 1 : 0)) blocks.insert(rng() % 2 ? recent(rng) : any(rng));
126    int64_t partial_block = part ? *std::next(blocks.begin(), (long) (rng() % blocks.size())) : -1;
127    for (int64_t b : blocks) {
128        const int64_t take = b == partial_block ? part : 4;
129        for (int64_t i = 0; i < take; ++i) ids.push_back((int32_t) (b * 4 + i));
130    }
131    for (int64_t c = n_bid * 4; c < n_kv; ++c) ids.push_back((int32_t) c);
132    std::sort(ids.begin(), ids.end());
133    return ids;
134}
135
136int g_bad = 0;
137void fail(const char* fmt_name, const char* what, long long a = 0, long long b = 0) {
138    if (g_bad++ < 12) std::fprintf(stderr, "  FAIL %s: %s (%lld, %lld)\n", fmt_name, what, a, b);
139}
140
141bool run(int fmt, bool graphs) {
142    const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : "int8";
143    k::QsaShapes s = k::qsa_real_shapes();
144    const int64_t N = 40000, n_blocks = (N + 3) / 4;
145    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
146    const int64_t n_slots = kMaxWin * (cap / 4 + 2) + 700;   // holds one window's selections; far fewer than n_blocks
147    const int64_t R = 1500;                                  // the drafter-like ring
148    const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head;
149    std::mt19937 rng(11 + 5 * fmt + graphs);
150    std::normal_distribution<float> nd(0.f, 1.f);
151
152    cudaStream_t cs;
153    ck(cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking), "stream");
154    Pools ref, slots, host, ring, ring_host;
155    ref.alloc(n_blocks, s, fmt, false);
156    slots.alloc(n_slots, s, fmt, false);
157    host.alloc(n_blocks, s, fmt, true);
158    ring.alloc(R, s, fmt, false);
159    ring_host.alloc(n_blocks, s, fmt, true);
160    int32_t* ident = dalloc<int32_t>(n_blocks);
161    int32_t* rtab = dalloc<int32_t>(n_blocks);
162    {
163        std::vector<int32_t> t(n_blocks);
164        for (int64_t i = 0; i < n_blocks; ++i) t[i] = (int32_t) i;
165        ck(cudaMemcpy(ident, t.data(), n_blocks * 4, cudaMemcpyHostToDevice), "ident");
166        k::kv_ring_table(rtab, n_blocks, R, nullptr);
167    }
168    k::KvStreamMap m;
169    m.page_table = dalloc<int32_t>(n_blocks);
170    m.slot_block = dalloc<int32_t>(n_slots); m.slot_stamp = dalloc<int32_t>(n_slots); m.slot_ref = dalloc<int32_t>(n_slots);
171    m.miss_block = dalloc<int32_t>(n_slots); m.miss_slot = dalloc<int32_t>(n_slots);
172    m.ctl = dalloc<int32_t>(k::kKvCtlInts);
173    m.n_blocks = n_blocks; m.n_slots = n_slots;
174    k::kv_stream_reset(m, nullptr);
175    ck(cudaDeviceSynchronize(), "setup");
176
177    float* kc = dalloc<float>(kMaxWin * H * D);
178    float* vc = dalloc<float>(kMaxWin * H * D);
179    int32_t* steps = dalloc<int32_t>(kMaxWin * k::kStepCount);
180    int32_t* ids = dalloc<int32_t>(kMaxWin * cap);
181    int32_t* ring_ids = dalloc<int32_t>(cap);
182    int32_t* ring_step = dalloc<int32_t>(k::kStepCount);
183    float* q = dalloc<float>(kMaxWin * NH * D);
184    const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s);
185    float* scratch = dalloc<float>(kMaxWin * scr);
186    float* out_ref = dalloc<float>(kMaxWin * NH * D);
187    float* out_str = dalloc<float>(kMaxWin * NH * D);
188    float* scratch2 = dalloc<float>(scr);
189    float* out_rref = dalloc<float>(NH * D);
190    float* out_rng = dalloc<float>(NH * D);
191    const k::KvHostPools* hp = &host.p;
192    const k::KvHostPools* rhp = &ring_host.p;
193
194    // per window size n: the appends (resident reference, streamed + host copy, ring + its host copy) and, for a window
195    // that is also attended, the streamed resolve + attention, each captured once
196    cudaGraphExec_t g_app[kMaxWin + 1] = {}, g_att[kMaxWin + 1] = {};
197    auto record_app = [&](int n) {
198        append_window(ref, ident, steps, kc, vc, n, s, fmt, nullptr, cs);
199        append_window(slots, m.page_table, steps, kc, vc, n, s, fmt, hp, cs);
200        append_window(ring, rtab, steps, kc, vc, n, s, fmt, rhp, cs);
201    };
202    auto record_att = [&](int n) {
203        k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n, cap, s, cs);
204        k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n, cs);
205    };
206    if (graphs) {
207        for (int n = 1; n <= kMaxWin; ++n) {
208            cudaGraph_t g = nullptr;
209            ck(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture");
210            record_app(n);
211            ck(cudaStreamEndCapture(cs, &g), "end capture");
212            ck(cudaGraphInstantiate(&g_app[n], g, 0), "instantiate append");
213            (void) cudaGraphDestroy(g);
214            ck(cudaStreamBeginCapture(cs, cudaStreamCaptureModeThreadLocal), "begin capture");
215            record_att(n);
216            ck(cudaStreamEndCapture(cs, &g), "end capture");
217            ck(cudaGraphInstantiate(&g_att[n], g, 0), "instantiate attention");
218            (void) cudaGraphDestroy(g);
219        }
220    }
221
222    std::vector<float> hk(kMaxWin * H * D), hv(kMaxWin * H * D), hq(kMaxWin * NH * D);
223    std::vector<float> a((size_t) kMaxWin * NH * D), b2((size_t) kMaxWin * NH * D);
224    int windows = 0, attended = 0;
225    int64_t pos = 0;
226    while (pos < N) {
227        const int n = (int) std::min<int64_t>(N - pos, 1 + (int64_t) (rng() % kMaxWin));
228        for (int j = 0; j < n; ++j)
229            for (int64_t i = 0; i < H * D; ++i) {
230                hk[j * H * D + i] = nd(rng) * (((pos + j) % 17 == 0) ? 30.f : 1.f);
231                hv[j * H * D + i] = nd(rng);
232            }
233        std::vector<int32_t> st((size_t) n * k::kStepCount);
234        for (int j = 0; j < n; ++j) {
235            const int64_t p = pos + j;
236            st[j * 4 + k::kStepPos] = (int32_t) p; st[j * 4 + k::kStepNKv] = (int32_t) (p + 1);
237            st[j * 4 + k::kStepNBid] = (int32_t) ((p + 1) / 4); st[j * 4 + k::kStepWidth] = (int32_t) std::min<int64_t>(p + 1, cap);
238        }
239        ck(cudaMemcpyAsync(kc, hk.data(), (size_t) n * H * D * 4, cudaMemcpyHostToDevice, cs), "k");
240        ck(cudaMemcpyAsync(vc, hv.data(), (size_t) n * H * D * 4, cudaMemcpyHostToDevice, cs), "v");
241        ck(cudaMemcpyAsync(steps, st.data(), st.size() * 4, cudaMemcpyHostToDevice, cs), "steps");
242        ck(cudaStreamSynchronize(cs), "upload");   // pageable sources: the copies above must be done before the vectors change
243        if (graphs) ck(cudaGraphLaunch(g_app[n], cs), "graph append");
244        else record_app(n);
245        ++windows;
246        pos += n;
247        if (windows % 37 != 0 && pos < N) continue;
248        // attend the window just appended: n queries at its n positions, each with a selection of its own
249        std::vector<int32_t> hids((size_t) n * cap, 0);
250        for (int j = 0; j < n; ++j) {
251            const int64_t n_kv = pos - (n - 1 - j), width = std::min<int64_t>(n_kv, cap);
252            const std::vector<int32_t> sel = selection(n_kv, width, rng);
253            if ((int64_t) sel.size() != width) { std::fprintf(stderr, "selection size\n"); std::exit(2); }
254            std::copy(sel.begin(), sel.end(), hids.begin() + (size_t) j * cap);
255        }
256        for (auto& x : hq) x = nd(rng);
257        ck(cudaMemcpyAsync(ids, hids.data(), hids.size() * 4, cudaMemcpyHostToDevice, cs), "ids");
258        ck(cudaMemcpyAsync(q, hq.data(), (size_t) n * NH * D * 4, cudaMemcpyHostToDevice, cs), "q");
259        ck(cudaStreamSynchronize(cs), "upload2");
260        k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n, cs);
261        if (graphs) ck(cudaGraphLaunch(g_att[n], cs), "graph attention");
262        else record_att(n);
263        // the ring: the last cells of the last query, through block % R (the drafter reads its window only)
264        {
265            const int64_t n_kv = pos, width = std::min<int64_t>(n_kv, cap);
266            std::vector<int32_t> rid((size_t) cap, 0);
267            for (int64_t i = 0; i < width; ++i) rid[i] = (int32_t) (n_kv - width + i);
268            const int32_t rs[4] = {(int32_t) (n_kv - 1), (int32_t) n_kv, (int32_t) (n_kv / 4), (int32_t) width};
269            ck(cudaMemcpyAsync(ring_ids, rid.data(), rid.size() * 4, cudaMemcpyHostToDevice, cs), "rid");
270            ck(cudaMemcpyAsync(ring_step, rs, sizeof(rs), cudaMemcpyHostToDevice, cs), "rs");
271            ck(cudaStreamSynchronize(cs), "upload3");
272            k::qsa_decode_attn_batch(q, ref.attn(ident), ring_ids, ring_step, cap, s, scratch2, out_rref, 1, cs);
273            k::qsa_decode_attn_batch(q, ring.attn(rtab), ring_ids, ring_step, cap, s, scratch2, out_rng, 1, cs);
274        }
275        ck(cudaStreamSynchronize(cs), "window");
276        ck(cudaGetLastError(), "window (last error)");
277        // 3. the streamed attention of the n queries equals the resident one
278        ck(cudaMemcpy(a.data(), out_ref, (size_t) n * NH * D * 4, cudaMemcpyDeviceToHost), "a");
279        ck(cudaMemcpy(b2.data(), out_str, (size_t) n * NH * D * 4, cudaMemcpyDeviceToHost), "b");
280        if (std::memcmp(a.data(), b2.data(), (size_t) n * NH * D * 4) != 0) fail(name, "streamed attention differs", pos, n);
281        // 4. the ring reads the same values as the resident pool
282        std::vector<float> r(NH * D), rr(NH * D);
283        ck(cudaMemcpy(r.data(), out_rng, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "r");
284        ck(cudaMemcpy(rr.data(), out_rref, (size_t) NH * D * 4, cudaMemcpyDeviceToHost), "rr");
285        if (std::memcmp(rr.data(), r.data(), (size_t) NH * D * 4) != 0) fail(name, "ring attention differs", pos, n);
286        ++attended;
287    }
288    // 1. the host copies equal the resident reference, byte for byte (all cells written)
289    long long host_bad = 0, slot_bad = 0, resident = 0;
290    for (int ai = 0; ai < (int) ref.arrs.size(); ++ai) {
291        const size_t per = ref.arrs[ai].per_block;
292        std::vector<uint8_t> rb((size_t) n_blocks * per);
293        ck(cudaMemcpy(rb.data(), ref.arrs[ai].d, rb.size(), cudaMemcpyDeviceToHost), "ref d2h");
294        const size_t written = (size_t) ((N + 3) / 4) * per;
295        host_bad += std::memcmp(rb.data(), host.arrs[ai].h, written) != 0;
296        host_bad += std::memcmp(rb.data(), ring_host.arrs[ai].h, written) != 0;
297        // 2. every resident slot equals the block it holds
298        std::vector<uint8_t> sb((size_t) n_slots * per);
299        ck(cudaMemcpy(sb.data(), slots.arrs[ai].d, sb.size(), cudaMemcpyDeviceToHost), "slots d2h");
300        std::vector<int32_t> pt(n_blocks);
301        ck(cudaMemcpy(pt.data(), m.page_table, n_blocks * 4, cudaMemcpyDeviceToHost), "pt");
302        for (int64_t bk = 0; bk < n_blocks; ++bk)
303            if (pt[bk] >= 0) {
304                if (ai == 0) ++resident;
305                slot_bad += std::memcmp(sb.data() + (size_t) pt[bk] * per, rb.data() + (size_t) bk * per, per) != 0;
306            }
307    }
308    if (host_bad) fail(name, "a host copy differs from the resident reference", host_bad);
309    if (slot_bad) fail(name, "a resident slot differs from its block", slot_bad);
310    const k::KvStreamCounters c = k::kv_stream_counters(m);
311    std::printf("  %-5s %-6s: %d windows (%d attended), %llu block lookups, %llu misses, %lld resident, overflow %d, host/ring-host bad %lld, stale slots %lld\n",
312                name, graphs ? "graph" : "direct", windows, attended, (unsigned long long) c.lookups, (unsigned long long) c.misses,
313                resident, (int) c.overflow, host_bad, slot_bad);
314    if (c.overflow || c.misses == 0 || c.misses >= c.lookups) fail(name, "the stream counters are off", (long long) c.misses, (long long) c.lookups);
315    for (int n = 1; n <= kMaxWin; ++n) {
316        if (g_app[n]) (void) cudaGraphExecDestroy(g_app[n]);
317        if (g_att[n]) (void) cudaGraphExecDestroy(g_att[n]);
318    }
319    (void) cudaStreamDestroy(cs);
320    return g_bad == 0;
321}
322}  // namespace
323
324int main() {
325    std::printf("kv_window_parity: verify-window KV calls on a streamed layer and on a ring, plain launches and graph replays\n");
326    bool ok = true;
327    for (int fmt : {k::kKvQ4, k::kKvInt8, k::kKvHybrid})
328        for (bool graphs : {false, true}) ok = run(fmt, graphs) && ok;
329    std::printf(ok && g_bad == 0 ? "PASS\n" : "FAIL\n");
330    return ok && g_bad == 0 ? 0 : 1;
331}