okami.mom/strata

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

Niko1221Merge f-mac-rel (Mac Metal support) into f-144-rel6a74320ca

main
14.8 KiB246 linesraw
1// metal/tests/gr2_parity.cpp - the two-dispatch hyper-connection read (gr2.metal: gr_down3 + gr_up3), BF16 and Q8_0
2// weights, against a double-precision reference of fused_gr.hpp's formulas on the SAME weights (the Q8_0 copy
3// dequantized for its own check), plus how far the Q8_0 read lands from the BF16 one; and the speed.
4//
5//   gr2_parity            parity: 1, 3 and 8 tokens, with and without the folded write, BF16 and Q8_0
6//   gr2_parity --bench    GPU time of the 2 dispatches (48 weight sets rotated) per tile, vs the 3-dispatch read
7#include "mtl_rt.h"
8#include "ref_quant.h"
9
10#include <algorithm>
11#include <cmath>
12#include <cstdio>
13#include <cstdlib>
14#include <cstring>
15#include <string>
16#include <vector>
17
18namespace {
19constexpr int N = 2560, HC = 4, LR = 320, NIN = HC * N, NR = LR + HC, MAXT = 8;
20struct GrArgs { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; };
21struct GrArgs3 { uint32_t n_embd, hc, hc_lr, n_tok, apply; float eps; uint32_t rb_down, rb_up, comb, topk; };
22double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
23struct Err {
24    double se = 0, sr = 0;
25    void add(double g, double r) { se += (g - r) * (g - r); sr += r * r; }
26    double l2() const { return sr > 0 ? std::sqrt(se / sr) : std::sqrt(se); }
27};
28}  // namespace
29
30int main(int argc, char** argv) {
31    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
32    mtl::Context cx;
33    const int lib = cx.compile({"quant.metal", "units.metal", "gr.metal", "gr2.metal"});
34    std::printf("device %s\n", cx.device_name().c_str());
35    const int SETS = bench ? 48 : 1;
36    const size_t bd = (size_t)LR * NIN * 2, bi = (size_t)HC * NIN * 2, bu = (size_t)NIN * LR * 2;
37    const size_t qd = (size_t)LR * NIN / 32 * 34, qi = (size_t)HC * NIN / 32 * 34, qu = (size_t)NIN * LR / 32 * 34;
38    const size_t set = bd + bi + bu + qd + qi + qu + NIN * 4;
39    mtl::Buffer W = cx.alloc(set * SETS);
40    ref::Rng rng(3);
41    {
42        uint8_t* b = W.as<uint8_t>();
43        ref::random_blocks(ref::BF16, b, LR, NIN, 11, 0.02f);
44        ref::random_blocks(ref::BF16, b + bd, HC, NIN, 22, 0.02f);
45        ref::random_blocks(ref::BF16, b + bd + bi, NIN, LR, 33, 0.1f);
46        std::vector<float> f((size_t)LR * NIN);
47        ref::dequant(ref::BF16, b, f.data(), (size_t)LR * NIN);
48        ref::quantize_q8_0(f.data(), (size_t)LR * NIN, b + bd + bi + bu);
49        ref::dequant(ref::BF16, b + bd, f.data(), (size_t)HC * NIN);
50        ref::quantize_q8_0(f.data(), (size_t)HC * NIN, b + bd + bi + bu + qd);
51        ref::dequant(ref::BF16, b + bd + bi, f.data(), (size_t)NIN * LR);
52        ref::quantize_q8_0(f.data(), (size_t)NIN * LR, b + bd + bi + bu + qd + qi);
53        float* wn = (float*)(b + bd + bi + bu + qd + qi + qu);
54        for (int i = 0; i < NIN; ++i) wn[i] = 1.0f + 0.1f * rng.sym();
55        for (int s = 1; s < SETS; ++s) std::memcpy(b + s * set, b, set);
56    }
57    mtl::Buffer R0 = cx.alloc(4 * MAXT * NIN), Rout = cx.alloc(4 * MAXT * NIN), bo = cx.alloc(4 * MAXT * N),
58                inj = cx.alloc(4 * MAXT * HC), Dprev = cx.alloc(4 * MAXT * NR * HC), D = cx.alloc(4 * MAXT * NR * HC),
59                rs = cx.alloc(4 * MAXT * HC), xp = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)),
60                xr = cx.alloc(4 * (4 * MAXT * N + MAXT * N / 16)), xpb = cx.alloc(4 * 2 * MAXT * N),
61                R3 = cx.alloc(4 * MAXT * NIN), xn = cx.alloc(4 * MAXT * NIN), lo = cx.alloc(4 * MAXT * LR),
62                injo = cx.alloc(4 * MAXT * HC);
63    for (int i = 0; i < MAXT * NIN; ++i) R0.as<float>()[i] = rng.sym() * 2.0f;
64    for (int i = 0; i < MAXT * N; ++i) bo.as<float>()[i] = rng.sym();
65    for (int i = 0; i < MAXT * HC; ++i) inj.as<float>()[i] = rng.sym() * 3.0f;
66    // the previous read's inject partials: stream 0 carries the whole value
67    for (int t = 0; t < MAXT; ++t)
68        for (int c = 0; c < HC; ++c) Dprev.as<float>()[(t * NR + LR + c) * HC] = inj.as<float>()[t * HC + c];
69    mtl::Pipeline pprep = cx.pipeline(lib, "xprep");
70    int fails = 0;
71    for (int nt : bench ? std::vector<int>{1, 3} : std::vector<int>{1, 3, 8}) {
72        for (int qq = 0; qq < 2; ++qq) {
73            const int q8 = std::getenv("GR_Q8FIRST") ? 1 - qq : qq;
74            const int F = q8 ? 8 : 30;
75            for (int tt : bench ? std::vector<int>{1, 2, 3} : std::vector<int>{3}) {
76                for (int rps : bench ? std::vector<int>{1, 2} : std::vector<int>{1}) {
77                    if (bench && tt > nt) continue;
78                    const char* pre = (!q8 && std::getenv("GR_PRELOAD")) ? "gr_down3b_" : "gr_down3_";
79                    const std::string dn = !q8 && std::getenv("GR_PRELOAD")
80                                               ? std::string(pre) + std::to_string(tt) + "_" + std::to_string(rps)
81                                               : std::string(pre) + std::to_string(F) + "_" + std::to_string(tt) + "_" + std::to_string(rps);
82                    mtl::Pipeline pd = cx.pipeline(lib, dn, mtl::Constants().i(1, nt)),
83                                  pu = cx.pipeline(lib, "gr_up3_" + std::to_string(F), mtl::Constants().i(1, nt));
84                    for (int apply = 0; apply < 2; ++apply) {
85                        if (bench && !apply) continue;
86                        GrArgs3 a{N, HC, LR, MAXT, (uint32_t)apply, 1e-6f, (uint32_t)(q8 ? NIN / 32 * 34 : NIN * 2),
87                                  (uint32_t)(q8 ? LR / 32 * 34 : LR * 2)};
88                        auto enc = [&](int s, std::vector<mtl::Dispatch>& ds) {
89                            const size_t o = (size_t)s * set;
90                            const size_t od = q8 ? o + bd + bi + bu : o, oi = q8 ? o + bd + bi + bu + qd : o + bd,
91                                         ou = q8 ? o + bd + bi + bu + qd + qi : o + bd + bi,
92                                         ow = o + bd + bi + bu + qd + qi + qu;
93                            mtl::Dispatch d;
94                            d.p = &pd;
95                            d.args = {mtl::Arg::B(W, od), mtl::Arg::B(W, oi), mtl::Arg::B(R0), mtl::Arg::B(Rout), mtl::Arg::B(bo),
96                                      mtl::Arg::B(Dprev), mtl::Arg::B(W, ow), mtl::Arg::B(D), mtl::Arg::B(rs), mtl::Arg::V(a)};
97                            d.grid[0] = (NR + 8 * rps - 1) / (8 * rps);
98                            d.grid[1] = HC;
99                            d.tg[0] = 256;
100                            ds.push_back(d);
101                            mtl::Dispatch u;
102                            u.p = &pu;
103                            u.args = {mtl::Arg::B(W, ou), mtl::Arg::B(D), mtl::Arg::B(Rout), mtl::Arg::B(xp), mtl::Arg::V(a),
104                                      mtl::Arg::B(W, ow), mtl::Arg::B(rs)};
105                            u.grid[0] = N / 16;
106                            u.tg[0] = 256;
107                            ds.push_back(u);
108                        };
109                        if (bench) {
110                            std::vector<mtl::Dispatch> ds;
111                            for (int k = 0; k < 96; ++k) enc(k % SETS, ds);
112                            if (const char* only = std::getenv("GR_ONLY")) {
113                                std::vector<mtl::Dispatch> o;
114                                for (size_t i = (std::string(only) == "up"); i < ds.size(); i += 2) o.push_back(ds[i]);
115                                ds = o;
116                            }
117                            cx.warm(ds, 0.1);
118                            std::vector<double> t;
119                            for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96);
120                            const double bytes = q8 ? qd + qi + qu : bd + bi + bu;
121                            std::printf("bench ntok %d %-4s TT %d RPS %d: 2 dispatches %7.2f us  %6.1f GB/s (%.2f MB)\n", nt,
122                                        q8 ? "Q8_0" : "BF16", tt, rps, median(t) * 1e6, bytes / median(t) / 1e9, bytes / 1e6);
123                            continue;
124                        }
125                        std::vector<mtl::Dispatch> ds;
126                        enc(0, ds);
127                        cx.run(ds);
128                        const uint8_t* b = W.as<uint8_t>();
129                        std::vector<float> wd((size_t)LR * NIN), wi((size_t)HC * NIN), wu((size_t)NIN * LR);
130                        const int ty = q8 ? ref::Q8_0 : ref::BF16;
131                        ref::dequant(ty, b + (q8 ? bd + bi + bu : 0), wd.data(), wd.size());
132                        ref::dequant(ty, b + (q8 ? bd + bi + bu + qd : bd), wi.data(), wi.size());
133                        ref::dequant(ty, b + (q8 ? bd + bi + bu + qd + qi : bd + bi), wu.data(), wu.size());
134                        const float* wn = (const float*)(b + bd + bi + bu + qd + qi + qu);
135                        Err eR, elo, einj, emix;
136                        for (int t = 0; t < nt; ++t) {
137                            std::vector<double> r(NIN), x(NIN);
138                            for (int c = 0; c < HC; ++c) {
139                                const double g = apply ? 2.0 / (1.0 + std::exp(-(double)inj.as<float>()[t * HC + c] / HC)) : 0.0;
140                                double ss = 0;
141                                for (int d = 0; d < N; ++d) {
142                                    double v = R0.as<float>()[t * NIN + c * N + d];
143                                    if (apply) v += bo.as<float>()[t * N + d] * g;
144                                    r[c * N + d] = v;
145                                    ss += v * v;
146                                }
147                                const double rsv = 1.0 / std::sqrt(ss / N + 1e-6);
148                                for (int d = 0; d < N; ++d) x[c * N + d] = r[c * N + d] * wn[c * N + d] * rsv;
149                            }
150                            for (int i = 0; i < NIN; ++i) eR.add(Rout.as<float>()[t * NIN + i], r[i]);
151                            std::vector<float> lg(LR);
152                            for (int k = 0; k < LR; ++k) {
153                                double s = 0;
154                                for (int i = 0; i < NIN; ++i) s += (double)wd[(size_t)k * NIN + i] * x[i];
155                                const double z = s / HC;
156                                const float* dp = D.as<float>() + (t * NR + k) * HC;
157                                const float zg = (((dp[0] + dp[1]) + dp[2]) + dp[3]) / (float)HC;
158                                lg[k] = zg / (1.0f + std::exp(-zg));
159                                elo.add(lg[k], z / (1.0 + std::exp(-z)));
160                            }
161                            for (int c = 0; c < HC; ++c) {
162                                double s = 0;
163                                for (int i = 0; i < NIN; ++i) s += (double)wi[(size_t)c * NIN + i] * x[i];
164                                const float* dp = D.as<float>() + (t * NR + LR + c) * HC;
165                                einj.add(((dp[0] + dp[1]) + dp[2]) + dp[3], s);
166                            }
167                            for (int d = 0; d < N; ++d) {
168                                double m = 0;
169                                for (int c = 0; c < HC; ++c) {
170                                    double s = 0;
171                                    for (int k = 0; k < LR; ++k) s += (double)wu[(size_t)(c * N + d) * LR + k] * lg[k];
172                                    m += x[c * N + d] / (1.0 + std::exp(-s));
173                                }
174                                emix.add(xp.as<float>()[t * N + d], m / HC);
175                            }
176                        }
177                        {
178                            mtl::Dispatch d;
179                            d.p = &pprep;
180                            const uint32_t n = N, ntt = MAXT;
181                            d.args = {mtl::Arg::B(xp), mtl::Arg::B(xr), mtl::Arg::V(n), mtl::Arg::V(ntt)};
182                            d.tg[0] = 256;
183                            d.grid[0] = (N / 16 * MAXT + 255) / 256;
184                            cx.run({d});
185                        }
186                        bool planes = true;
187                        for (int k = 0; k < 4; ++k)
188                            planes = planes && std::memcmp(xp.as<float>() + (size_t)k * MAXT * N,
189                                                           xr.as<float>() + (size_t)k * MAXT * N, 4 * (size_t)nt * N) == 0;
190                        planes = planes && std::memcmp(xp.as<float>() + 4 * MAXT * N, xr.as<float>() + 4 * MAXT * N,
191                                                       4 * nt * N / 16) == 0;
192                        double qdiff = -1;
193                        if (q8) {
194                            Err e;
195                            for (int i = 0; i < nt * N; ++i) e.add(xp.as<float>()[i], xpb.as<float>()[apply * MAXT * N + i]);
196                            qdiff = e.l2();
197                        } else {
198                            std::memcpy(xpb.as<float>() + apply * MAXT * N, xp.ptr, 4 * (size_t)MAXT * N);
199                        }
200                        const bool ok = eR.l2() < 1e-6 && elo.l2() < 1e-5 && einj.l2() < 1e-5 && emix.l2() < 1e-5 && planes;
201                        fails += !ok;
202                        char extra[96] = "";
203                        if (qdiff >= 0) std::snprintf(extra, sizeof extra, ", mixed vs the BF16 read %.2e", qdiff);
204                        std::printf("parity ntok %d %-4s apply %d: R' %.2e, lo %.2e, inject %.2e, mixed %.2e, planes %s%s  %s\n",
205                                    nt, q8 ? "Q8_0" : "BF16", apply, eR.l2(), elo.l2(), einj.l2(), emix.l2(),
206                                    planes ? "bitwise" : "NO", extra, ok ? "PASS" : "FAIL");
207                    }
208                }
209            }
210        }
211    }
212    if (bench) {
213        mtl::Pipeline pn = cx.pipeline(lib, "gr_norm"), pd = cx.pipeline(lib, "gr_down_8_8", mtl::Constants().i(1, 1)),
214                      pu = cx.pipeline(lib, "gr_up", mtl::Constants().i(1, 1));
215        GrArgs a{N, HC, LR, 1, 1, 1e-6f};
216        std::vector<mtl::Dispatch> ds;
217        for (int k = 0; k < 96; ++k) {
218            const size_t o = (size_t)(k % SETS) * set;
219            mtl::Dispatch d1, d2, d3;
220            d1.p = &pn;
221            d1.args = {mtl::Arg::B(R3), mtl::Arg::B(bo), mtl::Arg::B(inj), mtl::Arg::B(W, o + bd + bi + bu + qd + qi + qu),
222                       mtl::Arg::B(xn), mtl::Arg::V(a)};
223            d1.grid[0] = HC;
224            d1.tg[0] = 256;
225            d2.p = &pd;
226            d2.args = {mtl::Arg::B(W, o), mtl::Arg::B(W, o + bd), mtl::Arg::B(xn), mtl::Arg::B(lo), mtl::Arg::B(injo),
227                       mtl::Arg::V(a)};
228            d2.grid[0] = LR + HC;
229            d2.tg[0] = 256;
230            d3.p = &pu;
231            d3.args = {mtl::Arg::B(W, o + bd + bi), mtl::Arg::B(lo), mtl::Arg::B(xn), mtl::Arg::B(xp), mtl::Arg::V(a)};
232            d3.grid[0] = N / 16;
233            d3.tg[0] = 256;
234            ds.push_back(d1);
235            ds.push_back(d2);
236            ds.push_back(d3);
237        }
238        cx.warm(ds, 0.1);
239        std::vector<double> t;
240        for (int i = 0; i < 7; ++i) t.push_back(cx.run(ds) / 96);
241        std::printf("bench ntok 1 BF16 3-dispatch read (gr.metal): %.2f us\n", median(t) * 1e6);
242        return 0;
243    }
244    std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
245    return fails ? 1 : 0;
246}