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.

GGUF registry: Hy4 hyper-connections (identity-comb HC, HC with post norms, hyper head)

YanissAmz71da75b1029f
diff --git a/exllamav3/architecture/gguf_generic.py b/exllamav3/architecture/gguf_generic.py
index 6545cbe..3619f08 100644
--- a/exllamav3/architecture/gguf_generic.py
+++ b/exllamav3/architecture/gguf_generic.py
@@ -77,6 +77,9 @@ def name_map_generic(cfg: dict, plan=None) -> dict:
for slot in ("embed", "head"):
b = REGISTRY[plan.glob[slot]]
nm.update(b.names(cfg, None, None, None))
+ for bn in plan.glob["head_mod"]:
+ if REGISTRY[bn].names is not None:
+ nm.update(REGISTRY[bn].names(cfg, None, None, None))
for i in range(cfg["num_hidden_layers"]):
L, G = f"model.layers.{i}", f"blk.{i}"
for bn in plan.blocks_at(i):
@@ -105,11 +108,11 @@ def _fl(config, eng_key: str, i: int, o: int, out_dtype=None, bias=False, **kw):
gname = config.gguf.name_map[eng_key + ".weight"]
base = re.sub(r"\.e\d+(\.weight)$", r"\1", gname) if "_exps.e" in gname else gname
fmt = config.gguf_formats[base]
+ if fmt == "f8_e4m3":
+ raise GenericUnsupported(f"{base}: ggml F8_E4M3 (type 43) is a row-lookup-only type (loader/engram_rows.F8Rows), not a Linear")
if fmt == "fp" or fmt.startswith("unk"):
raise GenericUnsupported(f"{base}: ggml type {fmt!r} has no ForeignLinear format (add it to GGML_FMT)")
if bias:
- if fmt == "f8_e4m3":
- raise GenericUnsupported(f"{base}: ggml F8_E4M3 (type 43) is a row-lookup-only type (loader/engram_rows.F8Rows), not a Linear")
# Linear.load_gguf_ builds the ForeignLinear on the stored blocks and loads <key>.bias into _ForeignInner (inner.bias / inner.fl,
# what the grouped MXFP4 MoE path and Attention read). pad_to=1: the GGUF payload is not padded to 128 (gpt-oss 2880).
from ..modules.linear import Linear
@@ -238,6 +241,9 @@ class GGUFGenericModel(Model):
mlp = _built(lp["ffn"]).build(config, plan, idx, L)
self.modules += [_built(lp["stream"]).build(config, plan, idx, L, attn, mlp)]
self.last_kv_module_idx = len(self.modules) - 1
+ for bn in plan.glob["head_mod"]: # global head modifiers (the HC stream collapse) run before the final norm
+ if _built(bn).build is not CONFIG_ONLY:
+ self.modules += _built(bn).build(config, P)
self.modules += _built(plan.glob["head"]).build(config, P)
self.logit_layer_idx = len(self.modules) - 1
diff --git a/exllamav3/loader/gguf_blocks/hyperconnections.py b/exllamav3/loader/gguf_blocks/hyperconnections.py
index 99123d5..5d92e69 100644
--- a/exllamav3/loader/gguf_blocks/hyperconnections.py
+++ b/exllamav3/loader/gguf_blocks/hyperconnections.py
@@ -1,7 +1,7 @@
"""Blocks around modules/hyperconnections.py: HyperConnection stream (comb = identity, or Sinkhorn mHC) and HyperHead.
-Predicates + configs only (Hy4 step 5)."""
+Selection is by keys / tensors only. Builds: the per-site HC modules (build_site) and the head reduction (hyper_head)."""
from __future__ import annotations
-from ..gguf_registry import Block, register
+from ..gguf_registry import Block, register, GenericUnsupported
_RESID_NORMS = ("attn_norm.weight", "ffn_norm.weight", "post_attention_norm.weight", "post_ffw_norm.weight")
@@ -24,15 +24,88 @@ def hc_layer(ctx, i):
"mode": mode, "norms": [s for s in _RESID_NORMS if ctx.has(i, s)]}
+def _site_names(cfg, i, L, G):
+ return {f"{L}.hc_{s}_{t}": f"{G}.hc_{s}_{t}.weight" for s in ("attn", "ffn") for t in ("fn", "base", "scale")}
+
+
+def build_site(config, plan, idx, L, tag):
+ """one HC site module (tag attn | ffn) from the layer's hyper_connection config; tensors {L}.hc_<tag>_fn / _base / _scale"""
+ from ...modules.hyperconnections import HyperConnection, HyperConnectionPP
+ c = plan.configs[("hyper_connection", idx)]
+ kw = dict(config=config, key=f"{L}.hc_{tag}", hc_mult=c["count"], hidden_size=config.hidden_size,
+ hc_eps=c["eps"], rms_norm_eps=config.rms_norm_eps)
+ if c["mode"] == "identity":
+ return HyperConnectionPP(**kw, magnitude=c["magnitude"] if c["magnitude"] is not None else 2.0)
+ if c["mode"] == "sinkhorn":
+ if c["magnitude"] not in (None, 2.0):
+ raise GenericUnsupported(f"hyper_connection.magnitude {c['magnitude']} (the Sinkhorn HyperConnection hard-codes 2.0)")
+ return HyperConnection(**kw, sinkhorn_iters=c["sinkhorn_iterations"])
+ raise GenericUnsupported(f"hyper_connection layout not recognised at layer {idx}: fn dims {c['fn_dims']}, "
+ f"sinkhorn_iterations {c['sinkhorn_iterations']}")
+
+
+def _stream_names(cfg, i, L, G):
+ """sites + the norms of the layer: attn_norm / ffn_norm before the sublayers, post_attention_norm / post_ffw_norm on their output"""
+ nm = _site_names(cfg, i, L, G)
+ norms = cfg.get("norms") or []
+ for e, g in (("input_layernorm", "attn_norm"), ("post_attention_layernorm", "ffn_norm")):
+ if f"{g}.weight" in norms:
+ nm[f"{L}.{e}.weight"] = f"{G}.{g}.weight"
+ if "post_attention_norm.weight" in norms and "post_ffw_norm.weight" in norms:
+ nm[f"{L}.attn_post_norm.weight"] = f"{G}.post_attention_norm.weight"
+ nm[f"{L}.mlp_post_norm.weight"] = f"{G}.post_ffw_norm.weight"
+ return nm
+
+
+def _stream_build(config, plan, idx, L, attn, mlp):
+ """TransformerBlock with the HC sites. Order (llama.cpp hy_v4_flash, M:6064-6091): collapse (pre) -> attn_norm -> attn ->
+ post_attention_norm -> post mix into the streams; the same with ffn_norm / ffn / post_ffw_norm. Engram is outside the block
+ (it writes the streams before the attn pre-mix, M:6059)."""
+ import torch
+ from ...modules import RMSNorm, TransformerBlock
+ norms = plan.configs[("hyper_connection", idx)]["norms"]
+ if "attn_norm.weight" not in norms or "ffn_norm.weight" not in norms:
+ raise GenericUnsupported(f"hyper_connection layer {idx}: attn_norm / ffn_norm missing ({norms})")
+ sandwich = "post_attention_norm.weight" in norms and "post_ffw_norm.weight" in norms
+ if ("post_attention_norm.weight" in norms) != ("post_ffw_norm.weight" in norms):
+ raise GenericUnsupported(f"hyper_connection layer {idx}: only one of post_attention_norm / post_ffw_norm ({norms})")
+ eps = config.rms_norm_eps
+ post = {}
+ if sandwich:
+ post = dict(attn_post_norm=RMSNorm(config=config, key=f"{L}.attn_post_norm", rms_norm_eps=eps, out_dtype=torch.float),
+ mlp_post_norm=RMSNorm(config=config, key=f"{L}.mlp_post_norm", rms_norm_eps=eps, out_dtype=torch.float))
+ return TransformerBlock(config=config, key=L, layer_idx=idx,
+ attn_hc=build_site(config, plan, idx, L, "attn"),
+ attn_norm=RMSNorm(config=config, key=f"{L}.input_layernorm", rms_norm_eps=eps), attn=attn,
+ mlp_hc=build_site(config, plan, idx, L, "ffn"),
+ mlp_norm=RMSNorm(config=config, key=f"{L}.post_attention_layernorm", rms_norm_eps=eps), mlp=mlp,
+ **post)
+
+
register(Block(
- "hyper_connection", "stream", step="step 5", priority=1,
+ "hyper_connection", "stream", step="step 5", priority=1, names=_stream_names,
select=lambda ctx, i: bool(ctx.key("hyper_connection.count")) and ctx.has(i, "hc_attn_fn.weight"),
config=hc_layer,
claims=frozenset({f"hc_{s}_{t}.weight" for s in ("attn", "ffn") for t in ("fn", "base", "scale")} | set(_RESID_NORMS)),
- build=None))
+ build=_stream_build))
+
+
+def _head_names(cfg, i, L, G):
+ return {f"model.hc_head_{t}": f"output_hc_{t}.weight" for t in ("fn", "base", "scale")}
+
+
+def _head_build(config, P):
+ """[HyperHead], to sit before the final norm: mixes = fn @ rms(flat streams); pre = sigmoid(mixes * scale + base) + eps
+ (llama.cpp build_hc_head, no magnitude); collapsed = sum_i pre_i * stream_i"""
+ from ...modules.hyperconnections import HyperHead
+ c = config.gguf_plan.configs[("hyper_head", None)]
+ return [HyperHead(config=config, key=f"{P}.hc_head", hc_mult=c["count"], rms_norm_eps=config.rms_norm_eps, hc_eps=c["eps"])]
+
register(Block(
"hyper_head", "head_mod", step="step 5",
select=lambda ctx, i: "output_hc_fn.weight" in ctx.glob,
- config=lambda ctx, i: {"fn_dims": ctx.dims("output_hc_fn.weight"), "count": ctx.key("hyper_connection.count")},
- claims=frozenset({"output_hc_fn.weight", "output_hc_base.weight", "output_hc_scale.weight"}), build=None))
+ config=lambda ctx, i: {"fn_dims": ctx.dims("output_hc_fn.weight"), "count": ctx.key("hyper_connection.count"),
+ "eps": ctx.key("hyper_connection.epsilon")},
+ claims=frozenset({"output_hc_fn.weight", "output_hc_base.weight", "output_hc_scale.weight"}),
+ build=_head_build, names=_head_names))
diff --git a/exllamav3/modules/hyperconnections.py b/exllamav3/modules/hyperconnections.py
index 0ed41f6..3f6f49e 100644
--- a/exllamav3/modules/hyperconnections.py
+++ b/exllamav3/modules/hyperconnections.py
@@ -1070,3 +1070,52 @@ class HyperHead(Module):
mixes = F.linear(flat, self.fn)
pre = torch.sigmoid(mixes * self.scale + self.base) + self.hc_eps
return (pre.unsqueeze(-1) * x).sum(dim = 2)
+
+
+class HyperConnectionPP(HyperConnection):
+ """Pre/post-only HC site (hy_v4_flash, llama.cpp build_hc_pre / build_hc_post): fn is (2H, H * hidden), scale 2 scalars,
+ base 2H. No comb block, no Sinkhorn: comb is the identity, so apply_ gives stream_i + post_i * y.
+ mixes = fn @ rms(flat streams, rms_norm_eps) (rms is weightless)
+ pre = sigmoid(mixes[:H] * scale[0] + base[:H]) + hc_eps collapsed = sum_i pre_i * stream_i
+ post = magnitude * sigmoid(mixes[H:] * scale[1] + base[H:]) + hc_eps
+ Differs from the Sinkhorn mHC in: 2H rows instead of (2 + H) * H, post gets + hc_eps, magnitude is a parameter (2.0 there).
+ The fused ext.hc_mix kernels assume the (2 + H) * H layout, so every path here is torch (device agnostic)."""
+
+ def __init__(self, config, key: str, hc_mult: int, hidden_size: int, hc_eps: float, rms_norm_eps: float,
+ magnitude: float = 2.0):
+ super().__init__(config = config, key = key, hc_mult = hc_mult, hidden_size = hidden_size,
+ sinkhorn_iters = 0, hc_eps = hc_eps, rms_norm_eps = rms_norm_eps)
+ self.magnitude = magnitude
+
+ @override
+ def weights_numel(self):
+ h = self.hc_mult
+ return 2 * h * (h * self.hidden_size + 1) + 2
+
+ def gates(self, streams: torch.Tensor):
+ """streams (b, s, H, D) fp32 -> (pre (b,s,H), post (b,s,H))"""
+ H = self.hc_mult
+ flat = streams.flatten(2)
+ flat = flat * torch.rsqrt(flat.pow(2).mean(-1, keepdim = True) + self.rms_eps)
+ pre_w, post_w = F.linear(flat, self.fn).split([H, H], dim = -1)
+ pre_b, post_b = self.base.split([H, H])
+ pre_s, post_s = self.scale.unbind(0)
+ pre = torch.sigmoid(pre_w * pre_s + pre_b) + self.hc_eps
+ post = self.magnitude * torch.sigmoid(post_w * post_s + post_b) + self.hc_eps
+ return pre, post
+
+ @override
+ def mix(self, streams: torch.Tensor, params: dict, pending = None):
+ """streams (b, s, H, D) fp32 -> (post (b,s,H), comb = identity (b,s,H,H), collapsed (b,s,D) fp32)"""
+ if pending is not None:
+ HyperConnection.flush_pending(streams, pending)
+ b, s, H, D = streams.shape
+ pre, post = self.gates(streams)
+ comb = torch.eye(H, dtype = torch.float, device = streams.device).expand(b, s, H, H).contiguous()
+ return post, comb, (pre.unsqueeze(-1) * streams).sum(dim = 2)
+
+ @override
+ def mix_norm(self, streams: torch.Tensor, params: dict, norm, pending = None):
+ if pending is not None:
+ HyperConnection.flush_pending(streams, pending)
+ return None # no fused mix_norm kernel for the 2H layout: the caller takes mix() + norm
diff --git a/exllamav3/modules/transformer.py b/exllamav3/modules/transformer.py
index d258c88..6e01bd9 100644
--- a/exllamav3/modules/transformer.py
+++ b/exllamav3/modules/transformer.py
@@ -64,11 +64,13 @@ class TransformerBlock(Module):
if attn_hc is not None or mlp_hc is not None:
assert attn_hc is not None and mlp_hc is not None, \
"hyperconnections require both attn_hc and mlp_hc"
+ # post norms (Hy4: llama.cpp norms the sublayer output before the post mix) need both sites, or none
+ assert (attn_post_norm is None) == (mlp_post_norm is None), \
+ "hyperconnections need attn_post_norm and mlp_post_norm together (or neither)"
assert all(v is None for v in (
- attn_post_norm, mlp_post_norm,
key_layer_scalar, key_attn_resid_scalar, key_mlp_resid_scalar,
)), \
- "hyperconnections cannot combine with residual scalars/post-norms"
+ "hyperconnections cannot combine with residual scalars"
self.register_submodule(self.attn_hc)
self.register_submodule(self.attn_norm)
@@ -147,7 +149,7 @@ class TransformerBlock(Module):
"""MLP half of forward (norm, MLP, residual/hc apply). `y_resid` is a pending attention
output whose residual add is folded into the MLP input norm. Returns the new residual."""
if self.mlp:
- if self.mlp_hc and self._moe_fused_on:
+ if self.mlp_hc and self._moe_fused_on and not self.mlp_post_norm:
fused_x = moe_fused.maybe_apply(self, x, params, hc_pending)
if fused_x is not None:
return fused_x
@@ -211,7 +213,11 @@ class TransformerBlock(Module):
ablit_runtime.project(y, self.ablit[1], *self.ablit[2:])
if self.mlp_resid_scalar is not None:
y *= self.mlp_resid_scalar
- if self.mlp_hc:
+ if self.mlp_hc and self.mlp_post_norm:
+ # Hy4 order: collapse -> mlp_norm -> mlp -> post norm -> post mix into the streams (M:5943 / 6089)
+ y = self.mlp_post_norm.forward(y, params)
+ x = self.mlp_hc.apply_(x, y, hc_post, hc_comb, params)
+ elif self.mlp_hc:
# EXL3_PF_HC_FUSE: defer into the next block's attn mix_norm (see pf_can_defer)
if hc_defer and HyperConnection.pf_can_defer(x, y, hc_post, hc_comb, params):
params["hc_pending"] = (x, y, hc_post, hc_comb)
@@ -307,7 +313,11 @@ class TransformerBlock(Module):
ablit_runtime.project(y, self.ablit[0], *self.ablit[2:])
if self.attn_resid_scalar is not None:
y *= self.attn_resid_scalar
- if self.attn_hc:
+ if self.attn_hc and self.attn_post_norm:
+ # Hy4 order: collapse -> attn_norm -> attn -> post norm -> post mix into the streams
+ y = self.attn_post_norm.forward(y, params)
+ x = self.attn_hc.apply_(x, y, hc_post, hc_comb, params)
+ elif self.attn_hc:
if self.mlp and self.mlp_hc and self.mlp_norm \
and HyperConnection.pf_can_defer(x, y, hc_post, hc_comb, params):
mlp_pending = (x, y, hc_post, hc_comb)
diff --git a/tests/test_gguf_hy4_hc.py b/tests/test_gguf_hy4_hc.py
new file mode 100644
index 0000000..94cd969
--- /dev/null
+++ b/tests/test_gguf_hy4_hc.py
@@ -0,0 +1,191 @@
+"""Hy4-flash hyper-connection sites + head vs the llama.cpp oracle dumps (CPU only, no GPU, no extension).
+The modules under test are imported by path under stub packages (the extension needs libcudart); Module / RMSNorm are stubs,
+the rms is done inline in HyperConnectionPP.gates, so only the maths is exercised. Skips when the GGUF / oracle dumps are absent.
+
+ pre weights hc_pre-L_o0 (attn site) / hc_pre-L_o1 (ffn site), from the input stream
+ post mixing s1 = s0 + post * attn_out (identity comb); the ffn-site pre weights hc_pre-L_o1 are computed on s1, so they check it
+ ffn site mix l_out - s1 = post_ffn * ffn_out for all 4 streams with ONE ffn_out (least squares over the streams, residual)
+Bar: max abs / max |target| <= 1e-4 (fp32 vs fp32, ggml vs torch reduction order; the existing GGUF tests vs llama.cpp are bit-exact
+dequant checks, which do not apply to float maths)."""
+import json, os, sys, types
+import numpy as np
+import pytest
+import torch
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ORACLE = os.path.expanduser("/path/to/oracle_out")
+GGUF1 = "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf"
+BAR = 1e-4
+pytestmark = pytest.mark.skipif(not (os.path.isdir(ORACLE) and os.path.exists(GGUF1)), reason="oracle dumps / Hy4 GGUF absent")
+
+
+def _mod(n, **kw):
+ m = types.ModuleType(n)
+ for k, v in kw.items():
+ setattr(m, k, v)
+ sys.modules[n] = m
+ return m
+
+
+def _stubs():
+ import importlib.util
+ class _Ext:
+ def __getattr__(self, n):
+ raise AttributeError(n)
+ class RMSNorm:
+ def __init__(self, *a, **k): pass
+ class Module:
+ def __init__(self, config=None, key="", qmap=None, **k): self.config, self.key = config, key
+ def register_submodule(self, m): pass
+ def load(self, *a, **k): pass
+ def unload(self): pass
+ for n, s in (("exllamav3", ""), ("exllamav3.modules", "modules"), ("exllamav3.loader", "loader")):
+ _mod(n).__path__ = [os.path.join(ROOT, "exllamav3", s)]
+ _mod("exllamav3.ext", exllamav3_ext=_Ext())
+ _mod("exllamav3.model").__path__ = []
+ _mod("exllamav3.model.config", Config=object)
+ _mod("exllamav3.util").__path__ = []
+ _mod("exllamav3.util.tensor", g_tensor_cache=None)
+ _mod("exllamav3.modules.quant").__path__ = []
+ _mod("exllamav3.modules.quant.exl3", PAD_MIN_ROWS=1, PAD_ELEMS=1)
+ _mod("exllamav3.modules.rmsnorm", RMSNorm=RMSNorm)
+ _mod("exllamav3.modules.module", Module=Module)
+ for name, rel in (("exllamav3.loader.gguf_collection", "loader/gguf_collection.py"),
+ ("exllamav3.loader.gguf_registry", "loader/gguf_registry.py")):
+ sp = importlib.util.spec_from_file_location(name, os.path.join(ROOT, "exllamav3", rel))
+ m = importlib.util.module_from_spec(sp); m.__package__ = "exllamav3.loader"; sys.modules[name] = m; sp.loader.exec_module(m)
+ sys.modules["exllamav3.loader.gguf_registry"]._load_blocks()
+
+
+_stubs()
+from exllamav3.modules.hyperconnections import HyperConnectionPP, HyperHead # noqa: E402
+from exllamav3.loader.gguf_collection import GGUFCollection # noqa: E402
+from exllamav3.loader.gguf_registry import build_plan # noqa: E402
+from exllamav3.loader.gguf_blocks.hyperconnections import build_site, _head_build, _site_names, _head_names # noqa: E402
+
+_G = {}
+
+
+def gg():
+ if not _G:
+ g = GGUFCollection(GGUF1)
+ _G["g"], _G["plan"] = g, build_plan(g)
+ return _G["g"], _G["plan"]
+
+
+class Cfg:
+ hidden_size, rms_norm_eps = 3072, float(np.float32(9.999999747378752e-06))
+
+
+def site(layer, tag):
+ g, plan = gg()
+ cfg = Cfg(); cfg.gguf_plan = plan
+ m = build_site(cfg, plan, layer, f"model.layers.{layer}", tag)
+ for t in ("fn", "base", "scale"):
+ w = g.get_tensor(f"blk.{layer}.hc_{tag}_{t}.weight").float()
+ setattr(m, t, w.reshape(-1, m.hidden_size * m.hc_mult) if t == "fn" else w.reshape(-1))
+ return m
+
+
+def emb_rows(ids):
+ """token_embd.weight is Q8_0: 34-byte blocks (fp16 d + 32 int8), 96 blocks per 3072-wide row; read by offset, row by row"""
+ g, _ = gg()
+ ty, dims, off = g.infos["token_embd.weight"]
+ assert ty == 8 and dims[0] == 3072
+ rb = dims[0] // 32 * 34
+ out = np.empty((len(ids), dims[0]), np.float32)
+ for k, t in enumerate(ids):
+ raw = g._pread(off + int(t) * rb, rb).reshape(-1, 34)
+ d = raw[:, :2].copy().view(np.float16).astype(np.float32) # (96, 1)
+ q = raw[:, 2:].copy().view(np.int8).astype(np.float32) # (96, 32)
+ out[k] = (q * d).reshape(-1)
+ return torch.from_numpy(out)
+
+
+def rel(a, b):
+ a, b = a.double(), b.double()
+ return float((a - b).abs().max()), float((a - b).abs().max() / b.abs().max())
+
+
+def load_call(prompt, call, layers):
+ d = os.path.join(ORACLE, prompt)
+ idx = json.load(open(os.path.join(d, "index.json")))
+ ent = {(t["name"], t["layer"], t["occ"]): t for t in idx["tensors"] if t["call"] == call}
+ def get(name, layer, occ=0):
+ t = ent[(name, layer, occ)]
+ return torch.from_numpy(np.fromfile(os.path.join(d, t["file"]), np.float32).reshape(tuple(reversed(t["shape_ggml"]))).copy())
+ pos = ent[("hc_pre", 0, 0)]["positions"]
+ return idx, get, pos
+
+
+def check(prompt, call=0, layers=(0, 1, 2)):
+ """-> list of (tensor, target, prompt, max abs, rel, PASS/FAIL)"""
+ idx, get, pos = load_call(prompt, call, layers)
+ ids = [idx["prompt_ids"][p] for p in pos]
+ rows, nt = [], len(pos)
+ def rec(name, target, a, b):
+ ma, r = rel(a, b)
+ rows.append((name, target, f"{prompt}#{call}", ma, r, "PASS" if r <= BAR else "FAIL"))
+ for L in layers:
+ if L == 0:
+ s0 = emb_rows(ids).unsqueeze(1).repeat(1, 4, 1)
+ elif L == 1:
+ s0 = get("engram_out", 1)
+ elif L == 2:
+ s0 = get("l_out", 1)
+ s0 = s0.unsqueeze(0)
+ a, f = site(L, "attn"), site(L, "ffn")
+ pre, post = a.gates(s0)
+ rec(f"L{L} attn site pre", f"hc_pre-{L}_o0", pre[0], get("hc_pre", L, 0))
+ post_g, comb, coll = a.mix(s0, {})
+ y = get("attn_out", L)
+ s1 = a.apply_(s0.clone(), y.unsqueeze(0), post_g, comb, {})
+ pre2, post2 = f.gates(s1)
+ rec(f"L{L} post mix -> ffn site pre", f"hc_pre-{L}_o1", pre2[0], get("hc_pre", L, 1))
+ d = get("l_out", L) - s1[0] # (nt, 4, D) = post2_i * ffn_out
+ p2 = post2[0].unsqueeze(-1) # (nt, 4, 1)
+ fo = (p2 * d).sum(1, keepdim=True) / (p2 * p2).sum(1, keepdim=True)
+ rec(f"L{L} ffn post mix (l_out = s1 + post*ffn_out, 1 ffn_out for 4 streams)", f"l_out-{L}", s1[0] + p2 * fo, get("l_out", L))
+ return rows
+
+
+def test_registry_selects_identity_and_head():
+ g, plan = gg()
+ c = plan.configs[("hyper_connection", 0)]
+ assert c["mode"] == "identity" and c["sinkhorn_iterations"] is None and c["count"] == 4 and c["magnitude"] == 2.0
+ assert plan.glob["head_mod"] == ["hyper_head"] and plan.layers[0]["stream"] == "hyper_connection"
+ assert plan.layers[42]["stream"] != "hyper_connection" # the MTP block has no HC tensors
+ assert _site_names({}, 3, "L", "G")["L.hc_ffn_fn"] == "G.hc_ffn_fn.weight"
+ assert g.infos["output_hc_fn.weight"][1] == (12288, 4) and g.infos["blk.7.hc_attn_fn.weight"][1] == (12288, 8)
+
+
[email protected]("prompt,call", [("p1_short_en", 0), ("p4_long_n700", 0), ("p4_long_n700", 1), ("p5_long_n4000", 0), ("p5_long_n4000", 7)])
+def test_hc_sites_vs_oracle(prompt, call):
+ for row in check(prompt, call):
+ assert row[5] == "PASS", row
+
+
+def test_head_matches_formula():
+ """the oracle dumps no stream into the head (l_out of layer 41 is not dumped), so only the formula is checked,
+ against numpy on the real output_hc_* tensors"""
+ g, plan = gg()
+ cfg = Cfg(); cfg.gguf_plan = plan
+ h = _head_build(cfg, "model")[0]
+ h.fn, h.base, h.scale = (g.get_tensor(f"output_hc_{t}.weight").float().reshape(-1, 12288) if t == "fn"
+ else g.get_tensor(f"output_hc_{t}.weight").float().reshape(-1) for t in ("fn", "base", "scale"))
+ h.norm = types.SimpleNamespace(forward=lambda x, params: x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + h.rms_eps))
+ x = torch.randn(1, 3, 4, 3072)
+ out = h.forward(x, {})
+ xn = x.double().numpy(); fl = xn.reshape(1, 3, -1)
+ fl = fl / np.sqrt((fl ** 2).mean(-1, keepdims=True) + h.rms_eps)
+ m = fl @ h.fn.double().numpy().T
+ pre = 1 / (1 + np.exp(-(m * h.scale.double().numpy() + h.base.double().numpy()))) + h.hc_eps
+ ref = (pre[..., None] * xn).sum(2)
+ assert np.abs(out.double().numpy() - ref).max() / np.abs(ref).max() < 1e-5
+ assert _head_names({}, None, None, None)["model.hc_head_fn"] == "output_hc_fn.weight"
+
+
+if __name__ == "__main__":
+ for p, c in [("p1_short_en", 0), ("p4_long_n700", 0), ("p5_long_n4000", 0), ("p5_long_n4000", 7)]:
+ for r in check(p, c):
+ print(f"{r[0]} | {r[1]} | {r[2]} | maxabs {r[3]:.3e} | rel {r[4]:.3e} | bar {BAR} | {r[5]}")
diff --git a/tests/test_gguf_hy4_layer_hc.py b/tests/test_gguf_hy4_layer_hc.py
new file mode 100644
index 0000000..ee81548
--- /dev/null
+++ b/tests/test_gguf_hy4_layer_hc.py
@@ -0,0 +1,135 @@
+"""Hy4-flash hyper-connection stream block (TransformerBlock with attn_hc / mlp_hc + post norms) vs the llama.cpp oracle (CPU only).
+The REAL TransformerBlock.forward and the REAL registry build (loader/gguf_blocks/hyperconnections._stream_build) run; the extension is
+not loadable here, so Module / RMSNorm (same maths as modules/rmsnorm.forward_torch) and the sublayers are stubs:
+ attention : returns attn_out-L / post_attention_norm.weight (scaled so the eps is exact, `unnorm`), so the real post-norm gives back the oracle's attn_out-L
+ (llama.cpp dumps attn_out AFTER the post norm, M:5943)
+ ffn : ffn_moe_out-L is only the 1536-wide latent (no up-projection / shared expert), so the ffn output is derived from the
+ oracle: (l_out-L - s1) / post_gate on stream 0 (s1 = the stream after the attn site, from the real block), divided by
+ post_ffw_norm.weight; the 4 streams must agree (identity comb, no cross-stream mix) -> `spread` (bar 1e-2: the division by a small post gate amplifies the oracle's rounding). The ffn side is
+ therefore partly circular: it checks the post-norm + post-mix wiring, not the MoE
+Input stream: engram_out-1 (layer 1: the engram is applied before the layer, not built) / l_out-1 (layer 2). Target: l_out-L.
+Bar: max abs / max|target| <= 1e-3. Skips when the GGUF / oracle dumps are absent."""
+import os, sys, types, importlib.util
+import numpy as np
+import pytest
+import torch
+
+sys.path.insert(0, os.path.dirname(__file__))
+import test_gguf_hy4_hc as T # installs the stub packages, loads the registry
+from test_gguf_hy4_hc import ROOT, ORACLE, gg, load_call, Cfg, rel
+
+BAR = 1e-3
+pytestmark = pytest.mark.skipif(not (os.path.isdir(ORACLE) and os.path.exists(T.GGUF1)), reason="oracle dumps / Hy4 GGUF absent")
+
+
+class Module:
+ def __init__(self, config=None, key="", qmap=None, **k): self.config, self.key = config, key
+ def register_submodule(self, m): pass
+
+
+class WRMS(Module):
+ def __init__(self, config=None, key="", rms_norm_eps=1e-6, out_dtype=torch.half, **k):
+ super().__init__(config, key); self.rms_norm_eps, self.out_dtype, self.weight = rms_norm_eps, out_dtype, None
+ def forward(self, x, params, out_dtype=None, residual=None, residual_in=None):
+ assert residual is None and residual_in is None
+ h = x.float()
+ h = h * torch.rsqrt(h.pow(2).mean(-1, keepdim=True) + self.rms_norm_eps) * self.weight.float()
+ return h.to(out_dtype or self.out_dtype)
+
+
+class Sub:
+ num_slices = 1
+ def __init__(self): self.out = None
+ def forward(self, y, params): return self.out.clone()
+
+
+def _block_cls():
+ pk = sys.modules["exllamav3.modules"]
+ for n in ("LayerNorm", "Attention", "GatedDeltaNet", "GatedMLP", "MLP", "BlockSparseMLP", "Linear"):
+ setattr(pk, n, type(n, (), {}))
+ pk.Module, pk.RMSNorm = Module, WRMS
+ sys.modules["exllamav3.util.tensor"].to2 = lambda x, *a: x
+ sys.modules["exllamav3.util"].profile_opt = types.SimpleNamespace()
+ for n, kw in (("ablit_runtime", {}), ("moe_fused", {"enabled_by_env": lambda: False}),
+ ("block_graph", {"maybe_graph_forward": lambda *a, **k: None})):
+ m = types.ModuleType("exllamav3.modules." + n); m.__dict__.update(kw)
+ sys.modules[m.__name__] = m; setattr(pk, n, m)
+ sp = importlib.util.spec_from_file_location("exllamav3.modules.transformer", os.path.join(ROOT, "exllamav3/modules/transformer.py"))
+ m = importlib.util.module_from_spec(sp); m.__package__ = "exllamav3.modules"; sys.modules[sp.name] = m; sp.loader.exec_module(m)
+ pk.TransformerBlock = m.TransformerBlock
+ return m.TransformerBlock
+
+
+TB = _block_cls()
+from exllamav3.loader.gguf_blocks.hyperconnections import _stream_build, _stream_names # noqa: E402
+
+
+def unnorm(o, w, eps):
+ """y with rmsnorm(y) * w == o exactly: u = o / w has mean(u^2) = q < 1 (the eps shrinks it), y = c u with c^2 = eps / (1 - q)"""
+ u = o / w
+ q = u.double().pow(2).mean(-1, keepdim=True)
+ assert float(q.max()) < 1.0
+ return (u.double() * torch.sqrt(eps / (1 - q))).float()
+
+
+def block(L):
+ g, plan = gg()
+ cfg = Cfg(); cfg.gguf_plan = plan
+ attn, mlp = Sub(), Sub()
+ b = _stream_build(cfg, plan, L, f"model.layers.{L}", attn, mlp)
+ for site, tag in ((b.attn_hc, "attn"), (b.mlp_hc, "ffn")):
+ for t in ("fn", "base", "scale"):
+ w = g.get_tensor(f"blk.{L}.hc_{tag}_{t}.weight").float()
+ setattr(site, t, w.reshape(-1, site.hidden_size * site.hc_mult) if t == "fn" else w.reshape(-1))
+ for n, gn in ((b.attn_norm, "attn_norm"), (b.mlp_norm, "ffn_norm"), (b.attn_post_norm, "post_attention_norm"), (b.mlp_post_norm, "post_ffw_norm")):
+ n.weight = g.get_tensor(f"blk.{L}.{gn}.weight").float().reshape(-1)
+ return b, attn, mlp
+
+
+def test_names_and_order():
+ g, plan = gg()
+ nm = _stream_names(plan.configs[("hyper_connection", 1)], 1, "L", "G")
+ assert nm["L.attn_post_norm.weight"] == "G.post_attention_norm.weight" and nm["L.mlp_post_norm.weight"] == "G.post_ffw_norm.weight"
+ assert nm["L.input_layernorm.weight"] == "G.attn_norm.weight" and nm["L.post_attention_layernorm.weight"] == "G.ffn_norm.weight"
+ assert nm["L.hc_ffn_scale"] == "G.hc_ffn_scale.weight"
+ b, _, _ = block(1)
+ assert b.attn_post_norm is not None and b.mlp_post_norm is not None and b.attn_hc is not None
+ # one post norm without the other, or a scalar, is still refused
+ with pytest.raises(AssertionError):
+ TB(config=None, key="k", layer_idx=0, attn_hc=b.attn_hc, mlp_hc=b.mlp_hc, attn_post_norm=b.attn_post_norm)
+ with pytest.raises(AssertionError):
+ TB(config=None, key="k", layer_idx=0, attn_hc=b.attn_hc, mlp_hc=b.mlp_hc, key_layer_scalar="s")
+
+
+def check(prompt, call=0, layers=(1, 2)):
+ idx, get, pos = load_call(prompt, call, layers)
+ rows = []
+ rows_extra = []
+ for L in layers:
+ b, attn, mlp = block(L)
+ s0 = get("engram_out", 1) if L == 1 else get("l_out", L - 1)
+ attn.out = unnorm(get("attn_out", L), b.attn_post_norm.weight, b.attn_post_norm.rms_norm_eps).unsqueeze(0)
+ tgt = get("l_out", L)
+ mlp.out = torch.zeros(1, tgt.shape[0], b.mlp_post_norm.weight.numel())
+ s1 = b.forward(s0.unsqueeze(0).clone(), {}) # attn site only (post norm of 0 is 0)
+ post = b.mlp_hc.gates(s1)[1][0] # (T, 4)
+ fo = (tgt - s1[0]) / post.unsqueeze(-1) # (T, 4, D) ffn_out per stream
+ spread = float((fo - fo[:, :1]).abs().max() / fo[:, 0].abs().max())
+ mlp.out = unnorm(fo[:, 0], b.mlp_post_norm.weight, b.mlp_post_norm.rms_norm_eps).unsqueeze(0)
+ out = b.forward(s0.unsqueeze(0).clone(), {})
+ ma, r = rel(out[0], tgt)
+ rows_extra.append((L, spread))
+ rows.append((f"l_out-{L} (stream in {'engram_out-1' if L == 1 else 'l_out-1'})", f"l_out-{L}", f"{prompt}#{call}", ma, r, "PASS" if r <= BAR and spread <= 1e-2 else "FAIL", spread))
+ return rows
+
+
[email protected]("prompt,call", [("p1_short_en", 0), ("p4_long_n700", 0), ("p5_long_n4000", 0)])
+def test_layer_vs_oracle(prompt, call):
+ for row in check(prompt, call):
+ assert row[5] == "PASS", row
+
+
+if __name__ == "__main__":
+ for p, c in [("p1_short_en", 0), ("p4_long_n700", 0), ("p5_long_n4000", 0)]:
+ for r in check(p, c):
+ print(f"{r[0]} | {r[1]} | {r[2]} | maxabs {r[3]:.3e} | rel {r[4]:.3e} | bar {BAR} | {r[5]} | ffn stream spread {r[6]:.2e}")