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 MTP draft head (blk.42): eager torch + int8 expert kernels, trunk state hook for the draft

YanissAmzf97eb5046384
diff --git a/exllamav3/loader/attn_eager.py.pre_bg b/exllamav3/loader/attn_eager.py.pre_bg
deleted file mode 100644
index 82f83e9..0000000
--- a/exllamav3/loader/attn_eager.py.pre_bg
+++ /dev/null
@@ -1,123 +0,0 @@
-"""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_eager.py.pre_qf b/exllamav3/loader/attn_eager.py.pre_qf
deleted file mode 100644
index a4b97af..0000000
--- a/exllamav3/loader/attn_eager.py.pre_qf
+++ /dev/null
@@ -1,124 +0,0 @@
-"""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
-from . import mla_bgemv as _BG
-
-_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 = m.bg_kb.mv(m._q(qn, "kb")) if (_BG.ENABLED and T == 1 and getattr(m, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))
- return m._h(qlat, "q"), m._h(qp, "q")
-
-
-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/gguf_blocks/mlp.py.pre_preclamp b/exllamav3/loader/gguf_blocks/mlp.py.pre_preclamp
deleted file mode 100644
index 6b1a799..0000000
--- a/exllamav3/loader/gguf_blocks/mlp.py.pre_preclamp
+++ /dev/null
@@ -1,227 +0,0 @@
-"""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.pre_c2 b/exllamav3/loader/hc_fused.py.pre_c2
deleted file mode 100644
index 53ef504..0000000
--- a/exllamav3/loader/hc_fused.py.pre_c2
+++ /dev/null
@@ -1,166 +0,0 @@
-"""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/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 3492482..271f402 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -635,6 +635,7 @@ class Hy4Forward:
col = (xl * pre[:, :, None]).sum(1)
self._hk("hc_head", -1, col)
h = rms(col, self.eps) * self.out_norm
+ self._h = h # the trunk state the output head reads (MTP draft input)
if self.head_cpu:
h = h.cpu()
out = head_gemm(h.float(), self.out_w)
diff --git a/exllamav3/loader/hy4_forward.py.pre_ABC b/exllamav3/loader/hy4_forward.py.pre_ABC
deleted file mode 100755
index 63c16c7..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_ABC
+++ /dev/null
@@ -1,601 +0,0 @@
-"""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
deleted file mode 100644
index d750c2b..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_DFE
+++ /dev/null
@@ -1,627 +0,0 @@
-"""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
deleted file mode 100755
index dccf62f..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_attn
+++ /dev/null
@@ -1,624 +0,0 @@
-"""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
deleted file mode 100644
index f4eb878..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_attn_eager
+++ /dev/null
@@ -1,656 +0,0 @@
-"""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_bg b/exllamav3/loader/hy4_forward.py.pre_bg
deleted file mode 100644
index 7754c9e..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_bg
+++ /dev/null
@@ -1,665 +0,0 @@
-"""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_engram b/exllamav3/loader/hy4_forward.py.pre_engram
deleted file mode 100755
index 63c16c7..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_engram
+++ /dev/null
@@ -1,601 +0,0 @@
-"""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_ffng b/exllamav3/loader/hy4_forward.py.pre_ffng
deleted file mode 100644
index 5959bd9..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_ffng
+++ /dev/null
@@ -1,669 +0,0 @@
-"""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 mla_bgemv as _BGM
-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)
- if dev.type == "cuda": # stored Q8_0 bytes of the two per-head MLA matrices (used when HY4_MLA_BG=1, T == 1)
- L.mla.bg_kb = _BGM.load(g, b + "attn_k_b.weight", L.mla.H, dev)
- L.mla.bg_vb = _BGM.load(g, b + "attn_v_b.weight", L.mla.H, dev)
- L.mla.tm = self.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_graph b/exllamav3/loader/hy4_forward.py.pre_graph
deleted file mode 100644
index 860ae63..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_graph
+++ /dev/null
@@ -1,659 +0,0 @@
-"""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
deleted file mode 100644
index 9d8cc20..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_hc
+++ /dev/null
@@ -1,607 +0,0 @@
-"""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
deleted file mode 100644
index 5406e8b..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_head
+++ /dev/null
@@ -1,662 +0,0 @@
-"""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
deleted file mode 100644
index d750c2b..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_indexer
+++ /dev/null
@@ -1,627 +0,0 @@
-"""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_kvf b/exllamav3/loader/hy4_forward.py.pre_kvf
deleted file mode 100644
index 2086696..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_kvf
+++ /dev/null
@@ -1,679 +0,0 @@
-"""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 mla_bgemv as _BGM
-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)
- if dev.type == "cuda": # stored Q8_0 bytes of the two per-head MLA matrices (used when HY4_MLA_BG=1, T == 1)
- L.mla.bg_kb = _BGM.load(g, b + "attn_k_b.weight", L.mla.H, dev)
- L.mla.bg_vb = _BGM.load(g, b + "attn_v_b.weight", L.mla.H, dev)
- L.mla.tm = self.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")]
- if os.environ.get("HY4_FFN_GROUPED", "0") == "1":
- from .attn_grouped import group_linears
- v = group_linears(L.dense[:2])
- if v is not None:
- L.dense[:2] = v
- 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")]
- if os.environ.get("HY4_FFN_GROUPED", "0") == "1":
- from .attn_grouped import group_linears
- v = group_linears([L.rdown, L.shexp[0], L.shexp[1]])
- if v is not None:
- L.rdown, L.shexp[0], L.shexp[1] = v
- 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_m1a b/exllamav3/loader/hy4_forward.py.pre_m1a
deleted file mode 100644
index 4e918ea..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_m1a
+++ /dev/null
@@ -1,315 +0,0 @@
-"""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
deleted file mode 100644
index 84bce45..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_m1b
+++ /dev/null
@@ -1,531 +0,0 @@
-"""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
deleted file mode 100644
index 0d214a6..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_m3
+++ /dev/null
@@ -1,426 +0,0 @@
-"""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
deleted file mode 100644
index 9c75028..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_nosync
+++ /dev/null
@@ -1,645 +0,0 @@
-"""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
deleted file mode 100644
index 17523a9..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_ref
+++ /dev/null
@@ -1,650 +0,0 @@
-"""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
deleted file mode 100644
index d750c2b..0000000
--- a/exllamav3/loader/hy4_forward.py.pre_ref_mistake
+++ /dev/null
@@ -1,627 +0,0 @@
-"""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
deleted file mode 100755
index 978f5b8..0000000
--- a/exllamav3/loader/hy4_forward.py.with_ref_mistake
+++ /dev/null
@@ -1,633 +0,0 @@
-"""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.pre_graph b/exllamav3/loader/indexer_fused.py.pre_graph
deleted file mode 100644
index 5cbbeed..0000000
--- a/exllamav3/loader/indexer_fused.py.pre_graph
+++ /dev/null
@@ -1,117 +0,0 @@
-"""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 2935beb..d17624c 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -22,6 +22,9 @@ def _sinks_mod():
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]
+ if ty == 30: # BF16 (the MTP block): stored [ne2][ne1][ne0] row-major
+ raw = g._pread(off, dims[0] * dims[1] * dims[2] * 2)
+ return torch.from_numpy(raw.copy()).view(torch.bfloat16).float().reshape(h, dims[1], dims[0])
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])
diff --git a/exllamav3/loader/mla_hy4.py.pre_DFE b/exllamav3/loader/mla_hy4.py.pre_DFE
deleted file mode 100644
index 018d86c..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_DFE
+++ /dev/null
@@ -1,135 +0,0 @@
-"""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
deleted file mode 100644
index 6a8547e..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_attn_eager
+++ /dev/null
@@ -1,140 +0,0 @@
-"""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_bg b/exllamav3/loader/mla_hy4.py.pre_bg
deleted file mode 100644
index 61b627a..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_bg
+++ /dev/null
@@ -1,147 +0,0 @@
-"""CPU fp32 reference of the Hy4-flash attention layer (registry blocks mla + mla_window_sinks + mla_output_gate; design
-HY4_STRIX_DESIGN.md section 2). Maths of llama.cpp hy-v4-flash.cpp build_attention (patch M:5787-5947), config from the GGUF
-header keys and the per-layer tensors only. Weights are dequantised once (Q8_0 / F32); the ForeignLinear path is a later step.
-Only relative import: loader/engram_rows.py (tests load both by path)."""
-from __future__ import annotations
-import importlib.util, os
-import torch
-from .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rms
-from . import ref_fused as _rf
-from . import attn_eager as _ae
-
-
-def _sinks_mod():
- p = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "modules", "attention_fn", "mla_sinks.py")
- spec = importlib.util.spec_from_file_location("exl_mla_sinks", p)
- m = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(m)
- return m
-
-
-def _dense3(g, name, h):
- """GGUF 3-D Q8_0 tensor (ne0, ne1, h) -> [h, ne1, ne0] fp32 (ggml_mul_mat(w, x): out[h, j] = sum_k w[h, j, k] x[k])"""
- ty, dims, off = g.infos[name]
- assert ty == 8 and dims[2] == h, (name, ty, dims)
- return _dequant_q8_0(g._pread(off, dims[1] * dims[2] * (dims[0] // 32) * 34), dims[0], dims[1] * dims[2]).view(h, dims[1], dims[0])
-
-
-def rope_norm(x: torch.Tensor, pos: torch.Tensor, base: float) -> torch.Tensor:
- """ggml_rope_ext mode NORM (consecutive pairs), n_dims = x.shape[-1], no scaling / yarn: x [T, ..., P], pos [T]"""
- P = x.shape[-1]
- th = pos.double()[:, None] * (base ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=pos.device) / P))[None, :] # [T, P/2]
- c, s = th.cos().float().to(x.device), th.sin().float().to(x.device)
- shp = (x.shape[0],) + (1,) * (x.dim() - 2) + (P // 2,)
- c, s = c.view(shp), s.view(shp)
- x0, x1 = x[..., 0::2], x[..., 1::2]
- out = torch.empty_like(x)
- out[..., 0::2], out[..., 1::2] = x0 * c - x1 * s, x0 * s + x1 * c
- return out
-
-
-class Hy4MLA:
- """One attention layer: cur [T, n_embd] (normed collapsed stream) -> kqv / gated / out, with a K cache the caller keeps."""
-
- def __init__(self, g, layer: int, q8_act: bool = False, f16_kv: bool = False, lin=None):
- m = g.meta
- p = m["general.architecture"] + "."
- b = f"blk.{layer}."
- self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
- lin = lin or (lambda n: load_dense(g, n)) # lin(name) -> fp32 [N, K] or a QLinear (stored bytes, hy4_forward.py)
- self.H = int(list(m[p + "attention.head_count"])[layer])
- self.hd, self.vd = m[p + "attention.key_length_mla"], m[p + "attention.value_length_mla"]
- self.rope_dim, self.R = m[p + "rope.dimension_count"], m[p + "attention.kv_lora_rank"]
- self.nope = self.hd - self.rope_dim
- pat = m.get(p + "attention.sliding_window_pattern")
- self.swa = bool(list(pat)[layer]) if pat is not None else False
- self.window = int(m[p + "attention.sliding_window"]) if self.swa else 0
- self.theta = float(m[p + ("rope.freq_base_swa" if self.swa else "rope.freq_base")])
- self.eps = float(m[p + "attention.layer_norm_rms_epsilon"])
- self.scale = 1.0 / float(self.hd) ** 0.5
- self.wq_a, self.q_a_norm = lin(b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
- self.wq_b = lin(b + "attn_q_b.weight")
- self.wkv_a, self.kv_a_norm = lin(b + "attn_kv_a_mqa.weight"), load_dense(g, b + "attn_kv_a_norm.weight")
- self.wk_b, self.wv_b = _dense3(g, b + "attn_k_b.weight", self.H), _dense3(g, b + "attn_v_b.weight", self.H)
- self.wo, self.wgate = lin(b + "attn_output.weight"), lin(b + "attn_gate.weight")
- pn = b + POST_NORM
- self.post_norm = load_dense(g, pn) if pn in g.infos else None
- sk = b + "attn_sinks.weight"
- self.sinks = load_dense(g, sk) if sk in g.infos else None
- self.S = _sinks_mod()
-
- tm = type("_NoTm", (), {"t": staticmethod(lambda n: __import__("contextlib").nullcontext())})() # replaced by Hy4Forward._Tm
- q8_skip: tuple = () # matmul tags (wq_a wq_b wkv_a kb vb wgate wo) whose activation is NOT quantised (diagnostics)
- f16_parts: tuple = ("q", "k")
-
- def _q(self, x, tag=None): # activation of a Q8_0 mul_mat (llama.cpp CPU vec_dot_type)
- return q8_0_roundtrip(x) if self.q8_act and tag not in self.q8_skip else x
-
- def _h(self, x, part="k"):
- return x.half().float() if self.f16_kv and part in self.f16_parts else x
-
- def kv(self, cur, pos):
- """cur [T, n_embd], pos [T] -> K cache rows [T, R + rope] = [rms(kv_a)*w | rope(k_pe)] (V is the first R columns)"""
- if _ae.ENABLED: # HY4_ATTN_EAGER: table rope, no cat
- return _ae.kv(self, cur, pos)
- c = self._q(cur, "wkv_a") @ self.wkv_a.T
- lat = rms(c[:, :self.R], self.eps) * self.kv_a_norm
- pe = rope_norm(c[:, self.R:], pos, self.theta)
- return self._h(torch.cat([lat, pe], -1))
-
- def q(self, cur, pos):
- """-> q_lat [T,H,R], q_pe [T,H,rope] (q_nope absorbed with k_b; rope on the pe part)"""
- if _ae.ENABLED:
- return _ae.q(self, cur, pos)
- T, H = cur.shape[0], self.H
- qr = rms(self._q(cur, "wq_a") @ self.wq_a.T, self.eps) * self.q_a_norm
- q = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)
- qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)
- qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))
- return self._h(qlat, "q"), self._h(qp, "q")
-
- def attend(self, cur, pos, kcache, kpos, allow=None):
- """cur [T, n_embd] at positions pos; kcache [N, R+rope] at kpos (includes the T new rows). -> (kqv, gated, out)"""
- T, H = cur.shape[0], self.H
- tm = self.tm
- with tm.t("attn proj"):
- qlat, qpe = self.q(cur, pos)
- with tm.t("MLA core + sinks"):
- if _rf.ENABLED: # HY4_REF_FUSED=1: one online-softmax kernel (sinks / window / allow inside)
- o = _rf.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow,
- kpos_is_arange=getattr(self, "kpos_arange", False))
- else:
- o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)
- with tm.t("attn proj"):
- kqv = torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb")).reshape(T, H * self.vd)
- gated, out = self.gate_out(cur, kqv)
- return kqv, gated, out
-
- def gate_out(self, cur, kqv):
- """isolated tail (gate, then wo, then post norm): oracle attn_kqv + cur -> (gated, out)"""
- gated = self.S.sigmoid_gate(kqv, self._q(cur, "wgate") @ self.wgate.T)
- out = self._q(gated, "wo") @ self.wo.T
- if _ae.RMS and self.post_norm is not None: # HY4_ATTN_EAGER=2
- return gated, _ae.rmsw(out, self.post_norm, self.eps)
- return gated, (rms(out, self.eps) * self.post_norm if self.post_norm is not None else out)
-
-
-POST_NORM = "post_attention_norm.weight"
-
-
-class Hy4HCPre:
- """hc_pre (M:5383-5418) + reduce + attn_norm: stream [T, hc, n_embd] -> normed collapsed cur [T, n_embd] and pre weights [T, hc]"""
-
- def __init__(self, g, layer: int):
- m = g.meta
- p = m["general.architecture"] + "."
- b = f"blk.{layer}."
- self.hc, self.eps = m[p + "hyper_connection.count"], float(m[p + "attention.layer_norm_rms_epsilon"])
- self.hc_eps = float(m[p + "hyper_connection.epsilon"])
- self.fn, self.base, self.scale = load_dense(g, b + "hc_attn_fn.weight"), load_dense(g, b + "hc_attn_base.weight"), load_dense(g, b + "hc_attn_scale.weight")
- self.norm = load_dense(g, b + "attn_norm.weight")
-
- def __call__(self, x):
- T = x.shape[0]
- mixes = rms(x.reshape(T, -1), self.eps) @ self.fn.T
- pre = torch.sigmoid(mixes[:, :self.hc] * self.scale[0] + self.base[:self.hc]) + self.hc_eps
- cur = (x * pre[:, :, None]).sum(1)
- return rms(cur, self.eps) * self.norm, pre
diff --git a/exllamav3/loader/mla_hy4.py.pre_dev b/exllamav3/loader/mla_hy4.py.pre_dev
deleted file mode 100644
index 17a6ee0..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_dev
+++ /dev/null
@@ -1,129 +0,0 @@
-"""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
deleted file mode 100644
index cea356e..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_ft
+++ /dev/null
@@ -1,129 +0,0 @@
-"""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
deleted file mode 100644
index ae410e7..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_m1a
+++ /dev/null
@@ -1,129 +0,0 @@
-"""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
deleted file mode 100644
index 5e66a9b..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_m3
+++ /dev/null
@@ -1,134 +0,0 @@
-"""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
deleted file mode 100644
index 018d86c..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_ref
+++ /dev/null
@@ -1,135 +0,0 @@
-"""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
deleted file mode 100644
index 018d86c..0000000
--- a/exllamav3/loader/mla_hy4.py.pre_ref_mistake
+++ /dev/null
@@ -1,135 +0,0 @@
-"""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
deleted file mode 100644
index 6a8547e..0000000
--- a/exllamav3/loader/mla_hy4.py.with_ref_mistake
+++ /dev/null
@@ -1,140 +0,0 @@
-"""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/moe_i8.py b/exllamav3/loader/moe_i8.py
new file mode 100644
index 0000000..c30561f
--- /dev/null
+++ b/exllamav3/loader/moe_i8.py
@@ -0,0 +1,86 @@
+"""int8 (per output row scale) routed-expert stacks for the MTP draft head + two Triton kernels (decode, one row).
+
+The draft layer's experts are stored bf16 in the GGUF (3 x 2.25 GiB). A draft only changes the acceptance rate, never the output (the trunk
+verifies every token), so the stacks are quantised on load: w ~ q * s, q int8, s fp32 per output row (max |w| / 127). 1.1 GiB per stack.
+
+ gate_up(z [K], sel [S]) -> h [S, N] h[s] = silu(min(Wg[e] z, lim)) * clamp(Wu[e] z, -lim, lim) e = sel[s]
+ down(h [S, N], sel, w [S]) -> lat [N] lat = sum_s w[s] * (Wd[e_s] h[s])
+Weights are [E, N, K] row-major (ggml ne0 = K fastest), K = N = 1536 here; generic in (E, N, K)."""
+import numpy as np
+import torch
+import triton
+import triton.language as tl
+
+
+class Int8Stack:
+ def __init__(self, g, name, dev, chunk_experts=16):
+ ty, dims, off = g.infos[name]
+ assert ty == 30 and len(dims) == 3, (name, ty, dims)
+ K, N, E = dims
+ self.E, self.N, self.K = E, N, K
+ self.q = torch.empty(E, N, K, dtype=torch.int8, device=dev)
+ self.s = torch.empty(E, N, dtype=torch.float32, device=dev)
+ per = N * K * 2
+ for e0 in range(0, E, chunk_experts):
+ n = min(chunk_experts, E - e0)
+ raw = torch.from_numpy(np.array(g._pread(off + e0 * per, n * per))).to(dev)
+ w = raw.view(torch.bfloat16).float().reshape(n, N, K)
+ s = w.abs().amax(-1).clamp_min(1e-12) / 127.0
+ self.q[e0:e0 + n] = torch.round(w / s[..., None]).clamp(-127, 127).to(torch.int8)
+ self.s[e0:e0 + n] = s
+
+
+def _k_gu(wg_ptr, wu_ptr, sg_ptr, su_ptr, sel_ptr, z_ptr, h_ptr, N, K, lim, BN: tl.constexpr, BK: tl.constexpr):
+ s = tl.program_id(0)
+ rows = tl.program_id(1) * BN + tl.arange(0, BN)
+ rm = rows < N
+ e = tl.load(sel_ptr + s).to(tl.int64)
+ accg = tl.zeros([BN], dtype=tl.float32)
+ accu = tl.zeros([BN], dtype=tl.float32)
+ base = (e * N + rows)[:, None] * K
+ for k0 in range(0, K, BK):
+ cols = k0 + tl.arange(0, BK)
+ cm = cols < K
+ m2 = rm[:, None] & cm[None, :]
+ zv = tl.load(z_ptr + cols, mask=cm, other=0.0)
+ wg = tl.load(wg_ptr + base + cols[None, :], mask=m2, other=0).to(tl.float32)
+ wu = tl.load(wu_ptr + base + cols[None, :], mask=m2, other=0).to(tl.float32)
+ accg += tl.sum(wg * zv[None, :], axis=1)
+ accu += tl.sum(wu * zv[None, :], axis=1)
+ sg = tl.load(sg_ptr + e * N + rows, mask=rm, other=0.0)
+ su = tl.load(su_ptr + e * N + rows, mask=rm, other=0.0)
+ g = tl.minimum(accg * sg, lim)
+ u = tl.minimum(tl.maximum(accu * su, -lim), lim)
+ tl.store(h_ptr + s * N + rows, g * (1.0 / (1.0 + tl.exp(-g))) * u, mask=rm)
+
+
+def _k_down(wd_ptr, sd_ptr, sel_ptr, h_ptr, w_ptr, o_ptr, N, K, S: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):
+ rows = tl.program_id(0) * BN + tl.arange(0, BN)
+ rm = rows < N
+ out = tl.zeros([BN], dtype=tl.float32)
+ for s in tl.static_range(S):
+ e = tl.load(sel_ptr + s).to(tl.int64)
+ ws = tl.load(w_ptr + s)
+ acc = tl.zeros([BN], dtype=tl.float32)
+ base = (e * N + rows)[:, None] * K
+ for k0 in range(0, K, BK):
+ cols = k0 + tl.arange(0, BK)
+ cm = cols < K
+ m2 = rm[:, None] & cm[None, :]
+ hv = tl.load(h_ptr + s * K + cols, mask=cm, other=0.0)
+ wd = tl.load(wd_ptr + base + cols[None, :], mask=m2, other=0).to(tl.float32)
+ acc += tl.sum(wd * hv[None, :], axis=1)
+ out += ws * acc * tl.load(sd_ptr + e * N + rows, mask=rm, other=0.0)
+ tl.store(o_ptr + rows, out, mask=rm)
+
+
+def experts_forward(gate, up, down, z, sel, w, lim):
+ """z [K] fp32, sel [S] int64 device, w [S] fp32 -> lat [N] fp32 (K = gate/up K, N = gate/up N = down K, down N = latent)"""
+ S = sel.numel()
+ h = torch.empty(S, gate.N, dtype=torch.float32, device=z.device)
+ _k_gu[(S, triton.cdiv(gate.N, 16))](gate.q, up.q, gate.s, up.s, sel, z, h, gate.N, gate.K, lim, BN=16, BK=128, num_warps=4)
+ out = torch.empty(down.N, dtype=torch.float32, device=z.device)
+ _k_down[(triton.cdiv(down.N, 8),)](down.q, down.s, sel, h, w, out, down.N, down.K, S=S, BN=8, BK=128, num_warps=4)
+ return out
diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.py
new file mode 100644
index 0000000..cc2931b
--- /dev/null
+++ b/exllamav3/loader/mtp_head.py
@@ -0,0 +1,105 @@
+"""Hy4 MTP draft head (the GGUF's next-n block blk.<n_trunk>): eager torch + two Triton expert kernels. Night 18/11.
+
+One ordinary decoder layer of the trunk's class WITHOUT hyper-connection streams (plain residuals, sandwich norms) plus four tensors:
+ x = eh_proj( cat[ enorm(embed(token j+1)), hnorm(h_j) ] ) h_j = the trunk state the output head reads (after the hc head + output_norm)
+ s1 = x + attn(rms(x) * attn_norm); s2 = s1 + rms(moe(rms(s1) * ffn_norm)) * post_ffw_norm
+ y = shared_head_norm(s2); logits = trunk output head(y); the next chain step feeds y as `h`
+(llama.cpp hy-v4-flash.cpp graph_mtp; the Mac port kyojin_mlx/hy4_mtp.py.) The layer owns a full-attention MLA with its own K cache and an indexer.
+Weights are bf16 in the GGUF: dense ones are used as fp32 (draft quality only moves the acceptance rate, never the output: the trunk verifies),
+the 512-expert stacks are quantised on load to int8 + per-row scale (moe_i8.py). K rows and indexer state are written BY POSITION (index_copy_),
+so a rejected draft row is simply overwritten by the next round. Greedy chain only (argmax of the head logits)."""
+from __future__ import annotations
+
+import torch
+
+from . import moe_i8 as MI
+from . import step_graph as SG
+from . import step_nosync as _ns
+from .engram_rows import load_dense, rms
+from .hy4_forward import _mv, head_gemm
+from .indexer_fused import FusedKPoolIndexer
+from .mla_hy4 import Hy4MLA
+
+
+class Hy4MTP:
+ def __init__(self, fw, cap=None):
+ g, dev, il = fw.g, fw.dev, fw.n_trunk
+ b = f"blk.{il}."
+ self.fw, self.il, self.dev, self.eps = fw, il, dev, fw.eps
+ d = lambda n: load_dense(g, b + n).to(dev)
+ self.eh, self.enorm, self.hnorm, self.shn = d("nextn.eh_proj.weight"), d("nextn.enorm.weight"), d("nextn.hnorm.weight"), d("nextn.shared_head_norm.weight")
+ mla = Hy4MLA(g, il, lin=lambda n: load_dense(g, n))
+ _mv(mla, dev, torch.float32)
+ mla.post_norm, mla.sinks = mla.post_norm.to(dev), mla.sinks.to(dev)
+ mla.kpos_arange = True
+ mla.tm = fw.tm
+ self.mla = mla
+ self.attn_norm, self.ffn_norm, self.post_ffw = d("attn_norm.weight"), d("ffn_norm.weight"), d("post_ffw_norm.weight")
+ self.router, self.rbias = d("ffn_gate_inp.weight"), d("exp_probs_b.bias")
+ self.rdown, self.rup = d("ffn_routed_down.weight"), d("ffn_routed_up.weight")
+ self.shexp = [d(f"ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]
+ self.ex = [MI.Int8Stack(g, b + f"ffn_{n}_exps.weight", dev) for n in ("gate", "up", "down")]
+ self.lim = float(fw.clamp[il])
+ 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"}
+ self.ix = FusedKPoolIndexer({k: d(s) for k, s in names.items()}, dev, **fw.ixc)
+ st = _ns.state(fw)
+ self.cap = cap or st.cap
+ self.ar = st.ar if st.ar.shape[0] >= self.cap else torch.arange(self.cap, device=dev)
+ self.kbuf = torch.zeros(self.cap, mla.R + mla.rope_dim, device=dev)
+ SG.indexer_static_init(self.ix, self.cap)
+ try:
+ from . import attn_eager as _AE
+ _AE.ensure(self.cap)
+ except ImportError:
+ pass
+
+ def reset(self):
+ self.kbuf.zero_()
+ self.ix.n, self.ix.P, self.ix.vg = 0, 0, None
+ self.ix.pool.zero_()
+ self.ix.vgb.zero_()
+
+ def ffn(self, x):
+ fw = self.fw
+ p = torch.sigmoid(x @ self.router.T)
+ sel = torch.topk(p + self.rbias, fw.topk, dim=-1).indices
+ w = torch.gather(p, 1, sel)
+ w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * fw.w_scale
+ z = x @ self.rdown.T
+ lat = MI.experts_forward(self.ex[0], self.ex[1], self.ex[2], z[0].contiguous(), sel[0].contiguous(), w[0].contiguous(), self.lim)
+ gt, up, dn = self.shexp
+ sh = (torch.nn.functional.silu(x @ gt.T) * (x @ up.T)) @ dn.T
+ return lat[None] @ self.rup.T + sh
+
+ @torch.no_grad()
+ def step(self, tok, h, pos, N):
+ """tok device long [1] (token j+1), h [1, D] (trunk state h_j, or the previous y of the chain), pos device long [1] (= j), N rows attended (multiple of 4,
+ > j) -> y [1, D], logits [V]"""
+ fw, mla, eps = self.fw, self.mla, self.eps
+ e = _ns.embed(fw, tok)
+ x = torch.cat([rms(e, eps) * self.enorm, rms(h, eps) * self.hnorm], -1) @ self.eh.T
+ cur = rms(x, eps) * self.attn_norm
+ self.kbuf.index_copy_(0, pos, mla.kv(cur, pos))
+ qr = rms(mla._q(cur, "wq_a") @ mla.wq_a.T, eps) * mla.q_a_norm
+ allow = SG.indexer_forward_static(self.ix, cur, qr, pos, N, self.ar)
+ kqv, gated, out = mla.attend(cur, pos, self.kbuf[:N], self.ar[:N], allow)
+ s1 = x + out
+ f = self.ffn(rms(s1, eps) * self.ffn_norm)
+ s2 = s1 + rms(f, eps) * self.post_ffw
+ y = rms(s2, eps) * self.shn
+ return y, head_gemm(y.float(), fw.out_w)[0]
+
+ def chain(self, tok_next, h, j, k):
+ """greedy chain of k drafts from the pair (token j+1 = tok_next [device long [1]], trunk state h at position j): head rows j .. j+k-1 are written
+ (row j is the committed pair, the others are scratch). -> list of k device long [1] tensors"""
+ outs, tok = [], tok_next
+ for i in range(k):
+ jj = j + i
+ N = ((jj + 1 + 3) // 4) * 4
+ y, lg = self.step(tok, h, self.ar[jj:jj + 1], N)
+ tok = torch.argmax(lg).reshape(1)
+ outs.append(tok)
+ h = y
+ return outs
diff --git a/exllamav3/loader/ref_fused.py.pre_sub b/exllamav3/loader/ref_fused.py.pre_sub
deleted file mode 100644
index 495495f..0000000
--- a/exllamav3/loader/ref_fused.py.pre_sub
+++ /dev/null
@@ -1,180 +0,0 @@
-"""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
index ec4c00b..d6e95cd 100644
--- a/exllamav3/loader/step_graph.py
+++ b/exllamav3/loader/step_graph.py
@@ -252,7 +252,7 @@ class GraphDecoder:
lg = fw._head(x, False)
finally:
fw._ns_dev = False
- return lg, torch.argmax(lg), x
+ return lg, torch.argmax(lg), x, fw._h
def _graph(self, Nb):
g = self.graphs.get(Nb)
@@ -317,6 +317,7 @@ class GraphDecoder:
cg, _out = self._graph(Nb)
lg = _out[0]
self.x_out = _out[2]
+ fw._h = _out[3]
cg.replay()
self.ev.record()
self.ev_set = True
diff --git a/exllamav3/loader/step_nosync.py.pre_graph b/exllamav3/loader/step_nosync.py.pre_graph
deleted file mode 100644
index c6fcc5c..0000000
--- a/exllamav3/loader/step_nosync.py.pre_graph
+++ /dev/null
@@ -1,176 +0,0 @@
-"""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)}