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 prefill: un-absorbed MLA attention through CK fmha_fwd hd 256/256 (sink, sliding window and indexer mask inside), HY4_PF_CK=1 opt-in, falls back to the Triton banded path: 8K chunk 14.1 -> 12.9 s, MLA core 2.72 -> 2.25 s, q rope 0.47 -> 0.11 s

YanissAmz47de2c4c71d5
diff --git a/exllamav3/loader/ck_mla.py b/exllamav3/loader/ck_mla.py
new file mode 100644
index 0000000..329cea2
--- /dev/null
+++ b/exllamav3/loader/ck_mla.py
@@ -0,0 +1,57 @@
+"""CK fmha_fwd (hd 256, fp16, batch 1) behind ckmla_fwd, for un-absorbed MLA / any MHA prefill with strided operands.
+fmha(q, k, v, scale, sink=None, bias=None, window=0): q [T, H, D], k [N, H, D], v [N, H, Dv] (any strides, last dim contiguous, row / head strides
+multiples of 8), causal bottom-right (query t sees keys <= N - T + t), window > 0: only the last `window` keys; sink [H] fp32 (learnable softmax sink, in
+scaled-logit space: it joins the denominator only); bias [T, N] fp16 elementwise (row stride multiple of 8) added to the scaled logits.
+Returns o [T, H, Dv] fp16, or None when the library is missing / declines (caller keeps its fallback). Library: EXL3_CKMLA_SO or
+~/.cache/kyojin/ck-fmha/libckmla.so (tools/strix_halo/ck_fmha/build_mla.sh)."""
+import ctypes, os
+from pathlib import Path
+import torch
+
+_fn = None
+_tried = False
+
+
+def _load():
+ global _fn, _tried
+ if _tried:
+ return _fn
+ _tried = True
+ so = Path(os.environ.get("EXL3_CKMLA_SO") or Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "kyojin" / "ck-fmha" / "libckmla.so")
+ try:
+ f = ctypes.CDLL(str(so)).ckmla_fwd
+ f.restype = ctypes.c_float
+ f.argtypes = [ctypes.c_void_p] * 6 + [ctypes.c_int] * 6 + [ctypes.c_float] + [ctypes.c_long] * 9 + [ctypes.c_int, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
+ _fn = f
+ except OSError:
+ _fn = None
+ return _fn
+
+
+def available():
+ return _load() is not None
+
+
+def fmha(q, k, v, scale, sink=None, bias=None, window=0, out=None, time_it=False):
+ f = _load()
+ if f is None:
+ return None
+ T, H, D = q.shape
+ N, Hk, Dk = k.shape
+ Dv = v.shape[2]
+ if D != 256 or Dv != 256 or Hk != H or q.dtype != torch.float16 or q.stride(2) != 1 or k.stride(2) != 1 or v.stride(2) != 1:
+ return None
+ if any(s % 8 for s in (q.stride(0), q.stride(1), k.stride(0), k.stride(1), v.stride(0), v.stride(1))):
+ return None
+ o = out if out is not None else torch.empty(T, H, Dv, dtype=torch.float16, device=q.device)
+ if bias is not None and (bias.dtype != torch.float16 or bias.stride(1) != 1 or bias.stride(0) % 8):
+ return None
+ sk = sink.float().contiguous() if sink is not None else None
+ stream = torch.cuda.current_stream(q.device).cuda_stream
+ r = f(ctypes.c_void_p(q.data_ptr()), ctypes.c_void_p(k.data_ptr()), ctypes.c_void_p(v.data_ptr()), ctypes.c_void_p(o.data_ptr()),
+ ctypes.c_void_p(bias.data_ptr() if bias is not None else 0), ctypes.c_void_p(sk.data_ptr() if sk is not None else 0),
+ T, N, H, H, D, Dv, float(scale), q.stride(0), q.stride(1), k.stride(0), k.stride(1), v.stride(0), v.stride(1), o.stride(0), o.stride(1),
+ bias.stride(0) if bias is not None else 0, int(window - 1) if window else 0, 1, ctypes.c_void_p(stream), 1 if time_it else 0)
+ if r < 0:
+ return None
+ return (o, r) if time_it else o
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index 6c2ab42..f4ea423 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -196,11 +196,78 @@ class Hy4MLA:
out = rms(out, self.eps) * self.post_norm if self.post_norm is not None else out
return None, gated, out
+ def _ck_ok(self, cur):
+ """un-absorbed CK path (HY4_PF_CK=1): prefill rows >= 1024, fp16 chain, hd == vd == 256 (nope + rope), R == 512, libckmla loadable"""
+ if os.environ.get("HY4_PF_CK", "0") != "1" or not self._f16_ok(cur) or cur.shape[0] < int(os.environ.get("HY4_PF_CK_MINT", "1024")):
+ return False
+ from . import ck_mla
+ return self.hd == 256 and self.vd == 256 and self.R == 512 and self.rope_dim == 64 and ck_mla.available()
+
+ def _kvw(self):
+ w = self.__dict__.get("_kvw_c")
+ if w is None:
+ from . import prefill_unabs as _pu
+ w = self._kvw_c = _pu.kv_weight(self._w16("wk_b"), self._w16("wv_b"))
+ return w
+
+ def attend_ck(self, cur, pos, kcache, allow, qa):
+ """prefill attention in the un-absorbed form: K / V decompressed from the latent cache by one GEMM per call, CK fmha (hd 256 / 256) with the
+ sink, the sliding window and the indexer mask (fp16 elementwise bias) inside; None when CK declines (caller keeps attend16)"""
+ from . import prefill_kernels as _pk, prefill_unabs as _pu, ck_mla
+ T, H, R, P = cur.shape[0], self.H, self.R, self.rope_dim
+ tm = self.tm
+ N = kcache.shape[0]
+ with tm.t("attn proj"):
+ with tm.t("f q: wq_a mm"):
+ if qa is None:
+ qa = cur @ self.wq_a.T
+ with tm.t("f q: norm"):
+ qr = rms(qa, self.eps) * self.q_a_norm
+ with tm.t("f q: wq_b mm"):
+ q = _pk.qdense_raw16(qr, self.wq_b.packed, tm)
+ with tm.t("f q: rope"):
+ rc = pos.__dict__.setdefault("_rope_tabs", {})
+ if self.theta not in rc:
+ th = pos.double()[:, None] * (self.theta ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=pos.device) / P))[None, :]
+ rc[self.theta] = (th.cos().float().contiguous(), th.sin().float().contiguous())
+ _pu.qrope_inplace(q, rc[self.theta][0], rc[self.theta][1], H, self.hd, self.hd - P, P)
+ with tm.t("f ck: kv decompress"):
+ klo = max(0, N - T - self.window + 1) if self.window else 0
+ kc = kcache[klo:]
+ lat16 = kc[:, :R].clamp(-65504.0, 65504.0).half().contiguous()
+ pe16 = kc[:, R:].clamp(-65504.0, 65504.0).half().contiguous()
+ kk, vv = _pu.kv_decompress(lat16, pe16, self._kvw(), H)
+ bias = None
+ if allow is not None:
+ with tm.t("f ck: allow bias"):
+ Nk = N - klo
+ bias = torch.empty(T, (Nk + 7) // 8 * 8, dtype=torch.float16, device=cur.device)
+ bias[:, :Nk] = torch.where(allow[:, klo:], 0.0, -30000.0).half()
+ with tm.t("MLA core + sinks"):
+ o = ck_mla.fmha(q.view(T, H, self.hd), kk, vv, self.scale, self.sinks, bias, self.window)
+ if o is None:
+ return None
+ with tm.t("attn proj"):
+ with tm.t("f gate: wgate mm + sigmoid"):
+ g = _pk.qdense_raw16(cur, self.wgate.packed, tm)
+ gated = _pk.gate16t(o.view(T, H * self.vd), g)
+ with tm.t("f gate: wo mm"):
+ out = _pk.qdense_tm(gated, self.wo.packed, tm)
+ with tm.t("f gate: post norm"):
+ if self.post_norm is not None:
+ from . import hc_fused as _hf
+ out = _hf.rmsw(out, self.post_norm, self.eps) if _hf.ENABLED else rms(out, self.eps) * self.post_norm
+ return None, gated, out
+
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
tm = self.tm
qa, self._qa_pre = self._qa_pre, None
+ if self._ck_ok(cur):
+ r = self.attend_ck(cur, pos, kcache, allow, qa)
+ if r is not None:
+ return r
if self._f16_ok(cur):
return self.attend16(cur, pos, kcache, allow, qa)
with tm.t("attn proj"):
diff --git a/exllamav3/loader/prefill_unabs.py b/exllamav3/loader/prefill_unabs.py
new file mode 100644
index 0000000..71eeb0a
--- /dev/null
+++ b/exllamav3/loader/prefill_unabs.py
@@ -0,0 +1,56 @@
+"""Un-absorbed MLA prefill helpers (generic by (H, nope, rope, R, vd)): q rotary in place on the raw wq_b output, and the per-head K / V decompression
+weight W [R, H * S] with slot S = 512 per head = [k_nope (nope) | pad to 256 (filled with the shared rope key) | v (vd)], so ONE GEMM
+latent [N, R] @ W gives K / V as strided views (row stride H * S, head stride S) that the CK fmha reads without a copy."""
+import torch
+import triton
+import triton.language as tl
+
+
+def _qrope_kernel(Q, COS, SIN, H, HD: tl.constexpr, NOPE: tl.constexpr, P: tl.constexpr, HB: tl.constexpr):
+ """one program = HB heads of one row t of the raw fp16 wq_b output [T, H * HD], in place, coalesced [HB, HD] tile: nan -> 0 and saturate everything,
+ rotary (consecutive pairs) on the last P columns: out[c] = x[c] * cos + (c even ? -x[c + 1] : x[c - 1]) * sin (same rounding points as rope_norm + clamp)"""
+ t = tl.program_id(0)
+ h = tl.program_id(1) * HB + tl.arange(0, HB)
+ c = tl.arange(0, HD)
+ hm = (h < H)[:, None]
+ base = (t.to(tl.int64) * H + h)[:, None] * HD
+ x = tl.load(Q + base + c[None, :], mask=hm, other=0.0).to(tl.float32)
+ x = tl.where(x != x, 0.0, tl.minimum(tl.maximum(x, -65504.0), 65504.0))
+ xp = tl.load(Q + base + (c ^ 1)[None, :], mask=hm, other=0.0).to(tl.float32)
+ xp = tl.where(xp != xp, 0.0, tl.minimum(tl.maximum(xp, -65504.0), 65504.0))
+ pe = c >= NOPE
+ j = tl.where(pe, (c - NOPE) // 2, 0)
+ cs = tl.load(COS + t * (P // 2) + j)
+ sn = tl.load(SIN + t * (P // 2) + j)
+ sg = tl.where((c % 2) == 0, -sn, sn)
+ r = tl.minimum(tl.maximum(x * cs[None, :] + xp * sg[None, :], -65504.0), 65504.0)
+ o = tl.where(pe[None, :], r, x)
+ tl.store(Q + base + c[None, :], o.to(tl.float16), mask=hm)
+
+
+def qrope_inplace(q, cos, sin, H, hd, nope, P):
+ T = q.shape[0]
+ HB = 8
+ _qrope_kernel[(T, triton.cdiv(H, HB))](q, cos, sin, H, HD=hd, NOPE=nope, P=P, HB=HB, num_warps=4)
+ return q
+
+
+def kv_weight(wk16, wv16, slot=512, kpad=256):
+ """wk16 [H, R, nope] fp16, wv16 [H, vd, R] fp16 -> W [R, H * slot] fp16: head h columns [0:nope] = wk16[h], [kpad:kpad + vd] = wv16[h].T, rest 0"""
+ H, R, nope = wk16.shape
+ vd = wv16.shape[1]
+ W = torch.zeros(R, H, slot, dtype=torch.float16, device=wk16.device)
+ W[:, :, :nope] = wk16.permute(1, 0, 2)
+ W[:, :, kpad:kpad + vd] = wv16.permute(2, 0, 1)
+ return W.reshape(R, H * slot)
+
+
+def kv_decompress(lat16, pe16, W, H, hd=256, slot=512):
+ """lat16 [N, R] fp16, pe16 [N, P] fp16 (rope already applied), W from kv_weight -> (K [N, H, hd] view, V [N, H, hd] view) of one [N, H, slot] slab;
+ the rope key is broadcast over heads into the pad columns of K"""
+ N = lat16.shape[0]
+ P = pe16.shape[1]
+ slab = torch.mm(lat16, W).view(N, H, slot)
+ slab[:, :, hd - P:hd] = pe16[:, None, :]
+ return slab[:, :, :hd], slab[:, :, hd:hd + hd]