Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Hy4 KV10: fp16 indexer pool (HY4_IX_POOL16) and rope rows from positions (HY4_ROPE_POS), both in HY4_KV_COMPACT=1: 9220 bytes per token
YanissAmz5d735d0cef7b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex acabcdf..a6cc56e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,7 @@ Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, requ## Unreleased (1.9.3)- KV footprint: `HY4_KV_FP8_MTP=1` keeps the draft layer's K cache in fp8 too (needs `HY4_KV_FP8=1`), `HY4_KV_COMPACT=1` sets fp8 trunk + draft cache + the 1024-row window ring in one switch (about 11 KB per token instead of 113 KB); all off by default. `tools/hy4/kv_bytes.py` prints the per-component table, `tools/hy4/kv_bytes_probe.py` measures it. CPU tests: `tests/test_kv_bytes.py`.+- KV footprint 2: `HY4_IX_POOL16=1` (fp16 indexer pool, -832 bytes per token) and `HY4_ROPE_POS=1` (rope cos / sin rows evaluated from the positions of a call, no tables to the full context, -1280 bytes per token), both part of `HY4_KV_COMPACT=1` now: 9220 bytes per token (9.0 KB, 9.1 KB at 1M) instead of 11332. Off by default. CPU tests (including the Triton interpreter): `tests/test_kv10.py`; GPU gate: `tools/hy4/step/kv10_driver.py`.- Long context: opt-in fp8 e4m3 latent K cache for the full-attention layers (`HY4_KV_FP8=1`, off by default; 644 bytes per token and layer instead of 2304) and the head-blocked split-K sparse attend that reads it (`HY4_LC_HB`, `HY4_LC_HB_SPLIT`; only runs on the fp8 cache). `-c 65536` keeps the fp32 cache. Guide: `doc/hy4.md`, "Long context option". CPU tests: `tests/test_kv_fp8.py`, `tests/test_hy4_shipped_flags.py`.## 1.9.1diff --git a/doc/hy4.md b/doc/hy4.mdindex 28d4e2c..100b1fb 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -101,17 +101,18 @@ The free memory is steady, not a load transient: at the default `-c 65536` it st### KV bytes per token (persistent buffers at full capacity, `python tools/hy4/kv_bytes.py`)-| component | 1.9.1 default | `HY4_KV_COMPACT=1` |-|---|---|---|-| latent K, 12 trunk full-attention layers | 27648 (fp32 2304 each) | 7728 (fp8 644 each) |-| latent K, MTP draft layer | 2304 | 644 (`HY4_KV_FP8_MTP`) |-| 30 window layers | 69120 | 0 (ring of 1024 rows, 71 MB constant, `HY4_SWA_RING`) |-| indexer pool, 13 layers (one 128-d fp32 key per 4 tokens) | 1664 | 1664 |-| indexer value / gate rows, 13 layers | 13312 | 0 (ring, 54 MB constant) |-| token history, arange, rope tables | 1296 | 1296 |-| total | 115344 B (112.6 KB) | 11332 B (11.1 KB) + 125 MB |--The default row matches the measured slope of the memory table above (98 to 118 KB per token). `HY4_KV_COMPACT=1` is a shortcut that sets `HY4_KV_FP8=1`, `HY4_KV_FP8_MTP=1` and `HY4_SWA_RING=1024` unless you set them yourself; add `--draft-fill-rows 4096` to the serve command so the draft states of a long prompt (fp32 [n, 3072], 12 KB per token) are not kept. Transients not in the table: one prefill chunk of indexer scores (`chunk x n / 4 x 4` bytes) and, on the fp8 cache, one fp16 dequantised copy of one layer's cache for the sparse prefill (1152 bytes per token, freed per layer). Left to the 10 KB mark: the indexer pool in fp16 (-832) and the rope tables (1280). Measured: `tools/hy4/kv_bytes_probe.py`.+| component | 1.9.1 default | `HY4_KV_COMPACT=1` before kv10 (bcfb9e5) | `HY4_KV_COMPACT=1` now |+|---|---|---|---|+| latent K, 12 trunk full-attention layers | 27648 (fp32 2304 each) | 7728 (fp8 644 each) | 7728 |+| latent K, MTP draft layer | 2304 | 644 (`HY4_KV_FP8_MTP`) | 644 |+| 30 window layers | 69120 | 0 (ring of 1024 rows, 71 MB constant, `HY4_SWA_RING`) | 0 |+| indexer pool, 13 layers (one 128-d key per 4 tokens) | 1664 (fp32) | 1664 | 832 (fp16, `HY4_IX_POOL16`) |+| indexer value / gate rows, 13 layers | 13312 | 0 (ring, 54 MB constant) | 0 |+| token history, arange | 16 | 16 | 16 |+| rope tables (indexer cos / sin 256 + two attention tables 2 x 512) | 1280 | 1280 | 0 (`HY4_ROPE_POS`: rows of the call, evaluated from the positions) |+| total | 115344 B (112.6 KB) | 11332 B (11.1 KB) + 120 MB | 9220 B (9.0 KB) + 120 MB (9340 B = 9.1 KB per token at 1M) |++The default row matches the measured slope of the memory table above (98 to 118 KB per token). `HY4_KV_COMPACT=1` is a shortcut that sets `HY4_KV_FP8=1`, `HY4_KV_FP8_MTP=1`, `HY4_SWA_RING=1024`, `HY4_IX_POOL16=1` and `HY4_ROPE_POS=1` unless you set them yourself; add `--draft-fill-rows 4096` to the serve command so the draft states of a long prompt (fp32 [n, 3072], 12 KB per token) are not kept. `HY4_IX_POOL16=1` stores the pooled indexer keys in fp16 (the prefill scorer already scores with the fp16 copy); it can change which groups the top-k picks at the cut-off, so it is gated on the top-k set overlap and a paired NLL (`tools/hy4/step/kv10_driver.py`). `HY4_ROPE_POS=1` evaluates the rope cos / sin of a call from its positions in fp64 (the same expression the tables were built with) instead of keeping tables to the full context; neither lever runs with `--slots > 1`. Transients not in the table: one prefill chunk of indexer scores (`chunk x n / 4 x 4` bytes), the rope rows of one call (about 1.3 KB per row of the call), and, on the fp8 cache, one fp16 dequantised copy of one layer's cache for the sparse prefill (1152 bytes per token, freed per layer). Measured: `tools/hy4/kv_bytes_probe.py`.### Long context option: fp8 KV (`HY4_KV_FP8=1`, off by default)diff --git a/exllamav3/loader/attn_eager.py b/exllamav3/loader/attn_eager.pyindex 69e1475..2fb656f 100644--- a/exllamav3/loader/attn_eager.py+++ b/exllamav3/loader/attn_eager.py@@ -13,6 +13,7 @@ import osimport torchfrom . import mla_bgemv as _BGfrom . import kv_fused as _KVF+from . import rope_rows as _RR_F = os.environ.get("HY4_ATTN_EAGER", "0")ENABLED = _F in ("1", "2")@@ -54,11 +55,19 @@ def table(P, base, dev, pos):return tab+def table_rows(P, base, dev, pos):+ """-> (tab, per_row): the rope rows the kernels read. HY4_ROPE_POS=1: rows of THIS call's positions [T, 2, P/2, 2] (per_row = True, the kernel indexes by row),+ else the full-context table (indexed by position)"""+ if _RR.ENABLED:+ return _RR.attn_rows(P, base, pos), True+ return table(P, base, dev, pos), False++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]+ g = _RR.attn_rows(P, base, pos) if _RR.ENABLED else 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))@@ -93,7 +102,8 @@ def q(m, cur, pos):qq = (m._q(qr, "wq_b") @ m.wq_b.T).view(T, H, m.hd)qn = qq[..., :m.nope]if _KVF.ENABLED and 1 <= T <= _KVF.MAXT and qq.is_cuda: # HY4_KV_FUSED: the pe rotation in one launch (no slice copies)- qp = _KVF.rope_q(qq, table(m.rope_dim, m.theta, qq.device, pos), pos, m.nope, m.rope_dim)+ tab, per_row = table_rows(m.rope_dim, m.theta, qq.device, pos)+ qp = _KVF.rope_q(qq, tab, pos, m.nope, m.rope_dim, per_row)else:qp = rope(qq[..., m.nope:], pos, m.theta)qlat = m.bg_kb.mv(m._q(qn, "kb")) if (_BG.ENABLED and T <= _BG.MAXT and getattr(m, "bg_kb", None) is not None) else torch.einsum("hrk,thk->thr", m.wk_b, m._q(qn, "kb"))diff --git a/exllamav3/loader/indexer_fused.py b/exllamav3/loader/indexer_fused.pyindex 46763ba..80367b7 100644--- a/exllamav3/loader/indexer_fused.py+++ b/exllamav3/loader/indexer_fused.py@@ -11,8 +11,14 @@ Ties at the top-k boundary: torch.topk order is unspecified (the CPU reference t"""from __future__ import annotationsimport math+import osimport torch+from . import rope_rows as _RR++POOL16 = os.environ.get("HY4_IX_POOL16", "0") == "1" # pooled keys stored in fp16 (half the bytes; the prefill scorer already scores with the fp16 copy); selection reads fp16 either way+POOL_DT = torch.float16 if POOL16 else torch.float32+def _rms(x, w, eps):x = x.float()@@ -33,7 +39,7 @@ class FusedKPoolIndexer:self.n_top = top_k // kpool - self.tailself.n = 0 # tokens seen (host int)self.P = 0 # pooled groups stored (host int)- self.pool = torch.zeros(max(cap // kpool, 16), head_dim, device=self.dev)+ self.pool = torch.zeros(max(cap // kpool, 16), head_dim, device=self.dev, dtype=POOL_DT)self.vg = None # [<kpool, 2d] tokens of the open groupself._cs = None # (cos, sin) [Lpos, rope_dim/2] fp32self.last_scores = None@@ -55,8 +61,11 @@ class FusedKPoolIndexer: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]+ if _RR.ENABLED: # HY4_ROPE_POS: rows of these positions, no table to the full context+ c, s = _RR.ix_rows(self.base, self.rope_dim, pos)+ else:+ 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]@@ -88,7 +97,7 @@ class FusedKPoolIndexer:m = buf.shape[0] // kif 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 = torch.empty(max(2 * self.pool.shape[0], self.P + m), d, device=self.dev, dtype=self.pool.dtype)big[:self.P] = self.pool[:self.P]self.pool = bigself.pool[self.P:self.P + m] = self._pool_groups(buf[:m * k], self.P)@@ -98,7 +107,7 @@ class FusedKPoolIndexer: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]+ pk = self.pool[:P].to(iq.dtype)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)diff --git a/exllamav3/loader/kv_fused.py b/exllamav3/loader/kv_fused.pyindex 36ec888..2eac5a2 100644--- a/exllamav3/loader/kv_fused.py+++ b/exllamav3/loader/kv_fused.py@@ -12,7 +12,7 @@ MAXT = int(os.environ.get("HY4_KV_FUSED_MAXT", "16")) # rows per step the f@triton.jit-def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, RING: tl.constexpr):+def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, RING: tl.constexpr, TROW: tl.constexpr = 0):row = tl.program_id(0) # one program per row: T = 1 decode and the T-row verify share the kernelc_ptr += row * scpos = tl.load(pos_ptr + row)@@ -30,7 +30,10 @@ def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, Poffh = tl.arange(0, H)x0 = tl.load(c_ptr + R + 2 * offh)x1 = tl.load(c_ptr + R + 2 * offh + 1)- tb = tab_ptr + pos * (2 * H * 2)+ if TROW: # HY4_ROPE_POS: the table holds the rows of this call (row t = the t-th position)+ tb = tab_ptr + row * (2 * H * 2)+ else:+ tb = tab_ptr + pos * (2 * H * 2)a0 = tl.load(tb + offh * 2) # ca1 = tl.load(tb + offh * 2 + 1) # sb0 = tl.load(tb + H * 2 + offh * 2) # -s@@ -39,13 +42,13 @@ def _k_kv(c_ptr, w_ptr, tab_ptr, pos_ptr, k_ptr, sc, sk, eps, R: tl.constexpr, Ptl.store(k_ptr + slot * sk + R + 2 * offh + 1, x0 * a1 + x1 * b1)-def write_row(c, w, tab, pos, kbuf, R, P, eps, ring=0):+def write_row(c, w, tab, pos, kbuf, R, P, eps, ring=0, per_row=False):"""c [T, R+P] fp32 (unit column stride), w [R], tab [n, 2, P/2, 2], pos [T] long device, kbuf [cap, R+P] fp32"""- _k_kv[(c.shape[0],)](c, w, tab, pos, kbuf, c.stride(0), kbuf.stride(0), eps, R=R, P=P, BR=triton.next_power_of_2(R), RING=ring, num_warps=4)+ _k_kv[(c.shape[0],)](c, w, tab, pos, kbuf, c.stride(0), kbuf.stride(0), eps, R=R, P=P, BR=triton.next_power_of_2(R), RING=ring, TROW=int(per_row), num_warps=4)@triton.jit-def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqt, sqh, sot, soh, NOPE: tl.constexpr, P: tl.constexpr):+def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqt, sqh, sot, soh, NOPE: tl.constexpr, P: tl.constexpr, TROW: tl.constexpr = 0):h = tl.program_id(0)row = tl.program_id(1)q_ptr += row * sqt@@ -55,7 +58,10 @@ def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqt, sqh, sot, soh, NOPE: tl.consteoffh = tl.arange(0, H)x0 = tl.load(q_ptr + h * sqh + NOPE + 2 * offh)x1 = tl.load(q_ptr + h * sqh + NOPE + 2 * offh + 1)- tb = tab_ptr + pos * (2 * H * 2)+ if TROW:+ tb = tab_ptr + row * (2 * H * 2)+ else:+ tb = tab_ptr + pos * (2 * H * 2)a0 = tl.load(tb + offh * 2)a1 = tl.load(tb + offh * 2 + 1)b0 = tl.load(tb + H * 2 + offh * 2)@@ -64,9 +70,9 @@ def _k_qrope(q_ptr, tab_ptr, pos_ptr, o_ptr, sqt, sqh, sot, soh, NOPE: tl.constetl.store(o_ptr + h * soh + 2 * offh + 1, x0 * a1 + x1 * b1)-def rope_q(qq, tab, pos, nope, P):+def rope_q(qq, tab, pos, nope, P, per_row=False):"""qq [T, H, hd] fp32 (unit last stride; the pe part is qq[..., nope:nope+P]), pos [T] -> rotated pe [T, H, P] (one launch)"""T, H = qq.shape[0], qq.shape[1]out = torch.empty(T, H, P, dtype=torch.float32, device=qq.device)- _k_qrope[(H, T)](qq, tab, pos, out, qq.stride(0), qq.stride(1), out.stride(0), out.stride(1), NOPE=nope, P=P, num_warps=1)+ _k_qrope[(H, T)](qq, tab, pos, out, qq.stride(0), qq.stride(1), out.stride(0), out.stride(1), NOPE=nope, P=P, TROW=int(per_row), num_warps=1)return outdiff --git a/exllamav3/loader/lc_sparse.py b/exllamav3/loader/lc_sparse.pyindex 073b7c6..cf7eb38 100644--- a/exllamav3/loader/lc_sparse.py+++ b/exllamav3/loader/lc_sparse.py@@ -286,7 +286,7 @@ def sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks, scl=None)def check_rows(iq, wt, pool, pos, Pb, n_top, kp, sel):"""debug: dense reference selection (the stock torch path of step_graph.indexer_forward_static) vs the sparse one; counts rows whose group sets differand the largest score gap between a swapped pair (a pure tie / rounding swap has gap ~ 1e-7)"""- kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pool[:Pb]))+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, pool[:Pb].to(iq.dtype)))sc = (kq * wt[:, :, None]).sum(1)gend = torch.arange(Pb, device=iq.device) * kp + (kp - 1)vis = gend[None] < pos[:, None]diff --git a/exllamav3/loader/pool_fused.py b/exllamav3/loader/pool_fused.pyindex 23eb053..98341b8 100644--- a/exllamav3/loader/pool_fused.py+++ b/exllamav3/loader/pool_fused.py@@ -5,6 +5,8 @@ import torchimport tritonimport triton.language as tl+from . import rope_rows as _RR+ENABLED = False@@ -36,7 +38,7 @@ def _pooled(vgb, ape, g0, offs, k: tl.constexpr, d: tl.constexpr, VR: tl.constex@triton.jit-def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d: tl.constexpr, rd: tl.constexpr, VR: tl.constexpr):+def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d: tl.constexpr, rd: tl.constexpr, VR: tl.constexpr, TROW: tl.constexpr = 0):t = tl.program_id(0)p0 = tl.load(pos + t)gi = p0 // k@@ -54,14 +56,21 @@ def _pool_kernel(vgb, pos, ape, pnw, cosb, sinb, pool, eps, k: tl.constexpr, d:ob = oa + 1na = _pooled(vgb, ape, g0, oa, k, d, VR) * r * tl.load(pnw + oa)nb = _pooled(vgb, ape, g0, ob, k, d, VR) * r * tl.load(pnw + ob)- c = tl.load(cosb + g0 * h + ii)- s = tl.load(sinb + g0 * h + ii)+ if TROW: # HY4_ROPE_POS: cos / sin rows of the group start of each row [T, h]+ c = tl.load(cosb + t * h + ii)+ s = tl.load(sinb + t * h + ii)+ else:+ c = tl.load(cosb + g0 * h + ii)+ s = tl.load(sinb + g0 * h + ii)tl.store(pool + gi * d + oa, na * c - nb * s)tl.store(pool + gi * d + ob, na * s + nb * c)def pool_update(ix, pos):"""pos [T] long (device): update the pool row of each position's group from ix.vgb (the new rows are already in place)"""- cs, sn = ix._table(ix._max_pos)+ if _RR.ENABLED:+ cs, sn = _RR.ix_rows(ix.base, ix.rope_dim, pos, ix.k)+ else:+ cs, sn = ix._table(ix._max_pos)ape = ix.w["ape"]- _pool_kernel[(pos.shape[0],)](ix.vgb, pos, ape, ix.w["pool_norm"], cs, sn, ix.pool, ix.eps, k=ix.k, d=ix.d, rd=ix.rope_dim, VR=getattr(ix, "vg_ring", 0))+ _pool_kernel[(pos.shape[0],)](ix.vgb, pos, ape, ix.w["pool_norm"], cs, sn, ix.pool, ix.eps, k=ix.k, d=ix.d, rd=ix.rope_dim, VR=getattr(ix, "vg_ring", 0), TROW=int(_RR.ENABLED))diff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.pyindex 279a38c..5d590b5 100644--- a/exllamav3/loader/prefill_kernels.py+++ b/exllamav3/loader/prefill_kernels.py@@ -385,7 +385,7 @@ def _pf_indexer_forward(self, x, qr, n_keys=None):m = buf.shape[0] // kif 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 = torch.empty(max(2 * self.pool.shape[0], self.P + m), d, device=self.dev, dtype=self.pool.dtype)big[:self.P] = self.pool[:self.P]self.pool = bigwith t("f ixk: pool groups"):diff --git a/exllamav3/loader/rope_rows.py b/exllamav3/loader/rope_rows.pynew file mode 100644index 0000000..3721c92--- /dev/null+++ b/exllamav3/loader/rope_rows.py@@ -0,0 +1,63 @@+"""HY4_ROPE_POS=1: rope cos / sin rows computed from the positions of the call, no per-token table (pure torch, no triton).++The 1.9.1 tables are built once to the full context: attn_eager [n, 2, P/2, 2] fp32 per rope theta (512 B per token each, full + window layers) and the indexer+cos / sin [n, P/2] (256 B per token). Rope only ever looks up the positions of the rows in flight (T <= one prefill chunk), so these rows are evaluated from `pos`+instead: fp64 angle = pos * inv_freq (the same expression as the table build, so the fp32 values are the same), then cos / sin -> fp32.++Memo: the rows depend only on (pos values, theta), so every layer of one call shares them. The memo lives on the pos tensor object and is valid for the same+object at the same in-place version (a static graph input is overwritten in place: the version moves). Inside a graph capture only the GraphDecoder.pos view+(marked `_rope_ok`, a fresh object per segment body) is memoised: a replay does not run python, so an older capture's tensor must never be reused. STATS counts evaluations (FIRES)."""+import os++import torch++ENABLED = os.environ.get("HY4_ROPE_POS", "0") == "1"+STATS = {"attn": 0, "ix": 0}+_INV = {}+++def _inv(P, base, dev, cpu_build):+ """inv_freq [P/2] fp64 on dev, built like the table it replaces: attn_eager builds on the device, the indexer on the host (then moved)"""+ key = (P, float(base), str(dev), cpu_build)+ v = _INV.get(key)+ if v is None:+ if cpu_build:+ v = (base ** (-torch.arange(0, P, 2, dtype=torch.float64) / P)).to(dev)+ else:+ v = base ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=dev) / P)+ _INV[key] = v+ return v+++def _memo(pos, key, build):+ if pos.is_cuda and torch.cuda.is_current_stream_capturing() and not getattr(pos, "_rope_ok", False):+ return build() # a capture on a position tensor that does not start a fresh object per capture (GraphDecoder.pos does): no memo, evaluate here+ m = pos.__dict__.setdefault("_rope_rows", {})+ hit = m.get(key)+ if hit is not None and hit[0] == pos._version:+ return hit[1]+ val = build()+ m[key] = (pos._version, val)+ return val+++def attn_rows(P, base, pos):+ """pos [T] long -> [T, 2, P/2, 2] fp32 = rows (cos, sin | -sin, cos) of the attn_eager table for these positions"""+ def build():+ STATS["attn"] += 1+ th = pos.double()[:, None] * _inv(P, base, pos.device, False)[None, :]+ c, s = th.cos().float(), th.sin().float()+ tab = torch.empty(pos.shape[0], 2, P // 2, 2, dtype=torch.float32, device=pos.device)+ tab[:, 0, :, 0], tab[:, 0, :, 1], tab[:, 1, :, 0], tab[:, 1, :, 1] = c, s, -s, c+ return tab+ return _memo(pos, ("attn", P, float(base)), build)+++def ix_rows(base, rope_dim, pos, group=0):+ """pos [T] long -> (cos, sin) [T, rope_dim/2] fp32 contiguous, like indexer_fused._table()[pos]; group > 0: the rows of the group start (pos // group) * group"""+ def build():+ STATS["ix"] += 1+ p = (pos // group) * group if group else pos+ th = p.double()[:, None] * _inv(rope_dim, base, pos.device, True)[None, :]+ return th.cos().float().contiguous(), th.sin().float().contiguous()+ return _memo(pos, ("ix", rope_dim, float(base), group), build)diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.pyindex 2dd6b25..57d3bdc 100644--- a/exllamav3/loader/step_graph.py+++ b/exllamav3/loader/step_graph.py@@ -52,6 +52,8 @@ from . import pool_fused as _PFfrom . import lc_sparse as _LS_PF.ENABLED = os.environ.get("HY4_IDX_POOLK", "0") == "1"from . import kv_fp8 as _KV8+from . import rope_rows as _RR+POOL16 = os.environ.get("HY4_IX_POOL16", "0") == "1" # indexer pooled keys stored in fp16 (half the bytes; the prefill scorer already scores with the fp16 copy; selection reads fp16, top-k set overlap gate in tests/test_kv10.py)KV_FP8 = os.environ.get("HY4_KV_FP8", "0") == "1" # latent K cache of the full-attention layers in fp8 e4m3 + per-token scale (+ bf16 rope dims)@@ -60,9 +62,11 @@ def indexer_static_init(ix, cap):k, d = ix.k, ix.drows = cap // kif ix.pool.shape[0] < rows:- big = torch.zeros(rows, d, device=ix.dev)+ big = torch.zeros(rows, d, device=ix.dev, dtype=torch.float16 if POOL16 else ix.pool.dtype)big[:ix.P] = ix.pool[:ix.P]ix.pool = big+ elif POOL16 and ix.pool.dtype != torch.float16:+ ix.pool = ix.pool.half()vgb = getattr(ix, "vgb", None) # per-position (value | gate) rows [cap, 2d]: a rejected / re-run position just overwrites its rowif vgb is None:ix.vg_ring = VG_RING if (VG_RING and VG_RING < cap) else 0 # HY4_SWA_RING: only the open group (+ the rows of one batch call) is ever read: slot = position % VG_RING@@ -71,7 +75,8 @@ def indexer_static_init(ix, cap):m = ix.vg.shape[0]vgb[(torch.arange(ix.n - m, ix.n, device=ix.dev) % ix.vg_ring) if ix.vg_ring else slice(ix.n - m, ix.n)] = ix.vgix._max_pos = cap- ix._table(cap)+ if not _RR.ENABLED: # HY4_ROPE_POS: the rope rows of a call come from its positions, no table to the full context+ ix._table(cap)@torch.no_grad()@@ -92,7 +97,7 @@ def indexer_keys_static(ix, x, pos, ar):v, g = rows[..., :d].reshape(-1, k, d), rows[..., d:].reshape(-1, k, d)p = (torch.softmax(g + ix.w["ape"][None], dim=1) * v).sum(1)pooled = ix._rope(_rms(p, ix.w["pool_norm"], ix.eps), g0)- ix.pool.index_copy_(0, pos // k, pooled) # a group still open holds partial data here; it stays masked until it is complete+ ix.pool.index_copy_(0, pos // k, pooled.to(ix.pool.dtype)) # a group still open holds partial data here; it stays masked until it is complete@torch.no_grad()@@ -123,7 +128,7 @@ def indexer_forward_static(ix, x, qr, pos, Nb, ar):if _LS.CHECK and not torch.cuda.is_current_stream_capturing():_LS.check_rows(iq, wt, ix.pool, pos, Pb, ix.n_top, k, sel)return sel- kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, ix.pool[:Pb]))+ kq = torch.relu(torch.einsum("nhd,pd->nhp", iq, ix.pool[:Pb].to(iq.dtype)))sc = (kq * wt[:, :, None]).sum(1)gend = ar[:Pb] * k + (k - 1)vis = (gend[None] < pos[:, None]) if ix.tail else (gend[None] <= pos[:, None])@@ -176,6 +181,7 @@ class _GS:self.inp = torch.zeros(2, TM, dtype=torch.long, device=dev) # row 0 tokens, row 1 positions (first T columns used)self.ar = torch.arange(cap, device=dev)self.eng_raw = self.eng_valid = None+ self._pv = None@propertydef tok(self):@@ -183,7 +189,14 @@ class _GS:@propertydef pos(self):- return self.inp[1, :self.T]+ """the position row of this step: ONE view object per segment body (new_pos() starts a new one), so the rope rows computed from it (HY4_ROPE_POS, memo on the object) are shared by the layers"""+ if self._pv is None or self._pv.shape[0] != self.T:+ self._pv = self.inp[1, :self.T]+ self._pv._rope_ok = True+ return self._pv++ def new_pos(self):+ self._pv = None# -- Engram: rows are staged on the host before the replay, decoded + applied inside the graphdef engram(self, fw, i, x):@@ -216,9 +229,9 @@ class _GS:from . import attn_eager as AE, kv_fused as KVFb = _ns.state(self.fw).kv[i]c = mla._q(cur, "wkv_a") @ mla.wkv_a.T- tab = AE.table(mla.rope_dim, mla.theta, self.fw.dev, pos)+ tab, per_row = AE.table_rows(mla.rope_dim, mla.theta, self.fw.dev, pos)ring = getattr(mla, "kv_ring", 0)- KVF.write_row(c, mla.kv_a_norm, tab, pos, b, mla.R, mla.rope_dim, mla.eps, ring=ring)+ KVF.write_row(c, mla.kv_a_norm, tab, pos, b, mla.R, mla.rope_dim, mla.eps, ring=ring, per_row=per_row)return b if ring else b[:self.Nb]def indexer(self, fw, i, cur, qr, N):@@ -354,6 +367,7 @@ class GraphDecoder:def body_seg(self, si, x, bnds):fw, gs = self.fw, self.gslo, hi = bnds[si]+ gs.new_pos() # every segment body (eager warm-up, graph capture) starts its own position view: no rope rows memo outlives a captureif si == 0:e = _ns.gather_dequant_q8_0(self.st.table, gs.tok)if PERT is not None: # noise-ensemble null arm: 1e-6 fixed-seed perturbation of the embedding output (quality gate, never in production)@@ -436,6 +450,7 @@ class GraphDecoder:cgs.append(cg)finally:fw._gs = None+ gs.new_pos()g = self.graphs[key] = (cgs, x)self.stats["captures"] += 1self.stats["capture_s"] += time.perf_counter() - t_capdiff --git a/tests/kv10_interp.py b/tests/kv10_interp.pynew file mode 100644index 0000000..8a92124--- /dev/null+++ b/tests/kv10_interp.py@@ -0,0 +1,65 @@+"""Triton interpreter checks of the kv10 kernel changes on CPU tensors (TRITON_INTERPRET=1, no GPU): rope rows vs the full table, fp16 pool store. Run by tests/test_kv10.py in a subprocess."""+import importlib+import os+import sys+import types++os.environ["TRITON_INTERPRET"] = "1"+import torch++LOADER = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "exllamav3", "loader")+pkg = types.ModuleType("kvpk")+pkg.__path__ = [LOADER]+sys.modules["kvpk"] = pkg+RR = importlib.import_module("kvpk.rope_rows")+KF = importlib.import_module("kvpk.kv_fused")+PF = importlib.import_module("kvpk.pool_fused")+torch.manual_seed(0)+BASE, P, R, T, N = 1e7, 64, 512, 5, 4096+pos = torch.tensor([3, 4090, 777, 778, 1500], dtype=torch.long)+tab = RR.attn_rows(P, BASE, torch.arange(N)) # the full table (what attn_eager._build holds)+rows = RR.attn_rows(P, BASE, pos)+assert torch.equal(rows, tab[pos])++# kv write: table indexed by position == rows indexed by row, ring on and off+c = torch.randn(T, R + P)+w = torch.randn(R)+for ring in (0, 1024):+ k0, k1 = torch.zeros(N, R + P), torch.zeros(N, R + P)+ KF.write_row(c, w, tab, pos, k0, R, P, 1e-6, ring=ring)+ KF.write_row(c, w, rows, pos, k1, R, P, 1e-6, ring=ring, per_row=True)+ assert torch.equal(k0, k1) and k0.abs().sum() > 0, ring+# q rope+H, NOPE = 4, 128+q = torch.randn(T, H, NOPE + P)+assert torch.equal(KF.rope_q(q, tab, pos, NOPE, P), KF.rope_q(q, rows, pos, NOPE, P, True))++# pool update: cos / sin of the group start by position vs by row; fp16 pool store+k, d, rd, VR = 4, 128, 64, 0+vgb = torch.randn(N, 2 * d)+ape = torch.randn(k, d)+pnw = torch.randn(d)+cs_t, sn_t = RR.ix_rows(BASE, rd, torch.arange(N)) # table [N, 32] (cos | sin)+cs_r, sn_r = RR.ix_rows(BASE, rd, pos, k) # rows of the group starts of `pos`+assert torch.equal(cs_r, cs_t[(pos // k) * k]) and torch.equal(sn_r, sn_t[(pos // k) * k])+p32, p32r, p16 = torch.zeros(N // k, d), torch.zeros(N // k, d), torch.zeros(N // k, d, dtype=torch.float16)+PF._pool_kernel[(T,)](vgb, pos, ape, pnw, cs_t, sn_t, p32, 1e-6, k=k, d=d, rd=rd, VR=VR)+PF._pool_kernel[(T,)](vgb, pos, ape, pnw, cs_r, sn_r, p32r, 1e-6, k=k, d=d, rd=rd, VR=VR, TROW=1)+PF._pool_kernel[(T,)](vgb, pos, ape, pnw, cs_r, sn_r, p16, 1e-6, k=k, d=d, rd=rd, VR=VR, TROW=1)+g = pos // k+assert torch.equal(p32[g], p32r[g]) and p32[g].abs().sum() > 0+assert torch.equal(p16[g], p32r[g].half()) # the fp16 pool holds the fp32 value rounded to nearest+# the sparse selection kernel on an fp16 pool (what HY4_IX_POOL16 feeds it) vs the fp32 pool: group sets of the top-k+LS = importlib.import_module("kvpk.lc_sparse")+Pb, Hh, Tt, n_top = 1024, 16, 4, 127+pool = torch.randn(Pb, 128)+pool = pool / pool.pow(2).mean(-1, keepdim=True).sqrt()+iq = torch.randn(Tt, Hh, 128)+wt = torch.rand(Tt, Hh) / 45+qpos = torch.tensor([Pb * 4 + 8] * Tt, dtype=torch.long)+i32, n32 = LS.select_groups(iq, wt, pool, qpos, Pb, n_top, 4, True)+i16, n16 = LS.select_groups(iq, wt, pool.half().contiguous(), qpos, Pb, n_top, 4, True)+ov = [len(set(i32[t, :int(n32[t])].tolist()) & set(i16[t, :int(n16[t])].tolist())) / max(int(n32[t]), 1) for t in range(Tt)]+assert min(ov) > 0.95 and int(n32[0]) == n_top, ov+print("KV10_SELECT_OVERLAP min %.4f" % min(ov))+print("KV10_INTERP_OK")diff --git a/tests/test_kv10.py b/tests/test_kv10.pynew file mode 100644index 0000000..4ec50df--- /dev/null+++ b/tests/test_kv10.py@@ -0,0 +1,223 @@+"""zero-GPU checks of the 1.9.2 KV10 levers: HY4_IX_POOL16 (fp16 indexer pool), HY4_ROPE_POS (rope rows from positions), bytes per token <= 10 KB, top-k set overlap fp32 vs fp16 pool"""+import ast+import importlib.util+import os+import re+import subprocess+import sys++import pytest++HERE = os.path.dirname(os.path.abspath(__file__))+TREE = os.path.dirname(HERE)+LOADER = os.path.join(TREE, "exllamav3", "loader")+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))+torch = pytest.importorskip("torch")+++def _mod(name):+ sp = importlib.util.spec_from_file_location(name + "_t", os.path.join(LOADER, name + ".py"))+ m = importlib.util.module_from_spec(sp)+ sp.loader.exec_module(m)+ return m+++def _src(path, name, cls=None):+ text = open(os.path.join(TREE, path)).read()+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return ast.get_source_segment(text, node)+ raise AssertionError(name)+++def test_bytes_table_under_10kb():+ import kv_bytes as KB+ d = KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2, rope_pos=True)+ t, c = KB.total(d)+ assert t == 7728 + 644 + 832 + 16 and t == 9220+ assert KB.at_1m(d) < 10 * 1024 and KB.at_1m(d) < 10000 # owner rule: <= 10 KB / token at 1M (both readings of KB)+ assert KB.total(KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True))[0] == 11332 # bcfb9e5 unchanged without the new levers+ assert KB.total(KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2))[0] > 10 * 1024 # the pool alone is not enough+ assert KB.total(KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True, rope_pos=True))[0] > 10000 # nor are the rope rows alone+++def test_attn_rope_rows_equal_the_table():+ RR = _mod("rope_rows")+ build = {}+ exec(_src("exllamav3/loader/attn_eager.py", "_build"), {"torch": torch}, build)+ n = 100000+ for base in (1e7, 10000.0):+ tab = build["_build"](64, base, n, "cpu")+ pos = torch.cat([torch.tensor([0, 1, n - 1, 65535, 65536]), torch.randint(0, n, (4000,))])+ assert torch.equal(RR.attn_rows(64, base, pos), tab[pos])+++def test_indexer_rope_rows_equal_the_table():+ RR = _mod("rope_rows")+ src = _src("exllamav3/loader/indexer_fused.py", "_table")+ ns = {"torch": torch}+ exec(compile("class M:\n _TABS = {}\n" + "\n".join(" " + ln for ln in src.splitlines()), "t", "exec"), ns)+ m = ns["M"]()+ m.base, m.rope_dim, m.dev, m._cs = 1e7, 64, "cpu", None+ cos, sin = m._table(50000)+ pos = torch.cat([torch.tensor([0, 3, 4, 49999]), torch.randint(0, 50000, (3000,))])+ c, s = RR.ix_rows(1e7, 64, pos)+ assert torch.equal(c, cos[pos]) and torch.equal(s, sin[pos])+ c, s = RR.ix_rows(1e7, 64, pos, 4) # rows of the group start (the pool rope position)+ g0 = (pos // 4) * 4+ assert torch.equal(c, cos[g0]) and torch.equal(s, sin[g0])+++def test_rows_memo_follows_object_and_version():+ RR = _mod("rope_rows")+ pos = torch.tensor([5, 6, 7])+ a = RR.ix_rows(1e7, 64, pos)+ n0 = RR.STATS["ix"]+ assert RR.ix_rows(1e7, 64, pos)[0] is a[0] and RR.STATS["ix"] == n0 # same object, same version: shared by the layers+ pos.copy_(torch.tensor([9, 10, 11])) # a static graph input overwritten in place+ b = RR.ix_rows(1e7, 64, pos)+ assert RR.STATS["ix"] == n0 + 1 and not torch.equal(a[0], b[0])+ assert RR.ix_rows(1e7, 64, pos.clone())[0] is not b[0] # a new object never hits+++def test_pool16_topk_set_overlap_vs_fp32():+ """the selection set from an fp16-rounded pool vs the fp32 pool: random pooled keys (rms-normalised, 128-d), 16 heads, n_top 511 groups; real indexer inputs are gated by the GPU job (qual_kv10.py IXOVL)"""+ g = torch.Generator().manual_seed(1)+ rows = []+ for Pb in (4096, 16384, 65536):+ pool = torch.randn(Pb, 128, generator=g)+ pool = pool / pool.pow(2).mean(-1, keepdim=True).sqrt()+ iq = torch.randn(8, 16, 128, generator=g)+ wt = torch.rand(8, 16, generator=g) / 45+ def sel(pk):+ sc = (torch.relu(torch.einsum("nhd,pd->nhp", iq, pk)) * wt[:, :, None]).sum(1)+ return torch.topk(sc, 511, dim=1).indices+ a, b = sel(pool), sel(pool.half().float())+ ov = [len(set(a[t].tolist()) & set(b[t].tolist())) / 511 for t in range(8)]+ rows.append((Pb, min(ov), sum(ov) / 8))+ for Pb, mn, mean in rows:+ assert mean > 0.99 and mn > 0.985, (Pb, mn, mean) # the cut-off neighbours swap; the bulk of the set is the same+++def test_pool16_store_and_cast_sources():+ sg = open(os.path.join(LOADER, "step_graph.py")).read()+ assert 'HY4_IX_POOL16' in sg and "pooled.to(ix.pool.dtype)" in sg and 'ix.pool[:Pb].to(iq.dtype)' in sg+ assert "if not _RR.ENABLED:" in sg and "ix._table(cap)" in sg+ ixf = open(os.path.join(LOADER, "indexer_fused.py")).read()+ assert "dtype=POOL_DT" in ixf and "dtype=self.pool.dtype" in ixf and "self.pool[:P].to(iq.dtype)" in ixf+ assert "dtype=self.pool.dtype" in open(os.path.join(LOADER, "prefill_kernels.py")).read()+ assert "pool[:Pb].to(iq.dtype)" in open(os.path.join(LOADER, "lc_sparse.py")).read()+++def test_compact_sets_the_kv10_levers_and_user_values_win(monkeypatch):+ text = open(os.path.join(TREE, "tools/hy4/serve.py")).read()+ node = [n for n in ast.parse(text).body if isinstance(n, ast.FunctionDef) and n.name == "apply_env"][0]+ ns = {"os": os, "SHIPPED_ENV": {}, "TREE": TREE, "glob": None}+ exec(compile(ast.get_source_segment(text, node), "apply_env", "exec"), ns)+ for k in ("HY4_KV_COMPACT", "HY4_KV_FP8", "HY4_KV_FP8_MTP", "HY4_SWA_RING", "HY4_IX_POOL16", "HY4_ROPE_POS"):+ monkeypatch.delenv(k, raising=False)+ ns["apply_env"](65536)+ assert "HY4_IX_POOL16" not in os.environ and "HY4_ROPE_POS" not in os.environ # off without COMPACT+ monkeypatch.setenv("HY4_KV_COMPACT", "1")+ monkeypatch.setenv("HY4_IX_POOL16", "0")+ ns["apply_env"](262144)+ assert os.environ["HY4_IX_POOL16"] == "0" and os.environ["HY4_ROPE_POS"] == "1"+ for k in ("HY4_IX_POOL16", "HY4_ROPE_POS"):+ monkeypatch.delenv(k)+ ns["apply_env"](262144)+ assert os.environ["HY4_IX_POOL16"] == "1" and os.environ["HY4_ROPE_POS"] == "1"+ assert "HY4_IX_POOL16" in open(os.path.join(TREE, "tools/hy4/mu_engine.py")).read()+++def test_gate_regex_matches_the_qual_line():+ line = "QKL_VS_NOISE w32k kl 0.012345 x noise-null max 0.8 | |dNLL| 0.0007 vs null max 0.004 | prefill tok/s ref 800 cand 790"+ m = re.match(r"QKL_VS_NOISE (\w+) kl ([\d.eE-]+) x noise-null max ([\d.]+) \| \|dNLL\| ([\d.eE-]+) vs null max ([\d.eE-]+)", line)+ assert m and m.group(1) == "w32k" and float(m.group(3)) == 0.8+ assert 'print("QKL_VS_NOISE", k, "kl", s["kl_mean"], "x noise-null max"' in open(os.path.join(TREE, "tools/hy4/step/qual_kv10.py")).read()+++def test_triton_interpreter_rows_and_fp16_store():+ pytest.importorskip("triton")+ r = subprocess.run([sys.executable, os.path.join(HERE, "kv10_interp.py")], capture_output=True, text=True, timeout=900)+ assert "KV10_INTERP_OK" in r.stdout, r.stdout[-800:] + r.stderr[-1500:]+++def _probe():+ sp = importlib.util.spec_from_file_location("kvp_t", os.path.join(TREE, "tools", "hy4", "kv_bytes_probe.py"))+ m = importlib.util.module_from_spec(sp)+ sp.loader.exec_module(m)+ return m+++def test_probe_touch_sets_t0_and_reads_the_tables_back(capsys):+ P = _probe()+ seen = {}++ class GRStub:+ def step_rows(self, ids):+ seen.setdefault("steps", []).append(len(ids))++ class Eng:+ GR = GRStub()++ def reset(self):+ assert hasattr(self, "_t0") # prefill() reads _t0: the touch must set it first (engine.py)+ seen["reset"] = True++ def prefill(self, ids):+ assert hasattr(self, "_t0") and len(ids) == 2048+ seen["prefill"] = True++ def phase(self, name):+ seen["phase"] = name++ class T:+ shape = (7, 2)++ class IXF:+ class FusedKPoolIndexer:+ _TABS = {}++ class RR:+ ENABLED = True+ STATS = {"attn": 3, "ix": 2}++ class AE:+ _TAB = {}++ assert P.touch(Eng(), 10, lambda: None, lambda: 25, AE, IXF, RR) == []+ assert seen["steps"] == [4, 4] and seen["phase"] == "decode"+ out = capsys.readouterr().out+ assert out.startswith("KVTOUCH ") and '"alloc_after_B": 25' in out and '"rope_table_rows_attn": 0' in out+ AE._TAB = {("k",): T()} # a full-context table left after the touch while HY4_ROPE_POS is on -> failure string+ assert "full-context rope table" in P.touch(Eng(), 10, lambda: None, lambda: 25, AE, IXF, RR)[0]+++def test_probe_parent_keeps_the_measurement_of_a_failed_child_and_prints_touch_slope(monkeypatch, capsys):+ import json+ P = _probe()+ monkeypatch.setenv("K3_ARMS", "kv10:1000,3000:HY4_KV_COMPACT=1")+ monkeypatch.setenv("K3_OUT", os.path.join(os.environ.get("TMPDIR", "/tmp"), "kv10_probe_test.json"))++ class R:+ def __init__(self, c, rc):+ c = int(c)+ self.returncode, self.stderr = rc, "boom"+ self.stdout = ("KVBYTES " + json.dumps({"ctx": c, "cap": c, "alloc_B": c * 9220, "comp_B": {"a": c * 9000}}) + "\nKVTOUCH "+ + json.dumps({"alloc_after_B": c * 9220 + 500}) + "\nFAIL x\n")++ monkeypatch.setattr(P.subprocess, "run", lambda cmd, env, **kw: R(env["K3_CHILD"], 3))+ with pytest.raises(SystemExit) as e:+ P.parent()+ out = capsys.readouterr().out+ assert e.value.code == 1 and "DRIVER_FAIL" in out+ assert "SLOPE [kv10] ctx 1000->3000: total 9220 B/token" in out and "SLOPE_TOUCH [kv10] ctx 1000->3000: 9220 B/token" in out+++def test_driver_gate_lines_and_fires_kv10():+ d = open(os.path.join(TREE, "tools/hy4/step/kv10_driver.py")).read()+ m = re.search(r'm = re.match\(r"(IXOVL[^"]+)", ln\)', d)+ assert m and re.match(m.group(1), "IXOVL rows 40 mean_overlap 0.9991 min_overlap 0.9900 exact_rows 12")+ assert "KV10_GATE topk" in d and 'fires.get("kv10", 0)' in d+ q = open(os.path.join(TREE, "tools/hy4/step/qual_kv10.py")).read()+ assert 'print(f"FIRES kv10 {min(flagged)}"' in q and 'IXOVL rows' in qdiff --git a/tools/hy4/kv_bytes.py b/tools/hy4/kv_bytes.pyindex 99fc8e2..0c25eda 100644--- a/tools/hy4/kv_bytes.py+++ b/tools/hy4/kv_bytes.py@@ -6,7 +6,7 @@ RING_ROWS, VG_RING_ROWS = 1024, 4096ROPE_TABLES_B = 256 + 2 * 512 # assumption, checked by the measured residual: indexer cos / sin (rope 64, shared) + two attn_eager tables [n, 2, 32, 2] fp32-def per_token(fp8=False, fp8_mtp=False, swa_ring=False, pool_bytes=4):+def per_token(fp8=False, fp8_mtp=False, swa_ring=False, pool_bytes=4, rope_pos=False):"""-> {component: (bytes per token, constant bytes)} of the persistent buffers at full capacity"""lat32, lat8 = (R + P) * 4, R + 4 + 2 * P # fp32 latent + rope, fp8 e4m3 + fp32 scale + bf16 roped = {}@@ -16,7 +16,7 @@ def per_token(fp8=False, fp8_mtp=False, swa_ring=False, pool_bytes=4):d["indexer pool (13 layers)"] = ((FULL + MTP) * (DIX // KP) * pool_bytes, 0)d["indexer value|gate rows (13)"] = (0, (FULL + MTP) * VG_RING_ROWS * 2 * DIX * 4) if swa_ring else ((FULL + MTP) * 2 * DIX * 4, 0)d["token history + arange"] = (16, 0)- d["rope tables"] = (ROPE_TABLES_B, 0)+ d["rope tables"] = (0, 0) if rope_pos else (ROPE_TABLES_B, 0) # HY4_ROPE_POS: rows of the call, evaluated from the positions (kv10: transient, T rows)return d@@ -24,11 +24,23 @@ def total(d):return sum(v[0] for v in d.values()), sum(v[1] for v in d.values())+CTX_1M = 1 << 20+ARMS = (("1.9.1 default (fp32)", {}), ("fp8 trunk only", dict(fp8=True)), ("HY4_KV_COMPACT=1 (bcfb9e5)", dict(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=4)),+ ("COMPACT + HY4_IX_POOL16 (fp16 pool)", dict(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2)),+ ("COMPACT + HY4_ROPE_POS (rope rows from positions)", dict(fp8=True, fp8_mtp=True, swa_ring=True, rope_pos=True)),+ ("HY4_KV_COMPACT=1 now (fp16 pool + rope rows)", dict(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2, rope_pos=True)))+++def at_1m(d):+ """bytes per token at a 1M context: the per-token slope plus the constant buffers (window rings, indexer rings) spread over the context"""+ t, c = total(d)+ return t + c / CTX_1M++if __name__ == "__main__":- for name, kw in (("1.9.1 default (fp32)", {}), ("fp8 trunk only", dict(fp8=True)), ("HY4_KV_COMPACT=1", dict(fp8=True, fp8_mtp=True, swa_ring=True)),- ("COMPACT + fp16 pool", dict(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2))):+ for name, kw in ARMS:d = per_token(**kw)t, c = total(d)- print(f"== {name}: {t} B / token ({t / 1024:.1f} KB) + constant {c / 2**20:.0f} MiB")+ print(f"== {name}: {t} B / token ({t / 1024:.2f} KiB) + constant {c / 2**20:.0f} MiB -> {at_1m(d):.0f} B / token at 1M ({at_1m(d) / 1024:.2f} KiB; owner rule <= 10 KiB)")for k, (b, cc) in d.items():print(f" {k:34s} {b:7d} B/token const {cc / 2**20:7.1f} MiB")diff --git a/tools/hy4/kv_bytes_probe.py b/tools/hy4/kv_bytes_probe.pyindex f97938f..784d6e5 100644--- a/tools/hy4/kv_bytes_probe.py+++ b/tools/hy4/kv_bytes_probe.py@@ -16,6 +16,25 @@ def nb(t):return int(t.numel() * t.element_size())+def touch(eng, alloc, sync, mem, ae, IXF, RR):+ """a 2048-token prefill + 2 verify calls of 4 rows, then the lazy rope tables / row evaluations read back -> list of failure strings. KVTOUCH carries the allocation AFTER the touch+ (the parent prints SLOPE_TOUCH from it: it shows the lazy per-token tables that the load-only slope cannot see)"""+ ids = [(i * 7919) % 50000 + 1000 for i in range(2048 + 8)]+ eng._t0 = time.perf_counter() # prefill() reads it (qual_llc sets it the same way)+ eng.reset()+ eng.prefill(ids[:2048])+ eng.phase("decode")+ for i in range(2048, 2056, 4):+ eng.GR.step_rows(ids[i:i + 4])+ sync()+ rows_attn = sum(t.shape[0] for t in ae._TAB.values())+ rows_ix = sum(cs[0].shape[0] for cs in IXF.FusedKPoolIndexer._TABS.values())+ print("KVTOUCH", json.dumps({"rope_table_rows_attn": rows_attn, "rope_table_rows_ix": rows_ix, "rope_rows_evals": dict(RR.STATS), "alloc_before_B": alloc, "alloc_after_B": mem()}), flush=True)+ if RR.ENABLED and (rows_attn or rows_ix):+ return [f"HY4_ROPE_POS on but a full-context rope table exists (attn rows {rows_attn}, ix rows {rows_ix})"]+ return []++def child(ctx):sys.path.insert(0, here)tree = os.path.dirname(os.path.dirname(here))@@ -28,9 +47,10 @@ def child(ctx):eng.load(lambda s: None)torch.cuda.synchronize()alloc = torch.cuda.memory_allocated()- from exllamav3.loader import step_nosync as ns, kv_fp8, attn_eager as ae+ from exllamav3.loader import step_nosync as ns, kv_fp8, attn_eager as ae, rope_rows as RR, indexer_fused as IXFst = ns.state(eng.M)- comp = {"kv_full_fp8": 0, "kv_full_fp32": 0, "kv_window": 0, "mtp_k": 0, "ix_pool": 0, "ix_vgb": 0, "tok_ar": nb(st.tok) + nb(st.ar), "rope_attn": sum(nb(t) for t in ae._TAB.values())}+ comp = {"kv_full_fp8": 0, "kv_full_fp32": 0, "kv_window": 0, "mtp_k": 0, "ix_pool": 0, "ix_vgb": 0, "tok_ar": nb(st.tok) + nb(st.ar), "rope_attn": sum(nb(t) for t in ae._TAB.values()),+ "rope_ix": sum(nb(t) for cs in IXF.FusedKPoolIndexer._TABS.values() for t in cs)}fires = 0for i, b in st.kv.items():if isinstance(b, kv_fp8.Fp8KV):@@ -47,33 +67,67 @@ def child(ctx):comp["ix_vgb"] += nb(getattr(ix, "vgb", None))out = {"ctx": ctx, "cap": st.cap, "alloc_B": alloc, "alloc_gib": round(alloc / 2**30, 3), "comp_B": comp, "fires_kv": fires, "mtp_fp8": int(isinstance(mt.kbuf, kv_fp8.Fp8KV)),"env": {k: v for k, v in E.items() if k.startswith("HY4_KV") or k in ("HY4_SWA_RING", "HY4_LC_HB")}}+ pools = [ix.pool for ix in list(eng.M.ixf.values()) + [mt.ix]]+ out["pool16"] = sum(p.dtype == torch.float16 for p in pools)+ out["pools"] = len(pools)print("KVBYTES", json.dumps(out), flush=True)print(f"FIRES kv {fires} mtp {out['mtp_fp8']}", flush=True)+ bad = []+ if E.get("K3_TOUCH", "1") == "1": # one short prefill + a few verify steps: what the lazy rope tables / rows do once real requests run (the load-only numbers above are taken BEFORE this)+ bad += touch(eng, alloc, torch.cuda.synchronize, torch.cuda.memory_allocated, ae, IXF, RR)+ n16 = out["pool16"]+ evals = RR.STATS["attn"] + RR.STATS["ix"]+ print(f"FIRES kv10_pool16 {n16} of {out['pools']}", flush=True)+ print(f"FIRES kv10_rope {evals}", flush=True)+ flagged = ([n16] if IXF.POOL16 else []) + ([evals] if RR.ENABLED and E.get("K3_TOUCH", "1") == "1" else [])+ if flagged:+ print(f"FIRES kv10 {min(flagged)}", flush=True) # fewest firings of any flagged lever (0 = a lever did not fire: the arm FAILS)+ if IXF.POOL16 and n16 != out["pools"]:+ bad.append(f"HY4_IX_POOL16 on but {n16} of {out['pools']} pools are fp16")+ if flagged and min(flagged) == 0:+ bad.append("FIRES kv10 0: a flagged kv10 lever did not fire")+ if bad:+ print("FAIL " + "; ".join(bad), flush=True)+ sys.exit(3)def parent():- """K3_ARMS = 'name:ctx,ctx,ctx:K=V K=V;name2:...' (default: the 1.9.1 default at 16K / 32K / 64K and HY4_KV_COMPACT=1 at 64K / 128K / 256K; the fp32 cache does not fit 256K)"""- arms = E.get("K3_ARMS", "default:16384,32768,65536:;compact:65536,131072,262144:HY4_KV_COMPACT=1")- allres = {}+ """K3_ARMS = 'name:ctx,ctx,ctx:K=V+K=V;name2:...' (default: the 1.9.1 default at 16K / 32K / 64K, compact = HY4_KV_COMPACT=1 with the kv10 levers off (bcfb9e5 bytes) and kv10 = HY4_KV_COMPACT=1 as shipped now, both at 64K / 128K / 256K; the fp32 cache does not fit 256K)"""+ arms = E.get("K3_ARMS", "default:16384,32768,65536:;compact:65536,131072,262144:HY4_KV_COMPACT=1+HY4_IX_POOL16=0+HY4_ROPE_POS=0;kv10:65536,131072,262144:HY4_KV_COMPACT=1")+ allres, failed = {}, []for arm in arms.split(";"):name, ctxs, kv = arm.split(":", 2)- env = {**E, **dict(x.split("=", 1) for x in kv.split())}+ env = {**E, **dict(x.split("=", 1) for x in kv.replace("+", " ").split())} # flags of an arm: K=V joined by "+" (a job XENV cannot hold spaces)res = []for c in ctxs.split(","):t0 = time.time()r = subprocess.run([sys.executable, "-u", os.path.abspath(__file__)], env={**env, "K3_CHILD": c}, capture_output=True, text=True, timeout=1200)sys.stdout.write("".join(f"[{name}] {ln}\n" for ln in r.stdout.splitlines() if ln.startswith(("KVBYTES", "FIRES"))))+ sys.stdout.write("".join(f"[{name}] {ln}\n" for ln in r.stdout.splitlines() if ln.startswith(("KVTOUCH", "FAIL"))))+ kvl = [ln for ln in r.stdout.splitlines() if ln.startswith("KVBYTES")]if r.returncode:print(f"[{name}] ctx {c} rc={r.returncode} {r.stderr[-600:]}", flush=True)+ failed.append((name, c, r.returncode))+ if not kvl:continue- res.append(json.loads([ln for ln in r.stdout.splitlines() if ln.startswith("KVBYTES")][-1][8:]))+ d = json.loads(kvl[-1][8:])+ tl = [ln for ln in r.stdout.splitlines() if ln.startswith("KVTOUCH")]+ if tl:+ d["touch"] = json.loads(tl[-1][8:])+ res.append(d) # a failed touch / FIRES check keeps the load-only measurementprint(f"[{name}] ctx {c} done {time.time() - t0:.0f}s", flush=True)for a, b in zip(res, res[1:]):dc = b["cap"] - a["cap"]print(f"SLOPE [{name}] ctx {a['ctx']}->{b['ctx']}: total {(b['alloc_B'] - a['alloc_B']) / dc:.0f} B/token; " + ", ".join(f"{k} {(b['comp_B'][k] - a['comp_B'][k]) / dc:.0f}" for k in a["comp_B"])+ f", unlisted {((b['alloc_B'] - sum(b['comp_B'].values())) - (a['alloc_B'] - sum(a['comp_B'].values()))) / dc:.0f}", flush=True)+ for a, b in zip(res, res[1:]):+ if "touch" in a and "touch" in b:+ print(f"SLOPE_TOUCH [{name}] ctx {a['ctx']}->{b['ctx']}: {(b['touch']['alloc_after_B'] - a['touch']['alloc_after_B']) / (b['cap'] - a['cap']):.0f} B/token after the 2048-token touch (lazy rope tables included)", flush=True)allres[name] = resjson.dump(allres, open(E.get("K3_OUT", "/tmp/kvbytes.json"), "w"))+ if failed:+ print("DRIVER_FAIL", failed, flush=True)+ sys.exit(1)if __name__ == "__main__":diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.pyindex 46a67af..44045a1 100644--- a/tools/hy4/mu_engine.py+++ b/tools/hy4/mu_engine.py@@ -16,7 +16,7 @@ from engine import Hy4Engine, PRIME_ROWS, warmup_clampclass MuEngine(Hy4Engine):def __init__(self, *a, slots: int = 4, **kw):- for f in ("HY4_SWA_RING", "HY4_LC_SPARSE", "HY4_KV_FP8_MTP"): # long-context levers act on the single-session K / indexer buffers, not on the slot slabs+ for f in ("HY4_SWA_RING", "HY4_LC_SPARSE", "HY4_KV_FP8_MTP", "HY4_IX_POOL16", "HY4_ROPE_POS"): # long-context levers act on the single-session K / indexer buffers, not on the slot slabsif os.environ.get(f, "0") not in ("", "0"):raise RuntimeError(f + " is not supported with --slots > 1")super().__init__(*a, **kw)diff --git a/tools/hy4/serve.py b/tools/hy4/serve.pyindex 079ccd8..3323992 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -90,8 +90,8 @@ SLOTS_OFF = ("HY4_LC_SPARSE",) # shipped long-context levers that act on thedef apply_env(ctx: int, model: str = "", slots: int = 1) -> None:- if os.environ.get("HY4_KV_COMPACT", "0") == "1": # long lane footprint (about 11 KB per token, doc/hy4.md): fp8 latent K for the trunk and the draft layer, window layers in a 1024-row ring; each can still be set by hand- for k, v in (("HY4_KV_FP8", "1"), ("HY4_KV_FP8_MTP", "1"), ("HY4_SWA_RING", "1024")):+ if os.environ.get("HY4_KV_COMPACT", "0") == "1": # long lane footprint (about 9 KB per token, doc/hy4.md): fp8 latent K for the trunk and the draft layer, window layers in a 1024-row ring, fp16 indexer pool, rope rows from the positions (no per-token tables); each can still be set by hand+ for k, v in (("HY4_KV_FP8", "1"), ("HY4_KV_FP8_MTP", "1"), ("HY4_SWA_RING", "1024"), ("HY4_IX_POOL16", "1"), ("HY4_ROPE_POS", "1")):os.environ.setdefault(k, v)for k, v in SHIPPED_ENV.items():os.environ.setdefault(k, "0" if slots > 1 and k in SLOTS_OFF else v) # an explicit value still wins (and MuEngine refuses it)diff --git a/tools/hy4/step/kv10_driver.py b/tools/hy4/step/kv10_driver.pynew file mode 100644index 0000000..c9a5520--- /dev/null+++ b/tools/hy4/step/kv10_driver.py@@ -0,0 +1,50 @@+"""kv10_driver.py (cwd = tree): paired quality of the 1.9.2 KV levers HY4_IX_POOL16 (fp16 indexer pool) + HY4_ROPE_POS (rope rows from positions) against the compact arm.+Two processes (allocation flags cannot be toggled inside one load), both with HY4_KV_COMPACT=1:+ A HY4_IX_POOL16=0 HY4_ROPE_POS=0 ref log-probs + 3 noise nulls + the top-k SET overlap of the fp32 pool vs the same pool in fp16 on the real decode queries (qual_kv10.py)+ B as shipped (HY4_KV_COMPACT=1 sets both levers) paired dNLL / KL / top-1 vs A, short window (w4k: 2048 context rows) and long window (w32k: 31744 context rows)+Prints FIRES kv10 / kv10_* from both arms (a flagged lever with 0 firings fails the job: rc 1) and the lines KV10_GATE topk (mean / min overlap of the fp32-pool vs fp16-pool top-k group sets) and KV10_GATE short|long: KL / noise-null max <= 1.0 and |dNLL| <= null max.+env: LLC_CTX (default 65536), LLC_REF (scratch file of ~0.8 GB for the ref log-probs, deleted by arm B), LLC_CORPUS (text file), GGUF, DRV_GUARD_DIR."""+import os, re, subprocess, sys+sys.path.append(os.environ["DRV_GUARD_DIR"]) # directory of the job runner's shared drv_guard.py (dead / zero-sample arm = fail at once)+import drv_guard as guard+guard.install_excepthook()+E, tree = os.environ, os.getcwd()+base = dict(E, LLC_CTX=E.get("LLC_CTX", "65536"), LLC_REF=E["LLC_REF"], HY4_KV_COMPACT="1")+++def arm(mode, extra):+ out = []+ p = subprocess.Popen([sys.executable, "-u", tree + "/tools/hy4/step/qual_kv10.py"], env={**base, "LLC_MODE": mode, **extra}, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)+ for ln in p.stdout:+ sys.stdout.write(ln)+ sys.stdout.flush()+ out.append(ln.rstrip("\n"))+ p.wait()+ print(f"KV10_ARM {mode} rc={p.returncode}", flush=True)+ return p.returncode, out+++rcA, outA = arm("A", {"HY4_IX_POOL16": "0", "HY4_ROPE_POS": "0"})+if rcA:+ print("DRIVER_FAIL arm A", flush=True)+ sys.exit(1)+rcB, outB = arm("B", {})+qres = sum(ln.startswith("QRES") for ln in outB)+fires = {m.group(1): int(m.group(2)) for ln in outA + outB for m in [re.match(r"FIRES (kv10_\w+) (\d+)", ln)] if m}+for ln in outB:+ m = re.match(r"QKL_VS_NOISE (\w+) kl ([\d.eE-]+) x noise-null max ([\d.]+) \| \|dNLL\| ([\d.eE-]+) vs null max ([\d.eE-]+)", ln)+ if m:+ name, x, dn, dmax = {"w4k": "short", "w32k": "long"}.get(m.group(1), m.group(1)), float(m.group(3)), float(m.group(4)), float(m.group(5))+ print(f"KV10_GATE {name} kl_x_null {x} dNLL {dn} null_max {dmax} -> {'PASS' if x <= 1.0 and dn <= dmax else 'FAIL'}", flush=True)+TOPK_MEAN_MIN = float(E.get("KV10_TOPK_MEAN_MIN", "0.99")) # thresholds anchored on the random-data CPU check (tests/test_kv10.py: mean 0.9998, min 0.998 at 4K .. 64K groups) with margin; a pool in fp16 moves only the groups next to the cut-off+TOPK_ROW_MIN = float(E.get("KV10_TOPK_ROW_MIN", "0.97"))+for ln in outA:+ m = re.match(r"IXOVL rows (\d+) mean_overlap ([\d.]+) min_overlap ([\d.]+)", ln)+ if m:+ mean, mn = float(m.group(2)), float(m.group(3))+ print(f"KV10_GATE topk rows {m.group(1)} mean_overlap {mean} min_overlap {mn} -> {'PASS' if mean >= TOPK_MEAN_MIN and mn >= TOPK_ROW_MIN else 'FAIL'} (mean >= {TOPK_MEAN_MIN}, min >= {TOPK_ROW_MIN})", flush=True)+if rcB:+ print("DRIVER_FAIL arm B (a flagged lever did not fire or the arm crashed)", flush=True)+ sys.exit(1)+guard.require_samples({"qres_B": qres, "fires_kv10": fires.get("kv10", 0), "fires_kv10_pool16": fires.get("kv10_pool16", 0), "fires_kv10_ovl": fires.get("kv10_ovl", 0)}, label="kv10_driver")+print("KV10_DONE", flush=True)diff --git a/tools/hy4/step/qual_kv10.py b/tools/hy4/step/qual_kv10.pynew file mode 100644index 0000000..63709f2--- /dev/null+++ b/tools/hy4/step/qual_kv10.py@@ -0,0 +1,143 @@+"""qual_kv10.py (qual_llc.py + the kv10 gates): paired quality of HY4_IX_POOL16 / HY4_ROPE_POS against the compact arm, run inside kv10_driver.py (cwd = tree).+Mode A (ref = HY4_KV_COMPACT=1 with HY4_IX_POOL16=0 HY4_ROPE_POS=0, fp32 pool): also records, on the REAL decode queries of the eager warm-up bodies of every graph capture, the+overlap of the top-k group SET chosen from the fp32 pool with the set chosen from the same pool rounded to fp16 (the pool an fp16-pool arm stores): `IXOVL rows n mean_overlap x min_overlap y exact_rows z`.+Mode B (cand = HY4_KV_COMPACT=1 as shipped: fp16 pool + rope rows): prints FIRES kv10_pool16 / kv10_rope and exits 1 when a flagged lever did not fire.+qual_llc.py: short-context quality gate of the lane long-context config (run inside the job driver, cwd = tree).+Teacher-forced NLL of the decode path (graph step, R = 4 verify rows per call) on a FIXED text (bench corpus, first 400k chars, tokenised by the model vocab), two windows:+ w4k 2048 rows of context (prefill), then 2048 scored rows -> a 4096-row window+ w32k 31744 rows of context (prefill), then 1024 scored rows -> depth 31744 .. 32768+Allocation flags (HY4_SWA_RING / HY4_KV_FP8 / HY4_IX_POOL16 ...) cannot be toggled inside one load, so the two arms are two processes:+ LLC_MODE=A ref arm + 3 noise nulls (1e-6 embedding noise, seeds 1234 / 77 / 5) on the SAME config; saves the ref log-probs (fp16) + null stats to LLC_REF+ LLC_MODE=B one arm (the env of this process) scored against the saved ref: ppl, paired dNLL, KL(ref||arm), top-1 agreement, KL / noise-null max; deletes LLC_REF+env: LLC_CTX (server -c of this arm), LLC_MODE, LLC_REF (file). Prints NLL / KL numbers only, never text."""+import json, os, sys, time+import numpy as np+tree = os.getcwd()+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))+import serve+import serve_core as C+CTX = int(os.environ["LLC_CTX"]); MODE = os.environ["LLC_MODE"]; REFF = os.environ["LLC_REF"]+assert MODE in ("A", "B")+serve.apply_env(CTX)+import torch+from engine import Hy4Engine+GGUF = os.environ["GGUF"]+e = Hy4Engine(tree, GGUF, ctx=CTX, k=3, chunk=8192, prime_rows=64) # the draft cache is not read here: fill the last 64 rows only+e.load(print)+from exllamav3.loader import lc_sparse as LS, rope_rows as RR, indexer_fused as IXF, attn_eager as AE+OVL = {"rows": 0, "sum": 0.0, "min": 1.0, "exact": 0}+if MODE == "A" and os.environ.get("HY4_IX_POOL16", "0") != "1":+ _sel = LS.select_groups++ def _sel_ovl(iq, wt, pool, pos, Pb, n_top, kp, tail):+ idx, nsel = _sel(iq, wt, pool, pos, Pb, n_top, kp, tail)+ if pool.dtype == torch.float32 and not torch.cuda.is_current_stream_capturing():+ idx16, nsel16 = _sel(iq, wt, pool.half().contiguous(), pos, Pb, n_top, kp, tail)+ a, b, na, nb = idx.cpu(), idx16.cpu(), nsel.cpu(), nsel16.cpu()+ for t in range(a.shape[0]):+ sa, sb = set(a[t, :int(na[t])].tolist()), set(b[t, :int(nb[t])].tolist())+ ov = len(sa & sb) / max(len(sa), 1)+ OVL["rows"] += 1; OVL["sum"] += ov; OVL["min"] = min(OVL["min"], ov); OVL["exact"] += sa == sb+ return idx, nsel+ LS.select_groups = _sel_ovl # step_graph calls lc_sparse.select_groups through the module: the hook sees every eager (non-captured) selection+SG, GR, dev = e.SG, e.GR, e.dev+R = 4+text = open(os.environ["LLC_CORPUS"]).read(400000)+ids = C.Vocab(e.meta).encode(text)+WINS = [("w4k", ids[0:2048 + 2048 + 1], 2048, 2048), ("w32k", ids[4096:4096 + 31744 + 1024 + 1], 31744, 1024)]+assert all(len(w[1]) == w[2] + w[3] + 1 for w in WINS), "corpus too short"+print("LLC_TEXT tokens", len(ids), "mode", MODE, "ctx", CTX, flush=True)+++def run_arm(seed=None, ref=None):+ """-> {window: (nll [n], kl list, same list, lps fp16 [n, V] or None, prefill_s)}"""+ SG.PERT = None if seed is None else (torch.randn(GR.cap, e.M.D, generator=torch.Generator().manual_seed(seed)) * 1e-6).to(dev)+ out = {}+ GR.clear() # graphs bake the PERT table: fresh pool per arm (once per arm, not per window)+ for name, wid, nctx, nsc in WINS:+ e._t0 = time.perf_counter(); e.reset()+ t = time.perf_counter(); e.prefill(wid[:nctx]); torch.cuda.synchronize(); pf = time.perf_counter() - t+ e.phase("decode")+ nl, kl, same, lps = [], [], [], []+ for i in range(0, nsc, R):+ lg = GR.step_rows(wid[nctx + i:nctx + i + R])[0]+ lp = torch.log_softmax(lg.reshape(R, -1).float(), -1)+ tgt = torch.tensor(wid[nctx + i + 1:nctx + i + R + 1], device=dev)+ nl.extend((-lp[torch.arange(R, device=dev), tgt]).tolist())+ if ref is None:+ lps.append(lp.half().cpu())+ else:+ lr = ref[name][len(nl) - R:len(nl)].to(dev).float()+ kl.extend((lr.exp() * (lr - lp)).sum(-1).tolist())+ same.extend((lr.argmax(-1) == lp.argmax(-1)).tolist())+ out[name] = (np.array(nl), kl, same, torch.cat(lps) if ref is None else None, pf)+ SG.PERT = None+ GR.clear()+ return out+++def stats(arm, name, r, base_nl, nctx):+ nl, kl, same, _, pf = r+ r_ = dict(arm=arm, win=name, n=len(nl), ppl=round(float(np.exp(nl.mean())), 4), prefill_tps=round(nctx / pf, 1))+ if base_nl is not None:+ d = nl - base_nl+ r_.update(d_nll=round(float(d.mean()), 5), d_se=round(float(d.std(ddof=1) / np.sqrt(len(d))), 5), kl_mean=round(float(np.mean(kl)), 6),+ kl_p99=round(float(np.percentile(kl, 99)), 5), top1_same=round(float(np.mean(same)), 4))+ return r_+++NCTX = {w[0]: w[2] for w in WINS}+if MODE == "A":+ ref = run_arm()+ save = dict(lps={k: v[3] for k, v in ref.items()}, nll={k: v[0] for k, v in ref.items()}, nulls={})+ save["ref"] = {}+ for k, v in ref.items():+ save["ref"][k] = stats("ref", k, v, None, NCTX[k])+ print("QRES", json.dumps(save["ref"][k]), flush=True)+ refl = save["lps"]+ for nm, seed in (("noise1234", 1234), ("noise77", 77), ("noise5", 5)):+ res = run_arm(seed, refl)+ for k, v in res.items():+ s = stats(nm, k, v, ref[k][0], NCTX[k])+ save["nulls"].setdefault(k, {})[nm] = s+ print("QRES", json.dumps(s), flush=True)+ torch.save(save, REFF)+ for k in save["nulls"]:+ print("NULL_BAND", k, "kl max", max(s["kl_mean"] for s in save["nulls"][k].values()), "min", min(s["kl_mean"] for s in save["nulls"][k].values()), flush=True)+else:+ saved = torch.load(REFF)+ res = run_arm(None, saved["lps"])+ for k, v in res.items():+ s = stats("cand", k, v, saved["nll"][k], NCTX[k])+ print("QRES", json.dumps(s), flush=True)+ nz = max(x["kl_mean"] for x in saved["nulls"][k].values())+ nd = max(abs(x["d_nll"]) for x in saved["nulls"][k].values())+ print("QKL_VS_NOISE", k, "kl", s["kl_mean"], "x noise-null max", round(s["kl_mean"] / max(nz, 1e-12), 2), "| |dNLL|", abs(s["d_nll"]), "vs null max", nd,+ "| prefill tok/s ref", saved["ref"][k]["prefill_tps"], "cand", s["prefill_tps"], flush=True)+ if os.environ.get("LLC_KEEP") != "1":+ os.remove(REFF)+pools = [ix.pool for ix in list(e.M.ixf.values()) + [e.MT.ix]]+n16 = sum(p.dtype == torch.float16 for p in pools)+rows_attn = sum(t.shape[0] for t in AE._TAB.values())+rows_ix = sum(cs[0].shape[0] for cs in IXF.FusedKPoolIndexer._TABS.values())+if OVL["rows"]:+ print(f"IXOVL rows {OVL['rows']} mean_overlap {OVL['sum'] / OVL['rows']:.6f} min_overlap {OVL['min']:.4f} exact_rows {OVL['exact']}", flush=True)+ print(f"FIRES kv10_ovl {OVL['rows']}", flush=True)+print(f"FIRES kv10_pool16 {n16} of {len(pools)}", flush=True)+print(f"FIRES kv10_rope {RR.STATS['attn'] + RR.STATS['ix']} (rope table rows left: attn {rows_attn} ix {rows_ix})", flush=True)+bad = []+flagged = ([n16] if IXF.POOL16 else []) + ([RR.STATS["attn"] + RR.STATS["ix"]] if RR.ENABLED else [])+if flagged:+ print(f"FIRES kv10 {min(flagged)}", flush=True) # fewest firings of any flagged lever; 0 fails the arm+ if min(flagged) == 0:+ bad.append("FIRES kv10 0: a flagged kv10 lever did not fire")+if MODE == "B" and IXF.POOL16 and n16 != len(pools):+ bad.append("HY4_IX_POOL16 on but the pools are not fp16")+if MODE == "B" and RR.ENABLED and (not (RR.STATS["attn"] + RR.STATS["ix"]) or rows_attn or rows_ix):+ bad.append("HY4_ROPE_POS on but no row evaluation fired or a full-context rope table exists")+if MODE == "A" and not OVL["rows"]:+ bad.append("no top-k overlap row recorded (the sparse selection never ran eagerly)")+print("QUAL_DONE", flush=True)+if bad:+ print("FAIL " + "; ".join(bad), flush=True)+ sys.exit(1)