okami.mom/strata

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

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

main
11.7 KiB190 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#include "strata/kernels/f16_bits.hpp"
10#include "strata/kernels/kv_q8.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 <cstring>
19#include <random>
20#include <vector>
21
22namespace k = strata::kernels;
23
24namespace {
25int g_fail = 0;
26void ck(cudaError_t e, const char* w) {
27    if (e != cudaSuccess) { std::fprintf(stderr, "%s: %s\n", w, cudaGetErrorString(e)); std::exit(2); }
28}
29template <typename T> T* dalloc(size_t n) { T* p = nullptr; ck(cudaMalloc(&p, n * sizeof(T) + 64), "malloc"); ck(cudaMemset(p, 0, n * sizeof(T) + 64), "memset"); return p; }
30}  // namespace
31
32// A decode-shaped microbench: a 32k pool, the 2,051-cell selection the QSA decoder gathers per layer, random
33// cells (so the reads miss L2).  Reports the gather's effective traffic per call and GB/s.  Not part of the test.
34int bench() {
35    k::QsaShapes s = k::qsa_real_shapes();
36    const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
37    const int ctx = 32768, pages = ctx / P;
38    const long long rows = (long long) pages * H * P;
39    const int max_ids = (int) k::qsa_selection_width(ctx, s);
40    std::mt19937 rng(7);
41    std::vector<int8_t> kq((size_t) rows * D), vq((size_t) rows * D);
42    std::vector<uint16_t> ks((size_t) rows * G), vs((size_t) rows * G);
43    for (auto& x : kq) x = (int8_t) (rng() & 0xFF);
44    for (auto& x : vq) x = (int8_t) (rng() & 0xFF);
45    for (auto& x : ks) x = (uint16_t) (0x3000 | (rng() & 0x3FF));
46    for (auto& x : vs) x = (uint16_t) (0x3000 | (rng() & 0x3FF));
47    std::vector<int32_t> table(pages);
48    for (int i = 0; i < pages; ++i) table[i] = i;
49    std::shuffle(table.begin(), table.end(), rng);
50    std::vector<int32_t> ids(max_ids);
51    for (auto& x : ids) x = (int32_t) (rng() % ctx);
52    int8_t* d_kq = dalloc<int8_t>(kq.size()); ck(cudaMemcpy(d_kq, kq.data(), kq.size(), cudaMemcpyHostToDevice), "up");
53    int8_t* d_vq = dalloc<int8_t>(vq.size()); ck(cudaMemcpy(d_vq, vq.data(), vq.size(), cudaMemcpyHostToDevice), "up");
54    uint16_t* d_ks = dalloc<uint16_t>(ks.size()); ck(cudaMemcpy(d_ks, ks.data(), ks.size() * 2, cudaMemcpyHostToDevice), "up");
55    uint16_t* d_vs = dalloc<uint16_t>(vs.size()); ck(cudaMemcpy(d_vs, vs.data(), vs.size() * 2, cudaMemcpyHostToDevice), "up");
56    int32_t* d_table = dalloc<int32_t>(pages); ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "up");
57    int32_t* d_ids = dalloc<int32_t>(max_ids); ck(cudaMemcpy(d_ids, ids.data(), max_ids * 4, cudaMemcpyHostToDevice), "up");
58    int32_t* d_step = dalloc<int32_t>(k::kStepCount);
59    int32_t hstep[k::kStepCount] = {0, 0, 0, max_ids};
60    ck(cudaMemcpy(d_step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "up");
61    uint16_t* k8 = dalloc<uint16_t>((size_t) max_ids * H * D);
62    uint16_t* v8 = dalloc<uint16_t>((size_t) max_ids * H * D);
63    for (int i = 0; i < 5; ++i) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr);
64    ck(cudaDeviceSynchronize(), "warmup");
65    const int reps = 200;
66    cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1);
67    cudaEventRecord(e0);
68    for (int r = 0; r < reps; ++r) k::kv_gather_q8_step(d_kq, d_vq, d_ks, d_vs, d_table, d_ids, d_step, max_ids, s, k8, v8, nullptr);
69    cudaEventRecord(e1); ck(cudaEventSynchronize(e1), "time");
70    float ms = 0; cudaEventElapsedTime(&ms, e0, e1);
71    const double bytes = (double) max_ids * H * D * 2                       // K + V codes
72                       + (double) max_ids * H * G * 2 * 2                    // K + V scales
73                       + (double) max_ids * H * D * 2 * 2;                   // K + V fp16 scratch write
74    const double us = ms * 1000.0 / reps;
75    std::printf("kv_gather_q8 bench: %d ids, %.1f us/call, %.1f GB/s (%.2f MB moved)\n", max_ids, us,
76                bytes / (us * 1e-6) / 1e9, bytes / 1e6);
77    return 0;
78}
79
80int main(int argc, char** argv) {
81    for (int i = 1; i < argc; ++i) if (!std::strcmp(argv[i], "--bench")) return bench();
82    k::QsaShapes s = k::qsa_real_shapes();
83    s.page_size = 64;                                                              // several pages in a small pool
84    const int H = (int) s.n_head_kv, D = (int) s.head_dim, P = (int) s.page_size, G = D / k::KV_Q8_GROUP;
85    const int pages = 8, cells = pages * P;
86    std::mt19937 rng(17);
87    std::vector<int32_t> table(pages);
88    for (int i = 0; i < pages; ++i) table[i] = (i * 5 + 3) % pages;            // a non-identity permutation
89    int32_t* d_table = dalloc<int32_t>(pages);
90    ck(cudaMemcpy(d_table, table.data(), pages * 4, cudaMemcpyHostToDevice), "table");
91    int8_t *kq = dalloc<int8_t>((size_t) cells * H * D), *vq = dalloc<int8_t>((size_t) cells * H * D);
92    uint16_t *ks = dalloc<uint16_t>((size_t) cells * H * G), *vs = dalloc<uint16_t>((size_t) cells * H * G);
93    uint16_t *kp = dalloc<uint16_t>((size_t) cells * H * D), *vp = dalloc<uint16_t>((size_t) cells * H * D);
94    float *kcur = dalloc<float>(H * D), *vcur = dalloc<float>(H * D);
95    int32_t* step = dalloc<int32_t>(k::kStepCount);
96    std::vector<std::vector<float>> hk(cells), hv(cells);
97    std::normal_distribution<float> nd(0.f, 1.f);
98    std::vector<int> positions(cells);
99    for (int i = 0; i < cells; ++i) positions[i] = i;
100    std::shuffle(positions.begin(), positions.end(), rng);
101    const int n_fill = cells - 37;                                                  // leave some cells empty
102    for (int n = 0; n < n_fill; ++n) {
103        const int pos = positions[n];
104        std::vector<float> kv(H * D), vv(H * D);
105        const float scale = (n % 7 == 0) ? 1e-3f : (n % 11 == 0 ? 40.f : 1.f);    // small and large groups
106        for (auto& x : kv) x = nd(rng) * scale;
107        for (auto& x : vv) x = nd(rng) * scale;
108        if (n % 13 == 0) std::fill(kv.begin(), kv.begin() + 64, 0.f);              // an all-zero group
109        hk[pos] = kv; hv[pos] = vv;
110        int32_t hstep[k::kStepCount] = {pos, pos + 1, 0, 0};
111        ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step");
112        ck(cudaMemcpy(kcur, kv.data(), kv.size() * 4, cudaMemcpyHostToDevice), "k");
113        ck(cudaMemcpy(vcur, vv.data(), vv.size() * 4, cudaMemcpyHostToDevice), "v");
114        k::kv_append_q8_step(kq, vq, ks, vs, d_table, step, kcur, vcur, s, nullptr);
115        k::kv_append_step(kp, vp, d_table, step, kcur, vcur, s, nullptr);
116        ck(cudaDeviceSynchronize(), "append");
117    }
118    // 1. codes and scales bitwise vs the host reference
119    std::vector<int8_t> hkq((size_t) cells * H * D), hvq(hkq.size());
120    std::vector<uint16_t> hks((size_t) cells * H * G), hvs(hks.size());
121    ck(cudaMemcpy(hkq.data(), kq, hkq.size(), cudaMemcpyDeviceToHost), "d2h");
122    ck(cudaMemcpy(hvq.data(), vq, hvq.size(), cudaMemcpyDeviceToHost), "d2h");
123    ck(cudaMemcpy(hks.data(), ks, hks.size() * 2, cudaMemcpyDeviceToHost), "d2h");
124    ck(cudaMemcpy(hvs.data(), vs, hvs.size() * 2, cudaMemcpyDeviceToHost), "d2h");
125    long bad_codes = 0;
126    for (int n = 0; n < n_fill; ++n) {
127        const int pos = positions[n];
128        for (int kvsel = 0; kvsel < 2; ++kvsel)
129            for (int h = 0; h < H; ++h)
130                for (int g = 0; g < G; ++g) {
131                    const float* x = (kvsel ? hv[pos] : hk[pos]).data() + h * D + g * 64;
132                    float amax = 0.f;
133                    for (int t = 0; t < 64; ++t) amax = std::fmax(amax, std::fabs(x[t]));
134                    const uint16_t sb = k::f16_from_f32(amax / 127.0f);
135                    const float sf = k::f32_from_f16(sb);
136                    const long long row = ((long long) table[pos / P] * H + h) * P + pos % P;
137                    if ((kvsel ? hvs : hks)[row * G + g] != sb) ++bad_codes;
138                    for (int t = 0; t < 64; ++t) {
139                        int q = sf > 0.f ? (int) std::nearbyint(x[t] / sf) : 0;
140                        q = std::clamp(q, -127, 127);
141                        if ((kvsel ? hvq : hkq)[row * D + g * 64 + t] != (int8_t) q) ++bad_codes;
142                    }
143                }
144    }
145    if (bad_codes) { std::fprintf(stderr, "FAIL: %ld codes/scales differ from the host reference\n", bad_codes); ++g_fail; }
146    // 2 + 3. gather random selections from both paths
147    const int max_ids = 200;
148    int32_t* d_ids = dalloc<int32_t>(max_ids);
149    uint16_t *k8 = dalloc<uint16_t>((size_t) max_ids * H * D), *v8 = dalloc<uint16_t>((size_t) max_ids * H * D);
150    uint16_t *k16 = dalloc<uint16_t>((size_t) max_ids * H * D), *v16 = dalloc<uint16_t>((size_t) max_ids * H * D);
151    double worst = 0.0;
152    for (int trial = 0; trial < 20; ++trial) {
153        const int n_ids = 1 + (int) (rng() % max_ids);
154        std::vector<int32_t> ids(n_ids);
155        for (auto& id : ids) id = positions[rng() % n_fill];
156        ck(cudaMemcpy(d_ids, ids.data(), n_ids * 4, cudaMemcpyHostToDevice), "ids");
157        int32_t hstep[k::kStepCount] = {0, 0, 0, n_ids};
158        ck(cudaMemcpy(step, hstep, sizeof hstep, cudaMemcpyHostToDevice), "step");
159        k::kv_gather_q8_step(kq, vq, ks, vs, d_table, d_ids, step, max_ids, s, k8, v8, nullptr);
160        k::kv_gather_step(kp, vp, d_table, d_ids, step, max_ids, s, k16, v16, nullptr);
161        ck(cudaDeviceSynchronize(), "gather");
162        std::vector<uint16_t> a8((size_t) n_ids * H * D), b8(a8.size()), a16(a8.size()), b16(a8.size());
163        ck(cudaMemcpy(a8.data(), k8, a8.size() * 2, cudaMemcpyDeviceToHost), "d2h");
164        ck(cudaMemcpy(b8.data(), v8, b8.size() * 2, cudaMemcpyDeviceToHost), "d2h");
165        ck(cudaMemcpy(a16.data(), k16, a16.size() * 2, cudaMemcpyDeviceToHost), "d2h");
166        ck(cudaMemcpy(b16.data(), v16, b16.size() * 2, cudaMemcpyDeviceToHost), "d2h");
167        for (int j = 0; j < n_ids; ++j)
168            for (int h = 0; h < H; ++h) {
169                const long long row = ((long long) table[ids[j] / P] * H + h) * P + ids[j] % P;
170                for (int d = 0; d < D; ++d) {
171                    const size_t o = ((size_t) j * H + h) * D + d;
172                    for (int kvsel = 0; kvsel < 2; ++kvsel) {
173                        const float sf = k::f32_from_f16((kvsel ? hvs : hks)[row * G + d / 64]);
174                        const int8_t q = (kvsel ? hvq : hkq)[row * D + d];
175                        const uint16_t want = k::f16_from_f32((float) q * sf);
176                        const uint16_t got = (kvsel ? b8 : a8)[o];
177                        if (got != want) { if (g_fail < 5) std::fprintf(stderr, "FAIL: gather id %d h %d d %d\n", j, h, d); ++g_fail; }
178                        const float ref = k::f32_from_f16((kvsel ? b16 : a16)[o]);
179                        const double err = std::fabs(k::f32_from_f16(got) - ref) / (sf > 0 ? sf : 1.0);
180                        worst = std::max(worst, err);
181                    }
182                }
183            }
184    }
185    // |x - q*sf| <= sf/2 (the stored scale keeps |x|/sf <= 127.06, so no clamping), plus the fp16 rounding of each
186    // 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
187    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; }
188    std::printf("kv_q8_parity: %s (worst INT8-vs-FP16 error %.3f quantization steps)\n", g_fail ? "FAILED" : "OK", worst);
189    return g_fail ? 1 : 0;
190}