okami.mom/strata

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

Niko1221Strata: Qwen3.8-Flash-Next on a 12-24 GB NVIDIA GPU + 64 GB RAM, one-click install01529aaa8

main
10.2 KiB224 linesraw
1// src/kernels/cpu/pool_test.cpp - P2.S3's test for the expert pool.
2//
3// The pool's correctness claims are small and specific, so they are checked directly rather than through a
4// timing number:
5//
6//   1. THE SAME ANSWER AS SERIAL.  Every job's output must be bit-identical to running that expert serially.
7//      Each worker owns its own `ExpertScratch`, and the jobs share one read-only activation, so there is no
8//      legitimate source of difference - "close enough" here would be hiding a data race.
9//   2. EVERY JOB RUNS EXACTLY ONCE.  Claiming is `head.fetch_add`, and an off-by-one in the bound is the
10//      classic pool bug: it either drops a job or runs one twice.  Checked with a sentinel-filled output
11//      buffer, so a dropped job is visible as an untouched slot rather than as a slightly wrong number.
12//   3. REPEATED BATCHES.  A pool that works once and hangs or corrupts on the second `run()` is the failure
13//      mode the park protocol exists to prevent, so `run()` is called many times in a row.
14//   4. A BATCH BIGGER AND SMALLER THAN THE WORKER COUNT, because `n < workers` leaves most workers claiming
15//      nothing and `n > workers` is the real case (10 experts, 5 workers).
16#include "strata/kernels/cpu/pool.hpp"
17#include "strata/kernels/cpu/expert.hpp"
18
19#include <algorithm>
20#include <chrono>
21#include <cmath>
22#include <cstdio>
23#include <cstdlib>
24#include <cstring>
25#include <random>
26#include <string>
27#include <vector>
28
29namespace cpu = strata::kernels::cpu;
30
31namespace {
32
33bool read_blob(const char* path, long long index, std::vector<uint8_t>& out) {
34    out.assign(cpu::BLOB, 0);
35    std::FILE* f = std::fopen(path, "rb");
36    if (!f) return false;
37#if defined(_MSC_VER)
38    if (_fseeki64(f, index * (long long) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; }
39#else
40    if (fseeko(f, (off_t) index * (off_t) cpu::BLOB, SEEK_SET) != 0) { std::fclose(f); return false; }
41#endif
42    const size_t got = std::fread(out.data(), 1, out.size(), f);
43    std::fclose(f);
44    return got == out.size();
45}
46
47double now_ms() {
48    using namespace std::chrono;
49    return duration<double, std::milli>(steady_clock::now().time_since_epoch()).count();
50}
51
52}  // namespace
53
54int main(int argc, char** argv) {
55    bool selftest = false;
56    const char* path = "pack/full/experts.bin";
57    long long layer = 0;
58    for (int i = 1; i < argc; ++i) {
59        const std::string a = argv[i];
60        if (a == "--selftest") selftest = true;
61        else if (a == "--file" && i + 1 < argc) path = argv[++i];
62        else if (a == "--layer" && i + 1 < argc) layer = std::atoll(argv[++i]);
63        else { std::fprintf(stderr, "usage: pool_test [--selftest] [--file P] [--layer N]\n"); return 2; }
64    }
65
66    const cpu::CpuFeatures feat = cpu::cpu_features();
67    if (!feat.usable()) {
68        std::printf("  CPU lacks %s - the VNNI path cannot run here; pool test SKIPPED, not passed.\n",
69                    feat.reason());
70        std::printf("\npool: 0 failures, 1 SKIPPED\n");
71        return 0;
72    }
73
74    int bad = 0;
75
76    // ---- ten experts off one layer, which is exactly what a token uses
77    const int NEXP = 10;
78    std::vector<std::vector<uint8_t>> blobs((size_t) NEXP);
79    for (int e = 0; e < NEXP; ++e)
80        if (!read_blob(path, layer * 512 + e, blobs[(size_t) e])) {
81            std::fprintf(stderr, "cannot read expert %d of layer %lld from %s\n", e, layer, path);
82            return 2;
83        }
84
85    std::mt19937 rng(99);
86    std::normal_distribution<float> gauss(0.0f, 1.0f);
87    std::vector<float> x(cpu::H);
88    for (auto& v : x) v = gauss(rng);
89
90    cpu::ActQ act;
91    cpu::act_quant_q8_1(x.data(), cpu::H, act);
92
93    // ---- serial reference
94    std::vector<float> ref((size_t) NEXP * cpu::H);
95    {
96        cpu::ExpertScratch ws;
97        for (int e = 0; e < NEXP; ++e)
98            cpu::s2_expert_vnni_q(blobs[(size_t) e].data(), act, ref.data() + (size_t) e * cpu::H, ws);
99    }
100
101    // ---- the pool
102    const std::vector<int> cores = cpu::physical_cores(true);
103    const int hw = (int) std::thread::hardware_concurrency();
104    std::printf("  %-44s %d logical, %d physical (skipping the first)\n", "cores the pool will use",
105                hw, (int) cores.size());
106
107    cpu::ExpertPool pool;
108    std::printf("  %-44s %d\n", "workers", pool.workers());
109
110    std::vector<cpu::ExpertJob> jobs((size_t) NEXP);
111    std::vector<float> got((size_t) NEXP * cpu::H);
112    std::vector<float> weights((size_t) NEXP);
113    for (int e = 0; e < NEXP; ++e) weights[(size_t) e] = 0.1f * (float) (e + 1);
114
115    // ---- 1 + 2: same answer as serial, and every job exactly once.
116    // The output buffer starts at a sentinel no real result can equal, so a job that never runs shows up as
117    // an untouched slot instead of as a plausible number.
118    const float SENTINEL = -1.2345e33f;
119    for (int e = 0; e < NEXP; ++e) {
120        jobs[(size_t) e].blob = blobs[(size_t) e].data();
121        jobs[(size_t) e].act = &act;
122        jobs[(size_t) e].out = got.data() + (size_t) e * cpu::H;
123        jobs[(size_t) e].weight = weights[(size_t) e];
124        jobs[(size_t) e].slot = e;
125        std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL);
126    }
127    pool.run(jobs.data(), NEXP);
128
129    long long not_run = 0, diff = 0;
130    float worst = 0.f;
131    for (int e = 0; e < NEXP; ++e)
132        for (int i = 0; i < cpu::H; ++i) {
133            const float a = ref[(size_t) e * cpu::H + i], b = got[(size_t) e * cpu::H + i];
134            if (b == SENTINEL) { ++not_run; continue; }
135            if (std::memcmp(&a, &b, 4) != 0) ++diff;
136            worst = std::fmax(worst, std::fabs(a - b));
137        }
138    std::printf("  %-44s %s (%lld of %d outputs untouched)\n", "every job ran exactly once",
139                not_run ? "*** NO ***" : "yes", not_run, NEXP * cpu::H);
140    if (not_run) ++bad;
141    // BIT-IDENTICAL, not "close".  Each worker has a private scratch and the activation is shared read-only,
142    // so any difference at all is a race or a scratch collision - and a tolerance would hide exactly that.
143    std::printf("  %-44s %s (%lld of %d differ, worst |d| %.3e)\n", "identical to the serial run",
144                diff ? "*** NO ***" : "yes", diff, NEXP * cpu::H, (double) worst);
145    if (diff) ++bad;
146
147    // ---- 3: repeated batches.  A park protocol that works once and corrupts on the second call is the
148    //        exact failure this loop is here to catch.
149    {
150        int repeats_bad = 0;
151        for (int r = 0; r < 200; ++r) {
152            for (int e = 0; e < NEXP; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL);
153            pool.run(jobs.data(), NEXP);
154            for (int e = 0; e < NEXP && !repeats_bad; ++e)
155                for (int i = 0; i < cpu::H; ++i)
156                    if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) {
157                        ++repeats_bad;
158                        break;
159                    }
160        }
161        std::printf("  %-44s %s (200 consecutive batches)\n", "repeated batches stay correct",
162                    repeats_bad ? "*** NO ***" : "yes");
163        if (repeats_bad) ++bad;
164    }
165
166    // ---- 4: batch sizes either side of the worker count
167    {
168        int size_bad = 0;
169        for (int n : {1, 2, pool.workers() - 1 > 0 ? pool.workers() - 1 : 1, pool.workers(),
170                      pool.workers() + 1, NEXP}) {
171            if (n < 1 || n > NEXP) continue;
172            for (int e = 0; e < n; ++e) std::fill(jobs[(size_t) e].out, jobs[(size_t) e].out + cpu::H, SENTINEL);
173            pool.run(jobs.data(), n);
174            for (int e = 0; e < n && !size_bad; ++e)
175                for (int i = 0; i < cpu::H; ++i)
176                    if (std::memcmp(&ref[(size_t) e * cpu::H + i], &got[(size_t) e * cpu::H + i], 4) != 0) {
177                        ++size_bad;
178                        break;
179                    }
180        }
181        std::printf("  %-44s %s (1, w-1, w, w+1, 10)\n", "batch sizes around the worker count",
182                    size_bad ? "*** NO ***" : "yes");
183        if (size_bad) ++bad;
184    }
185
186    // ---- and the number that matters for the ledger: c for one layer, 10 experts over 48 layers.
187    //
188    // BEST OF N, not a mean.  The first version divided a 10-run total by 10 and reported 6.604 ms per layer -
189    // 2.1 GB/s against L9's measured 42.55 - purely because a CUDA build was running on the same 6-core
190    // machine at the time.  A mean over a contended machine measures the contention; a best-of measures the
191    // instrument, and every other timing tool in this project already takes the best.  The spread is printed
192    // so a contended run is visible rather than being read as a regression.
193    {
194        const int REPS = 20;
195        std::vector<double> t((size_t) REPS, 0.0);
196        for (int r = 0; r < REPS; ++r) {
197            const double t0 = now_ms();
198            pool.run(jobs.data(), NEXP);
199            t[(size_t) r] = now_ms() - t0;
200        }
201        std::vector<double> sorted = t;
202        std::sort(sorted.begin(), sorted.end());
203        const double best = sorted.front(), median = sorted[sorted.size() / 2], worst = sorted.back();
204        const double gbs = (double) NEXP * cpu::BLOB / (best * 1e-3) / 1e9;
205        std::printf("\n  %-44s %7.3f ms   (%.1f GB/s)\n", "10 experts, one layer (best of 20)",
206                    best, gbs);
207        std::printf("  %-44s %7.3f / %7.3f ms   (spread %.2fx)\n", "median / worst", median, worst,
208                    median / (best > 0 ? best : 1));
209        std::printf("  %-44s %7.3f ms   -> %.1f tok/s for the full 48 layers\n",
210                    "extrapolated to 48 layers", best * 48, 1000.0 / (best * 48));
211        std::printf("  L9 measured 42.55 GB/s on 6 cores; this pool uses %d workers (core 0 is left to the\n",
212                    pool.workers());
213        std::printf("  host loop), so %.1f GB/s x 6/%d = %.1f GB/s is the per-core comparison.\n",
214                    gbs, pool.workers(), gbs * 6.0 / pool.workers());
215        if (median / (best > 0 ? best : 1) > 1.5)
216            std::printf("  *** the spread is over 1.5x: this machine was CONTENDED and the median is not a\n"
217                        "      property of the pool.  Re-run on a quiet machine before quoting it. ***\n");
218    }
219
220    std::printf("\npool: %d failures\n", bad);
221    if (bad) return 1;
222    if (selftest) std::printf("pool_test OK\n");
223    return 0;
224}