Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

Relaxed acceptance: fix thinking loops (exact window and rewind on an early loop signal, loop guard) (#177)

Yaniss Amazouz9f1b368576fd
diff --git a/doc/env_vars.md b/doc/env_vars.md
index 47f8397..938620a 100644
--- a/doc/env_vars.md
+++ b/doc/env_vars.md
@@ -1308,7 +1308,9 @@ The same lane also exports `EXL3_HOST_LEAN`, `EXL3_HOST_CUTS`, `EXL3_LOAD_DEVICE
| `QWSPEC_NGRAM` | `2,7,16,3` | The same copy lookup for the Qwen server, in the same format. `2,3,5` gives the earlier setting (a 5-token match, 3 copied tokens). `off` turns it off. |
| `QWSPEC_NGRAM_IDX` | `1` | Builds the lookup index when the request is queued, so its cost lands in the time to first token and not in the first decode round. `0` builds it lazily and also turns off the `cmin` check. |
| `EXL3_SPEC_SAMPLED` | engine `0`; the GLM server sets `1` | For requests with temperature above 0 and an MTP drafter: the drafter draws its tokens from its own distribution, and the verify keeps each one with probability min(1, p/q), or resamples from the remainder. The output has the same distribution as plain sampling. Greedy requests are untouched. `0` goes back to taking the drafter's top token. The Qwen server does not set it. |
-| `EXL3_SPEC_TYPICAL` | `0` | Relaxed ("typical") acceptance of argmax drafts for sampled requests (temperature above 0, MTP drafter): a draft is also kept when its probability under the sampling law (top-k / top-p cuts, then temperature) is at least min(eps, delta * exp(-H)), H being the entropy of that law; tokens cut by the filters are never kept. Greedy requests and `0` are unchanged bit for bit. `EXL3_SPEC_TYPICAL_EPS` (0.09) and `EXL3_SPEC_TYPICAL_DELTA` (0.3) tune it; `EXL3_SPEC_TYPICAL_FILE` (test only) switches it at run time. Real Hermes turns: Qwen 3.8 Flash-Next iGPU 55.1 to 58.8 tok/s, Qwen 3.8 27B RTX 3090 88.9 to 116.3 tok/s; GSM8K and HumanEval unchanged. |
+| `EXL3_SPEC_TYPICAL` | `0` | Relaxed ("typical") acceptance of argmax drafts for sampled requests (temperature above 0, MTP drafter): a draft is also kept when its probability under the sampling law (top-k / top-p cuts, then temperature) is at least min(eps, delta * exp(-H)), H being the entropy of that law; tokens cut by the filters are never kept. Greedy requests and `0` are unchanged bit for bit. `EXL3_SPEC_TYPICAL_EPS` (0.09) and `EXL3_SPEC_TYPICAL_DELTA` (0.3) tune it; `EXL3_SPEC_TYPICAL_HMAX` (unset = off): entropy gate in nats; a non-matching draft is relaxed only at rows where the entropy H of the sampling law is at most this value, on top of the threshold above (relaxation is then skipped at high-entropy choice points; the repetition check is unchanged). `EXL3_SPEC_TYPICAL_FILE` (test only) switches it at run time. `EXL3_SPEC_TYPICAL_LOOKUP` (`rep`): the relaxed rule applies to every draft source (model head, and copies of the prompt / tool outputs), except for a draft token that would complete an 8-token n-gram already seen at least twice in the job's last 512 generated tokens (`EXL3_SPEC_TYPICAL_REP_N`, `EXL3_SPEC_TYPICAL_REP_W`): that one is accepted by equality only, so a sampled job is not pulled around its own loop. `0`: copied drafts exact, relaxed for model-head drafts only; `1`: relaxed for every source with no check (old behaviour). Greedy requests are unchanged. Real Hermes turns: Qwen 3.8 Flash-Next iGPU 55.1 to 58.8 tok/s, Qwen 3.8 27B RTX 3090 88.9 to 116.3 tok/s; GSM8K and HumanEval unchanged. |
+| `EXL3_SPEC_TYPICAL_COOLDOWN` | `512` | Adaptive loop control for the relaxed acceptance of `EXL3_SPEC_TYPICAL` (tokens, `0` = off, read per round; sampled requests only). When a request shows an early loop signal, it accepts drafts by exact equality (no relaxed rule, model-head and copied drafts alike) for the next window of its own generated tokens, then relaxes again; a re-trigger while the window is open or within the next window doubles it (cap 16384), and signals less than 64 tokens apart count once. Signals: a draft refused by the repetition check above, and (Qwen server) a thinking-text line of at least 40 non-space characters, outside code fences, seen a second time in the last 16K characters. Nothing changes while no signal fires (greedy output and acceptance are byte-identical). Counters in `GET /health` under `spec_typical`: `cooldown_triggers`, `cooldown_tokens`. |
+| `EXL3_SPEC_TYPICAL_REWIND` | `3` | Rewinds per reply when the loop signal above fires inside an open think block (`0` = off, only the exact-acceptance window applies; read per round). The Qwen server cuts the reply back to just before the first copy of the repeated span (the first occurrence of the refused n-gram, or of the repeated line), drops those tokens, continues from there with a new sampling seed and the exact-acceptance window, and the client text is retracted. The kept thinking is replayed through the prompt cache. The dropped tokens still count against `max_tokens`. After the cap the loop guard closes the think block as before. Never applies to the answer or a tool call, to a request without a think block, or when the think state is unknown. Counters in `GET /health` under `spec_typical`: `rewinds`, `rewound_tokens`. |
| `EXL3_GLM_SLOTS` | `0` (one recurrent state slot per session) | Minimum number of recurrent state slots the GLM server allocates. The default sizes them to `--sessions`, which frees about 6 GiB of GPU memory at one session. `16` restores the earlier layout. |
| `EXL3_GC_FREEZE` | Qwen server `1`, GLM server `0` | Moves the loaded model and tokenizer objects out of the Python garbage collector before the first generator is built. Without it, rebuilding the generator (for example after a `cache_salt` change) pays a collector pass of about 0.5 s inside the time to first token. `0` leaves them in the collector. |
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index 3bfa90c..d72b5c2 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -2165,6 +2165,9 @@ class Generator:
pre = None
_hacc("t_samp_h", _hs)
typ = None
+ # EXL3_SPEC_TYPICAL_LOOKUP: arm "0" keeps copied drafts exact; default "rep" refuses the relaxed rule (rep_refused, below) for a draft that
+ # completes an n-gram the job already repeated in its own output. The probe still logs every draft.
+ typ_relax = draft_tokens is not None and spec_sample.relax_allowed(self, draft_tokens, j)
if draft_tokens is not None and spec is None and (spec_sample.typical_on() or spec_sample.PTAP) \
and npos > 1 and not self.dflash_draft:
_tp = spec_sample.eligible(job)
@@ -2185,7 +2188,8 @@ class Generator:
next_token, next_k_tokens, next_k_probs, next_prob = job.receive_logits(
token_logits,
)
- if typ is not None and spec_sample.typical_on() and i < npos - 1 and typ[0][2][i] and int(next_token.view(-1)[0]) != typ[1][i]:
+ if typ is not None and typ_relax and spec_sample.typical_on() and i < npos - 1 and typ[0][2][i] and int(next_token.view(-1)[0]) != typ[1][i] \
+ and not spec_sample.cd_armed(job) and not spec_sample.rep_refused(job, typ[1][i]):
next_token = torch.full_like(next_token, typ[1][i])
eos, sampled_token, rq = job.receive_sample(
token_logits,
diff --git a/exllamav3/generator/spec_sample.py b/exllamav3/generator/spec_sample.py
index c671eb7..4847052 100644
--- a/exllamav3/generator/spec_sample.py
+++ b/exllamav3/generator/spec_sample.py
@@ -132,9 +132,27 @@ def verify(logits: torch.Tensor, q: torch.Tensor, d: int, prm: tuple, rng) -> to
TYPICAL = os.environ.get("EXL3_SPEC_TYPICAL", "0") != "0"
TYP_EPS = float(os.environ.get("EXL3_SPEC_TYPICAL_EPS", "0.09"))
TYP_DELTA = float(os.environ.get("EXL3_SPEC_TYPICAL_DELTA", "0.3"))
+# EXL3_SPEC_TYPICAL_HMAX (nats, default unset = off): entropy gate. A non-matching draft is relaxed only at rows whose entropy H
+# is <= HMAX, in addition to the p >= min(eps, delta * exp(-H)) rule; above it the draft is kept by equality only.
+_hm = os.environ.get("EXL3_SPEC_TYPICAL_HMAX", "").strip()
+TYP_HMAX = float(_hm) if _hm else None
# Read-only probe: EXL3_SPEC_PTAP=<file.jsonl> appends one line per verify round (p_draft, entropy, match per row)
PTAP = os.environ.get("EXL3_SPEC_PTAP") or None
# Test switch for in-server A/B: EXL3_SPEC_TYPICAL_FILE=<path>, the rule is on while the file holds "1" (re-read when its mtime changes)
+# EXL3_SPEC_TYPICAL_LOOKUP, how the relaxed rule treats the draft sources:
+# "rep" (default): relaxed for model-head (MTP) drafts and for drafts copied from the prompt / tool outputs, except that a draft
+# token which would complete an n-gram (REP_N tokens) already seen >= 2 times in the job's last REP_W generated tokens is
+# accepted by equality only. Source-independent and keyed on the job's own output: a sampled job cannot be pulled around a
+# loop by relaxed drafts, a copy of the prompt stays relaxed.
+# "0": drafts copied from the context keep the exact rule, relaxed for model-head drafts only (measurement arm).
+# "1": relaxed rule for every draft source, no repetition check (the old behaviour; measurement arm).
+TYPICAL_LOOKUP = os.environ.get("EXL3_SPEC_TYPICAL_LOOKUP", "rep").strip().lower()
+if TYPICAL_LOOKUP not in ("rep", "0", "1"):
+ TYPICAL_LOOKUP = "rep"
+REP_N = int(os.environ.get("EXL3_SPEC_TYPICAL_REP_N", "12"))
+REP_W = int(os.environ.get("EXL3_SPEC_TYPICAL_REP_W", "2048"))
+REP_COUNT = 2
+REP_REFUSED = [0] # relaxed acceptances refused by the repetition check, whole process
_TFILE = os.environ.get("EXL3_SPEC_TYPICAL_FILE") or None
_tstate = [0.0, TYPICAL]
@@ -152,6 +170,158 @@ def typical_on() -> bool:
return _tstate[1]
+def draft_is_copy(gen, draft_tokens: torch.Tensor, row: int) -> bool:
+ """
+ True when row `row` of this round's draft was copied from the context, not produced by the model head. A drafter round returns a
+ slice of gen.draft_ids_pinned; every other draft (lookup, mixed rows) is a tensor of its own, copied by default. A policy that
+ mixes sources in one tensor says which rows are copies in gen.draft_copy_rows = (tensor, [bool per row]).
+ """
+ mark = getattr(gen, "draft_copy_rows", None)
+ if mark is not None and mark[0] is draft_tokens:
+ return bool(mark[1][row])
+ return draft_tokens.data_ptr() != gen.draft_ids_pinned.data_ptr()
+
+
+def relax_allowed(gen, draft_tokens: torch.Tensor, row: int) -> bool:
+ """Source gate: False only in arm "0" for a copied draft. The repetition check (rep_refused) is separate."""
+ return TYPICAL_LOOKUP != "0" or not draft_is_copy(gen, draft_tokens, row)
+
+
+# Adaptive loop control for the relaxed rule. A loop is cheap to stop early and expensive once its span is in the context, so a job that
+# shows an early loop signal accepts by exact equality (no relaxed rule, MTP and copied drafts alike) for a window of its own generated
+# tokens, then relaxes again. Signals: a refused REP_N-gram (rep_refused), and a thinking-text line of >= 40 non-space chars seen twice
+# (tools/loopguard.LineWatch, fed by the server). A re-trigger while the window is open, or within the next window, doubles it.
+# EXL3_SPEC_TYPICAL_COOLDOWN: first window in tokens (default 512, 0 = off, read per round); cap CD_MAX; one burst of signals counts once.
+# EXL3_SPEC_TYPICAL_REWIND: rewinds per reply (default 3, 0 = off, read per round); the server cuts the thinking back to just before the first
+# copy of the repeated span and continues from there (see Cooldown.rw_abs). The relaxed rule is never touched while no signal fires.
+CD_MAX = 16384
+CD_DEBOUNCE = 64
+STATS = {"cooldown_triggers": 0, "cooldown_tokens": 0, "rewinds": 0, "rewound_tokens": 0} # whole process, exposed by the server
+
+
+def _int_env(name: str, default: int) -> int:
+ try:
+ return max(0, int(os.environ.get(name, str(default)) or 0))
+ except ValueError:
+ return 0
+
+
+def cooldown_base() -> int:
+ return _int_env("EXL3_SPEC_TYPICAL_COOLDOWN", 512)
+
+
+def rewind_max() -> int:
+ return _int_env("EXL3_SPEC_TYPICAL_REWIND", 3)
+
+
+class Cooldown:
+ """Per-job window state. Positions are the job's own generated-token count (job.new_tokens)."""
+
+ def __init__(self, win: int = 0, end: int = 0):
+ self.win = win # current window (0 = never triggered)
+ self.end = end # exact acceptance while the job's generated count is below end
+ self.last = -1 # generated count at the last trigger
+ self.rw_abs = None # absolute sequence index where the first copy of the refused n-gram starts (the server consumes it)
+
+ def armed(self, n: int) -> bool:
+ return n < self.end
+
+ def trigger(self, n: int, base: int) -> bool:
+ """Early loop signal at generated count n. True when it counted (not a repeat of the same burst)."""
+ if self.last >= 0 and n - self.last < CD_DEBOUNCE:
+ return False
+ win = min(2 * self.win, CD_MAX) if self.win and n < self.end + self.win else base
+ self.win, self.end, self.last = win, n + win, n
+ STATS["cooldown_triggers"] += 1
+ STATS["cooldown_tokens"] += win
+ return True
+
+
+def cd_armed(job) -> bool:
+ """True while the job is inside an exact-acceptance window (flag on)."""
+ cd = getattr(job, "cd", None)
+ return cd is not None and cd.armed(job.new_tokens)
+
+
+class RepTracker:
+ """
+ Counts the REP_N-grams of one job's last REP_W generated tokens (a dict from n-gram to count, updated from the new tail of
+ the sequence on each call, so O(new tokens) per round and O(REP_N) per check).
+ """
+ def __init__(self):
+ self.toks = [] # generated tokens inside the window
+ self.end = 0 # absolute length of the sequence consumed so far
+ self.counts = {}
+
+ def _add(self, t):
+ self.toks.append(t)
+ if len(self.toks) >= REP_N:
+ k = tuple(self.toks[-REP_N:])
+ self.counts[k] = self.counts.get(k, 0) + 1
+ if len(self.toks) > REP_W: # evict the oldest token and the n-gram that started on it
+ k = tuple(self.toks[:REP_N])
+ c = self.counts.get(k, 0) - 1
+ if c > 0: self.counts[k] = c
+ else: self.counts.pop(k, None)
+ del self.toks[0]
+
+ def feed(self, seq, ngen: int):
+ """seq: the job's token sequence (len, torch_slice), ngen: how many trailing tokens were generated. Reads only the new tail."""
+ n = len(seq)
+ if self.end and self.end <= n and n - self.end <= REP_W:
+ lo = self.end
+ else: # first call, truncation or a long gap: rebuild from the generated tail
+ lo = max(n - min(max(ngen, 0), REP_W), 0)
+ self.toks, self.counts = [], {}
+ for t in (seq.torch_slice(lo, n).reshape(-1).tolist() if n > lo else []):
+ self._add(t)
+ self.end = n
+
+ def repeated(self, d: int) -> bool:
+ if len(self.toks) < REP_N - 1:
+ return False
+ return self.counts.get(tuple(self.toks[-(REP_N - 1):]) + (d,), 0) >= REP_COUNT
+
+ def first_repeat(self, d: int) -> int:
+ """Absolute sequence index of the start of the FIRST occurrence (inside the window) of the n-gram that d would complete; -1 if none."""
+ t = self.toks
+ if len(t) < REP_N - 1:
+ return -1
+ gram = t[-(REP_N - 1):] + [d]
+ k = len(gram)
+ for i in range(len(t) - k + 1):
+ if t[i] == gram[0] and t[i:i + k] == gram:
+ return self.end - len(t) + i
+ return -1
+
+
+def rep_refused(job, d: int) -> bool:
+ """
+ True when draft token d, appended to the job's generated output so far, would complete a REP_N-gram already seen
+ >= REP_COUNT times in its last REP_W generated tokens. Only meaningful in "rep" mode. Counts the refusal.
+ """
+ if TYPICAL_LOOKUP != "rep":
+ return False
+ tr = getattr(job, "_rep_tracker", None)
+ if tr is None:
+ tr = job._rep_tracker = RepTracker()
+ tr.feed(job.sequences[0].sequence_ids, job.new_tokens + getattr(job, "rep_extra", 0)) # rep_extra: kept thinking of a rewound reply
+ if tr.repeated(d):
+ REP_REFUSED[0] += 1
+ job.rep_refused = getattr(job, "rep_refused", 0) + 1
+ base = cooldown_base()
+ if base: # the refused n-gram is an early loop signal
+ cd = getattr(job, "cd", None)
+ if cd is None:
+ cd = job.cd = Cooldown()
+ if cd.trigger(job.new_tokens, base) and rewind_max() > 0:
+ at = tr.first_repeat(d)
+ if at >= 0:
+ cd.rw_abs = at if cd.rw_abs is None else min(cd.rw_abs, at)
+ return True
+ return False
+
+
def _topk_of(prm: tuple):
"""The top-K cut of the law (None = no cut): lets typical_rows work on K logits per row instead of the whole vocabulary."""
kind, x, vs = prm
@@ -164,7 +334,8 @@ def _topk_of(prm: tuple):
def typical_rows(rows: torch.Tensor, drafts: list, prm: tuple, eps: float, delta: float):
"""
rows: (n, V) verify logits of the n draft rows; drafts: the n drafted ids. Returns (p, H, ok) as python lists, one
- host sync: p = law probability of the draft, H = entropy of the law, ok = p > 0 and p >= min(eps, delta * exp(-H)).
+ host sync: p = law probability of the draft, H = entropy of the law, ok = p > 0 and p >= min(eps, delta * exp(-H))
+ and, when TYP_HMAX is set, H <= TYP_HMAX.
With a top-K cut in the law only the K best logits of each row are sorted and normalised (the law is zero elsewhere,
so p and H are those of the dense law).
"""
@@ -187,5 +358,7 @@ def typical_rows(rows: torch.Tensor, drafts: list, prm: tuple, eps: float, delta
p = torch.stack(ps)
h = torch.stack(hs)
ok = (p > 0) & (p >= torch.clamp(delta * torch.exp(-h), max = eps))
+ if TYP_HMAX is not None:
+ ok = ok & (h <= TYP_HMAX)
out = torch.stack([p, h, ok.float()]).tolist()
return out[0], out[1], [x > 0.5 for x in out[2]]
diff --git a/tools/loopguard.py b/tools/loopguard.py
index 8f5f084..84719a4 100644
--- a/tools/loopguard.py
+++ b/tools/loopguard.py
@@ -22,6 +22,88 @@ TEXT_WINDOW, TEXT_RATIO, TEXT_MIN_CHARS = 1000, 0.30, 200
SPAN_TAIL, SPAN_LEN, SPAN_MIN = 3000, 50, 3
+LINE_MIN, LINE_REPEAT = 40, 3 # long-period rule (thinking only): a line of >= 40 non-space characters seen 3 times, exact after strip
+
+
+class LineRepeat:
+ """Long-period loop in a thinking block: the period rules look at <= 64 tokens and the text rule at the last 1000 characters, so a
+ loop of 20 lines (~380 tokens) slips through them. Here every complete line of at least LINE_MIN non-space characters is counted
+ (exact after strip); the LINE_REPEAT-th sighting is a loop. Lines inside a ``` fence are not counted: code repeats its own lines.
+ feed(text, tok0) -> None, or (char offset, token index) of the START of the second sighting (keep the thinking up to there: one copy
+ of the loop) and the char offset where the third one ended."""
+
+ def __init__(self):
+ self.seen: dict[str, list] = {} # line -> [count, char offset of 2nd sighting, token index of 2nd sighting]
+ self.buf, self.buf_at, self.buf_tok, self.fence, self.n = "", 0, 0, False, 0
+
+ def feed(self, text: str, tok0: int = 0):
+ for piece in text.splitlines(keepends=True):
+ if not self.buf:
+ self.buf_at, self.buf_tok = self.n, tok0
+ self.buf += piece
+ self.n += len(piece)
+ if not piece.endswith("\n"):
+ continue
+ line, self.buf = self.buf.strip(), ""
+ if line.startswith("```"):
+ self.fence = not self.fence
+ continue
+ if self.fence or len(line.replace(" ", "").replace("\t", "")) < LINE_MIN:
+ continue
+ rec = self.seen.setdefault(line, [0, 0, 0])
+ rec[0] += 1
+ if rec[0] == 2:
+ rec[1], rec[2] = self.buf_at, self.buf_tok
+ elif rec[0] >= LINE_REPEAT:
+ return rec[1], rec[2], self.n
+ return None
+
+
+class LineWatch:
+ """Early loop signal (EXL3_SPEC_TYPICAL_COOLDOWN), a detector only: it never ends a reply. feed(text) is True when a long line (LineRepeat's
+ normalisation: stripped, >= LINE_MIN non-space chars, outside ``` fences) completes for the 2nd time within the last WINDOW chars; first_at
+ is then the char offset where the FIRST copy of that line starts (the rewind point)."""
+ WINDOW = 16384
+
+ def __init__(self):
+ self.chars = 0
+ self.line = ""
+ self.last: dict[str, int] = {} # stripped line -> char offset where its last copy ended
+ self.first: dict[str, int] = {} # stripped line -> char offset where the earliest copy of the current chain started
+ self.first_at: int | None = None
+ self.fence = False
+
+ def feed(self, text: str) -> bool:
+ if not text:
+ return False
+ parts = (self.line + text).split("\n")
+ pos = self.chars - len(self.line)
+ self.line = parts.pop()
+ self.chars += len(text)
+ hit = False
+ self.first_at = None
+ for p in parts:
+ beg = pos
+ pos += len(p) + 1
+ q = p.strip()
+ if q.startswith("```"):
+ self.fence = not self.fence
+ continue
+ if not self.fence and len("".join(q.split())) >= LINE_MIN:
+ if pos - self.last.get(q, -10 ** 9) <= self.WINDOW:
+ if not hit:
+ self.first_at = self.first.get(q, beg)
+ hit = True
+ else:
+ self.first[q] = beg
+ self.last[q] = pos
+ if len(self.last) > 512:
+ lim = self.chars - self.WINDOW
+ self.last = {k: v for k, v in self.last.items() if v >= lim}
+ self.first = {k: v for k, v in self.first.items() if k in self.last}
+ return hit
+
+
def loop_guard_default() -> bool:
return os.environ.get("EXL3_LOOP_GUARD", "1") != "0"
@@ -154,6 +236,7 @@ class LoopMonitor:
self.run = [0] * (GUARD_MAX_N + 1)
self.text = ""
self.last_check = 0
+ self.lines = LineRepeat() if phase == "think" else None
self.flag_from: int | None = None
self.counter_from: int | None = None
self._data_at, self._data = -GUARD_CHECK_EVERY, False # data_like() of the tail, refreshed every GUARD_CHECK_EVERY tokens
@@ -191,6 +274,10 @@ class LoopMonitor:
if r < DATA_SUSTAIN and self.phase == "answer" and self._data_tail(i):
continue # legit repetitive data: the period must hold for DATA_SUSTAIN tokens before it is a loop
return {"phase": self.phase, "kind": "period", "cut": max(i - r + 1, 1), "at": i + 1, "period": n}
+ if self.detect and self.lines is not None and text:
+ lh = self.lines.feed(text, len(ids) - len(tokens))
+ if lh:
+ return {"phase": "think", "kind": "line", "cut": max(lh[1], 1), "at": len(ids), "period": 0, "chars": lh[2]}
if self.detect and len(ids) - self.last_check >= GUARD_CHECK_EVERY:
prev, self.last_check = self.last_check, len(ids)
if (answer_text_loop if self.phase == "answer" else text_loop)(self.text[-(SPAN_TAIL + 200):]):
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 19749ee..066c2a4 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -502,7 +502,7 @@ class Heartbeat:
# The detectors live in tools/loopguard.py (shared with the GLM server).
from loopguard import (GUARD_ANSWER, loop_guard_default, GUARD_CHECK_EVERY, GUARD_MAX_N, GUARD_THINK, SPAN_LEN, SPAN_MIN, SPAN_TAIL, # noqa: E402,F401
- TEXT_MIN_CHARS, TEXT_RATIO, TEXT_WINDOW, LoopMonitor, answer_text_loop, counter_drift,
+ LineWatch, TEXT_MIN_CHARS, TEXT_RATIO, TEXT_WINDOW, LoopMonitor, answer_text_loop, counter_drift,
max_span_repeat, repeated_units, shingle_repeat, text_loop)
THINK_CLOSE_TEXT = "\n</think>\n\n"
@@ -533,6 +533,15 @@ def final_cut(vis: str) -> int | None:
return None
+def _spec_sample():
+ """exllamav3.generator.spec_sample, None when the library is not importable (model-free tests)."""
+ try:
+ from exllamav3.generator import spec_sample
+ return spec_sample
+ except Exception:
+ return None
+
+
class Retract(int):
"""Yielded by QwenEngine.generate after a loop-guard restart: drop this many trailing characters of the text
streamed so far (the discarded part of the thinking). A streaming client has already received them."""
@@ -1336,21 +1345,36 @@ class QwenEngine:
generated = 0 # tokens the model produced, including the discarded thinking tail
discount = 0 # discarded tokens of final-check recoveries: not charged to max_tokens
final_tries = 0
+ open_eos = False
+ open_tried = False # the EOS-inside-an-open-think recovery runs once
final_on = guard_on and reasoning_first and close_id is not None and loop_final is not False
vis = "" # the text the client holds (Retract applied)
gmarks: list[tuple[int, int]] = [(0, 0)] # (len(token_ids), chars) after each event, all segments
job_ids = ids
+ ss = _spec_sample()
+ greedy = sampling.get("temperature") == 0 or sampling.get("top_k") == 1
+ think_open = bool(reasoning_first and close_id is not None) # the generation is inside an open think block
+ rewinds = 0 # EXL3_SPEC_TYPICAL_REWIND: thinking cut back to before a repeated span, this reply
+ carry_win = 0 # cooldown window the next job starts with (after a rewind)
+ lw = None # tools.loopguard.LineWatch over the thinking text, created per reply when the cooldown is on
while True:
max_new = max(max_tokens - generated + discount, 1)
rq = serve_compat.rq_budget(ctx, self.sessions, int(job_ids.numel()), max_new, int(getattr(self.generator, "num_draft_tokens", 0)), PAGE_TOKENS)
job = self.Job(input_ids=job_ids, max_new_tokens=max_new,
sampler=self._sampler(sampling), stop_conditions=([] if ignore_eos else self.eos) + list(stop),
- embeddings=embs or None, decode_special_tokens=True, seed=seed,
+ embeddings=embs or None, decode_special_tokens=True,
+ seed=seed if not rewinds or seed is None else seed + 1000003 * rewinds, # a rewound reply must not redraw the same tokens
**({} if rq is None else {"max_rq_tokens": rq}),
**({} if logprobs is None else {"return_probs": True, "return_top_tokens": logprobs}))
if disk_on and generated == 0 and not discount:
job._restore_ids = ids # see _pre_start
+ cd_base = ss.cooldown_base() if ss is not None and ss.typical_on() and not greedy else 0 # read per segment
+ if carry_win: # after a rewind: exact acceptance for the window, the kept thinking counts as the job's own output
+ job.cd = ss.Cooldown(win=carry_win, end=carry_win)
+ job.cd.last = 0 # same debounce as a trigger at the cut
+ job.rep_extra = len(token_ids)
+ carry_win = 0
_mine.append(job)
q = await self._submit(job)
seg: list[int] = []
@@ -1359,6 +1383,7 @@ class QwenEngine:
seg_t0 = time.perf_counter()
hit = None
redo = False
+ rw_cut = None
while True:
if cancel is not None and cancel.is_set():
return # generate() drops the job
@@ -1390,6 +1415,42 @@ class QwenEngine:
hit = mon.feed(toks, ev.get("text") or "")
if hit:
break
+ if cd_base and think_open and not ev.get("eos"):
+ # EXL3_SPEC_TYPICAL_COOLDOWN / _REWIND: an early loop signal switches this job to exact acceptance for a window and,
+ # inside the thinking, cuts the reply back to just before the first copy of the repeated span (at most REWIND times)
+ cut = None
+ cap = ss.rewind_max() > rewinds and not embs
+ if ev.get("text"):
+ if lw is None:
+ lw = LineWatch()
+ if lw.feed(ev["text"]):
+ cd = getattr(job, "cd", None)
+ if cd is None:
+ cd = job.cd = ss.Cooldown()
+ if cd.trigger(len(seg), cd_base) and cap and lw.first_at is not None:
+ cut = max(m[0] for m in gmarks if m[1] <= lw.first_at)
+ cd = getattr(job, "cd", None)
+ if cd is not None and cd.rw_abs is not None:
+ at = cd.rw_abs - int(ids.numel()) # the generator's own signal: absolute sequence index -> index in token_ids
+ if at < len(token_ids) or not cap:
+ cd.rw_abs = None
+ if cap and at >= 1:
+ c2 = max(m[0] for m in gmarks if m[0] <= at)
+ cut = c2 if cut is None else min(cut, c2)
+ if cut is not None and cut >= 1 and cut < len(token_ids) and close_id not in token_ids[cut:]:
+ rw_cut = cut
+ break
+ if close_id is not None and close_id in toks:
+ think_open = False
+ if ev.get("eos") and final_on and not open_tried and ev.get("eos_reason") == "stop_token" \
+ and THINK_CLOSE_TAG not in vis and generated - discount < max_tokens:
+ # EOS inside a think block that never closed: the client would get reasoning only and an empty answer.
+ # Keep the thinking (cut by final_cut when it loops), force the close and let the model answer, once.
+ open_tried = True
+ open_eos = True
+ final_c = (final_cut(vis) if text_loop(gate_text(vis)) else None) or len(vis)
+ redo = True
+ break
if ev.get("eos") and final_on and final_tries < FINAL_TRIES and text_loop(gate_text(vis)) \
and (THINK_CLOSE_TAG in vis or ev.get("eos_reason") == "max_new_tokens"
or generated - discount >= max_tokens) \
@@ -1406,23 +1467,51 @@ class QwenEngine:
if stop_lp is not None: # the sampled stop token: no content, but its position is scored
stats["logprobs"] = lps + [stop_lp]
stats["logprob_token_ids"] = token_ids + [int(ev["eos_triggering_token_id"])]
- if fired:
+ if fired or rewinds:
stats.update(prompt_tokens=int(ids.numel()), new_tokens=generated,
cached_tokens=min(int(stats.get("cached_tokens", 0)), int(ids.numel())),
- loop_guard=fired)
+ **({"loop_guard": fired} if fired else {}), **({"spec_rewinds": rewinds} if rewinds else {}))
if stats.get("time_generate") is not None:
stats["time_generate"] += spent
return
- if hit or redo:
+ if hit or redo or rw_cut is not None:
break
+ if rw_cut is not None:
+ await self._drop(job)
+ keep_tokens, keep_chars = max(m for m in gmarks if m[0] <= rw_cut)
+ n_drop = len(token_ids) - keep_tokens
+ rewinds += 1
+ ss.STATS["rewinds"] += 1
+ ss.STATS["rewound_tokens"] += n_drop
+ print(f"qserve: spec_typical rewind {rewinds}/{ss.rewind_max()}: {n_drop} tokens dropped, thinking kept to {keep_tokens} tokens", file=sys.stderr, flush=True)
+ carry_win = max(getattr(getattr(job, "cd", None), "win", 0), cd_base)
+ spent += time.perf_counter() - seg_t0
+ if len(vis) > keep_chars:
+ yield Retract(len(vis) - keep_chars)
+ vis, chars = vis[:keep_chars], keep_chars
+ del token_ids[keep_tokens:]
+ del lps[keep_tokens:]
+ gmarks[:] = [m for m in gmarks if m[0] <= keep_tokens and m[1] <= keep_chars]
+ lw = LineWatch()
+ lw.feed(vis) # the watch restarts on the kept prefix
+ if mon is not None: # ... and so does the loop monitor
+ mon.start_phase("think")
+ mon.feed(token_ids, vis)
+ extra = self.torch.tensor([token_ids], dtype=ids.dtype)
+ job_ids = self.torch.cat([ids, extra.to(ids.device)], dim=-1)
+ continue
if redo:
self._routes.pop(job.serial_number, None) # it sent its eos
cut_chars = final_c
- final_tries += 1
keep_tokens, keep_chars = max(m for m in gmarks if m[1] <= cut_chars)
- fired = {"phase": "think", "kind": "final", "cut": keep_tokens, "at": len(token_ids), "period": 0,
+ kind = "open_think" if open_eos else "final"
+ if not open_eos:
+ final_tries += 1
+ fired = {"phase": "think", "kind": kind, "cut": keep_tokens, "at": len(token_ids), "period": 0,
"tokens_streamed": len(token_ids), "kept_tokens": keep_tokens, "tries": final_tries}
- print(f"qserve: loop guard final in think: gate rule holds on the answer, thinking cut to {keep_tokens} tokens "
+ open_eos = False
+ print(f"qserve: loop guard {kind} in think: " + ("EOS before </think>, close forced" if kind == "open_think" else
+ "gate rule holds on the answer") + f", thinking kept to {keep_tokens} tokens "
f"({keep_chars} chars of {len(vis)}), try {final_tries}", file=sys.stderr, flush=True)
spent += time.perf_counter() - seg_t0
yield Retract(len(vis) - keep_chars)
@@ -1430,6 +1519,7 @@ class QwenEngine:
discount += len(token_ids) - keep_tokens
del token_ids[keep_tokens:]
token_ids += close_seq
+ think_open = False
del lps[keep_tokens:]
lps += [None] * len(close_seq)
generated += len(close_seq)
@@ -1465,6 +1555,7 @@ class QwenEngine:
vis = vis[:chars]
del token_ids[len(token_ids) - len(seg) + keep_tokens:]
token_ids += close_seq
+ think_open = False
del lps[len(token_ids) - len(close_seq):]
lps += [None] * len(close_seq)
generated += len(close_seq)
@@ -1504,7 +1595,11 @@ class QwenEngine:
return [(math.log(max(pl[i], 1e-45)), [(a, math.log(max(b, 1e-45))) for a, b in zip(il[i], tl[i])]) for i in range(n)]
def spec_stats(self) -> dict[str, Any]:
- return {"speculative": self.spec_on, "draft_policy": self.draft_policy if self.spec_on else "off", "ndt": self.ndt}
+ out = {"speculative": self.spec_on, "draft_policy": self.draft_policy if self.spec_on else "off", "ndt": self.ndt}
+ ss = _spec_sample()
+ if ss is not None: # relaxed-acceptance loop control, whole process
+ out["spec_typical"] = {**ss.STATS, "rep_refused": ss.REP_REFUSED[0]}
+ return out
# ---------------------------------------------------------------------------- HTTP
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index 7fa31bc..01216c7 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -824,7 +824,8 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule
ra_note(gj, srcs, lens, W)
if stats is not None:
stats["ngm"] = stats.get("ngm", 0) + 1; stats["rows"] = stats.get("rows", 0) + N * (W + 1)
- return torch.tensor(out, dtype=torch.long)
+ t = torch.tensor(out, dtype=torch.long); g.draft_copy_rows = (t, [bool(c) for c in conts]) # rows from the lookup are copies (spec_sample.draft_is_copy)
+ return t
def multi_conts(gj):
"""The lookup continuation of each decoding request (None = no match), same rule as the single-request round."""
for k in [k for k in mf if k not in gj]: del mf[k]
@@ -866,7 +867,8 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule
out.append(t + [t[-1] if t else 0] * (W - len(t)))
if stats is not None:
stats["ngm"] = stats.get("ngm", 0) + 1; stats["rows"] = stats.get("rows", 0) + N * (W + 1)
- return torch.tensor(out, dtype=torch.long)
+ t = torch.tensor(out, dtype=torch.long); g.draft_copy_rows = (t, [bool(c) for c in conts])
+ return t
def wrapped(results):
st.update(i=0, stop=False, keep=None, mode="mtp", ps=[])
ra_gj = None
diff --git a/tools/qwen/test_guard.py b/tools/qwen/test_guard.py
index 9baea56..0897c4d 100644
--- a/tools/qwen/test_guard.py
+++ b/tools/qwen/test_guard.py
@@ -79,6 +79,7 @@ def make_engine(model, per_iter=3):
e = object.__new__(serve.QwenEngine)
e.torch, e.Job, e.generator = torch, StubJob, StubGenerator(model, per_iter)
e.tokenizer, e.eos, e.draft_model, e.spec_on, e.slot_store, e.last_stats = StubTok(), [0], None, False, None, {}
+ e.sessions = 1
e._encode = lambda prompt, urls: (torch.tensor([[100, 101, 102]]), [])
e._sampler = lambda s: None
StubJob.jobs = []
@@ -268,6 +269,83 @@ class GuardEngineTests(unittest.TestCase):
self.assertTrue(re.search(r"seed: int = None", src) and "random.Random(seed)" in src)
+
+class LongPeriodTests(unittest.TestCase):
+ """Long-period rule: a thinking line of >= 40 non-space characters seen 3 times (exact after strip)."""
+ LINE = "Let me check the second constraint against the board once more."
+
+ def feed(self, text, phase="think", step=7):
+ import loopguard
+ mon = loopguard.LoopMonitor(phase, None)
+ for i in range(0, len(text), step):
+ hit = mon.feed([i // step + 1000], text[i:i + step])
+ if hit:
+ return hit, i + step
+ return None, len(text)
+
+ def test_third_sighting_in_think_fires(self):
+ body = "".join(f"Step {i} reasons about case number {i * 17} in detail.\n" for i in range(5))
+ text = body + (self.LINE + "\n" + "".join(f" fresh thought {i} about something new here. \n" for i in range(3))) * 3
+ hit, at = self.feed(text)
+ self.assertEqual(hit["kind"], "line")
+ self.assertEqual(hit["phase"], "think")
+ self.assertLess(hit["chars"], len(text) + 1)
+
+ def test_two_sightings_short_lines_and_answers_do_not_fire(self):
+ two = (self.LINE + "\nsomething else entirely, different words here ok.\n") * 2
+ self.assertIsNone(self.feed(two)[0])
+ short = "x = compute(a, b)\n" * 20
+ self.assertIsNone(self.feed(short)[0])
+ self.assertIsNone(self.feed((self.LINE + "\n") * 5, phase="answer")[0])
+
+ def test_fenced_code_in_think_is_not_counted(self):
+ code = "```python\n" + " result = compute_something(first_argument, second_argument)\n" * 4 + "```\n"
+ self.assertIsNone(self.feed(code)[0])
+
+ def test_real_traces(self):
+ d = os.environ.get("LOOPGUARD_TRACES") # a directory of looping traces (loop_think.txt) and valid answers (ok_*.md)
+ if not d or not Path(d).is_dir():
+ self.skipTest("LOOPGUARD_TRACES not set")
+ loop = Path(d) / "loop_think.txt"
+ if loop.exists():
+ hit, _ = self.feed(loop.read_text(), step=4)
+ self.assertEqual(hit["kind"], "line")
+ for f in sorted(Path(d).glob("ok_*.md")):
+ self.assertIsNone(self.feed(f.read_text(), step=4)[0], f.name)
+ self.assertIsNone(self.feed(f.read_text(), phase="answer", step=4)[0], f.name)
+
+
+class OpenThinkEosTests(unittest.TestCase):
+ def test_eos_before_close_forces_close_and_answers_once(self):
+ def m(ctx, job):
+ gen = ctx[3:]
+ if CLOSE in gen:
+ return answer_after_close(ctx)
+ return 200 + len(gen) if len(gen) < 40 else 0 # the model stops inside the think block
+ text, st = collect(make_engine(m), reasoning_first=True, loop_guard=True)
+ self.assertIn("</think>", text)
+ self.assertIn("<w1000>", text) # the answer follows the forced close
+ self.assertEqual(st["loop_guard"]["kind"], "open_think")
+ self.assertEqual(st["eos_reason"], "stop_token")
+
+ def test_second_eos_in_think_is_not_retried(self):
+ calls = []
+ def m(ctx, job):
+ calls.append(1)
+ return 200 + len(ctx[3:]) if len(ctx[3:]) < 40 else 0
+ text, st = collect(make_engine(m), reasoning_first=True, loop_guard=True)
+ self.assertLess(len(calls), 200)
+ self.assertEqual(st["eos_reason"], "stop_token")
+
+ def test_guard_off_or_no_think_unchanged(self):
+ def m(ctx, job):
+ return 200 + len(ctx[3:]) if len(ctx[3:]) < 40 else 0
+ for kw in ({"reasoning_first": True, "loop_guard": False}, {"reasoning_first": False, "loop_guard": True}):
+ text, st = collect(make_engine(m), **kw)
+ self.assertNotIn("</think>", text)
+ self.assertNotIn("loop_guard", st)
+
+
class MultiStubGenerator(StubGenerator):
"""StubGenerator with several jobs at once: each iterate() steps every job, like a batched decode."""
diff --git a/tools/qwen/test_spec_rewind.py b/tools/qwen/test_spec_rewind.py
new file mode 100644
index 0000000..80e40bf
--- /dev/null
+++ b/tools/qwen/test_spec_rewind.py
@@ -0,0 +1,181 @@
+#!/usr/bin/env python3
+"""EXL3_SPEC_TYPICAL_COOLDOWN / EXL3_SPEC_TYPICAL_REWIND at the server: model-free tests (stub generator, no GPU). python tools/qwen/test_spec_rewind.py
+A looping thinking block is rewound to just before the first copy of the repeated line (at most 3 times a reply), the new job starts in an
+exact-acceptance window, the answer channel is never rewound, and with the flags off or no signal the reply is the guard-only reply."""
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import unittest
+from pathlib import Path
+
+import torch
+
+sys.path.insert(0, str(Path(__file__).parent))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "evalgate"))
+import serve
+import test_guard as TG
+from test_guard import CLOSE, StubJob, StubGenerator, make_engine
+from exllamav3.generator import spec_sample as ss
+
+UNIQUE, PERIOD, APERIOD = 30, 70, 5 # a loop of 70 tokens: its 2nd sighting lies past the 64-token debounce of the restart
+
+
+def text_of(t):
+ """One line per token (>= 40 non-space chars, distinct per id); the close tag is not a line."""
+ if t == CLOSE:
+ return "</think>"
+ return f"reasoning step number {t} written out in full so that the line is long\n"
+
+
+class LineGenerator(StubGenerator):
+ def iterate(self):
+ evs = super().iterate()
+ for ev in evs:
+ ev["text"] = "".join(text_of(t) for t in ev["token_ids"].tolist())
+ return evs
+
+
+def make(model, per_iter=3):
+ e = make_engine(model, per_iter)
+ e.generator = LineGenerator(model, per_iter)
+ return e
+
+
+def loop_in_think(ctx, job):
+ gen = ctx[3:]
+ if CLOSE in gen:
+ return TG.answer_after_close(ctx)
+ return 200 + len(gen) if len(gen) < UNIQUE else 500 + (len(gen) - UNIQUE) % PERIOD
+
+
+def loop_in_answer(ctx, job):
+ gen = ctx[3:]
+ if CLOSE not in gen:
+ return 200 + len(gen) if len(gen) < 20 else CLOSE
+ a = len(gen) - gen.index(CLOSE) - 1
+ return 700 + a % APERIOD if a >= 3 else 600 + a
+
+
+def run(engine, temperature=0.7, **kw):
+ async def go():
+ out = ""
+ async for piece in engine.generate("p", sampling={"temperature": temperature}, stop=[], **{"max_tokens": 600, "reasoning_first": True} | kw):
+ out = out[:len(out) - int(piece)] if isinstance(piece, serve.Retract) else out + piece
+ return out
+ return asyncio.run(go()), engine.last_stats
+
+
+class RewindTests(unittest.TestCase):
+ def setUp(self):
+ self.old = (ss.TYPICAL, dict(ss.STATS))
+ ss.TYPICAL = True
+ for k in ("EXL3_SPEC_TYPICAL_COOLDOWN", "EXL3_SPEC_TYPICAL_REWIND"):
+ os.environ.pop(k, None)
+ self.n0 = dict(ss.STATS)
+
+ def tearDown(self):
+ ss.TYPICAL = self.old[0]
+ for k in ("EXL3_SPEC_TYPICAL_COOLDOWN", "EXL3_SPEC_TYPICAL_REWIND"):
+ os.environ.pop(k, None)
+
+ def d(self, k):
+ return ss.STATS[k] - self.n0[k]
+
+ def test_thinking_loop_rewinds_to_before_first_copy_then_cap_then_hard_guard(self):
+ text, st = run(make(loop_in_think), seed=1234)
+ self.assertEqual(self.d("rewinds"), 3) # the cap
+ jobs = StubJob.jobs
+ first = jobs[1].ids[3:] # the kept thinking of the first rewound job
+ self.assertEqual(first, [200 + i for i in range(UNIQUE)]) # cut just before the first copy of the repeated line
+ self.assertGreater(self.d("rewound_tokens"), 0)
+ self.assertGreaterEqual(self.d("cooldown_triggers"), 3) # one per rewind, then the window re-triggers (doubles) before the hard guard
+ for j in jobs[1:4]:
+ self.assertIsNotNone(getattr(j, "cd", None)) # exact-acceptance window carried to the new job
+ self.assertTrue(j.cd.armed(0)); self.assertGreaterEqual(j.cd.win, 512)
+ self.assertEqual([j.seed for j in jobs[:4]], [1234 + 1000003 * k for k in range(4)]) # the sampling key moves on at every rewind
+ self.assertIn("loop_guard", st) # after the cap the hard guard closes the think block
+ self.assertEqual(st["spec_rewinds"], 3)
+ self.assertIn("</think>", text)
+
+ def test_rewound_reply_does_not_double_the_text(self):
+ text, _ = run(make(loop_in_think), max_tokens=600)
+ for k in range(200, 200 + UNIQUE):
+ self.assertEqual(text.count(f"number {k} "), 1)
+
+ def test_rewind_off_cooldown_only(self):
+ os.environ["EXL3_SPEC_TYPICAL_REWIND"] = "0"
+ text, st = run(make(loop_in_think))
+ self.assertEqual(self.d("rewinds"), 0)
+ self.assertEqual(self.d("cooldown_triggers"), 2) # the signal still arms the window; a re-trigger (64+ tokens later) doubles it
+ self.assertEqual(StubJob.jobs[0].cd.win, 1024)
+ self.assertEqual(len(StubJob.jobs), 2) # only the hard guard's restart
+ self.assertNotIn("spec_rewinds", st)
+
+ def test_cooldown_off_nothing_fires(self):
+ os.environ["EXL3_SPEC_TYPICAL_COOLDOWN"] = "0"
+ run(make(loop_in_think))
+ self.assertEqual((self.d("rewinds"), self.d("cooldown_triggers")), (0, 0))
+
+ def test_relaxed_rule_off_or_greedy_nothing_fires(self):
+ ss.TYPICAL = False
+ run(make(loop_in_think))
+ self.assertEqual((self.d("rewinds"), self.d("cooldown_triggers")), (0, 0))
+ ss.TYPICAL = True
+ run(make(loop_in_think), temperature=0)
+ self.assertEqual((self.d("rewinds"), self.d("cooldown_triggers")), (0, 0))
+
+ def test_answer_channel_never_rewound(self):
+ text, st = run(make(loop_in_answer))
+ self.assertEqual(self.d("rewinds"), 0)
+ self.assertEqual(self.d("cooldown_triggers"), 0)
+ self.assertEqual(len(StubJob.jobs), 1) # no restart before the hard guard (answer) ends the reply
+ self.assertEqual(st.get("eos_reason"), "loop_guard")
+
+ def test_no_think_block_never_rewound(self):
+ run(make(loop_in_think), reasoning_first=False)
+ self.assertEqual(self.d("rewinds"), 0)
+
+ def test_no_signal_identical_to_flags_off(self):
+ a = run(make(TG.normal_model))
+ os.environ["EXL3_SPEC_TYPICAL_COOLDOWN"] = "0"; os.environ["EXL3_SPEC_TYPICAL_REWIND"] = "0"
+ b = run(make(TG.normal_model))
+ self.assertEqual(a[0], b[0]); self.assertEqual(a[1]["token_ids"], b[1]["token_ids"])
+ self.assertEqual((self.d("rewinds"), self.d("cooldown_triggers")), (0, 0))
+ self.assertNotIn("spec_rewinds", a[1])
+
+ def test_fenced_repeat_does_not_trigger(self): # a legit repeated code line inside a fence
+ w = serve.LineWatch()
+ line = " result = compute_the_value(alpha, beta, gamma, delta)\n"
+ self.assertFalse(w.feed("```python\n" + line + line + line + "```\n"))
+
+
+class LineWatchTests(unittest.TestCase):
+ def test_second_sighting_hits_and_marks_first_copy(self):
+ w = serve.LineWatch()
+ a = "this is a rather long reasoning line with enough characters\n"
+ b = "another distinct and rather long reasoning line of text here\n"
+ self.assertFalse(w.feed(a + b))
+ self.assertTrue(w.feed(a))
+ self.assertEqual(w.first_at, 0)
+ w2 = serve.LineWatch()
+ w2.feed("short\n" + b + a)
+ self.assertTrue(w2.feed(b))
+ self.assertEqual(w2.first_at, len("short\n"))
+
+ def test_short_line_and_fence_ignored(self):
+ w = serve.LineWatch()
+ self.assertFalse(w.feed("too short\ntoo short\ntoo short\n"))
+ line = " result = compute_the_value(alpha, beta, gamma, delta)\n"
+ self.assertFalse(w.feed("```\n" + line * 3 + "```\n"))
+
+ def test_split_across_feeds(self):
+ w = serve.LineWatch()
+ a = "this is a rather long reasoning line with enough characters\n"
+ w.feed(a[:20]); w.feed(a[20:])
+ self.assertTrue(w.feed(a[:30]) or w.feed(a[30:]))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/qwen/test_spec_typical.py b/tools/qwen/test_spec_typical.py
index e390279..8dd304a 100644
--- a/tools/qwen/test_spec_typical.py
+++ b/tools/qwen/test_spec_typical.py
@@ -87,5 +87,265 @@ class TypicalRule(unittest.TestCase):
self.assertIsNone(ss.eligible(J()))
+class EntropyGate(unittest.TestCase):
+ """EXL3_SPEC_TYPICAL_HMAX: relaxation only at rows with H <= HMAX."""
+ P = [0.5, 0.3, 0.2] + [0.0] * (V - 3)
+ H = -sum(x * math.log(x) for x in P if x > 0)
+
+ def setUp(self): self.old = ss.TYP_HMAX
+ def tearDown(self): ss.TYP_HMAX = self.old
+
+ def run_rule(self):
+ return ss.typical_rows(row_from_probs(self.P), [2], PRM_FULL, 0.09, 0.3)
+
+ def test_default_off(self):
+ self.assertIsNone(self.old)
+ ss.TYP_HMAX = None
+ pp, hh, ok = self.run_rule()
+ self.assertTrue(ok[0])
+
+ def test_above_hmax_never_relaxed(self):
+ ss.TYP_HMAX = self.H - 0.01
+ pp, hh, ok = self.run_rule()
+ self.assertGreater(pp[0], 0.09) # high p, still refused
+ self.assertFalse(ok[0])
+
+ def test_below_hmax_as_before(self):
+ ss.TYP_HMAX = self.H + 0.01
+ self.assertTrue(self.run_rule()[2][0])
+ # a draft under the threshold stays refused
+ pp, hh, ok = ss.typical_rows(row_from_probs(self.P), [2], PRM_FULL, 1.0, 1.0)
+ self.assertFalse(ok[0])
+
+ def test_greedy_not_eligible(self):
+ class J:
+ filters = []; forced_ids = None; return_probs = False; return_top_tokens = False; device_logit_mask = None; sequences = [1]
+ sampler = CustomSampler([SS_Argmax()])
+ class generator:
+ class tokenizer: actual_vocab_size = V
+ ss.TYP_HMAX = 0.1
+ self.assertIsNone(ss.eligible(J()))
+
+
+class CopiedDrafts(unittest.TestCase):
+ """EXL3_SPEC_TYPICAL_LOOKUP: copied drafts keep the exact rule; model-head drafts stay relaxed."""
+ class Gen:
+ draft_ids_pinned = torch.zeros(2, 4, dtype=torch.long)
+
+ def setUp(self):
+ self.old = ss.TYPICAL_LOOKUP
+
+ def tearDown(self):
+ ss.TYPICAL_LOOKUP = self.old
+
+ def test_default_is_exact_for_copies(self):
+ self.assertEqual(ss.TYPICAL_LOOKUP, "rep")
+
+ def test_model_head_vs_copy(self):
+ g = self.Gen()
+ mtp = g.draft_ids_pinned[:, :3] # drafter round: slice of the pinned buffer
+ copy = torch.tensor([[1, 2, 3]]) # lookup round: tensor of its own
+ for flag, want_copy in (("0", False), ("1", True), ("rep", True)):
+ ss.TYPICAL_LOOKUP = flag
+ self.assertTrue(ss.relax_allowed(g, mtp, 0)) # MTP unchanged in both modes
+ self.assertEqual(ss.relax_allowed(g, copy, 0), want_copy)
+
+ def test_mixed_rows_marked(self):
+ g = self.Gen()
+ t = torch.tensor([[1, 2], [3, 4]])
+ g.draft_copy_rows = (t, [True, False])
+ ss.TYPICAL_LOOKUP = "0"
+ self.assertFalse(ss.relax_allowed(g, t, 0))
+ self.assertTrue(ss.relax_allowed(g, t, 1))
+ g.draft_copy_rows = (torch.tensor([[9]]), [False, False]) # stale mark for another tensor: ignored
+ self.assertFalse(ss.relax_allowed(g, t, 1))
+
+ def test_copy_never_relaxed_end_to_end(self):
+ # the generator keeps a relaxed draft only when relax_allowed; a draft that rule 1 would keep (ok) is dropped at 0
+ p = [0.5, 0.3, 0.2] + [0.0] * (V - 3)
+ _, _, ok = ss.typical_rows(row_from_probs(p), [2], PRM_FULL, 0.09, 0.3)
+ self.assertTrue(ok[0])
+ g = self.Gen(); copy = torch.tensor([[2]])
+ ss.TYPICAL_LOOKUP = "0"
+ self.assertFalse(ok[0] and ss.relax_allowed(g, copy, 0))
+ ss.TYPICAL_LOOKUP = "1"
+ self.assertTrue(ok[0] and ss.relax_allowed(g, copy, 0))
+
+ def test_greedy_unchanged(self):
+ # greedy jobs are never eligible, so neither rule is reached whatever the flag
+ class J:
+ filters = []; forced_ids = None; return_probs = False; return_top_tokens = False; device_logit_mask = None; sequences = [1]
+ sampler = CustomSampler([SS_Argmax()])
+ class generator:
+ class tokenizer: actual_vocab_size = V
+ for flag in ("0", "1", "rep"):
+ ss.TYPICAL_LOOKUP = flag
+ self.assertIsNone(ss.eligible(J()))
+
+
+class FakeSeq:
+ def __init__(self, ids): self.ids = list(ids)
+ def __len__(self): return len(self.ids)
+ def torch_slice(self, a, b): return torch.tensor([self.ids[a:b]], dtype=torch.long) # (1, n), like the real SeqTensor
+
+
+class FakeJob:
+ def __init__(self, prompt, gen=()):
+ self.seq = FakeSeq(list(prompt) + list(gen)); self.new_tokens = len(gen)
+ class S: pass
+ s = S(); s.sequence_ids = self.seq; self.sequences = [s]
+ def emit(self, t): self.seq.ids.append(t); self.new_tokens += 1
+
+
+class RepetitionAware(unittest.TestCase):
+ """Default "rep": the relaxed rule is refused for a draft that completes an n-gram the job already repeated >= 2 times."""
+ def setUp(self):
+ self.old = (ss.TYPICAL_LOOKUP, ss.REP_N, ss.REP_W); ss.TYPICAL_LOOKUP = "rep"; ss.REP_N = 8; ss.REP_W = 512
+ self.n0 = ss.REP_REFUSED[0]
+
+ def tearDown(self):
+ ss.TYPICAL_LOOKUP, ss.REP_N, ss.REP_W = self.old
+
+ def test_prompt_copy_stays_relaxed(self):
+ prompt = list(range(100, 160))
+ gen = [5, 6, 7, 8, 9, 10, 11, 12] # output so far; the draft continues a span that exists only in the prompt
+ j = FakeJob(prompt, gen)
+ self.assertFalse(ss.rep_refused(j, 13))
+ self.assertEqual(ss.REP_REFUSED[0], self.n0)
+
+ def test_own_output_repeat_refused(self):
+ loop = list(range(200, 220)) # a 20-token span emitted twice, third copy starts
+ j = FakeJob([1, 2, 3], loop + loop + loop[:10])
+ self.assertTrue(ss.rep_refused(j, loop[10])) # would continue the third copy of a span seen twice
+ self.assertFalse(ss.rep_refused(j, 999)) # a different token is not a repeat
+ self.assertEqual(ss.REP_REFUSED[0], self.n0 + 1)
+ self.assertEqual(j.rep_refused, 1)
+
+ def test_seen_once_not_refused(self):
+ loop = list(range(200, 220))
+ j = FakeJob([1], loop + loop[:10]) # the span seen only once so far
+ self.assertFalse(ss.rep_refused(j, loop[10]))
+
+ def test_incremental_and_equality(self):
+ loop = list(range(200, 220))
+ j = FakeJob([1], loop + loop[:3])
+ self.assertFalse(ss.rep_refused(j, loop[3]))
+ for t in loop[3:] + loop + loop[:10]: j.emit(t) # tracker catches up from the new tail
+ self.assertTrue(ss.rep_refused(j, loop[10]))
+ # equality still accepts: the generator only replaces the sampled token by a draft when not refused, so a refused draft
+ # reaches acceptance only if the target sampled the same token (nothing in rep_refused touches that path)
+
+ def test_window_evicts(self):
+ ss.REP_W = 40
+ loop = list(range(200, 220))
+ j = FakeJob([1], loop + loop + list(range(300, 360)) + loop[:10]) # the repeats left the window
+ self.assertFalse(ss.rep_refused(j, loop[10]))
+
+ def test_other_arms_never_refuse(self):
+ loop = list(range(200, 220))
+ j = FakeJob([1], loop + loop + loop[:10])
+ for arm in ("0", "1"):
+ ss.TYPICAL_LOOKUP = arm
+ self.assertFalse(ss.rep_refused(j, loop[10]))
+
+ def test_mtp_source_checked_too(self):
+ # the check is keyed on the output only: relax_allowed (source gate) is True for a model-head draft, rep_refused still applies
+ class G: draft_ids_pinned = torch.zeros(1, 4, dtype=torch.long)
+ g = G(); mtp = g.draft_ids_pinned[:, :2]
+ loop = list(range(200, 220)); j = FakeJob([1], loop + loop + loop[:10])
+ self.assertTrue(ss.relax_allowed(g, mtp, 0))
+ self.assertTrue(ss.rep_refused(j, loop[10]))
+
+
+class CooldownRule(unittest.TestCase):
+ """EXL3_SPEC_TYPICAL_COOLDOWN: exact acceptance for a window after an early loop signal, doubling on re-trigger, capped."""
+ def setUp(self):
+ self.old = (ss.TYPICAL_LOOKUP, ss.REP_N, ss.REP_W, dict(ss.STATS))
+ ss.TYPICAL_LOOKUP = "rep"; ss.REP_N = 8; ss.REP_W = 512
+ for k in ("EXL3_SPEC_TYPICAL_COOLDOWN", "EXL3_SPEC_TYPICAL_REWIND"):
+ os.environ.pop(k, None)
+
+ def tearDown(self):
+ ss.TYPICAL_LOOKUP, ss.REP_N, ss.REP_W = self.old[:3]
+ ss.STATS.update(self.old[3])
+ for k in ("EXL3_SPEC_TYPICAL_COOLDOWN", "EXL3_SPEC_TYPICAL_REWIND"):
+ os.environ.pop(k, None)
+
+ def test_defaults_and_off(self):
+ self.assertEqual((ss.cooldown_base(), ss.rewind_max()), (512, 3))
+ os.environ["EXL3_SPEC_TYPICAL_COOLDOWN"] = "0"; os.environ["EXL3_SPEC_TYPICAL_REWIND"] = "0"
+ self.assertEqual((ss.cooldown_base(), ss.rewind_max()), (0, 0))
+ os.environ["EXL3_SPEC_TYPICAL_COOLDOWN"] = "junk"
+ self.assertEqual(ss.cooldown_base(), 0)
+
+ def test_window_exact_length_then_relaxed(self):
+ cd = ss.Cooldown()
+ self.assertFalse(cd.armed(0))
+ self.assertTrue(cd.trigger(100, 2048))
+ self.assertTrue(cd.armed(100)); self.assertTrue(cd.armed(100 + 2047)); self.assertFalse(cd.armed(100 + 2048))
+
+ def test_doubling_cap_and_debounce(self):
+ cd = ss.Cooldown(); t0 = ss.STATS["cooldown_triggers"]
+ self.assertTrue(cd.trigger(100, 2048))
+ self.assertFalse(cd.trigger(150, 2048)) # same burst (< 64 tokens): counted once
+ self.assertEqual(cd.win, 2048)
+ self.assertTrue(cd.trigger(200, 2048)); self.assertEqual(cd.win, 4096) # re-trigger while armed doubles
+ self.assertTrue(cd.trigger(200 + 4096 + 100, 2048)); self.assertEqual(cd.win, 8192) # ... or within the next window
+ self.assertTrue(cd.trigger(cd.end + 10, 2048)); self.assertEqual(cd.win, 16384)
+ self.assertTrue(cd.trigger(cd.end + 10, 2048)); self.assertEqual(cd.win, 16384) # cap
+ self.assertTrue(cd.trigger(cd.end + 3 * 16384, 2048)); self.assertEqual(cd.win, 2048) # long quiet: back to the base window
+ self.assertEqual(ss.STATS["cooldown_triggers"], t0 + 6)
+
+ def test_cd_armed_follows_job_count(self):
+ j = FakeJob([1], list(range(10)))
+ self.assertFalse(ss.cd_armed(j)) # no signal: no state, the relaxed path is untouched
+ j.cd = ss.Cooldown(); j.cd.trigger(j.new_tokens, 5)
+ self.assertTrue(ss.cd_armed(j))
+ for t in range(5): j.emit(t)
+ self.assertFalse(ss.cd_armed(j))
+
+ def test_rep_refusal_arms_job_and_marks_first_copy(self):
+ loop = list(range(200, 220))
+ j = FakeJob([1, 2, 3], loop + loop + loop[:10])
+ self.assertTrue(ss.rep_refused(j, loop[10]))
+ self.assertTrue(ss.cd_armed(j))
+ self.assertEqual(j.cd.win, 512)
+ self.assertEqual(j.cd.rw_abs, 6) # start of the first copy of the refused 8-gram: 3 prompt tokens + offset 3
+ self.assertEqual(ss.STATS["cooldown_triggers"] - self.old[3]["cooldown_triggers"], 1)
+
+ def test_rep_refusal_rewind_off_no_mark_cooldown_off_no_state(self):
+ loop = list(range(200, 220))
+ os.environ["EXL3_SPEC_TYPICAL_REWIND"] = "0"
+ j = FakeJob([1], loop + loop + loop[:10])
+ self.assertTrue(ss.rep_refused(j, loop[10])); self.assertIsNone(j.cd.rw_abs); self.assertTrue(ss.cd_armed(j))
+ os.environ["EXL3_SPEC_TYPICAL_COOLDOWN"] = "0"
+ j = FakeJob([1], loop + loop + loop[:10])
+ self.assertTrue(ss.rep_refused(j, loop[10])); self.assertFalse(hasattr(j, "cd")); self.assertFalse(ss.cd_armed(j))
+
+ def test_no_signal_leaves_job_untouched(self):
+ j = FakeJob([1], list(range(300, 340)))
+ self.assertFalse(ss.rep_refused(j, 5))
+ self.assertFalse(hasattr(j, "cd")); self.assertFalse(ss.cd_armed(j))
+ self.assertEqual(ss.STATS, self.old[3])
+
+ def test_rep_extra_sees_the_kept_thinking(self):
+ # a rewound reply restarts with its kept thinking in the prompt: rep_extra lets the tracker still see the first copy
+ loop = list(range(200, 220))
+ kept = loop + loop[:2]
+ j = FakeJob([1, 2, 3] + kept, loop[2:10] * 0) # no tokens generated yet by the new job
+ j.rep_extra = len(kept)
+ for t in loop[2:] + loop[:10]: j.emit(t) # the loop comes round again
+ self.assertTrue(ss.rep_refused(j, loop[10]))
+ self.assertEqual(j.cd.rw_abs, 6)
+
+ def test_first_repeat_picks_earliest_copy(self):
+ tr = ss.RepTracker()
+ loop = list(range(200, 220))
+ seq = FakeSeq([9, 9] + loop + loop + loop[:10])
+ tr.feed(seq, len(seq))
+ self.assertEqual(tr.first_repeat(loop[10]), 5) # 2 leading ids + offset 3
+ self.assertEqual(tr.first_repeat(999), -1)
+
+
if __name__ == "__main__":
unittest.main()