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: tokenise the prompt from the last shared prefix, not from the start (#1852, #567)
Niko1221f13a870d52bc
diff --git a/SECURITY.md b/SECURITY.mdindex 94be4eade..476dab975 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -39,6 +39,8 @@ this PC only. The details and every setting are in [docs/DETAILS.md](docs/DETAIL- **MCP tools** are opt-in: only the servers you put in the run config, only for requests from Strata's own pagethat ask for them. They run with your user's rights, and the model decides when to call them.- **The request monitor** (`/api-monitor`, which keeps the last prompts and answers in memory) is off unless- `"api_monitor": true` is set.+ `"api_monitor": true` is set. Apart from it, the server keeps in its process memory the text and tokens of its+ last few prompts, whatever `"api_monitor"` says, to encode the next turn faster; no endpoint shows them, and they+ are gone when the server stops.Strata has not had an outside security audit yet.diff --git a/serve/server.py b/serve/server.pyindex 5ca7f4e4d..0212dc951 100644--- a/serve/server.py+++ b/serve/server.py@@ -705,6 +705,19 @@ class ConvCacheLog:return dict(self.state)+def conversation_slots(engine) -> int | None:+ """How many conversations the engine's cache holds: its --conversation-cache-slots argument, which is known+ before the engine has started (a lazy start has reported no INFO line yet), else the INFO line it reported."""+ args = engine.spawn[1] if hasattr(engine, "spawn") else []+ if "--conversation-cache-slots" in args[:-1]:+ try:+ return int(args[args.index("--conversation-cache-slots") + 1])+ except ValueError:+ pass+ slots = (getattr(engine, "info", None) or {}).get("conversation_cache_slots")+ return slots if isinstance(slots, int) else None++def conversation_cache_view(info: dict, hist: list, totals: dict, parked: dict) -> dict:"""#596: the Monitor's Conversation cache card: the parked conversations (the engine's opt-in--conversation-cache-mib: budget, slots, what its log says) and how much of the prompts the cache gave back."""@@ -2868,23 +2881,32 @@ class ByteTokenizer:ALWAYS = () # specials matched without parse_special (type 4, as <think>)+ @property+ def max_special_len(self):+ return max(len(s) for s in self.SPECIALS)+@propertydef control_tokens(self):return [s for s in self.SPECIALS if s not in self.ALWAYS]def encode(self, text, parse_special=False, plain=()):- out, i = [], 0+ return self.encode_marked(text, parse_special, plain)[0]++ def encode_marked(self, text, parse_special=False, plain=()):+ """encode() and its resume points (after each special), as strata_tokenizer's for PromptEncoder."""+ out, marks, i = [], [], 0while i < len(text):for k, s in enumerate(self.SPECIALS):if (parse_special or s in self.ALWAYS) and text.startswith(s, i) and not any(a <= i < b for a, b in plain):out.append(256 + k)i += len(s)+ marks.append((i, len(out)))breakelse:out.extend(text[i].encode("utf-8"))i += 1- return out+ return out, marksdef decode(self, ids, errors="replace"):raw = bytearray()@@ -3104,6 +3126,17 @@ class Service:self.restore_after_load = None # a session file an image job saved before it unloadedself.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +tokenizer.encode("<|endoftext|>", parse_special=True))+ # #567: a prompt re-encodes only what follows the last special token it shares with a recent prompt (the+ # same ids as a full encode: tools/strata_tokenizer.py PromptEncoder). Tokenizers without resume points+ # encode in full.+ self.prompts = None+ if hasattr(tokenizer, "encode_marked") and hasattr(tokenizer, "max_special_len"):+ from strata_tokenizer import PromptEncoder+ # one kept prompt per conversation the engine's cache can hold (--conversation-cache-slots); the+ # encoder's own default without that setting+ slots = conversation_slots(engine)+ self.prompts = PromptEncoder(tokenizer, keep=slots) if slots is not None and slots > 0 \+ else PromptEncoder(tokenizer)def loaded(self) -> bool:return not hasattr(self.engine, "alive") or self.engine.alive()@@ -3787,17 +3820,21 @@ class Service:tail = "" if off else EFFORT_TURN.format(EFFORT_TEXT.get(effort, EFFORT_TEXT["medium"]))return history + tail + full[len(mine):]- def encode_prompt(self, messages, tools, kwargs) -> list[int]:+ def encode_prompt(self, messages, tools, kwargs, store: bool = True) -> list[int]:"""The request's prompt: the template rendered and tokenized. #537: a <think> / </think> written inside amessage's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).A control token's text (<|im_start|>, <|im_end|>, <|endoftext|>, ...) inside a message is text as well: only- the control tokens the template writes are control tokens."""+ the control tokens the template writes are control tokens. `store=False` (a token count) reuses the kept+ prompts without adding or replacing one."""marked, marked_tools, changed = mark_think_literals(messages, tools, self.literals)prompt = self.render_prompt(marked, marked_tools, kwargs)- if not changed:- return self.tok.encode(prompt, parse_special=True)- prompt, plain = unmark_think_literals(prompt, self.literals)- return self.tok.encode(prompt, parse_special=True, plain=plain)+ plain = ()+ if changed:+ prompt, plain = unmark_think_literals(prompt, self.literals)+ if self.prompts is not None: # #567: only what follows the last special shared with a recent prompt+ return self.prompts.encode(prompt, plain, store)+ return self.tok.encode(prompt, parse_special=True, plain=plain) if plain else \+ self.tok.encode(prompt, parse_special=True)@contextlib.contextmanagerdef _turn(self, cancel=None):@@ -3845,6 +3882,11 @@ class Service:content[n] = {"type": "text", "text": f"[image omitted: {why}]"}return fetched+ def forget_prompt(self, ids):+ if self.prompts is not None:+ self.prompts.forget(ids)++def prepare(self, messages, tools, kwargs, max_new=None, force=None, req=None, cancel=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@@ -3852,7 +3894,7 @@ class Service:# `cancel` (#1999): set when the client hangs up; the downloads, the wait for the turn and the encodes stop# between pictures and raise ClientGonefetched = self._note_unreadable_tool_images(messages, cancel)- ids = self.encode_prompt(messages, tools, kwargs)+ ids = encoded_ids = self.encode_prompt(messages, tools, kwargs)if force and kwargs.get("enable_thinking", True) is False:ids = ids + self.tok.encode(force, parse_special=True)self.embeddings.path = None@@ -3914,12 +3956,16 @@ class Service:room = ctx - CTX_SLACK - len(ids)if max_new is None or max_new <= 0 or (self.fit_max_tokens and room < 1):if room < 1:+ # A prompt refused for the context is not kept (#567): the client cannot resend it unchanged. The+ # other refusals (engine starting, images) keep it: the same prompt comes back and its encode is reused.+ self.forget_prompt(encoded_ids)raise ValueError("request exceeds the context window: "f"prompt ({len(ids)} tokens) leaves no room to answer in the context "f"({ctx}); requests are never truncated")max_new = roomelif max_new > room:if not self.fit_max_tokens:+ self.forget_prompt(encoded_ids)raise ValueError("request exceeds the context window: "f"prompt ({len(ids)} tokens) + max tokens ({max_new}) exceeds the context "f"({ctx}); requests are never truncated. Send a smaller "@@ -6045,7 +6091,7 @@ def make_handler(svc: Service):messages, tools, kw = anthropic_to_messages(req, svc.anthropic_think_unasked)stop_strings(req) # the same 400 as the request itself would getcheck_request_sampling(req) # ... likewise a sampling field of the wrong type- self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw))})+ self._json(200, {"input_tokens": len(svc.encode_prompt(messages, tools, kw, store=False))})def _anthropic(self, req):svc.load()diff --git a/serve/test_prompt_encoder.py b/serve/test_prompt_encoder.pynew file mode 100644index 000000000..36cc06f29--- /dev/null+++ b/serve/test_prompt_encoder.py@@ -0,0 +1,162 @@+"""serve/test_prompt_encoder.py - #567's incremental prompt encoding with #537's plain spans: every prompt's ids+are those of a full encode, and a turn reuses the previous one's.++ python -m unittest serve.test_prompt_encoder -v+"""+from __future__ import annotations++import random+import re+import sys+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"))+from serve.frontend import ChatTemplate # noqa: E402+from serve.server import ByteTokenizer, MockEngine, Service # noqa: E402+from strata_tokenizer import PromptEncoder, plain_agree_until # noqa: E402+++class ThinkTokenizer(ByteTokenizer):+ """ByteTokenizer whose <think> / </think> are specials matched even without parse_special (type 4), as in the+ Qwen vocabulary: the case #537's plain spans exist for."""+ SPECIALS = ByteTokenizer.SPECIALS + ["<think>", "</think>"]+ ALWAYS = ("<think>", "</think>")+++PIECES = ["<|im_start|>user\n", "<|im_end|>\n", "<think>", "</think>", "hello ", "é你 ", "<|im_sta", "x" * 7,+ "<|im_start|>assistant\n", "</thi", "\n\n", "<|endoftext|>", "<|vision_start|>", "<|image_pad|>"]+++def spans_of(text, rng):+ """Random plain spans over the specials' texts (<think>, </think>, <|im_start|>, ...), as unmark_think_literals+ marks the ones quoted inside a message."""+ matches = re.finditer("|".join(map(re.escape, ThinkTokenizer.SPECIALS)), text)+ return tuple((m.start(), m.end()) for m in matches if rng.random() < 0.5) # finditer: left to right, no overlap+++class Units(unittest.TestCase):+ def test_plain_agree_until(self):+ self.assertEqual(plain_agree_until((), (), 50), 50)+ self.assertEqual(plain_agree_until(((5, 13),), ((5, 13),), 50), 50)+ self.assertEqual(plain_agree_until(((5, 13),), (), 50), 5)+ self.assertEqual(plain_agree_until(((5, 13),), ((5, 9),), 50), 9)+ self.assertEqual(plain_agree_until(((60, 70),), (), 50), 50) # beyond the shared text: no matter+ self.assertEqual(plain_agree_until(((5, 13), (20, 28)), ((5, 13),), 50), 20)++ def test_same_ids_as_a_full_encode(self):+ tok = ThinkTokenizer()+ rng = random.Random(7)+ for conv in range(300):+ enc = PromptEncoder(tok)+ text, plain = "", ()+ for turn in range(8):+ text += "".join(rng.choice(PIECES) for _ in range(rng.randint(1, 12)))+ if rng.random() < 0.6:+ plain = spans_of(text, rng) # the spans may change in the shared part too+ with self.subTest(conv=conv, turn=turn):+ self.assertEqual(enc.encode(text, plain), tok.encode(text, True, plain))+ if rng.random() < 0.2 and len(text) > 10: # an edit: a client re-rendering its history+ cut = rng.randrange(len(text))+ text = text[:cut]+ plain = tuple((a, b) for a, b in plain if b <= cut)++ def test_a_turn_reuses_the_previous_one(self):+ tok = ThinkTokenizer()+ enc = PromptEncoder(tok)+ # as a chat turn: the earlier prompt goes on past its last special (the answer being written), and the+ # next one shares it up to there - the resume point needs max_special_len characters after it+ base = "<|im_start|>user\n" + "quoted </think> here " * 200 + "<|im_end|>\n<|im_start|>assistant\nan answer"+ plain = tuple((i, i + 8) for i in range(len(base)) if base.startswith("</think>", i))+ enc.encode(base, plain)+ more = base + " that goes on<|im_end|>\n<|im_start|>user\nnext<|im_end|>\n"+ self.assertEqual(enc.encode(more, plain), tok.encode(more, True, plain))+ self.assertGreater(enc.last_reused, len(base) // 2)+ # the same text with the quoted </think> no longer plain: nothing before it may be reused past its start+ self.assertEqual(enc.encode(more, ()), tok.encode(more, True, ()))+ self.assertLessEqual(enc.last_reused, plain[0][0])+++class Served(unittest.TestCase):+ def test_quoted_think_across_turns(self):+ tok = ThinkTokenizer()+ template = ChatTemplate(ROOT / "serve/chat_template.jinja")+ svc = Service(MockEngine(tok, "</think>\n\nok", max_context=1 << 20), tok, template)+ full = Service(MockEngine(tok, "</think>\n\nok", max_context=1 << 20), tok, template)+ full.prompts = None # the reference: a full encode every time+ self.assertIsNotNone(svc.prompts)+ msgs = [{"role": "system", "content": "Explain tags."}]+ for turn in range(5):+ msgs.append({"role": "user", "content": f"turn {turn}: what does </think> mean? <think> too " * 3})+ got, want = svc.encode_prompt(msgs, None, {}), full.encode_prompt(msgs, None, {})+ self.assertEqual(got, want)+ if turn:+ self.assertGreater(svc.prompts.last_reused, 0)+ msgs.append({"role": "assistant", "content": "It closes the reasoning: </think> is a marker."})++ def service(self, max_context=1 << 22):+ tok = ByteTokenizer()+ return Service(MockEngine(tok, "ok", max_context=max_context), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))++ def test_another_conversation_does_not_evict_the_first(self):+ """A subagent beside the main conversation: every rendered prompt starts with the template's header, which+ must not make the second client's prompt a continuation of the first's entry."""+ svc = self.service()+ turn2 = [{"role": "user", "content": "a long question " * 500}, {"role": "assistant", "content": "answer"},+ {"role": "user", "content": "next"}]+ svc.encode_prompt(turn2, None, {})+ svc.encode_prompt([{"role": "user", "content": "one unrelated prompt " * 300}], None, {})+ self.assertEqual(len(svc.prompts.entries), 2)+ turn3 = turn2 + [{"role": "assistant", "content": "x"}, {"role": "user", "content": "more"}]+ svc.encode_prompt(turn3, None, {})+ self.assertGreater(svc.prompts.last_reused, len(turn2[0]["content"]))+ self.assertEqual(len(svc.prompts.entries), 2) # turn 3 replaced turn 2, the other one stayed++ def test_a_refused_prompt_is_not_kept(self):+ svc = self.service(max_context=4096)+ msgs = [{"role": "user", "content": "kept " * 20}]+ svc.prepare(msgs, None, {}, 16)+ refused = msgs + [{"role": "assistant", "content": "a"}, {"role": "user", "content": "more " * 20}]+ full = self.service(max_context=4096)+ full.prompts = None+ refused_ids = full.encode_prompt(refused, None, {})+ with self.assertRaisesRegex(ValueError, "exceeds the context"):+ svc.prepare(refused, None, {}, 1 << 20)+ self.assertNotIn(refused_ids, [e[2] for e in svc.prompts.entries])+ self.assertNotIn(full.render_prompt(refused, None, {}), [e[0] for e in svc.prompts.entries])++ def test_random_messages_equal_a_full_encode(self):+ """Messages quoting control-token texts and <think> tags at random, growing, edited and cut back between+ requests: the incremental encoder's ids are the full encode's, 2400 prompts."""+ tok = ThinkTokenizer()+ template = ChatTemplate(ROOT / "serve/chat_template.jinja")+ svc = Service(MockEngine(tok, "ok", max_context=1 << 20), tok, template)+ full = Service(MockEngine(tok, "ok", max_context=1 << 20), tok, template)+ full.prompts = None+ rng = random.Random(567)+ quoted = ThinkTokenizer.SPECIALS + ["<|im_sta", "</thi"]+ words = ["hello ", "é你 ", "x" * 9, "\n", "tool "]++ def text():+ return "".join(rng.choice(quoted if rng.random() < 0.4 else words) for _ in range(rng.randint(1, 10)))++ reused = 0+ for conv in range(300):+ msgs = [{"role": "system", "content": text()}]+ for turn in range(8):+ msgs.append({"role": "user", "content": text()})+ if rng.random() < 0.15: # an earlier turn edited by the client+ msgs[rng.randrange(len(msgs))]["content"] = text()+ if rng.random() < 0.1 and len(msgs) > 2: # a shorter conversation+ msgs = msgs[:rng.randrange(1, len(msgs))] + msgs[-1:]+ with self.subTest(conv=conv, turn=turn):+ self.assertEqual(svc.encode_prompt(msgs, None, {}), full.encode_prompt(msgs, None, {}))+ reused += svc.prompts.last_reused > 0+ msgs.append({"role": "assistant", "content": text()})+ self.assertGreater(reused, 1000)+++if __name__ == "__main__":+ unittest.main()diff --git a/serve/test_server.py b/serve/test_server.pyindex 3a49ff255..5a1734a21 100644--- a/serve/test_server.py+++ b/serve/test_server.py@@ -1771,6 +1771,144 @@ class RecordingPrompt(MockEngine):yield from super().generate(ids, max_new, sampling, cancel, embeddings)+class IncrementalPrompts(unittest.TestCase):+ """The prompt encoder: every request's ids are those of a full encode, and a turn reuses the previous one's."""++ @classmethod+ def setUpClass(cls):+ tok = ByteTokenizer()+ cls.engine = RecordingPrompt(tok, "Thinking.\n</think>\n\nThe answer.", max_context=CTX)+ cls.svc = Service(cls.engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))+ cls.httpd = serve(cls.svc, port=0)+ cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"++ @classmethod+ def tearDownClass(cls):+ cls.httpd.shutdown()+ cls.httpd.server_close()++ post = ClientShapes.post++ def test_turns(self):+ self.assertIsNotNone(self.svc.prompts)+ full = Service(self.engine, self.svc.tok, self.svc.template)+ full.prompts = None # the reference: the same prompt, encoded in full+ msgs = [{"role": "system", "content": "Be brief."}]+ for turn in range(6):+ msgs.append({"role": "user", "content": f"question {turn} <|im_end|> é你 " * (turn + 1)})+ status, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 64, "messages": msgs})+ self.assertEqual(status, 200, b)+ prompt = self.svc.template.render(msgs)+ self.assertEqual(self.engine.last_ids, full.encode_prompt(msgs, None, {}))+ if turn:+ self.assertGreater(self.svc.prompts.last_reused, len(prompt) // 3)+ msgs.append({"role": "assistant", "content": b["choices"][0]["message"]["content"]})++ def conversation(self, n):+ """Messages of the n-th conversation: distinct from every other one from the number on."""+ return [{"role": "user", "content": f"conversation {n} says: " + f"topic {n} sentence {n} " * 20}]++ def service(self, **info):+ engine = RecordingPrompt(self.svc.tok, "The answer.", max_context=CTX)+ engine.info = info+ return Service(engine, self.svc.tok, self.svc.template)++ def test_the_kept_prompts_follow_the_engines_conversation_slots(self):+ svc = self.service(conversation_cache_slots=8)+ texts = []+ for n in range(8):+ msgs = self.conversation(n)+ svc.encode_prompt(msgs, None, {})+ texts.append(svc.render_prompt(msgs, None, {}))+ self.assertEqual(len(svc.prompts.entries), 8)+ self.assertEqual(sorted(e[0] for e in svc.prompts.entries), sorted(texts))+ msgs = self.conversation(8)+ svc.encode_prompt(msgs, None, {})+ kept = sorted(e[0] for e in svc.prompts.entries)+ self.assertEqual(len(kept), 8)+ self.assertEqual(kept, sorted(texts[1:] + [svc.render_prompt(msgs, None, {})]))++ def lazy_service(self, args, **info):+ """A Service over the real StrataEngine class started lazily: no process yet, so no INFO line either."""+ engine = StrataEngine("strata", args, lazy=True)+ engine.info.update(info)+ return Service(engine, self.svc.tok, self.svc.template)++ def test_a_lazy_engine_keeps_the_prompts_its_arguments_ask_for(self):+ svc = self.lazy_service(["--conversation-cache-slots", "8"])+ for n in range(10):+ svc.encode_prompt(self.conversation(n), None, {})+ self.assertEqual(len(svc.prompts.entries), 8)++ def test_the_slot_argument_wins_over_the_info_line_and_a_bad_one_falls_back(self):+ self.assertEqual(self.lazy_service(["--conversation-cache-slots", "6"], conversation_cache_slots=3)+ .prompts.keep, 6)+ self.assertEqual(self.lazy_service(["--conversation-cache-slots", "x"], conversation_cache_slots=3)+ .prompts.keep, 3)+ self.assertEqual(self.lazy_service(["--conversation-cache-slots"]).prompts.keep, 4)+ self.assertEqual(self.lazy_service([]).prompts.keep, 4)++ def test_without_a_slot_setting_four_prompts_are_kept(self):+ svc = self.service()+ for n in range(6):+ svc.encode_prompt(self.conversation(n), None, {})+ self.assertEqual(len(svc.prompts.entries), 4)++ def test_counting_tokens_leaves_the_kept_prompts_alone(self):+ svc = self.service(conversation_cache_slots=2)+ httpd = serve(svc, port=0)+ self.addCleanup(httpd.server_close)+ self.addCleanup(httpd.shutdown)+ self.base = f"http://127.0.0.1:{httpd.server_address[1]}"+ main = self.conversation(0)+ status, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 8, "messages": main})+ self.assertEqual(status, 200, b)+ before = list(svc.prompts.entries)+ full = self.service()+ full.prompts = None+ for n in range(1, 6):+ other = self.conversation(n)+ status, b = self.post("/v1/messages/count_tokens", {"model": "m", "messages": other})+ self.assertEqual(status, 200, b)+ self.assertEqual(b["input_tokens"], len(full.encode_prompt(other, None, {})))+ self.assertTrue(svc.prompts.entries == before, "the count wrote into the kept prompts")+ main.append({"role": "assistant", "content": "ok"})+ main.append({"role": "user", "content": "and then?"})+ svc.encode_prompt(main, None, {})+ self.assertGreater(svc.prompts.last_reused, len(svc.render_prompt(main, None, {})) // 2)++ def test_same_ids_as_a_full_encode_on_varied_conversations(self):+ import random+ sys.path.insert(0, str(ROOT / "tools"))+ from test_strata_tokenizer import conversation_prompts, load_tokenizer+ toks = [("byte", ByteTokenizer())]+ qwen = load_tokenizer()+ if qwen is not None:+ toks.append(("qwen35", qwen))+ for name, tok in toks:+ svc = Service(self.engine, tok, self.svc.template)+ for seed in range(3):+ for what, prompt in conversation_prompts(self.svc.template, random.Random(seed)):+ with self.subTest(tokenizer=name, seed=seed, what=what):+ self.assertEqual(svc.prompts.encode(prompt), tok.encode(prompt, parse_special=True))++ def test_a_tokenizer_without_resume_points_encodes_in_full(self):+ class Plain:+ """ByteTokenizer without the resume points."""+ def __init__(self):+ self.base = ByteTokenizer()++ def __getattr__(self, name):+ if name in ("encode_marked", "max_special_len"):+ raise AttributeError(name)+ return getattr(self.base, name)+ svc = Service(self.engine, Plain(), self.svc.template)+ self.assertIsNone(svc.prompts)+ msgs = [{"role": "user", "content": "hi"}]+ self.assertEqual(svc.encode_prompt(msgs, None, {}),+ ByteTokenizer().encode(svc.render_prompt(msgs, None, {}), parse_special=True))++class DyingEngine(MockEngine):"""Issue #27: an engine that dies after a few tokens of its first answer, and comes back when restarted."""diff --git a/tools/strata_tokenizer.py b/tools/strata_tokenizer.pyindex c9e84ee71..42a27fed3 100644--- a/tools/strata_tokenizer.py+++ b/tools/strata_tokenizer.py@@ -15,9 +15,11 @@ emoji (4-byte), combining marks, whitespace runs, and C0 control bytes."""from __future__ import annotations+import bisectimport jsonimport pathlibimport sys+import threadingimport regex@@ -115,6 +117,8 @@ class Tokenizer:# through __dict__.setdefault on each encoded segment or decoded token.self._piece_ids: dict[str, list[int]] = {}self._bytes_cache: dict[int, bytes] = {}+ # How far a special-token match can look ahead of where it starts (PromptEncoder's margin).+ self.max_special_len = max((len(t) for t in self.special_tokens), default=1)@staticmethoddef _alt(literals: list[str]):@@ -234,13 +238,16 @@ class Tokenizer:out.extend(got)return out- def _encode_matching(self, text: str, pat, plain=()) -> list[int]:+ def _encode_matching(self, text: str, pat, plain=(), marks: list | None = None) -> list[int]:"""Encode `text`, emitting any literal `pat` matches as single tokens and BPE-ing the rest.The split happens on the RAW text, before the byte mapping, because a special token's string is aliteral to match rather than bytes to decompose. Everything between the matches is tokenizednormally - which is why a near-miss like `<|im_star` still costs ordinary tokens. A match that startsinside one of the `plain` (start, end) spans is left to the text around it (#537).++ `marks`, when given, receives (end of the match in `text`, ids so far) for every match: the points where+ the encoding of a longer text with the same beginning can resume (PromptEncoder)."""if pat is None:return self._encode_plain(text)@@ -269,6 +276,8 @@ class Tokenizer:out.extend(self._encode_plain(text[pos:start]))out.append(self.special_tokens[m.group(0)])pos = m.end()+ if marks is not None:+ marks.append((pos, len(out)))if pos < len(text):out.extend(self._encode_plain(text[pos:]))return out@@ -283,6 +292,11 @@ class Tokenizer:"""return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain)+ def encode_marked(self, text: str, parse_special: bool = False, plain=()) -> tuple[list[int], list[tuple[int, int]]]:+ """encode() and its resume points: (end offset in `text`, ids so far) after every special-token match."""+ marks: list[tuple[int, int]] = []+ return self._encode_matching(text, self._special_re if parse_special else self._always_re, plain, marks), marks+def token_bytes(self, i: int) -> bytes:"""The raw bytes of one token (a multi-byte character can be split across tokens)."""cache = self._bytes_cache@@ -303,6 +317,111 @@ class Tokenizer:return b"".join(self.token_bytes(i) for i in ids).decode("utf-8", errors=errors)+# ------------------------------------------------------------------ incremental prompts (#567)+def common_prefix_len(a: str, b: str) -> int:+ """Length of the longest common prefix, by slices (C speed) rather than a loop over characters."""+ n = min(len(a), len(b))+ lo, step = 0, 4096+ while lo < n: # whole chunks first, doubling+ hi = min(n, lo + step)+ if a[lo:hi] != b[lo:hi]:+ break+ lo, step = hi, min(step * 2, 1 << 20)+ else:+ return n+ while hi - lo > 1: # the first difference is in [lo, hi): bisect it+ mid = (lo + hi) // 2+ if a[lo:mid] == b[lo:mid]:+ lo = mid+ else:+ hi = mid+ return lo+++def plain_agree_until(a, b, limit: int) -> int:+ """The first position below `limit` where the `plain` spans (#537) of two texts differ - a position inside a+ span in one and not in the other - or `limit`. Spans are (start, end), sorted and disjoint."""+ def clip(spans):+ return [(x, min(y, limit)) for x, y in spans if x < limit and y > x]+ ca, cb = clip(a), clip(b)+ for (xa, ya), (xb, yb) in zip(ca, cb):+ if (xa, ya) != (xb, yb):+ return min(xa, xb) if xa != xb else min(ya, yb)+ if len(ca) != len(cb):+ return (ca if len(ca) > len(cb) else cb)[min(len(ca), len(cb))][0]+ return limit+++class PromptEncoder:+ """`tok.encode(text, parse_special=True, plain=...)` for chat prompts, reusing the ids of an earlier prompt.++ A chat client sends the whole conversation every turn, and the rendered prompt of turn n+1 starts with most of+ turn n's. Running BPE over all of it again costs hundreds of milliseconds at 100K tokens, even when the engine+ reuses the whole prefix. So the ids up to a SPECIAL-TOKEN BOUNDARY both prompts share are taken as they were,+ and only the rest is encoded.++ WHY THAT IS EXACT. Encoding splits the text at special-token matches and BPE-encodes each stretch between two+ matches on its own (`_encode_matching`): nothing crosses a match. Whether a match is taken at position q+ depends only on text[q : q + max_special_len] and on whether q lies inside a `plain` span (#537: a </think>+ quoted in a message is text). So if the two texts agree up to L and their plain spans agree below L, every+ decision the scan makes at a position before c = the end of some match, with c + max_special_len - 1 <= L, is+ the same for both - the same matches, the same stretches, the same ids up to c - and from c the scan starts+ afresh, exactly as it does on text[c:] with the spans shifted by c. Hence encode(new) == ids_old[:ids at c] ++ encode(new[c:]). The margin matters only for a vocabulary where a literal overlaps another's end; it costs+ re-encoding one short stretch.++ A few recent prompts are kept (one per conversation: a prompt replaces the one it continues, that is, one whose+ text it reuses for more than half; a prompt that shares only the template's head with every entry is a new+ entry), so a second client does not evict the first. `encode(..., store=False)` reads the kept prompts without+ writing one (a token count is not a conversation's turn). The tokenizer needs `encode_marked` and+ `max_special_len`.+ """++ def __init__(self, tok, keep: int = 4):+ self.tok, self.keep = tok, keep+ # (text, plain spans, ids, mark ends, mark counts)+ self.entries: list[tuple[str, tuple, list[int], list[int], list[int]]] = []+ self.lock = threading.Lock()+ self.last_reused = 0 # characters taken from an earlier prompt (for tests)++ def encode(self, text: str, plain=(), store: bool = True) -> list[int]:+ plain = tuple(sorted(plain))+ with self.lock:+ entries = self.entries # replaced, never changed in place+ margin = self.tok.max_special_len - 1+ src, cut_k = None, -1+ for e in entries:+ same = plain_agree_until(e[1], plain, common_prefix_len(e[0], text))+ k = bisect.bisect_right(e[3], same - margin) - 1 # the last boundary c with c <= same - margin+ if k >= 0 and (src is None or e[3][k] > src[3][cut_k]):+ src, cut_k = e, k+ if src is None:+ ids, marks = self.tok.encode_marked(text, parse_special=True, plain=plain)+ ends, counts = [m[0] for m in marks], [m[1] for m in marks]+ self.last_reused = 0+ else:+ c, n = src[3][cut_k], src[4][cut_k]+ rest = tuple((max(x - c, 0), y - c) for x, y in plain if y > c)+ tail, marks = self.tok.encode_marked(text[c:], parse_special=True, plain=rest)+ ids = src[2][:n] + tail+ ends = src[3][:cut_k + 1] + [c + m[0] for m in marks]+ counts = src[4][:cut_k + 1] + [n + m[1] for m in marks]+ self.last_reused = c+ if not store:+ return ids+ # every rendered prompt starts with the template's header, so sharing a special boundary does not make two+ # prompts one conversation: only the entry whose text is mostly reused is replaced+ old = src if src is not None and 2 * src[3][cut_k] > len(src[0]) else None+ with self.lock:+ self.entries = [(text, plain, ids, ends, counts)] + [e for e in self.entries if e is not old][:self.keep - 1]+ return list(ids)++ def forget(self, ids: list[int]) -> None:+ """The prompt with these ids was refused: it is not kept."""+ with self.lock:+ self.entries = [e for e in self.entries if e[2] != ids]++# ------------------------------------------------------------------ the pack's tokenizer/ directorydef extract(gguf_path, out_dir) -> dict:"""Write the tokenizer into `<out_dir>/tokenizer/` so the engine never opens the weight shards for it."""diff --git a/tools/test_strata_tokenizer.py b/tools/test_strata_tokenizer.pyindex 17c3f6986..e3cb498c2 100644--- a/tools/test_strata_tokenizer.py+++ b/tools/test_strata_tokenizer.py@@ -1,9 +1,18 @@-"""The tokenizer's piece cache (0.1.41): the ids are the ones the merge loop gives, cache cold, warm or switched off.+"""Tests for tools/strata_tokenizer.py: llama.cpp's reference vectors, the piece cache (0.1.41: the ids are the ones the+merge loop gives, cache cold, warm or switched off), and the incremental prompt encoder, which must give exactly the+ids of a plain encode.- python -m unittest tools.test_strata_tokenizer+ python -m unittest tools.test_strata_tokenizer -v++The real vocabulary comes from $STRATA_TOKENIZER (a pack's tokenizer/ directory) when set, else from llama.cpp's+`models/ggml-vocab-qwen35.gguf` next to the gguf-py the tools use ($STRATA_GGUF_PY, third_party/llama.cpp); the+tests that need it are skipped without one. The chat template's USER_DEFINED tokens (`<think>`, `<tool_call>`,+...) are added to the llama.cpp vocabulary, which does not have them, as the pack's has."""from __future__ import annotations+import json+import osimport randomimport sysimport unittest@@ -11,8 +20,295 @@ from pathlib import PathROOT = Path(__file__).resolve().parents[1]sys.path.insert(0, str(ROOT / "tools"))+sys.path.insert(0, str(ROOT))import strata_tokenizer as ST # noqa: E402+ADDED = ["<think>", "</think>", "<tool_call>", "</tool_call>", "<tool_response>", "</tool_response>",+ "<|vision_start|>", "<|image_pad|>", "<|vision_end|>"]+++def vocab_gguf() -> Path | None:+ cands = [os.environ.get("STRATA_GGUF_PY"), ROOT / "third_party" / "llama.cpp" / "gguf-py", "/opt/llama.cpp/gguf-py"]+ for c in cands:+ if c and (Path(c).parent / "models" / "ggml-vocab-qwen35.gguf").is_file():+ return Path(c).parent / "models" / "ggml-vocab-qwen35.gguf"+ return None+++def load_tokenizer():+ pack = os.environ.get("STRATA_TOKENIZER")+ if pack and (Path(pack) / "vocab.json").is_file():+ t = Path(pack)+ vocab = json.loads((t / "vocab.json").read_text(encoding="utf-8"))+ tokens = [None] * len(vocab)+ for s, i in vocab.items():+ tokens[i] = s+ return ST.Tokenizer(tokens, (t / "merges.txt").read_text(encoding="utf-8").split("\n"),+ json.loads((t / "token_type.json").read_text()))+ path = vocab_gguf()+ return None if path is None else gguf_tokenizer(path)+++def gguf_tokenizer(path):+ """llama.cpp's qwen35 vocabulary with the template's added tokens: the one its test vectors were made with."""+ from gguf_reader import GGUFFile+ md = GGUFFile(path).metadata+ tokens, types = list(md["tokenizer.ggml.tokens"]), list(md["tokenizer.ggml.token_type"])+ for s in ADDED:+ if s not in tokens:+ tokens.append(s)+ types.append(4)+ return ST.Tokenizer(tokens, list(md["tokenizer.ggml.merges"]), types)+++def byte_tokenizer(specials: list[str]) -> ST.Tokenizer:+ """A vocabulary of the 256 byte tokens and `specials` (CONTROL), no merges: small enough to build per test."""+ tokens = [ST.BYTE_TO_UNICODE[b] for b in range(256)] + specials+ return ST.Tokenizer(tokens, [], [1] * 256 + [3] * len(specials))+++WORDS = ["the", "tokenizer", " ", " ", "\n", "\n\n", "\t", "def", "f(x):", "return", "x", "==", "->", "café",+ "你好", "\U0001f600", "é", "1234", "don't", "I'm", "<|im_", "<think", "</", "tool", "_call>",+ " ", "\r\n", "Hello,", "world!", "<", ">", "|", " ", "x" * 70]+++def random_text(rnd: random.Random, n: int, specials=()) -> str:+ parts = []+ for _ in range(n):+ parts.append(rnd.choice(WORDS) if not specials or rnd.random() > 0.05 else rnd.choice(specials))+ if rnd.random() < 0.5:+ parts.append(" ")+ return "".join(parts)+++def conversation_prompts(template, rnd: random.Random) -> list[tuple[str, str]]:+ """Rendered prompts, in the order a server would see them, from clients that grow a conversation turn after turn,+ use tools, send images, change the start of the prompt, edit an earlier turn, send a shorter conversation, and+ interleave with each other: (what happens, prompt)."""+ out: list[tuple[str, str]] = []+ specials = ["<|im_start|>", "<|im_end|>", "<think>", "</think>", "<tool_call>", "</tool_response>"]+ weather = [{"type": "function", "function": {"name": "get_weather", "description": "Get the weather",+ "parameters": {"type": "object", "properties": {+ "city": {"type": "string"}}, "required": ["city"]}}}]++ def add(what, msgs, tools=None, **kw):+ out.append((what, template.render(msgs, tools=tools, **kw)))++ # several turns, with unicode, a literal special token inside the text, and reasoning kept or not+ msgs = [{"role": "system", "content": "Be brief. Réponds en français si on te parle en français."}]+ for turn in range(6):+ msgs.append({"role": "user", "content": random_text(rnd, 60, specials) + " é你\U0001f600 " * turn})+ add(f"turn {turn}", msgs)+ answer = {"role": "assistant", "content": random_text(rnd, 30)}+ if turn % 2:+ answer["reasoning_content"] = random_text(rnd, 30)+ msgs.append(answer)+ grown = list(msgs)++ # tools: definitions, a call, its response, then a following turn+ tmsgs = [{"role": "user", "content": "Weather in Oslo?"}]+ add("tools 1", tmsgs, weather)+ tmsgs += [{"role": "assistant", "content": "", "tool_calls": [{"type": "function", "function": {+ "name": "get_weather", "arguments": {"city": "Oslo"}}}]},+ {"role": "tool", "content": "{\"temp\": 3}", "name": "get_weather"}]+ add("tools 2", tmsgs, weather)+ tmsgs += [{"role": "assistant", "content": "3 degrees."}, {"role": "user", "content": "And in Bergen? " * 20}]+ add("tools 3", tmsgs, weather)++ # images: one per user turn, the placeholder tokens are specials+ imsgs = []+ for turn in range(3):+ imsgs.append({"role": "user", "content": [{"type": "image", "source": f"img{turn}"},+ {"type": "text", "text": f"What is on picture {turn}?"}]})+ add(f"images {turn}", imsgs)+ imsgs.append({"role": "assistant", "content": "A cat."})++ # the start of the prompt changes (a thinking level, a system message), then the old conversation grows again+ add("effort changed", grown, reasoning_effort="low")+ add("system changed", [dict(grown[0], content=grown[0]["content"] + " Be kind.")] + grown[1:])+ grown.append({"role": "user", "content": "one more question"})+ add("grown again", grown)++ # an earlier turn edited, then a conversation that got shorter, then the full one again+ edited = list(grown)+ edited[3] = dict(edited[3], content=edited[3]["content"] + " (edited)")+ add("edited", edited)+ add("shorter", grown[:5])+ add("empty user", [{"role": "user", "content": ""}])+ add("full again", grown)+ return out+++class Oracle(unittest.TestCase):+ """llama.cpp's own tokenizer test vectors for qwen35."""++ def test_llama_cpp_vectors(self):+ path = vocab_gguf()+ if path is None or not path.with_suffix(".gguf.inp").is_file():+ self.skipTest("llama.cpp's ggml-vocab-qwen35.gguf test vectors are not here")+ tk = gguf_tokenizer(path) # not $STRATA_TOKENIZER: the vectors belong to this vocabulary+ inp = path.with_suffix(".gguf.inp").read_text(encoding="utf-8").split("\n__ggml_vocab_test__\n")+ out = path.with_suffix(".gguf.out").read_text(encoding="utf-8").split("\n")+ n = 0+ for text, want in zip(inp, out):+ if text.endswith("\n__ggml_vocab_test__"):+ text = text[:-len("\n__ggml_vocab_test__")]+ self.assertEqual(tk.encode(text), [int(x) for x in want.split()], repr(text[:40]))+ n += 1+ self.assertGreater(n, 40)+++class Marks(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.tk = load_tokenizer()+ if cls.tk is None:+ raise unittest.SkipTest("no tokenizer (set STRATA_TOKENIZER or STRATA_GGUF_PY)")++ def test_marks(self):+ text = "a<|im_start|>user\nhi<|im_end|>\n<think>\n"+ ids, marks = self.tk.encode_marked(text, parse_special=True)+ self.assertEqual(ids, self.tk.encode(text, parse_special=True))+ self.assertEqual([m[0] for m in marks], [text.index("user"), text.index("<|im_end|>") + len("<|im_end|>"),+ len(text) - 1])+ for end, n in marks: # each mark: the ids of the text up to it+ self.assertEqual(ids[:n], self.tk.encode(text[:end], parse_special=True))+++class Prompts(unittest.TestCase):+ """PromptEncoder: the ids of a plain encode, whatever the earlier prompts were."""++ @classmethod+ def setUpClass(cls):+ cls.tk = load_tokenizer()+ if cls.tk is None:+ raise unittest.SkipTest("no tokenizer (set STRATA_TOKENIZER or STRATA_GGUF_PY)")+ from serve.frontend import ChatTemplate+ cls.template = ChatTemplate(ROOT / "serve" / "chat_template.jinja")++ def check(self, enc, text):+ self.assertEqual(enc.encode(text), self.tk.encode(text, parse_special=True))++ def test_chat_golden(self):+ cases = json.loads((ROOT / "serve" / "chat_golden.json").read_text(encoding="utf-8"))+ enc = ST.PromptEncoder(self.tk)+ for c in cases + cases: # the second round finds its own earlier prompts+ if c.get("rendered"):+ with self.subTest(case=c["name"]):+ self.check(enc, c["rendered"])++ def test_conversations(self):+ for seed in range(3):+ prompts = conversation_prompts(self.template, random.Random(seed))+ wants = [self.tk.encode(prompt, parse_special=True) for _, prompt in prompts]+ for keep in (1, 2, 4):+ enc = ST.PromptEncoder(self.tk, keep=keep)+ for (what, prompt), want in zip(prompts, wants):+ with self.subTest(seed=seed, keep=keep, what=what):+ self.assertEqual(enc.encode(prompt), want)++ def test_growing_turn_reuses_the_previous_prompt(self):+ enc = ST.PromptEncoder(self.tk)+ msgs = [{"role": "user", "content": "first question " * 50}]+ prev = ""+ for turn in range(4):+ prompt = self.template.render(msgs)+ self.check(enc, prompt)+ if turn:+ self.assertGreater(enc.last_reused, len(prev) - 100)+ prev = prompt+ msgs += [{"role": "assistant", "content": f"answer {turn}"}, {"role": "user", "content": f"question {turn}"}]++ def test_prefix_of_an_earlier_prompt_and_unrelated_prompts(self):+ enc = ST.PromptEncoder(self.tk, keep=2)+ a = self.template.render([{"role": "user", "content": "first question " * 50}])+ b = self.template.render([{"role": "user", "content": "another conversation"}])+ c = self.template.render([{"role": "user", "content": "a third one"}])+ for text in (a, a[:len(a) // 2], b, c, a, a + "tail", "", "<|im_end|>", "<|im_end|><|im_end|>x"):+ with self.subTest(text=text[:30]):+ self.check(enc, text)++ def test_a_read_only_encode_gives_the_ids_and_stores_nothing(self):+ enc = ST.PromptEncoder(self.tk)+ a = self.template.render([{"role": "user", "content": "first question " * 50}])+ enc.encode(a)+ kept = list(enc.entries)+ for text in (a + "<|im_start|>user\nand a follow-up<|im_end|>\n", a[:len(a) // 2], "<|im_end|>x",+ self.template.render([{"role": "user", "content": "another conversation"}])):+ with self.subTest(text=text[:30]):+ self.assertEqual(enc.encode(text, store=False), self.tk.encode(text, parse_special=True))+ self.assertTrue(enc.entries == kept, "a read-only encode wrote an entry")+ self.assertEqual(enc.encode(a + "tail", store=False), self.tk.encode(a + "tail", parse_special=True))+ self.assertGreater(enc.last_reused, len(a) // 2)++ def test_the_returned_ids_are_the_callers(self):+ enc = ST.PromptEncoder(self.tk)+ text = "<|im_start|>user\nhi<|im_end|>\n" + "and a tail longer than the look-ahead margin. " * 3+ want = self.tk.encode(text, parse_special=True)+ got = enc.encode(text)+ got[0] = -1 # inside the part the next call takes from this one+ got.append(-1)+ self.assertEqual(enc.encode(text), want)+ self.assertGreater(enc.last_reused, 0)+++class Margin(unittest.TestCase):+ """A special literal that is a prefix of a longer one: cutting at the shorter one's end without the look-ahead+ margin would give different ids."""++ def test_longer_literal_past_the_common_prefix(self):+ tk = byte_tokenizer(["<|a|>", "<|a|>zz"])+ enc = ST.PromptEncoder(tk)+ first = "x<|a|>y" + "<|a|>" * 3 + "q"+ self.assertEqual(enc.encode(first), tk.encode(first, parse_special=True))+ second = "x<|a|>y" + "<|a|>" * 3 + "zz" # shares everything up to the last <|a|>+ got = enc.encode(second)+ self.assertEqual(got, tk.encode(second, parse_special=True))+ self.assertEqual(got[-1], tk.special_tokens["<|a|>zz"])+ self.assertGreater(enc.last_reused, 0) # the earlier boundaries were still reused++ def test_literal_ending_inside_another(self):+ tk = byte_tokenizer(["<|a|>", "b<|a|>c"])+ enc = ST.PromptEncoder(tk)+ for text in ("zzb<|a|>d", "zzb<|a|>c", "zzb<|a|>cz<|a|>", "zzb<|a|>cz<|a|>b<|a|>c"):+ with self.subTest(text=text):+ self.assertEqual(enc.encode(text), tk.encode(text, parse_special=True))++ def test_random_specials(self):+ """Literals that extend or end inside one another, texts that change right after one of them."""+ rnd = random.Random(3)++ def word(lo, hi):+ return "".join(rnd.choice("<|ab>") for _ in range(rnd.randint(lo, hi)))+ for trial in range(60):+ a, b = word(2, 4), word(2, 4)+ lits = sorted({a, a + word(1, 3), b, word(1, 2) + b + word(0, 2)})+ tk = byte_tokenizer(lits)+ enc = ST.PromptEncoder(tk, keep=3)+ pieces = lits + [x[:rnd.randint(1, len(x))] for x in lits] + ["x", "y", "a", "|"]+ base = "".join(rnd.choice(pieces) for _ in range(60))+ for _ in range(30):+ cut = rnd.randint(0, len(base))+ text = base[:cut] + "".join(rnd.choice(pieces) for _ in range(rnd.randint(0, 6)))+ self.assertEqual(enc.encode(text), tk.encode(text, parse_special=True), (lits, text))+ if rnd.random() < 0.3:+ base = text + base[cut:]+++class CommonPrefix(unittest.TestCase):+ def test_against_a_loop(self):+ rnd = random.Random(5)+ for _ in range(500):+ a = "".join(rnd.choice("ab") for _ in range(rnd.randint(0, 9000)))+ k = rnd.randint(0, len(a))+ b = a[:k] + rnd.choice(["", "c", "cd"]) + a[k:k + rnd.randint(0, 50)]+ want = 0+ while want < min(len(a), len(b)) and a[want] == b[want]:+ want += 1+ self.assertEqual(ST.common_prefix_len(a, b), want)+ self.assertEqual(ST.common_prefix_len(b, a), want)++def toy() -> ST.Tokenizer:base = [ST.BYTE_TO_UNICODE[b] for b in range(256)]