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: opt-in recovery from repeated reasoning passages
wangmengc34732624253
diff --git a/docs/DETAILS.md b/docs/DETAILS.mdindex c566b06e8..df47bd2ea 100644--- a/docs/DETAILS.md+++ b/docs/DETAILS.md@@ -517,6 +517,20 @@ print(r.choices[0].message.content)server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a brokenstate that answers one token forever (#606 saw 36,689 tokens of `!`). `"repeat_stop_tokens": N` in`strata-<model>.json` sets the run length; `0` turns it off (for a request that really wants one token many times).+- **Repeated reasoning (opt-in, #728).** The single-token guard above does not see a model that repeats whole+ passages. `"reasoning_loop_recovery"` in `strata-<model>.json` is `false` (the default), `"stop"` or `"recover"`+ (`true` means `"recover"`). Every 512 output tokens, at a complete character and parser boundary, the reasoning is+ measured over its last 2,000 words and punctuation marks (counting passages over the last 30,000 words). If at+ least 25% belong to 12-word passages seen three times, `"stop"` ends the reply there as `"length"` and says so in+ the server window. `"recover"` stops and drains that generation, then goes on once from all its generated token+ ids with the template's low-effort sentence in place of the xhigh one in the first system message (a splice of+ token ids: the rest of the prompt is not decoded or re-encoded). The task stays the same; no answer or `</think>`+ is inserted, and both passes share the original output limit. On recovery only, temperature is raised to at least+ 1.0 and presence penalty to at least 1.5; a client's top-p, top-k and seed are never changed. `/metrics` records+ `reasoning_recoveries` and the coverage. This is a policy, not a numerical engine fix or a guarantee of an answer.+ `"recover"` needs the exact xhigh sentence in the first system message and skips requests with images; re-reading+ the changed prefix costs prompt time. Either mode can mistake repeated useful code or checks for a loop, so keep+ the recorded answer quality alongside the completion rate when testing it.- **Changing the effort without re-reading the prompt (opt-in, 0.1.39, #458).** The effort's instruction is thefirst thing in the prompt, so a request that only changes the effort (an agent's "think harder" switch, `none` fora quick tool step) reads the whole conversation again. `"effort_position": "end"` in `strata-<model>.json` rendersdiff --git a/serve/server.py b/serve/server.pyindex 5681e71cf..1a1dd5ba9 100644--- a/serve/server.py+++ b/serve/server.py@@ -70,7 +70,11 @@ 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."}+ "elaboration.",+ # the template's own xhigh sentence (chat_template.jinja), which #728's recovery swaps for the low one+ "xhigh": "Reasoning effort is set to xhigh. Please think carefully through the task, validate key "+ "assumptions, consider plausible alternatives, and prioritize correctness, consistency, and "+ "clarity in the final answer."}VISION_START = "<|vision_start|>"# #606: a reply that repeats one token this many times in a row is ended there ("length"): a model in a loop, or a# broken state that answers one token forever (an issue saw 36,689 tokens of "!"). The config's "repeat_stop_tokens"@@ -78,6 +82,54 @@ VISION_START = "<|vision_start|>"REPEAT_STOP_TOKENS = 256# #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"+# #728: opt-in handling of reasoning that repeats whole passages (which the single-token guard above cannot see).+# "reasoning_loop_recovery": "stop" ends the reply there; "recover" (or true) goes on from the same output with the+# low-effort instruction in place of the xhigh one. Both off by default.+HIGH_EFFORT = EFFORT_TEXT["xhigh"]+LOW_EFFORT = EFFORT_TEXT["low"]+LOOP_CHECK_EVERY = 512 # output tokens between two looks at the reasoning (at a clean parser boundary)+LOOP_COVERAGE = 0.25 # the share of the last 2,000 words inside 12-word passages seen three times+LOOP_HISTORY_WORDS = 30000 # how far back the passages are counted (bounds the cost of a look)+++def reasoning_repeat_coverage(text):+ """Coverage of recent words by 12-word passages seen at least three times.++ Only reasoning is supplied. The history (the last LOOP_HISTORY_WORDS words) detects repeated verification passes+ separated by long code drafts; the recent window excludes old repetitions.+ """+ words = re.findall(r"\w+|[^\w\s]", text.lower())[-LOOP_HISTORY_WORDS:]+ width, window = 12, 2000+ if len(words) < window:+ return 0.0+ grams = [tuple(words[i:i + width]) for i in range(len(words) - width + 1)]+ counts = collections.Counter(grams)+ start = max(0, len(words) - window)+ covered = set()+ for i in range(start, len(grams)):+ if counts[grams[i]] >= 3:+ covered.update(range(i, i + width))+ return len(covered) / (len(words) - start)+++def focused_recovery_prompt(tok, ids, generated):+ """The prompt's ids with the xhigh effort sentence of the first system message replaced by the low one, then+ every token generated so far. A splice of token ids: the prompt is never decoded and encoded again, so a literal+ `</think>` or vision marker in it (#537, #554) stays what it was. None when the sentence is not there as whole+ tokens in the first system message (a user's text never counts). No answer or end-of-thinking is inserted."""+ end = tok.encode(IM_END, parse_special=True)+ if len(end) != 1 or end[0] not in ids:+ return None+ head = ids[:ids.index(end[0])]+ if not tok.decode(head).startswith("<|im_start|>system\n"):+ return None+ old, new = tok.encode(HIGH_EFFORT, parse_special=False), tok.encode(LOW_EFFORT, parse_special=False)+ for i in range(len(head) - len(old) + 1):+ if head[i:i + len(old)] == old:+ return ids[:i] + new + ids[i + len(old):] + list(generated)+ return None++LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")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@@ -1839,6 +1891,7 @@ class Service:self.min_free_vram_mib = 0self.before_load = Noneself.vram_reserve = None # #533: the last POST /v1/vram reserve (None: the start's)+ self.reasoning_loop_recovery = Falseself.reasoning_budget_tokens = 0 # #123: the config's default thinking budget (0: none)self.repeat_stop_tokens = REPEAT_STOP_TOKENS # #606: one token this many times in a row ends a reply (0: off)self.anthropic_think_unasked = True # #278: "anthropic_thinking": "on_request" -> False@@ -2467,6 +2520,8 @@ class Service:opening, force = parser.feed(force), Nonetail = "" # the last characters written (the newlines before a call)timings, before = None, None # this request's timings; the engine's `last` before it+ recovery_count, reasoning_text, repeat_coverage = 0, "", 0.0+ looped, next_loop_check = False, LOOP_CHECK_EVERY # #728: reasoning that repeats whole passagesraw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)emb, self.embeddings.path = getattr(self.embeddings, "path", None), None # this run's to delete now# Identity token: only a DONE line replaces engine.last, so a request that died, errored or was@@ -2497,7 +2552,7 @@ class Service:with self.status_lock:st.update(busy=True, phase="reading the prompt", prompt_tokens=len(ids),generated=0, started=time.time(), first_token=None, tool=None, tail="",- max_tokens=max_new)+ max_tokens=max_new, reasoning_recoveries=0)if par:self.live_reqs[id(st)] = (st, rate)self.status.update(st)@@ -2511,6 +2566,7 @@ class Service: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)+ recover_prompt = Noneseg, wrap, leaving = [], False, False # this pass's tokens; the budget is reached; closedopens = False # the thinking is over: write the forced call's openingtry:@@ -2541,10 +2597,24 @@ class Service:self._note(n, evs, st, rate)last_print = self._progress(last_print, st=st)for ev in evs:+ if self.reasoning_loop_recovery and ev.kind == "reasoning":+ reasoning_text += ev.text or ""yield "event", evif stops is not None and stops.hit is not None:finish = "stop" # gen.close() below STOPs the engine, as for a stop tokenbreak+ if (self.reasoning_loop_recovery and not recovery_count and parser.state == "reasoning"+ and n >= next_loop_check and not parser.buf and not detok.pending()):+ next_loop_check = n + LOOP_CHECK_EVERY+ repeat_coverage = reasoning_repeat_coverage(reasoning_text)+ if repeat_coverage >= LOOP_COVERAGE:+ if self.reasoning_loop_recovery == "stop":+ looped = True # #728: end the reply here, as for a repeated token+ break+ if not emb: # "recover": not for a request with pictures+ recover_prompt = focused_recovery_prompt(self.tok, ids, raw_ids)+ if recover_prompt is not None:+ breakif budget and parser.state == "reasoning":thought += 1# at a clean point: no tag held back, no character split across tokens@@ -2578,6 +2648,26 @@ class Service:self._say_died(e)if not leaving and not cancel.is_set():raise+ if recover_prompt is not None and not cancel.is_set() and n < max_new:+ recovery_count += 1+ # Only the two settings that keep the same words coming are raised (temperature to at+ # least 1.0, presence penalty to at least 1.5): a client's top_p and top_k are never+ # touched, and its own request dict is copied, not changed.+ want = (max(1.0, float((sampling or {}).get("temperature") or 0)),+ max(1.5, float((sampling or {}).get("presence_penalty") or 0)))+ if want != tuple(float((sampling or {}).get(k) or 0)+ for k in ("temperature", "presence_penalty")):+ sampling = {**(sampling or {}), "temperature": want[0], "presence_penalty": want[1]}+ prompt = recover_prompt+ with self.status_lock:+ st["reasoning_recoveries"] = recovery_count+ if trace is not None:+ trace["reasoning_recoveries"] = recovery_count+ trace["reasoning_repeat_coverage"] = round(repeat_coverage, 3)+ print(f"[strata] repeated reasoning detected at {n} tokens "+ f"(coverage={repeat_coverage:.3f}); resuming the same output with the low-effort "+ "instruction (reasoning_loop_recovery)", flush=True)+ continueif not (wrap or opens) or cancel.is_set():break# #123: the thinking reached reasoning_budget_tokens. Close it the way the model would (a@@ -2611,6 +2701,10 @@ class Service:prompt = prompt + seg + extraif cancel.is_set():finish = "cancel"+ elif looped:+ print(f"[strata] the thinking repeated the same passages (coverage={repeat_coverage:.3f}) at "+ f"{n} tokens: ended as \"length\" (reasoning_loop_recovery: \"stop\" in "+ "strata-<model>.json; remove it to turn this off)", flush=True)elif repeated:print(f"[strata] the reply repeated one token ({self.tok.decode([run_tok])!r}) "f"{run_len} times in a row: ended as \"length\" (repeat_stop_tokens in "@@ -2645,6 +2739,8 @@ class Service:"prompt_tokens": seen, "reused": last.get("reused"), "output_tokens": n,# the request's whole prompt, and the tokens read of it (None: an older engine)"prompt_total": len(ids), "prompt_read": last.get("prompt_read"),+ "reasoning_recoveries": recovery_count,+ "reasoning_repeat_coverage": round(repeat_coverage, 3),"engine_generated": last.get("generated"),"prompt_ms": last.get("prompt_ms"), "decode_ms": last.get("decode_ms"),"decode_tok_s": round(last["generated"] / (last["decode_ms"] / 1000), 1)@@ -2702,7 +2798,8 @@ class Service:if stops is not None and stops.hit is None and stops.held:yield "event", Event("content", stops.flush()) # the held tail was not a stop string after alldone = {"finish": finish, "completion_tokens": n, "reused": (timings or {}).get("cache_n", 0),- "timings": timings, "reasoning_tokens": thinking_n}+ "timings": timings, "reasoning_tokens": thinking_n,+ "reasoning_recoveries": recovery_count}if stops is not None and stops.hit is not None:done["stop_sequence"] = stops.hityield "done", done@@ -4434,6 +4531,13 @@ def main() -> int:if budget:print(f"[strata] thinking budget: {budget} tokens (reasoning_budget_tokens; a request can set its own)",flush=True)+ recovery = cfg.get("reasoning_loop_recovery", False) # #728: false (default) | "stop" | "recover" (true)+ if recovery is True:+ recovery = "recover"+ if recovery is not False and recovery not in ("stop", "recover"):+ raise SystemExit("[strata] config \"reasoning_loop_recovery\" must be false, \"stop\" or \"recover\", "+ f"not {recovery!r}")+ svc.reasoning_loop_recovery = recoverysvc.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)svc.backend = cfg.get("backend") # "hip": the AMD cards' readings come from sysfs (#301)diff --git a/serve/test_reasoning_loop_recovery.py b/serve/test_reasoning_loop_recovery.pynew file mode 100644index 000000000..879fd0ba7--- /dev/null+++ b/serve/test_reasoning_loop_recovery.py@@ -0,0 +1,195 @@+"""CPU-only regression for opt-in reasoning recovery: python -m unittest serve.test_reasoning_loop_recovery."""+import threading+import unittest+from serve.server import (Service, ByteTokenizer, MockEngine, HIGH_EFFORT,+ reasoning_repeat_coverage, focused_recovery_prompt)+++class Tokenizer(ByteTokenizer):+ def token_bytes(self, token):+ return self.SPECIALS[token - 256].encode() if token >= 256 else bytes([token])+++class RecordingEngine(MockEngine):+ def __init__(self, tokenizer, scripts):+ super().__init__(tokenizer, scripts, max_context=100000)+ self.calls = []+ self.sampling_calls = []+ self.sampling_objects = []++ def generate(self, ids, max_new, sampling, cancel, **kwargs):+ self.calls.append((list(ids), max_new))+ self.sampling_calls.append(dict(sampling or {}))+ self.sampling_objects.append(sampling)+ yield from super().generate(ids, max_new, sampling, cancel, **kwargs)+++class ReasoningLoopRecovery(unittest.TestCase):+ def setUp(self):+ self.tok = Tokenizer()+ self.ids = self.tok.encode('<|im_start|>system\n' + HIGH_EFFORT ++ '<|im_end|>\n<|im_start|>user\nSolve this unchanged task<|im_end|>\n'+ '<|im_start|>assistant\n<think>\n', parse_special=True)+ self.loop = 'Need maybe Agent support agent seven b. ' * 700++ def test_repetition_and_novel_work(self):+ self.assertEqual(reasoning_repeat_coverage(' '.join(str(i) for i in range(4000))), 0)+ self.assertGreater(reasoning_repeat_coverage(self.loop), .9)++ def test_user_instruction_is_never_rewritten(self):+ ids = self.tok.encode('<|im_start|>user\n' + HIGH_EFFORT, parse_special=True)+ self.assertIsNone(focused_recovery_prompt(self.tok, ids, []))++ def test_preserves_task_and_exact_generated_tokens(self):+ generated = self.tok.encode('中文 partially checked code', parse_special=False)+ prompt = focused_recovery_prompt(self.tok, self.ids, generated)+ self.assertEqual(prompt[-len(generated):], generated)+ self.assertIn('Solve this unchanged task', self.tok.decode(prompt))+ self.assertNotIn('</think>', self.tok.decode(prompt))++ def run_case(self, enabled):+ engine = RecordingEngine(self.tok, [self.loop,+ 'I have verified the solution.\n</think>\nComplete solution.'])+ service = Service(engine, self.tok, None)+ service.reasoning_loop_recovery = enabled+ events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))+ return engine, events++ def test_old_explicit_sampler_recovers_without_mutating_request(self):+ engine = RecordingEngine(self.tok, [self.loop,+ 'Verified.\n</think>\nComplete solution.'])+ service = Service(engine, self.tok, None)+ 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()))+ self.assertEqual(engine.sampling_calls[0], request)+ self.assertEqual(engine.sampling_calls[1]['temperature'], 1.0)+ self.assertEqual(engine.sampling_calls[1]['presence_penalty'], 1.5)+ self.assertEqual(engine.sampling_calls[1]['top_k'], 64) # a client's top_k and top_p are never touched+ self.assertEqual(engine.sampling_calls[1]['top_p'], .95)+ self.assertEqual(engine.sampling_calls[1]['seed'], request['seed'])+ self.assertEqual(request['temperature'], .2)+ self.assertEqual(request['presence_penalty'], 0)++ 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.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()))+ self.assertEqual(len(engine.sampling_objects), 2)+ self.assertIs(engine.sampling_objects[0], engine.sampling_objects[1])+ self.assertIs(engine.sampling_objects[1], sampler)++ 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.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))+ self.assertEqual((engine.sampling_calls[1]['temperature'], engine.sampling_calls[1]['presence_penalty']), (1.0, 1.5))++ def test_the_splice_keeps_a_literal_think_tag_as_text(self):+ """#537: the prompt is spliced as token ids, never decoded and encoded again."""+ from serve.frontend import THINK_TAGS+ head = '<|im_start|>system\n' + HIGH_EFFORT+ marked = self.tok.encode(head + '<|im_end|>\n<|im_start|>user\nquote ' + THINK_TAGS['</think>'] ++ ' please<|im_end|>\n<|im_start|>assistant\n<think>\n', parse_special=True)+ spliced = focused_recovery_prompt(self.tok, marked, [])+ tail = marked[len(self.tok.encode(head, parse_special=True)):]+ self.assertEqual(spliced[-len(tail):], tail) # everything after the sentence is the same ids+ self.assertNotEqual(spliced, marked)++ def test_stop_mode_ends_the_reply_at_the_loop(self):+ engine = RecordingEngine(self.tok, [self.loop])+ service = Service(engine, self.tok, None)+ service.reasoning_loop_recovery = "stop"+ events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))+ self.assertEqual(len(engine.calls), 1) # no second pass+ self.assertEqual(events[-1][1]['finish'], 'length')+ self.assertLess(events[-1][1]['completion_tokens'], 20000)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 0)++ def test_disabled_is_one_pass(self):+ engine, events = self.run_case(False)+ self.assertEqual(len(engine.calls), 1)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 0)++ def test_default_single_token_guard_does_not_detect_passage_loop(self):+ engine = RecordingEngine(self.tok, [self.loop])+ service = Service(engine, self.tok, None)+ events = list(service.run(self.ids, True, [], 16384, {}, threading.Event()))+ self.assertEqual(service.repeat_stop_tokens, 256)+ self.assertEqual(events[-1][1]['finish'], 'length')+ self.assertEqual(events[-1][1]['completion_tokens'], 16384)+ self.assertFalse(any(e.kind == 'content' for kind, e in events if kind == 'event'))++ 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.reasoning_loop_recovery = True+ events = list(service.run(self.ids, True, [], 16384, {}, threading.Event()))+ self.assertEqual(len(engine.calls), 2)+ self.assertEqual(events[-1][1]['finish'], 'length')+ self.assertEqual(events[-1][1]['completion_tokens'], 16384)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 1)++ 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.reasoning_loop_recovery = True+ events = list(service.run(self.ids, False, [], 40000, {}, threading.Event()))+ self.assertEqual(len(engine.calls), 1)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 0)++ def test_missing_native_high_hint_skips_recovery(self):+ engine = RecordingEngine(self.tok, [self.loop])+ service = Service(engine, self.tok, None)+ 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()))+ self.assertEqual(len(engine.calls), 1)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 0)++ def test_cancel_during_reasoning_does_not_start_recovery(self):+ engine = RecordingEngine(self.tok, [self.loop, 'Unused'])+ service = Service(engine, self.tok, None)+ service.reasoning_loop_recovery = True+ cancel = threading.Event()+ events = []+ for event in service.run(self.ids, True, [], 40000, {}, cancel):+ events.append(event)+ if event[0] == 'event':+ cancel.set()+ self.assertEqual(len(engine.calls), 1)+ self.assertEqual(events[-1][1]['finish'], 'cancel')+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 0)++ def test_batch_status_and_history_record_recovery(self):+ engine = RecordingEngine(self.tok, [self.loop, 'Done.\n</think>\nAnswer.'])+ engine.batch = 2+ service = Service(engine, self.tok, None)+ service.reasoning_loop_recovery = True+ events = list(service.run(self.ids, True, [], 40000, {}, threading.Event()))+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 1)+ self.assertEqual(service.history[-1]['reasoning_recoveries'], 1)+ self.assertGreaterEqual(service.history[-1]['reasoning_repeat_coverage'], .25)+ self.assertFalse(service.status['busy'])+ self.assertEqual(service.live_reqs, {})++ def test_natural_answer_with_shared_budget_and_preserved_prefix(self):+ engine, events = self.run_case(True)+ self.assertEqual(len(engine.calls), 2)+ self.assertEqual(events[-1][1]['reasoning_recoveries'], 1)+ self.assertEqual(events[-1][1]['finish'], 'stop')+ content = ''.join(e.text or '' for kind, e in events if kind == 'event' and e.kind == 'content')+ self.assertEqual(content, 'Complete solution.')+ head_size = len(focused_recovery_prompt(self.tok, self.ids, []))+ retained = engine.calls[1][0][head_size:]+ self.assertEqual(retained, self.tok.encode(self.loop)[:len(retained)])+ self.assertEqual(engine.calls[1][1], 40000 - len(retained))+ self.assertNotIn('</think>', self.tok.decode(engine.calls[1][0]))+++if __name__ == '__main__':+ unittest.main()