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 long context: exact decode group selection + sparse MLA attend (HY4_LC_SPARSE), SWA ring K buffers (HY4_SWA_RING); flag off by default, unit tests with poisoned guards

YanissAmz808c581ead99
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 19ede78..981a6ee 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -770,12 +770,19 @@ class Hy4Forward:
pre, post = self._site(x, L.hca)
cur = rms((x * pre[:, :, None]).sum(1), self.eps) * L.attn_norm
mla = L.mla
+ kbase = 0
+ ring = getattr(mla, "kv_ring", 0) # HY4_SWA_RING: window layers keep a ring of `ring` K rows instead of the full context
+ mla.ring_call = ring if gs is not None else 0
if gs is not None and gs.T == 1 and _KVF.ENABLED and _AE.ENABLED: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernel
kc = gs.kv_row_fused(i, mla, cur, pos)
else:
with tm.t("attn proj"):
kn = mla.kv(cur, pos)
- kc = gs.append_kv(i, kn) if gs is not None else _ns.append_kv(self, i, kn, start) if _ns.active(self) else (torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn)
+ if ring and gs is None: # HY4_SWA_RING: window layer, eager rows: window - 1 history rows + the new rows, relative positions
+ kc, kbase = _ns.append_kv_ring(self, i, kn, start, ring, mla.window)
+ mla.kpos_arange = T > 16 # short eager steps use the generic kpos path (absolute positions); prefill rows are relative to the scratch
+ else:
+ kc = gs.append_kv(i, kn) if gs is not None else _ns.append_kv(self, i, kn, start) if _ns.active(self) else (torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn)
N = kc.shape[0]
allow = None
if L.ix:
@@ -795,7 +802,7 @@ class Hy4Forward:
for t, r in enumerate(sel.rows):
allow[t, r.long()] = True
allow = allow.to(self.dev)
- kqv, gated, out = mla.attend(cur, pos, kc, gs.ar[:N] if gs is not None else _ns.kpos(self, N) if _ns.active(self) else torch.arange(N, device=self.dev), allow)
+ kqv, gated, out = mla.attend(cur, pos, kc, gs.ar[:N] if gs is not None else _ns.kpos(self, kbase + N)[kbase:] if _ns.active(self) else torch.arange(N, device=self.dev), allow)
self.kc[i] = kc
self._hk("attn_kqv", i, kqv)
self._hk("attn_gated", i, gated)
diff --git a/exllamav3/loader/kv_fused.py b/exllamav3/loader/kv_fused.py
index 19a4c15..ab2b30b 100644
--- a/exllamav3/loader/kv_fused.py
+++ b/exllamav3/loader/kv_fused.py
@@ -11,14 +11,18 @@ ENABLED = os.environ.get("HY4_KV_FUSED", "0") == "1"
@triton.jit
-def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr):
+def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, RING: tl.constexpr):
pos = tl.load(pos_ptr)
+ if RING > 0:
+ slot = pos % RING # window layer: ring buffer row (the rope table is still indexed by the absolute position)
+ else:
+ slot = pos
offr = tl.arange(0, BR)
mr = offr < R
x = tl.load(c_ptr + offr, mask=mr, other=0.0)
rc = tl.rsqrt(tl.sum(x * x, axis=0) / R + eps)
w = tl.load(w_ptr + offr, mask=mr, other=0.0)
- tl.store(k_ptr + pos * sk + offr, x * rc * w, mask=mr)
+ tl.store(k_ptr + slot * sk + offr, x * rc * w, mask=mr)
H: tl.constexpr = P // 2
offh = tl.arange(0, H)
x0 = tl.load(c_ptr + R + 2 * offh)
@@ -28,13 +32,13 @@ def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, P
a1 = tl.load(tb + offh * 2 + 1) # s
b0 = tl.load(tb + H * 2 + offh * 2) # -s
b1 = tl.load(tb + H * 2 + offh * 2 + 1) # c
- tl.store(k_ptr + pos * sk + R + 2 * offh, x0 * a0 + x1 * b0)
- tl.store(k_ptr + pos * sk + R + 2 * offh + 1, x0 * a1 + x1 * b1)
+ tl.store(k_ptr + slot * sk + R + 2 * offh, x0 * a0 + x1 * b0)
+ tl.store(k_ptr + slot * sk + R + 2 * offh + 1, x0 * a1 + x1 * b1)
-def write_row(c, w, tab, pos, kbuf, R, P, eps):
+def write_row(c, w, tab, pos, kbuf, R, P, eps, ring=0):
"""c [1, R+P] fp32 (unit column stride), w [R], tab [n, 2, P/2, 2], pos [1] long device, kbuf [cap, R+P] fp32"""
- _k_kv[(1,)](c, w, tab, pos, kbuf, c.stride(0), kbuf.stride(0), eps, R=R, P=P, BR=triton.next_power_of_2(R), num_warps=4)
+ _k_kv[(1,)](c, w, tab, pos, kbuf, c.stride(0), kbuf.stride(0), eps, R=R, P=P, BR=triton.next_power_of_2(R), RING=ring, num_warps=4)
@triton.jit
diff --git a/exllamav3/loader/lc_sparse.py b/exllamav3/loader/lc_sparse.py
new file mode 100644
index 0000000..99941c6
--- /dev/null
+++ b/exllamav3/loader/lc_sparse.py
@@ -0,0 +1,179 @@
+"""Long-context decode kernels for the k-pool sparse attention family (Hy4 indexer layers; generic by kpool / top_k / head dims, nothing keyed on a model name).
+
+ select_groups(iq, wt, pool, pos, Pb, n_top, kp, tail)
+ exact top-n_top selection over the pooled groups, one launch pair per layer: a tiled score kernel (sc[t, p] = sum_h wt[t, h] * relu(iq[t, h] . pool[p]),
+ -inf for groups the row cannot see) and a one-program-per-row selection kernel that keeps the row in registers: bisection on the order-preserving int
+ key of the fp32 score finds the n_top-th largest score, ties at that score are resolved to the LOWEST group ids (torch.topk leaves them unspecified),
+ the selected group ids are compacted in ascending order. Returns (idx [T, n_top] int32, nsel [T] int32). Fewer visible groups than n_top: all of them.
+ sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks, kp, tail)
+ the decode MLA attend (online softmax, per-head sink) over exactly the keys the dense `allow` mask would keep: the members of the selected groups plus the
+ open tail group of the row. Work is O(n_top * kp), independent of the context length (the dense kernel reads every key below the position).
+"""
+from __future__ import annotations
+import os
+
+import torch
+
+try:
+ import triton
+ import triton.language as tl
+except Exception:
+ triton = None
+
+CHECK = os.environ.get("HY4_LC_CHECK", "0") == "1" # eager (non-captured) calls also run the dense torch selection and count differing row sets (debug / gate)
+STATS = {"rows": 0, "diff_rows": 0, "diff_groups": 0, "max_gap": 0.0}
+ENABLED = os.environ.get("HY4_LC_SPARSE", "0") == "1" # decode: indexer layers use select_groups + sparse_mla_attend instead of the dense allow mask
+
+
+def _usable(*ts):
+ if triton is None:
+ return False
+ if os.environ.get("TRITON_INTERPRET", "0") == "1":
+ return True
+ return all(t.is_cuda for t in ts)
+
+
+if triton is not None:
+ @triton.jit
+ def _score_kernel(IQ, WT, POOL, SC, POS, P, s_sc, KP: tl.constexpr, TAIL: tl.constexpr, H: tl.constexpr, D: tl.constexpr, BP: tl.constexpr):
+ t = tl.program_id(0)
+ p = tl.program_id(1) * BP + tl.arange(0, BP)
+ inb = p < P
+ pos = tl.load(POS + t)
+ gend = p * KP + (KP - 1)
+ if TAIL:
+ vis = inb & (gend < pos)
+ else:
+ vis = inb & (gend <= pos)
+ d = tl.arange(0, D)
+ pk = tl.load(POOL + p[:, None].to(tl.int64) * D + d[None, :], mask=vis[:, None], other=0.0)
+ acc = tl.zeros([BP], tl.float32)
+ for h in range(H):
+ q = tl.load(IQ + (t * H + h) * D + d)
+ s = tl.sum(pk * q[None, :], axis=1)
+ acc += tl.maximum(s, 0.0) * tl.load(WT + t * H + h)
+ acc = tl.where(vis, acc, float("-inf"))
+ tl.store(SC + t.to(tl.int64) * s_sc + p, acc, mask=inb)
+
+ @triton.jit
+ def _select_kernel(SC, IDX, NSEL, P, s_sc, NTOP: tl.constexpr, BP: tl.constexpr):
+ t = tl.program_id(0)
+ p = tl.arange(0, BP)
+ inb = p < P
+ x = tl.load(SC + t.to(tl.int64) * s_sc + p, mask=inb, other=float("-inf"))
+ vis = inb & (x > float("-inf"))
+ bits = x.to(tl.int32, bitcast=True)
+ key = tl.where(bits < 0, bits ^ 0x7FFFFFFF, bits).to(tl.int64) # order-preserving signed key of the fp32 score
+ nvis = tl.sum(vis.to(tl.int32), 0)
+ lo = tl.full([], -2147483648, tl.int64) # invariant: count(vis & key >= lo) >= min(NTOP, nvis)
+ hi = tl.full([], 2147483647, tl.int64)
+ for _ in range(32):
+ mid = (lo + hi + 1) // 2
+ c = tl.sum((vis & (key >= mid)).to(tl.int32), 0)
+ ok = c >= NTOP
+ lo = tl.where(ok, mid, lo)
+ hi = tl.where(ok, hi, mid - 1)
+ gt = vis & (key > lo)
+ eq = vis & (key == lo)
+ need = NTOP - tl.sum(gt.to(tl.int32), 0)
+ eqr = tl.cumsum(eq.to(tl.int32), 0)
+ sel = gt | (eq & (eqr <= need))
+ rank = tl.cumsum(sel.to(tl.int32), 0) - 1
+ tl.store(IDX + t * NTOP + rank, p, mask=sel)
+ tl.store(NSEL + t, tl.sum(sel.to(tl.int32), 0))
+
+ @triton.jit
+ def _blk(q, qp, CK, KPE, offn, vis, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc):
+ ck = tl.load(CK + offn[:, None].to(tl.int64) * s_ck + offr[None, :], mask=vis[:, None] & mr[None, :], other=0.0).to(tl.float32)
+ kp = tl.load(KPE + offn[:, None].to(tl.int64) * s_kp + offp[None, :], mask=vis[:, None] & mp[None, :], other=0.0).to(tl.float32)
+ s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scale
+ s = tl.where(vis, s, float("-inf"))
+ mn = tl.maximum(m, tl.max(s, axis=0))
+ mn_s = tl.where(mn == float("-inf"), 0.0, mn)
+ alpha = tl.exp(m - mn_s)
+ pr = tl.exp(s - mn_s)
+ l = l * alpha + tl.sum(pr, axis=0)
+ acc = acc * alpha + tl.sum(pr[:, None] * ck, axis=0)
+ return mn, l, acc
+
+ @triton.jit
+ def _sparse_mla_kernel(QL, QP, CK, KPE, POS, IDX, NSEL, SINK, O, scale, s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_o_t, s_o_h,
+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BPE: tl.constexpr, BN: tl.constexpr, KG: tl.constexpr, NTOP: tl.constexpr):
+ t = tl.program_id(0)
+ h = tl.program_id(1)
+ offr = tl.arange(0, BR)
+ offp = tl.arange(0, BPE)
+ mr = offr < R
+ mp = offp < P
+ q = tl.load(QL + t * s_ql_t + h * s_ql_h + offr, mask=mr, other=0.0).to(tl.float32)
+ qp = tl.load(QP + t * s_qp_t + h * s_qp_h + offp, mask=mp, other=0.0).to(tl.float32)
+ qpos = tl.load(POS + t)
+ m = tl.load(SINK + h).to(tl.float32)
+ l = tl.zeros([], dtype=tl.float32) + 1.0
+ acc = tl.zeros([BR], dtype=tl.float32)
+ lo = qpos - qpos % KG # open tail group of the row (select_tail)
+ kk = tl.arange(0, BN)
+ offn = lo + kk
+ m, l, acc = _blk(q, qp, CK, KPE, offn, offn <= qpos, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)
+ n = tl.load(NSEL + t)
+ nk = n * KG
+ for i0 in range(0, nk, BN):
+ kj = i0 + kk
+ inb = kj < nk
+ g = tl.load(IDX + t * NTOP + kj // KG, mask=inb, other=0)
+ m, l, acc = _blk(q, qp, CK, KPE, g * KG + kj % KG, inb, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)
+ tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)
+
+
+def select_groups(iq, wt, pool, pos, Pb, n_top, kp, tail):
+ """iq [T, H, d] fp32 contiguous, wt [T, H] fp32, pool [>= Pb, d] fp32, pos [T] long (device) -> (idx [T, n_top] int32, nsel [T] int32)"""
+ T, H, D = iq.shape
+ assert iq.is_contiguous() and wt.is_contiguous() and pool.is_contiguous() and pool.shape[0] >= Pb and pool.shape[1] == D and Pb >= n_top
+ sc = torch.empty(T, Pb, dtype=torch.float32, device=iq.device)
+ idx = torch.empty(T, n_top, dtype=torch.int32, device=iq.device)
+ nsel = torch.empty(T, dtype=torch.int32, device=iq.device)
+ BP = 32
+ _score_kernel[(T, triton.cdiv(Pb, BP))](iq, wt, pool, sc, pos, Pb, sc.stride(0), KP=kp, TAIL=bool(tail), H=H, D=D, BP=BP, num_warps=4)
+ BPS = triton.next_power_of_2(Pb)
+ _select_kernel[(T,)](sc, idx, nsel, Pb, sc.stride(0), NTOP=n_top, BP=BPS, num_warps=16 if BPS >= 4096 else 4)
+ return idx, nsel
+
+
+class SparseSel:
+ """what the static indexer returns instead of a dense `allow` mask when HY4_LC_SPARSE is on; mla.attend routes it to sparse_mla_attend"""
+ __slots__ = ("idx", "nsel", "kp", "tail", "n_top")
+
+ def __init__(self, idx, nsel, kp, tail):
+ self.idx, self.nsel, self.kp, self.tail, self.n_top = idx, nsel, kp, tail, idx.shape[1]
+
+
+def sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks):
+ """q_lat [T,H,R] fp32, q_pe [T,H,P], ckv [N,R], k_pe [N,P] (row strides free), qpos [T] long, sel SparseSel -> o_lat [T,H,R] fp32"""
+ T, H, R = q_lat.shape
+ P = k_pe.shape[1]
+ assert sel.tail and q_lat.dtype == torch.float32 and ckv.dtype == torch.float32 and q_lat.stride(-1) == 1 and q_pe.stride(-1) == 1 and ckv.stride(-1) == 1 and k_pe.stride(-1) == 1
+ out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)
+ _sparse_mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, sel.idx, sel.nsel, sinks.float().contiguous(), out, float(scale),
+ q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0), out.stride(0), out.stride(1),
+ R=R, P=P, BR=triton.next_power_of_2(R), BPE=triton.next_power_of_2(P), BN=16, KG=sel.kp, NTOP=sel.n_top, num_warps=4)
+ return out
+
+
+def check_rows(iq, wt, pool, pos, Pb, n_top, kp, sel):
+ """debug: dense reference selection (the stock torch path of step_graph.indexer_forward_static) vs the sparse one; counts rows whose group sets differ
+ and the largest score gap between a swapped pair (a pure tie / rounding swap has gap ~ 1e-7)"""
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pool[:Pb]))
+ sc = (kq * wt[:, :, None]).sum(1)
+ gend = torch.arange(Pb, device=iq.device) * kp + (kp - 1)
+ vis = gend[None] < pos[:, None]
+ sc = torch.where(vis, sc, torch.full_like(sc, -float("inf")))
+ ref = torch.topk(sc, min(n_top, Pb), dim=1).indices
+ for t in range(sc.shape[0]):
+ a = set(ref[t].tolist()) - {g for g in ref[t].tolist() if not bool(vis[t, g])}
+ b = set(sel.idx[t, :int(sel.nsel[t])].tolist())
+ STATS["rows"] += 1
+ if a != b:
+ STATS["diff_rows"] += 1
+ STATS["diff_groups"] += len(a ^ b)
+ for g in a ^ b:
+ STATS["max_gap"] = max(STATS["max_gap"], abs(float(sc[t, g]) - float(sc[t][list(b | a)].min())))
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index 2d9a8bf..8e192cf 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -283,9 +283,12 @@ class Hy4MLA:
if 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 range
o = (_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)
+ elif allow.__class__.__name__ == "SparseSel": # HY4_LC_SPARSE: decode rows, exact selected groups + tail only
+ from . import lc_sparse as _LS
+ o = _LS.sparse_mla_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, allow, self.scale, self.sinks)
elif _rf.ENABLED: # HY4_REF_FUSED=1: one online-softmax kernel (sinks / window / allow inside)
o = _rf.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow,
- kpos_is_arange=getattr(self, "kpos_arange", False))
+ kpos_is_arange=getattr(self, "kpos_arange", False), ring=getattr(self, "ring_call", 0))
else:
o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)
with tm.t("attn proj"):
diff --git a/exllamav3/loader/ref_fused.py b/exllamav3/loader/ref_fused.py
index cabebf7..b27e5a7 100644
--- a/exllamav3/loader/ref_fused.py
+++ b/exllamav3/loader/ref_fused.py
@@ -112,7 +112,7 @@ if triton is not None:
def _mla_kernel(QL, QP, CK, KP, QPOS, KPOS, ALLOW, SINK, O, N, scale, window,
s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_al, s_o_t, s_o_h,
R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BP: tl.constexpr, BN: tl.constexpr,
- HAS_SINK: tl.constexpr, HAS_ALLOW: tl.constexpr, HAS_WIN: tl.constexpr, ARANGE: tl.constexpr):
+ HAS_SINK: tl.constexpr, HAS_ALLOW: tl.constexpr, HAS_WIN: tl.constexpr, ARANGE: tl.constexpr, RING: tl.constexpr = 0):
t = tl.program_id(0)
h = tl.program_id(1)
offr = tl.arange(0, BR)
@@ -147,8 +147,12 @@ if triton is not None:
vis = vis & ((qpos - kpos) < window)
if HAS_ALLOW:
vis = vis & (tl.load(ALLOW + t * s_al + offn, mask=inb, other=0) != 0)
- ck = tl.load(CK + offn[:, None] * s_ck + offr[None, :], mask=inb[:, None] & mr[None, :], other=0.0).to(tl.float32)
- kp = tl.load(KP + offn[:, None] * s_kp + offp[None, :], mask=inb[:, None] & mp[None, :], other=0.0).to(tl.float32)
+ if RING > 0: # window layer: the K rows live in a ring buffer, absolute position j in slot j % RING
+ offs = offn % RING
+ else:
+ offs = offn
+ ck = tl.load(CK + offs[:, None] * s_ck + offr[None, :], mask=inb[:, None] & mr[None, :], other=0.0).to(tl.float32)
+ kp = tl.load(KP + offs[:, None] * s_kp + offp[None, :], mask=inb[:, None] & mp[None, :], other=0.0).to(tl.float32)
s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scale
s = tl.where(vis, s, float("-inf"))
mn = tl.maximum(m, tl.max(s, axis=0))
@@ -161,24 +165,27 @@ if triton is not None:
tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)
-def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None, kpos_is_arange=False):
+def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None, kpos_is_arange=False, ring=0):
"""drop-in for mla_sink_attend: q_lat [T,H,R], q_pe [T,H,P], ckv [N,R], k_pe [N,P] (row strides free), qpos [T], kpos [N],
sinks [H] or None -> o_lat [T,H,R] fp32. kpos_is_arange (default False = generic): the caller's kpos is torch.arange(N)
(the Hy4 forward always passes it so), which lets causal / window bounds skip K blocks."""
+ assert not ring or (kpos_is_arange and window and allow is None and window < ring), "ring K buffers need the arange / window kernel path"
if os.environ.get("HY4_REF_MLA", "1") == "0": # sub-flag: MLA half off
return mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks, window, allow)
T, H, R = q_lat.shape
N, P = ckv.shape[0], k_pe.shape[1]
if (not _usable(q_lat, ckv) or T > MAX_T or sinks is None or N == 0 or q_lat.dtype != torch.float32 or ckv.dtype != torch.float32
or q_lat.stride(-1) != 1 or q_pe.stride(-1) != 1 or ckv.stride(-1) != 1 or k_pe.stride(-1) != 1):
+ if ring:
+ raise RuntimeError("ring K buffer: the fused kernel declined and the torch reference cannot read a ring")
return mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks, window, allow)
out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)
al = allow.view(torch.uint8) if allow is not None else qpos
BN = 16
- _mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, kpos, al, sinks.float().contiguous(), out, N, float(scale), int(window),
+ _mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, kpos, al, sinks.float().contiguous(), out, (1 << 30) if ring else N, float(scale), int(window),
q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0),
allow.stride(0) if allow is not None else 0, out.stride(0), out.stride(1),
R=R, P=P, BR=triton.next_power_of_2(R), BP=triton.next_power_of_2(P), BN=BN,
- HAS_SINK=True, HAS_ALLOW=allow is not None, HAS_WIN=bool(window), ARANGE=bool(kpos_is_arange),
+ HAS_SINK=True, HAS_ALLOW=allow is not None, HAS_WIN=bool(window), ARANGE=bool(kpos_is_arange), RING=int(ring),
num_warps=4)
return out
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index 1745a19..0dff54b 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -30,6 +30,7 @@ TM = int(os.environ.get("HY4_GRAPH_TM", "8")) # max rows of one graph s
MASK64 = (1 << 64) - 1
PERT = None # [cap, D] fp32 noise table (measurement arms only)
_IO_W = int(os.environ.get("HY4_GRAPH_IO", "64"))
+RING_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)
SPLIT = os.environ.get("HY4_GRAPH_SPLIT", "1") == "1" # 3 graphs per step, cut before the first two Engram layers: the rows of the later layers are staged while the GPU runs the earlier ones
STAGE_VEC = os.environ.get("HY4_STAGE_VEC", "1") == "1" # vectorised Engram hash + a few big read chunks (engram_stage); 0 = the per-row python path
@@ -44,6 +45,7 @@ def _rms(x, w, eps):
from . import pool_fused as _PF
+from . import lc_sparse as _LS
_PF.ENABLED = os.environ.get("HY4_IDX_POOLK", "0") == "1"
@@ -89,6 +91,12 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):
iq = ix._rope((qr @ ix.w["q_b"].T).reshape(T, H, d), pos)
wt = (x.float() @ ix.w["proj"].T) / math.sqrt(d * H)
Pb = Nb // k
+ 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)
+ idx, nsel = _LS.select_groups(iq.contiguous(), wt.contiguous(), ix.pool, pos, Pb, ix.n_top, k, ix.tail)
+ sel = _LS.SparseSel(idx, nsel, k, ix.tail)
+ if _LS.CHECK and not torch.cuda.is_current_stream_capturing():
+ _LS.check_rows(iq, wt, ix.pool, pos, Pb, ix.n_top, k, sel)
+ return sel
kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, ix.pool[:Pb]))
sc = (kq * wt[:, :, None]).sum(1)
gend = ar[:Pb] * k + (k - 1)
@@ -167,6 +175,10 @@ class _GS:
def append_kv(self, i, kn):
b = _ns.state(self.fw).kv[i]
+ ring = getattr(self.fw._layer(i).mla, "kv_ring", 0)
+ if ring: # window layer: ring buffer, slot = position % ring; attention reads the whole ring through absolute positions
+ b.index_copy_(0, self.pos % ring, kn)
+ return b
b.index_copy_(0, self.pos, kn)
return b[:self.Nb]
@@ -176,8 +188,9 @@ class _GS:
b = _ns.state(self.fw).kv[i]
c = mla._q(cur, "wkv_a") @ mla.wkv_a.T
tab = AE.table(mla.rope_dim, mla.theta, self.fw.dev, pos)
- KVF.write_row(c, mla.kv_a_norm, tab, pos, b, mla.R, mla.rope_dim, mla.eps)
- return b[:self.Nb]
+ ring = getattr(mla, "kv_ring", 0)
+ KVF.write_row(c, mla.kv_a_norm, tab, pos, b, mla.R, mla.rope_dim, mla.eps, ring=ring)
+ return b if ring else b[:self.Nb]
def indexer(self, fw, i, cur, qr, N):
# T rows in one pass: every row writes its vg row first, then the pooled groups are computed (a group completed inside this round gets its
@@ -228,8 +241,14 @@ class GraphDecoder:
except ImportError:
pass
for i in range(fw.n_layers):
- fw._layer(i)
+ m = fw._layer(i).mla
+ if RING_ROWS and m.swa and m.window and not hasattr(m, "kv_ring") and m.window + TM + 8 <= RING_ROWS:
+ m.kv_ring = RING_ROWS # exact: a window-W layer never reads a key older than W - 1 positions (RING_ROWS >= W + the verify rows)
b = st.kv.get(i)
+ if getattr(m, "kv_ring", 0):
+ if b is None or b.shape[0] != m.kv_ring:
+ st.kv[i] = torch.zeros(m.kv_ring, 512 + 64, dtype=torch.float32, device=fw.dev)
+ continue
if b is None or b.shape[0] < self.cap:
nb = torch.zeros(self.cap, 512 + 64, dtype=torch.float32, device=fw.dev) if b is None else torch.zeros(self.cap, b.shape[1], dtype=b.dtype, device=fw.dev)
if b is not None:
diff --git a/exllamav3/loader/step_nosync.py b/exllamav3/loader/step_nosync.py
index 5fb6d34..fe009d9 100644
--- a/exllamav3/loader/step_nosync.py
+++ b/exllamav3/loader/step_nosync.py
@@ -100,6 +100,25 @@ def append_kv(fw, i, kn, start):
return b[:need]
+def append_kv_ring(fw, i, kn, start, ring, window):
+ """window layer, eager rows (prefill chunk / short prompt) with a ring K buffer [ring, W]: returns (scratch, base) where scratch = the window - 1 rows before
+ `start` (gathered from the ring) + kn, as one contiguous [hist + T, W] tensor holding positions base .. start + T - 1; the last min(T, ring) rows of kn go
+ into the ring (slot = position % ring). The attend then sees the same keys, in the same order, as with the full-length buffer (relative offsets only)."""
+ st = state(fw)
+ b = st.kv[i]
+ T = kn.shape[0]
+ hist = min(start, window - 1)
+ base = start - hist
+ if hist:
+ slots = (torch.arange(base, start, device=kn.device)) % ring
+ scratch = torch.cat([b.index_select(0, slots), kn])
+ else:
+ scratch = kn
+ m = min(T, ring)
+ b.index_copy_(0, (torch.arange(start + T - m, start + T, device=kn.device)) % ring, kn[T - m:])
+ return scratch, base
+
+
def kpos(fw, N):
st = state(fw)
st.ensure(N)
diff --git a/tests/test_lc_sparse.py b/tests/test_lc_sparse.py
new file mode 100644
index 0000000..a737e9a
--- /dev/null
+++ b/tests/test_lc_sparse.py
@@ -0,0 +1,147 @@
+"""Unit tests of exllamav3/loader/lc_sparse.py (exact group selection + sparse MLA decode attend), with POISONED guard regions around every tensor so that any
+out-of-bounds read (NaN reaches the output) or write (guard changed) fails the test BEFORE a model run.
+CPU: TRITON_INTERPRET=1 DEV=cpu python tests/test_lc_sparse.py GPU: DEV=cuda python tests/test_lc_sparse.py"""
+import importlib.util
+import math
+import os
+import sys
+
+import torch
+
+DEV = os.environ.get("DEV", "cpu")
+here = os.path.dirname(os.path.abspath(__file__))
+sp = importlib.util.spec_from_file_location("lc_sparse", os.path.join(here, "..", "exllamav3", "loader", "lc_sparse.py"))
+LS = importlib.util.module_from_spec(sp)
+sp.loader.exec_module(LS)
+GUARD = 4096
+
+
+def guarded(t):
+ """copy of t placed inside a NaN / -1 poisoned buffer; returns (view, check()) where check() asserts the guards are untouched"""
+ flat = t.reshape(-1)
+ if t.dtype.is_floating_point:
+ buf = torch.full((flat.numel() + 2 * GUARD,), float("nan"), dtype=t.dtype, device=t.device)
+ else:
+ buf = torch.full((flat.numel() + 2 * GUARD,), -7, dtype=t.dtype, device=t.device)
+ buf[GUARD:GUARD + flat.numel()] = flat
+ ref = buf.clone()
+ view = buf[GUARD:GUARD + flat.numel()].view(t.shape)
+
+ def check():
+ a = torch.cat([buf[:GUARD], buf[GUARD + flat.numel():]])
+ b = torch.cat([ref[:GUARD], ref[GUARD + flat.numel():]])
+ assert torch.equal(torch.nan_to_num(a, nan=-12345.0), torch.nan_to_num(b, nan=-12345.0)), "guard region written"
+ return view, check
+
+
+def ref_scores(iq, wt, pool, pos, Pb, kp, tail):
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pool[:Pb]))
+ sc = (kq * wt[:, :, None]).sum(1)
+ gend = torch.arange(Pb, device=iq.device) * kp + (kp - 1)
+ vis = (gend[None] < pos[:, None]) if tail else (gend[None] <= pos[:, None])
+ return torch.where(vis, sc, torch.full_like(sc, -math.inf)), vis
+
+
+def case_select(T, H, D, Pb, kp, n_top, pos_list, ties=False, seed=0):
+ g = torch.Generator().manual_seed(seed)
+ iq = torch.randn(T, H, D, generator=g).to(DEV)
+ wt = torch.randn(T, H, generator=g).to(DEV) * 0.1
+ pool = torch.randn(Pb + 5, D, generator=g).to(DEV)
+ if ties:
+ pool[10:40] = pool[3]
+ pool[200:230] = pool[3]
+ pos = torch.tensor(pos_list, dtype=torch.long, device=DEV)
+ iq_g, c1 = guarded(iq); wt_g, c2 = guarded(wt); pool_g, c3 = guarded(pool); pos_g, c4 = guarded(pos)
+ idx, nsel = LS.select_groups(iq_g, wt_g, pool_g, pos_g, Pb, n_top, kp, True)
+ for c in (c1, c2, c3, c4):
+ c()
+ sc, vis = ref_scores(iq, wt, pool, pos, Pb, kp, True)
+ for t in range(T):
+ n = int(nsel[t])
+ got = idx[t, :n].tolist()
+ nv = int(vis[t].sum())
+ assert n == min(n_top, nv), (t, n, nv)
+ assert got == sorted(got) and len(set(got)) == n and all(0 <= x < Pb for x in got)
+ assert all(bool(vis[t, x]) for x in got)
+ if nv <= n_top:
+ assert got == torch.nonzero(vis[t]).flatten().tolist()
+ else:
+ # exact: every selected score >= every unselected visible score; ties at the boundary go to the lowest ids
+ s = sc[t]
+ selm = torch.zeros(Pb, dtype=torch.bool, device=DEV)
+ selm[torch.tensor(got, device=DEV)] = True
+ smin = s[selm].min()
+ smax_out = s[vis[t] & ~selm].max()
+ assert smin >= smax_out, (t, float(smin), float(smax_out))
+ if smin == smax_out:
+ tie = torch.nonzero(vis[t] & (s == smin)).flatten().tolist()
+ chosen = [x for x in tie if selm[x]]
+ assert chosen == tie[:len(chosen)], "ties not resolved to the lowest ids"
+ # same set as torch.topk when no ties at the boundary
+ if smin > smax_out:
+ tk = set(torch.topk(s, n_top).indices.tolist())
+ assert tk == set(got)
+ return idx, nsel, iq, pool
+
+
+def case_attend(T, H, R, P, Pb, kp, n_top, pos_list, seed=1, N=None):
+ idx, nsel, iq, pool = None, None, None, None
+ D = 128
+ g = torch.Generator().manual_seed(seed)
+ iq = torch.randn(T, 16, D, generator=g).to(DEV)
+ wt = torch.randn(T, 16, generator=g).to(DEV) * 0.1
+ pool = torch.randn(Pb + 3, D, generator=g).to(DEV)
+ pos = torch.tensor(pos_list, dtype=torch.long, device=DEV)
+ idx, nsel = LS.select_groups(iq, wt, pool, pos, Pb, n_top, kp, True)
+ N = N or (max(pos_list) + 1)
+ ckv = torch.randn(N, R, generator=g).to(DEV)
+ kpe = torch.randn(N, P, generator=g).to(DEV)
+ ql = torch.randn(T, H, R, generator=g).to(DEV)
+ qp = torch.randn(T, H, P, generator=g).to(DEV)
+ sinks = torch.randn(H, generator=g).to(DEV)
+ scale = 1.0 / 16.0
+ # dense reference mask
+ allow = torch.zeros(T, N, dtype=torch.bool, device=DEV)
+ for t in range(T):
+ for gi in idx[t, :int(nsel[t])].tolist():
+ allow[t, gi * kp:gi * kp + kp] = True
+ p = pos_list[t]
+ allow[t, p - p % kp:p + 1] = True
+ kpos = torch.arange(N, device=DEV)
+ s = torch.einsum("thr,nr->htn", ql, ckv) + torch.einsum("thp,np->htn", qp, kpe)
+ s = s * scale
+ vis = (kpos[None, :] <= pos[:, None]) & allow
+ s = s.masked_fill(~vis[None], float("-inf"))
+ s = torch.cat([s, sinks[:, None, None].expand(-1, T, 1)], -1)
+ pr = torch.softmax(s, -1)[..., :-1]
+ want = torch.einsum("htn,nr->thr", pr, ckv)
+ ql_g, c1 = guarded(ql); qp_g, c2 = guarded(qp); ckv_g, c3 = guarded(ckv); kpe_g, c4 = guarded(kpe); pos_g, c5 = guarded(pos)
+ idx_g, c6 = guarded(idx); ns_g, c7 = guarded(nsel); sk_g, c8 = guarded(sinks)
+ sel = LS.SparseSel(idx_g, ns_g, kp, True)
+ got = LS.sparse_mla_attend(ql_g, qp_g, ckv_g, kpe_g, pos_g, sel, scale, sk_g)
+ for c in (c1, c2, c3, c4, c5, c6, c7, c8):
+ c()
+ assert torch.isfinite(got).all()
+ err = (got - want).abs().max().item()
+ assert err < 2e-5, err
+ return err
+
+
+if __name__ == "__main__":
+ # selection: small / large visible counts, ties, short rows (fewer visible groups than n_top), several rows in one call
+ case_select(2, 16, 128, 700, 4, 64, [2800 - 1, 1000])
+ case_select(3, 16, 128, 512, 4, 511, [2047, 2100, 2051 + 4], seed=2)
+ case_select(2, 16, 128, 900, 4, 128, [3000, 3003], ties=True, seed=3)
+ case_select(1, 16, 128, 1024, 4, 511, [4090], seed=4)
+ print("select ok")
+ e1 = case_attend(2, 4, 64, 16, 300, 4, 32, [1199, 1204])
+ e2 = case_attend(3, 8, 512, 64, 640, 4, 511, [2600, 2601, 2602], N=2700)
+ print("attend ok", e1, e2)
+ if DEV == "cuda": # production sizes: T = 8 verify rows, 64K / 128K context pools, 32 heads, R = 512, P = 64
+ case_select(8, 16, 128, 16384, 4, 511, [65000 + 3 * i for i in range(8)], seed=5)
+ case_select(8, 16, 128, 32768, 4, 511, [131000 + i for i in range(8)], seed=6)
+ case_select(4, 16, 128, 16384, 4, 511, [5000, 40000, 65500, 2300], ties=True, seed=7)
+ e3 = case_attend(8, 32, 512, 64, 16384, 4, 511, [65000 + 3 * i for i in range(8)], N=65536)
+ e4 = case_attend(1, 32, 512, 64, 32768, 4, 511, [131070], N=131072)
+ print("production sizes ok", e3, e4)
+ print("ALL OK")
diff --git a/tests/test_swa_ring.py b/tests/test_swa_ring.py
new file mode 100644
index 0000000..8e4dc63
--- /dev/null
+++ b/tests/test_swa_ring.py
@@ -0,0 +1,87 @@
+"""HY4_SWA_RING unit tests (CPU interpreter or GPU): window layers keep their K rows in a ring buffer.
+ 1. ref_fused.mla_sink_attend(ring=RW) over the ring == the same call over the full-length buffer (exact), for decode / verify rows;
+ 2. kv_fused.write_row(ring=RW) writes slot pos % RW and the same values as the plain row write;
+ 3. step_nosync.append_kv_ring: scratch = window - 1 history rows + the new rows; the ring holds the last RW positions.
+Guard-poisoned buffers detect any out-of-bounds access. CPU: TRITON_INTERPRET=1 DEV=cpu python tests/test_swa_ring.py"""
+import importlib.util, os, sys, types
+import torch
+
+DEV = os.environ.get("DEV", "cpu")
+here = os.path.dirname(os.path.abspath(__file__))
+L = os.path.join(here, "..", "exllamav3", "loader")
+for n in ("exllamav3", "exllamav3.loader"):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(here, "..", "exllamav3") if n == "exllamav3" else L]; sys.modules[n] = m
+import importlib
+RF = importlib.import_module("exllamav3.loader.ref_fused")
+KVF = importlib.import_module("exllamav3.loader.kv_fused")
+NS = importlib.import_module("exllamav3.loader.step_nosync")
+sys.path.insert(0, here)
+from test_lc_sparse import guarded
+
+
+def test_attend(N, RW, window, qpos_list, H=4, R=512, P=64, seed=0):
+ g = torch.Generator().manual_seed(seed)
+ full = torch.randn(N, R + P, generator=g).to(DEV)
+ ring = torch.zeros(RW, R + P, device=DEV)
+ for j in range(N):
+ ring[j % RW] = full[j]
+ T = len(qpos_list)
+ ql = torch.randn(T, H, R, generator=g).to(DEV); qp = torch.randn(T, H, P, generator=g).to(DEV)
+ sinks = torch.randn(H, generator=g).to(DEV)
+ pos = torch.tensor(qpos_list, dtype=torch.long, device=DEV)
+ # the full buffer only has to hold positions <= max(qpos): rows past it are what the ring never wrote
+ Nf = max(qpos_list) + 1
+ want = RF.mla_sink_attend(ql, qp, full[:Nf, :R], full[:Nf, R:], pos, torch.arange(Nf, device=DEV), 0.0625, sinks, window, None, kpos_is_arange=True)
+ ring_g, c1 = guarded(ring)
+ ql_g, c2 = guarded(ql); qp_g, c3 = guarded(qp); pos_g, c4 = guarded(pos)
+ got = RF.mla_sink_attend(ql_g, qp_g, ring_g[:, :R], ring_g[:, R:], pos_g, torch.arange(RW, device=DEV), 0.0625, sinks, window, None, kpos_is_arange=True, ring=RW)
+ for c in (c1, c2, c3, c4):
+ c()
+ assert torch.isfinite(got).all()
+ err = (got - want).abs().max().item()
+ assert err < 1e-6, err
+ return err
+
+
+def test_write(RW=1024, R=512, P=64):
+ g = torch.Generator().manual_seed(3)
+ c = torch.randn(1, R + P, generator=g).to(DEV)
+ w = torch.randn(R, generator=g).to(DEV)
+ tab = torch.randn(5000, 2, P // 2, 2, generator=g).to(DEV)
+ for p in (0, 5, 1023, 1024, 3001):
+ pos = torch.tensor([p], dtype=torch.long, device=DEV)
+ a = torch.zeros(4096, R + P, device=DEV)
+ KVF.write_row(c, w, tab, pos, a, R, P, 1e-6)
+ b = torch.zeros(RW, R + P, device=DEV)
+ b_g, chk = guarded(b)
+ KVF.write_row(c, w, tab, pos, b_g, R, P, 1e-6, ring=RW)
+ chk()
+ assert torch.equal(a[p], b_g[p % RW]), p
+ assert int((b_g.abs().sum(1) > 0).sum()) == 1, "only one slot may be written"
+
+
+def test_append_ring(RW=1024, window=512, W=576):
+ class FW: pass
+ fw = FW(); fw.dev = torch.device(DEV)
+ st = NS.state(fw); st.kv = {0: torch.zeros(RW, W, device=DEV)}
+ full = torch.zeros(5000, W, device=DEV)
+ g = torch.Generator().manual_seed(9)
+ start = 0
+ for T in (100, 700, 2048, 3, 1, 1, 8, 1000):
+ kn = torch.randn(T, W, generator=g).to(DEV)
+ scratch, base = NS.append_kv_ring(fw, 0, kn, start, RW, window)
+ full[start:start + T] = kn
+ hist = min(start, window - 1)
+ assert base == start - hist and scratch.shape[0] == hist + T
+ assert torch.equal(scratch, full[base:start + T]), (start, T)
+ start += T
+ for j in range(max(0, start - RW), start):
+ assert torch.equal(st.kv[0][j % RW], full[j])
+
+
+if __name__ == "__main__":
+ print("attend", test_attend(1500, 1024, 512, [1499]), test_attend(3000, 1024, 512, [2990, 2991, 2992, 2993, 2994, 2995, 2996, 2997], H=2),
+ test_attend(700, 1024, 512, [690, 699]))
+ test_write(); print("write ok")
+ test_append_ring(); print("append ring ok")
+ print("ALL OK")