okami.mom/strata

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

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

main
12.5 KiB230 linesraw
1// src/kernels/kv_q8_parity.cpp - plan v0.3 P7: INT8 KV append/gather against a host reference (GPU, no model).
2//
3// Appends random K/V cells at scattered positions through a non-identity page table into both the INT8 pools
4// (kv_append_q8_step) and the FP16 pools (kv_append_step), gathers random cell sets from both, and checks:
5//   1. INT8 codes and FP16 scales are BITWISE equal to the host reference (same f16_from_f32 rounding);
6//   2. the INT8 gather is BITWISE equal to the host dequantization of those codes;
7//   3. against the FP16 path, the INT8 values differ by at most half a quantization step of their group plus the
8//      fp16 rounding of both sides (0.624 steps).
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_q8.hpp"
14#include "strata/kernels/qsa.hpp"
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstring>
20#include <random>
21#include <vector>
22
23namespace k = strata::kernels;
24
25namespace {
26int g_fail = 0;
27void ck(dpct::err0 e, const char *w) {
28    /*
29    DPCT1009: SYCL reports errors using exceptions and does not use error
30    codes. Please replace the "get_error_string_dummy(...)" with a real
31    error-handling function.
32    */
33}
34template <typename T>
35T *dalloc(size_t n) {
36    T *p = nullptr;
37    ck(DPCT_CHECK_ERROR(p = (T *)sycl::malloc_device(
38                            n * sizeof(T) + 64, dpct::get_in_order_queue())),
39       "malloc");
40    ck(DPCT_CHECK_ERROR(
41           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memset(p, 0, n * sizeof(T) + 64).wait()),
42       "memset");
43    return p;
44}
45}  // namespace
46
47int main() {
48    k::QsaShapes s = k::qsa_real_shapes();
49    s.page_size = 64;                                                              // several pages in a small pool
50    const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
51    const int pages = 8, cells = pages * P;
52    std::mt19937 rng(17);
53    std::vector<int32_t> table(pages);
54    for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;            // a non-identity permutation
55    int32_t* d_table = dalloc<int32_t>(pages);
56    /*
57    DPCT1114: cudaMemcpy is migrated to asynchronization memcpy, assuming in
58    the original code the source host memory is pageable memory. If the memory
59    is not pageable, call wait() on event return by memcpy API to ensure
60    synchronization behavior.
61    */
62    ck(DPCT_CHECK_ERROR(
63           (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_table, table.data(), pages * 4).wait()),
64       "table");
65    int8_t *kq = dalloc<int8_t>((size_t) cells * H * D), *vq = dalloc<int8_t>((size_t) cells * H * D);
66    uint16_t *ks = dalloc<uint16_t>((size_t) cells * H * G), *vs = dalloc<uint16_t>((size_t) cells * H * G);
67    uint16_t *kp = dalloc<uint16_t>((size_t) cells * H * D), *vp = dalloc<uint16_t>((size_t) cells * H * D);
68    float *kcur = dalloc<float>(H * D), *vcur = dalloc<float>(H * D);
69    int32_t* step = dalloc<int32_t>(k::kStepCount);
70    std::vector<std::vector<float>> hk(cells), hv(cells);
71    std::normal_distribution<float> nd(0.f, 1.f);
72    std::vector<int> positions(cells);
73    for (int i = 0; i < cells; ++i) positions[i] = i;
74    std::shuffle(positions.begin(), positions.end(), rng);
75    const int n_fill = cells - 37;                                                  // leave some cells empty
76    for (int n = 0; n < n_fill; ++n) {
77        const int pos = positions[n];
78        std::vector<float> kv(H * D), vv(H * D);
79        const float scale = (n % 7 == 0) ? 1e-3f : (n % 11 == 0 ? 40.f : 1.f);    // small and large groups
80        for (auto& x : kv) x = nd(rng) * scale;
81        for (auto& x : vv) x = nd(rng) * scale;
82        if (n % 13 == 0) std::fill(kv.begin(), kv.begin() + 64, 0.f);              // an all-zero group
83        hk[pos] = kv; hv[pos] = vv;
84        int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0};
85        /*
86        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
87        assuming in the original code the source host memory is pageable memory.
88        If the memory is not pageable, call wait() on event return by memcpy API
89        to ensure synchronization behavior.
90        */
91        ck(DPCT_CHECK_ERROR(
92               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(step, hstep, sizeof hstep).wait()),
93           "step");
94        /*
95        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
96        assuming in the original code the source host memory is pageable memory.
97        If the memory is not pageable, call wait() on event return by memcpy API
98        to ensure synchronization behavior.
99        */
100        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(kcur, kv.data(),
101                                                              kv.size() * 4).wait()),
102           "k");
103        /*
104        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
105        assuming in the original code the source host memory is pageable memory.
106        If the memory is not pageable, call wait() on event return by memcpy API
107        to ensure synchronization behavior.
108        */
109        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(vcur, vv.data(),
110                                                              vv.size() * 4).wait()),
111           "v");
112        k::kv_append_q8_step(kq, vq, ks, vs, d_table, step, kcur, vcur, s, nullptr);
113        k::kv_append_step(kp, vp, d_table, step, kcur, vcur, s, nullptr);
114        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
115           "append");
116    }
117    // 1. codes and scales bitwise vs the host reference
118    std::vector<int8_t> hkq((size_t) cells * H * D), hvq(hkq.size());
119    std::vector<uint16_t> hks((size_t) cells * H * G), hvs(hks.size());
120    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
121                            .memcpy(hkq.data(), kq, hkq.size())
122                            .wait()),
123       "d2h");
124    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
125                            .memcpy(hvq.data(), vq, hvq.size())
126                            .wait()),
127       "d2h");
128    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
129                            .memcpy(hks.data(), ks, hks.size() * 2)
130                            .wait()),
131       "d2h");
132    ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
133                            .memcpy(hvs.data(), vs, hvs.size() * 2)
134                            .wait()),
135       "d2h");
136    long bad_codes = 0;
137    for (int n = 0; n < n_fill; ++n) {
138        const int pos = positions[n];
139        for (int kvsel = 0; kvsel < 2; ++kvsel)
140            for (int h = 0; h < H; ++h)
141                for (int g = 0; g < G; ++g) {
142                    const float* x = (kvsel ? hv[pos] : hk[pos]).data() + h * D + g * 64;
143                    float amax = 0.f;
144                    for (int t = 0; t < 64; ++t) amax = std::fmax(amax, std::fabs(x[t]));
145                    const uint16_t sb = k::f16_from_f32(amax / 127.0f);
146                    const float sf = k::f32_from_f16(sb);
147                    const long long row = ((long long) table[pos / P] * H + h) * P + pos % P;
148                    if ((kvsel ? hvs : hks)[row * G + g] != sb) ++bad_codes;
149                    for (int t = 0; t < 64; ++t) {
150                        int q = sf > 0.f ? (int) std::nearbyint(x[t] / sf) : 0;
151                        q = std::clamp(q, -127, 127);
152                        if ((kvsel ? hvq : hkq)[row * D + g * 64 + t] != (int8_t) q) ++bad_codes;
153                    }
154                }
155    }
156    if (bad_codes) { std::fprintf(stderr, "FAIL: %ld codes/scales differ from the host reference\n", bad_codes); ++g_fail; }
157    // 2 + 3. gather random selections from both paths
158    const int max_ids = 200;
159    int32_t* d_ids = dalloc<int32_t>(max_ids);
160    uint16_t *k8 = dalloc<uint16_t>((size_t) max_ids * H * D), *v8 = dalloc<uint16_t>((size_t) max_ids * H * D);
161    uint16_t *k16 = dalloc<uint16_t>((size_t) max_ids * H * D), *v16 = dalloc<uint16_t>((size_t) max_ids * H * D);
162    double worst = 0.0;
163    for (int trial = 0; trial < 20; ++trial) {
164        const int n_ids = 1 + (int) (rng() % max_ids);
165        std::vector<int32_t> ids(n_ids);
166        for (auto& id : ids) id = positions[rng() % n_fill];
167        /*
168        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
169        assuming in the original code the source host memory is pageable memory.
170        If the memory is not pageable, call wait() on event return by memcpy API
171        to ensure synchronization behavior.
172        */
173        ck(DPCT_CHECK_ERROR(
174               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(d_ids, ids.data(), n_ids * 4).wait()),
175           "ids");
176        int32_t hstep[k::kStepCount] = {0, 0, 0, n_ids};
177        /*
178        DPCT1114: cudaMemcpy is migrated to asynchronization memcpy,
179        assuming in the original code the source host memory is pageable memory.
180        If the memory is not pageable, call wait() on event return by memcpy API
181        to ensure synchronization behavior.
182        */
183        ck(DPCT_CHECK_ERROR(
184               (dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue()).memcpy(step, hstep, sizeof hstep).wait()),
185           "step");
186        k::kv_gather_q8_step(kq, vq, ks, vs, d_table, d_ids, step, max_ids, s, k8, v8, nullptr);
187        k::kv_gather_step(kp, vp, d_table, d_ids, step, max_ids, s, k16, v16, nullptr);
188        ck(DPCT_CHECK_ERROR(dpct::get_current_device().queues_wait_and_throw()),
189           "gather");
190        std::vector<uint16_t> a8((size_t) n_ids * H * D), b8(a8.size()), a16(a8.size()), b16(a8.size());
191        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
192                                .memcpy(a8.data(), k8, a8.size() * 2)
193                                .wait()),
194           "d2h");
195        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
196                                .memcpy(b8.data(), v8, b8.size() * 2)
197                                .wait()),
198           "d2h");
199        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
200                                .memcpy(a16.data(), k16, a16.size() * 2)
201                                .wait()),
202           "d2h");
203        ck(DPCT_CHECK_ERROR((dpct::get_current_device().queues_wait_and_throw(), dpct::get_in_order_queue())
204                                .memcpy(b16.data(), v16, b16.size() * 2)
205                                .wait()),
206           "d2h");
207        for (int j = 0; j < n_ids; ++j)
208            for (int h = 0; h < H; ++h) {
209                const long long row = ((long long) table[ids[j] / P] * H + h) * P + ids[j] % P;
210                for (int d = 0; d < D; ++d) {
211                    const size_t o = ((size_t) j * H + h) * D + d;
212                    for (int kvsel = 0; kvsel < 2; ++kvsel) {
213                        const float sf = k::f32_from_f16((kvsel ? hvs : hks)[row * G + d / 64]);
214                        const int8_t q = (kvsel ? hvq : hkq)[row * D + d];
215                        const uint16_t want = k::f16_from_f32((float) q * sf);
216                        const uint16_t got = (kvsel ? b8 : a8)[o];
217                        if (got != want) { if (g_fail < 5) std::fprintf(stderr, "FAIL: gather id %d h %d d %d\n", j, h, d); ++g_fail; }
218                        const float ref = k::f32_from_f16((kvsel ? b16 : a16)[o]);
219                        const double err = std::fabs(k::f32_from_f16(got) - ref) / (sf > 0 ? sf : 1.0);
220                        worst = std::max(worst, err);
221                    }
222                }
223            }
224    }
225    // |x - q*sf| <= sf/2 (the stored scale keeps |x|/sf <= 127.06, so no clamping), plus the fp16 rounding of each
226    // side: at most 2^-11 relative of a value up to 127*sf, i.e. 127/2048 = 0.062 steps each -> 0.5 + 0.124
227    if (!(worst <= 0.5 + 2.0 * 127.0 / 2048.0 + 1e-3)) { std::fprintf(stderr, "FAIL: INT8 vs FP16 error %.3f steps\n", worst); ++g_fail; }
228    std::printf("kv_q8_parity: %s (worst INT8-vs-FP16 error %.3f quantization steps)\n", g_fail ? "FAILED" : "OK", worst);
229    return g_fail ? 1 : 0;
230}