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
mla2: precompile hook, trunk/draft fires split, CPU tests, CHANGELOG
YanissAmz5b561decbcf1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffb4616..cd6af72 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,10 @@# Changelog+## Unreleased (1.9.3)++- Hy4 decode graphs: context buckets can grow with the context (1/32 of the octave above 16K rows) instead of a fixed 512 rows, so a 256K prompt lists 225 buckets instead of 2049. `HY4_GRAPH_BUCKET_REL` (default 0 = fixed 512-row buckets, as in 1.9.2; 1 = growing buckets). CPU test: `tests/test_graph_bucket.py`.+- Hy4 MLA2 (`HY4_MLA_ROWS2`, default 0 = off, the 1.9.2 attention path is untouched): row-batched split-K decode attention. One pass over the K rows serves all verify rows, q is streamed in chunks, the output has 4 quarters. Tunables `HY4_MLA_ROWS2_BH` 16, `_RG` 1, `_BN` 32, `_BK` 64, `_NW` 4, `_PROG` 64, `_SPLIT` 0 (auto), `_RS` 8, `_MINB` 2. `HY4_MLA_ROWS2_PRECOMPILE=1` (default 0) compiles and loads every (T, S) specialisation at the end of load, outside any graph capture. `HY4_MLA_ROWS2_TRACE=1` prints the first sighting of each launch key and flags a JIT inside a capture. Fires counter: `HY4_MLA_ROWS2_FIRES=<file>` holds one line `FIRES mla2 <n> trunk <a> draft <b> fallback {reason: n} fallback_trunk {...} fallback_draft {...}`; an A/B arm with the flag on must show n > 0 and no fallback. Measured on the Strix Halo box (Hy4-flash): precision equal to the deployed head-blocked fp16-dot kernel (1152 calls, mean abs error 2.66e-05 for both); served hang matrix 12/12 boots clean, including an empty Triton cache. The quality gate (paired dNLL + GSM8K) is still pending, so the flag stays off. CPU tests (no GPU): `tools/hy4/step/mla2_precompile_cpu_test.py`, `mla2_engine_hook_test.py`, `mla2_fires_cpu_test.py`; micro `tools/hy4/step/mla2_micro.py` (`MLA_CPU=1` for a CPU smoke run).+## 1.9.2Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, request-parser fixes, Strix install fixes, docs.diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex 0bf2ea7..3e866df 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -18,6 +18,7 @@ import torchfrom . import moe_i8 as MIfrom . import step_graph as SGfrom . import graph_bucket as _gb+from . import ref_fused as _rffrom . import step_nosync as _nsfrom .engram_rows import load_dense, rmsfrom .hy4_forward import _mv, head_gemm, QLinear, GG_DENSE, dense_fn@@ -257,6 +258,7 @@ class MTPGraph:h = yreturn torch.cat(outs + confs)+ @_rf.r2_draftdef _graph(self, N):g = self.graphs.get(N)if g is not None:@@ -327,6 +329,7 @@ class MTPGraphCU(MTPGraph):h = yreturn torch.cat(outs)+ @_rf.r2_draftdef _graph(self, N, a):g = self.graphs.get((N, a))if g is not None:diff --git a/exllamav3/loader/ref_fused.py b/exllamav3/loader/ref_fused.pyindex 3579321..1f5c592 100644--- a/exllamav3/loader/ref_fused.py+++ b/exllamav3/loader/ref_fused.py@@ -9,6 +9,7 @@ Generic: shapes come from the tensors (E, k, R, P, H, N); nothing is keyed on a(CPU tensor without TRITON_INTERPRET, T > MAX_T, no sinks, non-fp32) falls back to the old torch code, so a caller can always use these."""import os+import sysimport torch@@ -29,6 +30,8 @@ R2_RS = int(os.environ.get("HY4_MLA_ROWS2_RS", "8")) # column slices of thR2_MINB = int(os.environ.get("HY4_MLA_ROWS2_MINB", "2")) # minimum key blocks per splitR2_FIRES = {"calls": 0, "fallback": {}} # fires-check of HY4_MLA_ROWS2: python-side counter of mla2 dispatches (graph capture / eager) and the reasons of decode-size calls that fell backR2_FIRES_FILE = os.environ.get("HY4_MLA_ROWS2_FIRES", "") # when set: the counter is written there (first calls, then every 256th, and at exit): the job reads it back as `FIRES mla2 <calls>`+R2_TRACE = os.environ.get("HY4_MLA_ROWS2_TRACE", "0") == "1" # first sighting of every mla2 launch key on stderr: key, whether a graph capture is running, whether Triton compiled a NEW specialisation for it (JIT inside a capture = the hang hypothesis of 18_mla2_quality)+R2_PRECOMPILE = os.environ.get("HY4_MLA_ROWS2_PRECOMPILE", "0") == "1" # 1: mla2_precompile() (called by the engine at the end of load) compiles + loads every (T, S) specialisation OUTSIDE any graph capture; default 0 = as beforeMAX_T = 16 # rows per call handled by the attention kernel (decode / short verify); more = prefill -> torch GEMMsCLAMP_MIN = 6.103515625e-5 # the old router's `sum.clamp(min=...)`@@ -404,22 +407,50 @@ if triton is not None:tl.store(O + t * s_o_t + h[:, None] * s_o_h + offc[None, :], A / L[:, None])+R2_ROLE = ["trunk"] # who is capturing / running the graph: the draft head graph captures run under r2_draft (counted apart from the trunk)+R2_BY_ROLE = {"trunk": {"calls": 0, "fallback": {}}, "draft": {"calls": 0, "fallback": {}}}+++def r2_draft(fn):+ """decorator for the draft head graph capture entries: mla2 dispatches inside count as role draft"""+ import functools++ @functools.wraps(fn)+ def w(*a, **k):+ prev = R2_ROLE[0]+ R2_ROLE[0] = "draft"+ try:+ return fn(*a, **k)+ finally:+ R2_ROLE[0] = prev+ return w++def _r2_note(reason=None):- """count one mla2 dispatch (reason None) or one decode-size fallback (reason = why), keep R2_FIRES_FILE current"""+ """count one mla2 dispatch (reason None) or one decode-size fallback (reason = why), total and per role (trunk / draft), keep R2_FIRES_FILE current"""+ r = R2_BY_ROLE[R2_ROLE[0]]if reason is None:R2_FIRES["calls"] += 1+ r["calls"] += 1else:R2_FIRES["fallback"][reason] = R2_FIRES["fallback"].get(reason, 0) + 1+ r["fallback"][reason] = r["fallback"].get(reason, 0) + 1n = R2_FIRES["calls"] + sum(R2_FIRES["fallback"].values())if R2_FIRES_FILE and (n <= 3 or n % 256 == 0 or reason is not None and R2_FIRES["fallback"][reason] <= 2):_r2_dump()+def _r2_line():+ t, d = R2_BY_ROLE["trunk"], R2_BY_ROLE["draft"]+ return (f"FIRES mla2 {R2_FIRES['calls']} trunk {t['calls']} draft {d['calls']} fallback {R2_FIRES['fallback']} "+ f"fallback_trunk {t['fallback']} fallback_draft {d['fallback']}")++def _r2_dump():if R2_FIRES_FILE:try:with open(R2_FIRES_FILE, "w") as f:- f.write(f"FIRES mla2 {R2_FIRES['calls']} fallback {R2_FIRES['fallback']}\n")+ f.write(_r2_line() + "\n")except OSError:pass@@ -429,16 +460,40 @@ if R2_FIRES_FILE:atexit.register(_r2_dump)-def _mla2_launch(q_lat, q_pe, ckv, k_pe, qpos, sinks, scale, window, ring, out):- T, H, R = q_lat.shape- N, P = ckv.shape[0], k_pe.shape[1]- BH = R2_BH+def _mla2_plan(T, H, N, window):+ """-> (RG, nrg, ngr, S): the program grid of one mla2 launch (host arithmetic only, no GPU call)"""RG = min(R2_RG, triton.next_power_of_2(T))nrg = -(-T // RG)- ngr = H // BH+ ngr = H // R2_BHnblk = (-(-(window + T) // R2_BN) + 1) if window else -(-N // R2_BN) # key blocks one program can walkS = R2_SPLIT if R2_SPLIT > 0 else min(16, max(1, -(-R2_PROG // (nrg * ngr))), max(1, nblk // R2_MINB))+ return RG, nrg, ngr, S+++def _jit_count():+ """number of compiled specialisations Triton holds for the two mla2 kernels (-1: API not found)"""+ try:+ return sum(len(v[0]) for f in (_mla2_split_kernel, _mla2_combine) for v in f.device_caches.values())+ except Exception:+ return -1+++_R2_SEEN = set()+++def _mla2_launch(q_lat, q_pe, ckv, k_pe, qpos, sinks, scale, window, ring, out, S=None):+ T, H, R = q_lat.shape+ N, P = ckv.shape[0], k_pe.shape[1]+ BH = R2_BH+ RG, nrg, ngr, S0 = _mla2_plan(T, H, N, window)+ S = S0 if S is None else Sdv = q_lat.device+ n0, cap, first = -1, False, False+ if R2_TRACE:+ key = (T, S, bool(window), int(ring), N % 16 == 0, N == 1)+ first = key not in _R2_SEEN+ _R2_SEEN.add(key)+ n0, cap = _jit_count(), (torch.cuda.is_available() and torch.cuda.is_current_stream_capturing())wa = torch.empty(T * ngr * S * BH * R, dtype=torch.float32, device=dv)wm = torch.empty(T * ngr * S * BH, dtype=torch.float32, device=dv)wl = torch.empty(T * ngr * S * BH, dtype=torch.float32, device=dv)@@ -447,9 +502,46 @@ def _mla2_launch(q_lat, q_pe, ckv, k_pe, qpos, sinks, scale, window, ring, out):R=R, P=P, BH=BH, RG=RG, BN=R2_BN, BK=R2_BK, HAS_WIN=bool(window), RING=int(ring), num_warps=R2_NW, num_stages=1)RS = max(1, min(R2_RS, R // 32))_mla2_combine[(T, ngr, RS)](wa, wm, wl, out, out.stride(0), out.stride(1), R=R, BH=BH, S=S, RC=R // RS, num_warps=4)+ if n0 >= 0:+ n1 = _jit_count()+ if first or n1 > n0:+ print(f"MLA2_FIRST key T={T} S={S} win={int(bool(window))} ring={ring} N={N} capturing={cap} new_specialisations={n1 - n0}" + (" <<< JIT INSIDE CAPTURE" if cap and n1 > n0 else ""), file=sys.stderr, flush=True)return out+def mla2_precompile(layers, ts, ns, device="cuda", log=print):+ """compile + load every mla2 specialisation a decode graph can need, now, OUTSIDE any capture (HY4_MLA_ROWS2_PRECOMPILE=1, called by the engine at the end of load).+ layers: iterable of (H, R, P, window, ring) of the model's attention layers; ts: verify row counts (1 .. TM); ns: context buckets of the graphs.+ One real launch per distinct (layer kind, T, S): S comes from the SAME plan as the real launch (_mla2_plan, N = the bucket), the K buffers are small dummies in the real+ layout (a [N, R + P] fp32 buffer, ckv / k_pe its two column views) so strides, alignment and int specialisation classes (N % 16, == 1) match. -> number of launches"""+ import time+ t0, n_launch, seen = time.perf_counter(), 0, set()+ for (H, R, P, window, ring) in sorted(set(layers)):+ if H % R2_BH or R != triton.next_power_of_2(R) or P != triton.next_power_of_2(P):+ continue+ nd = ring if ring else 512 # dummy key rows: a ring layer reads its ring buffer, the others a multiple of 16 (every real bucket is one)+ kc = torch.zeros(nd, R + P, dtype=torch.float32, device=device)+ sinks = torch.zeros(H, dtype=torch.float32, device=device)+ for T in ts:+ if R2_BH * min(R2_RG, triton.next_power_of_2(T)) < 16:+ continue # the real dispatcher declines it (M tile < 16)+ ql = torch.zeros(T, H, R, dtype=torch.float32, device=device)+ qp = torch.zeros(T, H, P, dtype=torch.float32, device=device)+ qpos = torch.arange(T, dtype=torch.int64, device=device)+ for N in ns:+ S = _mla2_plan(T, H, N, window)[3]+ key = (H, R, P, bool(window), int(ring), T, S)+ if key in seen:+ continue+ seen.add(key)+ _mla2_launch(ql, qp, kc[:, :R], kc[:, R:], qpos, sinks, 1.0, window, ring, torch.empty(T, H, R, dtype=torch.float32, device=device), S=S)+ n_launch += 1+ if torch.device(device).type == "cuda":+ torch.cuda.synchronize()+ log(f"mla2 precompile: {n_launch} launches ({len(seen)} keys), {time.perf_counter() - t0:.1f} s, {_jit_count()} specialisations held")+ return n_launch++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)diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex 99c352e..430b9d9 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -114,6 +114,7 @@ class Hy4Engine:self.GR.prepare() # static K / indexer / Engram buffers at the full context size: addresses never change after thisself.MT = MH.Hy4MTP(M)self.MG = self._mtp_graph()+ self._mla2_precompile()MH._STAGE_OV[0] = os.environ.get("HY4_SERVE_STAGE_OV", "1") == "1" # Engram row 0 of the next verify staged during the draft chaintorch.cuda.synchronize()self.load_s = time.time() - t0@@ -149,6 +150,21 @@ class Hy4Engine:hf.PF_MOE_I8 = hf.PF_MOE_REF = hf.PF_DENSE_I8 = hf.PF_ROUTER = hf.PF_DIAG = Falsemh.PF_ATTN, mh.PF_ATTN_FLASH = True, False # (rows <= 16 never take the prefill branches)+ def _mla2_precompile(self):+ """HY4_MLA_ROWS2=1 + HY4_MLA_ROWS2_PRECOMPILE=1: compile + load every mla2 kernel specialisation of the decode graphs now (a first launch inside a graph capture would JIT / hipModuleLoad there)"""+ rf = self.hf._rf+ if not (rf.ROWS2 and rf.R2_PRECOMPILE):+ return+ from exllamav3.loader import graph_bucket as gb+ kinds = set()+ for i in range(self.M.n_layers):+ m = self.M._layer(i).mla+ kinds.add((int(m.H), int(m.R), int(m.rope_dim), int(m.window), int(getattr(m, "kv_ring", 0))))+ mt = self.MT.mla+ kinds.add((int(mt.H), int(mt.R), int(mt.rope_dim), int(mt.window), 0))+ ns = set(gb.buckets(self.GR.cap)) | set(gb.buckets(self.MG.mt.cap, self.MG.BUCKET))+ rf.mla2_precompile(kinds, range(1, self.SG.TM + 1), sorted(ns), str(self.dev), log=lambda s: print("load:", s, flush=True))+def warmup(self, n: int):"""one synthetic request of n prompt tokens + 8 decode tokens: compiles the Triton prefill kernels (they would land in the first user chunk, about 0.3 s) and captures the decode graphs"""n = warmup_clamp(n, self.ctx, self.k)diff --git a/tools/hy4/step/mla2_engine_hook_test.py b/tools/hy4/step/mla2_engine_hook_test.pynew file mode 100644index 0000000..662396b--- /dev/null+++ b/tools/hy4/step/mla2_engine_hook_test.py@@ -0,0 +1,18 @@+"""offline exec of Engine._mla2_precompile (extracted by ast) on fake objects: CPU, TRITON_INTERPRET=1"""+import ast, os, sys, types, importlib.util, torch+os.environ["HY4_MLA_ROWS2"] = "1"; os.environ["HY4_MLA_ROWS2_PRECOMPILE"] = "1"; os.environ["TRITON_INTERPRET"] = "1"+spec = importlib.util.spec_from_file_location("ref_fused", "exllamav3/loader/ref_fused.py"); rf = importlib.util.module_from_spec(spec); spec.loader.exec_module(rf)+src = open("tools/hy4/engine.py").read()+fn = next(n for n in ast.walk(ast.parse(src)) if isinstance(n, ast.FunctionDef) and n.name == "_mla2_precompile")+ns = {}; exec(compile(ast.Module([fn], []), "engine.py", "exec"), ns)+mla = lambda w, ring: types.SimpleNamespace(H=16, R=64, rope_dim=16, window=w, kv_ring=ring)+layers = [types.SimpleNamespace(mla=mla(0, 0)), types.SimpleNamespace(mla=mla(128, 0)), types.SimpleNamespace(mla=mla(128, 192))]+gb = types.ModuleType("graph_bucket"); gb.buckets = lambda cap, base=512, *a: list(range(base, cap + 1, base))+pkg = types.ModuleType("exllamav3.loader"); pkg.graph_bucket = gb+sys.modules["exllamav3"] = types.ModuleType("exllamav3"); sys.modules["exllamav3.loader"] = pkg; sys.modules["exllamav3.loader.graph_bucket"] = gb+self = types.SimpleNamespace(hf=types.SimpleNamespace(_rf=rf), M=types.SimpleNamespace(n_layers=3, _layer=lambda i: layers[i]), MT=types.SimpleNamespace(mla=mla(0, 0)),+ MG=types.SimpleNamespace(mt=types.SimpleNamespace(cap=1024), BUCKET=512), GR=types.SimpleNamespace(cap=1024), SG=types.SimpleNamespace(TM=2), dev=torch.device("cpu"))+ns["_mla2_precompile"](self)+rf.R2_PRECOMPILE = False+n = []; rf.mla2_precompile = lambda *a, **k: n.append(1); ns["_mla2_precompile"](self); assert not n # flag off: no-op+print("ENGINE_HOOK_OK")diff --git a/tools/hy4/step/mla2_fires_cpu_test.py b/tools/hy4/step/mla2_fires_cpu_test.pynew file mode 100644index 0000000..6d06862--- /dev/null+++ b/tools/hy4/step/mla2_fires_cpu_test.py@@ -0,0 +1,26 @@+"""CPU test (TRITON_INTERPRET=1, no GPU): HY4_MLA_ROWS2 fires counter. Flag on: dispatches count as trunk, the r2_draft decorator counts as draft and restores the role (also on+an exception), decode-size fallbacks carry a reason, the HY4_MLA_ROWS2_FIRES file holds the line. Flag off: the counter stays at 0 and the old path runs."""+import os, sys, tempfile, importlib.util, torch+os.environ["TRITON_INTERPRET"] = "1"+path = os.path.join(tempfile.mkdtemp(), "fires.txt")+os.environ["HY4_MLA_ROWS2"] = "1"; os.environ["HY4_MLA_ROWS2_FIRES"] = path+spec = importlib.util.spec_from_file_location("ref_fused", "exllamav3/loader/ref_fused.py"); rf = importlib.util.module_from_spec(spec); spec.loader.exec_module(rf)+H, R, P, T, N = 16, 64, 16, 2, 64+torch.manual_seed(0)+kc = torch.randn(N, R + P); ql = torch.randn(T, H, R) * 0.2; qp = torch.randn(T, H, P) * 0.2; qpos = torch.tensor([N - 2, N - 1]); sinks = torch.randn(H); kpos = torch.arange(N)+call = lambda **k: rf.mla_sink_attend(ql, qp, kc[:, :R], kc[:, R:], qpos, kpos, 0.3, sinks, 0, None, **k)+call(kpos_is_arange=True)+assert rf.R2_FIRES["calls"] == 1 and rf.R2_BY_ROLE["trunk"]["calls"] == 1 and rf.R2_BY_ROLE["draft"]["calls"] == 0+rf.r2_draft(lambda: call(kpos_is_arange=True))()+assert rf.R2_BY_ROLE["draft"]["calls"] == 1 and rf.R2_ROLE[0] == "trunk" and rf.R2_FIRES["calls"] == 2+def boom(): raise RuntimeError("x")+try: rf.r2_draft(boom)()+except RuntimeError: pass+assert rf.R2_ROLE[0] == "trunk"+call(kpos_is_arange=False) # fallback reason: kpos not arange+assert rf.R2_FIRES["fallback"] == {"kpos not arange": 1} and rf.R2_BY_ROLE["trunk"]["fallback"] == {"kpos not arange": 1}, rf.R2_FIRES+line = open(path).read().strip()+assert line.startswith("FIRES mla2 2 trunk 1 draft 1 fallback {"), line+rf.R2_ROLE[0] = "trunk"; rf.ROWS2 = False; before = dict(rf.R2_FIRES); call(kpos_is_arange=True)+assert rf.R2_FIRES == before # flag off: no note, no mla2+print(line); print("FIRES_CPU_TEST_OK")diff --git a/tools/hy4/step/mla2_precompile_cpu_test.py b/tools/hy4/step/mla2_precompile_cpu_test.pynew file mode 100644index 0000000..fa3146d--- /dev/null+++ b/tools/hy4/step/mla2_precompile_cpu_test.py@@ -0,0 +1,31 @@+"""CPU test (TRITON_INTERPRET=1, no GPU): mla2_precompile launches the real kernels; plan dedupe; the result of _mla2_launch matches a torch reference."""+import os, sys, torch+os.environ.setdefault("TRITON_INTERPRET", "1")+os.environ["HY4_MLA_ROWS2"] = "1"; os.environ["HY4_MLA_ROWS2_TRACE"] = "1"+sys.path.insert(0, os.getcwd())+import importlib.util+spec = importlib.util.spec_from_file_location("ref_fused", "exllamav3/loader/ref_fused.py"); rf = importlib.util.module_from_spec(spec); spec.loader.exec_module(rf)+H, R, P = 16, 64, 16+# plan checks (host only)+for T in (1, 2, 4, 8):+ for N in (512, 1024, 8192):+ for win in (0, 128):+ RG, nrg, ngr, S = rf._mla2_plan(T, H, N, win)+ assert S >= 1 and nrg * RG >= T and ngr == H // rf.R2_BH, (T, N, win, S)+calls = []+orig = rf._mla2_launch+def spy(*a, **k): calls.append((a[0].shape[0], k.get("S"), a[7], a[8])); return orig(*a, **k)+rf._mla2_launch = spy+n = rf.mla2_precompile([(H, R, P, 0, 0), (H, R, P, 128, 0), (H, R, P, 128, 192)], [1, 2], [512, 1024], "cpu")+assert n == len(calls) and n > 0, (n, calls)+assert len(set(calls)) == len(calls) # one launch per distinct key+print("precompile launches", n, calls)+# numerical check of the real launch vs torch (T=2, N=64, no window)+torch.manual_seed(0)+T, N = 2, 64+kc = torch.randn(N, R + P); ql = torch.randn(T, H, R) * 0.2; qp = torch.randn(T, H, P) * 0.2; qpos = torch.tensor([N - 2, N - 1]); sinks = torch.randn(H)+out = rf._mla2_launch(ql, qp, kc[:, :R], kc[:, R:], qpos, sinks, 0.3, 0, 0, torch.empty(T, H, R))+ref = rf.mla_sink_attend_ref(ql, qp, kc[:, :R], kc[:, R:], qpos, torch.arange(N), 0.3, sinks, 0, None)+print("max abs err vs torch ref", float((out - ref).abs().max()))+assert float((out - ref).abs().max()) < 2e-2+print("CPU_TEST_OK")