okami.mom/strata

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

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

main
7.7 KiB139 linesraw
1// metal/tests/dense_mm_parity.cpp - dense prompt projections (dense_mm.metal): dequantize to fp16 once, then the
2// MPP GEMM. Parity vs a reference with the same fp16 operands (and the exact float one), every dense format and
3// awkward row counts; then the speed on the packs' shapes for a 2048-token chunk.
4//   dense_mm_parity            parity
5//   dense_mm_parity --bench    speed
6#include "mtl_rt.h"
7#include "ref_quant.h"
8
9#include <algorithm>
10#include <cmath>
11#include <cstdio>
12#include <cstring>
13#include <string>
14#include <vector>
15
16namespace {
17struct DqArgs { uint32_t n_in, n_out, row_bytes, perm; };
18struct GemmArgs { int M, N, K, pad; };
19double median(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }
20float h16(float v) { return ref::f16_to_f32(ref::f32_to_f16(v)); }
21int unit_of(int t) {
22    switch (t) {
23        case ref::Q2_0: case ref::IQ3_S: case ref::BF16: case ref::F32: return 16;
24        default: return 32;
25    }
26}
27}  // namespace
28
29int main(int argc, char** argv) {
30    const bool bench = argc > 1 && std::string(argv[1]) == "--bench";
31    mtl::Context cx;
32    const int lib = cx.compile({"quant.metal", "units.metal", "mma.metal", "dense_mm.metal"});
33    std::printf("device %s\n", cx.device_name().c_str());
34    mtl::Pipeline pact = cx.pipeline(lib, "act_f16");
35    auto run_all = [&](int ty, const mtl::Buffer& W, size_t woff, int n_in, int n_out, int T, const mtl::Buffer& x,
36                       const mtl::Buffer& xh, const mtl::Buffer& wh, const mtl::Buffer& y, const std::string& gk,
37                       std::vector<mtl::Dispatch>& ds, int which) {
38        static std::vector<mtl::Pipeline*> keep;
39        mtl::Pipeline* pdq = new mtl::Pipeline(cx.pipeline(lib, "dq_f16_" + std::to_string(ty)));
40        mtl::Pipeline* pg = new mtl::Pipeline(cx.pipeline(lib, gk));
41        keep.push_back(pdq);
42        keep.push_back(pg);
43        int tm = 64, tn = 64;
44        std::sscanf(gk.c_str(), "gemm_f16_%d_%d", &tm, &tn);
45        if (which & 1) {
46            const uint32_t n = (uint32_t)T * n_in;
47            mtl::Dispatch d; d.p = &pact; d.args = {mtl::Arg::B(x), mtl::Arg::B(xh), mtl::Arg::V(n)};
48            d.grid[0] = (n + 255) / 256; d.tg[0] = 256; ds.push_back(d);
49        }
50        if (which & 2) {
51            DqArgs a{(uint32_t)n_in, (uint32_t)n_out, (uint32_t)ref::row_bytes(ty, n_in)};
52            mtl::Dispatch d; d.p = pdq; d.args = {mtl::Arg::B(W, woff), mtl::Arg::B(wh), mtl::Arg::V(a)};
53            d.grid[0] = (n_in / unit_of(ty) + 63) / 64; d.grid[1] = n_out; d.tg[0] = 64; ds.push_back(d);
54        }
55        if (which & 4) {
56            GemmArgs g{T, n_out, n_in, 0};
57            mtl::Dispatch d; d.p = pg; d.args = {mtl::Arg::B(xh), mtl::Arg::B(wh), mtl::Arg::B(y), mtl::Arg::V(g)};
58            d.grid[0] = (n_out + tn - 1) / tn; d.grid[1] = (T + tm - 1) / tm; d.tg[0] = 128; ds.push_back(d);
59        }
60    };
61    const std::vector<int> types = {ref::F32, ref::BF16, ref::Q8_0, ref::Q4_0, ref::Q5_0, ref::IQ4_NL, ref::IQ4_XS, ref::Q2_0,
62                                    ref::IQ3_S, ref::Q3_K, ref::Q4_K, ref::Q5_K, ref::Q6_K};
63    if (!bench) {
64        int fails = 0;
65        for (int ty : types)
66            for (int n_in : {2560, 640, 6144}) {
67                if (n_in % 256 && ref::block_elems(ty) == 256) continue;
68                for (int n_out : {100, 48}) {
69                    const int T = 72;
70                    const size_t rb = ref::row_bytes(ty, n_in);
71                    mtl::Buffer W = cx.alloc(rb * n_out), x = cx.alloc(4 * (size_t)T * n_in), xh = cx.alloc(2 * (size_t)T * n_in),
72                                wh = cx.alloc(2 * (size_t)n_out * n_in), y = cx.alloc(4 * (size_t)T * n_out);
73                    ref::random_blocks(ty, W.as<uint8_t>(), n_out, n_in, 5 + ty + n_in, 0.02f);
74                    ref::Rng r(3);
75                    for (size_t i = 0; i < (size_t)T * n_in; ++i) x.as<float>()[i] = r.sym();
76                    std::vector<mtl::Dispatch> ds;
77                    run_all(ty, W, 0, n_in, n_out, T, x, xh, wh, y, "gemm_f16_64_64_4", ds, 7);
78                    cx.run(ds);
79                    std::vector<float> wf((size_t)n_in * n_out);
80                    ref::dequant(ty, W.ptr, wf.data(), wf.size());
81                    double se16 = 0, se = 0, sr = 0;
82                    for (int t = 0; t < T; ++t)
83                        for (int o = 0; o < n_out; ++o) {
84                            double a16 = 0, ae = 0;
85                            for (int k = 0; k < n_in; ++k) {
86                                const float xv = x.as<float>()[(size_t)t * n_in + k], wv = wf[(size_t)o * n_in + k];
87                                a16 += (double)h16(xv) * h16(wv);
88                                ae += (double)xv * wv;
89                            }
90                            const double g = y.as<float>()[(size_t)t * n_out + o];
91                            se16 += (g - a16) * (g - a16);
92                            se += (g - ae) * (g - ae);
93                            sr += ae * ae;
94                        }
95                    const double r16 = std::sqrt(se16 / sr), re = std::sqrt(se / sr);
96                    const bool ok = r16 < 1e-5;
97                    fails += !ok;
98                    std::printf("dense mm %-7s %5d -> %4d, T %d: vs fp16 operands %.2e, vs exact %.2e  %s\n",
99                                ref::type_name(ty), n_in, n_out, T, r16, re, ok ? "PASS" : "FAIL");
100                }
101            }
102        std::printf("%s\n", fails ? "SOME FAILED" : "ALL PASS");
103        return fails ? 1 : 0;
104    }
105    struct Shape { const char* name; int type, n_in, n_out; };
106    const std::vector<Shape> shapes = {{"gdn qkv", ref::IQ4_XS, 2560, 10240}, {"gdn qkv", ref::Q3_K, 2560, 10240},
107                                       {"gdn gate", ref::Q4_K, 2560, 6144},   {"gdn out", ref::Q6_K, 6144, 2560},
108                                       {"qsa q", ref::Q2_0, 2560, 12288},     {"hc down", ref::BF16, 10240, 324},
109                                       {"hc up", ref::BF16, 320, 10240},      {"router", ref::BF16, 2560, 512},
110                                       {"alpha", ref::BF16, 2560, 48}};
111    const int T = 2048;
112    for (const Shape& s : shapes) {
113        if (s.n_in % 128) { std::printf("%-9s %-6s: n_in %d not a multiple of 128 (needs the 32-chunk path)\n", s.name, ref::type_name(s.type), s.n_in); continue; }
114        const size_t rb = ref::row_bytes(s.type, s.n_in);
115        mtl::Buffer W = cx.alloc(rb * s.n_out), x = cx.alloc(4 * (size_t)T * s.n_in), xh = cx.alloc(2 * (size_t)T * s.n_in),
116                    wh = cx.alloc(2 * (size_t)s.n_out * s.n_in), y = cx.alloc(4 * (size_t)T * s.n_out);
117        ref::random_blocks(s.type, W.as<uint8_t>(), s.n_out, s.n_in, 3, 0.02f);
118        auto timeit = [&](int which, const std::string& gk) {
119            std::vector<mtl::Dispatch> ds;
120            for (int i = 0; i < 4; ++i) run_all(s.type, W, 0, s.n_in, s.n_out, T, x, xh, wh, y, gk, ds, which);
121            cx.warm(ds, 0.2);
122            std::vector<double> t;
123            for (int i = 0; i < 5; ++i) t.push_back(cx.run(ds) / 4);
124            return median(t);
125        };
126        const double tdq = timeit(2, "gemm_f16_64_64_4"), tact = timeit(1, "gemm_f16_64_64_4");
127        double best = 1e9;
128        std::string bk;
129        for (const char* gk : {"gemm_f16_64_64_4", "gemm_f16_128_64_4", "gemm_f16_64_128_4", "gemm_f16_64_32_4"}) {
130            const double tg = timeit(4, gk);
131            if (tg < best) { best = tg; bk = gk; }
132        }
133        const double fl = 2.0 * T * s.n_in * s.n_out;
134        std::printf("%-9s %-6s %5d -> %5d, T %d: dequant %7.1f us, act %6.1f us, GEMM %7.1f us (%5.1f TFLOP/s, %s) -> %.2f us a token\n",
135                    s.name, ref::type_name(s.type), s.n_in, s.n_out, T, tdq * 1e6, tact * 1e6, best * 1e6, fl / best / 1e12,
136                    bk.c_str(), (tdq + best) / T * 1e6);
137    }
138    return 0;
139}