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 decode: T-row graph step for verify rows (step_rows / rewind), batched k_b/v_b and head mat-vec for T rows, MTP draft chain graph
YanissAmz8a9d0919180b
diff --git a/exllamav3/loader/attn_eager.py b/exllamav3/loader/attn_eager.pyindex bd08f11..852e568 100644--- a/exllamav3/loader/attn_eager.py+++ b/exllamav3/loader/attn_eager.py@@ -96,7 +96,7 @@ def q(m, cur, pos):qp = _KVF.rope_q(qq, table(m.rope_dim, m.theta, qq.device, pos), pos, m.nope, m.rope_dim)else:qp = rope(qq[..., m.nope:], pos, m.theta)- qlat = m.bg_kb.mv(m._q(qn, "kb")) if (_BG.ENABLED and T == 1 and getattr(m, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))+ qlat = m.bg_kb.mv(m._q(qn, "kb")) if (_BG.ENABLED and T <= _BG.MAXT and getattr(m, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))return m._h(qlat, "q"), m._h(qp, "q")diff --git a/exllamav3/loader/head_bf16.py b/exllamav3/loader/head_bf16.pyindex 5b33b43..555b14c 100644--- a/exllamav3/loader/head_bf16.py+++ b/exllamav3/loader/head_bf16.py@@ -26,14 +26,36 @@ def _k_head(w_ptr, h_ptr, o_ptr, V, D, BV: tl.constexpr, BD: tl.constexpr):tl.store(o_ptr + rows, acc, mask=rm)+def _k_headt(w_ptr, h_ptr, o_ptr, V, D, T, BT: tl.constexpr, BV: tl.constexpr, BD: tl.constexpr):+ """T rows (verify): each weight tile is read once and applied to all rows; out [T, V]"""+ rows = tl.program_id(0) * BV + tl.arange(0, BV)+ rm = rows < V+ tt = tl.arange(0, BT)+ tm = tt < T+ acc = tl.zeros([BT, BV], dtype=tl.float32)+ for d0 in range(0, D, BD):+ cols = d0 + tl.arange(0, BD)+ cm = cols < D+ w = tl.load(w_ptr + rows[:, None] * D + cols[None, :], mask=rm[:, None] & cm[None, :], other=0.0).to(tl.float32)+ hv = tl.load(h_ptr + tt[:, None] * D + cols[None, :], mask=tm[:, None] & cm[None, :], other=0.0)+ acc += tl.sum(w[None, :, :] * hv[:, None, :], axis=2)+ tl.store(o_ptr + tt[:, None] * V + rows[None, :], acc, mask=tm[:, None] & rm[None, :])++def usable(h, W):- return ENABLED and h.shape[0] == 1 and W.dim() == 2 and W.is_contiguous() and h.dtype == torch.float32 and W.dtype in (torch.bfloat16, torch.float16, torch.float32) \+ return ENABLED and 1 <= h.shape[0] <= 16 and W.dim() == 2 and W.is_contiguous() and h.dtype == torch.float32 and W.dtype in (torch.bfloat16, torch.float16, torch.float32) \and (W.is_cuda or os.environ.get("TRITON_INTERPRET", "0") == "1")def gemv(h, W):- """h [1, D] fp32, W [V, D] -> logits [1, V] fp32"""+ """h [T, D] fp32 (T <= 16), W [V, D] -> logits [T, V] fp32"""V, D = W.shape+ T = h.shape[0]+ if T > 1:+ out = torch.empty(T, V, dtype=torch.float32, device=W.device)+ _k_headt[(triton.cdiv(V, BV),)](W, h.contiguous(), out, V, D, T, BT=triton.next_power_of_2(T), BV=BV, BD=min(BD, 128), num_warps=4)+ return outout = torch.empty(1, V, dtype=torch.float32, device=W.device)_k_head[(triton.cdiv(V, BV),)](W, h.contiguous(), out, V, D, BV=BV, BD=BD, num_warps=4)return outdiff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 271f402..b988b9a 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -567,7 +567,7 @@ class Hy4Forward:pre, post = self._site(x, L.hca)cur = rms((x * pre[:, :, None]).sum(1), self.eps) * L.attn_normmla = L.mla- if gs is not None and _KVF.ENABLED and _AE.ENABLED: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernel+ 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 kernelkc = gs.kv_row_fused(i, mla, cur, pos)else:with tm.t("attn proj"):diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.pyindex 6e819ec..d76eb39 100644--- a/exllamav3/loader/mla_bgemv.py+++ b/exllamav3/loader/mla_bgemv.py@@ -14,6 +14,7 @@ import triton.language as tlENABLED = os.environ.get("HY4_MLA_BG", "0") == "1"BN = int(os.environ.get("HY4_BG_BN", "16"))BK = int(os.environ.get("HY4_BG_BK", "128"))+MAXT = 8 # rows served by the batched kernels (verify rows)@triton.jit@@ -35,6 +36,27 @@ def _k_bg(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxh, BN: tl.constexpr, BK: tl.cotl.store(o_ptr + h * N + rows, acc, mask=rm)+def _k_bgt(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxt, sxh, T, BT: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):+ """T rows (verify): each weight tile is read ONCE and applied to all T rows. out[t, h, n] = sum_k (q * d)[h, n, k] * x[t, h, k]"""+ h = tl.program_id(0)+ rows = tl.program_id(1) * BN + tl.arange(0, BN)+ rm = rows < N+ tt = tl.arange(0, BT)+ tm = tt < T+ acc = tl.zeros([BT, BN], dtype=tl.float32)+ qrow = (h * N + rows)[:, None] * K+ drow = (h * N + rows)[:, None] * NB+ for k0 in range(0, K, BK):+ cols = k0 + tl.arange(0, BK)+ cm = cols < K+ m2 = rm[:, None] & cm[None, :]+ w = tl.load(q_ptr + qrow + cols[None, :], mask=m2, other=0).to(tl.float32) * tl.load(d_ptr + drow + (cols // 32)[None, :], mask=m2, other=0.0).to(tl.float32)+ xv = tl.load(x_ptr + tt[:, None] * sxt + h * sxh + cols[None, :], mask=tm[:, None] & cm[None, :], other=0.0)+ acc += tl.sum(w[None, :, :] * xv[:, None, :], axis=2)+ tl.store(o_ptr + (tt[:, None] * (tl.num_programs(0) * N)) + h * N + rows[None, :], acc, mask=tm[:, None] & rm[None, :])++class Q8Batched:"""[H, N, K] Q8_0 matrix as int8 + fp16 scales on a device"""@@ -45,7 +67,13 @@ class Q8Batched:self.H, self.N, self.K = H, N, Kdef mv(self, x):- """x [1, H, K] fp32 -> [1, H, N] fp32"""+ """x [T, H, K] fp32 -> [T, H, N] fp32 (T == 1: the single-row kernel; T > 1: one kernel, weights read once)"""+ if x.dim() == 3 and x.shape[0] > 1 and x.stride(-1) == 1:+ T = x.shape[0]+ out = torch.empty(T, self.H, self.N, dtype=torch.float32, device=x.device)+ _k_bgt[(self.H, triton.cdiv(self.N, BN))](self.q, self.d, x, out, self.N, self.K, self.K // 32, x.stride(0), x.stride(1), T,+ BT=triton.next_power_of_2(T), BN=BN, BK=min(BK, 64), num_warps=4)+ return outout = torch.empty(self.H, self.N, dtype=torch.float32, device=x.device)if x.dim() == 3 and x.shape[0] == 1 and x.stride(-1) == 1: # [1, H, K] view with a head stride (e.g. the nope part of q): no copyxv, sxh = x, x.stride(1)diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex d17624c..47b3ed9 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -99,7 +99,7 @@ class Hy4MLA:qr = rms(self._q(cur, "wq_a") @ self.wq_a.T, self.eps) * self.q_a_normq = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)- qlat = self.bg_kb.mv(self._q(qn, "kb")) if (_BG.ENABLED and T == 1 and getattr(self, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))+ qlat = self.bg_kb.mv(self._q(qn, "kb")) if (_BG.ENABLED and T <= _BG.MAXT and getattr(self, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))return self._h(qlat, "q"), self._h(qp, "q")def attend(self, cur, pos, kcache, kpos, allow=None):@@ -115,7 +115,7 @@ class Hy4MLA: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"):- kqv = (self.bg_vb.mv(self._q(o, "vb")) if (_BG.ENABLED and T == 1 and getattr(self, "bg_vb", None) is not None) else torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb"))).reshape(T, H * self.vd)+ kqv = (self.bg_vb.mv(self._q(o, "vb")) if (_BG.ENABLED and T <= _BG.MAXT and getattr(self, "bg_vb", None) is not None) else torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb"))).reshape(T, H * self.vd)gated, out = self.gate_out(cur, kqv)return kqv, gated, outdiff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex cc2931b..f7c3daa 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -103,3 +103,65 @@ class Hy4MTP:outs.append(tok)h = yreturn outs+++class MTPGraph:+ """the draft chain of k head steps as ONE HIP graph per context bucket: static inputs (token, trunk state, head position), greedy argmax feeds the next+ step on the device, output = the k drafted tokens [k] (device). No host work between the steps."""++ BUCKET = 512++ def __init__(self, mt, k):+ self.mt, self.k = mt, k+ dev = mt.dev+ D = mt.fw.D+ self.tok0 = torch.zeros(1, dtype=torch.long, device=dev)+ self.pos0 = torch.zeros(1, dtype=torch.long, device=dev)+ self.h0 = torch.zeros(1, D, device=dev)+ self.hin = torch.zeros(2, dtype=torch.long).pin_memory()+ self.inp = torch.zeros(2, dtype=torch.long, device=dev)+ self.graphs, self.pool = {}, torch.cuda.graph_pool_handle()+ self.ev, self.ev_set = torch.cuda.Event(), False++ def body(self, N):+ mt = self.mt+ outs, tok, h = [], self.inp[0:1], self.h0+ pos = self.inp[1:2]+ for i in range(self.k):+ y, lg = mt.step(tok, h, pos + i if i else pos, N)+ tok = torch.argmax(lg).reshape(1)+ outs.append(tok)+ h = y+ return torch.cat(outs)++ def _graph(self, N):+ g = self.graphs.get(N)+ if g is not None:+ return g+ s = torch.cuda.Stream()+ s.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(s):+ for _ in range(2):+ self.body(N)+ torch.cuda.current_stream().wait_stream(s)+ torch.cuda.synchronize()+ cg = torch.cuda.CUDAGraph()+ with torch.cuda.graph(cg, pool=self.pool):+ out = self.body(N)+ g = self.graphs[N] = (cg, out)+ return g++ def run(self, tok, h, j):+ """tok: host int (the token of the pair, x_{j+1}), h: device [1, D] trunk state h_j, j: head position -> device tensor [k] of drafts"""+ mt = self.mt+ N = min(mt.cap, ((j + self.k) // self.BUCKET + 1) * self.BUCKET)+ if self.ev_set:+ self.ev.synchronize()+ self.hin[0], self.hin[1] = int(tok), int(j)+ self.inp.copy_(self.hin, non_blocking=True)+ self.h0.copy_(h)+ self.ev.record()+ self.ev_set = True+ cg, out = self._graph(N)+ cg.replay()+ return outdiff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.pyindex d6e95cd..5e5d977 100644--- a/exllamav3/loader/step_graph.py+++ b/exllamav3/loader/step_graph.py@@ -23,6 +23,7 @@ from . import step_nosync as _nsfrom .engram_rows import QB, E4M3, E8M0BUCKET = int(os.environ.get("HY4_GRAPH_BUCKET", "512"))+TM = int(os.environ.get("HY4_GRAPH_TM", "8")) # max rows of one graph step (verify rows)MASK64 = (1 << 64) - 1_POOL = ThreadPoolExecutor(max_workers=int(os.environ.get("HY4_GRAPH_IO", "16")))@@ -119,25 +120,33 @@ def engram_row_ids(e, tokens, p):# ---------------------------------------------------------------------------------------------------- static context seen by Hy4Forward.layerclass _GS:def __init__(self, fw, cap):- self.fw, self.cap, self.Nb = fw, cap, 0+ self.fw, self.cap, self.Nb, self.T = fw, cap, 0, 1dev = fw.dev- self.inp = torch.zeros(2, dtype=torch.long, device=dev) # [token, position]- self.tok, self.pos = self.inp[0:1], self.inp[1:2]+ self.inp = torch.zeros(2, TM, dtype=torch.long, device=dev) # row 0 tokens, row 1 positions (first T columns used)self.ar = torch.arange(cap, device=dev)self.eng_raw = self.eng_valid = None+ @property+ def tok(self):+ return self.inp[0, :self.T]++ @property+ def pos(self):+ return self.inp[1, :self.T]+# -- Engram: rows are staged on the host before the replay, decoded + applied inside the graphdef engram(self, fw, i, x):e = fw.eng[i]- u = self.eng_raw[e.e]+ T = self.T+ u = self.eng_raw[e.e, :T] # [T, n_cols, row_bytes]tab = e.tablet4, t8 = _tabs(fw.dev)if tab.layout == "plain":rows = t4[u.long()]else:w = tab.width- rows = (t4[u[:, :w].long()].reshape(u.shape[0], -1, QB) * t8[u[:, w:].long()][:, :, None]).reshape(u.shape[0], w)- return e.apply(x, rows[None], self.eng_valid[e.e][None])+ rows = (t4[u[..., :w].long()].reshape(T, u.shape[1], -1, QB) * t8[u[..., w:].long()][..., None]).reshape(T, u.shape[1], w)+ return e.apply(x, rows, self.eng_valid[e.e, :T])def append_kv(self, i, kn):b = _ns.state(self.fw).kv[i]@@ -154,7 +163,12 @@ class _GS:return b[:self.Nb]def indexer(self, fw, i, cur, qr, N):- return indexer_forward_static(fw._indexer_fused(i), cur, qr, self.pos, N, self.ar)+ ix = fw._indexer_fused(i)+ if self.T == 1:+ return indexer_forward_static(ix, cur, qr, self.pos, N, self.ar)+ # verify rows: positions in order, each row writes its pool / vg state before the next row selects (same state as T eager steps)+ outs = [indexer_forward_static(ix, cur[r:r + 1], qr[r:r + 1], self.pos[r:r + 1], N, self.ar) for r in range(self.T)]+ return None if outs[0] is None else torch.cat(outs, 0)_T = {}@@ -177,7 +191,7 @@ class GraphDecoder:self.graphs, self.pool = {}, torch.cuda.graph_pool_handle()self.prepared = Falseself.expect_n = None- self.hin = torch.zeros(2, dtype=torch.long).pin_memory()+ self.hin = torch.zeros(2, TM, dtype=torch.long).pin_memory()self.stats = {"captures": 0, "replays": 0}self.ev = torch.cuda.Event()self.ev_set = False@@ -210,10 +224,10 @@ class GraphDecoder:fw.eng[i] = Hy4EngramGPU(fw.g, i, fw.dev, table=fw.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else fw._lin)e0 = fw.eng[min(fw.ple)]nE, nc, rb = len(fw.ple), e0.n_cols, e0.table.row_bytes- gs.eng_raw = torch.zeros(nE, nc, rb, dtype=torch.uint8, device=fw.dev)- gs.eng_valid = torch.zeros(nE, nc, dtype=torch.float32, device=fw.dev)- self.rpin = torch.zeros(nE, nc, rb, dtype=torch.uint8).pin_memory()- self.vpin = torch.zeros(nE, nc, dtype=torch.float32).pin_memory()+ gs.eng_raw = torch.zeros(nE, TM, nc, rb, dtype=torch.uint8, device=fw.dev)+ gs.eng_valid = torch.zeros(nE, TM, nc, dtype=torch.float32, device=fw.dev)+ self.rpin = torch.zeros(nE, TM, nc, rb, dtype=torch.uint8).pin_memory()+ self.vpin = torch.zeros(nE, TM, nc, dtype=torch.float32).pin_memory()self.rnp = self.rpin.numpy()for i in range(fw.n_layers):if fw._layer(i).ix:@@ -249,17 +263,17 @@ class GraphDecoder:x = fw.layer(i, x, gs.pos, None, 0)fw._ns_dev = Truetry:- lg = fw._head(x, False)+ lg = fw._head(x, gs.T > 1) # T > 1: logits of every row [T, V]finally:fw._ns_dev = False- return lg, torch.argmax(lg), x, fw._h+ return lg, torch.argmax(lg, -1), x, fw._h- def _graph(self, Nb):- g = self.graphs.get(Nb)+ def _graph(self, Nb, T=1):+ g = self.graphs.get((Nb, T))if g is not None:return gfw, gs = self.fw, self.gs- gs.Nb = Nb+ gs.Nb, gs.T = Nb, Tfw._gs = gstry:s = torch.cuda.Stream()@@ -274,54 +288,69 @@ class GraphDecoder:out = self.body()finally:fw._gs = None- g = self.graphs[Nb] = (cg, out)+ g = self.graphs[(Nb, T)] = (cg, out)self.stats["captures"] += 1return g- def stage(self, start):- """host side of one token: Engram hash + threaded pread of this token's rows into pinned staging, one H2D each"""+ 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.fwjobs = []toks = fw.tokensfor i in sorted(fw.ple):e = fw.eng[i]- ids, valid = engram_row_ids(e, toks, start)- self.vpin[e.e] = torch.tensor(valid)- jobs += [(e, c, r) for c, r in enumerate(ids)]+ for t in range(T):+ 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)]def rd(j):- e, c, r = j- self.rnp[e.e, c] = e.table.raw_row(r)+ e, t, c, r = j+ self.rnp[e.e, t, c] = e.table.raw_row(r)list(_POOL.map(rd, jobs))self.gs.eng_raw.copy_(self.rpin, non_blocking=True)self.gs.eng_valid.copy_(self.vpin, non_blocking=True)def step(self, tok):"""append host token id `tok` at position fw.n; returns the DEVICE logits [V] of this position (valid until the next step)"""+ return self.step_rows([int(tok)])[0]++ def step_rows(self, toks):+ """append T host token ids at positions fw.n .. fw.n + T - 1 in ONE graph replay (T = 1: a plain decode step). Returns (logits, argmax, x, h) as DEVICE+ tensors (T = 1: logits [V], argmax scalar; T > 1: [T, V], [T]). fw.n / fw.tokens advance by T: a verifier that rejects rows rewinds them (K rows and+ indexer state are written by position, so the rejected rows are simply overwritten by the next step)."""fw = self.fw+ T = len(toks)+ assert 1 <= T <= TMif not self.prepared:self.prepare()start = fw.n- assert start < self.cap, "context past the graph cap (HY4_NOSYNC_CAP)"+ assert start + T <= self.cap, "context past the graph cap (HY4_NOSYNC_CAP)"if self.expect_n != start: # an eager prefill / reset ran since the last graph step: refill the indexer vg rows from its statefor i in range(fw.n_layers):if fw._layer(i).ix:indexer_static_init(fw._indexer_fused(i), self.cap)if self.ev_set:self.ev.synchronize() # the previous replay has read the pinned staging buffers: safe to overwrite them- fw.tokens.append(int(tok))- Nb = min(self.cap, (start // BUCKET + 1) * BUCKET)+ fw.tokens.extend(int(t) for t in toks)+ Nb = min(self.cap, ((start + T - 1) // BUCKET + 1) * BUCKET)self.gs.Nb = Nb- self.hin[0], self.hin[1] = int(tok), start+ self.hin[0, :T] = torch.tensor([int(t) for t in toks])+ self.hin[1, :T] = torch.arange(start, start + T)self.gs.inp.copy_(self.hin, non_blocking=True)- self.stage(start)- cg, _out = self._graph(Nb)- lg = _out[0]+ self.stage(start, T)+ cg, _out = self._graph(Nb, T)self.x_out = _out[2]fw._h = _out[3]cg.replay()self.ev.record()self.ev_set = True- fw.n += 1+ fw.n += Tself.expect_n = fw.nself.stats["replays"] += 1- return lg+ return _out[0], _out[1], _out[2], _out[3]++ def rewind(self, n):+ """verifier rejected rows: the sequence continues from position n (<= fw.n); stale K / indexer rows past n are overwritten by position"""+ fw = self.fw+ del fw.tokens[n:]+ fw.n = self.expect_n = n