okami.mom/strata

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

Niko1221Merge branch 'f-139b-old' into f-139-relbd34d0d87

main
12.9 KiB263 linesraw
1// src/kernels/mmvq_multi_parity.cpp - the multi_exact contract of native_mmvq, tested bitwise.
2//
3//     build/mmvq_multi_parity
4//
5// WHY IT EXISTS.  `include/strata/kernels/native_mmvq.hpp` says of `native_mmvq_set_multi_exact`:
6//
7//     "true (default): the ncols == 1 layout, every column bitwise equal to a single-column call"
8//
9// and `include/strata/core/verify.hpp` counts "multi-column MMVQ in exact mode" among the reasons the verify window
10// produces what greedy decode would, bit for bit.  Nothing tested that sentence: `iq_parity` calls `native_mmvq`
11// with two columns and compares against a float64 reference at 2e-2, which cannot see a difference between one
12// column and T columns.
13//
14// WHAT IT COMPARES.  The SAME Q8_1 bytes: one T-column call against T single-column calls, each reading column j
15// from the same buffer (the header: "its Q8_1 blocks at j * n_in / 32").  The quantization is shared, so the only
16// thing under test is how the columns are laid out.
17//
18// THE DATA.  The weights are random bytes, except each block's fp16 scales (`d`, and `dmin` where the format has
19// one), which are rewritten as normal fp16 values in +-[2^-10, 2^-5): random bytes there would put inf and NaN in
20// the outputs, and on the GPU every NaN comes out as the same canonical bit pattern, so a NaN output compares equal
21// whatever operations produced it and proves nothing.  With finite scales and finite normal activations (the
22// precondition the header puts on the input) every output is finite, and a non-finite one fails the test.
23//
24// THE NEGATIVE CONTROL.  The same comparison with `multi_exact` off must find differences, or the test has no power
25// and its pass means nothing.  Where it has power depends on T: in `native_mmvq.cu` the generic layout uses
26// `NW = NCOLS <= 4 ? 4 : 2` warps, and with `WARPS = 4` and `BPI = F::BPI * NW / WARPS` it coincides with the
27// exact layout at T <= 4.  So the control is ASSERTED on T > 4 for every case, and at T <= 4 its silence is
28// reported as that coincidence rather than skipped.  The control needs a row long enough for the two layouts to
29// group blocks differently: IQ4_XS takes 16 blocks per iteration with 4 warps and 8 with 2, so at n_in = 2048 (8
30// blocks of 256) each thread holds at most one block in both layouts and they coincide; its case uses n_in = 4096.
31#include "strata/kernels/iq_kernels.hpp"
32#include "strata/kernels/native_mmvq.hpp"
33
34#include <cuda_runtime.h>
35
36#include <cmath>
37#include <cstdint>
38#include <cstdio>
39#include <cstdlib>
40#include <string>
41#include <cstring>
42#include <random>
43#include <vector>
44
45namespace {
46
47struct Case {
48    const char* name;
49    int type;          // stable GGML type id, from the list in native_mmvq.hpp
50    int n_in;
51    int n_out;
52    int block_elems;   // elements per weight block
53    int block_bytes;
54    int scale_at[2];   // byte offsets of the block's fp16 scales in native_mmvq.cu's block structs; -1 = none
55};
56
57// the types a head or a projection can have in this model
58const Case CASES[] = {
59    {"Q4_0", 2, 2048, 512, 32, 18, {0, -1}},          // Q40Block: half d
60    {"Q8_0", 8, 2048, 512, 32, 34, {0, -1}},          // Q80Block: half d
61    {"Q4_K", 12, 2048, 512, 256, 144, {0, 2}},        // Q4KBlock: half2 dm
62    {"Q5_K", 13, 2048, 512, 256, 176, {0, 2}},        // Q5KBlock: half2 dm
63    {"Q6_K", 14, 2048, 512, 256, 210, {208, -1}},     // Q6KBlock: half d after ql, qh, scales
64    {"IQ4_XS", 23, 4096, 512, 256, 136, {0, -1}},     // IQ4XSBlock: half d; n_in 4096, see THE NEGATIVE CONTROL
65    {"Q5_K wide", 13, 4096, 2048, 256, 176, {0, 2}},
66};
67
68// a normal fp16 in +-[2^-10, 2^-5): exponent field 5..9 (bias 15), any mantissa, either sign
69uint16_t sane_half(std::mt19937& rng) {
70    const uint32_t r = rng();
71    return (uint16_t) (((r >> 31) << 15) | ((5u + (r >> 10) % 5u) << 10) | (r & 0x3ffu));
72}
73
74// T = 4 is the last width where the two layouts coincide, T = 5 the first where they differ
75const int WIDTHS[] = {1, 2, 3, 4, 5, 6, 8};
76constexpr int COINCIDE_MAX_T = 4;
77
78bool ck(cudaError_t e, const char* what) {
79    if (e == cudaSuccess) return true;
80    std::printf("CUDA: %s: %s\n", what, cudaGetErrorString(e));
81    return false;
82}
83
84// Returns the number of outputs that differ bit for bit; counts the non-finite outputs and the differences on
85// outputs that are finite in both paths.
86long long compare(const Case& c, int T, cudaStream_t s, long long& nonfinite, long long& diff_finite, bool& ran) {
87    ran = false;
88    if (!strata::kernels::native_mmvq_supported(c.type)) return -1;
89
90    const std::size_t wbytes = strata::kernels::native_mmvq_weight_bytes(c.type, c.n_in, c.n_out);
91    const std::size_t qcol = strata::kernels::native_q8_1_bytes(c.n_in, 1);   // Q8_1 bytes of ONE column
92    const std::size_t qall = strata::kernels::native_q8_1_bytes(c.n_in, T);
93    if (qall != qcol * (std::size_t) T) {
94        std::printf("%-12s T=%d: the Q8_1 bytes of T columns (%zu) are not T times those of one (%zu): the test "
95                    "assumes contiguous columns and they are not\n", c.name, T, qall, qcol);
96        return -1;
97    }
98
99    std::mt19937 rng(1234u + (unsigned) c.type * 97u + (unsigned) T);
100    std::vector<uint8_t> w(wbytes);
101    for (auto& b : w) b = (uint8_t) (rng() & 0xff);
102    const std::size_t n_blocks = (std::size_t) c.n_out * (std::size_t) (c.n_in / c.block_elems);
103    if (n_blocks * (std::size_t) c.block_bytes != wbytes) {
104        std::printf("%-12s T=%d: %zu blocks of %d bytes are not the %zu weight bytes native_mmvq expects\n", c.name,
105                    T, n_blocks, c.block_bytes, wbytes);
106        return -1;
107    }
108    for (std::size_t k = 0; k < n_blocks; ++k)
109        for (int at : c.scale_at)
110            if (at >= 0) {
111                const uint16_t h = sane_half(rng);
112                std::memcpy(&w[k * (std::size_t) c.block_bytes + (std::size_t) at], &h, 2);
113            }
114    std::vector<float> x((std::size_t) T * c.n_in);
115    std::normal_distribution<float> nd(0.f, 1.f);
116    for (auto& v : x) v = nd(rng);
117
118    void* dw = nullptr;
119    void* xq = nullptr;
120    float* dx = nullptr;
121    float* dmulti = nullptr;
122    float* dsingle = nullptr;
123    const std::size_t ybytes = (std::size_t) T * c.n_out * 4;
124    if (!ck(cudaMalloc(&dw, wbytes), "malloc w") || !ck(cudaMalloc(&xq, qall), "malloc xq") ||
125        !ck(cudaMalloc(&dx, x.size() * 4), "malloc x") || !ck(cudaMalloc(&dmulti, ybytes), "malloc multi") ||
126        !ck(cudaMalloc(&dsingle, ybytes), "malloc single"))
127        return -1;
128    if (!ck(cudaMemcpy(dw, w.data(), wbytes, cudaMemcpyHostToDevice), "copy w") ||
129        !ck(cudaMemcpy(dx, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "copy x"))
130        return -1;
131
132    // ONE quantization, shared by both paths: the quantization is not under test
133    strata::kernels::quantize_q8_1_rows(dx, T, c.n_in, xq, s);
134    if (!ck(cudaStreamSynchronize(s), "quantize")) return -1;
135
136    try {
137        strata::kernels::native_mmvq(c.type, dw, xq, dmulti, c.n_in, c.n_out, T, s);
138        for (int j = 0; j < T; ++j)
139            strata::kernels::native_mmvq(c.type, dw, (const uint8_t*) xq + (std::size_t) j * qcol,
140                                         dsingle + (std::size_t) j * c.n_out, c.n_in, c.n_out, 1, s);
141    } catch (const std::exception& e) {
142        std::printf("%-12s T=%d: %s\n", c.name, T, e.what());
143        return -1;
144    }
145    if (!ck(cudaStreamSynchronize(s), "mmvq")) return -1;
146
147    std::vector<uint32_t> a((std::size_t) T * c.n_out), b(a.size());
148    if (!ck(cudaMemcpy(a.data(), dmulti, ybytes, cudaMemcpyDeviceToHost), "read multi") ||
149        !ck(cudaMemcpy(b.data(), dsingle, ybytes, cudaMemcpyDeviceToHost), "read single"))
150        return -1;
151
152    long long diff = 0;
153    nonfinite = 0;
154    diff_finite = 0;
155    for (std::size_t i = 0; i < a.size(); ++i) {
156        float fa, fb;
157        std::memcpy(&fa, &a[i], 4);
158        std::memcpy(&fb, &b[i], 4);
159        const bool both_finite = std::isfinite(fa) && std::isfinite(fb);
160        if (!both_finite) ++nonfinite;
161        if (a[i] != b[i]) {
162            ++diff;
163            if (both_finite) ++diff_finite;
164        }
165    }
166    cudaFree(dw); cudaFree(xq); cudaFree(dx); cudaFree(dmulti); cudaFree(dsingle);
167    ran = true;
168    return diff;
169}
170
171struct Totals {
172    long long checked = 0, diff = 0, diff_finite = 0, nonfinite = 0;   // all widths
173    long long diff_finite_wide = 0;                                     // T > COINCIDE_MAX_T only
174    int powerless_cases = 0;   // cases where the control found no difference at any T > COINCIDE_MAX_T
175};
176
177int sweep(bool exact, cudaStream_t s, Totals& t) {
178    strata::kernels::native_mmvq_set_multi_exact(exact);
179    if (strata::kernels::native_mmvq_multi_exact() != exact) {
180        std::printf("native_mmvq_multi_exact() does not reflect what was set\n");
181        return 1;
182    }
183    std::printf("\n=== multi_exact %s ===\n", exact ? "ON (the default)" : "off (negative control)");
184    std::printf("%-12s %3s %10s %10s %14s %10s\n", "type", "T", "outputs", "bits diff", "finite diff", "nonfinite");
185    int bad = 0;
186    for (const Case& c : CASES) {
187        long long case_wide = 0;
188        for (int T : WIDTHS) {
189            long long nf = 0, dfin = 0;
190            bool ran = false;
191            const long long diff = compare(c, T, s, nf, dfin, ran);
192            if (!ran) { ++bad; continue; }
193            const long long n = (long long) T * c.n_out;
194            t.checked += n;
195            t.diff += diff;
196            t.diff_finite += dfin;
197            t.nonfinite += nf;
198            if (T > COINCIDE_MAX_T) { t.diff_finite_wide += dfin; case_wide += dfin; }
199            const char* verdict;
200            if (exact) verdict = diff == 0 ? "ok" : "FAIL";
201            else if (dfin > 0) verdict = "control sees it";
202            else verdict = T <= COINCIDE_MAX_T ? "layouts coincide here (NW = 4)" : "no power at this T";
203            std::printf("%-12s %3d %10lld %10lld %14lld %10lld  %s\n", c.name, T, n, diff, dfin, nf, verdict);
204            if (exact && diff != 0) ++bad;
205        }
206        if (!exact && case_wide == 0) ++t.powerless_cases;
207    }
208    return bad;
209}
210
211}  // namespace
212
213int main() {
214    cudaStream_t s;
215    if (!ck(cudaStreamCreate(&s), "stream create")) return 1;
216
217    Totals on, off;
218    const int bad = sweep(true, s, on);
219    const int bad_off = sweep(false, s, off);
220    strata::kernels::native_mmvq_set_multi_exact(true);   // back to the default
221
222    std::printf("\nmulti_exact on:   %lld outputs compared, %lld differ bitwise, %lld non-finite\n",
223                on.checked, on.diff, on.nonfinite);
224    std::printf("multi_exact off:  %lld outputs compared, %lld differ bitwise (%lld on finite outputs, %lld at T > %d)\n",
225                off.checked, off.diff, off.diff_finite, off.diff_finite_wide, COINCIDE_MAX_T);
226
227    if (on.nonfinite != 0 || off.nonfinite != 0) {
228        std::printf("\nmmvq_multi_parity: FAILED. %lld non-finite outputs from finite scales and activations: the "
229                    "bit comparison is only meaningful on finite outputs.\n", on.nonfinite + off.nonfinite);
230        return 1;
231    }
232    if (bad != 0 || bad_off != 0) {
233        std::printf("\nmmvq_multi_parity: FAILED. %d case(s) with multi_exact on differ from single-column calls "
234                    "or did not run, %d case(s) did not run with it off. If they differ, the sentence in "
235                    "native_mmvq.hpp does not hold, and neither does the bit-exactness verify.hpp claims.\n",
236                    bad, bad_off);
237        return 1;
238    }
239    // THE NEGATIVE CONTROL, asserted where it can see something: past T = 4 the generic layout is a different one,
240    // so if it still finds no difference the comparison cannot tell the layouts apart and the pass proves nothing.
241#if defined(STRATA_HIP_GFX906)
242    // gfx906: the wave64 layout (one wavefront per row) is the same kernel for every column count, so multi_exact
243    // has nothing to switch and the control cannot see a difference.  The control with power is the CUDA layout:
244    // ctest's mmvq_multi_parity_cuda_layout runs this with STRATA_MMVQ_WAVE=0.
245    if (off.powerless_cases != 0 && !(std::getenv("STRATA_MMVQ_WAVE") && std::string(std::getenv("STRATA_MMVQ_WAVE")) == "0")) {
246        std::printf("\nmmvq_multi_parity: ok (gfx906 wave64 layout: every column count runs the same exact kernel, "
247                    "so the negative control has no other layout to find; mmvq_multi_parity_cuda_layout checks it).\n");
248        return 0;
249    }
250#endif
251    if (off.powerless_cases != 0) {
252        std::printf("\nmmvq_multi_parity: FAILED (no power). In %d case(s) no output differs with multi_exact off at "
253                    "any T > %d, where the generic layout is not the exact one: for those cases this comparison "
254                    "cannot tell the two layouts apart, so their pass above proves nothing.\n", off.powerless_cases,
255                    COINCIDE_MAX_T);
256        return 1;
257    }
258    std::printf("\nmmvq_multi_parity: ok. With multi_exact on every column is bitwise equal to a single-column "
259                "call; with it off the control finds differences at T > %d in every case, so the comparison has "
260                "power.\n",
261                COINCIDE_MAX_T);
262    return 0;
263}