Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

kq_cpu_bench: the CPU pool's expert rows per format on T threads in GB/s of weights; tools/quant_bound.py: decode bounds from the per-layer formats; setup copies libstrata_kq next to a compiled engine

Niko1221c7070a72cf2d
diff --git a/CMakeLists.txt b/CMakeLists.txt
index f35277bd4..408d469e0 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1329,6 +1329,9 @@ if(STRATA_NATIVE_EXPERTS)
# against ggml-cpu's dot, on random blocks; --bench: ms per expert on one thread, the weights streamed from DRAM
add_executable(iq_avx2_parity src/kernels/cpu/iq_avx2_parity.cpp)
target_link_libraries(iq_avx2_parity PRIVATE strata_kernels_cpu)
+ # MODEL-UPDATE: the pool's expert rows per format on T threads against the RAM bandwidth (a benchmark, no test)
+ add_executable(kq_cpu_bench src/kernels/cpu/kq_cpu_bench.cpp)
+ target_link_libraries(kq_cpu_bench PRIVATE strata_kernels_cpu)
if(STRATA_BUILD_TESTS)
add_test(NAME iq_avx2_parity COMMAND iq_avx2_parity)
add_test(NAME iq_avx2_parity_iq3s_mt1 COMMAND ${CMAKE_COMMAND} -E env STRATA_IQ3S_MT1=1 $<TARGET_FILE:iq_avx2_parity>)
diff --git a/setup.py b/setup.py
index 7d291e1c6..ea3fac207 100644
--- a/setup.py
+++ b/setup.py
@@ -308,6 +308,9 @@ VISION = {"gpu": {"max_tokens": 1024, "reserve_mib": 700},
"cpu": {"max_tokens": 300, "reserve_mib": 700}}
EXE = "strata.exe" if WIN else "strata"
VEXE = "strata-vision.exe" if WIN else "strata-vision"
+# MODEL-UPDATE Phase 1: the K-quant prompt kernels (Unsloth's UD-Q4/Q5/Q6_K_XL experts) are a library next to the CUDA
+# engine, opened only for those models; an engine without it runs them on the FP16 prompt path
+KQ_LIB = "strata_kq.dll" if WIN else "libstrata_kq.so"
# ------------------------------------------------------------------------------------------------ output
@@ -3430,6 +3433,10 @@ def build_engine(gpu, vision, yes, llama, toolkit=None) -> Path:
f"this source is {source_version()}): the installed engine and its stamp are left as they were",
"the build folder " + str(bdir) + " may be configured for something else: delete it and run this again")
shutil.copy2(bdir / EXE, eng / EXE)
+ if (bdir / KQ_LIB).exists(): # built with it (Phase 1): it goes next to the engine
+ shutil.copy2(bdir / KQ_LIB, eng / KQ_LIB)
+ elif (eng / KQ_LIB).exists(): # an older one of another build would only be refused
+ (eng / KQ_LIB).unlink()
if not vision_ok:
say(" Compiling the image encoder" + (" with CUDA (10-20 minutes, once) ..." if vision == "gpu" else " ..."))
defs = [f"-DLLAMA_DIR={llama}", f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}",
diff --git a/src/kernels/cpu/kq_cpu_bench.cpp b/src/kernels/cpu/kq_cpu_bench.cpp
new file mode 100644
index 000000000..706146fdf
--- /dev/null
+++ b/src/kernels/cpu/kq_cpu_bench.cpp
@@ -0,0 +1,172 @@
+// src/kernels/cpu/kq_cpu_bench.cpp - MODEL-UPDATE: how close the CPU pool's expert rows come to the RAM bandwidth, per
+// expert format. No GPU, no model: --mb MB of expert blobs (ggml-quantized random weights, far more than any L3) are
+// computed by T threads at once through the engine's own entry points (native_gu_rows + native_down_rows, the pool's
+// calls), each thread walking its own experts, nt tokens per expert - the decode case, where every CPU expert is a
+// fresh read from DRAM. Prints the weight bytes per second against the --ram-gbs given (a separate read test).
+//
+// kq_cpu_bench [--pairs q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl] [--threads 1,8,16,32] [--nt 1,2,4]
+// [--mb 4096] [--reps 3] [--ram-gbs N]
+#include "strata/kernels/cpu/expert_layout.hpp"
+#include "strata/kernels/cpu/native_expert.hpp"
+
+#include "ggml.h"
+#include "ggml-cpu.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <memory>
+#include <random>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace cpu = strata::kernels::cpu;
+
+namespace {
+
+constexpr int64_t kH = 2560, kFF = 640;
+constexpr int kMaxT = 8;
+
+int type_of(const std::string& s) {
+ for (int t = 0; t < GGML_TYPE_COUNT; ++t) {
+ const char* n = ggml_type_name((ggml_type) t);
+ if (n != nullptr && s == n) return t;
+ }
+ return -1;
+}
+
+std::vector<std::string> split(const std::string& s) {
+ std::vector<std::string> v;
+ size_t from = 0;
+ for (;;) {
+ const size_t c = s.find(',', from);
+ v.push_back(s.substr(from, c == std::string::npos ? std::string::npos : c - from));
+ if (c == std::string::npos) break;
+ from = c + 1;
+ }
+ return v;
+}
+
+// one expert blob in the GGUF form: gate rows, up rows (n_ff x n_embd each), down rows (n_embd x n_ff), from random
+// weights quantized by ggml-cpu (valid scales, as a real file has)
+void make_blob(const cpu::NativeFmt& f, uint8_t* blob, std::mt19937& rng) {
+ std::normal_distribution<float> nd(0.f, 0.02f);
+ std::vector<float> row((size_t) std::max(kH, kFF));
+ const auto* tg = ggml_get_type_traits_cpu((ggml_type) f.gu_type);
+ const auto* td = ggml_get_type_traits_cpu((ggml_type) f.d_type);
+ for (int64_t r = 0; r < 2 * kFF; ++r) {
+ for (int64_t i = 0; i < kH; ++i) row[(size_t) i] = nd(rng);
+ tg->from_float(row.data(), blob + (size_t) r * f.gu_row, kH);
+ }
+ for (int64_t r = 0; r < kH; ++r) {
+ for (int64_t i = 0; i < kFF; ++i) row[(size_t) i] = nd(rng);
+ td->from_float(row.data(), blob + f.down_off + (size_t) r * f.d_row, kFF);
+ }
+}
+
+} // namespace
+
+int main(int argc, char** argv) {
+ setvbuf(stdout, nullptr, _IONBF, 0);
+ std::vector<std::string> pairs = split("q4_K/q5_1,q5_K/q8_0,q6_K/q8_0,q8_0/q8_0,iq3_s/iq4_nl");
+ std::vector<int> threads = {1, 8, 16, 32}, nts = {1, 2, 4};
+ int mb = 4096, reps = 3;
+ double ram = 0;
+ for (int i = 1; i < argc; ++i) {
+ const std::string a = argv[i];
+ const bool more = i + 1 < argc;
+ auto ints = [](const std::string& s) { std::vector<int> v; for (auto& x : split(s)) v.push_back(std::atoi(x.c_str())); return v; };
+ if (a == "--pairs" && more) pairs = split(argv[++i]);
+ else if (a == "--threads" && more) threads = ints(argv[++i]);
+ else if (a == "--nt" && more) nts = ints(argv[++i]);
+ else if (a == "--mb" && more) mb = std::atoi(argv[++i]);
+ else if (a == "--reps" && more) reps = std::max(1, std::atoi(argv[++i]));
+ else if (a == "--ram-gbs" && more) ram = std::atof(argv[++i]);
+ else {
+ std::fprintf(stderr, "usage: kq_cpu_bench [--pairs a/b,...] [--threads 1,8] [--nt 1,2,4] [--mb 4096] [--reps 3] [--ram-gbs N]\n");
+ return 2;
+ }
+ }
+ ggml_cpu_init();
+ std::printf("kq_cpu_bench: %s (avx2 %d, avx512 %d), %d MB of blobs per format\n", cpu::cpu_name().c_str(),
+ (int) cpu::cpu_avx2_ok(), (int) cpu::cpu_avx512_ok(), mb);
+ for (const std::string& pair : pairs) {
+ const size_t slash = pair.find('/');
+ const int gt = slash == std::string::npos ? -1 : type_of(pair.substr(0, slash));
+ const int dt = slash == std::string::npos ? -1 : type_of(pair.substr(slash + 1));
+ cpu::NativeFmt f;
+ std::string err;
+ if (gt < 0 || dt < 0 || !cpu::native_fmt(gt, dt, kH, kFF, f, err)) {
+ std::printf("%s: %s\n", pair.c_str(), err.empty() ? "unknown types" : err.c_str());
+ continue;
+ }
+ const size_t E = std::max<size_t>(64, ((size_t) mb << 20) / f.bytes);
+ std::unique_ptr<uint8_t[]> mem(new uint8_t[E * f.bytes + 4096]);
+ uint8_t* blobs = (uint8_t*) (((uintptr_t) mem.get() + 4095) & ~(uintptr_t) 4095);
+ { // 16 distinct experts, copied over the whole buffer (the bytes in DRAM are what is measured)
+ std::mt19937 rng(1234 + gt * 64 + dt);
+ const size_t U = std::min<size_t>(16, E);
+ for (size_t e = 0; e < U; ++e) make_blob(f, blobs + e * f.bytes, rng);
+ for (size_t e = U; e < E; ++e) std::memcpy(blobs + e * f.bytes, blobs + (e % U) * f.bytes, f.bytes);
+ }
+ // activations: kMaxT tokens of x (n_embd) and h (n_ff), quantized the way the pool quantizes them
+ std::mt19937 rng(77);
+ std::normal_distribution<float> nd(0.f, 1.f);
+ std::vector<std::vector<uint8_t>> xa(kMaxT, std::vector<uint8_t>(cpu::kNativeActBytes)),
+ ha(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
+ const void* act[kMaxT];
+ const void* hq[kMaxT];
+ for (int t = 0; t < kMaxT; ++t) {
+ std::vector<float> x(kH), h(kFF);
+ for (auto& v : x) v = nd(rng);
+ for (auto& v : h) v = 0.1f * nd(rng);
+ cpu::native_quant_act(f, x.data(), xa[t].data());
+ cpu::native_quant_h(f, h.data(), ha[t].data());
+ act[t] = xa[t].data();
+ hq[t] = ha[t].data();
+ }
+ std::printf("\n%s: %zu experts of %.3f MB (%.0f MB)\n", pair.c_str(), E, f.bytes / 1e6, E * (double) f.bytes / 1e6);
+ for (int nt : nts) {
+ for (int T : threads) {
+ if (T < 1) continue;
+ std::vector<double> gbs;
+ for (int rep = 0; rep < reps; ++rep) {
+ std::atomic<size_t> next{0};
+ auto work = [&] {
+ std::vector<float> ffb((size_t) kMaxT * kFF), outb((size_t) kMaxT * kH);
+ float* ff[kMaxT];
+ float* out[kMaxT];
+ for (int t = 0; t < kMaxT; ++t) { ff[t] = &ffb[(size_t) t * kFF]; out[t] = &outb[(size_t) t * kH]; }
+ std::vector<std::vector<uint8_t>> hb(kMaxT, std::vector<uint8_t>(cpu::kNativeHBytes));
+ for (;;) {
+ const size_t e = next.fetch_add(1);
+ if (e >= E) break;
+ const uint8_t* blob = blobs + e * f.bytes;
+ cpu::native_gu_rows(f, blob, act, nt, ff, 0, (int) kFF);
+ cpu::native_down_rows(f, blob, hq, nt, out, 0, (int) kH);
+ }
+ volatile float sink = outb[0] + ffb[0];
+ (void) sink;
+ };
+ const auto t0 = std::chrono::steady_clock::now();
+ std::vector<std::thread> th;
+ for (int k = 0; k < T; ++k) th.emplace_back(work);
+ for (auto& x : th) x.join();
+ const double s = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
+ gbs.push_back(E * (double) f.bytes / s / 1e9);
+ }
+ std::sort(gbs.begin(), gbs.end());
+ const double med = gbs[gbs.size() / 2];
+ std::printf(" nt %d threads %2d: %6.1f GB/s of weights (%.3f ms per expert per thread)%s\n", nt, T, med,
+ f.bytes / (med * 1e9 / T) * 1e3,
+ ram > 0 ? (" = " + std::to_string((int) std::lround(100 * med / ram)) + "% of RAM").c_str() : "");
+ }
+ }
+ }
+ return 0;
+}
diff --git a/tools/quant_bound.py b/tools/quant_bound.py
new file mode 100644
index 000000000..cce03b001
--- /dev/null
+++ b/tools/quant_bound.py
@@ -0,0 +1,59 @@
+#!/usr/bin/env python3
+"""Decode bounds of a quant from its real per-layer formats (tools/quant_formats.py --json output).
+
+ python tools/quant_bound.py FMT.json [...] --ram-gbs 120 [--vram-gbs 640] [--hit 0.3] [--tokens-per-pass 1]
+
+Per token: the routed experts (10 of 512 per layer: each layer's gate + up + down bytes / 512 x 10), the shared expert
+and the dense side (attention, SSM, hyper-connections, router, head: read once per pass on the GPU). The bound for a
+pass of P tokens (a verify window) with a VRAM hit fraction h of the routed experts:
+ t_cpu = (1 - h) x routed bytes x U(P) / RAM bandwidth (the CPU pool reads every missed expert once per pass)
+ t_gpu = (h x routed x U(P) + dense) / VRAM bandwidth
+ tok/s <= P / max(t_cpu, t_gpu)
+U(P) is the distinct experts a pass of P tokens reads per expert a single token reads (1 for P = 1; measured from
+the engine's window logs where known, else --union). The CPU line alone (h = 0) is the floor of the all-on-CPU case.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import pathlib
+
+TOPK, N_EXPERT = 10, 512
+
+
+def bytes_of(js: dict) -> dict:
+ roles = js["roles"]
+ tot = lambda role: sum(v["bytes"] for v in roles.get(role, {}).values())
+ routed_all = tot("routed gate") + tot("routed up") + tot("routed down")
+ per_token = routed_all / N_EXPERT * TOPK
+ dense = sum(tot(r) for r in ("shared expert", "router", "attention", "SSM", "hyper-connections", "indexer",
+ "PLE key/value", "output head"))
+ return {"routed_all": routed_all, "routed_per_token": per_token, "dense_per_pass": dense,
+ "expert_bytes": routed_all / 48 / N_EXPERT}
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("fmt", nargs="+")
+ ap.add_argument("--ram-gbs", type=float, required=True, help="measured RAM read bandwidth, GB/s")
+ ap.add_argument("--vram-gbs", type=float, default=0, help="GPU memory bandwidth, GB/s (0: no GPU line)")
+ ap.add_argument("--hit", type=float, default=0.0, help="VRAM hit fraction of the routed experts")
+ ap.add_argument("--tokens-per-pass", type=float, default=1.0)
+ ap.add_argument("--union", type=float, default=1.0, help="distinct experts per pass / experts per token")
+ a = ap.parse_args()
+ print(f"{'quant':12s} {'expert MB':>9s} {'routed MB/tok':>13s} {'dense MB':>9s} {'CPU-only tok/s':>15s} "
+ f"{'bound tok/s':>11s}")
+ for f in a.fmt:
+ b = bytes_of(json.loads(pathlib.Path(f).read_text()))
+ r = b["routed_per_token"] * a.union
+ t_cpu = (1 - a.hit) * r / (a.ram_gbs * 1e9)
+ t_gpu = (a.hit * r + b["dense_per_pass"]) / (a.vram_gbs * 1e9) if a.vram_gbs else 0.0
+ cpu_only = 1 / (b["routed_per_token"] / (a.ram_gbs * 1e9))
+ bound = a.tokens_per_pass / max(t_cpu, t_gpu) if max(t_cpu, t_gpu) > 0 else float("inf")
+ print(f"{pathlib.Path(f).stem:12s} {b['expert_bytes'] / 1e6:9.2f} {b['routed_per_token'] / 1e6:13.1f} "
+ f"{b['dense_per_pass'] / 1e6:9.1f} {cpu_only:15.1f} {bound:11.1f}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())