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 k-pool DSA indexer in row-list form

YanissAmz23155ab8d398
diff --git a/exllamav3/loader/gguf_blocks/indexer.py b/exllamav3/loader/gguf_blocks/indexer.py
new file mode 100644
index 0000000..7e432fc
--- /dev/null
+++ b/exllamav3/loader/gguf_blocks/indexer.py
@@ -0,0 +1,75 @@
+"""Block around modules/kpool_indexer.py: the Hy4 (hy_v4_flash) k-pool DSA indexer, row-list form (design §2, indexer row).
+Selected by tensors / keys only: a layer with indexer.attn_k + indexer.attn_q_b + indexer_compressor_value and a weight-only
+indexer.k_norm (no bias), with the indexer.top_k / kpool keys. The other indexer variants (dsa with no pooling, glm5-next
+kpool_gate, LayerNorm k_norm) keep the plain 'dsa_indexer' block from mla_attn.py, which this file narrows so the two never
+select the same layer (the only touch on that registration; mla_attn.py itself is not edited)."""
+from __future__ import annotations
+from dataclasses import replace
+import numpy as np
+import torch
+from ..gguf_registry import Block, REGISTRY, register, GenericUnsupported
+from . import mla_attn as _mla # noqa: F401 (registers dsa_indexer first)
+
+_KP = ("indexer.attn_k.weight", "indexer.attn_q_b.weight", "indexer_compressor_value.weight")
+# engine name -> GGUF suffix
+_W = {"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"}
+
+
+def is_kpool(ctx, i):
+ return (all(ctx.has(i, s) for s in (*_KP, "indexer_compressor_gate.weight", "indexer_compressor_ape.weight",
+ "indexer_compressor_norm.weight", "indexer.k_norm.weight", "indexer.proj.weight"))
+ and not ctx.has(i, "indexer.k_norm.bias")
+ and all(ctx.key(f"attention.indexer.{k}") for k in ("top_k", "kpool", "head_count", "key_length")))
+
+
+_orig = REGISTRY["dsa_indexer"]
+register(replace(_orig, select=lambda ctx, i: _orig.select(ctx, i) and not is_kpool(ctx, i)))
+
+
+def _cfg(ctx, i):
+ c = _mla._indexer_layer(ctx, i)
+ swa = _mla._swa(ctx, i)
+ c.update(rope_dim=ctx.key("rope.dimension_count"), rope_base=ctx.key("rope.freq_base"), eps=ctx.key("attention.layer_norm_rms_epsilon"),
+ swa_layer=swa, dims={k: ctx.dims(f"blk.{i}.{s}") for k, s in _W.items()},
+ types={k: ctx.infos[f"blk.{i}.{s}"][0] for k, s in _W.items()})
+ return c
+
+
+def _w(g, name, ty, dims):
+ """fp32 (out, in) weight of one GGUF tensor: F32 as is, Q8_0 dequantised (34-byte blocks: fp16 d + 32 int8). Other types are refused."""
+ t = g.get_tensor(name)
+ if ty == 0:
+ return t.float().reshape(dims[1] if len(dims) > 1 else 1, dims[0]) if len(dims) > 1 else t.float().reshape(-1)
+ if ty == 8:
+ raw = t.numpy().reshape(dims[1], dims[0] // 32, 34)
+ d = np.ascontiguousarray(raw[..., :2]).view(np.float16).astype(np.float32)
+ q = np.ascontiguousarray(raw[..., 2:]).view(np.int8).astype(np.float32)
+ return torch.from_numpy((q * d).reshape(dims[1], dims[0]))
+ raise GenericUnsupported(f"indexer tensor {name}: ggml type {ty} (only F32 and Q8_0 are read)")
+
+
+def load_weights(g, i):
+ out = {}
+ for k, s in _W.items():
+ ty, dims, _ = g.infos[f"blk.{i}.{s}"]
+ out[k] = _w(g, f"blk.{i}.{s}", ty, dims)
+ return out
+
+
+def _build(config, plan, i, key=None):
+ """KPoolIndexer for layer i (CPU fp32): forward(x, qr) -> IndexerSelection (row lists + scores). Weights read by offset."""
+ from ...modules.kpool_indexer import KPoolIndexer
+ c = plan.configs[("dsa_kpool_indexer", i)]
+ if c["swa_layer"]:
+ raise GenericUnsupported(f"layer {i}: an indexer on a sliding-window layer (the cache mirrors the full-attention child)")
+ if c["rope_dim"] is None or c["rope_base"] is None or c["eps"] is None or c["rope_dim"] >= c["head_dim"]:
+ raise GenericUnsupported(f"layer {i}: indexer needs rope.dimension_count < indexer.key_length, rope.freq_base, rms eps")
+ g = getattr(config, "gguf", config)
+ return KPoolIndexer(load_weights(g, i), n_head=c["n_head"], head_dim=c["head_dim"], top_k=c["top_k"], kpool=c["kpool"],
+ select_tail=bool(c["select_tail"]), rope_dim=c["rope_dim"], rope_base=c["rope_base"], eps=c["eps"],
+ q8_weights=tuple(k for k, t in c["types"].items() if t == 8))
+
+
+register(Block("dsa_kpool_indexer", "attn_mod", select=is_kpool, config=_cfg, claims=_orig.claims, build=_build, priority=1))
diff --git a/exllamav3/loader/gguf_registry.py b/exllamav3/loader/gguf_registry.py
index dc6a8e7..e38d514 100644
--- a/exllamav3/loader/gguf_registry.py
+++ b/exllamav3/loader/gguf_registry.py
@@ -26,7 +26,7 @@ BASE_SLOTS = ("pre", "stream", "attn", "ffn")
MOD_SLOTS = ("attn_mod", "ffn_mod", "layer_mod")
GLOBAL_SLOTS = ("embed", "embed_mod", "head", "head_mod")
CONFIG_ONLY = "config-only" # build marker: the block feeds module configs, no module of its own
-BLOCK_MODULES = ("transformer", "attn", "mlp", "mla_attn", "hyperconnections", "engram", "mtp")
+BLOCK_MODULES = ("transformer", "attn", "mlp", "mla_attn", "indexer", "hyperconnections", "engram", "mtp")
# Per-arch features llama.cpp hard-codes with no GGUF key. Every entry names the llama.cpp source it mirrors
# (M = the model patch published with the model, else the llama.cpp file).
diff --git a/exllamav3/modules/kpool_indexer.py b/exllamav3/modules/kpool_indexer.py
new file mode 100644
index 0000000..5adb6fe
--- /dev/null
+++ b/exllamav3/modules/kpool_indexer.py
@@ -0,0 +1,134 @@
+"""Hy4 DSA indexer, k-pool variant, in ROW-LIST form (llama.cpp hy-v4-flash.cpp build_kpool_select, 769-905).
+
+Per layer it keeps a pooled key per complete group of `kpool` consecutive positions. For a query token at position p it
+scores the groups that ended before p, keeps the best `top_k // kpool - select_tail` groups and the tokens of p's own
+group up to p (the "tail"), and returns the key ROWS (positions) of that selection, one int32 list per query, plus the
+scores. No dense mask is built; the list is what the sparse attention gathers.
+
+Maths (all fp32, CPU; the model's norms are weight-only RMSNorm):
+ ik = rms(x @ Wk^T) * k_norm x = attn_norm output [n, n_embd] -> [n, d]
+ value = ik @ Wv^T ; gate = ik @ Wg^T [n, d] each
+ pooled = rope_tail(rms(sum_k softmax_k(gate_k + ape_k) * value_k) * pool_norm, pos = first of the group)
+ iq = rope_tail((qr @ Wq^T).reshape(n, H, d), pos = p) qr = q_a_norm(wq_a x), the main attention's lora residual
+ w = (x @ Wp^T) / sqrt(d * H) [n, H]
+ score = sum_h relu(iq_h . pooled_j) * w_h [n, n_pool]
+rope_tail rotates only the trailing `rope_dim` of each d-vector, NORM pairing (x[2i], x[2i+1]), theta = pos * base^(-2i/rope_dim).
+Visible groups for the token at p: group g with its last position 4g+3 < p when select_tail (the group holding p is the tail),
+<= p otherwise. Ties between equal scores: ggml's CPU top-k is std::partial_sort with a '>' comparator (order of ties
+unspecified); here the lowest group index wins (stable sort), the only deterministic choice.
+"""
+from __future__ import annotations
+import math
+from dataclasses import dataclass
+import torch
+
+
+def rms(x, w, eps):
+ x = x.float()
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * w
+
+
+def rope_tail(x, pos, rope_dim, base):
+ """x [..., n, (H,) d]; pos [n] int. Rotates x[..., -rope_dim:] (NORM pairs); the nope front is untouched."""
+ d = x.shape[-1]
+ inv = base ** (-torch.arange(0, rope_dim, 2, dtype=torch.float64) / rope_dim) # [rope_dim/2]
+ ang = pos.double()[:, None] * inv[None] # [n, rope_dim/2]
+ c, s = ang.cos().float(), ang.sin().float()
+ shp = [x.shape[0]] + [1] * (x.dim() - 2) + [rope_dim // 2]
+ c, s = c.reshape(shp), s.reshape(shp)
+ t = x[..., d - 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 - rope_dim], out], -1)
+
+
+def q8_act(x):
+ """ggml Q8_0 activation quantisation (what the CPU mul_mat does to the activations before a Q8_0 weight dot):
+ blocks of 32, d = amax/127, q = roundf(x/d) (half away from zero), d stored fp16."""
+ shp = x.shape
+ b = x.float().reshape(-1, 32)
+ d = b.abs().amax(-1, keepdim=True) / 127.0
+ idv = torch.where(d != 0, 1.0 / d, torch.zeros_like(d))
+ v = b * idv
+ q = torch.sign(v) * torch.floor(v.abs() + 0.5)
+ return (q * d.half().float()).reshape(shp)
+
+
+@dataclass
+class IndexerSelection:
+ rows: list # per query: int32 tensor, ascending key positions (selected groups' members + tail)
+ scores: torch.Tensor # [n, n_pool] fp32, -inf where the group is not visible to the query
+ pools: list # per query: int32 tensor, the picked group ids (descending score)
+ pos: torch.Tensor # [n] query positions
+
+
+class KPoolIndexer:
+ """w: dict of fp32 tensors (out, in): attn_k [d, E], k_norm [d], q_b [H*d, R], proj [H, E], value [d, d], gate [d, d],
+ ape [kpool, d], pool_norm [d]. q8_weights: names whose weights are Q8_0 in the file (activation quantised when act_q8)."""
+
+ def __init__(self, w, n_head=16, head_dim=128, top_k=2048, kpool=4, select_tail=True, rope_dim=64,
+ rope_base=1e7, eps=1e-5, act_q8=False, q8_weights=("attn_k", "q_b", "value", "gate")):
+ self.w, self.H, self.d, self.top_k, self.kpool = w, 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
+ self.act_q8, self.q8 = act_q8, set(q8_weights)
+ 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.reset()
+
+ def reset(self):
+ self.n = 0
+ self.vg = [] # (value, gate) per token not yet pooled: [m, 2d]
+ self.pooled = torch.empty(0, self.d)
+
+ def _mm(self, name, x):
+ if self.act_q8 and name in self.q8:
+ x = q8_act(x)
+ return x @ self.w[name].T
+
+ def _pool(self, vg, g0):
+ """vg [m*kpool, 2d] complete groups starting at group g0 -> pooled keys [m, d]"""
+ k, d = self.kpool, 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 rope_tail(p, torch.arange(g0, g0 + p.shape[0]) * k, self.rope_dim, self.base)
+
+ @torch.no_grad()
+ def forward(self, x, qr) -> IndexerSelection:
+ """x [n, E] attn_norm output, qr [n, R] q_a_norm output, for n consecutive new tokens (positions n_seen ...).
+ One call = one prefill chunk or one decode step; the pooled keys persist between calls."""
+ n, k, d, H = x.shape[0], self.kpool, self.d, self.H
+ pos = torch.arange(self.n, self.n + n)
+ ik = rms(self._mm("attn_k", x), self.w["k_norm"], self.eps)
+ vg_new = torch.cat([self._mm("value", ik), self._mm("gate", ik)], -1)
+ self.vg.append(vg_new)
+ buf = torch.cat(self.vg, 0) if len(self.vg) > 1 else self.vg[0]
+ g0 = self.pooled.shape[0]
+ m = buf.shape[0] // k # complete groups available (the buffer starts at group g0)
+ if m:
+ self.pooled = torch.cat([self.pooled, self._pool(buf[:m * k], g0)], 0)
+ self.vg = [buf[m * k:]] if buf.shape[0] - m * k else []
+ self.n += n
+ iq = rope_tail(self._mm("q_b", qr).reshape(n, H, d), pos, self.rope_dim, self.base)
+ wt = (x.float() @ self.w["proj"].T) / math.sqrt(d * H) # F32 tensor: no quantisation
+ pk = self.pooled # [P, d]
+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pk))
+ sc = (kq * wt[:, :, None]).sum(1) # [n, P]
+ P = pk.shape[0]
+ gend = torch.arange(P) * 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))
+ nvis = vis.sum(1)
+ order = torch.sort(-sc, dim=1, stable=True).indices if P else sc.long() # best first, lowest index on ties
+ rows, pools = [], []
+ for t in range(n):
+ nt = min(int(nvis[t]), self.n_top)
+ g = order[t, :nt]
+ p = int(pos[t])
+ mem = (g[:, None] * k + torch.arange(k)[None]).reshape(-1)
+ tail = torch.arange(p - (p % k), p + 1) if self.tail else torch.arange(p - ((p + 1) % k) + 1, p + 1)
+ rows.append(torch.cat([mem, tail]).sort().values.int())
+ pools.append(g.int())
+ return IndexerSelection(rows, sc, pools, pos)
diff --git a/tests/test_gguf_hy4_indexer.py b/tests/test_gguf_hy4_indexer.py
new file mode 100644
index 0000000..6dcdcd1
--- /dev/null
+++ b/tests/test_gguf_hy4_indexer.py
@@ -0,0 +1,218 @@
+"""Hy4 k-pool DSA indexer (row-list form): predicate, maths vs an independent float64 numpy reference, chunked == one-shot
+(prefill / decode), and layer-0 runs on the oracle prompts. The oracle (llama.cpp, hy4_oracle) dumps NO indexer tensor (only
+hc_pre, attn_kqv, attn_gated, attn_out, ffn_moe_out, l_out, engram_out, hc_head, result_output), so there is no oracle value
+for scores or indices: the real-prompt runs check selection structure and the numpy reference, nothing against llama.cpp."""
+import os, sys, json, types
+import numpy as np
+import pytest
+import torch
+
+sys.path.insert(0, os.path.dirname(__file__))
+import test_gguf_hy4_hc as H # noqa: E402 (stubs + GGUF + oracle helpers)
+from exllamav3.modules.kpool_indexer import KPoolIndexer, rms, rope_tail, q8_act # noqa: E402
+from exllamav3.loader.gguf_blocks import indexer as IB # noqa: E402
+from exllamav3.loader.gguf_registry import REGISTRY # noqa: E402
+
+pytestmark = pytest.mark.skipif(not os.path.exists(H.GGUF1), reason="Hy4 GGUF absent")
+EPS = 9.999999747378752e-06
+BAR = 1e-3
+INDEXER_LAYERS = [0, 1] + list(range(5, 42, 4)) + [42]
+_W = {}
+
+
+def weights(layer=0):
+ if layer not in _W:
+ _W[layer] = IB.load_weights(H.gg()[0], layer)
+ return _W[layer]
+
+
+def np_ref(x, qr, W, top_k, kpool=4, tail=True, rope_dim=64, base=1e7, H_=16, d=128, eps=EPS):
+ """independent float64 reference: complex-number rope, per-group loops, per-query sorted selection"""
+ f = lambda a: np.asarray(a, np.float64)
+ x, qr, W = f(x), f(qr), {k: f(v) for k, v in W.items()}
+ rmsn = lambda a, w: a / np.sqrt((a ** 2).mean(-1, keepdims=True) + eps) * w
+ inv = base ** (-np.arange(0, rope_dim, 2) / rope_dim)
+ def rope(a, p):
+ z = (a[..., d - rope_dim::2] + 1j * a[..., d - rope_dim + 1::2]) * np.exp(1j * p * inv)
+ o = a.copy(); o[..., d - rope_dim::2], o[..., d - rope_dim + 1::2] = z.real, z.imag
+ return o
+ n = x.shape[0]
+ ik = rmsn(x @ W["attn_k"].T, W["k_norm"]); val, gate = ik @ W["value"].T, ik @ W["gate"].T
+ pooled = []
+ for g in range(n // kpool):
+ s = slice(g * kpool, (g + 1) * kpool)
+ e = np.exp(gate[s] + W["ape"]); e /= e.sum(0)
+ pooled.append(rope(rmsn((e * val[s]).sum(0), W["pool_norm"]), g * kpool))
+ pooled = np.array(pooled).reshape(-1, d)
+ iq = (qr @ W["q_b"].T).reshape(n, H_, d)
+ wt = x @ W["proj"].T / np.sqrt(d * H_)
+ rows, scores = [], np.full((n, len(pooled)), -np.inf)
+ for t in range(n):
+ iqt = rope(iq[t], t)
+ for g in range(len(pooled)):
+ if g * kpool + kpool - 1 < t if tail else g * kpool + kpool - 1 <= t:
+ scores[t, g] = (np.maximum(iqt @ pooled[g], 0) * wt[t]).sum()
+ vis = [g for g in range(len(pooled)) if np.isfinite(scores[t, g])]
+ pick = sorted(vis, key=lambda g: (-scores[t, g], g))[:top_k // kpool - int(tail)]
+ r = {g * kpool + j for g in pick for j in range(kpool)}
+ r |= set(range(t - t % kpool, t + 1)) if tail else set(range(t - (t + 1) % kpool + 1, t + 1))
+ rows.append(sorted(r))
+ return rows, scores
+
+
+def compare(sel, rows, scores):
+ set_eq = all(a.tolist() == b for a, b in zip(sel.rows, rows))
+ fin = np.isfinite(scores)
+ assert (torch.isfinite(sel.scores).numpy() == fin).all()
+ got = sel.scores.double().numpy()
+ err = np.abs(got[fin] - scores[fin]).max() / max(np.abs(scores[fin]).max(), 1e-30) if fin.any() else 0.0
+ return set_eq, float(err)
+
+
+def mk(W, **kw):
+ return KPoolIndexer(W, eps=EPS, **kw)
+
+
+def test_predicate_and_plan():
+ g, plan = H.gg()
+ for i in range(43):
+ names = plan.layers[i]["attn_mod"]
+ if i in INDEXER_LAYERS:
+ assert "dsa_kpool_indexer" in names and "dsa_indexer" not in names, (i, names)
+ assert plan.claimed[f"blk.{i}.indexer.attn_k.weight"] == "dsa_kpool_indexer"
+ assert plan.claimed[f"blk.{i}.indexer_compressor_value.weight"] == "dsa_kpool_indexer"
+ else:
+ assert "dsa_kpool_indexer" not in names and "dsa_indexer" not in names, (i, names)
+ c = plan.configs[("dsa_kpool_indexer", 0)]
+ assert (c["n_head"], c["head_dim"], c["top_k"], c["kpool"], c["select_tail"], c["rope_dim"], c["rope_base"]) == (16, 128, 2048, 4, True, 64, 1e7)
+ assert c["variant"] == "kpool_value" and c["k_norm"] == "rms_weight" and not c["swa_layer"]
+ assert not any("dsa_kpool_indexer" in g_ for g_ in plan.gaps) and not any("dsa_indexer" in g_ for g_ in plan.gaps)
+ m = IB._build(g, plan, 5)
+ assert m.n_top == 511 and m.w["q_b"].shape == (2048, 1024) and m.w["ape"].shape == (4, 128) and m.q8 == {"attn_k", "q_b", "value", "gate"}
+
+
+def _fake(has, keys):
+ return types.SimpleNamespace(has=lambda i, s: s in has, key=lambda k, d=None: keys.get(k, d), feats={}, infos={})
+
+
+def test_other_gguf_unchanged():
+ """deepseek-style dsa indexer (no pooling) and glm5-next (kpool_gate, LayerNorm bias): stay on dsa_indexer"""
+ keys = {"attention.indexer.top_k": 2048, "attention.indexer.kpool": 4, "attention.indexer.head_count": 16, "attention.indexer.key_length": 128}
+ base = {"indexer.attn_k.weight", "indexer.attn_q_b.weight", "indexer.proj.weight", "indexer.k_norm.weight"}
+ dsa = _fake(base, {k: v for k, v in keys.items() if k.endswith(("top_k", "head_count", "key_length"))})
+ glm = _fake(base | {"indexer.k_norm.bias", "indexer_compressor_gate.weight", "indexer_compressor_ape.weight", "indexer_compressor_norm.weight"}, keys)
+ for ctx in (dsa, glm):
+ assert not IB.is_kpool(ctx, 0) and REGISTRY["dsa_indexer"].select(ctx, 0)
+ hy = _fake(base | {"indexer_compressor_value.weight", "indexer_compressor_gate.weight", "indexer_compressor_ape.weight", "indexer_compressor_norm.weight"}, keys)
+ assert IB.is_kpool(hy, 0) and not REGISTRY["dsa_indexer"].select(hy, 0)
+
+
[email protected]("tail", [True, False])
+def test_synthetic_small_topk(tail):
+ """selection actually exercised: top_k 16 (3 groups + tail, or 4 groups), 45 tokens, real layer-0 weights, random activations"""
+ torch.manual_seed(1)
+ W, n = weights(0), 45
+ x, qr = torch.randn(n, 3072), torch.randn(n, 1024)
+ sel = mk(W, top_k=16, select_tail=tail).forward(x, qr)
+ rows, sc = np_ref(x.numpy(), qr.numpy(), {k: v.numpy() for k, v in W.items()}, 16, tail=tail)
+ eq, err = compare(sel, rows, sc)
+ print(f"synthetic tail={tail}: rows set-equal {eq}, score max|d|/max|ref| {err:.2e}, max rows {max(len(r) for r in rows)}")
+ assert eq and err <= BAR
+ assert max(len(r) for r in rows) == (16 if tail else 19) and len(rows[n - 1]) == (12 if tail else 16) + ((n - 1) % 4 + 1 if tail else n % 4)
+
+
+def test_chunked_equals_oneshot():
+ """prefill in chunks then decode token by token == one call; also pooled keys carried across calls"""
+ torch.manual_seed(2)
+ W, n = weights(0), 61
+ x, qr = torch.randn(n, 3072), torch.randn(n, 1024)
+ a = mk(W, top_k=16).forward(x, qr)
+ m, parts, o = mk(W, top_k=16), [], 0
+ for c in (7, 16, 1, 1, 1, 13, 1, 1, 20):
+ parts.append(m.forward(x[o:o + c], qr[o:o + c])); o += c
+ assert o == n
+ rows = [r for p in parts for r in p.rows]
+ assert all(torch.equal(r1, r2) for r1, r2 in zip(a.rows, rows))
+ P = a.scores.shape[1]
+ for p, s0 in zip(parts, np.cumsum([0, 7, 16, 1, 1, 1, 13, 1, 1])):
+ k = p.scores.shape[0]
+ ref = a.scores[s0:s0 + k, :p.scores.shape[1]]
+ assert torch.equal(torch.isfinite(ref), torch.isfinite(p.scores)) and (ref[torch.isfinite(ref)] - p.scores[torch.isfinite(p.scores)]).abs().max() < 1e-4
+
+
+def test_rope_and_q8():
+ x = torch.randn(3, 2, 128)
+ pos = torch.tensor([0, 5, 977])
+ y = rope_tail(x, pos, 64, 1e7)
+ assert torch.equal(y[..., :64], x[..., :64]) and torch.equal(y[0], x[0])
+ assert torch.allclose(y.pow(2).sum(-1), x.pow(2).sum(-1), rtol=1e-5)
+ q = q8_act(x.reshape(-1, 128))
+ assert (q - x.reshape(-1, 128)).abs().max() < x.abs().max() / 127
+
+
+def real_inputs(ids):
+ """layer 0 attention inputs from the prompt tokens: the four streams are copies of the embedding, so the HC collapse is a
+ scalar times it and the RMSNorm of attn_norm removes the scalar: cur = rms(emb) * attn_norm.weight; qr = rms(cur Wq_a^T) * q_a_norm"""
+ g, _ = H.gg()
+ emb = H.emb_rows(ids)
+ an = g.get_tensor("blk.0.attn_norm.weight").float().reshape(-1)
+ cur = rms(emb, an, EPS)
+ ty, dims, _ = g.infos["blk.0.attn_q_a.weight"]
+ wqa = IB._w(g, "blk.0.attn_q_a.weight", ty, dims)
+ qn = g.get_tensor("blk.0.attn_q_a_norm.weight").float().reshape(-1)
+ return cur, rms(cur @ wqa.T, qn, EPS)
+
+
+def run_prompt(prompt, ndec):
+ idx = json.load(open(os.path.join(H.ORACLE, prompt, "index.json")))
+ ids = idx["prompt_ids"] + idx["gen_ids"][:ndec]
+ n0 = idx["n_prompt_tokens"]
+ assert len(idx["prompt_ids"]) == n0
+ cur, qr = real_inputs(ids)
+ out = {}
+ for q8 in (False, True):
+ m = KPoolIndexer(weights(0), eps=EPS, act_q8=q8)
+ pre = m.forward(cur[:n0], qr[:n0])
+ dec = [m.forward(cur[n0 + j:n0 + j + 1], qr[n0 + j:n0 + j + 1]) for j in range(ndec)]
+ out[q8] = (pre, dec)
+ return n0, cur, qr, out
+
+
[email protected]("prompt,ndec", [("p1_short_en", 4), ("p4_long_n700", 4), ("p5_long_n4000", 4)])
+def test_oracle_prompts_layer0(prompt, ndec):
+ n0, cur, qr, out = run_prompt(prompt, ndec)
+ pre, dec = out[False]
+ full = [torch.arange(t + 1, dtype=torch.int32) for t in range(n0)]
+ exercised = n0 > 2048 + 4
+ if not exercised:
+ # fewer than top_k rows: every causal row selected (the trivial case)
+ assert all(torch.equal(a, b) for a, b in zip(pre.rows, full))
+ assert all(torch.equal(d.rows[0], torch.arange(n0 + j + 1, dtype=torch.int32)) for j, d in enumerate(dec))
+ else:
+ lens = torch.tensor([len(r) for r in pre.rows])
+ assert int(lens.max()) <= 2048 and (lens[:2048] == torch.arange(1, 2049)).all()
+ t = n0 - 1
+ assert len(pre.rows[t]) == 4 * 511 + t % 4 + 1 and (pre.rows[t] != torch.arange(t + 1, dtype=torch.int32)[:len(pre.rows[t])]).any()
+ assert all(len(d.rows[0]) == 4 * 511 + (n0 + j) % 4 + 1 for j, d in enumerate(dec))
+ # full numpy reference on a prefix covering the first selection (all groups visible beyond 511)
+ m = 2400
+ rows, sc = np_ref(cur[:m].numpy(), qr[:m].numpy(), {k: v.numpy() for k, v in weights(0).items()}, 2048)
+ sel = KPoolIndexer(weights(0), eps=EPS).forward(cur[:m], qr[:m])
+ eq, err = compare(sel, rows, sc)
+ print(f"{prompt} L0 prefix {m}: rows set-equal {eq}, score rel {err:.2e}")
+ assert eq and err <= BAR
+ nsel = sum(1 for r, t in zip(rows, range(m)) if len(r) < t + 1)
+ print(f" queries with a real selection (rows < causal): {nsel} of {m}")
+ assert nsel > 0
+ # q8 activation emulation: scores and picks vs the float activations
+ pre8 = out[True][0]
+ f = torch.isfinite(pre.scores)
+ rel = float((pre.scores[f] - pre8.scores[f]).abs().max() / pre.scores[f].abs().max())
+ same = sum(torch.equal(a, b) for a, b in zip(pre.rows, pre8.rows))
+ print(f"{prompt} L0 n={n0}+{ndec} dec: selection exercised={exercised}; q8-act vs fp32-act score rel {rel:.2e}, "
+ f"rows identical for {same}/{n0} queries")
+ assert rel < 2e-2
+
+
+if __name__ == "__main__":
+ sys.exit(pytest.main(["-q", "-s", __file__]))