okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-intel (2b4d43bac)5438023a6

main
10.9 KiB217 linesraw
1// src/kernels/native_expert_bench.cpp - the grouped native experts on real GGUF rows: one AMD layout against
2// another, bit for bit, and each one's time.
3//
4//     build/native_expert_bench <shard1.gguf> <layer[,layer...]> <groups> <tokens per group> <ref mode> <mode> [iters]
5//
6// Modes are STRATA_EXP_MODE values.  A group is one expert (distinct blobs, ~2 MB each, so G >= 8 does not fit
7// in L2); its entries read distinct tokens of an 8-token window.  The output must be bitwise equal to the
8// reference mode's: the verify window's text depends on it.
9#define DPCT_PROFILING_ENABLED
10#include <sycl/sycl.hpp>
11#include <dpct/dpct.hpp>
12#include "strata/artifact/gguf_reader.hpp"
13#include "strata/kernels/cpu/native_expert.hpp"
14#include "strata/kernels/iq_kernels.hpp"
15
16#include "ggml.h"
17
18#include <chrono>
19#include <cmath>
20#include <cstdint>
21#include <cstdio>
22#include <cstdlib>
23#include <cstring>
24#include <random>
25#include <sstream>
26#include <string>
27#include <vector>
28
29namespace cpu = strata::kernels::cpu;
30namespace K = strata::kernels;
31
32uint64_t fnv1a(const void* data, size_t bytes) {
33    const auto* p = static_cast<const uint8_t*>(data);
34    uint64_t h = 1469598103934665603ull;
35    for (size_t i = 0; i < bytes; ++i) {
36        h ^= p[i];
37        h *= 1099511628211ull;
38    }
39    return h;
40}
41
42int main(int argc, char** argv) {
43    setvbuf(stdout, nullptr, _IONBF, 0);
44    if (argc < 7) {
45        std::fprintf(stderr, "usage: native_expert_bench <shard1.gguf> <layer[,layer]> <groups> <tokens> <ref mode> <mode> [iters]\n");
46        return 2;
47    }
48    strata::GgufFile gguf(argv[1]);
49    std::vector<int> layers;
50    {
51        std::stringstream ss(argv[2]);
52        std::string t;
53        while (std::getline(ss, t, ',')) layers.push_back(std::atoi(t.c_str()));
54    }
55    const int G = std::atoi(argv[3]), T = std::atoi(argv[4]), mref = std::atoi(argv[5]), mode = std::atoi(argv[6]);
56    const int iters = argc > 7 ? std::atoi(argv[7]) : 200;
57    const int NTOK = 8;
58    if (T < 1 || T > NTOK || G < 1) { std::fprintf(stderr, "tokens 1..8, groups >= 1\n"); return 2; }
59    const int64_t H = 2560, FF_FULL = 640, FF = FF_FULL;   // Flash-Next's expert geometry
60    int failures = 0;
61    dpct::queue_ptr s;
62    s = dpct::get_current_device().create_queue(true);
63    // SYCL port: the queue carries an exception handler, which would swallow a failing launch and leave the timing
64    // at "the kernel did nothing" (0.3 us for a group of experts).  Every wait goes through this, so a device-side
65    // error is printed instead of silently producing an empty measurement.
66    auto sync = [&](const char* what) {
67        try {
68            s->wait_and_throw();
69            return true;
70        } catch (std::exception const& e) {
71            std::printf("%s: %s\n", what, e.what());
72            return false;
73        }
74    };
75    for (int l : layers) {
76        const strata::TensorInfo* t[3] = {};
77        const char* roles[3] = {"gate", "up", "down"};
78        for (const auto& ti : gguf.tensors())
79            for (int r = 0; r < 3; ++r)
80                if (ti.name == "blk." + std::to_string(l) + ".ffn_" + roles[r] + "_exps.weight") t[r] = &ti;
81        if (!t[0] || !t[1] || !t[2]) { std::printf("layer %d: no expert tensors\n", l); ++failures; continue; }
82        cpu::NativeFmt f;
83        std::string err;
84        if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF, f, err)) {
85            std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
86        }
87        cpu::NativeFmt ff;    // the full expert's geometry, for strides into the GGUF
88        if (!cpu::native_fmt((int) t[0]->type, (int) t[2]->type, H, FF_FULL, ff, err)) {
89            std::printf("layer %d: %s\n", l, err.c_str()); ++failures; continue;
90        }
91        const size_t dsz = f.bytes - f.down_off, dsz_full = ff.bytes - ff.down_off;
92        const size_t drow = dsz / H, drow_full = dsz_full / H;
93        std::vector<uint8_t> blobs((size_t) G * f.bytes);
94        for (int g = 0; g < G; ++g) {
95            const size_t E = (size_t) ((g * 37 + 5) % 256);
96            uint8_t* b = blobs.data() + (size_t) g * f.bytes;
97            std::memcpy(b, gguf.tensor_data(*t[0]) + E * ff.up_off, f.up_off);
98            std::memcpy(b + f.up_off, gguf.tensor_data(*t[1]) + E * ff.up_off, f.up_off);
99            for (int64_t r = 0; r < H; ++r)
100                std::memcpy(b + f.down_off + r * drow, gguf.tensor_data(*t[2]) + E * dsz_full + r * drow_full, drow);
101        }
102        std::mt19937 rng(17 + l);
103        std::normal_distribution<float> nd(0.f, 1.f);
104        std::vector<float> x((size_t) NTOK * H);
105        for (auto& v : x) v = nd(rng);
106        const int NE = G * T;
107        std::vector<unsigned long long> ptr(G);
108        std::vector<int32_t> start(G + 1), dst(NE), tok(NE);
109        const auto L = K::native_expert_layout(f.gu_type, f.d_type, H, FF);
110        // SYCL port: this bench was never a build target, so its CUDA calls were never migrated.  Device buffers are
111        // USM allocations on the bench's own in-order queue, and every copy is ordered on that queue.
112        uint8_t* dblob = (uint8_t*) sycl::malloc_device(blobs.size(), *s);
113        void *dx = sycl::malloc_device((size_t) NTOK * H * 4, *s);
114        void *dxq = sycl::malloc_device((size_t) NTOK * H / 32 * 36, *s);
115        void *dscr = sycl::malloc_device(K::native_expert_scratch_bytes(NE, FF), *s);
116        float* dout = (float*) sycl::malloc_device((size_t) NE * H * 4, *s);
117        unsigned long long* dptr = (unsigned long long*) sycl::malloc_device((size_t) G * 8, *s);
118        int32_t* dstart = (int32_t*) sycl::malloc_device((size_t) (G + 1) * 4, *s);
119        int32_t* dn = (int32_t*) sycl::malloc_device(4, *s);
120        int32_t* ddst = (int32_t*) sycl::malloc_device((size_t) NE * 4, *s);
121        int32_t* dtok = (int32_t*) sycl::malloc_device((size_t) NE * 4, *s);
122        for (int g = 0; g < G; ++g) {
123            ptr[g] = (unsigned long long) (dblob + (size_t) g * f.bytes);
124            start[g] = g * T;
125            for (int j = 0; j < T; ++j) {
126                dst[g * T + j] = g * T + j;
127                tok[g * T + j] = (g * 3 + j) % NTOK;
128            }
129        }
130        start[G] = NE;
131        s->memcpy(dblob, blobs.data(), blobs.size()).wait();
132        s->memcpy(dx, x.data(), x.size() * 4).wait();
133        s->memcpy(dptr, ptr.data(), (size_t) G * 8).wait();
134        s->memcpy(dstart, start.data(), (size_t) (G + 1) * 4).wait();
135        s->memcpy(dn, &G, 4).wait();
136        s->memcpy(ddst, dst.data(), (size_t) NE * 4).wait();
137        s->memcpy(dtok, tok.data(), (size_t) NE * 4).wait();
138        K::quantize_q8_1_rows((const float*) dx, NTOK, H, dxq, s);
139        s->wait_and_throw();
140        auto run = [&](int m, int phase) {
141            K::native_expert_set_mode(m, phase);
142            K::native_expert_grouped(L, dptr, dstart, dn, ddst, dtok, G, NE, dxq, dscr, dout, s);
143        };
144        std::vector<float> ref((size_t) NE * H), got((size_t) NE * H);
145        s->memset(dout, 0xff, got.size() * 4).wait();
146        run(mref, 0);
147        if (!sync("reference window")) return 1;
148
149        s->memcpy(ref.data(), dout, ref.size() * 4).wait();
150        // SYCL port: a launch that returns without enqueueing leaves the 0xff fill intact, and then the mode and the
151        // reference agree bitwise on an untouched buffer - a "0 differing" that measures nothing.  The fill is NaN as
152        // a float, so a reference window with no finite value anywhere did no work: say so instead of timing it.
153        {
154            size_t written = 0;
155            for (size_t i = 0; i < ref.size(); ++i) {
156                float v;
157                std::memcpy(&v, &ref[i], 4);
158                if (std::isfinite(v)) ++written;
159            }
160            if (written == 0) {
161                std::printf("layer %d: the expert launch wrote nothing (%zu outputs, none finite) - refusing to time it\n",
162                            (int) l, ref.size());
163                ++failures;
164                continue;
165            }
166        }
167        s->memset(dout, 0xff, got.size() * 4).wait();
168        run(mode, 0);
169        if (!sync("mode window")) return 1;
170        s->memcpy(got.data(), dout, got.size() * 4).wait();
171        size_t ndiff = 0;
172        double worst = 0;
173        for (size_t i = 0; i < ref.size(); ++i)
174            if (std::memcmp(&ref[i], &got[i], 4) != 0) {
175                ++ndiff;
176                worst = std::fmax(worst, std::fabs((double) ref[i] - got[i]) / (std::fabs((double) ref[i]) + 1e-6));
177            }
178        auto time = [&](int m, int phase) {
179            for (int i = 0; i < 10; ++i) run(m, phase);
180            s->wait();
181            const auto t0 = std::chrono::steady_clock::now();
182            for (int i = 0; i < iters; ++i) run(m, phase);
183            sync("timing loop");
184            const double ms =
185                std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
186            // SYCL port: the printout below and the GB/s it derives both assume MICROseconds ("all %7.1f us",
187            // bytes / us / 1e3), but this returned milliseconds - so every published number was 1000x too small in
188            // time and 1000x too large in bandwidth (0.1 "us" and 148,713 GB/s for a launch that takes ~100 us and
189            // moves 19.7 MB at ~198 GB/s).  The wall clock always agreed with the real work: 200 iterations 618 ms,
190            // 2,000 iterations 3,566 ms.  Return microseconds.
191            return ms * 1e3 / iters;
192        };
193        const double gu_b = (double) G * 2 * f.up_off, d_b = (double) G * dsz;
194        double us[2][3] = {{1e30, 1e30, 1e30}, {1e30, 1e30, 1e30}};
195        for (int round = 0; round < 3; ++round)   // interleaved, the minimum: the clocks wander between runs
196            for (int k = 0; k < 2; ++k)
197                for (int p = 0; p < 3; ++p) us[k][p] = std::fmin(us[k][p], time(k ? mode : mref, p));
198        std::printf("layer %2d %-7s/%-6s G %d T %d | mode %d: all %7.1f us  gu %7.1f us (%3.0f GB/s)  down %6.1f us (%3.0f GB/s)"
199                    " | mode %d: all %7.1f us  gu %7.1f us (%3.0f GB/s)  down %6.1f us (%3.0f GB/s)"
200                    " | hash %016llx | %s\n",
201                    l, ggml_type_name((ggml_type) f.gu_type), ggml_type_name((ggml_type) f.d_type), G, T,
202                    mref, us[0][0], us[0][1], gu_b / us[0][1] / 1e3, us[0][2], d_b / us[0][2] / 1e3,
203                    mode, us[1][0], us[1][1], gu_b / us[1][1] / 1e3, us[1][2], d_b / us[1][2] / 1e3,
204                    (unsigned long long) fnv1a(got.data(), got.size() * sizeof(float)),
205                    ndiff ? "DIFFERS" : "bitwise equal");
206        if (ndiff) {
207            std::printf("          %zu of %zu outputs differ, worst rel %.2e\n", ndiff, ref.size(), worst);
208            ++failures;
209        }
210        K::native_expert_set_mode(-1, 0);
211        for (void* p : {(void*) dblob, (void*) dx, (void*) dxq, (void*) dscr, (void*) dout, (void*) dptr,
212                        (void*) dstart, (void*) dn, (void*) ddst, (void*) dtok})
213            sycl::free(p, *s);
214    }
215    std::printf("native_expert_bench: %d differing\n", failures);
216    return failures ? 1 : 0;
217}