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 bundle 1: Q8_0 output head (HY4_HEAD_Q8), shared-expert graph fork (HY4_GRAPH_FORK), router K block 1024 (HY4_RG_TUNE), block-wise absorb kernels (HY4_BG_V2), shipped on; =0 restores 1.9.0
YanissAmzc3f276a93bfe
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 0a86562..ea5f89d 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -243,6 +243,15 @@ def _gm():NO_ALIAS_LAT = os.environ.get("HY4_LAT_CLONE", "0") == "1" # 1 = copy the grouped MoE output before the rup matmul (old behaviour)++GRAPH_FORK = int(os.environ.get("HY4_GRAPH_FORK", "0")) # decode graph fork / join: 1 = the shared-expert branch of the FFN runs on a second capture stream (fork at the FFN entry, join before the residual add); 2 = also the latent down-projection (rdown) on a third stream beside the router; same math, own q8_1 scratch+_SIDE = []+++def _side_stream(dev, k=0):+ while len(_SIDE) <= k:+ _SIDE.append(torch.cuda.Stream(device=dev))+ return _SIDE[k]DENSE_DQ = os.environ.get("HY4_DENSE_DQ", "0") == "1" # 1 = old path: dense matrices dequantised once to fp32 and kept resident@@ -305,6 +314,23 @@ class QLinear:return out.to(x.dtype).reshape(*lead, N)+ def call_own(self, x):+ """__call__ for the decode GEMV with a PRIVATE q8_1 scratch (the cached global scratch is shared by every launch on the stream: two concurrent branches must not use it). Same kernels, same math."""+ K, N = self.shape[1], self.shape[0]+ lead = x.shape[:-1]+ xf = x.reshape(-1, K).float().contiguous()+ qb = torch.empty(xf.shape[0], K // 32 * 36, dtype=torch.uint8, device=x.device)+ out = torch.empty(xf.shape[0], N, dtype=torch.float32, device=x.device)+ e = _ext()+ e.fq_quant_q8_1_rows(xf, qb)+ e.fq_gemv_q8_0_q8(qb, self.packed, out)+ return out.to(x.dtype).reshape(*lead, N)++ def own_ok(self):+ return self.ty == 8 and self.gemv is not None and os.environ.get("BOLT_FQ_Q8Q8", "1") != "0" \+ and _ext() is not None and hasattr(_ext(), "fq_gemv_q8_0_q8") and hasattr(_ext(), "fq_quant_q8_1_rows")++class _QT:def __init__(self, q):self.q = q@@ -330,6 +356,8 @@ def load_linear(g, name, dev, stats=None):HEAD_CHUNK = 8192+HEAD_Q8 = os.environ.get("HY4_HEAD_Q8", "0") == "1" # 1 = the trunk output head as Q8_0 bytes (quantised once at load from the stored bf16, read by the dense Q8 GEMV); the bf16 copy is freed+HEAD_Q8_KEEP = os.environ.get("HY4_HEAD_Q8_KEEP", "0") == "1" # A/B drivers: keep the bf16 head too, so HEAD_Q8 can be flipped at run time (graphs re-captured)def head_gemm(h, W, chunk=HEAD_CHUNK):@@ -437,8 +465,32 @@ class Hy4Forward:assert tuple(self.out_w.shape) == (m[p + "vocab_size"], self.D), self.out_w.shapeif not self.head_cpu:self.out_w = self.out_w.to(self.dev) # resident in its stored dtype (bf16: 0.74 GB)+ self.out_q8 = self._quantize_head() if (HEAD_Q8 and self.out_w.is_cuda) else Noneself._load_resident()+ def _quantize_head(self):+ """HY4_HEAD_Q8=1: Q8_0 bytes of the bf16 output head, same block layout and scale rule (fp16 d = amax / 127) as the stored dense Q8_0 tensors, so the dense Q8 GEMV+ (rows 1..16) reads it; chunked so no fp32 copy of the whole head exists"""+ from .mtp_head import q8_0_pack+ W = self.out_w+ if W.shape[1] % 32 != 0:+ return None+ raw = torch.cat([q8_0_pack(W[a:a + HEAD_CHUNK].float()) for a in range(0, W.shape[0], HEAD_CHUNK)], 0)+ f = dense_fn(8, W.shape[1])+ q = QLinear(raw, 8, GG_DENSE[8], f[1] if f is not None else None)+ q.gname = "output.weight.q8"+ return q++ def free_bf16_head(self):+ """HY4_HEAD_Q8=1 without _KEEP: drop the bf16 head (0.74 GB) once nothing needs its values (the draft head is built from it first); idempotent. out_w stays as a meta tensor (shape only)"""+ if self.out_q8 is not None and not HEAD_Q8_KEEP and self.out_w.device.type != "meta":+ m0 = torch.cuda.memory_allocated()+ self.out_w = torch.empty_like(self.out_w, device="meta")+ import gc+ gc.collect()+ torch.cuda.empty_cache()+ print(f"HEAD_Q8: bf16 head freed, device allocation {m0 / 2**30:.3f} -> {torch.cuda.memory_allocated() / 2**30:.3f} GiB; Q8_0 head {self.out_q8.packed.numel() / 2**30:.3f} GiB", flush=True)+def _load_resident(self):'''routed experts of every MoE layer (while the byte budget lasts) resident on the GPU in their STORED bytes; decode rows then go throughfq_moe_kq_grouped_mixed_q8 (one launch set per layer). Layers whose formats are not in the grouped table, or past the budget, keep the pread path.'''@@ -599,6 +651,23 @@ class Hy4Forward:return self._ffn_gm(i, L, x), Nonersp = self.res.get(i)pf = bool(PF_MOE and T > MMVQ_MAXR and dev.type == "cuda" and rsp is not None and rsp.fu in _pk().FROM_GROUPED and rsp.fd in _pk().FROM_GROUPED)+ fork = fork_z = None+ if GRAPH_FORK and T <= min(MMVQ_MAXR, DENSE_MAXR) and not pf and dev.type == "cuda" and self.hook is None and all(isinstance(q, QLinear) and q.own_ok() for q in L.shexp):+ fork = _side_stream(dev) # created in the eager warm-up too, so the capture never creates a stream+ if GRAPH_FORK >= 2 and isinstance(L.rdown, QLinear) and L.rdown.own_ok():+ fork_z = _side_stream(dev, 1)+ if not torch.cuda.is_current_stream_capturing():+ fork = fork_z = None+ if fork is not None:+ fork.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(fork):+ g_, u_, d_ = L.shexp+ sh_side = d_.call_own((torch.nn.functional.silu(g_.call_own(x).float()) * u_.call_own(x).float()))+ sh_side = sh_side.float()+ if fork_z is not None:+ fork_z.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(fork_z):+ z_side = L.rdown.call_own(x).float()with tm.t("router"):if _rf.ENABLED: # HY4_REF_FUSED=1: one router kernel; the host sync (tolist) only where the pread loop needs itsel, w = _rf.router_select(_RG.mm(x, L.router), L.rbias, self.topk, self.w_scale)@@ -619,7 +688,11 @@ class Hy4Forward:w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * self.w_scalesel_l = [] if (pf or _ns.skip_host_ids(self, i, T, MMVQ_MAXR)) else sorted(set(sel.flatten().tolist()))with tm.t("other"):- z = self._mm(x, L.rdown)+ if fork_z is not None:+ z = z_side+ torch.cuda.current_stream().wait_stream(fork_z)+ else:+ z = self._mm(x, L.rdown)lat = None # allocated (zeros) only by the paths that accumulate into it: the grouped / prefill paths overwrite itlim, N = float(self.clamp[i]), z.shape[1]b = f"blk.{i}."@@ -699,6 +772,9 @@ class Hy4Forward:with tm.t("other"):y = self._mm(lat, L.rup)gt, up, dn = L.shexp+ if fork is not None:+ torch.cuda.current_stream().wait_stream(fork)+ return y + sh_side, latwith tm.t("shared expert"):sh = self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn)return y + sh, lat@@ -908,7 +984,10 @@ class Hy4Forward:self._h = h # the trunk state the output head reads (MTP draft input)if self.head_cpu:h = h.cpu()- out = head_gemm(h.float(), self.out_w)+ if HEAD_Q8 and self.out_q8 is not None:+ out = self.out_q8(h.float())+ else:+ out = head_gemm(h.float(), self.out_w)return out if all_pos else (out[0] if getattr(self, "_ns_dev", False) else out[0].cpu())def step(self, ids, all_pos=False):diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.pyindex de35e33..017d8c5 100644--- a/exllamav3/loader/mla_bgemv.py+++ b/exllamav3/loader/mla_bgemv.py@@ -20,6 +20,11 @@ DOT_BN = int(os.environ.get("HY4_BG_DOT_BN", "64"))DOT_MINT = int(os.environ.get("HY4_BG_DOT_MINT", "5")) # fewest rows on the dot path (box A/B: T 3-4 +-0.2 ms, T 6 -5 ms, T 2 +0.9 ms)DOT_NW = int(os.environ.get("HY4_BG_DOT_NW", "4"))MAXT = 8 # rows served by the batched kernels (verify rows)+V2 = os.environ.get("HY4_BG_V2", "0") == "1" # 1 = block-wise kernels: one scale load / multiply per 32-weight block (the v1 kernels load the scale once per WEIGHT), same products+V2_BN = int(os.environ.get("HY4_BG_V2_BN", "8"))+V2_BKB = int(os.environ.get("HY4_BG_V2_BKB", "4")) # 32-weight blocks per loop step+V2_NW = int(os.environ.get("HY4_BG_V2_NW", "4"))+V2_MAXT = int(os.environ.get("HY4_BG_V2_MAXT", "4")) # rows T on the v2 multi-row kernel (T above it keeps the v1 / dot path)@triton.jit@@ -87,6 +92,49 @@ def _k_bgd(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxt, sxh, T, BT: tl.constexpr,tl.store(o_ptr + (tt[:, None] * (tl.num_programs(0) * N)) + h * N + rows[None, :], acc, mask=tm[:, None] & rm[None, :])+def _k_bg2(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxh, BN: tl.constexpr, BKB: tl.constexpr):+ """HY4_BG_V2, one row: out[h, n] = sum_blocks d[h, n, b] * sum_{j < 32} q[h, n, 32 b + j] * x[h, 32 b + j]. q tile [BN, BKB, 32] (contiguous 32 B per block), scale tile [BN, BKB]."""+ h = tl.program_id(0)+ rows = tl.program_id(1) * BN + tl.arange(0, BN)+ rm = rows < N+ c32 = tl.arange(0, 32)+ acc = tl.zeros([BN], dtype=tl.float32)+ rb = (h * N + rows)+ for kb0 in range(0, NB, BKB):+ kb = kb0 + tl.arange(0, BKB)+ kbm = kb < NB+ cols = kb[:, None] * 32 + c32[None, :]+ q = tl.load(q_ptr + rb[:, None, None] * K + cols[None, :, :], mask=rm[:, None, None] & kbm[None, :, None], other=0).to(tl.float32)+ d = tl.load(d_ptr + rb[:, None] * NB + kb[None, :], mask=rm[:, None] & kbm[None, :], other=0.0).to(tl.float32)+ xv = tl.load(x_ptr + h * sxh + cols, mask=kbm[:, None], other=0.0)+ acc += tl.sum(tl.sum(q * xv[None, :, :], axis=2) * d, axis=1)+ tl.store(o_ptr + h * N + rows, acc, mask=rm)+++def _k_bgt2(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, sxt, sxh, T, BT: tl.constexpr, BN: tl.constexpr, BKB: tl.constexpr):+ """HY4_BG_V2, T rows (T <= BT): each weight tile is read once; the rows are applied one after the other to the same tile."""+ h = tl.program_id(0)+ rows = tl.program_id(1) * BN + tl.arange(0, BN)+ rm = rows < N+ c32 = tl.arange(0, 32)+ tt = tl.arange(0, BT)+ acc = tl.zeros([BT, BN], dtype=tl.float32)+ rb = (h * N + rows)+ for kb0 in range(0, NB, BKB):+ kb = kb0 + tl.arange(0, BKB)+ kbm = kb < NB+ cols = kb[:, None] * 32 + c32[None, :]+ q = tl.load(q_ptr + rb[:, None, None] * K + cols[None, :, :], mask=rm[:, None, None] & kbm[None, :, None], other=0).to(tl.float32)+ d = tl.load(d_ptr + rb[:, None] * NB + kb[None, :], mask=rm[:, None] & kbm[None, :], other=0.0).to(tl.float32)+ for t in tl.static_range(BT):+ xv = tl.load(x_ptr + t * sxt + h * sxh + cols, mask=kbm[:, None] & (t < T), other=0.0)+ part = tl.sum(tl.sum(q * xv[None, :, :], axis=2) * d, axis=1)+ acc += tl.where(tt[:, None] == t, part[None, :], 0.0)+ tl.store(o_ptr + (tt[:, None] * (tl.num_programs(0) * N)) + h * N + rows[None, :], acc, mask=(tt[:, None] < T) & rm[None, :])++class Q8Batched:"""[H, N, K] Q8_0 matrix as int8 + fp16 scales on a device"""@@ -101,6 +149,10 @@ class Q8Batched: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)+ if V2 and T <= V2_MAXT and self.K % 32 == 0:+ _k_bgt2[(self.H, triton.cdiv(self.N, V2_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=V2_BN, BKB=V2_BKB, num_warps=V2_NW)+ return outif DOT and DOT_MINT <= T <= 16 and self.K % 32 == 0:_k_bgd[(self.H, triton.cdiv(self.N, DOT_BN))](self.q, self.d, x, out, self.N, self.K, self.K // 32, x.stride(0), x.stride(1), T, BT=16, BN=DOT_BN, num_warps=DOT_NW)return out@@ -113,6 +165,9 @@ class Q8Batched:xv, sxh = x, x.stride(1)else:xv, sxh = x.reshape(self.H, self.K).contiguous(), self.K+ if V2 and self.K % 32 == 0:+ _k_bg2[(self.H, triton.cdiv(self.N, V2_BN))](self.q, self.d, xv, out, self.N, self.K, self.K // 32, sxh, BN=V2_BN, BKB=V2_BKB, num_warps=V2_NW)+ return out.reshape(1, self.H, self.N)_k_bg[(self.H, triton.cdiv(self.N, BN))](self.q, self.d, xv, out, self.N, self.K, self.K // 32, sxh, BN=BN, BK=BK, num_warps=4)return out.reshape(1, self.H, self.N)diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex 99fd348..3e6041a 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -77,18 +77,23 @@ class Hy4MTP:# draft head: "" = the trunk's bf16 head (Triton mat-vec), "q8" = Q8_0 copy (half the bytes), "sub<N>" = the first N vocabulary rows only (draft picks among them)hm = os.environ.get("HY4_MTP_HEAD", "")self.head_q8 = self.head_sub = self.ids = None- if hm == "q5k": # Q5_K bytes of the bf16 head from a file (make_head_bin.py): 0.255 GB instead of 0.394 GB (Q8_0); falls back to Q8_0 when the file is missing+ shared = getattr(fw, "out_q8", None)+ if shared is not None and hm in ("q8", "q8share"): # HY4_HEAD_Q8=1: the trunk's Q8_0 head bytes ARE the draft's Q8_0 head: one resident copy+ self.head_q8 = shared+ elif hm == "q5k": # Q5_K bytes of the bf16 head from a file (make_head_bin.py): 0.255 GB instead of 0.394 GB (Q8_0); falls back to Q8_0 when the file is missingfrom . import dense_req as _DRself.head_q8 = _DR.head_from_file(self, os.environ.get("HY4_MTP_HEAD_BIN", "/path/to/head_q5_k.bin"))if self.head_q8 is None:print("mtp_head: HY4_MTP_HEAD=q5k but no matching head file, using Q8_0", flush=True)- self.head_q8 = q8_linear(fw.out_w.float())+ self.head_q8 = shared if shared is not None else q8_linear(fw.out_w.float())elif hm == "q8":self.head_q8 = q8_linear(fw.out_w.float())elif hm.startswith("sub"):n = int(hm[3:])self.head_sub = fw.out_w[:n].contiguous()self.ids = torch.arange(n, device=dev)+ if shared is not None and self.head_q8 is None and self.head_sub is None: # draft on "the trunk's head" = the shared Q8_0 bytes once the bf16 copy is gone+ self.head_q8 = sharedst = _ns.state(fw)self.cap = cap or st.capself.ar = st.ar if st.ar.shape[0] >= self.cap else torch.arange(self.cap, device=dev)@@ -99,6 +104,8 @@ class Hy4MTP:_AE.ensure(self.cap)except ImportError:pass+ if hasattr(fw, "free_bf16_head"):+ fw.free_bf16_head() # HY4_HEAD_Q8=1: every consumer of the bf16 head values (draft head copies) has been builtdef reset(self):self.kbuf.zero_()diff --git a/exllamav3/loader/router_gemv.py b/exllamav3/loader/router_gemv.pyindex d6e654f..2bd223f 100644--- a/exllamav3/loader/router_gemv.py+++ b/exllamav3/loader/router_gemv.py@@ -11,7 +11,8 @@ import triton.language as tlENABLED = os.environ.get("HY4_ROUTER_GEMV", "0") == "1"MAXT = 8BN = int(os.environ.get("HY4_RG_BN", "4"))-BK = int(os.environ.get("HY4_RG_BK", "256"))+TUNE = os.environ.get("HY4_RG_TUNE", "0") == "1" # tuned K block (dec8_micro, real GGUF shape, fp16 weights): 1024 instead of 256, T=1 26.8 -> 16.2 us, T=4 30.7 -> 17.8 us per launch, max rel err 1.6e-6 (summation order only)+BK = int(os.environ.get("HY4_RG_BK", "1024" if TUNE else "256"))NW = int(os.environ.get("HY4_RG_NW", "4"))F16 = os.environ.get("HY4_RG_F16", "0") == "1" # router weights stored fp16 (GGUF F32 -> fp16: rel 5e-4 per weight, logits ~1e-5): half the bytes of the 41 gemvs; fp32 accumulatediff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex 4e2bef5..5394737 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -58,6 +58,7 @@ SHIPPED_ENV = {"HY4_MLA_HB": "1", "HY4_BG_DOT": "1", "HY4_HEAD_DOT": "1", "HY4_RG_F16": "1", # decode levers (box A/B 20/11, 256 tok x2: verify round -7 % at 4K, -4 % at 32K, plain flat; qual6 KL 0.94 x noise null)"HY4_PF_KV_HM": "1", "HY4_PF_QO_HM": "1", "HY4_PF_HC2": "1", "HY4_PF_ROUTER16": "1", # prefill set 3 (1.9.1): head-major CK attention operands, lazy layer residual (3 stream passes per layer), fp16 router logits of prefill rows (only on the HY4_REF_FUSED=0 router path)"HY4_PF_Q3K_V2": "1", # Q3_K prefill gate-up kernel with packed fp16 decode + aligned dword loads (bit-identical to the old kernel, -0.26 s per 8K chunk; needs the rebuilt gm_ext, else falls back; old kernel when K / 256 is odd)+ "HY4_HEAD_Q8": "1", "HY4_GRAPH_FORK": "1", "HY4_RG_TUNE": "1", "HY4_BG_V2": "1", # decode bundle 1 (1.9.1): Q8_0 output head (one resident copy, bf16 freed: -1.8 ms per step), shared-expert branch on a second capture stream (-1.7 ms per round), router mat-vec K block 1024, block-wise absorb kernels; quality gate: full bundle dNLL -0.0029 +- 0.011 vs noise null 0.0156"HY4_PF_WOT": "0", "HY4_MOE_HIP": "2", "HY4_PF_CK": "1", "HY4_PF_FUSE": "1", # prefill set 2: shared gm_ext WMMA experts (HY4_GM_EXT), CK MLA core (EXL3_CKMLA_SO), one-pass hc / norm / indexer kernels}