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

perf: opt in to resident expert exchange buffer rotation

David1e6cec80d1c7
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c7b44c3e8..fab751474 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -423,6 +423,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP)
src/core/conversation_snapshot.cpp src/core/conversation_state.cpp src/core/conversation_memory.cpp src/core/peer_experts.cpp)
target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include)
target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target})
+ if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp")
+ add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp)
+ target_include_directories(exchange_storage_test PRIVATE include)
+ target_link_libraries(exchange_storage_test PRIVATE Threads::Threads)
+ add_test(NAME exchange_storage_test COMMAND exchange_storage_test)
+ set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60)
+ endif()
+
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp")
enable_testing()
add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp)
diff --git a/bench/results/exchange-rotation-ab.json b/bench/results/exchange-rotation-ab.json
new file mode 100644
index 000000000..6c11cd2a8
--- /dev/null
+++ b/bench/results/exchange-rotation-ab.json
@@ -0,0 +1,65 @@
+{
+ "kind": "historical-native-same-binary-ab",
+ "date": "2026-10-03",
+ "qualification": "Original rotation build, not a new benchmark of the rebased patch.",
+ "source_commit": "1a50d913bf910a1f63fbc1a0788a7083e3ca5f8c",
+ "engine_sha256": "d14ed6b69a1814ce4b5c08932a47d6921a55fa0aa8dea50427ccf0782d1ad997",
+ "source_receipt_url": "https://github.com/CC-David-CC/Strata-a5500/blob/6beb57fd61ff7e15e48913e59f6a3558c87c8e63/bench/results/2026-10-03-q8-buffer-rotation/summary.json",
+ "source_receipt_sha256": "19ee56a37aa1c68ae2833da63af212e6f53f2a3ca156bceae94727b8e60d2ac9",
+ "hardware": "RTX PRO 6000 Blackwell Workstation Edition 96GB; Ryzen 9 7950X; 128GB installed RAM",
+ "weights": "Q8_0",
+ "kv": "fp16",
+ "task": "coding",
+ "mode": "target-only; MTP drafting and suffix drafting disabled",
+ "allocated_context": 73728,
+ "gpu_expert_slots": 16400,
+ "resident_complement_gib": 39.77,
+ "expert_blob_bytes": 5222400,
+ "adaptive_swaps": 96,
+ "wait_for_completion": true,
+ "output_tokens_identical": true,
+ "first_differing_output_index": null,
+ "token_evidence": "Original raw-ID comparison plus matching published token-count and serialized-token SHA-256 receipts; raw token arrays are not included in the published summary.",
+ "arms": [
+ {
+ "label": "serial-rotate0-r1",
+ "rotation": 0,
+ "prompt_sha256": "a8024ab0ba6b95ae36f2b9bd621723ed0f9b98e64ad82b94d389cdacb2232896",
+ "input_tokens": 65536,
+ "output_tokens": 1024,
+ "output_token_ids_sha256_json": "b1f0b9db418f250daa39ec15507b7e60afa8168c32bd23e7e7fdab178f95c25a",
+ "decode_tokens_per_second": 70.0741115848109,
+ "effective_output_tokens_per_second": 35.20482743535113,
+ "decode_milliseconds": 14613.1,
+ "resident_exchanges": 2377,
+ "rotated_blocks": 0,
+ "avoided_memcpy_payload_bytes": 0,
+ "diagnostics": [
+ "strata decode timing: 1024 windows, avg T 1.00, 1.00 tokens/window, 14.27 ms/window = verify 12.36 (GPU-reach wait 9.31 + per-layer host 2.53 [plan 0.03 actq 0.02 jobs 0.06 CPU 2.34] + stage 0.00) + commit/emit 0.02 + draft 0.00; per layer-window: CPU experts 0.34 (0.34 entries), VRAM hits 9.56, PCIe 0.11",
+ "strata serve: resident RAM: 39.77 GiB of experts in RAM, 2377 exchanged with the VRAM tier, 0 blob reads from the file",
+ "strata serve: expert tiers: GPU 469667 hits this request; since the start RAM 89645 blobs, files 0 blobs 85652.6 MB read (the GGUF in place)"
+ ]
+ },
+ {
+ "label": "serial-rotate1-r1",
+ "rotation": 1,
+ "prompt_sha256": "a8024ab0ba6b95ae36f2b9bd621723ed0f9b98e64ad82b94d389cdacb2232896",
+ "input_tokens": 65536,
+ "output_tokens": 1024,
+ "output_token_ids_sha256_json": "b1f0b9db418f250daa39ec15507b7e60afa8168c32bd23e7e7fdab178f95c25a",
+ "decode_tokens_per_second": 75.38724306496259,
+ "effective_output_tokens_per_second": 36.48173245764955,
+ "decode_milliseconds": 13583.2,
+ "resident_exchanges": 2377,
+ "rotated_blocks": 2377,
+ "avoided_memcpy_payload_bytes": 12413644800,
+ "diagnostics": [
+ "strata decode timing: 1024 windows, avg T 1.00, 1.00 tokens/window, 13.26 ms/window = verify 12.36 (GPU-reach wait 9.28 + per-layer host 2.56 [plan 0.04 actq 0.02 jobs 0.07 CPU 2.33] + stage 0.00) + commit/emit 0.02 + draft 0.00; per layer-window: CPU experts 0.34 (0.34 entries), VRAM hits 9.56, PCIe 0.11",
+ "strata serve: resident RAM: 39.77 GiB of experts in RAM, 2377 exchanged with the VRAM tier, 0 blob reads from the file",
+ "strata serve: exchange rotation: 2377 blocks, 12413644800 host memcpy bytes avoided (cumulative payload)",
+ "strata serve: expert tiers: GPU 469667 hits this request; since the start RAM 89645 blobs, files 0 blobs 85652.6 MB read (the GGUF in place)"
+ ]
+ }
+ ],
+ "limitation": "One pair on the original binary. No universal speedup, new-main throughput, or speculative-path token-parity claim."
+}
diff --git a/docs/EXCHANGE_ROTATION.md b/docs/EXCHANGE_ROTATION.md
new file mode 100644
index 000000000..567200611
--- /dev/null
+++ b/docs/EXCHANGE_ROTATION.md
@@ -0,0 +1,106 @@
+# Resident expert exchange buffer rotation
+
+When the resident RAM complement exchanges an expert with the GPU cache, the
+evicted expert lands in a temporary host buffer. The existing path then copies
+those bytes into the promoted expert's old RAM slot. Rotation removes that last
+host copy: the temporary buffer becomes resident, and the old RAM slot becomes
+the next temporary buffer.
+
+## Enable
+
+Rotation is **off by default**. Set `STRATA_EXCHANGE_ROTATE=1` before starting the
+engine with your existing arguments:
+
+```bash
+export STRATA_EXCHANGE_ROTATE=1
+```
+
+```powershell
+$env:STRATA_EXCHANGE_ROTATE = '1'
+```
+
+Only the exact value `1` opts in. Set it to `0` or remove it to restore the copy
+path. This setting does not select resident RAM mode or change any preset.
+It applies only when all layers have equal-size expert blocks, the resident
+complement is fully pinned and GPU-mapped, and the exchange buffers can also be
+pinned and mapped. Other layouts keep the copy path and log why rotation could
+not be enabled. Configurations without a resident complement do not use it.
+
+The startup diagnostic confirms activation:
+
+```text
+FileExpertSource: exchange buffer rotation enabled: ...; no host commit memcpy
+```
+
+Serving diagnostics report the cumulative rotated block count and avoided
+`memcpy` payload bytes. This counts the copied payload once, not read plus write
+traffic, and does not include the GPU transfers, which still occur.
+
+## Ownership and synchronization
+
+The original allocations own their memory until `FileExpertSource::close()`.
+Rotation updates slot ownership and keeps each host pointer paired with its GPU
+alias. Atomic slot IDs let background residency queries observe those immutable
+pairs. Compute readers and GPU transfers must still finish before the existing
+serialized commit; rotation adds no overlapping compute or new synchronization
+policy. Reserve the maximum exchange capacity before rotation starts: growing a
+live exchange arena is rejected because it can now hold resident experts.
+
+## Tests
+
+The ownership test can run without CUDA:
+
+```bash
+g++ -std=c++20 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer \
+ -pthread -Iinclude tests/core/exchange_storage_test.cpp -o /tmp/exchange_storage_test
+/tmp/exchange_storage_test
+```
+
+With an existing CUDA build configured:
+
+```bash
+cmake --build build --target strata exchange_storage_test file_expert_source_test
+ctest --test-dir build -R '^(exchange_storage_test|file_expert_source_test)$' --output-on-failure
+./build/file_expert_source_test --rotation-gpu
+compute-sanitizer --tool memcheck --error-exitcode 71 ./build/file_expert_source_test --rotation-gpu
+```
+
+The CPU test checks byte preservation, pointer/alias ownership, guards, invalid
+operations and concurrent residency queries across 12,304 exchanges. The CUDA
+fixture performs 64 exchanges in each of three modes: copy with pinned RAM,
+rotation with pinned RAM, and requested rotation with pageable RAM (fallback).
+It checks exact bytes, GPU alias reads, file fallback, capacity, and close/reopen.
+The GPU fixture is explicit; the ordinary CTest invocation does not run it.
+
+On 2026-10-04, the clean patch on upstream
+`6f32ec070f23ced9f50e704d854d775da52591ab` built on Linux with GCC 15.2 and CUDA
+13.3 for an RTX 4090. Both CTest tests, the ASan/UBSan ownership test, and the
+CUDA fixture passed. Compute Sanitizer reported **0 errors**. AMD and Windows
+GPU execution were not tested for this patch.
+
+## One native token-identical A/B
+
+This is one existing measurement from the original rotation implementation at
+`1a50d913bf910a1f63fbc1a0788a7083e3ca5f8c`, dated 2026-10-03. It is **not a new
+full-model benchmark of the clean patch on current main**. The available model
+packs for the fresh checks have mixed expert block sizes and cannot activate
+this deliberately narrow path.
+
+Both arms used the same native binary and coding prompt: Q8_0 weights, FP16 KV,
+65,536 input tokens, 1,024 output tokens, target-only decoding (MTP and suffix
+drafting disabled), 16,400 GPU expert slots, and a 39.77 GiB pinned RAM
+complement. Hardware: RTX PRO 6000 Blackwell 96GB, Ryzen 9 7950X, 128GB RAM.
+
+| Rotation | Decode tokens/s | Resident exchanges | Avoided host copy payload | Output token IDs |
+|---|---:|---:|---:|---|
+| `0` | 70.07 | 2,377 | 0 bytes | 1,024, identical |
+| `1` | 75.39 | 2,377 | 12,413,644,800 bytes | 1,024, identical |
+
+The [A/B receipt](../bench/results/exchange-rotation-ab.json) contains the binary,
+prompt and token hashes, diagnostics, and a pinned public source receipt. Both
+token hashes are
+`b1f0b9db418f250daa39ec15507b7e60afa8168c32bd23e7e7fdab178f95c25a`.
+The original comparison reported no differing token; its published summary
+retains counts and hashes, not raw token arrays. This single pair establishes
+the recorded parity result, not a general speedup or speculative-decoding
+parity guarantee.
diff --git a/include/strata/core/exchange_storage.hpp b/include/strata/core/exchange_storage.hpp
new file mode 100644
index 000000000..7e50d745d
--- /dev/null
+++ b/include/strata/core/exchange_storage.hpp
@@ -0,0 +1,114 @@
+#pragma once
+
+#include <atomic>
+#include <cstddef>
+#include <memory>
+#include <utility>
+#include <cstdint>
+#include <limits>
+#include <string>
+#include <vector>
+
+namespace strata::core::detail {
+
+// Non-owning views: the complement and exchange allocations retain their original
+// owners until FileExpertSource::close(). Ownership changes via slot IDs; the
+// physical buffer addresses, bytes and CUDA aliases stay in place. This first path requires uniform, fully mapped/pinned expert slots.
+class ExchangeStorage {
+public:
+ struct View {
+ uint8_t* host = nullptr;
+ const uint8_t* device = nullptr;
+ };
+
+ bool initialize(const std::vector<uint64_t>& offsets, uint8_t* resident_host,
+ const uint8_t* resident_device, uint64_t resident_bytes,
+ uint8_t* exchange_host, const uint8_t* exchange_device,
+ size_t count, size_t blob_bytes, std::string& error) {
+ error.clear();
+ if (active()) { error = "exchange storage already initialized"; return false; }
+ if (!resident_host || !resident_device || !exchange_host || !exchange_device ||
+ !blob_bytes || !count || !resident_bytes || resident_bytes % blob_bytes ||
+ count > std::numeric_limits<size_t>::max() / blob_bytes) {
+ error = "invalid uniform mapped exchange geometry"; return false;
+ }
+ const size_t resident_slots = (size_t)(resident_bytes / blob_bytes);
+ if (resident_slots > std::numeric_limits<size_t>::max() - count) {
+ error = "exchange slot count overflow"; return false;
+ }
+ auto experts = std::make_unique<std::atomic<size_t>[]>(offsets.size());
+ std::vector<size_t> spares(count);
+ std::vector<View> buffers(resident_slots + count);
+ for (size_t slot = 0; slot < resident_slots; ++slot)
+ buffers[slot] = {resident_host + slot * blob_bytes, resident_device + slot * blob_bytes};
+ std::vector<bool> used(resident_slots, false);
+ for (size_t i = 0; i < offsets.size(); ++i) {
+ const uint64_t at = offsets[i];
+ experts[i].store(kAbsent, std::memory_order_relaxed);
+ if (at == ~uint64_t{0}) continue;
+ if (at >= resident_bytes || at % blob_bytes || used[(size_t)(at / blob_bytes)]) {
+ error = "invalid or duplicate resident slot"; return false;
+ }
+ used[(size_t)(at / blob_bytes)] = true;
+ experts[i].store((size_t)(at / blob_bytes), std::memory_order_relaxed);
+ }
+ for (bool present : used) if (!present) {
+ error = "unassigned resident slot"; return false;
+ }
+ for (size_t q = 0; q < count; ++q) {
+ spares[q] = resident_slots + q;
+ buffers[spares[q]] = {exchange_host + q * blob_bytes, exchange_device + q * blob_bytes};
+ }
+ experts_ = std::move(experts);
+ expert_count_ = offsets.size();
+ spares_.swap(spares);
+ buffers_.swap(buffers);
+ blob_bytes_ = blob_bytes;
+ return true;
+ }
+
+ bool active() const { return blob_bytes_ != 0; }
+ View resident(size_t expert) const {
+ if (expert >= expert_count_) return {};
+ const size_t slot = experts_[expert].load(std::memory_order_acquire);
+ return slot != kAbsent ? buffers_[slot] : View{};
+ }
+ View spare(size_t q) const { return q < spares_.size() ? buffers_[spares_[q]] : View{}; }
+
+ // Only after every CPU reader and H2D copy of `in` has completed, and `out`
+ // has landed in spare(q). No allocation, memcpy, or CUDA operation here.
+ bool commit(size_t in, size_t out, size_t q, const uint8_t* staged, size_t bytes) {
+ if (in >= expert_count_ || out >= expert_count_ || q >= spares_.size() ||
+ !staged || bytes != blob_bytes_) return false;
+ const size_t incoming_slot = experts_[in].load(std::memory_order_acquire);
+ if (incoming_slot == kAbsent || experts_[out].load(std::memory_order_acquire) != kAbsent ||
+ buffers_[spares_[q]].host != staged) return false;
+ // A background router lookahead can query residency to skip redundant
+ // file prefetches. Publish one atomic slot ID; the pointer/alias pair is
+ // immutable. Actual compute readers still obey the completion contract.
+ experts_[out].store(spares_[q], std::memory_order_release);
+ spares_[q] = incoming_slot;
+ experts_[in].store(kAbsent, std::memory_order_release);
+ ++exchanges_;
+ avoided_bytes_ += bytes;
+ return true;
+ }
+
+ uint64_t exchanges() const { return exchanges_; }
+ uint64_t avoided_bytes() const { return avoided_bytes_; } // memcpy payload, not read+write total
+ void clear() {
+ experts_.reset(); expert_count_ = 0; buffers_.clear(); spares_.clear();
+ blob_bytes_ = 0; exchanges_ = avoided_bytes_ = 0;
+ }
+
+private:
+ static constexpr size_t kAbsent = std::numeric_limits<size_t>::max();
+ std::unique_ptr<std::atomic<size_t>[]> experts_;
+ size_t expert_count_ = 0;
+ std::vector<View> buffers_; // immutable physical addresses after initialize
+ std::vector<size_t> spares_; // touched only by the serialized cache manager
+ size_t blob_bytes_ = 0;
+ uint64_t exchanges_ = 0, avoided_bytes_ = 0;
+};
+
+} // namespace strata::core::detail
diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp
index 9bc1e6b46..14ac67d14 100644
--- a/include/strata/core/expert_source.hpp
+++ b/include/strata/core/expert_source.hpp
@@ -22,6 +22,7 @@
#pragma once
#include "strata/core/expert_cache.hpp"
+#include "strata/core/exchange_storage.hpp"
#include "strata/core/hit_hook.hpp"
#include "strata/kernels/cpu/pool.hpp"
@@ -475,6 +476,7 @@ public:
// buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU
// computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into
// `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file.
+ // STRATA_EXCHANGE_ROTATE=1 can instead transfer buffer ownership (uniform, fully pinned/mapped slots).
/// Whether the compact copy holds `(layer, expert)`.
bool has_resident(int64_t layer, int64_t expert) const;
/// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`.
@@ -496,6 +498,9 @@ public:
/// 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_; }
+ bool exchange_rotation() const { return exchange_storage_.active(); }
+ uint64_t rotated_exchanges() const { return exchange_storage_.exchanges(); }
+ uint64_t avoided_exchange_copy_bytes() const { return exchange_storage_.avoided_bytes(); }
/// 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); }
@@ -550,6 +555,7 @@ public:
int64_t reads() const override { return reads_; }
private:
+ const uint8_t* resident_blob(size_t index) const;
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;
@@ -619,6 +625,7 @@ private:
const uint8_t* complement_device_ = nullptr;
uint64_t complement_bytes_ = 0;
std::vector<uint64_t> complement_offsets_;
+ detail::ExchangeStorage exchange_storage_; // authoritative when active; original arenas still own memory
bool complement_pinned_ = false;
bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered
uint64_t complement_pin_limit_ = 0;
diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp
index b5b67e41e..a9cf15d1c 100644
--- a/src/core/expert_source.cpp
+++ b/src/core/expert_source.cpp
@@ -526,6 +526,7 @@ void FileExpertSource::close() {
xstage_blob_ = 0;
override_.clear();
staged_.clear();
+ exchange_storage_.clear();
exchanges_ = 0;
file_reads_.store(0);
complement_arena_ = nullptr;
@@ -823,7 +824,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n
const int64_t e = experts[i];
if (e < 0 || e >= n_expert_) continue;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
- if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
+ if (complement_ready_ && resident_blob(index) != nullptr)
continue; // in the RAM copy
if (!override_.empty() && override_[index] != nullptr) continue;
size_t v = 0;
@@ -1142,7 +1143,7 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) {
const int64_t e = experts[j];
if (e < 0 || e >= n_expert_) continue;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e;
- if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement)
+ if (complement_ready_ && resident_blob(index) != nullptr)
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);
@@ -1285,7 +1286,7 @@ 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;
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)
+ if (complement_ready_ && resident_blob(index) != nullptr)
return false;
return override_.empty() || override_[index] == nullptr;
}
@@ -1297,7 +1298,7 @@ bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) {
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);
+ resident_blob(index);
if (held == nullptr && !override_.empty()) held = override_[index];
if (held != nullptr) {
std::memcpy(dst, held, (size_t) bytes);
@@ -1726,16 +1727,25 @@ bool FileExpertSource::pin_cache_complement(
return true;
}
+const uint8_t* FileExpertSource::resident_blob(size_t index) const {
+ if (exchange_storage_.active()) return exchange_storage_.resident(index).host;
+ return detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr);
+}
+
bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const {
if (!complement_ready_ || 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;
- return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement;
+ return resident_blob(index) != nullptr;
}
bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) {
err.clear();
if (n <= xstage_cap_) return true;
if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; }
+ if (exchange_storage_.active()) {
+ err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation";
+ return false; // the original exchange allocation can now contain live resident experts
+ }
uint64_t blob = 0;
for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b);
if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; }
@@ -1745,9 +1755,18 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) {
xstage_ = nullptr;
xstage_cap_ = 0;
}
+ if ((uint64_t)n > std::numeric_limits<size_t>::max() / blob) {
+ err = "FileExpertSource: exchange allocation size overflow"; return false;
+ }
+ const char* rotate_env = std::getenv("STRATA_EXCHANGE_ROTATE");
+ const bool requested = rotate_env && std::strcmp(rotate_env, "1") == 0;
+ const bool uniform = std::all_of(layer_blob_bytes_.begin(), layer_blob_bytes_.end(),
+ [blob](uint64_t b) { return b == blob; });
+ const bool eligible = requested && uniform && complement_pinned_ && !complement_partial_ &&
+ complement_host_ && complement_device_ && complement_bytes_ > 0;
const size_t total = (size_t) n * (size_t) blob;
void* p = nullptr;
- if (cudaHostAlloc(&p, total, cudaHostAllocDefault) == cudaSuccess && p != nullptr) {
+ if (cudaHostAlloc(&p, total, eligible ? cudaHostAllocMapped : cudaHostAllocDefault) == cudaSuccess && p != nullptr) {
xstage_pinned_ = true;
} else {
(void) cudaGetLastError();
@@ -1758,16 +1777,36 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) {
xstage_ = (uint8_t*) p;
xstage_cap_ = n;
xstage_blob_ = blob;
+ if (requested) {
+ std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement";
+ void* device = nullptr;
+ if (eligible && xstage_pinned_ && cudaHostGetDevicePointer(&device, p, 0) == cudaSuccess && device) {
+ try {
+ if (exchange_storage_.initialize(complement_offsets_, (uint8_t*)complement_host_, complement_device_,
+ complement_bytes_, xstage_, (const uint8_t*)device, (size_t)n, (size_t)blob, reason)) {
+ std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers, %llu bytes each; no host commit memcpy\n",
+ (long long)n, (unsigned long long)blob);
+ }
+ } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; }
+ } else if (eligible) {
+ (void) cudaGetLastError();
+ reason = "exchange buffers could not be pinned and mapped";
+ }
+ if (!exchange_storage_.active())
+ std::fprintf(stderr, "FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n", reason.c_str());
+ }
return true;
}
uint8_t* FileExpertSource::exchange_buffer(int64_t q) const {
if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr;
+ if (exchange_storage_.active()) return exchange_storage_.spare((size_t)q).host;
return xstage_ + (size_t) q * (size_t) xstage_blob_;
}
bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) {
- if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false;
+ if (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) ||
+ exchange_buffer(q) == nullptr) return false;
const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in;
const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out;
if (override_.empty()) override_.assign((size_t) blobs_, nullptr);
@@ -1783,6 +1822,16 @@ int64_t FileExpertSource::commit_exchanges() {
int64_t n = 0;
for (const Exchange& x : staged_) {
const uint8_t* src = override_[x.out];
+ if (exchange_storage_.active()) {
+ if (!exchange_storage_.commit(x.in, x.out, (size_t)x.q, src, (size_t)x.bytes)) {
+ // Admitting the GPU swap after a failed RAM ownership update would lose an expert.
+ std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n");
+ std::abort();
+ }
+ ++n;
+ override_[x.out] = nullptr;
+ continue;
+ }
const uint64_t at = complement_offsets_[x.in];
if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at &&
complement_host_ != nullptr) {
@@ -1836,7 +1885,7 @@ const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) {
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);
+ result = resident_blob(index);
if (result != nullptr) {
ram_reads_.fetch_add(1, std::memory_order_relaxed);
from_files = false;
@@ -1863,6 +1912,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
if (!complement_ready_ || !complement_pinned_ || complement_host_ == 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;
+ if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr;
if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false;
// a partial pin (CS-T): only the registered prefix
return !complement_partial_ ||
@@ -1872,6 +1922,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const {
const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const {
if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr;
const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert;
+ if (exchange_storage_.active()) return exchange_storage_.resident(index).device;
return complement_device_ + (size_t) complement_offsets_[index];
}
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 58a99d96e..221495dc8 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -2498,8 +2498,7 @@ int main(int argc, char** argv) {
}
ss.db = &db;
- // ================================ THE PLE ================================
- //
+ // ================================ THE PLE ========================= //
// **ITS ABSENCE IS WHY GATE C1 FAILED** (LEDGER L123): layer 1 carries six `blk.1.ple_*` tensors, the whole
// module was built and parity-tested, and nothing called it. Everything below is construction - the table
// is a mapping of the ORIGINAL second GGUF shard, the six weights are already loaded in the arena, and the
@@ -8004,6 +8003,11 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, "
"%.1f ms per round (start to flip, between windows)\n",
(long long) a_rounds, (long long) a_swapped, a_rounds > 0 ? a_ms / (double) a_rounds : 0.0);
+=======
+ if (src.exchange_rotation())
+ std::fprintf(stderr, "strata serve: exchange rotation: %llu blocks, %llu host memcpy bytes avoided (cumulative payload)\n",
+ (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)
std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs "
diff --git a/tests/core/exchange_storage_test.cpp b/tests/core/exchange_storage_test.cpp
new file mode 100644
index 000000000..b790b4f20
--- /dev/null
+++ b/tests/core/exchange_storage_test.cpp
@@ -0,0 +1,133 @@
+#include "strata/core/exchange_storage.hpp"
+
+#include <algorithm>
+#include <cstring>
+#include <iostream>
+#include <random>
+#include <set>
+#include <thread>
+#include <stdexcept>
+#include <vector>
+
+using strata::core::detail::ExchangeStorage;
+constexpr uint64_t absent = ~uint64_t{0};
+void require(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); }
+
+void exercise(size_t bytes, size_t rounds) {
+ constexpr size_t n = 24, resident = 16, spare_count = 4, guard = 19;
+ std::vector<uint8_t> arena(guard + resident * bytes + guard, 0xcd);
+ std::vector<uint8_t> spare(guard + spare_count * bytes + guard, 0xef);
+ // Distinct alias arrays catch accidentally retaining the old CUDA address.
+ std::vector<uint8_t> aliases(resident * bytes), spare_aliases(spare_count * bytes);
+ std::vector<std::vector<uint8_t>> reference(n, std::vector<uint8_t>(bytes));
+ std::mt19937 random(601);
+ for (auto& row : reference) for (auto& v : row) v = (uint8_t)random();
+ std::vector<uint64_t> offsets(n, absent);
+ for (size_t i = 0; i < resident; ++i) {
+ offsets[i] = i * bytes;
+ std::memcpy(arena.data() + guard + offsets[i], reference[i].data(), bytes);
+ }
+ ExchangeStorage storage;
+ std::string error;
+ require(storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes,
+ spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), error.c_str());
+ std::set<uint8_t*> original;
+ for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) original.insert(p);
+ for (size_t q = 0; q < spare_count; ++q) original.insert(storage.spare(q).host);
+ // A lookahead thread may inspect residency while ownership is committed.
+ // It only observes immutable address pairs, never reads mutable expert bytes.
+ std::atomic<bool> stop{false}, reader_failed{false};
+ std::atomic<uint64_t> observations{0};
+ std::vector<ExchangeStorage::View> valid;
+ for (size_t i = 0; i < n; ++i) if (storage.resident(i).host) valid.push_back(storage.resident(i));
+ for (size_t q = 0; q < spare_count; ++q) valid.push_back(storage.spare(q));
+ std::thread reader([&] {
+ while (!stop.load()) {
+ for (size_t i = 0; i < n; ++i) {
+ const auto view = storage.resident(i);
+ if (view.host && std::none_of(valid.begin(), valid.end(), [&](auto v) {
+ return v.host == view.host && v.device == view.device; })) reader_failed.store(true);
+ }
+ ++observations;
+ }
+ });
+ struct Join {
+ std::atomic<bool>& stop; std::thread& reader;
+ void finish() { stop.store(true); if (reader.joinable()) reader.join(); }
+ ~Join() { finish(); }
+ } join{stop, reader};
+ while (!observations.load()) std::this_thread::yield();
+ uint64_t exchanges = 0;
+ for (size_t round = 0; round < rounds; ++round) {
+ std::vector<size_t> ins, outs;
+ for (size_t i = 0; i < n; ++i) (storage.resident(i).host ? ins : outs).push_back(i);
+ std::shuffle(ins.begin(), ins.end(), random);
+ std::shuffle(outs.begin(), outs.end(), random);
+ ExchangeStorage::View before[spare_count], staged[spare_count];
+ for (size_t q = 0; q < spare_count; ++q) {
+ before[q] = storage.resident(ins[q]); staged[q] = storage.spare(q);
+ // Simulated completed D2H eviction. The old RAM input stays readable
+ // until simulated H2D and all readers finish, before commit.
+ std::memcpy(staged[q].host, reference[outs[q]].data(), bytes);
+ require(!std::memcmp(before[q].host, reference[ins[q]].data(), bytes), "incoming expert overwritten early");
+ }
+ for (size_t q = 0; q < spare_count; ++q) {
+ require(!storage.commit(ins[q], ins[q], q, staged[q].host, bytes), "self swap accepted");
+ require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes + 1), "wrong size accepted");
+ require(!storage.commit(ins[q], outs[q], q, nullptr, bytes), "missing staged buffer accepted");
+ require(!storage.commit(ins[q], outs[q], spare_count, staged[q].host, bytes), "bad spare accepted");
+ require(!storage.commit(n, outs[q], q, staged[q].host, bytes), "bad expert accepted");
+ require(storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "valid swap rejected");
+ require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "duplicate commit accepted");
+ require(storage.resident(outs[q]).host == staged[q].host &&
+ storage.resident(outs[q]).device == staged[q].device, "evicted buffer was not adopted with its alias");
+ require(storage.spare(q).host == before[q].host && storage.spare(q).device == before[q].device,
+ "old RAM input was not recycled with its alias");
+ // Even the old incoming bytes have not changed: commit copies metadata only.
+ require(!std::memcmp(storage.spare(q).host, reference[ins[q]].data(), bytes), "commit changed spare bytes");
+ ++exchanges;
+ }
+ std::set<uint8_t*> live;
+ for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) {
+ require(live.insert(p).second, "two experts share storage");
+ require(!std::memcmp(p, reference[i].data(), bytes), "resident bytes corrupted");
+ }
+ for (size_t q = 0; q < spare_count; ++q)
+ require(live.insert(storage.spare(q).host).second, "spare aliases live expert");
+ require(live == original, "storage leaked or duplicated");
+ }
+ require(storage.exchanges() == exchanges && storage.avoided_bytes() == exchanges * bytes, "wrong accounting");
+ require(std::all_of(arena.begin(), arena.begin() + guard, [](auto x) { return x == 0xcd; }) &&
+ std::all_of(arena.end() - guard, arena.end(), [](auto x) { return x == 0xcd; }) &&
+ std::all_of(spare.begin(), spare.begin() + guard, [](auto x) { return x == 0xef; }) &&
+ std::all_of(spare.end() - guard, spare.end(), [](auto x) { return x == 0xef; }), "guard overwritten");
+ require(!storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes,
+ spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), "live storage reinitialized");
+ join.finish();
+ require(!reader_failed.load() && observations.load(), "concurrent residency reader observed invalid alias");
+ storage.clear();
+ require(!storage.active() && !storage.resident(0).host && !storage.spare(0).host &&
+ !storage.exchanges() && !storage.avoided_bytes(), "clear retained state");
+}
+
+void invalid_geometry() {
+ uint8_t h[64]{}, d[64]{}, x[64]{}, xd[64]{};
+ ExchangeStorage s; std::string e;
+ require(!s.initialize({0, 3}, h, d, 8, x, xd, 2, 4, e), "unaligned slot accepted");
+ require(!s.initialize({0, 0}, h, d, 8, x, xd, 2, 4, e), "duplicate offset accepted");
+ require(!s.initialize({0, 8}, h, d, 8, x, xd, 2, 4, e), "out of bounds accepted");
+ require(!s.initialize({0, absent}, h, d, 8, x, xd, 2, 4, e), "lost slot accepted");
+ require(!s.initialize({0, 4}, h, nullptr, 8, x, xd, 2, 4, e), "unmapped resident accepted");
+ require(!s.initialize({0, 4}, h, d, 8, x, nullptr, 2, 4, e), "unmapped spare accepted");
+ require(!s.initialize({0, 4}, h, d, 8, x, xd, 2, 0, e), "zero blob accepted");
+ require(!s.active(), "failed initialization left active state");
+}
+
+int main() {
+ try {
+ invalid_geometry();
+ for (size_t bytes : {1u, 33u, 4097u}) exercise(bytes, 1024);
+ exercise(5222400, 4); // actual Q8 expert size
+ std::cout << "exchange_storage_test: PASS (byte/alias/ownership checks, 12304 exchanges)\n";
+ } catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; }
+}
diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp
index 104507d13..f0b47c786 100644
--- a/tests/core/file_expert_source_test.cpp
+++ b/tests/core/file_expert_source_test.cpp
@@ -7,6 +7,9 @@
#include "ggml.h"
#endif
+#include <cuda_runtime.h>
+#include <cstdlib>
+#include <cstring>
#include <algorithm>
#include <chrono>
#include <cstddef>
@@ -338,9 +341,96 @@ void test_host_memory() {
#endif
}
+void test_rotating_source(bool rotate, bool pin) {
+ using namespace strata::core;
+ using namespace strata::kernels::cpu;
+#if defined(_WIN32)
+ _putenv_s("STRATA_EXCHANGE_ROTATE", rotate ? "1" : "0");
+#else
+ setenv("STRATA_EXCHANGE_ROTATE", rotate ? "1" : "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}};
+ // Keep expert 4 on the file tier to check that the fallback survives rotation.
+ require(src.pin_cache_complement(cache, err, pin, {}, -1, 0, 2 * bytes, &rank), err);
+ require(src.reserve_exchanges(2, err), err);
+ require(src.exchange_rotation() == (rotate && pin), "rotation activation/fallback wrong");
+ require(src.reserve_exchanges(1, err), "smaller capacity rejected");
+ if (rotate && pin) require(!src.reserve_exchanges(3, err), "live arena growth accepted");
+ int incoming[2] = {0, 1}, outgoing[2] = {2, 3};
+ std::vector<uint8_t> actual(bytes);
+ double commit_ms = 0;
+ for (int round = 0; round < 32; ++round) {
+ const uint8_t* prior[2]{};
+ uint8_t* eviction[2]{};
+ for (int q = 0; q < 2; ++q) {
+ prior[q] = src.blob(0, incoming[q]); eviction[q] = src.exchange_buffer(q);
+ require(prior[q] && !std::memcmp(prior[q], truth[incoming[q]].data(), bytes), "wrong incoming bytes");
+ require(cudaMemcpy(eviction[q], cache.device_slot(q), bytes, cudaMemcpyDeviceToHost) == cudaSuccess,
+ "D2H eviction failed");
+ require(src.stage_exchange(0, incoming[q], outgoing[q], q), "stage rejected");
+ require(!std::memcmp(src.blob(0, outgoing[q]), truth[outgoing[q]].data(), bytes), "staged override wrong");
+ require(cache.fill_slot_blocking(q, prior[q], err), err); // H2D completed before commit
+ }
+ require(!src.stage_exchange(0, incoming[0], outgoing[0], 0), "duplicate stage accepted");
+ require(!src.stage_exchange(0, incoming[0], 5, 0), "invalid expert accepted");
+ const auto t0 = std::chrono::steady_clock::now();
+ require(src.commit_exchanges() == 2, "commit count wrong");
+ commit_ms += std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
+ require(src.commit_exchanges() == 0, "empty commit not empty");
+ for (int q = 0; q < 2; ++q) {
+ require(!src.has_resident(0, incoming[q]) && src.has_resident(0, outgoing[q]), "residency wrong");
+ const uint8_t* held = src.blob(0, outgoing[q]);
+ require(!std::memcmp(held, truth[outgoing[q]].data(), bytes), "evicted bytes corrupted");
+ require(held == ((rotate && pin) ? eviction[q] : prior[q]), "wrong storage selected");
+ if (rotate && pin) require(src.exchange_buffer(q) == prior[q], "old input not recycled");
+ require(src.copy_blob(0, outgoing[q], actual.data()) && actual == truth[outgoing[q]], "copy_blob mismatch");
+ require(!src.transient(0, outgoing[q]), "resident became transient");
+ if (pin) {
+ require(src.pinned(0, outgoing[q]) && src.device_alias(0, outgoing[q]), "mapping lost");
+ require(cudaMemcpy(actual.data(), src.device_alias(0, outgoing[q]), bytes, cudaMemcpyDeviceToHost) == cudaSuccess,
+ "device alias read failed");
+ require(actual == truth[outgoing[q]], "CUDA alias points at stale expert");
+ }
+ require(cache.verify_slot(q, truth[incoming[q]].data(), err), err);
+ std::swap(incoming[q], outgoing[q]);
+ }
+ require(!src.has_resident(0, 4) && src.copy_blob(0, 4, actual.data()) && actual == truth[4], "file fallback changed");
+ }
+ require(src.exchanges() == 64, "exchange accounting wrong");
+ require(src.rotated_exchanges() == ((rotate && pin) ? 64u : 0u), "rotation accounting wrong");
+ require(src.avoided_exchange_copy_bytes() == ((rotate && pin) ? 64 * bytes : 0u), "avoided bytes wrong");
+ std::cout << "rotation integration: rotate=" << rotate << " pinned=" << pin
+ << " exchanges=64 commit_ms=" << commit_ms << " exact_bytes=PASS\n";
+ src.close();
+ require(!src.exchange_rotation() && !src.exchange_buffer(0), "close retained storage");
+ require(src.open(dir.path.string(), 1, 5, err), err);
+ require(!src.has_resident(0, 0) && !src.exchange_rotation(), "reopen retained residency");
+}
+
} // namespace
-int main() {
+int main(int argc, char** argv) {
try {
test_complement_plan();
test_resident_lend_region();
@@ -351,6 +441,11 @@ int main() {
#if defined(STRATA_NATIVE_EXPERTS)
test_native_variable_layout();
#endif
+ if (argc == 2 && std::string(argv[1]) == "--rotation-gpu") {
+ test_rotating_source(false, true);
+ test_rotating_source(true, true);
+ test_rotating_source(true, false);
+ }
std::cout << "file_expert_source_test: PASS\n";
return 0;
} catch (const std::exception& error) {