serve: an opt-in hard thinking budget, reasoning_budget_tokens (#123)

A request (OpenAI or Anthropic) may set "reasoning_budget_tokens": N, and "reasoning_budget_tokens" in
strata-<model>.json sets a default (a request's own value wins; 0 means no budget).  When the thinking reaches N
tokens - at a clean point, no tag held back and no character split across tokens - Service.run stops the engine,
feeds a short wrap-up line and </think> through the detokenizer and parser (the client sees it as the end of the
thinking; it counts as output), and generates again from prompt + what was generated + the wrap-up: a prefix of
what the engine's session already holds, so it continues from it.  With no room left to answer it ends with
"length" as before.  A bad value is a 400 before anything is sent (a bad config value refuses to start).  Off
by default: without the field and the key every request runs exactly as before (one engine pass).  Anthropic's
thinking.budget_tokens still only picks the level.  Documented in docs/DETAILS.md.

Tests (serve/test_server.py ThinkingBudget, a fake engine that continues after </think>): off by default, the
wrap-up and the continued prompt (the first prompt + the kept thinking + the wrap-up), the Anthropic stream, a
budget the thinking stays under, the config default and a request turning it off, thinking off, no room left,
bad values.
This commit is contained in:
Niko1221 committed 2026-09-30 20:58:59 +02:00
1 parent afc33c260e
commit 8eff54c845
3 files changed
+219 -30

No files matched your search

+6
View File
@@ -383,6 +383,12 @@ print(r.choices[0].message.content)
Without a setting the model uses its own default, **high**. `none` answers at once (fastest); `low` keeps the thinking
short. The levels are instructions the model was trained with, not a hard token limit: on easy questions all three
think briefly, on hard ones `high` thinks longest and is most accurate.
- **A hard thinking budget (opt-in).** `"reasoning_budget_tokens": N` in a request (OpenAI or Anthropic) caps the
thinking at N tokens: when it gets there the server ends it with a short wrap-up line and `</think>`, and the model
answers from there (the engine continues from what it already holds, so nothing is read again). The wrap-up is
part of the thinking the client sees and counts as output tokens. `"reasoning_budget_tokens": N` in
`strata-<model>.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.
- **Streaming.** With `"stream": true` everything arrives as it is made: the thinking, the answer, and tool calls
(the tool's name first, then its arguments piece by piece, like OpenAI and Anthropic do). While the model reads a
long prompt the stream sends keep-alives, so agents do not time out; the server window prints progress every
+93 -30
View File
@@ -54,6 +54,8 @@ from serve.winjob import contain # noqa: E402
IM_END = "<|im_end|>"
IMAGE_PAD = "<|image_pad|>"
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</think>\n\n"
CTX_SLACK = 8 # `strata --serve` rejects prompt + max_new + 8 > context: keep the same margin here
# The live tok/s is a rate over a window, not a mean since the first token: a mean reads ~1/elapsed at the first
# token (the Monitor showed five-digit numbers) and then undershoots for the first second of every answer.
@@ -601,6 +603,12 @@ class Detokenizer:
self.tok, self.ids, self.sent = tok, [], 0
self.inc = codecs.getincrementaldecoder("utf-8")(errors="replace") if hasattr(tok, "token_bytes") else None
def pending(self) -> bool:
"""A character is split across the tokens so far: its first bytes are held."""
if self.inc is not None:
return bool(self.inc.getstate()[0])
return self.tok.decode(self.ids).endswith("\ufffd")
def push(self, t: int) -> str:
if self.inc is not None:
return self.inc.decode(self.tok.token_bytes(t))
@@ -641,12 +649,26 @@ class Service:
self.idle_unload_s = 0
self.min_free_vram_mib = 0
self.before_load = None
self.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none)
self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +
tokenizer.encode("<|endoftext|>", parse_special=True))
def loaded(self) -> bool:
return not hasattr(self.engine, "alive") or self.engine.alive()
def reasoning_budget(self, req) -> int | None:
"""#123: the most tokens this request may think, or None: the request's `reasoning_budget_tokens`, else the
config's. 0 (or less) means no budget, so a request can turn a configured one off. ValueError (a 400) for
anything that is not a whole number."""
value = (req or {}).get("reasoning_budget_tokens") if isinstance(req, dict) else None
if value is None:
value = self.reasoning_budget_tokens
if isinstance(value, float) and value.is_integer():
value = int(value)
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"reasoning_budget_tokens={value!r}: expected a whole number of tokens (0: no budget)")
return value if value > 0 else None
def _vision_down(self) -> bool:
return self.vision is not None and hasattr(self.vision, "alive") and not self.vision.alive()
@@ -977,6 +999,7 @@ class Service:
def run(self, ids, thinking, tools, max_new, sampling, cancel) -> Iterator[tuple[str, object]]:
"""Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..})."""
budget = self.reasoning_budget(sampling) if thinking else None # #123: opt-in, off by default
defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps
if defaults: # the request's own fields win (explicit 0 stays greedy)
req_values = {k: v for k, v in (sampling or {}).items() if v is not None}
@@ -1006,42 +1029,71 @@ class Service:
self.rate.clear() # the previous request's samples must not leak into this one
before = getattr(self.engine, "last", None)
last_print = time.time()
gen = self.engine.generate(ids, max_new, sampling, cancel, embeddings=emb) if emb else \
self.engine.generate(ids, max_new, sampling, cancel)
try:
for t in gen:
if t is None: # heartbeat while the engine is quiet
last_print = self._progress(last_print)
yield "ping", None
continue
n += 1
if t in self.stop_ids:
finish = "stop"
prompt, thought = ids, 0 # thought: the reasoning tokens so far (the budget's count)
while True:
gen = self.engine.generate(prompt, max_new - n, sampling, cancel, embeddings=emb) if emb \
else self.engine.generate(prompt, max_new - n, sampling, cancel)
seg, wrap = [], False # this pass's tokens; the budget is reached
try:
for t in gen:
if t is None: # heartbeat while the engine is quiet
last_print = self._progress(last_print)
yield "ping", None
continue
n += 1
if t in self.stop_ids:
finish = "stop"
raw_ids.append(t)
break
raw_ids.append(t)
break
seg.append(t)
evs = parser.feed(detok.push(t))
self._note(n, evs)
last_print = self._progress(last_print)
for ev in evs:
yield "event", ev
if budget and parser.state == "reasoning":
thought += 1
# at a clean point: no tag held back, no character split across tokens
if thought >= budget and not parser.buf and not detok.pending():
wrap = True
break
except EngineDied as e:
finish = "error"
note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""
log = getattr(self.engine, "log_path", None)
print(f"[strata] {e}. {note} The next request starts the engine again."
f"{' Its log: ' + log if log else ''}", flush=True)
raise
except ValueError as e: # the engine's ERR line (it may have ended after it)
finish = "error"
print(f"[strata] the engine reported an error: {e}", flush=True)
raise
finally:
gen.close() # STOP+drain to THIS request's DONE while still holding the
# fifo, so a stop-token break can't leave the shared engine
# queue mid-drain for the next request to read as its own DONE
if not wrap or cancel.is_set():
break
# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a
# short wrap-up and </think>) and let it answer: the next pass's prompt is this one plus what
# was generated plus the wrap-up, so the engine continues from the prefix it already holds.
budget = None
extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True)
if max_new - n - len(extra) < 1:
break # no room left to answer: "length", as without a budget
print(f"[strata] thinking budget reached ({thought} tokens): wrapping up the thinking",
flush=True)
for t in extra:
n += 1
raw_ids.append(t)
evs = parser.feed(detok.push(t))
self._note(n, evs)
last_print = self._progress(last_print)
for ev in evs:
yield "event", ev
if cancel.is_set():
finish = "cancel"
except EngineDied as e:
finish = "error"
note = self.engine.death_note() if hasattr(self.engine, "death_note") else ""
log = getattr(self.engine, "log_path", None)
print(f"[strata] {e}. {note} The next request starts the engine again."
f"{' Its log: ' + log if log else ''}", flush=True)
raise
except ValueError as e: # the engine's ERR line (it may have ended after it)
finish = "error"
print(f"[strata] the engine reported an error: {e}", flush=True)
raise
finally:
gen.close() # STOP+drain to THIS request's DONE while still holding the
# fifo, so a stop-token break can't leave the shared engine
# queue mid-drain for the next request to read as its own DONE
prompt = prompt + seg + extra
if cancel.is_set():
finish = "cancel"
except GeneratorExit: # the client disconnected mid-stream
finish = "disconnect"
raise
@@ -1655,6 +1707,7 @@ def make_handler(svc: Service):
extra = svc.mcp.template_tools(exclude=own) # the request's own tools win a name clash
use_mcp = bool(extra)
tools = (tools or []) + extra or None
svc.reasoning_budget(req) # a bad value is a 400 before anything is sent
ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)
_debug_req("openai", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
@@ -1686,6 +1739,7 @@ def make_handler(svc: Service):
req = svc.with_shared(req, "anthropic")
messages, tools, kw = anthropic_to_messages(req)
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
ids, thinking, max_new = svc.prepare(messages, tools, kw, max_new)
_debug_req("anthropic", req, messages, tools, max_new, thinking, len(ids))
cancel = threading.Event()
@@ -1967,6 +2021,15 @@ def main() -> int:
svc.min_free_vram_mib = a.min_free_vram_mib if a.min_free_vram_mib is not None else \
int(cfg.get("min_free_vram_mib") or 0)
svc.before_load = a.before_load or cfg.get("before_load") or None
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"]
budget = svc.reasoning_budget({})
except ValueError as e:
raise SystemExit(f"[strata] config {e}")
if budget:
print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)",
flush=True)
svc.gpu_index = (gpu_list(cfg) or [0])[0] # the Monitor reads the card the engine runs on (issue #51)
svc.gpu_indices = gpu_list(cfg) # ... or every card of a layer split (issue #112)
if a.config: # the Chat settings shared with other apps, from last time
+120
View File
@@ -1180,6 +1180,126 @@ class SharingTheGpu(unittest.TestCase):
self.assertEqual(self.req("/health")[1]["loaded"], True)
class ThinkingEngine(MockEngine):
"""Thinks THOUGHT, then answers; a prompt that already ends its thinking (the budget's wrap-up) gets the answer
at once, the way the model continues after </think>. Records every prompt it is given."""
THOUGHT = "Let me think step by step about two plus two. " * 4 # 184 reasoning tokens (one per byte)
ANSWER = "The answer is 4."
def __init__(self, tok):
super().__init__(tok, "x", max_context=CTX)
self.prompts = []
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
self.prompts.append(list(ids))
done = self.tok.decode(ids).endswith("</think>\n\n")
text = self.ANSWER if done else self.THOUGHT + "</think>\n\n" + self.ANSWER
for t in (self.tok.encode(text) + self.tok.encode("<|im_end|>", parse_special=True))[:max_new]:
if cancel.is_set():
return
yield t
class ThinkingBudget(unittest.TestCase):
"""#123: reasoning_budget_tokens (opt-in): at the budget the thinking is wrapped up and the model answers,
continuing from the prompt plus what it generated plus the wrap-up (a prefix the engine already holds)."""
def setUp(self):
self.tok = ByteTokenizer()
self.engine = ThinkingEngine(self.tok)
self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
self.httpd = serve(self.svc, port=0)
self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
def tearDown(self):
self.httpd.shutdown()
self.httpd.server_close()
def post(self, path, body):
req = urllib.request.Request(self.base + path, data=json.dumps(body).encode(), headers={
"Content-Type": "application/json", "anthropic-version": "2023-06-01"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
raw = r.read().decode()
return r.status, (json.loads(raw) if not body.get("stream") else raw)
except urllib.error.HTTPError as e:
with e:
return e.code, json.loads(e.read())
def openai(self, **extra):
return self.post("/v1/chat/completions", {"model": "m", "messages": [{"role": "user", "content": "2+2?"}],
"max_tokens": 400, **extra})
def test_off_by_default(self):
code, b = self.openai()
self.assertEqual(code, 200, b)
msg = b["choices"][0]["message"]
self.assertEqual((msg["reasoning_content"], msg["content"]), (ThinkingEngine.THOUGHT, ThinkingEngine.ANSWER))
self.assertEqual(len(self.engine.prompts), 1)
def test_the_budget_wraps_up_the_thinking(self):
from serve.server import REASONING_WRAP_UP
code, b = self.openai(reasoning_budget_tokens=20)
self.assertEqual(code, 200, b)
msg = b["choices"][0]["message"]
wrap = REASONING_WRAP_UP.split("</think>")[0]
self.assertEqual(msg["reasoning_content"], ThinkingEngine.THOUGHT[:20] + wrap)
self.assertEqual(msg["content"], ThinkingEngine.ANSWER)
self.assertEqual(b["choices"][0]["finish_reason"], "stop")
first, second = self.engine.prompts
extra = self.tok.encode(REASONING_WRAP_UP, parse_special=True)
self.assertEqual(second, first + self.tok.encode(ThinkingEngine.THOUGHT[:20]) + extra) # a prefix + more
self.assertEqual(b["usage"]["completion_tokens"], 20 + len(extra) + len(ThinkingEngine.ANSWER) + 1)
self.assertEqual(b["usage"]["prompt_tokens"], len(first))
def test_anthropic_stream(self):
from serve.server import REASONING_WRAP_UP
code, raw = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "stream": True,
"reasoning_budget_tokens": 30,
"messages": [{"role": "user", "content": "2+2?"}]})
self.assertEqual(code, 200)
evs = [json.loads(line[6:]) for line in raw.splitlines() if line.startswith("data: {")]
thinking = "".join(e["delta"].get("thinking", "") for e in evs if e["type"] == "content_block_delta")
text = "".join(e["delta"].get("text", "") for e in evs if e["type"] == "content_block_delta")
self.assertEqual(thinking, ThinkingEngine.THOUGHT[:30] + REASONING_WRAP_UP.split("</think>")[0])
self.assertEqual(text, ThinkingEngine.ANSWER)
self.assertEqual(evs[-2]["delta"]["stop_reason"], "end_turn")
def test_a_budget_the_thinking_stays_under(self):
code, b = self.openai(reasoning_budget_tokens=10_000)
self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT)
self.assertEqual(len(self.engine.prompts), 1)
def test_the_config_default_and_a_request_that_turns_it_off(self):
self.svc.reasoning_budget_tokens = 20
code, b = self.openai()
self.assertEqual(len(self.engine.prompts), 2)
self.assertTrue(b["choices"][0]["message"]["reasoning_content"].startswith(ThinkingEngine.THOUGHT[:20] + "\n"))
code, b = self.openai(reasoning_budget_tokens=0)
self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT)
self.assertEqual(len(self.engine.prompts), 3)
def test_without_thinking_there_is_nothing_to_limit(self):
self.engine.THOUGHT = ""
code, b = self.openai(reasoning_budget_tokens=5, reasoning_effort="none")
self.assertEqual(code, 200, b)
self.assertEqual(len(self.engine.prompts), 1)
def test_no_room_left_to_answer(self):
code, b = self.openai(reasoning_budget_tokens=20, max_tokens=40) # 20 thought + the wrap-up > 40
self.assertEqual(b["choices"][0]["finish_reason"], "length")
self.assertEqual(len(self.engine.prompts), 1)
self.assertEqual(b["choices"][0]["message"]["reasoning_content"], ThinkingEngine.THOUGHT[:20])
def test_a_bad_value_is_a_400(self):
for bad in ("lots", 2.5, True, [1]):
with self.subTest(value=bad):
code, b = self.openai(reasoning_budget_tokens=bad)
self.assertEqual(code, 400)
self.assertIn("reasoning_budget_tokens", b["error"]["message"])
self.assertEqual(self.engine.prompts, [])
class StatusHandover(unittest.TestCase):
"""#266: a stream aborted mid-way and the next request, which was waiting for the fifo. The aborted request's
status/history block ran after the fifo was released, so the waiting request could start in that gap: the old