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.

GLM lookup: gate lookup rounds on their measured gain per request

YanissAmz2b4454bafb99
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index 05c9901..0905991 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -363,17 +363,43 @@ def install_lookup(g, ngram, stats=None):
if len(getattr(j, "sequences", ())) == 1: fol.sync(j.sequences[0].sequence_ids)
return r
g.enqueue = enq
+ # Gate (QWSPEC_NGRAM_GATE=0 turns it off): per request, the mean tokens gained per lookup round and per drafter round
+ # (from the sequence growth seen at the next round). A lookup round runs only while its mean is not below the drafter
+ # round's, with one probe every PROBE drafter rounds so a copy section later in the answer turns it back on. Long prompts
+ # hold many 16-token matches that do not continue (GLM 128K essay: lookup on 26.4 tok/s, off 30.7); copies keep it on.
+ gate = os.environ.get("QWSPEC_NGRAM_GATE", "1") != "0"
+ PROBE, A = 32, 0.25
+ # drafter prior: 1 + 0.6 per draft token (GLM 128K essay: 0.67 accepted per draft); it is measured from the first
+ # drafter round on, and lookup rounds start at the optimistic K + 1
+ dr0 = lambda: 1.0 + 0.6 * max(1, int(g.num_draft_tokens))
+ st = {"sid": None, "n": 0, "kind": None, "ng": float(K + 1), "dr": dr0(), "skip": 0}
+ def gate_ok(sid, n):
+ if sid is not st["sid"]:
+ st.update(sid=sid, kind=None, ng=float(K + 1), dr=dr0(), skip=0)
+ elif st["kind"] is not None and n > st["n"]:
+ k = st["kind"]; st[k] = (1 - A) * st[k] + A * (n - st["n"])
+ st["n"] = n
+ if not gate or st["ng"] >= st["dr"] or st["skip"] >= PROBE: return True
+ return False
def wrapped(results):
- cont = None
+ cont = None; sid = None
if len(g.active_jobs) == 1 and g.active_jobs[0].is_prefill_done() and len(g.active_jobs[0].sequences) == 1:
- idx = fol.sync(g.active_jobs[0].sequences[0].sequence_ids)
+ sid = g.active_jobs[0].sequences[0].sequence_ids
+ idx = fol.sync(sid)
L, c = idx.match(K)
if L >= lmin and c:
cont = c
if cmin > 0:
a = idx.witness_len(c)
if a < len(c): cont = c[:a] if a >= cmin else None
- if cont is None: return orig(results)
+ if not gate_ok(sid, len(sid)):
+ if cont is not None and stats is not None: stats["ng_gated"] = stats.get("ng_gated", 0) + 1
+ cont = None
+ if cont is None:
+ if sid is not None:
+ st["kind"] = "dr"; st["skip"] += 1
+ return orig(results)
+ st["kind"] = "ng"; st["skip"] = 0
w = g.num_draft_tokens; g.num_draft_tokens = 1
try: out = orig(results)
finally: g.num_draft_tokens = w
diff --git a/tools/qwen/test_lookup_gate.py b/tools/qwen/test_lookup_gate.py
new file mode 100644
index 0000000..0f4a0d1
--- /dev/null
+++ b/tools/qwen/test_lookup_gate.py
@@ -0,0 +1,60 @@
+"""install_lookup gate: model-free, fake Generator (no GPU, no exllamav3 import)."""
+import os, sys, unittest
+from pathlib import Path
+import torch
+sys.path.insert(0, str(Path(__file__).parent))
+import spec_policy
+
+class Sid:
+ def __init__(self, ids): self.ids = list(ids)
+ def __len__(self): return len(self.ids)
+ def torch(self): return torch.tensor([self.ids], dtype=torch.int32)
+ def torch_slice(self, a, b): return torch.tensor([self.ids[a:b]], dtype=torch.int32)
+ def truncate(self, n): del self.ids[n:]
+ def clear(self): self.ids.clear()
+
+class Seq:
+ def __init__(self, sid): self.sequence_ids = sid
+
+class Job:
+ def __init__(self, sid): self.sequences = [Seq(sid)]
+ def is_prefill_done(self): return True
+
+class Gen:
+ num_draft_tokens = 2
+ def __init__(self, sid): self.active_jobs = [Job(sid)]; self.draft_calls = 0
+ def enqueue(self, job): return None
+ def iterate_draftmodel_mtp_gen(self, results):
+ self.draft_calls += 1
+ return torch.tensor([[0] * self.num_draft_tokens], dtype=torch.long)
+
+def run(rounds, gain_ng, gain_dr, gate="1"):
+ """A prompt that repeats a 40-token block, so every round finds a long match. Lookup rounds grow the sequence by
+ gain_ng tokens, drafter rounds by gain_dr. Returns (lookup rounds, gated matches)."""
+ os.environ["QWSPEC_NGRAM_GATE"] = gate
+ block = list(range(100, 140)); sid = Sid(block * 50)
+ g = Gen(sid); stats = {}
+ spec_policy.install_lookup(g, (2, 7, 16, 3), stats)
+ ng = 0
+ for _ in range(rounds):
+ before = stats.get("ng", 0)
+ g.iterate_draftmodel_mtp_gen(None)
+ hit = stats.get("ng", 0) > before; ng += hit
+ n = len(sid); sid.ids += [100 + (n + i) % 40 for i in range(gain_ng if hit else gain_dr)]
+ return ng, stats.get("ng_gated", 0)
+
+class LookupGate(unittest.TestCase):
+ def test_good_copies_keep_lookup(self):
+ ng, gated = run(100, gain_ng=8, gain_dr=3)
+ self.assertEqual(ng, 100); self.assertEqual(gated, 0)
+
+ def test_bad_matches_are_gated_with_probes(self):
+ ng, gated = run(200, gain_ng=1, gain_dr=3)
+ self.assertLess(ng, 20); self.assertGreater(gated, 150)
+
+ def test_gate_off_restores_old_behaviour(self):
+ ng, gated = run(50, gain_ng=1, gain_dr=3, gate="0")
+ self.assertEqual(ng, 50); self.assertEqual(gated, 0)
+
+if __name__ == "__main__":
+ unittest.main()