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: indexer vg ring (HY4_SWA_RING), draft-prime fused select for T > 16 rows (HY4_LC_PRIME), prompt-lookup propose without copying the sequence; unit tests

YanissAmz4880a094aeae
diff --git a/exllamav3/loader/pool_fused.py b/exllamav3/loader/pool_fused.py
index f88579d..23eb053 100644
--- a/exllamav3/loader/pool_fused.py
+++ b/exllamav3/loader/pool_fused.py
@@ -9,42 +9,51 @@ ENABLED = False
@triton.jit
-def _pooled(vgb, ape, g0, offs, k: tl.constexpr, d: tl.constexpr):
+def _slot(g, VR: tl.constexpr):
+ if VR > 0:
+ r = g % VR # HY4_SWA_RING: the (value | gate) rows live in a ring of VR rows
+ else:
+ r = g
+ return r
+
+
+def _pooled(vgb, ape, g0, offs, k: tl.constexpr, d: tl.constexpr, VR: tl.constexpr):
m = tl.full(offs.shape, float("-inf"), tl.float32)
for j in tl.static_range(k):
- gj = tl.load(vgb + (g0 + j) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
+ gj = tl.load(vgb + _slot(g0 + j, VR) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
m = tl.maximum(m, gj)
s = tl.zeros(offs.shape, tl.float32)
for j in tl.static_range(k):
- gj = tl.load(vgb + (g0 + j) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
+ gj = tl.load(vgb + _slot(g0 + j, VR) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
s += tl.exp(gj - m)
acc = tl.zeros(offs.shape, tl.float32)
for j in tl.static_range(k):
- gj = tl.load(vgb + (g0 + j) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
- vj = tl.load(vgb + (g0 + j) * 2 * d + offs)
+ gj = tl.load(vgb + _slot(g0 + j, VR) * 2 * d + d + offs) + tl.load(ape + j * d + offs)
+ vj = tl.load(vgb + _slot(g0 + j, VR) * 2 * d + offs)
acc += (tl.exp(gj - m) / s) * vj
return acc
@triton.jit
-def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d: tl.constexpr, rd: tl.constexpr):
+def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d: tl.constexpr, rd: tl.constexpr, VR: tl.constexpr):
t = tl.program_id(0)
p0 = tl.load(pos + t)
gi = p0 // k
g0 = gi * k
allo = tl.arange(0, d)
- pall = _pooled(vgb, ape, g0, allo, k, d)
+ pall = _pooled(vgb, ape, g0, allo, k, d, VR)
r = tl.rsqrt(tl.sum(pall * pall, 0) / d + eps)
nr: tl.constexpr = d - rd
offn = tl.arange(0, nr)
- pn = _pooled(vgb, ape, g0, offn, k, d)
+ pn = _pooled(vgb, ape, g0, offn, k, d, VR)
tl.store(pool + gi * d + offn, pn * r * tl.load(pnw + offn))
h: tl.constexpr = rd // 2
ii = tl.arange(0, h)
oa = nr + 2 * ii
ob = oa + 1
- na = _pooled(vgb, ape, g0, oa, k, d) * r * tl.load(pnw + oa)
- nb = _pooled(vgb, ape, g0, ob, k, d) * r * tl.load(pnw + ob)
+ na = _pooled(vgb, ape, g0, oa, k, d, VR) * r * tl.load(pnw + oa)
+ nb = _pooled(vgb, ape, g0, ob, k, d, VR) * r * tl.load(pnw + ob)
c = tl.load(cosb + g0 * h + ii)
s = tl.load(sinb + g0 * h + ii)
tl.store(pool + gi * d + oa, na * c - nb * s)
@@ -55,4 +64,4 @@ def pool_update(ix, pos):
"""pos [T] long (device): update the pool row of each position's group from ix.vgb (the new rows are already in place)"""
cs, sn = ix._table(ix._max_pos)
ape = ix.w["ape"]
- _pool_kernel[(pos.shape[0],)](ix.vgb, pos, ape, ix.w["pool_norm"], cs, sn, ix.pool, ix.eps, k=ix.k, d=ix.d, rd=ix.rope_dim)
+ _pool_kernel[(pos.shape[0],)](ix.vgb, pos, ape, ix.w["pool_norm"], cs, sn, ix.pool, ix.eps, k=ix.k, d=ix.d, rd=ix.rope_dim, VR=getattr(ix, "vg_ring", 0))
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index 0dff54b..a4fa72a 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -30,6 +30,8 @@ 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"))
+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)
+VG_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 group
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
@@ -59,10 +61,11 @@ def indexer_static_init(ix, cap):
ix.pool = big
vgb = getattr(ix, "vgb", None) # per-position (value | gate) rows [cap, 2d]: a rejected / re-run position just overwrites its row
if vgb is None:
- vgb = ix.vgb = torch.zeros(cap, 2 * d, device=ix.dev)
+ ix.vg_ring = VG_RING if (VG_RING and VG_RING < cap) else 0 # HY4_SWA_RING: only the open group (+ the rows of one batch call) is ever read: slot = position % VG_RING
+ vgb = ix.vgb = torch.zeros(ix.vg_ring or cap, 2 * d, device=ix.dev)
if ix.vg is not None: # open group of an eager prefill (< k rows)
m = ix.vg.shape[0]
- vgb[ix.n - m:ix.n] = ix.vg
+ vgb[(torch.arange(ix.n - m, ix.n, device=ix.dev) % ix.vg_ring) if ix.vg_ring else slice(ix.n - m, ix.n)] = ix.vg
ix._max_pos = cap
ix._table(cap)
@@ -75,12 +78,15 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):
k, d, H = ix.k, ix.d, ix.H
ik = _rms(x @ ix.w["attn_k"].T, ix.w["k_norm"], ix.eps)
vg_new = torch.cat([ik @ ix.w["value"].T, ik @ ix.w["gate"].T], -1)
- ix.vgb.index_copy_(0, pos, vg_new)
+ vr = getattr(ix, "vg_ring", 0)
+ assert not vr or x.shape[0] + k <= vr, "vg ring smaller than one call"
+ ix.vgb.index_copy_(0, pos % vr if vr else pos, vg_new)
if _PF.ENABLED: # one Triton kernel for the whole pool update (HY4_IDX_POOLK)
_PF.pool_update(ix, pos)
else:
g0 = (pos // k) * k
- rows = ix.vgb[g0[:, None] + ar[:k][None, :]] # [1, k, 2d]: the (partial) group of this position
+ gi = g0[:, None] + ar[:k][None, :]
+ rows = ix.vgb[gi % vr if vr else gi] # [1, k, 2d]: the (partial) group of this position
v, g = rows[..., :d].reshape(-1, k, d), rows[..., d:].reshape(-1, k, d)
p = (torch.softmax(g + ix.w["ape"][None], dim=1) * v).sum(1)
pooled = ix._rope(_rms(p, ix.w["pool_norm"], ix.eps), g0)
@@ -91,6 +97,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 PRIME_IX and T > 16 and ix.tail and iq.is_cuda: # draft-cache fill of a long prompt (T up to 2048 rows): fused fp16 scorer + exact select instead of the fp32 [T, 16, Pb] einsum
+ 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
+ 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)
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)
diff --git a/tests/test_prime_ix.py b/tests/test_prime_ix.py
new file mode 100644
index 0000000..7467c3a
--- /dev/null
+++ b/tests/test_prime_ix.py
@@ -0,0 +1,46 @@
+"""GPU test: step_graph.indexer_forward_static for T > 16 rows (draft-cache fill): HY4_LC_PRIME path (fp16 fused scorer + exact select) vs the stock fp32 einsum path.
+The two allow masks must agree on >= 99.9 % of the visible entries (fp16 scorer rounding may swap boundary groups); poisoned guards on the inputs. DEV=cuda only."""
+import importlib, math, os, sys, types
+import torch
+DEV = os.environ.get("DEV", "cuda")
+here = os.path.dirname(os.path.abspath(__file__))
+for n in ("exllamav3", "exllamav3.loader"):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(here, "..", "exllamav3") if n == "exllamav3" else os.path.join(here, "..", "exllamav3", "loader")]; sys.modules[n] = m
+SG = importlib.import_module("exllamav3.loader.step_graph")
+IXF = importlib.import_module("exllamav3.loader.indexer_fused")
+PK = importlib.import_module("exllamav3.loader.prefill_kernels")
+
+def build(cap, E=256, R=128, H=16, d=128, k=4):
+ g = torch.Generator().manual_seed(0)
+ r = lambda *s: (torch.randn(*s, generator=g) * 0.05).to(DEV)
+ w = {"attn_k": r(d, E), "q_b": r(H * d, R), "value": r(d, d), "gate": r(d, d), "k_norm": torch.ones(d, device=DEV), "proj": r(H, E),
+ "ape": r(k, d), "pool_norm": torch.ones(d, device=DEV)}
+ ix = IXF.FusedKPoolIndexer(w, DEV, n_head=H, head_dim=d, top_k=2048, kpool=k, select_tail=True, rope_dim=64, rope_base=1e7, eps=1e-5, cap=cap)
+ SG.indexer_static_init(ix, cap)
+ return ix, g
+
+def run(Nb=16384, T=2048, start=12288):
+ cap = Nb
+ ix, g = build(cap)
+ k = ix.k
+ ix.pool.copy_(torch.randn(ix.pool.shape, generator=g).to(DEV))
+ x = torch.randn(T, 256, generator=g).to(DEV); qr = torch.randn(T, 128, generator=g).to(DEV)
+ ar = torch.arange(cap, device=DEV)
+ pos = ar[start:start + T]
+ outs = []
+ for flag in (False, True):
+ SG.PRIME_IX = flag
+ ix.vgb.zero_(); ix.pool_backup = None
+ pool0 = ix.pool.clone()
+ a = SG.indexer_forward_static(ix, x, qr, pos, Nb, ar)
+ ix.pool.copy_(pool0)
+ outs.append(a)
+ SG.PRIME_IX = False
+ a, b = outs
+ assert a is not None and b is not None and a.shape == b.shape == (T, Nb), (None if a is None else a.shape, None if b is None else b.shape)
+ agree = float((a == b).float().mean())
+ print("allow agreement", agree, "selected/row", float(a.sum(1).float().mean()), float(b.sum(1).float().mean()))
+ assert agree > 0.999
+run()
+run(Nb=65536, T=2048, start=60000)
+print("ALL OK")
diff --git a/tests/test_vg_ring.py b/tests/test_vg_ring.py
new file mode 100644
index 0000000..a2f8e9e
--- /dev/null
+++ b/tests/test_vg_ring.py
@@ -0,0 +1,36 @@
+"""indexer vg ring: pool_fused.pool_update with a ring vgb (VR rows) == with the full-length vgb, positions beyond VR, batch of rows (T = 8 and a 300-row call)"""
+import importlib, os, sys, types
+import torch
+DEV = os.environ.get("DEV", "cpu")
+here = os.path.dirname(os.path.abspath(__file__))
+for n in ("exllamav3", "exllamav3.loader"):
+ m = types.ModuleType(n); m.__path__ = [os.path.join(here, "..", "exllamav3") if n == "exllamav3" else os.path.join(here, "..", "exllamav3", "loader")]; sys.modules[n] = m
+PF = importlib.import_module("exllamav3.loader.pool_fused")
+sys.path.insert(0, here)
+from test_lc_sparse import guarded
+
+def run(T, start, VR, k=4, d=128, rd=64, cap=2048):
+ g = torch.Generator().manual_seed(start)
+ full = torch.randn(cap, 2 * d, generator=g).to(DEV)
+ ring = torch.zeros(VR, 2 * d, device=DEV)
+ for j in range(cap):
+ if j < start + T:
+ ring[j % VR] = full[j]
+ class IX: pass
+ ape = torch.randn(k, d, generator=g).to(DEV); pn = torch.randn(d, generator=g).to(DEV)
+ cs = torch.randn(cap, rd // 2, generator=g).to(DEV); sn = torch.randn(cap, rd // 2, generator=g).to(DEV)
+ pos = torch.arange(start, start + T, device=DEV)
+ outs = []
+ for vgb, vr in ((full, 0), (ring, VR)):
+ ix = IX(); ix.w = {"ape": ape, "pool_norm": pn}; ix.eps = 1e-5; ix.k = k; ix.d = d; ix.rope_dim = rd; ix.pool = torch.zeros(cap // k, d, device=DEV)
+ ix._max_pos = cap; ix._table = lambda n, cs=cs, sn=sn: (cs, sn); ix.vg_ring = vr
+ vgb_g, chk = guarded(vgb)
+ ix.vgb = vgb_g
+ PF.pool_update(ix, pos)
+ chk(); outs.append(ix.pool.clone())
+ done = torch.arange(cap // k, device=DEV) * k + (k - 1) <= start + T - 1 # groups complete after the call (an open group is partial data, masked by the indexer)
+ done &= torch.arange(cap // k, device=DEV) >= start // k
+ assert int(done.sum()) >= 1 and torch.equal(outs[0][done], outs[1][done]), (T, start)
+for T, start, VR in ((1, 1003, 64), (8, 1001, 64), (300, 700, 4096), (8, 5, 64), (2048 - 2048 + 16, 1500, 64)):
+ run(T, start, VR)
+print("ALL OK")
diff --git a/tools/hy4/ngram.py b/tools/hy4/ngram.py
index e65b96d..631ef15 100644
--- a/tools/hy4/ngram.py
+++ b/tools/hy4/ngram.py
@@ -29,19 +29,22 @@ class NGram:
ext = self.ext if ext is None else ext
if ext <= 0:
return [], 0
- ss = s + list(d)
- if len(ss) < n:
+ d = list(d)
+ L, nd = len(s), len(d)
+ if L + nd < n:
return [], 0
- end = len(ss) - 1
+ g = lambda j: s[j] if j < L else d[j - L] # the combined sequence s + d without copying it (O(n) per call at 64K tokens)
+ end = L + nd - 1
# the draft region ends at `end`; the index holds only positions < len(s), so a hit is always an earlier occurrence
- key = tuple(ss[-n:])
+ key = tuple((s[L - (n - nd):] if n > nd else []) + d[max(0, nd - n):])
i = self.idx.get(key)
if i is not None and i >= end: # no drafts: the suffix of the sequence is its own latest occurrence, use the one before it
i = self.prev.get(key)
if i is None or i >= end:
return [], 0
m = n # extend the match backwards
- while i - m >= 0 and end - m >= 0 and ss[i - m] == ss[end - m] and m < 32:
+ while i - m >= 0 and end - m >= 0 and g(i - m) == g(end - m) and m < 32:
m += 1
- cont = ss[i + 1:i + 1 + ext]
+ a, b = i + 1, i + 1 + ext
+ cont = (s[a:min(b, L)] if a < L else []) + d[max(0, a - L):max(0, b - L)]
return cont, m