okami.mom/strata

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

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

main
2.5 KiB61 linesraw
1// metal/tests/sample_parity.cpp - greedy argmax (sample.metal) vs the CPU over 248,320 logits with planted ties,
2// and its time.
3#include "mtl_rt.h"
4#include "ref_quant.h"
5
6#include <algorithm>
7#include <cmath>
8#include <cstdio>
9#include <vector>
10
11int main() {
12    constexpr uint32_t V = 248320, PARTS = 120;
13    mtl::Context cx;
14    const int lib = cx.compile({"sample.metal"}, "#define NO_GGML_COMMON 1\n");
15    mtl::Pipeline pp = cx.pipeline(lib, "argmax_part"), pf = cx.pipeline(lib, "argmax_final");
16    const int MAXT = 8;
17    mtl::Buffer lg = cx.alloc(4 * (size_t)V * MAXT), pv = cx.alloc(4 * PARTS * MAXT), pi = cx.alloc(4 * PARTS * MAXT),
18                out = cx.alloc(4 * MAXT);
19    ref::Rng r(5);
20    int fails = 0;
21    struct A { uint32_t n_vocab, parts; } a{V, PARTS};
22    for (int trial = 0; trial < 20; ++trial) {
23        const int nt = 1 + trial % MAXT;
24        for (size_t i = 0; i < (size_t)V * nt; ++i) lg.as<float>()[i] = std::round(r.sym() * 1000.0f) / 100.0f;
25        for (int t = 0; t < nt; ++t) {
26            // plant a tie at the maximum
27            const size_t i1 = r.next() % V, i2 = r.next() % V;
28            lg.as<float>()[t * V + i1] = 20.0f;
29            lg.as<float>()[t * V + i2] = 20.0f;
30        }
31        mtl::Dispatch d1, d2;
32        d1.p = &pp;
33        d1.args = {mtl::Arg::B(lg), mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::V(a)};
34        d1.grid[0] = PARTS;
35        d1.grid[1] = nt;
36        d1.tg[0] = 256;
37        d2.p = &pf;
38        d2.args = {mtl::Arg::B(pv), mtl::Arg::B(pi), mtl::Arg::B(out), mtl::Arg::V(a)};
39        d2.grid[0] = nt;
40        d2.tg[0] = 256;
41        cx.run({d1, d2});
42        for (int t = 0; t < nt; ++t) {
43            const float* l = lg.as<float>() + (size_t)t * V;
44            int best = 0;
45            for (uint32_t i = 1; i < V; ++i)
46                if (l[i] > l[best]) best = (int)i;
47            fails += out.as<int>()[t] != best;
48        }
49        if (trial == 19) {
50            std::vector<mtl::Dispatch> ds;
51            for (int k = 0; k < 64; ++k) { ds.push_back(d1); ds.push_back(d2); }
52            cx.warm(ds, 0.05);
53            std::vector<double> ts;
54            for (int k = 0; k < 7; ++k) ts.push_back(cx.run(ds) / 64);
55            std::sort(ts.begin(), ts.end());
56            std::printf("argmax %d token(s) over %u logits: %.2f us (2 dispatches)\n", nt, V, ts[3] * 1e6);
57        }
58    }
59    std::printf("argmax parity, 20 windows with planted ties: %d wrong  %s\n", fails, fails ? "FAIL" : "PASS");
60    return fails ? 1 : 0;
61}