okami.mom/strata

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

waveringanaedge0-strata: add the engine for Edge0 145B and Edge0 120Bfd19246dc

main
17.7 KiB331 linesraw
1// src/prefill/lat_q3k_down_test.cpp - M1 of the q3k latent A stage: the down half (IQ4_NL, K = 640) against
2// native_expert_grouped's own down, on the same staged H it produced (its phase knob stops it after the q8_1 of H,
3// then runs only the down).  Two things are checked:
4//   1. numbers: 128 groups x 4 entries of real quantized weights at 128 distinct blob addresses, against the
5//      reference and against a double-precision CPU dot of the same weights and the same H row;
6//   2. speed: the engine's shapes (entries per group 4 / 32 / 200 / 1400, ~4000 entries a call) against the
7//      reference's down on the same data.
8// Acceptance (q3k_fused/BRIEF.md): rel_mean <= 1e-3, cos_min >= 0.9999, no non-zero row under 0.99.
9#include "strata/prefill/lat_q3k_down.hpp"
10#include "strata/prefill/moe_mmq.hpp"
11#include "strata/kernels/iq_kernels.hpp"
12
13#include <cuda_runtime.h>
14#include <ggml.h>
15
16#include <algorithm>
17#include <cmath>
18#include <cstdio>
19#include <cstdlib>
20#include <cstring>
21#include <random>
22#include <vector>
23
24namespace mmq = strata::prefill::mmq;
25#define CK(e) do { const cudaError_t r_ = (e); if (r_ != cudaSuccess) { \
26    std::printf("FAIL %s: %s\n", #e, cudaGetErrorString(r_)); std::exit(1); } } while (0)
27
28namespace {
29
30constexpr int64_t ELL = 1280, FF = 640;
31constexpr int kNB = (int) (FF / 32);        // a plain q8_1 H row: 20 blocks of 36 B
32constexpr int kXNB = (int) (ELL / 32);      // the gate/up input row: n_embd / 32 = 40 blocks of 36 B
33constexpr int kChunks = (int) (FF / 64);    // the staged H row: 10 chunks of 80 B
34constexpr int kMaxE = 4500, kMaxG = 1024;   // the sweep's largest call (entries, groups)
35
36// One q8_1 block as the engine's quantizer stores it: {half d, half s, int8 qs[32]}.
37struct H8 { uint16_t d, s; int8_t qs[32]; };
38
39// A plain q8_1 H row (20 x 36 B) into the staged activation rows lat_q3k_down reads: per 64 values, the two 32-value
40// blocks' 64 codes in q8_1_store's order (a sub-block's byte p holds its value 4 * (p & 3) + (p >> 2)), then the
41// blocks' d's at 64.  This is the layout moe_fused.cu's latent gate/up epilogue writes for the down to read.
42void stage_h(const std::vector<H8>& q8, int64_t rows, std::vector<uint8_t>& out) {
43    out.assign((size_t) rows * kChunks * 80, 0);
44    for (int64_t r = 0; r < rows; ++r) {
45        for (int kb = 0; kb < kChunks; ++kb) {
46            uint8_t* dst = out.data() + ((size_t) r * kChunks + kb) * 80;
47            for (int b = 0; b < 2; ++b) {
48                const H8& blk = q8[(size_t) r * kNB + 2 * kb + b];
49                std::memcpy(dst + 64 + 2 * b, &blk.d, 2);
50                for (int h = 0; h < 2; ++h)
51                    for (int j = 0; j < 16; ++j)
52                        dst[16 * (2 * b + h) + 4 * (j & 3) + (j >> 2)] = (uint8_t) blk.qs[16 * h + j];
53            }
54        }
55    }
56}
57
58// The IQ4_NL codebook (ggml-common.h, kvalues_iq4nl) and a double-precision dot of the same weights against the
59// same q8_1 H row - the arbiter between this kernel and native_expert_grouped when the two disagree.
60const int8_t kIQ4[16] = {-127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113};
61
62double cpu_dot(const uint8_t* dn, const H8* hq_row, int row) {
63    const uint8_t* wr = dn + (size_t) row * 360;
64    double s = 0;
65    for (int b = 0; b < 20; ++b) {
66        const uint8_t* blk = wr + 18 * b;
67        uint16_t dh;
68        std::memcpy(&dh, blk, 2);
69        const double dw = (double) ggml_fp16_to_fp32(dh);
70        const double d8 = (double) ggml_fp16_to_fp32(hq_row[b].d);
71        for (int j = 0; j < 16; ++j) {
72            const double wl = dw * (double) kIQ4[blk[2 + j] & 0xF], wh = dw * (double) kIQ4[blk[2 + j] >> 4];
73            s += wl * (d8 * (double) hq_row[b].qs[j]) + wh * (d8 * (double) hq_row[b].qs[16 + j]);
74        }
75    }
76    return s;
77}
78
79unsigned long long fnv(const std::vector<float>& v) {
80    unsigned long long h = 1469598103934665603ULL;
81    for (float f : v) { uint32_t u; std::memcpy(&u, &f, 4); h = (h ^ u) * 1099511628211ULL; }
82    return h;
83}
84
85}  // namespace
86
87int main() {
88    constexpr int G = 128, EPG = 4, E = G * EPG;
89    const size_t gub = mmq::matrix_bytes(GGML_TYPE_Q3_K, 1280, ELL);    // gate 640 rows + up 640 rows
90    const size_t dnb = mmq::matrix_bytes(GGML_TYPE_IQ4_NL, ELL, FF);    // down 1280 x 640
91    std::printf("one expert: gu %zu B (Q3_K 1280x1280), dn %zu B (IQ4_NL 1280x640)\n", gub, dnb);
92
93    // the blob: real quantized weights (never random bytes - a random 6-bit scale is 1e-30 .. 1e+30)
94    std::mt19937 rng(11);
95    std::normal_distribution<float> nw(0.f, 0.05f), nd(0.f, 1.f);
96    std::vector<uint8_t> blob(gub + dnb);
97    {
98        std::vector<float> w((size_t) 1280 * ELL);
99        for (auto& v : w) v = nw(rng);
100        if ((size_t) ggml_quantize_chunk(GGML_TYPE_Q3_K, w.data(), blob.data(), 0, 1280, ELL, nullptr) != gub) {
101            std::printf("FAIL gu quantize\n"); return 1;
102        }
103        std::vector<float> wd((size_t) ELL * FF);
104        for (auto& v : wd) v = nw(rng);
105        if ((size_t) ggml_quantize_chunk(GGML_TYPE_IQ4_NL, wd.data(), blob.data() + gub, 0, ELL, FF, nullptr) != dnb) {
106            std::printf("FAIL dn quantize\n"); return 1;
107        }
108    }
109    const auto L = strata::kernels::native_expert_layout(GGML_TYPE_Q3_K, GGML_TYPE_IQ4_NL, ELL, FF);
110    std::printf("layout: gu_row %zu up_off %zu down_off %zu d_row %zu bytes %zu tail %zu\n", L.gu_row, L.up_off,
111                L.down_off, L.d_row, L.bytes, L.tail_off);
112    if (L.bytes != gub + dnb || L.down_off != 704000 || L.d_row != 360 || L.gu_row != 550 || L.tail_off != 0) {
113        std::printf("FAIL layout != the q3k pack's (704000 / 360 / 550 / no tail)\n");
114        return 1;
115    }
116
117    // 128 experts: replicas of this blob at distinct addresses (the reads are DRAM traffic), 4 entries each
118    uint8_t* dall = nullptr;
119    CK(cudaMalloc(&dall, (size_t) G * L.bytes));
120    {
121        std::vector<uint8_t> one(L.bytes);
122        std::memcpy(one.data(), blob.data(), gub);
123        std::memcpy(one.data() + L.down_off, blob.data() + gub, dnb);
124        std::vector<uint8_t> all((size_t) G * L.bytes);
125        for (int g = 0; g < G; ++g) std::memcpy(all.data() + (size_t) g * L.bytes, one.data(), L.bytes);
126        CK(cudaMemcpy(dall, all.data(), all.size(), cudaMemcpyHostToDevice));
127    }
128    std::vector<const uint8_t*> bp((size_t) kMaxG);
129    for (int g = 0; g < kMaxG; ++g) bp[(size_t) g] = dall + (size_t) (g % G) * L.bytes;
130    const uint8_t** dblob = nullptr;
131    CK(cudaMalloc(&dblob, (size_t) kMaxG * sizeof(uint8_t*)));
132    CK(cudaMemcpy(dblob, bp.data(), (size_t) kMaxG * sizeof(uint8_t*), cudaMemcpyHostToDevice));
133
134    // the gate/up input: a different x row per entry, so a row swap anywhere shows up (40 q8_1 blocks = n_embd 1280)
135    std::vector<float> xs((size_t) E * ELL);
136    for (auto& v : xs) v = nd(rng);
137    std::vector<H8> hx((size_t) E * kXNB);
138    for (int e = 0; e < E; ++e)
139        for (int b = 0; b < kXNB; ++b) {
140            float amax = 0.f, sum = 0.f;
141            for (int i = 0; i < 32; ++i) {
142                const float v = xs[(size_t) e * ELL + 32 * b + i];
143                amax = std::fmax(amax, std::fabs(v)); sum += v;
144            }
145            const float d = amax / 127.0f;
146            H8& o = hx[(size_t) e * kXNB + b];
147            o.d = ggml_fp32_to_fp16(d);
148            o.s = ggml_fp32_to_fp16(sum);
149            for (int i = 0; i < 32; ++i)
150                o.qs[i] = (int8_t) std::lround(d != 0.f ? xs[(size_t) e * ELL + 32 * b + i] / d : 0.f);
151        }
152    uint8_t* dxq = nullptr;
153    CK(cudaMalloc(&dxq, hx.size() * sizeof(H8)));
154    CK(cudaMemcpy(dxq, hx.data(), hx.size() * sizeof(H8), cudaMemcpyHostToDevice));
155
156    int32_t *dgs = nullptr, *dng = nullptr, *ded = nullptr, *det = nullptr;
157    CK(cudaMalloc(&dgs, (size_t) (G + 1) * sizeof(int32_t)));
158    CK(cudaMalloc(&dng, sizeof(int32_t)));
159    CK(cudaMalloc(&ded, (size_t) E * sizeof(int32_t)));
160    CK(cudaMalloc(&det, (size_t) E * sizeof(int32_t)));
161    std::vector<int32_t> gs((size_t) G + 1), ed((size_t) E), et((size_t) E), ng(1, G);
162    for (int g = 0; g <= G; ++g) gs[(size_t) g] = g * EPG;
163    for (int e = 0; e < E; ++e) { ed[(size_t) e] = e; et[(size_t) e] = e; }
164    CK(cudaMemcpy(dgs, gs.data(), gs.size() * 4, cudaMemcpyHostToDevice));
165    CK(cudaMemcpy(dng, ng.data(), 4, cudaMemcpyHostToDevice));
166    CK(cudaMemcpy(ded, ed.data(), ed.size() * 4, cudaMemcpyHostToDevice));
167    CK(cudaMemcpy(det, et.data(), et.size() * 4, cudaMemcpyHostToDevice));
168
169    void* scratch = nullptr;
170    const size_t sb = strata::kernels::native_expert_scratch_bytes(E, FF);
171    CK(cudaMalloc(&scratch, sb));
172    float* dout = nullptr;
173    CK(cudaMalloc(&dout, (size_t) E * ELL * sizeof(float)));
174    std::printf("native: %d groups x %d entries, scratch %zu B\n", G, EPG, sb);
175
176    // the reference: phase 1 = gate/up + SwiGLU + q8_1 (H), phase 2 = the down of that H, phase 0 = both.  All three
177    // read the same buffers, so 0 and 1+2 must match bitwise - it is the check that H is the one we compare against.
178    strata::kernels::native_expert_set_mode(-1, 1);
179    strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs, dng, ded, det, G, E, dxq, scratch,
180                                           dout, nullptr, 0);
181    CK(cudaDeviceSynchronize());
182    const size_t fa = ((size_t) E * FF * sizeof(float) + 255) & ~(size_t) 255;
183    std::vector<H8> hq_host((size_t) E * kNB);
184    CK(cudaMemcpy(hq_host.data(), (const uint8_t*) scratch + 3 * fa, hq_host.size() * sizeof(H8),
185                  cudaMemcpyDeviceToHost));
186
187    strata::kernels::native_expert_set_mode(-1, 2);
188    strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs, dng, ded, det, G, E, dxq, scratch,
189                                           dout, nullptr, 0);
190    CK(cudaDeviceSynchronize());
191    std::vector<float> ref((size_t) E * ELL);
192    CK(cudaMemcpy(ref.data(), dout, ref.size() * 4, cudaMemcpyDeviceToHost));
193
194    strata::kernels::native_expert_set_mode(-1, 0);
195    CK(cudaMemset(dout, 0, (size_t) E * ELL * sizeof(float)));
196    strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs, dng, ded, det, G, E, dxq, scratch,
197                                           dout, nullptr, 0);
198    CK(cudaDeviceSynchronize());
199    std::vector<float> full((size_t) E * ELL);
200    CK(cudaMemcpy(full.data(), dout, full.size() * 4, cudaMemcpyDeviceToHost));
201    std::printf("phase check: full %016llx  gu+h+down %016llx  %s\n", fnv(full), fnv(ref),
202                fnv(full) == fnv(ref) ? "same" : "DIFFERENT");
203
204    // the staged H, and the M1 down on it
205    std::vector<uint8_t> staged;
206    stage_h(hq_host, E, staged);
207    uint8_t* dstaged = nullptr;
208    CK(cudaMalloc(&dstaged, staged.size()));
209    CK(cudaMemcpy(dstaged, staged.data(), staged.size(), cudaMemcpyHostToDevice));
210    float* dmine = nullptr;
211    CK(cudaMalloc(&dmine, (size_t) E * ELL * sizeof(float)));
212    CK(cudaMemset(dmine, 0, (size_t) E * ELL * sizeof(float)));
213    strata::prefill::lat_q3k_down(dblob, dgs, G, dstaged, dmine, ELL, nullptr);
214    CK(cudaDeviceSynchronize());
215    std::vector<float> mine((size_t) E * ELL);
216    CK(cudaMemcpy(mine.data(), dmine, mine.size() * 4, cudaMemcpyDeviceToHost));
217
218    // ---- the comparison ---------------------------------------------------------------------------------------
219    // A row both sides leave at zero (no data for that entry) is not a difference: it is skipped.
220    double sabs = 0, sref = 0;
221    float dmax = 0.f;
222    double cosmin = 1.0;
223    int bad99 = 0, bad9999 = 0, skipped = 0;
224    for (int e = 0; e < E; ++e) {
225        double num = 0, aa = 0, bb = 0;
226        float big = 0.f;
227        for (int r = 0; r < ELL; ++r) {
228            const float a = mine[(size_t) e * ELL + r], b = ref[(size_t) e * ELL + r];
229            const double d = std::fabs((double) a - b);
230            sabs += d; sref += std::fabs((double) b);
231            dmax = std::fmax(dmax, (float) d);
232            num += (double) a * b; aa += (double) a * a; bb += (double) b * b;
233            big = std::fmax(big, std::fmax(std::fabs(a), std::fabs(b)));
234        }
235        if (big == 0.f) { ++skipped; continue; }
236        const double cos = num / (std::sqrt(aa) * std::sqrt(bb) + 1e-30);
237        cosmin = std::min(cosmin, cos);
238        if (cos < 0.99) ++bad99;
239        if (cos < 0.9999) ++bad9999;
240    }
241    std::printf("rows=%d (skipped %d all-zero)  rel_mean=%.3e  max|d|=%.6e  cos_min=%.9f  rows<0.99=%d  rows<0.9999=%d\n",
242                E, skipped, sref > 0 ? sabs / sref : 0.0, (double) dmax, cosmin, bad99, bad9999);
243    std::printf("row0 mine:"); for (int r = 0; r < 8; ++r) std::printf(" %.6f", mine[(size_t) r]);
244    std::printf("\nrow0 ref :"); for (int r = 0; r < 8; ++r) std::printf(" %.6f", ref[(size_t) r]);
245    std::printf("\n");
246    {   // the double-precision arbiter, entry 0: the same weights, the same H row
247        const uint8_t* dn = blob.data() + gub;
248        double cd = 0, csum = 0, ccc = 0, crr = 0, nrc = 0;
249        for (int r = 0; r < ELL; ++r) {
250            const double c = cpu_dot(dn, &hq_host[0], r), a = ref[(size_t) r];
251            ccc += c * c; cd += c * a; crr += a * a; csum += std::fabs(a); nrc += std::fabs(c - a);
252        }
253        double cm = 0, nm = 0, csum2 = 0, mm = 0;
254        for (int r = 0; r < ELL; ++r) {
255            const double c = cpu_dot(dn, &hq_host[0], r), b = mine[(size_t) r];
256            cm += c * b; nm += std::fabs(c - b); csum2 += std::fabs(c); mm += b * b;
257        }
258        std::printf("entry0 cpu vs ref : rel_mean %.3e cos %.9f\n", nrc / csum,
259                    cd / (std::sqrt(ccc) * std::sqrt(crr) + 1e-30));
260        std::printf("entry0 cpu vs mine: rel_mean %.3e cos %.9f\n", nm / csum2,
261                    cm / (std::sqrt(ccc) * std::sqrt(mm) + 1e-30));
262    }
263
264    // ---- the engine's shapes: entries per group 4 / 32 / 200 / 1400, ~4000 entries a call ----------------------
265    {
266        const int shapes[][2] = {{4, 1000}, {32, 128}, {200, 20}, {1400, 3}};
267        std::vector<H8> plain((size_t) kMaxE * kNB);       // a valid H for the reference to read
268        for (int e = 0; e < kMaxE; ++e)
269            for (int b = 0; b < kNB; ++b) {
270                H8& o = plain[(size_t) e * kNB + b];
271                o.d = ggml_fp32_to_fp16(0.004f + 1e-5f * (e % 211));
272                o.s = 0;
273                for (int i = 0; i < 32; ++i) o.qs[i] = (int8_t) (((e * 7 + b * 13 + i * 3) % 255) - 127);
274            }
275        std::vector<uint8_t> stAll;
276        stage_h(plain, kMaxE, stAll);
277        uint8_t* dstage = nullptr; CK(cudaMalloc(&dstage, stAll.size()));
278        CK(cudaMemcpy(dstage, stAll.data(), stAll.size(), cudaMemcpyHostToDevice));
279        float* dsw = nullptr; CK(cudaMalloc(&dsw, (size_t) kMaxE * ELL * sizeof(float)));
280        void* scr2 = nullptr; CK(cudaMalloc(&scr2, strata::kernels::native_expert_scratch_bytes(kMaxE, FF)));
281        int32_t *dgs2 = nullptr, *ded2 = nullptr, *det2 = nullptr, *dng2 = nullptr;
282        CK(cudaMalloc(&dgs2, (size_t) (kMaxG + 1) * 4));
283        CK(cudaMalloc(&ded2, (size_t) kMaxE * 4));
284        CK(cudaMalloc(&det2, (size_t) kMaxE * 4));
285        CK(cudaMalloc(&dng2, 4));
286        std::printf("\nthe shape sweep (one down, us/entry):\n");
287        double worst = 0;
288        for (const auto& sh : shapes) {
289            const int epg = sh[0], G2 = sh[1], E2 = epg * G2;
290            std::vector<int32_t> g2((size_t) G2 + 1), d2((size_t) E2), t2((size_t) E2), ng2(1, G2);
291            for (int g = 0; g <= G2; ++g) g2[(size_t) g] = g * epg;
292            for (int e = 0; e < E2; ++e) { d2[(size_t) e] = e; t2[(size_t) e] = e; }
293            CK(cudaMemcpy(dgs2, g2.data(), g2.size() * 4, cudaMemcpyHostToDevice));
294            CK(cudaMemcpy(ded2, d2.data(), d2.size() * 4, cudaMemcpyHostToDevice));
295            CK(cudaMemcpy(det2, t2.data(), t2.size() * 4, cudaMemcpyHostToDevice));
296            CK(cudaMemcpy(dng2, ng2.data(), 4, cudaMemcpyHostToDevice));
297            const size_t fa2 = ((size_t) E2 * FF * sizeof(float) + 255) & ~(size_t) 255;
298            CK(cudaMemcpy((uint8_t*) scr2 + 3 * fa2, plain.data(), (size_t) E2 * kNB * sizeof(H8),
299                          cudaMemcpyHostToDevice));
300            const int iters = E2 >= 4000 ? 20 : 50;
301            strata::kernels::native_expert_set_mode(-1, 2);
302            auto time2 = [&](bool use_mine) {
303                if (use_mine) strata::prefill::lat_q3k_down(dblob, dgs2, G2, dstage, dsw, ELL, nullptr);
304                else strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs2, dng2, ded2, det2,
305                                                            G2, E2, dxq, scr2, dsw, nullptr, 0);
306                CK(cudaDeviceSynchronize());
307                cudaEvent_t t0, t1; CK(cudaEventCreate(&t0)); CK(cudaEventCreate(&t1));
308                CK(cudaEventRecord(t0));
309                for (int i = 0; i < iters; ++i) {
310                    if (use_mine) strata::prefill::lat_q3k_down(dblob, dgs2, G2, dstage, dsw, ELL, nullptr);
311                    else strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs2, dng2, ded2,
312                                                                det2, G2, E2, dxq, scr2, dsw, nullptr, 0);
313                }
314                CK(cudaEventRecord(t1)); CK(cudaEventSynchronize(t1));
315                float ms = 0; CK(cudaEventElapsedTime(&ms, t0, t1));
316                CK(cudaEventDestroy(t0)); CK(cudaEventDestroy(t1));
317                return ms / iters;
318            };
319            const double tm = time2(true), tr = time2(false);
320            const double r = tr > 0 ? tm / tr : 0.0;
321            worst = std::max(worst, r);
322            std::printf("  epg %4d  groups %4d  E %5d | mine %.3f ms %6.3f us/entry | native %.3f ms %6.3f us/entry | "
323                        "mine/native %.2fx\n", epg, G2, E2, tm, tm * 1000.0 / E2, tr, tr * 1000.0 / E2, r);
324        }
325        std::printf("worst shape: mine/native %.2fx\n", worst);
326    }
327
328    const bool ok = (sref > 0 ? sabs / sref : 1.0) <= 1e-3 && cosmin >= 0.9999 && bad99 == 0;
329    std::printf("%s: M1 (IQ4_NL down, %d groups x %d entries)\n", ok ? "PASS" : "FAIL", G, EPG);
330    return ok ? 0 : 1;
331}