okami.mom/strata

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

Niko1221Merge branch 'f-1402-y' into f-14025af104b51

main
19.1 KiB356 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#define DPCT_PROFILING_ENABLED
14#include <sycl/sycl.hpp>
15#include <dpct/dpct.hpp>
16#include "strata/kernels/kv_q4.hpp"
17#include "strata/kernels/kv_q8.hpp"
18#include "strata/kernels/kv_stream.hpp"
19#include "strata/kernels/qsa.hpp"
20#include "strata/kernels/qsa_decode_attn.hpp"
21
22#include <algorithm>
23#include <cstdio>
24#include <cstdlib>
25#include <cstring>
26#include <random>
27#include <set>
28#include <vector>
29
30namespace k = strata::kernels;
31
32namespace {
33int g_fail = 0;
34void ck(dpct::err0 e, const char *w) {
35    /*
36    DPCT1009: SYCL reports errors using exceptions and does not use error
37    codes. Please replace the "get_error_string_dummy(...)" with a real
38    error-handling function.
39    */
40}
41template <typename T> T* dalloc(size_t n) {
42    T* p = nullptr;
43    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
44                            n * sizeof(T) + 64, dpct::get_in_order_queue())),
45       "malloc");
46    ck(DPCT_CHECK_ERROR(
47           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 64).wait()),
48       "memset");
49    return p;
50}
51template <typename T> T* halloc(size_t n) {   // pinned, mapped; returns the device pointer
52    void* h = nullptr;
53    void* d = nullptr;
54    /*
55    DPCT1048: The original value cudaHostAllocMapped is not meaningful in the
56    migrated code and was removed or replaced with 0. You may need to check the
57    migrated code.
58    */
59    ck(DPCT_CHECK_ERROR(h = (void *)sycl::malloc_host(
60                            n * sizeof(T) + 64, dpct::get_in_order_queue())),
61       "hostalloc");
62    std::memset(h, 0, n * sizeof(T) + 64);
63    ck(DPCT_CHECK_ERROR(d = (void *)h), "devptr");
64    return (T*) d;
65}
66
67struct Pools {   // one K/V pool set of `pages` pages
68    k::KvHostPools p;   // reused as a plain pointer bundle
69    void alloc(int64_t pages, const k::QsaShapes& s, int fmt, bool host) {
70        const size_t rows = (size_t) pages * s.n_head_kv * s.page_size;
71        if (fmt == k::kKvHybrid) {
72            const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);
73            p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
74            p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
75            p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
76        } else if (fmt == k::kKvQ4) {
77            const size_t b = rows * k::kv_q4_bytes_per_head((int) s.head_dim);
78            p.k_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
79            p.v_q4 = host ? halloc<uint8_t>(b) : dalloc<uint8_t>(b);
80        } else if (fmt == k::kKvInt8) {
81            p.k_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
82            p.v_q = host ? halloc<int8_t>(rows * s.head_dim) : dalloc<int8_t>(rows * s.head_dim);
83            p.k_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
84            p.v_scale = host ? halloc<uint16_t>(rows * 4) : dalloc<uint16_t>(rows * 4);
85        } else {
86            p.k_pool = host ? halloc<uint16_t>(rows * s.head_dim) : dalloc<uint16_t>(rows * s.head_dim);
87            p.v_pool = host ? halloc<uint16_t>(rows * s.head_dim) : dalloc<uint16_t>(rows * s.head_dim);
88        }
89    }
90    k::QsaAttnPools attn(const int32_t* table) const {
91        k::QsaAttnPools a;
92        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;
93        a.v_scale = p.v_scale; a.k_q4 = p.k_q4; a.v_q4 = p.v_q4; a.page_table = table;
94        return a;
95    }
96};
97
98void append(const Pools& pl, const int32_t* table, const int32_t* step, const float* kc, const float* vc,
99            const k::QsaShapes& s, int fmt, const k::KvHostPools* host) {
100    if (fmt == k::kKvHybrid) {   // exactly as qsa_layer: each half folded onto its own pool, 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_step(pl.p.k_q, pl.p.k_q, pl.p.k_scale, pl.p.k_scale, table, step, kc, kc, s, nullptr,
104                             host ? &hk : nullptr);
105        k::kv_append_q4_step(pl.p.v_q4, pl.p.v_q4, table, step, vc, vc, s, nullptr, host ? &hv : nullptr);
106    } 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);
107    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);
108    else k::kv_append_step(pl.p.k_pool, pl.p.v_pool, table, step, kc, vc, s, nullptr, host);
109}
110
111// A selection like qsa_block_topk's: ascending cells, whole blocks, the tail block's cells, and one partial block.
112std::vector<int32_t> selection(int64_t n_kv, int64_t width, std::mt19937& rng) {
113    std::vector<int32_t> ids;
114    if (n_kv <= width) {
115        for (int64_t c = 0; c < n_kv; ++c) ids.push_back((int32_t) c);
116        return ids;
117    }
118    const int64_t n_bid = n_kv / 4, tail = n_kv - n_bid * 4;
119    std::set<int64_t> blocks;
120    const int64_t want_full = (width - tail) / 4, part = (width - tail) % 4;
121    std::uniform_int_distribution<int64_t> any(0, n_bid - 1), recent(std::max<int64_t>(0, n_bid - 2048), n_bid - 1);
122    while ((int64_t) blocks.size() < want_full + (part ? 1 : 0)) blocks.insert(rng() % 2 ? recent(rng) : any(rng));
123    int64_t partial_block = part ? *std::next(blocks.begin(), (long) (rng() % blocks.size())) : -1;
124    for (int64_t b : blocks) {
125        const int64_t take = b == partial_block ? part : 4;
126        for (int64_t i = 0; i < take; ++i) ids.push_back((int32_t) (b * 4 + i));
127    }
128    for (int64_t c = n_bid * 4; c < n_kv; ++c) ids.push_back((int32_t) c);
129    std::sort(ids.begin(), ids.end());
130    return ids;
131}
132
133bool run(int fmt) {
134    const char* name = fmt == k::kKvHybrid ? "k8v4" : fmt == k::kKvQ4 ? "q4_0" : fmt == k::kKvInt8 ? "int8" : "fp16";
135    k::QsaShapes s = k::qsa_real_shapes();
136    const int64_t N = 40000, n_blocks = (N + 3) / 4, n_slots = 8 * 516 + 700;   // must evict: slots < blocks
137    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s), NQ = 8;
138    const int64_t H = s.n_head_kv, D = s.head_dim, NH = s.n_head;
139    std::mt19937 rng(7 + 4 * fmt);
140    std::normal_distribution<float> nd(0.f, 1.f);
141
142    Pools ref, slots, host;
143    ref.alloc(n_blocks, s, fmt, false);
144    slots.alloc(n_slots, s, fmt, false);
145    host.alloc(n_blocks, s, fmt, true);
146    int32_t* ident = dalloc<int32_t>(n_blocks);
147    {
148        std::vector<int32_t> t(n_blocks);
149        for (int64_t i = 0; i < n_blocks; ++i) t[i] = (int32_t) i;
150        /*
151        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
152        assuming in the original code the source host memory is pageable memory.
153        If the memory is not pageable, call wait() on event return by memcpy API
154        to ensure synchronization behavior.
155        */
156        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(ident, t.data(),
157                                                              n_blocks * 4).wait()),
158           "ident");
159    }
160    k::KvStreamMap m;
161    m.page_table = dalloc<int32_t>(n_blocks);
162    m.slot_block = dalloc<int32_t>(n_slots); m.slot_stamp = dalloc<int32_t>(n_slots); m.slot_ref = dalloc<int32_t>(n_slots);
163    m.miss_block = dalloc<int32_t>(n_slots); m.miss_slot = dalloc<int32_t>(n_slots);
164    m.ctl = dalloc<int32_t>(k::kKvCtlInts);
165    m.n_blocks = n_blocks; m.n_slots = n_slots;
166    k::kv_stream_reset(m, nullptr);
167
168    float* kc = dalloc<float>(H * D);
169    float* vc = dalloc<float>(H * D);
170    int32_t* step = dalloc<int32_t>(k::kStepCount);
171    int32_t* steps = dalloc<int32_t>(NQ * k::kStepCount);
172    int32_t* ids = dalloc<int32_t>(NQ * cap);
173    float* q = dalloc<float>(NQ * NH * D);
174    const uint64_t scr = k::qsa_decode_attn_scratch_floats(cap, s);
175    float* scratch = dalloc<float>(NQ * scr);
176    float* out_ref = dalloc<float>(NQ * NH * D);
177    float* out_str = dalloc<float>(NQ * NH * D);
178    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);
179    std::vector<int32_t> pt(n_blocks), sb(n_slots);
180
181    int batches = 0, bad = 0;
182    for (int64_t pos = 0; pos < N; ++pos) {
183        for (auto& x : hk) x = nd(rng) * ((pos % 17 == 0) ? 30.f : 1.f);
184        for (auto& x : hv) x = nd(rng);
185        const int32_t st[4] = {(int32_t) pos, (int32_t) (pos + 1), (int32_t) ((pos + 1) / 4), 0};
186        /*
187        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
188        assuming in the original code the source host memory is pageable memory.
189        If the memory is not pageable, call wait() on event return by memcpy API
190        to ensure synchronization behavior.
191        */
192        ck(DPCT_CHECK_ERROR(
193               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(kc, hk.data(), hk.size() * 4).wait()),
194           "k");
195        /*
196        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
197        assuming in the original code the source host memory is pageable memory.
198        If the memory is not pageable, call wait() on event return by memcpy API
199        to ensure synchronization behavior.
200        */
201        ck(DPCT_CHECK_ERROR(
202               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(vc, hv.data(), hv.size() * 4).wait()),
203           "v");
204        /*
205        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
206        assuming in the original code the source host memory is pageable memory.
207        If the memory is not pageable, call wait() on event return by memcpy API
208        to ensure synchronization behavior.
209        */
210        ck(DPCT_CHECK_ERROR(
211               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(step, st, sizeof(st)).wait()),
212           "step");
213        append(ref, ident, step, kc, vc, s, fmt, nullptr);
214        append(slots, m.page_table, step, kc, vc, s, fmt, &host.p);
215        if (pos % 131 != 130 && pos != N - 1) continue;
216        // a batch: n_q queries at the last n_q positions (as a verify window), each with its own selection
217        const int n_q = 1 + (int) (rng() % NQ);
218        std::vector<int32_t> hids((size_t) NQ * cap, 0), hst(NQ * 4, 0);
219        for (int t = 0; t < n_q; ++t) {
220            const int64_t p = std::max<int64_t>(0, pos - (n_q - 1 - t)), n_kv = p + 1;
221            const int64_t width = std::min<int64_t>(n_kv, cap);
222            const std::vector<int32_t> sel = selection(n_kv, width, rng);
223            if ((int64_t) sel.size() != width) { std::fprintf(stderr, "selection size %zu != %lld\n", sel.size(), (long long) width); return false; }
224            std::copy(sel.begin(), sel.end(), hids.begin() + (size_t) t * cap);
225            hst[t * 4 + 0] = (int32_t) p; hst[t * 4 + 1] = (int32_t) n_kv; hst[t * 4 + 2] = (int32_t) (n_kv / 4);
226            hst[t * 4 + 3] = (int32_t) width;
227        }
228        for (auto& x : hq) x = nd(rng);
229        /*
230        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
231        assuming in the original code the source host memory is pageable memory.
232        If the memory is not pageable, call wait() on event return by memcpy API
233        to ensure synchronization behavior.
234        */
235        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(ids, hids.data(),
236                                                              hids.size() * 4).wait()),
237           "ids");
238        /*
239        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
240        assuming in the original code the source host memory is pageable memory.
241        If the memory is not pageable, call wait() on event return by memcpy API
242        to ensure synchronization behavior.
243        */
244        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(steps, hst.data(),
245                                                              hst.size() * 4).wait()),
246           "steps");
247        /*
248        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
249        assuming in the original code the source host memory is pageable memory.
250        If the memory is not pageable, call wait() on event return by memcpy API
251        to ensure synchronization behavior.
252        */
253        ck(DPCT_CHECK_ERROR(
254               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(q, hq.data(), hq.size() * 4).wait()),
255           "q");
256        k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, n_q, nullptr);
257        k::kv_stream_resolve(m, slots.attn(m.page_table), host.p, fmt, ids, steps, n_q, cap, s, nullptr);
258        k::qsa_decode_attn_batch(q, slots.attn(m.page_table), ids, steps, cap, s, scratch, out_str, n_q, nullptr);
259        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
260           "batch");
261        ck(DPCT_CHECK_ERROR(
262               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
263                   .memcpy(a.data(), out_ref, (size_t)n_q * NH * D * 4)
264                   .wait()),
265           "a");
266        ck(DPCT_CHECK_ERROR(
267               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
268                   .memcpy(b2.data(), out_str, (size_t)n_q * NH * D * 4)
269                   .wait()),
270           "b");
271        if (std::memcmp(a.data(), b2.data(), (size_t) n_q * NH * D * 4) != 0) {
272            if (bad++ < 5) std::fprintf(stderr, "  %s pos %lld n_q %d: streamed attention differs\n", name, (long long) pos, n_q);
273        }
274        // the map inverts itself
275        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
276                                .memcpy(pt.data(), m.page_table, n_blocks * 4)
277                                .wait()),
278           "pt");
279        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
280                                .memcpy(sb.data(), m.slot_block, n_slots * 4)
281                                .wait()),
282           "sb");
283        int64_t resident = 0;
284        for (int64_t bk = 0; bk < n_blocks; ++bk) {
285            if (pt[bk] < -1 || pt[bk] >= n_slots || (pt[bk] >= 0 && sb[pt[bk]] != bk)) {
286                if (bad++ < 5) std::fprintf(stderr, "  map broken at block %lld (table %d)\n", (long long) bk, pt[bk]);
287                break;
288            }
289            resident += pt[bk] >= 0;
290        }
291        for (int64_t sl = 0; sl < n_slots; ++sl)
292            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; }
293        ++batches;
294    }
295    const k::KvStreamCounters c = k::kv_stream_counters(m);
296    std::printf("  %s: %d batches, %llu block lookups, %llu misses (%.1f%% hit), overflow %d, %d failures\n",
297                name, batches, (unsigned long long) c.lookups, (unsigned long long) c.misses,
298                c.lookups ? 100.0 * (double) (c.lookups - c.misses) / (double) c.lookups : 0.0, (int) c.overflow, bad);
299    if (c.overflow || c.calls != (uint64_t) batches || c.misses == 0 || c.misses >= c.lookups) ++bad;
300
301    // 4. a ring over the same host copy: blocks [b1 - R, b1) restored, read through `b % R`
302    {
303        const int64_t R = 1500, b1 = n_blocks, b0 = b1 - R;
304        Pools ring;
305        ring.alloc(R, s, fmt, false);
306        int32_t* rt = dalloc<int32_t>(n_blocks);
307        k::kv_ring_table(rt, n_blocks, R, nullptr);
308        k::kv_ring_restore(ring.attn(rt), host.p, fmt, b0, b1, R, s, nullptr);
309        const int64_t width = cap;
310        std::vector<int32_t> hids((size_t) cap), hst = {(int32_t) (N - 1), (int32_t) N, (int32_t) (N / 4), (int32_t) width};
311        for (int64_t i = 0; i < width; ++i) hids[i] = (int32_t) (N - width + i);   // the window's last cells
312        /*
313        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
314        assuming in the original code the source host memory is pageable memory.
315        If the memory is not pageable, call wait() on event return by memcpy API
316        to ensure synchronization behavior.
317        */
318        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(ids, hids.data(),
319                                                              hids.size() * 4).wait()),
320           "ids");
321        /*
322        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
323        assuming in the original code the source host memory is pageable memory.
324        If the memory is not pageable, call wait() on event return by memcpy API
325        to ensure synchronization behavior.
326        */
327        ck(DPCT_CHECK_ERROR(
328               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(steps, hst.data(), 16).wait()),
329           "steps");
330        k::qsa_decode_attn_batch(q, ref.attn(ident), ids, steps, cap, s, scratch, out_ref, 1, nullptr);
331        k::qsa_decode_attn_batch(q, ring.attn(rt), ids, steps, cap, s, scratch, out_str, 1, nullptr);
332        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
333           "ring");
334        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
335                                .memcpy(a.data(), out_ref, (size_t)NH * D * 4)
336                                .wait()),
337           "a");
338        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
339                                .memcpy(b2.data(), out_str, (size_t)NH * D * 4)
340                                .wait()),
341           "b");
342        const bool ok = std::memcmp(a.data(), b2.data(), (size_t) NH * D * 4) == 0;
343        std::printf("  %s ring restore: %s\n", name, ok ? "identical" : "DIFFERS");
344        if (!ok) ++bad;
345    }
346    return bad == 0;
347}
348}  // namespace
349
350int main() {
351    std::printf("kv_stream_parity: streamed vs resident KV, bitwise\n");
352    const bool a = run(k::kKvInt8), b = run(k::kKvF16), c = run(k::kKvQ4), d = run(k::kKvHybrid);
353    if (!a || !b || !c || !d) ++g_fail;
354    std::printf(g_fail ? "FAIL\n" : "PASS\n");
355    return g_fail ? 1 : 0;
356}