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.

Qwen n-gram lookup: copy only what the two latest occurrences of the match agree on

YanissAmz2ab6161817c8
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index 3442ed7..fd1fa7d 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -52,6 +52,7 @@ class NgramIndex:
self.prev = [None] + [array("i", [-1]) if m >= nmin else None for m in range(1, lmax + 1)]
self.latest = [None] + [{} if m >= nmin else None for m in range(1, lmax + 1)]
self.fallbacks = 0
+ self._hit = None
def __len__(self):
return len(self.toks)
@@ -134,6 +135,7 @@ class NgramIndex:
def match(self, K):
"""Same value as ngram_match(ctx, nmin, K) on ctx = the indexed tokens."""
toks = self.toks; n = len(toks); nmin = self.nmin
+ self._hit = None
if n < nmin + 1: return (0, [])
prev = self.prev
for m in range(self.lmax, nmin - 1, -1):
@@ -151,8 +153,20 @@ class NgramIndex:
if not ok:
self.fallbacks += 1
return ngram_match(toks.tolist(), nmin, K)
+ self._hit = (j, m)
return (L, toks[j:j + K].tolist())
+ def witness_len(self, cont):
+ """After match(): how many leading tokens of its continuation the PREVIOUS occurrence of the matched gram also
+ continues with. len(cont) when there is no previous occurrence (a single witness cannot be checked)."""
+ if self._hit is None: return len(cont)
+ j, m = self._hit; toks = self.toks
+ j2 = self.prev[m][j]
+ if j2 < m or toks[j2 - m:j2] != toks[j - m:j]: return len(cont)
+ a = 0
+ while a < len(cont) and toks[j2 + a] == cont[a]: a += 1
+ return a
+
def sync_array(self, ids):
"""Make the index equal to ids (numpy int array): keep the longest common prefix, roll back, add the rest."""
have = np.frombuffer(self.toks, dtype=np.int32)
@@ -313,19 +327,24 @@ def env_defaults(ndt):
"""(thf, thv, maxd) for install(): today's 0.6 / 0.3 / ndt unless QWSPEC_THF / QWSPEC_THV / QWSPEC_MAXD are set."""
return _envf("QWSPEC_THF", 0.6), _envf("QWSPEC_THV", 0.3), _envf("QWSPEC_MAXD", int(ndt))
-def ngram_from_env(default=(2, 7, 16)):
- """n-gram lookup setting for install(): (gram, K, match) from QWSPEC_NGRAM = "gram,K,match"; "off" = no lookup (None).
- Default (2, 7, 16): the lookup replaces the drafter only on a match of 16 tokens or more and then drafts 7 tokens.
+def ngram_from_env(default=(2, 7, 16, 3)):
+ """n-gram lookup setting for install(): (gram, K, match[, cmin]) from QWSPEC_NGRAM = "gram,K,match[,cmin]"; "off" = no
+ lookup (None). cmin: see install(); 0 or absent = no second-occurrence check.
+ Default (2, 7, 16, 3): the lookup replaces the drafter only on a match of 16 tokens or more and then drafts 7 tokens.
The former (2, 3, 5) dates from the time the drafter stopped at 3 drafts. With the deep tier the drafter keeps 4-5 drafts
on JSON and code where a 5-token match (keys, punctuation, idioms) copies the wrong values: lookup rounds accepted
1.7 of 3 drafts there against 5.1 of 5.5 for drafter rounds, and on a plain copy 3 drafts per round is less than the
- drafter gives alone. QWSPEC_NGRAM=2,3,5 restores the former setting."""
+ drafter gives alone. QWSPEC_NGRAM=2,3,5 restores the former setting.
+ cmin 3: on templated lists (SQL rows, log lines, table rows) a 16-token match is the constant part of a row and the
+ 7 copied tokens ran into the value that changes (0 to 3.9 of 7 accepted, 3-6 % slower than no lookup); cut at the point
+ where the two latest rows differ, the lookup is level with "off" there and keeps its gain on copies and edits."""
v = (os.environ.get("QWSPEC_NGRAM") or "").strip().lower()
if v == "": return default
if v in ("off", "0", "none"): return None
- g, k, m = (int(x) for x in v.split(","))
- if not (1 <= g <= LMAX and k >= 1 and m >= g): raise ValueError(f"QWSPEC_NGRAM={v}")
- return (g, k, m)
+ f = [int(x) for x in v.split(",")]
+ g, k, m = f[:3]
+ if not (3 <= len(f) <= 4 and 1 <= g <= LMAX and k >= 1 and m >= g and min(f) >= 0): raise ValueError(f"QWSPEC_NGRAM={v}")
+ return tuple(f)
def rule_from_env(thf, thv, maxd):
"""QWSPEC_RULE = tier (default) | product (the former 0.6/0.3/3 rule when maxd=3) | tier (default thresholds below depth 4, stricter 5+ row tier: QWSPEC_THFD/THVD/DSPLIT) | cost | online | table (depth from the request's acceptance history, no probabilities); QWSPEC_GAMMA / QWSPEC_SCALE tune the calibrated reach.
@@ -350,7 +369,10 @@ def apply_rule(rule, ps):
return keep
def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule=None, fixed=None, log=None, log_depth=7):
- """ngram = (nmin, K, lmin) or None. Returns an uninstall function.
+ """ngram = (nmin, K, lmin) or (nmin, K, lmin, cmin) or None. Returns an uninstall function.
+ cmin > 0: when the matched gram has a previous occurrence too, only the tokens that BOTH occurrences continue with are
+ copied (a templated list repeats its constant part and changes its values: the copy stops where the two rows differ),
+ and the lookup is taken only if at least cmin tokens are left, else the round is a drafter round.
rule: a depth rule (default ProductRule(thf, thv, maxd) = the shipped rule).
fixed = N: no host read per depth; N depths are drafted, the max probabilities stay on the device and one read per
round feeds the rule, which then truncates (rows kept <= N + 1).
@@ -433,7 +455,13 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, rule
if ref != (L, c):
if stats is not None: stats["shadow_bad"] = stats.get("shadow_bad", 0) + 1
raise RuntimeError(f"ngram index mismatch at n={n}: old {ref} new {(L, c)}")
- if L >= ngram[2] and c: cont = c
+ if L >= ngram[2] and c:
+ cont = c
+ if len(ngram) > 3 and ngram[3] > 0 and os.environ.get("QWSPEC_NGRAM_IDX", "1") != "0":
+ a = fol.idx.witness_len(c)
+ if a < len(c):
+ cont = c[:a] if a >= ngram[3] else None
+ if stats is not None: stats["ng_cut" if cont else "ng_skip"] = stats.get("ng_cut" if cont else "ng_skip", 0) + 1
if cont is not None:
st["mode"] = "ng"; g.num_draft_tokens = 1
try: out = orig_draft(results)
diff --git a/tools/qwen/test_spec_rule.py b/tools/qwen/test_spec_rule.py
index 1037113..d39046e 100644
--- a/tools/qwen/test_spec_rule.py
+++ b/tools/qwen/test_spec_rule.py
@@ -7,6 +7,7 @@ import os, sys, random, unittest
os.environ.setdefault("HIP_VISIBLE_DEVICES", ""); os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import torch
+import numpy as np
import spec_policy as sp
def ref_keep(ps, thf=0.6, thv=0.3, maxd=3):
@@ -138,16 +139,47 @@ class T(unittest.TestCase):
def test_ngram_from_env(self):
os.environ.pop("QWSPEC_NGRAM", None)
- self.assertEqual(sp.ngram_from_env(), (2, 7, 16))
+ self.assertEqual(sp.ngram_from_env(), (2, 7, 16, 3))
for v, want in (("2,3,5", (2, 3, 5)), ("off", None), ("0", None), (" 3, 7, 16 ", (3, 7, 16))):
os.environ["QWSPEC_NGRAM"] = v
try: self.assertEqual(sp.ngram_from_env(), want)
finally: del os.environ["QWSPEC_NGRAM"]
- for v in ("2,7", "17,7,32", "2,0,5", "4,7,3"):
+ for v in ("2,7", "17,7,32", "2,0,5", "4,7,3", "2,7,16,3,1", "2,7,16,-1"):
os.environ["QWSPEC_NGRAM"] = v
try:
with self.assertRaises(ValueError): sp.ngram_from_env()
finally: del os.environ["QWSPEC_NGRAM"]
+ for v, want in (("2,7,16,3", (2, 7, 16, 3)), ("2,7,16,0", (2, 7, 16, 0))):
+ os.environ["QWSPEC_NGRAM"] = v
+ try: self.assertEqual(sp.ngram_from_env(), want)
+ finally: del os.environ["QWSPEC_NGRAM"]
+
+ def test_witness_len(self):
+ # a templated list: the constant part is copied, the copy stops at the value that changes from row to row
+ row = lambda v: list(range(100, 120)) + [v, v + 1] + [7, 8, 9]
+ idx = sp.NgramIndex(2)
+ for t in row(1000) + row(2000) + list(range(100, 118)): idx.push(t)
+ L, c = idx.match(7)
+ self.assertEqual((L >= 16, c), (True, [118, 119, 2000, 2001, 7, 8, 9]))
+ self.assertEqual(idx.witness_len(c), 2)
+ # one earlier occurrence only: nothing to compare with, the whole continuation stands
+ idx = sp.NgramIndex(2)
+ for t in row(1000) + list(range(100, 118)): idx.push(t)
+ L, c = idx.match(7)
+ self.assertEqual(idx.witness_len(c), len(c))
+ # against a direct scan on random streams with many repeats
+ import random
+ rng = random.Random(5)
+ for _ in range(300):
+ n = rng.randint(20, 400); per = [rng.randrange(4) for _ in range(rng.randint(3, 40))]
+ ctx = [per[i % len(per)] if rng.random() > 0.03 else rng.randrange(4) for i in range(n)]
+ idx = sp.NgramIndex(2); idx.extend(np.array(ctx))
+ L, c = idx.match(7)
+ if not L or idx._hit is None: continue
+ j, m = idx._hit
+ j2 = next((e for e in range(j - 1, m - 1, -1) if ctx[e - m:e] == ctx[j - m:j]), -1)
+ want = len(c) if j2 < 0 else next((a for a in range(len(c)) if ctx[j2 + a] != c[a]), len(c))
+ self.assertEqual(idx.witness_len(c), want)
def test_online_scale(self):
r = sp.OnlineRule(0.5, 0.3, 6)