okami.mom/strata

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

Guillaume PUTIERs_gemv: the q8 split kernel reaches its barrier before a rowless warp returns91e8d2122

main
17.3 KiB343 linesraw
1// src/kernels/s_gemv_q8k_parity.cpp - the Q8_K activation path of `s_gemv`.
2//
3// THE POINT OF THIS KERNEL IS A CONTRACT, so the test is built around the contract rather than around the
4// arithmetic:
5//
6//   1. the kernel against a host reference that dequantizes the SAME Q8_K bytes and the SAME S-form planes,
7//      in double - so what is under test is the indexing, not the format;
8//   2. the Q8_K activation is produced by the ACTUAL `quantize_q8_K`, which is byte-exact against ggml
9//      (round 198).  Building the activation by hand here would make this a test of two transcriptions;
10//   3. **THE Q8_K-vs-FP16 GAP IS MEASURED**, because that is the number the whole activation-contract
11//      decision rests on and it has only ever been measured on Q2_0 weights (0.6175%) and on BF16 ones
12//      (0.141-0.156%).  A K-quant weight is a third case and it is the one the dense projections use.
13#include "strata/kernels/f16_bits.hpp"
14#include "strata/kernels/quantize_act.hpp"
15#include "strata/kernels/s_gemv.hpp"
16
17#include <cuda_runtime.h>
18
19#include <cmath>
20#include <cstdio>
21#include <cstdlib>
22#include <cstring>
23#include <random>
24#include <vector>
25
26namespace {
27
28using strata::kernels::SForm;
29using strata::kernels::Codebook;
30
31void check(cudaError_t e, const char* what) {
32    if (e != cudaSuccess) {
33        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
34        std::exit(1);
35    }
36}
37
38/// The host decode, transcribed from `docs/pack-format.md`'s rule: `value = cb[code] * scale + offset`, with
39/// the integer bias applied INSIDE the integer domain before the one multiply.
40const signed char kIq4Nl[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
41
42double weight_at(const std::vector<uint8_t>& codes, const std::vector<float>& scales,
43                 const std::vector<float>& offset, const SForm& f, long long n_in, long long o, long long i) {
44    const int per_byte = 8 / f.code_bits;
45    const long long codes_per_row = n_in / per_byte;
46    const long long n_groups = n_in / f.group_elems;
47    const uint8_t* c = codes.data() + o * codes_per_row;
48    const int code = (c[i / per_byte] >> ((int) (i % per_byte) * f.code_bits)) & ((1 << f.code_bits) - 1);
49    const double v = (f.codebook == Codebook::Iq4Nl) ? (double) kIq4Nl[code & 0x0F]
50                                                     : (double) (code + f.code_bias);
51    const long long g = i / f.group_elems;
52    double w = v * (double) scales[(size_t) (o * n_groups + g)];
53    if (f.has_offset) w += (double) offset[(size_t) (o * n_groups + g)];
54    return w;
55}
56
57/// Dequantize a block_q8_K buffer on the host: 292 bytes per 256 elements.
58double q8k_at(const std::vector<uint8_t>& x, long long i) {
59    const uint8_t* blk = x.data() + (size_t) (i / 256) * 292;
60    float d;
61    std::memcpy(&d, blk, 4);
62    const int8_t q = ((const int8_t*) (blk + 4))[i % 256];
63    return (double) d * (double) q;
64}
65
66struct Case {
67    const char* what;
68    int bits;
69    int bias;
70    int group;
71    Codebook cb;
72    bool has_offset;
73};
74
75/// THE RAGGED LAST BLOCK.  The split kernels give each warp one row and a block eight warps, so with
76/// `n_out % 8 != 0` the last block holds warps that have no row.  Those warps used to return BEFORE the
77/// codebook barrier - undefined behaviour that every real shape (a multiple of 8) avoided.  Here `n_out` is
78/// deliberately ragged, every row is checked against the host reference over the same bytes, and a guard
79/// band past `n_out` must come back untouched: a warp without a row must neither hang the block nor write.
80/// (`compute-sanitizer --tool synccheck` on this binary is the direct check of the barrier itself.)
81int ragged_rows(const Case& cs, long long n_out) {
82    const long long n_in = 512;
83    const long long guard = 64;
84    std::mt19937 rng(77 + (unsigned) n_out);
85    std::normal_distribution<float> g(0.0f, 1.0f);
86    std::vector<float> xf((size_t) n_in);
87    for (auto& v : xf) v = g(rng);
88    SForm f;
89    f.code_bits = cs.bits;
90    f.code_bias = cs.bias;
91    f.group_elems = cs.group;
92    f.codebook = cs.cb;
93    f.has_offset = cs.has_offset;
94    const int per_byte = 8 / cs.bits;
95    std::vector<uint8_t> codes((size_t) (n_out * n_in / per_byte));
96    for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);
97    const long long n_groups = n_in / cs.group;
98    std::vector<float> scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups));
99    for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20);
100    for (auto& v : offs) v = 0.2f * g(rng);
101
102    float* d_xf = nullptr;
103    uint8_t *d_xk = nullptr, *d_x0 = nullptr, *d_codes = nullptr;
104    float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr;
105    std::vector<uint8_t> xk((size_t) (n_in / 256) * 292), x0((size_t) (n_in / 32) * 34);
106    check(cudaMalloc(&d_xf, (size_t) n_in * 4), "rxf");
107    check(cudaMalloc(&d_xk, xk.size()), "rxk");
108    check(cudaMalloc(&d_x0, x0.size()), "rx0");
109    check(cudaMalloc(&d_codes, codes.size()), "rcodes");
110    check(cudaMalloc(&d_scales, scales.size() * 4), "rscales");
111    check(cudaMalloc(&d_offs, offs.size() * 4), "roffs");
112    check(cudaMalloc(&d_y, (size_t) (n_out + guard) * 4), "ry");
113    check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "rcxf");
114    check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "rcc");
115    check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "rcs");
116    check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "rco");
117    strata::kernels::quantize_q8_K(d_xf, d_xk, n_in, nullptr);
118    strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr);
119    check(cudaMemcpy(xk.data(), d_xk, xk.size(), cudaMemcpyDeviceToHost), "rcxk");
120    check(cudaMemcpy(x0.data(), d_x0, x0.size(), cudaMemcpyDeviceToHost), "rcx0");
121
122    int bad = 0;
123    for (int kind = 0; kind < 2; ++kind) {           // 0: Q8_K activation, 1: Q8_0 activation
124        std::vector<float> want((size_t) n_out);
125        std::vector<double> mag((size_t) n_out);   // sum |w_i a_i| per row: a row whose sum cancels near 0
126        for (long long o = 0; o < n_out; ++o) {    // must not turn f32 rounding into a relative failure
127            double acc = 0, am = 0;
128            for (long long i = 0; i < n_in; ++i) {
129                double a;
130                if (kind == 0) {
131                    a = q8k_at(xk, i);
132                } else {
133                    const uint8_t* blk = x0.data() + (size_t) (i / 32) * 34;
134                    uint16_t dbits;
135                    std::memcpy(&dbits, blk, 2);
136                    a = (double) strata::kernels::f32_from_f16(dbits) * (double) ((const int8_t*) (blk + 2))[i % 32];
137                }
138                const double wa = weight_at(codes, scales, offs, f, n_in, o, i) * a;
139                acc += wa;
140                am += std::fabs(wa);
141            }
142            want[(size_t) o] = (float) acc;
143            mag[(size_t) o] = am;
144        }
145        // the guard band holds a NaN pattern; any write there shows up as a changed bit
146        std::vector<uint32_t> sentinel((size_t) (n_out + guard), 0x7FC0DEADu);
147        check(cudaMemcpy(d_y, sentinel.data(), sentinel.size() * 4, cudaMemcpyHostToDevice), "rsent");
148        if (kind == 0)
149            strata::kernels::s_gemv_q8k_split(d_xk, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,
150                                              n_out, f, nullptr);
151        else
152            strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,
153                                               n_out, f, nullptr);
154        check(cudaDeviceSynchronize(), "ragged split");
155        std::vector<uint32_t> got_bits(sentinel.size());
156        check(cudaMemcpy(got_bits.data(), d_y, got_bits.size() * 4, cudaMemcpyDeviceToHost), "rcy");
157        double m = 0, d = 0;
158        for (long long o = 0; o < n_out; ++o) {
159            float v;
160            std::memcpy(&v, &got_bits[(size_t) o], 4);
161            m += mag[(size_t) o];
162            d += std::fabs((double) want[(size_t) o] - (double) v);
163        }
164        long long touched = 0;
165        for (long long o = n_out; o < n_out + guard; ++o) touched += got_bits[(size_t) o] != 0x7FC0DEADu;
166        const double rel = d / (m > 1e-30 ? m : 1e-30);
167        const bool ok = rel <= 1e-5 && touched == 0;
168        std::printf("  %-28s %s n_out %3lld: rel %.3e, guard words written %lld  %s\n", cs.what,
169                    kind == 0 ? "Q8_K" : "Q8_0", n_out, rel, touched, ok ? "ok" : "*** WRONG ***");
170        if (!ok) ++bad;
171    }
172    cudaFree(d_xf); cudaFree(d_xk); cudaFree(d_x0); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs);
173    cudaFree(d_y);
174    return bad;
175}
176
177}  // namespace
178
179int main(int argc, char** argv) {
180    bool selftest = false;
181    for (int i = 1; i < argc; ++i) {
182        if (std::string(argv[i]) == "--selftest") selftest = true;
183        else { std::fprintf(stderr, "usage: s_gemv_q8k_parity [--selftest]\n"); return 2; }
184    }
185    int bad = 0;
186
187    // The forms the DENSE weights actually use, taken from the manifest rather than invented:
188    //   attn_qkv.weight   IQ4_XS  S4  group 32, no offset   (the GDN mixer's qkv)
189    //   attn_gate.weight  Q4_K    S4  group 32, offset      (the GDN mixer's z)
190    //   ssm_out.weight    Q5_K    S8  group 32, offset      (the GDN mixer's output)
191    const Case cases[] = {
192        {"IQ4_XS  S4 g32 no-offset", 4, -8, 32, Codebook::Affine, false},
193        {"Q4_K    S4 g32 offset", 4, 0, 32, Codebook::Affine, true},
194        {"Q5_K    S8 g32 offset", 8, 0, 32, Codebook::Affine, true},
195    };
196
197    for (const Case& cs : cases) {
198        const long long n_in = 512, n_out = 64;   // 2 Q8_K blocks wide, small enough for a host reference
199        std::mt19937 rng(2024);
200        std::normal_distribution<float> g(0.0f, 1.0f);
201        std::vector<float> xf((size_t) n_in);
202        for (auto& v : xf) v = g(rng);
203
204        SForm f;
205        f.code_bits = cs.bits;
206        f.code_bias = cs.bias;
207        f.group_elems = cs.group;
208        f.codebook = cs.cb;
209        f.has_offset = cs.has_offset;
210
211        const int per_byte = 8 / cs.bits;
212        std::vector<uint8_t> codes((size_t) (n_out * n_in / per_byte));
213        for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);
214        const long long n_groups = n_in / cs.group;
215        std::vector<float> scales((size_t) (n_out * n_groups)), offs((size_t) (n_out * n_groups));
216        for (auto& v : scales) v = 0.01f + 0.001f * (float) (rng() % 20);
217        for (auto& v : offs) v = 0.2f * g(rng);
218
219        // ---- the activation, from the REAL quantizer
220        std::vector<uint8_t> xq8k((size_t) (n_in / 256) * 292);
221        float* d_xf = nullptr;
222        uint8_t* d_xq = nullptr;
223        check(cudaMalloc(&d_xf, (size_t) n_in * 4), "xf");
224        check(cudaMalloc(&d_xq, xq8k.size()), "xq");
225        check(cudaMemcpy(d_xf, xf.data(), (size_t) n_in * 4, cudaMemcpyHostToDevice), "cxf");
226        strata::kernels::quantize_q8_K(d_xf, d_xq, n_in, nullptr);
227        check(cudaMemcpy(xq8k.data(), d_xq, xq8k.size(), cudaMemcpyDeviceToHost), "cxq");
228
229        // ---- host reference in double, over the same bytes
230        std::vector<float> want((size_t) n_out, 0.0f);
231        for (long long o = 0; o < n_out; ++o) {
232            double acc = 0;
233            for (long long i = 0; i < n_in; ++i)
234                acc += weight_at(codes, scales, offs, f, n_in, o, i) * q8k_at(xq8k, i);
235            want[(size_t) o] = (float) acc;
236        }
237
238        // ---- device
239        uint8_t* d_codes = nullptr;
240        float *d_scales = nullptr, *d_offs = nullptr, *d_y = nullptr;
241        check(cudaMalloc(&d_codes, codes.size()), "codes");
242        check(cudaMalloc(&d_scales, scales.size() * 4), "scales");
243        check(cudaMalloc(&d_offs, offs.size() * 4), "offs");
244        check(cudaMalloc(&d_y, (size_t) n_out * 4), "y");
245        check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "cc");
246        check(cudaMemcpy(d_scales, scales.data(), scales.size() * 4, cudaMemcpyHostToDevice), "cs");
247        check(cudaMemcpy(d_offs, offs.data(), offs.size() * 4, cudaMemcpyHostToDevice), "co");
248
249        std::vector<float> naive((size_t) n_out), warp((size_t) n_out);
250        strata::kernels::s_gemv_q8k(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out,
251                                    f, nullptr);
252        check(cudaMemcpy(naive.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy1");
253        strata::kernels::s_gemv_q8k_split(d_xq, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in,
254                                          n_out, f, nullptr);
255        check(cudaMemcpy(warp.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy2");
256
257        double mag = 0, d1 = 0, d2 = 0;
258        for (long long o = 0; o < n_out; ++o) {
259            mag += std::fabs((double) want[(size_t) o]);
260            d1 += std::fabs((double) want[(size_t) o] - (double) naive[(size_t) o]);
261            d2 += std::fabs((double) want[(size_t) o] - (double) warp[(size_t) o]);
262        }
263        std::printf("  %-28s naive %.3e   warp %.3e\n", cs.what, d1 / mag, d2 / mag);
264        // The kernel accumulates in f32, the reference in f64, over 512 terms with values of similar size.
265        // 1e-5 is the arithmetic's floor, not a structural allowance.
266        if (!(d1 / mag <= 1e-5 && d2 / mag <= 1e-5)) { std::printf("    *** over 1e-5 ***\n"); ++bad; }
267
268        // ---- 2b. THE Q8_0 ACTIVATION, on the SAME weight planes.  `s_gemv_q8_0_split` exists because the
269        // legacy block formats want Q8_0 and `ffn_down_shexp` cannot use Q8_K at all (n_in = 640 is not a
270        // multiple of 256).  It shares every line with the Q8_K kernel except the activation loader, so what
271        // this checks is the LOADER - the 34-byte block, the fp16 `d`, and the element index inside it.
272        {
273            std::vector<uint8_t> xq0((size_t) (n_in / 32) * 34);
274            uint8_t* d_x0 = nullptr;
275            check(cudaMalloc(&d_x0, xq0.size()), "x0");
276            strata::kernels::quantize_q8_0(d_xf, d_x0, n_in, nullptr);
277            check(cudaMemcpy(xq0.data(), d_x0, xq0.size(), cudaMemcpyDeviceToHost), "cx0");
278
279            // the host reference over the SAME Q8_0 bytes, with the same weight decode
280            std::vector<float> want0((size_t) n_out, 0.0f);
281            for (long long o = 0; o < n_out; ++o) {
282                double acc = 0;
283                for (long long i = 0; i < n_in; ++i) {
284                    const uint8_t* blk = xq0.data() + (size_t) (i / 32) * 34;
285                    uint16_t dbits;
286                    std::memcpy(&dbits, blk, 2);
287                    const double d = (double) strata::kernels::f32_from_f16(dbits);
288                    const int8_t q = ((const int8_t*) (blk + 2))[i % 32];
289                    acc += weight_at(codes, scales, offs, f, n_in, o, i) * d * (double) q;
290                }
291                want0[(size_t) o] = (float) acc;
292            }
293            strata::kernels::s_gemv_q8_0_split(d_x0, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y,
294                                               n_in, n_out, f, nullptr);
295            std::vector<float> got0((size_t) n_out);
296            check(cudaMemcpy(got0.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy0");
297            double m0 = 0, dd0 = 0;
298            for (long long o = 0; o < n_out; ++o) {
299                m0 += std::fabs((double) want0[(size_t) o]);
300                dd0 += std::fabs((double) want0[(size_t) o] - (double) got0[(size_t) o]);
301            }
302            std::printf("  %-28s Q8_0 act %.3e\n", cs.what, dd0 / (m0 > 1e-30 ? m0 : 1e-30));
303            if (!(dd0 / (m0 > 1e-30 ? m0 : 1e-30) <= 1e-5)) {
304                std::printf("    *** the Q8_0 activation loader is WRONG ***\n");
305                ++bad;
306            }
307            check(cudaFree(d_x0), "fx0");
308        }
309
310        // ---- 3. THE Q8_K vs FP16 GAP, on a K-quant weight - the case the contract decision needs
311        {
312            std::vector<uint16_t> x16((size_t) n_in);
313            for (long long i = 0; i < n_in; ++i) x16[(size_t) i] = strata::kernels::f16_from_f32(xf[(size_t) i]);
314            uint16_t* d_x16 = nullptr;
315            check(cudaMalloc(&d_x16, (size_t) n_in * 2), "x16");
316            check(cudaMemcpy(d_x16, x16.data(), (size_t) n_in * 2, cudaMemcpyHostToDevice), "cx16");
317            std::vector<float> fp16out((size_t) n_out);
318            strata::kernels::s_gemv(d_x16, d_codes, d_scales, cs.has_offset ? d_offs : nullptr, d_y, n_in, n_out,
319                                    f);
320            check(cudaMemcpy(fp16out.data(), d_y, (size_t) n_out * 4, cudaMemcpyDeviceToHost), "cy3");
321            double dd = 0;
322            for (long long o = 0; o < n_out; ++o)
323                dd += std::fabs((double) naive[(size_t) o] - (double) fp16out[(size_t) o]);
324            const double rel = dd / mag;
325            const bool visible = rel > 1e-3;
326            std::printf("      %-24s %s (%.4f%% apart, tolerance 0.1%%)\n", "Q8_K vs fp16 activation",
327                        visible ? "yes" : "*** NO ***", rel * 100);
328            if (!visible) ++bad;
329            cudaFree(d_x16);
330        }
331        cudaFree(d_xf); cudaFree(d_xq); cudaFree(d_codes); cudaFree(d_scales); cudaFree(d_offs); cudaFree(d_y);
332    }
333
334    // ---- 4. output widths that are NOT a multiple of the eight rows per block
335    std::printf("\n");
336    for (const Case& cs : cases)
337        for (long long n_out : {1LL, 7LL, 9LL, 61LL}) bad += ragged_rows(cs, n_out);
338
339    std::printf("\ns_gemv_q8k: %d failures\n", bad);
340    if (bad) return 1;
341    if (selftest) std::printf("s_gemv_q8k_parity OK\n");
342    return 0;
343}