okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
8.8 KiB181 linesraw
1// src/kernels/s2_gemv_q8_parity.cpp - the Q8_0-activation GEMV, and the size of the gap it closes.
2//
3// THREE CHECKS:
4//   1. The quantized-activation GEMV matches a host reference that quantizes the activation exactly as
5//      `ref/quant.py::q8_0` does and then dots it against the same weights.
6//   2. **The gap is REAL and MEASURABLE in this project's own kernels**: the same weights driven by an FP16
7//      activation and by a Q8_0 activation must DIFFER, by roughly the activation contract's ~1%.  Without this
8//      the first check would pass on a kernel that quietly used fp16 anyway, and the round-186 gap would look
9//      fixed without being fixed.
10//   3. The measured size of that difference is reported, so the number in the state file is one this test
11//      produces rather than one quoted from elsewhere.
12#include "strata/kernels/quantize_act.hpp"
13#include "strata/kernels/s_gemv.hpp"
14#include "strata/kernels/s2_gemv_q8.hpp"
15
16#include <cuda_runtime.h>
17
18#include <cmath>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <random>
23#include <vector>
24
25namespace {
26
27void check(cudaError_t e, const char* what) {
28    if (e != cudaSuccess) {
29        std::fprintf(stderr, "%s: %s\n", what, cudaGetErrorString(e));
30        std::exit(1);
31    }
32}
33
34}  // namespace
35
36int main(int argc, char** argv) {
37    bool selftest = false;
38    for (int i = 1; i < argc; ++i) {
39        if (std::string(argv[i]) == "--selftest") selftest = true;
40        else { std::fprintf(stderr, "usage: s2_gemv_q8_parity [--selftest]\n"); return 2; }
41    }
42
43    const long long n_in = 2560, n_out = 64;
44    const int tpr = 32;
45    std::mt19937 rng(31);
46    std::normal_distribution<float> gauss(0.0f, 1.0f);
47
48    std::vector<float> x((size_t) n_in);
49    for (auto& v : x) v = gauss(rng);
50    std::vector<uint8_t> codes((size_t) n_out * n_in / 4);
51    for (auto& v : codes) v = (uint8_t) (rng() & 0xFF);
52    std::vector<float> scales((size_t) n_out * (n_in / 64));
53    for (auto& v : scales) v = 0.001f + 0.0001f * (float) (rng() % 100);
54
55    // ---- device buffers
56    float* d_x = nullptr;
57    uint8_t* d_act = nullptr;
58    uint8_t* d_codes = nullptr;
59    float *d_scales = nullptr, *d_y_fp16 = nullptr, *d_y_q8 = nullptr;
60    check(cudaMalloc(&d_x, (size_t) n_in * sizeof(float)), "m x");
61    check(cudaMalloc(&d_act, (size_t) (n_in / 32) * 34), "m act");
62    check(cudaMalloc(&d_codes, codes.size()), "m codes");
63    check(cudaMalloc(&d_scales, scales.size() * sizeof(float)), "m scales");
64    check(cudaMalloc(&d_y_fp16, (size_t) n_out * sizeof(float)), "m y1");
65    check(cudaMalloc(&d_y_q8, (size_t) n_out * sizeof(float)), "m y2");
66    check(cudaMemcpy(d_x, x.data(), x.size() * sizeof(float), cudaMemcpyHostToDevice), "c x");
67    check(cudaMemcpy(d_codes, codes.data(), codes.size(), cudaMemcpyHostToDevice), "c codes");
68    check(cudaMemcpy(d_scales, scales.data(), scales.size() * sizeof(float), cudaMemcpyHostToDevice), "c scales");
69
70    strata::kernels::quantize_q8_0(d_x, d_act, n_in, nullptr);
71
72    // ---- host reference: quantize the activation with the project's own rule, then dot
73    std::vector<uint8_t> h_act((size_t) (n_in / 32) * 34);
74    check(cudaMemcpy(h_act.data(), d_act, h_act.size(), cudaMemcpyDeviceToHost), "c act back");
75    auto act_val = [&](long long i) {
76        const uint8_t* blk = &h_act[(size_t) (i / 32) * 34];
77        const uint16_t dbits = (uint16_t) (blk[0] | (blk[1] << 8));
78        // fp16 -> f32 without a CUDA header: 0x3C00 = 1.0, and the block scales here are normal
79        float d;
80        const uint32_t sign = (uint32_t) (dbits & 0x8000) << 16;
81        uint32_t ex = (dbits >> 10) & 0x1F, man = dbits & 0x3FF;
82        uint32_t out;
83        if (ex == 0) { out = sign; }
84        else { out = sign | ((ex - 15 + 127) << 23) | (man << 13); }
85        std::memcpy(&d, &out, 4);
86        return (float) ((int8_t) blk[2 + (i % 32)]) * d;
87    };
88    std::vector<float> ref((size_t) n_out, 0.0f);
89    for (long long o = 0; o < n_out; ++o) {
90        float acc = 0.0f;
91        for (long long g = 0; g < n_in / 64; ++g) {
92            const float d = scales[(size_t) (o * (n_in / 64) + g)];
93            for (int j = 0; j < 64; ++j) {
94                const long long i = g * 64 + j;
95                const uint8_t byte = codes[(size_t) (o * (n_in / 4) + i / 4)];
96                const int code = (byte >> ((i % 4) * 2)) & 3;
97                acc += (float) (code - 1) * d * act_val(i);
98            }
99        }
100        ref[(size_t) o] = acc;
101    }
102    strata::kernels::s2_gemv_q8(d_act, d_codes, d_scales, d_y_q8, n_in, n_out, tpr, nullptr);
103    std::vector<float> got((size_t) n_out);
104    check(cudaMemcpy(got.data(), d_y_q8, got.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y2");
105
106    int bad = 0;
107    double worst = 0.0, sum_abs = 0.0;
108    for (long long o = 0; o < n_out; ++o) {
109        const double a = ref[(size_t) o], b = got[(size_t) o];
110        sum_abs += std::fabs(a);
111        // relative to the row magnitude is not needed here - these rows are not cancelling - but the metric is
112        // stated because round 169 and round 189 both showed the wrong denominator reads as a wrong kernel
113        const double rel = std::fabs(a - b) / (std::fabs(a) > 1e-30 ? std::fabs(a) : 1e-30);
114        if (!(rel <= worst)) worst = rel;
115        // 1e-4, not 1e-5: the measured worst is 1.479e-05, which is FMA contraction over 2560 terms rather
116        // than a structural error, and a threshold that passes 62 of 64 by luck is not a threshold.  The phase
117        // allows 1e-3 for FP16 paths, so this is ten times tighter than the spec and ten times looser than the
118        // measurement.
119        if (!(rel <= 1e-4)) ++bad;
120    }
121    std::printf("  %-38s %s (%d of %lld over 1e-4, worst rel %.3e, mean |ref| %.3f)\n",
122                "q8-activation GEMV vs host reference", bad ? "*** WRONG ***" : "matches", bad, n_out, worst,
123                sum_abs / (double) n_out);
124
125    // ---- CHECK 2: the gap is real.  The SAME weights driven by an fp16 activation must differ.
126    // The fp16 path wants fp16 activations, and `x` is f32, so it is converted exactly (the values are normal
127    // and small), which keeps the comparison about the ACTIVATION FORMAT and nothing else.
128    // A REAL fp32 -> fp16 conversion.  The first version wrote `0x3C00 + (int)(x*64)`, which adds to the raw
129    // BITS and therefore changes the EXPONENT - x = 2.0 became 0x3C80 = 1.25 - so the two paths were driven by
130    // unrelated activations and the comparison reported 2770%.  The number was a symptom of the fixture, and
131    // the fixture is what the check exists to be able to trust.
132    auto f32_to_f16 = [](float f) -> uint16_t {
133        uint32_t b;
134        std::memcpy(&b, &f, 4);
135        const uint32_t sign = (b >> 16) & 0x8000u;
136        int exp = (int) ((b >> 23) & 0xFF) - 127 + 15;
137        uint32_t man = b & 0x7FFFFFu;
138        if (exp >= 31) return (uint16_t) (sign | 0x7C00u | (man ? 0x200u : 0u));
139        if (exp <= 0) {
140            if (exp < -10) return (uint16_t) sign;
141            man |= 0x800000u;
142            const uint32_t sh = (uint32_t) (14 - exp);
143            uint32_t h = (man >> sh) & 0x3FFu;
144            const uint32_t rem = man & ((1u << sh) - 1u);
145            if (rem > (1u << (sh - 1)) || (rem == (1u << (sh - 1)) && (h & 1u))) ++h;
146            return (uint16_t) (sign | h);
147        }
148        uint16_t h = (uint16_t) (sign | ((uint32_t) exp << 10) | (man >> 13));
149        const uint32_t rem = man & 0x1FFFu;
150        if (rem > 0x1000u || (rem == 0x1000u && (h & 1u))) ++h;
151        return h;
152    };
153    std::vector<uint16_t> hx((size_t) n_in);
154    for (long long i = 0; i < n_in; ++i) hx[(size_t) i] = f32_to_f16(x[(size_t) i]);
155    uint16_t* d_hx = nullptr;
156    check(cudaMalloc(&d_hx, hx.size() * sizeof(uint16_t)), "m hx");
157    check(cudaMemcpy(d_hx, hx.data(), hx.size() * sizeof(uint16_t), cudaMemcpyHostToDevice), "c hx");
158    strata::kernels::SForm form{2, -1, 64, strata::kernels::Codebook::Affine, false};
159    strata::kernels::s_gemv_split(d_hx, d_codes, d_scales, nullptr, d_y_fp16, n_in, n_out, form, tpr);
160    std::vector<float> y16((size_t) n_out);
161    check(cudaMemcpy(y16.data(), d_y_fp16, y16.size() * sizeof(float), cudaMemcpyDeviceToHost), "c y1");
162
163    double diff = 0.0;
164    for (long long o = 0; o < n_out; ++o) {
165        diff += std::fabs((double) y16[(size_t) o] - (double) got[(size_t) o]);
166    }
167    const double rel_gap = diff / (sum_abs > 1e-30 ? sum_abs : 1e-30);
168    std::printf("  %-38s %.4f%% of the reference magnitude\n", "fp16-activation vs q8-activation", rel_gap * 100);
169    if (rel_gap < 1e-4) {
170        std::fprintf(stderr,
171                     "the two activation paths agree to %.2e, so this test CANNOT see the difference it exists "
172                     "to measure - either the q8 path silently used fp16, or the fixture is degenerate\n",
173                     rel_gap);
174        ++bad;
175    }
176
177    std::printf("\ns2_gemv_q8: %d failures\n", bad);
178    if (bad) return 1;
179    if (selftest) std::printf("s2_gemv_q8_parity OK\n");
180    return 0;
181}