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++
Foresight swap: an exchange holds the experts whose bytes it moves, so no slot is served with another expert's bytes (#2134)
Niko1221277be72a7f65
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hppindex 5d16d9977..9ea481753 100644--- a/include/strata/core/expert_source.hpp+++ b/include/strata/core/expert_source.hpp@@ -625,6 +625,10 @@ public:/// (the caller's thread, between windows) points `out` there and drops the staging. Returns how many were applied.void commit_copies();int64_t commit_flip();+ /// #2134: the Foresight swap space (STRATA_FS_SLOTS), null = none. Each commit above holds the staged experts in it+ /// (ForesightSwap::hold: their slots are dropped and not refilled) while their bytes move, so no slot is served+ /// with bytes copied from a place an exchange rewrote.+ void set_foresight_swap(ForesightSwap* fs) { fs_swap_.store(fs, std::memory_order_release); }/// The compact copy's blob of `(layer, expert)`, or null; not counted as a read (any thread).const uint8_t* resident_blob(int64_t layer, int64_t expert) const;int64_t exchanges() const { return exchanges_; }@@ -871,6 +875,8 @@ private:std::vector<const uint8_t*> override_; ///< staged exchanges: an evicted expert read from its exchange bufferstruct Exchange { size_t in, out; int64_t q; uint64_t bytes; };std::vector<Exchange> staged_;+ std::atomic<ForesightSwap*> fs_swap_{nullptr}; ///< set_foresight_swap+ void fs_hold_staged(bool hold);std::vector<size_t> soft_in_; ///< soft_commit_exchanges: per `out` index, the `in` whose place it will take (SIZE_MAX: none)const uint8_t* xstage_dev_ = nullptr; ///< the exchange buffers' device alias (soft_commit_exchanges)uint8_t* xstage_ = nullptr; ///< exchange buffers, `xstage_cap_ x xstage_blob_`diff --git a/include/strata/core/foresight_swap.hpp b/include/strata/core/foresight_swap.hppindex 379f4079e..93f4c675a 100644--- a/include/strata/core/foresight_swap.hpp+++ b/include/strata/core/foresight_swap.hpp@@ -64,6 +64,9 @@ struct ForesightSwap {uint64_t hits = 0, copies = 0, busy = 0, over_budget = 0, pending = 0, predicted = 0; // (under smu_)bool verify = false; ///< STRATA_FS_VERIFY=1: read every landed slot back and compare (slow, tests)uint64_t verify_ok = 0, verify_bad = 0;+ uint64_t dropped = 0; ///< slots dropped because an exchange moved their expert's bytes (under smu_)+ static constexpr int16_t kHeld = -2; ///< `where`: an exchange is moving this expert's bytes, no copy now (#2134)+ static constexpr int32_t kDropped = -2; ///< Slot::expert: dropped by `hold`, reusable under the same depth rule/// Allocates the slots on each card and starts the filler. `card_of_layer[l]` indexes `devices` (CUDA ids).bool init(int slots_per_layer, int64_t layers, int64_t experts, const std::vector<int>& card_of_layer,@@ -79,6 +82,12 @@ struct ForesightSwap {/// with note_miss (the same slots, budget and reuse rule); a prediction only ever moves bytes, the plan is still made/// by the host pool and the model's own router stays authoritative.void predict(ExpertSource* src, int64_t layer, int32_t expert);+ /// #2134: the adaptive tier moves this expert's bytes in the RAM copy (an exchange, its two halves or a rotation),+ /// so a copy issued from its old place may land holding another expert's bytes. Its slot is dropped (never served;+ /// refilled only once `depth` windows finished, like any slot a window may still read; a copy in flight finishes+ /// first) and no copy of it is issued until `unhold`, when its bytes sit at their new place. Any thread.+ void hold(int64_t layer, int32_t expert);+ void unhold(int64_t layer, int32_t expert);std::string report() const;private:diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cppindex 1e3788d9e..16b677021 100644--- a/src/core/expert_source.cpp+++ b/src/core/expert_source.cpp@@ -3317,8 +3317,21 @@ bool FileExpertSource::soft_commit_exchanges() {return true;}+void FileExpertSource::fs_hold_staged(bool hold) {+ ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire);+ if (fs == nullptr || n_expert_ <= 0) return;+ for (const Exchange& x : staged_)+ for (const size_t i : {x.in, x.out}) {+ const int64_t layer = (int64_t) (i / (size_t) n_expert_);+ const int32_t expert = (int32_t) (i % (size_t) n_expert_);+ if (hold) fs->hold(layer, expert);+ else fs->unhold(layer, expert);+ }+}+int64_t FileExpertSource::commit_exchanges() {int64_t n = 0;+ fs_hold_staged(true); // #2134: both experts' bytes move (in's place takes out's bytes, out leaves its buffer)for (const Exchange& x : staged_)if (!soft_in_.empty()) soft_in_[x.out] = SIZE_MAX;for (const Exchange& x : staged_) {@@ -3341,12 +3354,14 @@ int64_t FileExpertSource::commit_exchanges() {}override_[x.out] = nullptr;}+ fs_hold_staged(false);staged_.clear();exchanges_ += n;return n;}void FileExpertSource::commit_copies() {+ fs_hold_staged(true); // #2134: held until commit_flip has pointed `out` at its new placeif (exchange_storage_.active()) return; // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copyfor (const Exchange& x : staged_) {const uint8_t* src = override_.empty() ? nullptr : override_[x.out];@@ -3359,6 +3374,7 @@ void FileExpertSource::commit_copies() {int64_t FileExpertSource::commit_flip() {int64_t n = 0;+ fs_hold_staged(true); // (already held by commit_copies; idempotent)for (const Exchange& x : staged_) {const uint8_t* src = override_[x.out];if (exchange_storage_.active()) { // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges@@ -3377,6 +3393,7 @@ int64_t FileExpertSource::commit_flip() {++n;override_[x.out] = nullptr;}+ fs_hold_staged(false);staged_.clear();exchanges_ += n;return n;@@ -4873,6 +4890,26 @@ bool ForesightSwap::take(int64_t layer, int32_t expert, unsigned long long& ptr)return true;}+void ForesightSwap::hold(int64_t layer, int32_t expert) {+ if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return;+ std::lock_guard<std::mutex> smu_lk(smu_);+ const size_t key = (size_t) (layer * n_expert + expert);+ const int s = where[key];+ where[key] = kHeld;+ if (s < 0) return;+ Slot& sl = slot[(size_t) (layer * slots + s)];+ sl.expert = kDropped; // `loading` and `last_ref` stay: a copy in flight and a window that read it are waited for+ sl.ready = false;+ ++dropped;+}++void ForesightSwap::unhold(int64_t layer, int32_t expert) {+ if (layer < 0 || layer >= n_layers || expert < 0 || expert >= n_expert) return;+ std::lock_guard<std::mutex> smu_lk(smu_);+ int16_t& w = where[(size_t) (layer * n_expert + expert)];+ if (w == kHeld) w = -1;+}+void ForesightSwap::note_miss(ExpertSource* src, int64_t layer, int32_t expert) {std::lock_guard<std::mutex> smu_lk(smu_);request_locked(src, layer, expert, false);@@ -4887,7 +4924,7 @@ void ForesightSwap::predict(ExpertSource* src, int64_t layer, int32_t expert) {void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t expert, bool predicted_copy) {if (failed.load(std::memory_order_relaxed)) return;const size_t key = (size_t) (layer * n_expert + expert);- if (where[key] >= 0) return; // already on its way+ if (where[key] != -1) return; // already on its way, or held by an exchange (#2134)const uint64_t now = completed.load(std::memory_order_acquire);if (admit > 1 && !predicted_copy) {if (now > miss_at[key] + 4) miss_cnt[key] = 0;@@ -4912,7 +4949,7 @@ void ForesightSwap::request_locked(ExpertSource* src, int64_t layer, int32_t expsl.loading = false;sl.ready = true;}- if (sl.expert < 0) { best = s; break; }+ if (sl.expert == -1) { best = s; break; } // never used (a dropped slot, kDropped, waits like a used one)if (sl.last_ref + (uint64_t) depth > now) continue;if (sl.last_ref < best_ref) { best_ref = sl.last_ref; best = s; }}@@ -4944,6 +4981,7 @@ std::string ForesightSwap::report() const {(unsigned long long) hits, (unsigned long long) copies, (unsigned long long) predicted,(unsigned long long) pending, (unsigned long long) busy, (unsigned long long) over_budget, verify ? "" : "");std::string r = buf;+ if (dropped > 0) r += ", " + std::to_string(dropped) + " dropped by exchanges";if (verify) r += ", verified " + std::to_string(verify_ok) + " ok / " + std::to_string(verify_bad) + " BAD";return r;}diff --git a/src/program/generate.cpp b/src/program/generate.cppindex 7dbb42264..2cd885c92 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -8326,12 +8326,15 @@ int main(int argc, char** argv) {fs_swap.reset(strata::core::foresight_swap_from_env(g.n_layers, g.n_expert, card, devs));drive.d.fs = fs_swap.get();if (fs_swap && drive.d.lookahead != nullptr) lookahead.set_foresight(fs_swap.get());+ src.set_foresight_swap(fs_swap.get()); // #2134: the exchanges hold the experts whose bytes they move}- // the look-ahead thread must not touch the swap space once it is gone (declared after it: destroyed first)+ // the look-ahead thread and the exchanges must not touch the swap space once it is gone (declared after it:+ // destroyed first)struct FsDetach {strata::core::RouterLookahead* la;- ~FsDetach() { la->set_foresight(nullptr); }- } fs_detach{&lookahead};+ strata::core::FileExpertSource* src;+ ~FsDetach() { la->set_foresight(nullptr); src->set_foresight_swap(nullptr); }+ } fs_detach{&lookahead, &src};drive.d.pcie_num = std::max(0, std::min(256, (int) (o.pcie_frac * 256.0 + 0.5)));const bool all_experts_resident = !host_res.empty() &&std::all_of(host_res.begin(), host_res.end(), [](int32_t r) { return r >= 0; });diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cppindex d3b213692..51a4ee1e8 100644--- a/tests/core/file_expert_source_test.cpp+++ b/tests/core/file_expert_source_test.cpp@@ -1,4 +1,5 @@#include "strata/core/expert_source.hpp"+#include "strata/core/foresight_swap.hpp"#include "strata/kernels/cpu/expert.hpp"#include "strata/kernels/cpu/expert_layout.hpp"@@ -26,6 +27,7 @@#include <stdexcept>#include <string>#include <system_error>+#include <thread>#include <utility>#include <vector>@@ -737,6 +739,97 @@ void test_rotating_source(bool rotate, bool pin) {require(!src.has_resident(0, 0) && !src.exchange_rotation(), "reopen retained residency");}+// #2134: a Foresight slot copied from an expert's RAM place before an exchange rewrote that place is never served; the+// experts an exchange moves get no copy between commit_copies and commit_flip; and a dropped slot that a window may+// still read waits `depth` finished windows before it is refilled.+void test_foresight_exchange(bool two_phase) {+ using namespace strata::core;+ using namespace strata::kernels::cpu;+#if defined(_WIN32)+ _putenv_s("STRATA_EXCHANGE_ROTATE", "0");+#else+ setenv("STRATA_EXCHANGE_ROTATE", "0", 1);+#endif+ TempDirectory dir;+ std::string err;+ require(expert_layout_load(dir.path.string(), 1, 5, err), err);+ const size_t bytes = (size_t) BLOB;+ std::vector<std::vector<uint8_t>> truth(5, std::vector<uint8_t>(bytes));+ {+ std::ofstream out(dir.path / "experts.bin", std::ios::binary);+ for (size_t e = 0; e < truth.size(); ++e) {+ for (size_t i = 0; i < bytes; ++i) truth[e][i] = (uint8_t) ((i * 131u + e * 37u) ^ (i >> 8));+ out.write((const char*) truth[e].data(), (std::streamsize) bytes);+ }+ require((bool) out, "fixture write failed");+ }+ FileExpertSource src;+ ExpertCache cache;+ require(src.open(dir.path.string(), 1, 5, err), err);+ require(cache.open(2, 1, 5, BLOB, err), err);+ for (int e : {2, 3}) {+ const int slot = cache.admit(0, e);+ require(slot >= 0 && cache.fill_slot_blocking(slot, truth[e].data(), err), err);+ }+ const std::vector<std::pair<int32_t, int32_t>> rank{{0,0},{0,1},{0,2},{0,3},{0,4}};+ require(src.pin_cache_complement(cache, err, true, {}, -1, 0, 2 * bytes, &rank), err);+ require(src.reserve_exchanges(1, err), err);+ require(src.pinned(0, 0), "expert 0 is not in the pinned RAM copy");+ int dev = 0;+ cudaGetDevice(&dev);+ ForesightSwap fs;+ require(fs.init(1, 1, 5, {0}, {dev}, err), err); // one slot, depth 4+ fs.verify = true;+ src.set_foresight_swap(&fs);+ unsigned long long ptr = 0;+ auto landed = [&](int32_t e) {+ for (int i = 0; i < 5000; ++i) {+ if (fs.take(0, e, ptr)) return true;+ std::this_thread::sleep_for(std::chrono::milliseconds(1));+ }+ return false;+ };+ fs.note_miss(&src, 0, 0); // expert 0 -> the slot, from its RAM place+ require(landed(0) && fs.verify_ok == 1, "the first copy did not land");+ // the adaptive tier swaps expert 0 into cache slot 0 and evicts expert 2 into the exchange buffer+ uint8_t* eviction = src.exchange_buffer(0);+ const uint8_t* prior = src.blob(0, 0);+ require(cudaMemcpy(eviction, cache.device_slot(0), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, "D2H eviction failed");+ require(src.stage_exchange(0, 0, 2, 0), "stage rejected");+ require(cache.fill_slot_blocking(0, prior, err), err);+ if (two_phase) {+ src.commit_copies(); // 0's place holds 2's bytes from here on+ const uint64_t c0 = fs.copies;+ fs.completed.fetch_add(8);+ fs.note_miss(&src, 0, 2);+ fs.predict(&src, 0, 0);+ require(fs.copies == c0, "an expert was copied while its exchange was half done");+ require(!fs.take(0, 0, ptr), "a slot dropped by commit_copies was served");+ require(src.commit_flip() == 1, "flip count wrong");+ } else {+ require(src.commit_exchanges() == 1, "commit count wrong");+ }+ require(fs.dropped == 1, "the exchange did not drop the slot");+ require(!fs.take(0, 0, ptr), "a slot copied before the exchange was served");+ if (!two_phase) { // the slot was served at window 0: no refill before window 0 + depth+ const uint64_t c0 = fs.copies, b0 = fs.busy;+ fs.note_miss(&src, 0, 2);+ require(fs.copies == c0 && fs.busy == b0 + 1, "a dropped slot was refilled while a window may still read it");+ fs.completed.fetch_add(4);+ }+ require(src.has_resident(0, 2) && !src.has_resident(0, 0), "residency wrong");+ fs.note_miss(&src, 0, 2); // expert 2, now at 0's old place+ require(landed(2), "the copy after the exchange did not land");+ std::vector<uint8_t> back(bytes);+ require(cudaMemcpy(back.data(), (const void*) ptr, bytes, cudaMemcpyDeviceToHost) == cudaSuccess && back == truth[2],+ "the slot does not hold expert 2's bytes");+ require(fs.verify_bad == 0 && fs.verify_ok == 2, "verify counted a bad slot");+ src.set_foresight_swap(nullptr);+ std::cout << "foresight exchange (" << (two_phase ? "commit_copies + commit_flip" : "commit_exchanges")+ << "): dropped " << fs.dropped << ", " << fs.report() << ": PASS\n";+ src.close();+}+} // namespaceint main(int argc, char** argv) {@@ -759,6 +852,8 @@ int main(int argc, char** argv) {test_rotating_source(false, true);test_rotating_source(true, true);test_rotating_source(true, false);+ test_foresight_exchange(false);+ test_foresight_exchange(true);}std::cout << "file_expert_source_test: PASS\n";return 0;