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

file tier: opt-in Linux I/O path (STRATA_IO_PREFETCH=1) and counters that separate drive reads from page-cache hits

Niko12219745567e5f0c
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
index 3eda5a086..c6dcf2af8 100644
--- a/include/strata/core/expert_source.hpp
+++ b/include/strata/core/expert_source.hpp
@@ -30,6 +30,7 @@
#include <cstdint>
#include <cstddef>
#include <condition_variable>
+#include <deque>
#include <memory>
#include <mutex>
#include <thread>
@@ -131,6 +132,9 @@ public:
/// immediately and nothing is retained. A CACHING source must return pointers into the cache, not into a
/// reused staging buffer - otherwise the pool would read the next expert's bytes while computing this one.
virtual const uint8_t* blob(int64_t layer, int64_t expert) = 0;
+ /// A blob pointer that stays valid (not recycled) for as long as the source is open: for a copy that runs
+ /// asynchronously long after the call (the adaptive tier's swap-ins). Defaults to `blob`.
+ virtual const uint8_t* blob_stable(int64_t layer, int64_t expert) { return blob(layer, expert); }
/// Blobs touched, for the driver to report. A source that does not count returns 0.
virtual int64_t reads() const { return 0; }
@@ -202,6 +206,10 @@ public:
/// Layer `layer`'s MoE input for `n_tok` tokens (host floats): predict and warm layer + 1. Never waits: a
/// prediction still running for an earlier layer makes this one skip.
void submit(int64_t layer, const float* x, int64_t n_tok, const int32_t* host_res);
+ /// STRATA_IO_PREFETCH_DEPTH: how many layers ahead of `layer` are predicted and warmed (default 1, the next layer).
+ /// A deeper one predicts layer + j from layer's input, which is less exact the further it looks.
+ void set_depth(int d) { depth_ = d < 1 ? 1 : d > 4 ? 4 : d; }
+ int depth() const { return depth_; }
int64_t predicted() const { return predicted_.load(std::memory_order_relaxed); }
int64_t skipped() const { return skipped_.load(std::memory_order_relaxed); }
double busy_ms() const { return (double) busy_us_.load(std::memory_order_relaxed) / 1000.0; }
@@ -211,6 +219,7 @@ private:
std::vector<std::vector<uint16_t>> routers_;
int64_t n_embd_ = 0, n_expert_ = 0;
int k_ = 10;
+ int depth_ = 1;
ExpertSource* src_ = nullptr;
std::thread thread_;
std::mutex mu_;
@@ -558,6 +567,8 @@ public:
bool advise_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) const override;
const uint8_t* blob(int64_t layer, int64_t expert) override;
+ /// With io prefetch in the experts.bin tier, the mapping itself (blob() may hand out a recycled staging buffer).
+ const uint8_t* blob_stable(int64_t layer, int64_t expert) override;
/// Windows, opt-in with STRATA_FILE_RELEASE=1: trim the file mapping's full pages after their expert reaches
/// VRAM. Never touches the resident complement or staging buffers. Disabled by default.
uint64_t release(int64_t layer, int64_t expert) override;
@@ -574,7 +585,7 @@ public:
/// madvise(WILLNEED) elsewhere), skipping the RAM copy's.
void warm(int64_t layer, const int64_t* experts, int64_t n) override;
/// Not when the reads are unbuffered: the warmed pages would be read through the file cache, a second time.
- bool warms() const override { return !role_ptr_.empty() && direct_.empty(); }
+ bool warms() const override { return (!role_ptr_.empty() || io_pf_) && direct_.empty(); }
/// Of the blobs the file tier read for the decode, how many had been warmed for their layer beforehand.
int64_t warmed_hits() const { return warm_hits_.load(std::memory_order_relaxed); }
int64_t warmed() const { return warm_count_.load(std::memory_order_relaxed); }
@@ -585,6 +596,32 @@ public:
/// interesting once Phase 3 makes it not so.
int64_t reads() const override { return reads_; }
+ // ---- the Linux I/O path of the mapped file tier (STRATA_IO_PREFETCH=1, opt in; no effect on Windows)
+ //
+ // The file tier's reads are page faults: the CPU kernels (experts.bin) or the fetch threads (the GGUF in place)
+ // touch the mapping, and each fault is a read of a few pages that blocks the layer. With this on:
+ // - an expert whose pages are not in the page cache is read with ONE pread of its whole blob (large requests,
+ // several at once) into a staging buffer instead of being faulted in;
+ // - the experts the router lookahead predicts for the next layers are read the same way on a pool of I/O
+ // threads, while the current layer computes (warm() queues them; the kernels then find them staged);
+ // - an expert whose pages are all cached is still handed out as the mapped pointer (no copy).
+ // The bytes are the same bytes, so the output is the same. `threads` = I/O threads (0: default 4).
+ void set_io_prefetch(bool on, int threads);
+ bool io_prefetch() const { return io_pf_; }
+ /// Counts the cached / uncached bytes of every blob read from the files (mincore, page-granular). Free with
+ /// io_prefetch; otherwise opt in with STRATA_IO_STATS=1 (the check costs a few microseconds per blob).
+ void set_io_stats(bool on) { io_stats_ = on || io_pf_; }
+ bool io_stats() const { return io_stats_; }
+ struct IoCounters {
+ uint64_t cached_bytes = 0, uncached_bytes = 0; ///< file reads at hand-out, by page-cache residency
+ uint64_t pread_bytes = 0, pread_us = 0, pread_n = 0; ///< bytes read with pread, thread time, calls
+ uint64_t pf_jobs = 0, pf_read_blobs = 0, pf_resident_skips = 0, pf_dropped = 0; ///< prefetch workers
+ uint64_t pf_used = 0, pf_unused = 0; ///< prefetched blobs a layer then used / never used
+ uint64_t crit_us = 0; ///< wall time the decode waited on file reads (prefetch + staged_blob)
+ uint64_t crit_n = 0;
+ };
+ IoCounters io_counters() const;
+
private:
const uint8_t* resident_blob(size_t index) const;
const uint8_t* mapped_blob(int64_t layer, int64_t expert) const;
@@ -592,7 +629,7 @@ private:
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);
- bool claim_stage(int64_t key, size_t& v, bool& fill);
+ bool claim_stage(int64_t key, size_t& v, bool& fill, bool ahead = false);
bool fill_stage(size_t v, int64_t layer, int64_t expert, uint8_t* dst);
void publish_stage(size_t v, int64_t layer, bool ok, double us);
struct Fill { size_t v; int64_t layer, e; uint8_t* dst; };
@@ -606,7 +643,7 @@ private:
std::vector<void*> direct_; ///< #286: per file, an unbuffered handle (Windows) or O_DIRECT fd (Linux)
std::vector<int> role_file_; ///< 3 x n_layers: index into maps_ / direct_
/// blobs assembled in the stage buffers (`blob` hands those out): the GGUF in place, or any unbuffered source
- bool staged() const { return !role_ptr_.empty() || !direct_.empty(); }
+ bool staged() const { return !role_ptr_.empty() || !direct_.empty() || io_pf_; }
static constexpr uint64_t kNoComplement = detail::kNoCacheComplement;
// ---- CS-T: the GGUF shards in place
std::string gguf_;
@@ -646,6 +683,30 @@ private:
bool stage_grew_ = false;
std::atomic<int64_t> ram_reads_{0};
std::atomic<uint64_t> file_read_bytes_{0};
+ // ---- the Linux I/O path (set_io_prefetch)
+ bool io_pf_ = false;
+ bool io_ahead_ = true; ///< STRATA_IO_PF_AHEAD=0: no read-ahead workers' queue, demand preads only
+ bool io_stats_ = false;
+ int io_threads_ = 4;
+ std::vector<std::thread> io_workers_;
+ std::mutex io_mu_;
+ std::condition_variable io_cv_;
+ std::deque<std::pair<int32_t, int32_t>> io_q_; ///< (layer, expert) to read ahead
+ bool io_quit_ = false;
+ std::vector<char> stage_pf_; ///< per stage buffer: filled ahead, not yet used by a layer
+ std::vector<int> io_fds_; ///< per mapped file: a plain descriptor (POSIX_FADV_RANDOM) for the preads
+ mutable std::atomic<uint64_t> io_cached_{0}, io_uncached_{0}, io_pread_bytes_{0}, io_pread_us_{0}, io_pread_n_{0};
+ std::atomic<uint64_t> io_pf_jobs_{0}, io_pf_blobs_{0}, io_pf_skips_{0}, io_pf_dropped_{0}, io_pf_used_{0}, io_pf_unused_{0},
+ io_crit_us_{0}, io_crit_n_{0};
+ struct Span { const uint8_t* p; uint64_t n; int fd; uint64_t off; uint64_t at; };
+ /// The (up to 3) file ranges of a blob: pointer in the mapping, size, descriptor and file offset, offset in the blob.
+ int spans(int64_t layer, int64_t expert, Span* out) const;
+ /// Bytes of the blob's pages in the page cache (mincore); `total` the blob's bytes.
+ uint64_t cached_bytes(int64_t layer, int64_t expert, uint64_t& total) const;
+ void io_worker();
+ void io_enqueue(int64_t layer, int64_t expert);
+ void io_stop();
+ const uint8_t* io_blob(int64_t layer, int64_t expert);
const uint8_t* base_ = nullptr;
int64_t blobs_ = 0;
int64_t n_layers_ = 0;
diff --git a/include/strata/platform/memory.hpp b/include/strata/platform/memory.hpp
index 954f1589c..0ebc84a57 100644
--- a/include/strata/platform/memory.hpp
+++ b/include/strata/platform/memory.hpp
@@ -51,4 +51,13 @@ void advise_willneed(const void* p, uint64_t bytes);
/// The same for [offset, offset + bytes) of an open file.
void advise_willneed(int fd, uint64_t offset, uint64_t bytes);
+/// What the OS says this process read from storage: `read_bytes` (/proc/self/io: bytes fetched from the block layer on
+/// its behalf, page faults on a mapping included, page-cache hits not) and `major_faults` (/proc/self/stat). Linux
+/// only; `valid` is false elsewhere. Take one at the start of a request and one at its end.
+struct ProcIo {
+ bool valid = false;
+ uint64_t read_bytes = 0, major_faults = 0;
+};
+ProcIo proc_io_sample();
+
} // namespace strata::platform
diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp
index d0ff201ec..ce84c0220 100644
--- a/src/core/expert_source.cpp
+++ b/src/core/expert_source.cpp
@@ -22,6 +22,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
+#include <deque>
#include <fstream>
#include <filesystem>
#include <sstream>
@@ -415,6 +416,224 @@ bool file_tier_unbuffered(const std::vector<std::string>& paths, uint64_t arena_
FileExpertSource::~FileExpertSource() { close(); }
+#if defined(__linux__)
+namespace {
+/// Bytes of [p, p + n) whose pages are in the page cache (mincore, page-granular); 0 when the call fails.
+uint64_t resident_in(const uint8_t* p, uint64_t n) {
+ if (n == 0) return 0;
+ static thread_local std::vector<unsigned char> vec;
+ const uintptr_t a = (uintptr_t) p & ~(uintptr_t) 4095, e = ((uintptr_t) p + (uintptr_t) n + 4095) & ~(uintptr_t) 4095;
+ vec.resize((size_t) ((e - a) / 4096));
+ if (mincore((void*) a, (size_t) (e - a), vec.data()) != 0) return 0;
+ uint64_t pages = 0;
+ for (unsigned char c : vec) pages += c & 1;
+ return std::min<uint64_t>(n, pages * 4096);
+}
+/// The whole range with pread (a short read continues); false on an error or an end of file.
+bool pread_full(int fd, uint8_t* dst, uint64_t n, uint64_t off) {
+ uint64_t done = 0;
+ while (done < n) {
+ const ssize_t r = ::pread(fd, dst + done, (size_t) (n - done), (off_t) (off + done));
+ if (r < 0) { if (errno == EINTR) continue; return false; }
+ if (r == 0) return false;
+ done += (uint64_t) r;
+ }
+ return true;
+}
+} // namespace
+#endif
+
+int FileExpertSource::spans(int64_t layer, int64_t expert, Span* out) const {
+ if (layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return 0;
+ 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];
+ const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) expert * per);
+ const size_t f = (size_t) role_file_[i];
+ out[r] = {p, per, f < io_fds_.size() ? io_fds_[f] : -1, (uint64_t) (p - maps_[f].base), at};
+ at += per;
+ }
+ return 3;
+ }
+ const uint8_t* b = mapped_blob(layer, expert);
+ if (b == nullptr) return 0;
+ out[0] = {b, layer_blob_bytes_[(size_t) layer], io_fds_.empty() ? -1 : io_fds_[0], (uint64_t) (b - base_), 0};
+ return 1;
+}
+
+uint64_t FileExpertSource::cached_bytes(int64_t layer, int64_t expert, uint64_t& total) const {
+ total = 0;
+#if defined(__linux__)
+ Span sp[3];
+ const int ns = spans(layer, expert, sp);
+ uint64_t res = 0;
+ for (int i = 0; i < ns; ++i) {
+ total += sp[i].n;
+ res += resident_in(sp[i].p, sp[i].n);
+ }
+ return res;
+#else
+ (void) layer; (void) expert;
+ return 0;
+#endif
+}
+
+FileExpertSource::IoCounters FileExpertSource::io_counters() const {
+ IoCounters c;
+ c.cached_bytes = io_cached_.load(std::memory_order_relaxed);
+ c.uncached_bytes = io_uncached_.load(std::memory_order_relaxed);
+ c.pread_bytes = io_pread_bytes_.load(std::memory_order_relaxed);
+ c.pread_us = io_pread_us_.load(std::memory_order_relaxed);
+ c.pread_n = io_pread_n_.load(std::memory_order_relaxed);
+ c.pf_jobs = io_pf_jobs_.load(std::memory_order_relaxed);
+ c.pf_read_blobs = io_pf_blobs_.load(std::memory_order_relaxed);
+ c.pf_resident_skips = io_pf_skips_.load(std::memory_order_relaxed);
+ c.pf_dropped = io_pf_dropped_.load(std::memory_order_relaxed);
+ c.pf_used = io_pf_used_.load(std::memory_order_relaxed);
+ c.pf_unused = io_pf_unused_.load(std::memory_order_relaxed);
+ c.crit_us = io_crit_us_.load(std::memory_order_relaxed);
+ c.crit_n = io_crit_n_.load(std::memory_order_relaxed);
+ return c;
+}
+
+void FileExpertSource::set_io_prefetch(bool on, int threads) {
+ io_stop();
+#if defined(__linux__)
+ if (!on) return;
+ if (base_ == nullptr || paths_.empty() || !direct_.empty()) return; // unbuffered readers batch their own reads
+ std::vector<int> fds;
+ for (const std::string& path : paths_) {
+ const int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
+ if (fd < 0) {
+ for (int f : fds) ::close(f);
+ return;
+ }
+ (void) posix_fadvise(fd, 0, 0, POSIX_FADV_RANDOM); // read exactly the range asked for, no read-ahead beyond it
+ fds.push_back(fd);
+ }
+ io_fds_ = std::move(fds);
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ for (uint64_t b : layer_blob_bytes_) stage_blob_ = std::max(stage_blob_, b);
+ }
+ if (!warm_stamp_) warm_stamp_.reset(new std::atomic<uint32_t>[(size_t) (n_layers_ * n_expert_)]());
+ io_threads_ = threads > 0 ? threads : 4;
+ if (const char* v = std::getenv("STRATA_IO_PF_AHEAD")) io_ahead_ = std::atoi(v) != 0;
+ io_pf_ = true;
+ io_stats_ = true;
+ io_quit_ = false;
+ for (int i = 0; i < io_threads_; ++i) io_workers_.emplace_back([this] { io_worker(); });
+#else
+ (void) on; (void) threads;
+#endif
+}
+
+void FileExpertSource::io_stop() {
+ {
+ std::lock_guard<std::mutex> lk(io_mu_);
+ io_quit_ = true;
+ io_q_.clear();
+ }
+ io_cv_.notify_all();
+ for (std::thread& t : io_workers_)
+ if (t.joinable()) t.join();
+ io_workers_.clear();
+#if defined(__linux__)
+ for (int f : io_fds_) ::close(f);
+#endif
+ io_fds_.clear();
+ io_pf_ = false;
+ io_quit_ = false;
+}
+
+void FileExpertSource::io_enqueue(int64_t layer, int64_t expert) {
+ {
+ std::lock_guard<std::mutex> lk(io_mu_);
+ if (io_q_.size() >= 512) { // the predictions run ahead of the reads: the oldest are the stalest
+ io_q_.pop_front();
+ io_pf_dropped_.fetch_add(1, std::memory_order_relaxed);
+ }
+ io_q_.emplace_back((int32_t) layer, (int32_t) expert);
+ }
+ io_cv_.notify_one();
+}
+
+// A read-ahead worker: takes a predicted (layer, expert), skips it when its pages are cached or it is already
+// staged, and otherwise reads the whole blob into a staging buffer (copy_from_files preads what is not cached).
+void FileExpertSource::io_worker() {
+ for (;;) {
+ int32_t layer, expert;
+ {
+ std::unique_lock<std::mutex> lk(io_mu_);
+ io_cv_.wait(lk, [&] { return io_quit_ || !io_q_.empty(); });
+ if (io_quit_) return;
+ layer = io_q_.back().first; // the newest prediction first: it is the layer that comes next
+ expert = io_q_.back().second;
+ io_q_.pop_back();
+ }
+ io_pf_jobs_.fetch_add(1, std::memory_order_relaxed);
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ if (complement_ready_ && resident_blob(index) != nullptr) continue;
+ if (!override_.empty() && override_[index] != nullptr) continue;
+ uint64_t total = 0;
+ if (cached_bytes(layer, expert, total) >= total) {
+ io_pf_skips_.fetch_add(1, std::memory_order_relaxed);
+ continue;
+ }
+ size_t v = 0;
+ bool fill = false;
+ uint8_t* dst = nullptr;
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ if (stage_blob_ == 0) continue;
+ const bool have = claim_stage((int64_t) layer * n_expert_ + expert, v, fill, /*ahead=*/true);
+ if (have || !fill) continue; // already staged or being read, or no buffer
+ stage_pf_[v] = 1;
+ dst = stage_buf_[v].get();
+ }
+ const bool ok = copy_from_files(layer, expert, dst);
+ io_pf_blobs_.fetch_add(1, std::memory_order_relaxed);
+ if (ok) file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ stage_busy_[v] = 0;
+ if (!ok) {
+ stage_of_.erase(stage_key_[v]);
+ stage_key_[v] = -1;
+ stage_pf_[v] = 0;
+ }
+ }
+ stage_cv_.notify_all();
+ }
+}
+
+// The decode's hand-out of a blob in the experts.bin file tier with io prefetch on: what a layer's prediction read
+// ahead is staged; a blob whose pages are all cached is the mapping itself (no copy); the rest is read with one
+// pread into a staging buffer, not faulted in by the kernels one small request at a time.
+const uint8_t* FileExpertSource::io_blob(int64_t layer, int64_t expert) {
+ const int64_t key = layer * n_expert_ + expert;
+ bool have;
+ {
+ std::lock_guard<std::mutex> lk(stage_mu_);
+ have = stage_of_.find(key) != stage_of_.end();
+ }
+ if (!have) {
+ uint64_t total = 0;
+ const uint64_t cached = cached_bytes(layer, expert, total);
+ if (total > 0 && cached >= total) {
+ const uint8_t* b = mapped_blob(layer, expert);
+ if (b != nullptr) {
+ io_cached_.fetch_add(total, std::memory_order_relaxed);
+ file_read_bytes_.fetch_add(total, std::memory_order_relaxed);
+ return b;
+ }
+ }
+ }
+ return staged_blob(layer, expert);
+}
+
bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64_t n_expert, std::string& err) {
close();
if (n_layers <= 0 || n_expert <= 0) { err = "FileExpertSource: the geometry is empty"; return false; }
@@ -588,6 +807,7 @@ bool FileExpertSource::open(const std::string& pack_dir, int64_t n_layers, int64
}
void FileExpertSource::close() {
+ io_stop();
inputs_.clear();
if (complement_arena_ != nullptr) {
if (complement_pinned_ && !complement_partial_) (void) cudaFreeHost(complement_arena_);
@@ -650,6 +870,7 @@ void FileExpertSource::close() {
stage_epoch_.clear();
stage_used_.clear();
stage_busy_.clear();
+ stage_pf_.clear();
stage_of_.clear();
stage_blob_ = 0;
stage_seq_ = 0;
@@ -664,6 +885,9 @@ void FileExpertSource::close() {
file_read_bytes_.store(0);
file_blob_bytes_.store(0);
file_us_.store(0);
+ io_cached_.store(0); io_uncached_.store(0); io_pread_bytes_.store(0); io_pread_us_.store(0); io_pread_n_.store(0);
+ io_pf_jobs_.store(0); io_pf_blobs_.store(0); io_pf_skips_.store(0); io_pf_dropped_.store(0);
+ io_pf_used_.store(0); io_pf_unused_.store(0); io_crit_us_.store(0); io_crit_n_.store(0);
#if defined(_WIN32)
if (base_ != nullptr) UnmapViewOfFile((LPCVOID) base_);
if (mapping_ != nullptr) CloseHandle((HANDLE) mapping_);
@@ -785,6 +1009,30 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d
if (read_direct(&f, 1)) return true;
direct_fallbacks_.fetch_add(1, std::memory_order_relaxed);
}
+#if defined(__linux__)
+ if (io_pf_ || io_stats_) { // count what the page cache holds; with io prefetch, read what it does not with pread
+ Span sp[3];
+ const int ns = spans(layer, expert, sp);
+ for (int i = 0; i < ns; ++i) {
+ const uint64_t res = resident_in(sp[i].p, sp[i].n);
+ io_cached_.fetch_add(res, std::memory_order_relaxed);
+ io_uncached_.fetch_add(sp[i].n - res, std::memory_order_relaxed);
+ if (io_pf_ && res < sp[i].n && sp[i].fd >= 0) {
+ const auto t0 = std::chrono::steady_clock::now();
+ const bool ok = pread_full(sp[i].fd, dst + sp[i].at, sp[i].n, sp[i].off);
+ io_pread_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ io_pread_n_.fetch_add(1, std::memory_order_relaxed);
+ if (ok) {
+ io_pread_bytes_.fetch_add(sp[i].n, std::memory_order_relaxed);
+ continue;
+ }
+ }
+ std::memcpy(dst + sp[i].at, sp[i].p, (size_t) sp[i].n);
+ }
+ if (ns > 0) return true;
+ }
+#endif
if (!role_ptr_.empty()) {
uint64_t at = 0;
for (int r = 0; r < 3; ++r) {
@@ -808,7 +1056,7 @@ bool FileExpertSource::copy_from_files(int64_t layer, int64_t expert, uint8_t* d
//
// `claim_stage` finds or reserves the buffer of `key` (stage_mu_ held): true when the blob is already there (or
// being filled by another thread - the caller then waits), false when the caller must fill buffer `v`.
-bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
+bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill, bool ahead) {
constexpr uint64_t kStageSeq = 256;
const uint64_t seq = ++stage_seq_;
auto it = stage_of_.find(key);
@@ -817,6 +1065,7 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
v = it->second;
stage_epoch_[v] = epoch_;
stage_used_[v] = seq;
+ if (!ahead && stage_pf_[v]) { stage_pf_[v] = 0; io_pf_used_.fetch_add(1, std::memory_order_relaxed); } // a layer asked for what was read ahead
return true;
}
v = stage_buf_.size();
@@ -834,6 +1083,7 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
stage_epoch_.push_back(0);
stage_used_.push_back(0);
stage_busy_.push_back(0);
+ stage_pf_.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",
@@ -841,6 +1091,7 @@ bool FileExpertSource::claim_stage(int64_t key, size_t& v, bool& fill) {
}
} else {
stage_of_.erase(stage_key_[v]);
+ if (stage_pf_[v]) { stage_pf_[v] = 0; io_pf_unused_.fetch_add(1, std::memory_order_relaxed); } // read ahead, never asked for
}
stage_key_[v] = key;
stage_epoch_[v] = epoch_;
@@ -881,6 +1132,13 @@ const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
size_t v = 0;
bool fill = false;
uint8_t* dst = nullptr;
+ const auto t0 = std::chrono::steady_clock::now();
+ auto crit = [&] {
+ if (!io_pf_) return;
+ io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ io_crit_n_.fetch_add(1, std::memory_order_relaxed);
+ };
{
std::unique_lock<std::mutex> lk(stage_mu_);
const bool have = claim_stage(key, v, fill);
@@ -890,15 +1148,33 @@ const uint8_t* FileExpertSource::staged_blob(int64_t layer, int64_t expert) {
// another thread (a prefetch, the adaptive tier) is filling it: wait for that
stage_cv_.wait(lk, [&] { return !stage_busy_[v] || stage_key_[v] != key; });
if (stage_key_[v] != key) return nullptr; // its fill failed
+ lk.unlock();
+ crit();
return dst;
}
}
- return fill_stage(v, layer, expert, dst) ? dst : nullptr;
+ const bool ok = fill_stage(v, layer, expert, dst);
+ crit();
+ return ok ? dst : nullptr;
}
void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n) {
if (!staged() || n <= 0 || layer < 0 || layer >= n_layers_) return;
std::vector<Fill> todo;
+ // experts.bin with io prefetch: a blob whose pages are cached is handed out as the mapping (io_blob); only the
+ // uncached ones are read here, together, on the fetch threads
+ const bool only_uncached = io_pf_ && role_ptr_.empty() && direct_.empty();
+ std::vector<char> cold;
+ if (only_uncached) {
+ cold.assign((size_t) n, 0);
+ for (int64_t i = 0; i < n; ++i) {
+ const int64_t e = experts[i];
+ if (e < 0 || e >= n_expert_) continue;
+ uint64_t total = 0;
+ cold[(size_t) i] = cached_bytes(layer, e, total) < total ? 1 : 0;
+ }
+ }
+ const auto t0 = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lk(stage_mu_);
for (int64_t i = 0; i < n; ++i) {
@@ -908,6 +1184,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
if (complement_ready_ && resident_blob(index) != nullptr)
continue; // in the RAM copy
if (!override_.empty() && override_[index] != nullptr) continue;
+ if (only_uncached && !cold[(size_t) i] && stage_of_.find(layer * n_expert_ + e) == stage_of_.end()) continue;
size_t v = 0;
bool fill = false;
if (!claim_stage(layer * n_expert_ + e, v, fill) && fill) {
@@ -920,6 +1197,11 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
}
}
fill_many(todo);
+ if (io_pf_ && !todo.empty()) {
+ io_crit_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
+ std::memory_order_relaxed);
+ io_crit_n_.fetch_add(1, std::memory_order_relaxed);
+ }
}
void FileExpertSource::prefetch_pairs(const std::pair<int32_t, int32_t>* pairs, int64_t n) {
@@ -1385,7 +1667,7 @@ bool FileExpertSource::read_direct(const Fill* fills, size_t n) const {
}
void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
- if (role_ptr_.empty() || n <= 0 || layer < 0 || layer >= n_layers_) return;
+ if ((role_ptr_.empty() && !io_pf_) || n <= 0 || layer < 0 || layer >= n_layers_) return;
uint32_t stamp;
{
std::lock_guard<std::mutex> lk(stage_mu_);
@@ -1404,6 +1686,11 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
continue; // in the RAM copy
if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed);
warm_count_.fetch_add(1, std::memory_order_relaxed);
+ if (io_pf_ && direct_.empty()) { // read it ahead with pread on the I/O threads (instead of an madvise hint)
+ if (io_ahead_) io_enqueue(layer, e);
+ continue;
+ }
+ if (role_ptr_.empty()) continue;
for (int r = 0; r < 3; ++r) {
const size_t i = (size_t) (3 * layer + r);
const uint8_t* p = role_ptr_[i] + (size_t) ((uint64_t) e * role_bytes_[i]);
@@ -1477,6 +1764,9 @@ void RouterLookahead::run() {
host_res = host_res_;
}
const auto t0 = std::chrono::steady_clock::now();
+ const int64_t layer0 = layer;
+ for (int dj = 0; dj < depth_ && layer0 + dj < (int64_t) routers_.size(); ++dj) {
+ layer = layer0 + dj;
want.clear();
// The router dot is AVX2 (kq_avx2.cpp); a CPU without AVX2 (the experimental older-CPU builds) takes the AVX1
// one (kq_avx1.cpp) or, without AVX, the same sums in plain C++. From the Strata_Dirigo fork (rwkeyes): an
@@ -1520,6 +1810,7 @@ void RouterLookahead::run() {
}
src_->warm(layer, want.data(), (int64_t) want.size());
predicted_.fetch_add((int64_t) want.size(), std::memory_order_relaxed);
+ }
busy_us_.fetch_add((uint64_t) std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - t0).count(),
std::memory_order_relaxed);
{
@@ -1541,7 +1832,9 @@ void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k)
}
bool FileExpertSource::transient(int64_t layer, int64_t expert) const {
- if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false;
+ // the io-prefetch staging of the experts.bin tier is the decode's: the prompt path keeps reading the mapping
+ // (its own read-ahead hints), so this answers as it did without io prefetch
+ if ((role_ptr_.empty() && direct_.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_ && resident_blob(index) != nullptr)
return false;
@@ -2223,6 +2516,19 @@ const uint8_t* FileExpertSource::resident_blob(int64_t layer, int64_t expert) co
return resident_blob(index); // through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on
}
+const uint8_t* FileExpertSource::blob_stable(int64_t layer, int64_t expert) {
+ if (io_pf_ && role_ptr_.empty() && direct_.empty()) {
+ if (complement_ready_ && layer >= 0 && expert >= 0 && layer < n_layers_ && expert < n_expert_) {
+ const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ if (resident_blob(index) != nullptr || (!override_.empty() && override_[index] != nullptr)) return blob(layer, expert);
+ }
+ const uint8_t* b = mapped_blob(layer, expert);
+ if (b != nullptr) file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+ return b;
+ }
+ return blob(layer, expert);
+}
+
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;
@@ -2239,12 +2545,23 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
}
}
if (from_files) {
- if (staged()) {
+ if (io_pf_ && role_ptr_.empty() && direct_.empty()) {
+ result = io_blob(layer, expert); // staged when it had to be read, the mapping when cached
+ } else if (staged()) {
result = staged_blob(layer, expert); // counts its bytes
} else {
result = mapped_blob(layer, expert);
- if (result != nullptr)
+ if (result != nullptr) {
file_read_bytes_.fetch_add(layer_blob_bytes_[(size_t) layer], std::memory_order_relaxed);
+#if defined(__linux__)
+ if (io_stats_) { // STRATA_IO_STATS=1: what the page cache held when the kernels were handed the blob
+ uint64_t total = 0;
+ const uint64_t c = cached_bytes(layer, expert, total);
+ io_cached_.fetch_add(c, std::memory_order_relaxed);
+ io_uncached_.fetch_add(total - c, std::memory_order_relaxed);
+ }
+#endif
+ }
}
if (complement_ready_ && result != nullptr) file_reads_.fetch_add(1, std::memory_order_relaxed);
}
diff --git a/src/platform/memory.cpp b/src/platform/memory.cpp
index a43ecef20..c9f2a512a 100644
--- a/src/platform/memory.cpp
+++ b/src/platform/memory.cpp
@@ -9,7 +9,9 @@
#include <cstring>
#else
#include <algorithm>
+#include <cstdio>
#include <cstdlib>
+#include <cstring>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
@@ -168,4 +170,29 @@ void advise_willneed(int fd, uint64_t offset, uint64_t bytes) {
}
#endif
+ProcIo proc_io_sample() {
+ ProcIo r;
+#if defined(__linux__)
+ if (std::FILE* f = std::fopen("/proc/self/io", "r")) {
+ char key[64];
+ unsigned long long v;
+ while (std::fscanf(f, "%63[^:]: %llu\n", key, &v) == 2)
+ if (std::strcmp(key, "read_bytes") == 0) { r.read_bytes = v; r.valid = true; }
+ std::fclose(f);
+ }
+ if (std::FILE* f = std::fopen("/proc/self/stat", "r")) {
+ char buf[1024];
+ const size_t n = std::fread(buf, 1, sizeof buf - 1, f);
+ buf[n] = 0;
+ std::fclose(f);
+ if (const char* p = std::strrchr(buf, ')')) { // fields after the command: state ppid ... minflt cminflt majflt
+ unsigned long long minflt = 0, cminflt = 0, majflt = 0;
+ if (std::sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %llu %llu %llu", &minflt, &cminflt, &majflt) == 3)
+ r.major_faults = majflt;
+ }
+ }
+#endif
+ return r;
+}
+
} // namespace strata::platform
diff --git a/src/prefill/prefill.cpp b/src/prefill/prefill.cpp
index 15ae9438e..f757f225d 100644
--- a/src/prefill/prefill.cpp
+++ b/src/prefill/prefill.cpp
@@ -1966,7 +1966,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
job = (int) js.size();
js.push_back({nullptr, (size_t) lay0.blob_bytes(l), m.src, (int32_t) l, e});
} else {
- b = m.src->blob(l, e);
+ b = m.src->blob_stable(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
if (ps_on && m.src->pinned(l, e)) { // multi-GPU: every ps_frac-th one goes to the peer's ring
ps_acc += m.pp->ps_frac;
@@ -2926,7 +2926,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
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);
+ const uint8_t* b = m.src->blob_stable(l, e);
if (!b) { err = "prefill: expert source has no blob"; return false; }
js.push_back({b, (size_t) lay.blob_bytes(l)});
}
@@ -2941,7 +2941,7 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
stage_next = (stage_next + 1) % STAGE;
const auto th = Clock::now();
const bool pinned = m.src->pinned(l, e); // pinned: never transient
- const uint8_t* b = pinned ? m.src->blob(l, e) : nullptr;
+ const uint8_t* b = pinned ? m.src->blob_stable(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 slot
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index ccaec33df..9887cf920 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -14,6 +14,7 @@
// AND IT IS PHASE 2, so hit rate is `h = 0` and the number it prints is slow on purpose
// (`phase-2-correct-engine.md:5-9`). What it is FOR is the honest tok/s figure and the logit dump.
+#include "strata/platform/memory.hpp"
#include "strata/core/arch_defaults.hpp"
#include "strata/core/dma_batch.hpp"
#include "strata/core/device.hpp"
@@ -3745,6 +3746,21 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata generate: the file tier reads through the file cache (STRATA_UNBUFFERED_LOAD=%s "
"ignored: without --resident-budget-gib the file cache holds the experts)\n", env);
}
+ // Linux I/O path (opt in): whole-blob preads instead of page faults, and the predicted experts of the next
+ // layers read ahead on I/O threads while the current layer computes (see FileExpertSource::set_io_prefetch)
+ if (const char* v = std::getenv("STRATA_IO_PREFETCH"); v != nullptr && std::atoi(v) != 0) {
+ const char* th = std::getenv("STRATA_IO_PF_THREADS");
+ src.set_io_prefetch(true, th != nullptr ? std::atoi(th) : 0);
+ if (src.io_prefetch())
+ std::fprintf(stderr, "strata generate: file tier io prefetch ON (STRATA_IO_PREFETCH=1): whole-blob preads, "
+ "predicted experts read ahead on %s I/O threads (STRATA_IO_PF_THREADS, default 4)\n",
+ th != nullptr ? th : "4");
+ else
+ std::fprintf(stderr, "strata generate: STRATA_IO_PREFETCH=1 is not available here (Linux mapped file tier "
+ "only, not with unbuffered reads); the file tier reads as before\n");
+ } else if (const char* sv = std::getenv("STRATA_IO_STATS"); sv != nullptr && std::atoi(sv) != 0) {
+ src.set_io_stats(true);
+ }
srcp = &src;
} else {
arena_src.set_gguf(o.native_preset); // plan v0.3 P6: a native pack may take its experts from shard 1
@@ -4147,7 +4163,7 @@ int main(int argc, char** argv) {
if (per_layer) continue;
break;
}
- const uint8_t* b = srcp->blob(profile[(size_t) i].first, profile[(size_t) i].second);
+ const uint8_t* b = srcp->blob_stable(profile[(size_t) i].first, profile[(size_t) i].second);
if (b == nullptr || !xcache.fill_slot_blocking(slot, b, err,
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[(size_t) i].first))) {
std::fprintf(stderr, "strata generate: the profile fill failed at pair %lld: %s\n",
@@ -4162,7 +4178,7 @@ int main(int argc, char** argv) {
// about bytes produces a plausible token, which is this project's most expensive failure mode; the
// cache's own `verify_slot` is the check and it costs one 1.38 MB D2H at startup.
if (prefilled > 0 && !xcache.verify_slot(xcache.slot_of(profile[0].first, profile[0].second),
- srcp->blob(profile[0].first, profile[0].second), err,
+ srcp->blob_stable(profile[0].first, profile[0].second), err,
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(profile[0].first))) {
std::fprintf(stderr, "strata generate: %s\n", err.c_str());
return 1;
@@ -4221,7 +4237,7 @@ int main(int argc, char** argv) {
if (filled >= st.cache.slots()) break;
const int32_t slot = st.cache.admit(pr.first, pr.second);
if (slot == strata::core::kNotResident) break;
- const uint8_t* b = srcp->blob(pr.first, pr.second);
+ const uint8_t* b = srcp->blob_stable(pr.first, pr.second);
if (b == nullptr || !st.cache.fill_slot_blocking(slot, b, err, (int64_t) lay.blob_bytes(pr.first))) {
std::fprintf(stderr, "strata generate: layer split, CUDA%d profile fill failed at pair %lld: %s\n",
st.dev, (long long) filled, err.c_str());
@@ -4230,7 +4246,7 @@ int main(int argc, char** argv) {
++filled;
}
if (filled == 0 || !st.cache.verify_slot(st.cache.slot_of(st.profile[0].first, st.profile[0].second),
- srcp->blob(st.profile[0].first, st.profile[0].second), err,
+ srcp->blob_stable(st.profile[0].first, st.profile[0].second), err,
(int64_t) lay.blob_bytes(st.profile[0].first))) {
std::fprintf(stderr, "strata generate: layer split, CUDA%d expert cache: %s\n", st.dev,
filled == 0 ? "nothing filled" : err.c_str());
@@ -4390,6 +4406,10 @@ int main(int argc, char** argv) {
const char* kv = std::getenv("STRATA_LOOKAHEAD_K");
if (ok && lookahead.start(std::move(routers), g.n_embd, g.n_expert, kv ? std::atoi(kv) : 10, &src, err)) {
drive.d.lookahead = &lookahead;
+ if (const char* dv = std::getenv("STRATA_IO_PREFETCH_DEPTH"); dv != nullptr && std::atoi(dv) > 0)
+ lookahead.set_depth(std::atoi(dv));
+ else if (src.io_prefetch())
+ lookahead.set_depth(2);
std::fprintf(stderr, "strata generate: routing-aware prefetch of the file tier on (the next layer's router)\n");
} else {
(void) cudaGetLastError();
@@ -5436,7 +5456,7 @@ int main(int argc, char** argv) {
const int32_t l = profile[pi].first, e = profile[pi].second;
const size_t i = (size_t) l * (size_t) g.n_expert + (size_t) e;
if (host_res[i] >= 0 || lay.blob_bytes(l) > room) continue;
- const uint8_t* b = srcp->blob(l, e);
+ const uint8_t* b = srcp->blob_stable(l, e);
if (b == nullptr) continue;
cudaMemcpyAsync(xcache.device_slot((int32_t) s), b, (size_t) lay.blob_bytes(l), cudaMemcpyHostToDevice,
nullptr);
@@ -6818,7 +6838,7 @@ int main(int argc, char** argv) {
if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs)
std::vector<std::pair<uintptr_t, uintptr_t>> spans;
for (const Swap& s : swaps)
- if (const uint8_t* b = srcp->blob(s.layer, s.in))
+ if (const uint8_t* b = srcp->blob_stable(s.layer, s.in))
spans.emplace_back((uintptr_t) b,
(uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));
pin_blobs(std::move(spans), pin_live);
@@ -6847,7 +6867,7 @@ int main(int argc, char** argv) {
const Swap& s = swaps[si];
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si];
- const uint8_t* b = srcp->blob(s.layer, s.in);
+ const uint8_t* b = srcp->blob_stable(s.layer, s.in);
const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache
GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr;
const strata::core::OnDevice on(gs ? gs->dev : -1);
@@ -7537,7 +7557,7 @@ int main(int argc, char** argv) {
}
}
if (pick < 0) continue;
- const uint8_t* b = srcp->blob(layer, pick % g.n_expert);
+ const uint8_t* b = srcp->blob_stable(layer, pick % g.n_expert);
if (b == nullptr || !xcache.fill_slot_queued(slot, b, ferr,
(int64_t) strata::kernels::cpu::expert_layout().blob_bytes(layer))) {
e = "VRAM: refilling the cache failed: " + ferr;
@@ -8864,7 +8884,7 @@ int main(int argc, char** argv) {
tr("refill start", (long long) p.lent.size());
const strata::core::OnDevice on(p.dev);
for (const auto& [i, slot] : p.lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
- const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
+ const uint8_t* b = srcp->blob_stable(i / g.n_expert, i % g.n_expert);
const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert);
if (b == nullptr || !(refill_blocking() ? p.cache->fill_slot_blocking(slot, b, e, nb)
: p.cache->fill_slot_queued(slot, b, e, nb)))
@@ -10262,11 +10282,44 @@ int main(int argc, char** argv) {
(unsigned long long)src.rotated_exchanges(),
(unsigned long long)src.avoided_exchange_copy_bytes());
// CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache)
- if (srcp == &src)
+ 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)" : "");
+ // what the OS did for this request (since the previous one): the drive's share of the file tier's reads
+ // against the page cache's, and what the I/O path did about it
+ static strata::platform::ProcIo io_prev;
+ static strata::core::FileExpertSource::IoCounters ic_prev;
+ static uint64_t fb_prev = 0;
+ const strata::platform::ProcIo io_now = strata::platform::proc_io_sample();
+ const strata::core::FileExpertSource::IoCounters ic = src.io_counters();
+ const uint64_t fb = src.file_read_bytes();
+ if (io_now.valid) {
+ std::fprintf(stderr, "strata serve: file tier I/O this request: the OS read %.1f MB from storage (%llu major faults) for "
+ "%.1f MB of expert reads", (double) (io_now.read_bytes - io_prev.read_bytes) / 1e6,
+ (unsigned long long) (io_now.major_faults - io_prev.major_faults), (double) (fb - fb_prev) / 1e6);
+ if (src.io_stats())
+ std::fprintf(stderr, "; page cache held %.1f MB at the read, not %.1f MB",
+ (double) (ic.cached_bytes - ic_prev.cached_bytes) / 1e6,
+ (double) (ic.uncached_bytes - ic_prev.uncached_bytes) / 1e6);
+ if (src.io_prefetch())
+ std::fprintf(stderr, "; io prefetch: %llu read ahead (%.1f MB by pread), %llu used, %llu unused, %llu skipped "
+ "(cached), %llu dropped; decode waited %.1f ms in %llu fetches",
+ (unsigned long long) (ic.pf_read_blobs - ic_prev.pf_read_blobs),
+ (double) (ic.pread_bytes - ic_prev.pread_bytes) / 1e6,
+ (unsigned long long) (ic.pf_used - ic_prev.pf_used),
+ (unsigned long long) (ic.pf_unused - ic_prev.pf_unused),
+ (unsigned long long) (ic.pf_resident_skips - ic_prev.pf_resident_skips),
+ (unsigned long long) (ic.pf_dropped - ic_prev.pf_dropped),
+ (double) (ic.crit_us - ic_prev.crit_us) / 1e3,
+ (unsigned long long) (ic.crit_n - ic_prev.crit_n));
+ std::fprintf(stderr, "\n");
+ io_prev = io_now;
+ ic_prev = ic;
+ fb_prev = fb;
+ }
+ }
// 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)
@@ -10403,7 +10456,7 @@ int main(int argc, char** argv) {
if (!lent.empty()) {
const Clock::time_point tr = Clock::now();
for (const auto& [i, slot] : lent) { // D-4: queued, one wait (STRATA_REFILL_BLOCKING=1: each)
- const uint8_t* b = srcp->blob(i / g.n_expert, i % g.n_expert);
+ const uint8_t* b = srcp->blob_stable(i / g.n_expert, i % g.n_expert);
const int64_t nb = (int64_t) strata::kernels::cpu::expert_layout().blob_bytes(i / g.n_expert);
if (b == nullptr || !(refill_blocking() ? xcache.fill_slot_blocking(slot, b, err, nb)
: xcache.fill_slot_queued(slot, b, err, nb))) {
@@ -10822,7 +10875,7 @@ int main(int argc, char** argv) {
if (pin_blobs_on()) { // lock the batch's source pages (a file-backed arena on AMD; see pin_blobs)
std::vector<std::pair<uintptr_t, uintptr_t>> spans;
for (const Swap& s : swaps)
- if (const uint8_t* b = srcp->blob(s.layer, s.in))
+ if (const uint8_t* b = srcp->blob_stable(s.layer, s.in))
spans.emplace_back((uintptr_t) b,
(uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer));
pin_blobs(std::move(spans), pin_live);
@@ -10835,7 +10888,7 @@ int main(int argc, char** argv) {
for (const Swap& s : swaps) {
const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out;
const int32_t slot = host_res[out];
- const uint8_t* b = srcp->blob(s.layer, s.in);
+ const uint8_t* b = srcp->blob_stable(s.layer, s.in);
const size_t blob_n = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer);
// asynchronous: the copies run while the MTP drafts; the next window waits for them
if (slot < 0 || b == nullptr) {
@@ -11120,6 +11173,18 @@ int main(int argc, char** argv) {
fmb, rounds > 0 ? fmb / rounds : 0.0, rounds > 0 ? fms / rounds : 0.0,
fms > 0 ? fmb / fms : 0.0, src.gguf_mode() ? " (the GGUF in place)" : "",
(double) (fall0 - fbytes0) / 1e6);
+ if (src.io_stats()) {
+ const strata::core::FileExpertSource::IoCounters ic = src.io_counters();
+ std::printf("%-24s file reads: page cache held %.1f MB, not %.1f MB (mincore at the read); io prefetch %s: "
+ "%llu read ahead, %llu used, %llu unused, %llu skipped (cached), %llu dropped; pread %.1f MB in %llu calls "
+ "(%.2f ms each); decode waited %.1f ms/round in the fetches\n", "io path",
+ (double) ic.cached_bytes / 1e6, (double) ic.uncached_bytes / 1e6, src.io_prefetch() ? "on" : "off",
+ (unsigned long long) ic.pf_read_blobs, (unsigned long long) ic.pf_used,
+ (unsigned long long) ic.pf_unused, (unsigned long long) ic.pf_resident_skips,
+ (unsigned long long) ic.pf_dropped, (double) ic.pread_bytes / 1e6,
+ (unsigned long long) ic.pread_n, ic.pread_n > 0 ? (double) ic.pread_us / 1e3 / (double) ic.pread_n : 0.0,
+ rounds > 0 ? (double) ic.crit_us / 1e3 / rounds : 0.0);
+ }
if (drive.d.lookahead != nullptr)
std::printf("%-24s %lld experts warmed, %lld of the file tier's %lld blob reads had been warmed (%.1f%%); "
"predictor %.1f ms/round on its thread, %lld layers skipped (still busy)\n", "routing prefetch",
diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp
index 56590970a..88dd20e01 100644
--- a/tests/core/file_expert_source_test.cpp
+++ b/tests/core/file_expert_source_test.cpp
@@ -514,6 +514,67 @@ void test_host_memory() {
#endif
}
+// STRATA_IO_PREFETCH: the experts.bin file tier hands out the same bytes with the Linux I/O path on (whole-blob
+// preads, the read-ahead workers, the mapping for cached blobs), however the reads and the predictions interleave.
+void test_io_prefetch() {
+ using namespace strata::core;
+ using namespace strata::kernels::cpu;
+ constexpr int64_t layers = 3;
+ constexpr int64_t experts = 8;
+ const uint64_t layer_bytes = (uint64_t) experts * BLOB;
+ const uint64_t total = (uint64_t) layers * layer_bytes;
+ TempDirectory dir(fs::current_path());
+ std::string err;
+ require(expert_layout_load(dir.path.string(), layers, experts, err), "could not load canonical layout: " + err);
+ std::vector<uint8_t> bytes((size_t) total);
+ uint64_t x = 0xD1B54A32D192ED03ull;
+ for (uint8_t& b : bytes) {
+ x = x * 6364136223846793005ull + 1442695040888963407ull;
+ b = (uint8_t) (x >> 56);
+ }
+ {
+ std::ofstream out(dir.path / "experts.bin", std::ios::binary | std::ios::trunc);
+ out.write((const char*) bytes.data(), (std::streamsize) bytes.size());
+ require((bool) out, "could not write the synthetic experts.bin");
+ }
+ FileExpertSource source;
+ require(source.open(dir.path.string(), layers, experts, err), "could not map the synthetic pack: " + err);
+ source.set_io_prefetch(true, 3);
+#if defined(__linux__)
+ require(source.io_prefetch() && source.warms(), "io prefetch did not turn on");
+ // predictions for the next layers, some of them wrong or repeated, while the layers are read
+ for (int round = 0; round < 20; ++round)
+ for (int64_t l = 0; l < layers; ++l) {
+ const int64_t pred[5] = {(round + l) % experts, (round * 3 + 1) % experts, (round + 2 * l + 5) % experts,
+ (round + l) % experts, 7};
+ source.warm((l + 1) % layers, pred, 5);
+ source.begin_layer(l, nullptr, 0);
+ std::vector<int64_t> want = {(round + l) % experts, (round * 5 + 2) % experts, (l * 3 + round) % experts};
+ source.prefetch(l, want.data(), (int64_t) want.size());
+ for (int64_t e : want) {
+ const uint8_t* b = source.blob(l, e);
+ require(b != nullptr, "an io-prefetch blob lookup failed");
+ require(std::memcmp(b, bytes.data() + (size_t) (l * (int64_t) layer_bytes + e * (int64_t) BLOB), (size_t) BLOB) == 0,
+ "an io-prefetch blob differs from the file");
+ const uint8_t* s2 = source.blob_stable(l, e);
+ require(s2 != nullptr && std::memcmp(s2, bytes.data() + (size_t) (l * (int64_t) layer_bytes + e * (int64_t) BLOB), (size_t) BLOB) == 0,
+ "a blob_stable pointer differs from the file");
+ }
+ }
+ std::vector<uint8_t> copy((size_t) BLOB);
+ require(source.copy_blob(1, 6, copy.data()) &&
+ std::memcmp(copy.data(), bytes.data() + (size_t) (layer_bytes + 6 * BLOB), (size_t) BLOB) == 0,
+ "an io-prefetch copy_blob differs from the file");
+ const FileExpertSource::IoCounters c = source.io_counters();
+ require(c.cached_bytes + c.uncached_bytes > 0, "no residency counted");
+ std::cout << "io prefetch: " << c.pf_read_blobs << " read ahead, " << c.pf_used << " used, " << c.pf_resident_skips
+ << " skipped, pread " << c.pread_bytes << " B: bytes PASS\n";
+#else
+ require(!source.io_prefetch(), "io prefetch on a platform without it");
+#endif
+ source.close();
+}
+
void test_rotating_source(bool rotate, bool pin) {
using namespace strata::core;
using namespace strata::kernels::cpu;
@@ -613,6 +674,7 @@ int main(int argc, char** argv) {
test_host_memory();
test_canonical_layout();
test_unbuffered_reads();
+ test_io_prefetch();
#if defined(STRATA_NATIVE_EXPERTS)
test_native_variable_layout();
#endif