diff --git a/serve/server.py b/serve/server.py index 7584b3c394..b89284e11e 100644 --- a/serve/server.py +++ b/serve/server.py @@ -6504,7 +6504,8 @@ class Service: hold_end = None if (budget and getattr(self.engine, "can_hold", False) is True and (not getattr(self.engine, "batch", 0) or getattr(self.engine, "can_hold_batch", False) is True) - and not getattr(self.engine, "multi", 0)): + and not getattr(self.engine, "multi", 0) + and getattr(self.engine, "split_engine", False) is not True): # (the split engine's parser refuses the key: tests/split/test_split_gen_keys.py) te = self.tok.encode(THINK_END, parse_special=True) hold_end = te[0] if len(te) == 1 else None for ev in opening: @@ -6512,10 +6513,14 @@ class Service: while True: segment_before = getattr(self.engine, "last", None) segments_before = len(segments) # (#879: a pass sent again leaves no segment) - pass_sampling = {k: v for k, v in (sampling or {}).items() if k != HOLD_KEY} held = hold_end is not None and budget is not None if held: # the reasoning tokens left before the budget (at least one: a cut not yet clean) + pass_sampling = {k: v for k, v in (sampling or {}).items() if k != HOLD_KEY} # (a copy: the hold is this pass's own) pass_sampling[HOLD_KEY] = (max(1, int(budget) - thought), int(hold_end)) + elif sampling and HOLD_KEY in sampling: # (never a client's: strip it from a copy) + pass_sampling = {k: v for k, v in sampling.items() if k != HOLD_KEY} + else: + pass_sampling = sampling # no hold: the engine gets the caller's own sampler object, as before P2 gen = self.engine.generate(prompt, max_new - n, pass_sampling, cancel, embeddings=emb) if emb \ else self.engine.generate(prompt, max_new - n, pass_sampling, cancel) recover_prompt = None diff --git a/serve/test_thinking_hold.py b/serve/test_thinking_hold.py index e8a43c3ca1..8d6b961886 100644 --- a/serve/test_thinking_hold.py +++ b/serve/test_thinking_hold.py @@ -42,6 +42,7 @@ class WindowEngine: self.think_end = tok.encode("", parse_special=True)[0] self.end = tok.encode("<|im_end|>", parse_special=True) self.wrap = tok.encode(REASONING_WRAP_UP, parse_special=True) + self.sampling_objects: list = [] # the sampling object each pass was handed (identity, as test_reasoning_loop_recovery reads it) self.live: list[int] = [] self.checkpoints: list[int] = [] self.turn: list[int] | None = None @@ -67,6 +68,7 @@ class WindowEngine: else: reused = max([c for c in self.checkpoints if c <= len(ids) - 1 and c <= len(self.live) and ids[:c] == self.live[:c]] or [0]) + self.sampling_objects.append(sampling) hold = (sampling or {}).get(HOLD_KEY) if self.honours_hold else None row = {"prompt": len(ids), "reused": reused, "read": len(ids) - reused, "hold": hold} self.passes.append(row) @@ -131,6 +133,7 @@ class HoldCase(unittest.TestCase): self.tok = ThinkTokenizer() self.engine = WindowEngine(self.tok, **kw) svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja")) + self.svc = svc self.httpd = serve(svc, port=0) self.addCleanup(self.httpd.server_close) self.addCleanup(self.httpd.shutdown) @@ -233,6 +236,15 @@ class ThinkingHold(HoldCase): self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20)) self.assertTrue(all(p["hold"] is None for p in self.engine.passes)) + def test_a_split_engine_never_gets_the_hold_even_if_its_ready_said_hold(self): + """The split engine's parser ends a request that carries a key it does not know ("GEN: unknown key hold"): the server also keeps the hold + from an engine it knows is a split engine by name, whatever READY said.""" + self.start(can_hold=True, can_hold_batch=True) + self.engine.split_engine = True + self.engine.batch = 4 + self.assertEqual(self.chat(reasoning_budget_tokens=20), self.expected(20)) + self.assertTrue(all(p["hold"] is None for p in self.engine.passes)) + def test_a_batch_engine_that_says_holdb_gets_the_hold(self): """P2b: a --batch engine whose slots end at the hold (READY holdb) gets the key like a solo engine: the second pass reads the last reasoning token and the wrap-up, as in the solo case.""" @@ -252,6 +264,65 @@ class ThinkingHold(HoldCase): self.assertTrue(all(p["hold"] is None for p in self.engine.passes)) +class SamplerObject(HoldCase): + """The engine is handed the caller's own sampling object on every pass unless this pass adds (or must strip) the hold, and the caller's dict is + never mutated (serve/test_reasoning_loop_recovery.py::test_frozen_cohort_sampler_is_unchanged_during_recovery reads the identity; found by round 18's + py-serve run: be101072b made every pass hand the engine a copy).""" + + def run_it(self, sampling, **kw): + import copy + import threading + self.start(**kw) + ids = self.tok.encode("<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n\n", parse_special=True) + before = copy.deepcopy(sampling) + events = list(self.svc.run(ids, True, [], 400, sampling, threading.Event())) + self.assertEqual(sampling, before, "the caller's dict was mutated") + self.assertEqual(events[-1][0], "done") + return self.engine.sampling_objects + + def test_no_hold_the_engine_gets_the_callers_own_object_on_every_pass(self): + for kw in ({"can_hold": False}, {"can_hold": True, "honours_hold": True, "batch_engine": True}): + with self.subTest(**kw): + batch = kw.pop("batch_engine", False) + sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20} + self.start(**kw) + self.engine.batch = 4 if batch else 0 # (a --batch engine without holdb: no hold is sent either) + import threading + ids = self.tok.encode("<|im_start|>user\n2+2?<|im_end|>\n<|im_start|>assistant\n\n", parse_special=True) + list(self.svc.run(ids, True, [], 400, sampling, threading.Event())) + objs = self.engine.sampling_objects + self.assertEqual(len(objs), 2) # the budget's two passes + self.assertTrue(all(o is sampling for o in objs)) + self.assertNotIn(HOLD_KEY, sampling) + + def test_no_budget_one_pass_the_callers_own_object(self): + sampling = {"temperature": 0.0} + objs = self.run_it(sampling) + self.assertEqual(len(objs), 1) + self.assertIs(objs[0], sampling) + + def test_a_hold_is_added_to_a_copy_and_the_callers_dict_keeps_no_key(self): + sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20} + objs = self.run_it(sampling) + self.assertEqual(len(objs), 2) + self.assertIsNot(objs[0], sampling) + self.assertIn(HOLD_KEY, objs[0]) # the first pass carries the hold + self.assertNotIn(HOLD_KEY, objs[1]) # the answer pass: the budget is spent + self.assertNotIn(HOLD_KEY, sampling) + self.assertEqual({k: v for k, v in objs[0].items() if k != HOLD_KEY}, sampling) + + def test_a_hold_key_in_the_callers_dict_is_stripped_from_a_copy(self): + """The hold is the server's own key, never a client's: a caller's dict that carries one is not mutated and the engine does not see it + when this pass adds none.""" + sampling = {"temperature": 0.0, "reasoning_budget_tokens": 20, HOLD_KEY: (3, 5)} + objs = self.run_it(sampling, can_hold=False) + self.assertEqual(len(objs), 2) + for o in objs: + self.assertIsNot(o, sampling) + self.assertNotIn(HOLD_KEY, o) + self.assertEqual(sampling[HOLD_KEY], (3, 5)) + + class HoldKey(unittest.TestCase): def test_the_gen_key(self): self.assertEqual(StrataEngine.sampling_keys({HOLD_KEY: (512, 248069)}), " hold=512:248069") diff --git a/tests/split/test_split_gen_keys.py b/tests/split/test_split_gen_keys.py index 2cd92727a2..21f993a933 100644 --- a/tests/split/test_split_gen_keys.py +++ b/tests/split/test_split_gen_keys.py @@ -18,8 +18,11 @@ ACCEPTED = {"temperature", "top_p", "top_k", "min_p", "penalty_repeat", "penalty # (refuse_for_split, logit_bias.validate_request) DROPPED = {"pen_from"} REFUSED = {"logprobs", "allowed", "logit_bias"} -# keys only other engines are sent: the DeepSeek engine's restore points (STRATA_DS4_RESTORE_POINTS), the prefill-only request of serve/split.py, rid for several writers -OTHER_ENGINES = {"marks", "tail", "shared", "prefill", "rid"} +# keys only other engines are sent: the DeepSeek engine's restore points (STRATA_DS4_RESTORE_POINTS), the prefill-only request of serve/split.py, rid for several writers, +# and hold (the thinking budget's GEN hold=N:ID): the server sends it only to an engine whose READY line says "hold" (a --batch engine: "holdb" too), which is the +# single-card engine (src/program/generate.cpp prints "READY stop hold holdb"); the split engine says "READY stop" (sfnx.cpp), so it is never sent it, and +# the server also refuses it for a split engine by name (Service._run). Sent to a split engine anyway, parse_gen would end the request with "GEN: unknown key hold". +OTHER_ENGINES = {"marks", "tail", "shared", "prefill", "rid", "hold"} def server_keys() -> set[str]: @@ -36,6 +39,7 @@ def server_keys() -> set[str]: keys |= set(re.findall(r'"(logit_bias)="', (ROOT / "serve" / "logit_bias.py").read_text(encoding="utf-8"))) keys |= set(re.findall(r'" (\w+)=" \+', (ROOT / "serve" / "logit_bias.py").read_text(encoding="utf-8"))) keys |= set(re.findall(r'keys \+= f" (\w+)=', text)) + keys |= set(re.findall(r'keys0 \+ f" (\w+)=', text)) # generate_batched adds the thinking budget's hold per leg (P2b) return keys @@ -53,6 +57,19 @@ class SplitGenKeys(unittest.TestCase): for must in ("pen_from", "logprobs", "allowed", "temperature", "penalty_last_n", "seed"): self.assertIn(must, sent, f"{must}: the parse of serve/server.py no longer finds it (update this test)") + def test_hold_is_only_for_an_engine_that_says_hold_and_the_split_engine_never_does(self): + """The server sends `hold` only to an engine whose READY line says "hold" (the --batch slots: "holdb"); the split engine's READY line says neither, and + its parser does not know the key (it would end the request: "GEN: unknown key hold").""" + split = (ROOT / "src" / "split" / "tools" / "sfnx.cpp").read_text(encoding="utf-8") + readys = re.findall(r'say\("READY "[^;]*;', split) + self.assertTrue(readys, "the split engine's READY line is no longer found (update this test)") + for line in readys: + self.assertNotIn("hold", line) + self.assertNotIn("hold", parser_keys()) + gen = (ROOT / "src" / "program" / "generate.cpp").read_text(encoding="utf-8") + self.assertIn('"READY %lld stop hold holdb\\n"', gen) # the engine that does take it says both + self.assertIn('"hold" in f[2:]', (ROOT / "serve" / "server.py").read_text(encoding="utf-8")) # and the server reads the word, not the engine's name + def test_the_keys_sent_to_a_split_engine_are_accepted_by_its_parser(self): parser = parser_keys() self.assertEqual(sorted(ACCEPTED - parser), [], "a key the split engine is sent but its parse_gen does not know")