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: Q8_0 batched mat-vec for the per-head MLA k_b / v_b matrices (Triton, flag HY4_MLA_BG)
YanissAmz7b72a6688bd0
diff --git a/exllamav3/loader/attn_eager.py b/exllamav3/loader/attn_eager.pyindex 82f83e9..a4b97af 100644--- a/exllamav3/loader/attn_eager.py+++ b/exllamav3/loader/attn_eager.py@@ -11,6 +11,7 @@ Generic by shape: P, base, R, H come from the caller / tensors."""from __future__ import annotationsimport osimport torch+from . import mla_bgemv as _BG_F = os.environ.get("HY4_ATTN_EAGER", "0")ENABLED = _F in ("1", "2")@@ -90,7 +91,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, qp = qq[..., :m.nope], rope(qq[..., m.nope:], pos, m.theta)- qlat = torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))+ qlat = m.bg_kb.mv(m._q(qn, "kb")) if (_BG.ENABLED and T == 1 and getattr(m, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))return m._h(qlat, "q"), m._h(qp, "q")diff --git a/exllamav3/loader/attn_eager.py.pre_bg b/exllamav3/loader/attn_eager.py.pre_bgnew file mode 100644index 0000000..82f83e9--- /dev/null+++ b/exllamav3/loader/attn_eager.py.pre_bg@@ -0,0 +1,123 @@+"""HY4_ATTN_EAGER: fewer eager launches in the attention projections (flag default OFF; old path untouched when off).++ HY4_ATTN_EAGER=1 (bit-exact vs the old code)+ rope_norm : cos/sin built ONCE per (dim, base, device) in float64 with the SAME expression as the per-call path, cast to fp32,+ stored as [n, 2, P/2, 2] = [(c, s), (-s, c)]. A call = 1 index_select + 2 mul + 1 add (old: 18 launches, +1 contiguous+ in q). out = x0*(c,s) + x1*(-s,c) is the same fp32 ops as x0*c - x1*s / x0*s + x1*c (a - b == a + (-b), no FMA in eager).+ kv() : rms*w and rope write straight into one preallocated [T, R+rope] buffer (no torch.cat, no copy_ into out[..., 0::2]).+ HY4_ATTN_EAGER=2 = 1 + rmsw(): rms(x)*w as ONE Triton launch (kv_a, q_a, post-attn norm). The reduction order differs from torch's+ mean(), so NOT bit-exact (~1e-7 rel): gate it with teacher forcing before keeping.+Generic by shape: P, base, R, H come from the caller / tensors."""+from __future__ import annotations+import os+import torch++_F = os.environ.get("HY4_ATTN_EAGER", "0")+ENABLED = _F in ("1", "2")+RMS = _F == "2"+_NEED = [0] # highest position + 1 the caller announced (host int, set by ensure())+_TAB = {} # (P, base, device) -> [n, 2, P/2, 2]++try:+ import triton+ import triton.language as tl+except Exception:+ triton = None+++def ensure(n: int):+ """host-side bound on positions (start + T); tables grow lazily on the next rope call. No device sync."""+ if n > _NEED[0]:+ _NEED[0] = n+++def _build(P, base, n, dev):+ h = P // 2+ pos = torch.arange(n, device=dev)+ th = pos.double()[:, None] * (base ** (-2.0 * torch.arange(h, dtype=torch.float64, device=dev) / P))[None, :] # == rope_norm+ c, s = th.cos().float(), th.sin().float()+ tab = torch.empty(n, 2, h, 2, dtype=torch.float32, device=dev)+ tab[:, 0, :, 0], tab[:, 0, :, 1], tab[:, 1, :, 0], tab[:, 1, :, 1] = c, s, -s, c+ return tab+++def table(P, base, dev, pos):+ key = (P, float(base), str(dev))+ tab = _TAB.get(key)+ need = _NEED[0]+ if need == 0: # nobody announced a bound: derive it (one sync; CPU: free)+ need = int(pos.max()) + 1+ if tab is None or tab.shape[0] < need:+ tab = _TAB[key] = _build(P, base, max(need, 2 * (tab.shape[0] if tab is not None else 2048)), dev)+ return tab+++def rope(x, pos, base, out=None):+ """== mla_hy4.rope_norm (bit-exact). x [T, ..., P] with unit last stride (views / slices allowed); out: optional [T, ..., P] view"""+ P = x.shape[-1]+ h = P // 2+ g = table(P, base, x.device, pos).index_select(0, pos.long()) # [T, 2, h, 2]+ shp = (x.shape[0],) + (1,) * (x.dim() - 2) + (h, 2)+ a, b = g[:, 0].reshape(shp), g[:, 1].reshape(shp)+ xv = x.unflatten(-1, (h, 2))+ ov = torch.empty(xv.shape, dtype=x.dtype, device=x.device) if out is None else out.unflatten(-1, (h, 2))+ torch.add(xv[..., 0:1] * a, xv[..., 1:2] * b, out=ov)+ return ov.flatten(-2) if out is None else out+++def kv(m, cur, pos):+ """Hy4MLA.kv: [rms(kv_a)*w | rope(k_pe)] written into one buffer"""+ c = m._q(cur, "wkv_a") @ m.wkv_a.T+ R = m.R+ buf = torch.empty(c.shape[0], R + m.rope_dim, dtype=c.dtype, device=c.device)+ if RMS:+ rmsw(c[:, :R], m.kv_a_norm, m.eps, out=buf[:, :R])+ else:+ from .engram_rows import rms+ torch.mul(rms(c[:, :R], m.eps), m.kv_a_norm, out=buf[:, :R])+ rope(c[:, R:], pos, m.theta, out=buf[:, R:])+ return m._h(buf)+++def q(m, cur, pos):+ """Hy4MLA.q: same maths, rope reads the strided slice (no .contiguous())"""+ T, H = cur.shape[0], m.H+ qa = m._q(cur, "wq_a") @ m.wq_a.T+ if RMS:+ qr = rmsw(qa, m.q_a_norm, m.eps)+ else:+ from .engram_rows import rms+ qr = rms(qa, m.eps) * m.q_a_norm+ qq = (m._q(qr, "wq_b") @ m.wq_b.T).view(T, H, m.hd)+ qn, qp = qq[..., :m.nope], rope(qq[..., m.nope:], pos, m.theta)+ qlat = torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))+ return m._h(qlat, "q"), m._h(qp, "q")+++if triton is not None:+ @triton.jit+ def _k_rmsw(x_ptr, w_ptr, o_ptr, D, sx, so, eps, BD: tl.constexpr):+ r = tl.program_id(0)+ d = tl.arange(0, BD)+ dm = d < D+ x = tl.load(x_ptr + r * sx + d, mask=dm, other=0.0)+ rc = tl.math.rsqrt(tl.sum(x * x, axis=0) / D + eps)+ tl.store(o_ptr + r * so + d, x * rc * tl.load(w_ptr + d, mask=dm, other=0.0), mask=dm)+++def rmsw(x, w, eps, out=None):+ """rms(x, eps) * w over the last dim of a [R, D] fp32 tensor (row stride free, unit column stride): one launch"""+ from .engram_rows import rms+ usable = (triton is not None and x.dtype == torch.float32 and x.dim() == 2 and x.stride(1) == 1 and w.is_contiguous()+ and (x.is_cuda or os.environ.get("TRITON_INTERPRET", "0") == "1") and x.shape[1] <= 8192+ and (out is None or (out.stride(1) == 1 and out.dtype == torch.float32)))+ if not usable:+ r = rms(x, eps) * w+ if out is None:+ return r+ out.copy_(r)+ return out+ o = torch.empty(x.shape, dtype=x.dtype, device=x.device) if out is None else out+ D = x.shape[1]+ _k_rmsw[(x.shape[0],)](x, w, o, D, x.stride(0), o.stride(0), eps, BD=triton.next_power_of_2(D), num_warps=8)+ return odiff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 7754c9e..5959bd9 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -28,6 +28,7 @@ from .engram_rows import F8Rows, Hy4Engram, load_dense, _dequant_q8_0, rmsfrom .mla_hy4 import Hy4MLAfrom . import ref_fused as _rffrom . import step_nosync as _ns+from . import mla_bgemv as _BGMfrom . import head_bf16 as _HBfrom . import attn_eager as _AE@@ -384,6 +385,9 @@ class Hy4Forward:L = SimpleNamespace()L.mla = Hy4MLA(g, i, q8_act=self.q8_act, lin=self._lin)_mv(L.mla, dev, self.wdtype)+ if dev.type == "cuda": # stored Q8_0 bytes of the two per-head MLA matrices (used when HY4_MLA_BG=1, T == 1)+ L.mla.bg_kb = _BGM.load(g, b + "attn_k_b.weight", L.mla.H, dev)+ L.mla.bg_vb = _BGM.load(g, b + "attn_v_b.weight", L.mla.H, dev)L.mla.tm = self.tmL.mla.kpos_arange = True # layer(): kpos is torch.arange(N) (ref_fused window / causal block skip)if os.environ.get("HY4_ATTN_GROUPED", "0") == "1": # flag off: nothing below runs, the old path is untoucheddiff --git a/exllamav3/loader/hy4_forward.py.pre_bg b/exllamav3/loader/hy4_forward.py.pre_bgnew file mode 100644index 0000000..7754c9e--- /dev/null+++ b/exllamav3/loader/hy4_forward.py.pre_bg@@ -0,0 +1,665 @@+"""Hy4-flash (hy_v4_flash) WHOLE-MODEL forward, slow but correct: torch only, no extension kernel, runs on CPU or any torch device.++Composition of the registry blocks' reference maths (embedding, engram_hy4 + f8_rows, hyper_connection, mla + mla_window_sinks ++mla_output_gate, dsa_kpool_indexer, dense / latent_moe + router_score_bias, hyper_head, output_norm + output); the trunk is+block_count - nextn_predict_layers layers (blk 42, the MTP block, is never read). Only active when the GGUF plan selects those blocks+(`is_hy4_plan`); nothing else imports this file.++ weights non-expert tensors are dequantised once per layer (Q8_0 / F32 / BF16) into `wdtype` on `device` (kept when cache_weights);+ routed experts stay raw in the GGUF (page cache): per call only the experts the router picked are read by offset,+ dequantised (Q4_K / Q3_K torch paths) and dropped. The two-limit SwiGLU clamp (gate min 10, up +-10) is the torch path.+ streams [T, hc, n_embd] fp32 between layers; HC identity comb (no cross-stream mix); engram before hc_pre on ple.layers.+ cache per layer the MLA K rows [N, kv_lora + rope] (V = first kv_lora columns), full length (window layers mask, sinks always);+ per full layer one KPoolIndexer (CPU) whose selected rows become the attention mask (all-causal selections skip the mask).+ decode Hy4Forward.step(ids) appends to the caches; generate() = one prefill + greedy steps.+Activations are NOT Q8-quantised (llama.cpp CPU quantises them): small numeric differences vs the oracle are expected."""+from __future__ import annotations+import contextlib+import importlib.util+import os+import sys+import time+from types import SimpleNamespace++import numpy as np+import torch++from .engram_rows import F8Rows, Hy4Engram, load_dense, _dequant_q8_0, rms+from .mla_hy4 import Hy4MLA+from . import ref_fused as _rf+from . import step_nosync as _ns+from . import head_bf16 as _HB+from . import attn_eager as _AE++_HCF = None+if os.environ.get("HY4_HC_FUSED", "0") == "1": # fused hyper-connection sites (loader/hc_fused.py)+ from . import hc_fused as _HCF++_HERE = os.path.dirname(os.path.abspath(__file__))+_NEED = {"mla", "mla_window_sinks", "hyper_connection", "latent_moe", "engram_hy4"}+++def is_hy4_plan(plan) -> bool:+ """registry predicate: the plan selected the Hy4 block set (a plain llama / qwen plan never does)"""+ names = set()+ for i in range(len(plan.layers)):+ names |= set(plan.blocks_at(i))+ return _NEED <= names and "hyper_head" in set(plan.glob.get("head_mod", []))+++def _kpool_mod():+ sp = importlib.util.spec_from_file_location("exl_kpool_indexer", os.path.join(os.path.dirname(_HERE), "modules", "kpool_indexer.py"))+ m = importlib.util.module_from_spec(sp)+ sys.modules["exl_kpool_indexer"] = m+ sp.loader.exec_module(m)+ return m+++# ------------------------------------------------------------------------------------------------ dequant (any device)+def _raw(raw, dev):+ return raw.to(dev) if torch.is_tensor(raw) else torch.from_numpy(np.ascontiguousarray(raw)).to(dev)+++def dq_q4k(raw, N, K, dev="cpu"):+ """Q4_K (144 B / 256: fp16 d, fp16 dmin, 12 B 6-bit scales / mins, 128 B nibbles) -> fp32 [N, K] (ggml dequantize_row_q4_K)"""+ nb = K // 256+ r = _raw(raw, dev).reshape(N * nb, 144)+ d = r[:, 0:2].contiguous().view(torch.float16).float().reshape(-1, 1)+ dm = r[:, 2:4].contiguous().view(torch.float16).float().reshape(-1, 1)+ s = r[:, 4:16].int()+ sc = torch.cat([s[:, 0:4] & 63, (s[:, 8:12] & 15) | ((s[:, 0:4] >> 6) << 4)], 1).float()+ mn = torch.cat([s[:, 4:8] & 63, (s[:, 8:12] >> 4) | ((s[:, 4:8] >> 6) << 4)], 1).float()+ qs = r[:, 16:].int().reshape(-1, 4, 32)+ out = torch.empty(N * nb, 8, 32, device=r.device)+ for j in range(4):+ out[:, 2 * j] = (qs[:, j] & 15).float() * (d * sc[:, 2 * j:2 * j + 1]) - dm * mn[:, 2 * j:2 * j + 1]+ out[:, 2 * j + 1] = (qs[:, j] >> 4).float() * (d * sc[:, 2 * j + 1:2 * j + 2]) - dm * mn[:, 2 * j + 1:2 * j + 2]+ return out.reshape(N, K)+++def dq_q3k(raw, N, K, dev="cpu"):+ """Q3_K (110 B / 256: hmask 32, qs 64, 12 B packed 6-bit scales, fp16 d) -> fp32 [N, K] (ggml dequantize_row_q3_K)"""+ nb = K // 256+ b = _raw(raw, dev).reshape(N * nb, 110)+ d = b[:, 108:110].contiguous().view(torch.float16).float().reshape(-1, 1, 1, 1)+ s = b[:, 96:108].long()+ a0 = (s[:, 0:4] % 16) | (((s[:, 8:12] // 1) % 4) * 16)+ a1 = (s[:, 4:8] % 16) | (((s[:, 8:12] // 4) % 4) * 16)+ a2 = ((s[:, 0:4] // 16) % 16) | (((s[:, 8:12] // 16) % 4) * 16)+ a3 = ((s[:, 4:8] // 16) % 16) | (((s[:, 8:12] // 64) % 4) * 16)+ sc = (torch.cat([a0, a1, a2, a3], 1) - 32).float().reshape(-1, 2, 4, 2).repeat_interleave(16, dim=3) # [nb, half, j, 32]+ sh = (2 * torch.arange(4, device=b.device)).reshape(1, 1, 4, 1)+ q = (b[:, 32:96].long().reshape(-1, 2, 1, 32) >> sh) % 4+ bit = (torch.arange(2, device=b.device).reshape(2, 1) * 4 + torch.arange(4, device=b.device).reshape(1, 4)).reshape(1, 2, 4, 1)+ hm = (b[:, 0:32].long().reshape(-1, 1, 1, 32) >> bit) % 2+ return (d * sc * (q - 4 * (1 - hm)).float()).reshape(N, K)+++def dq_expert(raw, ty, N, K, dev):+ if ty == 12:+ return dq_q4k(raw, N, K, dev)+ if ty == 11:+ return dq_q3k(raw, N, K, dev)+ raise ValueError(f"routed expert tensor type {ty} not handled (Q4_K=12, Q3_K=11)")+++# ggml type id -> (format name, block elements): the SAME names foreign_linear._MMVQ_FN uses; the kernel is getattr(ext, "fq_mmvq_" + name)+# (llama.cpp mmvq port, fq_mmvq.cu, bound in bindings.cpp). Generic: keyed on the stored ggml type + K only, nothing model specific.+GG_MMVQ = {2: ("q4_0", 32), 3: ("q4_1", 32), 6: ("q5_0", 32), 7: ("q5_1", 32), 11: ("q3_k", 256), 12: ("q4_k", 256), 13: ("q5_k", 256),+ 14: ("q6_k", 256), 16: ("iq2_xxs", 256), 17: ("iq2_xs", 256), 18: ("iq3_xxs", 256), 20: ("iq4_nl", 32), 21: ("iq3_s", 256),+ 22: ("iq2_s", 256), 23: ("iq4_xs", 256)}+MMVQ_MAXR = 16 # decode rows per expert served by the row kernels (foreign_linear: rows < FUSED_ROWS_MAX), launched <= 4 columns at a time+_EXT = []++# ggml type id -> (grouped-kernel fmt id, block elements, block bytes): the fq_moe_kq_grouped_mixed_q8 table (fq_moe_kq.cu kFmtBytes). Generic: keyed on the stored type only.+# gate/up kernels exist for ids 0-5 and 8; down for 0-8.+GG_GROUPED = {12: (0, 256, 144), 13: (1, 256, 176), 14: (2, 256, 210), 23: (3, 256, 136), 18: (4, 256, 98), 22: (5, 256, 82), 8: (6, 32, 34),+ 7: (7, 32, 24), 11: (8, 256, 110)}+GROUPED_UG = (0, 1, 2, 3, 4, 5, 8)+EXPERT_PREAD = os.environ.get("HY4_EXPERT_PREAD", "0") == "1" # 1 = old path: experts pread from the GGUF every step ((1a) mmvq)+RESIDENT_GB = float(os.environ.get("HY4_EXPERT_RESIDENT_GB", "72")) # VRAM byte budget for resident routed experts (stored bytes)+++def _ext():+ """the compiled extension: $HY4_EXT_DIR/exllamav3_ext*.so if set (a tree built for THIS torch, e.g. the HIP tree on the Strix), else the tree root"""+ if not _EXT:+ try:+ import glob+ d = os.environ.get("HY4_EXT_DIR") or os.path.dirname(os.path.dirname(_HERE))+ f = sorted(glob.glob(os.path.join(d, "exllamav3_ext*.so")))[0]+ sp = importlib.util.spec_from_file_location("exllamav3_ext", f)+ e = importlib.util.module_from_spec(sp)+ sys.modules["exllamav3_ext"] = e+ sp.loader.exec_module(e)+ _EXT.append(e)+ except Exception as ex: # noqa: BLE001+ sys.modules.pop("exllamav3_ext", None)+ print("hy4_forward: extension unavailable:", repr(ex)[:160], flush=True)+ _EXT.append(None)+ return _EXT[0]+++def mmvq_fn(ty, K):+ """kernel for stored ggml type `ty` with row length K, or None (-> torch dequant path)"""+ f = GG_MMVQ.get(int(ty))+ e = _ext()+ if f is None or e is None or K % f[1] != 0 or not hasattr(e, "fq_mmvq_" + f[0]):+ return None+ return getattr(e, "fq_mmvq_" + f[0])+++def _dq_q8_0_t(packed):+ """stored Q8_0 blocks [N, nb, 34] uint8 (any device) -> fp32 [N, nb*32] (fp16 d, 32 int8): exact, same values as engram_rows._dequant_q8_0"""+ d = packed[:, :, 0:2].contiguous().view(torch.float16).float()+ q = packed[:, :, 2:].contiguous().view(torch.int8).float()+ return (q * d).reshape(packed.shape[0], -1)+++# DENSE table (move 3): stored ggml type id -> (block elems, bytes per block, decode GEMV name in the extension, torch dequant [N, nb, bb] -> fp32 [N, K]).+# Generic: keyed on the stored ggml type + K only, nothing model specific. A dense matrix whose type is here stays as stored bytes on the GPU;+# 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+DENSE_DQ = os.environ.get("HY4_DENSE_DQ", "0") == "1" # 1 = old path: dense matrices dequantised once to fp32 and kept resident+++def dense_fn(ty, K):+ """(spec, GEMV or None) for stored type `ty` with row length K, or None when the type is not in GG_DENSE / K is not a block multiple"""+ spec = GG_DENSE.get(int(ty))+ if spec is None or K % spec[0] != 0:+ return None+ e = _ext()+ return spec, (getattr(e, spec[2], None) if e is not None else None)+++class QLinear:+ """a dense [N, K] matrix kept as STORED bytes on the device; `x @ q.T` / q(x) = x [.., K] -> [.., N]"""++ def __init__(self, packed, ty, spec, gemv, stats=None):+ self.packed, self.ty, self.spec, self.gemv, self.stats = packed, int(ty), spec, gemv, stats+ self.shape = (packed.shape[0], packed.shape[1] * spec[0])++ @property+ def T(self):+ return _QT(self)++ def dense(self):+ return self.spec[3](self.packed)++ def __call__(self, x):+ K, N = self.shape[1], self.shape[0]+ lead = x.shape[:-1]+ x2 = x.reshape(-1, K)+ if x2.shape[0] <= DENSE_MAXR and self.gemv is not None:+ xf = x2.float().contiguous()+ out = torch.empty(xf.shape[0], N, dtype=torch.float32, device=x.device)+ self.gemv(xf, self.packed, out)+ if self.stats is not None:+ self.stats["dense_gemv"] = self.stats.get("dense_gemv", 0) + 1+ else:+ out = x2.float() @ self.dense().T+ if self.stats is not None:+ self.stats["dense_dq"] = self.stats.get("dense_dq", 0) + 1+ return out.to(x.dtype).reshape(*lead, N)+++class _QT:+ def __init__(self, q):+ self.q = q++ def __rmatmul__(self, x):+ return self.q(x)+++def load_linear(g, name, dev, stats=None):+ """Q8_0 (any type in GG_DENSE) dense tensor as QLinear on a cuda device when its GEMV exists and HY4_DENSE_DQ != 1; else None (caller dequantises)"""+ ty, dims, off = g.infos[name]+ if DENSE_DQ or torch.device(dev).type != "cuda" or len(dims) != 2:+ return None+ f = dense_fn(ty, dims[0])+ if f is None or f[1] is None:+ return None+ spec, fn = f+ K, N = dims[0], dims[1]+ raw = np.ascontiguousarray(g._pread(off, N * (K // spec[0]) * spec[1]))+ return QLinear(torch.from_numpy(raw).reshape(N, K // spec[0], spec[1]).to(dev), ty, spec, fn, stats)+++HEAD_CHUNK = 8192+++def head_gemm(h, W, chunk=HEAD_CHUNK):+ """output head, generic by dtype: h [R, D] fp32, W [V, D] bf16 / f16 / f32 (resident on h.device) -> logits [R, V] fp32.+ Per vocab chunk W is upcast to fp32 and multiplied (R == 1 = the same mat-vec the old CPU head used; R > 1 = one GEMM per chunk)."""+ if _HB.usable(h, W): # HY4_HEAD_BF16=1: one Triton mat-vec on the stored weights (no fp32 copy of W per chunk)+ return _HB.gemv(h, W)+ V = W.shape[0]+ out = torch.empty(h.shape[0], V, dtype=torch.float32, device=h.device)+ for a in range(0, V, chunk):+ w = W[a:a + chunk].float()+ if h.shape[0] == 1:+ out[0, a:a + chunk] = w @ h[0]+ else:+ out[:, a:a + chunk] = h @ w.T+ return out+++class _Tm:+ """per-class synchronised wall timers (off unless .on)"""+ CLASSES = ("attn proj", "MLA core + sinks", "indexer / kpool", "router", "routed experts", "shared expert", "Engram", "hc / norms", "head", "other")++ def __init__(self):+ self.on, self.acc = False, {}++ def reset(self):+ self.acc = {}++ @contextlib.contextmanager+ def t(self, name):+ if not self.on:+ yield+ return+ torch.cuda.synchronize()+ t0 = time.time()+ yield+ torch.cuda.synchronize()+ self.acc[name] = self.acc.get(name, 0.0) + time.time() - t0+++def _mv(o, dev, dtype=None):+ for k, v in list(vars(o).items()):+ if torch.is_tensor(v) and v.is_floating_point():+ setattr(o, k, v.to(dev, dtype) if (dtype is not None and v.dim() > 1) else v.to(dev))+ return o+++# ------------------------------------------------------------------------------------------------ the model+class Hy4Forward:+ _gs = None # step_graph._GS while a decode graph is warmed up / captured (static buffers), else None++ def __init__(self, g, device="cpu", n_layers=None, cache_weights=False, hook=None, wdtype=torch.float32, use_indexer=True, q8_act=False):+ m = g.meta+ p = m["general.architecture"] + "."+ self.g, self.dev, self.hook, self.cache_weights, self.wdtype = g, torch.device(device), hook, cache_weights, wdtype+ self.n_trunk = m[p + "block_count"] - m.get(p + "nextn_predict_layers", 0)+ self.n_layers = n_layers or self.n_trunk+ assert self.n_layers <= self.n_trunk+ self.D, self.hc = m[p + "embedding_length"], m[p + "hyper_connection.count"]+ self.eps, self.hc_eps = float(m[p + "attention.layer_norm_rms_epsilon"]), float(m[p + "hyper_connection.epsilon"])+ self.magnitude = float(m[p + "hyper_connection.magnitude"])+ self.n_dense = m[p + "leading_dense_block_count"]+ self.topk, self.w_scale = m[p + "expert_used_count"], float(m[p + "expert_weights_scale"])+ self.clamp = list(m[p + "swiglu_clamp_exp"])+ self.ple = set(m[p + "ple.layers"])+ self.idx_types = list(m[p + "attention.indexer.types"])+ self.swa = list(m[p + "attention.sliding_window_pattern"])+ self.ixc = dict(n_head=m[p + "attention.indexer.head_count"], head_dim=m[p + "attention.indexer.key_length"],+ top_k=m[p + "attention.indexer.top_k"], kpool=m[p + "attention.indexer.kpool"],+ select_tail=bool(m[p + "attention.indexer.kpool_select_tail"]), rope_dim=m[p + "rope.dimension_count"],+ rope_base=float(m[p + "rope.freq_base"]), eps=self.eps)+ self.use_indexer, self.q8_act = use_indexer, q8_act+ self.tm = _Tm()+ self.expert_dq = os.environ.get("HY4_EXPERT_DQ", "0") == "1" # 1 = old path (torch dequant) for decode rows too+ self.dense_dq = DENSE_DQ+ self.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+ self.table = F8Rows(g)+ self.kp = _kpool_mod()+ self.kc = [None] * self.n_layers+ self.ix, self.eng, self._lc = {}, {}, {}+ self.tokens: list[int] = []+ self.n = 0+ self.stats = {"layer_s": 0.0}+ ty, dims, off = g.infos["token_embd.weight"]+ assert ty == 8 and dims[0] % 32 == 0+ self._emb = (off, dims[0])+ self.out_norm = load_dense(g, "output_norm.weight").to(self.dev)+ self.hh = [load_dense(g, f"output_hc_{k}.weight").to(self.dev) for k in ("fn", "base", "scale")]+ self.out_w = g.get_tensor("output.weight", allow_bf16=True) # [vocab, n_embd] bf16 (or f32)+ assert tuple(self.out_w.shape) == (m[p + "vocab_size"], self.D), self.out_w.shape+ if not self.head_cpu:+ self.out_w = self.out_w.to(self.dev) # resident in its stored dtype (bf16: 0.74 GB)+ self._load_resident()++ 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 through+ fq_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.'''+ self.res, self.res_bytes = {}, 0+ self.stats["resident_layers"], self.stats["resident_gib"] = 0, 0.0+ if EXPERT_PREAD or self.expert_dq or self.dev.type != "cuda":+ return+ e = _ext()+ if e is None or not hasattr(e, "fq_moe_kq_grouped_mixed_q8") or not hasattr(e, "fq_moe_kq_set_swiglu_limit"):+ print("hy4_forward: grouped kernel unavailable -> experts stay on the pread path", flush=True)+ return+ g, dev, budget, skipped = self.g, self.dev, int(RESIDENT_GB * 2**30), []+ for i in range(self.n_dense, self.n_layers):+ info = {n: g.infos[f"blk.{i}.ffn_{n}_exps.weight"] for n in ("gate", "up", "down")}+ f = {n: GG_GROUPED.get(int(info[n][0])) for n in info}+ if None in f.values() or f["gate"][0] != f["up"][0] or f["gate"][0] not in GROUPED_UG or info["gate"][1] != info["up"][1]:+ skipped.append((i, "format"))+ continue+ if any(info[n][1][0] % f[n][1] or (f[n][0] < 6 and info[n][1][0] % 256) for n in info):+ skipped.append((i, "shape"))+ continue+ rows = {n: (info[n][1][1], info[n][1][0] // f[n][1] * f[n][2], info[n][1][2]) for n in info} # (rows, row bytes, experts)+ need = sum(r * rb * E for r, rb, E in rows.values())+ if self.res_bytes + need > budget:+ skipped.append((i, "budget"))+ break+ bufs, ptrs, strides = {}, {}, {}+ for n in ("gate", "up", "down"):+ r, rb, E = rows[n]+ tot = r * rb * E+ buf = torch.empty(tot, dtype=torch.uint8, device=dev)+ off = info[n][2]+ for o in range(0, tot, 1 << 27):+ c = min(1 << 27, tot - o)+ buf[o:o + c].copy_(torch.from_numpy(g._pread(off + o, c)))+ bufs[n], strides[n] = buf, rb+ ptrs[n] = torch.arange(E, dtype=torch.int64, device=dev) * (r * rb) + buf.data_ptr()+ self.res[i] = SimpleNamespace(bufs=bufs, ptrs=(ptrs["gate"], ptrs["up"], ptrs["down"]), strides=(strides["gate"], strides["up"], strides["down"]),+ fu=f["gate"][0], fd=f["down"][0])+ self.res_bytes += need+ for fd in getattr(g, "fds", []):+ try:+ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)+ except Exception: # noqa: BLE001+ pass+ self.stats["resident_layers"], self.stats["resident_gib"] = len(self.res), round(self.res_bytes / 2**30, 3)+ print(f"hy4_forward: resident experts {len(self.res)} layers {self.res_bytes / 2**30:.2f} GiB (budget {RESIDENT_GB} GiB) skipped={skipped[:3]}", flush=True)++ # -- weights+ def _w(self, name):+ q = load_linear(self.g, name, self.dev, self.stats)+ return q if q is not None else load_dense(self.g, name).to(self.dev, self.wdtype)++ def _lin(self, name):+ q = load_linear(self.g, name, self.dev, self.stats)+ return q if q is not None else load_dense(self.g, name)++ def _layer(self, i):+ if i in self._lc:+ return self._lc[i]+ g, b, dev = self.g, f"blk.{i}.", self.dev+ L = SimpleNamespace()+ L.mla = Hy4MLA(g, i, q8_act=self.q8_act, lin=self._lin)+ _mv(L.mla, dev, self.wdtype)+ L.mla.tm = self.tm+ L.mla.kpos_arange = True # layer(): kpos is torch.arange(N) (ref_fused window / causal block skip)+ if os.environ.get("HY4_ATTN_GROUPED", "0") == "1": # flag off: nothing below runs, the old path is untouched+ from .attn_grouped import install as _attn_group+ _attn_group(L.mla)+ L.mla.post_norm, L.mla.sinks = L.mla.post_norm.to(dev), L.mla.sinks.to(dev)+ for tag in ("hca", "hcf"):+ s = "attn" if tag == "hca" else "ffn"+ setattr(L, tag, [load_dense(g, f"{b}hc_{s}_{k}.weight").to(dev) for k in ("fn", "base", "scale")])+ L.attn_norm, L.ffn_norm, L.post_ffw = (load_dense(g, b + n).to(dev) for n in ("attn_norm.weight", "ffn_norm.weight", "post_ffw_norm.weight"))+ if i < self.n_dense:+ L.dense = [self._w(f"{b}ffn_{n}.weight") for n in ("gate", "up", "down")]+ else:+ L.router = g.get_tensor(b + "ffn_gate_inp.weight").float().to(dev)+ L.rbias = g.get_tensor(b + "exp_probs_b.bias").float().to(dev)+ L.rdown, L.rup = self._w(b + "ffn_routed_down.weight"), self._w(b + "ffn_routed_up.weight")+ L.shexp = [self._w(f"{b}ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]+ L.ety = g.infos[b + "ffn_gate_exps.weight"][0]+ L.ety_down = g.infos[b + "ffn_down_exps.weight"][0]+ L.ix = bool(self.use_indexer and self.idx_types[i] and not self.swa[i] and (b + "indexer.attn_k.weight") in g.infos)+ if self.cache_weights:+ self._lc[i] = L+ return L++ def _indexer(self, i):+ if i not in self.ix:+ g, b = self.g, f"blk.{i}."+ names = {"attn_k": "indexer.attn_k.weight", "k_norm": "indexer.k_norm.weight", "q_b": "indexer.attn_q_b.weight",+ "proj": "indexer.proj.weight", "value": "indexer_compressor_value.weight", "gate": "indexer_compressor_gate.weight",+ "ape": "indexer_compressor_ape.weight", "pool_norm": "indexer_compressor_norm.weight"}+ w = {k: load_dense(g, b + s) for k, s in names.items()}+ q8 = tuple(k for k, s in names.items() if g.infos[b + s][0] == 8)+ self.ix[i] = self.kp.KPoolIndexer(w, q8_weights=q8, **self.ixc)+ return self.ix[i]++ def _indexer_fused(self, i):+ fx = self.__dict__.setdefault("ixf", {})+ if i not in fx:+ from .indexer_fused import FusedKPoolIndexer+ g, b = self.g, f"blk.{i}."+ big = {"attn_k": "indexer.attn_k.weight", "q_b": "indexer.attn_q_b.weight",+ "value": "indexer_compressor_value.weight", "gate": "indexer_compressor_gate.weight"}+ small = {"k_norm": "indexer.k_norm.weight", "proj": "indexer.proj.weight",+ "ape": "indexer_compressor_ape.weight", "pool_norm": "indexer_compressor_norm.weight"}+ w = {k: self._lin(b + s) for k, s in big.items()} # QLinear (stored Q8 bytes) or fp32 tensor; `x @ w.T` works for both+ w.update({k: load_dense(g, b + s).to(self.dev) for k, s in small.items()})+ w = {k: (v.to(self.dev) if isinstance(v, torch.Tensor) else v) for k, v in w.items()}+ fx[i] = FusedKPoolIndexer(w, self.dev, **self.ixc)+ return fx[i]++ # -- pieces+ def _site(self, x, hw):+ fn, base, scale = hw+ T, H = x.shape[0], self.hc+ mix = rms(x.reshape(T, -1), self.eps) @ fn.T+ pre = torch.sigmoid(mix[:, :H] * scale[0] + base[:H]) + self.hc_eps+ post = self.magnitude * torch.sigmoid(mix[:, H:] * scale[1] + base[H:]) + self.hc_eps+ return pre, post++ def _mm(self, x, w):+ if isinstance(w, QLinear):+ return w(x).float()+ return (x.to(w.dtype) @ w.T).float()++ def _ffn(self, i, L, x):+ tm = self.tm+ if i < self.n_dense:+ gt, up, dn = L.dense+ with tm.t("other"):+ return self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn), None+ T, dev = x.shape[0], self.dev+ with tm.t("router"):+ if _rf.ENABLED: # HY4_REF_FUSED=1: one router kernel; the host sync (tolist) only where the pread loop needs it+ sel, w = _rf.router_select(x @ L.router.T, L.rbias, self.topk, self.w_scale)+ sel_l = [] if (self.res.get(i) is not None and T <= MMVQ_MAXR and dev.type == "cuda") else sorted(set(sel.flatten().tolist()))+ else:+ p = torch.sigmoid(x @ L.router.T)+ sel = torch.topk(p + L.rbias, self.topk, dim=-1).indices+ w = torch.gather(p, 1, sel)+ w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * self.w_scale+ sel_l = [] if _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)+ lat = torch.zeros(T, z.shape[1], device=dev)+ lim, N = float(self.clamp[i]), z.shape[1]+ b = f"blk.{i}."+ rs = self.res.get(i) if (T <= MMVQ_MAXR and dev.type == "cuda") else None+ if 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:+ self._gpart = torch.empty(MMVQ_MAXR * S, N, dtype=torch.float32, device=dev)+ self._gout = torch.empty(MMVQ_MAXR, N, dtype=torch.float32, device=dev)+ ext.fq_moe_kq_set_swiglu_limit(lim)+ ext.fq_moe_kq_grouped_mixed_q8(z.half().contiguous(), sel.contiguous(), w.half().contiguous(), *rs.ptrs, *rs.strides, rs.fu, rs.fd,+ self._gpart[:T * S], self._gout[:T])+ lat = self._gout[:T].clone()+ self.stats["grouped_calls"] = self.stats.get("grouped_calls", 0) + 1+ sel_l = [] # the per-expert pread loop below runs zero times+ kg, kd = (None, None) if (self.expert_dq or T > MMVQ_MAXR or dev.type != "cuda") else (mmvq_fn(L.ety, N), mmvq_fn(L.ety_down, N))+ use_k = kg is not None or kd is not None # per tensor: a stored type without a kernel keeps the torch dequant for that tensor only+ with tm.t("routed experts"):+ if use_k:+ ext, di = _ext(), (dev.index if dev.index is not None else torch.cuda.current_device())+ for e in sel_l:+ rows, slot = (sel == e).nonzero(as_tuple=True)+ zi = z[rows]+ R = zi.shape[0]+ raw = {n: self.g.get_tensor(f"{b}ffn_{n}_exps.e{e}.weight") for n in ("gate", "up", "down")}+ ty = {"gate": L.ety, "up": L.ety, "down": L.ety_down}+ fk = {"gate": kg, "up": kg, "down": kd}++ def mv(xr, n):+ """x [R,K] . W_n.T -> [R,N] fp32: mmvq on the stored bytes if the type has a kernel, else torch dequant (old path)"""+ self.stats["mmvq_calls" if fk[n] is not None else "dq_calls"] = self.stats.get("mmvq_calls" if fk[n] is not None else "dq_calls", 0) + 1+ if fk[n] is None:+ return xr @ dq_expert(raw[n], ty[n], N, N, dev).T+ Wb = _raw(raw[n], dev).reshape(N, -1).contiguous()+ qb = ext.fq_q8_scratch(di, R, N)+ ext.fq_quant_q8_1_rows(xr.half().contiguous(), qb)+ o = torch.empty(R, N, dtype=torch.float32, device=dev)+ for a0 in range(0, R, 4):+ fk[n](qb[a0:a0 + 4], Wb, o[a0:a0 + 4])+ return o+ ga, upv = mv(zi, "gate"), mv(zi, "up")+ h = torch.nn.functional.silu(ga.clamp(max=lim)) * upv.clamp(-lim, lim)+ dn_o = mv(h, "down")+ lat.index_add_(0, rows, dn_o * w[rows, slot].unsqueeze(-1))+ with tm.t("other"):+ y = self._mm(lat, L.rup)+ gt, up, dn = L.shexp+ with tm.t("shared expert"):+ sh = self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn)+ return y + sh, lat++ def _engram(self, i, x, ids, start):+ if os.environ.get("HY4_ENGRAM_GPU", "0") in ("1", "2") and self.dev.type == "cuda": # flag off: the old CPU path below, untouched+ if i not in self.eng:+ from .engram_gpu import Hy4EngramGPU+ self.eng[i] = Hy4EngramGPU(self.g, i, self.dev, table=self.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else self._lin) # 2 = dense fp32 kv (bit-exact vs CPU path)+ with self.tm.t("Engram"):+ return self.eng[i](x, ids, start)+ if i not in self.eng:+ self.eng[i] = Hy4Engram(self.g, i, table=self.table)+ with self.tm.t("Engram"):+ return self.eng[i](x.cpu(), ids, start).to(self.dev)++ def _hk(self, name, i, t):+ if self.hook is not None:+ self.hook(name, i, t)++ def layer(self, i, x, pos, ids, start):+ L = self._layer(i)+ T = x.shape[0]+ if _AE.ENABLED: # HY4_ATTN_EAGER: host bound for the rope tables (no sync)+ _AE.ensure(start + T)+ gs = self._gs+ if i in self.ple:+ x = gs.engram(self, i, x) if gs is not None else self._engram(i, x, ids, start)+ self._hk("engram_out", i, x)+ tm = self.tm+ with tm.t("hc / norms"):+ if _HCF is not None and _HCF.ok(x, L.hca, self.hc):+ post, cur = _HCF.site(x, L.hca, L.attn_norm, self.eps, self.hc_eps, self.magnitude)+ else:+ pre, post = self._site(x, L.hca)+ cur = rms((x * pre[:, :, None]).sum(1), self.eps) * L.attn_norm+ mla = L.mla+ with tm.t("attn proj"):+ kn = mla.kv(cur, pos)+ kc = gs.append_kv(i, kn) if gs is not None else _ns.append_kv(self, i, kn, start) if _ns.active(self) else (torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn)+ N = kc.shape[0]+ allow = None+ if L.ix:+ with tm.t("indexer / kpool"):+ qr = mla._q(cur, "wq_a") @ mla.wq_a.T+ qr = _HCF.rmsw(qr, mla.q_a_norm, mla.eps) if _HCF is not None else rms(qr, mla.eps) * mla.q_a_norm+ if os.environ.get("HY4_INDEXER_FUSED", "0") == "1" and self.dev.type == "cuda": # flag off: the old CPU path below, untouched+ allow = gs.indexer(self, i, cur, qr, N) if gs is not None else self._indexer_fused(i).forward(cur, qr, N)+ else:+ sel = self._indexer(i).forward(cur.cpu(), qr.cpu())+ if any(len(r) < int(pp) + 1 for r, pp in zip(sel.rows, pos.tolist())):+ allow = torch.zeros(T, N, dtype=torch.bool)+ for t, r in enumerate(sel.rows):+ allow[t, r.long()] = True+ allow = allow.to(self.dev)+ kqv, gated, out = mla.attend(cur, pos, kc, gs.ar[:N] if gs is not None else _ns.kpos(self, N) if _ns.active(self) else torch.arange(N, device=self.dev), allow)+ self.kc[i] = kc+ self._hk("attn_kqv", i, kqv)+ self._hk("attn_gated", i, gated)+ self._hk("attn_out", i, out)+ with tm.t("hc / norms"):+ if _HCF is not None and _HCF.ok(x, L.hcf, self.hc) and out.shape == (T, self.D):+ s1, post2, cur2 = _HCF.res_site(x, out, post, L.hcf, L.ffn_norm, self.eps, self.hc_eps, self.magnitude)+ else:+ s1 = x + post[:, :, None] * out[:, None, :]+ pre2, post2 = self._site(s1, L.hcf)+ cur2 = rms((s1 * pre2[:, :, None]).sum(1), self.eps) * L.ffn_norm+ f, lat = self._ffn(i, L, cur2)+ if lat is not None:+ self._hk("ffn_moe_out", i, lat)+ with tm.t("hc / norms"):+ if _HCF is not None and _HCF.ok(s1, L.hcf, self.hc) and f.shape == (T, self.D):+ s2 = _HCF.resid(s1, f, post2, L.post_ffw, self.eps)+ else:+ f = rms(f, self.eps) * L.post_ffw+ s2 = s1 + post2[:, :, None] * f[:, None, :]+ self._hk("l_out", i, s2)+ return s2++ def embed(self, ids):+ off, K = self._emb+ rb = K // 32 * 34+ rows = [_dequant_q8_0(self.g._pread(off + int(t) * rb, rb), K, 1) for t in ids]+ return torch.cat(rows).to(self.dev)++ def head(self, x, all_pos=False):+ """x [T, hc, n_embd] -> logits of the LAST position [vocab] (all_pos: [T, vocab])"""+ with self.tm.t("head"):+ return self._head(x, all_pos)++ def _head(self, x, all_pos=False):+ fn, base, scale = self.hh+ xl = x if all_pos else x[-1:]+ R = xl.shape[0]+ if _HCF is not None and self.hook is None and _HCF.ok(xl, self.hh, self.hc):+ h = _HCF.site(xl, self.hh, self.out_norm, self.eps, self.hc_eps, self.magnitude)[1]+ else:+ mix = rms(xl.reshape(R, -1), self.eps) @ fn.T+ pre = torch.sigmoid(mix * scale[0] + base) + self.hc_eps+ col = (xl * pre[:, :, None]).sum(1)+ self._hk("hc_head", -1, col)+ h = rms(col, self.eps) * self.out_norm+ if self.head_cpu:+ h = h.cpu()+ 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):+ """append ids (prefill = all prompt ids at once, decode = one id), return last-position logits (None on a truncated stack)"""+ if _ns.active(self):+ return _ns.step(self, ids, all_pos)+ if self.tm.on:+ torch.cuda.synchronize()+ base = sum(self.tm.acc.values())+ t0 = time.time()+ start = self.n+ self.tokens += [int(t) for t in ids]+ pos = torch.arange(start, start + len(ids), device=self.dev)+ e = self.embed(ids)+ x = e[:, None, :].expand(-1, self.hc, -1).contiguous()+ for i in range(self.n_layers):+ x = self.layer(i, x, pos, self.tokens, start)+ self.n += len(ids)+ self._x = x+ lg = self.head(x, all_pos) if self.n_layers == self.n_trunk else None+ if self.tm.on:+ torch.cuda.synchronize()+ tot = time.time() - t0+ self.tm.acc["other"] = self.tm.acc.get("other", 0.0) + max(0.0, tot - (sum(self.tm.acc.values()) - base))+ self.tm.last_total = tot+ self.stats["layer_s"] += time.time() - t0+ return lg++ def generate(self, ids, n_new):+ if _ns.active(self):+ return _ns.generate(self.step, ids, n_new)+ t0 = time.time()+ lg = self.step(ids)+ t1 = time.time()+ first, out = lg, []+ for _ in range(n_new):+ nxt = int(lg.argmax())+ out.append(nxt)+ if len(out) == n_new:+ break+ lg = self.step([nxt])+ t2 = time.time()+ return first, out, {"prefill_s": t1 - t0, "decode_s": t2 - t1, "decode_steps": max(len(out) - 1, 0)}diff --git a/exllamav3/loader/mla_bgemv.py b/exllamav3/loader/mla_bgemv.pynew file mode 100644index 0000000..0a9065c--- /dev/null+++ b/exllamav3/loader/mla_bgemv.py@@ -0,0 +1,59 @@+"""HY4_MLA_BG=1: the two per-head absorbed MLA matrices (attn_k_b [H, R, nope], attn_v_b [H, vd, R]) read from their STORED Q8_0 bytes at decode.++The old path keeps them as fp32 (`_dense3`, 4.25x the stored size) and runs `einsum` per token: 2.1 GiB read per token (all layers), ~10 ms.+Here int8 q [H, N, K] + fp16 block scales [H, N, K/32] (1.0625 B / weight, exactly the stored values) are read by ONE Triton batched mat-vec per+matrix (grid H x N tiles), fp32 accumulate: out[h, n] = sum_k (q * d)[h, n, k] * x[h, k]. Same products as the fp32 einsum (q * d is the+same fp32 value), only the summation order differs. T > 1 (prefill) keeps the fp32 einsum. Generic by shape (H, N, K % 32 == 0)."""+import os++import numpy as np+import torch+import triton+import triton.language as tl++ENABLED = 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"))+++def _k_bg(q_ptr, d_ptr, x_ptr, o_ptr, N, K, NB, BN: tl.constexpr, BK: tl.constexpr):+ h = tl.program_id(0)+ rows = tl.program_id(1) * BN + tl.arange(0, BN)+ rm = rows < N+ acc = tl.zeros([BN], dtype=tl.float32)+ qrow = (h * N + rows)[:, None] * K+ drow = (h * N + rows)[:, None] * NB+ for k0 in range(0, K, BK):+ cols = k0 + tl.arange(0, BK)+ cm = cols < K+ m2 = rm[:, None] & cm[None, :]+ q = tl.load(q_ptr + qrow + cols[None, :], mask=m2, other=0).to(tl.float32)+ d = tl.load(d_ptr + drow + (cols // 32)[None, :], mask=m2, other=0.0).to(tl.float32)+ xv = tl.load(x_ptr + h * K + cols, mask=cm, other=0.0)+ acc += tl.sum(q * d * xv[None, :], axis=1)+ tl.store(o_ptr + h * N + rows, acc, mask=rm)+++class Q8Batched:+ """[H, N, K] Q8_0 matrix as int8 + fp16 scales on a device"""++ def __init__(self, raw, H, N, K, dev):+ b = torch.from_numpy(np.ascontiguousarray(raw)).reshape(H * N, K // 32, 34).to(dev)+ self.d = b[:, :, 0:2].contiguous().view(torch.float16).reshape(H, N, K // 32).contiguous()+ self.q = b[:, :, 2:].contiguous().view(torch.int8).reshape(H, N, K).contiguous()+ self.H, self.N, self.K = H, N, K++ def mv(self, x):+ """x [1, H, K] fp32 -> [1, H, N] fp32"""+ out = torch.empty(self.H, self.N, dtype=torch.float32, device=x.device)+ _k_bg[(self.H, triton.cdiv(self.N, BN))](self.q, self.d, x.reshape(self.H, self.K).contiguous(), out, self.N, self.K, self.K // 32, BN=BN, BK=BK, num_warps=4)+ return out.reshape(1, self.H, self.N)+++def load(g, name, H, dev):+ """GGUF 3-D Q8_0 tensor (ne0 = K, ne1 = N, ne2 = H) -> Q8Batched"""+ ty, dims, off = g.infos[name]+ assert ty == 8 and dims[2] == H and dims[0] % 32 == 0, (name, ty, dims)+ K, N = dims[0], dims[1]+ return Q8Batched(g._pread(off, N * H * (K // 32) * 34), H, N, K, dev)diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex 61b627a..2935beb 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -7,6 +7,7 @@ import importlib.util, osimport torchfrom .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rmsfrom . import ref_fused as _rf+from . import mla_bgemv as _BGfrom . import attn_eager as _ae@@ -95,7 +96,7 @@ class Hy4MLA:qr = rms(self._q(cur, "wq_a") @ self.wq_a.T, self.eps) * self.q_a_normq = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)- qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))+ qlat = self.bg_kb.mv(self._q(qn, "kb")) if (_BG.ENABLED and T == 1 and getattr(self, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))return self._h(qlat, "q"), self._h(qp, "q")def attend(self, cur, pos, kcache, kpos, allow=None):@@ -111,7 +112,7 @@ class Hy4MLA:else:o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)with tm.t("attn proj"):- kqv = torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb")).reshape(T, H * self.vd)+ kqv = (self.bg_vb.mv(self._q(o, "vb")) if (_BG.ENABLED and T == 1 and getattr(self, "bg_vb", None) is not None) else torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb"))).reshape(T, H * self.vd)gated, out = self.gate_out(cur, kqv)return kqv, gated, outdiff --git a/exllamav3/loader/mla_hy4.py.pre_bg b/exllamav3/loader/mla_hy4.py.pre_bgnew file mode 100644index 0000000..61b627a--- /dev/null+++ b/exllamav3/loader/mla_hy4.py.pre_bg@@ -0,0 +1,147 @@+"""CPU fp32 reference of the Hy4-flash attention layer (registry blocks mla + mla_window_sinks + mla_output_gate; design+HY4_STRIX_DESIGN.md section 2). Maths of llama.cpp hy-v4-flash.cpp build_attention (patch M:5787-5947), config from the GGUF+header keys and the per-layer tensors only. Weights are dequantised once (Q8_0 / F32); the ForeignLinear path is a later step.+Only relative import: loader/engram_rows.py (tests load both by path)."""+from __future__ import annotations+import importlib.util, os+import torch+from .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rms+from . import ref_fused as _rf+from . import attn_eager as _ae+++def _sinks_mod():+ p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "modules", "attention_fn", "mla_sinks.py")+ spec = importlib.util.spec_from_file_location("exl_mla_sinks", p)+ m = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(m)+ return m+++def _dense3(g, name, h):+ """GGUF 3-D Q8_0 tensor (ne0, ne1, h) -> [h, ne1, ne0] fp32 (ggml_mul_mat(w, x): out[h, j] = sum_k w[h, j, k] x[k])"""+ ty, dims, off = g.infos[name]+ assert ty == 8 and dims[2] == h, (name, ty, dims)+ return _dequant_q8_0(g._pread(off, dims[1] * dims[2] * (dims[0] // 32) * 34), dims[0], dims[1] * dims[2]).view(h, dims[1], dims[0])+++def rope_norm(x: torch.Tensor, pos: torch.Tensor, base: float) -> torch.Tensor:+ """ggml_rope_ext mode NORM (consecutive pairs), n_dims = x.shape[-1], no scaling / yarn: x [T, ..., P], pos [T]"""+ P = x.shape[-1]+ th = pos.double()[:, None] * (base ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=pos.device) / P))[None, :] # [T, P/2]+ c, s = th.cos().float().to(x.device), th.sin().float().to(x.device)+ shp = (x.shape[0],) + (1,) * (x.dim() - 2) + (P // 2,)+ c, s = c.view(shp), s.view(shp)+ x0, x1 = x[..., 0::2], x[..., 1::2]+ out = torch.empty_like(x)+ out[..., 0::2], out[..., 1::2] = x0 * c - x1 * s, x0 * s + x1 * c+ return out+++class Hy4MLA:+ """One attention layer: cur [T, n_embd] (normed collapsed stream) -> kqv / gated / out, with a K cache the caller keeps."""++ def __init__(self, g, layer: int, q8_act: bool = False, f16_kv: bool = False, lin=None):+ m = g.meta+ p = m["general.architecture"] + "."+ b = f"blk.{layer}."+ self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv+ lin = lin or (lambda n: load_dense(g, n)) # lin(name) -> fp32 [N, K] or a QLinear (stored bytes, hy4_forward.py)+ self.H = int(list(m[p + "attention.head_count"])[layer])+ self.hd, self.vd = m[p + "attention.key_length_mla"], m[p + "attention.value_length_mla"]+ self.rope_dim, self.R = m[p + "rope.dimension_count"], m[p + "attention.kv_lora_rank"]+ self.nope = self.hd - self.rope_dim+ pat = m.get(p + "attention.sliding_window_pattern")+ self.swa = bool(list(pat)[layer]) if pat is not None else False+ self.window = int(m[p + "attention.sliding_window"]) if self.swa else 0+ self.theta = float(m[p + ("rope.freq_base_swa" if self.swa else "rope.freq_base")])+ self.eps = float(m[p + "attention.layer_norm_rms_epsilon"])+ self.scale = 1.0 / float(self.hd) ** 0.5+ self.wq_a, self.q_a_norm = lin(b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")+ self.wq_b = lin(b + "attn_q_b.weight")+ self.wkv_a, self.kv_a_norm = lin(b + "attn_kv_a_mqa.weight"), load_dense(g, b + "attn_kv_a_norm.weight")+ self.wk_b, self.wv_b = _dense3(g, b + "attn_k_b.weight", self.H), _dense3(g, b + "attn_v_b.weight", self.H)+ self.wo, self.wgate = lin(b + "attn_output.weight"), lin(b + "attn_gate.weight")+ pn = b + POST_NORM+ self.post_norm = load_dense(g, pn) if pn in g.infos else None+ sk = b + "attn_sinks.weight"+ self.sinks = load_dense(g, sk) if sk in g.infos else None+ self.S = _sinks_mod()++ tm = type("_NoTm", (), {"t": staticmethod(lambda n: __import__("contextlib").nullcontext())})() # replaced by Hy4Forward._Tm+ q8_skip: tuple = () # matmul tags (wq_a wq_b wkv_a kb vb wgate wo) whose activation is NOT quantised (diagnostics)+ f16_parts: tuple = ("q", "k")++ def _q(self, x, tag=None): # activation of a Q8_0 mul_mat (llama.cpp CPU vec_dot_type)+ return q8_0_roundtrip(x) if self.q8_act and tag not in self.q8_skip else x++ def _h(self, x, part="k"):+ return x.half().float() if self.f16_kv and part in self.f16_parts else x++ 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)"""+ if _ae.ENABLED: # HY4_ATTN_EAGER: table rope, no cat+ return _ae.kv(self, cur, pos)+ c = self._q(cur, "wkv_a") @ self.wkv_a.T+ lat = rms(c[:, :self.R], self.eps) * self.kv_a_norm+ pe = rope_norm(c[:, self.R:], pos, self.theta)+ return self._h(torch.cat([lat, pe], -1))++ def q(self, cur, pos):+ """-> q_lat [T,H,R], q_pe [T,H,rope] (q_nope absorbed with k_b; rope on the pe part)"""+ if _ae.ENABLED:+ return _ae.q(self, cur, pos)+ T, H = cur.shape[0], self.H+ qr = rms(self._q(cur, "wq_a") @ self.wq_a.T, self.eps) * self.q_a_norm+ q = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)+ qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)+ qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))+ return self._h(qlat, "q"), self._h(qp, "q")++ def attend(self, cur, pos, kcache, kpos, allow=None):+ """cur [T, n_embd] at positions pos; kcache [N, R+rope] at kpos (includes the T new rows). -> (kqv, gated, out)"""+ T, H = cur.shape[0], self.H+ tm = self.tm+ with tm.t("attn proj"):+ qlat, qpe = self.q(cur, pos)+ with tm.t("MLA core + sinks"):+ if _rf.ENABLED: # HY4_REF_FUSED=1: one online-softmax kernel (sinks / window / allow inside)+ o = _rf.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow,+ kpos_is_arange=getattr(self, "kpos_arange", False))+ else:+ o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)+ with tm.t("attn proj"):+ 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)+ return kqv, gated, out++ def gate_out(self, cur, kqv):+ """isolated tail (gate, then wo, then post norm): oracle attn_kqv + cur -> (gated, out)"""+ gated = self.S.sigmoid_gate(kqv, self._q(cur, "wgate") @ self.wgate.T)+ out = self._q(gated, "wo") @ self.wo.T+ if _ae.RMS and self.post_norm is not None: # HY4_ATTN_EAGER=2+ return gated, _ae.rmsw(out, self.post_norm, self.eps)+ return gated, (rms(out, self.eps) * self.post_norm if self.post_norm is not None else out)+++POST_NORM = "post_attention_norm.weight"+++class Hy4HCPre:+ """hc_pre (M:5383-5418) + reduce + attn_norm: stream [T, hc, n_embd] -> normed collapsed cur [T, n_embd] and pre weights [T, hc]"""++ def __init__(self, g, layer: int):+ m = g.meta+ p = m["general.architecture"] + "."+ b = f"blk.{layer}."+ self.hc, self.eps = m[p + "hyper_connection.count"], float(m[p + "attention.layer_norm_rms_epsilon"])+ self.hc_eps = float(m[p + "hyper_connection.epsilon"])+ self.fn, self.base, self.scale = load_dense(g, b + "hc_attn_fn.weight"), load_dense(g, b + "hc_attn_base.weight"), load_dense(g, b + "hc_attn_scale.weight")+ self.norm = load_dense(g, b + "attn_norm.weight")++ def __call__(self, x):+ T = x.shape[0]+ mixes = rms(x.reshape(T, -1), self.eps) @ self.fn.T+ pre = torch.sigmoid(mixes[:, :self.hc] * self.scale[0] + self.base[:self.hc]) + self.hc_eps+ cur = (x * pre[:, :, None]).sum(1)+ return rms(cur, self.eps) * self.norm, pre