okami.mom/strata

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

Niko1221Merge branch 'f-0212-int' into f-0212-splitdf2c65b9f8be

main
7.3 KiB127 linesraw
1// src/prefill/gemm_w16_parity.cu - the FP16 weight cache (STRATA_PF_W16_CACHE_MIB) against the uncached Gemm::native, bitwise
2// (GPU, synthetic weights, no model).
3//
4// gemm_dequant_side_parity runs Gemm::native twice, with the cache and without the side-stream scratch, and its scratch (10.5 M elements) is
5// smaller than three of its eight weights, so those take the SLICED path (several GEMMs of N/k rows) uncached but ONE full-N GEMM cached:
6// two different cuBLAS calls that need not round alike.  The engine's scratch is GEMM_SCRATCH = 32 M elements (src/prefill/prefill.cpp) and every
7// dense projection of Qwen3.8-Flash-Next (the largest is attn_q, 12288 x 2560 = 31.5 M) fits it, so in the engine the cached and the uncached
8// forms are the same GEMM on the same FP16 values.  This test runs exactly that: the engine's scratch size, the engine's dense shapes and types
9// (Q8_0 on IQ3_S, Q4_K / Q5_K / Q6_K on the Unsloth sets), several token counts, with the cache off (STRATA_PF_W16_CACHE_MIB=0) and on
10// ("auto"), each cached weight used twice.  Every output must be identical bit for bit.  A weight larger than the scratch (the 248320 x 2560
11// output head) is reported separately and is NOT part of the verdict: it never goes through Gemm::native in the prompt path.
12// Exit 77 without a CUDA device.
13#include "strata/prefill/gemm.hpp"
14
15#include <cuda_fp16.h>
16#include <cuda_runtime.h>
17
18#include <cstdint>
19#include <cstdio>
20#include <cstdlib>
21#include <cstring>
22#include <random>
23#include <string>
24#include <vector>
25
26namespace {
27__global__ void fill_f16(__half* p, int64_t n, unsigned seed, float scale) {
28    const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
29    if (i >= n) return;
30    unsigned x = (unsigned) i * 2654435761u + seed;
31    x ^= x >> 16; x *= 2246822519u; x ^= x >> 13; x *= 3266489917u; x ^= x >> 16;
32    p[i] = __float2half(((float) (x & 0xffff) / 32768.0f - 1.0f) * scale);
33}
34bool ok(cudaError_t e, const char* what) {
35    if (e != cudaSuccess) std::printf("FAIL: %s: %s\n", what, cudaGetErrorString(e));
36    return e == cudaSuccess;
37}
38uint16_t sane_half(std::mt19937& rng) {
39    const uint32_t r = rng();
40    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
41}
42// one quantization type: ggml type id, elements and bytes per block, offsets of the FP16 scales inside a block
43struct QType { int type, elems, bytes; int at[2]; const char* name; };
44struct Shape { int qt; int64_t N, K; const char* what; bool production; };
45struct Weight { Shape s; void* dev = nullptr; };
46}  // namespace
47
48int main() {
49    setvbuf(stdout, nullptr, _IONBF, 0);
50    int n_dev = 0;
51    if (cudaGetDeviceCount(&n_dev) != cudaSuccess || n_dev < 1) { std::printf("no CUDA device (skipped)\n"); return 77; }
52    cudaStream_t st = nullptr;
53    if (!ok(cudaStreamCreate(&st), "stream")) return 1;
54    const int64_t scratch_elems = 32ll << 20;   // GEMM_SCRATCH in src/prefill/prefill.cpp
55    const QType qts[] = {{8, 32, 34, {0, -1}, "Q8_0"}, {12, 256, 144, {0, 2}, "Q4_K"}, {13, 256, 176, {0, 2}, "Q5_K"}, {14, 256, 210, {208, -1}, "Q6_K"}};
56    // the dense projections of Qwen3.8-Flash-Next (index of the IQ3_S pack: attn_q 12288 x 2560, attn_qkv 10240, attn_gate 6144, ssm_out / attn_output
57    // 2560 x 6144, the shared expert 640, attn_k / attn_v 512), in each type; the 248320-row head last (larger than the scratch)
58    std::vector<Shape> shapes;
59    for (int q = 0; q < 4; ++q) {
60        shapes.push_back({q, 12288, 2560, "attn_q", true});
61        shapes.push_back({q, 10240, 2560, "attn_qkv", true});
62        shapes.push_back({q, 6144, 2560, "attn_gate", true});
63        shapes.push_back({q, 2560, 6144, "ssm_out", true});
64        shapes.push_back({q, 640, 2560, "shexp_gate", true});
65        shapes.push_back({q, 2560, 640, "shexp_down", true});
66        shapes.push_back({q, 512, 2560, "attn_k", true});
67    }
68    shapes.push_back({0, 248320, 2560, "output head (bigger than the scratch)", false});
69    std::mt19937 rng(20261103u);
70    std::vector<Weight> ws;
71    for (const Shape& s : shapes) {
72        const QType& q = qts[s.qt];
73        if (s.K % q.elems != 0) continue;
74        const size_t blocks = (size_t) (s.N * s.K / q.elems), bytes = blocks * (size_t) q.bytes;
75        std::vector<uint8_t> h(bytes);
76        for (auto& b : h) b = (uint8_t) (rng() & 0xff);
77        for (size_t k = 0; k < blocks; ++k)
78            for (int at : q.at)
79                if (at >= 0) { const uint16_t v = sane_half(rng); std::memcpy(&h[k * (size_t) q.bytes + (size_t) at], &v, 2); }
80        Weight w; w.s = s;
81        if (!ok(cudaMalloc(&w.dev, bytes), "W") || !ok(cudaMemcpy(w.dev, h.data(), bytes, cudaMemcpyHostToDevice), "W copy")) return 1;
82        ws.push_back(w);
83    }
84    int64_t max_k = 0, max_n = 0;
85    for (const Weight& w : ws) { if (w.s.K > max_k) max_k = w.s.K; if (w.s.N > max_n) max_n = w.s.N; }
86    const int64_t Ts[] = {16, 64, 512, 4096};
87    const int64_t Tmax = 4096;
88    uint16_t* X = nullptr;
89    float* Y[2] = {nullptr, nullptr};
90    if (!ok(cudaMalloc((void**) &X, (size_t) Tmax * max_k * 2), "X") || !ok(cudaMalloc((void**) &Y[0], (size_t) Tmax * max_n * 4), "Y0") ||
91        !ok(cudaMalloc((void**) &Y[1], (size_t) Tmax * max_n * 4), "Y1"))
92        return 1;
93    fill_f16<<<(unsigned) ((Tmax * max_k + 255) / 256), 256, 0, st>>>((__half*) X, Tmax * max_k, 17u, 2.0f);
94    if (!ok(cudaStreamSynchronize(st), "fill")) return 1;
95
96    int bad = 0, bad_other = 0, checked = 0;
97    for (const Weight& w : ws) {
98        for (const int64_t T : Ts) {
99            std::vector<uint8_t> out[2];
100            for (int on = 0; on < 2; ++on) {
101                setenv("STRATA_PF_W16_CACHE_MIB", on ? "auto" : "0", 1);
102                strata::prefill::Gemm gemm;          // a fresh one reads the variable at its first native()
103                std::string err;
104                if (!gemm.init(st, scratch_elems, err)) { std::printf("FAIL: %s\n", err.c_str()); return 1; }
105                cudaMemset(Y[on], 0xff, (size_t) T * max_n * 4);
106                for (int rep = 0; rep < (on ? 2 : 1); ++rep)   // cached: the first call fills the cache, the second reads it
107                    gemm.native(X, qts[w.s.qt].type, w.dev, Y[on], T, w.s.N, w.s.K, max_n, 0.0f);
108                if (!ok(cudaStreamSynchronize(st), "run") || !ok(cudaDeviceSynchronize(), "device")) return 1;
109                out[on].resize((size_t) T * max_n * 4);
110                cudaMemcpy(out[on].data(), Y[on], out[on].size(), cudaMemcpyDeviceToHost);
111            }
112            long long diff = 0;
113            for (int64_t r = 0; r < T; ++r)
114                if (std::memcmp(&out[0][(size_t) r * max_n * 4], &out[1][(size_t) r * max_n * 4], (size_t) w.s.N * 4) != 0) ++diff;
115            const bool fits = w.s.N * w.s.K <= scratch_elems;
116            if (w.s.production) ++checked;
117            if (diff || !w.s.production)
118                std::printf("  %-5s %-22s N %6lld K %4lld T %5lld%s: %s\n", qts[w.s.qt].name, w.s.what, (long long) w.s.N, (long long) w.s.K, (long long) T,
119                            fits ? "" : " (sliced when uncached)", diff ? "*** DIFFERS ***" : "bitwise equal");
120            if (diff) { if (w.s.production) ++bad; else ++bad_other; }
121        }
122    }
123    std::printf("gemm_w16_parity: %d production (shape, type, T) combinations checked, %d differ; head (not part of the verdict) %s\n", checked, bad,
124                bad_other ? "differs" : "equal");
125    std::printf("gemm_w16_parity: %s\n", bad ? "FAILED" : "OK");
126    return bad ? 1 : 0;
127}