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 prefill: row-major batch-over-heads MLA projections (the permuted view made every later elementwise op a stride-T gather: attention projections 38 s -> 13 s at 8K), stage timers in the dense prefill path, stable router top-k (tie order was nondeterministic)
YanissAmz458230f65319
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex f8de453..e8c855d 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -216,6 +216,9 @@ def dense_fn(ty, K):return spec, (getattr(e, spec[2], None) if e is not None else None)+_TM_HOLD = [None] # the live _Tm (stage timers inside prefill dense calls)++class QLinear:"""a dense [N, K] matrix kept as STORED bytes on the device; `x @ q.T` / q(x) = x [.., K] -> [.., N]"""@@ -242,7 +245,7 @@ class QLinear:self.stats["dense_gemv"] = self.stats.get("dense_gemv", 0) + 1elif PF_DENSE and self.ty == 8 and x2.is_cuda:k_ = _pk()- out = k_.qdense_i8(x2, self.packed) if PF_DENSE_I8 else (k_.qdense_tm(x2, self.packed) if x2.shape[0] >= k_.DENSE_TM_MIN_M else k_.qdense(x2, self.packed, k_.FMT_Q8))+ out = k_.qdense_i8(x2, self.packed) if PF_DENSE_I8 else (k_.qdense_tm(x2, self.packed, _TM_HOLD[0]) if x2.shape[0] >= k_.DENSE_TM_MIN_M else k_.qdense(x2, self.packed, k_.FMT_Q8))if PF_DIAG:ex = x2.float() @ self.dense().Tdf = out.float() - ex@@ -351,6 +354,7 @@ class Hy4Forward:rope_base=float(m[p + "rope.freq_base"]), eps=self.eps)self.use_indexer, self.q8_act = use_indexer, q8_actself.tm = _Tm()+ _TM_HOLD[0] = self.tmself.expert_dq = os.environ.get("HY4_EXPERT_DQ", "0") == "1" # 1 = old path (torch dequant) for decode rows tooself.dense_dq = DENSE_DQself.head_cpu = os.environ.get("HY4_HEAD_CPU", "0") == "1" or self.dev.type != "cuda" # 1 = old path: head on the CPU, last position only@@ -521,7 +525,7 @@ class Hy4Forward:p = torch.sigmoid(_pk().mm_f32(_pk().to_f16(x), L.router16.T))else:p = torch.sigmoid(x @ L.router.T)- sel = torch.topk(p + L.rbias, self.topk, dim=-1).indices+ sel = torch.sort(p + L.rbias, dim=-1, descending=True, stable=True).indices[:, :self.topk] # stable: tied experts resolve to the lowest id every call (torch.topk tie order varies between calls on gfx1151)w = torch.gather(p, 1, sel)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()))diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex 33d1b2e..917783e 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -91,6 +91,13 @@ class Hy4MLA:def _f16(x):return x.clamp(-65504.0, 65504.0).half()+ @staticmethod+ def _bmm_th(w16, x16):+ """w16 [H, Nout, K] fp16, x16 [T, H, K] fp16 -> [T, H, Nout] fp32 ROW-major: the batch-over-heads GEMM writes [H, T, Nout]; the permute-back copy keeps Nout contiguous.+ (Writing the result as a permuted view [T, H, Nout] with T fastest made every later elementwise / cat / clamp on it a stride-T gather: 10-30x slower.)"""+ o = torch.bmm(x16.permute(1, 0, 2), w16.transpose(1, 2))+ return o.permute(1, 0, 2).contiguous().float()+def kv(self, cur, pos):"""cur [T, n_embd], pos [T] -> K cache rows [T, R + rope] = [rms(kv_a)*w | rope(k_pe)] (V is the first R columns)"""tm = self.tm@@ -115,7 +122,7 @@ class Hy4MLA:qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)with tm.t("f q: wk_b bmm"):if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda: # prefill rows: fp16 batched GEMM over heads (fp32 einsum is ~3x slower)- qlat = torch.bmm(self._w16("wk_b"), self._f16(qn).permute(1, 2, 0)).permute(2, 0, 1).float()+ qlat = self._bmm_th(self._w16("wk_b"), self._f16(qn))else:qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))return self._h(qlat, "q"), self._h(qp, "q")@@ -138,7 +145,7 @@ class Hy4MLA:with tm.t("attn proj"):with tm.t("f attend: wv_b bmm"):if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda:- kqv = torch.bmm(self._w16("wv_b"), self._f16(o).permute(1, 2, 0)).permute(2, 0, 1).float().reshape(T, H * self.vd)+ kqv = self._bmm_th(self._w16("wv_b"), self._f16(o)).reshape(T, H * self.vd)else:kqv = torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb")).reshape(T, H * self.vd)gated, out = self.gate_out(cur, kqv)diff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.pyindex 255ba85..1db2c27 100644--- a/exllamav3/loader/prefill_kernels.py+++ b/exllamav3/loader/prefill_kernels.py@@ -7,6 +7,7 @@ Generic by stored format (FMT constexpr) and shape; nothing keyed on a model namaccumulation fp32. Formats follow ggml: Q4_K 144 B / 256, Q3_K 110 B / 256, Q8_0 34 B / 32."""from __future__ import annotations+import contextlibimport torchimport tritonimport triton.language as tl@@ -494,11 +495,18 @@ def dequant_q8(packed):return out-def qdense_tm(x, packed):- """x [.., K] -> [.., N] fp32 = x @ W.T: dequantise the stored Q8_0 weight to fp16 once per call, then the vendor fp16 GEMM"""+def qdense_tm(x, packed, tm=None):+ """x [.., K] -> [.., N] fp32 = x @ W.T: dequantise the stored Q8_0 weight to fp16 once per call, then the vendor fp16 GEMM (tm = optional stage timers)"""N, nb, bb = packed.shapeK = nb * 32lead = x.shape[:-1]- x2 = to_f16(x.reshape(-1, K)).contiguous()- out = mm_f32(x2, dequant_q8(packed).T)+ t = tm.t if tm is not None and tm.on else (lambda n: contextlib.nullcontext())+ with t(f"f dense N={N} K={K}: to_f16"):+ x2 = to_f16(x.reshape(-1, K)).contiguous()+ with t(f"f dense N={N} K={K}: dequant"):+ w16 = dequant_q8(packed)+ with t(f"f dense N={N} K={K}: mm"):+ o = torch.mm(x2, w16.T)+ with t(f"f dense N={N} K={K}: float"):+ out = torch.nan_to_num(o.float(), nan=0.0, posinf=F16MAX, neginf=-F16MAX)return out.reshape(*lead, N)