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.

Sampled MTP drafts with an exact keep / resample rule for T > 0 jobs (EXL3_SPEC_SAMPLED, off by default)

YanissAmz736f1d06af1f
diff --git a/exllamav3/architecture/glm5_next_mtp.py b/exllamav3/architecture/glm5_next_mtp.py
index 8dd848a..a9cca19 100644
--- a/exllamav3/architecture/glm5_next_mtp.py
+++ b/exllamav3/architecture/glm5_next_mtp.py
@@ -282,6 +282,8 @@ class Glm5NextMTPModel(Model):
lm = self.attached_model().modules[ll]
logits = lm.prepare_for_device(state, params)
logits = lm.forward(logits, params)
+ if params.get("export_draft_logits"):
+ params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs
if params.get("export_draft_conf"):
# Per-position confidence for the generator's draft truncation: the argmax logit
# value, over the unpadded vocabulary
diff --git a/exllamav3/architecture/qwen4_exp_mtp.py b/exllamav3/architecture/qwen4_exp_mtp.py
index d55f89c..ae8888f 100644
--- a/exllamav3/architecture/qwen4_exp_mtp.py
+++ b/exllamav3/architecture/qwen4_exp_mtp.py
@@ -177,6 +177,8 @@ class Qwen4ExpMTPModel(Model):
lm = self.attached_model().modules[ll]
logits = lm.prepare_for_device(state, params)
logits = lm.forward(logits, params)
+ if params.get("export_draft_logits"):
+ params["draft_logits"] = logits # spec_sample: the drafter's law for sampled jobs
if params.get("export_draft_conf"):
logits = logits[..., :self.attached_model().config.vocab_size]
conf, ids = torch.max(logits, dim = -1)
diff --git a/exllamav3/generator/generator.py b/exllamav3/generator/generator.py
index c885869..f04585e 100644
--- a/exllamav3/generator/generator.py
+++ b/exllamav3/generator/generator.py
@@ -20,6 +20,7 @@ from .pagetable import PageTable, is_content_hash
from .cpu_cache import CPUPageCache
from .draft_confidence import DraftConfidenceCalibrator
from .job import Job, _ttrace_begin, _ttrace_end
+from . import spec_sample
from .filter import Filter
from concurrent.futures import ThreadPoolExecutor
from .sampler import Sampler
@@ -340,6 +341,8 @@ class Generator:
# leaving the calibrator inert
self.draft_calibrator = None
self._draft_conf_round = None
+ # Sampled-draft round (spec_sample): (job, sampler params, draft laws per depth) for the next verify
+ self._spec_round = None
# Lazy drafter KV catch-up: plain 1-row steps do not feed the drafter cache, they park the
# target hidden rows here and the next drafting round (or a flush point) writes them in one pass
self._dkv_pending = None
@@ -848,6 +851,7 @@ class Generator:
def iterate_draftmodel_mtp_gen(self, results: list):
+ self._spec_round = None
if self._mtp_defer_gate():
return None
self._draft_conf_round = None
@@ -930,6 +934,16 @@ class Generator:
cal = self.draft_calibrator
conf_cols = []
reach = None
+ # A sampled job (T > 0) draws its drafts from the drafter's law under its own sampler (spec_sample)
+ spec_job = spec_prm = None
+ if spec_sample.SPEC_SAMPLED and batch_size == 1:
+ spec_job = next(j for j in self.active_jobs if j.is_prefill_done())
+ spec_prm = spec_sample.eligible(spec_job)
+ spec_q = []
+ if spec_prm is not None:
+ # Filled depth by depth: a draft policy that stops the loop early (tools/qwen/spec_policy StopDraft) verifies
+ # a prefix of draft_ids_pinned, whose laws are all recorded by then
+ self._spec_round = (spec_job, spec_prm, spec_q)
for idx in range(window):
params = {
"target_hidden": temp_hidden,
@@ -940,6 +954,8 @@ class Generator:
}
if cal is not None:
params["export_draft_conf"] = True
+ if spec_prm is not None:
+ params["export_draft_logits"] = True
if idx == 0 and n_pend and _mtp_fuse_catchup() == 2:
params["dflash_verify"] = True
batch_state = self.draft_model.forward(first_ids if idx == 0 else batch_ids, params)
@@ -948,6 +964,14 @@ class Generator:
lm_head = self.model.modules[self.model.logit_layer_idx]
batch_state = lm_head.prepare_for_device(batch_state, params)
new_ids = self.draft_model.sample_from_state(batch_state, params)
+ if spec_prm is not None:
+ dl = params.pop("draft_logits", None)
+ if dl is None:
+ spec_prm = self._spec_round = None
+ else:
+ q = spec_sample.law(dl[0, -1, :], spec_prm)
+ spec_q.append(q)
+ new_ids = spec_sample.draw(q, spec_job.rng.random()).view(1, 1)
self.draft_ids_pinned[:batch_size, idx:idx+1].copy_(new_ids)
batch_ids.copy_(new_ids)
cache_seqlens += 1 + (n_pend if idx == 0 else 0)
@@ -1472,11 +1496,22 @@ class Generator:
# One bulk D2H + one synchronize replaces one sync per position; the consume
# loop below is unchanged, so RNG order, accept logic and ids are identical.
npos = batch_logits.shape[1]
+ # Sampled-draft round: the draft positions take the spec_sample keep / residual rule, only the last
+ # (bonus) position samples from the target as usual. Applies only to drafts read from the drafter's own
+ # buffer, for which this round recorded a law per position (a lookup round brings its own tensor of
+ # copied tokens: a deterministic draft keeps the argmax rule)
+ spec = None
+ sr = self._spec_round
+ if sr is not None and sr[0] is job and draft_tokens is not None and len(sr[2]) >= npos - 1 and \
+ draft_tokens.data_ptr() == self.draft_ids_pinned.data_ptr():
+ spec = [(spec_sample.verify(job_logits[0, pi, :], sr[2][pi], int(draft_tokens[j, pi]), sr[1], job.rng),
+ None, None, None) for pi in range(npos - 1)]
pre = None
if draft_tokens is not None and _host_lean() and _lean_verify_job(job, b - a):
launched = []
for pi in range(npos):
- launched.append(job.receive_logits(job_logits[:, pi:pi + 1, :]))
+ launched.append(spec[pi] if spec is not None and pi < npos - 1 else
+ job.receive_logits(job_logits[:, pi:pi + 1, :]))
n_dev = sum(1 for s in launched
if s[0] is not None and s[0].is_cuda and s[0].numel() == 1)
if n_dev == len(launched):
@@ -1493,6 +1528,8 @@ class Generator:
token_logits = job_logits[:, i:i + 1, :]
if pre is not None:
next_token, next_k_tokens, next_k_probs, next_prob = pre[i]
+ elif spec is not None and i < npos - 1:
+ next_token, next_k_tokens, next_k_probs, next_prob = spec[i]
else:
next_token, next_k_tokens, next_k_probs, next_prob = job.receive_logits(
token_logits,
diff --git a/exllamav3/generator/spec_sample.py b/exllamav3/generator/spec_sample.py
new file mode 100644
index 0000000..468472f
--- /dev/null
+++ b/exllamav3/generator/spec_sample.py
@@ -0,0 +1,116 @@
+import os
+import torch
+from .sampler.custom import CustomSampler, SS_Fused, SS_Sample, SS_Normalize, SS_Sort, SS_TopK, SS_TopP, SS_Temperature, \
+ SamplingState, SS
+
+# Speculative sampling with a sampled draft (Leviathan et al. 2023, arXiv 2211.17192, Alg. 1; Chen et al. 2023,
+# arXiv 2302.01318, Alg. 2). For sampled jobs (T > 0) the MTP drafter draws d ~ q from its own logits under the job's
+# sampler law instead of taking its argmax; the verify keeps d with probability min(1, p(d) / q(d)) and otherwise draws
+# from norm(max(0, p - q)). The output is distributed exactly as plain sampling from p, for any q; the keep rate is
+# sum_x min(p(x), q(x)) instead of p(argmax q). Greedy jobs never take this path. EXL3_SPEC_SAMPLED=0 disables it.
+SPEC_SAMPLED = os.environ.get("EXL3_SPEC_SAMPLED", "0") != "0"
+
+
+# Step-by-step stacks whose law is rebuilt by running them up to (not including) the final SS_Sample
+LAW_STEPS = (SS_Normalize, SS_Sort, SS_TopK, SS_TopP, SS_Temperature)
+
+
+def eligible(job) -> tuple | None:
+ """
+ How to rebuild the job's sampling law exactly, or None (the job keeps the argmax draft rule). Two cases: the fused
+ sampler (temperature, top-K, top-P; no min-P), rebuilt by fused_law(); or a step-by-step stack of LAW_STEPS ending in
+ SS_Sample (Gumbel-max over the kept probabilities, i.e. a draw proportional to them), rebuilt by running the same steps
+ on the same row. No penalties, masks, filters, forced tokens or returned probabilities.
+ """
+ if job.filters or job.forced_ids is not None or job.return_probs or job.return_top_tokens or \
+ job.device_logit_mask is not None or len(job.sequences) != 1:
+ return None
+ s = job.sampler
+ if not isinstance(s, CustomSampler) or not s.steps:
+ return None
+ vs = job.generator.tokenizer.actual_vocab_size
+ st = s.steps
+ if len(st) == 1 and type(st[0]) is SS_Fused:
+ f = st[0]
+ if f.mode not in (SS_Fused.MODE_SAMPLE, SS_Fused.MODE_SAMPLE_FILTERS):
+ return None
+ if f.mode == SS_Fused.MODE_SAMPLE_FILTERS and f.filters & SS_Fused.F_MINP:
+ return None
+ filters = f.filters if f.mode == SS_Fused.MODE_SAMPLE_FILTERS else 0
+ return ("fused", (f.inv_temp, f.inv_temp_filter, filters, f.top_k, f.top_p), vs)
+ if type(st[-1]) is SS_Sample and all(type(x) in LAW_STEPS for x in st[:-1]):
+ return ("steps", st[:-1], vs)
+ return None
+
+
+def law(logits: torch.Tensor, prm: tuple) -> torch.Tensor:
+ """Dense sampling law (sums to 1, zero on the padded vocabulary) of one row of logits over the padded vocabulary."""
+ kind, x, vs = prm
+ row = logits.view(-1)
+ if kind == "fused":
+ p = torch.zeros(row.numel(), dtype = torch.float, device = row.device)
+ p[:vs] = fused_law(row[:vs], x)
+ return p
+ # Same input as Sampler.forward gives the steps: the full padded row with the padding at -inf
+ row = row.float().clone()
+ row[vs:] = -float("inf")
+ state = SamplingState(rand_u32 = 0, dim = row.numel(), bsz = 1, in_logits = row.view(1, -1))
+ for step in x:
+ step.run(state)
+ match state.state:
+ case SS.PROBS_S | SS.PROBS_N_S:
+ p = torch.zeros_like(row).scatter_(0, state.indices.view(-1), state.probs.view(-1))
+ case SS.PROBS | SS.PROBS_N:
+ p = state.probs.view(-1).clone()
+ case SS.LOGITS_S:
+ p = torch.zeros_like(row).scatter_(0, state.indices.view(-1), torch.softmax(state.logits.view(-1), 0))
+ case SS.LOGITS:
+ p = torch.softmax(state.logits.view(-1), 0)
+ case _:
+ p = torch.softmax(row, 0)
+ return p / p.sum()
+
+
+def fused_law(logits: torch.Tensor, prm: tuple) -> torch.Tensor:
+ """
+ Dense sampling law of the fused sampler (sampling_fused.cu) for one row of logits over the unpadded vocabulary:
+ top-K keeps the k best with their exact ties; top-P (mass at the filter temperature, over the top-K set) keeps the
+ tokens strictly above the first one whose inclusive cumulative mass exceeds top_p, dropping that token's tie group
+ (the top token always kept); then softmax(l / T) over the kept set. No host sync.
+ """
+ inv_temp, inv_temp_filter, filters, top_k, top_p = prm
+ l = logits.float().view(-1)
+ n = l.numel()
+ sl, si = torch.sort(l, descending = True)
+ kept = torch.ones_like(sl, dtype = torch.bool)
+ if filters & SS_Fused.F_TOPK and 0 < top_k < n:
+ kept = sl >= sl[top_k - 1]
+ if filters & SS_Fused.F_TOPP and top_p < 1.0:
+ w = torch.exp((sl - sl[0]) * inv_temp_filter) * kept
+ cs = torch.cumsum(w, 0)
+ # cs[-1] (the top-K mass) exceeds the target, so the crossing index c is always inside the top-K set
+ c = (cs <= top_p * cs[-1]).sum().clamp(max = n - 1)
+ kept = kept & ((sl > sl.gather(0, c.view(1))) | (sl == sl[0]))
+ pw = torch.exp((sl - sl[0]) * inv_temp) * kept
+ p = torch.zeros_like(l)
+ p.scatter_(0, si, pw / pw.sum())
+ return p
+
+
+def draw(p: torch.Tensor, u: float) -> torch.Tensor:
+ """Inverse-CDF draw from a dense (unnormalized) law with a uniform u in [0, 1); never returns a zero-mass index."""
+ cs = torch.cumsum(p, 0)
+ idx = torch.searchsorted(cs, (cs[-1:] * u), right = True)
+ return idx.clamp(max = p.numel() - 1)
+
+
+def verify(logits: torch.Tensor, q: torch.Tensor, d: int, prm: tuple, rng) -> torch.Tensor:
+ """
+ One verify position: target logits (padded vocabulary), the draft law q and the drafted token d (d ~ q). Returns
+ the emitted token as a (1, 1) long tensor: d if kept, else a draw from norm(max(0, p - q)) (never d).
+ """
+ p = law(logits, prm)
+ u1, u2 = rng.random(), rng.random()
+ keep = u1 * q[d] < p[d]
+ r = draw((p - q).clamp_(min = 0.0), u2)
+ return torch.where(keep, torch.full_like(r, d), r).view(1, 1)
diff --git a/tests/test_spec_sample.py b/tests/test_spec_sample.py
new file mode 100644
index 0000000..521205c
--- /dev/null
+++ b/tests/test_spec_sample.py
@@ -0,0 +1,91 @@
+# CPU tests of exllamav3/generator/spec_sample.py (no GPU, no model). python tests/test_spec_sample.py
+# 1. law() of a step-by-step ComboSampler stack == an fp64 reference (softmax, sort, top-K, top-P cumsum <= p), padding gets 0
+# 2. fused_law() == a slow reference of the fused kernel's truncation, with tie groups
+# 3. draft d ~ q, verify(): emitted tokens follow p (chi-square), keep rate == sum min(p, q), never outside p's support
+# 4. eligible(): sampled ComboSampler jobs qualify, greedy / masked / forced jobs do not
+import os, sys, math, random, unittest
+os.environ.setdefault("HIP_VISIBLE_DEVICES", ""); os.environ.setdefault("CUDA_VISIBLE_DEVICES", "")
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+import torch
+from exllamav3.generator import spec_sample as ss
+from exllamav3.generator.sampler import ComboSampler, ArgmaxSampler
+
+def steps_prm(sampler, vs):
+ return ("steps", sampler.steps[:-1], vs)
+
+def ref_steps(l, T, k, tp):
+ pr = torch.softmax(l.double() / T, 0); sp, si = torch.sort(pr, descending = True)
+ if k: sp[k:] = 0; sp = sp / sp.sum()
+ if tp < 1: m = torch.cumsum(sp, 0) <= tp; m[0] = True; sp = sp * m
+ out = torch.zeros_like(pr); out[si] = sp
+ return (out / out.sum()).float()
+
+def ref_fused(l, prm):
+ inv_t, inv_tf, filt, k, tp = prm
+ v, order = torch.sort(l.double(), descending = True); v = v.tolist(); order = order.tolist()
+ kept = [True] * len(v)
+ if filt & 1 and 0 < k < len(v): kept = [x >= v[k - 1] for x in v]
+ if filt & 2 and tp < 1:
+ w = [math.exp((x - v[0]) * inv_tf) if kk else 0.0 for x, kk in zip(v, kept)]; z = sum(w); acc = 0.0; c = len(v) - 1
+ for i, x in enumerate(w):
+ acc += x
+ if acc > tp * z: c = i; break
+ kept = [kk and (x > v[c] or x == v[0]) for x, kk in zip(v, kept)]
+ pw = [math.exp((x - v[0]) * inv_t) if kk else 0.0 for x, kk in zip(v, kept)]; z = sum(pw)
+ out = [0.0] * len(v)
+ for i, x in zip(order, pw): out[i] = x / z
+ return torch.tensor(out)
+
+class FakeJob:
+ def __init__(self, sampler, **kw):
+ self.sampler = sampler; self.filters = []; self.forced_ids = None; self.return_probs = False
+ self.return_top_tokens = 0; self.device_logit_mask = None; self.sequences = [None]
+ self.generator = type("G", (), {"tokenizer": type("T", (), {"actual_vocab_size": 100})()})()
+ self.__dict__.update(kw)
+
+class TestSpecSample(unittest.TestCase):
+
+ def test_steps_law(self):
+ g = torch.Generator().manual_seed(1)
+ for T, k, tp in ((1.0, 0, 0.95), (1.0, 20, 0.95), (0.7, 0, 0.9)):
+ prm = steps_prm(ComboSampler(temperature = T, top_k = k, top_p = tp), 300)
+ for _ in range(100):
+ l = torch.randn(310, generator = g) * (0.5 + 3 * torch.rand(1, generator = g))
+ p = ss.law(l, prm)
+ self.assertEqual(float(p[300:].abs().max()), 0.0)
+ self.assertLess(float((p[:300] - ref_steps(l[:300], T, k, tp)).abs().max()), 1e-6)
+
+ def test_fused_law_ties(self):
+ g = torch.Generator().manual_seed(2)
+ for prm in ((1.0, 1.0, 2, 0, 0.95), (1.0, 1.0, 3, 20, 0.95), (1 / 0.7, 1 / 0.7, 2, 0, 0.9)):
+ for _ in range(100):
+ l = (torch.randn(300, generator = g) * 2).half().float()
+ l[torch.randint(0, 300, (40,), generator = g)] = l[torch.randint(0, 300, (1,), generator = g)]
+ self.assertLess(float((ss.law(l, ("fused", prm, 300)) - ref_fused(l, prm)).abs().max()), 1e-6)
+
+ def test_exact_in_distribution(self):
+ g = torch.Generator().manual_seed(3); rng = random.Random(4)
+ V, N = 48, 40000
+ for prm in (steps_prm(ComboSampler(temperature = 1.0, top_p = 0.95), V), ("fused", (1.0, 1.0, 3, 20, 0.95), V)):
+ lt = torch.randn(V, generator = g) * 2.0; ld = lt + torch.randn(V, generator = g) * 1.2
+ p = ss.law(lt, prm); q = ss.law(ld, prm)
+ cnt = torch.zeros(V); keep = 0
+ for _ in range(N):
+ d = int(ss.draw(q, rng.random())); x = int(ss.verify(lt, q, d, prm, rng)); cnt[x] += 1; keep += (x == d)
+ m = p > 0
+ self.assertEqual(int(cnt[~m].sum()), 0)
+ e = p[m] * N; chi = float(((cnt[m] - e) ** 2 / e).sum()); dof = int(m.sum()) - 1
+ self.assertLess((chi - dof) / math.sqrt(2 * dof), 4.0)
+ self.assertLess(abs(keep / N - float(torch.minimum(p, q).sum())), 0.01)
+
+ def test_eligible(self):
+ self.assertEqual(ss.eligible(FakeJob(ComboSampler(temperature = 1.0, top_p = 0.95)))[0], "steps")
+ self.assertEqual(ss.eligible(FakeJob(ComboSampler(temperature = 1.0, top_k = 20, top_p = 0.95)))[0], "steps")
+ self.assertIsNone(ss.eligible(FakeJob(ArgmaxSampler())))
+ self.assertIsNone(ss.eligible(FakeJob(ComboSampler(temperature = 0.0))))
+ self.assertIsNone(ss.eligible(FakeJob(ComboSampler(temperature = 1.0, rep_p = 1.1))))
+ self.assertIsNone(ss.eligible(FakeJob(ComboSampler(temperature = 1.0), device_logit_mask = torch.zeros(1))))
+ self.assertIsNone(ss.eligible(FakeJob(ComboSampler(temperature = 1.0), forced_ids = [1])))
+
+if __name__ == "__main__":
+ unittest.main()