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: the streaming arena fills in 1.5 GB steps and stops at macOS's floor; available memory is free + purgeable + the clean file cache (not other programs' inactive memory); the least arena layout goes ahead instead of failing the re-check
Niko1221612633c3b03d
diff --git a/docs/MAC.md b/docs/MAC.mdindex 23851a95b..6afd23a37 100644--- a/docs/MAC.md+++ b/docs/MAC.md@@ -26,7 +26,7 @@ with 32 GB, where the experts stream from the SSD. Other chips and memory sizes- **The n-gram table:** each pack also has a 28.8 GB n-gram table (the model's second file). It is read from the SSD a few rows at a time and does not count against the memory above.- **Disk:** the download is 66-84 GB, plus about 7 GB for the pack and the draft layer. A Mac that streams also needs room for the experts' copy (below): 34-40 GB.- **A Mac whose memory cannot hold the pack (32-48 GB):** the engine streams the experts from the SSD instead. It decides this by itself when the experts are more than 60% of Metal's share.- - It keeps the most-used experts in an arena: Metal's share, or the memory macOS reports as available less what it keeps for macOS, whichever is smaller. It keeps 7 GB, or 15% of the RAM when that is more, and it also keeps the n-gram table's share. It checks the free memory again just before it takes the arena, and takes less if less is free.+ - It keeps the most-used experts in an arena: Metal's share, or the memory macOS reports as available less what it keeps for macOS, whichever is smaller. It keeps 7 GB, or 15% of the RAM when that is more, and it also keeps the n-gram table's share. It counts as free only what macOS can give without swapping (free and purgeable memory and the clean file cache, not other programs' idle memory). It checks again just before it takes the arena, and fills the arena in 1.5 GB steps, checking again before each one; it stops early rather than push macOS below what it keeps.- It reads the rest as each token needs them, and reads ahead the experts the next layer will probably use.- Setup writes a second copy of the experts for such a Mac (`<model>.experts`, 40 GB for IQ3_XXS). In it each expert's three matrices sit together, so the SSD reads an expert with one request instead of three. On the 32 GB M4 that is about 17% faster decoding and 30% faster prompts, with the same tokens. Setup writes it only when the disk has room for it plus 10 GB; otherwise it warns, and the engine reads the model file as before.- Setup configures such a Mac without the MTP draft layer: one token per step is faster there.diff --git a/metal/src/engine/arena_budget.h b/metal/src/engine/arena_budget.hindex 261f77579..4f6985290 100644--- a/metal/src/engine/arena_budget.h+++ b/metal/src/engine/arena_budget.h@@ -14,6 +14,13 @@// GPU the Metal working set less what is already allocated, less 1 GB.// STRATA_METAL_ARENA_GB sets the arena outright. The arena is placed just before it is filled, and the memory macOS// can give is asked again then: when it has dropped (another program), the arena shrinks (arena_shrink).+// "Available" (arena_avail) counts free and purgeable pages and the file cache macOS drops without writing anything:+// inactive pages, but no more of them than there are file-backed pages. Inactive anonymous memory (other programs')+// is left out: macOS frees it only by compressing or swapping it (the soak's 93 MB swapped out while an arena planned+// with every inactive page filled). Free + purgeable alone is too little: at the engine's start the model file's own+// pages fill the cache (6.4 GB free + purgeable on the 32 GB M4 against 15 GB a minute later). The arena is filled in steps (STRATA_METAL_ARENA_STEP_GB, default 1.5): before each step the free+// memory is asked again, and the fill stops - the rest of the arena's slots unused - when a step would take macOS+// below what it keeps (arena_grow).#pragma once#include <algorithm>@@ -24,7 +31,7 @@ struct ArenaMem {double phys = 0; // bytes of RAMdouble working_set = 0; // the Metal device's recommended working setdouble allocated = 0; // already allocated by the engine (Metal buffers)- double available = 0; // what macOS can give now: free + inactive + speculative + purgeable pages+ double available = 0; // what macOS can give now without paging anything out (arena_avail)double ple_mapped = 0; // the n-gram table's bytes when it is mapped whole in RAM, else 0double keep_gb = -1; // STRATA_METAL_KEEP_FREE_GB (< 0: unset)double arena_gb = -1; // STRATA_METAL_ARENA_GB (< 0: unset)@@ -32,6 +39,12 @@ struct ArenaMem {constexpr double kGB = 1e9;+/// Bytes macOS can give without compressing or swapping: free + purgeable + the clean file cache (inactive and+/// speculative pages, at most the file-backed ones).+inline double arena_avail(double free_b, double purgeable_b, double inactive_b, double speculative_b, double file_b) {+ return free_b + purgeable_b + std::min(inactive_b + speculative_b, file_b);+}+inline double arena_keep(const ArenaMem& m) {return m.keep_gb >= 0 ? m.keep_gb * kGB : std::max(7.0 * kGB, 0.15 * m.phys);}@@ -55,4 +68,28 @@ inline double arena_shrink(const ArenaMem& m, double planned, double available_nreturn std::min(planned, arena_budget(now));}+/// The stepped fill: may the next `step` bytes of the arena be filled while macOS has `available_now` free + purgeable?+/// (the explicit STRATA_METAL_ARENA_GB always fills)+inline bool arena_grow(const ArenaMem& m, double available_now, double step) {+ if (m.arena_gb >= 0) return true;+ return available_now - step >= arena_keep(m) + arena_ple_reserve(m);+}++/// The fill as a plan, for the test: the pairs' bytes in rank order, steps of `step` bytes, `avail(filled)` the free+/// memory once `filled` bytes are in. Returns how many pairs are filled.+template <class Avail>+inline size_t arena_fill_plan(const ArenaMem& m, const double* cost, size_t n, double step, Avail avail) {+ size_t i = 0;+ double filled = 0;+ while (i < n) {+ double s = 0;+ size_t j = i;+ while (j < n && (s < step || j == i)) s += cost[j++];+ if (!arena_grow(m, avail(filled), s)) break;+ filled += s;+ i = j;+ }+ return i;+}+} // namespace strata::metal_enginediff --git a/metal/src/engine/stream.cpp b/metal/src/engine/stream.cppindex 4aef6a090..6a9cf39b1 100644--- a/metal/src/engine/stream.cpp+++ b/metal/src/engine/stream.cpp@@ -359,7 +359,7 @@ void ExpertStream::promote_slot(int s) {}bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err,- const std::function<uint64_t()>& recheck) {+ const std::function<uint64_t()>& recheck, const std::function<bool(uint64_t)>& grow) {const double t0 = now_ms();shrink_to_ = 0;for (auto& k : cls_) k.n = 0; // a second try (after a shrink) lays the arena out again@@ -458,6 +458,7 @@ bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::strismap_ = cx.alloc((size_t) NL * NE * 4);std::memset(smap_.ptr, 0xFF, (size_t) NL * NE * 4);slots_ = std::vector<Slot>((size_t) base);+ retired_.assign((size_t) base, 0);where_.assign((size_t) NL * NE, -1);for (auto& k : cls_) {for (int s = k.base; s < k.base + k.n; ++s) {@@ -468,35 +469,67 @@ bool ExpertStream::make_arena(mtl::Context& cx, uint64_t budget, const std::strik.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;- });+ // the fill: the ranked pairs in steps (best first; each step in file order) on the I/O threads; before each step+ // grow() asks whether macOS still has the memory for it (arena_grow); the best-ranked ends at the LRU front+ uint64_t step = 1536ull << 20;+ if (const char* e = std::getenv("STRATA_METAL_ARENA_STEP_GB")) step = std::max<uint64_t>(64ull << 20, (uint64_t) (std::atof(e) * 1e9));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);+ size_t done = 0;+ bool stopped = false;+ uint64_t filled = 0;+ while (done < fill.size()) {+ size_t j = done;+ uint64_t sb = 0;+ while (j < fill.size() && (sb < step || j == done)) sb += cls_[(size_t) lay_[(size_t) fill[j++].first].cls].pages * PAGE;+ if (grow && !grow(sb)) { stopped = true; break; }+ std::vector<std::pair<int, int>> order(fill.begin() + (long) done, fill.begin() + (long) j);+ 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::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; });}+ filled += sb;+ done = j;}- cv_.notify_all();+ uint64_t retired_bytes = 0;+ size_t nretired = 0;{std::unique_lock<std::mutex> g(mu_);- done_cv_.wait(g, [&] { return outstanding_ == 0; });+ if (stopped) // the slots not filled stay unused (their pages never touched), all but min_slots of each class+ for (size_t c = 0; c < cls_.size(); ++c) {+ const Cls& k = cls_[c];+ for (int s = std::max(next_free[c], k.base + std::min(min_slots, k.n)); s < k.base + k.n; ++s) {+ lru_unlink(s);+ retired_[(size_t) s] = 1;+ retired_bytes += k.pages * PAGE;+ ++nretired;+ }+ }// 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)]);+ for (size_t i = done; i-- > 0;) lru_front(where_[(size_t) (fill[i].first * NE + fill[i].second)]);}+ if (stopped)+ std::fprintf(stderr, "strata metal stream: the arena's fill stopped after %.2f GB: macOS's free memory reached what it "+ "keeps; %.2f GB of the arena (%zu slots) stay unused\n", filled / 1e9, retired_bytes / 1e9, nretired);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_,+ (arena_bytes_ - retired_bytes) / 1e9, (unsigned long long) (pairs - nretired), cls_.size(), done, from_profile, fill_s_,fill_bytes_ / 1e9 / std::max(1e-9, fill_s_), nio_, prefetch_ ? pre_k_ : 0, chunks_.size());(void) err;return true;@@ -693,7 +726,7 @@ void ExpertStream::hold_region(bool hold) {} else {for (int s : region_slots_) {slots_[(size_t) s].state = 0;- lru_back(s);+ if (!retired_[(size_t) s]) lru_back(s); // a retired slot's memory serves the prompt only}}}diff --git a/metal/src/engine/stream.h b/metal/src/engine/stream.hindex e2d230ad9..46317d3a1 100644--- a/metal/src/engine/stream.h+++ b/metal/src/engine/stream.h@@ -49,7 +49,8 @@ public:// recheck (optional): just before the arena is committed, the bytes it may have now (arena_shrink); when that is// less than the arena laid out, nothing is allocated, shrink_to() says how much, and the caller tries againbool make_arena(mtl::Context& cx, uint64_t budget, const std::string& profile, int min_slots, std::string& err,- const std::function<uint64_t()>& recheck = {});+ const std::function<uint64_t()>& recheck = {},+ const std::function<bool(uint64_t)>& grow = {});uint64_t shrink_to() const { return shrink_to_; }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@@ -96,6 +97,7 @@ private:std::vector<Lay> lay_;std::vector<Cls> cls_;std::vector<Slot> slots_;+ std::vector<uint8_t> retired_; // slots left unused when the stepped fill stopped at macOS's floor (never in an LRU)std::vector<int32_t> where_; // (l * 512 + e) -> slot, -1std::vector<mtl::Buffer> chunks_;std::vector<int> region_slots_;diff --git a/metal/src/engine/window.cpp b/metal/src/engine/window.cppindex aed846c86..474e36f8c 100644--- a/metal/src/engine/window.cpp+++ b/metal/src/engine/window.cpp@@ -1076,12 +1076,16 @@ bool Window::stream_arena(std::string& err) {"Metal window)\n", g / 1e9);}const double used = (double) cx_->allocated();- // what macOS could give now: free + inactive + speculative + purgeable pages (the file cache is given back)+ // what macOS gives now without paging anything out (arena_avail: free, purgeable, the clean file cache; not other+ // programs' inactive memory, freed only by compressing or swapping it)auto avail_now = [&]() -> double {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)- return (double) (vs.free_count + vs.inactive_count + vs.speculative_count + vs.purgeable_count) * (double) vm_page_size;+ if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &cnt) == KERN_SUCCESS) {+ const double pg = (double) vm_page_size;+ return arena_avail(vs.free_count * pg, vs.purgeable_count * pg, vs.inactive_count * pg, vs.speculative_count * pg,+ vs.external_page_count * pg);+ }return (double) phys - (double) cx_->allocated();};ArenaMem am; // arena_budget.h: the rule, testable@@ -1110,12 +1114,15 @@ bool Window::stream_arena(std::string& err) {cx_->recommended_working_set() / gb);const char* epg = std::getenv("STRATA_METAL_PROMPT_GEMM");const bool pg_on = !(epg && std::string(epg) == "0");+ bool minimal = false; // the arena's least layout (the min slots) is not shrunk further: it goes ahead, filled in stepsfor (int tries = 0;; ++tries) {const double planned = budget;- if (st_->make_arena(*cx_, (uint64_t) budget, prof, pg_on ? 576 : 64, err,- [&]() -> uint64_t { return (uint64_t) arena_shrink(am, planned, avail_now()); }))+ std::function<uint64_t()> recheck = [&]() -> uint64_t { return (uint64_t) arena_shrink(am, planned, avail_now()); };+ if (st_->make_arena(*cx_, (uint64_t) budget, prof, pg_on ? 576 : 64, err, minimal ? std::function<uint64_t()>() : recheck,+ [&](uint64_t step) { return arena_grow(am, avail_now(), (double) step); }))break;if (st_->shrink_to() == 0 || tries == 4) return false;+ if ((double) st_->shrink_to() + 64.0 * (1 << 20) >= budget) minimal = true; // no smaller layout than this onestd::fprintf(stderr, "strata metal stream: less memory is free than when the arena was planned: %.1f -> %.1f GB\n",budget / gb, st_->shrink_to() / gb);budget = (double) st_->shrink_to();diff --git a/metal/tests/arena_budget_test.cpp b/metal/tests/arena_budget_test.cppindex 71f7d847a..ce8050d1e 100644--- a/metal/tests/arena_budget_test.cpp+++ b/metal/tests/arena_budget_test.cpp@@ -4,6 +4,7 @@#include <cmath>#include <cstdio>+#include <vector>using namespace strata::metal_engine;@@ -47,6 +48,34 @@ int main() {const double s1 = arena_shrink(m5, b5, 60.0 * kGB);check(s1 < b5 && std::fabs(s1 - (60.0 - 20.61 - 0.5) * kGB) < 0.1 * kGB, "less free when committing: it shrinks", s1);check(std::fabs(arena_shrink(m5, b5, 130.0 * kGB) - b5) < 1e6, "more free when committing: it stays as planned", b5);+ // the stepped fill (arena_grow / arena_fill_plan): 1.5 GB steps of 1.75 MB experts on the M4 (7 GB kept + 0.5)+ ArenaMem s4 = m4;+ s4.available = 17.8 * kGB;+ check(arena_grow(s4, 17.8 * kGB, 1.5 * kGB), "a step with room: it fills", 17.8 * kGB);+ check(!arena_grow(s4, 8.9 * kGB, 1.5 * kGB), "a step that would leave < 7.5 GB: it stops", 8.9 * kGB);+ check(arena_grow(s4, 9.0 * kGB, 1.5 * kGB), "a step that leaves exactly 7.5 GB: it fills", 9.0 * kGB);+ ArenaMem pin = s4;+ pin.arena_gb = 12.0;+ check(arena_grow(pin, 1.0 * kGB, 1.5 * kGB), "STRATA_METAL_ARENA_GB: always fills", 1.0 * kGB);+ std::vector<double> cost(6000, 1.75e6); // 10.5 GB of experts planned+ // macOS gives exactly what is filled: the plan fills all of it while free stays >= 7.5 GB+ const size_t all = arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB, [](double f) { return 18.5 * kGB - f; });+ check(all == cost.size(), "free memory follows the fill: every planned expert is filled", all * 1.75e6);+ // another program takes 4 GB while the arena fills (after 3 GB): the fill stops at the floor, a step short+ const size_t part = arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB,+ [](double f) { return 18.5 * kGB - f - (f >= 3 * kGB ? 4 * kGB : 0); });+ const double left = 18.5 * kGB - part * 1.75e6 - 4 * kGB;+ check(part < cost.size() && left >= 7.5 * kGB && left - 1.5 * kGB < 7.5 * kGB + 1.75e6,+ "4 GB taken meanwhile: it stops with >= 7.5 GB free, less than a step above", part * 1.75e6);+ // no room even for the first step: nothing is filled (the min slots still exist, unfilled)+ check(arena_fill_plan(s4, cost.data(), cost.size(), 1.5 * kGB, [](double) { return 8.0 * kGB; }) == 0,+ "no room for one step: nothing filled", 0);+ // what counts as available: the M4 at the engine's start (16 KiB pages: 6.3 GB free + purgeable, 10.4 GB+ // inactive, 14 GB file-backed) - the clean file cache counts; another program's inactive memory does not+ check(std::fabs(arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 14.1 * kGB) - 16.87 * kGB) < 1e6,+ "inactive file cache counts", arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 14.1 * kGB));+ check(std::fabs(arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 2.0 * kGB) - 8.37 * kGB) < 1e6,+ "inactive anonymous memory does not (only 2 GB file-backed)", arena_avail(6.3 * kGB, 0.07 * kGB, 10.4 * kGB, 0.1 * kGB, 2.0 * kGB));std::printf("%s\n", failures ? "FAILED" : "all passed");return failures ? 1 : 0;}