okami.mom/strata

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

Niko1221Merge branch 'f-split-int' into f-split-fitfa6367a98

main
19.5 KiB369 linesraw
1// src/kernels/kv_hybrid_parity.cpp - hybrid K8V4 KV against host references (GPU, no model).
2//
3// Exercises the EXACT composed calls the engine's hybrid path makes (layer.cpp / prefill.cpp): the q8/q4
4// append and gather kernels invoked with the unused half's pointers folded onto the used pool, and the
5// fused decode attention's KV_MODE 3 (INT8 K, rotated Q4_0 V) followed by the output's inverse Hadamard.
6//   1. K: INT8 codes + FP16 scales bitwise vs the host reference (kv_q8.hpp's rules);
7//   2. V: after fwht256, Q4_0 blocks bitwise vs the host reference (kv_q4.hpp's rules, PR #21);
8//   3. the composed gathers bitwise vs the host dequantization of those codes;
9//   4. qsa_decode_attn<3> + output fwht vs a host attention over the SAME dequantized K/V (fp32 math), and
10//      bounded against the fp32-true attention from the unquantized K/V.
11#include "strata/kernels/f16_bits.hpp"
12#include "strata/kernels/kv_q4.hpp"
13#include "strata/kernels/kv_q8.hpp"
14#include "strata/kernels/qsa.hpp"
15#include "strata/kernels/qsa_decode_attn.hpp"
16#include "strata/kernels/qsa_prompt_attn.hpp"
17
18#include <cuda_runtime.h>
19
20#include <algorithm>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <vector>
27
28namespace k = strata::kernels;
29
30namespace {
31int g_fail = 0;
32void ck(cudaError_t e, const char* w) {
33    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
34}
35template <typename T> T* dalloc(size_t n) {
36    T* p = nullptr;
37    ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc");
38    ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset");
39    return p;
40}
41
42// kv_q4_parity.cpp's exact CPU references.
43void fwht256_host_reference(float* x) {
44    constexpr int n = 256;
45    for (int s = 1; s < n; s *= 2) {
46        for (int i = 0; i < n; i += 2 * s) {
47            for (int j = 0; j < s; ++j) {
48                const float u = x[i + j];
49                const float v = x[i + j + s];
50                x[i + j]     = u + v;
51                x[i + j + s] = u - v;
52            }
53        }
54    }
55    const float scale = 1.0f / 16.0f;
56    for (int i = 0; i < n; ++i) x[i] *= scale;
57}
58void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) {
59    float amax = 0.0f, max_val = 0.0f;
60    for (int i = 0; i < 32; ++i) {
61        const float v = x[i];
62        if (amax < std::fabs(v)) { amax = std::fabs(v); max_val = v; }
63    }
64    const float d = max_val / -8.0f;
65    const float id = d != 0.0f ? 1.0f / d : 0.0f;
66    blk.d = k::f16_from_f32(d);
67    for (int i = 0; i < 16; ++i) {
68        const int q0 = (int) (x[i] * id + 8.5f);
69        const int q1 = (int) (x[i + 16] * id + 8.5f);
70        const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0));
71        const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1));
72        blk.qs[i] = xi0 | (xi1 << 4);
73    }
74}
75}  // namespace
76
77int main() {
78    std::printf("=== Running kv_hybrid_parity test ===\n");
79    k::QsaShapes s = k::qsa_real_shapes();
80    s.page_size = 64;
81    const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
82    const int QH = (int) s.n_head, PER = QH / H;   // query heads per KV head
83    const int pages = 24, cells = pages * P;   // n_chunks >= n_head: the batched merge overlaps queries below that
84    std::mt19937 rng(17);
85    std::normal_distribution<float> nd(0.0f, 1.0f);
86
87    std::vector<int32_t> table(pages);
88    for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;
89    int32_t* d_table = dalloc<int32_t>(pages);
90    ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table");
91
92    std::vector<float> K((size_t) cells * H * D), V((size_t) cells * H * D);
93    for (auto& x : K) x = nd(rng) * 0.5f;
94    for (auto& x : V) x = nd(rng) * 0.5f;
95
96    // ---- host reference: K in INT8 (kv_q8.hpp), rotated V in Q4_0 (kv_q4.hpp)
97    std::vector<int8_t> rk((size_t) cells * H * D);
98    std::vector<uint16_t> rk_s((size_t) cells * H * G);
99    for (int c = 0; c < cells; ++c)
100        for (int h = 0; h < H; ++h)
101            for (int g = 0; g < G; ++g) {
102                float amax = 0.0f;
103                for (int t = 0; t < k::KV_Q8_GROUP; ++t)
104                    amax = std::max(amax, std::fabs(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t]));
105                const uint16_t sb = k::f16_from_f32(amax / 127.0f);
106                const float sf = k::f32_from_f16(sb);
107                for (int t = 0; t < k::KV_Q8_GROUP; ++t) {
108                    int q = 0;
109                    if (sf > 0.0f) {
110                        q = (int) std::nearbyint(K[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] / sf);   // rn: ties to even, as the kernel
111                        q = std::max(-127, std::min(127, q));
112                    }
113                    rk[((size_t) c * H + h) * D + g * k::KV_Q8_GROUP + t] = (int8_t) q;
114                }
115                rk_s[((size_t) c * H + h) * G + g] = sb;
116            }
117    std::vector<float> Vrot((size_t) cells * H * D);
118    std::memcpy(Vrot.data(), V.data(), V.size() * 4);
119    for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vrot.data() + (size_t) c * D);
120    std::vector<k::block_q4_0> rv4((size_t) cells * H * (D / 32));
121    for (int c = 0; c < cells; ++c)
122        for (int h = 0; h < H; ++h)
123            for (int b = 0; b < D / 32; ++b)
124                quantize_block_q4_0_host(&Vrot[((size_t) c * H + h) * D + b * 32],
125                                         rv4[((size_t) c * H + h) * (D / 32) + b]);
126
127    // ---- device: one cell appended through the COMPOSED hybrid calls, then gathered
128    const int64_t q4_row = (int64_t) k::kv_q4_bytes_per_head(D);
129    int8_t* d_kq = dalloc<int8_t>((size_t) cells * H * D);
130    uint16_t* d_ks = dalloc<uint16_t>((size_t) cells * H * G);
131    uint8_t* d_v4 = dalloc<uint8_t>((size_t) cells * H * q4_row);
132    float *d_kcur = dalloc<float>((size_t) H * D), *d_vcur = dalloc<float>((size_t) H * D);
133    int32_t* d_step = dalloc<int32_t>(k::kStepCount);
134
135    int append_bad = 0, gather_bad = 0;
136    for (int c = 0; c < cells; ++c) {
137        ck(cudaMemcpy(d_kcur, &K[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "kcur");
138        ck(cudaMemcpy(d_vcur, &V[(size_t) c * H * D], (size_t) H * D * 4, cudaMemcpyHostToDevice), "vcur");
139        int32_t step[k::kStepCount];
140        k::qsa_step_fill(step, c, s);
141        ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step");
142        // exactly what qsa_layer's hybrid branch does
143        k::fwht256_inplace_cuda(d_vcur, H, nullptr);
144        k::kv_append_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_step, d_kcur, d_kcur, s, nullptr, nullptr);
145        k::kv_append_q4_step(d_v4, d_v4, d_table, d_step, d_vcur, d_vcur, s, nullptr, nullptr);
146        ck(cudaGetLastError() != cudaSuccess ? cudaGetLastError() : cudaSuccess, "append");
147    }
148    ck(cudaDeviceSynchronize(), "append sync");
149
150    std::vector<int8_t> hk((size_t) cells * H * D);
151    std::vector<uint16_t> hks((size_t) cells * H * G);
152    std::vector<uint8_t> hv4((size_t) cells * H * q4_row);
153    ck(cudaMemcpy(hk.data(), d_kq, hk.size(), cudaMemcpyDeviceToHost), "kq");
154    ck(cudaMemcpy(hks.data(), d_ks, hks.size() * 2, cudaMemcpyDeviceToHost), "ks");
155    ck(cudaMemcpy(hv4.data(), d_v4, hv4.size(), cudaMemcpyDeviceToHost), "v4");
156    // the pools are PHYSICAL (page, head, slot); the reference is by LOGICAL cell - compare through the table
157    const k::block_q4_0* hv4b = reinterpret_cast<const k::block_q4_0*>(hv4.data());
158    for (int c = 0; c < cells; ++c) {
159        const long long row = ((long long) table[c / P] * H);
160        for (int h = 0; h < H; ++h) {
161            const long long r = (row + h) * P + c % P;
162            for (int d = 0; d < D; ++d)
163                if (hk[(size_t) r * D + d] != rk[((size_t) c * H + h) * D + d]) ++append_bad;
164            for (int g = 0; g < G; ++g)
165                if (hks[(size_t) r * G + g] != rk_s[((size_t) c * H + h) * G + g]) ++append_bad;
166            for (int b = 0; b < D / 32; ++b) {
167                const k::block_q4_0& got = hv4b[(size_t) r * (D / 32) + b];
168                if (got.d != rv4[((size_t) c * H + h) * (D / 32) + b].d ||
169                    std::memcmp(got.qs, rv4[((size_t) c * H + h) * (D / 32) + b].qs, 16) != 0) ++append_bad;
170            }
171        }
172    }
173    std::printf("[1/3] composed appends: %s (%d bad values of %zu K / %zu V)\n",
174                append_bad == 0 ? "PASS" : "FAIL", append_bad, hk.size(), rv4.size());
175
176    // gather every cell (ids = all, ascending - the identity selection for width = cells)
177    std::vector<int32_t> ids(cells);
178    for (int i = 0; i < cells; ++i) ids[i] = i;
179    int32_t* d_ids = dalloc<int32_t>(cells);
180    ck(cudaMemcpy(d_ids, ids.data(), cells * 4, cudaMemcpyHostToDevice), "ids");
181    int32_t step[k::kStepCount];
182    k::qsa_step_fill(step, cells - 1, s);
183    step[k::kStepWidth] = cells;   // select everything
184    ck(cudaMemcpy(d_step, step, sizeof step, cudaMemcpyHostToDevice), "step2");
185    uint16_t *d_ksc = dalloc<uint16_t>((size_t) cells * H * D), *d_vsc = dalloc<uint16_t>((size_t) cells * H * D);
186    k::kv_gather_q8_step(d_kq, d_kq, d_ks, d_ks, d_table, d_ids, d_step, cells, s, d_ksc, d_ksc, nullptr);
187    k::kv_gather_q4_step(d_v4, d_v4, d_table, d_ids, d_step, cells, s, d_vsc, d_vsc, nullptr);
188    ck(cudaDeviceSynchronize(), "gather sync");
189    std::vector<uint16_t> h_ksc((size_t) cells * H * D), h_vsc((size_t) cells * H * D);
190    ck(cudaMemcpy(h_ksc.data(), d_ksc, h_ksc.size() * 2, cudaMemcpyDeviceToHost), "ksc");
191    ck(cudaMemcpy(h_vsc.data(), d_vsc, h_vsc.size() * 2, cudaMemcpyDeviceToHost), "vsc");
192    for (int c = 0; c < cells; ++c)
193        for (int h = 0; h < H; ++h)
194            for (int d = 0; d < D; ++d) {
195                const float kref = k::f32_from_f16(k::f16_from_f32(
196                    (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP])));
197                if (k::f32_from_f16(h_ksc[((size_t) c * H + h) * D + d]) != kref) ++gather_bad;
198                const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32];
199                const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8);
200                const float vref = k::f32_from_f16(k::f16_from_f32((float) nib * k::f32_from_f16(b.d)));
201                if (k::f32_from_f16(h_vsc[((size_t) c * H + h) * D + d]) != vref) ++gather_bad;
202            }
203    std::printf("[2/3] composed gathers: %s (%d bad of %zu)\n",
204                gather_bad == 0 ? "PASS" : "FAIL", gather_bad, h_ksc.size());
205
206    // ---- attention: qsa_decode_attn KV_MODE 3 over the hybrid pools + output fwht, vs fp32 references
207    std::vector<float> q((size_t) QH * D);
208    for (auto& x : q) x = nd(rng);
209    float* d_q = dalloc<float>(q.size());
210    ck(cudaMemcpy(d_q, q.data(), q.size() * 4, cudaMemcpyHostToDevice), "q");
211    k::QsaAttnPools pools;
212    pools.k_q = d_kq; pools.k_scale = d_ks; pools.v_q4 = d_v4; pools.page_table = d_table;
213    float* d_scr = dalloc<float>(k::qsa_decode_attn_scratch_floats(cells, s) + 16);
214    float* d_attn = dalloc<float>((size_t) QH * D);
215    k::qsa_decode_attn_step(d_q, pools, d_ids, d_step, cells, s, d_scr, d_attn, nullptr);
216    k::fwht256_inplace_cuda(d_attn, QH, nullptr);   // the engine's inverse rotation of the output
217    ck(cudaDeviceSynchronize(), "attn sync");
218    std::vector<float> h_attn((size_t) QH * D);
219    ck(cudaMemcpy(h_attn.data(), d_attn, h_attn.size() * 4, cudaMemcpyDeviceToHost), "attn");
220
221    // reference A: attention over the SAME dequantized K/V (isolates the kernel; fp32 host math)
222    // reference B: attention over the TRUE unquantized K/V (bounds the format's error)
223    auto host_attn = [&](const std::vector<float>& Keq, const std::vector<float>& Veq, std::vector<float>& out) {
224        out.assign((size_t) QH * D, 0.0f);
225        for (int h = 0; h < QH; ++h) {
226            const int kvh = h / PER;
227            std::vector<float> sc(cells);
228            float m = -1e30f;
229            for (int c = 0; c < cells; ++c) {
230                float d_ = 0.0f;
231                for (int t = 0; t < D; ++t)
232                    d_ += q[(size_t) h * D + t] * Keq[((size_t) c * H + kvh) * D + t];
233                sc[c] = d_ / std::sqrt((float) D);
234                m = std::max(m, sc[c]);
235            }
236            float l = 0.0f;
237            for (int c = 0; c < cells; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; }
238            for (int c = 0; c < cells; ++c)
239                for (int t = 0; t < D; ++t) out[(size_t) h * D + t] += sc[c] / l * Veq[((size_t) c * H + kvh) * D + t];
240        }
241    };
242    std::vector<float> Kdq((size_t) cells * H * D), Vdq((size_t) cells * H * D);
243    for (int c = 0; c < cells; ++c)
244        for (int h = 0; h < H; ++h)
245            for (int d = 0; d < D; ++d) {
246                Kdq[((size_t) c * H + h) * D + d] =
247                    (float) rk[((size_t) c * H + h) * D + d] * k::f32_from_f16(rk_s[((size_t) c * H + h) * G + d / k::KV_Q8_GROUP]);
248                const k::block_q4_0& b = rv4[((size_t) c * H + h) * (D / 32) + d / 32];
249                const int nib = d % 32 < 16 ? (b.qs[d % 32] & 0x0F) - 8 : ((b.qs[d % 32 - 16] >> 4) - 8);
250                Vdq[((size_t) c * H + h) * D + d] = (float) nib * k::f32_from_f16(b.d);
251            }
252    // un-rotate the dequantized V (the kernel returns the output in the UNROTATED domain)
253    std::vector<float> Vdq_un(Vdq.size());
254    std::memcpy(Vdq_un.data(), Vdq.data(), Vdq.size() * 4);
255    for (int c = 0; c < cells * H; ++c) fwht256_host_reference(Vdq_un.data() + (size_t) c * D);
256
257    // ---- batched form with TWO queries and per-query step arrays (the verify.cpp window's exact call)
258    {
259        const int nq = 2;
260        std::vector<float> q2((size_t) nq * QH * D);
261        for (auto& x : q2) x = nd(rng);
262        float* d_q2 = dalloc<float>(q2.size());
263        ck(cudaMemcpy(d_q2, q2.data(), q2.size() * 4, cudaMemcpyHostToDevice), "q2");
264        // the batched kernel indexes ids[z * cap + ...]: one FULL selection per query
265        std::vector<int32_t> ids2((size_t) nq * cells);
266        for (int i = 0; i < nq; ++i) for (int c = 0; c < cells; ++c) ids2[(size_t) i * cells + c] = c;
267        int32_t* d_ids2 = dalloc<int32_t>((size_t) nq * cells);
268        ck(cudaMemcpy(d_ids2, ids2.data(), ids2.size() * 4, cudaMemcpyHostToDevice), "ids2");
269        int32_t* d_steps2 = dalloc<int32_t>(nq * k::kStepCount);
270        for (int i = 0; i < nq; ++i) {
271            int32_t st2[k::kStepCount];
272            k::qsa_step_fill(st2, cells - 1 - i, s);
273            st2[k::kStepWidth] = cells - i;   // slightly different widths, as verify's windows have
274            ck(cudaMemcpy(d_steps2 + i * k::kStepCount, st2, sizeof st2, cudaMemcpyHostToDevice), "steps2");
275        }
276        float* d_scr2 = dalloc<float>(k::qsa_decode_attn_scratch_floats(cells, s) * nq + 64);
277        float* d_at2 = dalloc<float>((size_t) nq * QH * D);
278        k::qsa_decode_attn_batch(d_q2, pools, d_ids2, d_steps2, cells, s, d_scr2, d_at2, nq, nullptr);
279        k::fwht256_inplace_cuda(d_at2, (int64_t) nq * QH, nullptr);
280        ck(cudaDeviceSynchronize(), "attn2 sync");
281        std::vector<float> h_at2((size_t) nq * QH * D);
282        ck(cudaMemcpy(h_at2.data(), d_at2, h_at2.size() * 4, cudaMemcpyDeviceToHost), "at2");
283        double max_b = 0.0;
284        double per_q[2] = {0.0, 0.0};
285        for (int i = 0; i < nq; ++i)
286            for (int h = 0; h < QH; ++h) {
287                // reference over the cells this query's width selects (ids are ascending: the first width)
288                const int w = cells - i;
289                std::vector<float> sc(w);
290                float m = -1e30f;
291                for (int c = 0; c < w; ++c) {
292                    float d_ = 0.0f;
293                    for (int t = 0; t < D; ++t)
294                        d_ += q2[((size_t) i * QH + h) * D + t] * Kdq[((size_t) c * H + h / PER) * D + t];
295                    sc[c] = d_ / std::sqrt((float) D);
296                    m = std::max(m, sc[c]);
297                }
298                float l = 0.0f;
299                for (int c = 0; c < w; ++c) { sc[c] = std::exp(sc[c] - m); l += sc[c]; }
300                for (int d = 0; d < D; ++d) {
301                    float acc = 0.0f;
302                    for (int c = 0; c < w; ++c)
303                        acc += sc[c] / l * Vdq_un[((size_t) c * H + h / PER) * D + d];   // dim d only
304                    const double e = (double) std::fabs(h_at2[((size_t) i * QH + h) * D + d] - acc);
305                    max_b = std::max(max_b, e);
306                    per_q[i] = std::max(per_q[i], e);
307                }
308            }
309        const bool bok = max_b < 5e-3;
310        std::printf("       (per-query max: q0 %.2e, q1 %.2e)\n", per_q[0], per_q[1]);
311        std::printf("[4/4] mode-3 BATCHED attention (verify's form): %s (vs dequant ref %.2e)\n",
312                    bok ? "PASS" : "FAIL", max_b);
313        if (!bok) g_fail = 1;
314    }
315
316    std::vector<float> ref_deq, ref_true;
317    host_attn(Kdq, Vdq_un, ref_deq);
318    host_attn(K, V, ref_true);
319    double max_deq = 0.0, max_true = 0.0;
320    for (size_t i = 0; i < h_attn.size(); ++i) {
321        max_deq = std::max(max_deq, (double) std::fabs(h_attn[i] - ref_deq[i]));
322        max_true = std::max(max_true, (double) std::fabs(h_attn[i] - ref_true[i]));
323    }
324    // The tensor-core prompt path (qsa_prompt_attn, 0.1.22+) takes hybrid pools as KV_MODE 3: INT8 K, and V
325    // dequantized from its q4_0 blocks to fp16 at gather. Its summation order differs from the old kernel's
326    // (accuracy-level, not bitwise - qsa_prompt_attn.hpp says the same of its int8 mode), so: tolerance check
327    // against the SAME dequant reference, output un-rotated exactly as prefill.cpp does.
328    {
329        float* d_at4 = dalloc<float>((size_t) QH * D);
330        const bool took = k::qsa_prompt_attn_batch(d_q, pools, d_ids, d_step, cells, s, d_at4, 1, nullptr);
331        if (!took) {
332#if defined(STRATA_USE_HIP) || defined(STRATA_HIP_GFX906)
333            // AMD: the tensor-core prompt path is CUDA-only, so it refuses every pool and the old kernel runs
334            std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused on HIP - the old kernel runs)\n");
335#else
336            // a card below compute capability 7.0 (Pascal) never had the tensor-core prompt kernels: the old kernel runs
337            int dev5 = 0, major5 = 0;
338            cudaGetDevice(&dev5);
339            cudaDeviceGetAttribute(&major5, cudaDevAttrComputeCapabilityMajor, dev5);
340            if (major5 > 0 && major5 < 7) {
341                std::printf("[5/5] qsa_prompt_attn mode 3: PASS (refused below sm_70 - the old kernel runs)\n");
342            } else {
343                std::printf("[5/5] qsa_prompt_attn mode 3: FAIL (refused the hybrid pools)\n");
344                g_fail = 1;
345            }
346#endif
347        } else {
348            k::fwht256_inplace_cuda(d_at4, QH, nullptr);
349            ck(cudaDeviceSynchronize(), "at4 sync");
350            std::vector<float> h_at4((size_t) QH * D);
351            ck(cudaMemcpy(h_at4.data(), d_at4, h_at4.size() * 4, cudaMemcpyDeviceToHost), "at4");
352            double max_p = 0.0;
353            for (size_t i = 0; i < h_at4.size(); ++i)
354                max_p = std::max(max_p, (double) std::fabs(h_at4[i] - ref_deq[i]));
355            const bool pok = max_p < 1e-2;
356            std::printf("[5/5] qsa_prompt_attn mode 3 (tensor cores): %s (vs dequant ref %.2e)\n",
357                        pok ? "PASS" : "FAIL", max_p);
358            if (!pok) g_fail = 1;
359        }
360    }
361
362    const bool attn_ok = max_deq < 5e-3;   // fp32 kernel math vs fp64-ish host accumulation
363    std::printf("[3/3] mode-3 attention + output fwht: %s (vs dequant ref %.2e, vs true fp32 %.2e)\n",
364                attn_ok ? "PASS" : "FAIL", max_deq, max_true);
365
366    const bool ok = append_bad == 0 && gather_bad == 0 && attn_ok && g_fail == 0;
367    std::printf("=== kv_hybrid_parity: %s ===\n", ok ? "ALL PASS" : "FAILED");
368    return ok ? 0 : 1;
369}