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++
ple: keep the SSD awake while rows are read (STRATA_SSD_KEEPALIVE)
BlueKingMuch4da8bfcbf9e0
diff --git a/include/strata/kernels/ngram.hpp b/include/strata/kernels/ngram.hppindex 29698422c..33f3eb020 100644--- a/include/strata/kernels/ngram.hpp+++ b/include/strata/kernels/ngram.hpp@@ -113,6 +113,11 @@ struct PleIoOptions {/// Mmap mode only (`--ple-io ram`): lock the whole mapped table in RAM at open, so no SSD read ever sits on/// the prompt or token path. Needs RAM for the full table. POSIX only (mlock); `locked()` reports the outcome.bool lock = false;+ /// Direct mode with the I/O worker only: keep the SSD awake while rows are asked for - one page of the table+ /// after this long without a read (0 = off), until `keepalive_window_s` after the last request for rows+ /// (see PleReader::set_keepalive).+ double keepalive_ms = 0;+ double keepalive_window_s = 60;};/// The PLE table. Held by pointer-to-impl so this header does not drag `<windows.h>` into everydiff --git a/include/strata/ngram/ple_reader.hpp b/include/strata/ngram/ple_reader.hppindex 0552ff1e4..721645c0a 100644--- a/include/strata/ngram/ple_reader.hpp+++ b/include/strata/ngram/ple_reader.hpp@@ -37,6 +37,8 @@ struct ReaderStats {double submit_us = 0; ///< time spent inside the read submission call (non-zero = it blocks)double read_us_sum = 0; ///< sum of per-read latencies (issue to completion)uint64_t late_injected = 0; ///< reads delayed by fault injection+ uint64_t keepalive_reads = 0; ///< pages read only to keep the SSD awake (not in `reads`, `bytes` or latencies)+ double keepalive_us_max = 0; ///< the slowest of themstd::vector<float> read_us; ///< last <= 65,536 read latencies, for percentilesdouble percentile(double q) const;};@@ -68,12 +70,22 @@ public:/// Block until every row of the ticket is in `out_raw`. Returns false on an I/O error (message in `err`).bool collect(Ticket t, std::string& err);+ /// Keep the SSD awake while the table is in use (io_thread mode only; call after `open`): when no read has+ /// gone out for `period_ms`, the worker reads one page of the table, until `window_s` after the last `issue`.+ /// Some SSDs drop into a power state after ~250 ms without a command and stall the next reads 50-150 ms+ /// (a WD_BLACK SN7100 on Windows 11; the NVMe idle timeouts of the power plan did not change it), which in+ /// decode happens after a few rounds whose rows all came from the row cache. 0 turns it off (the reader's+ /// default; generate turns it on, see STRATA_SSD_KEEPALIVE). A keep-alive read that fails turns it off.+ void set_keepalive(double period_ms, double window_s);+/// Fault injection for tests and for the plan's P2 exit check: every read completes no earlier than/// `delay_us` after it was issued. 0 disables.void set_injected_delay_us(double delay_us);- /// Read with no ticket in flight (the worker updates these while reads are outstanding).+ /// Read with no ticket in flight (the worker updates these while reads are outstanding; with the keep-alive+ /// on it may also be counting a keep-alive read - `snapshot` takes a consistent copy).const ReaderStats& stats() const;+ ReaderStats snapshot() const;void reset_stats();uint64_t cache_capacity() const;uint64_t cache_size() const;diff --git a/src/kernels/ngram.cpp b/src/kernels/ngram.cppindex 9def33097..4831f63d8 100644--- a/src/kernels/ngram.cpp+++ b/src/kernels/ngram.cpp@@ -198,6 +198,7 @@ bool PleTable::open(const std::string& gguf_path, std::string& err, const PleIoOclose();return false;}+ impl_->reader.set_keepalive(io.keepalive_ms, io.keepalive_window_s);impl_->n_rows = n_rows;}if (io.mode == PleIo::Mmap && io.lock && impl_->data != nullptr) {@@ -317,15 +318,18 @@ void PleTable::set_injected_delay_us(double us) { impl_->reader.set_injected_delstd::string PleTable::io_report() const {if (impl_->mode != PleIo::Direct || !impl_->reader.is_open()) return {};- const strata::ngram::ReaderStats& s = impl_->reader.stats();- char buf[320];- std::snprintf(buf, sizeof buf,+ const strata::ngram::ReaderStats s = impl_->reader.snapshot();+ char buf[400];+ int n = std::snprintf(buf, sizeof buf,"ple io: %llu rows, %.1f%% row-cache hits, %llu SSD reads (%.1f MB), read p50 %.0f us p99 %.0f us, ""blocked %.3f ms total (submit %.3f ms), cache %llu/%llu rows",(unsigned long long) s.requests, s.requests ? 100.0 * (double) s.cache_hits / (double) s.requests : 0.0,(unsigned long long) s.reads, (double) s.bytes / 1e6, s.percentile(0.5), s.percentile(0.99),s.wait_us / 1000.0, s.submit_us / 1000.0, (unsigned long long) impl_->reader.cache_size(),(unsigned long long) impl_->reader.cache_capacity());+ if (s.keepalive_reads > 0 && n > 0 && n < (int) sizeof buf)+ std::snprintf(buf + n, sizeof buf - (size_t) n, ", SSD kept awake by %llu reads (slowest %.1f ms)",+ (unsigned long long) s.keepalive_reads, s.keepalive_us_max / 1000.0);return buf;}diff --git a/src/ngram/ple_reader.cpp b/src/ngram/ple_reader.cppindex ff6d5139c..e7a3101f4 100644--- a/src/ngram/ple_reader.cpp+++ b/src/ngram/ple_reader.cpp@@ -2,6 +2,7 @@#include "strata/ngram/ple_reader.hpp"#include <algorithm>+#include <chrono>#include <condition_variable>#include <cstring>#include <deque>@@ -79,6 +80,7 @@ struct Job {uint32_t ticket = 0;std::vector<Use> uses;double issued_us = 0;+ bool keepalive = false;// no rows and no ticket: it only keeps the SSD awake (`set_keepalive`)};struct TicketState {@@ -108,6 +110,12 @@ struct PleReader::Impl {size_t ring_pos = 0;double delay_us = 0;std::string error;+ // the keep-alive (`set_keepalive`), steady-clock microseconds; `keep_us` 0 = off+ double keep_us = 0;+ double keep_window_us = 0;+ double last_issue_us = 0; // the last `issue`+ double last_read_us = 0; // the last read that went out, rows or keep-alive+ uint64_t rng = 0x9E3779B97F4A7C15ull;bool threaded = false;bool stop = false;@@ -141,7 +149,14 @@ struct PleReader::Impl {queue.pop_front();Job& j = inflight[s];j.issued_us = now_us();- if (!file.submit(j.offset, slot_buf(s), j.length, s, error)) {+ std::string kerr; // a keep-alive read that cannot go out must not fail the reader+ if (!file.submit(j.offset, slot_buf(s), j.length, s, j.keepalive ? kerr : error)) {+ if (j.keepalive) { // no more of them: the SSD may sleep as before+ keep_us = 0;+ j.keepalive = false;+ free_slots.push_back(s);+ continue;+ }j.uses.clear();auto it = tickets.find(j.ticket);if (it != tickets.end() && it->second.pending > 0) --it->second.pending;@@ -149,12 +164,35 @@ struct PleReader::Impl {cancel_queued();return false;}- stats.submit_us += now_us() - j.issued_us;- ++stats.reads;+ last_read_us = j.issued_us;+ if (!j.keepalive) { // a keep-alive read counts when it completes (`finish`)+ stats.submit_us += now_us() - j.issued_us;+ ++stats.reads;+ }}return true;}+ /// When the next keep-alive read is due, or < 0 when none is: it is off, the reader failed, or no rows+ /// were asked for within the window (then the SSD may sleep; the next `issue` re-arms it).+ double keepalive_due(double now) const {+ if (keep_us <= 0 || !error.empty() || last_issue_us <= 0 || now - last_issue_us > keep_window_us) return -1;+ return last_read_us + keep_us;+ }++ /// One page of the table, a different one each time, so the SSD really reads (not its controller's buffer).+ void queue_keepalive() {+ rng ^= rng << 13;+ rng ^= rng >> 7;+ rng ^= rng << 17;+ const uint64_t first = table_offset / PAGE, end = (table_offset + n_rows * (uint64_t) ROW_BYTES) / PAGE;+ Job j;+ j.offset = (first + (end > first ? rng % (end - first) : 0)) * PAGE;+ j.length = PAGE;+ j.keepalive = true;+ queue.push_back(std::move(j));+ }+bool finish(const Completion& c) {const uint32_t s = (uint32_t) c.tag;if (s >= inflight.size()) {@@ -163,6 +201,17 @@ struct PleReader::Impl {return false;}Job& j = inflight[s];+ if (j.keepalive) { // no rows: it counts once it is done, with how long it took;+ if (c.ok) { // a failed one turns the keep-alive off, not the reader+ ++stats.keepalive_reads;+ stats.keepalive_us_max = std::max(stats.keepalive_us_max, now_us() - j.issued_us);+ } else {+ keep_us = 0;+ }+ j.keepalive = false;+ free_slots.push_back(s);+ return error.empty() ? pump() : true;+ }if (!c.ok) {error = "PleReader: a table read failed";cancel_queued();@@ -246,7 +295,14 @@ struct PleReader::Impl {void worker_loop() {std::unique_lock<std::mutex> lk(mu);for (;;) {- cv_work.wait(lk, [&] { return stop || !queue.empty() || busy(); });+ // Idle: wait for work. While rows are being asked for, the wait ends in time for a keep-alive read.+ while (!(stop || !queue.empty() || busy())) {+ const double now = now_us();+ const double due = keepalive_due(now);+ if (due < 0) cv_work.wait(lk);+ else if (now >= due) queue_keepalive();+ else cv_work.wait_for(lk, std::chrono::microseconds(std::max<int64_t>(1000, (int64_t) (due - now))));+ }if (stop && !busy()) break;if (error.empty() && !pump() && error.empty()) error = "PleReader: submit failed";if (!delayed.empty() && !release_delayed() && error.empty()) error = "PleReader: read failed";@@ -293,6 +349,10 @@ bool PleReader::open(const std::string& path, uint64_t table_offset, uint64_t n_for (uint32_t s = max_inflight; s-- > 0;) impl_->free_slots.push_back(s);impl_->cache.init(cache_rows);impl_->error.clear();+ impl_->keep_us = 0;+ impl_->last_issue_us = impl_->last_read_us = 0;+ impl_->rng = 0x9E3779B97F4A7C15ull ^ (uint64_t) now_us();+ if (impl_->rng == 0) impl_->rng = 1;reset_stats();impl_->stop = false;impl_->threaded = io_thread;@@ -346,6 +406,8 @@ void PleReader::close() {m.cache.init(0);m.threaded = false;m.stop = false;+ m.keep_us = 0;+ m.last_issue_us = m.last_read_us = 0;}bool PleReader::is_open() const { return impl_->file.is_open(); }@@ -356,6 +418,9 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_if (m.threaded) lk.lock();const uint32_t id = m.next_ticket++;if (m.next_ticket == 0) m.next_ticket = 1;+ const double now = now_us();+ const bool rearm = m.keep_us > 0 && (m.last_issue_us <= 0 || now - m.last_issue_us > m.keep_window_us);+ m.last_issue_us = now;TicketState& ts = m.tickets[id];std::unordered_map<uint64_t, size_t> by_page; // aligned offset -> index in `jobs`std::vector<Job> jobs;@@ -400,6 +465,8 @@ PleReader::Ticket PleReader::issue(const uint32_t* rows, size_t n, uint8_t* out_if (has_jobs) {m.cv_work.notify_one();m.file.wake(); // in case the worker is blocked in the port+ } else if (rearm) {+ m.cv_work.notify_one(); // the keep-alive had lapsed: start it again}} else if (!m.pump() && m.error.empty()) {m.error = "PleReader: submit failed";@@ -439,14 +506,33 @@ bool PleReader::collect(Ticket t, std::string& err) {return true;}+void PleReader::set_keepalive(double period_ms, double window_s) {+ Impl& m = *impl_;+ {+ std::lock_guard<std::mutex> lk(m.mu);+ m.keep_us = m.threaded && period_ms > 0 ? period_ms * 1000.0 : 0.0;+ m.keep_window_us = window_s > 0 ? window_s * 1e6 : 0.0;+ }+ m.cv_work.notify_all();+}+void PleReader::set_injected_delay_us(double delay_us) {std::lock_guard<std::mutex> lk(impl_->mu);impl_->delay_us = delay_us < 0 ? 0 : delay_us;}const ReaderStats& PleReader::stats() const { return impl_->stats; }+ReaderStats PleReader::snapshot() const {+ Impl& m = *impl_;+ std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);+ if (m.threaded) lk.lock();+ return m.stats;+}void PleReader::reset_stats() {- impl_->stats = ReaderStats{};- impl_->ring_pos = 0;+ Impl& m = *impl_;+ std::unique_lock<std::mutex> lk(m.mu, std::defer_lock);+ if (m.threaded) lk.lock(); // the worker may be counting a keep-alive read+ m.stats = ReaderStats{};+ m.ring_pos = 0;}uint64_t PleReader::cache_capacity() const { return impl_->cache.sets * WAYS; }uint64_t PleReader::cache_size() const { return impl_->cache.used; }diff --git a/src/ngram/ple_reader_test.cpp b/src/ngram/ple_reader_test.cppindex 37e55f3b5..86b48624a 100644--- a/src/ngram/ple_reader_test.cpp+++ b/src/ngram/ple_reader_test.cpp@@ -10,6 +10,7 @@#include "strata/ngram/ple_reader.hpp"#include "strata/platform/direct_file.hpp"+#include <chrono>#include <cstdio>#include <cstdlib>#include <cstring>@@ -18,6 +19,7 @@#include <random>#include <sstream>#include <string>+#include <thread>#include <vector>namespace ng = strata::ngram;@@ -135,6 +137,56 @@ int selftest(const std::string& dir) {CHECK(now_us() - t0 >= 3000, "injected delay not observed (%.0f us)", now_us() - t0);CHECK(rd.stats().late_injected > 0, "no read was held back");}+ // keep-alive: while rows are asked for, a page goes out after `period` without a read; it stops once the+ // window after the last issue has passed, starts again with the next issue (even one the row cache serves),+ // and never shows up as a row read or changes a row+ {+ ng::PleReader rd;+ std::string err;+ CHECK(rd.open(path, HEADER, N, 16, 4096, err, true), "open: %s", err.c_str());+ rd.set_keepalive(20.0, 0.5);+ std::vector<uint32_t> rows(16);+ for (auto& r : rows) r = rng() % N;+ check_rows(rd, rows, N, "keep-alive, first ticket");+ const uint64_t reads0 = rd.snapshot().reads;+ const auto nap = [](int ms) { std::this_thread::sleep_for(std::chrono::milliseconds(ms)); };+ nap(300);+ const uint64_t k1 = rd.snapshot().keepalive_reads;+ CHECK(k1 >= 8 && k1 <= 20, "keep-alive: %llu reads in 300 ms at a 20 ms period", (unsigned long long) k1);+ CHECK(rd.snapshot().reads == reads0, "keep-alive reads were counted as row reads");+ nap(600); // the 0.5 s window has passed+ const uint64_t k2 = rd.snapshot().keepalive_reads;+ nap(300);+ const uint64_t k3 = rd.snapshot().keepalive_reads;+ CHECK(k3 == k2, "keep-alive went on after the window (%llu -> %llu)", (unsigned long long) k2,+ (unsigned long long) k3);+ CHECK(k2 <= k1 + 20, "keep-alive: %llu reads by the end of a 0.5 s window", (unsigned long long) k2);+ check_rows(rd, rows, N, "keep-alive, cached ticket"); // the row cache serves all 16: no row read+ CHECK(rd.snapshot().reads == reads0, "cached rows were read again");+ nap(200);+ CHECK(rd.snapshot().keepalive_reads >= k3 + 5, "the keep-alive did not start again (%llu -> %llu)",+ (unsigned long long) k3, (unsigned long long) rd.snapshot().keepalive_reads);+ std::vector<uint32_t> more(2000);+ for (auto& r : more) r = rng() % N;+ check_rows(rd, more, N, "keep-alive, rows afterwards");+ rd.set_keepalive(0, 0.5); // off+ const uint64_t k4 = rd.snapshot().keepalive_reads;+ nap(200);+ CHECK(rd.snapshot().keepalive_reads <= k4 + 1, "keep-alive went on after it was turned off");+ rd.reset_stats();+ CHECK(rd.snapshot().keepalive_reads == 0 && rd.snapshot().keepalive_us_max == 0, "reset_stats kept keep-alive counts");+ }+ { // the caller's thread does the reads: no worker, so no keep-alive+ ng::PleReader rd;+ std::string err;+ CHECK(rd.open(path, HEADER, N, 16, 0, err, false), "open: %s", err.c_str());+ rd.set_keepalive(20.0, 1.0);+ std::vector<uint32_t> rows(16);+ for (auto& r : rows) r = rng() % N;+ check_rows(rd, rows, N, "keep-alive, caller thread");+ std::this_thread::sleep_for(std::chrono::milliseconds(150));+ CHECK(rd.snapshot().keepalive_reads == 0, "keep-alive without the worker thread");+ }std::filesystem::remove(path);std::printf("ple_reader selftest: %s\n", g_fail ? "FAILED" : "OK");return g_fail ? 1 : 0;diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 0eb5ee845..9a468b4e3 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -1923,6 +1923,17 @@ int main(int argc, char** argv) {pio.max_inflight = (uint32_t) o.ple_inflight;pio.cache_rows = (uint64_t) o.ple_row_cache;pio.io_thread = !o.ple_sync_submit;+ // Keep the SSD awake while rows are being asked for (PleReader::set_keepalive): some SSDs stall the first+ // reads 50-150 ms after ~250 ms without a command. STRATA_SSD_KEEPALIVE = ms without a read before one+ // page is read anyway (default 100, 0 = off), STRATA_SSD_KEEPALIVE_WINDOW = seconds after the last row+ // request that this goes on (default 60; then the SSD may sleep until the next request).+ {+ const char* ka = std::getenv("STRATA_SSD_KEEPALIVE");+ const char* kw = std::getenv("STRATA_SSD_KEEPALIVE_WINDOW");+ pio.keepalive_ms = ka != nullptr && *ka ? std::clamp(std::atof(ka), 0.0, 10000.0) : 100.0;+ pio.keepalive_window_s = kw != nullptr && *kw ? std::clamp(std::atof(kw), 1.0, 86400.0) : 60.0;+ if (pio.mode != strata::kernels::PleIo::Direct || !pio.io_thread) pio.keepalive_ms = 0;+ }if (!ple_table.open(o.ple_gguf, err, pio)) {std::fprintf(stderr, "strata generate: %s\n", err.c_str());return 1;@@ -1931,6 +1942,12 @@ int main(int argc, char** argv) {std::fprintf(stderr, "strata generate: PLE table %s (--ple-io ram) in %.1f s\n",ple_table.locked() ? "locked in RAM" : "loaded (not locked)",std::chrono::duration<double>(Clock::now() - tpl).count());+ if (pio.keepalive_ms > 0)+ std::fprintf(stderr, "strata generate: the SSD is kept awake while rows are read: one page of the table after "+ "%.0f ms without a read, until %.0f s after the last request "+ "(STRATA_SSD_KEEPALIVE=0 turns it off)\n", pio.keepalive_ms, pio.keepalive_window_s);+ else if (pio.mode == strata::kernels::PleIo::Direct)+ std::fprintf(stderr, "strata generate: SSD keep-alive off: the SSD may fall asleep between reads\n");const strata::core::WeightRef* wk = wt.find("blk.1.ple_key.weight");const strata::core::WeightRef* wv = wt.find("blk.1.ple_value.weight");const strata::core::WeightRef* wnk = wt.find("blk.1.ple_norm_key.weight");