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++
serve: the conversation cache keeps its shared prefix; the rest rotates LRU
Jakub Luwierski5f8ad8284edb
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 6c628552b..22de6cf2b 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -455,6 +455,10 @@ if(STRATA_BUILD_TESTS)add_executable(draft_policy_test src/spec/draft_policy_test.cpp)target_link_libraries(draft_policy_test PRIVATE strata_spec)add_test(NAME draft_policy_test COMMAND draft_policy_test)+ # the serve loop's conversation-cache retention policy (header-only, no library to link)+ add_executable(conv_cache_test src/program/conv_cache_test.cpp)+ target_include_directories(conv_cache_test PRIVATE include)+ add_test(NAME conv_cache_test COMMAND conv_cache_test)endif()add_library(strata_kernels_cpu STATIC src/kernels/cpu/expert.cpp src/kernels/cpu/pool.cppdiff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex 7b436fc67..2895ba73c 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -297,10 +297,14 @@ print(r.choices[0].message.content)**Conversation cache.** A request that continues a chat reads only the part after what the engine already holds: thelive session, or one of the checkpoints it keeps in RAM (up to 6, ~118 MB each, taken at the start of each newassistant turn and every 16K prompt tokens). A checkpoint is used only when the prompt starts with exactly its tokens-and pictures. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`, `--turn-token ID`.--**Current limits (v1):** one request at a time, and one conversation cached at a time (switching between two chats-re-reads the other one); images only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /+and pictures. The oldest checkpoint - in practice the end of the system prompt, which every chat of the same client+shares - is kept for good while the rest rotates by least recent use, so a NEW chat that shares that prefix starts+reading after it instead of from token 0. Engine options: `--prompt-cache N` (0 = off), `--prompt-cache-every N`,+`--turn-token ID`.++**Current limits (v1):** one request at a time, and one conversation's history in the KV cache at a time (switching+between two chats re-reads the part where they diverge; the shared prefix, such as the system prompt, is reused); images+only when set up with them (below); no video. **Temperature / top_p / top_k / min_p /seed** are honored per request (OpenAI and Anthropic fields); with the default adaptive expert tier a sampled resultis not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to theengine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields outdiff --git a/include/strata/program/conv_cache.hpp b/include/strata/program/conv_cache.hppnew file mode 100644index 000000000..7fe4bfa75--- /dev/null+++ b/include/strata/program/conv_cache.hpp@@ -0,0 +1,43 @@+// include/strata/program/conv_cache.hpp - the conversation cache's retention policy: which checkpoint+// leaves when the cache is over its slot budget.+//+// The cache holds conversation checkpoints: snapshots of the running state (the GDN recurrence, the PLE+// history, the QSA indexer tails - `ConvCheckpoint` in generate.cpp) that a request resumes its prompt+// from instead of reading those tokens again. The request path keeps only the checkpoints whose tokens+// are a prefix of the current prompt - any other checkpoint's positional cells have been overwritten,+// because the KV cache is one arena that holds one branch of history at a time - so at any moment the+// retained checkpoints are a CHAIN: sorted by length, each a prefix of the next. That is a radix cache's+// tree collapsed onto the one branch of history the session can hold.+//+// The chain's root is therefore the deepest point every request so far has shared - in practice the end+// of the system prompt, which every new chat of the same client mounts through - and it is exactly the+// node a radix cache keeps alive while its leaves rotate. First-in-first-out kept it only by accident of+// being first: after `prompt_cache` newer checkpoints it was gone, and the next chat read the whole+// prefix again at prefill speed. So:+//+// * the root is PINNED: dropping it frees one slot's ~118 MB and costs every future conversation that+// shares the prefix a full re-read of it (a 30K system prompt is ~30 s at ~1,000 tok/s);+// * every other slot rotates by least recent use. A checkpoint's stamp advances when it is created,+// when a new checkpoint lands on its length, and when a request mounts through it.+//+// With a budget below two slots there is no room to keep root and leaf apart, so the pin switches off and+// the oldest checkpoint leaves - the previous behaviour, one slot = the newest point only.+#pragma once++#include <cstddef>+#include <cstdint>++namespace strata::program::conv_cache {++/// The index in `stamps` of the chain item to drop once the chain holds more than `cap` items. `stamps`+/// are the items' last-use stamps; the caller owns the chain and erases the returned index. Pure and+/// deterministic so conv_cache_test.cpp can walk the scenarios by hand.+inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap) {+ if (cap < 2 || n < 2) return 0; // no room for root and leaf: the pin is off, the oldest leaves+ size_t v = 1; // the root (0) is pinned; least recent use among the rest+ for (size_t i = 2; i < n; ++i)+ if (stamps[i] < stamps[v]) v = i;+ return v;+}++} // namespace strata::program::conv_cachediff --git a/src/program/conv_cache_test.cpp b/src/program/conv_cache_test.cppnew file mode 100644index 000000000..f4a0c2b7c--- /dev/null+++ b/src/program/conv_cache_test.cpp@@ -0,0 +1,67 @@+// src/program/conv_cache_test.cpp - the conversation cache's retention policy: the shared root survives,+// the leaves rotate by least recent use.+//+// The scenarios, in the serve loop's terms (generate.cpp): checkpoints are a prefix chain - stamps[0] is+// the root, the deepest point every request so far has shared (the end of the system prompt, in practice).+// A stamp advances on creation, when a new checkpoint lands on an existing length, and when a request+// mounts through the checkpoint.+//+// 1. one conversation over its budget: the oldest leaf leaves - with fresh stamps in creation order this+// is exactly the previous first-in-first-out behaviour;+// 2. the root survives arbitrarily many newer checkpoints however old its stamp is;+// 3. a mount advances a checkpoint's stamp and the rotation then takes a different leaf;+// 4. a one-slot budget has no room for root and leaf, so the pin is off and the oldest leaves (the+// newest point stays, as before);+// 5. the policy is pure: the same stamps, the same victim.+#include "strata/program/conv_cache.hpp"++#include <cstdint>+#include <cstdio>+#include <vector>++using strata::program::conv_cache::eviction_victim;++namespace {+int g_fail = 0;+void check(bool ok, const char* what) {+ std::printf(" %-66s %s\n", what, ok ? "ok" : "FAIL");+ if (!ok) ++g_fail;+}+} // namespace++int main() {+ std::printf("conv_cache_test\n");+ {+ const std::vector<uint64_t> stamps = {1, 2, 3, 4, 5, 6, 7}; // chat A: root + six turns, one over+ check(eviction_victim(stamps.data(), stamps.size(), 6) == 1,+ "over budget with fresh stamps: the oldest leaf leaves (the FIFO it was)");+ }+ {+ // chat B mounts through the root long after it was created; its stamp stays ancient+ const std::vector<uint64_t> stamps = {1, 100, 101, 102, 103, 104, 105};+ const size_t v = eviction_victim(stamps.data(), stamps.size(), 6);+ check(v == 1, "the root's stale stamp never makes it the victim");+ check(v != 0, "the root - the shared prefix - is never the victim");+ }+ {+ // the same chain after mounting checkpoint 1: its stamp jumps, the rotation moves to the next leaf+ const std::vector<uint64_t> stamped = {1, 8, 3, 4, 5, 6, 7};+ check(eviction_victim(stamped.data(), stamped.size(), 6) == 2,+ "after a mount, the rotation takes the next least recently used leaf");+ }+ {+ const std::vector<uint64_t> stamps = {1, 90, 91, 92};+ check(eviction_victim(stamps.data(), stamps.size(), 2) == 1,+ "a two-slot budget keeps root + newest and drops the leaf in between");+ check(eviction_victim(stamps.data(), stamps.size(), 1) == 0,+ "a one-slot budget has no pin: the oldest leaves, the newest point stays");+ }+ {+ const std::vector<uint64_t> stamps = {7, 3, 3, 5};+ const size_t a = eviction_victim(stamps.data(), stamps.size(), 4);+ const size_t b = eviction_victim(stamps.data(), stamps.size(), 4);+ check(a == 1 && b == 1, "ties among equally stale leaves: the earlier index, deterministically");+ }+ std::printf(g_fail ? "FAIL\n" : "PASS\n");+ return g_fail ? 1 : 0;+}diff --git a/src/program/generate.cpp b/src/program/generate.cppindex d84d86476..6051c99bc 100644--- a/src/program/generate.cpp+++ b/src/program/generate.cpp@@ -42,6 +42,7 @@#include "strata/prefill/prefill.hpp"#include "strata/core/native_dense.hpp"#include "strata/program/logits_selection.hpp"+#include "strata/program/conv_cache.hpp"#include "strata/spec/draft_policy.hpp"#include "strata/spec/suffix_drafter.hpp"#include "strata/kernels/cvec.hpp"@@ -622,6 +623,7 @@ struct ConvCheckpoint {std::vector<int32_t> ids; ///< the tokens this state has consumedstd::vector<ImgKey> imgs; ///< the images among themstd::vector<uint8_t> gdn, ple, tails;+ uint64_t used = 0; ///< last-use stamp for the retention policy (conv_cache.hpp)};uint64_t fnv1a(const void* data, size_t n, uint64_t h = 1469598103934665603ull) {@@ -2367,11 +2369,16 @@ int main(int argc, char** argv) {std::vector<int64_t> cur;// ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens// it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the- // saved points; every one of them is a prefix of `live` (the loop drops the rest).+ // saved points; every one of them is a prefix of `live` (the loop drops the rest), so they form a chain -+ // the radix cache's tree collapsed onto the one branch of history whose cells the session holds. The+ // chain's root is the deepest point every request so far shared (the end of the system prompt, in+ // practice); the retention policy pins it and rotates the rest LRU (conv_cache.hpp), so a NEW chat that+ // shares that prefix mounts through it instead of reading it again.std::vector<int32_t> live;std::vector<ImgKey> live_imgs, req_imgs;bool live_ok = false;std::vector<ConvCheckpoint> checks;+ uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance itbool cvec_cached = true; // the control vector's state the live session and the checkpoints were read withint64_t pp_total = 0, pp_from = 0, pp_next_check = 0;Clock::time_point pp_t0 = Clock::now();@@ -2383,13 +2390,22 @@ int main(int argc, char** argv) {// a checkpoint of the state after `cur[0, L)`; false only when the copy itself failedauto checkpoint_at = [&](int64_t L) -> bool {if (o.prompt_cache <= 0 || L < 1) return true;- for (const ConvCheckpoint& c : checks) if ((int64_t) c.ids.size() == L) return true;+ for (ConvCheckpoint& c : checks)+ if ((int64_t) c.ids.size() == L) { c.used = ++check_clock; return true; }ConvCheckpoint c;c.ids.assign(cur.begin(), cur.begin() + L);c.imgs = imgs_below(req_imgs, L);if (cudaDeviceSynchronize() != cudaSuccess || !checkpoint_save(c, ss, g)) return false;+ c.used = ++check_clock;checks.push_back(std::move(c));- while ((int) checks.size() > o.prompt_cache) checks.erase(checks.begin()); // the oldest goes first+ while ((int) checks.size() > o.prompt_cache) {+ std::vector<uint64_t> stamps;+ stamps.reserve(checks.size());+ for (const ConvCheckpoint& k : checks) stamps.push_back(k.used);+ const size_t victim = strata::program::conv_cache::eviction_victim(stamps.data(), stamps.size(),+ o.prompt_cache);+ checks.erase(checks.begin() + (std::ptrdiff_t) victim);+ }return true;};sp.on_chunk = [&](const float* R_rows, int64_t T, int64_t p0, std::string& e) -> bool {@@ -2805,8 +2821,9 @@ int main(int argc, char** argv) {cudaStreamSynchronize(main_stream);checks.clear();} else if (!from_live) {- const ConvCheckpoint* c = nullptr;- for (const ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k;+ ConvCheckpoint* c = nullptr;+ for (ConvCheckpoint& k : checks) if ((int64_t) k.ids.size() == resume) c = &k;+ if (c != nullptr) c->used = ++check_clock; // mounting through it is the use LRU countsstatic const bool reread = std::getenv("STRATA_CKPT_REREAD") != nullptr;if (reread && c != nullptr) {// THE CHECK OF THE CHECKPOINT: instead of restoring it, read its tokens again from position 0 in