From 9eceb375ab088cc2febf190eda9bcdd96a9a393e Mon Sep 17 00:00:00 2001 From: Niko1221 Date: Sat, 3 Oct 2026 18:26:01 +0200 Subject: [PATCH] serve + engine: opt-in "effort_position": "end" keeps the cached conversation when the effort changes (#458) The effort's instruction is the first thing the template renders, so a request that only changes reasoning_effort (or turns thinking off) read the whole prompt again. With "effort_position": "end" in the run config the server renders every prompt's start as the default effort's and puts a low/medium effort in a short system turn right before the answer (thinking off: just the template's empty thinking block); the rendering is template-agnostic (history + turn + the generation prompt). Engine: --tail-role-token ID (default -1, off) moves the turn checkpoint in front of such a trailing turn, so it holds the conversation and not the effort text; INFO reports tail_role_token. The server passes the id of "system" only when the engine binary knows the flag, and says so when it does not. Without the key nothing changes: the same prompt ids, no flag. --- docs/DETAILS.md | 8 +++ serve/server.py | 64 ++++++++++++++++++++++- serve/test_server.py | 106 +++++++++++++++++++++++++++++++++++++++ src/program/generate.cpp | 21 +++++++- 4 files changed, 195 insertions(+), 4 deletions(-) diff --git a/docs/DETAILS.md b/docs/DETAILS.md index aeef21da..2ea4641b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -473,6 +473,14 @@ print(r.choices[0].message.content) part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in `strata-.json` sets it for every request; a request's own value wins, and `0` means no budget. Off by default; Anthropic's `"thinking": {"budget_tokens": N}` still only chooses the level, as above. +- **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is the + first thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` for + a quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-.json` renders + every request's prompt start as the default effort's and puts a `low` / `medium` effort in a short system turn + right before the answer (no thinking: the empty thinking block, as always); the engine (0.1.39+, which the server + checks) keeps its checkpoint in front of that turn, so the next request reuses the conversation whatever its + effort. The default (`"start"`) prompt is unchanged. The model sees a level that is not the default in another + place than it was trained with; how well it follows it there is not measured yet. - **Anthropic requests that don't ask for thinking (opt-in, 0.1.32, #278).** By default a `/v1/messages` request with no `"thinking"`, effort or budget thinks as the model's template does. `"anthropic_thinking": "on_request"` in `strata-.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short diff --git a/serve/server.py b/serve/server.py index 9ed8d7be..0c2c65b2 100644 --- a/serve/server.py +++ b/serve/server.py @@ -58,6 +58,13 @@ from serve.structured import StructuredOutputError, prepare_format, validated_js IM_END = "<|im_end|>" IMAGE_PAD = "<|image_pad|>" +# #458: the trailing effort turn ("effort_position": "end"); low is the template's own sentence, medium (which the +# template says nothing for: no xhigh sentence is medium there) says it, since the xhigh one stays at the top +EFFORT_TURN = "<|im_start|>system\n{}<|im_end|>\n" +EFFORT_TEXT = {"low": "Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the " + "conclusion without unnecessary elaboration.", + "medium": "Reasoning effort is set to medium. Think as much as the task needs, without unnecessary " + "elaboration."} VISION_START = "<|vision_start|>" # #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it) REASONING_WRAP_UP = "\n\nI have thought about this long enough; time to give my answer.\n\n\n" @@ -778,6 +785,31 @@ def gpu_list(cfg: dict) -> list[int]: return [int(str(x).strip()) for x in items if str(x).strip() != ""] +def effort_end_args(cfg: dict, exe: str, tok) -> list[str] | None: + """#458 (opt-in): the engine arguments for "effort_position": "end" - the id of "system" as --tail-role-token, so + the engine checkpoints in front of the trailing effort turn - or None when the config leaves it at the top (the + default) or the engine is too old for it (said once; the prompt stays the default one). ValueError for a value + other than "start" / "end".""" + pos = cfg.get("effort_position", "start") + if pos not in ("start", "end"): + raise ValueError(f'"effort_position" must be "start" (the default) or "end", not {pos!r}') + if pos == "start": + return None + try: + with open(exe, "rb") as f: + known = b"--tail-role-token" in f.read() + except OSError: + known = False + role = tok.encode("system", parse_special=True) + if not known or len(role) != 1: + print("[strata] effort_position \"end\" needs engine 0.1.39 or newer (--tail-role-token): the reasoning " + "effort stays at the top of the prompt", flush=True) + return None + print("[strata] effort_position end: a request's non-default reasoning effort goes right before the answer, so " + "changing it keeps the cached conversation", flush=True) + return ["--tail-role-token", str(role[0])] + + def engine_silence_s(cfg: dict) -> float: """#481: the config's "engine_silence_s" - seconds an engine may print nothing during a request before the server ends it (default ENGINE_SILENCE_S; 0 = wait forever). ValueError for anything but a number >= 0.""" @@ -958,6 +990,9 @@ class Service: self.fifo = threading.Lock() self.embeddings = threading.local() # the current request's image embeddings file (GENI) self.api_key = "" # when set, /v1/* needs it (Bearer or x-api-key) + # #458 (opt-in, the config's "effort_position": "end"): a non-default reasoning effort goes in a short system + # turn before the answer instead of the top of the prompt, so switching it keeps the cached conversation + self.effort_end = False # #321: browser pages of these origins may call /v1/* (CORS; "*" = any page - only with an api_key that # matters); empty = no CORS headers at all, as before self.cors_origins: list[str] = [] @@ -1337,11 +1372,29 @@ class Service: "ram": {"used_gib": scaled(hw.get("ram_used"), 2 ** 30, 1), "total_gib": scaled(hw.get("ram_total"), 2 ** 30, 1)} if hw.get("ram_total") else None}} + def render_prompt(self, messages, tools, kwargs) -> str: + """The template rendered. #458: with `effort_end`, a request with a non-default effort (low, medium or no + thinking) is rendered as a default one up to the answer - the same prompt start, so the conversation cache + keeps it - and its effort follows in a short system turn right before the answer (thinking off: the template's + empty thinking block). The engine (--tail-role-token) checkpoints in front of that turn.""" + effort = kwargs.get("reasoning_effort") + off = kwargs.get("enable_thinking") is False + if not self.effort_end or (not off and effort in (None, "", "xhigh", "high")): + return self.template.render(messages, tools=tools, **kwargs) + base = {k: v for k, v in kwargs.items() if k not in ("reasoning_effort", "enable_thinking")} + history = self.template.render(messages, tools=tools, add_generation_prompt=False, **base) + full = self.template.render(messages, tools=tools, add_generation_prompt=True, **kwargs) + mine = self.template.render(messages, tools=tools, add_generation_prompt=False, **kwargs) + if not full.startswith(mine): # a template this cannot take apart: rendered as asked + return full + 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]: """The request's prompt: the template rendered and tokenized. #537: a / written inside a message's text is encoded as the text it is, not as the model's reasoning markers (the template's own are).""" marked, marked_tools, changed = mark_think_literals(messages, tools) - prompt = self.template.render(marked, tools=marked_tools, **kwargs) + 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) @@ -2933,7 +2986,12 @@ def main() -> int: silence = engine_silence_s(cfg) # #481: checked before the (minutes-long) start except ValueError as e: raise SystemExit(f"[strata] config {e}") - engine = StrataEngine(exe, engine_args(cfg), cwd=cfg.get("cwd"), log=cfg.get("log"), env=env, lazy=lazy) + try: + effort_end = effort_end_args(cfg, exe, tok) # #458 + except ValueError as e: + raise SystemExit(f"[strata] config {e}") + engine = StrataEngine(exe, engine_args(cfg) + (effort_end or []), cwd=cfg.get("cwd"), log=cfg.get("log"), + env=env, lazy=lazy) engine.silence_s = silence # an attribute of its own: restart() keeps it warn_tight_ram(engine.info.get("arena_mib")) note = desktop_vram_note(cfg.get("backend"), engine.info.get("vram_free_mib"), engine.spawn[1], @@ -2941,6 +2999,7 @@ def main() -> int: if note: # #560 #516: before --open starts a browser on that card print(note, flush=True) else: + effort_end = None engine, vision, sampling_defaults = MockEngine(tok, a.script or [ "Thinking about it.\n\nHello from the mock engine."]), None, {} # the model's own chat template (exported with its tokenizer), else the original model's @@ -2988,6 +3047,7 @@ def main() -> int: if mode not in ("model", "on_request"): raise SystemExit(f"[strata] config anthropic_thinking must be \"model\" or \"on_request\", not {mode!r}") svc.anthropic_think_unasked = mode == "model" + svc.effort_end = bool(effort_end) # #458: "effort_position": "end" with an engine that has it if cfg.get("reasoning_budget_tokens") is not None: # #123: a default thinking budget for every request try: svc.reasoning_budget_tokens = cfg["reasoning_budget_tokens"] diff --git a/serve/test_server.py b/serve/test_server.py index cb96d1f9..bf8a74a3 100644 --- a/serve/test_server.py +++ b/serve/test_server.py @@ -319,6 +319,112 @@ class LiteralThinkTags(unittest.TestCase): self.assertEqual(plain, [*b"say now", 258]) # the tag as text, im_end still special +class EffortAtTheEnd(unittest.TestCase): + """#458 (opt-in "effort_position": "end"): a non-default effort goes in a system turn right before the answer, so + a request that changes only the effort keeps the cached conversation. The engine's checkpoint rule is simulated + on the token ids (src/program/generate.cpp: the last <|im_start|>, and with --tail-role-token the one in front + of a trailing system turn); the default prompt does not change.""" + + TURN = 256 # the byte tokenizer's <|im_start|> + ROLE = ord("s") # "system"'s first byte stands for its token + + def setUp(self): + self.tok = ByteTokenizer() + self.svc = Service(MockEngine(self.tok, "ok", max_context=1 << 20), self.tok, + ChatTemplate(ROOT / "serve/chat_template.jinja")) + + def ids(self, messages, end, **kw): + self.svc.effort_end = end + return self.svc.encode_prompt(messages, None, kw) + + def checkpoint(self, ids, tail, resume=0): + """Where the engine checkpoints a prompt (the tokens before it), as generate.cpp's serve loop does.""" + turn_at = next((i for i in range(len(ids) - 1, resume, -1) if ids[i] == self.TURN), -1) + if turn_at > 0 and tail: + i = next((i for i in range(turn_at - 1, resume, -1) if ids[i] == self.TURN), None) + if i is not None and ids[i + 1] == self.ROLE: + turn_at = i + return ids[:turn_at] + + def session(self, requests, end, tail): + """The reused tokens of each request after the first: the longest earlier checkpoint it starts with.""" + checks, reused = [], [] + for messages, kw in requests: + ids = self.ids(messages, end, **kw) + reused.append(max([len(c) for c in checks if ids[:len(c)] == c], default=0)) + checks.append(self.checkpoint(ids, tail)) + return reused[1:] + + CHAT = [{"role": "system", "content": "You are a careful assistant. " * 40}, + {"role": "user", "content": "Explain the conversation cache. " * 20}] + REPLY = {"role": "assistant", "content": "It keeps the prompt's state. " * 20, "reasoning_content": "ok"} + NEXT = {"role": "user", "content": "And the checkpoints?"} + + def test_the_default_prompt_is_unchanged(self): + for kw in ({}, {"reasoning_effort": "xhigh"}): + self.assertEqual(self.ids(self.CHAT, True, **kw), self.ids(self.CHAT, False, **kw)) + self.assertEqual(self.ids(self.CHAT, True, **kw), + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + self.assertEqual(self.ids(self.CHAT, False, **kw), # off: every effort renders as before + self.tok.encode(self.svc.template.render(self.CHAT, **kw), parse_special=True)) + + def test_the_trailing_turn(self): + text = self.tok.decode(self.ids(self.CHAT, True, reasoning_effort="low")) + self.assertTrue(text.endswith("<|im_end|>\n<|im_start|>system\nReasoning effort is set to low. Keep your " + "thinking brief and focused, moving directly to the conclusion without " + "unnecessary elaboration.<|im_end|>\n<|im_start|>assistant\n\n"), text[-300:]) + self.assertIn("Reasoning effort is set to xhigh", text) # the top stays the default's + text = self.tok.decode(self.ids(self.CHAT, True, enable_thinking=False)) + self.assertTrue(text.endswith("<|im_start|>assistant\n\n\n\n\n")) + self.assertNotIn("<|im_start|>system\nReasoning effort", text[-200:]) + default = self.ids(self.CHAT, True) + for kw in ({"reasoning_effort": "low"}, {"reasoning_effort": "medium"}, {"enable_thinking": False}): + ids = self.ids(self.CHAT, True, **kw) + head = len(self.checkpoint(default, False)) # all before the answer's turn + self.assertEqual(ids[:head], default[:head], kw) # the same prompt up to the answer + + def test_changing_the_effort_keeps_the_conversation(self): + efforts = [{}, {"reasoning_effort": "low"}, {"enable_thinking": False}, {"reasoning_effort": "medium"}, {}] + history = len(self.checkpoint(self.ids(self.CHAT, False), False)) + # at the top (the default): another effort differs a few tokens in, and the whole prompt is read again + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], False, False)[:2], [0, 0]) + # at the end, with the engine's rule: every request reuses the whole conversation + self.assertEqual(self.session([(self.CHAT, kw) for kw in efforts], True, True), [history] * 4) + + def test_the_next_turn_reuses_the_checkpoint(self): + turn1, turn2 = self.CHAT, self.CHAT + [self.REPLY, self.NEXT] + low = {"reasoning_effort": "low"} + first = len(self.checkpoint(self.ids(turn1, True, **low), True)) + # the engine's rule: the next turn (the same effort) reuses the first turn's whole conversation + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, True), [first]) + # without it the checkpoint held the effort turn and the next turn reused nothing (what #458 measured) + self.assertEqual(self.session([(turn1, low), (turn2, low)], True, False), [0]) + + def test_the_config(self): + from serve.server import effort_end_args + + class Tok: + def encode(self, text, parse_special=False): + return [8678] if text == "system" else [1, 2] + + with tempfile.TemporaryDirectory() as d: + new, old = Path(d) / "new.exe", Path(d) / "old.exe" + new.write_bytes(b"... --tail-role-token ID --serve: ...") + old.write_bytes(b"... --turn-token ID ...") + out = io.StringIO() + with contextlib.redirect_stdout(out): + self.assertIsNone(effort_end_args({}, str(new), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "start"}, str(new), Tok())) + self.assertEqual(effort_end_args({"effort_position": "end"}, str(new), Tok()), + ["--tail-role-token", "8678"]) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(old), Tok())) + self.assertIsNone(effort_end_args({"effort_position": "end"}, str(new), ByteTokenizer())) + self.assertIn("needs engine 0.1.39 or newer", out.getvalue()) + with self.assertRaises(ValueError): + effort_end_args({"effort_position": "middle"}, str(new), Tok()) + + class StatusNeedsTheKey(unittest.TestCase): """#212: /status shows the end of the answer being written, so it needs the key like /v1/*.""" diff --git a/src/program/generate.cpp b/src/program/generate.cpp index a7c77d0e..4558100b 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -413,6 +413,11 @@ struct Options { /// --serve: the token that opens a chat turn (<|im_start|>). The last one in a prompt is where the chat's /// history ends and the new assistant turn begins, which is the checkpoint the next request can reuse. int64_t turn_token = 248045; + /// --serve (#458, opt-in): the role token of a short turn the server puts right before the new assistant turn + /// (the "system" of a trailing reasoning-effort turn). When the turn before the last <|im_start|> opens with it, + /// the checkpoint goes in front of that turn instead, so it holds the conversation and not the effort text. + /// -1 = off (the checkpoint at the last <|im_start|>, as before). + int64_t tail_role_token = -1; /// --serve: a text part of the prompt of at most N tokens (a chat message, the assistant header, a short tool /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) @@ -517,6 +522,8 @@ void usage() { " --conversation-cache-min-free-mib N --serve: physical RAM floor when parking (default 2560)\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" + " --tail-role-token ID --serve: a turn of this role right before the last turn is left out of\n" + " the conversation checkpoint (a trailing effort turn; default -1 = off)\n" " --short-read N --serve: read at most N fresh text tokens through the decode windows instead\n" " of the batched prompt path (default 64, 0 = off)\n" " --suffix-draft N prompt lookup: draft from an earlier repeat of the last N+ tokens of context\n" @@ -1248,6 +1255,7 @@ int main(int argc, char** argv) { else if (a == "--prompt-cache-every") o.prompt_cache_every = std::max(0LL, std::atoll(next("--prompt-cache-every"))); else if (a == "--prompt-cache-root") o.prompt_cache_root = std::max(0LL, std::atoll(next("--prompt-cache-root"))); else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); + else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); @@ -4986,7 +4994,7 @@ int main(int argc, char** argv) { "expert_slots_primary=%lld expert_cache_primary_mib=%lld spec=%d " "mtp_max=%d lookup=%d vram_free_mib=%lld cvec=%s arena_mib=%lld pool_workers=%d pcie_frac=%.2f " "spec_min_p=%.2f conversation_cache_mib=%lld conversation_cache_slots=%d " - "conversation_cache_min_free_mib=%lld engine=" STRATA_VERSION "\n", + "conversation_cache_min_free_mib=%lld tail_role_token=%lld engine=" STRATA_VERSION "\n", (long long) o.max_context, o.kv.c_str(), (long long) (g.n_qsa_layers() > 0 && ss.qsa_states[ss.qsa_primary()].kv_mode == 1 ? ss.qsa_states[ss.qsa_primary()].n_slots * 4 : 0), @@ -4997,7 +5005,7 @@ int main(int argc, char** argv) { (long long) ((o.mmap_experts ? src.resident_bytes() : strata::kernels::cpu::expert_layout().total) >> 20), pool.workers(), o.pcie_frac, o.spec_min_p, (long long) o.conversation_cache_mib, o.conversation_cache_slots, - (long long) o.conversation_cache_min_free_mib); + (long long) o.conversation_cache_min_free_mib, (long long) o.tail_role_token); } // issue #29: a request whose heartbeat (tokens, prompt chunks, verify windows) stops for this long is stuck on // a flag nobody will raise - end the engine with where it was, so the server starts it again instead of the @@ -5597,6 +5605,15 @@ int main(int argc, char** argv) { if (o.prompt_cache > 0 && o.turn_token >= 0) for (int64_t i = n - 1; i > resume; --i) if (ids[(size_t) i] == o.turn_token) { turn_at = i; break; } + // #458 (opt-in): a short turn of --tail-role-token's role right before the new assistant turn (the + // server's trailing reasoning-effort turn) stays out of the checkpoint, so the next request - another + // effort, or the next turn of the chat - finds the conversation without it + if (turn_at > 0 && o.tail_role_token >= 0) + for (int64_t i = turn_at - 1; i > resume; --i) + if (ids[(size_t) i] == o.turn_token) { + if (ids[(size_t) i + 1] == o.tail_role_token) turn_at = i; + break; + } // A prompt read from token 0 also stops at its FIRST turn boundary: the end of the system prompt (with // the tools), which every new chat of the same client shares. That checkpoint becomes the chain's root, // which the retention policy pins (conv_cache.hpp), so the next new chat reads only what comes after it.