okami.mom/strata

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

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

main
18.5 KiB357 linesraw
1// src/prefill/lat_q3k_gu_test.cpp - M2a of the q3k latent A stage: gate/up (Q3_K, K = 1280) against a
2// double-precision host dequantization of the same blob bytes and the same q8_1 activations, plus the decode gate:
3// one row's super-block, its 16 sub-blocks' codes and sub-scales against the host's.
4// Acceptance (q3k_fused/BRIEF.md, M2a): rel_mean <= 1e-3, cos_min >= 0.9999, no row under 0.99, all data real;
5// the decode gate: codes exactly equal, sub-scales within 1e-6 relative.
6#include "strata/prefill/lat_q3k_gu.hpp"
7#include "strata/kernels/iq_kernels.hpp"
8
9#include <cuda_runtime.h>
10#include <ggml.h>
11
12#include <algorithm>
13#include <cmath>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17#include <random>
18#include <vector>
19
20#define CK(e) do { const cudaError_t r_ = (e); if (r_ != cudaSuccess) { \
21    std::printf("FAIL %s: %s\n", #e, cudaGetErrorString(r_)); std::exit(1); } } while (0)
22
23namespace {
24
25constexpr int64_t ELL = 1280, FF = 640;
26constexpr int kXNB = (int) (ELL / 32);          // the gate/up input row: 40 q8_1 blocks of 36 B
27constexpr int kRowBytes = 550;                  // a Q3_K gate/up row: 5 x 110 B
28constexpr int kSB = 5;                          // super-blocks in a row
29constexpr int kChunks = 20;
30constexpr int kStagedRow = strata::prefill::lat_q3k_gu_staged_row;
31
32struct H8 { uint16_t d, s; int8_t qs[32]; };
33
34// ggml-quants.c:1305 dequantize_row_q3_K, transcribed: 16 sub-blocks per 128-value half, the 12-byte 6-bit scales
35// (sub-block s: the low (s < 8) or high nibble of byte s & 7, and the two high bits 2 * (s / 4) of byte 8 + (s & 3)).
36void host_q3k_row(const uint8_t* row, float* y) {
37    for (int i = 0; i < kSB; ++i) {
38        const uint8_t* b = row + 110 * i;
39        const float d_all = ggml_fp16_to_fp32(*(const uint16_t*) (b + 108));
40        int sc[16];
41        for (int s = 0; s < 16; ++s) {
42            const int nib = (b[96 + (s & 7)] >> (4 * (s >> 3))) & 0xF;
43            const int hi2 = (b[96 + 8 + (s & 3)] >> (2 * (s >> 2))) & 3;
44            sc[s] = nib | (hi2 << 4);
45        }
46        for (int s = 0; s < 16; ++s) {
47            const float dl = d_all * (float) (sc[s] - 32);
48            const int t = (s & 7) >> 1, m = t + 4 * (s >> 3), qb = 32 * (s >> 3) + 16 * (s & 1);
49            const int hb = 16 * (s & 1);   // the hmask is not advanced across the halves (ggml: hm[l] / hm[l + 16])
50            for (int l = 0; l < 16; ++l) {
51                const int q = b[32 + qb + l], h = b[hb + l];
52                const int code = ((q >> (2 * t)) & 3) - (((h >> m) & 1) ? 0 : 4);
53                y[(size_t) i * 256 + 16 * s + l] = dl * (float) code;
54            }
55        }
56    }
57}
58
59// One sub-block's 16 codes and its scale (the host's view of the same bytes).
60void host_q3k_sub(const uint8_t* row, int sb, int sub, int* codes, double* scale) {
61    const uint8_t* b = row + 110 * sb;
62    const int s = sub;   // 0..15 within the super-block
63    const int nib = (b[96 + (s & 7)] >> (4 * (s >> 3))) & 0xF;
64    const int hi2 = (b[96 + 8 + (s & 3)] >> (2 * (s >> 2))) & 3;
65    *scale = (double) ggml_fp16_to_fp32(*(const uint16_t*) (b + 108)) * (double) ((nib | (hi2 << 4)) - 32);
66    const int t = (s & 7) >> 1, m = t + 4 * (s >> 3), qb = 32 * (s >> 3) + 16 * (s & 1);
67    const int hb = 16 * (s & 1);
68    for (int l = 0; l < 16; ++l) {
69        const int q = b[32 + qb + l], h = b[hb + l];
70        codes[l] = ((q >> (2 * t)) & 3) - (((h >> m) & 1) ? 0 : 4);
71    }
72}
73
74}  // namespace
75
76int main() {
77    constexpr int G = 128, EPG = 4, E = G * EPG;
78    const size_t gub = (size_t) 1280 * kRowBytes;   // 1280 Q3_K rows (gate 640 + up 640)
79    const size_t dnb = (size_t) ELL * FF / 32 * 18;
80    std::printf("one expert: gu %zu B (Q3_K 1280x1280), dn %zu B (IQ4_NL 1280x640)\n", gub, dnb);
81
82    std::mt19937 rng(11);
83    std::normal_distribution<float> nw(0.f, 0.05f), nd(0.f, 1.f);
84    std::vector<uint8_t> blob(gub + dnb);
85    std::vector<float> wgu((size_t) 1280 * ELL);
86    {
87        for (auto& v : wgu) v = nw(rng);
88        if ((size_t) ggml_quantize_chunk(GGML_TYPE_Q3_K, wgu.data(), blob.data(), 0, 1280, ELL, nullptr) != gub) {
89            std::printf("FAIL gu quantize\n"); return 1;
90        }
91        std::vector<float> wd((size_t) ELL * FF);
92        for (auto& v : wd) v = nw(rng);
93        if ((size_t) ggml_quantize_chunk(GGML_TYPE_IQ4_NL, wd.data(), blob.data() + gub, 0, ELL, FF, nullptr) != dnb) {
94            std::printf("FAIL dn quantize\n"); return 1;
95        }
96    }
97
98    // the host dequantization against ggml's own quantizer: if my reading of the block were wrong, this would be
99    // garbage rather than Q3_K's ~1 % quantization noise
100    {
101        std::vector<float> deq((size_t) ELL);
102        double num = 0, den = 0, aa = 0, bb = 0;
103        for (int r = 0; r < 1280; ++r) {
104            host_q3k_row(blob.data() + (size_t) r * kRowBytes, deq.data());
105            for (int k = 0; k < ELL; ++k) {
106                const double a = deq[(size_t) k], b = wgu[(size_t) r * ELL + k];
107                num += a * b; aa += a * a; bb += b * b; den += std::fabs(b);
108            }
109        }
110        const double cs = num / (std::sqrt(aa) * std::sqrt(bb) + 1e-30);
111        std::printf("host dequant vs the quantized source: cos %.6f (Q3_K's own 3.44-bit noise)\n", cs);
112        if (!(cs > 0.98)) { std::printf("FAIL host dequant (structure, not precision)\n"); return 1; }
113    }
114
115    // 128 experts: replicas at distinct addresses, 4 entries each
116    uint8_t* dall = nullptr;
117    CK(cudaMalloc(&dall, (size_t) G * blob.size()));
118    {
119        std::vector<uint8_t> all((size_t) G * blob.size());
120        for (int g = 0; g < G; ++g) std::memcpy(all.data() + (size_t) g * blob.size(), blob.data(), blob.size());
121        CK(cudaMemcpy(dall, all.data(), all.size(), cudaMemcpyHostToDevice));
122    }
123    std::vector<const uint8_t*> bp((size_t) G);
124    for (int g = 0; g < G; ++g) bp[(size_t) g] = dall + (size_t) g * blob.size();
125    const uint8_t** dblob = nullptr;
126    CK(cudaMalloc(&dblob, (size_t) G * sizeof(uint8_t*)));
127    CK(cudaMemcpy(dblob, bp.data(), (size_t) G * sizeof(uint8_t*), cudaMemcpyHostToDevice));
128    int32_t *dgs = nullptr, *dng = nullptr;
129    CK(cudaMalloc(&dgs, (size_t) (G + 1) * sizeof(int32_t)));
130    CK(cudaMalloc(&dng, sizeof(int32_t)));
131    std::vector<int32_t> gs((size_t) G + 1), ng(1, G);
132    for (int g = 0; g <= G; ++g) gs[(size_t) g] = g * EPG;
133    CK(cudaMemcpy(dgs, gs.data(), gs.size() * 4, cudaMemcpyHostToDevice));
134    CK(cudaMemcpy(dng, ng.data(), 4, cudaMemcpyHostToDevice));
135
136    // ---- the decode gate: one gate row's super-block, the kernel's staged rows against the host's bytes ---------
137    uint8_t* drow = nullptr;
138    CK(cudaMalloc(&drow, kRowBytes));
139    CK(cudaMemcpy(drow, blob.data(), kRowBytes, cudaMemcpyHostToDevice));
140    std::vector<uint8_t> dump((size_t) kChunks * kStagedRow);
141    uint8_t* ddump = nullptr;
142    CK(cudaMalloc(&ddump, dump.size()));
143    strata::prefill::lat_q3k_gu_dump(drow, 0, ddump, nullptr);
144    CK(cudaDeviceSynchronize());
145    CK(cudaMemcpy(dump.data(), ddump, dump.size(), cudaMemcpyDeviceToHost));
146    {
147        const int sb = 2;                       // the super-block under the microscope
148        int worst_code = 0;
149        double worst_sc = 0, worst_sc_rel = 0;
150        int shown = 0;
151        for (int cl = 0; cl < 4; ++cl) {
152            const uint8_t* st = dump.data() + (size_t) (4 * sb + cl) * kStagedRow;
153            for (int sub = 0; sub < 4; ++sub) {
154                int codes[16];
155                double sc = 0;
156                host_q3k_sub(blob.data(), sb, 4 * cl + sub, codes, &sc);
157                // the staged order: word k byte c is the sub-block's value 4c + k, so byte p is value 4*(p & 3)+(p>>2)
158                int mine[16];
159                int lo = 99, hi = -99;
160                for (int p = 0; p < 16; ++p) mine[4 * (p & 3) + (p >> 2)] = (int8_t) st[16 * sub + p];
161                for (int l = 0; l < 16; ++l) {
162                    worst_code = std::max(worst_code, std::abs(mine[l] - codes[l]));
163                    lo = std::min(lo, mine[l]); hi = std::max(hi, mine[l]);
164                }
165                float scm = 0;
166                std::memcpy(&scm, st + 64 + 4 * sub, 4);
167                worst_sc = std::max(worst_sc, std::fabs((double) scm - sc));
168                worst_sc_rel = std::max(worst_sc_rel, std::fabs((double) scm - sc) / (std::fabs(sc) + 1e-30));
169                if (shown < 2) {
170                    std::printf("  sb %d sub %2d: codes[", sb, 4 * cl + sub);
171                    for (int l = 0; l < 16; ++l) std::printf(" %2d", mine[l]);
172                    std::printf(" ] host["); 
173                    for (int l = 0; l < 16; ++l) std::printf(" %2d", codes[l]);
174                    std::printf(" ] in [%d,%d]  scale %.9g host %.9g\n", lo, hi, (double) scm, sc);
175                    ++shown;
176                }
177            }
178        }
179        std::printf("decode gate: 16 sub-blocks of sb %d -> max code |diff| %d, max scale |diff| %.3e (rel %.3e)\n",
180                    sb, worst_code, worst_sc, worst_sc_rel);
181        if (worst_code != 0 || worst_sc_rel > 1e-6) { std::printf("FAIL decode gate\n"); return 1; }
182    }
183
184    // ---- the products -----------------------------------------------------------------------------------------
185    std::vector<float> xs((size_t) E * ELL);
186    for (auto& v : xs) v = nd(rng);
187    std::vector<H8> hx((size_t) E * kXNB);
188    for (int e = 0; e < E; ++e)
189        for (int b = 0; b < kXNB; ++b) {
190            float amax = 0.f, sum = 0.f;
191            for (int i = 0; i < 32; ++i) {
192                const float v = xs[(size_t) e * ELL + 32 * b + i];
193                amax = std::fmax(amax, std::fabs(v)); sum += v;
194            }
195            const float d = amax / 127.0f;
196            H8& o = hx[(size_t) e * kXNB + b];
197            o.d = ggml_fp32_to_fp16(d);
198            o.s = ggml_fp32_to_fp16(sum);
199            for (int i = 0; i < 32; ++i)
200                o.qs[i] = (int8_t) std::lround(d != 0.f ? xs[(size_t) e * ELL + 32 * b + i] / d : 0.f);
201        }
202    uint8_t* dxq = nullptr;
203    CK(cudaMalloc(&dxq, hx.size() * sizeof(H8)));
204    CK(cudaMemcpy(dxq, hx.data(), hx.size() * sizeof(H8), cudaMemcpyHostToDevice));
205
206    float* dgate = nullptr;
207    float* dup = nullptr;
208    CK(cudaMalloc(&dgate, (size_t) E * FF * sizeof(float)));
209    CK(cudaMalloc(&dup, (size_t) E * FF * sizeof(float)));
210    CK(cudaMemset(dgate, 0, (size_t) E * FF * sizeof(float)));
211    CK(cudaMemset(dup, 0, (size_t) E * FF * sizeof(float)));
212    strata::prefill::lat_q3k_gu(dblob, dgs, G, dxq, dgate, dup, FF, nullptr);
213    CK(cudaDeviceSynchronize());
214    std::vector<float> gate((size_t) E * FF), up((size_t) E * FF);
215    CK(cudaMemcpy(gate.data(), dgate, gate.size() * 4, cudaMemcpyDeviceToHost));
216    CK(cudaMemcpy(up.data(), dup, up.size() * 4, cudaMemcpyDeviceToHost));
217
218    // the host reference: the activations the kernel reads (d8 * code) against the dequantized rows, in double
219    std::vector<double> xh((size_t) E * ELL);
220    for (int e = 0; e < E; ++e)
221        for (int b = 0; b < kXNB; ++b) {
222            const double d8 = (double) ggml_fp16_to_fp32(hx[(size_t) e * kXNB + b].d);
223            for (int i = 0; i < 32; ++i)
224                xh[(size_t) e * ELL + 32 * b + i] = d8 * (double) hx[(size_t) e * kXNB + b].qs[i];
225        }
226    std::vector<float> wrow((size_t) ELL);
227    std::vector<double> ref((size_t) 2 * E * FF);
228    for (int r = 0; r < 1280; ++r) {
229        const bool is_up = r >= FF;
230        host_q3k_row(blob.data() + (size_t) r * kRowBytes, wrow.data());
231        const size_t proj = is_up ? 1 : 0;
232        const int f = r % FF;
233        for (int e = 0; e < E; ++e) {
234            const double* xr = xh.data() + (size_t) e * ELL;
235            double s = 0;
236            for (int k = 0; k < ELL; ++k) s += (double) wrow[(size_t) k] * xr[k];
237            ref[((proj * E) + e) * FF + f] = s;
238        }
239    }
240
241    // native_expert_grouped's gate/up only (its phase 3) on the same xq: the cross-check of the host reference
242    std::vector<float> ngate((size_t) E * FF), nup((size_t) E * FF);
243    {
244        const auto L = strata::kernels::native_expert_layout(GGML_TYPE_Q3_K, GGML_TYPE_IQ4_NL, ELL, FF);
245        void* nscratch = nullptr;
246        CK(cudaMalloc(&nscratch, strata::kernels::native_expert_scratch_bytes(E, FF)));
247        int32_t* ded = nullptr; int32_t* det = nullptr; int32_t* dnn = nullptr;
248        CK(cudaMalloc(&ded, (size_t) E * 4)); CK(cudaMalloc(&det, (size_t) E * 4)); CK(cudaMalloc(&dnn, 4));
249        std::vector<int32_t> id((size_t) E), ngv(1, G);
250        for (int e = 0; e < E; ++e) id[(size_t) e] = e;
251        CK(cudaMemcpy(ded, id.data(), id.size() * 4, cudaMemcpyHostToDevice));
252        CK(cudaMemcpy(det, id.data(), id.size() * 4, cudaMemcpyHostToDevice));
253        CK(cudaMemcpy(dnn, ngv.data(), 4, cudaMemcpyHostToDevice));
254        strata::kernels::native_expert_set_mode(-1, 3);
255        strata::kernels::native_expert_grouped(L, (const unsigned long long*) dblob, dgs, dnn, ded, det, G, E, dxq,
256                                               nscratch, dgate, nullptr, 0);
257        CK(cudaDeviceSynchronize());
258        const size_t fa = ((size_t) E * FF * sizeof(float) + 255) & ~(size_t) 255;
259        CK(cudaMemcpy(ngate.data(), nscratch, (size_t) E * FF * 4, cudaMemcpyDeviceToHost));
260        CK(cudaMemcpy(nup.data(), (const uint8_t*) nscratch + fa, (size_t) E * FF * 4, cudaMemcpyDeviceToHost));
261        strata::kernels::native_expert_set_mode(-1, 0);
262        auto cmp = [&](const std::vector<float>& a, const double* b, const char* tag) {
263            double num = 0, den = 0, aa = 0, bb = 0;
264            for (int e = 0; e < E; ++e)
265                for (int f = 0; f < FF; ++f) {
266                    const double x = a[(size_t) e * FF + f], y = b[(size_t) e * FF + f];
267                    num += x * y; aa += x * x; bb += y * y; den += std::fabs(y);
268                }
269            double dabs = 0;
270            for (int e = 0; e < E; ++e)
271                for (int f = 0; f < FF; ++f)
272                    dabs += std::fabs((double) a[(size_t) e * FF + f] - b[(size_t) e * FF + f]);
273            std::printf("%s vs host: cos %.9f  rel_mean %.3e\n", tag, num / (std::sqrt(aa) * std::sqrt(bb) + 1e-30),
274                        den > 0 ? dabs / den : 0.0);
275        };
276        cmp(ngate, ref.data(), "native gate");
277        cmp(nup, ref.data() + (size_t) E * FF, "native up  ");
278    }
279
280    // compared row by row: an (entry, projection)'s 640 values
281    double sabs = 0, sref = 0;
282    float dmax = 0.f;
283    double cosmin = 1.0;
284    int bad99 = 0, skipped = 0;
285    for (int proj = 0; proj < 2; ++proj)
286        for (int e = 0; e < E; ++e) {
287            const float* m = (proj ? up.data() : gate.data()) + (size_t) e * FF;
288            const double* rf = ref.data() + ((size_t) proj * E + e) * FF;
289            double num = 0, aa = 0, bb = 0;
290            for (int f = 0; f < FF; ++f) {
291                const double d = std::fabs((double) m[f] - rf[f]);
292                sabs += d; sref += std::fabs(rf[f]);
293                dmax = std::fmax(dmax, (float) d);
294                num += (double) m[f] * rf[f]; aa += (double) m[f] * m[f]; bb += rf[f] * rf[f];
295            }
296            if (aa == 0 && bb == 0) { ++skipped; continue; }
297            const double cos = num / (std::sqrt(aa) * std::sqrt(bb) + 1e-30);
298            cosmin = std::min(cosmin, cos);
299            if (cos < 0.99) ++bad99;
300        }
301    std::printf("rows=%d (skipped %d)  rel_mean=%.3e  max|d|=%.6e  cos_min=%.9f  rows<0.99=%d\n", 2 * E, skipped,
302                sref > 0 ? sabs / sref : 0.0, (double) dmax, cosmin, bad99);
303    std::printf("gate[0][0:8] mine:"); for (int f = 0; f < 8; ++f) std::printf(" %.6f", gate[(size_t) f]);
304    std::printf("\ngate[0][0:8] host:"); for (int f = 0; f < 8; ++f) std::printf(" %.6f", ref[(size_t) f]);
305    std::printf("\nup  [0][0:8] mine:"); for (int f = 0; f < 8; ++f) std::printf(" %.6f", up[(size_t) f]);
306    std::printf("\nup  [0][0:8] host:"); for (int f = 0; f < 8; ++f) std::printf(" %.6f", ref[(size_t) (E * FF) + f]);
307    std::printf("\n");
308
309    // ---- timing (informational) -------------------------------------------------------------------------------
310    {
311        auto t = [&] {
312            strata::prefill::lat_q3k_gu(dblob, dgs, G, dxq, dgate, dup, FF, nullptr);
313            CK(cudaDeviceSynchronize());
314            cudaEvent_t t0, t1; CK(cudaEventCreate(&t0)); CK(cudaEventCreate(&t1));
315            CK(cudaEventRecord(t0));
316            for (int i = 0; i < 20; ++i) strata::prefill::lat_q3k_gu(dblob, dgs, G, dxq, dgate, dup, FF, nullptr);
317            CK(cudaEventRecord(t1)); CK(cudaEventSynchronize(t1));
318            float ms = 0; CK(cudaEventElapsedTime(&ms, t0, t1));
319            CK(cudaEventDestroy(t0)); CK(cudaEventDestroy(t1));
320            return ms / 20.0;
321        };
322        const double ms = t();
323        // the same shape through native_expert_grouped's gate/up only (phase 3), informational as well
324        const auto L2 = strata::kernels::native_expert_layout(GGML_TYPE_Q3_K, GGML_TYPE_IQ4_NL, ELL, FF);
325        void* nsc = nullptr;
326        CK(cudaMalloc(&nsc, strata::kernels::native_expert_scratch_bytes(E, FF)));
327        int32_t* ded = nullptr; int32_t* det = nullptr; int32_t* dnn = nullptr;
328        CK(cudaMalloc(&ded, (size_t) E * 4)); CK(cudaMalloc(&det, (size_t) E * 4)); CK(cudaMalloc(&dnn, 4));
329        std::vector<int32_t> id2((size_t) E), ngv2(1, G);
330        for (int e = 0; e < E; ++e) id2[(size_t) e] = e;
331        CK(cudaMemcpy(ded, id2.data(), id2.size() * 4, cudaMemcpyHostToDevice));
332        CK(cudaMemcpy(det, id2.data(), id2.size() * 4, cudaMemcpyHostToDevice));
333        CK(cudaMemcpy(dnn, ngv2.data(), 4, cudaMemcpyHostToDevice));
334        strata::kernels::native_expert_set_mode(-1, 3);
335        auto tn = [&] {
336            strata::kernels::native_expert_grouped(L2, (const unsigned long long*) dblob, dgs, dnn, ded, det, G, E, dxq,
337                                                   nsc, dgate, nullptr, 0);
338            CK(cudaDeviceSynchronize());
339            cudaEvent_t t0, t1; CK(cudaEventCreate(&t0)); CK(cudaEventCreate(&t1));
340            CK(cudaEventRecord(t0));
341            for (int i = 0; i < 20; ++i)
342                strata::kernels::native_expert_grouped(L2, (const unsigned long long*) dblob, dgs, dnn, ded, det, G, E,
343                                                       dxq, nsc, dgate, nullptr, 0);
344            CK(cudaEventRecord(t1)); CK(cudaEventSynchronize(t1));
345            float ms2 = 0; CK(cudaEventElapsedTime(&ms2, t0, t1));
346            CK(cudaEventDestroy(t0)); CK(cudaEventDestroy(t1));
347            return ms2 / 20.0;
348        };
349        const double msn = tn();
350        std::printf("M2a gu: mine %.3f ms  %.2f us/entry | native gate/up only %.3f ms  %.2f us/entry (128 groups x 4 "
351                    "entries, informational)\n", ms, ms * 1000.0 / E, msn, msn * 1000.0 / E);
352    }
353
354    const bool ok = (sref > 0 ? sabs / sref : 1.0) <= 1e-3 && cosmin >= 0.9999 && bad99 == 0;
355    std::printf("%s: M2a (Q3_K gate/up)\n", ok ? "PASS" : "FAIL");
356    return ok ? 0 : 1;
357}