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 spec cost: draft confidences + cost-aware draft length (HY4_DRAFT_POLICY), gm_ext MoE at verify rows (HY4_GM_MOE), verify-row Triton tiles (HY4_ROW_TILES)
YanissAmz665b1dd29b11
diff --git a/exllamav3/loader/head_bf16.py b/exllamav3/loader/head_bf16.pyindex 555b14c..587386a 100644--- a/exllamav3/loader/head_bf16.py+++ b/exllamav3/loader/head_bf16.py@@ -10,6 +10,7 @@ import triton.language as tlENABLED = os.environ.get("HY4_HEAD_BF16", "0") == "1"BV = int(os.environ.get("HY4_HEAD_BV", "8"))BD = int(os.environ.get("HY4_HEAD_BD", "512"))+ROW_TILES = os.environ.get("HY4_ROW_TILES", "0") == "1" # 1 = verify-row tiles tuned on the Strix (T 2..4: BD 64 + 2 warps; T >= 5: BV 16, BD 32)@triton.jit@@ -54,7 +55,10 @@ def gemv(h, W):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)+ bv, bd, nw = BV, min(BD, 128), 4+ if ROW_TILES:+ bv, bd, nw = (BV, 64, 2) if T <= 4 else (16, 32, 4)+ _k_headt[(triton.cdiv(V, bv),)](W, h.contiguous(), out, V, D, T, BT=triton.next_power_of_2(T), BV=bv, BD=bd, num_warps=nw)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)diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex a583a16..19ede78 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -212,6 +212,9 @@ def _dq_q8_0_t(packed):# rows <= DENSE_MAXR run the extension GEMV (activation quantised to q8_1 inside, like llama.cpp), more rows dequantise per call (no resident fp32 copy).GG_DENSE = {8: (32, 34, "fq_gemv_q8_0", _dq_q8_0_t)}DENSE_MAXR = 16+GM_MOE = os.environ.get("HY4_GM_MOE", "0") == "1" # 1 = verify rows (2..8) of the grouped MoE through gm_moe_kq_decode (expert-major: each distinct expert read once per tile for all rows); everything else stays stock+GM_MOE_Q4MINR = int(os.environ.get("HY4_GM_MOE_Q4MINR", "2")) # fewest rows for Q4_K gate/up layers (measured: gm = stock at 2 rows, -7 % at 3, -15 % at 4, -29 % at 8)+GM_MOE_Q3MINR = int(os.environ.get("HY4_GM_MOE_Q3MINR", "4")) # fewest rows for Q3_K gate/up layers (box microbench 19/11: gm 5 % faster at 4 rows, stock 8 % faster at 2-3)GM_FFN = os.environ.get("HY4_GM_FFN", "0") == "1" # 1 = decode FFN (<= 8 rows) through the shared gm_ext ops: gm_route + one Q8_0 launch (rdown, shared gate, shared up) + gm_moe_kq_decode + rup / shared swiglu-down in one buffer_GMX = []@@ -598,7 +601,20 @@ class Hy4Forward:self.stats["moe_path_" + getattr(k_, "LAST_PATH", "?")] = self.stats.get("moe_path_" + getattr(k_, "LAST_PATH", "?"), 0) + 1sel_l = []rs = self.res.get(i) if (T <= MMVQ_MAXR and dev.type == "cuda") else None- if rs is not None:+ if rs is not None and GM_MOE and 2 <= T <= 8 and self.hook is None and self._gm_moe_ok(rs, T, N):+ with tm.t("routed experts"):+ S = sel.shape[1]+ st = getattr(self, "_gmm", None)+ if st is None or st.act.shape[1] != N:+ st = self._gmm = SimpleNamespace(act=torch.empty(8 * S, N, dtype=torch.float16, device=dev), qb=torch.empty(8 * N // 32 * 36, dtype=torch.uint8, device=dev),+ part=torch.empty(8 * S, N, dtype=torch.float32, device=dev), lat=torch.empty(8, N, dtype=torch.float32, device=dev),+ meta=torch.zeros(8 * S * 9, dtype=torch.int32, device=dev), nores=torch.empty(0, dtype=torch.float32, device=dev))+ _gm().gm_moe_kq_decode(z.half().contiguous(), sel.reshape(-1).contiguous(), w.half().reshape(-1).contiguous(), *rs.ptrs, *rs.strides[:3], rs.fd,+ st.act, st.qb, st.part, st.lat[:T], st.nores, rs.fu, lim, st.meta)+ lat = st.lat[:T]+ self.stats["gm_moe_calls"] = self.stats.get("gm_moe_calls", 0) + 1+ sel_l = []+ elif rs is not None:with tm.t("routed experts"):ext, S = _ext(), sel.shape[1]if getattr(self, "_gpart", None) is None or self._gpart.shape[1] != N:@@ -648,6 +664,12 @@ class Hy4Forward:sh = self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn)return y + sh, lat+ def _gm_moe_ok(self, rs, T, N):+ """the resident experts of this layer run on gm_moe_kq_decode at T rows: gate/up Q4_K (>= GM_MOE_Q4MINR rows) or Q3_K (>= GM_MOE_Q3MINR rows), down Q4_K / Q6_K, 256-multiples"""+ if _gm() is None or rs.fd not in (0, 2) or N % 256 != 0 or N > 4096:+ return False+ return T >= (GM_MOE_Q4MINR if rs.fu == 0 else GM_MOE_Q3MINR) if rs.fu in (0, 8) else False+def _gm_ok(self, i, L, x):"""layer i FFN can run on the gm_ext ops: resident experts in a gm format, Q8_0 latent / shared matrices, 1..8 rows, no hooks"""if not GM_FFN or self.hook is not None or self.dev.type != "cuda" or i < self.n_dense or x.shape[0] > 8:diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.pyindex d76eb39..5f4dfa6 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"))+ROW_TILES = os.environ.get("HY4_ROW_TILES", "0") == "1" # 1 = tile sizes tuned on the Strix for verify rows (T >= 4: BN 32, BK 32; box microbench 19/11)MAXT = 8 # rows served by the batched kernels (verify rows)@@ -71,8 +72,9 @@ 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)- _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)+ bn, bk = (32, 32) if (ROW_TILES and T >= 4) else (BN, min(BK, 64))+ _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=bk, 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 copydiff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex a5f1243..9a10024 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -194,6 +194,10 @@ class Hy4MTP:return outs+CONF = os.environ.get("HY4_DRAFT_CONF", "0") == "1"+CONF_ONE = float(1 << 20)++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 nextstep on the device, output = the k drafted tokens [k] (device). No host work between the steps."""@@ -216,12 +220,16 @@ class MTPGraph:mt = self.mtouts, tok, h = [], self.inp[0:1], self.h0pos = self.inp[1:2]+ confs = []for i in range(self.k):y, lg = mt.step(tok, h, pos + i if i else pos, N)tok = mt.pick(lg)outs.append(tok)+ if CONF: # max softmax probability of the draft head, fixed point 2^-20, appended after the k tokens (cost-aware draft length)+ l32 = lg.float()+ confs.append((torch.exp(l32.max() - torch.logsumexp(l32, 0)) * CONF_ONE).long().reshape(1))h = y- return torch.cat(outs)+ return torch.cat(outs + confs)def _graph(self, N):g = self.graphs.get(N)diff --git a/tools/hy4/draft_policy.py b/tools/hy4/draft_policy.pynew file mode 100644index 0000000..9e580f1--- /dev/null+++ b/tools/hy4/draft_policy.py@@ -0,0 +1,84 @@+"""Cost-aware draft length per round (generic: nothing model specific). Inputs: the drafter's confidence of each chained draft token and a verify-cost table+(ms of one verify step with T rows, measured on the machine). Chain model: draft i is accepted with probability p_i = cal(conf_i) given all earlier drafts were; the expected+tokens of a round that verifies L drafts are E(L) = 1 + sum_{i<=L} prod_{j<=i} p_j, its cost is overhead + verify_ms(1 + L); pick the L with the best E / cost (L = 0 allowed).+cal() = per-confidence-bin acceptance, learnt online (prior = the confidence itself, weight PRIOR_N), updated from every verified draft; every PROBE-th round verifies the whole+chain so the bins of long drafts keep learning. Same design as the Mac policy (expected accepted tokens x per-row cost table): only the cost table differs by machine."""+import os++NBIN = 10+++def _table(s):+ t = {}+ for kv in s.split(","):+ a, b = kv.split(":")+ t[int(a)] = float(b)+ return t+++class CostPolicy:+ def __init__(self, verify_ms, overhead_ms, prior_n=6.0, probe=16):+ self.vt = dict(verify_ms)+ self.ovh = overhead_ms+ self.prior_n, self.probe = prior_n, probe+ self.reset_stats()+ self.hits = [[0.0, 0.0] for _ in range(NBIN)] # per bin: [accepted, total] observed (prior added in cal)++ @classmethod+ def from_env(cls):+ t = _table(os.environ.get("HY4_ROW_MS", "1:57,2:66,3:75,4:84,5:93,6:102,7:111,8:120"))+ return cls(t, float(os.environ.get("HY4_ROUND_OVH_MS", "12")), float(os.environ.get("HY4_POLICY_PRIOR_N", "6")), int(os.environ.get("HY4_POLICY_PROBE", "16")))++ def reset_stats(self):+ self.n_round = 0+ self.cut = 0 # rounds where fewer drafts than the chain length were verified+ self.rows_saved = 0+ self.lhist = {}++ def verify_ms(self, T):+ if T in self.vt:+ return self.vt[T]+ ks = sorted(self.vt)+ lo = max([x for x in ks if x < T], default=ks[0])+ hi = min([x for x in ks if x > T], default=ks[-1])+ if lo == hi:+ return self.vt[lo] + (T - lo) * (self.vt[ks[-1]] - self.vt[ks[-2]]) / max(1, ks[-1] - ks[-2]) if len(ks) > 1 else self.vt[lo]+ return self.vt[lo] + (self.vt[hi] - self.vt[lo]) * (T - lo) / (hi - lo)++ def cal(self, conf):+ b = min(NBIN - 1, int(conf * NBIN))+ a, n = self.hits[b]+ c = (b + 0.5) / NBIN+ return (a + self.prior_n * c) / (n + self.prior_n)++ def choose(self, confs, min_l=0):+ self.n_round += 1+ k = len(confs)+ if self.probe and self.n_round % self.probe == 0:+ best = k+ else:+ best, bs, surv, e = 0, 1.0 / (self.ovh + self.verify_ms(1)), 1.0, 1.0+ for L in range(1, k + 1):+ surv *= self.cal(confs[L - 1])+ e += surv+ sc = e / (self.ovh + self.verify_ms(1 + L))+ if sc > bs:+ best, bs = L, sc+ best = max(best, min_l)+ if best < k:+ self.cut += 1+ self.rows_saved += k - best+ self.lhist[best] = self.lhist.get(best, 0) + 1+ return best++ def update(self, confs, nd, acc):+ """nd drafts were verified, the first `acc` of them accepted"""+ for i in range(min(nd, acc + 1, len(confs))):+ b = min(NBIN - 1, int(confs[i] * NBIN))+ self.hits[b][1] += 1.0+ if i < acc:+ self.hits[b][0] += 1.0++ def stats(self):+ return {"rounds": self.n_round, "cut_rounds": self.cut, "rows_saved": self.rows_saved, "lhist": dict(self.lhist),+ "bins": [[round(a, 1), round(n, 1)] for a, n in self.hits]}diff --git a/tools/hy4/engine.py b/tools/hy4/engine.pyindex fa530d8..ec05f7e 100644--- a/tools/hy4/engine.py+++ b/tools/hy4/engine.py@@ -41,6 +41,11 @@ class Hy4Engine:self.ngram_fill = os.environ.get("HY4_NGRAM_FILL", "0") == "1"self.ngram_long = int(os.environ.get("HY4_NGRAM_LONG", "0")) # >= 1: a match of at least this many tokens REPLACES the MTP draft chain (verify y + up to TM - 1 copied tokens; the draft cache is refilled from the trunk states); 0 = offself._tune = None # torch.cuda.tunable module while a frozen TunableOp results file is loaded (HY4_TUNABLEOP_FILE)+ self.policy = None+ if os.environ.get("HY4_DRAFT_POLICY", "0") == "1":+ from draft_policy import CostPolicy+ os.environ["HY4_DRAFT_CONF"] = "1" # the draft graph appends the confidences (read at the import of mtp_head, i.e. in load())+ self.policy = CostPolicy.from_env()self.ready = Falseself.meta = Noneself.last_stats: dict = {}@@ -229,6 +234,8 @@ class Hy4Engine:from ngram import NGramng = NGram(self.ngram_min, self.ngram_ext)ng.reset(list(ids) + [y])+ if self.policy is not None:+ self.policy.reset_stats()n_ext = n_hit = n_extacc = n_long = 0rate, since = 0.7, 0 # recent acceptance of the extra rows; below 0.4 the proposer pauses (a probe every 8 rounds)while out_n < max_new and not stop and not cancel():@@ -243,6 +250,12 @@ class Hy4Engine:tb = pc()else:d = MG.run(y, hcur, j).tolist()+ confs = None+ if self.MH.CONF: # the draft graph appended the k confidences (fixed point 2^-20)+ confs = [c / 1048576.0 for c in d[k:]]+ d = d[:k]+ if self.policy is not None:+ d = d[:self.policy.choose(confs, 1 if ng is not None else 0)]tb = pc()ext = []if ng is not None and not skip:@@ -271,11 +284,16 @@ class Hy4Engine:nd = len(toks) - 1while acc < nd and toks[acc + 1] == amh[acc]:acc += 1+ kk = len(toks) - 1 - len(ext) # drafted rows of this round (the policy may cut the chain below k)+ if skip:+ pass+ elif self.policy is not None and confs is not None:+ self.policy.update(confs, kk, acc)if not skip:- n_extacc += max(0, acc - k)+ n_extacc += max(0, acc - kk)if ext and not skip:since = 0- rate = 0.75 * rate + 0.25 * (max(0, acc - k) / len(ext))+ rate = 0.75 * rate + 0.25 * (max(0, acc - len(d)) / len(ext))new = toks[1:acc + 1] + [amh[acc]] # toks[0] = y was already emitted; the verified drafts + the trunk's own next tokenGR.rewind(j + 2 + acc)if skip: # the chain wrote no head rows: pairs (token m, state before it) for head positions j .. j + acc@@ -283,10 +301,10 @@ class Hy4Engine:N = ((j + acc + 1 + 3) // 4) * 4sts = torch.cat([hc0, hv[:acc]]) if acc > 0 else hc0MT.step(torch.tensor(toks[:acc + 1], dtype=torch.long, device=self.dev), sts, MT.ar[j:j + acc + 1], N)- elif self.ngram_fill and acc >= k: # head rows j + k .. j + acc were never written by the draft chain: true pairs (token p + 1, trunk state h_p)+ elif self.ngram_fill and acc >= len(d) and len(d) >= 1: # head rows j + k .. j + acc were never written by the draft chain: true pairs (token p + 1, trunk state h_p)MT = self.MTN = ((j + acc + 1 + 3) // 4) * 4- MT.step(torch.tensor(toks[k:acc + 1], dtype=torch.long, device=self.dev), hv[k - 1:acc], MT.ar[j + k:j + acc + 1], N)+ MT.step(torch.tensor(toks[len(d):acc + 1], dtype=torch.long, device=self.dev), hv[len(d) - 1:acc], MT.ar[j + len(d):j + acc + 1], N)if ng is not None:ng.add(new)y, hcur = amh[acc], hv[acc:acc + 1]@@ -298,6 +316,8 @@ class Hy4Engine:out_n += len(new)stop = on_tokens(new)st["round_ms"] = [x / max(rounds, 1) * 1000 for x in tm]+ if self.policy is not None:+ st["policy"] = self.policy.stats()st["ngram"] = {"ext": self.ngram_ext, "min": self.ngram_min, "fill": self.ngram_fill, "hit_rounds": n_hit, "ext_rows": n_ext, "ext_accepted": n_extacc, "long": self.ngram_long, "long_rounds": n_long}else:while out_n < max_new and not stop and not cancel():