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++

metal: SSD-streaming expert arena for Macs whose memory cannot hold the model (the M4 32 GB)

Niko1221a6e55d062e54
diff --git a/metal/kernels/moe.metal b/metal/kernels/moe.metal
index 029a20b05..c625d4bdc 100644
--- a/metal/kernels/moe.metal
+++ b/metal/kernels/moe.metal
@@ -42,6 +42,18 @@ struct MoeArgs {
uint pad;
};
+// The SSD-streaming arena (metal/src/engine/stream.cpp): with function constant 20 set, expert e of the layer lies in
+// an arena slot, smap[e] = (chunk << 28) | its 16 KiB page in that chunk; the chunks are W (buffer 0) and buffers 7..9
+// (gate_off / up_off / down_off are then offsets inside the slot).
+constant bool kArenaFc [[function_constant(20)]];
+constant bool kArena = is_function_constant_defined(kArenaFc) && kArenaFc;
+static inline device const uchar* arena_slot(uint v, device const uchar* W, device const uchar* W1, device const uchar* W2,
+ device const uchar* W3) {
+ const uint c = v >> 28;
+ device const uchar* b = c == 0 ? W : (c == 1 ? W1 : (c == 2 ? W2 : W3));
+ return b + (ulong)(v & 0x0FFFFFFFu) * 16384ul;
+}
+
static inline void plan_body(device const int* ids, device const float* w, device int* plan, constant MoeArgs& a,
ushort tid, ushort nth, ushort sg, ushort lane, threadgroup int* s_grp,
threadgroup int* s_ent) {
@@ -188,6 +200,8 @@ template <int F, int LPR, int NR, int SG>
kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[buffer(1)]],
device float* h [[buffer(2)]], device const int* plan [[buffer(3)]],
constant MoeArgs& a [[buffer(4)]], device const float* xs16 [[buffer(5)]],
+ device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]],
+ device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]],
uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
constexpr int RG = 32 / LPR;
@@ -201,8 +215,9 @@ kernel void moe_gu(device const uchar* W [[buffer(0)]], device const float* x [[
const ulong ex = (ulong)plan[P_GEXP + g];
const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
device const int* etok = plan + P_ETOK + c;
- device const uchar* g0 = W + a.gate_off + ex * a.gu_stride + (ulong)row0 * a.gu_row;
- device const uchar* u0 = W + a.up_off + ex * a.gu_stride + (ulong)row0 * a.gu_row;
+ device const uchar* E = kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.gu_stride;
+ device const uchar* g0 = E + a.gate_off + (ulong)row0 * a.gu_row;
+ device const uchar* u0 = E + a.up_off + (ulong)row0 * a.gu_row;
switch (ne) {
case 1: gu_body<F, LPR, NR, 1>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
case 2: gu_body<F, LPR, NR, 2>(g0, u0, x, xs16, h, etok, c, row0, li, a, tab); break;
@@ -250,6 +265,8 @@ template <int F, int LPR, int NR, int SG>
kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h [[buffer(1)]],
device float* ye [[buffer(2)]], device const int* plan [[buffer(3)]],
constant MoeArgs& a [[buffer(4)]], device const float* hs16 [[buffer(5)]],
+ device const uint* smap [[buffer(6)]], device const uchar* W1 [[buffer(7)]],
+ device const uchar* W2 [[buffer(8)]], device const uchar* W3 [[buffer(9)]],
uint3 tg [[threadgroup_position_in_grid]], ushort sg [[simdgroup_index_in_threadgroup]],
ushort lane [[thread_index_in_simdgroup]], ushort tid [[thread_index_in_threadgroup]]) {
constexpr int RG = 32 / LPR;
@@ -262,7 +279,7 @@ kernel void moe_down(device const uchar* W [[buffer(0)]], device const float* h
const int row0 = ((int(tg.x) * SG + sg) * RG + lane / LPR) * NR;
const ulong ex = (ulong)plan[P_GEXP + g];
const int c = plan[P_GSTART + g], ne = plan[P_GSTART + g + 1] - c;
- device const uchar* d0 = W + a.down_off + ex * a.d_stride + (ulong)row0 * a.d_row;
+ device const uchar* d0 = (kArena ? arena_slot(smap[ex], W, W1, W2, W3) : W + ex * a.d_stride) + a.down_off + (ulong)row0 * a.d_row;
switch (ne) {
case 1: dn_body<F, LPR, NR, 1>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
case 2: dn_body<F, LPR, NR, 2>(d0, h, hs16, ye, plan, c, row0, li, a, tab); break;
diff --git a/metal/src/engine/stream.cpp b/metal/src/engine/stream.cpp
new file mode 100644
index 000000000..c98c6cf29
--- /dev/null
+++ b/metal/src/engine/stream.cpp
@@ -0,0 +1,521 @@
+// metal/src/engine/stream.cpp - see stream.h.
+#include "stream.h"
+
+#include "ref_quant.h"
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <map>
+
+namespace strata::metal_engine {
+
+namespace {
+constexpr int NL = 48, NE = 512;
+constexpr uint64_t PAGE = 16384;
+double now_ms() { return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
+int env_int(const char* n, int d) {
+ const char* e = std::getenv(n);
+ return e && *e ? std::atoi(e) : d;
+}
+} // namespace
+
+bool ExpertStream::wanted(const gguf::File& f, const mtl::Context& cx) {
+ const char* e = std::getenv("STRATA_METAL_STREAM");
+ if (e && std::string(e) == "1") return true;
+ if (e && std::string(e) == "0") return false;
+ uint64_t exp = 0;
+ for (const auto& kv : f.tensors)
+ if (kv.first.find("_exps") != std::string::npos) exp += kv.second.bytes;
+ return (double) exp > 0.6 * (double) cx.recommended_working_set();
+}
+
+ExpertStream::~ExpertStream() {
+ {
+ std::lock_guard<std::mutex> g(mu_);
+ stop_ = true;
+ }
+ cv_.notify_all();
+ for (auto& t : io_) t.join();
+ if (fd_ >= 0) ::close(fd_);
+}
+
+bool ExpertStream::open(const gguf::File& f, std::string& err) {
+ fd_ = ::open(f.path.c_str(), O_RDONLY);
+ if (fd_ < 0) { err = "metal stream: cannot open " + f.path; return false; }
+ fcntl(fd_, F_NOCACHE, 1);
+ fcntl(fd_, F_RDAHEAD, 0);
+ lay_.resize(NL);
+ for (int l = 0; l < NL; ++l) {
+ const std::string b = "blk." + std::to_string(l) + ".";
+ const gguf::Tensor* g = f.find(b + "ffn_gate_exps.weight");
+ const gguf::Tensor* u = f.find(b + "ffn_up_exps.weight");
+ const gguf::Tensor* d = f.find(b + "ffn_down_exps.weight");
+ 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};
+ }
+ // size classes: slots of the same page count share one LRU pool
+ std::map<uint64_t, int> by_pages;
+ for (int l = 0; l < NL; ++l) {
+ const Lay& x = lay_[(size_t) l];
+ const uint64_t pages = (x.gs + x.us + x.ds + PAGE - 1) / PAGE;
+ auto it = by_pages.find(pages);
+ if (it == by_pages.end()) {
+ it = by_pages.emplace(pages, (int) cls_.size()).first;
+ Cls c;
+ c.pages = pages;
+ cls_.push_back(c);
+ }
+ lay_[(size_t) l].cls = it->second;
+ }
+ nio_ = std::max(1, env_int("STRATA_METAL_IO_THREADS", 6));
+ split_ = std::max(1, std::min(8, env_int("STRATA_METAL_READ_SPLIT", 2)));
+ pre_k_ = env_int("STRATA_METAL_PREFETCH", 10);
+ prefetch_ = pre_k_ > 0;
+ // timing only (WRONG answers): every missing expert is pointed at slot 0, nothing is read
+ fake_ = env_int("STRATA_METAL_STREAM_FAKE", 0) != 0;
+ return true;
+}
+
+bool ExpertStream::read(void* dst, uint64_t len, uint64_t off) const {
+ uint8_t* p = (uint8_t*) dst;
+ while (len > 0) {
+ const ssize_t r = ::pread(fd_, p, (size_t) std::min<uint64_t>(len, 64ull << 20), (off_t) off);
+ if (r <= 0) return false;
+ p += r;
+ off += (uint64_t) r;
+ len -= (uint64_t) r;
+ }
+ return true;
+}
+
+bool ExpertStream::load_dense(gguf::File& f, mtl::Context& cx, const std::vector<std::string>& skip, mtl::Buffer& out,
+ std::string& err) {
+ const double t0 = now_ms();
+ std::vector<gguf::Tensor*> ts;
+ uint64_t tot = 0;
+ for (auto& kv : f.tensors) {
+ gguf::Tensor& t = kv.second;
+ if (t.name.find("_exps") != std::string::npos) continue;
+ if (std::find(skip.begin(), skip.end(), t.name) != skip.end()) { t.offset = 0; continue; }
+ ts.push_back(&t);
+ tot += (t.bytes + 255) / 256 * 256;
+ }
+ out = cx.alloc((tot + PAGE - 1) / PAGE * PAGE);
+ std::vector<uint64_t> src(ts.size()), dst(ts.size());
+ uint64_t o = 0;
+ for (size_t i = 0; i < ts.size(); ++i) {
+ src[i] = ts[i]->offset;
+ dst[i] = o;
+ o += (ts[i]->bytes + 255) / 256 * 256;
+ }
+ std::atomic<size_t> next{0};
+ std::atomic<bool> ok{true};
+ std::vector<std::thread> th;
+ for (int k = 0; k < 4; ++k)
+ th.emplace_back([&] {
+ for (;;) {
+ const size_t i = next++;
+ if (i >= ts.size()) break;
+ if (!read(out.as<uint8_t>() + dst[i], ts[i]->bytes, src[i])) ok = false;
+ }
+ });
+ for (auto& x : th) x.join();
+ if (!ok) { err = "metal stream: reading the dense tensors failed"; return false; }
+ for (size_t i = 0; i < ts.size(); ++i) ts[i]->offset = dst[i];
+ std::fprintf(stderr, "strata metal stream: %zu dense tensors read into memory (%.2f GB, %.1f s; %zu left out)\n", ts.size(),
+ tot / 1e9, (now_ms() - t0) / 1e3, skip.size());
+ return true;
+}
+
+int ExpertStream::cls_of(int s) const { // the class ranges are contiguous
+ int ci = 0;
+ while (!(s >= cls_[(size_t) ci].base && s < cls_[(size_t) ci].base + cls_[(size_t) ci].n)) ++ci;
+ return ci;
+}
+
+void ExpertStream::lru_unlink(int s) {
+ Slot& x = slots_[(size_t) s];
+ Cls& k = cls_[(size_t) cls_of(s)];
+ if (x.prev >= 0) slots_[(size_t) x.prev].next = x.next; else k.head = x.next;
+ if (x.next >= 0) slots_[(size_t) x.next].prev = x.prev; else k.tail = x.prev;
+ x.prev = x.next = -1;
+}
+
+void ExpertStream::lru_back(int s) {
+ lru_unlink(s);
+ Cls& k = cls_[(size_t) cls_of(s)];
+ Slot& x = slots_[(size_t) s];
+ x.prev = k.tail;
+ x.next = -1;
+ if (k.tail >= 0) slots_[(size_t) k.tail].next = s;
+ k.tail = s;
+ if (k.head < 0) k.head = s;
+}
+
+void ExpertStream::lru_front(int s) {
+ lru_unlink(s);
+ Cls& k = cls_[(size_t) cls_of(s)];
+ Slot& x = slots_[(size_t) s];
+ x.next = k.head;
+ x.prev = -1;
+ if (k.head >= 0) slots_[(size_t) k.head].prev = s;
+ k.head = s;
+ if (k.tail < 0) k.tail = s;
+}
+
+int ExpertStream::victim(int ci) {
+ Cls& k = cls_[(size_t) ci];
+ for (int s = k.tail; s >= 0; s = slots_[(size_t) s].prev)
+ if (slots_[(size_t) s].state.load() == 0) {
+ Slot& x = slots_[(size_t) s];
+ if (x.layer >= 0) {
+ const int key = x.layer * NE + x.e;
+ where_[(size_t) key] = -1;
+ smap_.as<uint32_t>()[key] = 0xFFFFFFFFu;
+ }
+ x.layer = x.e = -1;
+ return s;
+ }
+ return -1;
+}
+
+// One piece of an expert: slice part / split_ (gate, up, down), piece part % split_ of it. The pieces of one expert
+// go to several I/O threads, so a single miss is read with several requests in flight (its latency, not only the
+// 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];
+ 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;
+ const uint64_t dst = k == 0 ? 0 : (k == 1 ? x.gs : x.gs + x.us);
+ const uint64_t a = len * (uint64_t) p / (uint64_t) split_ / 4096 * 4096;
+ const uint64_t b = p + 1 == split_ ? len : len * (uint64_t) (p + 1) / (uint64_t) split_ / 4096 * 4096;
+ if (b > a && !read(host_[(size_t) s] + dst + a, b - a, src + a)) {
+ std::fprintf(stderr, "strata metal stream: reading expert %d of layer %d failed\n", e, l);
+ std::exit(6);
+ }
+ bytes_read_ += b - a;
+}
+
+void ExpertStream::io_main() {
+ for (;;) {
+ Job j;
+ {
+ std::unique_lock<std::mutex> g(mu_);
+ cv_.wait(g, [&] { return stop_ || !urgent_q_.empty() || !pre_q_.empty(); });
+ if (stop_) return;
+ if (!urgent_q_.empty()) { j = urgent_q_.front(); urgent_q_.pop_front(); }
+ else { j = pre_q_.front(); pre_q_.pop_front(); }
+ slots_[(size_t) j.slot].state = 2;
+ }
+ read_part(j.slot, j.layer, j.e, j.part);
+ bool done = false;
+ {
+ std::lock_guard<std::mutex> g(mu_);
+ Slot& x = slots_[(size_t) j.slot];
+ if (--x.left == 0) {
+ smap_.as<uint32_t>()[j.layer * NE + j.e] = code_[(size_t) j.slot];
+ x.state = 0;
+ --outstanding_;
+ ++reads_;
+ done = true;
+ }
+ }
+ if (done) done_cv_.notify_all();
+ }
+}
+
+void ExpertStream::submit(int s, int l, int e, bool urgent) {
+ Slot& x = slots_[(size_t) s];
+ x.layer = (int16_t) l;
+ x.e = (int16_t) e;
+ x.state = 1;
+ x.pre = !urgent;
+ x.left = 3 * split_;
+ ++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});
+}
+
+// a queued read-ahead nobody wants: its pieces dropped, the slot freed (only before any piece has started)
+void ExpertStream::cancel_slot(int s) {
+ Slot& x = slots_[(size_t) s];
+ for (auto it = pre_q_.begin(); it != pre_q_.end();) it = it->slot == s ? pre_q_.erase(it) : it + 1;
+ where_[(size_t) (x.layer * NE + x.e)] = -1;
+ x.layer = x.e = -1;
+ x.state = 0;
+ x.pre = false;
+ x.left = 0;
+ --outstanding_;
+ ++pre_cancel_;
+ lru_back(s);
+}
+
+// a read-ahead that is wanted now: its queued pieces go first
+void ExpertStream::promote_slot(int s) {
+ std::vector<Job> mine;
+ for (auto it = pre_q_.begin(); it != pre_q_.end();)
+ if (it->slot == s) { mine.push_back(*it); it = pre_q_.erase(it); }
+ else ++it;
+ for (auto it = mine.rbegin(); it != mine.rend(); ++it) urgent_q_.push_front(*it);
+}
+
+bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, std::string& err) {
+ const double t0 = now_ms();
+ // the ranking: the profile's pairs, then every pair it misses, layer-interleaved
+ std::vector<std::pair<int, int>> rank;
+ std::vector<uint8_t> seen((size_t) NL * NE, 0);
+ if (FILE* f = std::fopen(profile.c_str(), "rb")) {
+ char magic[4];
+ uint32_t h[5];
+ if (std::fread(magic, 1, 4, f) == 4 && std::memcmp(magic, "STRP", 4) == 0 && std::fread(h, 4, 5, f) == 5 &&
+ h[1] == (uint32_t) NL && h[2] == (uint32_t) NE) {
+ for (uint32_t i = 0; i < h[4]; ++i) {
+ uint16_t p[2];
+ if (std::fread(p, 2, 2, f) != 2) break;
+ if (p[0] < NL && p[1] < NE && !seen[(size_t) p[0] * NE + p[1]]) {
+ seen[(size_t) p[0] * NE + p[1]] = 1;
+ rank.push_back({p[0], p[1]});
+ }
+ }
+ }
+ std::fclose(f);
+ } else {
+ std::fprintf(stderr, "strata metal stream: no expert profile at %s: the arena starts layer-interleaved\n", profile.c_str());
+ }
+ const size_t from_profile = rank.size();
+ for (int e = 0; e < NE; ++e)
+ for (int l = 0; l < NL; ++l)
+ if (!seen[(size_t) l * NE + e]) rank.push_back({l, e});
+ // the pool of each size class: the top-ranked pairs that fit in the budget
+ uint64_t used = 0;
+ std::vector<std::pair<int, int>> fill;
+ for (const auto& p : rank) {
+ const Cls& k = cls_[(size_t) lay_[(size_t) p.first].cls];
+ if (used + k.pages * PAGE > budget) break;
+ used += k.pages * PAGE;
+ ++cls_[(size_t) lay_[(size_t) p.first].cls].n;
+ fill.push_back(p);
+ }
+ int base = 0;
+ for (auto& k : cls_) {
+ if (k.n < 64 && !fill.empty()) { // a class needs room for at least a few windows' experts
+ const int add = 64 - k.n;
+ k.n = 64;
+ used += (uint64_t) add * k.pages * PAGE;
+ }
+ k.base = base;
+ base += k.n;
+ }
+ // the slots placed in chunks of at most maxBufferLength (and 8 GB), up to 4 (the kernels' buffers 0, 7, 8, 9)
+ const uint64_t cmax = std::min<uint64_t>(cx.max_buffer_length(), 8ull << 30) / PAGE * PAGE;
+ code_.assign((size_t) base, 0);
+ host_.assign((size_t) base, nullptr);
+ std::vector<uint64_t> csize;
+ std::vector<std::pair<int, uint64_t>> at((size_t) base);
+ uint64_t cur = 0;
+ for (const auto& k : cls_)
+ for (int s = k.base; s < k.base + k.n; ++s) {
+ if (csize.empty() || cur + k.pages * PAGE > cmax) {
+ if (!csize.empty()) csize.back() = cur;
+ csize.push_back(0);
+ cur = 0;
+ }
+ at[(size_t) s] = {(int) csize.size() - 1, cur / PAGE};
+ cur += k.pages * PAGE;
+ }
+ if (!csize.empty()) csize.back() = cur;
+ if (csize.size() > 4) { err = "metal stream: the arena needs more than 4 buffers (lower STRATA_METAL_ARENA_GB)"; return false; }
+ for (uint64_t b : csize) { chunks_.push_back(cx.alloc(b)); arena_bytes_ += b; }
+ for (int s = 0; s < base; ++s) {
+ code_[(size_t) s] = ((uint32_t) at[(size_t) s].first << 28) | (uint32_t) at[(size_t) s].second;
+ host_[(size_t) s] = chunks_[(size_t) at[(size_t) s].first].as<uint8_t>() + at[(size_t) s].second * PAGE;
+ }
+ smap_ = cx.alloc((size_t) NL * NE * 4);
+ std::memset(smap_.ptr, 0xFF, (size_t) NL * NE * 4);
+ slots_ = std::vector<Slot>((size_t) base);
+ where_.assign((size_t) NL * NE, -1);
+ for (auto& k : cls_) {
+ for (int s = k.base; s < k.base + k.n; ++s) {
+ slots_[(size_t) s].prev = s == k.base ? -1 : s - 1;
+ slots_[(size_t) s].next = s + 1 == k.base + k.n ? -1 : s + 1;
+ }
+ k.head = k.n ? k.base : -1;
+ k.tail = k.n ? k.base + k.n - 1 : -1;
+ }
+ for (int i = 0; i < nio_; ++i) io_.emplace_back([this] { io_main(); });
+ // the fill: the ranked pairs, in file order, on the I/O threads; the best-ranked ends at the LRU front
+ std::vector<std::pair<int, int>> order = fill;
+ std::sort(order.begin(), order.end(), [&](const auto& a, const auto& b) {
+ return lay_[(size_t) a.first].g + (uint64_t) a.second * lay_[(size_t) a.first].gs <
+ lay_[(size_t) b.first].g + (uint64_t) b.second * lay_[(size_t) b.first].gs;
+ });
+ std::vector<int> next_free(cls_.size());
+ for (size_t c = 0; c < cls_.size(); ++c) next_free[c] = cls_[c].base;
+ {
+ std::lock_guard<std::mutex> g(mu_);
+ for (const auto& p : order) {
+ const int c = lay_[(size_t) p.first].cls;
+ submit(next_free[(size_t) c]++, p.first, p.second, true);
+ }
+ }
+ cv_.notify_all();
+ {
+ std::unique_lock<std::mutex> g(mu_);
+ done_cv_.wait(g, [&] { return outstanding_ == 0; });
+ // the LRU order = the rank order (best at the front)
+ for (auto it = fill.rbegin(); it != fill.rend(); ++it) lru_front(where_[(size_t) (it->first * NE + it->second)]);
+ }
+ fill_s_ = (now_ms() - t0) / 1e3;
+ fill_bytes_ = bytes_read_.load();
+ uint64_t pairs = 0;
+ for (const auto& k : cls_) pairs += (uint64_t) k.n;
+ std::fprintf(stderr, "strata metal stream: expert arena %.2f GB, %llu slots in %zu size classes, %zu experts read from the "
+ "profile's top (%zu ranked) in %.1f s (%.2f GB/s); %d I/O threads, read-ahead top %d; %zu buffers\n",
+ arena_bytes_ / 1e9, (unsigned long long) pairs, cls_.size(), fill.size(), from_profile, fill_s_,
+ fill_bytes_ / 1e9 / std::max(1e-9, fill_s_), nio_, prefetch_ ? pre_k_ : 0, chunks_.size());
+ (void) err;
+ return true;
+}
+
+void ExpertStream::at_layer(int l, int T, int topk, const int32_t* ids, const float* pred) {
+ const double t0 = now_ms();
+ if (l == 0) ++windows_;
+ int want[8 * 16];
+ int nw = 0;
+ for (int i = 0; i < T * topk; ++i) {
+ const int e = ids[i];
+ if (e < 0 || e >= NE) continue;
+ bool dup = false;
+ for (int j = 0; j < nw; ++j) dup |= want[j] == e;
+ if (!dup) want[nw++] = e;
+ }
+ if (fake_) {
+ for (int j = 0; j < nw; ++j)
+ if (where_[(size_t) (l * NE + want[j])] < 0) smap_.as<uint32_t>()[l * NE + want[j]] = code_[0];
+ host_ms_ += now_ms() - t0;
+ return;
+ }
+ std::vector<int> wait;
+ {
+ std::lock_guard<std::mutex> g(mu_);
+ // read-aheads of this layer (or older) that were not started and are not wanted: dropped (the slot goes free)
+ {
+ std::vector<int> drop;
+ for (const Job& j : pre_q_) {
+ if (j.layer > l || slots_[(size_t) j.slot].state.load() != 1) continue;
+ bool w = false;
+ for (int q = 0; q < nw; ++q) w |= j.layer == l && want[q] == j.e;
+ if (!w && std::find(drop.begin(), drop.end(), j.slot) == drop.end()) drop.push_back(j.slot);
+ }
+ for (int s : drop) cancel_slot(s);
+ }
+ for (int j = 0; j < nw; ++j) {
+ const int e = want[j], key = l * NE + e;
+ ++lookups_;
+ int s = where_[(size_t) key];
+ if (s >= 0) {
+ Slot& x = slots_[(size_t) s];
+ const int st = x.state.load();
+ if (st == 0) { if (x.pre) ++pre_hits_; else ++hits_; }
+ else {
+ ++pre_hits_;
+ ++late_;
+ promote_slot(s); // a queued read-ahead becomes urgent
+ wait.push_back(s);
+ }
+ x.pre = false;
+ lru_front(s);
+ continue;
+ }
+ ++misses_;
+ s = victim(lay_[(size_t) l].cls);
+ if (s < 0) { std::fprintf(stderr, "strata metal stream: no free slot (layer %d)\n", l); std::exit(6); }
+ submit(s, l, e, true);
+ lru_front(s);
+ wait.push_back(s);
+ }
+ }
+ if (!wait.empty()) {
+ cv_.notify_all();
+ const double tw = now_ms();
+ std::unique_lock<std::mutex> g(mu_);
+ done_cv_.wait(g, [&] {
+ for (int s : wait) if (slots_[(size_t) s].state.load() != 0) return false;
+ return true;
+ });
+ wait_ms_ += now_ms() - tw;
+ }
+ // read-ahead for layer l + 1: each token's top pre_k_ of the predicted router logits
+ if (prefetch_ && pred && l + 1 < NL) {
+ int pw[8 * 32];
+ int np = 0;
+ const int K = std::min(pre_k_, 32);
+ for (int t = 0; t < T; ++t) {
+ const float* lg = pred + (size_t) t * NE;
+ int top[32];
+ int nt = 0;
+ for (int e = 0; e < NE; ++e) {
+ if (nt < K) { top[nt++] = e; }
+ else {
+ int m = 0;
+ for (int j = 1; j < K; ++j) if (lg[top[j]] < lg[top[m]]) m = j;
+ if (lg[e] > lg[top[m]]) top[m] = e;
+ else continue;
+ }
+ }
+ for (int j = 0; j < nt; ++j) {
+ bool dup = false;
+ for (int q = 0; q < np; ++q) dup |= pw[q] == top[j];
+ if (!dup) pw[np++] = top[j];
+ }
+ }
+ bool any = false;
+ {
+ std::lock_guard<std::mutex> g(mu_);
+ const int ln = l + 1;
+ for (int j = 0; j < np; ++j) {
+ const int key = ln * NE + pw[j];
+ const int s0 = where_[(size_t) key];
+ if (s0 >= 0) { lru_front(s0); continue; }
+ const int s = victim(lay_[(size_t) ln].cls);
+ if (s < 0) break;
+ submit(s, ln, pw[j], false);
+ lru_front(s);
+ ++pre_issued_;
+ any = true;
+ }
+ }
+ if (any) cv_.notify_all();
+ }
+ host_ms_ += now_ms() - t0;
+}
+
+void ExpertStream::reset_stats() {
+ lookups_ = hits_ = pre_hits_ = late_ = misses_ = pre_issued_ = pre_cancel_ = windows_ = 0;
+ bytes_read_ = 0;
+ reads_ = 0;
+ wait_ms_ = host_ms_ = 0;
+}
+
+void ExpertStream::report(FILE* f) const {
+ if (!ready()) return;
+ const double w = std::max<uint64_t>(1, windows_);
+ std::fprintf(f,
+ "expert stream %llu windows: %llu distinct lookups (%.1f per window), hits %.4f, read-ahead hits "
+ "%.4f (%llu of them late), misses %.4f (%.1f per window); read-aheads %llu (%.1f per window, %llu dropped); %.1f MB "
+ "read per window (%llu reads); host %.2f ms per window, of it waiting %.2f ms\n",
+ (unsigned long long) windows_, (unsigned long long) lookups_, lookups_ / w,
+ hits_ / std::max(1.0, (double) lookups_), pre_hits_ / std::max(1.0, (double) lookups_),
+ (unsigned long long) late_, misses_ / std::max(1.0, (double) lookups_), misses_ / w,
+ (unsigned long long) pre_issued_, pre_issued_ / w, (unsigned long long) pre_cancel_,
+ (bytes_read_.load() - 0) / 1e6 / w, (unsigned long long) reads_.load(), host_ms_ / w, wait_ms_ / w);
+}
+
+} // namespace strata::metal_engine
diff --git a/metal/src/engine/stream.h b/metal/src/engine/stream.h
new file mode 100644
index 000000000..934f5d7e4
--- /dev/null
+++ b/metal/src/engine/stream.h
@@ -0,0 +1,103 @@
+// metal/src/engine/stream.h - the SSD-streaming expert arena for Macs whose memory cannot hold the model (MAC-PLAN
+// Phase 3, the small-Mac path; measured on the M4 Mac mini 32 GB, phaseA-tests/notes-mac-ssd.md).
+//
+// * The dense weights (everything but the routed experts) are read once into one resident shared buffer; the
+// GGUF is never wrapped as a whole (a 37.6 GB NoCopy buffer cannot be made resident in 32 GB).
+// * The routed experts live in a resident arena of slots (one shared MTLBuffer), filled straight from the GGUF
+// with F_NOCACHE preads: one SSD read per expert slice, no staging copy, no page cache. smap (48 x 512 uint32:
+// the slot's 16 KiB page in the arena, or ~0) is what the expert kernels read (moe.metal, function constant 20).
+// * The decode window is one command buffer in 48 segments; after each layer's router the GPU signals a shared
+// event and waits for the host (mtl_rt run_graph_seg). The host's turn (at_layer): the window's routed experts
+// of that layer are looked up, the missing ones read into LRU victims (several reads in flight), smap updated;
+// then the experts the NEXT layer's router predicts from this layer's FFN input are read ahead on the I/O
+// threads while the GPU computes.
+// * The arena starts with the expert profile's top-ranked pairs (data/expert-profile.bin).
+// The numbers are exact: a slot holds the expert's GGUF bytes unchanged, so the answers are those of the resident
+// engine (the kernels read the same bytes at another address).
+#pragma once
+
+#include "gguf_lite.h"
+#include "mtl_rt.h"
+
+#include <atomic>
+#include <condition_variable>
+#include <cstdint>
+#include <deque>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <vector>
+
+namespace strata::metal_engine {
+
+class ExpertStream {
+public:
+ ~ExpertStream();
+ // On when STRATA_METAL_STREAM=1, or (unset / auto) when the GGUF's experts do not fit in the GPU working set
+ // with room to spare. =0: never (the whole GGUF wrapped, as on the M5 Max).
+ static bool wanted(const gguf::File& f, const mtl::Context& cx);
+ bool open(const gguf::File& f, std::string& err);
+ // pread `len` bytes at file offset `off` (F_NOCACHE)
+ bool read(void* dst, uint64_t len, uint64_t off) const;
+ // The dense tensors into one buffer; every tensor's offset in `f` is rewritten to its offset in `out`.
+ // Tensors named in `skip` are left out (their offset is set to 0: they must not be read any more).
+ bool load_dense(gguf::File& f, mtl::Context& cx, const std::vector<std::string>& skip, mtl::Buffer& out,
+ std::string& err);
+ // The arena: `budget` bytes of slots, filled from the profile's ranking (or layer-interleaved if none).
+ bool make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, std::string& err);
+ bool ready() const { return !chunks_.empty(); }
+ // the arena's buffers (at most 4, each within the device's maxBufferLength): chunk(i) for i >= count is chunk 0
+ const mtl::Buffer& chunk(int i) const { return chunks_[(size_t) i < chunks_.size() ? (size_t) i : 0]; }
+ const mtl::Buffer& smap() const { return smap_; }
+ uint64_t up_in_slot(int l) const { return lay_[(size_t) l].gs; }
+ uint64_t down_in_slot(int l) const { return lay_[(size_t) l].gs + lay_[(size_t) l].us; }
+ // The host's turn at layer l: ids = the window's T x topk routed ids; pred = T x 512 router logits of layer l + 1
+ // computed from this layer's FFN input (nullptr: no read-ahead).
+ void at_layer(int l, int T, int topk, const int32_t* ids, const float* pred);
+ void report(FILE* f) const;
+ void reset_stats();
+
+private:
+ struct Lay { uint64_t g, gs, u, us, d, ds; int cls; };
+ struct Slot { int16_t layer = -1; int16_t e = -1; int prev = -1, next = -1; bool pre = false; int left = 0; std::atomic<int> state{0}; }; // 0 idle, 1 queued, 2 reading
+ struct Cls { uint64_t pages = 0; int n = 0; int base = 0; int head = -1, tail = -1; }; // slot range [base, base+n)
+ struct Job { int slot; int layer, e, part; }; // part: slice * split_ + piece
+ void lru_unlink(int s);
+ void lru_front(int s);
+ void lru_back(int s);
+ int cls_of(int s) const;
+ int victim(int cls);
+ void read_part(int slot, int l, int e, int part);
+ void cancel_slot(int s);
+ void promote_slot(int s);
+ void io_main();
+ void submit(int slot, int l, int e, bool urgent);
+ void wait_slot(int s);
+
+ int fd_ = -1;
+ std::vector<Lay> lay_;
+ std::vector<Cls> cls_;
+ std::vector<Slot> slots_;
+ std::vector<int32_t> where_; // (l * 512 + e) -> slot, -1
+ std::vector<mtl::Buffer> chunks_;
+ std::vector<uint32_t> code_; // slot -> its smap value (chunk << 28 | page)
+ std::vector<uint8_t*> host_; // slot -> its CPU address
+ mtl::Buffer smap_;
+ uint64_t arena_bytes_ = 0;
+ // the I/O threads
+ std::vector<std::thread> io_;
+ std::mutex mu_;
+ std::condition_variable cv_, done_cv_;
+ std::deque<Job> urgent_q_, pre_q_;
+ bool stop_ = false;
+ int outstanding_ = 0;
+ int nio_ = 6, pre_k_ = 10, split_ = 2;
+ bool prefetch_ = true, fake_ = false;
+ // stats
+ uint64_t lookups_ = 0, hits_ = 0, pre_hits_ = 0, late_ = 0, misses_ = 0, pre_issued_ = 0, pre_cancel_ = 0, windows_ = 0;
+ std::atomic<uint64_t> bytes_read_{0}, reads_{0};
+ double wait_ms_ = 0, host_ms_ = 0, fill_s_ = 0;
+ uint64_t fill_bytes_ = 0;
+};
+
+} // namespace strata::metal_engine
diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cpp
index bda727760..786f27d12 100644
--- a/metal/src/engine/window.cpp
+++ b/metal/src/engine/window.cpp
@@ -14,6 +14,7 @@
#include "gguf_lite.h"
#include "mtl_rt.h"
#include "ref_quant.h"
+#include "stream.h"
#include "strata/core/layer.hpp"
#include "strata/core/session.hpp"
@@ -30,6 +31,8 @@
#include <memory>
#include <string>
#include <sys/mman.h>
+#include <sys/sysctl.h>
+#include <mach/mach.h>
#include <thread>
#include <vector>
@@ -97,14 +100,33 @@ private:
}
const mtl::Pipeline* P(int lib, const std::string& fn, const mtl::Constants& c, const std::string& key) {
auto it = pcache_.find(key);
- if (it == pcache_.end()) it = pcache_.emplace(key, cx_->pipeline(lib, fn, c)).first;
+ if (it == pcache_.end()) {
+ it = pcache_.emplace(key, cx_->pipeline(lib, fn, c)).first;
+ pkey_of_[&it->second] = key;
+ }
return &it->second;
}
void push(std::vector<mtl::Dispatch>& ds, mtl::Dispatch d) {
d.barrier = !nb_;
nb_ = false;
+ // timing only (WRONG answers): STRATA_METAL_SKIP=a,b,... runs the dispatches whose pipeline name contains one
+ // of the words as empty grids (the marginal cost of a kernel class by leaving it out)
+ static const std::vector<std::string> skip = [] {
+ std::vector<std::string> v;
+ if (const char* e = std::getenv("STRATA_METAL_SKIP")) {
+ std::string s = e, w;
+ for (char c : s + ",") { if (c == ',') { if (!w.empty()) v.push_back(w); w.clear(); } else w += c; }
+ }
+ return v;
+ }();
+ if (!skip.empty()) {
+ const std::string& k = pkey_of_[d.p];
+ for (const auto& w : skip)
+ if (k.find(w) != std::string::npos) { d.indirect = nullptr; d.grid[0] = 0; break; }
+ }
ds.push_back(std::move(d));
}
+ std::map<const mtl::Pipeline*, std::string> pkey_of_;
void gemv(std::vector<mtl::Dispatch>& ds, const gguf::Tensor& t, const Act& x, const mtl::Buffer& y, size_t y_stride,
int ntok, size_t y_off = 0, const mtl::Buffer* wb = nullptr);
void xprep(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& x, const Act& out, int n);
@@ -156,10 +178,34 @@ private:
// the encoded window per (T, head, hp_): built once, then only the positions are patched (the host's encode cost)
struct Cached {
std::vector<mtl::Dispatch> ds;
+ std::vector<int> cuts; // SSD streaming: the segment ends (one per layer, before its experts)
std::vector<std::pair<int, int>> qsa; // (dispatch, kind): 0 QsaArgs n_tok = T, 1 the merge (MAXT), 2 the scores
};
std::map<int, Cached> wcache_;
std::vector<std::pair<int, int>>* rec_ = nullptr;
+ // ---- SSD streaming (stream.h): the dense weights in W_, the routed experts in the arena
+ std::unique_ptr<ExpertStream> st_;
+ bool stream_ = false, st_pred_ = false;
+ std::vector<int>* cuts_ = nullptr;
+ mtl::Buffer predL_; // 48 x MAXT x 512: layer l + 1's router logits from layer l's FFN input
+ int seg_T_ = 0;
+ bool stream_arena(std::string& err);
+ double run_ds(Cached& c);
+public:
+ void stream_report(FILE* f) const {
+ if (!st_) return;
+ st_->report(f);
+ for (int t = 1; t <= MAXT; ++t)
+ if (win_n_[t])
+ std::fprintf(f, "stream windows T=%d %d (%s): %.2f ms each (GPU incl. the host's turns %.2f ms)\n", t, win_n_[t],
+ t == 8 ? "prompt rows" : "decode", win_ms_[t] / win_n_[t], win_gpu_[t] / win_n_[t]);
+ }
+ int win_n_[MAXT + 1] = {};
+ double win_ms_[MAXT + 1] = {}, win_gpu_[MAXT + 1] = {};
+ void at_cut(int s) {
+ st_->at_layer(s, seg_T_, TOPK, ids_.as<int32_t>(), st_pred_ ? predL_.as<float>() + (size_t) s * MAXT * 512 : nullptr);
+ }
+private:
std::vector<float> ple_hist_; // NG_HIST x hc_dim normalized rows, row-fastest
bool ple_on_ = false;
int last_T_ = 0;
@@ -212,9 +258,16 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
const double t0 = now_ms();
if (!f_.open(shard1, err)) return false;
cx_ = std::make_unique<mtl::Context>();
- madvise(f_.map, f_.map_bytes, MADV_WILLNEED);
- W_ = cx_->wrap(f_.map, f_.map_bytes);
- if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; }
+ stream_ = ExpertStream::wanted(f_, *cx_);
+ if (stream_) {
+ // the model does not fit: the dense weights are read into memory below, the experts stream from the SSD
+ st_ = std::make_unique<ExpertStream>();
+ if (!st_->open(f_, err)) return false;
+ } else {
+ madvise(f_.map, f_.map_bytes, MADV_WILLNEED);
+ W_ = cx_->wrap(f_.map, f_.map_bytes);
+ if (W_.handle == nullptr) { err = "metal window: cannot wrap " + shard1 + " as a Metal buffer"; return false; }
+ }
n_vocab_ = (int64_t) T("output.weight").shape[1];
lib_ = cx_->compile({"quant.metal", "units.metal", "moe.metal", "gemv.metal", "gr.metal", "gr2.metal", "glue.metal"});
lgdn_ = cx_->compile({"gdn.metal"}, "#define NO_GGML_COMMON 1\n");
@@ -293,12 +346,19 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
for (unsigned k = 0; k < nth; ++k)
th.emplace_back([&, k] {
std::vector<float> tmp;
+ std::vector<uint8_t> raw;
for (size_t i = k; i < names.size(); i += nth) {
const gguf::Tensor& x = *f_.find(names[i]);
uint64_t ne = 1;
for (uint64_t d : x.shape) ne *= d;
tmp.resize(ne);
- ref::dequant(ref::BF16, (const uint8_t*) f_.map + x.offset, tmp.data(), ne);
+ const uint8_t* src = (const uint8_t*) f_.map + x.offset;
+ if (stream_) { // F_NOCACHE reads: the page cache is kept for the arena
+ raw.resize(x.bytes);
+ if (!st_->read(raw.data(), x.bytes, x.offset)) { std::fprintf(stderr, "strata metal: read failed\n"); std::exit(6); }
+ src = raw.data();
+ }
+ ref::dequant(ref::BF16, src, tmp.data(), ne);
ref::quantize_q8_0(tmp.data(), ne, Q8_.as<uint8_t>() + q8off_[names[i]]);
}
});
@@ -306,12 +366,21 @@ bool Window::init(const strata::core::ModelGeometry& g, strata::core::SessionSta
std::fprintf(stderr, "strata metal: HC read in Q8_0 (STRATA_HC_Q8=0: BF16): %zu matrices, %.0f MB, made in %.0f ms\n",
names.size(), tot / 1e6, now_ms() - tq);
}
+ if (stream_) {
+ std::vector<std::string> skip; // the BF16 originals of the Q8_0 HC copies are not read again
+ if (hc_q8_)
+ for (const auto& kv : q8off_) skip.push_back(kv.first);
+ if (!st_->load_dense(f_, *cx_, skip, W_, err)) return false;
+ const char* e = std::getenv("STRATA_METAL_PREFETCH");
+ st_pred_ = !(e && std::atoi(e) <= 0);
+ if (st_pred_) predL_ = A(4 * (size_t) 48 * MAXT * 512);
+ }
ple_on_ = ss.ple.ready() && f_.find("blk.1.ple_key.weight") != nullptr;
ple_hist_.assign((size_t) strata::kernels::NG_HIST * strata::kernels::NG_HC_DIM, 0.0f);
last_norm_.assign((size_t) MAXT * strata::kernels::NG_HC_DIM, 0.0f);
- std::fprintf(stderr, "strata metal: decode window on %s: %s wrapped (%.1f GB), %d cells, PLE %s, ready in %.0f ms\n",
- cx_->device_name().c_str(), shard1.c_str(), f_.file_bytes / 1e9, MAXC, ple_on_ ? "on" : "OFF",
- now_ms() - t0);
+ std::fprintf(stderr, "strata metal: decode window on %s: %s %s (%.1f GB), %d cells, PLE %s, ready in %.0f ms\n",
+ cx_->device_name().c_str(), shard1.c_str(), stream_ ? "streamed from the SSD (experts)" : "wrapped",
+ f_.file_bytes / 1e9, MAXC, ple_on_ ? "on" : "OFF", now_ms() - t0);
return true;
}
@@ -323,6 +392,16 @@ void Window::gemv(std::vector<mtl::Dispatch>& ds, const gguf::Tensor& t, const A
if (n_in >= 6144) { L = 32; Rr = 1; S = 8; K = 2; }
else if (n_in == 640) { L = 8; Rr = 1; S = 4; K = 1; }
else if (n_out <= 640 || ty == ref::Q2_0 || ty == ref::BF16) { L = 32; Rr = 1; S = 4; K = 1; }
+ {
+ // windows of several tokens: NR rows a lane share each x load (the window's cost is its x traffic). The sums
+ // run in the same order for any NR, so the answers do not change. STRATA_METAL_GEMV_NR (1, 2): the tile.
+ static const int nr_env = [] { const char* e = std::getenv("STRATA_METAL_GEMV_NR"); return e ? std::atoi(e) : 1; }();
+ if (ntok > 1 && nr_env == 2 && n_out >= 2048) {
+ if (S == 8 && K == 2) { S = 4; K = 2; }
+ if (S == 8 && K == 1) S = 4;
+ if (K == 1 || (L == 32 && K == 2)) Rr = 2;
+ }
+ }
const std::string fn = "gemv_" + std::to_string(ty) + "_" + std::to_string(L) + "_" + std::to_string(Rr) + "_" +
std::to_string(S) + "_" + std::to_string(K);
const mtl::Pipeline* p = P(lib_, fn, mtl::Constants().i(0, ntok), fn + "#" + std::to_string(ntok));
@@ -487,6 +566,11 @@ void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0
// ---- the MoE
gr_read(ds, b + "hc_ffn", true, XF_, false, ntok);
gemv(ds, T(b + "ffn_gate_inp.weight"), XF_, logits_, 512, ntok);
+ if (stream_ && st_pred_ && l + 1 < 48) { // the next layer's routing guessed from this layer's FFN input
+ nb_ = true;
+ gemv(ds, T("blk." + std::to_string(l + 1) + ".ffn_gate_inp.weight"), XF_, predL_, 512, ntok,
+ (size_t) l * MAXT * 512 * 4);
+ }
nb_ = true;
gemv(ds, T(b + "ffn_gate_shexp.weight"), XF_, gsh_, NFF, ntok);
nb_ = true;
@@ -500,6 +584,11 @@ void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0
a.gate_off = tg_.offset;
a.up_off = tu.offset;
a.down_off = td.offset;
+ if (stream_) { // offsets inside the expert's arena slot
+ a.gate_off = 0;
+ a.up_off = st_->up_in_slot(l);
+ a.down_off = st_->down_in_slot(l);
+ }
a.gu_row = (uint32_t) ref::row_bytes(tg_.type, N);
a.d_row = (uint32_t) ref::row_bytes(td.type, NFF);
a.gu_stride = (uint64_t) a.gu_row * NFF;
@@ -534,18 +623,28 @@ void Window::layer(std::vector<mtl::Dispatch>& ds, int l, int ntok, int64_t pos0
const std::string dnn = "moe_down_" + std::to_string(dq2 ? 142 : td.type) + "_" + std::to_string(dl) + "_" +
std::to_string(dr) + "_" + std::to_string(ds_);
mtl::Dispatch g;
- g.p = P(lib_, gun, {}, gun);
- g.args = {mtl::Arg::B(W_), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_),
+ const mtl::Buffer& EW = stream_ ? st_->chunk(0) : W_;
+ const mtl::Constants ac = stream_ ? mtl::Constants().b(20, true) : mtl::Constants();
+ const std::string ak = stream_ ? "#arena" : "";
+ g.p = P(lib_, gun, ac, gun + ak);
+ g.args = {mtl::Arg::B(EW), mtl::Arg::B(XF_.b, XF_.plane_bytes() * xkind(tg_.type)), mtl::Arg::B(h_), mtl::Arg::B(plan_),
mtl::Arg::V(a), mtl::Arg::B(XF_.b, XF_.plane_bytes() * 4)};
+ if (stream_)
+ for (int c = -1; c < 3; ++c)
+ g.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1)));
g.tg[0] = 32 * gs;
g.indirect = &plan_;
g.ind_off = P_IGU * 4;
+ if (cuts_) cuts_->push_back((int) ds.size()); // the host's turn: this layer's experts put in place
push(ds, g);
nb_ = true;
gemv(ds, T(b + "ffn_down_shexp.weight"), XH_, ysh_, N, ntok);
mtl::Dispatch dd;
- dd.p = P(lib_, dnn, {}, dnn);
- dd.args = {mtl::Arg::B(W_), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)};
+ dd.p = P(lib_, dnn, ac, dnn + ak);
+ dd.args = {mtl::Arg::B(EW), mtl::Arg::B(h_), mtl::Arg::B(ye_), mtl::Arg::B(plan_), mtl::Arg::V(a), mtl::Arg::B(h_)};
+ if (stream_)
+ for (int c = -1; c < 3; ++c)
+ dd.args.push_back(c < 0 ? mtl::Arg::B(st_->smap(), (size_t) l * 512 * 4) : mtl::Arg::B(st_->chunk(c + 1)));
dd.tg[0] = 32 * ds_;
dd.indirect = &plan_;
dd.ind_off = P_IDN * 4;
@@ -582,10 +681,10 @@ void gnorm(const float* x, const float* w, float* y, int n_embd, int hc, float e
void Window::ple_cpu(int Tn) {
using namespace strata::kernels;
const int hc_dim = NG_HC_DIM;
- const float* nkey = (const float*) ((const uint8_t*) f_.map + T("blk.1.ple_norm_key.weight").offset);
- const float* nqry = (const float*) ((const uint8_t*) f_.map + T("blk.1.ple_norm_query.weight").offset);
- const float* nconv = (const float*) ((const uint8_t*) f_.map + T("blk.1.ple_norm_conv.weight").offset);
- const uint16_t* kw = (const uint16_t*) ((const uint8_t*) f_.map + T("blk.1.ple_conv1d.weight").offset);
+ const float* nkey = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_key.weight").offset);
+ const float* nqry = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_query.weight").offset);
+ const float* nconv = (const float*) ((const uint8_t*) W_.ptr + T("blk.1.ple_norm_conv.weight").offset);
+ const uint16_t* kw = (const uint16_t*) ((const uint8_t*) W_.ptr + T("blk.1.ple_conv1d.weight").offset);
std::vector<float> key(hc_dim), query(hc_dim), gated(hc_dim), norm(hc_dim), hist = ple_hist_;
for (int t = 0; t < Tn; ++t) {
float* hidden = R_.as<float>() + (size_t) t * HC * N;
@@ -633,7 +732,7 @@ bool Window::run(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t
const size_t rb = ref::row_bytes(te.type, N);
for (int t = 0; t < Tn; ++t) {
float* r = R_.as<float>() + (size_t) t * HC * N;
- ref::dequant(te.type, (const uint8_t*) f_.map + te.offset + (size_t) tokens[t] * rb, r, N);
+ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[t] * rb, r, N);
for (int c = 1; c < HC; ++c) std::memcpy(r + (size_t) c * N, r, (size_t) N * 4);
}
// ---- the PLE rows (the table read is the shared host code's), projected on the GPU
@@ -659,12 +758,15 @@ bool Window::run(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t
std::memcpy(d.args.back().bytes.data(), &a, sizeof a);
if (kind == 2) d.grid[0] = (uint32_t) (((pos0 + Tn) / 4 + 1 + 7) / 8);
}
- last_gpu_ms_ = 1000.0 * cx_->run_graph(c.ds);
+ seg_T_ = Tn;
+ last_gpu_ms_ = 1000.0 * run_ds(c);
last_n_disp_ = (int) c.ds.size();
return finish(Tn, tokens, pos0, head, out, t0);
}
+ if (stream_ && !st_->ready() && !stream_arena(err)) return false;
Cached& cw = wcache_[key];
rec_ = &cw.qsa;
+ cuts_ = stream_ ? &cw.cuts : nullptr;
std::vector<mtl::Dispatch>& ds = cw.ds;
nb_ = false;
if (ple_on_) {
@@ -731,12 +833,67 @@ bool Window::run(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t
push(ds, d2);
}
rec_ = nullptr;
- last_gpu_ms_ = 1000.0 * cx_->run_graph(ds);
+ cuts_ = nullptr;
+ seg_T_ = Tn;
+ last_gpu_ms_ = 1000.0 * run_ds(cw);
last_n_disp_ = (int) ds.size();
return finish(Tn, tokens, pos0, head, out, t0);
}
+double Window::run_ds(Cached& c) {
+ if (!stream_) return cx_->run_graph(c.ds);
+ return cx_->run_graph_seg(c.ds, c.cuts, [](void* u, int s) { ((Window*) u)->at_cut(s); }, this);
+}
+
+namespace {
+Window* g_stream_window = nullptr;
+void stream_atexit() {
+ if (g_stream_window) g_stream_window->stream_report(stderr);
+}
+} // namespace
+
+// The arena, once the rest is allocated (the MTP layer loads after init): what the GPU working set and the RAM leave
+// with STRATA_METAL_KEEP_FREE_GB (default 9) kept for macOS; STRATA_METAL_ARENA_GB sets it.
+bool Window::stream_arena(std::string& err) {
+ uint64_t phys = 0;
+ size_t len = sizeof phys;
+ sysctlbyname("hw.memsize", &phys, &len, nullptr, 0);
+ const double gb = 1e9;
+ const double used = (double) cx_->allocated();
+ const char* ek = std::getenv("STRATA_METAL_KEEP_FREE_GB");
+ const double keep = (ek ? std::atof(ek) : 8.0) * gb;
+ // what macOS could give now: free + inactive + speculative + purgeable pages (the file cache is given back)
+ double avail = (double) phys - used;
+ {
+ vm_statistics64_data_t vs;
+ mach_msg_type_number_t cnt = HOST_VM_INFO64_COUNT;
+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &cnt) == KERN_SUCCESS)
+ avail = (double) (vs.free_count + vs.inactive_count + vs.speculative_count + vs.purgeable_count) * (double) vm_page_size;
+ }
+ double budget = std::min((double) cx_->recommended_working_set() - used - 1.0 * gb, avail - keep);
+ if (const char* e = std::getenv("STRATA_METAL_ARENA_GB")) budget = std::atof(e) * gb;
+ if (budget < 2 * gb) {
+ std::fprintf(stderr, "strata metal stream: only %.1f GB left for the expert arena (the GPU working set %.1f GB, RAM %.1f GB, "
+ "%.1f GB allocated): expect a low hit rate\n", budget / gb, cx_->recommended_working_set() / gb,
+ phys / gb, used / gb);
+ budget = std::max(budget, 1.0 * gb);
+ }
+ std::string prof;
+ if (const char* e = std::getenv("STRATA_METAL_EXPERT_PROFILE")) prof = e;
+ else prof = std::string(STRATA_METAL_DATA_DEFAULT) + "/expert-profile.bin";
+ std::fprintf(stderr, "strata metal stream: %.2f GB allocated before the arena; RAM %.1f GB (%.1f GB available, %.1f GB kept "
+ "for macOS), GPU working set %.1f GB\n", used / gb, phys / gb, avail / gb, keep / gb,
+ cx_->recommended_working_set() / gb);
+ if (!st_->make_arena(*cx_, (uint64_t) budget, prof, err)) return false;
+ g_stream_window = this;
+ std::atexit(stream_atexit);
+ return true;
+}
+
bool Window::finish(int Tn, const int32_t* tokens, int64_t pos0, bool head, int32_t* out, double t0) {
+ ++win_n_[Tn];
+ win_ms_[Tn] += now_ms() - t0;
+ win_gpu_[Tn] += last_gpu_ms_;
if (Tn == 1) hp_ = 1 - hp_; // a one-token window committed its GDN steps
for (int t = 0; t < Tn; ++t) out[t] = head ? tokout_.as<int32_t>()[t] : -1;
last_T_ = Tn;
@@ -883,7 +1040,7 @@ bool Window::mtp_load(const std::string& gguf_path, int max_t, std::string& err)
const size_t rb = ref::row_bytes(h.type, N);
mhead_ = A(dvocab_.size() * rb + 4096);
for (size_t i = 0; i < dvocab_.size(); ++i)
- std::memcpy(mhead_.as<uint8_t>() + i * rb, (const uint8_t*) f_.map + h.offset + (size_t) dvocab_[i] * rb, rb);
+ std::memcpy(mhead_.as<uint8_t>() + i * rb, (const uint8_t*) W_.ptr + h.offset + (size_t) dvocab_[i] * rb, rb);
mhead_t_ = h;
mhead_t_.offset = 0;
mhead_t_.shape = {(uint64_t) N, (uint64_t) dvocab_.size()};
@@ -919,7 +1076,7 @@ bool Window::mtp_load(const std::string& gguf_path, int max_t, std::string& err)
d.tg[0] = 256;
push(ds, d);
cx_->run_graph(ds);
- ref::dequant(te.type, (const uint8_t*) f_.map + te.offset + (size_t) probe[k] * rb, ref_row.data(), N);
+ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) probe[k] * rb, ref_row.data(), N);
for (int i = 0; i < N; ++i) worst = std::max(worst, (double) std::fabs(ref_row[i] - memb_.as<float>()[i]));
}
std::fprintf(stderr, "strata metal: MTP draft round in one command buffer (embedding type %d on the GPU: max "
@@ -978,7 +1135,7 @@ void Window::mtp_encode(std::vector<mtl::Dispatch>& ds, const mtl::Buffer& srcR,
const size_t rb = ref::row_bytes(te.type, N);
if (tokens)
for (int i = 0; i < n; ++i)
- ref::dequant(te.type, (const uint8_t*) f_.map + te.offset + (size_t) tokens[i] * rb,
+ ref::dequant(te.type, (const uint8_t*) W_.ptr + te.offset + (size_t) tokens[i] * rb,
memb_.as<float>() + (size_t) (erow + i) * N, N);
const std::string L = "mtp.layers.0.";
auto rms = [&](const mtl::Buffer& x, size_t xo, const std::string& w, mtl::Buffer& y, int width, int rows) {
@@ -1283,6 +1440,10 @@ void* window_create() {
}
void window_destroy(void* w) {
if (w != nullptr && w == g_the_window) {
+ if (g_stream_window == g_the_window) {
+ g_the_window->stream_report(stderr);
+ g_stream_window = nullptr;
+ }
delete g_the_window;
g_the_window = nullptr;
window_register(nullptr);
diff --git a/metal/src/gpu/runtime.cpp b/metal/src/gpu/runtime.cpp
index 3b8d158e6..694f086c1 100644
--- a/metal/src/gpu/runtime.cpp
+++ b/metal/src/gpu/runtime.cpp
@@ -20,6 +20,7 @@
#include <sys/sysctl.h>
+#include <atomic>
#include <chrono>
#include <cstdio>
#include <cstring>
@@ -251,12 +252,21 @@ Error run_op(StreamImpl* s, const Op& o) {
return kSuccess;
}
+// STRATA_METAL_ALLOC_LOG=1: every allocation of 16 MB or more, with the running total (memory budgets on small Macs)
+void alloc_log(const char* what, size_t n) {
+ static const bool on = std::getenv("STRATA_METAL_ALLOC_LOG") != nullptr;
+ static std::atomic<uint64_t> tot{0};
+ const uint64_t t = tot += n;
+ if (on && n >= (16u << 20)) std::fprintf(stderr, "strata metal runtime: %s %.1f MB (total %.2f GB)\n", what, n / 1e6, t / 1e9);
+}
+
Error new_alloc(void** p, size_t bytes, bool host) {
Runtime& r = rt();
const size_t n = bytes ? bytes : 1;
MTL::Buffer* b = r.dev->newBuffer(n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked);
if (!b) return fail(kErrorMemoryAllocation);
Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, host};
+ alloc_log(host ? "host alloc" : "device alloc", n);
{
std::lock_guard<std::mutex> lk(r.mu);
r.by_gpu[a.gpu] = a;
@@ -366,6 +376,7 @@ Error host_register(void* p, size_t bytes, unsigned) {
MTL::Buffer* b = r.dev->newBuffer(p, n, MTL::ResourceStorageModeShared | MTL::ResourceHazardTrackingModeUntracked, nullptr);
if (!b) return fail(kErrorMemoryAllocation);
Alloc a{b, b->gpuAddress(), (uint8_t*) b->contents(), n, true};
+ alloc_log("host register", n);
std::lock_guard<std::mutex> lk(r.mu);
r.by_gpu[a.gpu] = a;
r.by_cpu[(uintptr_t) a.cpu] = a.gpu;
diff --git a/metal/src/mtl_rt.h b/metal/src/mtl_rt.h
index 1cd22881b..60a493f8f 100644
--- a/metal/src/mtl_rt.h
+++ b/metal/src/mtl_rt.h
@@ -67,6 +67,7 @@ public:
bool supports_metal4() const;
uint64_t recommended_working_set() const;
uint64_t max_buffer_length() const;
+ uint64_t allocated() const { return allocated_; } // bytes of alloc() + wrap() buffers so far
// Compiles a library from MSL source files (paths), prepended by `prelude` (defines) and, if include_ggml,
// ggml-common.h with GGML_COMMON_DECL_METAL/IMPL_METAL. Returns a library id (index); aborts with the
@@ -85,6 +86,12 @@ public:
// A dependency graph in ONE concurrent encoder: a memory barrier only before dispatches with `barrier` set, so
// the dispatches between two barriers may overlap. Returns the GPU time in seconds.
double run_graph(const std::vector<Dispatch>& ds);
+ // run_graph in segments: the dispatches [cuts[s-1], cuts[s]) are one concurrent encoder; after segment s (for
+ // s < cuts.size()) the GPU signals a shared event and waits until the host has run at_cut(s) - the host's turn
+ // between two parts of one committed command buffer (the SSD-streaming handshake: the routing is read, the
+ // missing experts are put in place). Returns the GPU time in seconds.
+ double run_graph_seg(const std::vector<Dispatch>& ds, const std::vector<int>& cuts, void (*at_cut)(void*, int),
+ void* user);
// One command buffer per `run_cb` call, empty or not: measures commit+wait round trips.
double run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds = nullptr);
@@ -100,6 +107,7 @@ public:
private:
struct Impl;
Impl* impl_;
+ uint64_t allocated_ = 0;
};
double now_s(); // monotonic wall clock (seconds)
diff --git a/metal/src/mtl_rt.mm b/metal/src/mtl_rt.mm
index 573b22e2d..b85408925 100644
--- a/metal/src/mtl_rt.mm
+++ b/metal/src/mtl_rt.mm
@@ -31,6 +31,8 @@ struct Context::Impl {
id<MTLDevice> dev;
id<MTLCommandQueue> q;
std::vector<id<MTLLibrary>> libs;
+ id<MTLSharedEvent> ev = nil; // run_graph_seg's handshake timeline
+ uint64_t ev_v = 0;
};
static inline id<MTLBuffer> B(const Buffer& b) { return (__bridge id<MTLBuffer>)b.handle; }
@@ -99,6 +101,9 @@ Pipeline Context::pipeline(int lib, const std::string& fn, const Constants& c) {
NSString* name = [NSString stringWithUTF8String:fn.c_str()];
if (c.vals.empty()) {
f = [impl_->libs[lib] newFunctionWithName:name];
+ // a function with (optional) function constants needs a specialization even when none is set
+ if (f && f.functionConstantsDictionary.count > 0)
+ f = [impl_->libs[lib] newFunctionWithName:name constantValues:[MTLFunctionConstantValues new] error:&err];
} else {
MTLFunctionConstantValues* cv = [MTLFunctionConstantValues new];
for (const auto& v : c.vals) {
@@ -143,6 +148,7 @@ Buffer Context::alloc(size_t bytes) {
std::exit(4);
}
std::memset([b contents], 0, bytes);
+ allocated_ += bytes;
Buffer r;
r.handle = (__bridge_retained void*)b;
r.ptr = [b contents];
@@ -156,6 +162,7 @@ Buffer Context::wrap(void* p, size_t bytes) {
std::fprintf(stderr, "mtl: wrap %zu failed\n", bytes);
std::exit(4);
}
+ allocated_ += bytes;
Buffer r;
r.handle = (__bridge_retained void*)b;
r.ptr = p;
@@ -230,6 +237,47 @@ double Context::run_graph(const std::vector<Dispatch>& ds) {
}
}
+double Context::run_graph_seg(const std::vector<Dispatch>& ds, const std::vector<int>& cuts, void (*at_cut)(void*, int),
+ void* user) {
+ @autoreleasepool {
+ if (impl_->ev == nil) impl_->ev = [impl_->dev newSharedEvent];
+ id<MTLSharedEvent> ev = impl_->ev;
+ const uint64_t base = impl_->ev_v;
+ id<MTLCommandBuffer> cb = [impl_->q commandBufferWithUnretainedReferences];
+ size_t i = 0;
+ for (size_t s = 0; s <= cuts.size(); ++s) {
+ const size_t end = s < cuts.size() ? (size_t) cuts[s] : ds.size();
+ id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoderWithDispatchType:MTLDispatchTypeConcurrent];
+ const size_t first = i;
+ for (; i < end; ++i) {
+ if (i > first && ds[i].barrier) [enc memoryBarrierWithScope:MTLBarrierScopeBuffers];
+ encode(enc, ds[i]);
+ }
+ [enc endEncoding];
+ if (s < cuts.size()) {
+ [cb encodeSignalEvent:ev value:base + 2 * s + 1];
+ [cb encodeWaitForEvent:ev value:base + 2 * s + 2];
+ }
+ }
+ [cb commit];
+ for (size_t s = 0; s < cuts.size(); ++s) {
+ const uint64_t want = base + 2 * s + 1;
+ while (ev.signaledValue < want) {
+ if (cb.status >= MTLCommandBufferStatusCompleted) break; // an error: the wait below reports it
+ }
+ at_cut(user, (int) s);
+ ev.signaledValue = base + 2 * s + 2;
+ }
+ impl_->ev_v = base + 2 * cuts.size() + 2;
+ [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ std::fprintf(stderr, "mtl: command buffer failed: %s\n", [[cb.error localizedDescription] UTF8String]);
+ std::exit(5);
+ }
+ return cb.GPUEndTime - cb.GPUStartTime;
+ }
+}
+
double Context::run_wall(const std::vector<Dispatch>& ds, int reps, double* gpu_seconds) {
double gpu = 0;
const double t0 = now_s();