okami.mom/strata

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

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

main
12.3 KiB223 linesraw
1// The golden reference for the q3k latent A stage: ONE expert, its real blob layout, through the MMQ products
2// that are already verified against the default path (rel_mean 1.4e-3, cos_min 0.99997).  The fused latent kernel's
3// Q3_K/IQ4_NL dot has to reproduce these numbers; this prints them so the port has a target.
4#include "strata/prefill/moe_mmq.hpp"
5#include "strata/kernels/iq_kernels.hpp"
6
7#include <cuda_runtime.h>
8#include <ggml.h>
9
10#include <cmath>
11#include <cstdio>
12#include <cstdlib>
13#include <random>
14#include <vector>
15#include <cstring>
16
17namespace mmq = strata::prefill::mmq;
18#define CK(e) do { const cudaError_t r_ = (e); if (r_ != cudaSuccess) { \
19    std::printf("FAIL %s: %s\n", #e, cudaGetErrorString(r_)); std::exit(1); } } while (0)
20
21int main(int argc, char** argv) {
22    // argv[1]: 0 = the default IQ4_NL down, 1 = STRATA_LAT_DOWN_S26 (the S26 rows)
23    const int s26 = argc > 1 ? std::atoi(argv[1]) : 0;
24    if (s26) setenv("STRATA_LAT_DOWN_S26", "1", 1);
25    constexpr int64_t ELL = 1280, FF = 640;
26    const size_t gub = mmq::matrix_bytes(GGML_TYPE_Q3_K, 1280, ELL);    // gate 640 rows + up 640 rows
27    const size_t dnb = mmq::matrix_bytes(GGML_TYPE_IQ4_NL, ELL, FF);    // down 1280 x 640
28    std::printf("one expert: gu %zu B (Q3_K 1280x1280), dn %zu B (IQ4_NL 1280x640)\n", gub, dnb);
29
30    std::mt19937 rng(11);
31    std::normal_distribution<float> nw(0.f, 0.05f);
32    // VALID weights: quantize a real weight matrix, never random bytes (a random 6-bit scale is 1e-30..1e+30)
33    std::vector<uint8_t> blob(gub + dnb);
34    {
35        std::vector<float> w((size_t) 1280 * ELL);
36        for (auto& v : w) v = nw(rng);
37        const int64_t used = ggml_quantize_chunk(GGML_TYPE_Q3_K, w.data(), blob.data(), 0, 1280, ELL, nullptr);
38        if (used != (int64_t) gub) { std::printf("FAIL gu quantize %lld != %zu\n", (long long) used, gub); return 1; }
39        std::vector<float> wd((size_t) ELL * FF);
40        for (auto& v : wd) v = nw(rng);
41        const int64_t used2 = ggml_quantize_chunk(GGML_TYPE_IQ4_NL, wd.data(), blob.data() + gub, 0, ELL, FF, nullptr);
42        if (used2 != (int64_t) dnb) { std::printf("FAIL dn quantize %lld != %zu\n", (long long) used2, dnb); return 1; }
43    }
44    std::vector<float> x((size_t) ELL);
45    std::normal_distribution<float> nd(0.f, 1.f);
46    for (auto& v : x) v = nd(rng);
47
48    uint8_t *dgu = nullptr, *ddn = nullptr, *dxq = nullptr, *dhq = nullptr;
49    float *dgo = nullptr, *dho = nullptr, *ddo = nullptr;
50    int32_t* db = nullptr; int32_t* did = nullptr;
51    CK(cudaMalloc(&dgu, gub)); CK(cudaMalloc(&ddn, dnb));
52    CK(cudaMalloc(&dxq, mmq::q8_bytes(1, ELL))); CK(cudaMalloc(&dhq, mmq::q8_bytes(1, FF)));
53    CK(cudaMalloc(&dgo, 1280 * sizeof(float))); CK(cudaMalloc(&dho, FF * sizeof(float)));
54    CK(cudaMalloc(&ddo, ELL * sizeof(float)));
55    CK(cudaMalloc(&db, 2 * sizeof(int32_t))); CK(cudaMalloc(&did, sizeof(int32_t)));
56
57    CK(cudaMemcpy(dgu, blob.data(), gub, cudaMemcpyHostToDevice));            // gate|up, the blob's own order
58    CK(cudaMemcpy(ddn, blob.data() + gub, dnb, cudaMemcpyHostToDevice));
59    const int32_t b01[2] = {0, 1};
60    const int32_t id0 = 0;
61    CK(cudaMemcpy(db, b01, 2 * 4, cudaMemcpyHostToDevice));
62    CK(cudaMemcpy(did, &id0, 4, cudaMemcpyHostToDevice));
63    mmq::quantize(x.data(), nullptr, dxq, GGML_TYPE_Q3_K, ELL, ELL, 1, nullptr);
64
65    mmq::Context ctx;
66    mmq::Product gu;
67    gu.w = dgu; gu.type = GGML_TYPE_Q3_K; gu.w_rows = 1280; gu.w_cols = ELL; gu.expert_bytes = gub;
68    gu.n = 1; gu.xq = dxq; gu.bounds = db; gu.ids = did; gu.total_rows = 1; gu.max_rows = 1;
69    gu.dst = dgo; gu.ld_dst = 1280;
70    ctx.run(gu, nullptr);
71    mmq::swiglu(dgo, dho, 1, FF, false, nullptr);
72    mmq::quantize(dho, nullptr, dhq, GGML_TYPE_IQ4_NL, FF, FF, 1, nullptr);
73    mmq::Product dn;
74    dn.w = ddn; dn.type = GGML_TYPE_IQ4_NL; dn.w_rows = ELL; dn.w_cols = FF; dn.expert_bytes = dnb;
75    dn.n = 1; dn.xq = dhq; dn.bounds = db; dn.ids = did; dn.total_rows = 1; dn.max_rows = 1;
76    dn.dst = ddo; dn.ld_dst = ELL;
77    ctx.run(dn, nullptr);
78    CK(cudaDeviceSynchronize());
79
80    std::vector<float> y((size_t) ELL), g((size_t) 1280), h((size_t) FF);
81    CK(cudaMemcpy(g.data(), dgo, 1280 * 4, cudaMemcpyDeviceToHost));
82    CK(cudaMemcpy(h.data(), dho, FF * 4, cudaMemcpyDeviceToHost));
83    CK(cudaMemcpy(y.data(), ddo, ELL * 4, cudaMemcpyDeviceToHost));
84    double sg = 0, sh = 0, sy = 0;
85    for (float v : g) sg += v;
86    for (float v : h) sh += v;
87    for (float v : y) sy += v;
88    std::printf("GU  first8:"); for (int i = 0; i < 8; ++i) std::printf(" %.6f", g[(size_t) i]);
89    std::printf("  sum %.6f\nH   first8:", sg);
90    for (int i = 0; i < 8; ++i) std::printf(" %.6f", h[(size_t) i]);
91    std::printf("  sum %.6f\nyl  first8:", sh);
92    for (int i = 0; i < 8; ++i) std::printf(" %.6f", y[(size_t) i]);
93    std::printf("  sum %.6f\n", sy);
94
95    // ---- the native grouped kernels at the same latent layout ------------------------------------------------
96    // 128 experts (replicas of this one blob, distinct addresses so the reads are DRAM traffic), 4 entries each:
97    // the engine's shape, not one big group.  native_expert_grouped runs gate/up (Q3_K), SwiGLU + q8_1, then the
98    // down; the phase knob stops it before the down, so down = all - nodown.  Every input is identical between the
99    // two runs, so `out` must match bitwise.
100    {
101        const int G = 128, EPG = 4, E = G * EPG;
102        const auto L = strata::kernels::native_expert_layout(GGML_TYPE_Q3_K, GGML_TYPE_IQ4_NL, ELL, FF);
103        std::printf("layout: gu_row %zu up_off %zu down_off %zu d_row %zu bytes %zu\n", L.gu_row, L.up_off,
104                    L.down_off, L.d_row, L.bytes);
105        if (L.bytes != gub + dnb || L.up_off != gub / 2 || L.down_off != gub) {
106            std::printf("FAIL layout != the pack's (bytes %zu vs %zu)\n", L.bytes, gub + dnb);
107            return 1;
108        }
109        std::vector<uint8_t> one(L.bytes);
110        std::memcpy(one.data(), blob.data(), gub);
111        std::memcpy(one.data() + L.down_off, blob.data() + gub, dnb);
112        std::vector<uint8_t> all((size_t) G * L.bytes);
113        for (int g = 0; g < G; ++g) std::memcpy(all.data() + (size_t) g * L.bytes, one.data(), L.bytes);
114        uint8_t* dall = nullptr; CK(cudaMalloc(&dall, all.size()));
115        CK(cudaMemcpy(dall, all.data(), all.size(), cudaMemcpyHostToDevice));
116        std::vector<unsigned long long> gp((size_t) G);
117        for (int g = 0; g < G; ++g) gp[(size_t) g] = (unsigned long long) (dall + (size_t) g * L.bytes);
118
119        // q8_1 rows of x (every entry the same x; the down's input is produced inside the call, so only X is ours)
120        struct H8 { uint16_t d, s; int8_t qs[32]; };
121        std::vector<H8> hx((size_t) E * (ELL / 32));
122        for (int e = 0; e < E; ++e)
123            for (int b = 0; b < ELL / 32; ++b) {
124                float amax = 0.f, sum = 0.f;
125                for (int i = 0; i < 32; ++i) {
126                    const float v = x[(size_t) 32 * b + i];
127                    amax = std::fmax(amax, std::fabs(v)); sum += v;
128                }
129                const float d = amax / 127.0f;
130                H8& o = hx[(size_t) e * (ELL / 32) + b];
131                o.d = ggml_fp32_to_fp16(d);
132                o.s = ggml_fp32_to_fp16(sum);
133                for (int i = 0; i < 32; ++i)
134                    o.qs[i] = (int8_t) std::lround(d != 0.f ? x[(size_t) 32 * b + i] / d : 0.f);
135            }
136        uint8_t* dxq2 = nullptr;
137        CK(cudaMalloc(&dxq2, hx.size() * sizeof(H8)));
138        CK(cudaMemcpy(dxq2, hx.data(), hx.size() * sizeof(H8), cudaMemcpyHostToDevice));
139
140        unsigned long long* dgp = nullptr;
141        int32_t *dgs = nullptr, *dng = nullptr, *ded = nullptr, *det = nullptr;
142        CK(cudaMalloc(&dgp, (size_t) G * sizeof(unsigned long long)));
143        CK(cudaMalloc(&dgs, (size_t) (G + 1) * sizeof(int32_t)));
144        CK(cudaMalloc(&dng, sizeof(int32_t)));
145        CK(cudaMalloc(&ded, (size_t) E * sizeof(int32_t)));
146        CK(cudaMalloc(&det, (size_t) E * sizeof(int32_t)));
147        std::vector<int32_t> gs((size_t) G + 1), ed((size_t) E), et((size_t) E), ng(1, G);
148        for (int g = 0; g <= G; ++g) gs[(size_t) g] = g * EPG;
149        for (int e = 0; e < E; ++e) { ed[(size_t) e] = e; et[(size_t) e] = e; }
150        CK(cudaMemcpy(dgp, gp.data(), gp.size() * 8, cudaMemcpyHostToDevice));
151        CK(cudaMemcpy(dgs, gs.data(), gs.size() * 4, cudaMemcpyHostToDevice));
152        CK(cudaMemcpy(dng, ng.data(), 4, cudaMemcpyHostToDevice));
153        CK(cudaMemcpy(ded, ed.data(), ed.size() * 4, cudaMemcpyHostToDevice));
154        CK(cudaMemcpy(det, et.data(), et.size() * 4, cudaMemcpyHostToDevice));
155
156        void* scratch = nullptr;
157        const size_t sb = strata::kernels::native_expert_scratch_bytes(E, FF);
158        CK(cudaMalloc(&scratch, sb));
159        float* dout = nullptr;
160        CK(cudaMalloc(&dout, (size_t) E * ELL * sizeof(float)));
161        std::printf("native: %d groups x %d entries, scratch %zu B\n", G, EPG, sb);
162
163        // the same expert set as ONE call per `group_batch` groups: gs[] tiles exactly (gs[g] = g*EPG), so this is
164        // the API's own contract.  batch 1 = what the engine's per-expert walk does.
165        int32_t* dngk = nullptr;
166        CK(cudaMalloc(&dngk, sizeof(int32_t)));
167        auto run = [&](int phase, int group_batch) {
168            strata::kernels::native_expert_set_mode(-1, phase);
169            if (group_batch <= 0 || group_batch >= G) {
170                strata::kernels::native_expert_grouped(L, dgp, dgs, dng, ded, det, G, E, dxq2, scratch, dout, nullptr, 0);
171                return;
172            }
173            for (int q0 = 0; q0 < G; q0 += group_batch) {
174                const int k = std::min(group_batch, G - q0);
175                CK(cudaMemcpy(dngk, &k, 4, cudaMemcpyHostToDevice));
176                strata::kernels::native_expert_grouped(L, dgp + q0, dgs + q0, dngk, ded, det, k, E, dxq2, scratch,
177                                                       dout, nullptr, 0);
178            }
179        };
180        auto time_it = [&](int phase, int gb) {
181            run(phase, gb); CK(cudaDeviceSynchronize());
182            cudaEvent_t t0, t1; CK(cudaEventCreate(&t0)); CK(cudaEventCreate(&t1));
183            CK(cudaEventRecord(t0));
184            for (int i = 0; i < 50; ++i) run(phase, gb);
185            CK(cudaEventRecord(t1)); CK(cudaEventSynchronize(t1));
186            float ms = 0; CK(cudaEventElapsedTime(&ms, t0, t1));
187            CK(cudaEventDestroy(t0)); CK(cudaEventDestroy(t1));
188            return ms / 50.0;
189        };
190        {   // the batching question first: the same groups, one call per gb groups
191            unsigned long long ref = 0;
192            for (int gb : {1, 2, 4, 8, 16, 64, 128}) {
193                CK(cudaMemset(dout, 0, (size_t) E * ELL * sizeof(float)));
194                run(0, gb);
195                CK(cudaDeviceSynchronize());
196                std::vector<float> oo((size_t) E * ELL);
197                CK(cudaMemcpy(oo.data(), dout, oo.size() * 4, cudaMemcpyDeviceToHost));
198                unsigned long long h = 1469598103934665603ULL;
199                for (float v : oo) { uint32_t u; std::memcpy(&u, &v, 4); h = (h ^ u) * 1099511628211ULL; }
200                const double us = time_it(0, gb) * 1000.0 / E;
201                if (gb == 1) ref = h;
202                std::printf("group_batch %3d: hash %016llx %s  %.2f us/entry\n", gb, h,
203                            h == ref ? "same" : "DIFFERENT", us);
204            }
205        }
206        const double t_nodown = time_it(1, 1);   // gate/up + SwiGLU + q8_1
207        const double t_all = time_it(0, G);      // ... + the down
208        std::vector<float> o((size_t) E * ELL);
209        CK(cudaMemcpy(o.data(), dout, o.size() * 4, cudaMemcpyDeviceToHost));
210        unsigned long long hsh = 1469598103934665603ULL;
211        for (float v : o) { uint32_t u; std::memcpy(&u, &v, 4); hsh = (hsh ^ u) * 1099511628211ULL; }
212        double om = 0; for (float v : o) om += v;
213        double num = 0, den = 0;
214        for (int i = 0; i < ELL; ++i) { num += std::fabs(o[(size_t) i] - y[(size_t) i]); den += std::fabs(y[(size_t) i]); }
215        std::printf("s26=%d  all %.3f ms  nodown %.3f ms  down %.3f ms (%.1f us/entry)  hash %016llx  sum %.6f  row0 rel %.2e\n",
216                    s26, t_all, t_nodown, t_all - t_nodown, (t_all - t_nodown) * 1000.0 / E, hsh, om,
217                    den > 0 ? num / den : 0.0);
218    }
219    bool finite = true;
220    for (float v : y) finite = finite && std::isfinite(v);
221    std::printf("%s: the golden reference for one expert (all finite: %d)\n", finite ? "PASS" : "FAIL", (int) finite);
222    return finite ? 0 : 1;
223}