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++
metal: streaming reads each expert with one request from <gguf>.experts (stream_experts.py: gate, up, down together) - M4 IQ3_XXS after 6K: 8.62 vs 7.37 tok/s, prompts 84 vs 65 tok/s, same tokens
Niko1221c34ac7093fe8
diff --git a/metal/src/engine/stream.cpp b/metal/src/engine/stream.cppindex 57034c273..4aef6a090 100644--- a/metal/src/engine/stream.cpp+++ b/metal/src/engine/stream.cpp@@ -5,6 +5,7 @@#include <fcntl.h>#include <sys/mman.h>+#include <sys/stat.h>#include <unistd.h>#include <algorithm>@@ -63,6 +64,54 @@ bool ExpertStream::open(const gguf::File& f, std::string& err) {if (!g || !u || !d) { err = "metal stream: layer " + std::to_string(l) + " has no routed experts"; return false; }lay_[(size_t) l] = {g->offset, g->bytes / NE, u->offset, u->bytes / NE, d->offset, d->bytes / NE, -1};}+ // the expert-contiguous copy beside the GGUF, when it is this GGUF's (sizes in its header) and its first and+ // last experts match the GGUF's bytes+ if (env_int("STRATA_METAL_CONTIG", 1) != 0) {+ const std::string cp = f.path + ".experts";+ const int cfd = ::open(cp.c_str(), O_RDONLY);+ bool ok = cfd >= 0;+ std::vector<uint64_t> off(NL);+ if (ok) {+ uint8_t h[64];+ std::vector<uint64_t> t((size_t) NL * 4);+ struct stat st {};+ ::fstat(fd_, &st);+ ok = ::pread(cfd, h, 64, 0) == 64 && std::memcmp(h, "STRX", 4) == 0 &&+ ::pread(cfd, t.data(), t.size() * 8, 64) == (ssize_t) (t.size() * 8);+ uint32_t ver = 0, nl = 0, ne = 0;+ uint64_t src = 0;+ std::memcpy(&ver, h + 4, 4); std::memcpy(&nl, h + 8, 4); std::memcpy(&ne, h + 12, 4); std::memcpy(&src, h + 16, 8);+ ok = ok && ver == 1 && nl == (uint32_t) NL && ne == (uint32_t) NE && src == (uint64_t) st.st_size;+ for (int l = 0; ok && l < NL; ++l) {+ const Lay& x = lay_[(size_t) l];+ ok = t[(size_t) l * 4 + 1] == x.gs && t[(size_t) l * 4 + 2] == x.us && t[(size_t) l * 4 + 3] == x.ds;+ off[(size_t) l] = t[(size_t) l * 4];+ }+ if (ok) { // spot check: layer 0's first and layer 47's last expert, every slice+ for (const int l : {0, NL - 1}) {+ const Lay& x = lay_[(size_t) l];+ const int e = l == 0 ? 0 : NE - 1;+ std::vector<uint8_t> a(x.gs + x.us + x.ds), b(a.size());+ ok = ok && ::pread(cfd, a.data(), a.size(), (off_t) (off[(size_t) l] + (uint64_t) e * a.size())) == (ssize_t) a.size() &&+ ::pread(fd_, b.data(), x.gs, (off_t) (x.g + (uint64_t) e * x.gs)) == (ssize_t) x.gs &&+ ::pread(fd_, b.data() + x.gs, x.us, (off_t) (x.u + (uint64_t) e * x.us)) == (ssize_t) x.us &&+ ::pread(fd_, b.data() + x.gs + x.us, x.ds, (off_t) (x.d + (uint64_t) e * x.ds)) == (ssize_t) x.ds &&+ a == b;+ }+ }+ }+ if (ok) {+ fcntl(cfd, F_NOCACHE, 1);+ fcntl(cfd, F_RDAHEAD, 0);+ cfd_ = cfd;+ coff_ = off;+ std::fprintf(stderr, "strata metal stream: experts read from %s (one request per expert)\n", cp.c_str());+ } else if (cfd >= 0) {+ ::close(cfd);+ std::fprintf(stderr, "strata metal stream: %s is not this GGUF's (sizes or bytes differ): the GGUF is read\n",+ cp.c_str());+ }+ }// size classes: one LRU pool per class. The layers' slot sizes (9 in the IQ3_XXS mix) are merged into a few// classes, each as big as its largest member, so that no member wastes more than STRATA_METAL_CLASS_WASTE (default// 0.15) of its slot: every class must hold a whole layer's experts for a prompt chunk, so fewer classes = less@@ -215,6 +264,23 @@ int ExpertStream::victim(int ci) {// SSD's throughput, is what a layer waits for).void ExpertStream::read_part(int s, int l, int e, int part) {const Lay& x = lay_[(size_t) l];+ if (cfd_ >= 0) { // the contiguous copy: the whole expert, piece part of split_ (the slot keeps gate | up | down)+ const uint64_t len = x.gs + x.us + x.ds, src = coff_[(size_t) l] + (uint64_t) e * len;+ const uint64_t a = len * (uint64_t) part / (uint64_t) split_ / 4096 * 4096;+ const uint64_t b = part + 1 == split_ ? len : len * (uint64_t) (part + 1) / (uint64_t) split_ / 4096 * 4096;+ uint8_t* p = host_[(size_t) s] + a;+ uint64_t n = b - a, o = src + a;+ while (n > 0) {+ const ssize_t r = ::pread(cfd_, p, (size_t) n, (off_t) o);+ if (r <= 0) {+ std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l);+ std::exit(6);+ }+ p += r; o += (uint64_t) r; n -= (uint64_t) r;+ }+ bytes_read_ += b - a;+ return;+ }const int k = part / split_, p = part % split_;const uint64_t len = k == 0 ? x.gs : (k == 1 ? x.us : x.ds);const uint64_t src = (k == 0 ? x.g : (k == 1 ? x.u : x.d)) + (uint64_t) e * len;@@ -262,10 +328,11 @@ void ExpertStream::submit(int s, int l, int e, bool urgent) {x.e = (int16_t) e;x.state = 1;x.pre = !urgent;- x.left = 3 * split_;+ const int parts = cfd_ >= 0 ? split_ : 3 * split_;+ x.left = parts;++outstanding_;where_[(size_t) (l * NE + e)] = s;- for (int p = 0; p < 3 * split_; ++p) (urgent ? urgent_q_ : pre_q_).push_back({s, l, e, p});+ for (int p = 0; p < parts; ++p) (urgent ? urgent_q_ : pre_q_).push_back({s, l, e, p});}// a queued read-ahead nobody wants: its pieces dropped, the slot freed (only before any piece has started)diff --git a/metal/src/engine/stream.h b/metal/src/engine/stream.hindex 362a00338..e2d230ad9 100644--- a/metal/src/engine/stream.h+++ b/metal/src/engine/stream.h@@ -89,6 +89,10 @@ private:void wait_slot(int s);int fd_ = -1;+ // <gguf>.experts (metal/tools/stream_experts.py): each expert's gate, up and down rows together, read with one+ // request (cfd_ >= 0); else the GGUF's three slices. STRATA_METAL_CONTIG=0: the GGUF always.+ int cfd_ = -1;+ std::vector<uint64_t> coff_;std::vector<Lay> lay_;std::vector<Cls> cls_;std::vector<Slot> slots_;diff --git a/metal/tools/stream_experts.py b/metal/tools/stream_experts.pynew file mode 100644index 000000000..4eedafbe6--- /dev/null+++ b/metal/tools/stream_experts.py@@ -0,0 +1,102 @@+#!/usr/bin/env python3+"""stream_experts.py: the routed experts of a GGUF re-laid for SSD streaming - every expert's gate, up and down rows+next to each other, so the Metal engine reads a missed expert with one request instead of three (the M4 Mac mini's+SSD: 2.97 GB/s for one 1.75 MB read per expert against 2.30 GB/s for three 0.58 MB reads, 6 threads, F_NOCACHE).++ python3 metal/tools/stream_experts.py --gguf <model shard 1 or the repacked -metal.gguf> [--out <gguf>.experts] [--verify]++The file: a 64-byte header ("STRX", version 1, 48 layers, 512 experts, the source GGUF's size), then per layer its+offset in this file and the three slice sizes (4 x u64 each), then the experts, layer by layer, expert by expert:+gate slice, up slice, down slice - each byte for byte the GGUF's. --verify compares every expert with the GGUF.+The engine (metal/src/engine/stream.cpp) uses it when it sits beside the GGUF as <gguf>.experts and its header+matches; otherwise it reads the GGUF as before.+"""+from __future__ import annotations++import argparse+import hashlib+import os+import struct+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import metal_repack as R # noqa: E402++NL, NE = 48, 512+ALIGN = 16384+++def plan(gguf: Path):+ """The reader, each layer's (gate, up, down, slice sizes), each layer's offset in the file, the file's size, the+ first data offset."""+ rd = R.Reader(gguf)+ tab = {t["name"]: t for t in rd.tensors}+ lay = []+ for l in range(NL):+ g, u, d = (tab[f"blk.{l}.ffn_{k}_exps.weight"] for k in ("gate", "up", "down"))+ lay.append((g, u, d, g["bytes"] // NE, u["bytes"] // NE, d["bytes"] // NE))+ head_len = 64 + NL * 32+ data0 = (head_len + ALIGN - 1) // ALIGN * ALIGN+ offs, at = [], data0+ for g, u, d, gs, us, ds in lay:+ offs.append(at)+ at += NE * (gs + us + ds)+ at = (at + ALIGN - 1) // ALIGN * ALIGN+ return rd, lay, offs, at, data0+++def size_bytes(gguf: Path) -> int:+ """The size the file for this GGUF will have (setup checks the free disk with it)."""+ rd, _, _, at, _ = plan(gguf)+ rd.f.close()+ return at+++def main() -> int:+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])+ ap.add_argument("--gguf", required=True, type=Path)+ ap.add_argument("--out", type=Path)+ ap.add_argument("--verify", action="store_true")+ a = ap.parse_args()+ out = a.out or a.gguf.with_name(a.gguf.name + ".experts")+ rd, lay, offs, at, data0 = plan(a.gguf)+ head = struct.pack("<4sIIIQ", b"STRX", 1, NL, NE, os.path.getsize(a.gguf)).ljust(64, b"\0")+ for (g, u, d, gs, us, ds), o in zip(lay, offs):+ head += struct.pack("<QQQQ", o, gs, us, ds)+ tmp = out.with_name(out.name + ".part")+ src = rd.f+ with open(tmp, "wb") as f:+ f.write(head.ljust(data0, b"\0"))+ for l, ((g, u, d, gs, us, ds), o) in enumerate(zip(lay, offs)):+ src.seek(g["abs"]); G = src.read(g["bytes"])+ src.seek(u["abs"]); U = src.read(u["bytes"])+ src.seek(d["abs"]); D = src.read(d["bytes"])+ f.seek(o)+ f.write(b"".join(G[e * gs:(e + 1) * gs] + U[e * us:(e + 1) * us] + D[e * ds:(e + 1) * ds] for e in range(NE)))+ print(f"\r layer {l + 1} / {NL}", end="", flush=True)+ f.truncate(at)+ print()+ if a.verify:+ with open(tmp, "rb") as f:+ for l, ((g, u, d, gs, us, ds), o) in enumerate(zip(lay, offs)):+ h1, h2 = hashlib.sha256(), hashlib.sha256()+ for t in (g, u, d):+ src.seek(t["abs"])+ h1.update(src.read(t["bytes"]))+ f.seek(o)+ blob = f.read(NE * (gs + us + ds))+ step = gs + us + ds+ for part, size, base in ((0, gs, 0), (1, us, gs), (2, ds, gs + us)):+ h2.update(b"".join(blob[e * step + base:e * step + base + size] for e in range(NE)))+ if h1.digest() != h2.digest():+ tmp.unlink()+ sys.exit(f"verify FAILED at layer {l} (output removed)")+ print(f"verify: {NL} layers x {NE} experts identical to the GGUF")+ os.replace(tmp, out)+ print(f"{out}: {at / 2**30:.2f} GiB")+ return 0+++if __name__ == "__main__":+ sys.exit(main())