okami.mom/strata

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

Niko1221Merge f-151-b70 (c765c5f87) into f-split-int283cde2ca3

main
16.2 KiB284 linesraw
1// esimd_moe_parity (151-b70): the fused int8 DPAS expert products (prefill/esimd_moe.dp.cpp) against
2//   (a) the engine's dequantize + oneMKL path (FP16 weights, FP16 activations), the path they replace,
3//   (b) an FP64 host reference from the blobs with the unquantized activations,
4//   (c) an exact host reference on the SAME int8 activations the device produced (isolates the kernel arithmetic from the
5//       activation quantization: only the float accumulation order differs),
6// for every gate/up x down type pair the kernels handle, and times both paths per expert.
7//   esimd_moe_parity [mean_rows=80] [experts=16] [reps=10] [seed=1] [gate_up_type down_type]
8//   types: gate/up 21 IQ3_S, 18 IQ3_XXS, 22 IQ2_S; down 20 IQ4_NL, 42 Q2_0.
9// Exit status 1 when (c) is off by more than 2e-5 of the largest value or (b) exceeds the int8 activation error budget.
10#include "strata/kernels/iq_kernels.hpp"
11#include "strata/kernels/iq_dequant_expert.hpp"
12#include "strata/prefill/esimd_moe.hpp"
13#include "strata/prefill/kernels.hpp"
14#include "strata/sycl_queue.hpp"
15#include <sycl/sycl.hpp>
16#include <dpct/dpct.hpp>
17#include <dpct/blas_utils.hpp>
18#include <algorithm>
19#include <chrono>
20#include <cmath>
21#include <cstdio>
22#include <cstdlib>
23#include <cstring>
24#include <random>
25#include <vector>
26
27#define GGML_TABLE_BEGIN(type, name, size) static const type name[size] = {
28#define GGML_TABLE_END() };
29#include "../prefill/iq_tables.inc"
30
31namespace i8 = strata::prefill::i8;
32static uint16_t f2h(float f) { return sycl::bit_cast<uint16_t>(sycl::half(f)); }
33static float h2f(uint16_t h) { return (float) sycl::bit_cast<sycl::half>(h); }
34
35static int block_bytes(int t) { return t == 21 ? 110 : t == 18 ? 98 : t == 22 ? 82 : 18; }
36static int block_vals(int t) { return (t == 21 || t == 18 || t == 22) ? 256 : t == 42 ? 64 : 32; }
37
38// host decode of one row (K values) -> double
39static void dec_row(int t, const uint8_t* row, int K, double* out) {
40    const int bb = block_bytes(t), bv = block_vals(t);
41    for (int b = 0; b < K / bv; ++b) {
42        const uint8_t* blk = row + (size_t) b * bb;
43        uint16_t dh; std::memcpy(&dh, blk, 2);
44        const double d = h2f(dh);
45        double* o = out + (size_t) b * bv;
46        if (t == 21) {
47            const uint8_t *qs = blk + 2, *qh = blk + 66, *sgn = blk + 74, *scl = blk + 106;
48            for (int ib = 0; ib < 8; ++ib) {
49                const double dd = d * (1 + 2 * ((scl[ib / 2] >> (4 * (ib % 2))) & 0xf));
50                for (int r = 0; r < 8; ++r) {
51                    const int idx = qs[8 * ib + r] | (((qh[ib] >> r) & 1) << 8);
52                    const uint8_t* g = (const uint8_t*) &iq3s_grid[idx];
53                    const uint8_t sb = sgn[4 * ib + r / 2];
54                    for (int j = 0; j < 4; ++j) o[ib * 32 + 4 * r + j] = dd * ((sb >> (4 * (r & 1) + j) & 1) ? -(int) g[j] : (int) g[j]);
55                }
56            }
57        } else if (t == 18) {
58            const uint8_t* qs = blk + 2;
59            for (int ib = 0; ib < 8; ++ib) {
60                uint32_t aux; std::memcpy(&aux, blk + 66 + 4 * ib, 4);
61                const double dd = d * (0.5 + (aux >> 28)) * 0.5;
62                for (int l = 0; l < 4; ++l) {
63                    const uint8_t sb = ksigns_iq2xs[(aux >> (7 * l)) & 127];
64                    const uint8_t *g1 = (const uint8_t*) &iq3xxs_grid[qs[8 * ib + 2 * l]], *g2 = (const uint8_t*) &iq3xxs_grid[qs[8 * ib + 2 * l + 1]];
65                    for (int j = 0; j < 4; ++j) {
66                        o[ib * 32 + 8 * l + j] = dd * ((sb >> j & 1) ? -(int) g1[j] : (int) g1[j]);
67                        o[ib * 32 + 8 * l + 4 + j] = dd * ((sb >> (4 + j) & 1) ? -(int) g2[j] : (int) g2[j]);
68                    }
69                }
70            }
71        } else if (t == 22) {
72            const uint8_t *qs = blk + 2, *qh = blk + 66, *scl = blk + 74, *sgn = blk + 34;
73            for (int ib = 0; ib < 8; ++ib)
74                for (int l = 0; l < 4; ++l) {
75                    const int idx = qs[4 * ib + l] | ((qh[ib] << (8 - 2 * l)) & 0x300);
76                    const uint8_t* g = (const uint8_t*) &iq2s_grid[idx];
77                    const double dd = d * (0.5 + ((scl[ib] >> (4 * (l / 2))) & 0xf)) * 0.25;
78                    const uint8_t sb = sgn[4 * ib + l];
79                    for (int j = 0; j < 8; ++j) o[ib * 32 + 8 * l + j] = dd * ((sb >> j & 1) ? -(int) g[j] : (int) g[j]);
80                }
81        } else if (t == 20) {
82            for (int j = 0; j < 16; ++j) {
83                o[j] = d * kvalues_iq4nl[blk[2 + j] & 15];
84                o[16 + j] = d * kvalues_iq4nl[blk[2 + j] >> 4];
85            }
86        } else {   // 42 Q2_0
87            for (int i = 0; i < 64; ++i) o[i] = d * (((blk[2 + i / 4] >> ((i % 4) * 2)) & 3) - 1);
88        }
89    }
90}
91
92struct Result { bool ok; double t_ref, t_fused; };
93
94static Result run_case(sycl::queue* q, dpct::blas::descriptor_ptr hd, int gt, int dt, int mean, int n, int reps, int seed) {
95    const int K = 2560, NFF = 640, NE = 2560;
96    std::mt19937 rng(seed);
97    std::vector<int32_t> cnt(n);
98    std::gamma_distribution<double> gd(1.5, mean / 1.5);
99    int tot = 0;
100    for (auto& c : cnt) { c = std::max(1, (int) gd(rng)); tot += c; }
101    if (n >= 3) { cnt[0] = 1; cnt[1] = 7; cnt[2] = 9; tot = 0; for (int c : cnt) tot += c; }   // pad edge cases
102    i8::Layout lo;
103    i8::make_layout(lo, cnt.data(), n);
104
105    const size_t rowb_gu = (size_t) (K / block_vals(gt)) * block_bytes(gt), rowb_dn = (size_t) (NFF / block_vals(dt)) * block_bytes(dt);
106    const size_t gate_b = NFF * rowb_gu, down_b = NE * rowb_dn, blob_b = 2 * gate_b + down_b;
107    std::vector<std::vector<uint8_t>> hb(n);
108    std::vector<uint8_t*> db(n);
109    for (int i = 0; i < n; ++i) {
110        hb[i].resize(blob_b);
111        for (auto& x : hb[i]) x = (uint8_t) rng();
112        for (size_t o = 0; o < 2 * gate_b; o += block_bytes(gt)) { const uint16_t d = f2h(0.0004f + 0.00002f * (rng() % 50)); std::memcpy(&hb[i][o], &d, 2); }
113        for (size_t o = 2 * gate_b; o < blob_b; o += block_bytes(dt)) { const uint16_t d = f2h(0.0004f + 0.00002f * (rng() % 50)); std::memcpy(&hb[i][o], &d, 2); }
114        db[i] = sycl::malloc_device<uint8_t>(blob_b + 256, *q);
115        q->memcpy(db[i], hb[i].data(), blob_b);
116    }
117    std::vector<uint16_t> hx((size_t) tot * K);
118    std::normal_distribution<float> nd(0.f, 1.f);
119    for (auto& x : hx) { float v = nd(rng) * 0.5f; if (rng() % 97 == 0) v *= 12.f; x = f2h(v); }   // a few outliers
120    uint16_t* dxh = sycl::malloc_device<uint16_t>(hx.size(), *q);
121    q->memcpy(dxh, hx.data(), hx.size() * 2);
122    int8_t* Xq = sycl::malloc_device<int8_t>(i8::xq_bytes(lo, K), *q);
123    float* dX = sycl::malloc_device<float>(i8::dx_bytes(lo, K) / 4, *q);
124    int8_t* Hq = sycl::malloc_device<int8_t>(i8::xq_bytes(lo, NFF), *q);
125    float* dH = sycl::malloc_device<float>(i8::dx_bytes(lo, NFF) / 4, *q);
126    float *GU = sycl::malloc_device<float>((size_t) tot * 2 * NFF, *q), *Dm = sycl::malloc_device<float>((size_t) tot * NE, *q);
127    float *GUr = sycl::malloc_device<float>((size_t) tot * 2 * NFF, *q), *Dmr = sycl::malloc_device<float>((size_t) tot * NE, *q);
128    uint16_t* Hh = sycl::malloc_device<uint16_t>((size_t) tot * NFF, *q);
129    uint16_t* dwgu = sycl::malloc_device<uint16_t>((size_t) 2 * NFF * K, *q);
130    uint16_t* dwd = sycl::malloc_device<uint16_t>((size_t) NE * NFF, *q);
131    q->wait();
132    std::vector<const uint8_t*> pb(n);
133    for (int i = 0; i < n; ++i) pb[i] = db[i];
134
135    auto fused = [&]() {
136        i8::quantize_rows(dxh, lo, K, Xq, dX, q);
137        if (!i8::gate_up(gt, pb.data(), gate_b, NFF, lo, K, Xq, dX, GU, q)) { std::printf("gate_up refused (type %d)\n", gt); std::exit(2); }
138        i8::swiglu_quantize(GU, lo, NFF, Hq, dH, q);
139        if (!i8::down(dt, pb.data(), 2 * gate_b, NE, lo, NFF, Hq, dH, Dm, q)) { std::printf("down refused (type %d)\n", dt); std::exit(2); }
140    };
141    auto ref = [&]() {
142        int64_t o = 0;
143        for (int i = 0; i < n; ++i) {
144            strata::kernels::iq_dequant_expert_f16(gt, dt, db[i], db[i] + gate_b, db[i] + 2 * gate_b, NFF, K, dwgu, dwd, q);
145            const float a = 1.f, b = 0.f;
146            dpct::blas::gemm(hd, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, 2 * NFF, cnt[i], K, &a, dwgu,
147                             dpct::library_data_t::real_half, K, dxh + o * K, dpct::library_data_t::real_half, K, &b,
148                             GUr + o * 2 * NFF, dpct::library_data_t::real_float, 2 * NFF, dpct::compute_type::f32);
149            strata::prefill::swiglu_interleaved(GUr + o * 2 * NFF, Hh + o * NFF, cnt[i], q);
150            dpct::blas::gemm(hd, oneapi::mkl::transpose::trans, oneapi::mkl::transpose::nontrans, NE, cnt[i], NFF, &a, dwd,
151                             dpct::library_data_t::real_half, NFF, Hh + o * NFF, dpct::library_data_t::real_half, NFF, &b,
152                             Dmr + o * NE, dpct::library_data_t::real_float, NE, dpct::compute_type::f32);
153            o += cnt[i];
154        }
155    };
156    auto tm = [&](auto f) {
157        f(); q->wait();
158        const auto t0 = std::chrono::steady_clock::now();
159        while (std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count() < 0.5) { f(); q->wait(); }   // GPU clocks up
160        const auto a = std::chrono::steady_clock::now();
161        for (int r = 0; r < reps; ++r) f();
162        q->wait();
163        return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - a).count() / reps;
164    };
165
166    fused(); q->wait();
167    std::vector<int8_t> hXq(i8::xq_bytes(lo, K));
168    std::vector<float> hdX(i8::dx_bytes(lo, K) / 4), hGU((size_t) tot * 2 * NFF);
169    q->memcpy(hXq.data(), Xq, hXq.size());
170    q->memcpy(hdX.data(), dX, hdX.size() * 4);
171    q->memcpy(hGU.data(), GU, hGU.size() * 4).wait();
172    const int nkb = K / 32;
173    auto xq_at = [&](int tile, int r, int k) { return (int) hXq[(((size_t) tile * nkb + k / 32) * 8 + r) * 32 + (k % 32)]; };
174    auto dx_at = [&](int tile, int r, int kb) { return (double) hdX[((size_t) tile * nkb + kb) * 8 + r]; };
175    bool ok = true;
176    std::vector<double> wrow(K);
177    double err_c = 0, mx_c = 0, err_b = 0, rms_bref = 0;
178    int sampled = 0;
179    for (int e = 0; e < n; ++e)
180        for (int rl = 0; rl < cnt[e]; rl += (cnt[e] > 12 ? 5 : 1)) {
181            const int tile = lo.tile0[e] + rl / 8, r = rl % 8, row = lo.row0[e] + rl;
182            for (int v = 0; v < 2 * NFF; v += 37) {
183                dec_row(gt, &hb[e][(size_t) (v & 1 ? gate_b : 0) + (size_t) (v >> 1) * rowb_gu], K, wrow.data());
184                double refc = 0, refb = 0;
185                for (int kb = 0; kb < nkb; ++kb) {
186                    double s = 0;
187                    for (int k = 0; k < 32; ++k) s += (double) xq_at(tile, r, kb * 32 + k) * wrow[kb * 32 + k];
188                    refc += s * dx_at(tile, r, kb);
189                }
190                for (int k = 0; k < K; ++k) refb += (double) h2f(hx[(size_t) row * K + k]) * wrow[k];
191                const double got = hGU[(size_t) row * 2 * NFF + v];
192                err_c = std::max(err_c, std::fabs(got - refc)); mx_c = std::max(mx_c, std::fabs(refc));
193                err_b += (got - refb) * (got - refb); rms_bref += refb * refb;
194                ++sampled;
195            }
196        }
197    const bool ok1 = err_c <= 2e-5 * mx_c && std::sqrt(err_b / rms_bref) < 0.02;
198    ok = ok && ok1;
199    std::printf("  gate/up type %2d: exact-int8 ref max err %.2e of %.2e (%.1e)  vs FP64 true rms rel err %.2e (%d samples)  %s\n", gt,
200                err_c, mx_c, err_c / mx_c, std::sqrt(err_b / rms_bref), sampled, ok1 ? "OK" : "FAIL");
201    {
202        std::vector<int8_t> hHq(i8::xq_bytes(lo, NFF));
203        std::vector<float> hdH(i8::dx_bytes(lo, NFF) / 4), hDm((size_t) tot * NE);
204        q->memcpy(hHq.data(), Hq, hHq.size());
205        q->memcpy(hdH.data(), dH, hdH.size() * 4);
206        q->memcpy(hDm.data(), Dm, hDm.size() * 4).wait();
207        const int nkh = NFF / 32;
208        double ec = 0, mc = 0, eb = 0, rb = 0, hq_bad = 0;
209        std::vector<double> drow(NFF);
210        int smp = 0;
211        for (int e = 0; e < n; ++e)
212            for (int rl = 0; rl < cnt[e]; rl += (cnt[e] > 12 ? 5 : 1)) {
213                const int tile = lo.tile0[e] + rl / 8, r = rl % 8, row = lo.row0[e] + rl;
214                std::vector<double> H(NFF);
215                for (int j = 0; j < NFF; ++j) {
216                    const double g = hGU[(size_t) row * 2 * NFF + 2 * j], u = hGU[(size_t) row * 2 * NFF + 2 * j + 1];
217                    H[j] = g / (1.0 + std::exp(-g)) * u;
218                }
219                for (int kb = 0; kb < nkh; ++kb) {
220                    double amax = 0; for (int k = 0; k < 32; ++k) amax = std::max(amax, std::fabs(H[kb * 32 + k]));
221                    const double dd = hdH[((size_t) tile * nkh + kb) * 8 + r];
222                    if (std::fabs(dd - amax / 127.0) > 1e-5 * amax + 1e-30) hq_bad += 1;
223                }
224                for (int v = 0; v < NE; v += 41) {
225                    dec_row(dt, &hb[e][2 * gate_b + (size_t) v * rowb_dn], NFF, drow.data());
226                    double refc = 0, refb = 0;
227                    for (int kb = 0; kb < nkh; ++kb) {
228                        double s = 0;
229                        for (int k = 0; k < 32; ++k) s += (double) hHq[(((size_t) tile * nkh + kb) * 8 + r) * 32 + k] * drow[kb * 32 + k];
230                        refc += s * hdH[((size_t) tile * nkh + kb) * 8 + r];
231                    }
232                    for (int k = 0; k < NFF; ++k) refb += H[k] * drow[k];
233                    const double got = hDm[(size_t) row * NE + v];
234                    ec = std::max(ec, std::fabs(got - refc)); mc = std::max(mc, std::fabs(refc));
235                    eb += (got - refb) * (got - refb); rb += refb * refb;
236                    ++smp;
237                }
238            }
239        const bool ok2 = ec <= 2e-5 * mc && std::sqrt(eb / rb) < 0.03 && hq_bad == 0;
240        ok = ok && ok2;
241        std::printf("  down type %2d   : exact-int8 ref max err %.2e of %.2e (%.1e)  vs FP64 true rms rel err %.2e, swiglu scale mismatches %.0f (%d samples)  %s\n",
242                    dt, ec, mc, ec / mc, std::sqrt(eb / rb), hq_bad, smp, ok2 ? "OK" : "FAIL");
243    }
244    ref(); q->wait();
245    {
246        std::vector<float> a((size_t) tot * NE), b((size_t) tot * NE);
247        q->memcpy(a.data(), Dmr, a.size() * 4);
248        q->memcpy(b.data(), Dm, b.size() * 4).wait();
249        double e2 = 0, r2 = 0;
250        for (size_t i = 0; i < a.size(); ++i) { e2 += (double) (a[i] - b[i]) * (a[i] - b[i]); r2 += (double) a[i] * a[i]; }
251        std::printf("  chain vs dequantize + oneMKL (FP16 path): rms rel diff %.2e (rows %d)\n", std::sqrt(e2 / r2), tot);
252    }
253    Result res{ok, tm(ref) / n, tm(fused) / n};
254    const double t_q = tm([&] { i8::quantize_rows(dxh, lo, K, Xq, dX, q); }) / n;
255    const double t_gu = tm([&] { i8::gate_up(gt, pb.data(), gate_b, NFF, lo, K, Xq, dX, GU, q); }) / n;
256    const double t_sw = tm([&] { i8::swiglu_quantize(GU, lo, NFF, Hq, dH, q); }) / n;
257    const double t_dn = tm([&] { i8::down(dt, pb.data(), 2 * gate_b, NE, lo, NFF, Hq, dH, Dm, q); }) / n;
258    std::printf("  rows %d (%d experts, mean %.0f): dequant+oneMKL %.1f us/expert | fused int8 %.1f us/expert (%.2fx)  [quantize %.1f, gate/up %.1f, swiglu+q %.1f, down %.1f]\n",
259                tot, n, (double) tot / n, res.t_ref, res.t_fused, res.t_ref / res.t_fused, t_q, t_gu, t_sw, t_dn);
260    for (int i = 0; i < n; ++i) sycl::free(db[i], *q);
261    sycl::free(dxh, *q); sycl::free(Xq, *q); sycl::free(dX, *q); sycl::free(Hq, *q); sycl::free(dH, *q); sycl::free(GU, *q);
262    sycl::free(Dm, *q); sycl::free(GUr, *q); sycl::free(Dmr, *q); sycl::free(Hh, *q); sycl::free(dwgu, *q); sycl::free(dwd, *q);
263    return res;
264}
265
266int main(int argc, char** argv) {
267    const int mean = argc > 1 ? std::atoi(argv[1]) : 80;
268    const int n = argc > 2 ? std::atoi(argv[2]) : 16;
269    const int reps = argc > 3 ? std::atoi(argv[3]) : 10;
270    const int seed = argc > 4 ? std::atoi(argv[4]) : 1;
271    sycl::queue* q = &dpct::get_in_order_queue();
272    if (!i8::available(q)) { std::printf("esimd_moe_parity: SKIP (no ESIMD device with the s8 8x16x32 DPAS)\n"); return 0; }
273    dpct::blas::descriptor_ptr hd = new dpct::blas::descriptor();
274    hd->set_queue(q);
275    std::vector<std::pair<int, int>> cases = {{21, 20}, {18, 20}, {22, 20}, {21, 42}, {18, 42}, {22, 42}};
276    if (argc > 6) cases = {{std::atoi(argv[5]), std::atoi(argv[6])}};
277    int fails = 0;
278    for (auto [gt, dt] : cases) {
279        std::printf("gate/up %d, down %d, mean %d rows, %d experts\n", gt, dt, mean, n);
280        fails += !run_case(q, hd, gt, dt, mean, n, reps, seed).ok;
281    }
282    std::printf("%s\n", fails ? "FAILED" : "all OK");
283    return fails ? 1 : 0;
284}