okami.mom/strata

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

Niko1221Merge branch 'f-139b-arc' into f-139-relad33b8074

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