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 spec round: Engram row 0 staged during the draft chain (stage overlap) and one Triton kernel for the indexer k-pool update (HY4_IDX_POOLK)

YanissAmz65234fe4cb89
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
index b40f89a..6f9dfa0 100644
--- a/exllamav3/loader/mtp_head.py
+++ b/exllamav3/loader/mtp_head.py
@@ -308,6 +308,10 @@ class MTPGraphCU(MTPGraph):
return out
+import os
+_STAGE_OV = [False]
+
+
def spec_generate(gd, mg, y, hcur, n_new, cu=False, timers=None):
"""Greedy speculative decode on the whole-step graph. gd = GraphDecoder (the trunk, context already in it), mg = MTPGraph / MTPGraphCU (k drafts per round),
y = the trunk's greedy token after the context (host int, NOT yet fed), hcur = the trunk hidden [1, D] of the last context position, n_new = tokens wanted.
@@ -322,7 +326,10 @@ def spec_generate(gd, mg, y, hcur, n_new, cu=False, timers=None):
while len(out) < n_new:
j = fw.n - 1
ta = pc()
- d = (mg.run(cu_toks, cu_h, cu_p) if cu else mg.run(y, hcur, j)).tolist()
+ dd = mg.run(cu_toks, cu_h, cu_p) if cu else mg.run(y, hcur, j)
+ if _STAGE_OV[0]:
+ gd.prestage(y)
+ d = dd.tolist()
tb = pc()
toks = [y] + d
_lg, amv, _x, hv = gd.step_rows(toks)
diff --git a/exllamav3/loader/pool_fused.py b/exllamav3/loader/pool_fused.py
new file mode 100644
index 0000000..f88579d
--- /dev/null
+++ b/exllamav3/loader/pool_fused.py
@@ -0,0 +1,58 @@
+"""One Triton kernel for the k-pool update of the static indexer (HY4_IDX_POOLK=1): gather the (partial) group of each verify row from the per-position
+(value | gate) rows, softmax over the group with the ape bias, weighted sum, rms norm, rope of the trailing rope_dim, store into the pool row.
+Replaces ~10 small torch kernels per indexer layer. Same maths as the torch path in step_graph.indexer_forward_static (fp32; exp / rsqrt rounding may differ in the last ulp)."""
+import torch
+import triton
+import triton.language as tl
+
+ENABLED = False
+
+
+def _pooled(vgb, ape, g0, offs, k: tl.constexpr, d: 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)
+ 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)
+ 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)
+ acc += (tl.exp(gj - m) / s) * vj
+ return acc
+
+
+def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d: tl.constexpr, rd: 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)
+ 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)
+ 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)
+ c = tl.load(cosb + g0 * h + ii)
+ s = tl.load(sinb + g0 * h + ii)
+ tl.store(pool + gi * d + oa, na * c - nb * s)
+ tl.store(pool + gi * d + ob, na * s + nb * c)
+
+
+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)
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
index 9d6fea9..5cd5570 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -39,6 +39,10 @@ def _rms(x, w, eps):
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
+from . import pool_fused as _PF
+_PF.ENABLED = os.environ.get("HY4_IDX_POOLK", "0") == "1"
+
+
def indexer_static_init(ix, cap):
"""FusedKPoolIndexer -> fixed buffers: pool [cap // k, d], per-position (value | gate) rows vgb [cap, 2d] (open group filled from the eager state), rope table to cap"""
k, d = ix.k, ix.d
@@ -66,12 +70,15 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):
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)
- g0 = (pos // k) * k
- rows = ix.vgb[g0[:, None] + ar[:k][None, :]] # [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)
- ix.pool.index_copy_(0, pos // k, pooled) # a group still open holds partial data here; it stays masked until it is complete
+ 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
+ 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)
+ ix.pool.index_copy_(0, pos // k, pooled) # a group still open holds partial data here; it stays masked until it is complete
if Nb <= (ix.n_top + 1) * k: # every position of this bucket sees <= n_top groups: the selection is all-causal (the eager path returns None)
return None
T = x.shape[0]
@@ -298,17 +305,20 @@ class GraphDecoder:
self.stats["captures"] += 1
return g
- def stage(self, start, T=1):
- """host side of T tokens: Engram hash + threaded pread of their rows into pinned staging, one H2D each (fw.tokens holds them at start .. start + T - 1)"""
+ def _jobs(self, start, t0, t1, toks):
fw = self.fw
jobs = []
- toks = fw.tokens
for i in sorted(fw.ple):
e = fw.eng[i]
- for t in range(T):
+ for t in range(t0, t1):
ids, valid = engram_row_ids(e, toks, start + t)
self.vpin[e.e, t] = torch.tensor(valid)
jobs += [(e, t, c, r) for c, r in enumerate(ids)]
+ return jobs
+
+ def _submit(self, jobs):
+ """spread the row reads over the thread pool; returns futures (preadv releases the GIL)"""
+ fw = self.fw
tab = fw.table
fi = tab.off >> 48
fd, o0, rb, nrows = fw.g.fds[fi], fw.g.bases[fi] + (tab.off & ((1 << 48) - 1)), tab.row_bytes, tab.rows
@@ -325,7 +335,29 @@ class GraphDecoder:
if os.preadv(fd, [mv], o0 + r * rb) != rb:
raise IOError(f"{tab.name}: short read of row {r}")
per = max(1, -(-len(jobs) // _IO_W))
- list(_POOL.map(rd, [jobs[a:a + per] for a in range(0, len(jobs), per)]))
+ return [_POOL.submit(rd, jobs[a:a + per]) for a in range(0, len(jobs), per)]
+
+ def prestage(self, tok):
+ """HY4_STAGE_OV: row 0 of the next verify (token tok at position fw.n) does not depend on the drafts: start its Engram reads now, while the draft chain runs on the GPU"""
+ fw = self.fw
+ if self.ev_set:
+ self.ev.synchronize() # the previous replay has finished reading the pinned staging rows
+ start = fw.n
+ jobs = self._jobs(start, 0, 1, fw.tokens + [int(tok)])
+ self._pre = (start, int(tok), self._submit(jobs))
+
+ def stage(self, start, T=1):
+ """host side of T tokens: Engram hash + threaded pread of their rows into pinned staging, one H2D each (fw.tokens holds them at start .. start + T - 1)"""
+ fw = self.fw
+ pre, self._pre = getattr(self, "_pre", None), None
+ t0 = 0
+ if pre is not None and pre[0] == start and pre[1] == fw.tokens[start]:
+ t0 = 1
+ futs = self._submit(self._jobs(start, t0, T, fw.tokens)) if T > t0 else []
+ if t0:
+ futs += pre[2]
+ for f in futs:
+ f.result()
self.gs.eng_raw.copy_(self.rpin, non_blocking=True)
self.gs.eng_valid.copy_(self.vpin, non_blocking=True)