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 server: optional n-gram lookup for copied text (GLM_NGRAM, off by default)

YanissAmzcbe7fbd4f334
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 0a00305..aeb53a5 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -371,6 +371,16 @@ class ResidentEngine:
ctx = min(max_position, max_ctx)
self.ctx = ctx
slots = max(1 if sessions == 1 else MAX_SESSIONS, int(os.environ.get("EXL3_GLM_SLOTS", "0") or 0))
+ # GLM_NGRAM = "gram,K,match[,cmin]" (off by default): n-gram lookup of tools/qwen/spec_policy.install_lookup. When the
+ # last `match` tokens occurred before, the round verifies the K tokens that followed them instead of the drafter's
+ # --num-draft tokens. K rows beyond the first need K history levels (138 MiB each per slot).
+ v = (os.environ.get("GLM_NGRAM") or "off").strip().lower()
+ self.lookup = None if v in ("off", "0", "none") or num_draft < 1 else tuple(int(x) for x in v.split(","))
+ if self.lookup:
+ if not (3 <= len(self.lookup) <= 4 and 1 <= self.lookup[0] <= 16 and self.lookup[1] >= 1 and self.lookup[2] >= self.lookup[0]):
+ raise ValueError(f"GLM_NGRAM={v}")
+ max_history = max(max_history, self.lookup[1])
+ self.lookup_stats: dict[str, int] = {}
self.cache = Cache(self.model, max_num_tokens=ctx + 4096,
max_history=max_history, max_batch_size=slots)
startup_health.stage("target weights")
@@ -392,9 +402,8 @@ class ResidentEngine:
self.Generator = Generator
# The loaded model and tokenizer are 1.1 M Python objects and every later gc.collect() walks them all: the Generator
# rebuild of a cache_salt change pays 0.4 s for it inside time to first token. EXL3_GC_FREEZE=1 keeps them out of the
- # collector, before the first Generator exists (a frozen Generator would never be freed). Off by default here: one
- # load, arms interleaved, +3.8 % first-token rate at 8K and +11 % at 2K, but over five server loads the 8K figure did
- # not move and two of the three loads with the switch had slow outliers (cause not found). The Qwen server has it on.
+ # collector, before the first Generator exists (a frozen Generator would never be freed). Off by default here: four
+ # server loads in both orders give +2.1 % first-token rate at 8K and +7.9 % at 2K. The Qwen server has it on.
if os.environ.get("EXL3_GC_FREEZE", "0") != "0":
import gc
gc.collect()
@@ -407,10 +416,20 @@ class ResidentEngine:
os.environ.setdefault("EXL3_MOE_UNION_V2", "1") # the "+v2" of n1f2+v2
def _make_generator(self):
- return self.Generator(
+ lookup = getattr(self, "lookup", None)
+ g = self.Generator(
model=self.model, cache=self.cache, tokenizer=self.tokenizer,
- draft_model=self.draft_model, draft_cache=self.draft_cache, num_draft_tokens=self.num_draft or None,
+ draft_model=self.draft_model, draft_cache=self.draft_cache,
+ num_draft_tokens=max(self.num_draft, lookup[1] if lookup else 0) or None, # buffers for the widest round
record_draft_stats=True)
+ if lookup:
+ qdir = str(Path(__file__).resolve().parent.parent / "qwen")
+ if qdir not in sys.path:
+ sys.path.append(qdir)
+ import spec_policy
+ spec_policy.install_lookup(g, lookup, self.lookup_stats)
+ g.num_draft_tokens = self.num_draft # the drafter's own depth; lookup rounds bring their K tokens
+ return g
def _rebuild_generator(self) -> None:
"""A fresh Generator over the same Cache (one at a time: a second one takes the Cache over). It drops the whole prompt
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.py
index fd1fa7d..734c0fb 100644
--- a/tools/qwen/spec_policy.py
+++ b/tools/qwen/spec_policy.py
@@ -346,6 +346,35 @@ def ngram_from_env(default=(2, 7, 16, 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 install_lookup(g, ngram, stats=None):
+ """The n-gram lookup alone, for a Generator whose drafter keeps its own fixed depth (GLM): no depth rule, no read of the
+ draft probabilities. ngram = (nmin, K, lmin[, cmin]) as in install(). When the context suffix (>= lmin tokens) occurred
+ before, the round verifies its continuation (K tokens, cut by cmin as in install()) and runs ONE draft forward so the
+ drafter cache has no hole; every other round is the Generator's own. Only with a single active request. The cache
+ needs max_history >= K. Returns an uninstall function."""
+ fol = SeqFollower(ngram[0]); K, lmin = ngram[1], ngram[2]; cmin = ngram[3] if len(ngram) > 3 else 0
+ orig = type(g).iterate_draftmodel_mtp_gen.__get__(g)
+ def wrapped(results):
+ cont = 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)
+ 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)
+ w = g.num_draft_tokens; g.num_draft_tokens = 1
+ try: out = orig(results)
+ finally: g.num_draft_tokens = w
+ if out is None: return None
+ if stats is not None: stats["ng"] = stats.get("ng", 0) + 1; stats["ng_tokens"] = stats.get("ng_tokens", 0) + len(cont)
+ return torch.tensor([cont], dtype=torch.long)
+ g.iterate_draftmodel_mtp_gen = wrapped
+ def uninstall(): g.__dict__.pop("iterate_draftmodel_mtp_gen", None)
+ 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 d39046e..7e05721 100644
--- a/tools/qwen/test_spec_rule.py
+++ b/tools/qwen/test_spec_rule.py
@@ -154,6 +154,30 @@ class T(unittest.TestCase):
try: self.assertEqual(sp.ngram_from_env(), want)
finally: del os.environ["QWSPEC_NGRAM"]
+ def test_install_lookup(self):
+ # lookup-only installer (GLM): a lookup round runs ONE draft forward and returns the copied tokens; any other round
+ # is the generator's own, at its own depth; the window is restored
+ from exllamav3.util.tensor import SeqTensor
+ row = lambda v: list(range(100, 120)) + [v] + [7, 8, 9]
+ def gen(ctx):
+ g = FakeGen(2); dm = FakeDM(g, [0.9] * 8); g.dm, g.lm = dm, FakeLM(dm); dm.chain = [0.9] * 16
+ sid = SeqTensor((1, 1), torch.long, -1, init_cap=256); sid.append(torch.tensor([ctx], dtype=torch.long))
+ g.job.sequences[0].sequence_ids = sid
+ return g
+ st = {}
+ g = gen(row(1000) + list(range(100, 118))); un = sp.install_lookup(g, (2, 3, 16, 1), st)
+ out = g.iterate_draftmodel_mtp_gen([])
+ self.assertEqual((out.tolist(), g.forwards, g.num_draft_tokens, st), ([[118, 119, 1000]], 1, 2, {"ng": 1, "ng_tokens": 3}))
+ g = gen(row(1000) + row(2000) + list(range(100, 118))); sp.install_lookup(g, (2, 3, 16, 1))
+ self.assertEqual(g.iterate_draftmodel_mtp_gen([]).tolist(), [[118, 119]]) # cut where the two rows differ
+ g = gen(row(1000) + row(2000) + list(range(100, 118))); sp.install_lookup(g, (2, 3, 16, 3))
+ self.assertEqual((g.iterate_draftmodel_mtp_gen([]).shape[-1], g.forwards), (2, 2)) # under cmin: the drafter's own round
+ g = gen(list(range(40))); un = sp.install_lookup(g, (2, 3, 16, 1))
+ self.assertEqual((g.iterate_draftmodel_mtp_gen([]).shape[-1], g.forwards), (2, 2)) # no match
+ g.active_jobs = [g.job, FakeJob()]
+ self.assertEqual(g.iterate_draftmodel_mtp_gen([]).shape[-1], 2) # two requests: no lookup
+ un(); self.assertNotIn("iterate_draftmodel_mtp_gen", g.__dict__)
+
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]