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
MTP draft head: adaptive vocabulary subset of frequent 128-id blocks, per-row miss rule, multi-row draft steps
YanissAmz3e087163c2ab
diff --git a/exllamav3/architecture/qwen3_5_mtp.py b/exllamav3/architecture/qwen3_5_mtp.pyindex b243697..bf76eb3 100644--- a/exllamav3/architecture/qwen3_5_mtp.py+++ b/exllamav3/architecture/qwen3_5_mtp.py@@ -19,6 +19,18 @@ if TYPE_CHECKING:from .qwen3_5 import Qwen3_5Config, Qwen3_5MoeConfig+def exl3_block_subhead(inner, blocks):+ """The EXL3 linear `inner` restricted to the given 128-row output blocks (sorted LongTensor): output column j of the+ result is column blocks[j // 128] * 128 + j % 128 of `inner`, bit for bit."""+ from ..modules.quant.exl3 import LinearEXL3+ dev = inner.trellis.device+ rows = (blocks.to(dev)[:, None] * 128 + torch.arange(128, device = dev)).reshape(-1)+ tiles = (blocks.to(dev)[:, None] * 8 + torch.arange(8, device = dev)).reshape(-1)+ return LinearEXL3(None, inner.in_features, rows.numel(), suh = inner.suh, svh = inner.svh[rows].contiguous(),+ trellis = inner.trellis[:, tiles].contiguous(), mcg = inner.mcg_tensor,+ mul1 = inner.mul1_tensor, out_dtype = inner.out_dtype)++class Qwen3_5MTPModel(Model):def __init__(@@ -229,28 +241,103 @@ class Qwen3_5MTPModel(Model):return {}- def _draft_subhead(self, lm):- """The draft head restricted to the first EXL3_DRAFT_VOCAB vocabulary rows (a multiple of 128: the head's output- Hadamard works on 128-row blocks, so a prefix of whole blocks is a self-contained EXL3 linear with the same- trellis tiles). None when off or when the head is not a plain integer-K EXL3 linear. Every draft is verified by the- target, so a draft that misses a rare id only costs an accept, never changes the text."""+ @staticmethod+ def _head_plain(lm):+ inner = getattr(lm, "inner", None)+ return inner is not None and type(inner).__name__ == "LinearEXL3" and isinstance(inner.K, int) \+ and inner.bias is None and lm.pre_scale == 1.0 and lm.post_scale == 1.0 and lm.softcap == 0.0++ def _draft_subhead(self, lm, blocks = None):+ """The draft head restricted to whole 128-row blocks of the vocabulary (the head's output Hadamard works on 128-row+ blocks, so any set of whole blocks is a self-contained EXL3 linear with the same trellis tiles). blocks = None: the+ first EXL3_DRAFT_VOCAB rows. Else a sorted LongTensor of block numbers. None when off or when the head is not a plain+ integer-K EXL3 linear. Every draft is verified by the target, so a draft that misses a rare id only costs an accept,+ never changes the text."""n = int(os.environ.get("EXL3_DRAFT_VOCAB", "0") or 0) // 128 * 128if n <= 0:return None- cache = self.__dict__.setdefault("_dsub", {})- if n in cache:- return cache[n]- sub = None- inner = getattr(lm, "inner", None)- if inner is not None and type(inner).__name__ == "LinearEXL3" and isinstance(inner.K, int) \- and inner.bias is None and lm.pre_scale == 1.0 and lm.post_scale == 1.0 and lm.softcap == 0.0 \- and n < lm.out_features:- from ..modules.quant.exl3 import LinearEXL3- sub = LinearEXL3(None, inner.in_features, n, suh = inner.suh, svh = inner.svh[:n].contiguous(),- trellis = inner.trellis[:, :n // 16].contiguous(), mcg = inner.mcg_tensor,- mul1 = inner.mul1_tensor, out_dtype = inner.out_dtype)- cache[n] = sub- return sub+ if not self._head_plain(lm):+ return None+ inner = lm.inner+ from ..modules.quant.exl3 import LinearEXL3+ if blocks is None:+ cache = self.__dict__.setdefault("_dsub", {})+ if n in cache:+ return cache[n]+ sub = None+ if n < lm.out_features:+ sub = LinearEXL3(None, inner.in_features, n, suh = inner.suh, svh = inner.svh[:n].contiguous(),+ trellis = inner.trellis[:, :n // 16].contiguous(), mcg = inner.mcg_tensor,+ mul1 = inner.mul1_tensor, out_dtype = inner.out_dtype)+ cache[n] = sub+ return sub+ return exl3_block_subhead(inner, blocks)++ def _adapt_state(self, lm):+ """Adaptive draft-head subset (EXL3_DRAFT_ADAPT, default on when EXL3_DRAFT_VOCAB is set; 0 = the fixed prefix).+ Counts the head's own argmax ids per 128-id block (every step while the full head runs, the probe steps while the+ subset runs), then keeps the most frequent blocks that cover EXL3_DRAFT_COVER (default 0.99) of the counts, at most+ EXL3_DRAFT_VOCAB rows. Keyed on the model's own token statistics, no language or model list."""+ st = self.__dict__.get("_dad")+ if st is None:+ nb = lm.out_features // 128+ lim = getattr(self, "vocab_limit", None) or self.attached_model().config.vocab_size+ st = self.__dict__["_dad"] = {+ "counts": torch.zeros(nb, dtype = torch.float32, device = lm.inner.trellis.device),+ "seen": 0, "built_at": 0, "numeric": 0.0, "member": None, "probes": 0, "misses": 0.0, "sub": None, "gmap": None, "ok_blocks": lim // 128,+ "calls": 0, "ema": 0.0, "on": False, "nbuilt": 0, "vs": self.attached_model().config.vocab_size,+ "warm": int(os.environ.get("EXL3_DRAFT_WARM", "2048") or 2048),+ "maxmiss": float(os.environ.get("EXL3_DRAFT_MAXMISS", "0.05") or 0.05),+ "log": bool(os.environ.get("EXL3_DRAFT_ADAPT_LOG")),+ "every": int(os.environ.get("EXL3_DRAFT_PROBE", "16") or 16), # the probe runs the full head too: 1.0 ms at 4 rows+ }+ path = os.environ.get("EXL3_DRAFT_COUNTS")+ if path and os.path.exists(path):+ try:+ c = torch.load(path, map_location = st["counts"].device)+ if c.shape == st["counts"].shape:+ prior = float(os.environ.get("EXL3_DRAFT_PRIOR", "20000") or 20000) # the file weighs this many rows: the live ids take over+ st["counts"] += c.float() * (prior / max(float(c.sum().item()), 1.0))+ st["seen"] = int(os.environ.get("EXL3_DRAFT_WARM", "2048") or 2048) # warm start: the first step builds+ except Exception as e:+ print(f"[draft-head] counts file ignored: {e}", flush = True)+ return st++ def _adapt_build(self, lm, st):+ """(Re)build the subset from the counts. Blocks holding ids above the real vocabulary are left out (a draft there+ is rejected for sure); the counts decay by half so a change of language takes over."""+ cap = int(os.environ.get("EXL3_DRAFT_VOCAB", "0") or 0) // 128+ cover = float(os.environ.get("EXL3_DRAFT_COVER", "0.99") or 0.99)+ c = st["counts"][:st["ok_blocks"]]+ tot = float(c.sum().item())+ order = torch.argsort(c, descending = True, stable = True)+ cum = torch.cumsum(c[order], 0) / max(tot, 1.0)+ k = int(torch.searchsorted(cum, torch.tensor(cover, device = cum.device)).item()) + 1+ k = max(int(os.environ.get("EXL3_DRAFT_MINROWS", "49152") or 0) // 128, k) # a short calibration under-counts the tail+ k = max(2, min(k + (k & 1), cap, order.numel())) # an even number of blocks: the 1-2 row int8 GEMV needs n % 256 == 0+ blocks = torch.sort(order[:k]).values+ sub = self._draft_subhead(lm, blocks)+ if sub is None:+ return False+ st["sub"] = sub+ st["member"] = torch.zeros(st["counts"].numel(), dtype = torch.bool, device = blocks.device)+ st["member"][blocks] = True+ st["gmap"] = (blocks[:, None] * 128 + torch.arange(128, device = blocks.device)).reshape(-1)+ st["built_at"] = st["seen"]+ st["nbuilt"] += 1+ path = os.environ.get("EXL3_DRAFT_COUNTS")+ if path:+ try:+ torch.save(st["counts"].cpu(), path + ".tmp"); os.replace(path + ".tmp", path)+ except OSError:+ pass+ st["counts"] *= 0.5+ st["ema"] = 0.0+ st["on"] = True+ if st["log"]:+ print(f"[draft-head] subset #{st['nbuilt']}: {k * 128} rows, covers {float(cum[k - 1]):.4f} of {int(tot)} counts "+ f"(seen {st['seen']})", flush = True)+ return Truedef sample_from_state(self,@@ -261,20 +348,77 @@ class Qwen3_5MTPModel(Model):ll = self.attached_model().logit_layer_idxlm = self.attached_model().modules[ll]logits = lm.prepare_for_device(state, params)- # EXL3_DRAFT_VOCAB=N: 1-row draft steps read only the first N vocabulary rows of the head (the common BPE ids).- # Every 8th step runs both heads and compares the argmax: a language whose tokens sit above N (French, CJK ...)- # switches the subset off until the probes agree again.- sub = self._draft_subhead(lm) if state.shape[0] * state.shape[1] == 1 and not params.get("export_draft_logits") else None+ # EXL3_DRAFT_VOCAB=N: draft steps read only part of the head. Every EXL3_DRAFT_PROBE-th step (16) runs both heads and compares the argmax+ # per row: a language whose tokens sit outside the subset switches it off until the probes agree again.+ # Adaptive (default): the subset is the most frequent 128-id blocks of the head's own argmax ids, built after+ # EXL3_DRAFT_WARM rows and rebuilt when the probes disagree. Fixed (EXL3_DRAFT_ADAPT=0): the first N rows, 1-row steps only.+ sub = None+ adapt = None+ mode = self.__dict__.get("_dmode")+ if mode is None: # read once: this runs on every draft step+ mode = self._dmode = 0+ if int(os.environ.get("EXL3_DRAFT_VOCAB", "0") or 0) >= 128:+ mode = self._dmode = (2 if os.environ.get("EXL3_DRAFT_ADAPT", "1") != "0" else 1) if self._head_plain(lm) else 0+ if mode and not params.get("export_draft_logits"):+ if mode == 2:+ adapt = self._adapt_state(lm)+ sub = adapt["sub"]+ elif state.shape[0] * state.shape[1] == 1:+ sub = self._draft_subhead(lm)+ vs = adapt["vs"] if adapt is not None else self.attached_model().config.vocab_size+ if adapt is not None:+ rows = state.shape[0] * state.shape[1]+ adapt["calls"] += 1+ probe = adapt["calls"] % adapt["every"] == 0+ if sub is None or not adapt["on"] and not probe:+ # cold (no subset yet) or off: the full head, counting its argmax+ fl = lm.forward(logits, params)[..., :vs].float()+ fconf, fids = torch.max(fl, dim = -1)+ adapt["counts"].index_add_(0, (fids.reshape(-1) // 128), torch.ones(rows, device = fids.device))+ adapt["seen"] += rows+ if adapt["seen"] - adapt["built_at"] >= adapt["warm"]:+ self._adapt_build(lm, adapt)+ if params.get("export_draft_conf"):+ params["draft_conf"] = fconf+ params["draft_p"] = (1.0 / torch.exp(fl - fconf.unsqueeze(-1)).sum(-1)).reshape(-1)+ return fids+ sl = sub.forward(logits, params).float()+ conf, li = torch.max(sl, dim = -1)+ ids = adapt["gmap"][li]+ pp = (1.0 / torch.exp(sl - conf.unsqueeze(-1)).sum(-1)).reshape(-1) # max probability over the subset+ if probe:+ fl = lm.forward(logits, params)[..., :vs].float()+ fconf, fids = torch.max(fl, dim = -1)+ # per row, not "any row". A row whose full argmax sits inside the subset but differs (fp16 tie broken the other way+ # by the other GEMV shape) costs nothing: only an argmax outside the subset can never be drafted.+ out = ~adapt["member"][fids // 128]+ miss, num = (float(v) for v in torch.stack((out.float().mean(), (fids != ids).float().mean())).tolist())+ adapt["numeric"] += num - miss+ adapt["ema"] += (miss - adapt["ema"]) / 32 # a row that misses costs ~one accepted token in 1.5: the break-even rate is a few %+ adapt["counts"].index_add_(0, (fids.reshape(-1) // 128), torch.ones(rows, device = fids.device))+ adapt["seen"] += rows+ adapt["probes"] += 1+ adapt["misses"] += miss+ if adapt["log"] and adapt["probes"] % 25 == 0:+ print(f"[draft-head] {adapt['probes']} probes, row miss rate {adapt['misses'] / adapt['probes']:.4f} (+{adapt['numeric'] / adapt['probes']:.4f} fp16 ties), "+ f"on={adapt['on']}, subset {adapt['sub'].out_features} rows", flush = True)+ adapt["on"] = adapt["ema"] < adapt["maxmiss"]+ conf, ids = fconf, fids+ pp = (1.0 / torch.exp(fl - fconf.unsqueeze(-1)).sum(-1)).reshape(-1)+ params["draft_p"] = pp+ if params.get("export_draft_conf"):+ params["draft_conf"] = conf+ return idsif sub is not None:st = self.__dict__.setdefault("_dsub_st", {"calls": 0, "ema": 0.0, "on": True})st["calls"] += 1probe = st["calls"] % 8 == 0if st["on"] or probe:- sl = sub.forward(logits, params)[..., :min(sub.out_features, self.attached_model().config.vocab_size)].float()+ sl = sub.forward(logits, params)[..., :min(sub.out_features, vs)].float()conf, ids = torch.max(sl, dim = -1)pp = (1.0 / torch.exp(sl - conf.unsqueeze(-1)).sum(-1)).reshape(-1) # max probability over the subsetif probe:- fl = lm.forward(logits, params)[..., :self.attached_model().config.vocab_size].float()+ fl = lm.forward(logits, params)[..., :vs].float()fconf, fids = torch.max(fl, dim = -1)miss = float((fids != ids).any().item())st["ema"] = 0.9 * st["ema"] + 0.1 * missdiff --git a/tests/test_draft_head_blocks_.py b/tests/test_draft_head_blocks_.pynew file mode 100644index 0000000..1de1470--- /dev/null+++ b/tests/test_draft_head_blocks_.py@@ -0,0 +1,45 @@+"""Draft head restricted to a set of 128-row blocks: column j of the restricted EXL3 linear is column blocks[j // 128] * 128 + j % 128+of the full one, to fp16 rounding (the accumulation order follows n), at 1..16 rows (the draft steps of N requests). Needs a CUDA device."""+import os, sys+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+try:+ import pytest+except ImportError: # plain-python run (the serving venv ships no pytest)+ pytest = None+import torch+from exllamav3.architecture.qwen3_5_mtp import exl3_block_subhead+from exllamav3.modules.quant.exl3 import LinearEXL3++if pytest is not None:+ pytestmark = pytest.mark.skipif(not torch.cuda.is_available(), reason = "needs CUDA")++def check(K, mul1):+ torch.manual_seed(K * 10 + mul1)+ k, nb = 512, 24+ n = nb * 128+ dev = "cuda"+ trellis = torch.randint(-32768, 32767, (k // 16, n // 16, 16 * K), dtype = torch.short, device = dev)+ suh = (torch.randint(0, 2, (k,), device = dev) * 2 - 1).half()+ svh = torch.randn((n,), device = dev).half()+ code = torch.ones((), dtype = torch.int32, device = dev)+ full = LinearEXL3(None, k, n, suh = suh, svh = svh, trellis = trellis, mcg = None if mul1 else code, mul1 = code if mul1 else None)+ blocks = torch.tensor([0, 3, 4, 11, 17, 23])+ sub = exl3_block_subhead(full, blocks)+ cols = (blocks[:, None] * 128 + torch.arange(128))[:].reshape(-1).to(dev)+ for rows in (1, 2, 4, 8, 16):+ x = (torch.randn((rows, k), device = dev) * 1e-2).half()+ yf = full.forward(x.clone(), {})+ ys = sub.forward(x.clone(), {})+ assert ys.shape == (rows, cols.numel())+ d = (ys.float() - yf[:, cols].float()).abs().max().item()+ # the split-K decomposition of the GEMV / the kernel family follows n: same products, fp16 accumulation order differs+ assert d < 5e-3 * max(1.0, yf.float().abs().max().item()), f"K={K} rows={rows}: max diff {d}"+++if pytest is not None:+ test_block_subhead_columns = pytest.mark.parametrize("K", [4, 5])(pytest.mark.parametrize("mul1", [True, False])(check))++if __name__ == "__main__":+ for K in (4, 5):+ for mul1 in (True, False):+ check(K, mul1); print("ok", K, mul1)diff --git a/tools/qwen/draft_counts.py b/tools/qwen/draft_counts.pynew file mode 100644index 0000000..dc28823--- /dev/null+++ b/tools/qwen/draft_counts.py@@ -0,0 +1,24 @@+"""draft_counts.py MODEL_DIR OUT.pt FILE... : per-128-id-block token counts of a calibration corpus (any mix of languages / code),+the seed of the adaptive draft-head subset (EXL3_DRAFT_COUNTS=OUT.pt, see exllamav3/architecture/qwen3_5_mtp.py). Tokenizer only, no GPU."""+import sys, os, json+import torch+from tokenizers import Tokenizer++def main():+ model, out, files = sys.argv[1], sys.argv[2], sys.argv[3:]+ cfg = json.load(open(os.path.join(model, "config.json")))+ vocab = (cfg.get("text_config") or cfg)["vocab_size"]+ tk = Tokenizer.from_file(os.path.join(model, "tokenizer.json"))+ counts = torch.zeros((vocab + 127) // 128, dtype = torch.float32)+ n = 0+ for f in files:+ try:+ ids = tk.encode(open(f, errors = "strict").read()[:200000]).ids+ except (UnicodeDecodeError, OSError):+ continue+ counts += torch.bincount(torch.tensor(ids, dtype = torch.long) // 128, minlength = counts.numel())[:counts.numel()].float()+ n += len(ids)+ torch.save(counts, out)+ print(f"{n} tokens, {int((counts > 0).sum())} of {counts.numel()} blocks seen -> {out}")++main()diff --git a/tools/qwen/spec_policy.py b/tools/qwen/spec_policy.pyindex 579721f..7efb8a4 100644--- a/tools/qwen/spec_policy.py+++ b/tools/qwen/spec_policy.py@@ -697,7 +697,7 @@ def install(g, dm, model, thf=0.6, thv=0.3, maxd=3, ngram=None, stats=None, ruleif st["mode"] == "mtp" and not getattr(rule, "needs_p", True):return idsif st["mode"] == "mtp":- if dp is not None: pt = dp.reshape(())+ if dp is not None: pt = dp.reshape(-1).max() # one value per row of a multi-request step: the max, as softmax(cap["lg"]).max() belowelse: pt = torch.softmax(cap["lg"][..., :model.config.vocab_size].float().reshape(-1, model.config.vocab_size), -1).max()i = st["i"]if fixed is not None: