okami.mom/strata

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

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

main
16.4 KiB308 linesraw
1// prefill_mmq_v31_test - the prompt path's MMQ products for the expert formats of the Unsloth v3.1 Qwen3.8-Flash-Next
2// sets (UD-IQ1_M .. UD-IQ4_XS): gate/up IQ2_XXS / IQ2_XS / IQ2_S / IQ3_XXS / IQ4_XS at 1280 x 2560 and down Q2_0 /
3// IQ4_NL / Q8_0 / Q5_0 at 2560 x 640, on synthetic weights quantized by ggml, against a double-precision product of ggml's
4// dequantized weights.  MMQ rounds the activations to q8_1 by design, so this is a screen for layout, stride,
5// expert-bound and row-id errors, not a bit-exactness test (the bounds are those of prefill_mmq_kquant_test).
6//
7// Q5_0 has an MMQ instance only in a build with STRATA_ORCA_Q4KS_MMQ=ON (#296): without it the Q5_0 down product is
8// reported as "not in this build" (the prompt path then dequantizes to FP16 and runs cuBLAS) and does not fail.
9//
10//     prefill_mmq_v31_test [--require-q5_0]        --require-q5_0: a build without the Q5_0 instance fails
11//     prefill_mmq_v31_test --bench [--reps N]       Q5_0 down: MMQ against the dequantize-to-FP16 + cuBLAS route
12//                                                    (what a build without the instance runs), per expert-group size
13#include "strata/kernels/dequant_bf16.hpp"
14#include "strata/prefill/mmq_ids_margin.hpp"
15#include "strata/prefill/moe_mmq.hpp"
16
17#include "ggml.h"
18
19#include <cublas_v2.h>
20#include <cuda_fp16.h>
21#include <cuda_runtime.h>
22
23#include <algorithm>
24#include <chrono>
25#include <cmath>
26#include <cstdint>
27#include <cstdio>
28#include <cstdlib>
29#include <cstring>
30#include <numeric>
31#include <stdexcept>
32#include <string>
33#include <vector>
34
35namespace {
36namespace mmq = strata::prefill::mmq;
37
38void ck(cudaError_t e, const char* what) {
39    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
40}
41
42struct Dev {
43    void* p = nullptr;
44    explicit Dev(size_t n) { ck(cudaMalloc(&p, n), "cudaMalloc"); }
45    ~Dev() { cudaFree(p); }
46    Dev(const Dev&) = delete;
47    Dev& operator=(const Dev&) = delete;
48};
49
50std::vector<uint8_t> make_matrix(ggml_type t, int64_t rows, int64_t cols, int expert, int trial) {
51    std::vector<float> w((size_t) (rows * cols));
52    for (int64_t r = 0; r < rows; ++r)
53        for (int64_t k = 0; k < cols; ++k) {
54            const int code = (int) ((k * 37 + r * 19 + expert * 23 + trial * 11) % 101) - 50;
55            w[(size_t) (r * cols + k)] = 0.025f * std::sin(0.013f * (float) (k + 1) + 0.17f * (float) r + 0.31f * (float) expert) +
56                                         0.0015f * (float) code;
57        }
58    std::vector<uint8_t> out((size_t) rows * ggml_row_size(t, cols));
59    const std::vector<float> imatrix((size_t) cols, 1.0f);
60    ggml_quantize_chunk(t, w.data(), out.data(), 0, rows, cols, ggml_quantize_requires_imatrix(t) ? imatrix.data() : nullptr);
61    return out;
62}
63
64std::vector<float> make_x(int rows, int64_t cols, int trial) {
65    std::vector<float> x((size_t) rows * (size_t) cols);
66    for (int r = 0; r < rows; ++r)
67        for (int64_t k = 0; k < cols; ++k)
68            x[(size_t) r * (size_t) cols + (size_t) k] =
69                0.45f * std::sin(0.009f * (float) (k + 1) + 0.23f * (float) r + 0.07f * (float) trial) +
70                0.17f * std::cos(0.021f * (float) (k + 3) - 0.19f * (float) r) +
71                0.002f * (float) (((k * 7 + r * 13 + trial * 5) % 19) - 9);
72    std::fill(x.end() - cols, x.end(), 0.0f);   // an all-zero row: exactly zero out
73    return x;
74}
75
76std::vector<int32_t> perm(int n, int shift, bool reverse) {
77    std::vector<int32_t> p((size_t) n);
78    for (int i = 0; i < n; ++i) p[(size_t) i] = (int32_t) (((reverse ? n - 1 - i : i) + shift) % n);
79    return p;
80}
81
82// one grouped product: experts side by side at one stride (a zeroed tail after them, as prefill.cpp stages them)
83void product(mmq::Context& ctx, cudaStream_t s, const char* name, ggml_type t, int64_t out_rows, int64_t cols,
84             const std::vector<int>& counts, int trial) {
85    const int n = (int) counts.size(), rows = std::accumulate(counts.begin(), counts.end(), 0);
86    std::vector<int32_t> bounds((size_t) n + 1, 0);
87    for (int e = 0; e < n; ++e) bounds[(size_t) e + 1] = bounds[(size_t) e] + counts[(size_t) e];
88    const auto src = perm(rows, trial + 1, false), dst = perm(rows, trial + 2, true);
89    const std::vector<float> x = make_x(rows, cols, trial);
90    const size_t eb = mmq::matrix_bytes((int) t, out_rows, cols);
91    if (eb != (size_t) out_rows * ggml_row_size(t, cols)) throw std::runtime_error(std::string(name) + ": matrix_bytes");
92    std::vector<std::vector<uint8_t>> ws;
93    std::vector<uint8_t> w((size_t) n * eb + 4096, 0);
94    for (int e = 0; e < n; ++e) {
95        ws.push_back(make_matrix(t, out_rows, cols, e, trial));
96        std::copy(ws.back().begin(), ws.back().end(), w.begin() + (ptrdiff_t) ((size_t) e * eb));
97    }
98    // 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)
99    // 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)
100    const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) *std::max_element(counts.begin(), counts.end()));
101    std::vector<int32_t> dst_table(dst);
102    dst_table.resize(ids_rows, 0);
103    Dev dx(x.size() * 4), dsrc((size_t) rows * 4), ddst(ids_rows * 4), db(bounds.size() * 4), dw(w.size()),
104        dxq(mmq::q8_bytes(rows, cols)), dy((size_t) rows * (size_t) out_rows * 4);
105    ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
106    ck(cudaMemcpy(dsrc.p, src.data(), src.size() * 4, cudaMemcpyHostToDevice), "src");
107    ck(cudaMemcpy(ddst.p, dst_table.data(), dst_table.size() * 4, cudaMemcpyHostToDevice), "dst");
108    ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "bounds");
109    ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
110    ck(cudaMemset(dy.p, 0xff, (size_t) rows * (size_t) out_rows * 4), "sentinel");
111    ck(cudaDeviceSynchronize(), "inputs");
112    mmq::quantize((const float*) dx.p, (const int32_t*) dsrc.p, dxq.p, (int) t, cols, cols, rows, s);
113    mmq::Product p;
114    p.w = dw.p; p.type = (int) t; p.w_rows = out_rows; p.w_cols = cols; p.expert_bytes = eb; p.n = n;
115    p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) ddst.p; p.total_rows = rows;
116    p.max_rows = *std::max_element(counts.begin(), counts.end()); p.dst = (float*) dy.p; p.ld_dst = out_rows;
117    ctx.run(p, s);
118    ck(cudaGetLastError(), "launch");
119    ck(cudaStreamSynchronize(s), "sync");
120    std::vector<float> got((size_t) rows * (size_t) out_rows);
121    ck(cudaMemcpy(got.data(), dy.p, got.size() * 4, cudaMemcpyDeviceToHost), "y");
122
123    const auto* tr = ggml_get_type_traits(t);
124    std::vector<float> ref(got.size(), 0.0f), wd((size_t) out_rows * (size_t) cols);
125    for (int e = 0; e < n; ++e) {
126        const size_t rb = ggml_row_size(t, cols);
127        for (int64_t o = 0; o < out_rows; ++o)
128            tr->to_float(ws[(size_t) e].data() + (size_t) o * rb, wd.data() + (size_t) o * (size_t) cols, cols);
129        for (int r = bounds[(size_t) e]; r < bounds[(size_t) e + 1]; ++r) {
130            const float* xr = x.data() + (size_t) src[(size_t) r] * (size_t) cols;
131            for (int64_t o = 0; o < out_rows; ++o) {
132                double acc = 0;
133                const float* wr = wd.data() + (size_t) o * (size_t) cols;
134                for (int64_t k = 0; k < cols; ++k) acc += (double) wr[k] * xr[k];
135                ref[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o] = (float) acc;
136            }
137        }
138    }
139    double err2 = 0, ref2 = 0, max_abs = 0, zero_max = 0;
140    for (size_t i = 0; i < got.size(); ++i) {
141        if (!std::isfinite(got[i])) throw std::runtime_error(std::string(name) + ": unwritten or non-finite output");
142        const double d = (double) got[i] - ref[i];
143        err2 += d * d; ref2 += (double) ref[i] * ref[i]; max_abs = std::max(max_abs, std::fabs(d));
144    }
145    for (int r = 0; r < rows; ++r)
146        if (src[(size_t) r] == rows - 1)   // the zero row
147            for (int64_t o = 0; o < out_rows; ++o)
148                zero_max = std::max(zero_max, (double) std::fabs(got[(size_t) dst[(size_t) r] * (size_t) out_rows + (size_t) o]));
149    const double rms = std::sqrt(ref2 / (double) ref.size()), rel = std::sqrt(err2 / (double) ref.size()) / rms;
150    std::printf("%-22s rows %2d experts %d  ref_rms %.4g  rel_l2 %.5f  max/rms %.4f  zero row %.3g\n", name, rows, n, rms,
151                rel, max_abs / rms, zero_max);
152    if (rel > 0.04 || max_abs / rms > 0.35 || zero_max > std::max(1e-5, 1e-4 * rms))
153        throw std::runtime_error(std::string(name) + ": outside the screen");
154}
155
156// ---- --bench: Q5_0 down, MMQ against dequantize-to-FP16 + cuBLAS, per expert group -------------------------------
157double median(std::vector<double> v) {
158    std::sort(v.begin(), v.end());
159    return v[v.size() / 2];
160}
161
162template <class F>
163double time_ms(F fn, cudaStream_t s, int reps, int rounds) {
164    cudaEvent_t e0, e1;
165    cudaEventCreate(&e0);
166    cudaEventCreate(&e1);
167    std::vector<double> r;
168    for (int k = 0; k < rounds; ++k) {
169        cudaEventRecord(e0, s);
170        for (int i = 0; i < reps; ++i) fn();
171        cudaEventRecord(e1, s);
172        cudaEventSynchronize(e1);
173        float ms = 0;
174        cudaEventElapsedTime(&ms, e0, e1);
175        r.push_back(ms / reps);
176    }
177    cudaEventDestroy(e0);
178    cudaEventDestroy(e1);
179    return median(r);
180}
181
182void bench(ggml_type t, int reps) {
183    cudaStream_t s = nullptr;
184    ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
185    cublasHandle_t h;
186    if (cublasCreate(&h) != CUBLAS_STATUS_SUCCESS) throw std::runtime_error("cublasCreate");
187    cublasSetStream(h, s);
188    cublasSetMathMode(h, CUBLAS_DEFAULT_MATH);
189    const bool have_mmq = mmq::supported((int) t);
190    constexpr int64_t N = 2560, FF = 640;
191    constexpr int NE = 16;   // experts a group holds (kGatherGroupMax)
192    std::printf("bench %s down [%lld x %lld], %d experts a group, median of 5 rounds x %d calls\n", ggml_type_name(t),
193                (long long) N, (long long) FF, NE, reps);
194    std::printf("%-8s %12s %12s %12s %8s\n", "rows/exp", "MMQ ms", "f16+cuBLAS ms", "(dequant ms)", "ratio");
195    const size_t eb = (size_t) N * ggml_row_size(t, FF);
196    std::vector<uint8_t> w((size_t) NE * eb + 4096, 0);
197    for (int e = 0; e < NE; ++e) {
198        auto m = make_matrix(t, N, FF, e, 1);
199        std::copy(m.begin(), m.end(), w.begin() + (ptrdiff_t) ((size_t) e * eb));
200    }
201    Dev dw(w.size());
202    ck(cudaMemcpy(dw.p, w.data(), w.size(), cudaMemcpyHostToDevice), "w");
203    mmq::Context ctx;
204    for (int per : {16, 64, 256, 1024}) {
205        const int rows = per * NE;
206        const std::vector<float> x = make_x(rows, FF, 3);
207        const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) per);   // (the identity over the whole table: mmq_ids_margin.hpp)
208        std::vector<int32_t> bounds((size_t) NE + 1), iota(ids_rows);
209        for (int e = 0; e <= NE; ++e) bounds[(size_t) e] = e * per;
210        std::iota(iota.begin(), iota.end(), 0);
211        Dev dx(x.size() * 4), db(bounds.size() * 4), di(iota.size() * 4), dxq(mmq::q8_bytes(rows, FF)),
212            dy((size_t) rows * N * 4), dwh((size_t) N * FF * 2), dxh((size_t) rows * FF * 2);
213        ck(cudaMemcpy(dx.p, x.data(), x.size() * 4, cudaMemcpyHostToDevice), "x");
214        ck(cudaMemcpy(db.p, bounds.data(), bounds.size() * 4, cudaMemcpyHostToDevice), "b");
215        ck(cudaMemcpy(di.p, iota.data(), iota.size() * 4, cudaMemcpyHostToDevice), "i");
216        std::vector<__half> xh(x.size());
217        for (size_t i = 0; i < x.size(); ++i) xh[i] = __float2half(x[i]);
218        ck(cudaMemcpy(dxh.p, xh.data(), xh.size() * 2, cudaMemcpyHostToDevice), "xh");
219        ck(cudaDeviceSynchronize(), "setup");
220        double t_mmq = -1;
221        if (have_mmq) {
222            mmq::Product p;
223            p.w = dw.p; p.type = (int) t; p.w_rows = N; p.w_cols = FF; p.expert_bytes = eb; p.n = NE;
224            p.xq = dxq.p; p.bounds = (const int32_t*) db.p; p.ids = (const int32_t*) di.p; p.total_rows = rows;
225            p.max_rows = per; p.dst = (float*) dy.p; p.ld_dst = N;
226            t_mmq = time_ms([&] {
227                mmq::quantize((const float*) dx.p, nullptr, dxq.p, (int) t, FF, FF, rows, s);
228                ctx.run(p, s);
229            }, s, reps, 5);
230        }
231        const float one = 1.f, zero = 0.f;
232        // the non-MMQ route: per expert, dequantize its matrix to FP16 and one HGEMM over its rows (what prefill.cpp does
233        // for a type without an instance); the dequantize alone is timed too
234        const double t_deq = time_ms([&] {
235            for (int e = 0; e < NE; ++e)
236                strata::kernels::dequant_f16((int) t, (const uint8_t*) dw.p + (size_t) e * eb, 0, N, FF, (uint16_t*) dwh.p, s);
237        }, s, reps, 5);
238        const double t_f16 = time_ms([&] {
239            for (int e = 0; e < NE; ++e) {
240                strata::kernels::dequant_f16((int) t, (const uint8_t*) dw.p + (size_t) e * eb, 0, N, FF, (uint16_t*) dwh.p, s);
241                cublasGemmEx(h, CUBLAS_OP_T, CUBLAS_OP_N, (int) N, per, (int) FF, &one, dwh.p, CUDA_R_16F, (int) FF,
242                             (const __half*) dxh.p + (size_t) e * per * FF, CUDA_R_16F, (int) FF, &zero,
243                             (float*) dy.p + (size_t) e * per * N, CUDA_R_32F, (int) N, CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
244            }
245        }, s, reps, 5);
246        if (have_mmq) std::printf("%-8d %12.4f %12.4f %12.4f %7.2fx\n", per, t_mmq, t_f16, t_deq, t_f16 / t_mmq);
247        else std::printf("%-8d %12s %12.4f %12.4f %8s\n", per, "(no instance)", t_f16, t_deq, "-");
248    }
249    cublasDestroy(h);
250    ck(cudaStreamDestroy(s), "destroy");
251}
252}  // namespace
253
254int main(int argc, char** argv) {
255    try {
256        bool bench_mode = false, require_q5 = false;
257        int reps = 20;
258        for (int i = 1; i < argc; ++i) {
259            if (!std::strcmp(argv[i], "--bench")) bench_mode = true;
260            else if (!std::strcmp(argv[i], "--require-q5_0")) require_q5 = true;
261            else if (!std::strcmp(argv[i], "--reps") && i + 1 < argc) reps = std::atoi(argv[++i]);
262        }
263        if (!mmq::built()) { std::printf("no MMQ in this build\n"); return 1; }
264        int nd = 0;
265        if (cudaGetDeviceCount(&nd) != cudaSuccess || nd == 0) { std::printf("no CUDA device\n"); return 77; }
266        if (bench_mode) {
267            bench(GGML_TYPE_Q5_0, reps);
268            return 0;
269        }
270        cudaStream_t s = nullptr;
271        ck(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), "stream");
272        int skipped = 0;
273        {
274            mmq::Context ctx;
275            const std::vector<std::vector<int>> batches{{1, 3, 3}, {4, 1, 2}, {2, 3}, {17}};
276            struct Case { const char* name; ggml_type t; int64_t out_rows, cols; int salt; };
277            const Case cases[] = {
278                {"IQ2_XXS gate/up", GGML_TYPE_IQ2_XXS, 1280, 2560, 0}, {"IQ2_XS gate/up", GGML_TYPE_IQ2_XS, 1280, 2560, 3},
279                {"IQ2_S gate/up", GGML_TYPE_IQ2_S, 1280, 2560, 5},     {"IQ3_XXS gate/up", GGML_TYPE_IQ3_XXS, 1280, 2560, 7},
280                {"IQ4_XS gate/up", GGML_TYPE_IQ4_XS, 1280, 2560, 11},  {"Q2_0 down", GGML_TYPE_Q2_0, 2560, 640, 13},
281                {"IQ4_NL down", GGML_TYPE_IQ4_NL, 2560, 640, 17},      {"Q8_0 down", GGML_TYPE_Q8_0, 2560, 640, 19},
282                {"Q5_0 down", GGML_TYPE_Q5_0, 2560, 640, 23},
283            };
284            int trial = 0;
285            for (const auto& counts : batches) {
286                const std::string tag = "-" + std::to_string(trial);
287                for (const Case& c : cases) {
288                    if (!mmq::supported((int) c.t)) {
289                        if (trial == 0) {
290                            std::printf("%-22s not in this build (the prompt path dequantizes to FP16)\n", c.name);
291                            if (c.t == GGML_TYPE_Q5_0) { ++skipped; if (require_q5) throw std::runtime_error("Q5_0 MMQ required"); }
292                            else throw std::runtime_error(std::string(c.name) + ": MMQ must cover this format");
293                        }
294                        continue;
295                    }
296                    product(ctx, s, (std::string(c.name) + tag).c_str(), c.t, c.out_rows, c.cols, counts, trial + c.salt);
297                }
298                ++trial;
299            }
300        }
301        ck(cudaStreamDestroy(s), "destroy");
302        std::printf("prefill MMQ v3.1 screen passed%s\n", skipped ? " (Q5_0 not built)" : "");
303        return 0;
304    } catch (const std::exception& e) {
305        std::fprintf(stderr, "prefill MMQ v3.1 screen failed: %s\n", e.what());
306        return 1;
307    }
308}