serve: end a reply that repeats one token 256 times in a row (#606)
A broken state (or a model in a loop) can answer one token forever: #606 streamed 36,689 tokens of "!" for four minutes, because a request without max_tokens gets the whole remaining context. The server now ends such a reply at 256 identical tokens in a row with finish "length" and a line in its window saying what to do if it repeats on a new request. "repeat_stop_tokens": N in strata-<model>.json sets the run (0 = off). Nothing changes for a reply without such a run.
This commit is contained in:
1 parent
2b726ba683
commit
bb162e2edf
3 files changed
+53
No files matched your search
@@ -473,6 +473,10 @@ print(r.choices[0].message.content)
|
||||
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.
|
||||
- **A reply stuck on one token is ended (0.1.39, #606).** When a reply repeats the same token 256 times in a row, the
|
||||
server ends it there with `finish_reason` `"length"` and says so in its window: a model in a loop, or a broken
|
||||
state 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).
|
||||
- **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-<model>.json` renders such a request without thinking - Anthropic's own rule, and what Claude Code's short
|
||||
|
||||
@@ -59,6 +59,10 @@ from serve.structured import StructuredOutputError, prepare_format, validated_js
|
||||
IM_END = "<|im_end|>"
|
||||
IMAGE_PAD = "<|image_pad|>"
|
||||
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"
|
||||
# sets it; 0 turns it off.
|
||||
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"
|
||||
LOOPBACK_NAMES = ("localhost", "127.0.0.1", "::1")
|
||||
@@ -1023,6 +1027,7 @@ class Service:
|
||||
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.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
|
||||
self.stop_ids = set(tokenizer.encode(IM_END, parse_special=True) +
|
||||
tokenizer.encode("<|endoftext|>", parse_special=True))
|
||||
@@ -1470,6 +1475,7 @@ class Service:
|
||||
sampling = {**defaults, **req_values}
|
||||
parser = OutputParser(thinking=thinking, tools=tools, stream_tools=True)
|
||||
detok, n, finish = Detokenizer(self.tok), 0, "length"
|
||||
run_tok, run_len, repeated = None, 0, False # #606: the current run of one repeated token
|
||||
timings, before = None, None # this request's timings; the engine's `last` before it
|
||||
raw_ids = [] # every generated id (STRATA_DEBUG: dump raw model text)
|
||||
emb = getattr(self.embeddings, "path", None)
|
||||
@@ -1519,6 +1525,11 @@ class Service:
|
||||
break
|
||||
raw_ids.append(t)
|
||||
seg.append(t)
|
||||
run_len = run_len + 1 if t == run_tok else 1
|
||||
run_tok = t
|
||||
if self.repeat_stop_tokens and run_len >= self.repeat_stop_tokens:
|
||||
repeated = True # #606: a degenerate output, not an answer: end it here
|
||||
break
|
||||
evs = parser.feed(detok.push(t))
|
||||
self._note(n, evs)
|
||||
last_print = self._progress(last_print)
|
||||
@@ -1572,6 +1583,11 @@ class Service:
|
||||
prompt = prompt + seg + extra
|
||||
if cancel.is_set():
|
||||
finish = "cancel"
|
||||
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 "
|
||||
"strata-<model>.json; 0 turns this off). If a new request with a short prompt does the "
|
||||
"same, restart the server and report it (#606)", flush=True)
|
||||
except GeneratorExit: # the client disconnected mid-stream
|
||||
finish = "disconnect"
|
||||
raise
|
||||
@@ -3015,6 +3031,10 @@ 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"
|
||||
rs = cfg.get("repeat_stop_tokens", REPEAT_STOP_TOKENS) # #606: opt-out with 0
|
||||
if isinstance(rs, bool) or not isinstance(rs, int) or rs < 0:
|
||||
raise SystemExit(f"[strata] config \"repeat_stop_tokens\" must be a whole number >= 0 (0 = off), not {rs!r}")
|
||||
svc.repeat_stop_tokens = rs
|
||||
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"]
|
||||
|
||||
@@ -848,6 +848,35 @@ class LearnedProfile(unittest.TestCase):
|
||||
self.assertEqual(engine_args(cfg), ["--native", "x", "--expert-profile-save", "learned.bin"])
|
||||
|
||||
|
||||
class RepeatStop(unittest.TestCase):
|
||||
"""#606: one token repeated repeat_stop_tokens times in a row ends the reply as "length"; 0 turns it off."""
|
||||
|
||||
def run_reply(self, script, limit=None):
|
||||
tok = ByteTokenizer()
|
||||
svc = Service(MockEngine(tok, script, max_context=CTX), tok, ChatTemplate(ROOT / "serve/chat_template.jinja"))
|
||||
if limit is not None:
|
||||
svc.repeat_stop_tokens = limit
|
||||
ids = tok.encode("hi")
|
||||
with contextlib.redirect_stdout(io.StringIO()) as out:
|
||||
done = [x for kind, x in svc.run(ids, False, None, 3000, {}, threading.Event()) if kind == "done"][0]
|
||||
return done, out.getvalue()
|
||||
|
||||
def test_a_long_run_is_ended(self):
|
||||
done, log = self.run_reply("ok " + "!" * 1000 + " never")
|
||||
self.assertEqual(done["finish"], "length")
|
||||
self.assertEqual(done["completion_tokens"], 3 + 256)
|
||||
self.assertIn("repeated one token ('!') 256 times", log)
|
||||
|
||||
def test_short_runs_and_off(self):
|
||||
done, _ = self.run_reply("=" * 255 + " fine")
|
||||
self.assertEqual(done["finish"], "stop")
|
||||
done, log = self.run_reply("!" * 1000, limit=0)
|
||||
self.assertEqual((done["finish"], done["completion_tokens"]), ("stop", 1001))
|
||||
self.assertNotIn("repeated one token", log)
|
||||
done, _ = self.run_reply("ab" * 400, limit=8) # alternating tokens are not one run
|
||||
self.assertEqual(done["finish"], "stop")
|
||||
|
||||
|
||||
class LayerSplit(unittest.TestCase):
|
||||
"""#644: "layer_split" is the first layer of each later GPU; a list is accepted, counts per card are not."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user