okami.mom/strata

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

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

main
14.4 KiB281 linesraw
1// prefill_ws_parity_test - the weight-stationary expert products of PR #3752 (STRATA_MMQ_WS, GP100) against the per-group
2// MMQ they replace, byte for byte, on random experts (GPU, synthetic data, no model).
3//
4// A layer of E resident experts (random gate/up [1280 x 2560] and down [2560 x 640] blocks with sane fp16 scales, laid out
5// as the expert cache holds them: gate rows then up rows, the down matrix at down_off) gets random activations, quantized
6// as the prompt path does (mmq::quantize), and a routing of random row counts per expert (1 .. 300 rows, so u spans the
7// measured range, some experts with one row).  The reference is mmq::Context::run per expert (gate/up, then
8// swiglu + quantize, then down), i.e. what Prefill does per 16-expert group; the candidate is ws::gate_up, ONE
9// mmq::swiglu_quant over all rows and ws::down.  Compared: GU (floats), Hq (the q8_1 bytes) and Dm (floats) of every row.
10// The down is also run alone on the reference Hq, so a difference points at the product. For the IQ4_NL down the run
11// repeats with STRATA_WS_FAST on (ws::set_fast(1)); the same Dm is required.
12//
13// The kernels were written for GP100 (the integer sums are exact, the float epilogue follows MMQ's sm_60 SASS), so the
14// verdict is only given on a compute capability 6.0 card; on another card the kernels are run too (ws::set_mode(1))
15// and the counts printed for information, with exit 77.  Needs the CUDA build with STRATA_EXPERIMENTAL_SM60.
16//
17//   prefill_ws_parity_test [--device N] [--any]    exit 0: all identical (cc 6.0); 77: other card; 1: a difference
18#include "strata/prefill/mmq_ids_margin.hpp"
19#include "strata/prefill/moe_mmq.hpp"
20#include "strata/prefill/moe_ws.hpp"
21
22#include "ggml.h"
23
24#include <cuda_runtime.h>
25
26#include <algorithm>
27#include <cmath>
28#include <cstdint>
29#include <cstdio>
30#include <cstdlib>
31#include <cstring>
32#include <numeric>
33#include <random>
34#include <stdexcept>
35#include <string>
36#include <vector>
37
38namespace {
39namespace mmq = strata::prefill::mmq;
40namespace ws = strata::prefill::ws;
41
42void ck(cudaError_t e, const char* what) {
43    if (e != cudaSuccess) throw std::runtime_error(std::string(what) + ": " + cudaGetErrorString(e));
44}
45
46struct Dev {
47    void* p = nullptr;
48    size_t n = 0;
49    explicit Dev(size_t bytes) : n(bytes) {
50        ck(cudaMalloc(&p, bytes + 256), "cudaMalloc");
51        ck(cudaMemset(p, 0, bytes + 256), "cudaMemset");
52    }
53    ~Dev() { cudaFree(p); }
54    Dev(const Dev&) = delete;
55    Dev& operator=(const Dev&) = delete;
56    template <class T> T* as() const { return (T*) p; }
57    template <class T> void up(const std::vector<T>& h) { ck(cudaMemcpy(p, h.data(), h.size() * sizeof(T), cudaMemcpyHostToDevice), "upload"); }
58    template <class T> std::vector<T> down(size_t count) const {
59        std::vector<T> h(count);
60        ck(cudaMemcpy(h.data(), p, count * sizeof(T), cudaMemcpyDeviceToHost), "download");
61        return h;
62    }
63};
64
65constexpr int64_t kNEmbd = 2560, kNFF = 640, kGuRows = 1280;
66
67// random blocks of `type` for a [rows x cols] matrix; every block starts with its fp16 scale d: a finite value in
68// [2^-6, 2^-5) (all the formats used here put d first)
69std::vector<uint8_t> random_matrix(ggml_type type, int64_t rows, int64_t cols, std::mt19937& rng) {
70    const size_t bytes = mmq::matrix_bytes((int) type, rows, cols);
71    const size_t bs = ggml_type_size(type);
72    std::vector<uint8_t> w(bytes);
73    for (auto& b : w) b = (uint8_t) rng();
74    for (size_t o = 0; o + bs <= bytes; o += bs) {
75        const uint16_t d = (uint16_t) ((9u << 10) | (rng() & 0x3FFu));
76        std::memcpy(&w[o], &d, 2);
77    }
78    return w;
79}
80
81size_t count_diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t n) {
82    size_t d = 0;
83    for (size_t i = 0; i < n; ++i) d += a[i] != b[i];
84    return d;
85}
86
87// the largest |a - b| over the largest |a|, both float arrays in byte form (how far apart two results are in rounding terms)
88double max_norm_err(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, size_t bytes) {
89    const float* x = (const float*) a.data();
90    const float* y = (const float*) b.data();
91    double mx = 0.0, err = 0.0;
92    for (size_t i = 0; i < bytes / 4; ++i) {
93        mx = std::max(mx, (double) std::fabs(x[i]));
94        err = std::max(err, (double) std::fabs(x[i] - y[i]));
95    }
96    return mx > 0.0 ? err / mx : err;
97}
98
99struct Result {
100    size_t gu = 0, hq = 0, dm = 0, dm_ref_hq = 0, dm_fast = 0, fast_vs_default = 0;
101    double e_gu = 0, e_dm = 0, e_dm_rh = 0;   // normalized max errors against the reference
102    bool ran = true;
103};
104
105Result run_case(ggml_type gt, ggml_type dt, const std::vector<int32_t>& cnt, uint32_t seed, bool test_fast) {
106    std::mt19937 rng(seed);
107    const int E = (int) cnt.size();
108    std::vector<int32_t> bounds(E + 1, 0);
109    for (int j = 0; j < E; ++j) bounds[j + 1] = bounds[j] + cnt[j];
110    const int64_t rows = bounds[E];
111    const size_t gub = mmq::matrix_bytes((int) gt, kGuRows, kNEmbd), db = mmq::matrix_bytes((int) dt, kNEmbd, kNFF);
112    const size_t stride = (gub + db + 255) / 256 * 256;
113    // the layer's experts, "resident" in one buffer at 256-byte aligned offsets (the expert cache's slots)
114    std::vector<uint8_t> blob((size_t) E * stride, 0);
115    std::vector<int64_t> xoff(E);
116    for (int j = 0; j < E; ++j) {
117        xoff[j] = (int64_t) j * (int64_t) stride;
118        const auto g = random_matrix(gt, kGuRows, kNEmbd, rng), d = random_matrix(dt, kNEmbd, kNFF, rng);
119        std::memcpy(&blob[(size_t) xoff[j]], g.data(), gub);
120        std::memcpy(&blob[(size_t) xoff[j] + gub], d.data(), db);
121    }
122    std::normal_distribution<float> nd(0.0f, 1.0f);
123    std::vector<float> x((size_t) (rows * kNEmbd));
124    for (auto& v : x) v = nd(rng) * 0.7f;
125
126    const size_t xqb = mmq::q8_bytes(rows, kNEmbd), hqb = mmq::q8_bytes(rows, kNFF);
127    Dev dblob(blob.size()), dx(x.size() * 4), dxq(xqb), dbnd((size_t) (E + 1) * 4), dxoff((size_t) E * 8);
128    const size_t ids_rows = (size_t) mmq::mmq_ids_table_rows((uint64_t) rows, (uint64_t) rows);   // (mul_mat_q reads the row table past its last row: mmq_ids_margin.hpp)
129    Dev dident(ids_rows * 4), dgu_ref((size_t) rows * kGuRows * 4), dgu((size_t) rows * kGuRows * 4);
130    Dev dh((size_t) rows * kNFF * 4), dhq_ref(hqb), dhq(hqb), ddm_ref((size_t) rows * kNEmbd * 4), ddm((size_t) rows * kNEmbd * 4),
131        ddm_rh((size_t) rows * kNEmbd * 4), ddm_fast((size_t) rows * kNEmbd * 4);
132    dblob.up(blob); dx.up(x); dbnd.up(bounds); dxoff.up(xoff);
133    std::vector<int32_t> ident(ids_rows);
134    for (size_t i = 0; i < ids_rows; ++i) ident[i] = (int32_t) i;
135    dident.up(ident);
136    mmq::quantize(dx.as<float>(), nullptr, dxq.p, (int) gt, kNEmbd, kNEmbd, rows, nullptr);
137
138    // the reference: per expert, as a one-expert group (absolute rows)
139    mmq::Context ctx;
140    for (int j = 0; j < E; ++j) {
141        mmq::Product gu;
142        gu.w = dblob.as<uint8_t>() + xoff[j]; gu.type = (int) gt; gu.w_rows = kGuRows; gu.w_cols = kNEmbd; gu.expert_bytes = gub;
143        gu.n = 1; gu.xq = dxq.p; gu.bounds = dbnd.as<int32_t>() + j; gu.ids = dident.as<int32_t>();
144        gu.total_rows = rows; gu.max_rows = cnt[j]; gu.dst = dgu_ref.as<float>(); gu.ld_dst = kGuRows;
145        ctx.run(gu, nullptr);
146    }
147    mmq::swiglu(dgu_ref.as<float>(), dh.as<float>(), rows, kNFF, false, nullptr);
148    mmq::quantize(dh.as<float>(), nullptr, dhq_ref.p, (int) dt, kNFF, kNFF, rows, nullptr);
149    for (int j = 0; j < E; ++j) {
150        mmq::Product dn;
151        dn.w = dblob.as<uint8_t>() + xoff[j] + gub; dn.type = (int) dt; dn.w_rows = kNEmbd; dn.w_cols = kNFF; dn.expert_bytes = db;
152        dn.n = 1; dn.xq = dhq_ref.p; dn.bounds = dbnd.as<int32_t>() + j; dn.ids = dident.as<int32_t>();
153        dn.total_rows = rows; dn.max_rows = cnt[j]; dn.dst = ddm_ref.as<float>(); dn.ld_dst = kNEmbd;
154        ctx.run(dn, nullptr);
155    }
156    ck(cudaDeviceSynchronize(), "reference");
157
158    // the candidate
159    std::vector<int32_t> order(E);
160    for (int j = 0; j < E; ++j) order[j] = j;
161    std::vector<ws::Chunk> chunks(ws::max_chunks(rows, E));
162    const size_t nch = ws::chunks(order.data(), (size_t) E, cnt.data(), bounds.data(), chunks.data());
163    chunks.resize(nch);
164    Dev dch(std::max<size_t>(1, nch) * sizeof(ws::Chunk));
165    dch.up(chunks);
166    ws::Layer L;
167    L.gu_type = (int) gt; L.d_type = (int) dt; L.w = dblob.p; L.xoff = dxoff.as<int64_t>(); L.down_off = (int64_t) gub;
168    L.chunks = dch.as<ws::Chunk>(); L.nchunks = (int64_t) nch; L.rows = rows; L.n = E; L.xq = dxq.p; L.gu = dgu.as<float>();
169    L.hq = dhq.p; L.dm = ddm.as<float>();
170    Result r;
171    if (!ws::gate_up(L, nullptr)) { r.ran = false; return r; }
172    mmq::swiglu_quant(dgu.as<float>(), dhq.p, rows, false, nullptr);
173    ws::down(L, nullptr);
174    ck(cudaDeviceSynchronize(), "candidate");
175    // the down alone on the reference H (a difference above this one is the gate/up's)
176    ws::Layer L2 = L;
177    L2.hq = dhq_ref.p; L2.dm = ddm_rh.as<float>();
178    ws::down(L2, nullptr);
179    if (test_fast) {
180        ws::set_fast(1);
181        ws::Layer L3 = L;
182        L3.dm = ddm_fast.as<float>();
183        ws::down(L3, nullptr);
184        ws::set_fast(-1);
185    }
186    ck(cudaDeviceSynchronize(), "candidate (down alone, fast)");
187
188    const size_t gun = (size_t) rows * kGuRows * 4, dmn = (size_t) rows * kNEmbd * 4;
189    const auto gur = dgu_ref.down<uint8_t>(gun), gun_c = dgu.down<uint8_t>(gun);
190    r.gu = count_diff(gur, gun_c, gun);
191    r.e_gu = max_norm_err(gur, gun_c, gun);
192    r.hq = count_diff(dhq_ref.down<uint8_t>(hqb), dhq.down<uint8_t>(hqb), hqb);
193    const auto dmr = ddm_ref.down<uint8_t>(dmn);
194    const auto dmc = ddm.down<uint8_t>(dmn), dmh = ddm_rh.down<uint8_t>(dmn);
195    r.dm = count_diff(dmr, dmc, dmn);
196    r.dm_ref_hq = count_diff(dmr, dmh, dmn);
197    r.e_dm = max_norm_err(dmr, dmc, dmn);
198    r.e_dm_rh = max_norm_err(dmr, dmh, dmn);
199    if (test_fast) {
200        const auto dmf = ddm_fast.down<uint8_t>(dmn);
201        r.dm_fast = count_diff(dmr, dmf, dmn);
202        r.fast_vs_default = count_diff(dmc, dmf, dmn);   // STRATA_WS_FAST: the same bits as the default kernel, on any card
203    }
204    return r;
205}
206
207std::vector<int32_t> counts(int E, int lo, int hi, std::mt19937& rng) {
208    std::vector<int32_t> c(E);
209    for (auto& v : c) v = lo + (int32_t) (rng() % (uint32_t) (hi - lo + 1));
210    return c;
211}
212}  // namespace
213
214int main(int argc, char** argv) {
215    int device = 0;
216    bool any = false;
217    for (int i = 1; i < argc; ++i) {
218        if (std::strcmp(argv[i], "--device") == 0 && i + 1 < argc) device = std::atoi(argv[++i]);
219        else if (std::strcmp(argv[i], "--any") == 0) any = true;
220        else {
221            std::fprintf(stderr, "usage: prefill_ws_parity_test [--device N] [--any]\n");
222            return 2;
223        }
224    }
225    int ndev = 0;
226    if (cudaGetDeviceCount(&ndev) != cudaSuccess || ndev == 0) {
227        std::puts("prefill_ws_parity_test: no CUDA device (skipped)");
228        return 77;
229    }
230    try {
231        ck(cudaSetDevice(device), "cudaSetDevice");
232        cudaDeviceProp prop{};
233        ck(cudaGetDeviceProperties(&prop, device), "cudaGetDeviceProperties");
234        const bool gp100 = prop.major == 6 && prop.minor == 0;
235        std::printf("prefill_ws_parity_test on %s (%d.%d)%s\n", prop.name, prop.major, prop.minor,
236                    gp100 ? "" : ": not a GP100, so the counts are for information only");
237        if (!gp100 && !any) {
238            std::puts("prefill_ws_parity_test: not a compute capability 6.0 card (skipped; --any runs it for information)");
239            return 77;
240        }
241        ws::set_mode(1);
242        std::mt19937 rng(20261026u);
243        const ggml_type gus[] = {GGML_TYPE_IQ2_XXS, GGML_TYPE_IQ2_XS, GGML_TYPE_IQ2_S, GGML_TYPE_IQ3_XXS, GGML_TYPE_IQ3_S};
244        const ggml_type dns[] = {GGML_TYPE_Q2_0, GGML_TYPE_IQ4_NL};
245        size_t total_diff = 0, total_fast = 0;
246        double worst_err = 0.0;
247        int cases = 0, declined = 0;
248        for (ggml_type gt : gus)
249            for (ggml_type dt : dns) {
250                // a spread of rows per expert (u from ~2 to ~150), and a tiny layer with one-row experts
251                const std::vector<std::vector<int32_t>> shapes = {counts(24, 1, 12, rng), counts(24, 5, 40, rng),
252                                                                  counts(20, 60, 300, rng), {1, 2, 65, 1, 64, 63}};
253                for (const auto& cnt : shapes) {
254                    const Result r = run_case(gt, dt, cnt, 1000u + (uint32_t) cases, dt == GGML_TYPE_IQ4_NL);
255                    ++cases;
256                    if (!r.ran) { ++declined; std::printf("  %-8s -> %-6s %zu experts: ws declined (not faster here)\n", ggml_type_name(gt), ggml_type_name(dt), cnt.size()); continue; }
257                    const size_t bad = r.gu + r.hq + r.dm + r.dm_ref_hq + r.dm_fast;
258                    total_diff += gp100 ? bad : 0;
259                    total_fast += r.fast_vs_default;
260                    worst_err = std::max(worst_err, std::max(r.e_gu, r.e_dm_rh));   // Dm after the full chain also carries int8 flips of H
261                    std::printf("  %-8s -> %-6s %2zu experts %5d rows: bytes differ GU %zu  Hq %zu  Dm %zu  Dm(down alone) %zu  Dm(fast) %zu"
262                                "  fast vs default %zu | max error / max value: GU %.2e  Dm %.2e  Dm(down alone) %.2e%s\n",
263                                ggml_type_name(gt), ggml_type_name(dt), cnt.size(),
264                                (int) std::accumulate(cnt.begin(), cnt.end(), 0), r.gu, r.hq, r.dm, r.dm_ref_hq, r.dm_fast,
265                                r.fast_vs_default, r.e_gu, r.e_dm, r.e_dm_rh, gp100 && bad ? "  <-- FAIL" : "");
266                }
267            }
268        if (!gp100) {   // no verdict on this card: the float epilogue of its MMQ is not the one the kernels follow
269            std::printf("prefill_ws_parity_test (information, %s): %d cases (%d declined), STRATA_WS_FAST vs default: %zu differing bytes, "
270                        "largest GU / down-alone error against this card's MMQ %.2e of the largest value -> %s\n", prop.name, cases, declined,
271                        total_fast, worst_err, total_fast == 0 && worst_err < 1e-5 && declined < cases ? "consistent" : "INCONSISTENT");
272            return total_fast == 0 && worst_err < 1e-5 && declined < cases ? 77 : 1;
273        }
274        std::printf("prefill_ws_parity_test: %d cases (%d declined), %zu differing bytes, STRATA_WS_FAST vs default %zu -> %s\n", cases,
275                    declined, total_diff, total_fast, total_diff == 0 && total_fast == 0 && declined < cases ? "PASS" : "FAIL");
276        return total_diff == 0 && total_fast == 0 && declined < cases ? 0 : 1;
277    } catch (const std::exception& e) {
278        std::fprintf(stderr, "prefill_ws_parity_test: %s\n", e.what());
279        return 1;
280    }
281}