okami.mom/strata

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

Niko1221Merge f-q4-geometry (fc1c4e429): the model shape is fixed at build time (-DSTRATA_GEOMETRY / -DSTRATA_GEOMETRY_FILE); the default Flash-Next build is unchanged (CUDA SASS 3573/3573, HIP gfx1201 3920/3920, gfx1151 path-string offsets only, SYCL 22/22 checksums, Metal 10/10 tokens, CUDA 130/130 tokens); Qwen4 test shapes q4_lite/q4_mid/q4_big pass logits gate 2 on CUDA (Qwen4 prep)4dad59ab3

main
9.2 KiB196 linesraw
1// src/kernels/native_dense_parity.cpp - the dense GGUF projections of the Unsloth v3.1 Qwen3.8-Flash-Next sets
2// (Q5_0, Q6_K, Q5_K, Q4_K, Q8_0, IQ4_XS, IQ4_NL, Q2_0 ...) on synthetic weights quantized by ggml, no model files.
3//
4//     build/native_dense_parity [--only=NAME]
5//
6// Decode: the GPU's q8_1 quantizer and native_mmvq (1, 2, 3, 4 and 8 columns) against a double-precision product of
7// ggml's own dequantized weights (to_float) and the FP32 activations.  The only difference is the activations'
8// q8_1 rounding, so the relative L1 error has to stay under 2e-2 (it is a few 1e-3; 4e-2 for Q4_0 / Q5_0, see run_case); columns of a multi-column call
9// are bitwise the single-column call (native_mmvq_multi_exact, the default).
10// Prompt (the dequantize-to-FP16/BF16 route that serves a type without an MMQ instance): dequant_f32 against
11// to_float (relative error 1e-6), dequant_f16 and dequant_bf16 against the rounded to_float.
12// Shapes: the model's hidden width 2560 (attention, SSM and shared-expert inputs, the head) and 640 (the shared
13// expert's and the experts' FF width) for the formats with a block of 64 values or fewer.
14#include "strata/kernels/dequant_bf16.hpp"
15#include "strata/kernels/native_mmvq.hpp"
16
17#include "ggml.h"
18
19#include <cuda_runtime.h>
20
21#include <algorithm>
22#include <cmath>
23#include <cstdint>
24#include <cstdio>
25#include <cstdlib>
26#include <cstring>
27#include <random>
28#include <string>
29#include <vector>
30
31namespace k = strata::kernels;
32
33namespace {
34struct T { const char* name; ggml_type type; };
35const T kTypes[] = {
36    {"Q2_0", GGML_TYPE_Q2_0},   {"Q4_0", GGML_TYPE_Q4_0}, {"Q5_0", GGML_TYPE_Q5_0},   {"Q8_0", GGML_TYPE_Q8_0},
37    {"IQ4_NL", GGML_TYPE_IQ4_NL}, {"IQ4_XS", GGML_TYPE_IQ4_XS}, {"Q3_K", GGML_TYPE_Q3_K}, {"Q4_K", GGML_TYPE_Q4_K},
38    {"Q5_K", GGML_TYPE_Q5_K},   {"Q6_K", GGML_TYPE_Q6_K},
39};
40
41bool ck(cudaError_t e, const char* what) {
42    if (e == cudaSuccess) return true;
43    std::printf("  CUDA error in %s: %s\n", what, cudaGetErrorString(e));
44    return false;
45}
46
47double rel_l1(const std::vector<float>& a, const std::vector<double>& b) {
48    double n = 0, d = 0;
49    for (size_t i = 0; i < a.size(); ++i) { n += std::fabs((double) a[i] - b[i]); d += std::fabs(b[i]); }
50    return n / (d + 1e-30);
51}
52
53uint16_t bf16_rne(float f) {
54    uint32_t u;
55    std::memcpy(&u, &f, 4);
56    if ((u & 0x7fffffffu) > 0x7f800000u) return (uint16_t) ((u >> 16) | 0x40);
57    u += 0x7fffu + ((u >> 16) & 1u);
58    return (uint16_t) (u >> 16);
59}
60
61// returns the number of failed checks
62int run_case(const T& t, int n_in, int n_out, int seed) {
63    int fails = 0;
64    const int64_t blck = ggml_blck_size(t.type);
65    if (n_in % blck != 0) return 0;
66    std::mt19937 rng(1000 + seed);
67    std::normal_distribution<float> nd(0.f, 1.f);
68    std::vector<float> w((size_t) n_out * n_in);
69    for (int r = 0; r < n_out; ++r) {
70        const float scale = 0.02f * (0.5f + (float) (r % 7) / 7.0f);
71        for (int c = 0; c < n_in; ++c) w[(size_t) r * n_in + c] = scale * nd(rng);
72    }
73    const size_t rb = ggml_row_size(t.type, n_in);
74    std::vector<uint8_t> blob((size_t) n_out * rb);
75    const std::vector<float> imatrix((size_t) n_in, 1.0f);
76    ggml_quantize_chunk(t.type, w.data(), blob.data(), 0, n_out, n_in,
77                        ggml_quantize_requires_imatrix(t.type) ? imatrix.data() : nullptr);
78    const auto* tr = ggml_get_type_traits(t.type);
79    std::vector<float> wd((size_t) n_out * n_in);
80    for (int r = 0; r < n_out; ++r) tr->to_float(blob.data() + (size_t) r * rb, wd.data() + (size_t) r * n_in, n_in);
81
82    constexpr int NC = 8;
83    std::vector<float> x((size_t) NC * n_in);
84    for (auto& v : x) v = nd(rng);
85    for (int j = 0; j < NC; ++j) x[(size_t) j * n_in + (size_t) (j * 37 % n_in)] *= 12.f;   // an outlier per column
86    std::vector<double> ref((size_t) NC * n_out);
87    for (int j = 0; j < NC; ++j)
88        for (int r = 0; r < n_out; ++r) {
89            double a = 0;
90            for (int c = 0; c < n_in; ++c) a += (double) wd[(size_t) r * n_in + c] * x[(size_t) j * n_in + c];
91            ref[(size_t) j * n_out + r] = a;
92        }
93
94    cudaStream_t s;
95    cudaStreamCreate(&s);
96    void *dw = nullptr, *dxq = nullptr;
97    float *dx = nullptr, *dy = nullptr, *df = nullptr;
98    uint16_t *dh = nullptr, *db = nullptr;
99    const size_t welems = (size_t) n_out * n_in;
100    bool ok = ck(cudaMalloc(&dw, blob.size()), "w") && ck(cudaMalloc((void**) &dx, x.size() * 4), "x") &&
101              ck(cudaMalloc(&dxq, k::native_q8_1_bytes(n_in, NC)), "xq") && ck(cudaMalloc((void**) &dy, (size_t) NC * n_out * 4), "y") &&
102              ck(cudaMalloc((void**) &df, welems * 4), "f32") && ck(cudaMalloc((void**) &dh, welems * 2), "f16") &&
103              ck(cudaMalloc((void**) &db, welems * 2), "bf16");
104    if (!ok) return 1;
105    cudaMemcpy(dw, blob.data(), blob.size(), cudaMemcpyHostToDevice);
106    cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice);
107
108    char line[256];
109    std::string res;
110    // decode: native_mmvq at 1, 2, 3, 4, 8 columns
111    std::vector<float> y1((size_t) n_out);
112    // Q4_0 / Q5_0 subtract an offset (8 / 16) times the q8_1 block's sum of the ORIGINAL activations (llama.cpp CUDA's form, the
113    // same in ggml-cuda), so the activations' rounding shows 3x larger on these random zero-mean outputs: 1.6-2.3e-2 measured
114    const double tol = (t.type == GGML_TYPE_Q4_0 || t.type == GGML_TYPE_Q5_0) ? 4e-2 : 2e-2;
115    double worst = 0;
116    bool cols_equal = true;
117    if (!k::native_mmvq_supported((int) t.type)) {
118        std::printf("%-8s n_in %-5d native_mmvq: NOT SUPPORTED\n", t.name, n_in);
119        ++fails;
120    } else {
121        for (int nc : {1, 2, 3, 4, 8}) {
122            cudaMemset(dy, 0xff, (size_t) NC * n_out * 4);
123            k::native_quantize_q8_1(dx, dxq, n_in, nc, s);
124            k::native_mmvq((int) t.type, dw, dxq, dy, n_in, n_out, nc, s);
125            cudaStreamSynchronize(s);
126            std::vector<float> got((size_t) nc * n_out);
127            cudaMemcpy(got.data(), dy, got.size() * 4, cudaMemcpyDeviceToHost);
128            std::vector<double> rr(ref.begin(), ref.begin() + (ptrdiff_t) got.size());
129            const double e = rel_l1(got, rr);
130            worst = std::max(worst, e);
131            if (!(e < tol) || !std::isfinite(e)) ++fails;
132            if (nc == 1) y1.assign(got.begin(), got.end());
133            else if (std::memcmp(got.data(), y1.data(), y1.size() * 4) != 0) cols_equal = false;
134        }
135        if (!cols_equal) ++fails;
136        std::snprintf(line, sizeof line, "decode rel %.2e (1-8 cols), col0 same as 1 col: %s;", worst, cols_equal ? "yes" : "NO");
137        res += line;
138    }
139    // prompt dequantizers
140    if (!k::dequant_bf16_supported((int) t.type)) {
141        res += " dequant: NOT SUPPORTED";
142        ++fails;
143    } else {
144        std::vector<float> gf(welems);
145        std::vector<uint16_t> gh(welems), gb(welems);
146        k::dequant_f32((int) t.type, dw, 0, n_out, n_in, df, s);
147        k::dequant_f16((int) t.type, dw, 0, n_out, n_in, dh, s);
148        k::dequant_bf16((int) t.type, dw, 0, n_out, n_in, db, s);
149        cudaStreamSynchronize(s);
150        cudaMemcpy(gf.data(), df, welems * 4, cudaMemcpyDeviceToHost);
151        cudaMemcpy(gh.data(), dh, welems * 2, cudaMemcpyDeviceToHost);
152        cudaMemcpy(gb.data(), db, welems * 2, cudaMemcpyDeviceToHost);
153        double num = 0, den = 0;
154        size_t d32 = 0, d16 = 0, dbf = 0;
155        for (size_t i = 0; i < welems; ++i) {
156            num += std::fabs((double) gf[i] - wd[i]);
157            den += std::fabs((double) wd[i]);
158            d32 += std::memcmp(&gf[i], &wd[i], 4) != 0;
159            d16 += gh[i] != ggml_fp32_to_fp16(wd[i]);
160            dbf += gb[i] != bf16_rne(wd[i]);
161        }
162        const double e32 = num / (den + 1e-30);
163        // f32: a rounding at most (fused multiply-adds); f16/bf16: the rounded to_float, or one step off where the f32 differs
164        const bool ok32 = e32 < 1e-6;
165        const bool ok16 = d16 <= d32 && dbf <= d32;
166        if (!ok32 || !ok16) ++fails;
167        std::snprintf(line, sizeof line, " dequant f32 rel %.1e (%zu of %zu bits differ), f16 %zu / bf16 %zu differ", e32, d32, welems,
168                      d16, dbf);
169        res += line;
170    }
171    cudaFree(dw); cudaFree(dx); cudaFree(dxq); cudaFree(dy); cudaFree(df); cudaFree(dh); cudaFree(db);
172    cudaStreamDestroy(s);
173    std::printf("%-8s n_in %-5d n_out %-4d %s  %s\n", t.name, n_in, n_out, res.c_str(), fails ? "FAIL" : "ok");
174    return fails;
175}
176}  // namespace
177
178int main(int argc, char** argv) {
179    setvbuf(stdout, nullptr, _IONBF, 0);
180    const char* only = nullptr;
181    for (int i = 1; i < argc; ++i)
182        if (std::strncmp(argv[i], "--only=", 7) == 0) only = argv[i] + 7;
183    int dev = 0;
184    if (cudaGetDeviceCount(&dev) != cudaSuccess || dev == 0) { std::printf("no CUDA device\n"); return 77; }
185    int fails = 0, seed = 0;
186    for (const T& t : kTypes) {
187        if (only && std::strcmp(only, t.name) != 0) continue;
188        for (int n_in : {2560, 640, 4096, 512, 1024, 2048, 3072}) {
189            if (n_in == 640 && ggml_blck_size(t.type) > 64) continue;   // (K-quants and IQ4_XS: 256-value blocks; 640 is not a multiple)
190            if (n_in == 640 && ggml_blck_size(t.type) == 256) continue;
191            fails += run_case(t, n_in, 512, seed++);
192        }
193    }
194    std::printf("native_dense_parity: %d failures\n", fails);
195    return fails ? 1 : 0;
196}