Skip to content

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.

Hy4 decode: HIP-graph step (static buffers, bucketed attention), table rope, bf16 head GEMV (flags, default off)

YanissAmz222caab70aaa
diff --git a/exllamav3/loader/attn_eager.py b/exllamav3/loader/attn_eager.py
new file mode 100644
index 0000000..82f83e9
--- /dev/null
+++ b/exllamav3/loader/attn_eager.py
@@ -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 o
diff --git a/exllamav3/loader/attn_grouped.py b/exllamav3/loader/attn_grouped.py
new file mode 100644
index 0000000..edba632
--- /dev/null
+++ b/exllamav3/loader/attn_grouped.py
@@ -0,0 +1,87 @@
+"""HY4_ATTN_GROUPED=1: attention projections that read the SAME input row run as ONE dense GEMV launch on the stored bytes.
+
+Generic by shape / stored type: any set of QLinear (hy4_forward.py) with equal K, stored ggml type and GEMV is concatenated along N
+(rows of the stored [N, K/blk, bb] bytes; the per-row dot never depends on N, so each output row is bit-identical to the separate
+launch). The originals are re-pointed to slices of the concatenated buffer (no extra resident bytes). One activation quantisation
+and one launch replace n. Results are cached per input tensor (identity + version), so a later projection of the same row
+(wkv_a, wgate, the indexer's repeated wq_a) is a cache hit. Rows > DENSE_MAXR (prefill) use each member's own path unchanged.
+"""
+from __future__ import annotations
+import torch
+
+from .hy4_forward import QLinear, DENSE_MAXR
+
+# attribute names of the MLA object that read the layer input `cur` (wq_a, wkv_a, wgate); keyed by role, not by model
+INPUT_SHARED = ("wq_a", "wkv_a", "wgate")
+
+
+class _Group:
+ def __init__(self, lins):
+ self.sizes = [q.shape[0] for q in lins]
+ self.offs = [sum(self.sizes[:i]) for i in range(len(lins))]
+ self.K, self.gemv, self.stats = lins[0].shape[1], lins[0].gemv, lins[0].stats
+ self.packed = torch.cat([q.packed for q in lins], 0)
+ self.ref = None # (x, x._version, outs)
+
+ def run(self, x):
+ r = self.ref
+ if r is not None and r[0] is x and r[1] == x._version:
+ return r[2]
+ x2 = x.reshape(-1, self.K)
+ xf = x2.float().contiguous()
+ out = torch.empty(xf.shape[0], sum(self.sizes), 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
+ self.stats["attn_grouped_calls"] = self.stats.get("attn_grouped_calls", 0) + 1
+ lead = x.shape[:-1]
+ outs = [out[:, o:o + n].to(x.dtype).reshape(*lead, n) for o, n in zip(self.offs, self.sizes)]
+ self.ref = (x, x._version, outs)
+ return outs
+
+
+class _GT:
+ def __init__(self, v):
+ self.v = v
+
+ def __rmatmul__(self, x):
+ return self.v(x)
+
+
+class GroupedView(QLinear):
+ """a member of a group: same attributes as the QLinear, decode rows go through the shared launch"""
+
+ def __init__(self, lin, group, idx, packed_view):
+ super().__init__(packed_view, lin.ty, lin.spec, lin.gemv, lin.stats)
+ self.group, self.idx, self.orig_call = group, idx, QLinear.__call__
+
+ @property
+ def T(self):
+ return _GT(self)
+
+ def __call__(self, x):
+ if x.numel() // self.shape[1] <= DENSE_MAXR and self.gemv is not None:
+ return self.group.run(x)[self.idx]
+ return QLinear.__call__(self, x)
+
+
+def group_linears(lins):
+ """list of QLinear reading the same input -> list of GroupedView (same order), or None when they cannot share one launch"""
+ if len(lins) < 2 or not all(isinstance(q, QLinear) and q.gemv is not None for q in lins):
+ return None
+ k = (lins[0].shape[1], lins[0].ty, lins[0].gemv)
+ if any((q.shape[1], q.ty, q.gemv) != k for q in lins) or len({q.packed.device for q in lins}) != 1:
+ return None
+ grp = _Group(lins)
+ return [GroupedView(q, grp, i, grp.packed[o:o + n]) for i, (q, o, n) in enumerate(zip(lins, grp.offs, grp.sizes))]
+
+
+def install(mla, names=INPUT_SHARED):
+ """regroup mla.<names> in place; returns True when grouped (originals' bytes are freed, the views share one buffer)"""
+ lins = [getattr(mla, n, None) for n in names]
+ views = group_linears(lins) if all(l is not None for l in lins) else None
+ if views is None:
+ return False
+ for n, v in zip(names, views):
+ setattr(mla, n, v)
+ return True
diff --git a/exllamav3/loader/engram_gpu.py b/exllamav3/loader/engram_gpu.py
new file mode 100644
index 0000000..345acc2
--- /dev/null
+++ b/exllamav3/loader/engram_gpu.py
@@ -0,0 +1,103 @@
+"""GPU Engram for hy4_forward (flag HY4_ENGRAM_GPU=1, patched in by hy4/patch_engram.py).
+
+Same maths as engram_rows.Hy4Engram.apply, but nothing of the hidden state leaves the device:
+ * the big row table stays on the CPU side (pread of the DISTINCT needed rows only, threaded, one pinned staging buffer),
+ * the raw bytes are copied to the device once per call and decoded there (E4M3 [* E8M0 scale] table gather, exact),
+ * engram_kv stays as stored bytes (QLinear, GEMV kernel for small T) when `lin` gives one, else a dense matrix on the device,
+ * norms / gate / signal are torch ops on the device (no x.cpu(), no .to(dev) round trip).
+The hash (integer, token ids only) stays on the CPU: it never touches activations.
+Generic: config comes from the GGUF header keys, the row form from F8Rows.layout; nothing keyed on a model name.
+"""
+from __future__ import annotations
+from concurrent.futures import ThreadPoolExecutor
+import numpy as np
+import torch
+
+from .engram_rows import Hy4Engram, F8Rows, load_dense, rms, E4M3, E8M0, QB
+
+_POOL = ThreadPoolExecutor(max_workers=16)
+_TABS: dict = {}
+
+
+def _tabs(dev):
+ k = str(dev)
+ if k not in _TABS:
+ _TABS[k] = (E4M3.to(dev), E8M0.to(dev))
+ return _TABS[k]
+
+
+def fetch_rows(table: F8Rows, ids, dev) -> torch.Tensor:
+ """ids (any int shape) -> float32 [*shape, width] on `dev`. Distinct rows are pread once (threaded), copied once, decoded on `dev`."""
+ ids = np.asarray(torch.as_tensor(ids, dtype=torch.int64).numpy())
+ uniq, inv = np.unique(ids.reshape(-1), return_inverse=True)
+ rb = table.row_bytes
+ buf = torch.empty(len(uniq), rb, dtype=torch.uint8).pin_memory() if torch.device(dev).type == "cuda" else torch.empty(len(uniq), rb, dtype=torch.uint8)
+ view = buf.numpy()
+
+ def one(a):
+ j, r = a
+ view[j] = table.raw_row(int(r))
+ if len(uniq) > 8:
+ list(_POOL.map(one, enumerate(uniq)))
+ else:
+ for a in enumerate(uniq):
+ one(a)
+ u = buf.to(dev, non_blocking=True)
+ t4, t8 = _tabs(dev)
+ w = table.width
+ if table.layout == "plain":
+ rows = t4[u.long()]
+ else: # width e4m3 values, then width/32 e8m0 scales (same as F8Rows.decode_raw)
+ rows = (t4[u[:, :w].long()].reshape(len(uniq), -1, QB) * t8[u[:, w:].long()][:, :, None]).reshape(len(uniq), w)
+ sel = torch.from_numpy(inv.astype(np.int64)).to(dev)
+ return rows[sel].reshape(*ids.shape, w)
+
+
+class Hy4EngramGPU:
+ def __init__(self, g, layer: int, dev, table: F8Rows | None = None, lin=None, eps: float = 1.1920929e-07):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ pl = list(m[p + "ple.layers"])
+ self.layer, self.e, self.dev, self.eps = layer, pl.index(layer), torch.device(dev), eps
+ self.n_gram, self.n_head = m[p + "ple.ngram_size"], m[p + "ple.heads_per_ngram"]
+ self.n_cols = (self.n_gram - 1) * self.n_head
+ e, nc, ng = self.e, self.n_cols, self.n_gram
+ self.mult = list(m[p + "ple.layer_multipliers"])[e * ng:(e + 1) * ng]
+ self.primes = list(m[p + "ple.head_vocab_sizes"])[e * nc:(e + 1) * nc]
+ self.offs = list(m[p + "ple.head_offsets"])[e * nc:(e + 1) * nc]
+ self.token_map, self.pad_id = m[p + "engram.token_map"], m[p + "engram.pad_token_id"]
+ self.head_dim = m[p + "embedding_length_per_layer_input"]
+ self.n_embd, self.hc = m[p + "embedding_length"], m[p + "hyper_connection.count"]
+ b = f"blk.{layer}."
+ f = lambda n: load_dense(g, b + n).to(self.dev)
+ kv = lin(b + "engram_kv.weight") if lin is not None else load_dense(g, b + "engram_kv.weight")
+ self.kv = kv if not torch.is_tensor(kv) else kv.to(self.dev)
+ self.kv_b, self.lookup_norm, self.gate = f("engram_kv_b.weight"), f("engram_lookup_norm.weight"), f("engram_gate.weight")
+ self.hc_scale, self.pre_gamma = f("engram_hc_scale.weight"), f("engram_pre_gamma.weight")
+ self.table = table if table is not None else F8Rows(g)
+ assert self.table.width == self.head_dim
+
+ row_ids = Hy4Engram.row_ids
+
+ def _kv(self, r):
+ return self.kv(r) if callable(self.kv) else r @ self.kv.T
+
+ def apply(self, x, rows, valid):
+ T, eps = x.shape[0], self.eps
+ r = rms(rows, eps) * self.lookup_norm * valid[:, :, None]
+ r = r.reshape(T, -1)
+ kv = self._kv(r).reshape(T, self.hc + 1, self.n_embd) + self.kv_b
+ key, value = kv[:, :self.hc], kv[:, self.hc]
+ dot = (rms(x, eps) * rms(key, eps) * self.gate).sum(-1) / self.n_embd ** 0.5
+ mag = dot.abs().clamp_min(1e-6).sqrt()
+ sign = 1.0 - 2.0 * (-dot > 0).float()
+ gate = torch.sigmoid(mag * sign)
+ signal = rms(value, eps) * self.pre_gamma
+ delta = signal[:, None, :] * (gate[:, :, None] + self.hc_scale)
+ anyv = (valid.sum(-1) > 0).float()
+ return x + delta * anyv[:, None, None]
+
+ def __call__(self, x: torch.Tensor, tokens, start: int = 0) -> torch.Tensor:
+ ids, valid = self.row_ids(tokens, start, x.shape[0])
+ rows = fetch_rows(self.table, ids, self.dev)
+ return self.apply(x, rows, valid.to(self.dev, non_blocking=True))
diff --git a/exllamav3/loader/gguf_blocks/mlp.py.pre_preclamp b/exllamav3/loader/gguf_blocks/mlp.py.pre_preclamp
new file mode 100644
index 0000000..6b1a799
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/mlp.py.pre_preclamp
@@ -0,0 +1,227 @@
+"""Blocks around modules/mlp.py and block_sparse_mlp.py: dense gated MLP, standard top-k MoE (+shared, +biases),
+and the predicates of the latent MoE / sigmoid-bias router (not built yet)."""
+from __future__ import annotations
+from ..gguf_registry import Block, register, req
+
+_EXPS = ("ffn_gate_exps", "ffn_up_exps", "ffn_down_exps")
+_MOE_CLAIMS = frozenset({"ffn_gate_inp.weight", "ffn_gate_inp.bias", *(f"{e}.weight" for e in _EXPS), *(f"{e}.bias" for e in _EXPS),
+ "ffn_gate_shexp.weight", "ffn_up_shexp.weight", "ffn_down_shexp.weight", "ffn_gate_inp_shexp.weight"})
+
+
+def moe_layers(ctx):
+ return ctx.once("moe_layers", lambda c: [i for i in range(c.nl) if c.has(i, "ffn_gate_exps.weight")])
+
+
+def moe_global(ctx):
+ """standard MoE config (first MoE layer's shapes); empty when the header has no routed experts"""
+ def f(ctx):
+ m, infos, p, arch, gaps, ml = ctx.meta, ctx.infos, ctx.p, ctx.arch, ctx.gaps, moe_layers(ctx)
+ if not ml:
+ return {}
+ gd = infos[f"blk.{ml[0]}.ffn_gate_exps.weight"][1] # gguf dims (H, I, E)
+ cfg = {"num_experts": gd[2], "moe_intermediate_size": gd[1], "num_experts_per_tok": req(m, p + "expert_used_count")}
+ if m.get(p + "expert_count", gd[2]) != gd[2]:
+ gaps.append("expert_count metadata disagrees with ffn_gate_exps shape")
+ sh = [i for i in ml if ctx.has(i, "ffn_gate_shexp.weight")]
+ if sh and len(sh) != len(ml):
+ gaps.append("shared experts present on only some MoE layers")
+ elif sh:
+ cfg["shared_intermediate_size"] = infos[f"blk.{sh[0]}.ffn_gate_shexp.weight"][1][1]
+ cfg["shared_gate"] = ctx.has(sh[0], "ffn_gate_inp_shexp.weight")
+ elif m.get(p + "expert_shared_count", 0):
+ gaps.append("expert_shared_count > 0 but no ffn_*_shexp tensors")
+ for sfx, nmk in (("ffn_gate_inp.bias", "router_bias"), ("ffn_gate_exps.bias", "expert_bias_gate"),
+ ("ffn_up_exps.bias", "expert_bias_up"), ("ffn_down_exps.bias", "expert_bias_down")):
+ have = [i for i in ml if ctx.has(i, sfx)]
+ if have and len(have) != len(ml):
+ gaps.append(f"{sfx} present on only some MoE layers")
+ cfg[nmk] = bool(have) and len(have) == len(ml)
+ if cfg["router_bias"]:
+ bd = infos[f"blk.{ml[0]}.ffn_gate_inp.bias"][1]
+ if tuple(bd) != (gd[2],):
+ gaps.append(f"ffn_gate_inp.bias dims {tuple(bd)} != (num_experts,)")
+ for pj, nmk, shp in (("gate", "expert_bias_gate", (gd[1], gd[2])), ("up", "expert_bias_up", (gd[1], gd[2])),
+ ("down", "expert_bias_down", (gd[0], gd[2]))):
+ if cfg[nmk] and tuple(infos[f"blk.{ml[0]}.ffn_{pj}_exps.bias"][1]) != shp:
+ gaps.append(f"ffn_{pj}_exps.bias dims {tuple(infos[f'blk.{ml[0]}.ffn_{pj}_exps.bias'][1])} != {shp}")
+ act, lim = ctx.feats.get("moe_act", ("silu", 0.0))
+ cfg["moe_activation"], cfg["moe_act_limit"] = act, float(m.get(p + "swiglu_limit", lim))
+ norm = m.get(p + "expert_weights_norm", ctx.feats.get("norm_topk"))
+ if norm is None:
+ gaps.append(f"unknown expert_weights_norm for arch {arch!r}")
+ if m.get(p + "expert_gating_func", 1) not in (0, 1):
+ gaps.append("router gating func is not softmax")
+ cfg["norm_topk_prob"] = bool(norm)
+ return cfg
+ return ctx.once("moe", f)
+
+
+def _dense_names(cfg, i, L, G):
+ return {f"{L}.mlp.gate_proj.weight": f"{G}.ffn_gate.weight", f"{L}.mlp.up_proj.weight": f"{G}.ffn_up.weight",
+ f"{L}.mlp.down_proj.weight": f"{G}.ffn_down.weight"}
+
+
+def _dense_build(config, plan, idx, L):
+ import torch
+ from ...modules import GatedMLP
+ from ...architecture.gguf_generic import _fl
+ H, I = config.hidden_size, config.intermediate_size
+ mlp = GatedMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, qmap="block.mlp", activation_fn=config.hidden_act,
+ interm_dtype=torch.half, out_dtype=torch.float,
+ gates=[_fl(config, f"{L}.mlp.gate_proj", H, I)], ups=[_fl(config, f"{L}.mlp.up_proj", H, I)],
+ downs=[_fl(config, f"{L}.mlp.down_proj", I, H, out_dtype=torch.float)])
+ for m in mlp.gates + mlp.ups + mlp.downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+register(Block(
+ "dense_ffn", "ffn",
+ select=lambda ctx, i: not ctx.has(i, "ffn_gate_exps.weight"),
+ config=lambda ctx, i: {"intermediate_size": ctx.key("feed_forward_length", 0), "act": ctx.feats.get("act", "silu")},
+ claims=frozenset({"ffn_gate.weight", "ffn_up.weight", "ffn_down.weight"}), build=_dense_build, names=_dense_names))
+
+
+def _moe_names(cfg, i, L, G):
+ nm = {f"{L}.mlp.gate.weight": f"{G}.ffn_gate_inp.weight"}
+ if cfg.get("router_bias"):
+ nm[f"{L}.mlp.gate.bias"] = f"{G}.ffn_gate_inp.bias"
+ if cfg.get("shared_intermediate_size"):
+ for proj in ("gate", "up", "down"):
+ nm[f"{L}.mlp.shared_experts.{proj}_proj.weight"] = f"{G}.ffn_{proj}_shexp.weight"
+ if cfg.get("shared_gate"):
+ nm[f"{L}.mlp.shared_expert_gate.weight"] = f"{G}.ffn_gate_inp_shexp.weight"
+ for e in range(cfg["num_experts"]):
+ for proj, gp in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):
+ nm[f"{L}.mlp.experts.{e}.{proj}.weight"] = f"{G}.{gp}.e{e}.weight"
+ if cfg.get("expert_bias_" + proj[:-5]):
+ nm[f"{L}.mlp.experts.{e}.{proj}.bias"] = f"{G}.{gp}.e{e}.bias"
+ return nm
+
+
+def _moe_build(config, plan, idx, L):
+ import torch
+ from ...modules import GatedMLP, BlockSparseMLP
+ from ...architecture.gguf_generic import _fl
+ H, I, E = config.hidden_size, config.moe_intermediate_size, config.num_experts
+ eb = config.expert_bias
+ gates = [_fl(config, f"{L}.mlp.experts.{e}.gate_proj", H, I, bias=eb["gate"]) for e in range(E)]
+ ups = [_fl(config, f"{L}.mlp.experts.{e}.up_proj", H, I, bias=eb["up"]) for e in range(E)]
+ downs = [_fl(config, f"{L}.mlp.experts.{e}.down_proj", I, H, out_dtype=torch.float, bias=eb["down"]) for e in range(E)]
+ moe_kw = {}
+ if config.router_bias: # logit bias before top-k, softmax over the picked biased logits (engine gpt-oss: routing_std_bias)
+ moe_kw.update(router_type="std_bias", key_e_score_bias=None)
+ if config.moe_activation != "silu":
+ moe_kw.update(activation_fn=config.moe_activation, act_limit=config.moe_act_limit)
+ shared = None
+ if config.shared_intermediate:
+ SI, SK = config.shared_intermediate, f"{L}.mlp.shared_experts"
+ shared = GatedMLP(config=config, key=SK, hidden_size=H, intermediate_size=SI, qmap="block.mlp",
+ interm_dtype=torch.half, out_dtype=torch.float,
+ gates=[_fl(config, f"{SK}.gate_proj", H, SI)], ups=[_fl(config, f"{SK}.up_proj", H, SI)],
+ downs=[_fl(config, f"{SK}.down_proj", SI, H, out_dtype=torch.float)])
+ for m in shared.gates + shared.ups + shared.downs:
+ shared.register_submodule(m)
+ mlp = BlockSparseMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, num_experts=E,
+ shared_experts=shared, key_shared_gate="shared_expert_gate" if config.shared_gate else None,
+ num_experts_per_tok=config.num_experts_per_tok, norm_topk=bool(config.norm_topk_prob), key_up=None, key_gate=None,
+ key_down=None, key_routing_gate="gate", qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ gates=gates, ups=ups, downs=downs, **moe_kw)
+ for m in gates + ups + downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+def _moe_layer(ctx, i):
+ g = moe_global(ctx)
+ keys = ("num_experts", "moe_intermediate_size", "num_experts_per_tok", "shared_intermediate_size", "shared_gate", "router_bias",
+ "expert_bias_gate", "expert_bias_up", "expert_bias_down", "moe_activation", "moe_act_limit", "norm_topk_prob")
+ return {k: g.get(k) for k in keys}
+
+
+register(Block(
+ "moe_ffn", "ffn",
+ select=lambda ctx, i: ctx.has(i, "ffn_gate_exps.weight") and not ctx.has(i, "ffn_routed_down.weight"),
+ config=_moe_layer, claims=_MOE_CLAIMS, build=_moe_build, names=_moe_names))
+
+
+# ---- latent MoE (Hy4-flash, llama.cpp build_latent_moe M:5949): router on the full-width input (sigmoid + exp_probs_b for the pick,
+# unbiased weights, renormalised, x weights_scale), routed experts at expert_latent_length between ffn_routed_down / _up,
+# pre-activation swiglu clamp on the routed experts only, one full-width shared expert added after ffn_routed_up.
+# The post_ffw_norm that follows is the stream block's (hyperconnections._stream_build), not this block's.
+# engine module: block_sparse_mlp latent_in / latent_out + router_type "ds3" with one group
+def _latent_layer(ctx, i):
+ gd = ctx.dims(f"blk.{i}.ffn_gate_exps.weight")
+ sh = ctx.dims(f"blk.{i}.ffn_gate_shexp.weight")
+ rd = ctx.dims(f"blk.{i}.ffn_routed_down.weight")
+ clamp = ctx.per_layer("swiglu_clamp_exp", 0.0)
+ lat = ctx.key("expert_latent_length")
+ if ctx.key("expert_gating_func") != 2:
+ ctx.gaps.append("latent MoE: expert_gating_func is not sigmoid (2)")
+ if gd and rd and not (gd[0] == lat == rd[1]):
+ ctx.gaps.append(f"latent MoE layer {i}: expert_latent_length {lat} disagrees with ffn_gate_exps {gd} / ffn_routed_down {rd}")
+ if not ctx.has(i, "exp_probs_b.bias") or not ctx.has(i, "ffn_routed_up.weight"):
+ ctx.gaps.append(f"latent MoE layer {i}: exp_probs_b.bias / ffn_routed_up.weight missing")
+ return {"latent": lat, "latent_down": rd, "expert_dims": gd, "num_experts": gd[2] if gd else None, "top_k": ctx.key("expert_used_count"),
+ "gating_func": ctx.key("expert_gating_func"), "weights_scale": ctx.key("expert_weights_scale"),
+ "weights_norm": ctx.key("expert_weights_norm"), "e_score_bias": ctx.has(i, "exp_probs_b.bias"),
+ "clamp": clamp[i] if i < len(clamp) else None, "clamp_routed_only": bool(ctx.feats.get("clamp_routed_only")),
+ "shared_dims": sh}
+
+
+def _latent_names(cfg, i, L, G):
+ nm = {f"{L}.mlp.gate.weight": f"{G}.ffn_gate_inp.weight", f"{L}.mlp.gate.e_score_correction_bias": f"{G}.exp_probs_b.bias",
+ f"{L}.mlp.fc1_latent_proj.weight": f"{G}.ffn_routed_down.weight", f"{L}.mlp.fc2_latent_proj.weight": f"{G}.ffn_routed_up.weight"}
+ for proj in ("gate", "up", "down"):
+ nm[f"{L}.mlp.shared_experts.{proj}_proj.weight"] = f"{G}.ffn_{proj}_shexp.weight"
+ for e in range(cfg["num_experts"]):
+ for proj, gp in (("gate_proj", "ffn_gate_exps"), ("up_proj", "ffn_up_exps"), ("down_proj", "ffn_down_exps")):
+ nm[f"{L}.mlp.experts.{e}.{proj}.weight"] = f"{G}.{gp}.e{e}.weight"
+ return nm
+
+
+def _latent_build(config, plan, idx, L):
+ import torch
+ from ...modules import GatedMLP, BlockSparseMLP
+ from ...architecture.gguf_generic import _fl
+ c = plan.configs[("latent_moe", idx)]
+ H, LAT, I, E = config.hidden_size, c["latent"], c["expert_dims"][1], c["num_experts"]
+ SI, SK = c["shared_dims"][1], f"{L}.mlp.shared_experts"
+ gates = [_fl(config, f"{L}.mlp.experts.{e}.gate_proj", LAT, I) for e in range(E)]
+ ups = [_fl(config, f"{L}.mlp.experts.{e}.up_proj", LAT, I) for e in range(E)]
+ downs = [_fl(config, f"{L}.mlp.experts.{e}.down_proj", I, LAT, out_dtype=torch.float) for e in range(E)]
+ shared = GatedMLP(config=config, key=SK, hidden_size=H, intermediate_size=SI, qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ gates=[_fl(config, f"{SK}.gate_proj", H, SI)], ups=[_fl(config, f"{SK}.up_proj", H, SI)],
+ downs=[_fl(config, f"{SK}.down_proj", SI, H, out_dtype=torch.float)])
+ for m in shared.gates + shared.ups + shared.downs:
+ shared.register_submodule(m)
+ kw = {}
+ if c["clamp"]:
+ # the tree's clamp is post-activation; Hy4's is pre-activation (min(gate, c) then silu): they differ only for gate > c (<= 4.6e-4 at c = 10)
+ kw["act_limit"] = float(c["clamp"])
+ mlp = BlockSparseMLP(config=config, key=f"{L}.mlp", hidden_size=H, intermediate_size=I, num_experts=E, shared_experts=shared,
+ num_experts_per_tok=c["top_k"], norm_topk=bool(c["weights_norm"]), key_up=None, key_gate=None, key_down=None,
+ key_routing_gate="gate", qmap="block.mlp", interm_dtype=torch.half, out_dtype=torch.float,
+ gates=gates, ups=ups, downs=downs, latent_size=LAT,
+ key_latent_in="fc1_latent_proj", key_latent_out="fc2_latent_proj",
+ latent_in=_fl(config, f"{L}.mlp.fc1_latent_proj", H, LAT),
+ latent_out=_fl(config, f"{L}.mlp.fc2_latent_proj", LAT, H, out_dtype=torch.float),
+ router_type="ds3", n_group=1, topk_group=1, routed_scaling_factor=float(c["weights_scale"]), **kw)
+ for m in gates + ups + downs:
+ mlp.register_submodule(m)
+ return mlp
+
+
+register(Block(
+ "latent_moe", "ffn", step="step 5",
+ select=lambda ctx, i: ctx.has(i, "ffn_routed_down.weight") and ctx.has(i, "ffn_gate_exps.weight"),
+ config=_latent_layer, claims=_MOE_CLAIMS | {"ffn_routed_down.weight", "ffn_routed_up.weight", "exp_probs_b.bias"},
+ build=_latent_build, names=_latent_names))
+
+# sigmoid / sqrt-softplus router with a per-expert score bias on a plain MoE layer (glm5-next, deepseek41); predicate only
+register(Block(
+ "router_score_bias", "ffn_mod", step="step 5",
+ select=lambda ctx, i: ctx.has(i, "exp_probs_b.bias") and not ctx.has(i, "ffn_routed_down.weight"),
+ config=lambda ctx, i: {"gating_func": ctx.key("expert_gating_func"), "weights_scale": ctx.key("expert_weights_scale"),
+ "vl_bias": ctx.has(i, "exp_probs_b_vl.bias")},
+ claims=frozenset({"exp_probs_b.bias", "exp_probs_b_vl.bias"}), build=None))
diff --git a/exllamav3/loader/hc_fused.py b/exllamav3/loader/hc_fused.py
new file mode 100644
index 0000000..5982a86
--- /dev/null
+++ b/exllamav3/loader/hc_fused.py
@@ -0,0 +1,168 @@
+"""Fused hyper-connection sites + norms (Triton). Flag HY4_HC_FUSED=1 (default off; hy4_forward only calls in here when ENABLED).
+
+Generic by SHAPE: n_streams H (any), hidden D, fn [NO, H*D] fp32 with NO = 2H (pre+post, "site") or H (pre only, "head"); no model name.
+The math is exactly the current torch path of hy4_forward.py (_site / layer / _head), fp32:
+ mix = rms(x.flat, eps) @ fn.T
+ pre = sigmoid(mix[:H] * scale[0] + base[:H]) + hc_eps
+ post = magnitude * sigmoid(mix[H:] * scale[1] + base[H:]) + hc_eps
+ cur = rms((x * pre[:, None]).sum(streams), eps) * w
+Launches per layer: site A = 2, residual+site B = 2, residual C = 1 (old path: ~80-100 torch launches).
+ K1 hc_mix_partials : per (row, chunk) of the H*D row: [optional s = x + post_prev * y written out], sumsq, NO dot partials with fn
+ K2 hc_mix_collapse : per row: reduce partials -> pre/post (store post), collapse streams by pre, rms, * norm weight -> cur
+ K3 hc_resid : per row: f = rms(f) * w ; s = s + post * f (all streams)
+"""
+import os
+
+import torch
+import triton
+import triton.language as tl
+
+ENABLED = os.environ.get("HY4_HC_FUSED", "0") == "1"
+BK = int(os.environ.get("HY4_HC_BK", "512")) # K1 chunk (elements of the flattened H*D row)
+MAX_D = 16384 # K2/K3 keep one row of D in registers
+
+
+def _p2(n):
+ return 1 << max(0, (int(n) - 1).bit_length())
+
+
+def _k1_partials(x_ptr, y_ptr, post_ptr, s_ptr, fn_ptr, part_ptr, sq_ptr,
+ K, D, NO, NCH,
+ HAS_RES: tl.constexpr, NOP: tl.constexpr, BK: tl.constexpr):
+ r = tl.program_id(0)
+ c = tl.program_id(1)
+ k = c * BK + tl.arange(0, BK)
+ km = k < K
+ xv = tl.load(x_ptr + r * K + k, mask=km, other=0.0)
+ if HAS_RES:
+ h = k // D
+ d = k - h * D
+ yv = tl.load(y_ptr + r * D + d, mask=km, other=0.0)
+ pv = tl.load(post_ptr + r * (K // D) + h, mask=km, other=0.0)
+ xv = xv + pv * yv
+ tl.store(s_ptr + r * K + k, xv, mask=km)
+ o = tl.arange(0, NOP)
+ fm = (o[:, None] < NO) & km[None, :]
+ fv = tl.load(fn_ptr + o[:, None] * K + k[None, :], mask=fm, other=0.0)
+ acc = tl.sum(fv * xv[None, :], axis=1)
+ tl.store(part_ptr + (r * NCH + c) * NOP + o, acc, mask=o < NO)
+ tl.store(sq_ptr + r * NCH + c, tl.sum(xv * xv, axis=0))
+
+
+def _k2_collapse(x_ptr, part_ptr, sq_ptr, base_ptr, scale_ptr, w_ptr, post_ptr, cur_ptr,
+ D, K, NCH, eps, hc_eps, mag,
+ H: tl.constexpr, HP: tl.constexpr, NOP: tl.constexpr, NCHP: tl.constexpr,
+ HAS_POST: tl.constexpr, BD: tl.constexpr):
+ r = tl.program_id(0)
+ ch = tl.arange(0, NCHP)
+ hv = tl.arange(0, HP)
+ cm = ch < NCH
+ ss = tl.sum(tl.load(sq_ptr + r * NCH + ch, mask=cm, other=0.0), axis=0)
+ rr = tl.math.rsqrt(ss / K + eps)
+ pm = tl.sum(tl.load(part_ptr + (r * NCH + ch[:, None]) * NOP + hv[None, :],
+ mask=cm[:, None] & (hv[None, :] < H), other=0.0), axis=0) # [HP] mix[:H]
+ s0 = tl.load(scale_ptr)
+ pre = tl.sigmoid(pm * rr * s0 + tl.load(base_ptr + hv, mask=hv < H, other=0.0)) + hc_eps
+ if HAS_POST:
+ qm = tl.sum(tl.load(part_ptr + (r * NCH + ch[:, None]) * NOP + H + hv[None, :],
+ mask=cm[:, None] & (hv[None, :] < H), other=0.0), axis=0) # [HP] mix[H:]
+ s1 = tl.load(scale_ptr + 1)
+ post = mag * tl.sigmoid(qm * rr * s1 + tl.load(base_ptr + H + hv, mask=hv < H, other=0.0)) + hc_eps
+ tl.store(post_ptr + r * H + hv, post, mask=hv < H)
+ d = tl.arange(0, BD)
+ dm = d < D
+ col = tl.zeros([BD], dtype=tl.float32)
+ for h in tl.static_range(H):
+ ph = tl.sum(tl.where(hv == h, pre, 0.0), axis=0)
+ xh = tl.load(x_ptr + r * K + h * D + d, mask=dm, other=0.0)
+ col = col + xh * ph
+ rc = tl.math.rsqrt(tl.sum(col * col, axis=0) / D + eps)
+ w = tl.load(w_ptr + d, mask=dm, other=0.0)
+ tl.store(cur_ptr + r * D + d, col * rc * w, mask=dm)
+
+
+def _k3_resid(s_ptr, f_ptr, post_ptr, w_ptr, o_ptr, D, eps,
+ H: tl.constexpr, BD: tl.constexpr):
+ r = tl.program_id(0)
+ d = tl.arange(0, BD)
+ dm = d < D
+ f = tl.load(f_ptr + r * D + d, mask=dm, other=0.0)
+ rc = tl.math.rsqrt(tl.sum(f * f, axis=0) / D + eps)
+ fn = f * rc * tl.load(w_ptr + d, mask=dm, other=0.0)
+ for h in tl.static_range(H):
+ ph = tl.load(post_ptr + r * H + h)
+ sv = tl.load(s_ptr + (r * H + h) * D + d, mask=dm, other=0.0)
+ tl.store(o_ptr + (r * H + h) * D + d, sv + ph * fn, mask=dm)
+
+
+def _k4_rmsw(x_ptr, w_ptr, o_ptr, D, eps, BD: tl.constexpr):
+ r = tl.program_id(0)
+ d = tl.arange(0, BD)
+ dm = d < D
+ x = tl.load(x_ptr + r * D + d, mask=dm, other=0.0)
+ rc = tl.math.rsqrt(tl.sum(x * x, axis=0) / D + eps)
+ tl.store(o_ptr + r * D + d, x * rc * tl.load(w_ptr + d, mask=dm, other=0.0), mask=dm)
+
+
+def ok(x, hw, H):
+ """the fused kernels apply: fp32 contiguous streams [T, H, D], fn [NO, H*D] fp32 with NO in (H, 2H), D within the register budget"""
+ if not ENABLED or x.dim() != 3 or x.dtype != torch.float32 or not x.is_contiguous() or x.shape[1] != H:
+ return False
+ fn = hw[0]
+ if not (fn.is_contiguous() and hw[1].is_contiguous() and hw[2].is_contiguous() and hw[1].dtype == torch.float32 and hw[2].dtype == torch.float32):
+ return False
+ return fn.dtype == torch.float32 and fn.shape[1] == H * x.shape[2] and fn.shape[0] in (H, 2 * H) and x.shape[2] <= MAX_D
+
+
+def _mix(x, y, post_prev, hw, w, eps, hc_eps, mag):
+ T, H, D = x.shape
+ fn, base, scale = hw
+ NO = fn.shape[0]
+ K = H * D
+ NOP = _p2(NO)
+ NCH = triton.cdiv(K, BK)
+ dev = x.device
+ part = torch.empty(T, NCH, NOP, dtype=torch.float32, device=dev)
+ sq = torch.empty(T, NCH, dtype=torch.float32, device=dev)
+ has_res = y is not None
+ s = torch.empty_like(x) if has_res else x
+ _k1_partials[(T, NCH)](x, y if has_res else x, post_prev if has_res else x, s, fn, part, sq, K, D, NO, NCH,
+ HAS_RES=has_res, NOP=NOP, BK=BK)
+ has_post = NO == 2 * H
+ post = torch.empty(T, H, dtype=torch.float32, device=dev) if has_post else None
+ cur = torch.empty(T, D, dtype=torch.float32, device=dev)
+ _k2_collapse[(T,)](s, part, sq, base, scale, w, post if has_post else cur, cur, D, K, NCH,
+ eps, hc_eps, mag, H=H, HP=_p2(H), NOP=NOP, NCHP=_p2(NCH),
+ HAS_POST=has_post, BD=_p2(D), num_warps=8)
+ return s, post, cur
+
+
+def site(x, hw, w_norm, eps, hc_eps, mag):
+ """site A / head: x [T,H,D] -> (post [T,H] or None for a pre-only head fn, cur [T,D] = rms(sum_h pre_h x_h) * w_norm)"""
+ _, post, cur = _mix(x, None, None, hw, w_norm.contiguous(), eps, hc_eps, mag)
+ return post, cur
+
+
+def res_site(x, y, post_prev, hw, w_norm, eps, hc_eps, mag):
+ """s = x + post_prev[:, :, None] * y[:, None, :]; then the site on s -> (s, post, cur)"""
+ return _mix(x, y.float().contiguous(), post_prev.float().contiguous(), hw, w_norm.contiguous(), eps, hc_eps, mag)
+
+
+def resid(s, f, post, w_post, eps):
+ """s + post[:, :, None] * (rms(f) * w_post)[:, None, :] -> new [T,H,D]"""
+ T, H, D = s.shape
+ o = torch.empty_like(s)
+ _k3_resid[(T,)](s, f.float().contiguous(), post.float().contiguous(), w_post.contiguous(), o, D, eps, H=H, BD=_p2(D), num_warps=8)
+ return o
+
+
+def rmsw(x, w, eps):
+ """rms(x, eps) * w over the last dim, fp32 [R, D] (one launch instead of 5)"""
+ x = x.float().contiguous()
+ o = torch.empty_like(x)
+ _k4_rmsw[(x.shape[0],)](x, w.contiguous(), o, x.shape[1], eps, BD=_p2(x.shape[1]), num_warps=8)
+ return o
diff --git a/exllamav3/loader/hc_fused.py.pre_c2 b/exllamav3/loader/hc_fused.py.pre_c2
new file mode 100644
index 0000000..53ef504
--- /dev/null
+++ b/exllamav3/loader/hc_fused.py.pre_c2
@@ -0,0 +1,166 @@
+"""Fused hyper-connection sites + norms (Triton). Flag HY4_HC_FUSED=1 (default off; hy4_forward only calls in here when ENABLED).
+
+Generic by SHAPE: n_streams H (any), hidden D, fn [NO, H*D] fp32 with NO = 2H (pre+post, "site") or H (pre only, "head"); no model name.
+The math is exactly the current torch path of hy4_forward.py (_site / layer / _head), fp32:
+ mix = rms(x.flat, eps) @ fn.T
+ pre = sigmoid(mix[:H] * scale[0] + base[:H]) + hc_eps
+ post = magnitude * sigmoid(mix[H:] * scale[1] + base[H:]) + hc_eps
+ cur = rms((x * pre[:, None]).sum(streams), eps) * w
+Launches per layer: site A = 2, residual+site B = 2, residual C = 1 (old path: ~80-100 torch launches).
+ K1 hc_mix_partials : per (row, chunk) of the H*D row: [optional s = x + post_prev * y written out], sumsq, NO dot partials with fn
+ K2 hc_mix_collapse : per row: reduce partials -> pre/post (store post), collapse streams by pre, rms, * norm weight -> cur
+ K3 hc_resid : per row: f = rms(f) * w ; s = s + post * f (all streams)
+"""
+import os
+
+import torch
+import triton
+import triton.language as tl
+
+ENABLED = os.environ.get("HY4_HC_FUSED", "0") == "1"
+BK = int(os.environ.get("HY4_HC_BK", "512")) # K1 chunk (elements of the flattened H*D row)
+MAX_D = 16384 # K2/K3 keep one row of D in registers
+
+
+def _p2(n):
+ return 1 << max(0, (int(n) - 1).bit_length())
+
+
+def _k1_partials(x_ptr, y_ptr, post_ptr, s_ptr, fn_ptr, part_ptr, sq_ptr,
+ K, D, NO, NCH,
+ HAS_RES: tl.constexpr, NOP: tl.constexpr, BK: tl.constexpr):
+ r = tl.program_id(0)
+ c = tl.program_id(1)
+ k = c * BK + tl.arange(0, BK)
+ km = k < K
+ xv = tl.load(x_ptr + r * K + k, mask=km, other=0.0)
+ if HAS_RES:
+ h = k // D
+ d = k - h * D
+ yv = tl.load(y_ptr + r * D + d, mask=km, other=0.0)
+ pv = tl.load(post_ptr + r * (K // D) + h, mask=km, other=0.0)
+ xv = xv + pv * yv
+ tl.store(s_ptr + r * K + k, xv, mask=km)
+ o = tl.arange(0, NOP)
+ fm = (o[:, None] < NO) & km[None, :]
+ fv = tl.load(fn_ptr + o[:, None] * K + k[None, :], mask=fm, other=0.0)
+ acc = tl.sum(fv * xv[None, :], axis=1)
+ tl.store(part_ptr + (r * NCH + c) * NOP + o, acc, mask=o < NO)
+ tl.store(sq_ptr + r * NCH + c, tl.sum(xv * xv, axis=0))
+
+
+def _k2_collapse(x_ptr, part_ptr, sq_ptr, base_ptr, scale_ptr, w_ptr, post_ptr, cur_ptr,
+ D, K, NCH, eps, hc_eps, mag,
+ H: tl.constexpr, HP: tl.constexpr, NOP: tl.constexpr, NCHP: tl.constexpr,
+ HAS_POST: tl.constexpr, BD: tl.constexpr):
+ r = tl.program_id(0)
+ ch = tl.arange(0, NCHP)
+ hv = tl.arange(0, HP)
+ cm = ch < NCH
+ ss = tl.sum(tl.load(sq_ptr + r * NCH + ch, mask=cm, other=0.0), axis=0)
+ rr = tl.math.rsqrt(ss / K + eps)
+ pm = tl.sum(tl.load(part_ptr + (r * NCH + ch[:, None]) * NOP + hv[None, :],
+ mask=cm[:, None] & (hv[None, :] < H), other=0.0), axis=0) # [HP] mix[:H]
+ s0 = tl.load(scale_ptr)
+ pre = tl.sigmoid(pm * rr * s0 + tl.load(base_ptr + hv, mask=hv < H, other=0.0)) + hc_eps
+ if HAS_POST:
+ qm = tl.sum(tl.load(part_ptr + (r * NCH + ch[:, None]) * NOP + H + hv[None, :],
+ mask=cm[:, None] & (hv[None, :] < H), other=0.0), axis=0) # [HP] mix[H:]
+ s1 = tl.load(scale_ptr + 1)
+ post = mag * tl.sigmoid(qm * rr * s1 + tl.load(base_ptr + H + hv, mask=hv < H, other=0.0)) + hc_eps
+ tl.store(post_ptr + r * H + hv, post, mask=hv < H)
+ d = tl.arange(0, BD)
+ dm = d < D
+ col = tl.zeros([BD], dtype=tl.float32)
+ for h in tl.static_range(H):
+ ph = tl.sum(tl.where(hv == h, pre, 0.0), axis=0)
+ xh = tl.load(x_ptr + r * K + h * D + d, mask=dm, other=0.0)
+ col = col + xh * ph
+ rc = tl.math.rsqrt(tl.sum(col * col, axis=0) / D + eps)
+ w = tl.load(w_ptr + d, mask=dm, other=0.0)
+ tl.store(cur_ptr + r * D + d, col * rc * w, mask=dm)
+
+
+def _k3_resid(s_ptr, f_ptr, post_ptr, w_ptr, o_ptr, D, eps,
+ H: tl.constexpr, BD: tl.constexpr):
+ r = tl.program_id(0)
+ d = tl.arange(0, BD)
+ dm = d < D
+ f = tl.load(f_ptr + r * D + d, mask=dm, other=0.0)
+ rc = tl.math.rsqrt(tl.sum(f * f, axis=0) / D + eps)
+ fn = f * rc * tl.load(w_ptr + d, mask=dm, other=0.0)
+ for h in tl.static_range(H):
+ ph = tl.load(post_ptr + r * H + h)
+ sv = tl.load(s_ptr + (r * H + h) * D + d, mask=dm, other=0.0)
+ tl.store(o_ptr + (r * H + h) * D + d, sv + ph * fn, mask=dm)
+
+
+def _k4_rmsw(x_ptr, w_ptr, o_ptr, D, eps, BD: tl.constexpr):
+ r = tl.program_id(0)
+ d = tl.arange(0, BD)
+ dm = d < D
+ x = tl.load(x_ptr + r * D + d, mask=dm, other=0.0)
+ rc = tl.math.rsqrt(tl.sum(x * x, axis=0) / D + eps)
+ tl.store(o_ptr + r * D + d, x * rc * tl.load(w_ptr + d, mask=dm, other=0.0), mask=dm)
+
+
+def ok(x, hw, H):
+ """the fused kernels apply: fp32 contiguous streams [T, H, D], fn [NO, H*D] fp32 with NO in (H, 2H), D within the register budget"""
+ if not ENABLED or x.dim() != 3 or x.dtype != torch.float32 or not x.is_contiguous() or x.shape[1] != H:
+ return False
+ fn = hw[0]
+ return fn.dtype == torch.float32 and fn.shape[1] == H * x.shape[2] and fn.shape[0] in (H, 2 * H) and x.shape[2] <= MAX_D
+
+
+def _mix(x, y, post_prev, hw, w, eps, hc_eps, mag):
+ T, H, D = x.shape
+ fn, base, scale = hw
+ NO = fn.shape[0]
+ K = H * D
+ NOP = _p2(NO)
+ NCH = triton.cdiv(K, BK)
+ dev = x.device
+ part = torch.empty(T, NCH, NOP, dtype=torch.float32, device=dev)
+ sq = torch.empty(T, NCH, dtype=torch.float32, device=dev)
+ has_res = y is not None
+ s = torch.empty_like(x) if has_res else x
+ _k1_partials[(T, NCH)](x, y if has_res else x, post_prev if has_res else x, s, fn, part, sq, K, D, NO, NCH,
+ HAS_RES=has_res, NOP=NOP, BK=BK)
+ has_post = NO == 2 * H
+ post = torch.empty(T, H, dtype=torch.float32, device=dev) if has_post else None
+ cur = torch.empty(T, D, dtype=torch.float32, device=dev)
+ _k2_collapse[(T,)](s, part, sq, base, scale, w, post if has_post else cur, cur, D, K, NCH,
+ eps, hc_eps, mag, H=H, HP=_p2(H), NOP=NOP, NCHP=_p2(NCH),
+ HAS_POST=has_post, BD=_p2(D), num_warps=8)
+ return s, post, cur
+
+
+def site(x, hw, w_norm, eps, hc_eps, mag):
+ """site A / head: x [T,H,D] -> (post [T,H] or None for a pre-only head fn, cur [T,D] = rms(sum_h pre_h x_h) * w_norm)"""
+ _, post, cur = _mix(x, None, None, hw, w_norm, eps, hc_eps, mag)
+ return post, cur
+
+
+def res_site(x, y, post_prev, hw, w_norm, eps, hc_eps, mag):
+ """s = x + post_prev[:, :, None] * y[:, None, :]; then the site on s -> (s, post, cur)"""
+ return _mix(x, y.float().contiguous(), post_prev, hw, w_norm, eps, hc_eps, mag)
+
+
+def resid(s, f, post, w_post, eps):
+ """s + post[:, :, None] * (rms(f) * w_post)[:, None, :] -> new [T,H,D]"""
+ T, H, D = s.shape
+ o = torch.empty_like(s)
+ _k3_resid[(T,)](s, f.float().contiguous(), post, w_post, o, D, eps, H=H, BD=_p2(D), num_warps=8)
+ return o
+
+
+def rmsw(x, w, eps):
+ """rms(x, eps) * w over the last dim, fp32 [R, D] (one launch instead of 5)"""
+ x = x.float().contiguous()
+ o = torch.empty_like(x)
+ _k4_rmsw[(x.shape[0],)](x, w, o, x.shape[1], eps, BD=_p2(x.shape[1]), num_warps=8)
+ return o
diff --git a/exllamav3/loader/head_bf16.py b/exllamav3/loader/head_bf16.py
new file mode 100644
index 0000000..5b33b43
--- /dev/null
+++ b/exllamav3/loader/head_bf16.py
@@ -0,0 +1,39 @@
+"""HY4_HEAD_BF16=1: output head as ONE Triton mat-vec on the stored bf16 weights (fp32 accumulate, fp32 logits).
+Old path (hy4_forward.head_gemm): per 8192-row chunk `W[a:a+c].float() @ h` = bf16 -> fp32 copy (write 4 B + read 4 B per weight) + GEMV:
+~3.7 GB of traffic per token for a 0.74 GB matrix (18 ms). Here: 0.74 GB read once (~3.5 ms at 210 GB/s). Same products in fp32; only the
+summation order differs (rel ~1e-6). Generic: any [V, D] bf16 / f16 / f32 weight, h [1, D] fp32."""
+import os
+import torch
+import triton
+import triton.language as tl
+
+ENABLED = 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"))
+
+
+def _k_head(w_ptr, h_ptr, o_ptr, V, D, BV: tl.constexpr, BD: tl.constexpr):
+ rows = tl.program_id(0) * BV + tl.arange(0, BV)
+ rm = rows < V
+ acc = tl.zeros([BV], dtype=tl.float32)
+ for d0 in range(0, D, BD):
+ cols = d0 + tl.arange(0, BD)
+ cm = cols < D
+ w = tl.load(w_ptr + rows[:, None] * D + cols[None, :], mask=rm[:, None] & cm[None, :], other=0.0).to(tl.float32)
+ hv = tl.load(h_ptr + cols, mask=cm, other=0.0)
+ acc += tl.sum(w * hv[None, :], axis=1)
+ tl.store(o_ptr + rows, acc, mask=rm)
+
+
+def usable(h, W):
+ return ENABLED and h.shape[0] == 1 and W.dim() == 2 and W.is_contiguous() and h.dtype == torch.float32 and W.dtype in (torch.bfloat16, torch.float16, torch.float32) \
+ and (W.is_cuda or os.environ.get("TRITON_INTERPRET", "0") == "1")
+
+
+def gemv(h, W):
+ """h [1, D] fp32, W [V, D] -> logits [1, V] fp32"""
+ V, D = W.shape
+ out = 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)
+ return out
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
new file mode 100644
index 0000000..7754c9e
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py
@@ -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/hy4_forward.py.pre_ABC b/exllamav3/loader/hy4_forward.py.pre_ABC
new file mode 100755
index 0000000..63c16c7
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_ABC
@@ -0,0 +1,601 @@
+"""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
+
+_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)."""
+ 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:
+ 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.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]
+
+ # -- 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"):
+ 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 = 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 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ 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 = 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 = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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"):
+ 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"):
+ 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]
+ 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].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 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):
+ 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/hy4_forward.py.pre_DFE b/exllamav3/loader/hy4_forward.py.pre_DFE
new file mode 100644
index 0000000..d750c2b
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_DFE
@@ -0,0 +1,627 @@
+"""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
+
+_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)."""
+ 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:
+ 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
+ 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]
+
+ # -- 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"):
+ 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 = 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 i in self.ple:
+ x = 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 = 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
+ 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, 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].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 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):
+ 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/hy4_forward.py.pre_attn b/exllamav3/loader/hy4_forward.py.pre_attn
new file mode 100755
index 0000000..dccf62f
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_attn
@@ -0,0 +1,624 @@
+"""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
+
+_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)."""
+ 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:
+ 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.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]
+
+ # -- 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"):
+ 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 = 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 i in self.ple:
+ x = 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 = 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
+ 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, 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].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 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):
+ 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/hy4_forward.py.pre_attn_eager b/exllamav3/loader/hy4_forward.py.pre_attn_eager
new file mode 100644
index 0000000..f4eb878
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_attn_eager
@@ -0,0 +1,656 @@
+"""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
+
+_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)."""
+ 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:
+ 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 i in self.ple:
+ x = 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 = _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 = 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, _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/hy4_forward.py.pre_engram b/exllamav3/loader/hy4_forward.py.pre_engram
new file mode 100755
index 0000000..63c16c7
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_engram
@@ -0,0 +1,601 @@
+"""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
+
+_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)."""
+ 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:
+ 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.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]
+
+ # -- 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"):
+ 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 = 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 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ 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 = 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 = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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"):
+ 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"):
+ 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]
+ 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].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 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):
+ 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/hy4_forward.py.pre_graph b/exllamav3/loader/hy4_forward.py.pre_graph
new file mode 100644
index 0000000..860ae63
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_graph
@@ -0,0 +1,659 @@
+"""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 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)."""
+ 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:
+ 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)
+ if i in self.ple:
+ x = 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 = _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 = 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, _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/hy4_forward.py.pre_hc b/exllamav3/loader/hy4_forward.py.pre_hc
new file mode 100644
index 0000000..9d8cc20
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_hc
@@ -0,0 +1,607 @@
+"""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
+
+_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)."""
+ 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:
+ 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.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]
+
+ # -- 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"):
+ 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 = 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ 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 = 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 = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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"):
+ 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"):
+ 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]
+ 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].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 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):
+ 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/hy4_forward.py.pre_head b/exllamav3/loader/hy4_forward.py.pre_head
new file mode 100644
index 0000000..5406e8b
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_head
@@ -0,0 +1,662 @@
+"""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 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)."""
+ 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/hy4_forward.py.pre_indexer b/exllamav3/loader/hy4_forward.py.pre_indexer
new file mode 100644
index 0000000..d750c2b
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_indexer
@@ -0,0 +1,627 @@
+"""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
+
+_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)."""
+ 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:
+ 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
+ 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]
+
+ # -- 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"):
+ 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 = 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 i in self.ple:
+ x = 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 = 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
+ 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, 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].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 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):
+ 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/hy4_forward.py.pre_m1a b/exllamav3/loader/hy4_forward.py.pre_m1a
new file mode 100644
index 0000000..4e918ea
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_m1a
@@ -0,0 +1,315 @@
+"""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 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
+
+_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)")
+
+
+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:
+ 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.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
+
+ # -- weights
+ def _w(self, name):
+ return load_dense(self.g, name).to(self.dev, self.wdtype)
+
+ 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)
+ _mv(L.mla, dev, self.wdtype)
+ 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]
+
+ # -- 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):
+ return (x.to(w.dtype) @ w.T).float()
+
+ def _ffn(self, i, L, x):
+ if i < self.n_dense:
+ gt, up, dn = L.dense
+ return self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn), None
+ T, dev = x.shape[0], self.dev
+ 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
+ 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}."
+ for e in sorted(set(sel.flatten().tolist())):
+ rows, slot = (sel == e).nonzero(as_tuple=True)
+ zi = z[rows]
+ W = {n: dq_expert(self.g.get_tensor(f"{b}ffn_{n}_exps.e{e}.weight"), L.ety_down if n == "down" else L.ety, N, N, dev) for n in ("gate", "up", "down")}
+ ga, upv = zi @ W["gate"].T, zi @ W["up"].T
+ h = torch.nn.functional.silu(ga.clamp(max=lim)) * upv.clamp(-lim, lim)
+ lat.index_add_(0, rows, (h @ W["down"].T) * w[rows, slot].unsqueeze(-1))
+ y = self._mm(lat, L.rup)
+ gt, up, dn = L.shexp
+ 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 i not in self.eng:
+ self.eng[i] = Hy4Engram(self.g, i, table=self.table)
+ 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ pre, post = self._site(x, L.hca)
+ cur = rms((x * pre[:, :, None]).sum(1), self.eps) * L.attn_norm
+ mla = L.mla
+ kn = mla.kv(cur, pos)
+ kc = torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn
+ N = kc.shape[0]
+ allow = None
+ if L.ix:
+ qr = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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)
+ 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)
+ 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):
+ """x [T, hc, n_embd] -> logits of the LAST position [vocab]"""
+ fn, base, scale = self.hh
+ xl = x[-1:]
+ mix = rms(xl.reshape(1, -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)[0].cpu()
+ W = self.out_w
+ out = torch.empty(W.shape[0])
+ for a in range(0, W.shape[0], 8192):
+ out[a:a + 8192] = W[a:a + 8192].float() @ h
+ return out
+
+ def step(self, ids):
+ """append ids (prefill = all prompt ids at once, decode = one id), return last-position logits (None on a truncated stack)"""
+ 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) if self.n_layers == self.n_trunk else None
+ self.stats["layer_s"] += time.time() - t0
+ return lg
+
+ def generate(self, 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/hy4_forward.py.pre_m1b b/exllamav3/loader/hy4_forward.py.pre_m1b
new file mode 100644
index 0000000..84bce45
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_m1b
@@ -0,0 +1,531 @@
+"""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
+
+_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 = []
+
+
+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)."""
+ 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:
+ 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)
+
+ # -- 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.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]
+
+ # -- 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"):
+ 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 = 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}."
+ 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 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ 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 = 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 = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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"):
+ 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"):
+ 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]
+ 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].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 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):
+ 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/hy4_forward.py.pre_m3 b/exllamav3/loader/hy4_forward.py.pre_m3
new file mode 100644
index 0000000..0d214a6
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_m3
@@ -0,0 +1,426 @@
+"""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
+
+_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 = []
+
+
+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])
+
+
+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:
+ 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.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
+
+ # -- weights
+ def _w(self, name):
+ return load_dense(self.g, name).to(self.dev, self.wdtype)
+
+ 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)
+ _mv(L.mla, dev, self.wdtype)
+ L.mla.tm = self.tm
+ 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]
+
+ # -- 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):
+ 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"):
+ 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 = 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}."
+ 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 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 i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ 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 = 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 = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.eps) * mla.q_a_norm
+ 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, 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"):
+ 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"):
+ 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):
+ """x [T, hc, n_embd] -> logits of the LAST position [vocab]"""
+ with self.tm.t("head"):
+ return self._head(x)
+
+ def _head(self, x):
+ fn, base, scale = self.hh
+ xl = x[-1:]
+ mix = rms(xl.reshape(1, -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)[0].cpu()
+ W = self.out_w
+ out = torch.empty(W.shape[0])
+ for a in range(0, W.shape[0], 8192):
+ out[a:a + 8192] = W[a:a + 8192].float() @ h
+ return out
+
+ def step(self, ids):
+ """append ids (prefill = all prompt ids at once, decode = one id), return last-position logits (None on a truncated stack)"""
+ 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) 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):
+ 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/hy4_forward.py.pre_nosync b/exllamav3/loader/hy4_forward.py.pre_nosync
new file mode 100644
index 0000000..9c75028
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_nosync
@@ -0,0 +1,645 @@
+"""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
+
+_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)."""
+ 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:
+ 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
+ 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"):
+ 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 = 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 i in self.ple:
+ x = 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 = 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 = 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, 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].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 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):
+ 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/hy4_forward.py.pre_ref b/exllamav3/loader/hy4_forward.py.pre_ref
new file mode 100644
index 0000000..17523a9
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_ref
@@ -0,0 +1,650 @@
+"""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 step_nosync as _ns
+
+_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)."""
+ 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:
+ 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
+ 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"):
+ 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 i in self.ple:
+ x = 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 = _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 = 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, _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/hy4_forward.py.pre_ref_mistake b/exllamav3/loader/hy4_forward.py.pre_ref_mistake
new file mode 100644
index 0000000..d750c2b
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.pre_ref_mistake
@@ -0,0 +1,627 @@
+"""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
+
+_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)."""
+ 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:
+ 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
+ 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]
+
+ # -- 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"):
+ 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 = 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 i in self.ple:
+ x = 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 = 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
+ 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, 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].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 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):
+ 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/hy4_forward.py.with_ref_mistake b/exllamav3/loader/hy4_forward.py.with_ref_mistake
new file mode 100755
index 0000000..978f5b8
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py.with_ref_mistake
@@ -0,0 +1,633 @@
+"""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
+
+_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)."""
+ 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:
+ 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]
+
+ # -- 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 = 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 i in self.ple:
+ x = 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 = 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
+ 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, 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].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 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):
+ 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/indexer_fused.py b/exllamav3/loader/indexer_fused.py
new file mode 100644
index 0000000..07d09b4
--- /dev/null
+++ b/exllamav3/loader/indexer_fused.py
@@ -0,0 +1,117 @@
+"""Device-resident k-pool indexer: pooled keys cached on the device, score + group top-k + attention mask built with
+torch ops only and NO host sync (every size is derived from the host-side token counter).
+
+Same maths and op order as modules/kpool_indexer.KPoolIndexer (so on one device it is bit-exact); differences:
+ * pooled keys live in a preallocated [cap, d] buffer, a completed group is written in place (no torch.cat of the pool);
+ * the token-position rope table (cos/sin) is built once and grown, not recomputed per step in float64;
+ * selection = topk over the visible group scores -> bool group mask -> allow [T, N] (members | tail), all on device;
+ * returns allow=None (host-decided, no sync) when every query sees all of its causal keys.
+Generic by (n_head, head_dim, top_k, kpool, select_tail, rope_dim); nothing keyed on a model name.
+Ties at the top-k boundary: torch.topk order is unspecified (the CPU reference takes the lowest group index).
+"""
+from __future__ import annotations
+import math
+import torch
+
+
+def _rms(x, w, eps):
+ x = x.float()
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
+
+
+class FusedKPoolIndexer:
+ """w: name -> weight with `x @ w.T` support (fp32 tensor or a Q8 QLinear) for attn_k, q_b, value, gate; dense tensors
+ for proj [H, E], k_norm [d], ape [kpool, d], pool_norm [d]. Small dense ones are moved to `device`."""
+
+ def __init__(self, w, device, n_head=16, head_dim=128, top_k=2048, kpool=4, select_tail=True, rope_dim=64,
+ rope_base=1e7, eps=1e-5, cap=4096):
+ self.dev = torch.device(device)
+ self.w = {k: (v.to(self.dev) if isinstance(v, torch.Tensor) else v) for k, v in w.items()}
+ self.H, self.d, self.top_k, self.k = n_head, head_dim, top_k, kpool
+ self.tail, self.rope_dim, self.base, self.eps = int(bool(select_tail)), rope_dim, rope_base, eps
+ assert top_k % kpool == 0 and top_k // kpool - self.tail >= 1 and rope_dim < head_dim
+ self.n_top = top_k // kpool - self.tail
+ self.n = 0 # tokens seen (host int)
+ self.P = 0 # pooled groups stored (host int)
+ self.pool = torch.zeros(max(cap // kpool, 16), head_dim, device=self.dev)
+ self.vg = None # [<kpool, 2d] tokens of the open group
+ self._cs = None # (cos, sin) [Lpos, rope_dim/2] fp32
+ self.last_scores = None
+
+ # -- rope table, built like the reference (float64 angle, then fp32 cos / sin)
+ def _table(self, upto):
+ if self._cs is None or self._cs[0].shape[0] < upto:
+ L = max(upto, 2 * (self._cs[0].shape[0] if self._cs else 0), 4096)
+ inv = self.base ** (-torch.arange(0, self.rope_dim, 2, dtype=torch.float64) / self.rope_dim)
+ ang = torch.arange(L, dtype=torch.float64)[:, None] * inv[None]
+ self._cs = (ang.cos().float().to(self.dev), ang.sin().float().to(self.dev))
+ return self._cs
+
+ def _rope(self, x, pos):
+ """x [n, (H,) d], pos [n] long (device). Rotates the trailing rope_dim (NORM pairs)."""
+ c, s = self._table(self._max_pos)
+ c, s = c[pos], s[pos]
+ sh = [x.shape[0]] + [1] * (x.dim() - 2) + [self.rope_dim // 2]
+ c, s = c.reshape(sh), s.reshape(sh)
+ d = x.shape[-1]
+ t = x[..., d - self.rope_dim:]
+ a, b = t[..., 0::2], t[..., 1::2]
+ out = torch.empty_like(t)
+ out[..., 0::2] = a * c - b * s
+ out[..., 1::2] = a * s + b * c
+ return torch.cat([x[..., :d - self.rope_dim], out], -1)
+
+ def _pool_groups(self, vg, g0):
+ k, d = self.k, self.d
+ v, g = vg[:, :d].reshape(-1, k, d), vg[:, d:].reshape(-1, k, d)
+ p = (torch.softmax(g + self.w["ape"][None], dim=1) * v).sum(1)
+ p = _rms(p, self.w["pool_norm"], self.eps)
+ return self._rope(p, (torch.arange(g0, g0 + p.shape[0], device=self.dev) * k))
+
+ @torch.no_grad()
+ def forward(self, x, qr, n_keys=None):
+ """x [T, E] attn_norm output, qr [T, R] q_a_norm output (both on the device), T consecutive new tokens.
+ n_keys = rows of the attention key cache after this call (default: tokens seen). -> allow [T, n_keys] bool or None."""
+ T, k, d, H = x.shape[0], self.k, self.d, self.H
+ start = self.n
+ self._max_pos = start + T
+ pos = torch.arange(start, start + T, device=self.dev)
+ ik = _rms(x @ self.w["attn_k"].T, self.w["k_norm"], self.eps)
+ vg_new = torch.cat([ik @ self.w["value"].T, ik @ self.w["gate"].T], -1)
+ buf = vg_new if self.vg is None else torch.cat([self.vg, vg_new], 0)
+ m = buf.shape[0] // k
+ if m:
+ if self.P + m > self.pool.shape[0]:
+ big = torch.empty(max(2 * self.pool.shape[0], self.P + m), d, device=self.dev)
+ big[:self.P] = self.pool[:self.P]
+ self.pool = big
+ self.pool[self.P:self.P + m] = self._pool_groups(buf[:m * k], self.P)
+ self.P += m
+ self.vg = buf[m * k:] if buf.shape[0] - m * k else None
+ self.n += T
+ iq = self._rope((qr @ self.w["q_b"].T).reshape(T, H, d), pos)
+ wt = (x.float() @ self.w["proj"].T) / math.sqrt(d * H)
+ P = self.P
+ pk = self.pool[:P]
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pk))
+ sc = (kq * wt[:, :, None]).sum(1) # [T, P]
+ gend = torch.arange(P, device=self.dev) * k + (k - 1)
+ vis = (gend[None] < pos[:, None]) if self.tail else (gend[None] <= pos[:, None])
+ sc = torch.where(vis, sc, torch.full_like(sc, -math.inf))
+ self.last_scores = sc
+ # host-side: does any query see fewer keys than its causal range? nvis(p) = p // k (tail) or (p + 1) // k
+ last = start + T - 1
+ nvis_max = last // k if self.tail else (last + 1) // k
+ if nvis_max <= self.n_top:
+ return None
+ N = self.n if n_keys is None else n_keys
+ idx = torch.topk(sc, min(self.n_top, P), dim=1).indices # [T, n_top]
+ gsel = torch.zeros(T, P, dtype=torch.bool, device=self.dev)
+ gsel.scatter_(1, idx, True)
+ gsel &= vis # picked -inf slots (fewer visible than n_top)
+ allow = torch.zeros(T, N, dtype=torch.bool, device=self.dev)
+ allow[:, :P * k] = gsel.repeat_interleave(k, dim=1)
+ j = torch.arange(N, device=self.dev)[None]
+ lo = (pos - (pos % k)) if self.tail else (pos - ((pos + 1) % k) + 1)
+ allow |= (j >= lo[:, None]) & (j <= pos[:, None])
+ return allow
diff --git a/exllamav3/loader/indexer_fused.py.pre_graph b/exllamav3/loader/indexer_fused.py.pre_graph
new file mode 100644
index 0000000..5cbbeed
--- /dev/null
+++ b/exllamav3/loader/indexer_fused.py.pre_graph
@@ -0,0 +1,117 @@
+"""Device-resident k-pool indexer: pooled keys cached on the device, score + group top-k + attention mask built with
+torch ops only and NO host sync (every size is derived from the host-side token counter).
+
+Same maths and op order as modules/kpool_indexer.KPoolIndexer (so on one device it is bit-exact); differences:
+ * pooled keys live in a preallocated [cap, d] buffer, a completed group is written in place (no torch.cat of the pool);
+ * the token-position rope table (cos/sin) is built once and grown, not recomputed per step in float64;
+ * selection = topk over the visible group scores -> bool group mask -> allow [T, N] (members | tail), all on device;
+ * returns allow=None (host-decided, no sync) when every query sees all of its causal keys.
+Generic by (n_head, head_dim, top_k, kpool, select_tail, rope_dim); nothing keyed on a model name.
+Ties at the top-k boundary: torch.topk order is unspecified (the CPU reference takes the lowest group index).
+"""
+from __future__ import annotations
+import math
+import torch
+
+
+def _rms(x, w, eps):
+ x = x.float()
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
+
+
+class FusedKPoolIndexer:
+ """w: name -> weight with `x @ w.T` support (fp32 tensor or a Q8 QLinear) for attn_k, q_b, value, gate; dense tensors
+ for proj [H, E], k_norm [d], ape [kpool, d], pool_norm [d]. Small dense ones are moved to `device`."""
+
+ def __init__(self, w, device, n_head=16, head_dim=128, top_k=2048, kpool=4, select_tail=True, rope_dim=64,
+ rope_base=1e7, eps=1e-5, cap=4096):
+ self.dev = torch.device(device)
+ self.w = {k: (v.to(self.dev) if isinstance(v, torch.Tensor) else v) for k, v in w.items()}
+ self.H, self.d, self.top_k, self.k = n_head, head_dim, top_k, kpool
+ self.tail, self.rope_dim, self.base, self.eps = int(bool(select_tail)), rope_dim, rope_base, eps
+ assert top_k % kpool == 0 and top_k // kpool - self.tail >= 1 and rope_dim < head_dim
+ self.n_top = top_k // kpool - self.tail
+ self.n = 0 # tokens seen (host int)
+ self.P = 0 # pooled groups stored (host int)
+ self.pool = torch.empty(max(cap // kpool, 16), head_dim, device=self.dev)
+ self.vg = None # [<kpool, 2d] tokens of the open group
+ self._cs = None # (cos, sin) [Lpos, rope_dim/2] fp32
+ self.last_scores = None
+
+ # -- rope table, built like the reference (float64 angle, then fp32 cos / sin)
+ def _table(self, upto):
+ if self._cs is None or self._cs[0].shape[0] < upto:
+ L = max(upto, 2 * (self._cs[0].shape[0] if self._cs else 0), 4096)
+ inv = self.base ** (-torch.arange(0, self.rope_dim, 2, dtype=torch.float64) / self.rope_dim)
+ ang = torch.arange(L, dtype=torch.float64)[:, None] * inv[None]
+ self._cs = (ang.cos().float().to(self.dev), ang.sin().float().to(self.dev))
+ return self._cs
+
+ def _rope(self, x, pos):
+ """x [n, (H,) d], pos [n] long (device). Rotates the trailing rope_dim (NORM pairs)."""
+ c, s = self._table(self._max_pos)
+ c, s = c[pos], s[pos]
+ sh = [x.shape[0]] + [1] * (x.dim() - 2) + [self.rope_dim // 2]
+ c, s = c.reshape(sh), s.reshape(sh)
+ d = x.shape[-1]
+ t = x[..., d - self.rope_dim:]
+ a, b = t[..., 0::2], t[..., 1::2]
+ out = torch.empty_like(t)
+ out[..., 0::2] = a * c - b * s
+ out[..., 1::2] = a * s + b * c
+ return torch.cat([x[..., :d - self.rope_dim], out], -1)
+
+ def _pool_groups(self, vg, g0):
+ k, d = self.k, self.d
+ v, g = vg[:, :d].reshape(-1, k, d), vg[:, d:].reshape(-1, k, d)
+ p = (torch.softmax(g + self.w["ape"][None], dim=1) * v).sum(1)
+ p = _rms(p, self.w["pool_norm"], self.eps)
+ return self._rope(p, (torch.arange(g0, g0 + p.shape[0], device=self.dev) * k))
+
+ @torch.no_grad()
+ def forward(self, x, qr, n_keys=None):
+ """x [T, E] attn_norm output, qr [T, R] q_a_norm output (both on the device), T consecutive new tokens.
+ n_keys = rows of the attention key cache after this call (default: tokens seen). -> allow [T, n_keys] bool or None."""
+ T, k, d, H = x.shape[0], self.k, self.d, self.H
+ start = self.n
+ self._max_pos = start + T
+ pos = torch.arange(start, start + T, device=self.dev)
+ ik = _rms(x @ self.w["attn_k"].T, self.w["k_norm"], self.eps)
+ vg_new = torch.cat([ik @ self.w["value"].T, ik @ self.w["gate"].T], -1)
+ buf = vg_new if self.vg is None else torch.cat([self.vg, vg_new], 0)
+ m = buf.shape[0] // k
+ if m:
+ if self.P + m > self.pool.shape[0]:
+ big = torch.empty(max(2 * self.pool.shape[0], self.P + m), d, device=self.dev)
+ big[:self.P] = self.pool[:self.P]
+ self.pool = big
+ self.pool[self.P:self.P + m] = self._pool_groups(buf[:m * k], self.P)
+ self.P += m
+ self.vg = buf[m * k:] if buf.shape[0] - m * k else None
+ self.n += T
+ iq = self._rope((qr @ self.w["q_b"].T).reshape(T, H, d), pos)
+ wt = (x.float() @ self.w["proj"].T) / math.sqrt(d * H)
+ P = self.P
+ pk = self.pool[:P]
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pk))
+ sc = (kq * wt[:, :, None]).sum(1) # [T, P]
+ gend = torch.arange(P, device=self.dev) * k + (k - 1)
+ vis = (gend[None] < pos[:, None]) if self.tail else (gend[None] <= pos[:, None])
+ sc = torch.where(vis, sc, torch.full_like(sc, -math.inf))
+ self.last_scores = sc
+ # host-side: does any query see fewer keys than its causal range? nvis(p) = p // k (tail) or (p + 1) // k
+ last = start + T - 1
+ nvis_max = last // k if self.tail else (last + 1) // k
+ if nvis_max <= self.n_top:
+ return None
+ N = self.n if n_keys is None else n_keys
+ idx = torch.topk(sc, min(self.n_top, P), dim=1).indices # [T, n_top]
+ gsel = torch.zeros(T, P, dtype=torch.bool, device=self.dev)
+ gsel.scatter_(1, idx, True)
+ gsel &= vis # picked -inf slots (fewer visible than n_top)
+ allow = torch.zeros(T, N, dtype=torch.bool, device=self.dev)
+ allow[:, :P * k] = gsel.repeat_interleave(k, dim=1)
+ j = torch.arange(N, device=self.dev)[None]
+ lo = (pos - (pos % k)) if self.tail else (pos - ((pos + 1) % k) + 1)
+ allow |= (j >= lo[:, None]) & (j <= pos[:, None])
+ return allow
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index cea356e..61b627a 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -6,6 +6,8 @@ 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():
@@ -26,8 +28,8 @@ def _dense3(g, name, h):
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) / P))[None, :] # [T, P/2]
- c, s = th.cos().float(), th.sin().float()
+ 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]
@@ -39,11 +41,12 @@ def rope_norm(x: torch.Tensor, pos: torch.Tensor, base: float) -> torch.Tensor:
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):
+ 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"]
@@ -54,17 +57,18 @@ class Hy4MLA:
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 = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
- self.wq_b = load_dense(g, b + "attn_q_b.weight")
- self.wkv_a, self.kv_a_norm = load_dense(g, b + "attn_kv_a_mqa.weight"), load_dense(g, b + "attn_kv_a_norm.weight")
+ 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 = load_dense(g, b + "attn_output.weight"), load_dense(g, b + "attn_gate.weight")
+ 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")
@@ -76,6 +80,8 @@ class Hy4MLA:
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)
@@ -83,6 +89,8 @@ class Hy4MLA:
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)
@@ -90,19 +98,29 @@ class Hy4MLA:
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):
+ 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
- qlat, qpe = self.q(cur, pos)
- o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window)
- 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)
+ 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)
diff --git a/exllamav3/loader/mla_hy4.py.pre_DFE b/exllamav3/loader/mla_hy4.py.pre_DFE
new file mode 100644
index 0000000..018d86c
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_DFE
@@ -0,0 +1,135 @@
+"""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
+
+
+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)"""
+ 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)"""
+ 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"):
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_attn_eager b/exllamav3/loader/mla_hy4.py.pre_attn_eager
new file mode 100644
index 0000000..6a8547e
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_attn_eager
@@ -0,0 +1,140 @@
+"""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
+
+
+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)"""
+ 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)"""
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_dev b/exllamav3/loader/mla_hy4.py.pre_dev
new file mode 100644
index 0000000..17a6ee0
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_dev
@@ -0,0 +1,129 @@
+"""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
+
+
+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) / 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):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ b = f"blk.{layer}."
+ self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
+ 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 = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
+ self.wq_b = load_dense(g, b + "attn_q_b.weight")
+ self.wkv_a, self.kv_a_norm = load_dense(g, 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 = load_dense(g, b + "attn_output.weight"), load_dense(g, 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()
+
+ 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)"""
+ 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)"""
+ 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
+ qlat, qpe = self.q(cur, pos)
+ o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_ft b/exllamav3/loader/mla_hy4.py.pre_ft
new file mode 100644
index 0000000..cea356e
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_ft
@@ -0,0 +1,129 @@
+"""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
+
+
+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) / P))[None, :] # [T, P/2]
+ c, s = th.cos().float(), th.sin().float()
+ 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):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ b = f"blk.{layer}."
+ self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
+ 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 = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
+ self.wq_b = load_dense(g, b + "attn_q_b.weight")
+ self.wkv_a, self.kv_a_norm = load_dense(g, 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 = load_dense(g, b + "attn_output.weight"), load_dense(g, 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()
+
+ 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)"""
+ 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)"""
+ 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):
+ """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
+ qlat, qpe = self.q(cur, pos)
+ o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window)
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_m1a b/exllamav3/loader/mla_hy4.py.pre_m1a
new file mode 100644
index 0000000..ae410e7
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_m1a
@@ -0,0 +1,129 @@
+"""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
+
+
+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):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ b = f"blk.{layer}."
+ self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
+ 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 = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
+ self.wq_b = load_dense(g, b + "attn_q_b.weight")
+ self.wkv_a, self.kv_a_norm = load_dense(g, 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 = load_dense(g, b + "attn_output.weight"), load_dense(g, 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()
+
+ 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)"""
+ 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)"""
+ 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
+ qlat, qpe = self.q(cur, pos)
+ o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_m3 b/exllamav3/loader/mla_hy4.py.pre_m3
new file mode 100644
index 0000000..5e66a9b
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_m3
@@ -0,0 +1,134 @@
+"""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
+
+
+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):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ b = f"blk.{layer}."
+ self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
+ 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 = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
+ self.wq_b = load_dense(g, b + "attn_q_b.weight")
+ self.wkv_a, self.kv_a_norm = load_dense(g, 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 = load_dense(g, b + "attn_output.weight"), load_dense(g, 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)"""
+ 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)"""
+ 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"):
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_ref b/exllamav3/loader/mla_hy4.py.pre_ref
new file mode 100644
index 0000000..018d86c
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_ref
@@ -0,0 +1,135 @@
+"""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
+
+
+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)"""
+ 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)"""
+ 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"):
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.pre_ref_mistake b/exllamav3/loader/mla_hy4.py.pre_ref_mistake
new file mode 100644
index 0000000..018d86c
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.pre_ref_mistake
@@ -0,0 +1,135 @@
+"""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
+
+
+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)"""
+ 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)"""
+ 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"):
+ 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
+ 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
diff --git a/exllamav3/loader/mla_hy4.py.with_ref_mistake b/exllamav3/loader/mla_hy4.py.with_ref_mistake
new file mode 100644
index 0000000..6a8547e
--- /dev/null
+++ b/exllamav3/loader/mla_hy4.py.with_ref_mistake
@@ -0,0 +1,140 @@
+"""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
+
+
+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)"""
+ 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)"""
+ 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
+ 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
diff --git a/exllamav3/loader/ref_fused.py b/exllamav3/loader/ref_fused.py
new file mode 100644
index 0000000..9ef3972
--- /dev/null
+++ b/exllamav3/loader/ref_fused.py
@@ -0,0 +1,184 @@
+"""PART E: fused replacements for two torch reference paths of the decode step (flag HY4_REF_FUSED=1, default OFF).
+
+ router_select(logits, bias, k, w_scale) sigmoid + (+bias) top-k + gather + normalise + scale: ONE Triton launch per call
+ (old: sigmoid, add, topk, gather, sum, clamp, div, mul = ~8 launches)
+ mla_sink_attend(...) same signature / result as attention_fn.mla_sinks.mla_sink_attend: scores, window /
+ causal / allow mask, per-head sink in the denominator, softmax, p @ ckv as one
+ online-softmax Triton kernel, grid (T, H), no [H,T,N] score tensor, no mask tensors.
+Generic: shapes come from the tensors (E, k, R, P, H, N); nothing is keyed on a model name. Anything outside the kernel's range
+(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 torch
+
+ENABLED = os.environ.get("HY4_REF_FUSED", "0") == "1"
+MAX_T = 16 # rows per call handled by the attention kernel (decode / short verify); more = prefill -> torch GEMMs
+CLAMP_MIN = 6.103515625e-5 # the old router's `sum.clamp(min=...)`
+
+try:
+ import triton
+ import triton.language as tl
+except Exception: # no triton: every function below uses its torch reference
+ triton = None
+
+
+def _usable(*ts):
+ if triton is None:
+ return False
+ if os.environ.get("TRITON_INTERPRET", "0") == "1":
+ return True
+ return all(t.is_cuda for t in ts)
+
+
+# ------------------------------------------------------------------------------------------------ router
+def router_ref(logits, bias, k, w_scale):
+ """the old code (hy4_forward._ffn), verbatim maths: logits [T, E] = x @ router.T -> sel [T, k] int64, w [T, k] fp32"""
+ p = torch.sigmoid(logits)
+ sel = torch.topk(p + bias, k, dim=-1).indices
+ w = torch.gather(p, 1, sel)
+ w = w / w.sum(-1, keepdim=True).clamp(min=CLAMP_MIN) * w_scale
+ return sel, w
+
+
+if triton is not None:
+ @triton.jit
+ def _router_kernel(LG, BIAS, SEL, W, E, w_scale, clamp_min, s_lg,
+ HAS_BIAS: tl.constexpr, K: tl.constexpr, BE: tl.constexpr, BK: tl.constexpr):
+ t = tl.program_id(0)
+ offe = tl.arange(0, BE)
+ me = offe < E
+ x = tl.load(LG + t * s_lg + offe, mask=me, other=0.0).to(tl.float32)
+ p = 1.0 / (1.0 + tl.exp(-x))
+ sc = p
+ if HAS_BIAS:
+ sc = p + tl.load(BIAS + offe, mask=me, other=0.0).to(tl.float32)
+ sc = tl.where(me, sc, float("-inf"))
+ offk = tl.arange(0, BK)
+ selv = tl.zeros([BK], dtype=tl.int32)
+ pv = tl.zeros([BK], dtype=tl.float32)
+ for j in tl.static_range(K):
+ mx = tl.max(sc, axis=0)
+ idx = tl.min(tl.where(sc == mx, offe, BE), axis=0) # ties -> lowest expert id, like torch.topk
+ hit = offe == idx
+ pj = tl.sum(tl.where(hit, p, 0.0), axis=0)
+ selv = tl.where(offk == j, idx, selv)
+ pv = tl.where(offk == j, pj, pv)
+ sc = tl.where(hit, float("-inf"), sc)
+ s = tl.sum(pv, axis=0)
+ w = pv / tl.maximum(s, clamp_min) * w_scale
+ mk = offk < K
+ tl.store(SEL + t * K + offk, selv.to(tl.int64), mask=mk)
+ tl.store(W + t * K + offk, w, mask=mk)
+
+
+def router_select(logits, bias, k, w_scale):
+ """one launch: logits [T, E] fp32 (the router matmul output, unchanged) -> (sel [T, k] int64, w [T, k] fp32)"""
+ if os.environ.get("HY4_REF_ROUTER", "1") == "0": # sub-flag: router half off
+ return router_ref(logits, bias, k, w_scale)
+ if not _usable(logits) or logits.dtype != torch.float32 or k > logits.shape[1]:
+ return router_ref(logits, bias, k, w_scale)
+ logits = logits.contiguous()
+ T, E = logits.shape
+ sel = torch.empty(T, k, dtype=torch.int64, device=logits.device)
+ w = torch.empty(T, k, dtype=torch.float32, device=logits.device)
+ has_bias = bias is not None
+ _router_kernel[(T,)](logits, bias.contiguous() if has_bias else logits, sel, w, E, float(w_scale), CLAMP_MIN, logits.stride(0),
+ HAS_BIAS=has_bias, K=k, BE=triton.next_power_of_2(E), BK=triton.next_power_of_2(k))
+ return sel, w
+
+
+# ------------------------------------------------------------------------------------------------ MLA core + sinks
+def mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None):
+ """attention_fn/mla_sinks.py:mla_sink_attend, copied verbatim (the fallback and the test reference)"""
+ s = torch.einsum("thr,nr->htn", q_lat, ckv) + torch.einsum("thp,np->htn", q_pe, k_pe)
+ s = s * scale
+ vis = kpos[None, :] <= qpos[:, None]
+ if window:
+ vis = vis & ((qpos[:, None] - kpos[None, :]) < window)
+ if allow is not None:
+ vis = vis & allow
+ s = s.masked_fill(~vis[None], float("-inf"))
+ if sinks is not None:
+ s = torch.cat([s, sinks.float()[:, None, None].expand(-1, s.shape[1], 1)], dim=-1)
+ p = torch.softmax(s, dim=-1)
+ if sinks is not None:
+ p = p[..., :-1]
+ return torch.einsum("htn,nr->thr", p, ckv)
+
+
+if triton is not None:
+ @triton.jit
+ def _mla_kernel(QL, QP, CK, KP, QPOS, KPOS, ALLOW, SINK, O, N, scale, window,
+ s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_al, s_o_t, s_o_h,
+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BP: tl.constexpr, BN: tl.constexpr,
+ HAS_SINK: tl.constexpr, HAS_ALLOW: tl.constexpr, HAS_WIN: tl.constexpr, ARANGE: tl.constexpr):
+ t = tl.program_id(0)
+ h = tl.program_id(1)
+ offr = tl.arange(0, BR)
+ offp = tl.arange(0, BP)
+ mr = offr < R
+ mp = offp < P
+ q = tl.load(QL + t * s_ql_t + h * s_ql_h + offr, mask=mr, other=0.0).to(tl.float32)
+ qp = tl.load(QP + t * s_qp_t + h * s_qp_h + offp, mask=mp, other=0.0).to(tl.float32)
+ qpos = tl.load(QPOS + t)
+ if HAS_SINK: # the sink is a key with logit s and a zero value: start the softmax from it
+ m = tl.load(SINK + h).to(tl.float32)
+ l = tl.zeros([], dtype=tl.float32) + 1.0
+ else:
+ m = tl.zeros([], dtype=tl.float32) + float("-inf")
+ l = tl.zeros([], dtype=tl.float32)
+ acc = tl.zeros([BR], dtype=tl.float32)
+ lo = 0
+ hi = N
+ if ARANGE: # kpos[j] == j: causal / window bounds skip whole blocks
+ hi = tl.minimum(N, qpos + 1)
+ if HAS_WIN:
+ lo = tl.maximum(0, qpos - window + 1) // BN * BN
+ for n0 in range(lo, hi, BN):
+ offn = n0 + tl.arange(0, BN)
+ inb = offn < N
+ if ARANGE:
+ kpos = offn
+ else:
+ kpos = tl.load(KPOS + offn, mask=inb, other=0)
+ vis = inb & (kpos <= qpos)
+ if HAS_WIN:
+ vis = vis & ((qpos - kpos) < window)
+ if HAS_ALLOW:
+ vis = vis & (tl.load(ALLOW + t * s_al + offn, mask=inb, other=0) != 0)
+ ck = tl.load(CK + offn[:, None] * s_ck + offr[None, :], mask=inb[:, None] & mr[None, :], other=0.0).to(tl.float32)
+ kp = tl.load(KP + offn[:, None] * s_kp + offp[None, :], mask=inb[:, None] & mp[None, :], other=0.0).to(tl.float32)
+ s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scale
+ s = tl.where(vis, s, float("-inf"))
+ mn = tl.maximum(m, tl.max(s, axis=0))
+ mn_s = tl.where(mn == float("-inf"), 0.0, mn)
+ alpha = tl.exp(m - mn_s)
+ pr = tl.exp(s - mn_s)
+ l = l * alpha + tl.sum(pr, axis=0)
+ acc = acc * alpha + tl.sum(pr[:, None] * ck, axis=0)
+ m = mn
+ tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)
+
+
+def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None, kpos_is_arange=False):
+ """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)
+ (the Hy4 forward always passes it so), which lets causal / window bounds skip K blocks."""
+ if os.environ.get("HY4_REF_MLA", "1") == "0": # sub-flag: MLA half off
+ return mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks, window, allow)
+ T, H, R = q_lat.shape
+ N, P = ckv.shape[0], k_pe.shape[1]
+ if (not _usable(q_lat, ckv) or T > MAX_T or sinks is None or N == 0 or q_lat.dtype != torch.float32 or ckv.dtype != torch.float32
+ or q_lat.stride(-1) != 1 or q_pe.stride(-1) != 1 or ckv.stride(-1) != 1 or k_pe.stride(-1) != 1):
+ return mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks, window, allow)
+ out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)
+ al = allow.view(torch.uint8) if allow is not None else qpos
+ BN = 16
+ _mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, kpos, al, sinks.float().contiguous(), out, N, float(scale), int(window),
+ q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0),
+ allow.stride(0) if allow is not None else 0, out.stride(0), out.stride(1),
+ R=R, P=P, BR=triton.next_power_of_2(R), BP=triton.next_power_of_2(P), BN=BN,
+ HAS_SINK=True, HAS_ALLOW=allow is not None, HAS_WIN=bool(window), ARANGE=bool(kpos_is_arange),
+ num_warps=4)
+ return out
diff --git a/exllamav3/loader/ref_fused.py.pre_sub b/exllamav3/loader/ref_fused.py.pre_sub
new file mode 100644
index 0000000..495495f
--- /dev/null
+++ b/exllamav3/loader/ref_fused.py.pre_sub
@@ -0,0 +1,180 @@
+"""PART E: fused replacements for two torch reference paths of the decode step (flag HY4_REF_FUSED=1, default OFF).
+
+ router_select(logits, bias, k, w_scale) sigmoid + (+bias) top-k + gather + normalise + scale: ONE Triton launch per call
+ (old: sigmoid, add, topk, gather, sum, clamp, div, mul = ~8 launches)
+ mla_sink_attend(...) same signature / result as attention_fn.mla_sinks.mla_sink_attend: scores, window /
+ causal / allow mask, per-head sink in the denominator, softmax, p @ ckv as one
+ online-softmax Triton kernel, grid (T, H), no [H,T,N] score tensor, no mask tensors.
+Generic: shapes come from the tensors (E, k, R, P, H, N); nothing is keyed on a model name. Anything outside the kernel's range
+(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 torch
+
+ENABLED = os.environ.get("HY4_REF_FUSED", "0") == "1"
+MAX_T = 16 # rows per call handled by the attention kernel (decode / short verify); more = prefill -> torch GEMMs
+CLAMP_MIN = 6.103515625e-5 # the old router's `sum.clamp(min=...)`
+
+try:
+ import triton
+ import triton.language as tl
+except Exception: # no triton: every function below uses its torch reference
+ triton = None
+
+
+def _usable(*ts):
+ if triton is None:
+ return False
+ if os.environ.get("TRITON_INTERPRET", "0") == "1":
+ return True
+ return all(t.is_cuda for t in ts)
+
+
+# ------------------------------------------------------------------------------------------------ router
+def router_ref(logits, bias, k, w_scale):
+ """the old code (hy4_forward._ffn), verbatim maths: logits [T, E] = x @ router.T -> sel [T, k] int64, w [T, k] fp32"""
+ p = torch.sigmoid(logits)
+ sel = torch.topk(p + bias, k, dim=-1).indices
+ w = torch.gather(p, 1, sel)
+ w = w / w.sum(-1, keepdim=True).clamp(min=CLAMP_MIN) * w_scale
+ return sel, w
+
+
+if triton is not None:
+ @triton.jit
+ def _router_kernel(LG, BIAS, SEL, W, E, w_scale, clamp_min, s_lg,
+ HAS_BIAS: tl.constexpr, K: tl.constexpr, BE: tl.constexpr, BK: tl.constexpr):
+ t = tl.program_id(0)
+ offe = tl.arange(0, BE)
+ me = offe < E
+ x = tl.load(LG + t * s_lg + offe, mask=me, other=0.0).to(tl.float32)
+ p = 1.0 / (1.0 + tl.exp(-x))
+ sc = p
+ if HAS_BIAS:
+ sc = p + tl.load(BIAS + offe, mask=me, other=0.0).to(tl.float32)
+ sc = tl.where(me, sc, float("-inf"))
+ offk = tl.arange(0, BK)
+ selv = tl.zeros([BK], dtype=tl.int32)
+ pv = tl.zeros([BK], dtype=tl.float32)
+ for j in tl.static_range(K):
+ mx = tl.max(sc, axis=0)
+ idx = tl.min(tl.where(sc == mx, offe, BE), axis=0) # ties -> lowest expert id, like torch.topk
+ hit = offe == idx
+ pj = tl.sum(tl.where(hit, p, 0.0), axis=0)
+ selv = tl.where(offk == j, idx, selv)
+ pv = tl.where(offk == j, pj, pv)
+ sc = tl.where(hit, float("-inf"), sc)
+ s = tl.sum(pv, axis=0)
+ w = pv / tl.maximum(s, clamp_min) * w_scale
+ mk = offk < K
+ tl.store(SEL + t * K + offk, selv.to(tl.int64), mask=mk)
+ tl.store(W + t * K + offk, w, mask=mk)
+
+
+def router_select(logits, bias, k, w_scale):
+ """one launch: logits [T, E] fp32 (the router matmul output, unchanged) -> (sel [T, k] int64, w [T, k] fp32)"""
+ if not _usable(logits) or logits.dtype != torch.float32 or k > logits.shape[1]:
+ return router_ref(logits, bias, k, w_scale)
+ logits = logits.contiguous()
+ T, E = logits.shape
+ sel = torch.empty(T, k, dtype=torch.int64, device=logits.device)
+ w = torch.empty(T, k, dtype=torch.float32, device=logits.device)
+ has_bias = bias is not None
+ _router_kernel[(T,)](logits, bias.contiguous() if has_bias else logits, sel, w, E, float(w_scale), CLAMP_MIN, logits.stride(0),
+ HAS_BIAS=has_bias, K=k, BE=triton.next_power_of_2(E), BK=triton.next_power_of_2(k))
+ return sel, w
+
+
+# ------------------------------------------------------------------------------------------------ MLA core + sinks
+def mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None):
+ """attention_fn/mla_sinks.py:mla_sink_attend, copied verbatim (the fallback and the test reference)"""
+ s = torch.einsum("thr,nr->htn", q_lat, ckv) + torch.einsum("thp,np->htn", q_pe, k_pe)
+ s = s * scale
+ vis = kpos[None, :] <= qpos[:, None]
+ if window:
+ vis = vis & ((qpos[:, None] - kpos[None, :]) < window)
+ if allow is not None:
+ vis = vis & allow
+ s = s.masked_fill(~vis[None], float("-inf"))
+ if sinks is not None:
+ s = torch.cat([s, sinks.float()[:, None, None].expand(-1, s.shape[1], 1)], dim=-1)
+ p = torch.softmax(s, dim=-1)
+ if sinks is not None:
+ p = p[..., :-1]
+ return torch.einsum("htn,nr->thr", p, ckv)
+
+
+if triton is not None:
+ @triton.jit
+ def _mla_kernel(QL, QP, CK, KP, QPOS, KPOS, ALLOW, SINK, O, N, scale, window,
+ s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_al, s_o_t, s_o_h,
+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BP: tl.constexpr, BN: tl.constexpr,
+ HAS_SINK: tl.constexpr, HAS_ALLOW: tl.constexpr, HAS_WIN: tl.constexpr, ARANGE: tl.constexpr):
+ t = tl.program_id(0)
+ h = tl.program_id(1)
+ offr = tl.arange(0, BR)
+ offp = tl.arange(0, BP)
+ mr = offr < R
+ mp = offp < P
+ q = tl.load(QL + t * s_ql_t + h * s_ql_h + offr, mask=mr, other=0.0).to(tl.float32)
+ qp = tl.load(QP + t * s_qp_t + h * s_qp_h + offp, mask=mp, other=0.0).to(tl.float32)
+ qpos = tl.load(QPOS + t)
+ if HAS_SINK: # the sink is a key with logit s and a zero value: start the softmax from it
+ m = tl.load(SINK + h).to(tl.float32)
+ l = tl.zeros([], dtype=tl.float32) + 1.0
+ else:
+ m = tl.zeros([], dtype=tl.float32) + float("-inf")
+ l = tl.zeros([], dtype=tl.float32)
+ acc = tl.zeros([BR], dtype=tl.float32)
+ lo = 0
+ hi = N
+ if ARANGE: # kpos[j] == j: causal / window bounds skip whole blocks
+ hi = tl.minimum(N, qpos + 1)
+ if HAS_WIN:
+ lo = tl.maximum(0, qpos - window + 1) // BN * BN
+ for n0 in range(lo, hi, BN):
+ offn = n0 + tl.arange(0, BN)
+ inb = offn < N
+ if ARANGE:
+ kpos = offn
+ else:
+ kpos = tl.load(KPOS + offn, mask=inb, other=0)
+ vis = inb & (kpos <= qpos)
+ if HAS_WIN:
+ vis = vis & ((qpos - kpos) < window)
+ if HAS_ALLOW:
+ vis = vis & (tl.load(ALLOW + t * s_al + offn, mask=inb, other=0) != 0)
+ ck = tl.load(CK + offn[:, None] * s_ck + offr[None, :], mask=inb[:, None] & mr[None, :], other=0.0).to(tl.float32)
+ kp = tl.load(KP + offn[:, None] * s_kp + offp[None, :], mask=inb[:, None] & mp[None, :], other=0.0).to(tl.float32)
+ s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scale
+ s = tl.where(vis, s, float("-inf"))
+ mn = tl.maximum(m, tl.max(s, axis=0))
+ mn_s = tl.where(mn == float("-inf"), 0.0, mn)
+ alpha = tl.exp(m - mn_s)
+ pr = tl.exp(s - mn_s)
+ l = l * alpha + tl.sum(pr, axis=0)
+ acc = acc * alpha + tl.sum(pr[:, None] * ck, axis=0)
+ m = mn
+ tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)
+
+
+def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, window=0, allow=None, kpos_is_arange=False):
+ """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)
+ (the Hy4 forward always passes it so), which lets causal / window bounds skip K blocks."""
+ T, H, R = q_lat.shape
+ N, P = ckv.shape[0], k_pe.shape[1]
+ if (not _usable(q_lat, ckv) or T > MAX_T or sinks is None or N == 0 or q_lat.dtype != torch.float32 or ckv.dtype != torch.float32
+ or q_lat.stride(-1) != 1 or q_pe.stride(-1) != 1 or ckv.stride(-1) != 1 or k_pe.stride(-1) != 1):
+ return mla_sink_attend_ref(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks, window, allow)
+ out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)
+ al = allow.view(torch.uint8) if allow is not None else qpos
+ BN = 16
+ _mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, kpos, al, sinks.float().contiguous(), out, N, float(scale), int(window),
+ q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0),
+ allow.stride(0) if allow is not None else 0, out.stride(0), out.stride(1),
+ R=R, P=P, BR=triton.next_power_of_2(R), BP=triton.next_power_of_2(P), BN=BN,
+ HAS_SINK=True, HAS_ALLOW=allow is not None, HAS_WIN=bool(window), ARANGE=bool(kpos_is_arange),
+ num_warps=4)
+ return out
diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.py
new file mode 100644
index 0000000..f55c3c1
--- /dev/null
+++ b/exllamav3/loader/step_graph.py
@@ -0,0 +1,306 @@
+"""HY4_GRAPH: the whole Hy4 decode step (T = 1) captured as ONE HIP graph per context bucket (night 18/11, perf/hy4-night-graph).
+
+Why: the eager step is host / launch bound (~196 ms for ~4000 small launches; the GPU work itself is a fraction). One replay launches the
+whole step with no Python and no per-kernel host cost. Everything that changes between tokens lives in STATIC device buffers:
+ inp[0] token id, inp[1] position written by the host before each replay (one H2D of 16 bytes)
+ eng_raw / eng_valid the Engram rows of the 4 Engram layers for THIS token (host: hash + threaded pread, one H2D)
+ K buffers [cap, 576] per layer row `pos` written with index_copy_ (device index), attention reads the first Nb rows (bucket)
+ indexer pool / ring pooled key of group pos // 4 written every step; groups not complete yet are masked (gend < pos)
+The attention kernels see a fixed number of rows Nb (bucket = next multiple of HY4_GRAPH_BUCKET above pos + 1): rows past pos are masked
+by the existing `kpos <= qpos` test, so the maths is the eager maths. One graph is captured lazily per bucket (shared memory pool).
+Prefill (T > 1) stays eager. After the first graph step the eager indexer state is stale: reset (new sequence) before an eager step again.
+Generic: shapes and config come from the Hy4Forward object; nothing is keyed on a model name.
+"""
+from __future__ import annotations
+import math
+import os
+from concurrent.futures import ThreadPoolExecutor
+
+import numpy as np
+import torch
+
+from . import step_nosync as _ns
+from .engram_rows import QB, E4M3, E8M0
+
+BUCKET = int(os.environ.get("HY4_GRAPH_BUCKET", "512"))
+MASK64 = (1 << 64) - 1
+_POOL = ThreadPoolExecutor(max_workers=int(os.environ.get("HY4_GRAPH_IO", "16")))
+
+
+# ---------------------------------------------------------------------------------------------------- static indexer
+def _rms(x, w, eps):
+ x = x.float()
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
+
+
+def indexer_static_init(ix, cap):
+ """FusedKPoolIndexer -> fixed buffers: pool [cap // k, d], ring of the open group [k, 2d] (filled from the eager state), rope table to cap"""
+ k, d = ix.k, ix.d
+ rows = cap // k
+ if ix.pool.shape[0] < rows:
+ big = torch.zeros(rows, d, device=ix.dev)
+ big[:ix.P] = ix.pool[:ix.P]
+ ix.pool = big
+ ring = getattr(ix, "vgr", None)
+ if ring is None:
+ ring = torch.zeros(k, 2 * d, device=ix.dev)
+ ring.zero_() # in place: a captured graph keeps the pointer
+ if ix.vg is not None:
+ m = ix.vg.shape[0]
+ slots = (ix.n - m + torch.arange(m, device=ix.dev)) % k
+ ring[slots] = ix.vg
+ ix.vgr = ring
+ ix._max_pos = cap
+ ix._table(cap)
+
+
+def indexer_forward_static(ix, x, qr, pos, Nb, ar):
+ """x [1, E], qr [1, R], pos [1] long (device), Nb rows -> allow [1, Nb] bool. Same maths and op order as FusedKPoolIndexer.forward for one
+ token; no host value is read: group slot and rope position come from `pos`, the visible groups from a mask (gend < pos)."""
+ k, d, H = ix.k, ix.d, ix.H
+ ik = _rms(x @ ix.w["attn_k"].T, ix.w["k_norm"], ix.eps)
+ vg_new = torch.cat([ik @ ix.w["value"].T, ik @ ix.w["gate"].T], -1)
+ ix.vgr.index_copy_(0, pos % k, vg_new)
+ v, g = ix.vgr[:, :d].reshape(-1, k, d), ix.vgr[:, d:].reshape(-1, k, d)
+ p = (torch.softmax(g + ix.w["ape"][None], dim=1) * v).sum(1)
+ pooled = ix._rope(_rms(p, ix.w["pool_norm"], ix.eps), (pos // k) * k)
+ ix.pool.index_copy_(0, pos // k, pooled) # a group still open holds partial data here; it stays masked until it is complete
+ iq = ix._rope((qr @ ix.w["q_b"].T).reshape(1, H, d), pos)
+ wt = (x.float() @ ix.w["proj"].T) / math.sqrt(d * H)
+ Pb = Nb // k
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, ix.pool[:Pb]))
+ sc = (kq * wt[:, :, None]).sum(1)
+ gend = ar[:Pb] * k + (k - 1)
+ vis = (gend[None] < pos[:, None]) if ix.tail else (gend[None] <= pos[:, None])
+ sc = torch.where(vis, sc, torch.full_like(sc, -math.inf))
+ idx = torch.topk(sc, min(ix.n_top, Pb), dim=1).indices
+ gsel = torch.zeros(1, Pb, dtype=torch.bool, device=ix.dev)
+ gsel.scatter_(1, idx, True)
+ gsel &= vis
+ allow = torch.zeros(1, Nb, dtype=torch.bool, device=ix.dev)
+ allow[:, :Pb * k] = gsel.repeat_interleave(k, dim=1)
+ lo = (pos - (pos % k)) if ix.tail else (pos - ((pos + 1) % k) + 1)
+ j = ar[:Nb][None]
+ allow |= (j >= lo[:, None]) & (j <= pos[:, None])
+ return allow
+
+
+# ---------------------------------------------------------------------------------------------------- Engram, host side
+def engram_row_ids(e, tokens, p):
+ """engram_rows.engram_hash for ONE position p (same integer maths), with the token map converted once -> (ids [n_cols] int, valid [n_cols] float)"""
+ tm = getattr(e, "_tm", None)
+ if tm is None:
+ tm = e._tm = [int(t) for t in e.token_map]
+ e._tpad = int(tm[e.pad_id])
+ e._mult = [int(m) for m in e.mult]
+ e._primes = [int(m) for m in e.primes]
+ e._offs = [int(m) for m in e.offs]
+ n_tm, pad = len(tm), e._tpad
+ cid = lambda t: -1 if t < 0 or t >= n_tm else tm[t]
+ c = cid(tokens[p])
+ dead = c == -1
+ toks = [pad if dead else c]
+ for s in range(1, e.n_gram):
+ c = -1 if p - s < 0 else cid(tokens[p - s])
+ toks.append(pad if c == -1 else c)
+ rolling = (toks[0] * e._mult[0]) & MASK64
+ ids, valid = [0] * e.n_cols, [0.0 if dead else 1.0] * e.n_cols
+ for o in range(1, e.n_gram):
+ rolling ^= (toks[o] * e._mult[o]) & MASK64
+ for h in range(e.n_head):
+ col = (o - 1) * e.n_head + h
+ ids[col] = rolling % e._primes[col] + e._offs[col]
+ return ids, valid
+
+
+# ---------------------------------------------------------------------------------------------------- static context seen by Hy4Forward.layer
+class _GS:
+ def __init__(self, fw, cap):
+ self.fw, self.cap, self.Nb = fw, cap, 0
+ dev = fw.dev
+ self.inp = torch.zeros(2, dtype=torch.long, device=dev) # [token, position]
+ self.tok, self.pos = self.inp[0:1], self.inp[1:2]
+ self.ar = torch.arange(cap, device=dev)
+ self.eng_raw = self.eng_valid = None
+
+ # -- Engram: rows are staged on the host before the replay, decoded + applied inside the graph
+ def engram(self, fw, i, x):
+ e = fw.eng[i]
+ u = self.eng_raw[e.e]
+ tab = e.table
+ t4, t8 = _tabs(fw.dev)
+ if tab.layout == "plain":
+ rows = t4[u.long()]
+ else:
+ w = tab.width
+ rows = (t4[u[:, :w].long()].reshape(u.shape[0], -1, QB) * t8[u[:, w:].long()][:, :, None]).reshape(u.shape[0], w)
+ return e.apply(x, rows[None], self.eng_valid[e.e][None])
+
+ def append_kv(self, i, kn):
+ b = _ns.state(self.fw).kv[i]
+ b.index_copy_(0, self.pos, kn)
+ return b[:self.Nb]
+
+ def indexer(self, fw, i, cur, qr, N):
+ return indexer_forward_static(fw._indexer_fused(i), cur, qr, self.pos, N, self.ar)
+
+
+_T = {}
+
+
+def _tabs(dev):
+ k = str(dev)
+ if k not in _T:
+ _T[k] = (E4M3.to(dev), E8M0.to(dev))
+ return _T[k]
+
+
+class GraphDecoder:
+ def __init__(self, fw, cap=None):
+ self.fw = fw
+ self.st = _ns.state(fw)
+ self.cap = cap or self.st.cap
+ assert self.cap % BUCKET == 0 and self.cap % 4 == 0
+ self.gs = _GS(fw, self.cap)
+ self.graphs, self.pool = {}, torch.cuda.graph_pool_handle()
+ self.prepared = False
+ self.expect_n = None
+ self.hin = torch.zeros(2, dtype=torch.long).pin_memory()
+ self.stats = {"captures": 0, "replays": 0}
+ self.ev = torch.cuda.Event()
+ self.ev_set = False
+
+ # -- one-time setup (eager): weights, K buffers, indexer state, Engram modules / staging
+ def prepare(self):
+ fw, gs, st = self.fw, self.gs, self.st
+ assert fw.cache_weights and _ns.active(fw) and len(fw.res) == fw.n_layers - fw.n_dense, "graph mode needs cache_weights, HY4_NOSYNC=1 and every MoE layer resident"
+ st.ensure(self.cap)
+ if st.table is None:
+ st.table = _ns.load_table(fw.g, "token_embd.weight", fw.dev)
+ try:
+ from . import attn_eager as _AE
+ _AE.ensure(self.cap)
+ except ImportError:
+ pass
+ for i in range(fw.n_layers):
+ fw._layer(i)
+ b = st.kv.get(i)
+ if b is None or b.shape[0] < self.cap:
+ nb = torch.zeros(self.cap, 512 + 64, dtype=torch.float32, device=fw.dev) if b is None else torch.zeros(self.cap, b.shape[1], dtype=b.dtype, device=fw.dev)
+ if b is not None:
+ nb[:b.shape[0]] = b
+ st.kv[i] = nb
+ if os.environ.get("HY4_ENGRAM_GPU", "0") not in ("1", "2"):
+ raise RuntimeError("graph mode needs HY4_ENGRAM_GPU=1")
+ from .engram_gpu import Hy4EngramGPU
+ for i in sorted(fw.ple):
+ if i not in fw.eng:
+ fw.eng[i] = Hy4EngramGPU(fw.g, i, fw.dev, table=fw.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else fw._lin)
+ e0 = fw.eng[min(fw.ple)]
+ nE, nc, rb = len(fw.ple), e0.n_cols, e0.table.row_bytes
+ gs.eng_raw = torch.zeros(nE, nc, rb, dtype=torch.uint8, device=fw.dev)
+ gs.eng_valid = torch.zeros(nE, nc, dtype=torch.float32, device=fw.dev)
+ self.rpin = torch.zeros(nE, nc, rb, dtype=torch.uint8).pin_memory()
+ self.vpin = torch.zeros(nE, nc, dtype=torch.float32).pin_memory()
+ self.rnp = self.rpin.numpy()
+ for i in range(fw.n_layers):
+ if fw._layer(i).ix:
+ indexer_static_init(fw._indexer_fused(i), self.cap)
+ self.prepared = True
+
+ def reset(self):
+ """new sequence: zero the static state (buffers keep their addresses so captured graphs stay valid)"""
+ fw = self.fw
+ self.expect_n = None
+ for b in self.st.kv.values():
+ b.zero_()
+ for ix in getattr(fw, "ixf", {}).values():
+ ix.n, ix.P, ix.vg = 0, 0, None
+ ix.pool.zero_()
+ if getattr(ix, "vgr", None) is not None:
+ ix.vgr.zero_()
+
+ # -- the step body (eager warm-up and capture run exactly this)
+ def body(self):
+ fw, gs = self.fw, self.gs
+ e = _ns.gather_dequant_q8_0(self.st.table, gs.tok)
+ x = e[:, None, :].expand(-1, fw.hc, -1).contiguous()
+ for i in range(fw.n_layers):
+ x = fw.layer(i, x, gs.pos, None, 0)
+ fw._ns_dev = True
+ try:
+ lg = fw._head(x, False)
+ finally:
+ fw._ns_dev = False
+ return lg, torch.argmax(lg)
+
+ def _graph(self, Nb):
+ g = self.graphs.get(Nb)
+ if g is not None:
+ return g
+ fw, gs = self.fw, self.gs
+ gs.Nb = Nb
+ fw._gs = gs
+ try:
+ s = torch.cuda.Stream()
+ s.wait_stream(torch.cuda.current_stream())
+ with torch.cuda.stream(s):
+ for _ in range(2):
+ self.body()
+ torch.cuda.current_stream().wait_stream(s)
+ torch.cuda.synchronize()
+ cg = torch.cuda.CUDAGraph()
+ with torch.cuda.graph(cg, pool=self.pool):
+ out = self.body()
+ finally:
+ fw._gs = None
+ g = self.graphs[Nb] = (cg, out)
+ self.stats["captures"] += 1
+ return g
+
+ def stage(self, start):
+ """host side of one token: Engram hash + threaded pread of this token's rows into pinned staging, one H2D each"""
+ fw = self.fw
+ jobs = []
+ toks = fw.tokens
+ for i in sorted(fw.ple):
+ e = fw.eng[i]
+ ids, valid = engram_row_ids(e, toks, start)
+ self.vpin[e.e] = torch.tensor(valid)
+ jobs += [(e, c, r) for c, r in enumerate(ids)]
+ def rd(j):
+ e, c, r = j
+ self.rnp[e.e, c] = e.table.raw_row(r)
+ list(_POOL.map(rd, jobs))
+ self.gs.eng_raw.copy_(self.rpin, non_blocking=True)
+ self.gs.eng_valid.copy_(self.vpin, non_blocking=True)
+
+ def step(self, tok):
+ """append host token id `tok` at position fw.n; returns the DEVICE logits [V] of this position (valid until the next step)"""
+ fw = self.fw
+ if not self.prepared:
+ self.prepare()
+ start = fw.n
+ assert start < self.cap, "context past the graph cap (HY4_NOSYNC_CAP)"
+ if self.expect_n != start: # an eager prefill / reset ran since the last graph step: refill the indexer rings from its state
+ for i in range(fw.n_layers):
+ if fw._layer(i).ix:
+ indexer_static_init(fw._indexer_fused(i), self.cap)
+ if self.ev_set:
+ self.ev.synchronize() # the previous replay has read the pinned staging buffers: safe to overwrite them
+ fw.tokens.append(int(tok))
+ Nb = min(self.cap, (start // BUCKET + 1) * BUCKET)
+ self.gs.Nb = Nb
+ self.hin[0], self.hin[1] = int(tok), start
+ self.gs.inp.copy_(self.hin, non_blocking=True)
+ self.stage(start)
+ cg, _out = self._graph(Nb)
+ lg = _out[0]
+ cg.replay()
+ self.ev.record()
+ self.ev_set = True
+ fw.n += 1
+ self.expect_n = fw.n
+ self.stats["replays"] += 1
+ return lg
diff --git a/exllamav3/loader/step_nosync.py b/exllamav3/loader/step_nosync.py
new file mode 100644
index 0000000..5fb6d34
--- /dev/null
+++ b/exllamav3/loader/step_nosync.py
@@ -0,0 +1,176 @@
+"""Host-sync-free decode step driver (flag HY4_NOSYNC=1, default off). Part F of the Hy4 Strix forward.
+
+Owns only: the step driver, token history / position / K-cache bookkeeping, embedding lookup, logits -> next id, and the
+host read of the expert ids. Generic (stored Q8_0 embedding table, any [rows, R+rope] K rows); nothing here is keyed on a model name.
+Every function is only reached when active(fw) is true, so the flag-off path of hy4_forward.py is the old code, untouched.
+
+What it removes from the decode loop (per token):
+ * 41x sel.flatten().tolist() (router ids to host) when the layer's experts are resident (the result was thrown away)
+ * embed: per-token pread + CPU dequant + pageable H2D -> resident Q8_0 table on the device, gather + dequant on the device
+ * torch.arange(start, ..) per step + torch.arange(N) per layer -> slices of one preallocated device arange
+ * torch.cat([kc, kn]) per layer per step (alloc + O(N) copy) -> preallocated [cap, R+rope] buffer, append in place, view [:N]
+ * out[0].cpu() (129k floats D2H + queue drain) and int(lg.argmax()) per token -> device argmax, the id stays on the device,
+ one host read of all ids at the end of generate()
+Syncs that remain here until other parts land: fw.tokens (host list) is fed by one .tolist() per token while the Engram part
+(A) still hashes on the host (fw.engram_device_tokens is False); A sets fw.engram_device_tokens = True and reads fw._ns.tok (device history).
+"""
+import os
+import time
+
+import torch
+
+
+def enabled():
+ return os.environ.get("HY4_NOSYNC", "0") == "1"
+
+
+def active(fw):
+ return enabled() and fw.dev.type == "cuda"
+
+
+class State:
+ CAP = int(os.environ.get("HY4_NOSYNC_CAP", "4096")) # rows of the K buffers / token history; grows (host int check) when exceeded
+
+ def __init__(self, dev):
+ self.dev, self.cap = dev, State.CAP
+ self.ar = torch.arange(self.cap, device=dev) # int64, same values / dtype as torch.arange(N, device=dev)
+ self.tok = torch.zeros(self.cap, dtype=torch.long, device=dev) # device token history (for a device-side Engram hash)
+ self.kv = {} # layer -> [cap, W] buffer
+ self.table = None # resident Q8_0 embedding bytes [V, K//32*34] uint8
+
+ def ensure(self, need):
+ if need > self.cap:
+ cap = max(need, 2 * self.cap)
+ ar = torch.arange(cap, device=self.dev)
+ tok = torch.zeros(cap, dtype=torch.long, device=self.dev)
+ tok[:self.cap].copy_(self.tok)
+ self.ar, self.tok, self.cap = ar, tok, cap
+
+
+def state(fw):
+ st = getattr(fw, "_ns", None)
+ if st is None:
+ st = fw._ns = State(fw.dev)
+ return st
+
+
+# ---- embedding -------------------------------------------------------------------------------------------------------
+def load_table(g, name, dev):
+ """whole Q8_0 [V, K] tensor as raw bytes [V, K//32*34] uint8 on dev (stored bytes, ~V*K*1.0625)"""
+ import numpy as np
+ ty, dims, off = g.infos[name]
+ assert ty == 8 and dims[0] % 32 == 0, (name, ty, dims)
+ K, V = dims[0], dims[1]
+ rb = K // 32 * 34
+ raw = torch.from_numpy(np.ascontiguousarray(g._pread(off, V * rb))).reshape(V, rb)
+ return raw.to(dev)
+
+
+def gather_dequant_q8_0(table, ids):
+ """table [V, nb*34] uint8, ids [T] int -> fp32 [T, nb*32]; same arithmetic as engram_rows._dequant_q8_0 (fp16 d -> fp32, int8 q -> fp32, one multiply)"""
+ T = ids.shape[0]
+ rows = table[ids].reshape(T, -1, 34)
+ d = rows[..., :2].contiguous().view(torch.float16).float() # [T, nb, 1]
+ q = rows[..., 2:].contiguous().view(torch.int8).float() # [T, nb, 32]
+ return (q * d).reshape(T, -1)
+
+
+def embed(fw, ids_dev):
+ st = state(fw)
+ if st.table is None:
+ st.table = load_table(fw.g, "token_embd.weight", fw.dev)
+ return gather_dequant_q8_0(st.table, ids_dev)
+
+
+# ---- K cache / positions -----------------------------------------------------------------------------------------------
+def append_kv(fw, i, kn, start):
+ """K rows of layer i: write kn [T, W] at rows start..start+T-1 of a preallocated buffer, return the view [:start+T] (== torch.cat([old, kn]))"""
+ st = state(fw)
+ T = kn.shape[0]
+ need = start + T
+ b = st.kv.get(i)
+ if b is None or b.shape[0] < need:
+ nb = torch.zeros(max(st.cap, need, 2 * (b.shape[0] if b is not None else 0)), kn.shape[1], dtype=kn.dtype, device=kn.device)
+ if b is not None:
+ nb[:start].copy_(b[:start])
+ elif fw.kc[i] is not None and start > 0: # cache built by the old path before the flag was switched on
+ nb[:start].copy_(fw.kc[i])
+ b = st.kv[i] = nb
+ b[start:need].copy_(kn)
+ return b[:need]
+
+
+def kpos(fw, N):
+ st = state(fw)
+ st.ensure(N)
+ return st.ar[:N]
+
+
+# ---- router ids --------------------------------------------------------------------------------------------------------
+def skip_host_ids(fw, i, T, maxr):
+ """True when the host list of picked experts is never used: resident grouped kernel takes the device ids (hy4_forward._ffn: rs is not None)"""
+ return active(fw) and fw.res.get(i) is not None and T <= maxr
+
+
+# ---- step / generate ---------------------------------------------------------------------------------------------------
+def argmax_id(lg):
+ return torch.argmax(lg.reshape(-1)) # 0-d device tensor, stays on the device
+
+
+def step(fw, ids, all_pos=False):
+ """Hy4Forward.step with ids = list[int] (prefill, or host-fed decode) or a device int tensor [T] (the id from argmax_id). Returns DEVICE logits."""
+ st = state(fw)
+ host = not torch.is_tensor(ids)
+ if fw.tm.on:
+ torch.cuda.synchronize()
+ base = sum(fw.tm.acc.values())
+ t0 = time.time()
+ start = fw.n
+ if host:
+ fw.tokens += [int(t) for t in ids]
+ T = len(ids)
+ idt = torch.tensor(list(ids), dtype=torch.long, device=fw.dev)
+ else:
+ idt = ids.to(fw.dev, torch.long).reshape(-1)
+ T = idt.shape[0]
+ if not getattr(fw, "engram_device_tokens", False):
+ fw.tokens += idt.tolist() # the one remaining per-token sync until Engram (A) hashes on the device
+ st.ensure(start + T)
+ st.tok[start:start + T].copy_(idt)
+ pos = st.ar[start:start + T]
+ e = embed(fw, idt)
+ x = e[:, None, :].expand(-1, fw.hc, -1).contiguous()
+ for i in range(fw.n_layers):
+ x = fw.layer(i, x, pos, fw.tokens, start)
+ fw.n += T
+ fw._x = x
+ fw._ns_dev = True # _head: keep the logits on the device
+ try:
+ lg = fw.head(x, all_pos) if fw.n_layers == fw.n_trunk else None
+ finally:
+ fw._ns_dev = False
+ if fw.tm.on:
+ torch.cuda.synchronize()
+ tot = time.time() - t0
+ fw.tm.acc["other"] = fw.tm.acc.get("other", 0.0) + max(0.0, tot - (sum(fw.tm.acc.values()) - base))
+ fw.tm.last_total = tot
+ fw.stats["layer_s"] += time.time() - t0
+ return lg
+
+
+def generate(step_fn, ids, n_new):
+ """greedy loop: step_fn(ids_or_device_tensor) -> logits. The next id never leaves the device; one host read of all ids at the end."""
+ t0 = time.time()
+ lg = step_fn(ids)
+ t1 = time.time()
+ first, out = lg, []
+ nxt = argmax_id(lg)
+ for k in range(n_new):
+ out.append(nxt)
+ if k + 1 == n_new:
+ break
+ lg = step_fn(nxt.reshape(1))
+ nxt = argmax_id(lg)
+ ids_out = torch.stack(out).tolist() if out else []
+ t2 = time.time()
+ return first, ids_out, {"prefill_s": t1 - t0, "decode_s": t2 - t1, "decode_steps": max(len(ids_out) - 1, 0)}
diff --git a/exllamav3/loader/step_nosync.py.pre_graph b/exllamav3/loader/step_nosync.py.pre_graph
new file mode 100644
index 0000000..c6fcc5c
--- /dev/null
+++ b/exllamav3/loader/step_nosync.py.pre_graph
@@ -0,0 +1,176 @@
+"""Host-sync-free decode step driver (flag HY4_NOSYNC=1, default off). Part F of the Hy4 Strix forward.
+
+Owns only: the step driver, token history / position / K-cache bookkeeping, embedding lookup, logits -> next id, and the
+host read of the expert ids. Generic (stored Q8_0 embedding table, any [rows, R+rope] K rows); nothing here is keyed on a model name.
+Every function is only reached when active(fw) is true, so the flag-off path of hy4_forward.py is the old code, untouched.
+
+What it removes from the decode loop (per token):
+ * 41x sel.flatten().tolist() (router ids to host) when the layer's experts are resident (the result was thrown away)
+ * embed: per-token pread + CPU dequant + pageable H2D -> resident Q8_0 table on the device, gather + dequant on the device
+ * torch.arange(start, ..) per step + torch.arange(N) per layer -> slices of one preallocated device arange
+ * torch.cat([kc, kn]) per layer per step (alloc + O(N) copy) -> preallocated [cap, R+rope] buffer, append in place, view [:N]
+ * out[0].cpu() (129k floats D2H + queue drain) and int(lg.argmax()) per token -> device argmax, the id stays on the device,
+ one host read of all ids at the end of generate()
+Syncs that remain here until other parts land: fw.tokens (host list) is fed by one .tolist() per token while the Engram part
+(A) still hashes on the host (fw.engram_device_tokens is False); A sets fw.engram_device_tokens = True and reads fw._ns.tok (device history).
+"""
+import os
+import time
+
+import torch
+
+
+def enabled():
+ return os.environ.get("HY4_NOSYNC", "0") == "1"
+
+
+def active(fw):
+ return enabled() and fw.dev.type == "cuda"
+
+
+class State:
+ CAP = int(os.environ.get("HY4_NOSYNC_CAP", "4096")) # rows of the K buffers / token history; grows (host int check) when exceeded
+
+ def __init__(self, dev):
+ self.dev, self.cap = dev, State.CAP
+ self.ar = torch.arange(self.cap, device=dev) # int64, same values / dtype as torch.arange(N, device=dev)
+ self.tok = torch.zeros(self.cap, dtype=torch.long, device=dev) # device token history (for a device-side Engram hash)
+ self.kv = {} # layer -> [cap, W] buffer
+ self.table = None # resident Q8_0 embedding bytes [V, K//32*34] uint8
+
+ def ensure(self, need):
+ if need > self.cap:
+ cap = max(need, 2 * self.cap)
+ ar = torch.arange(cap, device=self.dev)
+ tok = torch.zeros(cap, dtype=torch.long, device=self.dev)
+ tok[:self.cap].copy_(self.tok)
+ self.ar, self.tok, self.cap = ar, tok, cap
+
+
+def state(fw):
+ st = getattr(fw, "_ns", None)
+ if st is None:
+ st = fw._ns = State(fw.dev)
+ return st
+
+
+# ---- embedding -------------------------------------------------------------------------------------------------------
+def load_table(g, name, dev):
+ """whole Q8_0 [V, K] tensor as raw bytes [V, K//32*34] uint8 on dev (stored bytes, ~V*K*1.0625)"""
+ import numpy as np
+ ty, dims, off = g.infos[name]
+ assert ty == 8 and dims[0] % 32 == 0, (name, ty, dims)
+ K, V = dims[0], dims[1]
+ rb = K // 32 * 34
+ raw = torch.from_numpy(np.ascontiguousarray(g._pread(off, V * rb))).reshape(V, rb)
+ return raw.to(dev)
+
+
+def gather_dequant_q8_0(table, ids):
+ """table [V, nb*34] uint8, ids [T] int -> fp32 [T, nb*32]; same arithmetic as engram_rows._dequant_q8_0 (fp16 d -> fp32, int8 q -> fp32, one multiply)"""
+ T = ids.shape[0]
+ rows = table[ids].reshape(T, -1, 34)
+ d = rows[..., :2].contiguous().view(torch.float16).float() # [T, nb, 1]
+ q = rows[..., 2:].contiguous().view(torch.int8).float() # [T, nb, 32]
+ return (q * d).reshape(T, -1)
+
+
+def embed(fw, ids_dev):
+ st = state(fw)
+ if st.table is None:
+ st.table = load_table(fw.g, "token_embd.weight", fw.dev)
+ return gather_dequant_q8_0(st.table, ids_dev)
+
+
+# ---- K cache / positions -----------------------------------------------------------------------------------------------
+def append_kv(fw, i, kn, start):
+ """K rows of layer i: write kn [T, W] at rows start..start+T-1 of a preallocated buffer, return the view [:start+T] (== torch.cat([old, kn]))"""
+ st = state(fw)
+ T = kn.shape[0]
+ need = start + T
+ b = st.kv.get(i)
+ if b is None or b.shape[0] < need:
+ nb = torch.empty(max(st.cap, need, 2 * (b.shape[0] if b is not None else 0)), kn.shape[1], dtype=kn.dtype, device=kn.device)
+ if b is not None:
+ nb[:start].copy_(b[:start])
+ elif fw.kc[i] is not None and start > 0: # cache built by the old path before the flag was switched on
+ nb[:start].copy_(fw.kc[i])
+ b = st.kv[i] = nb
+ b[start:need].copy_(kn)
+ return b[:need]
+
+
+def kpos(fw, N):
+ st = state(fw)
+ st.ensure(N)
+ return st.ar[:N]
+
+
+# ---- router ids --------------------------------------------------------------------------------------------------------
+def skip_host_ids(fw, i, T, maxr):
+ """True when the host list of picked experts is never used: resident grouped kernel takes the device ids (hy4_forward._ffn: rs is not None)"""
+ return active(fw) and fw.res.get(i) is not None and T <= maxr
+
+
+# ---- step / generate ---------------------------------------------------------------------------------------------------
+def argmax_id(lg):
+ return torch.argmax(lg.reshape(-1)) # 0-d device tensor, stays on the device
+
+
+def step(fw, ids, all_pos=False):
+ """Hy4Forward.step with ids = list[int] (prefill, or host-fed decode) or a device int tensor [T] (the id from argmax_id). Returns DEVICE logits."""
+ st = state(fw)
+ host = not torch.is_tensor(ids)
+ if fw.tm.on:
+ torch.cuda.synchronize()
+ base = sum(fw.tm.acc.values())
+ t0 = time.time()
+ start = fw.n
+ if host:
+ fw.tokens += [int(t) for t in ids]
+ T = len(ids)
+ idt = torch.tensor(list(ids), dtype=torch.long, device=fw.dev)
+ else:
+ idt = ids.to(fw.dev, torch.long).reshape(-1)
+ T = idt.shape[0]
+ if not getattr(fw, "engram_device_tokens", False):
+ fw.tokens += idt.tolist() # the one remaining per-token sync until Engram (A) hashes on the device
+ st.ensure(start + T)
+ st.tok[start:start + T].copy_(idt)
+ pos = st.ar[start:start + T]
+ e = embed(fw, idt)
+ x = e[:, None, :].expand(-1, fw.hc, -1).contiguous()
+ for i in range(fw.n_layers):
+ x = fw.layer(i, x, pos, fw.tokens, start)
+ fw.n += T
+ fw._x = x
+ fw._ns_dev = True # _head: keep the logits on the device
+ try:
+ lg = fw.head(x, all_pos) if fw.n_layers == fw.n_trunk else None
+ finally:
+ fw._ns_dev = False
+ if fw.tm.on:
+ torch.cuda.synchronize()
+ tot = time.time() - t0
+ fw.tm.acc["other"] = fw.tm.acc.get("other", 0.0) + max(0.0, tot - (sum(fw.tm.acc.values()) - base))
+ fw.tm.last_total = tot
+ fw.stats["layer_s"] += time.time() - t0
+ return lg
+
+
+def generate(step_fn, ids, n_new):
+ """greedy loop: step_fn(ids_or_device_tensor) -> logits. The next id never leaves the device; one host read of all ids at the end."""
+ t0 = time.time()
+ lg = step_fn(ids)
+ t1 = time.time()
+ first, out = lg, []
+ nxt = argmax_id(lg)
+ for k in range(n_new):
+ out.append(nxt)
+ if k + 1 == n_new:
+ break
+ lg = step_fn(nxt.reshape(1))
+ nxt = argmax_id(lg)
+ ids_out = torch.stack(out).tolist() if out else []
+ t2 = time.time()
+ return first, ids_out, {"prefill_s": t1 - t0, "decode_s": t2 - t1, "decode_steps": max(len(ids_out) - 1, 0)}