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 server: optional drafter-free n-gram lookup (QWSPEC_PLAIN_LOOKUP, off by default)

YanissAmzc1830123385f
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 6eda111..990cfcd 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -754,7 +754,9 @@ class QwenEngine:
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
torch.set_grad_enabled(False)
self.torch, self.Generator, self.Job = torch, Generator, Job
- ndt = max(ndt, int(os.environ.get("QWSPEC_MAXD") or 0), int(os.environ.get("QWSPEC_FIXD") or 0)) # buffers fit the deepest draft
+ import spec_policy # tools/qwen/spec_policy.py
+ pl = spec_policy.plain_lookup_from_env(row_budget if sessions > 1 else 0) # drafter-free lookup (plain rounds): its K needs the same history depth
+ ndt = max(ndt, int(os.environ.get("QWSPEC_MAXD") or 0), int(os.environ.get("QWSPEC_FIXD") or 0), pl[1] if pl else 0) # buffers fit the deepest draft
self.model_path, self.ctx, self.ndt, self.draft_policy = model_path, ctx, ndt, draft_policy
self.sessions = sessions
self.config = Config.from_directory(model_path)
@@ -841,11 +843,16 @@ class QwenEngine:
self.torch.cuda.empty_cache()
spec = spec and self.draft_model is not None
kw = dict(model=self.model, cache=self.cache, tokenizer=self.tokenizer)
+ import spec_policy # tools/qwen/spec_policy.py: dynamic length + n-gram lookup, the shipped rule
+ pl = None if spec else spec_policy.plain_lookup_from_env(self.row_budget)
if spec:
kw.update(draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=self.ndt)
+ elif pl:
+ kw.update(ngram_match_min=pl[0], num_draft_tokens=pl[1])
self.generator = self.Generator(**kw)
+ if pl:
+ self.uninstall = spec_policy.install_plain_lookup(self.generator, pl)
if spec and self.draft_policy == "mix":
- import spec_policy # tools/qwen/spec_policy.py: dynamic length + n-gram lookup, the shipped rule
thf, thv, maxd = spec_policy.env_defaults(self.ndt) # 0.6 / 0.3 / ndt unless QWSPEC_THF / THV / MAXD are set
fx = os.environ.get("QWSPEC_FIXD")
self.uninstall = spec_policy.install(self.generator, self.draft_model, self.model,
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index 538f120..fdbfad7 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -423,6 +423,79 @@ def install_lookup(g, ngram, stats=None):
if g.__dict__.get("enqueue") is enq: g.__dict__.pop("enqueue")
return uninstall
+def plain_lookup_from_env(rows_default=0):
+ """Drafter-free n-gram lookup for a Generator WITHOUT a drafter (rtx1 14/10, rule "S2"): QWSPEC_PLAIN_LOOKUP = "lmin,K[,cmin[,rows]]"
+ (unset / off = none). Returns (lmin, K, cmin, rows) or None. Measured on the 3090 (EXL3, greedy, 18 prompts x 2, text = plain up
+ to near-ties): lmin 2, cmin 1, K = rows the backend verifies for ~free - 1 (15 for EXL3 dense on Ampere, 7 for a MoE pack
+ whose MoE kernels change cost above 8 rows): dense x1.46 overall / x2.9 on edits, MoE x1.26 / x2.0, ahead of the upstream
+ SAM defaults (x1.30 / x1.21). lmin 16 (ngram_from_env) is the right cut only when a drafter competes for the round.
+ Optional 4th field rows (default rows_default = 0 = one active request only): with B >= 2 requests decoding together each one
+ drafts, capped at rows // B - 1 tokens, and short drafts are padded to the longest (rtx1 sim19 / prof19: the batch keeps the
+ longest copy instead of the shortest). rows = the backend's ~free verify rows (16 for EXL3 dense on Ampere). serve.py passes
+ the served row_budget as rows_default so the plain-lookup cap matches the drafter-path row budget; an explicit 4th field wins.
+ """
+ v = (os.environ.get("QWSPEC_PLAIN_LOOKUP") or "").strip().lower()
+ if v in ("", "off", "0", "none"): return None
+ f = [int(x) for x in v.split(",")]
+ if not (2 <= len(f) <= 4 and f[0] >= 1 and f[1] >= 1 and min(f) >= 0): raise ValueError(f"QWSPEC_PLAIN_LOOKUP={v}")
+ return (f[0], f[1], f[2] if len(f) > 2 else 1, f[3] if len(f) > 3 else rows_default)
+
+def install_plain_lookup(g, pl, stats=None):
+ """Answers the Generator's n-gram slot (Generator(ngram_match_min > 0) -> iterate_ngram_gen) with the NgramIndex: the
+ longest earlier suffix match (>= lmin tokens) proposes its continuation, capped at K and cut to the prefix that the
+ previous occurrence of the same gram also continues with (>= cmin tokens, 0 = no cut); no match = a plain round.
+ rows = 0: one active request only (batched rounds decode plain). rows > 0: every prefill-done request drafts, capped at
+ rows // B - 1 for B requests, and short drafts are padded to the longest with the request's last token (filler the
+ verification rejects, or accepts only where it IS the target's choice), so one request without a match no longer turns
+ the lookup off for the batch (the generator's own slot trims to the shortest draft). Greedy verification: changes speed,
+ not the accepted text. The cache needs max_history >= K. Returns an uninstall function."""
+ lmin, K, cmin = pl[:3]; rows = pl[3] if len(pl) > 3 else 0
+ fol = SeqFollower(2); fols = {}
+ orig_enqueue = g.enqueue
+ def enq(job):
+ r = orig_enqueue(job)
+ for j in (job if isinstance(job, list) else [job]):
+ if len(getattr(j, "sequences", ())) == 1: (fols.setdefault(id(j), SeqFollower(2)) if rows else fol).sync(j.sequences[0].sequence_ids)
+ return r
+ def draft(f, sid, k):
+ idx = f.sync(sid)
+ L, c = idx.match(k)
+ if L < lmin or not c: return []
+ if cmin:
+ w = idx.witness_len(c)
+ if w < len(c):
+ if w < cmin: return []
+ c = c[:w]
+ return c
+ def rnd(results):
+ job = g.active_jobs[0] if len(g.active_jobs) == 1 else None
+ if job is None or not job.is_prefill_done() or len(job.sequences) != 1: return None
+ c = draft(fol, job.sequences[0].sequence_ids, K)
+ if not c: return None
+ if stats is not None: stats["ng"] = stats.get("ng", 0) + 1; stats["ng_tokens"] = stats.get("ng_tokens", 0) + len(c)
+ return torch.tensor([c], dtype=torch.long)
+ def rnd_rows(results):
+ jobs = [j for j in g.active_jobs if j.is_prefill_done()] # the generator's verify order (iterate_ngram_gen)
+ if not jobs or any(len(j.sequences) != 1 for j in jobs): return None
+ k = min(K, rows // len(jobs) - 1)
+ if k < 1: return None
+ live = {id(j) for j in g.active_jobs}
+ for d in [d for d in fols if d not in live]: del fols[d]
+ fs = [fols.setdefault(id(j), SeqFollower(2)) for j in jobs]
+ cs = [draft(f, j.sequences[0].sequence_ids, k) for f, j in zip(fs, jobs)]
+ w = max(len(c) for c in cs)
+ if not w: return None
+ if stats is not None:
+ stats["ng"] = stats.get("ng", 0) + 1; stats["ng_tokens"] = stats.get("ng_tokens", 0) + sum(len(c) for c in cs)
+ stats["ng_pad"] = stats.get("ng_pad", 0) + sum(w - len(c) for c in cs)
+ return torch.tensor([c + [f.idx.toks[-1]] * (w - len(c)) for c, f in zip(cs, fs)], dtype=torch.long)
+ g.enqueue = enq
+ g.iterate_ngram_gen = rnd_rows if rows else rnd
+ def uninstall():
+ g.__dict__.pop("iterate_ngram_gen", None)
+ if g.__dict__.get("enqueue") is enq: g.__dict__.pop("enqueue")
+ return uninstall
+
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.
QWSPEC_FIXD = N: draft N depths with no host read and truncate once per round (rule applied on the stacked probabilities)."""
diff --git a/tools/qwen/test_spec_rule.py b/tools/qwen/test_spec_rule.py
index 0e0dce9..9dba5bc 100644
--- a/tools/qwen/test_spec_rule.py
+++ b/tools/qwen/test_spec_rule.py
@@ -190,6 +190,71 @@ class T(unittest.TestCase):
self.assertEqual((fols[0].sid is g.job.sequences[0].sequence_ids, len(fols[0].idx)), (True, 42))
self.assertEqual(g.iterate_draftmodel_mtp_gen([]).tolist(), [[118, 119, 1000]])
+ def test_plain_lookup_from_env(self):
+ # QWSPEC_PLAIN_LOOKUP = "lmin,K[,cmin[,rows]]"; unset / off / 0 / none -> None; rows defaults to the row_budget argument
+ os.environ.pop("QWSPEC_PLAIN_LOOKUP", None)
+ self.assertIsNone(sp.plain_lookup_from_env())
+ for v in ("off", "0", "none", "OFF", " None "):
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = v
+ try: self.assertIsNone(sp.plain_lookup_from_env())
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+ for v, want in (("2,15", (2, 15, 1, 0)), ("2,15,3", (2, 15, 3, 0)), (" 2 , 15 , 1 , 16 ", (2, 15, 1, 16))):
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = v
+ try: self.assertEqual(sp.plain_lookup_from_env(), want)
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = "2,15" # 2 fields: rows = the default (row_budget)
+ try: self.assertEqual(sp.plain_lookup_from_env(16), (2, 15, 1, 16))
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = "2,15,3" # 3 fields: rows = the default
+ try: self.assertEqual(sp.plain_lookup_from_env(16), (2, 15, 3, 16))
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = "2,15,1,4" # explicit 4th field wins over the default
+ try: self.assertEqual(sp.plain_lookup_from_env(16), (2, 15, 1, 4))
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+ for v in ("2", "2,15,1,4,9", "0,15", "2,0", "2,15,-1", "x,15"):
+ os.environ["QWSPEC_PLAIN_LOOKUP"] = v
+ try:
+ with self.assertRaises(ValueError): sp.plain_lookup_from_env()
+ finally: del os.environ["QWSPEC_PLAIN_LOOKUP"]
+
+ def test_install_plain_lookup(self):
+ # drafter-free lookup: answers iterate_ngram_gen. A match returns its continuation (K cap, cmin cut) as ONE draft per
+ # round and needs NO drafter forward; no match = a plain round (no draft); uninstall restores the generator's slot.
+ from exllamav3.util.tensor import SeqTensor
+ row = lambda v: list(range(100, 120)) + [v] + [7, 8, 9]
+
+ class PJob:
+ def __init__(s, ids):
+ sid = SeqTensor((1, 1), torch.long, -1, init_cap=256)
+ sid.append(torch.tensor([ids], dtype=torch.long))
+ s.sequences = [type("S", (), {"sequence_ids": sid})()]
+ def is_prefill_done(s): return True
+
+ class PGen:
+ def __init__(s):
+ s.active_jobs = []; s.forwards = 0
+ def enqueue(s, j): s.active_jobs.append(j)
+ def iterate_ngram_gen(s, results): s.forwards += 1; return None # the generator's own slot
+
+ def gen(ids):
+ g = PGen(); st = {}; un = sp.install_plain_lookup(g, (2, 7, 1, 0), st); g.enqueue(PJob(ids)); return g, st, un
+ # one earlier occurrence: the whole continuation (K = 7), one draft row, no drafter forward
+ g1, st1, un = gen(row(1000) + list(range(100, 118)))
+ out = g1.iterate_ngram_gen([])
+ self.assertEqual((out.tolist(), out.shape[-1], g1.forwards, st1),
+ ([[118, 119, 1000, 7, 8, 9, 100]], 7, 0, {"ng": 1, "ng_tokens": 7}))
+ # the two latest occurrences agree on only 2 tokens: cmin 1 cuts the draft to the common prefix
+ g2, _, _ = gen(row(1000) + row(2000) + list(range(100, 118)))
+ self.assertEqual(g2.iterate_ngram_gen([]).tolist(), [[118, 119]])
+ # no match: no draft, and the generator's own slot was never used
+ g3, _, _ = gen(list(range(40)))
+ self.assertIsNone(g3.iterate_ngram_gen([])); self.assertEqual(g3.forwards, 0)
+ self.assertIn("iterate_ngram_gen", g1.__dict__) # the lookup answers the slot
+ un()
+ self.assertNotIn("enqueue", g1.__dict__)
+ self.assertNotIn("iterate_ngram_gen", g1.__dict__) # the generator's own slot is back
+ self.assertEqual((g1.iterate_ngram_gen([]), g1.forwards), (None, 1))
+
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]