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
Relaxed acceptance of argmax drafts for sampled requests (EXL3_SPEC_TYPICAL, default off) (#164)
Yaniss Amazouzd8dbb75e3bcb
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 1f905e5..467a09c 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -1289,6 +1289,7 @@ The same lane also exports `EXL3_HOST_LEAN`, `EXL3_HOST_CUTS`, `EXL3_LOAD_DEVICE| `QWSPEC_NGRAM` | `2,7,16,3` | The same copy lookup for the Qwen server, in the same format. `2,3,5` gives the earlier setting (a 5-token match, 3 copied tokens). `off` turns it off. || `QWSPEC_NGRAM_IDX` | `1` | Builds the lookup index when the request is queued, so its cost lands in the time to first token and not in the first decode round. `0` builds it lazily and also turns off the `cmin` check. || `EXL3_SPEC_SAMPLED` | engine `0`; the GLM server sets `1` | For requests with temperature above 0 and an MTP drafter: the drafter draws its tokens from its own distribution, and the verify keeps each one with probability min(1, p/q), or resamples from the remainder. The output has the same distribution as plain sampling. Greedy requests are untouched. `0` goes back to taking the drafter's top token. The Qwen server does not set it. |+| `EXL3_SPEC_TYPICAL` | `0` | Relaxed ("typical") acceptance of argmax drafts for sampled requests (temperature above 0, MTP drafter): a draft is also kept when its probability under the sampling law (top-k / top-p cuts, then temperature) is at least min(eps, delta * exp(-H)), H being the entropy of that law; tokens cut by the filters are never kept. Greedy requests and `0` are unchanged bit for bit. `EXL3_SPEC_TYPICAL_EPS` (0.09) and `EXL3_SPEC_TYPICAL_DELTA` (0.3) tune it; `EXL3_SPEC_TYPICAL_FILE` (test only) switches it at run time. Real Hermes turns: Qwen 3.8 Flash-Next iGPU 55.1 to 58.8 tok/s, Qwen 3.8 27B RTX 3090 88.9 to 116.3 tok/s; GSM8K and HumanEval unchanged. || `EXL3_GLM_SLOTS` | `0` (one recurrent state slot per session) | Minimum number of recurrent state slots the GLM server allocates. The default sizes them to `--sessions`, which frees about 6 GiB of GPU memory at one session. `16` restores the earlier layout. || `EXL3_GC_FREEZE` | Qwen server `1`, GLM server `0` | Moves the loaded model and tokenizer objects out of the Python garbage collector before the first generator is built. Without it, rebuilding the generator (for example after a `cache_salt` change) pays a collector pass of about 0.5 s inside the time to first token. `0` leaves them in the collector. |diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.pyindex d8bfb8e..3bfa90c 100644--- a/exllamav3/generator/generator.py+++ b/exllamav3/generator/generator.py@@ -2164,6 +2164,17 @@ class Generator:else:pre = None_hacc("t_samp_h", _hs)+ typ = None+ if draft_tokens is not None and spec is None and (spec_sample.typical_on() or spec_sample.PTAP) \+ and npos > 1 and not self.dflash_draft:+ _tp = spec_sample.eligible(job)+ if _tp is not None:+ _dr = [int(draft_tokens[j, pi]) for pi in range(npos - 1)]+ typ = (spec_sample.typical_rows(job_logits[0, :npos - 1, :], _dr, _tp, spec_sample.TYP_EPS, spec_sample.TYP_DELTA), _dr)+ if spec_sample.PTAP:+ import json as _json+ with open(spec_sample.PTAP, "a") as _f:+ _f.write(_json.dumps({"src": "mtp", "p_draft": typ[0][0], "entropy": typ[0][1]}) + "\n")for i in range(batch_logits.shape[1]):token_logits = job_logits[:, i:i + 1, :]if pre is not None:@@ -2174,6 +2185,8 @@ class Generator:next_token, next_k_tokens, next_k_probs, next_prob = job.receive_logits(token_logits,)+ if typ is not None and spec_sample.typical_on() and i < npos - 1 and typ[0][2][i] and int(next_token.view(-1)[0]) != typ[1][i]:+ next_token = torch.full_like(next_token, typ[1][i])eos, sampled_token, rq = job.receive_sample(token_logits,next_token,diff --git a/exllamav3/generator/spec_sample.py b/exllamav3/generator/spec_sample.pyindex b7d7151..c671eb7 100644--- a/exllamav3/generator/spec_sample.py+++ b/exllamav3/generator/spec_sample.py@@ -123,3 +123,69 @@ def verify(logits: torch.Tensor, q: torch.Tensor, d: int, prm: tuple, rng) -> tores = (p - q).clamp_(min = 0.0)r = draw(torch.where(res.sum() > 0, res, p), u2) # p == q leaves no residual: draw from p then (keep is true but for rounding)return torch.where(keep, torch.full_like(r, d), r).view(1, 1)+++# Relaxed ("typical") acceptance, Medusa rule (Cai et al. 2024, arXiv 2401.10774) for sampled jobs that keep the argmax draft:+# the verify keeps draft j when the sampled token equals it (exact) OR when p(draft_j) >= min(eps, delta * exp(-H_j)), p and H+# being the job's sampling law (top-k / top-p cuts, then temperature) at row j. A token cut by the filters has p = 0 and is never+# kept. At the first rejected row the token is the normal sample. EXL3_SPEC_TYPICAL=0 (default): nothing changes, bit for bit.+TYPICAL = os.environ.get("EXL3_SPEC_TYPICAL", "0") != "0"+TYP_EPS = float(os.environ.get("EXL3_SPEC_TYPICAL_EPS", "0.09"))+TYP_DELTA = float(os.environ.get("EXL3_SPEC_TYPICAL_DELTA", "0.3"))+# Read-only probe: EXL3_SPEC_PTAP=<file.jsonl> appends one line per verify round (p_draft, entropy, match per row)+PTAP = os.environ.get("EXL3_SPEC_PTAP") or None+# Test switch for in-server A/B: EXL3_SPEC_TYPICAL_FILE=<path>, the rule is on while the file holds "1" (re-read when its mtime changes)+_TFILE = os.environ.get("EXL3_SPEC_TYPICAL_FILE") or None+_tstate = [0.0, TYPICAL]+++def typical_on() -> bool:+ if _TFILE is None:+ return TYPICAL+ try:+ m = os.stat(_TFILE).st_mtime+ if m != _tstate[0]:+ _tstate[0] = m+ _tstate[1] = open(_TFILE).read().strip() == "1"+ except OSError:+ pass+ return _tstate[1]+++def _topk_of(prm: tuple):+ """The top-K cut of the law (None = no cut): lets typical_rows work on K logits per row instead of the whole vocabulary."""+ kind, x, vs = prm+ if kind == "fused":+ return x[3] if x[2] & SS_Fused.F_TOPK and 0 < x[3] < vs else None+ ks = [st.top_k for st in x if type(st) is SS_TopK and 0 < st.top_k < vs]+ return min(ks) if ks else None+++def typical_rows(rows: torch.Tensor, drafts: list, prm: tuple, eps: float, delta: float):+ """+ rows: (n, V) verify logits of the n draft rows; drafts: the n drafted ids. Returns (p, H, ok) as python lists, one+ host sync: p = law probability of the draft, H = entropy of the law, ok = p > 0 and p >= min(eps, delta * exp(-H)).+ With a top-K cut in the law only the K best logits of each row are sorted and normalised (the law is zero elsewhere,+ so p and H are those of the dense law).+ """+ ps, hs = [], []+ K = _topk_of(prm)+ if K is not None:+ kind, x, vs = prm+ v, ix = torch.topk(rows[:, :vs].float(), K, dim = -1)+ sub = (kind, x, K)+ dr = torch.tensor(drafts, dtype = ix.dtype, device = ix.device).view(-1, 1)+ hit = (ix == dr)+ for i, d in enumerate(drafts):+ if K is not None:+ pl = law(v[i], sub)+ ps.append((pl * hit[i]).sum())+ else:+ pl = law(rows[i], prm)+ ps.append(pl[d])+ hs.append(-(pl * torch.log(pl.clamp_min(1e-30))).sum())+ p = torch.stack(ps)+ h = torch.stack(hs)+ ok = (p > 0) & (p >= torch.clamp(delta * torch.exp(-h), max = eps))+ out = torch.stack([p, h, ok.float()]).tolist()+ return out[0], out[1], [x > 0.5 for x in out[2]]diff --git a/tools/qwen/test_spec_typical.py b/tools/qwen/test_spec_typical.pynew file mode 100644index 0000000..e390279--- /dev/null+++ b/tools/qwen/test_spec_typical.py@@ -0,0 +1,91 @@+# CPU tests of the relaxed ("typical") acceptance rule in generator/spec_sample.py (no GPU, no model). python tools/qwen/test_spec_typical.py+# 1. rule boundary: p >= min(eps, delta*exp(-H)) keeps the draft, just below does not+# 2. H = 0 (one-hot law): threshold is min(eps, delta) and the draft that carries all the mass is kept; any other draft has p = 0+# 3. tokens cut by top-k / top-p have p = 0 and are never kept, whatever eps and delta+# 4. flag off (default): EXL3_SPEC_TYPICAL unset -> typical_on() is False, the verify loop never calls typical_rows (code path guarded)+# 5. greedy jobs (SS_Argmax) are not eligible, so the rule never applies to them+import math, os, sys, unittest+os.environ.setdefault("HIP_VISIBLE_DEVICES", ""); os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")+sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))+import torch+from exllamav3.generator import spec_sample as ss+from exllamav3.generator.sampler.custom import SS_Sort, SS_TopK, SS_TopP, SS_Temperature, SS_Normalize, SS_Sample, SS_Argmax, CustomSampler++V = 16+PRM_FULL = ("steps", [SS_Temperature(1.0), SS_Normalize()], V)+++def row_from_probs(p):+ p = torch.tensor(p, dtype=torch.float)+ return torch.log(p).view(1, -1) # log(0) = -inf: the token is outside the law+++class TypicalRule(unittest.TestCase):+ def test_boundary(self):+ # law (0.5, 0.3, 0.2, 0 ...): H known; threshold for the draft with p = 0.2+ p = [0.5, 0.3, 0.2] + [0.0] * (V - 3)+ H = -sum(x * math.log(x) for x in p if x > 0)+ eps, delta = 0.09, 0.3+ thr = min(eps, delta * math.exp(-H))+ rows = row_from_probs(p)+ for d, want in ((2, True), (1, True), (0, True)):+ pp, hh, ok = ss.typical_rows(rows, [d], PRM_FULL, eps, delta)+ self.assertAlmostEqual(hh[0], H, places=4)+ self.assertEqual(ok[0], want)+ # push the threshold above the draft's probability: kept iff p >= thr+ pp, hh, ok = ss.typical_rows(rows, [2], PRM_FULL, 1.0, 1.0) # thr = exp(-H) ~ 0.31 > 0.2+ self.assertFalse(ok[0])+ pp, hh, ok = ss.typical_rows(rows, [2], PRM_FULL, 0.2 - 1e-4, 10.0) # thr = eps = 0.1999+ self.assertTrue(ok[0])+ pp, hh, ok = ss.typical_rows(rows, [2], PRM_FULL, 0.2 + 1e-3, 10.0)+ self.assertFalse(ok[0])++ def test_entropy_zero(self):+ p = [1.0] + [0.0] * (V - 1)+ rows = row_from_probs(p)+ pp, hh, ok = ss.typical_rows(rows.repeat(2, 1), [0, 5], PRM_FULL, 0.09, 0.3)+ self.assertAlmostEqual(hh[0], 0.0, places=5)+ self.assertEqual(ok, [True, False])+ self.assertEqual(pp[1], 0.0)++ def test_filtered_tokens_never_kept(self):+ p = [0.4, 0.3, 0.2, 0.05, 0.03, 0.02] + [0.0] * (V - 6)+ rows = row_from_probs(p)+ prm = ("steps", [SS_Temperature(1.0), SS_Sort(), SS_TopK(3), SS_Normalize()], V)+ pp, hh, ok = ss.typical_rows(rows.repeat(3, 1), [3, 4, 5], prm, 1e-9, 1e-9) # tiny thresholds+ self.assertEqual(pp, [0.0, 0.0, 0.0])+ self.assertEqual(ok, [False, False, False])+ pp, hh, ok = ss.typical_rows(rows, [2], prm, 0.09, 0.3)+ self.assertTrue(ok[0] and pp[0] > 0.2)++ def test_topk_fast_path_equals_dense(self):+ g = torch.Generator().manual_seed(3)+ Vb = 200+ rows = torch.randn(6, Vb, generator=g) * 2.0+ prm = ("steps", [SS_Temperature(1.0), SS_Sort(), SS_TopK(20), SS_Normalize(), SS_Sort(), SS_TopP(0.95)], Vb)+ drafts = [int(rows[i].argmax()) if i % 2 == 0 else int(rows[i].argsort()[-5]) for i in range(6)]+ drafts[5] = int(rows[5].argsort()[0]) # far outside the top-K: p = 0+ pp, hh, ok = ss.typical_rows(rows, drafts, prm, 0.09, 0.3)+ for i, d in enumerate(drafts):+ pl = ss.law(rows[i], prm)+ H = float(-(pl * torch.log(pl.clamp_min(1e-30))).sum())+ self.assertAlmostEqual(pp[i], float(pl[d]), places=5)+ self.assertAlmostEqual(hh[i], H, places=4)+ self.assertEqual(pp[5], 0.0)+ self.assertFalse(ok[5])++ def test_default_off(self):+ self.assertFalse(ss.TYPICAL)+ self.assertFalse(ss.typical_on())++ def test_greedy_not_eligible(self):+ class J:+ filters = []; forced_ids = None; return_probs = False; return_top_tokens = False; device_logit_mask = None; sequences = [1]+ sampler = CustomSampler([SS_Argmax()])+ class generator:+ class tokenizer: actual_vocab_size = V+ self.assertIsNone(ss.eligible(J()))+++if __name__ == "__main__":+ unittest.main()