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.

Hy4 MTP draft-only fast path: Q8_0 dense draft weights, fused router / attention core, rmsw norms, Q8 or vocabulary-subset draft head (HY4_MTP_FAST, HY4_MTP_HEAD)

YanissAmz21b5c869d25d
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
index 2732a05..abda83e 100644
--- a/exllamav3/loader/mtp_head.py
+++ b/exllamav3/loader/mtp_head.py
@@ -10,25 +10,54 @@ the 512-expert stacks are quantised on load to int8 + per-row scale (moe_i8.py).
so a rejected draft row is simply overwritten by the next round. Greedy chain only (argmax of the head logits)."""
from __future__ import annotations
+import os
+
import torch
from . import moe_i8 as MI
from . import step_graph as SG
from . import step_nosync as _ns
from .engram_rows import load_dense, rms
-from .hy4_forward import _mv, head_gemm
+from .hy4_forward import _mv, head_gemm, QLinear, GG_DENSE, dense_fn
from .indexer_fused import FusedKPoolIndexer
from .mla_hy4 import Hy4MLA
+def q8_0_pack(W):
+ """fp32 [N, K] (K % 32 == 0, any device) -> stored Q8_0 bytes [N, K // 32, 34] uint8 (fp16 d = amax / 127, int8 q = round(w / d))"""
+ N, K = W.shape
+ Wb = W.reshape(N, K // 32, 32)
+ d16 = (Wb.abs().amax(-1) / 127.0).half()
+ ds = d16.float()
+ q = torch.where(ds[..., None] > 0, torch.round(Wb / ds[..., None].clamp_min(1e-30)), torch.zeros_like(Wb)).clamp(-127, 127).to(torch.int8)
+ raw = torch.empty(N, K // 32, 34, dtype=torch.uint8, device=W.device)
+ raw[..., :2] = d16.contiguous().view(torch.uint8).reshape(N, K // 32, 2)
+ raw[..., 2:] = q.view(torch.uint8)
+ return raw
+
+
+def q8_linear(W, chunk=8192):
+ """fp32 [N, K] -> QLinear on Q8_0 bytes (the trunk's dense decode GEMV; the CPU test falls back to dequantised matmul)"""
+ raw = torch.cat([q8_0_pack(W[a:a + chunk]) for a in range(0, W.shape[0], chunk)], 0) if W.shape[0] > chunk else q8_0_pack(W)
+ f = dense_fn(8, W.shape[1])
+ return QLinear(raw, 8, GG_DENSE[8], f[1] if f is not None else None)
+
+
class Hy4MTP:
def __init__(self, fw, cap=None):
g, dev, il = fw.g, fw.dev, fw.n_trunk
b = f"blk.{il}."
self.fw, self.il, self.dev, self.eps = fw, il, dev, fw.eps
d = lambda n: load_dense(g, b + n).to(dev)
- self.eh, self.enorm, self.hnorm, self.shn = d("nextn.eh_proj.weight"), d("nextn.enorm.weight"), d("nextn.hnorm.weight"), d("nextn.shared_head_norm.weight")
- mla = Hy4MLA(g, il, lin=lambda n: load_dense(g, n))
+ # draft-only cheapness (HY4_MTP_FAST=1): the draft never changes the output (the trunk verifies every token), so its dense matrices are re-packed
+ # as Q8_0 bytes read by the trunk's decode GEMV, its router / attention core run the fused Triton kernels, norms are one launch
+ self.fast = os.environ.get("HY4_MTP_FAST", "0") == "1" and (dev.type == "cuda" or os.environ.get("HY4_MTP_FAST_CPU", "0") == "1")
+ def dl(n):
+ t = load_dense(g, n).to(dev)
+ return q8_linear(t) if (self.fast and t.dim() == 2 and t.shape[1] % 32 == 0 and t.shape[0] >= 64) else t
+ self.eh = dl(b + "nextn.eh_proj.weight")
+ self.enorm, self.hnorm, self.shn = d("nextn.enorm.weight"), d("nextn.hnorm.weight"), d("nextn.shared_head_norm.weight")
+ mla = Hy4MLA(g, il, lin=(lambda n: dl(n)) if self.fast else (lambda n: load_dense(g, n)))
_mv(mla, dev, torch.float32)
mla.post_norm, mla.sinks = mla.post_norm.to(dev), mla.sinks.to(dev)
mla.kpos_arange = True
@@ -36,14 +65,23 @@ class Hy4MTP:
self.mla = mla
self.attn_norm, self.ffn_norm, self.post_ffw = d("attn_norm.weight"), d("ffn_norm.weight"), d("post_ffw_norm.weight")
self.router, self.rbias = d("ffn_gate_inp.weight"), d("exp_probs_b.bias")
- self.rdown, self.rup = d("ffn_routed_down.weight"), d("ffn_routed_up.weight")
- self.shexp = [d(f"ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]
+ self.rdown, self.rup = dl(b + "ffn_routed_down.weight"), dl(b + "ffn_routed_up.weight")
+ self.shexp = [dl(b + f"ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]
self.ex = [MI.Int8Stack(g, b + f"ffn_{n}_exps.weight", dev) for n in ("gate", "up", "down")]
self.lim = float(fw.clamp[il])
names = {"attn_k": "indexer.attn_k.weight", "k_norm": "indexer.k_norm.weight", "q_b": "indexer.attn_q_b.weight", "proj": "indexer.proj.weight",
"value": "indexer_compressor_value.weight", "gate": "indexer_compressor_gate.weight", "ape": "indexer_compressor_ape.weight",
"pool_norm": "indexer_compressor_norm.weight"}
self.ix = FusedKPoolIndexer({k: d(s) for k, s in names.items()}, dev, **fw.ixc)
+ # draft head: "" = the trunk's bf16 head (Triton mat-vec), "q8" = Q8_0 copy (half the bytes), "sub<N>" = the first N vocabulary rows only (draft picks among them)
+ hm = os.environ.get("HY4_MTP_HEAD", "")
+ self.head_q8 = self.head_sub = self.ids = None
+ if hm == "q8":
+ self.head_q8 = q8_linear(fw.out_w.float())
+ elif hm.startswith("sub"):
+ n = int(hm[3:])
+ self.head_sub = fw.out_w[:n].contiguous()
+ self.ids = torch.arange(n, device=dev)
st = _ns.state(fw)
self.cap = cap or st.cap
self.ar = st.ar if st.ar.shape[0] >= self.cap else torch.arange(self.cap, device=dev)
@@ -63,10 +101,14 @@ class Hy4MTP:
def ffn(self, x):
fw = self.fw
- p = torch.sigmoid(x @ self.router.T)
- sel = torch.topk(p + self.rbias, fw.topk, dim=-1).indices
- w = torch.gather(p, 1, sel)
- w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * fw.w_scale
+ if self.fast:
+ from . import ref_fused as _RF
+ sel, w = _RF.router_select(x @ self.router.T, self.rbias, fw.topk, fw.w_scale) # one launch, lowest id on ties
+ else:
+ p = torch.sigmoid(x @ self.router.T)
+ sel = torch.topk(p + self.rbias, fw.topk, dim=-1).indices
+ w = torch.gather(p, 1, sel)
+ w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * fw.w_scale
z = x @ self.rdown.T
lat = torch.stack([MI.experts_forward(self.ex[0], self.ex[1], self.ex[2], z[r].contiguous(), sel[r].contiguous(), w[r].contiguous(), self.lim) for r in range(x.shape[0])])
gt, up, dn = self.shexp
@@ -78,18 +120,53 @@ class Hy4MTP:
"""tok device long [T] (tokens j+1 ..), h [T, D] (trunk states h_j .., or the previous y of the chain), pos device long [T] (= j .., ascending), N rows
attended (multiple of 4, > last position) -> y [T, D], logits of the LAST row [V]"""
fw, mla, eps = self.fw, self.mla, self.eps
+ nm = self._rmsw
e = _ns.embed(fw, tok)
- x = torch.cat([rms(e, eps) * self.enorm, rms(h, eps) * self.hnorm], -1) @ self.eh.T
- cur = rms(x, eps) * self.attn_norm
+ x = torch.cat([nm(e, self.enorm), nm(h, self.hnorm)], -1) @ self.eh.T
+ cur = nm(x, self.attn_norm)
self.kbuf.index_copy_(0, pos, mla.kv(cur, pos))
- qr = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, eps) * mla.q_a_norm
+ qr = nm(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.q_a_norm)
allow = SG.indexer_forward_static(self.ix, cur, qr, pos, N, self.ar)
- kqv, gated, out = mla.attend(cur, pos, self.kbuf[:N], self.ar[:N], allow)
+ if self.fast:
+ from . import ref_fused as _RF
+ old = (_RF.ENABLED, os.environ.get("HY4_REF_MLA"))
+ _RF.ENABLED = True
+ os.environ["HY4_REF_MLA"] = "1"
+ try:
+ kqv, gated, out = mla.attend(cur, pos, self.kbuf[:N], self.ar[:N], allow)
+ finally:
+ _RF.ENABLED = old[0]
+ if old[1] is None:
+ os.environ.pop("HY4_REF_MLA", None)
+ else:
+ os.environ["HY4_REF_MLA"] = old[1]
+ else:
+ kqv, gated, out = mla.attend(cur, pos, self.kbuf[:N], self.ar[:N], allow)
s1 = x + out
- f = self.ffn(rms(s1, eps) * self.ffn_norm)
- s2 = s1 + rms(f, eps) * self.post_ffw
- y = rms(s2, eps) * self.shn
- return y, head_gemm(y[-1:].float(), fw.out_w)[0]
+ f = self.ffn(nm(s1, self.ffn_norm))
+ s2 = s1 + nm(f, self.post_ffw)
+ y = nm(s2, self.shn)
+ return y, self.logits(y[-1:].float())
+
+ def _rmsw(self, x, w):
+ if self.fast:
+ from . import attn_eager as _AE
+ return _AE.rmsw(x, w, self.eps)
+ return rms(x, self.eps) * w
+
+ def logits(self, y):
+ """y [1, D] fp32 -> logits [V'] of the draft's output head (V' = N rows with HY4_MTP_HEAD=sub<N>)"""
+ if self.head_q8 is not None:
+ return self.head_q8(y)[0]
+ if self.head_sub is not None:
+ from . import head_bf16 as _HB
+ return _HB.gemv(y, self.head_sub)[0]
+ return head_gemm(y, self.fw.out_w)[0]
+
+ def pick(self, lg):
+ """greedy draft token (device long [1]) from the draft logits"""
+ t = torch.argmax(lg).reshape(1)
+ return self.ids[t] if self.ids is not None else t
def chain(self, tok_next, h, j, k):
"""greedy chain of k drafts from the pair (token j+1 = tok_next [device long [1]], trunk state h at position j): head rows j .. j+k-1 are written
@@ -99,7 +176,7 @@ class Hy4MTP:
jj = j + i
N = ((jj + 1 + 3) // 4) * 4
y, lg = self.step(tok, h, self.ar[jj:jj + 1], N)
- tok = torch.argmax(lg).reshape(1)
+ tok = self.pick(lg)
outs.append(tok)
h = y
return outs
@@ -129,7 +206,7 @@ class MTPGraph:
pos = self.inp[1:2]
for i in range(self.k):
y, lg = mt.step(tok, h, pos + i if i else pos, N)
- tok = torch.argmax(lg).reshape(1)
+ tok = mt.pick(lg)
outs.append(tok)
h = y
return torch.cat(outs)
@@ -184,11 +261,11 @@ class MTPGraphCU(MTPGraph):
mt, k = self.mt, self.k
tok, pos0 = self.inp[:a + 1], self.inp[k + 1:k + 2]
y, lg = mt.step(tok, self.hs[:a + 1], pos0 + self.arr[:a + 1], N)
- t = torch.argmax(lg).reshape(1)
+ t = mt.pick(lg)
outs, h = [t], y[-1:]
for i in range(1, k):
y, lg = mt.step(t, h, pos0 + (a + i), N)
- t = torch.argmax(lg).reshape(1)
+ t = mt.pick(lg)
outs.append(t)
h = y
return torch.cat(outs)