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
Hy4 prefill: per-query sparse gather MLA attention for DSA layers (HY4_PF_SPARSE=1): ix_select emits compact group ids, mla_sparse gathers them once per head block; CPU exactness test vs fp64 reference
YanissAmzf48b26739437
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex c81df05..5f2ca84 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -189,7 +189,10 @@ class Hy4MLA:with tm.t("attn proj"):qcat = self.q16(cur, pos, qa)with tm.t("MLA core + sinks"):- o = _pa.mla_banded(self.R, None, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow, qcat=qcat, o16=True, ht=True) # [H, T, R] fp16+ if allow.__class__.__name__ == "PfSparse": # HY4_PF_SPARSE=1: per-query gather of the selected groups+ o = _pa.mla_sparse(self.R, kcache, kcache.shape[0] - T, self.scale, self.sinks, allow, qcat) # [H, T, R] fp16+ else:+ o = _pa.mla_banded(self.R, None, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow, qcat=qcat, o16=True, ht=True) # [H, T, R] fp16with tm.t("attn proj"):with tm.t("f attend: wv_b bmm"):kv = torch.bmm(o, self._w16("wv_b").transpose(1, 2)) # [H, T, vd] fp16@@ -272,6 +275,10 @@ class Hy4MLA:T, H = cur.shape[0], self.Htm = self.tmqa, self._qa_pre = self._qa_pre, None+ if allow.__class__.__name__ == "PfSparse":+ if self._f16_ok(cur) and self.H % 32 == 0:+ return self.attend16(cur, pos, kcache, allow, qa)+ allow = allow.to_dense()if self._ck_ok(cur):r = self.attend_ck(cur, pos, kcache, allow, qa)if r is not None:diff --git a/exllamav3/loader/prefill_attn.py b/exllamav3/loader/prefill_attn.pyindex 6e6fcc9..06b798c 100644--- a/exllamav3/loader/prefill_attn.py+++ b/exllamav3/loader/prefill_attn.py@@ -258,3 +258,102 @@ def mla_banded(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None,num_warps=c["pwarps"], num_stages=c.get("qs", 1))t0 += Bqreturn o+++# ------------------------------------------------------------------------------------------------ per-query sparse gather (HY4_PF_SPARSE=1)+# DSA layers: query t attends only the groups the indexer selected for it (gidx [T, GS] group ids, nsel [T] valid count, KP keys per group) plus its own open+# group (tail keys lo_t..pos). One program = one query x a block of heads: the selected latent rows are gathered once and serve every head of the block.+# Same maths as _mla_kernel with an allow mask (masked keys contribute exactly 0); the sink joins the denominator only.+SPCFG = {"HB": 32, "BG": 16, "warps": 4, "stages": 1}+++def _mla_sparse_kernel(Q, KC, SINK, GIDX, NSEL, O, T, qstart, H, GS, scale,+ R: tl.constexpr, P: tl.constexpr, HB: tl.constexpr, BG: tl.constexpr, KP: tl.constexpr, TAIL: tl.constexpr,+ HAS_SINK: tl.constexpr):+ DC: tl.constexpr = R // 4+ D: tl.constexpr = R + P+ BK: tl.constexpr = BG * KP+ hb = tl.program_id(0)+ t = tl.program_id(1)+ pos = qstart + t+ h = hb * HB + tl.arange(0, HB)+ rowq = (h * T + t).to(tl.int64)+ cd = tl.arange(0, DC)+ cp = tl.arange(0, P)+ qp = tl.load(Q + rowq[:, None] * D + R + cp[None, :])+ if HAS_SINK:+ m = tl.load(SINK + h).to(tl.float32) * LOG2E+ l = tl.full((HB,), 1.0, dtype=tl.float32)+ else:+ m = tl.full((HB,), -1e30, dtype=tl.float32)+ l = tl.zeros((HB,), dtype=tl.float32)+ a0 = tl.zeros((HB, DC), dtype=tl.float32)+ a1 = tl.zeros((HB, DC), dtype=tl.float32)+ a2 = tl.zeros((HB, DC), dtype=tl.float32)+ a3 = tl.zeros((HB, DC), dtype=tl.float32)+ ns = tl.load(NSEL + t)+ nit = (ns + BG - 1) // BG+ if TAIL:+ lo_t = pos - (pos % KP)+ else:+ lo_t = pos - ((pos + 1) % KP) + 1+ sc = scale * LOG2E+ jb = tl.arange(0, BK)+ for it in range(0, nit + 1): # the last pass is the tail tile (own open group)+ istail = it == nit+ gi = it * BG + jb // KP+ gv = (gi < ns) & (it < nit)+ g = tl.load(GIDX + t.to(tl.int64) * GS + gi, mask=gv, other=0)+ kg = g.to(tl.int64) * KP + (jb % KP)+ kt = lo_t + jb+ kidx = tl.where(istail, kt, kg)+ kin = tl.where(istail, (kt <= pos) & (jb < KP), gv)+ krow = tl.where(kin, kidx, 0).to(tl.int64) * D+ kp = tl.load(KC + krow[:, None] + R + cp[None, :], mask=kin[:, None], other=0.0)+ s = tl.dot(qp, tl.trans(kp))+ for c in tl.static_range(4):+ qc = tl.load(Q + rowq[:, None] * D + c * DC + cd[None, :], volatile=True)+ kc = tl.load(KC + krow[:, None] + c * DC + cd[None, :], mask=kin[:, None], other=0.0)+ s = tl.dot(qc, tl.trans(kc), s)+ s = s * sc+ s = tl.where(kin[None, :], s, -1e30)+ mn = tl.maximum(m, tl.max(s, 1))+ alpha = tl.exp2(m - mn)+ p = tl.exp2(s - mn[:, None])+ p = tl.where(kin[None, :], p, 0.0)+ l = l * alpha + tl.sum(p, 1)+ p16 = p.to(tl.float16)+ v0 = tl.load(KC + krow[:, None] + 0 * DC + cd[None, :], mask=kin[:, None], other=0.0)+ a0 = tl.dot(p16, v0, a0 * alpha[:, None])+ v1 = tl.load(KC + krow[:, None] + 1 * DC + cd[None, :], mask=kin[:, None], other=0.0)+ a1 = tl.dot(p16, v1, a1 * alpha[:, None])+ v2 = tl.load(KC + krow[:, None] + 2 * DC + cd[None, :], mask=kin[:, None], other=0.0)+ a2 = tl.dot(p16, v2, a2 * alpha[:, None])+ v3 = tl.load(KC + krow[:, None] + 3 * DC + cd[None, :], mask=kin[:, None], other=0.0)+ a3 = tl.dot(p16, v3, a3 * alpha[:, None])+ m = mn+ inv = 1.0 / tl.maximum(l, 1e-30)+ lim = 65504.0+ tl.store(O + rowq[:, None] * R + 0 * DC + cd[None, :], tl.minimum(tl.maximum(a0 * inv[:, None], -lim), lim).to(tl.float16))+ tl.store(O + rowq[:, None] * R + 1 * DC + cd[None, :], tl.minimum(tl.maximum(a1 * inv[:, None], -lim), lim).to(tl.float16))+ tl.store(O + rowq[:, None] * R + 2 * DC + cd[None, :], tl.minimum(tl.maximum(a2 * inv[:, None], -lim), lim).to(tl.float16))+ tl.store(O + rowq[:, None] * R + 3 * DC + cd[None, :], tl.minimum(tl.maximum(a3 * inv[:, None], -lim), lim).to(tl.float16))+++def mla_sparse(R, kc, qstart, scale, sinks, sel, qcat, cfg=None):+ """qcat fp16 [H, T, R + P] (q16 layout, saturated), kc [N, R + P] latent rows of ALL positions (N = qstart + T), sel = PfSparse (gidx, nsel, kpool, tail),+ sinks [H] or None -> o_lat [H, T, R] fp16 (saturated). Visible keys of query t = its selected groups + its own open group."""+ c = cfg or SPCFG+ H, T, D = qcat.shape+ P = D - R+ N = kc.shape[0]+ assert N == qstart + T and sel.gidx.shape[0] == T and H % min(c["HB"], H) == 0+ HB = min(c["HB"], H)+ kc16 = kc.clamp(-65504.0, 65504.0).half().contiguous()+ qcat = qcat.contiguous()+ o = torch.empty(H, T, R, dtype=torch.float16, device=kc.device)+ sk = sinks.float().contiguous() if sinks is not None else qcat+ _mla_sparse_kernel[(H // HB, T)](qcat, kc16, sk, sel.gidx, sel.nsel, o, T, qstart, H, sel.gidx.shape[1], float(scale), R=R, P=P, HB=HB, BG=c["BG"],+ KP=int(sel.kpool), TAIL=int(bool(sel.tail)), HAS_SINK=sinks is not None, num_warps=c["warps"], num_stages=c["stages"])+ return odiff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.pyindex 8f988ca..39c924c 100644--- a/exllamav3/loader/prefill_kernels.py+++ b/exllamav3/loader/prefill_kernels.py@@ -413,7 +413,8 @@ def _pf_indexer_forward(self, x, qr, n_keys=None):N = self.n if n_keys is None else n_keysif PF_FUSE and N >= P * k:with t("f ix: select + allow + bias"):- return ix_select(sc, start, N, self.n_top, k, self.tail, want_bias=CK_BIAS[0])+ sp = PF_SPARSE and N >= SPARSE_MINN+ return ix_select(sc, start, N, self.n_top, k, self.tail, want_bias=CK_BIAS[0] and not sp, sparse=sp)with t("f ix: topk"):idx = torch.topk(sc, min(self.n_top, P), dim=1).indiceswith t("f ix: allow mask"):@@ -543,7 +544,7 @@ def ix_scores_fused(iq16, pk16, wt, start, kpool, tail):@triton.jit-def _ix_select_kernel(SC, ALLOW, BIAS, P, N, NP, start, n_top, PP: tl.constexpr, KP: tl.constexpr, TAIL: tl.constexpr, WRITE_BIAS: tl.constexpr):+def _ix_select_kernel(SC, ALLOW, BIAS, GIDX, NSEL, P, N, NP, start, n_top, PP: tl.constexpr, KP: tl.constexpr, TAIL: tl.constexpr, WRITE_BIAS: tl.constexpr, SPARSE: tl.constexpr):"""one row per program: the n_top highest scores (ties: lowest group index first; invisible groups never selected) -> group mask expanded to keys,OR the row's own open group (tail); writes allow [T, N] (int8) and optionally the CK bias [T, NP] fp16 (0 / -30000)"""r = tl.program_id(0)@@ -568,6 +569,11 @@ def _ix_select_kernel(SC, ALLOW, BIAS, P, N, NP, start, n_top, PP: tl.constexpr,need = n_top - tl.sum(gt.to(tl.int32), axis=0)rank = tl.cumsum(eq.to(tl.int32), axis=0)sel = (gt | (eq & (rank <= need))) & vis+ if SPARSE: # compact group ids (ascending) + count; the own open group is added by the attention kernel+ si = sel.to(tl.int32)+ tl.store(GIDX + r.to(tl.int64) * n_top + tl.cumsum(si, axis=0) - 1, g, mask=sel)+ tl.store(NSEL + r, tl.sum(si, axis=0))+ returnselx = tl.reshape(tl.broadcast_to(sel.to(tl.int8)[:, None], [PP, KP]), [PP * KP])j = tl.arange(0, PP * KP)if TAIL:@@ -582,14 +588,46 @@ def _ix_select_kernel(SC, ALLOW, BIAS, P, N, NP, start, n_top, PP: tl.constexpr,tl.store(BIAS + r.to(tl.int64) * NP + j2, tl.full([8], -30000.0, dtype=tl.float16), mask=j2 < NP)-def ix_select(sc, start, N, n_top, kpool, tail, want_bias=True):- """sc [T, P] fp32 (-inf = invisible) -> allow [T, N] bool (+ its CK bias [T, ceil8(N)] fp16 attached as allow._ck_bias when want_bias)"""+SPARSE_MINN = int(os.environ.get("HY4_PF_SPARSE_MINN", "0")) # HY4_PF_SPARSE=1 (per-query sparse gather attention) only when the key count N >= this+PF_SPARSE = os.environ.get("HY4_PF_SPARSE", "0") == "1"+++class PfSparse:+ """indexer selection of a prefill call without the dense mask: gidx [T, n_top] int32 group ids (ascending), nsel [T] int32 valid counts, kpool keys per group,+ tail = the own-open-group convention of the indexer. Visible keys of row t = its groups + the open group (mla_sparse); to_dense() gives the equivalent allow mask"""++ def __init__(self, gidx, nsel, kpool, tail, start, N):+ self.gidx, self.nsel, self.kpool, self.tail, self.start, self.N = gidx, nsel, kpool, bool(tail), start, N++ def to_dense(self):+ T, k = self.gidx.shape[0], self.kpool+ dev = self.gidx.device+ P = (self.N + k - 1) // k+ ok = torch.arange(self.gidx.shape[1], device=dev)[None] < self.nsel[:, None]+ gs = torch.zeros(T, P + 1, dtype=torch.bool, device=dev)+ gs.scatter_(1, torch.where(ok, self.gidx.long(), P), True)+ allow = gs[:, :P].repeat_interleave(k, dim=1)[:, :self.N].clone()+ pos = self.start + torch.arange(T, device=dev)+ lo = (pos - (pos % k)) if self.tail else (pos - ((pos + 1) % k) + 1)+ j = torch.arange(self.N, device=dev)[None]+ allow |= (j >= lo[:, None]) & (j <= pos[:, None])+ return allow+++def ix_select(sc, start, N, n_top, kpool, tail, want_bias=True, sparse=False):+ """sc [T, P] fp32 (-inf = invisible) -> allow [T, N] bool (+ its CK bias [T, ceil8(N)] fp16 attached as allow._ck_bias when want_bias);+ sparse=True -> PfSparse (compact group ids, no [T, N] mask)"""T, P = sc.shapePP = 1 << max(1, int(P).bit_length()) # strictly above P: PP * kpool >= N + 1NP = (N + 7) // 8 * 8+ if sparse:+ gidx = torch.empty(T, n_top, dtype=torch.int32, device=sc.device)+ nsel = torch.empty(T, dtype=torch.int32, device=sc.device)+ _ix_select_kernel[(T,)](sc, sc, sc, gidx, nsel, P, N, NP, start, n_top, PP=PP, KP=kpool, TAIL=int(bool(tail)), WRITE_BIAS=False, SPARSE=True, num_warps=8)+ return PfSparse(gidx, nsel, kpool, tail, start, N)allow = torch.empty(T, N, dtype=torch.bool, device=sc.device)bias = torch.empty(T, NP, dtype=torch.float16, device=sc.device) if want_bias else allow- _ix_select_kernel[(T,)](sc, allow.view(torch.int8), bias, P, N, NP, start, n_top, PP=PP, KP=kpool, TAIL=int(bool(tail)), WRITE_BIAS=bool(want_bias), num_warps=8)+ _ix_select_kernel[(T,)](sc, allow.view(torch.int8), bias, sc, sc, P, N, NP, start, n_top, PP=PP, KP=kpool, TAIL=int(bool(tail)), WRITE_BIAS=bool(want_bias), SPARSE=False, num_warps=8)if want_bias:allow._ck_bias = biasreturn allowdiff --git a/tests/test_hy4_sparse_attn_cpu.py b/tests/test_hy4_sparse_attn_cpu.pynew file mode 100644index 0000000..d55a301--- /dev/null+++ b/tests/test_hy4_sparse_attn_cpu.py@@ -0,0 +1,47 @@+"""CPU test (TRITON_INTERPRET=1, no GPU) of the per-query sparse gather attention: python test_hy4_sparse_attn_cpu.py TREE+ix_select(sparse=True) -> PfSparse must expand to exactly the dense allow mask; mla_sparse must match an fp64 reference built from that mask (masked keys contribute 0, sink in the denominator only)."""+import os, sys, types+os.environ["TRITON_INTERPRET"] = "1"+os.environ["HIP_VISIBLE_DEVICES"] = ""+os.environ["CUDA_VISIBLE_DEVICES"] = ""+import torch+tree = sys.argv[1]+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 prefill_kernels as PK, prefill_attn as PA++def ref64(qc, kc, scale, sinks, allow, R):+ H, T, D = qc.shape+ s = torch.einsum("htd,nd->htn", qc.double(), kc.double()) * scale+ s = s.masked_fill(~allow[None], float("-inf"))+ sk = sinks.double()[:, None, None].expand(H, T, 1)+ p = torch.softmax(torch.cat([s, sk], -1), -1)[..., :-1]+ return torch.einsum("htn,nr->htr", p, kc.double()[:, :R])++torch.manual_seed(0)+R, Pd, H, KP = 64, 16, 16, 4+bad = 0+for (qstart, T, n_top, tail) in ((0, 9, 6, 1), (0, 9, 6, 0), (37, 11, 6, 1), (37, 11, 6, 0), (50, 8, 3, 1), (4, 5, 20, 0), (61, 3, 5, 1), (62, 2, 5, 0), (127, 17, 8, 0)):+ N = qstart + T+ P = N // KP+ pos = torch.arange(qstart, N)+ sc = torch.randn(T, P)+ if P > 3: sc[:, :2] = sc[:, 2:3] # ties: lowest group index must win in both paths+ gend = torch.arange(P) * KP + KP - 1+ vis = (gend[None] < pos[:, None]) if tail else (gend[None] <= pos[:, None])+ sc = sc.masked_fill(~vis, float("-inf"))+ dense = PK.ix_select(sc, qstart, N, n_top, KP, tail, want_bias=False)+ sp = PK.ix_select(sc, qstart, N, n_top, KP, tail, sparse=True)+ same = bool((sp.to_dense() == dense).all())+ qc = (torch.randn(H, T, R + Pd) * 0.5).half()+ kc = (torch.randn(N, R + Pd) * 0.5).half()+ sinks = torch.randn(H)+ scale = 0.125+ ref = ref64(qc, kc.float(), scale, sinks, dense, R)+ o = PA.mla_sparse(R, kc.float(), qstart, scale, sinks, sp, qc, cfg={"HB": 16, "BG": 4, "warps": 4, "stages": 1}).double()+ e = float((o - ref).norm() / ref.norm())+ ok = same and e < 3e-3 and bool(torch.isfinite(o).all())+ bad += not ok+ print(f"qstart={qstart} T={T} n_top={n_top} tail={tail}: mask_same={same} err_sparse={e:.2e} nsel_max={int(sp.nsel.max())} {'OK' if ok else 'FAIL'}", flush=True)+print("ALL OK" if not bad else f"{bad} FAILED")+sys.exit(1 if bad else 0)