Confirmed against the C++ in engine/strata and fixed: - rust_native_general.rs group_dot_bytes_policy omitted the `gu == 23 && !avx512` multi-token branch of native_expert.cpp native_gu_rows (`nt >= mt_min && (iq512_supported || (!cpu512 && iq256_supported))`); rust_pool.rs had it since STRA-324. The choice is now one function, gu_multi_route, shared in shape with the pool. Regression: a differential test (re-runs itself with STRATA_FORCE_AVX2=1 on an AVX-512 CPU) fails with a 1-ULP difference on the old code, plus a routing-table test. - rust_legacy.rs row256 (STRATA_CPU_YMM=1 on an AVX-512 CPU) now fuses `corr += d*(hx0+hx1)` like expert.cpp row_dot (line 242) and row_dot_multi (line 294) under GCC -mfma. Regression: scalar model, fails on old code. NOT changed, unconfirmed (need the pinned ggml source, which is not in the repo): rust_kq.rs small_dot `sums += m*s`, rust_k_blocks.rs mins_sum, rust_ggml_extra.rs iq1 scalar. KAB1: new `--cases ext` (72 cases; the 40 of `all` are untouched) adds token counts 4-7 for the row-type list and IQ2_XXS / IQ2_XS at 1..8 tokens; GateUpFormat gains Iq2Xxs / Iq2Xs (additive; the runtime still admits only 18/21/22/23/42). The C++ driver edits are list-only and were NOT compiled here (no ggml). 16 tokens exceed MAXT and the KAB1 header and are not covered. New Rust-only test token_count_invariance: the first two tokens of a group are bit-identical for groups of 2..8 tokens on all 14 gate/up x down pairs. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
661 lines
35 KiB
C++
661 lines
35 KiB
C++
// tools/kernel-ab/cpp/kab.cpp - STRA-248 (S0.8a): the C++ reference half of the CPU kernel A/B (contract KAB1).
|
|
//
|
|
// kab gen --run-dir D --seed N --cases all|gu:down:rows[,...] write D/case-<id>.in, run the C++ kernels for tree
|
|
// avx512 and tree avx2 (two child processes), write
|
|
// D/case-<id>.cpp-{avx512,avx2}.out, then manifest.json LAST
|
|
// kab run-tree --run-dir D --tree avx512|avx2 (internal) one tree's .out files; prints one JSON probe line
|
|
// kab poolcheck --run-dir D [--workers N] stage composition vs the real ExpertPool (bitwise), same process
|
|
// kab time --run-dir D --case ID --slices N --pin CPU --out F.json STRA-317: timing, resident + streamed regimes (cpp/kab_time.cpp)
|
|
//
|
|
// The kernels are engine/strata's, UNCHANGED, built by ../cpp/Makefile. Nothing here is kernel arithmetic: the driver only
|
|
// COMPOSES the stage entry points of include/strata/kernels/cpu/native_expert.hpp (+ the Q2_0 kernels of expert_layout.hpp)
|
|
// in the order the engine's pool runs them for one routed expert (README.md: file:line evidence). Data is synthetic.
|
|
#include "strata/kernels/cpu/native_expert.hpp"
|
|
#include "strata/kernels/cpu/expert.hpp"
|
|
#include "strata/kernels/cpu/expert_layout.hpp"
|
|
#include "strata/kernels/cpu/iq_avx512.hpp"
|
|
#include "strata/kernels/cpu/pool.hpp"
|
|
|
|
#include <cpuid.h>
|
|
#include <dirent.h>
|
|
#include <fcntl.h>
|
|
#include <sched.h> // STRA-317 (time mode): sched_setaffinity / sched_getcpu
|
|
#include <time.h> // clock_gettime
|
|
#include <x86intrin.h> // __rdtsc, _mm_lfence
|
|
#include <sys/stat.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
#include <algorithm>
|
|
#include <array>
|
|
#include <cerrno>
|
|
#include <cmath>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <map>
|
|
#include <memory>
|
|
#include <set>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
extern char** environ;
|
|
using namespace strata::kernels::cpu;
|
|
|
|
namespace {
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// KAB1 constants
|
|
constexpr uint32_t kMagicIn = 0x4942414Bu; // 'KABI' little-endian bytes 4B 41 42 49 ("KABI" read back as written)
|
|
constexpr uint32_t kMagicOut = 0x4F42414Bu; // 'KABO'
|
|
constexpr uint32_t kVersion = 1;
|
|
constexpr size_t kInHeader = 64;
|
|
constexpr size_t kOutHeader = 20; // magic, version, rows, n_embd, tree id: 5 x u32
|
|
constexpr uint32_t kTreeAvx512 = 0, kTreeAvx2 = 1;
|
|
|
|
struct Fmt { int id; const char* name; int qk; int bytes; }; // elements per block, bytes per block (lib.rs block())
|
|
constexpr Fmt kFmts[] = {{18, "IQ3_XXS", 256, 98}, {21, "IQ3_S", 256, 110}, {22, "IQ2_S", 256, 82},
|
|
{23, "IQ4_XS", 256, 136}, {42, "Q2_0", 64, 18}, {20, "IQ4_NL", 32, 18},
|
|
{16, "IQ2_XXS", 256, 66}, {17, "IQ2_XS", 256, 74}};
|
|
const Fmt* fmt_of(int id) {
|
|
for (const Fmt& f : kFmts) if (f.id == id) return &f;
|
|
return nullptr;
|
|
}
|
|
bool gu_ok(int id) { return id == 16 || id == 17 || id == 18 || id == 21 || id == 22 || id == 23 || id == 42; }
|
|
bool down_ok(int id) { return id == 20 || id == 42; }
|
|
size_t gu_bytes(const Fmt& f) { return (size_t) (H / f.qk) * (size_t) f.bytes * (size_t) FF; }
|
|
size_t down_bytes(const Fmt& f) { return (size_t) (FF / f.qk) * (size_t) f.bytes * (size_t) H; }
|
|
|
|
[[noreturn]] void die(const std::string& m) {
|
|
std::fprintf(stderr, "kab: %s\n", m.c_str());
|
|
std::exit(1);
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// SHA-256 (FIPS 180-4), for the manifest
|
|
struct Sha256 {
|
|
uint32_t h[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
|
uint8_t buf[64];
|
|
size_t fill = 0;
|
|
uint64_t total = 0;
|
|
static uint32_t ror(uint32_t x, int n) { return (x >> n) | (x << (32 - n)); }
|
|
void block(const uint8_t* p) {
|
|
static const uint32_t K[64] = {
|
|
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01,
|
|
0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
|
|
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
|
|
0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08,
|
|
0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
|
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
|
uint32_t w[64];
|
|
for (int i = 0; i < 16; ++i)
|
|
w[i] = (uint32_t) p[4 * i] << 24 | (uint32_t) p[4 * i + 1] << 16 | (uint32_t) p[4 * i + 2] << 8 | p[4 * i + 3];
|
|
for (int i = 16; i < 64; ++i) {
|
|
const uint32_t s0 = ror(w[i - 15], 7) ^ ror(w[i - 15], 18) ^ (w[i - 15] >> 3);
|
|
const uint32_t s1 = ror(w[i - 2], 17) ^ ror(w[i - 2], 19) ^ (w[i - 2] >> 10);
|
|
w[i] = w[i - 16] + s0 + w[i - 7] + s1;
|
|
}
|
|
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], hh = h[7];
|
|
for (int i = 0; i < 64; ++i) {
|
|
const uint32_t S1 = ror(e, 6) ^ ror(e, 11) ^ ror(e, 25), ch = (e & f) ^ (~e & g);
|
|
const uint32_t t1 = hh + S1 + ch + K[i] + w[i];
|
|
const uint32_t S0 = ror(a, 2) ^ ror(a, 13) ^ ror(a, 22), mj = (a & b) ^ (a & c) ^ (b & c);
|
|
const uint32_t t2 = S0 + mj;
|
|
hh = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
|
}
|
|
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
|
|
}
|
|
void update(const void* data, size_t n) {
|
|
const uint8_t* p = (const uint8_t*) data;
|
|
total += n;
|
|
while (n > 0) {
|
|
if (fill == 0 && n >= 64) { block(p); p += 64; n -= 64; continue; }
|
|
const size_t k = std::min(n, 64 - fill);
|
|
std::memcpy(buf + fill, p, k);
|
|
fill += k; p += k; n -= k;
|
|
if (fill == 64) { block(buf); fill = 0; }
|
|
}
|
|
}
|
|
std::string hex() {
|
|
const uint64_t bits = total * 8;
|
|
const uint8_t one = 0x80, zero = 0;
|
|
update(&one, 1);
|
|
while (fill != 56) update(&zero, 1);
|
|
uint8_t len[8];
|
|
for (int i = 0; i < 8; ++i) len[i] = (uint8_t) (bits >> (56 - 8 * i));
|
|
update(len, 8);
|
|
char out[65];
|
|
for (int i = 0; i < 8; ++i) std::snprintf(out + 8 * i, 9, "%08x", h[i]);
|
|
return std::string(out, 64);
|
|
}
|
|
};
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// files
|
|
std::vector<uint8_t> read_file(const std::string& path) {
|
|
FILE* f = std::fopen(path.c_str(), "rb");
|
|
if (!f) die("cannot open " + path + ": " + std::strerror(errno));
|
|
std::vector<uint8_t> v;
|
|
uint8_t tmp[1 << 16];
|
|
for (size_t n; (n = std::fread(tmp, 1, sizeof tmp, f)) > 0;) v.insert(v.end(), tmp, tmp + n);
|
|
std::fclose(f);
|
|
return v;
|
|
}
|
|
void write_file(const std::string& path, const void* data, size_t n) {
|
|
FILE* f = std::fopen(path.c_str(), "wb");
|
|
if (!f) die("cannot create " + path + ": " + std::strerror(errno));
|
|
if (std::fwrite(data, 1, n, f) != n || std::fflush(f) != 0 || fsync(fileno(f)) != 0) die("write failed: " + path);
|
|
if (std::fclose(f) != 0) die("close failed: " + path);
|
|
}
|
|
std::string sha_of(const std::vector<uint8_t>& v) { Sha256 s; s.update(v.data(), v.size()); return s.hex(); }
|
|
void put32(std::vector<uint8_t>& v, uint32_t x) { for (int i = 0; i < 4; ++i) v.push_back((uint8_t) (x >> (8 * i))); }
|
|
uint32_t get32(const uint8_t* p) { return (uint32_t) p[0] | (uint32_t) p[1] << 8 | (uint32_t) p[2] << 16 | (uint32_t) p[3] << 24; }
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// synthetic data: SplitMix64 (the numbers are informational only, KAB1: inputs are always the dumped bytes)
|
|
struct Rng {
|
|
uint64_t s;
|
|
uint64_t next() {
|
|
uint64_t z = (s += 0x9E3779B97F4A7C15ull);
|
|
z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull;
|
|
z = (z ^ (z >> 27)) * 0x94D049BB133111EBull;
|
|
return z ^ (z >> 31);
|
|
}
|
|
double unit() { return (double) (next() >> 11) * (1.0 / 9007199254740992.0); } // [0,1)
|
|
};
|
|
uint16_t half_trunc(float f) { // positive normal fp16 range only: scales are generated in [2^-9, 2^-4]
|
|
uint32_t b;
|
|
std::memcpy(&b, &f, 4);
|
|
const int e = (int) ((b >> 23) & 0xff) - 127 + 15;
|
|
return (uint16_t) ((e << 10) | ((b >> 13) & 0x3ff));
|
|
}
|
|
void fill_blocks(Rng& r, std::vector<uint8_t>& v, size_t off, size_t bytes, int block_bytes) {
|
|
for (size_t i = 0; i < bytes; i += 8) {
|
|
const uint64_t x = r.next();
|
|
std::memcpy(&v[off + i], &x, std::min<size_t>(8, bytes - i));
|
|
}
|
|
for (size_t at = 0; at < bytes; at += (size_t) block_bytes) { // the FP16 header of every block: finite, small scale
|
|
const uint16_t d = half_trunc((float) (0.002 + 0.028 * r.unit()));
|
|
v[off + at] = (uint8_t) d;
|
|
v[off + at + 1] = (uint8_t) (d >> 8);
|
|
}
|
|
}
|
|
|
|
struct Case {
|
|
int gu = 0, down = 0, rows = 0;
|
|
uint64_t seed = 0;
|
|
std::string id() const { return std::to_string(gu) + "-" + std::to_string(down) + "-r" + std::to_string(rows); }
|
|
};
|
|
|
|
std::vector<uint8_t> make_case_file(const Case& c) {
|
|
const Fmt& g = *fmt_of(c.gu);
|
|
const Fmt& d = *fmt_of(c.down);
|
|
const size_t gb = gu_bytes(g), db = down_bytes(d);
|
|
Rng r{c.seed};
|
|
std::vector<uint8_t> v;
|
|
v.reserve(kInHeader + 2 * gb + db + (size_t) c.rows * H * 4);
|
|
put32(v, kMagicIn); put32(v, kVersion);
|
|
put32(v, (uint32_t) c.gu); put32(v, (uint32_t) c.down);
|
|
put32(v, (uint32_t) c.rows); put32(v, H); put32(v, FF);
|
|
put32(v, (uint32_t) gb); put32(v, (uint32_t) gb); put32(v, (uint32_t) db);
|
|
v.resize(kInHeader, 0);
|
|
const size_t base = v.size();
|
|
v.resize(base + 2 * gb + db);
|
|
fill_blocks(r, v, base, gb, g.bytes);
|
|
fill_blocks(r, v, base + gb, gb, g.bytes);
|
|
fill_blocks(r, v, base + 2 * gb, db, d.bytes);
|
|
for (size_t i = 0; i < (size_t) c.rows * H; ++i) { // activations: [-1,1) with ~1% x8 outliers; all finite
|
|
float x = (float) (2.0 * r.unit() - 1.0);
|
|
if (r.next() % 100 == 0) x *= 8.f;
|
|
uint32_t b;
|
|
std::memcpy(&b, &x, 4);
|
|
put32(v, b);
|
|
}
|
|
return v;
|
|
}
|
|
|
|
// A parsed, fully validated case file (the KAB1 reader rule: validate before use).
|
|
struct Loaded {
|
|
Case c;
|
|
std::vector<uint8_t> blob; // gate | up | down
|
|
std::vector<float> x; // rows * H
|
|
};
|
|
Loaded load_case(const std::string& path) {
|
|
const std::vector<uint8_t> v = read_file(path);
|
|
if (v.size() < kInHeader) die(path + ": shorter than the 64-byte header");
|
|
if (get32(&v[0]) != kMagicIn || get32(&v[4]) != kVersion) die(path + ": bad magic or version");
|
|
Loaded l;
|
|
l.c.gu = (int32_t) get32(&v[8]);
|
|
l.c.down = (int32_t) get32(&v[12]);
|
|
l.c.rows = (int) get32(&v[16]);
|
|
if (!gu_ok(l.c.gu) || !down_ok(l.c.down)) die(path + ": row type not in the KAB1 list");
|
|
if (l.c.rows < 1 || l.c.rows > 8 || get32(&v[20]) != (uint32_t) H || get32(&v[24]) != (uint32_t) FF) die(path + ": bad rows / n_embd / n_ff");
|
|
const Fmt& g = *fmt_of(l.c.gu);
|
|
const Fmt& d = *fmt_of(l.c.down);
|
|
const size_t gb = gu_bytes(g), db = down_bytes(d);
|
|
if (get32(&v[28]) != gb || get32(&v[32]) != gb || get32(&v[36]) != db) die(path + ": byte counts differ from the format-derived sizes");
|
|
for (size_t i = 40; i < kInHeader; ++i) if (v[i] != 0) die(path + ": header padding is not zero");
|
|
if (v.size() != kInHeader + 2 * gb + db + (size_t) l.c.rows * H * 4) die(path + ": file length differs from the header-derived length");
|
|
const uint8_t* p = &v[kInHeader];
|
|
const struct { size_t off, bytes; int block; } parts[3] = {{0, gb, g.bytes}, {gb, gb, g.bytes}, {2 * gb, db, d.bytes}};
|
|
for (const auto& pt : parts)
|
|
for (size_t at = 0; at < pt.bytes; at += (size_t) pt.block)
|
|
if (((p[pt.off + at] | p[pt.off + at + 1] << 8) & 0x7c00) == 0x7c00) die(path + ": a block's FP16 header is not finite");
|
|
l.blob.assign(p, p + 2 * gb + db);
|
|
l.x.resize((size_t) l.c.rows * H);
|
|
std::memcpy(l.x.data(), p + 2 * gb + db, l.x.size() * 4);
|
|
for (float f : l.x) if (!std::isfinite(f)) die(path + ": a non-finite activation");
|
|
return l;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// The composition of ONE routed expert over `nt` tokens, as the engine's pool runs it. Order, branches and arithmetic are the
|
|
// ones of miss_abi.cpp (quantize the inputs) + pool.cpp ExpertPool::drain mode 5 / mode 6 and run_split_multi_native (quantize
|
|
// the SwiGLU output between the two row phases), over the whole row range [0, FF) and [0, H) on this thread. Rows are
|
|
// independent in every kernel, so a partition of the range across workers does not change a bit (poolcheck proves it here).
|
|
void compose_expert(const NativeFmt& f, const uint8_t* blob, const float* x, int nt, float* out /* nt * H */) {
|
|
std::vector<ActQ> act((size_t) nt); // gate/up activations, Q2_0 kernels
|
|
std::unique_ptr<uint8_t, decltype(&std::free)> nact((uint8_t*) std::aligned_alloc(64, (size_t) nt * kNativeActBytes), &std::free);
|
|
std::unique_ptr<uint8_t, decltype(&std::free)> hq((uint8_t*) std::aligned_alloc(64, (size_t) nt * kNativeHBytes), &std::free);
|
|
std::vector<ActQ> a2((size_t) nt);
|
|
std::vector<float> ff((size_t) nt * FF);
|
|
const void* nactp[MAXT];
|
|
const void* hqp[MAXT];
|
|
const ActQ* actp[MAXT];
|
|
const ActQ* a2p[MAXT];
|
|
float* ffp[MAXT];
|
|
float* outp[MAXT];
|
|
// miss_abi.cpp: `if (format.gu_type == 42) act_quant_any(...) else native_quant_act(...)`, per token
|
|
for (int t = 0; t < nt; ++t) {
|
|
if (f.gu_type == 42) act_quant_any(x + (size_t) t * H, H, act[(size_t) t]);
|
|
else native_quant_act(f, x + (size_t) t * H, nact.get() + (size_t) t * kNativeActBytes);
|
|
nactp[t] = nact.get() + (size_t) t * kNativeActBytes;
|
|
actp[t] = &act[(size_t) t];
|
|
ffp[t] = &ff[(size_t) t * FF];
|
|
outp[t] = out + (size_t) t * H;
|
|
hqp[t] = hq.get() + (size_t) t * kNativeHBytes;
|
|
a2p[t] = &a2[(size_t) t];
|
|
}
|
|
// pool.cpp mode 5: gate/up rows (a native Q2_0 pack on the Q2_0 kernels, then SwiGLU; every other type through native_gu_rows)
|
|
if (q2_native_kernels(f.gu_type)) {
|
|
std::vector<float> g((size_t) nt * FF), u((size_t) nt * FF);
|
|
float* gp[MAXT];
|
|
float* up[MAXT];
|
|
for (int t = 0; t < nt; ++t) { gp[t] = &g[(size_t) t * FF]; up[t] = &u[(size_t) t * FF]; }
|
|
const int nbk = (int) (f.n_embd / 64);
|
|
q2_rows_any(blob, f.gu_row, nbk, actp, nt, gp, 0, FF);
|
|
q2_rows_any(blob + f.up_off, f.gu_row, nbk, actp, nt, up, 0, FF);
|
|
for (int t = 0; t < nt; ++t)
|
|
for (int r = 0; r < FF; ++r) ffp[t][r] = (gp[t][r] / (1.f + std::exp(-gp[t][r]))) * up[t][r];
|
|
} else {
|
|
native_gu_rows(f, blob, nactp, nt, ffp, 0, FF);
|
|
}
|
|
// run_split_multi_native: the SwiGLU output is quantized for the down projection
|
|
for (int t = 0; t < nt; ++t) {
|
|
if (q2_native_kernels(f.d_type)) act_quant_any(ffp[t], FF, a2[(size_t) t]);
|
|
else native_quant_h(f, ffp[t], (void*) hqp[t]);
|
|
}
|
|
// pool.cpp mode 6: down rows
|
|
if (q2_native_kernels(f.d_type)) q2_rows_any(blob + f.down_off, f.d_row, (int) (f.n_ff / 64), a2p, nt, outp, 0, H);
|
|
else native_down_rows(f, blob, hqp, nt, outp, 0, H);
|
|
}
|
|
|
|
bool format_for(const Case& c, NativeFmt& f) {
|
|
std::string err;
|
|
if (!native_fmt(c.gu, c.down, H, FF, f, err)) { std::fprintf(stderr, "kab: native_fmt(%d,%d): %s\n", c.gu, c.down, err.c_str()); return false; }
|
|
const Fmt& g = *fmt_of(c.gu);
|
|
const Fmt& d = *fmt_of(c.down);
|
|
if (f.up_off != gu_bytes(g) || f.bytes - f.down_off != down_bytes(d) || f.tail_off != 0 || f.had_gu || f.had_d) {
|
|
std::fprintf(stderr, "kab: the engine's blob layout for (%d,%d) differs from the KAB1 sizes\n", c.gu, c.down);
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// JSON helpers
|
|
std::string jstr(const std::string& s) {
|
|
std::string o = "\"";
|
|
for (unsigned char ch : s) {
|
|
if (ch == '"' || ch == '\\') { o += '\\'; o += (char) ch; }
|
|
else if (ch == '\n') o += "\\n";
|
|
else if (ch == '\t') o += "\\t";
|
|
else if (ch < 0x20) { char b[8]; std::snprintf(b, sizeof b, "\\u%04x", ch); o += b; }
|
|
else o += (char) ch;
|
|
}
|
|
return o + "\"";
|
|
}
|
|
const char* jbool(bool b) { return b ? "true" : "false"; }
|
|
|
|
std::map<std::string, std::string> env_matching(char** envp) { // STRATA_* and LELEKA_* variables
|
|
std::map<std::string, std::string> m;
|
|
for (char** e = envp; *e; ++e) {
|
|
if (std::strncmp(*e, "STRATA_", 7) == 0 || std::strncmp(*e, "LELEKA_", 7) == 0) {
|
|
const char* eq = std::strchr(*e, '=');
|
|
if (eq) m[std::string(*e, (size_t) (eq - *e))] = eq + 1;
|
|
}
|
|
}
|
|
return m;
|
|
}
|
|
std::string env_json(const std::map<std::string, std::string>& m) {
|
|
std::string o = "{";
|
|
bool first = true;
|
|
for (const auto& kv : m) { o += (first ? "" : ", ") + jstr(kv.first) + ": " + jstr(kv.second); first = false; }
|
|
return o + "}";
|
|
}
|
|
|
|
std::string probe_json(const char* tree) {
|
|
return std::string("{\"tree\": ") + jstr(tree) + ", \"avx2_ok\": " + jbool(cpu_avx2_ok()) + ", \"avx512_ok\": " + jbool(cpu_avx512_ok()) +
|
|
", \"avx512bw_ok\": " + jbool(cpu_avx512bw_ok()) + ", \"avxvnni_ok\": " + jbool(cpu_avxvnni_ok()) +
|
|
", \"isa_cap\": " + std::to_string(cpu_isa_cap()) + ", \"iq512_gather_on\": " + jbool(iq512_gather_on()) +
|
|
", \"iq256_gather_setting\": " + std::to_string(iq256_gather_setting()) + ", \"cpu_gather_fast\": " + jbool(cpu_gather_fast()) +
|
|
", \"strata_env\": " + env_json(env_matching(environ)) + "}";
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// argument parsing
|
|
struct Args {
|
|
std::map<std::string, std::string> kv;
|
|
std::string get(const std::string& k, const std::string& def = "") const { auto it = kv.find(k); return it == kv.end() ? def : it->second; }
|
|
bool has(const std::string& k) const { return kv.count(k) != 0; }
|
|
};
|
|
Args parse(int argc, char** argv, int from) {
|
|
Args a;
|
|
for (int i = from; i < argc; ++i) {
|
|
std::string k = argv[i];
|
|
if (k.rfind("--", 0) != 0 || i + 1 >= argc) die("bad argument: " + k);
|
|
a.kv[k.substr(2)] = argv[++i];
|
|
}
|
|
return a;
|
|
}
|
|
|
|
std::vector<std::string> list_cases(const std::string& dir) {
|
|
DIR* d = opendir(dir.c_str());
|
|
if (!d) die("cannot open " + dir);
|
|
std::vector<std::string> ids;
|
|
while (dirent* e = readdir(d)) {
|
|
std::string n = e->d_name;
|
|
if (n.rfind("case-", 0) == 0 && n.size() > 8 && n.compare(n.size() - 3, 3, ".in") == 0) ids.push_back(n.substr(5, n.size() - 8));
|
|
}
|
|
closedir(d);
|
|
std::sort(ids.begin(), ids.end());
|
|
return ids;
|
|
}
|
|
|
|
std::vector<Case> parse_cases(const std::string& spec, uint64_t seed) {
|
|
std::vector<Case> cs;
|
|
auto add = [&](int gu, int down, int rows) {
|
|
if (!gu_ok(gu) || !down_ok(down) || rows < 1 || rows > 8) die("bad case " + std::to_string(gu) + ":" + std::to_string(down) + ":" + std::to_string(rows));
|
|
Case c;
|
|
c.gu = gu; c.down = down; c.rows = rows;
|
|
Rng r{seed ^ ((uint64_t) gu << 40) ^ ((uint64_t) down << 24) ^ ((uint64_t) rows << 8)};
|
|
c.seed = r.next();
|
|
cs.push_back(c);
|
|
};
|
|
if (spec == "all") {
|
|
// every (gate/up, down) pair of the row-type list at one token (the single-token dot paths), at two and three tokens
|
|
// (the multi-token kernels from the #152 rule), and at the 8-token maximum
|
|
for (int gu : {18, 21, 22, 23, 42})
|
|
for (int dn : {20, 42})
|
|
for (int rows : {1, 2, 3, 8}) add(gu, dn, rows);
|
|
} else if (spec == "ext") {
|
|
// STRA-329 (the 40 cases of "all" are unchanged): the token counts 4, 5, 6 and 7 of the row-type list, and IQ2_XXS / IQ2_XS
|
|
// (gate/up types 16 and 17) with both down types at every token count 1..8. 16 tokens exceed MAXT (8) and the KAB1 header.
|
|
for (int gu : {18, 21, 22, 23, 42})
|
|
for (int dn : {20, 42})
|
|
for (int rows : {4, 5, 6, 7}) add(gu, dn, rows);
|
|
for (int gu : {16, 17})
|
|
for (int dn : {20, 42})
|
|
for (int rows : {1, 2, 3, 4, 5, 6, 7, 8}) add(gu, dn, rows);
|
|
} else {
|
|
size_t at = 0;
|
|
while (at < spec.size()) {
|
|
size_t comma = spec.find(',', at);
|
|
if (comma == std::string::npos) comma = spec.size();
|
|
int gu = 0, dn = 0, rows = 0;
|
|
if (std::sscanf(spec.substr(at, comma - at).c_str(), "%d:%d:%d", &gu, &dn, &rows) != 3) die("bad --cases entry: " + spec.substr(at, comma - at));
|
|
add(gu, dn, rows);
|
|
at = comma + 1;
|
|
}
|
|
}
|
|
return cs;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// run-tree: one tree's outputs
|
|
int cmd_run_tree(const Args& a) {
|
|
const std::string dir = a.get("run-dir"), tree = a.get("tree");
|
|
if (dir.empty() || (tree != "avx512" && tree != "avx2")) die("run-tree needs --run-dir and --tree avx512|avx2");
|
|
if (!cpu_avx2_ok()) die("this CPU has no AVX2: the engine would not run its experts here (miss_abi.cpp refuses too)");
|
|
if (tree == "avx2" && cpu_avx512_ok()) die("tree avx2 needs STRATA_FORCE_AVX2=1 (cpu_avx512_ok() is still true)");
|
|
for (const std::string& id : list_cases(dir)) {
|
|
Loaded l = load_case(dir + "/case-" + id + ".in");
|
|
NativeFmt f;
|
|
if (!format_for(l.c, f)) return 2;
|
|
std::vector<float> out((size_t) l.c.rows * H, 0.f);
|
|
compose_expert(f, l.blob.data(), l.x.data(), l.c.rows, out.data());
|
|
for (float v : out) if (!std::isfinite(v)) die("case " + id + ": a non-finite output value");
|
|
std::vector<uint8_t> o;
|
|
put32(o, kMagicOut); put32(o, kVersion); put32(o, (uint32_t) l.c.rows); put32(o, H); put32(o, tree == "avx512" ? kTreeAvx512 : kTreeAvx2);
|
|
const size_t hdr = o.size();
|
|
o.resize(hdr + out.size() * 4);
|
|
std::memcpy(&o[hdr], out.data(), out.size() * 4); // raw f32 bit patterns, little-endian host
|
|
write_file(dir + "/case-" + id + ".cpp-" + tree + ".out", o.data(), o.size());
|
|
}
|
|
std::printf("%s\n", probe_json(tree.c_str()).c_str());
|
|
return 0;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// poolcheck: the real ExpertPool (miss_abi.cpp's sequence) against compose_expert, bitwise, same process / same tree
|
|
int cmd_poolcheck(const Args& a) {
|
|
const std::string dir = a.get("run-dir");
|
|
if (dir.empty()) die("poolcheck needs --run-dir");
|
|
if (!cpu_avx2_ok()) die("this CPU has no AVX2");
|
|
const int workers = std::atoi(a.get("workers", "1").c_str());
|
|
ExpertPool pool(workers, /*pin=*/false, /*host_works=*/true, PoolAffinity::All);
|
|
int n = 0, bad = 0;
|
|
for (const std::string& id : list_cases(dir)) {
|
|
Loaded l = load_case(dir + "/case-" + id + ".in");
|
|
NativeFmt f;
|
|
if (!format_for(l.c, f)) return 2;
|
|
const int nt = l.c.rows;
|
|
std::vector<float> want((size_t) nt * H, 0.f), got((size_t) nt * H, 0.f);
|
|
compose_expert(f, l.blob.data(), l.x.data(), nt, want.data());
|
|
// miss_abi.cpp leleka_cpu_miss_compute_batch, one expert
|
|
std::vector<ActQ> act((size_t) nt);
|
|
std::unique_ptr<uint8_t, decltype(&std::free)> nact((uint8_t*) std::aligned_alloc(64, (size_t) nt * kNativeActBytes), &std::free);
|
|
ExpertJobMulti job;
|
|
job.blob = l.blob.data();
|
|
job.nt = nt;
|
|
for (int t = 0; t < nt; ++t) {
|
|
if (f.gu_type == 42) act_quant_any(l.x.data() + (size_t) t * H, H, act[(size_t) t]);
|
|
else native_quant_act(f, l.x.data() + (size_t) t * H, nact.get() + (size_t) t * kNativeActBytes);
|
|
job.act[t] = &act[(size_t) t];
|
|
job.nact[t] = nact.get() + (size_t) t * kNativeActBytes;
|
|
job.out[t] = got.data() + (size_t) t * H;
|
|
}
|
|
pool.run_split_multi_native(f, &job, 1);
|
|
const bool same = std::memcmp(want.data(), got.data(), want.size() * 4) == 0;
|
|
std::printf("poolcheck %-12s workers=%d %s\n", id.c_str(), pool.workers(), same ? "bitwise-equal" : "DIFFERENT");
|
|
++n;
|
|
bad += same ? 0 : 1;
|
|
}
|
|
if (n == 0) die("poolcheck: no cases in " + dir);
|
|
std::printf("%s %d cases\n", bad == 0 ? "POOLCHECK OK" : "POOLCHECK FAILED", n);
|
|
return bad == 0 ? 0 : 1;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------------------------------------
|
|
// gen
|
|
std::map<std::string, std::string> read_build_info(const std::string& path) {
|
|
std::map<std::string, std::string> m;
|
|
FILE* f = std::fopen(path.c_str(), "r");
|
|
if (!f) return m;
|
|
char line[4096];
|
|
while (std::fgets(line, sizeof line, f)) {
|
|
std::string s = line;
|
|
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back();
|
|
const size_t tab = s.find('\t');
|
|
if (tab != std::string::npos) m[s.substr(0, tab)] = s.substr(tab + 1);
|
|
}
|
|
std::fclose(f);
|
|
return m;
|
|
}
|
|
|
|
std::string run_child(const std::string& exe, const std::string& dir, const char* tree) {
|
|
int fds[2];
|
|
if (pipe(fds) != 0) die("pipe failed");
|
|
const pid_t pid = fork();
|
|
if (pid < 0) die("fork failed");
|
|
if (pid == 0) {
|
|
dup2(fds[1], 1);
|
|
close(fds[0]);
|
|
close(fds[1]);
|
|
std::vector<std::string> env;
|
|
for (char** e = environ; *e; ++e)
|
|
if (std::strncmp(*e, "STRATA_", 7) != 0 && std::strncmp(*e, "LELEKA_", 7) != 0) env.push_back(*e); // scrub
|
|
if (std::strcmp(tree, "avx2") == 0) env.push_back("STRATA_FORCE_AVX2=1");
|
|
std::vector<char*> envp;
|
|
for (std::string& s : env) envp.push_back(s.data());
|
|
envp.push_back(nullptr);
|
|
const char* argv[] = {exe.c_str(), "run-tree", "--run-dir", dir.c_str(), "--tree", tree, nullptr};
|
|
execve(exe.c_str(), (char* const*) argv, envp.data());
|
|
std::perror("execve");
|
|
_exit(127);
|
|
}
|
|
close(fds[1]);
|
|
std::string out;
|
|
char b[4096];
|
|
for (ssize_t n; (n = read(fds[0], b, sizeof b)) > 0;) out.append(b, (size_t) n);
|
|
close(fds[0]);
|
|
int st = 0;
|
|
waitpid(pid, &st, 0);
|
|
if (!WIFEXITED(st) || WEXITSTATUS(st) != 0) die(std::string("child for tree ") + tree + " failed");
|
|
while (!out.empty() && (out.back() == '\n' || out.back() == '\r')) out.pop_back();
|
|
return out;
|
|
}
|
|
|
|
std::string cpu_brand_and_bits() {
|
|
unsigned r[4] = {0, 0, 0, 0};
|
|
char brand[49] = {0};
|
|
__cpuid(0x80000000u, r[0], r[1], r[2], r[3]);
|
|
if (r[0] >= 0x80000004u)
|
|
for (unsigned i = 0; i < 3; ++i) {
|
|
__cpuid(0x80000002u + i, r[0], r[1], r[2], r[3]);
|
|
std::memcpy(brand + 16 * i, r, 16);
|
|
}
|
|
std::string b = brand;
|
|
while (!b.empty() && b.front() == ' ') b.erase(b.begin());
|
|
unsigned a0 = 0, b0 = 0, c0 = 0, d0 = 0, a1 = 0, bb1 = 0, c1 = 0, d1 = 0;
|
|
__cpuid_count(7, 0, a0, b0, c0, d0);
|
|
__cpuid_count(7, 1, a1, bb1, c1, d1);
|
|
char hx[400];
|
|
std::snprintf(hx, sizeof hx, "\"cpuid_leaf7_sub0\": {\"eax\": \"0x%08x\", \"ebx\": \"0x%08x\", \"ecx\": \"0x%08x\", \"edx\": \"0x%08x\"}, "
|
|
"\"cpuid_leaf7_sub1\": {\"eax\": \"0x%08x\", \"ebx\": \"0x%08x\", \"ecx\": \"0x%08x\", \"edx\": \"0x%08x\"}", a0, b0, c0, d0, a1, bb1, c1, d1);
|
|
return "\"host_cpu_brand\": " + jstr(b) + ", " + hx;
|
|
}
|
|
|
|
int cmd_gen(const Args& a, const std::string& exe) {
|
|
const std::string dir = a.get("run-dir");
|
|
if (dir.empty()) die("gen needs --run-dir");
|
|
const uint64_t seed = std::strtoull(a.get("seed", "1").c_str(), nullptr, 10);
|
|
const std::string spec = a.get("cases", "all");
|
|
std::string bi_path = a.get("build-info");
|
|
if (bi_path.empty()) {
|
|
const size_t slash = exe.rfind('/');
|
|
bi_path = (slash == std::string::npos ? std::string(".") : exe.substr(0, slash)) + "/build-info.txt";
|
|
}
|
|
const std::map<std::string, std::string> bi = read_build_info(bi_path);
|
|
if (bi.empty()) die("no build record at " + bi_path + " (run make first)");
|
|
for (size_t at = 1; at <= dir.size(); ++at) // mkdir -p
|
|
if (at == dir.size() || dir[at] == '/') mkdir(dir.substr(0, at).c_str(), 0755);
|
|
struct stat st;
|
|
if (stat(dir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) die("cannot use run directory " + dir);
|
|
if (!list_cases(dir).empty() || access((dir + "/manifest.json").c_str(), F_OK) == 0) die(dir + " already holds a run; use a new directory");
|
|
const std::vector<Case> cases = parse_cases(spec, seed);
|
|
std::map<std::string, std::string> files; // name -> "sha256 bytes"
|
|
for (const Case& c : cases) {
|
|
const std::vector<uint8_t> v = make_case_file(c);
|
|
write_file(dir + "/case-" + c.id() + ".in", v.data(), v.size());
|
|
}
|
|
const std::string p512 = run_child(exe, dir, "avx512"), p2 = run_child(exe, dir, "avx2");
|
|
|
|
std::string cj;
|
|
bool first = true;
|
|
std::string fj;
|
|
bool ffirst = true;
|
|
auto add_file = [&](const std::string& name, std::string& sha, size_t& bytes) {
|
|
const std::vector<uint8_t> v = read_file(dir + "/" + name);
|
|
sha = sha_of(v);
|
|
bytes = v.size();
|
|
fj += std::string(ffirst ? "" : ",\n ") + jstr(name) + ": {\"sha256\": " + jstr(sha) + ", \"bytes\": " + std::to_string(bytes) + "}";
|
|
ffirst = false;
|
|
};
|
|
for (const Case& c : cases) {
|
|
std::string sha, sha5, sha2;
|
|
size_t nb = 0, n5 = 0, n2 = 0;
|
|
add_file("case-" + c.id() + ".in", sha, nb);
|
|
add_file("case-" + c.id() + ".cpp-avx512.out", sha5, n5);
|
|
add_file("case-" + c.id() + ".cpp-avx2.out", sha2, n2);
|
|
cj += std::string(first ? "" : ",\n ") + "{\"id\": " + jstr(c.id()) + ", \"gu_type\": " + std::to_string(c.gu) + ", \"down_type\": " +
|
|
std::to_string(c.down) + ", \"gu_name\": " + jstr(fmt_of(c.gu)->name) + ", \"down_name\": " + jstr(fmt_of(c.down)->name) +
|
|
", \"rows\": " + std::to_string(c.rows) + ", \"seed\": " + std::to_string(c.seed) + ", \"seed_informational\": true" +
|
|
", \"equality\": \"bitwise\", \"tolerance\": null, \"in\": " + jstr("case-" + c.id() + ".in") + ", \"in_sha256\": " + jstr(sha) +
|
|
", \"in_bytes\": " + std::to_string(nb) + ", \"out_cpp_avx512\": " + jstr("case-" + c.id() + ".cpp-avx512.out") +
|
|
", \"out_cpp_avx512_sha256\": " + jstr(sha5) + ", \"out_cpp_avx512_bytes\": " + std::to_string(n5) +
|
|
", \"out_cpp_avx2\": " + jstr("case-" + c.id() + ".cpp-avx2.out") + ", \"out_cpp_avx2_sha256\": " + jstr(sha2) +
|
|
", \"out_cpp_avx2_bytes\": " + std::to_string(n2) + "}";
|
|
first = false;
|
|
}
|
|
auto g = [&](const char* k) { auto it = bi.find(k); return it == bi.end() ? std::string("unknown") : it->second; };
|
|
const bool avx512_ok = p512.find("\"avx512_ok\": true") != std::string::npos;
|
|
const bool avx2_ok = p512.find("\"avx2_ok\": true") != std::string::npos;
|
|
std::string m = "{\n \"format\": \"KAB1\",\n \"version\": 1,\n \"run_id\": " + jstr(dir.substr(dir.rfind('/') + 1)) + ",\n \"writer\": \"cpp\",\n";
|
|
m += " \"provenance\": {\n \"tools_kernel_ab_commit\": " + jstr(g("tools_commit")) + ",\n \"tools_kernel_ab_dirty_paths\": " + jstr(g("tools_dirty_paths")) +
|
|
",\n \"engine_strata_pin\": " + jstr(g("engine_strata_pin")) + ",\n \"strata_version\": " + jstr(g("strata_version")) +
|
|
",\n \"ggml_commit\": " + jstr(g("ggml_commit")) + ",\n \"ggml_pin\": " + jstr(g("ggml_pin")) + ",\n \"ggml_source\": " + jstr(g("ggml_source")) +
|
|
",\n \"compiler_id\": " + jstr(g("compiler_id")) + ",\n \"compiler_version\": " + jstr(g("compiler_version")) +
|
|
",\n \"compiler_banner\": " + jstr(g("compiler_banner")) + ",\n \"target_triple\": " + jstr(g("target_triple")) +
|
|
",\n \"build_system\": " + jstr(g("build_system")) + ",\n \"built_at_utc\": " + jstr(g("built_at_utc")) +
|
|
",\n \"flags\": {\n \"CMAKE_BUILD_TYPE\": " + jstr(g("CMAKE_BUILD_TYPE")) + ",\n \"CMAKE_CXX_FLAGS_RELEASE\": " + jstr(g("CMAKE_CXX_FLAGS_RELEASE")) +
|
|
",\n \"strata_cxx_flags\": " + jstr(g("strata_cxx_flags")) + ",\n \"strata_per_file_flags\": " + jstr(g("strata_per_file_flags")) +
|
|
",\n \"strata_avxvnni_define\": " + jstr(g("strata_avxvnni_define")) + ",\n \"ggml_c_flags\": " + jstr(g("ggml_c_flags")) +
|
|
",\n \"ggml_cxx_flags\": " + jstr(g("ggml_cxx_flags")) + ",\n \"ggml_cpu_arch_flags\": " + jstr(g("ggml_cpu_arch_flags")) +
|
|
",\n \"GGML_NATIVE\": " + jstr(g("GGML_NATIVE")) + ",\n \"STRATA_PORTABLE\": " + jstr(g("STRATA_PORTABLE")) +
|
|
",\n \"STRATA_ISA_FLOOR\": " + jstr(g("STRATA_ISA_FLOOR")) + ",\n \"STRATA_ENABLE_CUDA\": " + jstr(g("STRATA_ENABLE_CUDA")) +
|
|
",\n \"STRATA_NATIVE_EXPERTS\": " + jstr(g("STRATA_NATIVE_EXPERTS")) + "\n },\n " + cpu_brand_and_bits() +
|
|
",\n \"avx2_ok\": " + jbool(avx2_ok) + ",\n \"avx512_ok\": " + jbool(avx512_ok) + ",\n \"trees\": {\"avx512\": " + p512 + ", \"avx2\": " + p2 +
|
|
"},\n \"strata_env_seen\": " + env_json(env_matching(environ)) + ",\n \"seed\": " + std::to_string(seed) + ",\n \"cases_spec\": " + jstr(spec) +
|
|
"\n },\n \"cases\": [\n " + cj + "\n ],\n \"files\": {\n " + fj + "\n }\n}\n";
|
|
write_file(dir + "/manifest.json.tmp", m.data(), m.size());
|
|
if (rename((dir + "/manifest.json.tmp").c_str(), (dir + "/manifest.json").c_str()) != 0) die("rename of manifest.json failed");
|
|
std::printf("kab gen: %zu cases, %zu files, manifest %s/manifest.json (avx2_ok=%s avx512_ok=%s)\n", cases.size(), cases.size() * 3, dir.c_str(),
|
|
jbool(avx2_ok), jbool(avx512_ok));
|
|
return 0;
|
|
}
|
|
|
|
// STRA-317 (S0.8a2): the `time` sub-command lives in kab_time.cpp, included here so it shares this file's reader and composition
|
|
#define KAB_TIME_INCLUDED_FROM_KAB 1
|
|
#include "kab_time.cpp"
|
|
|
|
} // namespace
|
|
|
|
int main(int argc, char** argv) {
|
|
if (argc < 2) die("usage: kab gen|run-tree|poolcheck|time ...");
|
|
const std::string cmd = argv[1];
|
|
const Args a = parse(argc, argv, 2);
|
|
if (cmd == "gen" || cmd == "time") {
|
|
char self[4096];
|
|
const ssize_t n = readlink("/proc/self/exe", self, sizeof self - 1);
|
|
if (n <= 0) die("cannot resolve /proc/self/exe");
|
|
self[n] = 0;
|
|
return cmd == "gen" ? cmd_gen(a, self) : cmd_time(a, self);
|
|
}
|
|
if (cmd == "run-tree") return cmd_run_tree(a);
|
|
if (cmd == "poolcheck") return cmd_poolcheck(a);
|
|
die("unknown command " + cmd);
|
|
}
|