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 glue: fused K-row / q-rope kernels take the verify rows (HY4_KV_FUSED_MAXT 16, was 1 row) and a two-launch fused Engram block (HY4_ENGRAM_FUSED=1, opt-in); CPU-interpreter row tests
YanissAmz63074bb24ef3
diff --git a/exllamav3/loader/attn_eager.py b/exllamav3/loader/attn_eager.pyindex 852e568..69e1475 100644--- a/exllamav3/loader/attn_eager.py+++ b/exllamav3/loader/attn_eager.py@@ -92,7 +92,7 @@ def q(m, cur, pos):qr = rms(qa, m.eps) * m.q_a_normqq = (m._q(qr, "wq_b") @ m.wq_b.T).view(T, H, m.hd)qn = qq[..., :m.nope]- if _KVF.ENABLED and T == 1 and qq.is_cuda: # HY4_KV_FUSED: the pe rotation in one launch (no slice copies)+ if _KVF.ENABLED and 1 <= T <= _KVF.MAXT and qq.is_cuda: # HY4_KV_FUSED: the pe rotation in one launch (no slice copies)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)diff --git a/exllamav3/loader/engram_fused.py b/exllamav3/loader/engram_fused.pynew file mode 100644index 0000000..f874262--- /dev/null+++ b/exllamav3/loader/engram_fused.py@@ -0,0 +1,64 @@+"""HY4_ENGRAM_FUSED=1: the Engram block of a layer in TWO Triton launches around its one GEMM (old: ~35 torch launches per Engram layer: rms / pow / mean / rsqrt / abs / clamp /+sqrt / neg / compare / sigmoid chains, the dominant part of the decode step's torch glue).+ pre(rows, lookup_norm, valid) r = rms(rows) * lookup_norm * valid [T, n_cols * hd]+ (torch) kv = r @ kv_w.T+ post(kv, kv_b, x, gate, hc_scale, pre_gamma, valid) x + delta [T, hc, D] (same maths as Hy4Engram.apply, M:5292-5353)+Shapes come from the tensors; the reduction order differs from torch (1e-7 relative)."""+import os+import torch+import triton+import triton.language as tl++ENABLED = os.environ.get("HY4_ENGRAM_FUSED", "0") == "1"+++def _k_pre(rows_ptr, ln_ptr, valid_ptr, o_ptr, HD, eps, BH: tl.constexpr, NC: tl.constexpr):+ pid = tl.program_id(0) # row t * NC + col+ d = tl.arange(0, BH)+ m = d < HD+ x = tl.load(rows_ptr + pid * HD + d, mask=m, other=0.0)+ rc = tl.rsqrt(tl.sum(x * x, axis=0) / HD + eps)+ w = tl.load(ln_ptr + (pid % NC) * HD + d, mask=m, other=0.0)+ v = tl.load(valid_ptr + pid)+ tl.store(o_ptr + pid * HD + d, x * rc * w * v, mask=m)+++def _k_post(kv_ptr, kvb_ptr, x_ptr, gate_ptr, hcs_ptr, pg_ptr, valid_ptr, o_ptr, D, eps, inv_sqrt_d,+ HC: tl.constexpr, NC: tl.constexpr, BD: tl.constexpr):+ t = tl.program_id(0)+ d = tl.arange(0, BD)+ m = d < D+ kvt = kv_ptr + t * (HC + 1) * D+ val = tl.load(kvt + HC * D + d, mask=m, other=0.0) + tl.load(kvb_ptr + HC * D + d, mask=m, other=0.0)+ sig = val * tl.rsqrt(tl.sum(val * val, axis=0) / D + eps) * tl.load(pg_ptr + d, mask=m, other=0.0)+ vs = 0.0+ for c in range(NC):+ vs += tl.load(valid_ptr + t * NC + c)+ anyv = tl.where(vs > 0, 1.0, 0.0)+ for h in range(HC):+ xh = tl.load(x_ptr + (t * HC + h) * D + d, mask=m, other=0.0)+ key = tl.load(kvt + h * D + d, mask=m, other=0.0) + tl.load(kvb_ptr + h * D + d, mask=m, other=0.0)+ rx = xh * tl.rsqrt(tl.sum(xh * xh, axis=0) / D + eps)+ rk = key * tl.rsqrt(tl.sum(key * key, axis=0) / D + eps)+ dot = tl.sum(rx * rk * tl.load(gate_ptr + h * D + d, mask=m, other=0.0), axis=0) * inv_sqrt_d+ mag = tl.sqrt(tl.maximum(tl.abs(dot), 1e-6))+ sgn = tl.where(dot < 0, -1.0, 1.0)+ g = 1.0 / (1.0 + tl.exp(-(mag * sgn)))+ delta = sig * (g + tl.load(hcs_ptr + h * D + d, mask=m, other=0.0))+ tl.store(o_ptr + (t * HC + h) * D + d, xh + delta * anyv, mask=m)+++def apply(e, x, rows, valid):+ """== Hy4Engram.apply for fp32 [T, hc, D] x, rows [T, n_cols, hd], valid [T, n_cols] float"""+ T, hc, D = x.shape+ nc, hd = rows.shape[1], rows.shape[2]+ rows = rows.contiguous()+ r = torch.empty(T, nc * hd, dtype=torch.float32, device=x.device)+ _k_pre[(T * nc,)](rows, e.lookup_norm, valid.contiguous(), r, hd, e.eps, BH=triton.next_power_of_2(hd), NC=nc, num_warps=1)+ kv = r @ e.kv.T+ out = torch.empty_like(x)+ _k_post[(T,)](kv.contiguous(), e.kv_b, x.contiguous(), e.gate, e.hc_scale, e.pre_gamma, valid.contiguous(), out, D, e.eps, D ** -0.5,+ HC=hc, NC=nc, BD=triton.next_power_of_2(D), num_warps=8)+ return outdiff --git a/exllamav3/loader/engram_rows.py b/exllamav3/loader/engram_rows.pyindex 46807f7..b06e5cc 100644--- a/exllamav3/loader/engram_rows.py+++ b/exllamav3/loader/engram_rows.py@@ -216,6 +216,9 @@ class Hy4Engram:def apply(self, x: torch.Tensor, rows: torch.Tensor, valid: torch.Tensor) -> torch.Tensor:"""x [T, hc, n_embd] fp32 stream, rows [T, n_cols, head_dim] decoded table rows, valid [T, n_cols] -> x + delta (M:5292-5353)."""+ if not self.q8_act and x.is_cuda and x.dtype == torch.float32 and os.environ.get("HY4_ENGRAM_FUSED", "0") == "1": # two fused launches around the GEMM (engram_fused.py)+ from . import engram_fused as _EF+ return _EF.apply(self, x, rows, valid)T, eps = x.shape[0], self.epsr = rms(rows, eps) * self.lookup_norm * valid[:, :, None] # delta 1r = r.reshape(T, -1)diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex d569163..2f3af8c 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -801,7 +801,7 @@ class Hy4Forward:ring = getattr(mla, "kv_ring", 0) # HY4_SWA_RING: window layers keep a ring of `ring` K rows instead of the full contextmla.ring_call = ring if gs is not None else 0slots = gs is not None and getattr(gs, "slots", False) # multi-session step (step_mu): K rows / indexer / attention go through the slot slabs- if gs is not None and gs.T == 1 and _KVF.ENABLED and _AE.ENABLED and not slots: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernel+ if gs is not None and 1 <= gs.T <= _KVF.MAXT and _KVF.ENABLED and _AE.ENABLED and not slots: # 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/kv_fused.py b/exllamav3/loader/kv_fused.pyindex ab2b30b..36ec888 100644--- a/exllamav3/loader/kv_fused.py+++ b/exllamav3/loader/kv_fused.py@@ -8,11 +8,14 @@ import tritonimport triton.language as tlENABLED = os.environ.get("HY4_KV_FUSED", "0") == "1"+MAXT = int(os.environ.get("HY4_KV_FUSED_MAXT", "16")) # rows per step the fused kernels take (verify rows included); 1 = decode only (old behaviour)@triton.jitdef _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)+ row = tl.program_id(0) # one program per row: T = 1 decode and the T-row verify share the kernel+ c_ptr += row * sc+ pos = tl.load(pos_ptr + row)if RING > 0:slot = pos % RING # window layer: ring buffer row (the rope table is still indexed by the absolute position)else:@@ -37,14 +40,17 @@ def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, Pdef 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), RING=ring, num_warps=4)+ """c [T, R+P] fp32 (unit column stride), w [R], tab [n, 2, P/2, 2], pos [T] long device, kbuf [cap, R+P] fp32"""+ _k_kv[(c.shape[0],)](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-def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqh, soh, NOPE: tl.constexpr, P: tl.constexpr):+def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqt, sqh, sot, soh, NOPE: tl.constexpr, P: tl.constexpr):h = tl.program_id(0)- pos = tl.load(pos_ptr)+ row = tl.program_id(1)+ q_ptr += row * sqt+ o_ptr += row * sot+ pos = tl.load(pos_ptr + row)H: tl.constexpr = P // 2offh = tl.arange(0, H)x0 = tl.load(q_ptr + h * sqh + NOPE + 2 * offh)@@ -59,8 +65,8 @@ def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqh, soh, NOPE: tl.constexpr, P: tldef rope_q(qq, tab, pos, nope, P):- """qq [1, H, hd] fp32 (unit last stride; the pe part is qq[..., nope:nope+P]) -> rotated pe [1, H, P] (one launch)"""- H = qq.shape[1]- out = torch.empty(1, H, P, dtype=torch.float32, device=qq.device)- _k_qrope[(H,)](qq, tab, pos, out, qq.stride(1), out.stride(1), NOPE=nope, P=P, num_warps=1)+ """qq [T, H, hd] fp32 (unit last stride; the pe part is qq[..., nope:nope+P]), pos [T] -> rotated pe [T, H, P] (one launch)"""+ T, H = qq.shape[0], qq.shape[1]+ out = torch.empty(T, H, P, dtype=torch.float32, device=qq.device)+ _k_qrope[(H, T)](qq, tab, pos, out, qq.stride(0), qq.stride(1), out.stride(0), out.stride(1), NOPE=nope, P=P, num_warps=1)return outdiff --git a/tools/hy4/step/engram_test.py b/tools/hy4/step/engram_test.pynew file mode 100644index 0000000..10e5861--- /dev/null+++ b/tools/hy4/step/engram_test.py@@ -0,0 +1,35 @@+"""Engram fused vs Hy4Engram.apply reference (random shapes like the model: hc 4, D 4096? small here). GPU if present else TRITON_INTERPRET=1"""+import os, sys, importlib.util, types+import torch+dev = "cuda" if torch.cuda.is_available() and os.environ.get("TRITON_INTERPRET") != "1" else "cpu"+L = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "exllamav3", "loader")+sp = importlib.util.spec_from_file_location("engf", os.path.join(L, "engram_fused.py")); EF = importlib.util.module_from_spec(sp); sys.modules["engf"] = EF; sp.loader.exec_module(EF)+def rms(x, eps): return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)+class E: pass+def ref(e, x, rows, valid): # copy of Hy4Engram.apply (q8_act off)+ T, eps = x.shape[0], e.eps+ r = rms(rows, eps) * e.lookup_norm * valid[:, :, None]+ r = r.reshape(T, -1)+ kv = (r @ e.kv.T).reshape(T, e.hc + 1, e.n_embd) + e.kv_b+ key, value = kv[:, :e.hc], kv[:, e.hc]+ dot = (rms(x, eps) * rms(key, eps) * e.gate).sum(-1) / e.n_embd ** 0.5+ mag = dot.abs().clamp_min(1e-6).sqrt()+ sign = 1.0 - 2.0 * (-dot > 0).float()+ gate = torch.sigmoid(mag * sign)+ signal = rms(value, eps) * e.pre_gamma+ delta = signal[:, None, :] * (gate[:, :, None] + e.hc_scale)+ anyv = (valid.sum(-1) > 0).float()+ return x + delta * anyv[:, None, None]+torch.manual_seed(1)+hc, D, nc, hd = 4, 384, 6, 48+e = E(); e.eps = 1.1920929e-07; e.hc, e.n_embd = hc, D+e.lookup_norm = torch.randn(nc, hd, device=dev); e.kv = torch.randn((hc + 1) * D, nc * hd, device=dev) * 0.05+e.kv_b = torch.randn(hc + 1, D, device=dev); e.gate = torch.randn(hc, D, device=dev); e.hc_scale = torch.randn(hc, D, device=dev); e.pre_gamma = torch.randn(D, device=dev)+bad = 0+for T in (1, 2, 4, 6):+ x = torch.randn(T, hc, D, device=dev); rows = torch.randn(T, nc, hd, device=dev)+ valid = (torch.rand(T, nc, device=dev) > 0.3).float(); valid[0] = 1.0+ if T > 1: valid[1] = 0.0+ a, b = ref(e, x, rows, valid), EF.apply(e, x, rows, valid)+ err = ((a - b).abs().max() / a.abs().max()).item(); print("T", T, "rel err %.2e" % err); bad += err > 1e-4+print("ENGRAM_FUSED_OK" if not bad else "ENGRAM_FUSED_FAIL", dev)diff --git a/tools/hy4/step/kvrows_test.py b/tools/hy4/step/kvrows_test.pynew file mode 100644index 0000000..28bac0c--- /dev/null+++ b/tools/hy4/step/kvrows_test.py@@ -0,0 +1,43 @@+"""rows test of the fused K-row / q-rope kernels (T = 1..8): bit-compare with the torch reference chains. GPU if available, else TRITON_INTERPRET=1 on CPU."""+import os, sys, importlib.util+import torch+dev = "cuda" if torch.cuda.is_available() and os.environ.get("TRITON_INTERPRET") != "1" else "cpu"+L = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "..", "exllamav3", "loader")+def load(n):+ sp = importlib.util.spec_from_file_location("kvt_" + n, os.path.join(L, n + ".py")); m = importlib.util.module_from_spec(sp); sys.modules["kvt_" + n] = m; sp.loader.exec_module(m); return m+AE = load("attn_eager") if False else None+import triton+KV = load("kv_fused")+torch.manual_seed(0)+R, P, H, NOPE, base, eps, CAP = 512, 64, 8, 128, 10000.0, 1e-6, 64+h = P // 2+def build(n):+ inv = 1.0 / base ** (torch.arange(0, P, 2, dtype=torch.float64) / P)+ th = torch.arange(n, dtype=torch.float64)[:, None] * inv[None]+ c, s = th.cos().float(), th.sin().float()+ t = torch.empty(n, 2, h, 2); t[:, 0, :, 0], t[:, 0, :, 1], t[:, 1, :, 0], t[:, 1, :, 1] = c, s, -s, c+ return t+tab = build(CAP).to(dev)+def rope_ref(x, pos):+ g = tab.index_select(0, pos)+ a, b = g[:, 0].reshape(x.shape[0], 1, h, 2), g[:, 1].reshape(x.shape[0], 1, h, 2)+ xv = x.unflatten(-1, (h, 2))+ return (xv[..., 0:1] * a + xv[..., 1:2] * b).flatten(-2)+bad = 0+for T in (1, 2, 4, 6, 8):+ pos = torch.randint(0, CAP, (T,), device=dev)+ qq = torch.randn(T, H, NOPE + P, device=dev)+ got = KV.rope_q(qq, tab, pos, NOPE, P)+ ref = rope_ref(qq[..., NOPE:], pos)+ e1 = (got - ref).abs().max().item()+ c = torch.randn(T, R + P, device=dev); w = torch.randn(R, device=dev)+ for ring in (0, 16):+ kb = torch.zeros(CAP, R + P, device=dev)+ pos2 = torch.arange(40, 40 + T, device=dev)+ KV.write_row(c, w, tab, pos2, kb, R, P, eps, ring=ring)+ x = c[:, :R]; kref = torch.cat([x * torch.rsqrt((x * x).mean(-1, keepdim=True) + eps) * w, rope_ref(c[:, R:].reshape(T, 1, P), pos2).reshape(T, P)], -1)+ slot = pos2 % ring if ring else pos2+ e2 = (kb[slot] - kref).abs().max().item()+ print("T", T, "ring", ring, "rope_q err %.2e" % e1, "kv row err %.2e" % e2)+ bad += (e1 > 1e-5) + (e2 > 1e-4)+print("KVROWS_OK" if not bad else "KVROWS_FAIL", dev)