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 draft cache fill: MTP expert rows grouped per expert (one pass per chunk of 2048 rows instead of one kernel pair per row)

YanissAmz66a531fe3a92
diff --git a/exllamav3/loader/moe_i8.py b/exllamav3/loader/moe_i8.py
index c30561f..dc7e838 100644
--- a/exllamav3/loader/moe_i8.py
+++ b/exllamav3/loader/moe_i8.py
@@ -84,3 +84,29 @@ def experts_forward(gate, up, down, z, sel, w, lim):
out = torch.empty(down.N, dtype=torch.float32, device=z.device)
_k_down[(triton.cdiv(down.N, 8),)](down.q, down.s, sel, h, w, out, down.N, down.K, S=S, BN=8, BK=128, num_warps=4)
return out
+
+
+def experts_rows(gate, up, down, z, sel, w, lim):
+ """many rows at once (prefill of the draft cache): z [T, K] fp32, sel [T, S] int64, w [T, S] fp32 -> lat [T, down.N] fp32.
+ Rows are grouped per expert (each expert's int8 stack is read once per call) and run as fp16 GEMMs with fp32 accumulation; same maths as experts_forward."""
+ T, S = sel.shape
+ flat = sel.reshape(-1)
+ order = torch.argsort(flat, stable=True)
+ counts = torch.bincount(flat, minlength=gate.E).tolist()
+ out = torch.zeros(T, down.N, dtype=torch.float32, device=z.device)
+ zh = z.clamp(-6e4, 6e4).to(torch.float16)
+ wf = w.reshape(-1)
+ pos = 0
+ for e, c in enumerate(counts):
+ if c == 0:
+ continue
+ pr = order[pos:pos + c]
+ pos += c
+ rows = pr // S
+ x = zh[rows]
+ g = (x @ gate.q[e].to(torch.float16).T).float() * gate.s[e]
+ u = (x @ up.q[e].to(torch.float16).T).float() * up.s[e]
+ h = (torch.nn.functional.silu(g.clamp(max=lim)) * u.clamp(-lim, lim)).to(torch.float16)
+ d = (h @ down.q[e].to(torch.float16).T).float() * down.s[e]
+ out.index_add_(0, rows, d * wf[pr][:, None])
+ return out
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
index b40f89a..dcc1e85 100644
--- a/exllamav3/loader/mtp_head.py
+++ b/exllamav3/loader/mtp_head.py
@@ -113,7 +113,10 @@ class Hy4MTP:
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])])
+ if x.shape[0] > 16: # draft-cache fill of a prompt: rows grouped per expert
+ lat = MI.experts_rows(self.ex[0], self.ex[1], self.ex[2], z.float().contiguous(), sel, w, self.lim)
+ else:
+ 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
sh = (torch.nn.functional.silu(x @ gt.T) * (x @ up.T)) @ dn.T
return lat @ self.rup.T + sh
diff --git a/tests/test_hy4_moe_rows.py b/tests/test_hy4_moe_rows.py
new file mode 100644
index 0000000..3843885
--- /dev/null
+++ b/tests/test_hy4_moe_rows.py
@@ -0,0 +1,45 @@
+"""CPU test: moe_i8.experts_rows (rows grouped per expert) equals the per-row maths of the draft head expert kernels. Needs torch + triton importable."""
+import os
+import sys
+import types
+import unittest
+
+import torch
+
+TREE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n)
+ m.__path__ = [os.path.join(TREE, "exllamav3", s)]
+ sys.modules[n] = m
+from exllamav3.loader import moe_i8 as MI # noqa: E402
+
+
+class Stack:
+ def __init__(self, E, N, K):
+ self.E, self.N, self.K = E, N, K
+ self.q = torch.randint(-127, 128, (E, N, K), dtype=torch.int8)
+ self.s = torch.rand(E, N) * 0.02 / 127
+
+
+class Rows(unittest.TestCase):
+ def test_matches_per_row_reference(self):
+ torch.manual_seed(0)
+ E, N, K, T, S, lat = 8, 64, 64, 40, 3, 32
+ g, u, d = Stack(E, N, K), Stack(E, N, K), Stack(E, lat, N)
+ z = torch.randn(T, K)
+ sel = torch.stack([torch.randperm(E)[:S] for _ in range(T)])
+ w = torch.rand(T, S)
+ got = MI.experts_rows(g, u, d, z, sel, w, 10.0)
+ ref = torch.zeros(T, lat)
+ for t in range(T):
+ for j in range(S):
+ e = int(sel[t, j])
+ gg = ((g.q[e].float() @ z[t]) * g.s[e]).clamp(max=10.0)
+ uu = ((u.q[e].float() @ z[t]) * u.s[e]).clamp(-10.0, 10.0)
+ h = torch.nn.functional.silu(gg) * uu
+ ref[t] += w[t, j] * ((d.q[e].float() @ h) * d.s[e])
+ self.assertLess(float((got - ref).abs().max() / ref.abs().max()), 5e-3)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/hy4/engine.py b/tools/hy4/engine.py
index 3a54419..d4adbdb 100644
--- a/tools/hy4/engine.py
+++ b/tools/hy4/engine.py
@@ -18,7 +18,7 @@ import types
from typing import Callable
CHUNK_DEFAULT = 8192
-PRIME_ROWS = 512 # rows per batched MTP draft-cache fill call
+PRIME_ROWS = 2048 # rows per batched MTP draft-cache fill call
def _stub_package(tree: str):
@@ -141,6 +141,8 @@ class Hy4Engine:
tok = torch.tensor(ids, dtype=torch.long, device=self.dev)
ar = MT.ar
s = lo
+ f16 = os.environ.get("HY4_PF_F16")
+ os.environ["HY4_PF_F16"] = "0" # the fp16 attention chain is tuned for the trunk's matrices; the draft layer takes the generic prefill path
try:
while s < n - 1:
e = min(n - 1, s + PRIME_ROWS)
@@ -154,6 +156,11 @@ class Hy4Engine:
for j in range(max(0, n - 129), n - 1):
MT.chain(tok[j + 1:j + 2], H[j:j + 1], j, 1)
self.last_stats["prime_mode"] = "per-row tail 128 (batched failed)"
+ finally:
+ if f16 is None:
+ os.environ.pop("HY4_PF_F16", None)
+ else:
+ os.environ["HY4_PF_F16"] = f16
# ------------------------------------------------------------------------------------------ generate
def generate(self, ids: list[int], max_new: int, on_tokens: Callable[[list[int]], bool], speculative: bool = True,