merge f-145-int 194c26881 (model-card sampling defaults, web sampling, answer room, thinking budget) into f-split-int
serve/server.py: the model_arch line joins the existing engine == strata block next to requested_slots.
This commit is contained in:
commit
07fe758ac9
9 files changed
+314
-13
No files matched your search
+17
-3
@@ -786,7 +786,16 @@ print(r.choices[0].message.content)
|
||||
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.
|
||||
Anthropic's `"thinking": {"budget_tokens": N}` chooses the level, as above, and since 0.1.45 is also the budget (a
|
||||
`reasoning_budget_tokens` in the same request wins).
|
||||
- **max_tokens counts the thinking, so the answer keeps its room (0.1.45).** A client that caps the whole reply (the
|
||||
desktop agent's harness sends `max_completion_tokens: 8192` on every request) and a task the model thinks long about
|
||||
used to be cut off in the middle of the thinking, with no answer. Now a request with thinking on, no budget of its
|
||||
own and `max_tokens` of 1,024 or more gets one: the thinking is wrapped up when only a quarter of the cap (at least
|
||||
512 tokens) is left, and the model answers in that room (8,192: thinking up to 6,144, answer 2,048). Requests without
|
||||
`max_tokens` (the rest of the context) get a budget of three quarters of it. `"answer_room": false` in
|
||||
`strata-<model>.json` turns it off. Qwen recommends up to 262,144 tokens of reasoning and 131,072 of answer: a client
|
||||
should not cap the reply far below what the context allows.
|
||||
- **A reply that ends inside its thinking (#1053, opt-in).** Some turns write a sentence of reasoning and then the
|
||||
end-of-turn token with no `</think>`: the content is empty and an agent stops. `"reasoning_close_retry": true` in
|
||||
`strata-<model>.json` closes the thinking once (as the thinking budget does) and continues, once per request, only for
|
||||
@@ -1280,8 +1289,13 @@ to 4; Anthropic `stop_sequences`): the answer ends before the first one, which i
|
||||
there (`finish_reason` "stop"; `stop_reason` "stop_sequence" with `stop_sequence` set to the one found); with the default adaptive expert tier a sampled result
|
||||
is not reproducible run to run - for seed-reproducible output add `--adapt-every 100000` (static residency) to the
|
||||
engine arguments. The run config's optional `sampling` block sets the defaults for requests that leave the fields out
|
||||
(`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win, and with no
|
||||
block at all a request without sampling keys decodes greedy. The penalties (`presence_penalty`, `frequency_penalty`,
|
||||
(`"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20}`); a request's own fields always win. **With no
|
||||
block at all (0.1.45) a request without sampling keys gets the sampling the model card recommends**, picked by the
|
||||
request's thinking state: Qwen3.8-Flash-Next (and Gyro) thinking temperature 1.0, top_p 0.95, top_k 20; not thinking temperature 0.7,
|
||||
top_p 0.8, top_k 20, presence_penalty 1.5. Qwen3.6-35B-A3B thinking 1.0 / 0.95 / 20 with presence_penalty 1.5, not thinking
|
||||
0.7 / 0.8 / 20 with 1.5 (min_p 0 and repetition_penalty 1 are "off"). Order of precedence: the request, the web page's shared Chat settings,
|
||||
the config's `sampling` block, the card. Greedy is only for who asks for it: `temperature: 0` in the request, or `"sampling": {"temperature": 0}` in the config
|
||||
(before 0.1.45 a config without a block ran greedy, and greedy decoding is what makes small local models loop; #2685). The web page sends no sampling of its own until you change its Sampling settings (it showed and sent 0.6 before); an old stored 0.6 with the default top_p and top_k counts as not set. The penalties (`presence_penalty`, `frequency_penalty`,
|
||||
`repetition_penalty`, with `penalty_last_n` capping how many recent tokens they count over, default 64 when any
|
||||
penalty is set; llama.cpp's names `repeat_penalty` and `repeat_last_n` work too, in the config's `sampling` block and in a request, #1819) ride the same path; they count the tokens the request has consumed, so a repetition penalty
|
||||
suppresses what the model itself just said, not the prompt alone. Since engine 0.1.19 they apply to every token
|
||||
|
||||
@@ -637,6 +637,11 @@ def anthropic_to_messages(req: dict, think_unasked: bool = True) -> tuple[list[d
|
||||
# "output_config": {"effort": "low" | "medium" | "high"}
|
||||
thinking = req.get("thinking")
|
||||
effort = (req.get("output_config") or {}).get("effort") if isinstance(req.get("output_config"), dict) else None
|
||||
# 0.1.45: Anthropic's budget_tokens is a real budget, not only a level: the thinking is closed (wrap-up, </think>,
|
||||
# the answer) after that many tokens. A reasoning_budget_tokens of the request's own wins.
|
||||
bt = thinking.get("budget_tokens") if isinstance(thinking, dict) and thinking.get("type") != "disabled" else None
|
||||
if isinstance(bt, int) and not isinstance(bt, bool) and bt > 0 and req.get("reasoning_budget_tokens") is None:
|
||||
req["reasoning_budget_tokens"] = bt
|
||||
if isinstance(thinking, dict) and thinking.get("type") == "disabled":
|
||||
kwargs["enable_thinking"] = False
|
||||
elif effort:
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ from pathlib import Path
|
||||
# of the "sampling" block, ("arg", flag) for an engine option kept in "args".
|
||||
EDITABLE = [
|
||||
("sampling.temperature", ("sampling", "num>=0"),
|
||||
"Default temperature for requests that send none (0 = greedy, the default without a sampling block)"),
|
||||
"Default temperature for requests that send none (0 = greedy; without it the model card's: 1.0 thinking, 0.7 not)"),
|
||||
("sampling.top_p", ("sampling", "0<x<=1"), "Default top_p for requests that send none"),
|
||||
("sampling.top_k", ("sampling", "1..64"), "Default top_k for requests that send none (1-64)"),
|
||||
("sampling.min_p", ("sampling", "0<=x<=1"), "Default min_p for requests that send none"),
|
||||
|
||||
+38
-3
@@ -170,6 +170,7 @@ VISION_START = "<|vision_start|>"
|
||||
# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens"
|
||||
# sets it; 0 turns it off.
|
||||
REPEAT_STOP_TOKENS = 256
|
||||
ANSWER_ROOM_MIN_CAP = 1024 # 0.1.45: from this max_tokens on, thinking without a budget is closed early enough to leave room to answer
|
||||
ANSWER_RESERVE_MIN = 512 # #984: the tokens kept for the answer when a thinking budget is cut down to fit max_tokens
|
||||
# #123: what closes the thinking when it reaches reasoning_budget_tokens (the model's own end-of-thinking tag after it)
|
||||
# #1053 (opt-in "reasoning_close_retry": true): a reply that ends on its stop token still inside <think>, with no answer
|
||||
@@ -3275,10 +3276,12 @@ class Service:
|
||||
self.literals = literal_tags(getattr(tokenizer, "control_tokens", ())) # texts that stay text inside a message
|
||||
self.fit_max_tokens = fit_max_tokens # --fit-max-tokens: clamp the output cap instead of 400
|
||||
self.aliases: list[str] = [] # #297: other names of the model (the config's `aliases`)
|
||||
self.answer_room = True # 0.1.45: see ANSWER_ROOM_MIN_CAP (the config's "answer_room": false turns it off)
|
||||
self.reasoning_close_retry = False # #1053 (opt-in): close the thinking once when a reply ends inside it
|
||||
self.codex_compaction_cache = False # #924 (opt-in): a Codex compaction is rendered with its conversation's tools
|
||||
self.codex_thread_titles = False # #923 (opt-in): answer Codex's thread-title turns without the engine
|
||||
self.sampling_defaults = dict(sampling_defaults or {}) # the run config's `sampling` block
|
||||
self.model_arch = None # the config's family ("qwen4exp", "qwen35moe"): None = no model-card defaults
|
||||
self.shared = {} # the web app's Chat settings for every client (POST /settings)
|
||||
self.shared_path = None # where they are kept between starts (next to the config)
|
||||
self.config_effort = None # #1641: the config's "reasoning_effort": the level for requests with none
|
||||
@@ -4446,12 +4449,23 @@ class Service:
|
||||
def _run(self, ids, thinking, tools, max_new, sampling, cancel, force=None) -> Iterator[tuple[str, object]]:
|
||||
"""Yields ("event", Event) as text arrives, then ("done", {"finish": .., "completion_tokens": ..}).
|
||||
`force` (forced_call): the opening of the call the reply must make - see prepare()."""
|
||||
defaults = {**self.sampling_defaults, **self.shared} # the config's, then the Chat settings shared with apps
|
||||
# the model card's sampling for this thinking state, then the config's block, then the Chat settings shared with
|
||||
# apps; the request's own fields win over all of them
|
||||
defaults = {**model_card_sampling(self.model_arch, thinking), **self.sampling_defaults, **self.shared}
|
||||
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}
|
||||
sampling = {**defaults, **req_values}
|
||||
# #123: read after the merge, so a budget shared through POST /settings is seen like the other keys
|
||||
budget = self.reasoning_budget(sampling) if thinking else None
|
||||
if thinking and not budget and self.answer_room and max_new and max_new >= ANSWER_ROOM_MIN_CAP:
|
||||
# 0.1.45: max_tokens counts the thinking too. A client that caps the reply at 8192 (the desktop agent's
|
||||
# harness sends max_completion_tokens: 8192 on every request) and a task the model thinks long about got
|
||||
# the cut-off in the middle of the thinking and NO answer. So thinking is closed early enough to leave
|
||||
# the answer its quarter of the cap (the budget's wrap-up: a short closing sentence, </think>, the answer).
|
||||
# A request with a budget of its own, or max_tokens below ANSWER_ROOM_MIN_CAP, is left as it was.
|
||||
budget = max_new - min(max(ANSWER_RESERVE_MIN, max_new // 4), max_new // 2)
|
||||
if max_new <= 32768: print(f"[strata] thinking limited to {budget} of max_tokens {max_new} so the answer has room "
|
||||
"(\"answer_room\": false in the config turns this off)", flush=True)
|
||||
if budget and max_new and max_new > 0:
|
||||
# #984: a budget at or near max_tokens never fires before the reply is cut off while still thinking, so
|
||||
# it has no answer. Close the thinking early enough to leave room for one.
|
||||
@@ -6258,7 +6272,7 @@ def make_handler(svc: Service):
|
||||
if not svc.loaded() and not getattr(svc.engine, "unloaded", False):
|
||||
self._json(503, {"error": {"message": "the engine is not running"}})
|
||||
return
|
||||
defaults = {**svc.sampling_defaults, **svc.shared}
|
||||
defaults = {**model_card_sampling(svc.model_arch, True), **svc.sampling_defaults, **svc.shared}
|
||||
names = {"repetition_penalty": "repeat_penalty", "penalty_last_n": "repeat_last_n"}
|
||||
params = {names.get(k, k): v for k, v in defaults.items()
|
||||
if k in ("temperature", "top_p", "top_k", "min_p", "seed", "repetition_penalty",
|
||||
@@ -7276,6 +7290,25 @@ def check_request_sampling(req) -> None:
|
||||
FAMILY_MODEL_NAMES = {"qwen4exp": "qwen3.8-flash-next", "qwen35moe": "qwen3.6-35b-a3b"}
|
||||
|
||||
|
||||
# The sampling each model card recommends ("Best Practices"), used when neither the request, the Chat settings nor the
|
||||
# run config's `sampling` block says otherwise. Greedy is only for a request or config that asks for temperature 0.
|
||||
# min_p 0, repetition_penalty 1 and presence_penalty 0 are the engine's own "off", so they are not listed.
|
||||
MODEL_CARD_SAMPLING = {
|
||||
# Qwen3.8-Flash-Next (and Gyro, the same base model)
|
||||
"qwen4exp": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20},
|
||||
"instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
|
||||
# Qwen3.6-35B-A3B: the general-task sets (the card's precise-coding set is temperature 0.6, presence_penalty 0)
|
||||
"qwen35moe": {"thinking": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "presence_penalty": 1.5},
|
||||
"instruct": {"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5}},
|
||||
}
|
||||
|
||||
|
||||
def model_card_sampling(arch, thinking) -> dict:
|
||||
"""The model card's sampling for the family `arch` and the thinking state ({} for an unknown or unset family)."""
|
||||
sets = MODEL_CARD_SAMPLING.get(arch) if arch else None
|
||||
return dict(sets["thinking" if thinking else "instruct"]) if sets else {}
|
||||
|
||||
|
||||
def default_model_name(cfg: dict) -> str:
|
||||
"""The config's "model_name", else its family's name ("arch": qwen4exp, qwen35moe), else Flash-Next's."""
|
||||
return cfg.get("model_name") or FAMILY_MODEL_NAMES.get(cfg.get("arch") or "qwen4exp", "qwen3.8-flash-next")
|
||||
@@ -7588,7 +7621,8 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
svc.offline = a.offline
|
||||
svc.max_queue = max_queue
|
||||
svc.queue_timeout_s = float(queue_timeout) if queue_timeout is not None else None
|
||||
if a.engine == "strata":
|
||||
if a.engine == "strata": # the model card's sampling when nothing else is said (see MODEL_CARD_SAMPLING)
|
||||
svc.model_arch = cfg.get("arch") or "qwen4exp"
|
||||
requested = cfg.get("parallel")
|
||||
if requested is None:
|
||||
args = cfg.get("args", [])
|
||||
@@ -7600,6 +7634,7 @@ def main(argv=None, *, lifecycle_event=None, interrupt_exit_code: int = 0) -> in
|
||||
pass
|
||||
per_replica = requested if isinstance(requested, int) and not isinstance(requested, bool) and requested > 0 else 1
|
||||
svc.requested_slots = per_replica * len(groups) if groups else per_replica
|
||||
svc.answer_room = cfg.get("answer_room") is not False
|
||||
svc.reasoning_close_retry = cfg.get("reasoning_close_retry") is True # #1053: opt-in, off by default
|
||||
if cfg.get("images"): # image generation (serve/images.py), set up by setup --images
|
||||
icfg = {k: (os.path.abspath(os.path.join(cfg.get("cwd") or ".", v))
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""serve/test_model_card_sampling.py - a request that sends no sampling gets the model card's, not greedy (mock engine).
|
||||
|
||||
Qwen's "Best Practices": thinking mode temperature 1.0 / top_p 0.95 / top_k 20, non-thinking 0.7 / 0.8 / 20 with
|
||||
presence_penalty 1.5. The request's own fields win, then the Chat settings shared with apps, then the config's
|
||||
`sampling` block, then the card; temperature 0 asked for is still greedy.
|
||||
|
||||
python -m unittest serve.test_model_card_sampling -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from serve.frontend import ChatTemplate # noqa: E402
|
||||
from serve.server import ByteTokenizer, MockEngine, Service, StrataEngine, model_card_sampling, serve # noqa: E402
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
class Recording(MockEngine):
|
||||
def generate(self, ids, max_new, sampling, cancel, embeddings=None):
|
||||
self.sampling = dict(sampling or {})
|
||||
yield from super().generate(ids, max_new, sampling, cancel, embeddings)
|
||||
|
||||
|
||||
class ModelCardSampling(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tok = ByteTokenizer()
|
||||
cls.engine = Recording(cls.tok, "<think>\nhm\n</think>\n\nok", max_context=8192)
|
||||
cls.svc = Service(cls.engine, cls.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()
|
||||
|
||||
def setUp(self):
|
||||
self.svc.model_arch = "qwen4exp"
|
||||
self.svc.sampling_defaults = {}
|
||||
self.svc.shared = {}
|
||||
self.svc.config_effort = None
|
||||
|
||||
def tearDown(self):
|
||||
self.svc.model_arch = None
|
||||
|
||||
def keys(self, **body):
|
||||
body = {"model": "m", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 8, **body}
|
||||
self.engine.sampling = {}
|
||||
req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
urllib.request.urlopen(req, timeout=10).read()
|
||||
return StrataEngine.sampling_keys(self.engine.sampling)
|
||||
|
||||
def test_tables(self):
|
||||
self.assertEqual(model_card_sampling("qwen4exp", True), {"temperature": 1.0, "top_p": 0.95, "top_k": 20})
|
||||
self.assertEqual(model_card_sampling("qwen4exp", False),
|
||||
{"temperature": 0.7, "top_p": 0.8, "top_k": 20, "presence_penalty": 1.5})
|
||||
self.assertEqual(model_card_sampling("qwen35moe", True)["presence_penalty"], 1.5)
|
||||
self.assertEqual(model_card_sampling(None, True), {})
|
||||
self.assertEqual(model_card_sampling("unknown", False), {})
|
||||
|
||||
def test_thinking_default(self):
|
||||
k = self.keys()
|
||||
self.assertIn("temperature=1.0", k)
|
||||
self.assertIn("top_p=0.95", k)
|
||||
self.assertIn("top_k=20", k)
|
||||
self.assertNotIn("penalty_present", k)
|
||||
|
||||
def test_non_thinking_default(self):
|
||||
k = self.keys(reasoning_effort="none")
|
||||
self.assertIn("temperature=0.7", k)
|
||||
self.assertIn("top_p=0.8", k)
|
||||
self.assertIn("penalty_present=1.5", k)
|
||||
|
||||
def test_request_wins_and_zero_is_greedy(self):
|
||||
k = self.keys(temperature=0)
|
||||
self.assertNotIn("temperature", k)
|
||||
self.assertIn("top_k=20", k)
|
||||
k = self.keys(temperature=0.3, top_p=0.5)
|
||||
self.assertIn("temperature=0.3", k)
|
||||
self.assertIn("top_p=0.5", k)
|
||||
|
||||
def test_config_block_and_shared_settings_win_over_the_card(self):
|
||||
self.svc.sampling_defaults = {"temperature": 0.6, "top_k": 40}
|
||||
k = self.keys()
|
||||
self.assertIn("temperature=0.6", k)
|
||||
self.assertIn("top_k=40", k)
|
||||
self.assertIn("top_p=0.95", k)
|
||||
self.svc.shared = {"temperature": 0.2}
|
||||
self.assertIn("temperature=0.2", self.keys())
|
||||
self.svc.sampling_defaults = {"temperature": 0}
|
||||
self.svc.shared = {}
|
||||
self.assertNotIn("temperature", self.keys()) # a config that asks for greedy gets it
|
||||
|
||||
def test_no_family_no_defaults(self):
|
||||
self.svc.model_arch = None
|
||||
self.assertEqual(self.keys(), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -58,6 +58,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
engine = RecordingEngine(self.tok, [self.loop,
|
||||
'I have verified the solution.\n</think>\nComplete solution.'])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = enabled
|
||||
events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))
|
||||
return engine, events
|
||||
@@ -66,6 +67,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
engine = RecordingEngine(self.tok, [self.loop,
|
||||
'Verified.\n</think>\nComplete solution.'])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
request = {'temperature': .2, 'presence_penalty': 0, 'top_p': .95, 'top_k': 64, 'seed': 2}
|
||||
list(service.run(self.ids, True, [], 40000, request, threading.Event()))
|
||||
@@ -81,6 +83,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_frozen_cohort_sampler_is_unchanged_during_recovery(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop, 'Done.\n</think>\nComplete solution.'])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
sampler = {'temperature': 1.0, 'top_p': .95, 'top_k': 20, 'presence_penalty': 1.5, 'seed': 2}
|
||||
list(service.run(self.ids, True, [], 40000, sampler, threading.Event()))
|
||||
@@ -91,6 +94,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_a_lower_top_p_and_top_k_are_never_raised_or_lowered(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop, 'Verified.\n</think>\nComplete solution.'])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = "recover"
|
||||
list(service.run(self.ids, True, [], 40000, {'temperature': 0, 'top_p': .5, 'top_k': 5}, threading.Event()))
|
||||
self.assertEqual((engine.sampling_calls[1]['top_p'], engine.sampling_calls[1]['top_k']), (.5, 5))
|
||||
@@ -110,6 +114,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_stop_mode_ends_the_reply_at_the_loop(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = "stop"
|
||||
events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))
|
||||
self.assertEqual(len(engine.calls), 1) # no second pass
|
||||
@@ -121,6 +126,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
"""#1753: the word count never sees the digits, so only the tail's period ends the reply."""
|
||||
engine = RecordingEngine(self.tok, ['9^104 = ' + '58747693387' * 3000])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = "stop"
|
||||
events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))
|
||||
self.assertEqual(len(engine.calls), 1) # no second pass
|
||||
@@ -136,6 +142,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_default_single_token_guard_does_not_detect_passage_loop(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
events = list(service.run(self.ids, True, [], 16384, {}, threading.Event()))
|
||||
self.assertEqual(service.repeat_stop_tokens, 256)
|
||||
self.assertEqual(events[-1][1]['finish'], 'length')
|
||||
@@ -145,6 +152,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_recovery_is_once_and_never_extends_output_limit(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop, self.loop])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
events = list(service.run(self.ids, True, [], 16384, {}, threading.Event()))
|
||||
self.assertEqual(len(engine.calls), 2)
|
||||
@@ -155,6 +163,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_repeated_final_text_does_not_change_sampler_or_prompt(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
events = list(service.run(self.ids, False, [], 40000, {}, threading.Event()))
|
||||
self.assertEqual(len(engine.calls), 1)
|
||||
@@ -163,6 +172,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_missing_native_high_hint_skips_recovery(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
ids = self.tok.encode('<|im_start|>user\nTask<|im_end|>\n', parse_special=True)
|
||||
events = list(service.run(ids, True, [], 40000, {}, threading.Event()))
|
||||
@@ -172,6 +182,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
def test_cancel_during_reasoning_does_not_start_recovery(self):
|
||||
engine = RecordingEngine(self.tok, [self.loop, 'Unused'])
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
cancel = threading.Event()
|
||||
events = []
|
||||
@@ -187,6 +198,7 @@ class ReasoningLoopRecovery(unittest.TestCase):
|
||||
engine = RecordingEngine(self.tok, [self.loop, 'Done.\n</think>\nAnswer.'])
|
||||
engine.batch = 2
|
||||
service = Service(engine, self.tok, None)
|
||||
service.answer_room = False # these cases test the loop guards at the cap itself
|
||||
service.reasoning_loop_recovery = True
|
||||
events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))
|
||||
self.assertEqual(events[-1][1]['reasoning_recoveries'], 1)
|
||||
|
||||
@@ -3809,6 +3809,45 @@ class ThinkingBudget(unittest.TestCase):
|
||||
self.assertEqual(text, ThinkingEngine.ANSWER)
|
||||
self.assertEqual(evs[-2]["delta"]["stop_reason"], "end_turn")
|
||||
|
||||
def test_a_cap_that_the_thinking_would_eat_leaves_room_to_answer(self):
|
||||
"""0.1.45: max_tokens counts the thinking; a thinking that would fill it gets closed with a quarter left (the
|
||||
agent harness sends max_completion_tokens 8192; the pagoda's thinking took all of it and no answer came)."""
|
||||
self.engine.THOUGHT = "Let me think step by step about two plus two. " * 40 # 1,800 reasoning tokens
|
||||
code, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "2+2?"}]})
|
||||
self.assertEqual(code, 200, b)
|
||||
msg = b["choices"][0]["message"]
|
||||
self.assertEqual(msg["content"], ThinkingEngine.ANSWER)
|
||||
self.assertEqual(b["choices"][0]["finish_reason"], "stop")
|
||||
self.assertLess(len(msg["reasoning_content"]), 1024 - 256)
|
||||
self.assertEqual(len(self.engine.prompts), 2) # the wrap-up continuation
|
||||
|
||||
def test_the_answer_room_has_its_limits(self):
|
||||
self.engine.THOUGHT = "Let me think step by step about two plus two. " * 40
|
||||
code, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 300, # below the floor: as before
|
||||
"messages": [{"role": "user", "content": "2+2?"}]})
|
||||
self.assertEqual(b["choices"][0]["finish_reason"], "length")
|
||||
self.assertFalse(b["choices"][0]["message"]["content"])
|
||||
self.svc.answer_room = False # the config's "answer_room": false
|
||||
code, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 1024,
|
||||
"messages": [{"role": "user", "content": "2+2?"}]})
|
||||
self.assertEqual(b["choices"][0]["finish_reason"], "length")
|
||||
self.svc.answer_room = True
|
||||
code, b = self.post("/v1/chat/completions", {"model": "m", "max_tokens": 1024, "reasoning_effort": "none",
|
||||
"messages": [{"role": "user", "content": "2+2?"}]})
|
||||
self.assertEqual(len(self.engine.prompts), 3) # thinking off: no budget, one prompt each
|
||||
|
||||
def test_anthropic_thinking_budget_tokens_is_a_budget(self):
|
||||
"""0.1.45: thinking {type: enabled, budget_tokens: N} closes the thinking after N tokens (it was only a level)."""
|
||||
from serve.server import REASONING_WRAP_UP
|
||||
code, b = self.post("/v1/messages", {"model": "m", "max_tokens": 400, "thinking": {"type": "enabled", "budget_tokens": 30},
|
||||
"messages": [{"role": "user", "content": "2+2?"}]})
|
||||
self.assertEqual(code, 200, b)
|
||||
thinking = "".join(c.get("thinking", "") for c in b["content"] if c["type"] == "thinking")
|
||||
self.assertEqual(thinking, ThinkingEngine.THOUGHT[:30] + REASONING_WRAP_UP.split("</think>")[0])
|
||||
self.assertEqual("".join(c.get("text", "") for c in b["content"] if c["type"] == "text"), ThinkingEngine.ANSWER)
|
||||
self.assertEqual(len(self.engine.prompts), 2)
|
||||
|
||||
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)
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""serve/test_web_sampling.py - the web page sends no sampling of its own until the user changes it (0.1.45, #2685).
|
||||
|
||||
The page used to send temperature 0.6 / top_p 0.95 / top_k 20 with every request, so the server's model-card defaults
|
||||
(thinking 1.0, not thinking 0.7 + presence penalty) never applied to it. Pins, with node, the page's own functions:
|
||||
untouched (the shown defaults, or the old stored 0.6) sends nothing, a changed value is sent whole, 0 is greedy.
|
||||
Skipped without node.
|
||||
|
||||
python -m unittest serve.test_web_sampling -v
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
APP = Path(__file__).resolve().parent / "web" / "app.js"
|
||||
|
||||
|
||||
def slice_between(src: str, start: str, end: str) -> str:
|
||||
a = src.index(start)
|
||||
return src[a:src.index(end, a)]
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("node"), "node is not installed")
|
||||
class WebSampling(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
src = APP.read_text(encoding="utf-8")
|
||||
cls.defaults = slice_between(src, "const DEFAULTS", "let settings")
|
||||
cls.shared = slice_between(src, "function sharedDefaults", "async function saveShared")
|
||||
cls.body = slice_between(src, " if (!(settings.temperature > 0)) {", " if (settings.seed)")
|
||||
|
||||
def run_js(self, settings: dict, pieces: str):
|
||||
js = (self.defaults + "function projectionLoaded() { return false; }\n" + self.shared +
|
||||
f"\nconst settings = {json.dumps(settings)};\nconst body = {{}};\n{pieces}\n"
|
||||
"console.log(JSON.stringify({body, shared: sharedDefaults(settings)}));")
|
||||
out = subprocess.run(["node", "-e", js], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return json.loads(out.stdout)
|
||||
|
||||
def sampling(self, **kw):
|
||||
s = {"thinking": "high", "temperature": 1.0, "top_p": 0.95, "top_k": 20, "max": "", "seed": "", "esp": True}
|
||||
s.update(kw)
|
||||
r = self.run_js(s, self.body)
|
||||
return r["body"], r["shared"]
|
||||
|
||||
def test_untouched_sends_nothing(self):
|
||||
for t in (1.0, 0.6): # the shown default, and the old stored default
|
||||
body, shared = self.sampling(temperature=t)
|
||||
self.assertEqual(body, {})
|
||||
self.assertEqual(shared, {"reasoning_effort": "high"})
|
||||
|
||||
def test_changed_values_are_sent_whole(self):
|
||||
body, shared = self.sampling(temperature=0.3)
|
||||
self.assertEqual(body, {"temperature": 0.3, "top_p": 0.95, "top_k": 20})
|
||||
self.assertEqual(shared["temperature"], 0.3)
|
||||
body, _ = self.sampling(top_k=40)
|
||||
self.assertEqual(body, {"temperature": 1.0, "top_p": 0.95, "top_k": 40})
|
||||
body, _ = self.sampling(temperature=0.6, top_p=0.9)
|
||||
self.assertEqual(body["temperature"], 0.6)
|
||||
|
||||
def test_zero_is_greedy(self):
|
||||
body, shared = self.sampling(temperature=0)
|
||||
self.assertEqual(body, {"temperature": 0})
|
||||
self.assertEqual(shared["temperature"], 0)
|
||||
|
||||
def test_the_old_default_is_shown_as_the_new_one(self):
|
||||
src = APP.read_text(encoding="utf-8")
|
||||
self.assertRegex(src, r"if \(samplingUntouched\(settings\)\) settings\.temperature = DEFAULTS\.temperature;")
|
||||
self.assertIsNone(re.search(r"temperature: 0\.6", src))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+17
-6
@@ -560,8 +560,18 @@ function markdown(text) {
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Chat
|
||||
const DEFAULTS = {thinking: "high", temperature: 0.6, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true};
|
||||
// The sampling shown until the user changes it is the model card's thinking set. Untouched, the page sends NO sampling
|
||||
// fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking
|
||||
// 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two
|
||||
// values untouched counts as "not set" too.
|
||||
const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true};
|
||||
const OLD_DEFAULT_TEMPERATURE = 0.6;
|
||||
function samplingUntouched(s) {
|
||||
const t = +s.temperature;
|
||||
return (t === DEFAULTS.temperature || t === OLD_DEFAULT_TEMPERATURE) && +s.top_p === DEFAULTS.top_p && +s.top_k === DEFAULTS.top_k;
|
||||
}
|
||||
let settings = {...DEFAULTS, ...store.get("sampling", {})};
|
||||
if (samplingUntouched(settings)) settings.temperature = DEFAULTS.temperature;
|
||||
let messages = store.get("chat", []);
|
||||
let attachments = []; // {name, url}
|
||||
let busy = null; // {controller, msg}
|
||||
@@ -790,10 +800,10 @@ async function send() {
|
||||
|
||||
const body = {model: health.model, messages: apiMessages(), stream: true,
|
||||
reasoning_effort: settings.thinking};
|
||||
if (settings.temperature > 0) {
|
||||
Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k});
|
||||
} else {
|
||||
if (!(settings.temperature > 0)) {
|
||||
body.temperature = 0;
|
||||
} else if (!samplingUntouched(settings)) {
|
||||
Object.assign(body, {temperature: +settings.temperature, top_p: +settings.top_p, top_k: +settings.top_k});
|
||||
}
|
||||
if (settings.seed) body.seed = +settings.seed;
|
||||
if (settings.max) body.max_tokens = +settings.max;
|
||||
@@ -1011,8 +1021,9 @@ async function loadShared() {
|
||||
$("s-share").setAttribute("aria-checked", String(sharedOn));
|
||||
}
|
||||
function sharedDefaults(s) {
|
||||
const d = {reasoning_effort: s.thinking, temperature: +s.temperature};
|
||||
if (+s.temperature > 0) Object.assign(d, {top_p: +s.top_p, top_k: +s.top_k});
|
||||
const d = {reasoning_effort: s.thinking};
|
||||
if (!(+s.temperature > 0)) d.temperature = 0;
|
||||
else if (!samplingUntouched(s)) Object.assign(d, {temperature: +s.temperature, top_p: +s.top_p, top_k: +s.top_k});
|
||||
if (s.seed) d.seed = +s.seed;
|
||||
if (s.max) d.max_tokens = +s.max;
|
||||
if (projectionLoaded()) d.experimental_speed_projection = s.esp !== false;
|
||||
|
||||
Reference in new issue
Block a user