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 draft-cache fill at long context: above 16K pooled groups the blocked linear-time selection stays sparse (PfSparse) and the MTP head attends it with the sparse gather kernel (HIP when available) instead of the dense [T, N] mask + banded kernel (O(T x N) work, JIT specialisations sized by the context: > 60 s at 128K, never finishes at 256K); warm-up at load compiles the blocked + sparse draft path; CPU test
YanissAmz9be385e5d040
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex a143719..42070e7 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -14,6 +14,7 @@ from . import dense_req as _DRPF_ATTN = os.environ.get("HY4_PREFILL_ATTN", "0") in ("1", "flash")PF_ATTN_FLASH = os.environ.get("HY4_PREFILL_ATTN", "0") == "flash" # 1 = prefill rows (T > PF_ATTN_MIN): flash-style MLA kernel (prefill_attn.py)PF_ATTN_MIN = 16+PRIME_SPARSE = os.environ.get("HY4_PRIME_SPARSE", "1") == "1" # PfSparse selections of the draft-cache fill are attended sparse (see step_graph.PRIME_SPARSE)def pf_wot():return os.environ.get("HY4_PF_WOT", "0") == "1"# # HY4_PF_WOT=1: gate output written transposed [H*vd, T] so the wo GEMM reads A column-major (faster vendor kernel at K=8192-16384)@@ -299,6 +300,18 @@ class Hy4MLA:out = _hf.rmsw(out, self.post_norm, self.eps) if _hf.ENABLED else rms(out, self.eps) * self.post_normreturn None, gated, out+ def _sparse_o(self, qlat, qpe, kcache, T, sel):+ """sparse gather attention for T consecutive rows starting at sel.start (rows of kcache beyond start + T are never visible: the draft head passes N rounded up to a+ multiple of 4) -> o_lat [T, H, R] fp32; HIP kernel when available, else the Triton one; no kernel specialises on the context length"""+ from . import prefill_attn as _pa+ end = sel.start + T+ kc = kcache[:end]+ qcat = torch.cat([qlat.float(), qpe.float()], -1).clamp(-65504.0, 65504.0).half().transpose(0, 1).contiguous() # [H, T, R + P]+ o = _sp_hip_call(self, kc, T, sel, qcat)+ if o is None:+ o = _pa.mla_sparse(self.R, kc, end - T, self.scale, self.sinks, sel, qcat)+ return o.transpose(0, 1).float()+def attend(self, cur, pos, kcache, kpos, allow=None):"""cur [T, n_embd] at positions pos; kcache [N, R+rope] at kpos (includes the T new rows). -> (kqv, gated, out)"""T, H = cur.shape[0], self.H@@ -307,8 +320,9 @@ class Hy4MLA: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):+ if not (PRIME_SPARSE and cur.is_cuda):+ allow = allow.to_dense() # else: generic path below, sparse gather (draft-cache fill at long context: a dense [T, N] mask costs O(T x N) and compiles N-sized kernels)+ if allow.__class__.__name__ != "PfSparse" and self._ck_ok(cur):r = self.attend_ck(cur, pos, kcache, allow, qa)if r is not None:return r@@ -320,6 +334,8 @@ class Hy4MLA:if self.slot_base is not None: # multi-session step: kcache = the flat K slabs, row t reads its own slab (mu_slots)from . import mu_slots as _muo = _mu.mla_attend_slots(qlat, qpe, kcache, pos, self.slot_base, kpos.shape[0], self.scale, self.sinks, self.window, allow)+ elif allow.__class__.__name__ == "PfSparse": # draft-cache fill (HY4_LC_PRIME) above the blocked-selection threshold: selected groups + own open group only+ o = self._sparse_o(qlat, qpe, kcache, T, allow)elif PF_ATTN and T > PF_ATTN_MIN and qlat.is_cuda and getattr(self, "kpos_arange", False):from . import prefill_attn as _pa # prefill rows: flash-style kernel, keys visited only inside the window / causal rangeo = (_pa.mla_flash if PF_ATTN_FLASH else _pa.mla_banded)(qlat, qpe, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow)diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.pyindex a4fa72a..1427707 100644--- a/exllamav3/loader/step_graph.py+++ b/exllamav3/loader/step_graph.py@@ -31,6 +31,8 @@ MASK64 = (1 << 64) - 1PERT = None # [cap, D] fp32 noise table (measurement arms only)_IO_W = int(os.environ.get("HY4_GRAPH_IO", "64"))PRIME_IX = os.environ.get("HY4_LC_PRIME", "0") == "1" # draft-cache fill rows (T > 16) select with the prefill scorer (fp16 GEMM, exact top-k)+PRIME_SPARSE = os.environ.get("HY4_PRIME_SPARSE", "1") == "1" # draft-cache fill above PRIME_IX_BLK groups: the selection stays a PfSparse (gather kernel in Hy4MLA.attend), never a dense [T, N] mask+PRIME_IX_BLK = int(os.environ.get("HY4_PRIME_IX_BLK", "16384")) # draft-cache fill: pooled groups above this use the blocked linear-time selectionVG_RING = 4096 if int(os.environ.get("HY4_SWA_RING", "0")) else 0 # rows of the indexer (value | gate) ring: one prime call (2048 rows) + the open groupRING_ROWS = int(os.environ.get("HY4_SWA_RING", "0")) # >= 1: K rows of window layers in a ring buffer of this many rows (e.g. 1024) instead of cap rows_POOL = ThreadPoolExecutor(max_workers=_IO_W)@@ -101,6 +103,9 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):off = (pos.data_ptr() - ar.data_ptr()) // ar.element_size()if pos.dim() == 1 and 0 <= off < ar.shape[0] and Nb == Pb * k:from . import prefill_kernels as _pkm+ if Pb > PRIME_IX_BLK: # long prompt: the unblocked ix_select keeps a pow2(P)-wide row in registers (P = 65K groups at 256K: the Triton compile alone ran > 20 min at 100 % CPU)+ sel = _pkm.ix_select_blocked(_pkm.to_f16(iq), _pkm.to_f16(ix.pool[:Pb]), wt, int(off), k, ix.tail, ix.n_top, Nb)+ return sel if PRIME_SPARSE else sel.to_dense()sc = _pkm.ix_scores_fused(_pkm.to_f16(iq), _pkm.to_f16(ix.pool[:Pb]), wt, int(off), k, ix.tail)return _pkm.ix_select(sc, int(off), Nb, ix.n_top, k, ix.tail, want_bias=False)if _LS.ENABLED and ix.tail and T <= 16 and _LS._usable(iq): # HY4_LC_SPARSE: exact top-k over the pools + sparse attend (no [T, Nb] mask, no dense key scan)diff --git a/tests/test_prime_sparse_cpu.py b/tests/test_prime_sparse_cpu.pynew file mode 100644index 0000000..8f340d7--- /dev/null+++ b/tests/test_prime_sparse_cpu.py@@ -0,0 +1,48 @@+"""CPU test (TRITON_INTERPRET=1, no GPU): python test_prime_sparse_cpu.py TREE+Hy4MLA._sparse_o (draft-cache fill above the blocked-selection threshold) must equal the dense masked attention over PfSparse.to_dense(), also when the K buffer holds+rows beyond start + T (the draft head passes N rounded up to a multiple of 4: those rows are garbage / zeros and must never be read)."""+import os, sys, types+os.environ["TRITON_INTERPRET"] = "1"+os.environ["HIP_VISIBLE_DEVICES"] = ""+os.environ["CUDA_VISIBLE_DEVICES"] = ""+os.environ["HY4_PF_SPARSE_HIP"] = "0"+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, mla_hy4 as MLA++def ref64(qc, kc, scale, sinks, allow, R):+ 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(*qc.shape[:2], 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 (start, T, n_top, tail, extra) in ((37, 11, 6, 1, 3), (40, 8, 5, 0, 0), (61, 3, 5, 1, 2), (96, 17, 8, 0, 1)):+ end = start + T+ P = end // KP+ pos = torch.arange(start, end)+ sc = torch.randn(T, P)+ 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"))+ sp = PK.ix_select(sc, start, end, n_top, KP, tail, sparse=True)+ qlat = torch.randn(T, H, R) * 0.5+ qpe = torch.randn(T, H, Pd) * 0.5+ kc = torch.randn(end + extra, R + Pd) * 0.5+ kc[end:] = 1e4 # rows nobody may read+ sinks = torch.randn(H)+ ns = types.SimpleNamespace(R=R, scale=0.125, sinks=sinks, tm=None)+ o = MLA.Hy4MLA._sparse_o(ns, qlat, qpe, kc, T, sp).double()+ qc = torch.cat([qlat, qpe], -1).half().float().transpose(0, 1)+ ref = ref64(qc, kc[:end].half().float(), 0.125, sinks, sp.to_dense(), R).transpose(0, 1)+ e = float((o - ref).norm() / ref.norm())+ ok = e < 3e-3 and bool(torch.isfinite(o).all()) and o.shape == (T, H, R)+ bad += not ok+ print(f"start={start} T={T} tail={tail} extra={extra}: err={e:.2e} {"OK" if ok else "FAIL"}", flush=True)+print("ALL OK" if not bad else f"{bad} FAILED")+sys.exit(1 if bad else 0)diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex b0e9894..0796c70 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -140,6 +140,15 @@ class Hy4Engine:spec = os.environ.get("HY4_PRECAPTURE", "0")if spec != "0":self.precapture(spec)+ if os.environ.get("HY4_WARMUP_PRIME_SPARSE", "1") == "1" and os.environ.get("HY4_LC_PRIME", "0") == "1":+ # the draft-cache fill of a long prompt (> 16K groups) runs the blocked selection + sparse gather kernels: compile them now (a request must never JIT at depth)+ old, self.SG.PRIME_IX_BLK = self.SG.PRIME_IX_BLK, 0+ try:+ self.reset()+ self.prefill(ids)+ self.torch.cuda.synchronize()+ finally:+ self.SG.PRIME_IX_BLK = oldself.reset()print(f"warm-up {n} tokens: {time.perf_counter() - t0:.1f} s", flush=True)if os.environ.get("HY4_WARMUP_TAILS", "1") == "1":