okami.mom/strata

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

Niko1221Merge f-q36-testpad 9f0056e41 into f-p4-intf2b41fd29

main
9.7 KiB178 linesraw
1// prefill_mmq_kquant_test - the prompt path's MMQ products for the expert formats of Unsloth's UD-Q4_K_XL and
2// UD-Q6_K_XL (gate/up Q4_K / Q5_K / Q6_K at 1280 x 2560, down Q5_1 and Q8_0 at 2560 x 640), on synthetic weights
3// quantized by ggml's own
4// reference quantizers, against a double-precision product of ggml's dequantized weights.  MMQ rounds the activations
5// to q8_1 by design, so this is a screen for layout, stride, expert-bound and row-id errors (the bounds of
6// tests/hip/prefill_mmq_parity.cpp), not a bit-exactness test.  Several experts per product, permuted rows, an
7// all-zero row.  The MMQ path covers gate/up Q4_K / Q5_K / Q6_K and down Q5_1 / Q8_0 (UD-Q4_K_XL / UD-Q6_K_XL).
8#include "strata/prefill/mmq_ids_margin.hpp"
9#include "strata/prefill/moe_mmq.hpp"
10
11#include "ggml.h"
12
13#include <cuda_runtime.h>
14
15#include <algorithm>
16#include <cmath>
17#include <cstdint>
18#include <cstdio>
19#include <numeric>
20#include <stdexcept>
21#include <string>
22#include <vector>
23
24namespace {
25namespace mmq = strata::prefill::mmq;
26
27void ck(cudaError_t e, const char* what) {
28    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
29}
30
31struct Dev {
32    void* p = nullptr;
33    explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
34    ~Dev() { cudaFree(p); }
35    Dev(const Dev&) = delete;
36    Dev& operator=(const Dev&) = delete;
37};
38
39std::vector<uint8_t> make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) {
40    const auto* tr = ggml_get_type_traits(t);
41    if (tr == nullptr || tr->from_float_ref == nullptr) throw std::runtime_error("no reference quantizer");
42    const size_t rb = ggml_row_size(t, cols);
43    std::vector<uint8_t> out((size_t) rows * rb);
44    std::vector<float> row((size_t) cols);
45    for (int64_t r = 0; r < rows; ++r) {
46        for (int64_t k = 0; k < cols; ++k) {
47            const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50;
48            row[(size_t) k] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) +
49                              0.0015f * (float) code;
50        }
51        tr->from_float_ref(row.data(), out.data() + (size_t) r * rb, cols);
52    }
53    return out;
54}
55
56std::vector<float> make_x(int rows, int64_t cols, int trial) {
57    std::vector<float> x((size_t) rows * (size_t) cols);
58    for (int r = 0; r < rows; ++r)
59        for (int64_t k = 0; k < cols; ++k)
60            x[(size_t) r * (size_t) cols + (size_t) k] =
61                0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) +
62                0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) +
63                0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9);
64    std::fill(x.end() - cols, x.end(), 0.0f);   // an all-zero row: exactly zero out
65    return x;
66}
67
68std::vector<int32_t> perm(int n, int shift, bool reverse) {
69    std::vector<int32_t> p((size_t) n);
70    for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n);
71    return p;
72}
73
74// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them)
75void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols,
76             const std::vector<int>& counts, int trial) {
77    if (!mmq::supported((int) t)) throw std::runtime_error(std::string(name) + ": not covered by this build");
78    const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0);
79    std::vector<int32_t> bounds((size_t) n + 1, 0);
80    for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e];
81    const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true);
82    const std::vector<float> x = make_x(rows, cols, trial);
83    const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols);
84    if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes");
85    std::vector<std::vector<uint8_t>> ws;
86    std::vector<uint8_t> w((size_t) n * eb + 4096, 0);
87    for (int e = 0; e < n; ++e) {
88        ws.push_back(make_matrix(t, out_rows, cols, e, trial));
89        std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb));
90    }
91    // llama.cpp's mul_mat_q and its stream-k fixup read the row-id table up to a J-column tile (J <= 128) past the last row, up to roundup(max_rows, J)
92    // from an expert's first row (mmq_ids_margin.hpp): the table has the margin, its extra entries hold row index 0 (valid; they are read, never used)
93    const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) *std::max_element(counts.begin(), counts.end()));
94    std::vector<int32_t> dst_table(dst);
95    dst_table.resize(ids_rows, 0);
96    Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst(ids_rows * 4), db(bounds.size() * 4), dw(w.size()),
97        dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4);
98    ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
99    ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src");
100    ck(cudaMemcpy(ddst.p, dst_table.data(), dst_table.size() * 4, cudaMemcpyHostToDevice), "dst");
101    ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds");
102    ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
103    ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel");
104    // the copies and the sentinel above run on the legacy stream, which a non-blocking stream does not wait for: a
105    // pageable cudaMemcpy/cudaMemset can still be in flight when the kernels start (a 128-SM 4090 caught it)
106    ck(cudaDeviceSynchronize(), "inputs");
107    mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s);
108    mmq::Product p;
109    p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n;
110    p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows;
111    p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows;
112    ctx.run(p, s);
113    ck(cudaGetLastError(), "launch");
114    ck(cudaStreamSynchronize(s), "sync");
115    std::vector<float> got((size_t) rows * (size_t) out_rows);
116    ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y");
117
118    const auto* tr = ggml_get_type_traits(t);
119    std::vector<float> ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols);
120    for (int e = 0; e < n; ++e) {
121        const size_t rb = ggml_row_size(t, cols);
122        for (int64_t o = 0; o < out_rows; ++o)
123            tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols);
124        for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) {
125            const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols;
126            for (int64_t o = 0; o < out_rows; ++o) {
127                double acc = 0;
128                const float* wr = wd.data() + (size_t) o * (size_t) cols;
129                for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k];
130                ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc;
131            }
132        }
133    }
134    double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0;
135    for (size_t i = 0; i < got.size(); ++i) {
136        if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output");
137        const double d = (double) got[i] - ref[i];
138        err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d));
139    }
140    for (int r = 0; r < rows; ++r)
141        if (src[(size_t) r] == rows - 1)   // the zero row
142            for (int64_t o = 0; o < out_rows; ++o)
143                zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o]));
144    const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms;
145    std::printf("%-22s rows %2d experts %d  ref_rms %.4g  rel_l2 %.5f  max/rms %.4f  zero row %.3g\n", name, rows, n, rms,
146                rel, max_abs / rms, zero_max);
147    if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms))
148        throw std::runtime_error(std::string(name) + ": outside the screen");
149}
150}  // namespace
151
152int main() {
153    try {
154        if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; }
155        cudaStream_t s = nullptr;
156        ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
157        {
158            mmq::Context ctx;
159            const std::vector<std::vector<int>> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}};
160            int trial = 0;
161            for (const auto& counts : batches) {
162                const std::string tag = "-" + std::to_string(trial);
163                product(ctx, s, ("Q4_K gate/up" + tag).c_str(), GGML_TYPE_Q4_K, 1280, 2560, counts, trial);
164                product(ctx, s, ("Q5_K gate/up" + tag).c_str(), GGML_TYPE_Q5_K, 1280, 2560, counts, trial + 5);
165                product(ctx, s, ("Q6_K gate/up" + tag).c_str(), GGML_TYPE_Q6_K, 1280, 2560, counts, trial + 17);
166                product(ctx, s, ("Q5_1 down" + tag).c_str(), GGML_TYPE_Q5_1, 2560, 640, counts, trial + 9);
167                product(ctx, s, ("Q8_0 down" + tag).c_str(), GGML_TYPE_Q8_0, 2560, 640, counts, trial + 13);
168                ++trial;
169            }
170        }
171        ck(cudaStreamDestroy(s), "destroy");
172        std::printf("prefill MMQ K-quant screen passed\n");
173        return 0;
174    } catch (const std::exception& e) {
175        std::fprintf(stderr, "prefill MMQ K-quant screen failed: %s\n", e.what());
176        return 1;
177    }
178}