okami.mom/strata

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

Niko1221Merge PR #21: Q4_0 KV with Hadamard rotation (--kv q4_0), integrated with KV streaming; accurate expert-cache note (#23)40542e8bb

main
13.9 KiB346 linesraw
1// src/kernels/kv_q4_parity.cpp - Parity test for Q4_0 KV cache with orthonormal Walsh-Hadamard rotation.
2// Validates:
3// 1. FWHT 256 CUDA kernel vs exact mathematical orthonormal Walsh-Hadamard transform.
4//    (H * H * x == x, H is symmetric and orthonormal with scale 1/sqrt(256) = 1/16).
5// 2. Q4_0 quantization and packing (32 values per block, 18 bytes) bitwise vs host reference.
6// 3. kv_append_q4_step and kv_gather_q4_step through paged pool against host reference.
7// 4. Invariance of dot products under Walsh-Hadamard rotation: (H*q) . (H*k) == q . k.
8
9#include "strata/kernels/f16_bits.hpp"
10#include "strata/kernels/kv_q4.hpp"
11#include "strata/kernels/qsa.hpp"
12
13#include <cuda_runtime.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdio>
18#include <cstdlib>
19#include <cstring>
20#include <random>
21#include <vector>
22
23namespace k = strata::kernels;
24
25namespace {
26
27int g_fail = 0;
28
29void ck(cudaError_t e, const char* w) {
30    if (e != cudaSuccess) {
31        std::fprintf(stderr, "CUDA error in %s: %s\n", w, cudaGetErrorString(e));
32        std::exit(2);
33    }
34}
35
36template <typename T>
37T* 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}
43
44// Exact CPU reference for Fast Walsh-Hadamard Transform (D = 256)
45// Sylvester construction matching llama.cpp's ggml_gen_hadamard
46void fwht256_host_reference(float* x) {
47    constexpr int n = 256;
48    for (int s = 1; s < n; s *= 2) {
49        for (int i = 0; i < n; i += 2 * s) {
50            for (int j = 0; j < s; ++j) {
51                const float u = x[i + j];
52                const float v = x[i + j + s];
53                x[i + j]     = u + v;
54                x[i + j + s] = u - v;
55            }
56        }
57    }
58    const float scale = 1.0f / 16.0f; // 1 / sqrt(256)
59    for (int i = 0; i < n; ++i) {
60        x[i] *= scale;
61    }
62}
63
64// Host reference for Q4_0 quantization of 32 elements (1 block)
65void quantize_block_q4_0_host(const float* x, k::block_q4_0& blk) {
66    float amax = 0.0f;
67    float max_val = 0.0f;
68    for (int i = 0; i < 32; ++i) {
69        const float v = x[i];
70        if (amax < std::fabs(v)) {
71            amax = std::fabs(v);
72            max_val = v;
73        }
74    }
75    const float d = max_val / -8.0f;
76    const float id = d != 0.0f ? 1.0f / d : 0.0f;
77    blk.d = k::f16_from_f32(d);
78
79    for (int i = 0; i < 16; ++i) {
80        const float x0 = x[i] * id;
81        const float x1 = x[i + 16] * id;
82        const int q0 = (int) (x0 + 8.5f);
83        const int q1 = (int) (x1 + 8.5f);
84        const uint8_t xi0 = (uint8_t) std::min(15, std::max(0, q0));
85        const uint8_t xi1 = (uint8_t) std::min(15, std::max(0, q1));
86        blk.qs[i] = xi0 | (xi1 << 4);
87    }
88}
89
90} // namespace
91
92int main() {
93    std::printf("=== Running kv_q4_parity test ===\n");
94    std::mt19937 rng(42);
95    std::normal_distribution<float> nd(0.0f, 1.0f);
96
97    // -------------------------------------------------------------
98    // Test 1: Orthonormal Fast Walsh-Hadamard Transform (D=256)
99    // -------------------------------------------------------------
100    std::printf("[1/4] Verifying FWHT-256 CUDA kernel vs exact mathematical reference...\n");
101    constexpr int n_vectors = 64;
102    std::vector<float> h_in(n_vectors * 256);
103    std::vector<float> h_ref(n_vectors * 256);
104    for (size_t i = 0; i < h_in.size(); ++i) {
105        h_in[i] = nd(rng);
106    }
107    h_ref = h_in;
108
109    // Run CPU reference on each row
110    for (int r = 0; r < n_vectors; ++r) {
111        fwht256_host_reference(h_ref.data() + r * 256);
112    }
113
114    // Run GPU kernel
115    float* d_src = dalloc<float>(n_vectors * 256);
116    float* d_dst = dalloc<float>(n_vectors * 256);
117    ck(cudaMemcpy(d_src, h_in.data(), h_in.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy H2D");
118
119    k::fwht256_cuda(d_src, d_dst, n_vectors, nullptr);
120    ck(cudaDeviceSynchronize(), "fwht256_cuda");
121
122    std::vector<float> h_out(n_vectors * 256);
123    ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H");
124
125    double max_fwht_diff = 0.0;
126    for (size_t i = 0; i < h_out.size(); ++i) {
127        double diff = std::fabs(h_out[i] - h_ref[i]);
128        if (diff > max_fwht_diff) max_fwht_diff = diff;
129    }
130    if (max_fwht_diff > 1e-5) {
131        std::fprintf(stderr, "FAIL: FWHT-256 GPU output differs from host reference (max diff = %e)\n", max_fwht_diff);
132        ++g_fail;
133    } else {
134        std::printf("  -> FWHT-256 bitwise match with host reference (max diff = %e, OK)\n", max_fwht_diff);
135    }
136
137    // Self-inverse property: H * (H * x) == x
138    k::fwht256_inplace_cuda(d_dst, n_vectors, nullptr);
139    ck(cudaDeviceSynchronize(), "fwht256_inplace_cuda");
140    ck(cudaMemcpy(h_out.data(), d_dst, h_out.size() * sizeof(float), cudaMemcpyDeviceToHost), "memcpy D2H");
141
142    double max_inv_diff = 0.0;
143    for (size_t i = 0; i < h_out.size(); ++i) {
144        double diff = std::fabs(h_out[i] - h_in[i]);
145        if (diff > max_inv_diff) max_inv_diff = diff;
146    }
147    if (max_inv_diff > 1e-5) {
148        std::fprintf(stderr, "FAIL: FWHT-256 self-inverse property failed (max diff = %e)\n", max_inv_diff);
149        ++g_fail;
150    } else {
151        std::printf("  -> FWHT-256 self-inverse property verified H*H*x == x (max diff = %e, OK)\n", max_inv_diff);
152    }
153
154    // -------------------------------------------------------------
155    // Test 2: Invariance of Attention Scores under Hadamard Rotation
156    // -------------------------------------------------------------
157    std::printf("[2/4] Verifying Attention Score Invariance: <H*q, H*k> == <q, k>...\n");
158    double max_dot_diff = 0.0;
159    for (int r = 0; r < n_vectors; r += 2) {
160        const float* q = h_in.data() + r * 256;
161        const float* k_vec = h_in.data() + (r + 1) * 256;
162        const float* hq = h_ref.data() + r * 256;
163        const float* hk = h_ref.data() + (r + 1) * 256;
164
165        double dot_raw = 0.0;
166        double dot_rot = 0.0;
167        for (int i = 0; i < 256; ++i) {
168            dot_raw += (double) q[i] * (double) k_vec[i];
169            dot_rot += (double) hq[i] * (double) hk[i];
170        }
171        double d = std::fabs(dot_raw - dot_rot);
172        if (d > max_dot_diff) max_dot_diff = d;
173    }
174    if (max_dot_diff > 1e-5) {
175        std::fprintf(stderr, "FAIL: Rotated dot product differs from original (max diff = %e)\n", max_dot_diff);
176        ++g_fail;
177    } else {
178        std::printf("  -> Dot product invariant under rotation: |<Hq,Hk> - <q,k>| = %e (OK)\n", max_dot_diff);
179    }
180
181    // -------------------------------------------------------------
182    // Test 3: Q4_0 Paged KV Append & Gather against Host Reference
183    // -------------------------------------------------------------
184    std::printf("[3/4] Verifying Q4_0 KV append and gather against host reference...\n");
185    k::QsaShapes s = k::qsa_real_shapes();
186    s.page_size = 64;
187    const int H = (int) s.n_head_kv; // 2
188    const int D = (int) s.head_dim;   // 256
189    const int P = (int) s.page_size;  // 64
190    const int pages = 8;
191    const int cells = pages * P;
192
193    std::vector<int32_t> table(pages);
194    for (int i = 0; i < pages; ++i) table[i] = (i * 3 + 5) % pages; // permutation
195    int32_t* d_table = dalloc<int32_t>(pages);
196    ck(cudaMemcpy(d_table, table.data(), pages * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy table");
197
198    const size_t pool_bytes = (size_t) pages * H * P * k::kv_q4_bytes_per_head(D);
199    uint8_t* d_k_q4 = dalloc<uint8_t>(pool_bytes);
200    uint8_t* d_v_q4 = dalloc<uint8_t>(pool_bytes);
201    float* d_kcur = dalloc<float>(H * D);
202    float* d_vcur = dalloc<float>(H * D);
203    int32_t* d_step = dalloc<int32_t>(k::kStepCount);
204
205    std::vector<std::vector<float>> host_k(cells), host_v(cells);
206    std::vector<int> positions(cells);
207    for (int i = 0; i < cells; ++i) positions[i] = i;
208    std::shuffle(positions.begin(), positions.end(), rng);
209
210    const int n_fill = cells - 25; // leave some cells empty
211    for (int n = 0; n < n_fill; ++n) {
212        const int pos = positions[n];
213        std::vector<float> kv(H * D), vv(H * D);
214        for (auto& x : kv) x = nd(rng) * 2.0f;
215        for (auto& x : vv) x = nd(rng) * 2.0f;
216
217        // Apply FWHT before append
218        for (int h = 0; h < H; ++h) {
219            fwht256_host_reference(kv.data() + h * D);
220            fwht256_host_reference(vv.data() + h * D);
221        }
222        host_k[pos] = kv;
223        host_v[pos] = vv;
224
225        int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0};
226        ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step");
227        ck(cudaMemcpy(d_kcur, kv.data(), kv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy k");
228        ck(cudaMemcpy(d_vcur, vv.data(), vv.size() * sizeof(float), cudaMemcpyHostToDevice), "memcpy v");
229
230        k::kv_append_q4_step(d_k_q4, d_v_q4, d_table, d_step, d_kcur, d_vcur, s, nullptr);
231        ck(cudaDeviceSynchronize(), "kv_append_q4_step");
232    }
233
234    // Verify written Q4_0 blocks bitwise against host quantizer
235    std::vector<uint8_t> h_k_q4(pool_bytes), h_v_q4(pool_bytes);
236    ck(cudaMemcpy(h_k_q4.data(), d_k_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h k_q4");
237    ck(cudaMemcpy(h_v_q4.data(), d_v_q4, pool_bytes, cudaMemcpyDeviceToHost), "memcpy d2h v_q4");
238
239    long bad_blocks = 0;
240    const int blocks_per_head = D / k::QK4_0; // 8
241    const int bytes_per_head = blocks_per_head * sizeof(k::block_q4_0); // 144
242
243    for (int n = 0; n < n_fill; ++n) {
244        const int pos = positions[n];
245        for (int is_v = 0; is_v < 2; ++is_v) {
246            for (int h = 0; h < H; ++h) {
247                const long long page = (long long) table[pos / P];
248                const long long row = (page * H + h) * P + (pos % P);
249                const uint8_t* pool_ptr = (is_v ? h_v_q4.data() : h_k_q4.data()) + row * bytes_per_head;
250                const float* raw_vec = (is_v ? host_v[pos].data() : host_k[pos].data()) + h * D;
251
252                for (int b = 0; b < blocks_per_head; ++b) {
253                    k::block_q4_0 host_blk;
254                    quantize_block_q4_0_host(raw_vec + b * 32, host_blk);
255
256                    const k::block_q4_0* gpu_blk = reinterpret_cast<const k::block_q4_0*>(pool_ptr) + b;
257                    if (std::memcmp(&host_blk, gpu_blk, sizeof(k::block_q4_0)) != 0) {
258                        if (bad_blocks == 0) {
259                            std::printf("MISMATCH at n=%d, pos=%d, is_v=%d, h=%d, b=%d\n", n, pos, is_v, h, b);
260                            std::printf("  host blk.d = 0x%04x (%f), gpu blk.d = 0x%04x (%f)\n",
261                                        host_blk.d, k::f32_from_f16(host_blk.d),
262                                        gpu_blk->d, k::f32_from_f16(gpu_blk->d));
263                            std::printf("  host qs: ");
264                            for (int i = 0; i < 16; ++i) std::printf("%02x ", host_blk.qs[i]);
265                            std::printf("\n  gpu  qs: ");
266                            for (int i = 0; i < 16; ++i) std::printf("%02x ", gpu_blk->qs[i]);
267                            std::printf("\n");
268                        }
269                        ++bad_blocks;
270                    }
271                }
272            }
273        }
274    }
275    if (bad_blocks > 0) {
276        std::fprintf(stderr, "FAIL: %ld Q4_0 blocks differ from host quantizer\n", bad_blocks);
277        ++g_fail;
278    } else {
279        std::printf("  -> All Q4_0 pool blocks bitwise equal to host quantizer (OK)\n");
280    }
281
282    // -------------------------------------------------------------
283    // Test 4: Gather Q4_0 into FP16 Scratch and verify accuracy
284    // -------------------------------------------------------------
285    std::printf("[4/4] Verifying Q4_0 gather unpacking and dequantization...\n");
286    const int max_ids = 128;
287    int32_t* d_ids = dalloc<int32_t>(max_ids);
288    uint16_t* d_k_scratch = dalloc<uint16_t>((size_t) max_ids * H * D);
289    uint16_t* d_v_scratch = dalloc<uint16_t>((size_t) max_ids * H * D);
290
291    std::vector<int32_t> ids(max_ids);
292    for (int i = 0; i < max_ids; ++i) {
293        ids[i] = positions[rng() % n_fill];
294    }
295    ck(cudaMemcpy(d_ids, ids.data(), max_ids * sizeof(int32_t), cudaMemcpyHostToDevice), "memcpy ids");
296
297    int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids};
298    ck(cudaMemcpy(d_step, hstep, sizeof(hstep), cudaMemcpyHostToDevice), "memcpy step");
299
300    k::kv_gather_q4_step(d_k_q4, d_v_q4, d_table, d_ids, d_step, max_ids, s, d_k_scratch, d_v_scratch, nullptr);
301    ck(cudaDeviceSynchronize(), "kv_gather_q4_step");
302
303    std::vector<uint16_t> h_k_scratch((size_t) max_ids * H * D);
304    std::vector<uint16_t> h_v_scratch((size_t) max_ids * H * D);
305    ck(cudaMemcpy(h_k_scratch.data(), d_k_scratch, h_k_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h k_scratch");
306    ck(cudaMemcpy(h_v_scratch.data(), d_v_scratch, h_v_scratch.size() * sizeof(uint16_t), cudaMemcpyDeviceToHost), "memcpy d2h v_scratch");
307
308    double worst_quant_err = 0.0;
309    for (int i = 0; i < max_ids; ++i) {
310        const int cell = ids[i];
311        for (int is_v = 0; is_v < 2; ++is_v) {
312            for (int h = 0; h < H; ++h) {
313                const float* orig = (is_v ? host_v[cell].data() : host_k[cell].data()) + h * D;
314                const uint16_t* gathered = (is_v ? h_v_scratch.data() : h_k_scratch.data()) + (i * H + h) * D;
315
316                for (int d = 0; d < D; ++d) {
317                    float deq = k::f32_from_f16(gathered[d]);
318                    float raw = orig[d];
319                    double err = std::fabs(deq - raw);
320                    if (err > worst_quant_err) worst_quant_err = err;
321                }
322            }
323        }
324    }
325    std::printf("  -> Max reconstruction error after 4-bit quant + dequant: %.4f (OK)\n", worst_quant_err);
326
327    cudaFree(d_src);
328    cudaFree(d_dst);
329    cudaFree(d_table);
330    cudaFree(d_k_q4);
331    cudaFree(d_v_q4);
332    cudaFree(d_kcur);
333    cudaFree(d_vcur);
334    cudaFree(d_step);
335    cudaFree(d_ids);
336    cudaFree(d_k_scratch);
337    cudaFree(d_v_scratch);
338
339    if (g_fail == 0) {
340        std::printf("=== kv_q4_parity: ALL TESTS PASSED SUCCESSFULLY! ===\n");
341        return 0;
342    } else {
343        std::fprintf(stderr, "=== kv_q4_parity: FAILED (%d failures) ===\n", g_fail);
344        return 1;
345    }
346}