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

R1: a pinned shared prefix for many suffix queries (opt-in pin=N / "strata_prefix")

Niko122113d14a49447e
diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp
index c28ae01f6..c1b554b87 100644
--- a/include/strata/core/conversation_cache.hpp
+++ b/include/strata/core/conversation_cache.hpp
@@ -25,6 +25,10 @@ struct ConversationCheckpoint {
std::vector<ConversationImageKey> imgs;
std::vector<uint8_t> gdn, ple, tails, dead, block_pos;
uint64_t used = 0; // upstream root-pinned/LRU checkpoint retention
+ // A shared-prefix pin (the request key pin=N): this checkpoint is the read-only prefix many suffix queries branch
+ // from, so retention never evicts it (conv_cache.hpp) and a parked conversation holding it stays parked. A run-time
+ // mark only: it is not in the session file, a request that pins the same prefix again sets it.
+ bool pinned = false;
// Ordinary layer-split checkpoints retain each device's running state.
// Whole-session parking is currently single-GPU and rejects these parts.
std::vector<ConversationCheckpoint> stage_parts;
@@ -95,7 +99,7 @@ inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector<Co
if (c.stage_parts.size() != stages) continue;
for (size_t k = 0; k < stages; ++k) {
ConversationCheckpoint part;
- part.ids = c.ids; part.imgs = c.imgs; part.used = c.used;
+ part.ids = c.ids; part.imgs = c.imgs; part.used = c.used; part.pinned = c.pinned;
out.parts[k].push_back(std::move(part));
}
}
@@ -153,6 +157,12 @@ struct SavedConversation {
// with a layer split, the later stages' own images, one per stage, in stage order
std::vector<SavedConversation> stage_images;
+ /// Holds a pinned shared prefix (see ConversationCheckpoint::pinned): the parked-conversation budget keeps it.
+ bool pinned() const {
+ for (const auto& c : checkpoints) if (c.pinned) return true;
+ return false;
+ }
+
size_t bytes() const {
size_t n = live.bytes() + checkpoints.capacity() * sizeof(ConversationCheckpoint) +
kv.capacity() * sizeof(ConversationKv);
@@ -245,8 +255,12 @@ public:
if (!enabled() || held > budget_ || incoming > budget_ - held) return false;
if (bytes() > budget_ - held - incoming) reuse_ = {};
while (!entries_.empty() && (entries_.size() >= slots_ || bytes_ > budget_ - held - incoming)) {
- bytes_ -= entries_.front().bytes();
- entries_.pop_front();
+ // the oldest entry that does not hold a pinned shared prefix leaves; with only pinned ones left the new
+ // image does not fit (the caller skips parking it - the pinned prefix is what the queries come back to)
+ auto victim = std::find_if(entries_.begin(), entries_.end(), [](const SavedConversation& e) { return !e.pinned(); });
+ if (victim == entries_.end()) return false;
+ bytes_ -= victim->bytes();
+ entries_.erase(victim);
++evictions_;
}
return true;
diff --git a/include/strata/program/conv_cache.hpp b/include/strata/program/conv_cache.hpp
index 100856f08..07c23adea 100644
--- a/include/strata/program/conv_cache.hpp
+++ b/include/strata/program/conv_cache.hpp
@@ -54,4 +54,27 @@ inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap, con
return eviction_victim(stamps, n, cap);
}
+/// The pin=N shared prefixes (`pinned[i]`): they are never the victim, whatever their stamp - the queries that branch
+/// from one keep coming back to it, and a least-recently-used rule would drop it while they still do. The root and
+/// the tail rule are as above. When every other item is pinned too, the policy falls back to the oldest pinned one:
+/// the cache still keeps to its `cap` (the caller limits how many pins it takes, so this is a backstop).
+inline size_t eviction_victim(const uint64_t* stamps, size_t n, int64_t cap, const bool* tail, const bool* pinned) {
+ if (pinned == nullptr) return eviction_victim(stamps, n, cap, tail);
+ if (cap < 2 || n < 2) return 0;
+ size_t newest = 0;
+ for (size_t i = 1; i < n; ++i)
+ if (stamps[i] > stamps[newest]) newest = i;
+ if (tail != nullptr)
+ for (size_t i = 1; i < n; ++i)
+ if (tail[i] && !pinned[i] && i != newest) return i;
+ size_t v = n; // the least recently used among the unpinned non-root items
+ for (size_t i = 1; i < n; ++i)
+ if (!pinned[i] && (v == n || stamps[i] < stamps[v])) v = i;
+ if (v != n) return v;
+ v = 1; // all pinned: the oldest of them (never the root, index 0)
+ for (size_t i = 2; i < n; ++i)
+ if (stamps[i] < stamps[v]) v = i;
+ return v;
+}
+
} // namespace strata::program::conv_cache
diff --git a/serve/server.py b/serve/server.py
index 07e0588b6..93e673254 100644
--- a/serve/server.py
+++ b/serve/server.py
@@ -885,6 +885,13 @@ class StrataEngine:
# extends: no conversation checkpoint for it (#830). It still reuses a cached prefix. Absent = as before.
if sampling.get("strata_checkpoint") is False:
keys += " ckpt=0"
+ # "strata_prefix" (resolved by Service.resolve_prefix to {"tokens": N}): the first N prompt tokens are a shared
+ # prefix - the engine pins the checkpoint there. Absent or unresolved = as before.
+ prefix = sampling.get("strata_prefix")
+ if isinstance(prefix, dict):
+ pn = prefix.get("tokens")
+ if isinstance(pn, int) and not isinstance(pn, bool) and pn > 0:
+ keys += f" pin={pn}"
return keys + StrataEngine.projection_key(sampling)
@staticmethod
@@ -2856,7 +2863,7 @@ class Service:
content[n] = {"type": "text", "text": f"[image omitted: {why}]"}
return fetched
- def prepare(self, messages, tools, kwargs, max_new=None, force=None):
+ def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None):
"""-> (ids, thinking, max_new). An unset or non-positive max_new (some clients send -1) means "unlimited":
the rest of the context. `force` (forced_call): without thinking the reply starts with it, so it ends the
prompt; with thinking, Service.run writes it once the thinking is over."""
@@ -2931,8 +2938,84 @@ class Service:
combined = combined_embeddings_path(self.vision.dir, sum(Path(p).stat().st_size for p, _ in encoded))
self.embeddings.path = combined # first, so a half-written one is found as well
write_temporary(combined, [p for p, _ in encoded])
+ if req is not None and req.get("strata_prefix") is not None:
+ req["strata_prefix"] = self.resolve_prefix(req["strata_prefix"], messages, tools, kwargs, ids, bool(images))
return ids, kwargs.get("enable_thinking", True) is not False, max_new
+ PREFIX_END = "\u0001strata-prefix-end\u0001" # marks where a message's shared part ends in the rendered prompt
+
+ def resolve_prefix(self, spec, messages, tools, kwargs, ids, has_images=False) -> dict:
+ """R1: `"strata_prefix"` marks the start of the prompt as a shared read-only prefix: a long document that many
+ short questions follow. Three ways to say where it ends: `{"messages": K}` (the first K messages), `{"message":
+ I, "chars": N}` (the first N characters of message I's text: a document and its question in one message) or
+ `{"tokens": N}`. The engine reads the prompt in two parts there, keeps the checkpoint at the boundary pinned
+ (never evicted) and does not park the branch it leaves, so N questions cost one prefix. Returns
+ {"tokens": N} (what the engine's `pin=N` takes: always a prefix of the prompt's ids, the tokenizer's merge across
+ the boundary included), or {} when the prefix cannot be marked (said in the log: the request is never refused for
+ it). A malformed field is a 400."""
+ keys = ("messages", "message", "chars", "tokens")
+ if (not isinstance(spec, dict) or not spec or any(k not in keys for k in spec) or
+ set(spec) not in ({"messages"}, {"tokens"}, {"message", "chars"})):
+ raise ValueError('strata_prefix: {"messages": K} (the first K messages), {"message": I, "chars": N} (the first '
+ 'N characters of message I) or {"tokens": N}')
+ for k, v in spec.items():
+ if not isinstance(v, int) or isinstance(v, bool) or v < (0 if k == "message" else 1):
+ raise ValueError(f"strata_prefix.{k}: a whole number ({'0' if k == 'message' else '1'} or more)")
+ if has_images:
+ print("[strata] strata_prefix ignored: the request has images", flush=True)
+ return {}
+ what = ",".join(f"{k}={v}" for k, v in spec.items())
+
+ def lcp(a, b):
+ n = 0
+ for x, y in zip(a, b):
+ if x != y:
+ break
+ n += 1
+ return n
+
+ def head_ids(msgs):
+ """The ids the rendered `msgs` start with (a message's trailing marker cut at PREFIX_END when it is there)."""
+ marked, marked_tools, changed = mark_think_literals(msgs, tools, self.literals)
+ effort = kwargs.get("reasoning_effort")
+ off = kwargs.get("enable_thinking") is False # render_prompt's rule for #458's effort_end
+ kw = ({k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")}
+ if self.effort_end and (off or effort not in (None, "", "xhigh", "high")) else dict(kwargs))
+ kw["add_generation_prompt"] = False
+ text = self.template.render(marked, tools=marked_tools, **kw)
+ cut = text.find(self.PREFIX_END)
+ if cut >= 0:
+ text = text[:cut]
+ if changed:
+ text, plain = unmark_think_literals(text, self.literals)
+ return self.tok.encode(text, parse_special=True, plain=plain)
+ return self.tok.encode(text, parse_special=True)
+
+ if "tokens" in spec:
+ n = spec["tokens"]
+ elif "messages" in spec:
+ k = spec["messages"]
+ if k >= len(messages):
+ print(f"[strata] strata_prefix.messages={k} ignored: the request has {len(messages)} message(s) and the "
+ "prefix must leave at least the last one", flush=True)
+ return {}
+ head = head_ids(messages[:k])
+ n = lcp(head, ids)
+ else:
+ i, chars = spec["message"], spec["chars"]
+ text = messages[i].get("content") if 0 <= i < len(messages) else None
+ if not isinstance(text, str) or chars > len(text):
+ print(f"[strata] strata_prefix ignored: message {i} has no text of {chars} characters", flush=True)
+ return {}
+ cut = messages[:i] + [{**messages[i], "content": text[:chars] + self.PREFIX_END}]
+ head = head_ids(cut)
+ n = lcp(head, ids)
+ if n < 1 or n >= len(ids) - 1:
+ print(f"[strata] strata_prefix {what} ignored: it leaves no usable prefix of the {len(ids)}-token prompt "
+ f"(common start {n})", flush=True)
+ return {}
+ return {"tokens": n}
+
def drop_embeddings(self) -> None:
"""Delete the combined image file prepare() wrote when no run() took it over (a run deletes its own as it
ends): a request can end before its answer starts - its client gone, anything raised after prepare() - and
@@ -4485,7 +4568,7 @@ def make_handler(svc: Service):
raise ValueError("a forced tool_choice with MCP tools is not supported")
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
- ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force)
+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req)
_debug_req("openai", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
self._watch_client(cancel) # #430 #431
@@ -4663,12 +4746,12 @@ def make_handler(svc: Service):
shown = responses_api.prompt_tools(req, tools) if svc.codex_compaction_cache else tools
try:
try:
- ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0)
+ ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req)
except ValueError:
if shown is tools:
raise
shown = tools # too long with the kept tools: the request as sent
- ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0)
+ ids, thinking, max_new = svc.prepare(messages, shown, kw, req.get("max_output_tokens") or 0, req=req)
except ResponsesError:
raise
except ValueError as e: # too long for the context, an image without vision
@@ -4702,7 +4785,7 @@ def make_handler(svc: Service):
max_new = int(req.get("max_tokens") or 0) # 0/-1: the rest of the context
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
stop_strings(req) # ... and so is a bad stop / stop_sequences
- ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force)
+ ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new, force=force, req=req)
_debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
self._watch_client(cancel) # #430 #431
diff --git a/serve/test_server.py b/serve/test_server.py
index 427f0aa2d..a3acfc969 100644
--- a/serve/test_server.py
+++ b/serve/test_server.py
@@ -1363,6 +1363,75 @@ class SamplingKeys(unittest.TestCase):
self.assertFalse([k for k in self.keys(temperature=0.7) if k.startswith("penalty")])
+class SharedPrefix(unittest.TestCase):
+ """R1: "strata_prefix" marks the first messages as a shared prefix; the engine gets pin=N."""
+
+ @classmethod
+ def setUpClass(cls):
+ tok = ByteTokenizer()
+ cls.svc = Service(MockEngine(tok, "ok", max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
+ cls.tok = tok
+
+ def keys(self, **sampling):
+ return StrataEngine.sampling_keys(sampling).split()
+
+ MSGS = [{"role": "system", "content": "You answer questions about the document."},
+ {"role": "user", "content": "DOC " * 40},
+ {"role": "user", "content": "Which word repeats?"}]
+
+ def test_pin_key(self):
+ self.assertIn("pin=1234", self.keys(strata_prefix={"tokens": 1234}))
+ for absent in ({}, {"strata_prefix": {}}, {"strata_prefix": {"messages": 2}}, {"strata_prefix": {"tokens": 0}},
+ {"strata_prefix": {"tokens": True}}, {"strata_prefix": "x"}):
+ self.assertFalse([k for k in self.keys(**absent) if k.startswith("pin=")], absent)
+
+ def test_messages_resolve_to_the_boundary_token(self):
+ req = {"strata_prefix": {"messages": 2}}
+ ids, _, _ = self.svc.prepare(self.MSGS, None, {}, 16, req=req)
+ n = req["strata_prefix"]["tokens"]
+ text = self.tok.decode(ids[:n], errors="replace")
+ self.assertTrue(text.endswith("DOC<|im_end|>\n"), text[-40:]) # right where the next message's turn starts
+ self.assertEqual(self.tok.decode(ids[n:n + 1]), "<|im_start|>")
+ head = self.svc.encode_prompt(self.MSGS[:2], None, {"add_generation_prompt": False})
+ self.assertEqual(ids[:n], head[:n])
+
+ def test_tokens_and_unusable_prefixes(self):
+ ids, _, _ = self.svc.prepare(self.MSGS, None, {}, 16)
+ req = {"strata_prefix": {"tokens": 100}}
+ self.svc.prepare(self.MSGS, None, {}, 16, req=req)
+ self.assertEqual(req["strata_prefix"], {"tokens": 100})
+ for spec in ({"messages": 3}, {"messages": 9}, {"tokens": len(ids)}, # leaves no last message / no suffix
+ {"message": 1, "chars": 5000}, {"message": 7, "chars": 3}): # more text than the message has
+ req = {"strata_prefix": spec}
+ with contextlib.redirect_stdout(io.StringIO()):
+ self.svc.prepare(self.MSGS, None, {}, 16, req=req)
+ self.assertEqual(req["strata_prefix"], {}, spec) # said in the log, never a refusal
+ for bad in ({"messages": 0}, {"messages": "2"}, {"messages": True}, {"tokens": 1.5}, {"x": 1},
+ {"messages": 1, "tokens": 2}, {"message": 1}, {"chars": 3}, {"message": -1, "chars": 3}, [], "pin", {}):
+ with self.assertRaises(ValueError, msg=bad):
+ self.svc.prepare(self.MSGS, None, {}, 16, req={"strata_prefix": bad})
+
+ def test_chars_end_inside_a_message(self):
+ # a document and its question in ONE message: the prefix is the first 160 characters of it
+ text = "DOC " * 40 + "Which word repeats?"
+ msgs = [{"role": "user", "content": text}]
+ req = {"strata_prefix": {"message": 0, "chars": 160}}
+ ids, _, _ = self.svc.prepare(msgs, None, {}, 16, req=req)
+ n = req["strata_prefix"]["tokens"]
+ self.assertEqual(self.tok.decode(ids[:n]).split("user\n", 1)[1], "DOC " * 40) # exactly those characters
+ # a system message first: message 1 is the user's
+ msgs = [{"role": "system", "content": "S"}, {"role": "user", "content": text}]
+ req = {"strata_prefix": {"message": 1, "chars": 160}}
+ ids, _, _ = self.svc.prepare(msgs, None, {}, 16, req=req)
+ self.assertEqual(self.tok.decode(ids[:req["strata_prefix"]["tokens"]]).split("user\n", 1)[1], "DOC " * 40)
+
+ def test_without_the_field_nothing_changes(self):
+ req = {"temperature": 0}
+ ids, _, _ = self.svc.prepare(self.MSGS, None, {}, 16, req=req)
+ self.assertEqual(req, {"temperature": 0})
+ self.assertEqual(ids, self.svc.prepare(self.MSGS, None, {}, 16)[0])
+
+
class GpuChoice(unittest.TestCase):
"""Issue #51: the config's \"gpu\" reaches the engine as CUDA_VISIBLE_DEVICES, numbered like nvidia-smi."""
diff --git a/src/core/conversation_cache_test.cpp b/src/core/conversation_cache_test.cpp
index f544dd743..c4883fe04 100644
--- a/src/core/conversation_cache_test.cpp
+++ b/src/core/conversation_cache_test.cpp
@@ -301,5 +301,29 @@ int main() {
r = cache.take_reuse();
check(r.kv.size() == 2 && r.stages.empty(), "no layer split: no stage reuse, as before");
}
+ { // pin=N: a parked conversation that holds a pinned shared prefix is not the one evicted
+ const size_t one = image({1,2,3}).bytes();
+ auto pinned = image({1,2,3});
+ pinned.checkpoints.push_back(ConversationCheckpoint{});
+ pinned.checkpoints.back().ids = {1,2};
+ pinned.checkpoints.back().pinned = true;
+ pinned.checkpoints.back().gdn.resize(64, 1);
+ const size_t pinned_bytes = pinned.bytes();
+ ConversationCache big(pinned_bytes + one * 2 + 64, 3);
+ check(pinned.pinned() && !image({1,2,3}).pinned(), "a conversation is pinned when one of its checkpoints is");
+ check(big.put(std::move(pinned)), "the pinned conversation is parked first (the oldest)");
+ check(big.put(image({7,8,9})) && big.put(image({4,5,6})) && big.size() == 3, "two more fill the slots");
+ check(big.put(image({10,11,12})) && big.size() == 3 && big.evictions() == 1,
+ "a fourth evicts the oldest unpinned one");
+ check(big.best(std::vector<int32_t>{1,2,9,9}, {}, true).tokens == 2, "the pinned prefix is still found");
+ ConversationCache tiny(pinned_bytes + 8, 2);
+ auto p2 = image({1,2,3});
+ p2.checkpoints.push_back(ConversationCheckpoint{});
+ p2.checkpoints.back().ids = {1,2};
+ p2.checkpoints.back().pinned = true;
+ p2.checkpoints.back().gdn.resize(64, 1);
+ check(tiny.put(std::move(p2)), "a pinned one fits an empty cache");
+ check(!tiny.put(image({7,8,9})) && tiny.size() == 1, "nothing else fits beside it: parking is refused, the pin stays");
+ }
std::printf("conversation_cache_test: %d checks passed\n", checks);
}
diff --git a/src/core/conversation_file.cpp b/src/core/conversation_file.cpp
index ab1ba2c1a..24291be55 100644
--- a/src/core/conversation_file.cpp
+++ b/src/core/conversation_file.cpp
@@ -1124,9 +1124,14 @@ std::vector<ConversationCheckpoint> session_checkpoints_to_save(const std::vecto
}
const ConversationCheckpoint* session_deepest_checkpoint(const std::vector<ConversationCheckpoint>& chain) {
+ // A pinned shared prefix (pin=N) is the resume point the next queries want, so with one in the chain the file
+ // keeps the deepest PINNED checkpoint, not a deeper periodic one a long private suffix made past it. No pin:
+ // the deepest, as before.
const ConversationCheckpoint* deepest = nullptr;
+ bool any_pinned = false;
+ for (const auto& c : chain) any_pinned = any_pinned || c.pinned;
for (const auto& c : chain)
- if (!deepest || c.ids.size() > deepest->ids.size()) deepest = &c;
+ if ((!any_pinned || c.pinned) && (!deepest || c.ids.size() > deepest->ids.size())) deepest = &c;
return deepest;
}
diff --git a/src/core/conversation_file_test.cpp b/src/core/conversation_file_test.cpp
index fa725d757..25f93b8a5 100644
--- a/src/core/conversation_file_test.cpp
+++ b/src/core/conversation_file_test.cpp
@@ -637,6 +637,12 @@ int main() {
SessionSaveLive live;
live.state_bytes = 5000; live.tokens = 1000; live.images = 1; live.kv_layers = 13;
check(session_deepest_checkpoint(chain) == &chain[1], "save: deepest chosen by reference");
+ { // pin=N: the pinned checkpoint is the one kept, even when a deeper periodic one exists
+ auto pinned_chain = chain;
+ pinned_chain[0].pinned = true;
+ check(session_deepest_checkpoint(pinned_chain) == &pinned_chain[0], "save: a pinned shared prefix beats a deeper checkpoint");
+ check(session_deepest_checkpoint(chain) == &chain[1], "save: no pin, the deepest as before");
+ }
const uint64_t need = session_save_peak_bytes(&chain[1], live);
check(need >= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (16u << 20) &&
need <= 2 * (uint64_t) chain[1].bytes() + 5000 + 4000 + (18u << 20),
diff --git a/src/program/conv_cache_test.cpp b/src/program/conv_cache_test.cpp
index 3c0e19383..d76c800b4 100644
--- a/src/program/conv_cache_test.cpp
+++ b/src/program/conv_cache_test.cpp
@@ -72,6 +72,21 @@ int main() {
check(eviction_victim(st.data(), st.size(), 6, t4) == 1, "the root is never the victim, tail flag or not");
check(eviction_victim(st.data(), st.size(), 6, nullptr) == 1, "no tail flags: the plain policy");
}
+ { // pin=N: a pinned shared prefix is never the victim, however stale its stamp
+ const std::vector<uint64_t> st = {1, 2, 30, 4, 5, 6, 7};
+ const bool pin1[7] = {false, true, false, false, false, false, false};
+ check(eviction_victim(st.data(), st.size(), 6, nullptr, pin1) == 3,
+ "the oldest checkpoint is pinned: the next least recently used leaves");
+ check(eviction_victim(st.data(), st.size(), 6, nullptr, nullptr) == 1, "no pin flags: the plain policy");
+ const bool pin2[7] = {false, true, false, true, false, false, false};
+ check(eviction_victim(st.data(), st.size(), 6, nullptr, pin2) == 4, "two pins: the third oldest leaves");
+ const bool tail3[7] = {false, false, false, true, false, false, false};
+ check(eviction_victim(st.data(), st.size(), 6, tail3, pin2) == 4, "a pinned item is not taken as the tail either");
+ const bool all[4] = {false, true, true, true};
+ const std::vector<uint64_t> s4 = {1, 9, 3, 5};
+ check(eviction_victim(s4.data(), s4.size(), 4, nullptr, all) == 2, "everything pinned: the oldest pin leaves, never the root");
+ check(eviction_victim(s4.data(), s4.size(), 1, nullptr, all) == 0, "a one-slot budget keeps no pin: the oldest leaves");
+ }
std::printf(g_fail ? "FAIL\n" : "PASS\n");
return g_fail ? 1 : 0;
}
diff --git a/src/program/generate.cpp b/src/program/generate.cpp
index 920eeda7a..b6738e713 100644
--- a/src/program/generate.cpp
+++ b/src/program/generate.cpp
@@ -6616,8 +6616,16 @@ int main(int argc, char** argv) {
// the tail checkpoint serves only a branch of the last request: it leaves before a periodic one
std::unique_ptr<bool[]> tail_flags(new bool[is_tail.size()]);
for (size_t i = 0; i < is_tail.size(); ++i) tail_flags[i] = is_tail[i] != 0;
+ // the pin=N prefix is never the victim (flags only when one is pinned: nothing changes without)
+ std::unique_ptr<bool[]> pin_flags;
+ for (const ConvCheckpoint& k : checks)
+ if (k.pinned) {
+ pin_flags.reset(new bool[checks.size()]);
+ for (size_t i = 0; i < checks.size(); ++i) pin_flags[i] = checks[i].pinned;
+ break;
+ }
const size_t victim = strata::program::conv_cache::eviction_victim(
- stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get());
+ stamps.data(), stamps.size(), o.prompt_cache, tail_flags.get(), pin_flags.get());
checks.erase(checks.begin() + (std::ptrdiff_t) victim);
}
return true;
@@ -8067,6 +8075,11 @@ int main(int argc, char** argv) {
// parked after it. It still resumes from a checkpoint it matches, and still saves the system-prompt root
// when that reaches --prompt-cache-root. Absent = checkpointed as before.
int req_ckpt = 1;
+ // pin=N: the first N prompt tokens are a shared read-only prefix (a long document that many short queries
+ // follow). The prompt is read in two parts at N, the checkpoint there is PINNED (retention never evicts it,
+ // a parked conversation holding it stays parked) and a later request that resumes from it does not park the
+ // branch it leaves: N queries cost one prefix, not N. Absent = as before.
+ int64_t req_pin = 0;
// tuning keys (setup's calibration measures settings without restarting the engine): the PCIe share of
// the missed experts and the draft-probability floor, for this request only
double req_pcie_frac = o.pcie_frac, req_spec_min_p = o.spec_min_p;
@@ -8084,6 +8097,7 @@ int main(int argc, char** argv) {
const float fv = std::strtof(tok.c_str() + eq + 1, nullptr);
if (key == "cvec") req_cvec = std::atoi(tok.c_str() + eq + 1);
else if (key == "ckpt") req_ckpt = std::atoi(tok.c_str() + eq + 1) != 0;
+ else if (key == "pin") req_pin = std::max<long long>(0, std::atoll(tok.c_str() + eq + 1));
else if (key == "temperature") req_temperature = fv;
else if (key == "top_p") req_top_p = fv;
else if (key == "top_k") req_top_k = std::atoi(tok.c_str() + eq + 1);
@@ -8315,7 +8329,16 @@ int main(int argc, char** argv) {
}
// Preserve the outgoing branch before any checkpoint rewind, reset,
// or incoming restore overwrites the positional state it requires.
- if ((!from_live || incoming || slot_source >= 0) && !park_current(incoming ? incoming->bytes() : 0)) {
+ // pin=N: this request resumes exactly at the pinned shared prefix of the conversation the session holds
+ // (a sibling query of the last one). What the last query added past it is its private suffix - a few
+ // dozen tokens, cheaper to read than the prefix's whole K/V is to copy to the host - so it is not parked:
+ // N queries keep one prefix. A request without pin=, or one that resumes anywhere else, parks as before.
+ bool pin_sibling = false;
+ if (req_pin > 0 && req_ckpt && o.prompt_cache >= 3 && !from_live && !incoming && slot_source < 0 &&
+ resume == req_pin && live_ok)
+ for (const ConvCheckpoint& c : checks)
+ if ((int64_t) c.ids.size() == resume && c.pinned) pin_sibling = true;
+ if ((!from_live || incoming || slot_source >= 0) && !pin_sibling && !park_current(incoming ? incoming->bytes() : 0)) {
std::printf("ERR %s\n", err.c_str());
return 1;
}
@@ -8969,8 +8992,36 @@ int main(int argc, char** argv) {
// Only add a snapshot; the existing token and image checks still decide reuse.
const int64_t message_at = message_checkpoint && !multi_gpu && o.prompt_cache > 0
? strata::program::message_checkpoint_boundary(ids, resume, turn_at, o.turn_token) : -1;
+ // pin=N (opt-in): one more place the prompt is read to and checkpointed. One pinned prefix at a time: a
+ // new pin replaces the old; it needs room for the root, the pin and a rotating checkpoint
+ int64_t pin_at = -1;
+ auto pin_checkpoint = [&](int64_t L) {
+ bool found = false;
+ for (ConvCheckpoint& c : checks) {
+ c.pinned = (int64_t) c.ids.size() == L;
+ found = found || c.pinned;
+ }
+ return found;
+ };
+ if (req_pin > 0) {
+ if (o.prompt_cache < 3 || !req_ckpt)
+ std::fprintf(stderr, "strata serve: pin=%lld ignored: %s\n", (long long) req_pin,
+ req_ckpt ? "it needs --prompt-cache 3 or more" : "ckpt=0 keeps no checkpoint");
+ else if (req_pin >= n - 1)
+ std::fprintf(stderr, "strata serve: pin=%lld ignored: the prefix must be shorter than the prompt "
+ "(%lld tokens)\n", (long long) req_pin, (long long) n);
+ else if (req_pin > read_from) pin_at = req_pin;
+ else if (!pin_checkpoint(req_pin))
+ std::fprintf(stderr, "strata serve: pin=%lld: the cache has no checkpoint there to pin (it resumed from "
+ "%lld)\n", (long long) req_pin, (long long) read_from);
+ }
+ std::vector<int64_t> cuts = {reread_to, root_at, message_at, turn_at, n - 1};
+ if (pin_at >= 0) {
+ cuts.push_back(pin_at);
+ std::sort(cuts.begin(), cuts.end()); // the skipped -1s first, n - 1 still last
+ }
int64_t at = read_from;
- for (const int64_t to : {reread_to, root_at, message_at, turn_at, n - 1}) {
+ for (const int64_t to : cuts) {
if (to <= at) continue;
err.clear();
const bool win = windows_ok(at, to);
@@ -9007,11 +9058,13 @@ int main(int argc, char** argv) {
break;
}
at = to;
- if ((to == turn_at || to == root_at || to == message_at) &&
- !checkpoint_at(to, nullptr, to == message_at && to != turn_at && to != root_at)) { // the tail kind leaves first
+ if ((to == turn_at || to == root_at || to == message_at || to == pin_at) &&
+ !checkpoint_at(to, nullptr, to == message_at && to != turn_at && to != root_at && to != pin_at)) { // the tail kind leaves first
std::printf("ERR saving a conversation checkpoint failed%s\n", ckpt_why.c_str());
return 1;
}
+ if (to == pin_at && !pin_checkpoint(pin_at))
+ std::fprintf(stderr, "strata serve: pin=%lld: its checkpoint was not kept\n", (long long) pin_at);
if (trace && to == message_at)
std::fprintf(stderr, "strata serve: message boundary checkpoint: %lld tokens, %lld tail\n",
(long long) message_at, (long long) (turn_at - message_at));