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.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
N-gram lookup: one follower per conversation (pool of 4) instead of one shared by all
YanissAmzd63ac3ff97e1
diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.pyindex 9ee08c4..7fa31bc 100644--- a/tools/qwen/spec_policy.py+++ b/tools/qwen/spec_policy.py@@ -227,6 +227,50 @@ class SeqFollower:sid._ng_lw = nreturn idx+class FollowerPool:+ """SeqFollower for a server that alternates between sessions: one follower per conversation (at most `cap`, least recently used+ goes first), so a returning session resyncs by its new tokens only. A single follower matched the next request by common prefix+ with the LAST request: with users taking turns that prefix is the shared system prompt and every return rebuilt the whole index+ (about 2.5 us per token: 0.42 s at 117K). A request goes to the follower sharing most of its prompt; with none sharing half of it,+ it takes a new follower (the oldest one while the pool is full). One user: one follower, the same work as before.+ Host RAM: about 2 MB per 1000 tokens per follower (QWSPEC_NG_POOL=1 gives the single follower back)."""+ def __init__(self, nmin, cap=None):+ self.nmin = nmin; self.cap = max(1, cap if cap is not None else int(os.environ.get("QWSPEC_NG_POOL", "4")))+ self.fs = []; self.cur = SeqFollower(nmin); self.fs.append(self.cur)++ @property+ def idx(self):+ return self.cur.idx++ @staticmethod+ def _common(f, ids):+ have = np.frombuffer(f.idx.toks, dtype=np.int32)+ m = min(len(ids), len(have))+ neq = np.flatnonzero(ids[:m] != have[:m])+ return int(neq[0]) if len(neq) else m++ def sync(self, sid):+ f = next((f for f in self.fs if f.sid is sid), None)+ if f is None:+ if len(self.fs) == 1 and self.cap == 1:+ f = self.fs[0]+ else:+ ids = _as_np(sid.torch()) if len(sid) else np.zeros(0, dtype=np.int64)+ best, bp = None, -1+ for g in self.fs:+ p = self._common(g, ids)+ if p > bp: best, bp = g, p+ if bp * 2 >= len(ids) or (best is not None and not len(best.idx.toks)):+ f = best+ elif len(self.fs) < self.cap:+ f = SeqFollower(self.nmin); self.fs.append(f)+ else:+ f = self.fs[0]+ if f is not self.fs[-1]:+ self.fs.remove(f); self.fs.append(f)+ self.cur = f+ return f.sync(sid)+# ---------------------------------------------------------------------------------------------- depth rules# A rule decides, per drafted depth, from the drafter's max token probability p (the "reach" is the running product):# step(i, p) -> (keep, more): keep = this depth's token goes to the verify; more = draft one more depth.@@ -482,7 +526,7 @@ def install_lookup(g, ngram, stats=None):before, the round verifies its continuation (K tokens, cut by cmin as in install()) and runs ONE draft forward so thedrafter cache has no hole; every other round is the Generator's own. Only with a single active request. The cacheneeds 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+ fol = FollowerPool(ngram[0]); K, lmin = ngram[1], ngram[2]; cmin = ngram[3] if len(ngram) > 3 else 0orig = type(g).iterate_draftmodel_mtp_gen.__get__(g)orig_enqueue = g.enqueuedef enq(job):@@ -659,7 +703,7 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, ruleorig_draft = type(g).iterate_draftmodel_mtp_gen.__get__(g)orig_sfs = dm.sample_from_state; orig_fwd = dm.forward; orig_lmf = lm.forwardcap = {}- fol = SeqFollower(ngram[0]) if ngram is not None else None+ fol = FollowerPool(ngram[0]) if ngram is not None else None# Lookup drafts while several requests decode together (QWSPEC_NG_MULTI_ROWS = verify-row budget of such a round, 0 = off,# default 32 = the multi-job graph's B x Q limit for a dense CUDA model, off elsewhere): one follower per requestngm_rows = int(os.environ.get("QWSPEC_NG_MULTI_ROWS", "") or (2 * dense_cuda_rows(model))) if ngram is not None else 0diff --git a/tools/qwen/test_ngram_index.py b/tools/qwen/test_ngram_index.pyindex 1da6f5a..3b7c95f 100644--- a/tools/qwen/test_ngram_index.py+++ b/tools/qwen/test_ngram_index.py@@ -153,10 +153,43 @@ def recorded(dd, rounds=300, seed=3):print(f"recorded {L:>6}: ctx {len(ctx)} {rounds} rounds equal ({n_hits} with L>=5); cold build {cold:.2f}s, turn2 resync {turn2*1e3:.1f} ms, "f"new sync+match median {1e6*sorted(times)[len(times)//2]:.0f} us (max {1e6*max(times):.0f}), old tolist+scan median {1e3*sorted(t_old)[10]:.2f} ms; fallbacks {fol.idx.fallbacks}")+def pool(rounds=40):+ """FollowerPool: sessions taking turns on a shared system prompt give the same match as ngram_match, hold at most `cap` followers,+ and a returning session resyncs by its new tokens only (no rebuild)."""+ rnd = random.Random(7); nmin, K = 2, 6+ sysp = [rnd.randrange(50) for _ in range(300)]+ for cap in (1, 3):+ fp = sp.FollowerPool(nmin, cap); ctxs = [sysp + [rnd.randrange(50) for _ in range(500 + 100 * u)] for u in range(5)]+ sids = [SeqTensor((1, 1), torch.long, -1, init_cap=64) for _ in ctxs]+ for u, c in enumerate(ctxs): sids[u].append(torch.tensor([c]))+ rebuilds = 0+ for r in range(rounds):+ u = rnd.randrange(len(ctxs)); new = [rnd.randrange(50) for _ in range(rnd.randrange(1, 40))]+ ctxs[u] = ctxs[u] + new; sids[u].append(torch.tensor([new]))+ n0 = len(fp.cur.idx.toks) if fp.cur.sid is not sids[u] else 0+ idx = fp.sync(sids[u])+ assert idx is fp.idx and len(fp.fs) <= cap+ assert np.array_equal(np.frombuffer(idx.toks, dtype=np.int32), np.array(ctxs[u], dtype=np.int32)), f"pool index != ctx (cap {cap}, round {r})"+ assert idx.match(K) == sp.ngram_match(ctxs[u], nmin, K), f"pool match != ngram_match (cap {cap}, round {r})"+ hit(f"pool_cap{cap}")+ # alternating two sessions: once both are known, a return costs the new tokens only+ fp = sp.FollowerPool(nmin, 2); a = [rnd.randrange(50) for _ in range(3000)]; b = [rnd.randrange(50) for _ in range(3000)]+ sa = SeqTensor((1, 1), torch.long, -1, init_cap=64); sa.append(torch.tensor([sysp + a]))+ sb = SeqTensor((1, 1), torch.long, -1, init_cap=64); sb.append(torch.tensor([sysp + b]))+ fp.sync(sa); fp.sync(sb)+ fa, fb = [f for f in fp.fs if f.sid is sa][0], [f for f in fp.fs if f.sid is sb][0]+ assert fa is not fb+ for sid in (sa, sb, sa, sb):+ sid.append(torch.tensor([[1, 2, 3]])); before = len(fp.cur.idx.toks) if fp.cur.sid is sid else None+ fp.sync(sid)+ assert fp.cur.sid is sid and (fp.cur is fa) == (sid is sa)+ hit("pool_alternate")+if __name__ == "__main__":ap = argparse.ArgumentParser(); ap.add_argument("--fuzz", type=int, default=10000); ap.add_argument("--docs", default=os.path.expanduser("$WORK_DIR"))ap.add_argument("--skip-recorded", action="store_true"); a = ap.parse_args()fuzz(a.fuzz)+ pool()print("branches:", json.dumps(BR, sort_keys=True))if not a.skip_recorded: recorded(a.docs)print("ALL OK")