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++
CS-T: native packs read their experts from the GGUF shards in place (--mmap-experts without experts.bin), --resident-budget-gib N, per-tier counters
Niko12211e663cc70ee2
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hppindex 8af105aa7..6a1668bba 100644--- a/include/strata/core/expert_source.hpp+++ b/include/strata/core/expert_source.hpp@@ -28,6 +28,9 @@#include <atomic>#include <cstdint>#include <cstddef>+#include <memory>+#include <mutex>+#include <unordered_map>#include <utility>#include <string>#include <vector>@@ -120,6 +123,15 @@ public:/// checked with `pinned`). The arena answers per layer through its expert 0; the resident RAM mode's compact/// copy has no expert 0 when the GPU cache holds it, so it answers for the whole copy.virtual bool pcie_layer(int64_t layer) const { return device_alias(layer, 0) != nullptr; }++ /// CS-T: whether `blob(layer, expert)` would be assembled into a short-lived buffer (a native pack read from its+ /// GGUF shards in place, where an expert's gate, up and down rows are three separate slices). Such a pointer+ /// stays valid for the layer it was asked in and the next one or two; a consumer that keeps a blob longer (the+ /// prompt path's stager queues a whole chunk) copies it with `copy_blob` instead.+ virtual bool transient(int64_t layer, int64_t expert) const { (void) layer; (void) expert; return false; }+ /// The blob's bytes into `dst` (blob_bytes(layer) of them). Safe from several threads for a source whose+ /// `transient` can be true.+ virtual bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst);};/// Plan v0.3 P6: what the GPU computes in a verify window's layer, written by the pool (mapped host memory) right@@ -334,7 +346,16 @@ public:////// The size check is not a formality: a short file would fault at the END of a long sequence, and an/// over-long one means the pack is not the one the geometry came from. Refuses with the two numbers.+ ///+ /// CS-T: a native pack WITHOUT experts.bin, after `set_gguf`, maps the model's GGUF shards instead (every file+ /// native_experts.txt names, after `check_experts_gguf`), and assembles a blob from its three role slices when+ /// it is asked for: the SSD tier, read in place through the OS file cache, with no 30-77 GB experts.bin copy.+ /// With experts.bin present nothing changes.bool open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err);+ /// CS-T: the --native shard (native_experts.txt names the other files beside it); see `open`.+ void set_gguf(const std::string& native) { gguf_ = native; }+ /// Whether the experts are read from the GGUF shards in place (no experts.bin).+ bool gguf_mode() const { return !role_ptr_.empty(); }/// Pin a compact host mirror of experts absent from a fully filled static GPU cache. The mmap remains open/// as a fallback for later cache reloads. This is opt-in because the complement may still be a large allocation.///@@ -347,10 +368,15 @@ public:/// experts are kept in RAM too, from the last slot down, as far as `available RAM - headroom_bytes` allows/// (a lent slot's expert is streamed during the prompt and copied back after it)./// - the rest (the experts no slot holds) must fit that budget, or nothing is allocated and this returns false.+ ///+ /// CS-T, `budget_bytes` > 0 (`--resident-budget-gib`): only as many of those experts as fit `budget_bytes`, taken+ /// in `rank` order (the expert profile: the hottest after the GPU cache's), are copied; the rest stay on the+ /// mapped files (the SSD tier). No lend region then (a lent slot's expert is read from the files).bool pin_cache_complement(const ExpertCache& cache, std::string& err, bool pin = true,const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs = {}, int64_t lend_from_slot = -1,- uint64_t headroom_bytes = 8ull << 30);+ uint64_t headroom_bytes = 8ull << 30, uint64_t budget_bytes = 0,+ const std::vector<std::pair<int32_t, int32_t>>* rank = nullptr);void close();bool mapped() const { return base_ != nullptr; }@@ -382,11 +408,19 @@ public:/// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from/// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here.int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); }+ /// CS-T per-tier counters: blobs served from the RAM copy, and the bytes read from the mapped files (the blobs+ /// `file_reads` counts, plus the prompt path's copies of them).+ int64_t ram_reads() const { return ram_reads_.load(std::memory_order_relaxed); }+ uint64_t file_read_bytes() const { return file_read_bytes_.load(std::memory_order_relaxed); }const uint8_t* blob(int64_t layer, int64_t expert) override;bool pinned(int64_t layer, int64_t expert) const override;const uint8_t* device_alias(int64_t layer, int64_t expert) const override;bool pcie_layer(int64_t layer) const override;+ bool transient(int64_t layer, int64_t expert) const override;+ bool copy_blob(int64_t layer, int64_t expert, uint8_t* dst) override;+ /// CS-T: advances the assembled blobs' age (see staged_blob).+ void begin_layer(int64_t layer, const int32_t* ids, int64_t k) override;/// Blobs touched, for the driver to report. With `h = 0` this is `48 * k` per token and the number is only/// interesting once Phase 3 makes it not so.@@ -394,7 +428,42 @@ public:private:const uint8_t* mapped_blob(int64_t layer, int64_t expert) const;+ /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`.+ bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const;+ bool open_gguf(std::string& err);+ const uint8_t* staged_blob(int64_t layer, int64_t expert);static constexpr uint64_t kNoComplement = detail::kNoCacheComplement;+ // ---- CS-T: the GGUF shards in place+ std::string gguf_;+ struct Map {+ const uint8_t* base = nullptr;+ uint64_t bytes = 0;+#if defined(_WIN32)+ void* file = nullptr;+ void* mapping = nullptr;+#else+ int fd = -1;+#endif+ };+ std::vector<Map> maps_;+ std::vector<const uint8_t*> role_ptr_; ///< 3 x n_layers: gate / up / down of the layer's expert 0+ std::vector<uint64_t> role_bytes_; ///< 3 x n_layers: bytes per expert of that role+ // the blobs assembled for `blob()`: a small pool of buffers, one per recent (layer, expert). A buffer is+ // reused only once `kStageAge` layer changes have passed since its blob was last asked for, so a pointer holds+ // through the layer it was asked in and the next ones (the pool computes a layer's misses before the next).+ static constexpr uint64_t kStageAge = 3;+ std::mutex stage_mu_;+ std::vector<std::unique_ptr<uint8_t[]>> stage_buf_;+ std::vector<int64_t> stage_key_;+ std::vector<uint64_t> stage_epoch_, stage_used_;+ std::unordered_map<int64_t, size_t> stage_of_;+ uint64_t stage_blob_ = 0;+ uint64_t stage_seq_ = 0;+ uint64_t epoch_ = 0;+ int64_t last_layer_ = -1;+ bool stage_grew_ = false;+ std::atomic<int64_t> ram_reads_{0};+ std::atomic<uint64_t> file_read_bytes_{0};const uint8_t* base_ = nullptr;int64_t blobs_ = 0;int64_t n_layers_ = 0;diff --git a/serve/server.py b/serve/server.pyindex e03379e08..e363e3fa1 100644--- a/serve/server.py+++ b/serve/server.py@@ -284,6 +284,8 @@ class StrataEngine:self.last.update(drafts_accepted=int(f[6]), drafts_offered=int(f[7]), reused=int(f[8]))if len(f) >= 11: # decode hit rate fieldsself.last.update(hits=int(f[9]), lookups=int(f[10]))+ if len(f) >= 14: # the expert tiers (engine 0.1.31+): RAM / file blobs, file MB+ self.last.update(ram_blobs=int(f[11]), file_blobs=int(f[12]), file_mb=float(f[13]))@staticmethoddef sampling_keys(sampling: dict) -> str:@@ -1063,7 +1065,8 @@ class Service:"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)if n and last.get("generated") and last.get("decode_ms") else None,- "hit_rate": hit_rate})+ "hit_rate": hit_rate, "ram_blobs": last.get("ram_blobs"),+ "file_blobs": last.get("file_blobs"), "file_mb": last.get("file_mb")})t = self.totalst["requests"] += 1t["prompt_tokens"] += len(ids)diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cppindex 71a2ecc59..8d0ab32fb 100644--- a/src/core/expert_source.cpp+++ b/src/core/expert_source.cpp@@ -350,6 +350,16 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64}}const std::string path = pack_dir + "/experts.bin";+ if (layout.native && !gguf_.empty() && !std::filesystem::exists(path)) {+ // CS-T: no experts.bin - the model's GGUF shards, read in place+ blobs_ = (int64_t) blob_count;+ n_layers_ = n_layers;+ n_expert_ = n_expert;+ layer_offsets_ = std::move(layer_offsets);+ layer_blob_bytes_ = std::move(layer_blob_bytes);+ if (!open_gguf(err)) { close(); return false; }+ return true;+ }#if defined(_WIN32)// UTF-8 -> UTF-16: the pack may live under a path with non-ASCII characters, and `CreateFileA` would@@ -465,6 +475,37 @@ void FileExpertSource::close() {complement_ready_ = false;complement_locked_ = 0;complement_lent_slots_ = 0;+ if (!maps_.empty()) {+ for (Map& m : maps_) {+#if defined(_WIN32)+ if (m.base != nullptr) UnmapViewOfFile((LPCVOID) m.base);+ if (m.mapping != nullptr) CloseHandle((HANDLE) m.mapping);+ if (m.file != nullptr) CloseHandle((HANDLE) m.file);+#else+ if (m.base != nullptr) munmap((void*) m.base, (size_t) m.bytes);+ if (m.fd >= 0) ::close(m.fd);+#endif+ }+ maps_.clear();+ base_ = nullptr; // one of the views above+ }+ role_ptr_.clear();+ role_bytes_.clear();+ {+ std::lock_guard<std::mutex> lk(stage_mu_);+ stage_buf_.clear();+ stage_key_.clear();+ stage_epoch_.clear();+ stage_used_.clear();+ stage_of_.clear();+ stage_blob_ = 0;+ stage_seq_ = 0;+ epoch_ = 0;+ last_layer_ = -1;+ stage_grew_ = false;+ }+ ram_reads_.store(0);+ file_read_bytes_.store(0);#if defined(_WIN32)if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_);if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);@@ -486,7 +527,199 @@ void FileExpertSource::close() {reads_ = 0;}++bool ExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {+ const uint8_t* b = blob(layer, expert);+ if (b == nullptr || dst == nullptr) return false;+ std::memcpy(dst, b, (size_t) strata::kernels::cpu::expert_layout().blob_bytes(layer));+ return true;+}++// ================================ CS-T: THE GGUF SHARDS IN PLACE ================================+//+// A native pack without experts.bin: every file native_experts.txt names is mapped (MapViewOfFile / mmap, no+// flag - the same retention argument as experts.bin above), and an expert's blob [gate rows | up rows | down rows]+// is three slices of three tensors, possibly in two shards (UD-Q4_K_XL's layer 11). Nothing is read at open; a+// blob is assembled when it is asked for (`blob`, into a small pool of buffers) or copied where it is needed+// (`copy_blob`: the RAM copy, the prompt path's pinned stager buffers).+bool FileExpertSource::open_gguf(std::string& err) {+ const auto& lay = strata::kernels::cpu::expert_layout();+ if (!check_experts_gguf(gguf_, lay, err)) { err = "FileExpertSource: " + err; return false; }+ const size_t cut = gguf_.find_last_of("/\\");+ const std::string dir = cut == std::string::npos ? std::string() : gguf_.substr(0, cut + 1);+ std::map<std::string, size_t> index;+ role_ptr_.assign((size_t) (3 * n_layers_), nullptr);+ role_bytes_.assign((size_t) (3 * n_layers_), 0);+ for (int64_t l = 0; l < n_layers_; ++l) {+ const auto& fm = lay.fmt[(size_t) l];+ const uint64_t per[3] = {fm.up_off, fm.up_off, lay.bytes[(size_t) l] - fm.down_off};+ for (int r = 0; r < 3; ++r) {+ const size_t i = (size_t) (3 * l + r);+ const std::string path = lay.gguf_file.size() > i && !lay.gguf_file[i].empty() ? dir + lay.gguf_file[i]+ : gguf_;+ auto it = index.find(path);+ if (it == index.end()) {+ Map m;+#if defined(_WIN32)+ const int wide = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);+ std::vector<wchar_t> wpath((size_t) (wide > 0 ? wide : 1));+ if (wide > 0) MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, wpath.data(), wide);+ HANDLE f = CreateFileW(wpath.data(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING,+ FILE_ATTRIBUTE_NORMAL, nullptr);+ LARGE_INTEGER sz{};+ if (f == INVALID_HANDLE_VALUE || !GetFileSizeEx(f, &sz)) {+ if (f != INVALID_HANDLE_VALUE) CloseHandle(f);+ err = "FileExpertSource: cannot open " + path;+ return false;+ }+ HANDLE mh = CreateFileMappingW(f, nullptr, PAGE_READONLY, 0, 0, nullptr);+ void* view = mh != nullptr ? MapViewOfFile(mh, FILE_MAP_READ, 0, 0, 0) : nullptr;+ if (view == nullptr) {+ if (mh != nullptr) CloseHandle(mh);+ CloseHandle(f);+ err = "FileExpertSource: cannot map " + path;+ return false;+ }+ m.file = f;+ m.mapping = mh;+ m.bytes = (uint64_t) sz.QuadPart;+ m.base = (const uint8_t*) view;+#else+ const int fd = ::open(path.c_str(), O_RDONLY);+ struct stat st{};+ if (fd < 0 || fstat(fd, &st) != 0 || st.st_size <= 0) {+ if (fd >= 0) ::close(fd);+ err = "FileExpertSource: cannot open " + path;+ return false;+ }+ void* view = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_SHARED, fd, 0);+ if (view == MAP_FAILED) { ::close(fd); err = "FileExpertSource: cannot map " + path; return false; }+ m.fd = fd;+ m.bytes = (uint64_t) st.st_size;+ m.base = (const uint8_t*) view;+#endif+ maps_.push_back(m);+ it = index.emplace(path, maps_.size() - 1).first;+ }+ const Map& m = maps_[it->second];+ const uint64_t at = lay.gguf_off[i], bytes = per[r] * (uint64_t) n_expert_;+ if (at > m.bytes || bytes > m.bytes - at) { // check_experts_gguf proved it; the mapping must agree+ err = "FileExpertSource: an expert span runs past the end of " + path;+ return false;+ }+ role_ptr_[i] = m.base + (size_t) at;+ role_bytes_[i] = per[r];+ }+ }+ base_ = maps_.front().base; // "opened"; mapped_blob answers nullptr in this mode+ for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);+ return true;+}++bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const {+ if (dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;+ if (!role_ptr_.empty()) {+ uint64_t at = 0;+ for (int r = 0; r < 3; ++r) {+ const size_t i = (size_t) (3 * layer + r);+ const uint64_t per = role_bytes_[i];+ std::memcpy(dst + at, role_ptr_[i] + (size_t) ((uint64_t) expert * per), (size_t) per);+ at += per;+ }+ return true;+ }+ const uint8_t* b = mapped_blob(layer, expert);+ if (b == nullptr) return false;+ std::memcpy(dst, b, (size_t) layer_blob_bytes_[(size_t) layer]);+ return true;+}++// A blob assembled from the three role slices. The buffer of a (layer, expert) is reused for another only once+// its blob has not been asked for during `kStageAge` layers (begin_layer) or 256 assemblies, whichever comes+// first: the pool computes a layer's misses before it starts the next, and a fill (the GPU cache at startup, an+// adaptive swap, a helper GPU) copies the blob right away.+const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {+ constexpr uint64_t kStageSeq = 256;+ const int64_t key = layer * n_expert_ + expert;+ std::lock_guard<std::mutex> lk(stage_mu_);+ const uint64_t seq = ++stage_seq_;+ auto it = stage_of_.find(key);+ if (it != stage_of_.end()) {+ stage_epoch_[it->second] = epoch_;+ stage_used_[it->second] = seq;+ return stage_buf_[it->second].get();+ }+ size_t v = stage_buf_.size();+ uint64_t oldest = std::numeric_limits<uint64_t>::max();+ for (size_t i = 0; i < stage_buf_.size(); ++i)+ if ((stage_epoch_[i] + kStageAge <= epoch_ || stage_used_[i] + kStageSeq <= seq) && stage_used_[i] < oldest) {+ oldest = stage_used_[i];+ v = i;+ }+ if (v == stage_buf_.size()) {+ stage_buf_.emplace_back(new (std::nothrow) uint8_t[(size_t) stage_blob_]);+ if (!stage_buf_.back()) { stage_buf_.pop_back(); return nullptr; }+ stage_key_.push_back(-1);+ stage_epoch_.push_back(0);+ stage_used_.push_back(0);+ if (stage_buf_.size() == 512 && !stage_grew_) {+ stage_grew_ = true;+ std::fprintf(stderr, "FileExpertSource: %zu blobs assembled from the GGUF are in use at once (%.2f GiB)\n",+ stage_buf_.size(), (double) stage_buf_.size() * (double) stage_blob_ / 1073741824.0);+ }+ } else {+ stage_of_.erase(stage_key_[v]);+ }+ uint8_t* dst = stage_buf_[v].get();+ if (!copy_from_files(layer, expert, dst)) { stage_key_[v] = -1; return nullptr; }+ file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);+ stage_key_[v] = key;+ stage_epoch_[v] = epoch_;+ stage_used_[v] = seq;+ stage_of_[key] = v;+ return dst;+}++void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) {+ (void) ids;+ (void) k;+ if (role_ptr_.empty()) return;+ std::lock_guard<std::mutex> lk(stage_mu_);+ if (layer != last_layer_) {+ ++epoch_;+ last_layer_ = layer;+ }+}++bool FileExpertSource::transient(int64_t layer, int64_t expert) const {+ if (role_ptr_.empty() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;+ if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)+ return false;+ return override_.empty() || override_[index] == nullptr;+}++bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {+ if (base_ == nullptr || dst == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_)+ return false;+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;+ const uint64_t bytes = layer_blob_bytes_[(size_t) layer];+ if (complement_ready_) {+ const uint8_t* held =+ detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);+ if (held == nullptr && !override_.empty()) held = override_[index];+ if (held != nullptr) {+ std::memcpy(dst, held, (size_t) bytes);+ return true;+ }+ }+ if (!copy_from_files(layer, expert, dst)) return false;+ file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed);+ return true;+}+const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) const {+ if (!role_ptr_.empty()) return nullptr; // the GGUF in place: no contiguous blob in any fileif (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;const size_t i = (size_t) layer;if (i >= layer_offsets_.size() || i >= layer_blob_bytes_.size()) return nullptr;@@ -503,7 +736,7 @@ const uint8_t* FileExpertSource::mapped_blob(int64_t layer, int64_t expert) consbool FileExpertSource::pin_cache_complement(const ExpertCache& cache, std::string& err, bool pin,const std::vector<std::pair<int32_t, int32_t>>& additional_gpu_pairs, int64_t lend_from_slot,- uint64_t headroom_bytes) {+ uint64_t headroom_bytes, uint64_t budget_bytes, const std::vector<std::pair<int32_t, int32_t>>* rank) {err.clear();if (base_ == nullptr) { err = "FileExpertSource: open the mapped experts before pinning a complement"; return false; }if (complement_ready_) { err = "FileExpertSource: the cache complement is already pinned"; return false; }@@ -539,6 +772,43 @@ bool FileExpertSource::pin_cache_complement(uint64_t bytes = 0;if (!detail::make_cache_complement_plan(n_layers_, n_expert_, layer_blob_bytes_, primary_gpu_pairs,additional_gpu_pairs, offsets, bytes, err)) return false;+ if (budget_bytes > 0) {+ // CS-T: a RAM budget. The complement's experts in `rank` order (the expert profile, hottest first) while+ // they fit, the rest left on the mapped files; clamped to what the RAM has room for.+ uint64_t physical = 0;+ if (!available_memory_bytes(physical)) {+ err = "FileExpertSource: cannot determine available RAM for --resident-budget-gib";+ return false;+ }+ const uint64_t room = physical > headroom_bytes ? physical - headroom_bytes : 0;+ if (budget_bytes > room) {+ std::fprintf(stderr, "FileExpertSource: --resident-budget-gib %.2f is more than the RAM has room for "+ "(%.2f GiB available minus %.0f GiB headroom): %.2f GiB\n",+ (double) budget_bytes / 1073741824.0, (double) physical / 1073741824.0,+ (double) headroom_bytes / 1073741824.0, (double) room / 1073741824.0);+ budget_bytes = room;+ }+ std::vector<uint64_t> ranked(offsets.size(), kNoComplement);+ uint64_t at = 0;+ int64_t held = 0;+ if (rank != nullptr)+ for (const auto& pr : *rank) {+ if (pr.first < 0 || pr.second < 0 || pr.first >= n_layers_ || pr.second >= n_expert_) continue;+ const size_t i = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second;+ if (offsets[i] == kNoComplement || ranked[i] != kNoComplement) continue; // on a GPU, or twice+ const uint64_t b = layer_blob_bytes_[(size_t) pr.first];+ if (b > budget_bytes - at) continue;+ ranked[i] = at;+ at += b;+ ++held;+ }+ std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does "+ "not hold, by profile rank; the rest are read from the files\n",+ (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0);+ offsets.swap(ranked);+ bytes = at;+ lend_from_slot = -1;+ }const bool lend = lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty();uint64_t budget = std::numeric_limits<uint64_t>::max();@@ -663,15 +933,15 @@ bool FileExpertSource::pin_cache_complement(const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;const uint64_t offset = offsets[index];if (offset == kNoComplement) continue;- const uint8_t* source = mapped_blob(layer, expert);- if (source == nullptr || offset > bytes || blob_bytes > bytes - offset) {+ if (offset > bytes || blob_bytes > bytes - offset ||+ !copy_from_files(layer, expert, (uint8_t*) host + (size_t) offset)) {fail("FileExpertSource: invalid blob bounds while building the cache complement");return;}- std::memcpy((uint8_t*) host + (size_t) offset, source, (size_t) blob_bytes);copied.fetch_add(blob_bytes);}#if !defined(_WIN32)+ if (role_ptr_.empty()) { // experts.bin; the GGUF in place leaves its pages to the OSconst uint64_t layer_offset = layer_offsets_[(size_t) layer];const uint64_t layer_bytes = blob_bytes * (uint64_t) n_expert_;const uint64_t layer_end = layer_offset + layer_bytes;@@ -689,6 +959,7 @@ bool FileExpertSource::pin_cache_complement(fail("FileExpertSource: posix_fadvise could not release expert layer " + std::to_string(layer));return;}+ }#endifconst int64_t done = layers_done.fetch_add(1) + 1;if (done % 8 == 0 || done == n_layers_)@@ -712,7 +983,8 @@ bool FileExpertSource::pin_cache_complement(#if defined(_WIN32)// The mapped pages this process touched (the GPU cache's fill and this copy) leave its working set for the// standby list: VirtualUnlock on pages that are not locked does exactly that (it then reports ERROR_NOT_LOCKED).- (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);+ if (maps_.empty()) (void) VirtualUnlock((LPVOID) base_, (SIZE_T) mapped_bytes_);+ for (const Map& m : maps_) (void) VirtualUnlock((LPVOID) m.base, (SIZE_T) m.bytes);#endifcomplement_arena_ = arena;@@ -814,14 +1086,27 @@ int64_t FileExpertSource::commit_exchanges() {const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr;const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;- const uint8_t* mapped_fallback = mapped_blob(layer, expert);- const uint8_t* result = mapped_fallback;+ const uint8_t* result = nullptr;+ bool from_files = true;if (complement_ready_) {result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);- if (result == nullptr) {- result = !override_.empty() && override_[index] != nullptr ? override_[index] : mapped_fallback;- if (result == mapped_fallback && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);+ if (result != nullptr) {+ ram_reads_.fetch_add(1, std::memory_order_relaxed);+ from_files = false;+ } else if (!override_.empty() && override_[index] != nullptr) {+ result = override_[index];+ from_files = false;+ }+ }+ if (from_files) {+ if (!role_ptr_.empty()) {+ result = staged_blob(layer, expert); // counts its bytes+ } else {+ result = mapped_blob(layer, expert);+ if (result != nullptr)+ file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);}+ if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);}if (result != nullptr) ++reads_;return result;diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cppindex 116094adb..28981d12b 100644--- a/src/prefill/prefill.cpp+++ b/src/prefill/prefill.cpp@@ -138,7 +138,9 @@ struct Stager {// D-5: the pinned ring's depth (STRATA_STAGER_RING, default 16) - how far the host copies can run ahead of the// DMAs of the unpinned experts' blobsint kRing = 16;- struct Job { const uint8_t* src; size_t bytes; };+ // `from` set: the blob is copied by the source itself (CS-T: a GGUF read in place assembles it from its three+ // role slices; a pointer to it would not live as long as the queue)+ struct Job { const uint8_t* src; size_t bytes; core::ExpertSource* from = nullptr; int32_t l = 0, e = 0; };std::vector<uint8_t*> buf;std::vector<char> pinned;std::vector<std::vector<uint8_t>> pageable; // the fallback when no more RAM can be pinned@@ -205,7 +207,12 @@ struct Stager {while (issued.load(std::memory_order_acquire) <= j - kRing) std::this_thread::yield();cudaEventSynchronize(dma_done[b]);}- std::memcpy(buf[b], jobs[(size_t) j].src, jobs[(size_t) j].bytes);+ const Job& jb = jobs[(size_t) j];+ if (jb.from == nullptr) std::memcpy(buf[b], jb.src, jb.bytes);+ else if (!jb.from->copy_blob(jb.l, jb.e, buf[b])) {+ std::fprintf(stderr, "prefill: the expert source could not copy expert %d of layer %d\n", jb.e, jb.l);+ std::abort();+ }ready[(size_t) j].store(1, std::memory_order_release);active.fetch_sub(1, std::memory_order_acq_rel);}@@ -1095,12 +1102,18 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& eseq_start[(size_t) l] = seq.size();for (int32_t e = 0; e < m.g->n_expert; ++e) {if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;- const uint8_t* b = m.src->blob(l, e);- if (!b) { err = "prefill: expert source has no blob"; return false; }int job = -1;- if (!m.src->pinned(l, e)) {+ const uint8_t* b = nullptr;+ if (m.src->transient(l, e)) { // CS-T: copied by the source into the stager's bufferjob = (int) js.size();- js.push_back({b, (size_t) lay0.blob_bytes(l)});+ js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});+ } else {+ b = m.src->blob(l, e);+ if (!b) { err = "prefill: expert source has no blob"; return false; }+ if (!m.src->pinned(l, e)) {+ job = (int) js.size();+ js.push_back({b, (size_t) lay0.blob_bytes(l)});+ }}seq.push_back({(int32_t) l, e, b, job});}@@ -1585,9 +1598,13 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst int32_t e = order[j];if (m.host_res && m.cache && m.host_res[(size_t) l * m.g->n_expert + e] >= 0) continue;if (m.src->pinned(l, e)) continue;+ job_of[j] = (int) js.size();+ if (m.src->transient(l, e)) { // CS-T: copied by the source+ js.push_back({nullptr, (size_t) lay.blob_bytes(l), m.src, (int32_t) l, e});+ continue;+ }const uint8_t* b = m.src->blob(l, e);if (!b) { err = "prefill: expert source has no blob"; return false; }- job_of[j] = (int) js.size();js.push_back({b, (size_t) lay.blob_bytes(l)});}m.stager->start(std::move(js));@@ -1600,9 +1617,10 @@ bool Prefill::run(const int64_t* tokens, int64_t n, int64_t pos0, std::string& econst int sl = stage_next;stage_next = (stage_next + 1) % STAGE;const auto th = Clock::now();- const uint8_t* b = m.src->blob(l, e);- if (!b) { err = "prefill: expert source has no blob"; return false; }- if (m.src->pinned(l, e)) {+ const bool pinned = m.src->pinned(l, e); // pinned: never transient+ const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;+ if (pinned && !b) { err = "prefill: expert source has no blob"; return false; }+ if (pinned) {// DMA straight from the page-locked arena: the copy stream only waits for the slotif (m.stage_live[sl]) cudaStreamWaitEvent(m.copy, m.used[sl], 0);cudaMemcpyAsync(m.stage_dev[sl], b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice, m.copy);diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 9b89f5f72..6b927744e 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -251,6 +251,10 @@ struct Options {bool resident_pin = false;uint64_t resident_headroom = 8ull << 30;bool resident_soft = false;+ /// CS-T `--resident-budget-gib N`: the resident mode with a RAM budget - the N GiB of experts the GPU cache does+ /// not hold that the expert profile ranks hottest are copied into RAM, the rest are read from the files in place+ /// (the GGUF shards when the pack has no experts.bin). 0 = the whole complement (--resident-experts).+ uint64_t resident_budget = 0;/// R4: slots of VRAM-resident experts. **0 = off, and off is the default.**/// **THE COMMENT THAT USED TO BE HERE WAS FALSE AND ROUND 328 MEASURED IT.** It said "the cache has no/// consumer yet - `moe_hit_grouped_s2` does not exist - so switching it on costs the fill traffic and@@ -1155,6 +1159,17 @@ int main(int argc, char** argv) {if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);}+ else if (a == "--resident-budget-gib") {+ const double gib = std::atof(next("--resident-budget-gib"));+ if (!(gib > 0.0)) { std::fprintf(stderr, "strata generate: --resident-budget-gib needs N > 0\n"); return 2; }+ o.resident_budget = (uint64_t) (gib * 1073741824.0);+ o.mmap_experts = o.resident_cpu_experts = o.resident_pin = true;+ o.resident_headroom = 4ull << 30;+ if (const char* v = std::getenv("STRATA_RESIDENT_PIN"); v != nullptr && std::string(v) == "0")+ o.resident_pin = false;+ if (const char* v = std::getenv("STRATA_RESIDENT_HEADROOM_GIB"); v != nullptr && std::atof(v) >= 0.0)+ o.resident_headroom = (uint64_t) (std::atof(v) * 1073741824.0);+ }else if (a == "--stats") o.stats = true;else if (a == "--shared-late") o.shared_late = true;else if (a == "--keep-canonical") o.keep_canonical = true;@@ -2302,17 +2317,15 @@ int main(int argc, char** argv) {// built with `tools/iq_pack.py --experts-bin` (the per-layer blob sizes of its layout, PR #121). The low-RAM// mode: the experts come from the file through the OS cache instead of a pinned copy in RAM, for a PC whose// GPU holds most of them but whose RAM cannot hold them all.- if (native_pack && !std::filesystem::exists(std::filesystem::path(o.pack) / "experts.bin")) {- std::fprintf(stderr, "strata generate: --mmap-experts needs the pack's experts.bin; %s is a native (IQ) pack "- "built without it: python tools/iq_pack.py --gguf <shard 1> --out %s --experts-bin\n",- o.pack.c_str(), o.pack.c_str());- return 2;- }+ // CS-T: a native pack without experts.bin maps the model's GGUF shards instead (native_experts.txt's spans,+ // checked against the files first) - no 30-77 GB copy of the experts on the disk+ src.set_gguf(o.native_preset);if (!src.open(o.pack, g.n_layers, g.n_expert, err)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;}- std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; the A/B arm of R2.1)\n");+ std::fprintf(stderr, "strata generate: experts via mmap (--mmap-experts; %s)\n",+ src.gguf_mode() ? "the GGUF shards in place, no experts.bin" : "the A/B arm of R2.1");srcp = &src;} else {arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1@@ -3453,7 +3466,8 @@ int main(int argc, char** argv) {const int64_t k = plan_lend(chunk);if (k > 0) lend_from = xcache.slots() - k;}- if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom)) {+ if (src.pin_cache_complement(xcache, err, o.resident_pin, {}, lend_from, o.resident_headroom,+ o.resident_budget, &profile)) {if (o.adapt_every > 0 && o.adapt_swaps > 0 &&!src.reserve_exchanges(std::min<int64_t>(o.adapt_swaps, 96), err)) {std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());@@ -4766,6 +4780,9 @@ int main(int argc, char** argv) {double dt_run = 0, dt_commit = 0, dt_draft = 0;int64_t dec_windows = 0, dec_T = 0;const int64_t decode_hits0 = drive.d.cache_hits;+ // CS-T: the RAM and file tiers of this request (the mmap source; 0 with the arena)+ const int64_t ram0 = src.ram_reads(), files0 = src.file_reads();+ const uint64_t file_bytes0 = src.file_read_bytes();const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused;if (cancelled) finish = "cancel";while (!cancelled && produced_n < max_new) {@@ -5007,9 +5024,12 @@ int main(int argc, char** argv) {const int64_t req_hits = drive.d.cache_hits - decode_hits0;const int64_t req_look = (drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused) - decode_look0;// DONE <generated> <prompt> <prompt ms> <decode ms> <finish> <drafts accepted> <drafts offered> <reused> [hits] [lookups]- std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld\n", (long long) produced_n, (long long) n, prompt_ms,- decode_ms, finish, (long long) draft_accepted, (long long) draft_offered, (long long) resume,- (long long) req_hits, (long long) req_look);+ // [RAM blobs] [file blobs] [file MB] (CS-T tiers; appended, so an older server reads the rest)+ std::printf("DONE %lld %lld %.1f %.1f %s %lld %lld %lld %lld %lld %lld %lld %.1f\n", (long long) produced_n,+ (long long) n, prompt_ms, decode_ms, finish, (long long) draft_accepted, (long long) draft_offered,+ (long long) resume, (long long) req_hits, (long long) req_look,+ (long long) (src.ram_reads() - ram0), (long long) (src.file_reads() - files0),+ (double) (src.file_read_bytes() - file_bytes0) / 1e6);std::fflush(stdout);if (drive.routing != nullptr) std::fflush(drive.routing); // the routing trace survives a crash and is watchable mid-sessionconst int64_t fresh = n - resume;@@ -5033,6 +5053,12 @@ int main(int argc, char** argv) {"VRAM tier, %lld blob reads from the file\n",(double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(),(long long) src.file_reads());+ // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache)+ if (srcp == &src)+ std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs "+ "%.1f MB read%s\n", (long long) req_hits, (long long) src.ram_reads(),+ (long long) src.file_reads(), (double) src.file_read_bytes() / 1e6,+ src.gguf_mode() ? " (the GGUF in place)" : "");// STRATA_SPLIT_TIMING: where each verify stage's host time went, cumulative per window since the start// (waiting for its GPU to ring a layer, the CPU pool and plan per layer, staging the window)if (static const bool st_timing = std::getenv("STRATA_SPLIT_TIMING") != nullptr; st_timing)@@ -5690,6 +5716,12 @@ int main(int argc, char** argv) {std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from ""the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0,(long long) src.exchanges(), (long long) src.file_reads());+ if (srcp == &src) // CS-T: the RAM and file tiers (the GPU cache's share is the hit rate above)+ std::printf("%-24s RAM %lld blobs, files %lld blobs, %.1f MB read from the files (%.2f MB/round)%s\n",+ "expert tiers", (long long) src.ram_reads(), (long long) src.file_reads(),+ (double) src.file_read_bytes() / 1e6,+ rounds > 0 ? (double) src.file_read_bytes() / 1e6 / rounds : 0.0,+ src.gguf_mode() ? " (the GGUF in place)" : "");if (rounds > 0 && drive.d.pcie_num > 0)std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n","pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers),diff --git a/tests/core/expert_layout_test.cpp b/tests/core/expert_layout_test.cppindex f69e5c559..a28ba2c7a 100644--- a/tests/core/expert_layout_test.cpp+++ b/tests/core/expert_layout_test.cpp@@ -18,7 +18,9 @@#include "strata/kernels/cpu/expert_layout.hpp"#include "strata/kernels/cpu/native_expert.hpp"+#include <algorithm>#include <chrono>+#include <cstring>#include <cstdio>#include <filesystem>#include <fstream>@@ -206,6 +208,57 @@ void arena() {}check(exact, "every blob is [gate | up | down] of its expert, layer 1 from both files");+ { // CS-T: the same blobs from FileExpertSource reading the shards in place (no experts.bin in the pack)+ strata::core::FileExpertSource fs;+ fs.set_gguf(A.string());+ std::string e1;+ const bool opened = fs.open(pack.string(), 2, NE, e1);+ check(opened && fs.gguf_mode(), "FileExpertSource opens the GGUF in place" + (opened ? "" : ": " + e1));+ if (opened) {+ bool same = true, copies = true, transient = true;+ std::vector<uint8_t> buf((size_t) std::max(f0.bytes, f1.bytes));+ for (int64_t l = 0; l < 2; ++l)+ for (int64_t e = 0; e < NE; ++e) {+ fs.begin_layer(l, nullptr, 0);+ const uint8_t* b = fs.blob(l, e);+ const size_t n = (size_t) L.blob_bytes(l);+ same = same && b != nullptr && std::memcmp(b, dst.data() + L.blob_offset(l, e), n) == 0;+ copies = copies && fs.copy_blob(l, e, buf.data()) &&+ std::memcmp(buf.data(), dst.data() + L.blob_offset(l, e), n) == 0;+ transient = transient && fs.transient(l, e);+ }+ check(same && copies && transient, "blob() and copy_blob() equal the loaded arena byte for byte (transient)");+ // a blob asked again in the same layer is the same buffer; its bytes hold through two more layers+ fs.begin_layer(0, nullptr, 0);+ const uint8_t* p = fs.blob(0, 1);+ const uint8_t* q = fs.blob(0, 1);+ fs.begin_layer(1, nullptr, 0);+ (void) fs.blob(1, 0);+ (void) fs.blob(1, 1);+ fs.begin_layer(0, nullptr, 0);+ (void) fs.blob(0, 0);+ check(p == q && std::memcmp(p, dst.data() + L.blob_offset(0, 1), (size_t) L.blob_bytes(0)) == 0,+ "an assembled blob stays put while it is in use");+ check(fs.file_read_bytes() > 0, "the file tier counts its bytes (" + std::to_string(fs.file_read_bytes()) + ")");+ }+ fs.close();+ // with experts.bin present, the pack's file is mapped as before, whatever set_gguf says+ {+ std::ofstream eb(pack / "experts.bin", std::ios::binary);+ eb.write((const char*) dst.data(), (std::streamsize) dst.size());+ }+ strata::core::FileExpertSource fb;+ fb.set_gguf(A.string());+ std::string e2;+ const bool ob = fb.open(pack.string(), 2, NE, e2);+ const uint8_t* b11 = ob ? fb.blob(1, 1) : nullptr;+ check(ob && !fb.gguf_mode() && !fb.transient(1, 1) && b11 != nullptr &&+ std::memcmp(b11, dst.data() + L.blob_offset(1, 1), (size_t) L.blob_bytes(1)) == 0,+ "with experts.bin the mapped file is used (unchanged behaviour)");+ fb.close();+ fs::remove(pack / "experts.bin");+ }+auto refused = [&](const std::string& what, const std::string& needle) {std::string e2;const bool bad = load(pack, 2, 512, e2) && !strata::core::check_experts_gguf(A.string(),