okami.mom/strata

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

waveringanaRestore the DeepSeek V4.1 engine and CPU tests removed upstream8ac8ce32e

main
16.8 KiB288 linesraw
1// Strata. The trellis routed experts of the DeepSeek-V4.1 path (ds4_tq.cu on the device, ds4_tq_cpu.cpp on the CPU lane) against
2// a double reference on host-decoded weights (tools/trellis/tqenc: decode_blocks), for the six types (TQK6 / TQK7 / TQK5X /
3// TQK4X / TQK5T / TQK4T): the token path, the window path (grouped entries), the prompt sets (gate/up and down) and the CPU
4// lane, plus the two lanes against each other.  Random legal streams: any bit pattern is one.
5//   tq_expert_test [--type 145,146,...]
6#include "../../src/dsv41/ds4_gguf_cpu.hpp"
7#include "../../src/dsv41/ds4_iq.cuh"
8#include "../../tools/trellis/tqenc.hpp"
9
10#include "strata/dsv41/hip_or_cuda.h"   // HIP names on a HIP build, the CUDA runtime otherwise
11
12#include <algorithm>
13#include <cmath>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <random>
18#include <string>
19#include <vector>
20
21namespace iq = strata::ds4::gguf::iq;
22namespace gg = strata::ds4::gguf;
23#define CK(x) do { hipError_t e_ = (x); if (e_ != hipSuccess) { std::printf("HIP error %s at %d\n", hipGetErrorString(e_), __LINE__); std::exit(2); } } while (0)
24
25template <typename T> static T* up(const std::vector<T>& v) {
26    T* d; CK(hipMalloc(&d, std::max<size_t>(1, v.size() * sizeof(T)))); CK(hipMemcpy(d, v.data(), v.size() * sizeof(T), hipMemcpyHostToDevice)); return d;
27}
28template <typename T> static std::vector<T> down_(const T* d, size_t n) {
29    std::vector<T> v(n); CK(hipMemcpy(v.data(), d, n * sizeof(T), hipMemcpyDeviceToHost)); return v;
30}
31static float h2f(uint16_t h) {
32    const int s = h >> 15, e = (h >> 10) & 31, m = h & 1023;
33    float f = e == 0 ? std::ldexp((float) m, -24) : std::ldexp(1.0f + m / 1024.0f, e - 15);
34    return s ? -f : f;
35}
36static uint16_t f2h(float f) {   // round to nearest even, normal range
37    uint32_t u; std::memcpy(&u, &f, 4);
38    const uint32_t s = (u >> 16) & 0x8000u; int e = (int) ((u >> 23) & 0xff) - 127 + 15; uint32_t m = u & 0x7fffffu;
39    uint32_t hm = m >> 13; const uint32_t rem = m & 0x1fffu;
40    uint32_t v = ((uint32_t) e << 10) | hm;
41    if (rem > 0x1000u || (rem == 0x1000u && (v & 1))) ++v;
42    return (uint16_t) (s | v);
43}
44
45struct Q8 { std::vector<int8_t> q; std::vector<float> d; std::vector<float> xhat; };
46// the engine's q8_quant: sc = max|x| / 127 per 32, q = round-half-even(x / sc)
47static Q8 quant(const float* x, int k) {
48    Q8 r; r.q.resize(k); r.d.resize(k / 32); r.xhat.resize(k);
49    for (int b = 0; b < k / 32; ++b) {
50        float am = 0; for (int j = 0; j < 32; ++j) am = std::max(am, std::fabs(x[b * 32 + j]));
51        const float sc = am / 127.0f; r.d[b] = sc;
52        for (int j = 0; j < 32; ++j) { const int q = am > 0 ? (int) std::nearbyint(x[b * 32 + j] / sc) : 0; r.q[b * 32 + j] = (int8_t) q; r.xhat[b * 32 + j] = (float) q * sc; }
53    }
54    return r;
55}
56static double swiglu(double g, double u, double lim) {
57    if (lim > 0) { g = std::min(g, lim); u = std::min(std::max(u, -lim), lim); }
58    return g / (1.0 + std::exp(-g)) * u;
59}
60
61struct Mat { std::vector<uint8_t> bytes; std::vector<float> w; int rows, k; };
62static Mat make_mat(std::mt19937_64& rng, int type, int K, int rows, int k) {
63    Mat m; m.rows = rows; m.k = k;
64    const int bsz = 2 + 4 * K, nblk = k / 128;
65    m.bytes.resize((size_t) rows * nblk * bsz);
66    for (auto& b : m.bytes) b = (uint8_t) rng();
67    for (int64_t b = 0; b < (int64_t) rows * nblk; ++b) { const uint16_t d = f2h(0.05f + 0.0005f * (float) (rng() % 600)); std::memcpy(&m.bytes[(size_t) b * bsz], &d, 2); }
68    m.w.resize((size_t) rows * k);
69    tqenc::decode_blocks(type, m.bytes.data(), (int64_t) rows * nblk, m.w.data());
70    return m;
71}
72static double dotd(const float* w, const float* x, int k, double* sabs = nullptr) {
73    double s = 0, sa = 0; for (int i = 0; i < k; ++i) { const double t = (double) w[i] * x[i]; s += t; sa += std::fabs(t); } if (sabs) *sabs = sa; return s;
74}
75
76// one decode token of the DeepSeek shape (n_embd 5120, n_ff 2304, top-6 experts, distinct blobs) through the token path: gate/up +
77// down launches, hipEvent time per layer; and a 5-entry verify window of one expert group
78static void bench(int type) {
79    const int K = iq::tq_kbits(type), E = 5120, FF = 2304, NE = 6;
80    const size_t rb_g = (size_t) (E / 128) * (2 + 4 * K), rb_d = (size_t) (FF / 128) * (2 + 4 * K);
81    auto al = [](size_t n) { return (n + 255) / 256 * 256; };
82    const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
83    std::mt19937_64 rng(5);
84    std::vector<uint8_t> one(blob);
85    for (auto& b : one) b = (uint8_t) rng();
86    std::vector<unsigned long long> plan(NE);
87    for (int e = 0; e < NE; ++e) { uint8_t* d; CK(hipMalloc(&d, blob)); CK(hipMemcpy(d, one.data(), blob, hipMemcpyHostToDevice)); plan[e] = (unsigned long long) d; }
88    std::vector<int8_t> xq(E, 3), hq((size_t) NE * FF, 3); std::vector<float> xd(E / 32, 0.01f), hd((size_t) NE * FF / 32, 0.01f);
89    iq::Args a{};
90    a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = 10.0f; a.xq = up(xq); a.xd = up(xd); a.hq = up(hq); a.hd = up(hd); a.tg = a.td = type;
91    for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
92    float *dh, *dp; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMalloc(&dp, (size_t) NE * E * 4)); a.h = dh; a.part = dp;
93    hipEvent_t e0, e1; hipEventCreate(&e0); hipEventCreate(&e1);
94    for (int rep = 0; rep < 5; ++rep) { iq::gate_up(a, NE, 1, 0); iq::down(a, NE, 1, 0); }
95    CK(hipDeviceSynchronize());
96    float ms_gu = 0, ms_dn = 0;
97    for (int part = 0; part < 2; ++part) {
98        hipEventRecord(e0);
99        for (int rep = 0; rep < 100; ++rep) { if (part == 0) iq::gate_up(a, NE, 1, 0); else iq::down(a, NE, 1, 0); }
100        hipEventRecord(e1); hipEventSynchronize(e1);
101        float ms; hipEventElapsedTime(&ms, e0, e1);
102        (part == 0 ? ms_gu : ms_dn) = ms / 100;
103    }
104    const double bytes = (double) NE * blob;
105    std::printf("bench %-6s token path, 6 experts: gate/up %.0f us, down %.0f us, layer %.0f us (%.0f GB/s, %.2f Tw/s), x40 = %.1f ms per token\n", iq::name(type), ms_gu * 1e3,
106                ms_dn * 1e3, (ms_gu + ms_dn) * 1e3, bytes / ((ms_gu + ms_dn) * 1e-3) / 1e9, (double) NE * 3 * FF * E / ((ms_gu + ms_dn) * 1e-3) / 1e12, 40.0 * (ms_gu + ms_dn));
107}
108
109int main(int argc, char** argv) {
110    std::vector<int> types = {145, 146, 224, 225, 226, 227};
111    for (int i = 1; i < argc; ++i)
112        if (std::string(argv[i]) == "--bench") { for (int t : {225, 224, 145, 146}) bench(t); return 0; }
113        else if (std::string(argv[i]) == "--type" && i + 1 < argc) { types.clear(); for (const char* p = argv[++i]; *p;) { types.push_back(std::atoi(p)); while (*p && *p != ',') ++p; if (*p) ++p; } }
114    std::mt19937_64 rng(11);
115    std::normal_distribution<float> nd(0.f, 1.f);
116    int fails = 0;
117    auto report = [&](const char* what, int type, double worst, double tol) {
118        const bool ok = worst <= tol;
119        std::printf("%-6s %-22s worst %.2e (tol %.0e) %s\n", iq::name(type), what, worst, tol, ok ? "ok" : "FAIL");
120        fails += !ok;
121    };
122    for (int type : types) {
123        const int K = iq::tq_kbits(type);
124        const int E = 512, FF = 256, NEXP = 3, T = 4;
125        const float lim = 7.0f;
126        const size_t rb_g = (size_t) (E / 128) * (2 + 4 * K), rb_d = (size_t) (FF / 128) * (2 + 4 * K);
127        // experts: blob = gate | up | down, each 256-aligned
128        auto al = [](size_t n) { return (n + 255) / 256 * 256; };
129        const size_t off[3] = {0, al(FF * rb_g), al(FF * rb_g) * 2}, blob = off[2] + al((size_t) E * rb_d);
130        std::vector<Mat> G(NEXP), U(NEXP), D(NEXP);
131        // h of row r of expert e for the input xv (F32 values), and the size of the operands it was made of
132        auto refh = [&](int e, int r, const float* xv, double& scale) {
133            double sg, su;
134            const double g = dotd(&G[e].w[(size_t) r * E], xv, E, &sg), u = dotd(&U[e].w[(size_t) r * E], xv, E, &su);
135            scale = sg + su + 1e-30;
136            return swiglu(g, u, lim);
137        };
138        std::vector<uint8_t> blobs((size_t) NEXP * blob, 0);
139        for (int e = 0; e < NEXP; ++e) {
140            G[e] = make_mat(rng, type, K, FF, E); U[e] = make_mat(rng, type, K, FF, E); D[e] = make_mat(rng, type, K, E, FF);
141            std::memcpy(&blobs[e * blob + off[0]], G[e].bytes.data(), G[e].bytes.size());
142            std::memcpy(&blobs[e * blob + off[1]], U[e].bytes.data(), U[e].bytes.size());
143            std::memcpy(&blobs[e * blob + off[2]], D[e].bytes.data(), D[e].bytes.size());
144        }
145        uint8_t* dblob = up(blobs);
146        // tokens
147        std::vector<float> x((size_t) T * E);
148        for (auto& v : x) v = nd(rng) * (1.0f + 3.0f * (rng() % 7 == 0));
149        std::vector<Q8> qx(T);
150        std::vector<int8_t> xq((size_t) T * E); std::vector<float> xd((size_t) T * E / 32);
151        for (int t = 0; t < T; ++t) { qx[t] = quant(&x[(size_t) t * E], E); std::memcpy(&xq[(size_t) t * E], qx[t].q.data(), E); std::memcpy(&xd[(size_t) t * E / 32], qx[t].d.data(), E / 32 * 4); }
152        const int8_t* dxq = up(xq); const float* dxd = up(xd);
153
154        // ---- token path: plan = 3 experts, input row 0
155        {
156            std::vector<unsigned long long> plan(NEXP);
157            for (int e = 0; e < NEXP; ++e) plan[e] = (unsigned long long) (dblob + e * blob);
158            iq::Args a{};
159            a.plan_ptr = up(plan); a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
160            for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
161            float* dh; CK(hipMalloc(&dh, (size_t) NEXP * FF * 4)); a.h = dh;
162            if (!iq::gate_up(a, NEXP, 1, 0)) { std::printf("gate_up refused\n"); return 1; }
163            CK(hipDeviceSynchronize());
164            const auto h = down_(dh, (size_t) NEXP * FF);
165            double worst = 0;
166            std::vector<float> href((size_t) NEXP * FF);
167            for (int e = 0; e < NEXP; ++e)
168                for (int r = 0; r < FF; ++r) {
169                    double sc;
170                    const double ref = refh(e, r, qx[0].xhat.data(), sc);
171                    href[(size_t) e * FF + r] = (float) ref;
172                    worst = std::max(worst, std::fabs(h[(size_t) e * FF + r] - ref) / sc);
173                }
174            report("token gate_up", type, worst, 1e-5);
175            // down over the reference h, quantized
176            std::vector<int8_t> hq((size_t) NEXP * FF); std::vector<float> hd((size_t) NEXP * FF / 32);
177            std::vector<Q8> qh(NEXP);
178            for (int e = 0; e < NEXP; ++e) { qh[e] = quant(&href[(size_t) e * FF], FF); std::memcpy(&hq[(size_t) e * FF], qh[e].q.data(), FF); std::memcpy(&hd[(size_t) e * FF / 32], qh[e].d.data(), FF / 32 * 4); }
179            a.hq = up(hq); a.hd = up(hd);
180            float* dp; CK(hipMalloc(&dp, (size_t) NEXP * E * 4)); a.part = dp;
181            if (!iq::down(a, NEXP, 1, 0)) { std::printf("down refused\n"); return 1; }
182            CK(hipDeviceSynchronize());
183            const auto part = down_(dp, (size_t) NEXP * E);
184            worst = 0;
185            for (int e = 0; e < NEXP; ++e)
186                for (int r = 0; r < E; ++r) {
187                    double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa);
188                    worst = std::max(worst, std::fabs(part[(size_t) e * E + r] - ref) / (sa + 1e-30));
189                }
190            report("token down", type, worst, 1e-6);
191
192            // ---- the CPU lane on the same experts and inputs; against the reference and the device
193            gg::IqCpu fm; std::string err;
194            if (!gg::iq_cpu_fmt(type, type, E, FF, fm, err)) { std::printf("cpu fmt: %s\n", err.c_str()); ++fails; }
195            else {
196                std::vector<uint8_t> act(fm.act_bytes), hact(fm.h_bytes);
197                gg::iq_cpu_quant(fm.gu_act, x.data(), E, act.data());
198                bool same = std::memcmp(act.data(), qx[0].d.data(), E / 32 * 4) == 0 && std::memcmp(act.data() + E / 32 * 4, qx[0].q.data(), E) == 0;
199                std::printf("%-6s cpu activation == device quantizer: %s\n", iq::name(type), same ? "ok" : "FAIL");
200                fails += !same;
201                double wg = 0, wd = 0, wx = 0;
202                for (int e = 0; e < NEXP; ++e) {
203                    std::vector<float> hc(FF), yc(E);
204                    float* hp[1] = {hc.data()}; float* yp[1] = {yc.data()};
205                    const void* ap[1] = {act.data()};
206                    gg::iq_cpu_gate_up(fm, &blobs[e * blob + off[0]], &blobs[e * blob + off[1]], ap, 1, hp, 0, FF, lim);
207                    for (int r = 0; r < FF; ++r) { double sc; refh(e, r, qx[0].xhat.data(), sc); wg = std::max(wg, std::fabs(hc[r] - href[(size_t) e * FF + r]) / sc); wx = std::max(wx, std::fabs(hc[r] - h[(size_t) e * FF + r]) / sc); }
208                    gg::iq_cpu_quant(fm.d_act, &href[(size_t) e * FF], FF, hact.data());
209                    const void* hpp[1] = {hact.data()};
210                    gg::iq_cpu_down(fm, &blobs[e * blob + off[2]], hpp, 1, yp, 0, E);
211                    for (int r = 0; r < E; ++r) { double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], qh[e].xhat.data(), FF, &sa); wd = std::max(wd, std::fabs(yc[r] - ref) / (sa + 1e-30)); }
212                }
213                report("cpu gate_up vs ref", type, wg, 1e-5);
214                report("cpu down vs ref", type, wd, 1e-6);
215                report("cpu vs device gate_up", type, wx, 1e-5);
216            }
217        }
218
219        // ---- window path: groups of entries (entry e = t * 8 + i reads input row e >> 3)
220        {
221            std::vector<unsigned long long> grp = {(unsigned long long) (dblob + 0 * blob), (unsigned long long) (dblob + 2 * blob)};
222            std::vector<int> start = {0, 3, 5}, ent = {1, 10, 19, 2, 8}, ng = {2};
223            iq::Args a{};
224            a.grp_ptr = up(grp); a.grp_start = up(start); a.grp_ent = up(ent); a.n_groups = up(ng);
225            a.n_embd = E; a.n_ff = FF; a.limit = lim; a.xq = dxq; a.xd = dxd; a.tg = a.td = type;
226            for (int r = 0; r < 3; ++r) a.tr[r] = off[r];
227            const int NE = 24;
228            float* dh; CK(hipMalloc(&dh, (size_t) NE * FF * 4)); CK(hipMemset(dh, 0, (size_t) NE * FF * 4)); a.h = dh;
229            iq::gate_up(a, 2, 3, 0);
230            CK(hipDeviceSynchronize());
231            const auto h = down_(dh, (size_t) NE * FF);
232            double worst = 0;
233            for (int gi = 0; gi < 2; ++gi)
234                for (int j = start[gi]; j < start[gi + 1]; ++j) {
235                    const int en = ent[j], t = en >> 3, e = gi == 0 ? 0 : 2;
236                    for (int r = 0; r < FF; ++r) {
237                        double sc;
238                        const double ref = refh(e, r, qx[t].xhat.data(), sc);
239                        worst = std::max(worst, std::fabs(h[(size_t) en * FF + r] - ref) / sc);
240                    }
241                }
242            report("window gate_up", type, worst, 1e-5);
243        }
244
245        // ---- the prompt sets: expert 0 owns sorted rows [0, 37), expert 2 rows [37, 42); input rows idx[sorted]
246        {
247            const int NR = 42;
248            std::vector<int> bounds = {0, 37, 37, 42}, idx(NR);
249            for (int i = 0; i < NR; ++i) idx[i] = i % T;
250            iq::SetArgs q{};
251            q.wbase = dblob; q.stride = blob; for (int r = 0; r < 3; ++r) q.tr[r] = off[r];
252            q.bounds = up(bounds); q.row0 = 0; q.max_rows = 37; q.n_exp = 3; q.n_embd = E; q.n_ff = FF; q.limit = lim;
253            q.tg = q.td = type; q.xf = up(x); q.idx = up(idx); q.ldx = E;
254            uint16_t* dh16; CK(hipMalloc(&dh16, (size_t) NR * FF * 2)); q.h = dh16; q.ldo = FF;
255            iq::set_gate_up(q, 0);
256            CK(hipDeviceSynchronize());
257            const auto h16 = down_(dh16, (size_t) NR * FF);
258            double worst = 0;
259            for (int e = 0; e < 3; ++e)
260                for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr)
261                    for (int r = 0; r < FF; ++r) {
262                        double sc;
263                        const double ref = refh(e, r, &x[(size_t) idx[lr] * E], sc);
264                        worst = std::max(worst, std::fabs(h2f(h16[(size_t) lr * FF + r]) - ref) / sc);
265                    }
266            report("set gate_up (f16 out)", type, worst, 1e-3);
267            // down over those f16 h rows
268            q.xh = dh16; q.ldx = FF;
269            float* dy; CK(hipMalloc(&dy, (size_t) NR * E * 4)); q.y = dy; q.ldo = E;
270            iq::set_down(q, 0);
271            CK(hipDeviceSynchronize());
272            const auto y = down_(dy, (size_t) NR * E);
273            worst = 0;
274            for (int e = 0; e < 3; ++e)
275                for (int lr = bounds[e]; lr < bounds[e + 1]; ++lr) {
276                    std::vector<float> hf(FF);
277                    for (int c = 0; c < FF; ++c) hf[c] = h2f(h16[(size_t) lr * FF + c]);
278                    for (int r = 0; r < E; ++r) {
279                        double sa; const double ref = dotd(&D[e].w[(size_t) r * FF], hf.data(), FF, &sa);
280                        worst = std::max(worst, std::fabs(y[(size_t) lr * E + r] - ref) / (sa + 1e-30));
281                    }
282                }
283            report("set down", type, worst, 1e-6);
284        }
285    }
286    std::printf("%s\n", fails ? "FAILED" : "ALL OK");
287    return fails;
288}