okami.mom/strata

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

Niko1221Merge f-145-havok (#2364 multi-user series, opt-in)df44bcb71

main
10.8 KiB225 linesraw
1// src/kernels/qsa_slots_parity.cpp - STRATA_QSA_SLOTS: a batch window's block scores, top-k and attention as one
2// launch over rows of different slots (qsa_block_scores_slots, qsa_block_topk over the rows, qsa_decode_attn_slots)
3// against one call per row, as verify.cpp makes them without the switch.  Every slot has its own indexer keys, page
4// table and K/V pools (fp16, int8, q4_0 and int8-K/q4_0-V) and its own context length; scores, selected ids and the
5// attention output must be bitwise identical.  Synthetic data, no model.  Run it once more with
6// STRATA_ATTN_LANECELL=1 for the lane-cell kernels.  Where a launcher declines by design (STRATA_SCORES_MULTI=0, the
7// pre-sm_75 attention, the gfx906 query swizzle) the engine keeps its per-row calls and the test skips (77).
8#include "strata/kernels/kv_q4.hpp"
9#include "strata/kernels/kv_q8.hpp"
10#include "strata/kernels/qsa.hpp"
11#include "strata/kernels/qsa_decode_attn.hpp"
12#include "strata/kernels/qsa_select.hpp"
13
14#include <cuda_runtime.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <numeric>
22#include <random>
23#include <vector>
24
25namespace k = strata::kernels;
26namespace {
27
28void ck(cudaError_t e) {
29    if (e != cudaSuccess) {
30        std::fprintf(stderr, "CUDA: %s\n", cudaGetErrorString(e));
31        std::exit(2);
32    }
33}
34template <typename T> T* up(const std::vector<T>& h) {
35    T* d = nullptr;
36    ck(cudaMalloc(&d, h.size() * sizeof(T)));
37    ck(cudaMemcpy(d, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice));
38    return d;
39}
40template <typename T> std::vector<T> down(const T* d, size_t n) {
41    std::vector<T> h(n);
42    ck(cudaMemcpy(h.data(), d, n * sizeof(T), cudaMemcpyDeviceToHost));
43    return h;
44}
45// a finite fp16 of magnitude 2^-5 .. 2^2
46uint16_t rnd_half(std::mt19937& r) {
47    const uint32_t x = r();
48    return (uint16_t) (((x & 1u) << 15) | ((10u + (x >> 1) % 7u) << 10) | ((x >> 4) & 0x3ffu));
49}
50
51constexpr int64_t kMaxCells = 32768;
52
53struct Slot {
54    float *pooled = nullptr, *dead = nullptr;
55    int32_t* page_table = nullptr;
56    void* bufs[6] = {};
57    k::QsaAttnPools pools;
58};
59
60Slot make_slot(int fmt, const k::QsaShapes& s, int64_t max_blocks, std::mt19937& r) {
61    Slot sl;
62    std::normal_distribution<float> nd(0.f, 1.f);
63    std::vector<float> pooled((size_t) (max_blocks * s.idx_dim)), dead((size_t) s.idx_dim);
64    for (auto& v : pooled) v = nd(r);
65    for (auto& v : dead) v = nd(r);
66    sl.pooled = up(pooled);
67    sl.dead = up(dead);
68    const int64_t pages = kMaxCells / s.page_size;
69    std::vector<int32_t> pt((size_t) pages);
70    std::iota(pt.begin(), pt.end(), 0);
71    std::shuffle(pt.begin(), pt.end(), r);
72    for (int i = 0; i < 3; ++i) pt[(size_t) (r() % pages)] = -1;   // a few non-resident pages (masked cells)
73    sl.page_table = up(pt);
74    sl.pools.page_table = sl.page_table;
75    const size_t rows = (size_t) (pages * s.n_head_kv * s.page_size), hd = (size_t) s.head_dim;
76    auto halves = [&](size_t n) { std::vector<uint16_t> h(n); for (auto& v : h) v = rnd_half(r); return h; };
77    auto codes = [&](size_t n) { std::vector<int8_t> h(n); for (auto& v : h) v = (int8_t) (r() & 0xff); return h; };
78    auto q4 = [&](size_t n_rows) {
79        std::vector<uint8_t> h(n_rows * (size_t) k::kv_q4_bytes_per_head((int) hd));
80        k::block_q4_0* b = reinterpret_cast<k::block_q4_0*>(h.data());
81        for (size_t i = 0; i < h.size() / sizeof(k::block_q4_0); ++i) {
82            b[i].d = rnd_half(r);
83            for (auto& q : b[i].qs) q = (uint8_t) (r() & 0xff);
84        }
85        return h;
86    };
87    if (fmt == 0) {
88        sl.pools.k_pool = (const uint16_t*) (sl.bufs[0] = up(halves(rows * hd)));
89        sl.pools.v_pool = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd)));
90    } else if (fmt == 1 || fmt == 3) {
91        sl.pools.k_q = (const int8_t*) (sl.bufs[0] = up(codes(rows * hd)));
92        sl.pools.k_scale = (const uint16_t*) (sl.bufs[1] = up(halves(rows * hd / k::KV_Q8_GROUP)));
93        if (fmt == 1) {
94            sl.pools.v_q = (const int8_t*) (sl.bufs[2] = up(codes(rows * hd)));
95            sl.pools.v_scale = (const uint16_t*) (sl.bufs[3] = up(halves(rows * hd / k::KV_Q8_GROUP)));
96        } else {
97            sl.pools.v_q4 = (const uint8_t*) (sl.bufs[2] = up(q4(rows)));
98        }
99    } else {
100        sl.pools.k_q4 = (const uint8_t*) (sl.bufs[0] = up(q4(rows)));
101        sl.pools.v_q4 = (const uint8_t*) (sl.bufs[1] = up(q4(rows)));
102    }
103    return sl;
104}
105
106void free_slot(Slot& sl) {
107    ck(cudaFree(sl.pooled)); ck(cudaFree(sl.dead)); ck(cudaFree(sl.page_table));
108    for (void* b : sl.bufs) if (b) ck(cudaFree(b));
109}
110
111enum Result { kPass, kFail, kSkip };
112
113// one case: `m` rows of different slots, KV format `fmt`, contexts `ctx[i]`
114Result check(int fmt, int m, const int64_t* ctx, uint32_t seed) {
115    const k::QsaShapes s = k::qsa_real_shapes();
116    const int64_t cap = k::qsa_selection_width(k::kTopkMaxCells, s);
117    const int64_t max_blocks = kMaxCells / s.idx_block + 2;
118    const int64_t NH = s.n_head, HD = s.head_dim, QI = s.idx_n_head * s.idx_dim;
119    const int64_t sf = (int64_t) k::qsa_decode_attn_scratch_floats(cap, s);
120    std::mt19937 r(seed);
121    std::normal_distribution<float> nd(0.f, 1.f);
122    std::vector<Slot> slots;
123    for (int i = 0; i < m; ++i) slots.push_back(make_slot(fmt, s, max_blocks, r));
124    std::vector<float> qidx((size_t) (m * QI)), qcur((size_t) (m * NH * HD));
125    for (auto& v : qidx) v = nd(r);
126    for (auto& v : qcur) v = nd(r);
127    std::vector<int32_t> steps((size_t) (m * k::kStepCount));
128    for (int i = 0; i < m; ++i) k::qsa_step_fill(steps.data() + i * k::kStepCount, ctx[i] - 1, s);
129    float* d_qidx = up(qidx);
130    float* d_qcur = up(qcur);
131    int32_t* d_steps = up(steps);
132    float *sc[2], *scratch[2], *attn[2];
133    int32_t* sel[2];
134    for (int v = 0; v < 2; ++v) {
135        ck(cudaMalloc(&sc[v], (size_t) (m * max_blocks) * 4));
136        ck(cudaMalloc(&sel[v], (size_t) (m * cap) * 4));
137        ck(cudaMalloc(&scratch[v], (size_t) (m * sf) * 4));
138        ck(cudaMalloc(&attn[v], (size_t) (m * NH * HD) * 4));
139        ck(cudaMemset(sc[v], 0, (size_t) (m * max_blocks) * 4));
140        ck(cudaMemset(sel[v], 0, (size_t) (m * cap) * 4));
141        ck(cudaMemset(attn[v], 0, (size_t) (m * NH * HD) * 4));
142    }
143    // 0: one call per row (verify.cpp's batch-window loop)
144    for (int t = 0; t < m; ++t) {
145        k::qsa_block_scores(slots[t].pooled, slots[t].dead, d_qidx + t * QI, d_steps + t * k::kStepCount, 1,
146                            max_blocks, s, sc[0] + t * max_blocks, nullptr);
147        k::qsa_block_topk(sc[0] + t * max_blocks, d_steps + t * k::kStepCount, 1, max_blocks, cap, s, sel[0] + t * cap,
148                          nullptr);
149        k::qsa_decode_attn_batch(d_qcur + t * NH * HD, slots[t].pools, sel[0] + t * cap, d_steps + t * k::kStepCount,
150                                 cap, s, scratch[0] + t * sf, attn[0] + t * NH * HD, 1, nullptr);
151    }
152    // 1: one launch per step over the rows
153    const float* pooled[k::kQsaAttnMaxSlots];
154    const float* dead[k::kQsaAttnMaxSlots];
155    k::QsaAttnSlotPools px;
156    for (int t = 0; t < m; ++t) { pooled[t] = slots[t].pooled; dead[t] = slots[t].dead; px.p[t] = slots[t].pools; }
157    // a declined launch is no failure: the engine runs the per-row calls there (STRATA_SCORES_MULTI=0, the pre-sm_75
158    // attention, the gfx906 query swizzle)
159    Result res = kPass;
160    if (!k::qsa_block_scores_slots(pooled, dead, d_qidx, d_steps, m, max_blocks, s, sc[1], nullptr)) {
161        std::puts("SKIP: qsa_block_scores_slots declined (STRATA_SCORES_MULTI=0); the engine keeps the per-row calls");
162        res = kSkip;
163    } else {
164        k::qsa_block_topk(sc[1], d_steps, m, max_blocks, cap, s, sel[1], nullptr);
165        if (!k::qsa_decode_attn_slots(d_qcur, px, sel[1], d_steps, cap, s, scratch[1], attn[1], m, nullptr)) {
166            std::puts("SKIP: qsa_decode_attn_slots declined (the pre-sm_75 or gfx906 query-swizzle attention); the "
167                      "engine keeps the per-row calls");
168            res = kSkip;
169        }
170    }
171    ck(cudaDeviceSynchronize());
172    bool ok = res == kPass;
173    const auto s0 = down(sc[0], (size_t) (m * max_blocks)), s1 = down(sc[1], (size_t) (m * max_blocks));
174    const auto i0 = down(sel[0], (size_t) (m * cap)), i1 = down(sel[1], (size_t) (m * cap));
175    const auto a0 = down(attn[0], (size_t) (m * NH * HD)), a1 = down(attn[1], (size_t) (m * NH * HD));
176    for (int t = 0; t < m && ok; ++t) {
177        const int64_t nb = steps[(size_t) (t * k::kStepCount + k::kStepNBid)] + 1;
178        const int64_t w = steps[(size_t) (t * k::kStepCount + k::kStepWidth)];
179        const char* what = nullptr;
180        if (std::memcmp(&s0[(size_t) (t * max_blocks)], &s1[(size_t) (t * max_blocks)], (size_t) nb * 4)) what = "scores";
181        else if (std::memcmp(&i0[(size_t) (t * cap)], &i1[(size_t) (t * cap)], (size_t) w * 4)) what = "ids";
182        else if (std::memcmp(&a0[(size_t) (t * NH * HD)], &a1[(size_t) (t * NH * HD)], (size_t) (NH * HD) * 4))
183            what = "attention";
184        if (what) {
185            std::fprintf(stderr, "FAIL fmt=%d rows=%d row=%d ctx=%lld: %s differ\n", fmt, m, t, (long long) ctx[t], what);
186            ok = false;
187        }
188    }
189    double mag = 0;   // the attention output is not trivially zero
190    for (float v : a0) mag += std::fabs(v);
191    if (ok && !(mag > 0)) { std::fprintf(stderr, "FAIL fmt=%d rows=%d: attention output is zero\n", fmt, m); ok = false; }
192    if (res == kPass && !ok) res = kFail;
193    for (int v = 0; v < 2; ++v) { ck(cudaFree(sc[v])); ck(cudaFree(sel[v])); ck(cudaFree(scratch[v])); ck(cudaFree(attn[v])); }
194    ck(cudaFree(d_qidx)); ck(cudaFree(d_qcur)); ck(cudaFree(d_steps));
195    for (auto& sl : slots) free_slot(sl);
196    return res;
197}
198
199}  // namespace
200
201int main() {
202    int devices = 0;
203    if (cudaGetDeviceCount(&devices) != cudaSuccess || devices == 0) {
204        std::puts("SKIP: no CUDA device");
205        return 77;
206    }
207    if (const char* v = std::getenv("STRATA_SCORES_MULTI"); v && std::atoi(v) == 0) {
208        std::puts("SKIP: STRATA_SCORES_MULTI=0 (the slots launch is off; the engine keeps the per-row calls)");
209        return 77;
210    }
211    // contexts per row: under and over the selection width (2048 cells), partial and complete indexer blocks
212    const int64_t ctx[8] = {1500, 37, 9000, 2049, 32768, 300, 20001, 4096};
213    int cases = 0, skipped = 0;   // the gfx906 query swizzle declines only the int8 K/V format
214    for (int fmt = 0; fmt < 4; ++fmt)
215        for (int m : {1, 2, 4, 8}) {
216            const Result res = check(fmt, m, ctx, 1000u * (uint32_t) fmt + (uint32_t) m);
217            if (res == kFail) return 1;
218            ++(res == kSkip ? skipped : cases);
219        }
220    if (cases == 0) return 77;
221    std::printf("PASS: %d cases (4 KV formats x 1/2/4/8 rows of different slots%s, %d declined): scores, ids and "
222                "attention bitwise identical to one call per row\n", cases,
223                std::getenv("STRATA_ATTN_LANECELL") ? ", lane-cell" : "", skipped);
224    return 0;
225}