diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 0d07ca04..5822913c 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -857,6 +857,20 @@ follows the reused prefix (or the root) is read in one run, and its session is n It still starts from a checkpoint it matches, and still saves the system-prompt root when that reaches `--prompt-cache-root`. Without the field (or with `true`) nothing changes. +**One long document, many questions: a pinned shared prefix (opt-in, 0.1.40.2, [RESEARCH_RUNS.md](RESEARCH_RUNS.md)).** +A request can say where the document ends: `"strata_prefix": {"messages": 1}` (the first message is the document), +`{"message": 0, "chars": 210000}` (the first 210,000 characters of message 0, for a client that sends the document and +the question in one message) or `{"tokens": 12345}`. The engine reads the prompt in two parts there, keeps the checkpoint +at the boundary pinned (retention never evicts it, a parked conversation holding it stays parked, `SAVE` keeps it) and, +when a later question resumes from it, does not park the question it leaves. So the next question starts at the end of +the document, and 20 questions cost one read of it. Without the field the server's checkpoints are where they were: the +last turn's start, the system prompt's end and every `--prompt-cache-every` tokens, so a question that follows a long +document in the same chat re-reads up to 16K tokens of it (55 s at 262K on a Tesla P100). The field is checked against the +prompt's own ids (the prefix is always the longest common start), a prefix that cannot be marked is said in the server's +window and ignored, and a malformed field is a 400. One pinned prefix at a time per engine (a new one replaces it); +it needs `--prompt-cache 3` or more. `tools/research_run.py` runs a document and a question list against a server with and +without it. The engine's own key is `pin=N` on the `GEN` line. + **Multiple conversations (opt-in).** Add `--conversation-cache-mib 8192 --conversation-cache-slots 4` to the engine arguments to park up to four conversations in a bounded 8 GiB host-RAM cache. This preserves controller/worker histories when diff --git a/docs/RESEARCH_RUNS.md b/docs/RESEARCH_RUNS.md new file mode 100644 index 00000000..49fec87b --- /dev/null +++ b/docs/RESEARCH_RUNS.md @@ -0,0 +1,60 @@ +# One long document, many questions (0.1.40.2, opt-in) + +Read a long document once, then ask many different questions without reading it again. All numbers: Tesla P100 16 GB, +IQ2_XS, `--kv int8 --kv-resident 32768`, MTP on, greedy, the 0.1.40 engine unless a row says "pin". + +## What the engine already did (0.1.40) + +The conversation cache keeps small checkpoints (the GDN and indexer state, about 118 MiB each); the K/V of the document +stays in the session, so a question that starts from a checkpoint reads only what lies past it. + +| 262K document (258,655 tokens) | time to first token | +|---|---| +| first question (cold read) | 904 s (286 tok/s) | +| questions 2-20, engine with a turn boundary at the document's end | 0.53 s median (0.44-0.72) | +| the same through the server's chat API (no turn boundary at the document's end) | 55.5 s each (15 measured): the engine re-reads up to `--prompt-cache-every` (16,384) tokens from the last periodic checkpoint | +| `parallel` 2 through the server | the first two questions 918 s and 979 s; the next pair read the document again from token 0 | + +Checkpoint RAM: +804 MiB resident after the first read (6 checkpoints); each later question adds at most 10 MiB. The +K/V of 262K takes 3.06 GiB of pinned RAM, once per session (`--batch` slots each take their own). +Identity (greedy, 64 tokens): questions 1 and 12 on a fresh engine give the same tokens as in the 20-question run. +Caveat: IQ models are not byte-reproducible at temperature 0 between runs unless `STRATA_IQ_MT_MIN=1` (DETAILS.md); +some answers differ between two runs of the same prompt for that reason, with or without the field below. + +## `strata_prefix` (and the engine's `pin=N`) + +`"strata_prefix": {"messages": 1}`, `{"message": 0, "chars": N}` or `{"tokens": N}` marks the start of the prompt as the +shared document. The checkpoint at its end is pinned: never evicted, kept in the parked-conversation budget, kept by +`SAVE`, and a question that resumes from it does not park the branch it leaves. + +| 64K document (P100) | no field | with the field | +|---|---|---| +| engine, raw prompts, questions 2-5 | 48.6 s | 0.35-0.53 s | +| a 100K-token branch between two questions, then a question | 149 s | 0.55 s | +| another 20K prompt between (`--conversation-cache-mib 8192`) | 49 s | 0.97 s (restored), then 0.44 s | +| server, 18K-token document, split messages / one message | 8.8 s | 0.6-0.8 s | +| server `parallel` 2, six questions | 730 s (every pair re-reads) | 220 s (questions 3-6: 2.5-3.8 s) | + +Copy-on-write K/V pages across `--batch` slots are NOT built: each slot keeps its own K/V (3.06 GiB at 262K, about 12 GiB +at 1M), and admitting a branch copies the prefix K/V (3 s at 262K). The pinned prefix removes the re-read, not the copy. + +`tools/research_run.py` runs a document and a question list against a server with and without the field. + +## R3: expert slots against K/V blocks (P100, IQ2_XS) + +64K document, 5 questions. Prefill, then median first token of a short question, then decode: + +| expert slots (GiB) | prefill | first token | decode | +|---|---|---|---| +| 2,083 (2.81) | 230 s | 0.69 s | 27.5 tok/s | +| 3,500 | 200.7 s | 0.61 s | 30.9 | +| 5,000 | 200.7 s | 0.55 s | 34.2 | +| 7,000 | 200.7 s | 0.51 s | 36.7 | + +Marginal value of VRAM: decode 0.31-0.41 s per GiB per 200-token answer between 2,000 and 5,000 slots, 0.15 above; +prefill gains only below the prompt loan's floor. K/V cells in VRAM (`--kv-resident`): 4096 / 16384 / 32768 / 65536 give +34.05 / 34.06 / 34.21 / 34.92 tok/s at 64K; at 262K (5,000 slots) 8192 / 32768 / 131072 give 29.54 / 29.46 / 29.49 tok/s +(block hit rate 92.6 / 94.5 / 95.7 %). So the K/V block cache is worth nothing per GiB, experts only help decode, and the +read is already served by the loan. A split planner would gain almost nothing, so none was built. The one real lever in +the read is the chunk: `--prefill 16384` with 7,000 slots reads 64K in 186.4 s against 200.7 s (-7%), and 4096 takes 228 s; +it needs the larger loan and changes the chunking, hence the rounding, so it is not a placement-only change. diff --git a/include/strata/core/conversation_cache.hpp b/include/strata/core/conversation_cache.hpp index 86e04c6b..305d352b 100644 --- a/include/strata/core/conversation_cache.hpp +++ b/include/strata/core/conversation_cache.hpp @@ -25,6 +25,10 @@ struct ConversationCheckpoint { std::vector imgs; std::vector 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 stage_parts; @@ -95,7 +99,7 @@ inline ConversationCheckpointSplit conversation_checkpoints_split(std::vector 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); @@ -251,8 +261,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 100856f0..07c23ade 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 bd8f0a3a..fd90e3cd 100644 --- a/serve/server.py +++ b/serve/server.py @@ -887,6 +887,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 @@ -2899,7 +2906,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.""" @@ -2974,8 +2981,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 @@ -4541,7 +4624,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 @@ -4716,12 +4799,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 @@ -4755,7 +4838,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 c2bf362e..fe374614 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -1514,6 +1514,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 f544dd74..c4883fe0 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{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 ab1ba2c1..24291be5 100644 --- a/src/core/conversation_file.cpp +++ b/src/core/conversation_file.cpp @@ -1124,9 +1124,14 @@ std::vector session_checkpoints_to_save(const std::vecto } const ConversationCheckpoint* session_deepest_checkpoint(const std::vector& 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 fa725d75..25f93b8a 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 3c0e1938..d76c800b 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 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 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 3fbf4a18..cdab2706 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -7010,8 +7010,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 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 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; @@ -8605,6 +8613,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; @@ -8622,6 +8635,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(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); @@ -8853,7 +8867,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; } @@ -9509,8 +9532,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 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); @@ -9547,11 +9598,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)); diff --git a/tools/research_run.py b/tools/research_run.py new file mode 100644 index 00000000..ec02c40a --- /dev/null +++ b/tools/research_run.py @@ -0,0 +1,144 @@ +"""A scripted research run against a running Strata server: one long document, then many different questions. + +Reads the document once, then asks each question and reports, per question, the time to the first streamed token and +the whole request, and the run's total. Greedy (temperature 0), so two runs of the same file give the same answers and +a change in how the server keeps the document (the shared prefix below) can be compared answer by answer. + + python tools/research_run.py --url http://127.0.0.1:8080 --doc paper.txt --questions questions.txt + python tools/research_run.py --doc paper.txt --questions q.txt --prefix off --json base.json + python tools/research_run.py --doc paper.txt --questions q.txt --prefix on --json fork.json + python tools/research_run.py --compare base.json fork.json + +--layout split (the default): the document is the first message, the question the second. +--layout joined: one message, "document + question" (a client that cannot split them). +--prefix on: the request carries "strata_prefix" naming the document as the shared prefix (docs/DETAILS.md): the +server reads it once and every question starts from it. off: the field is left out. +--parallel N: N questions at a time (the server needs "parallel": N for them to run together). +""" +from __future__ import annotations + +import argparse +import json +import statistics +import sys +import threading +import time +import urllib.request +from pathlib import Path + + +def request_body(doc: str, question: str, layout: str, prefix: bool, max_tokens: int, model: str | None) -> dict: + if layout == "joined": + body = {"messages": [{"role": "user", "content": doc + "\n\nQuestion: " + question + "\nAnswer:"}]} + if prefix: + body["strata_prefix"] = {"message": 0, "chars": len(doc) + 2} + else: + body = {"messages": [{"role": "user", "content": doc}, {"role": "user", "content": question}]} + if prefix: + body["strata_prefix"] = {"messages": 1} + body.update(temperature=0, max_tokens=max_tokens, stream=True) + if model: + body["model"] = model + return body + + +def ask(url: str, body: dict, headers: dict, timeout: float) -> dict: + t0 = time.time() + req = urllib.request.Request(url + "/v1/chat/completions", data=json.dumps(body).encode(), headers=headers) + first, parts = None, [] + with urllib.request.urlopen(req, timeout=timeout) as r: + for raw in r: + line = raw.decode("utf-8", "replace").strip() + if not line.startswith("data:") or line.endswith("[DONE]"): + continue + event = json.loads(line[5:]) + for choice in event.get("choices", []): + delta = choice.get("delta", {}) + piece = (delta.get("reasoning_content") or "") + (delta.get("content") or "") + if piece and first is None: + first = time.time() - t0 + parts.append(piece) + return {"ttft_s": round(first or 0.0, 3), "wall_s": round(time.time() - t0, 2), "text": "".join(parts)} + + +def run(args) -> dict: + doc = Path(args.doc).read_text(encoding="utf-8", errors="replace") + if args.limit_chars: + doc = doc[:args.limit_chars] + questions = [x.strip() for x in Path(args.questions).read_text(encoding="utf-8").splitlines() if x.strip()] + questions = questions[:args.n] if args.n else questions + headers = {"Content-Type": "application/json"} + if args.api_key: + headers["Authorization"] = "Bearer " + args.api_key + rows: list[dict | None] = [None] * len(questions) + started = time.time() + for k in range(0, len(questions), max(1, args.parallel)): + group = list(range(k, min(k + max(1, args.parallel), len(questions)))) + + def one(i): + try: + rows[i] = {"q": i, **ask(args.url, request_body(doc, questions[i], args.layout, args.prefix == "on", + args.max_tokens, args.model), headers, args.timeout)} + except Exception as e: # noqa: BLE001 - a failed question is reported, the run goes on + rows[i] = {"q": i, "error": repr(e)} + threads = [threading.Thread(target=one, args=(i,)) for i in group] + [t.start() for t in threads] + [t.join() for t in threads] + for i in group: + r = rows[i] + print(f"q{i:02d} first token {r.get('ttft_s', '-')} s total {r.get('wall_s', '-')} s " + f"{r.get('error') or repr(r['text'][:60])}", flush=True) + out = {"url": args.url, "layout": args.layout, "prefix": args.prefix, "doc_chars": len(doc), "questions": rows, + "total_s": round(time.time() - started, 1)} + later = [r["ttft_s"] for r in rows[1:] if r and "ttft_s" in r] + if later: + out["first_token_median_after_first_s"] = round(statistics.median(later), 3) + print(f"total {out['total_s']} s" + (f", median first token after the first question {out['first_token_median_after_first_s']} s" + if later else ""), flush=True) + return out + + +def compare(a_path: str, b_path: str) -> int: + a, b = (json.loads(Path(p).read_text(encoding="utf-8")) for p in (a_path, b_path)) + same = diff = 0 + for x, y in zip(a["questions"], b["questions"]): + if "text" in x and "text" in y: + if x["text"] == y["text"]: + same += 1 + else: + diff += 1 + print(f"q{x['q']:02d}: the answers differ") + print(f"{same} answers identical, {diff} differ; total {a['total_s']} s -> {b['total_s']} s; median first token " + f"{a.get('first_token_median_after_first_s')} s -> {b.get('first_token_median_after_first_s')} s") + return 1 if diff else 0 + + +def main(argv=None) -> int: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--url", default="http://127.0.0.1:8080") + ap.add_argument("--api-key", default="") + ap.add_argument("--model", default=None) + ap.add_argument("--doc") + ap.add_argument("--questions", help="a text file, one question per line") + ap.add_argument("--n", type=int, default=0, help="only the first N questions") + ap.add_argument("--layout", choices=("split", "joined"), default="split") + ap.add_argument("--prefix", choices=("on", "off"), default="on") + ap.add_argument("--parallel", type=int, default=1) + ap.add_argument("--max-tokens", type=int, default=128) + ap.add_argument("--limit-chars", type=int, default=0, help="use only the first N characters of the document") + ap.add_argument("--timeout", type=float, default=7200.0) + ap.add_argument("--json", help="write the per-question results here") + ap.add_argument("--compare", nargs=2, metavar=("A.json", "B.json"), help="compare two saved runs' answers and times") + args = ap.parse_args(argv) + if args.compare: + return compare(*args.compare) + if not args.doc or not args.questions: + ap.error("--doc and --questions are needed") + out = run(args) + if args.json: + Path(args.json).write_text(json.dumps(out, indent=1), encoding="utf-8") + return 1 if any("error" in r for r in out["questions"]) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/test_research_run.py b/tools/test_research_run.py new file mode 100644 index 00000000..0f5aa02f --- /dev/null +++ b/tools/test_research_run.py @@ -0,0 +1,89 @@ +"""Offline test of tools/research_run.py against the server's mock engine (no GPU, no pack).""" +import contextlib +import io +import json +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +sys.path.insert(0, str(ROOT / "tools")) +import research_run # noqa: E402 +from serve.frontend import ChatTemplate # noqa: E402 +from serve.server import ByteTokenizer, MockEngine, Service, serve # noqa: E402 + + +class Recorder(MockEngine): + def __init__(self, *a, **k): + super().__init__(*a, **k) + self.samplings = [] + + def generate(self, ids, max_new, sampling, cancel, embeddings=None): + self.samplings.append(dict(sampling)) + yield from super().generate(ids, max_new, sampling, cancel, embeddings) + + +class ResearchRun(unittest.TestCase): + @classmethod + def setUpClass(cls): + tok = ByteTokenizer() + cls.engine = Recorder(tok, "an answer", max_context=8192) + cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + cls.httpd = serve(cls.svc, port=0) + cls.url = f"http://127.0.0.1:{cls.httpd.server_address[1]}" + cls.dir = tempfile.TemporaryDirectory() + d = Path(cls.dir.name) + (d / "doc.txt").write_text("The document. " * 40, encoding="utf-8") + (d / "q.txt").write_text("What is it?\nWho wrote it?\n\nWhen?\n", encoding="utf-8") + + @classmethod + def tearDownClass(cls): + cls.httpd.shutdown() + cls.httpd.server_close() + cls.dir.cleanup() + + def go(self, *extra): + d = Path(self.dir.name) + out = d / "out.json" + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = research_run.main(["--url", self.url, "--doc", str(d / "doc.txt"), "--questions", str(d / "q.txt"), + "--json", str(out), *extra]) + return code, json.loads(out.read_text(encoding="utf-8")), buf.getvalue() + + def test_split_run_names_the_prefix_and_reports_every_question(self): + self.engine.samplings.clear() + code, out, text = self.go("--prefix", "on") + self.assertEqual(code, 0, text) + self.assertEqual([q["q"] for q in out["questions"]], [0, 1, 2]) # the blank line is skipped + self.assertTrue(all(q["text"] for q in out["questions"])) + self.assertEqual(len(self.engine.samplings), 3) + for s in self.engine.samplings: + self.assertEqual(s["strata_prefix"]["tokens"] > 0, True) # resolved by the server + self.assertIn("median first token", text) + + def test_prefix_off_and_the_joined_layout(self): + self.engine.samplings.clear() + self.go("--prefix", "off") + self.assertTrue(all("strata_prefix" not in s for s in self.engine.samplings)) + self.engine.samplings.clear() + code, out, _ = self.go("--prefix", "on", "--layout", "joined", "--parallel", "2") + self.assertEqual(code, 0) + self.assertTrue(all(s["strata_prefix"]["tokens"] > 0 for s in self.engine.samplings)) + + def test_compare(self): + d = Path(self.dir.name) + self.go("--prefix", "off") + (d / "a.json").write_text((d / "out.json").read_text(encoding="utf-8"), encoding="utf-8") + self.go("--prefix", "on") + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + code = research_run.main(["--compare", str(d / "a.json"), str(d / "out.json")]) + self.assertEqual(code, 0, buf.getvalue()) + self.assertIn("3 answers identical, 0 differ", buf.getvalue()) + + +if __name__ == "__main__": + unittest.main()