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 KV footprint: HY4_KV_FP8_MTP (fp8 draft-layer K cache), HY4_KV_COMPACT shortcut (fp8 trunk + draft cache + window ring), analytic bytes-per-token table, measurement probe, CPU tests, docs
YanissAmz2ec1853886e7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fd77889..acabcdf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,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`.- 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 2439ff9..28d4e2c 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -99,6 +99,20 @@ The free memory is steady, not a load transient: at the default `-c 65536` it st128K (`-c 131072`) is opt-in. At load, fp32 KV, the server reached 110.4 GiB of GTT and the free memory fell to 7.8 GiB. It was not measured under a 128K prefill on the release build; if memory runs out, use a smaller `-c`.+### 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`.+### Long context option: fp8 KV (`HY4_KV_FP8=1`, off by default)Default (`-c 65536`): fp32 latent K cache, the measured quality. For `-c 131072` and `-c 262144`, switch the fp8 cache on: `HY4_KV_FP8=1 python tools/hy4/serve.py ... -c 131072`. The 12 trunk full-attention layers keep their latent K in e4m3 (512 bytes) + one fp32 scale per token + bf16 rope dims: 644 bytes per token and layer instead of 2304. The MTP layer and the 30 window layers stay fp32. The sparse decode kernel decodes e4m3 itself; prefill and the other paths read a dequantised copy of the keys of the call. With the fp8 cache the head-blocked sparse attend (`HY4_LC_HB`, default 1: one key decode shared by 16 heads, split-K with `HY4_LC_HB_SPLIT=-1` auto) is on; it never runs on the fp32 cache. `HY4_LC_HB=0` returns to the one-head kernel; `HY4_KV_FP8=0` (or unset) returns to the fp32 cache.diff --git a/exllamav3/loader/mtp_head.py b/exllamav3/loader/mtp_head.pyindex 3e6041a..9d000d3 100644--- a/exllamav3/loader/mtp_head.py+++ b/exllamav3/loader/mtp_head.py@@ -15,6 +15,7 @@ import timeimport torch+from . import kv_fp8 as _KV8from . import moe_i8 as MIfrom . import step_graph as SGfrom . import step_nosync as _ns@@ -23,6 +24,8 @@ from .hy4_forward import _mv, head_gemm, QLinear, GG_DENSE, dense_fnfrom .indexer_fused import FusedKPoolIndexerfrom .mla_hy4 import Hy4MLA+KV_FP8_MTP = os.environ.get("HY4_KV_FP8_MTP", "0") == "1" and os.environ.get("HY4_KV_FP8", "0") == "1" # draft layer K cache in fp8 like the trunk (644 B per token instead of 2304); needs HY4_KV_FP8=1+def q8_0_pack(W):"""fp32 [N, K] (K % 32 == 0, any device) -> stored Q8_0 bytes [N, K // 32, 34] uint8 (fp16 d = amax / 127, int8 q = round(w / d))"""@@ -97,7 +100,7 @@ class Hy4MTP:st = _ns.state(fw)self.cap = cap or st.capself.ar = st.ar if st.ar.shape[0] >= self.cap else torch.arange(self.cap, device=dev)- self.kbuf = torch.zeros(self.cap, mla.R + mla.rope_dim, device=dev)+ self.kbuf = _KV8.Fp8KV(self.cap, mla.R, mla.rope_dim, dev) if KV_FP8_MTP else torch.zeros(self.cap, mla.R + mla.rope_dim, device=dev)SG.indexer_static_init(self.ix, self.cap)try:from . import attn_eager as _AE@@ -107,6 +110,13 @@ class Hy4MTP:if hasattr(fw, "free_bf16_head"):fw.free_bf16_head() # HY4_HEAD_Q8=1: every consumer of the bf16 head values (draft head copies) has been built+ def _kput(self, pos, kn):+ """K rows by position (graph-capturable): fp32 index_copy_, or quantise on write when the draft cache is fp8"""+ if isinstance(self.kbuf, _KV8.Fp8KV):+ self.kbuf.write_pos(pos, kn)+ else:+ self.kbuf.index_copy_(0, pos, kn)+def reset(self):self.kbuf.zero_()self.ix.n, self.ix.P, self.ix.vg = 0, 0, None@@ -143,7 +153,7 @@ class Hy4MTP:e = _ns.embed(fw, tok)x = torch.cat([nm(e, self.enorm), nm(h, self.hnorm)], -1) @ self.eh.Tcur = nm(x, self.attn_norm)- self.kbuf.index_copy_(0, pos, mla.kv(cur, pos))+ self._kput(pos, mla.kv(cur, pos))qr = nm(mla._q(cur, "wq_a") @ mla.wq_a.T, mla.q_a_norm)allow = SG.indexer_forward_static(self.ix, cur, qr, pos, N, self.ar)if self.fast:@@ -176,7 +186,7 @@ class Hy4MTP:e = _ns.embed(self.fw, tok)x = torch.cat([nm(e, self.enorm), nm(h, self.hnorm)], -1) @ self.eh.Tcur = nm(x, self.attn_norm)- self.kbuf.index_copy_(0, pos, self.mla.kv(cur, pos))+ self._kput(pos, self.mla.kv(cur, pos))SG.indexer_keys_static(self.ix, cur, pos, self.ar)def prime(self, tok, h, pos, N):diff --git a/tests/test_kv_bytes.py b/tests/test_kv_bytes.pynew file mode 100644index 0000000..c6f116f--- /dev/null+++ b/tests/test_kv_bytes.py@@ -0,0 +1,87 @@+"""zero-GPU checks of the KV footprint levers (1.9.2): analytic bytes per token, HY4_KV_COMPACT defaults, the fp8 draft-layer cache"""+import ast+import os+import sys++import pytest++HERE = os.path.dirname(os.path.abspath(__file__))+TREE = os.path.dirname(HERE)+sys.path.insert(0, os.path.join(TREE, "tools", "hy4"))+sys.path.insert(0, TREE)+++def _fn(path, name, cls=None):+ tree = ast.parse(open(os.path.join(TREE, path)).read())+ for node in ast.walk(tree):+ if isinstance(node, ast.ClassDef) and cls and node.name != cls:+ continue+ if isinstance(node, ast.FunctionDef) and node.name == name:+ return ast.get_source_segment(open(os.path.join(TREE, path)).read(), node)+ raise AssertionError(name)+++def _kv8():+ import importlib.util+ sp = importlib.util.spec_from_file_location("kv_fp8_t", os.path.join(TREE, "exllamav3", "loader", "kv_fp8.py"))+ m = importlib.util.module_from_spec(sp)+ sp.loader.exec_module(m)+ return m+++def test_bytes_per_token_table():+ import kv_bytes as KB+ t, c = KB.total(KB.per_token())+ assert t == 115344 and c == 0 # 1.9.1 default: fp32 latent everywhere, window layers at full context (measured slope of the release table: 98-118 KB)+ t8, _ = KB.total(KB.per_token(fp8=True))+ assert t8 == 115344 - 12 * (2304 - 644)+ tc, cc = KB.total(KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True))+ assert tc == 7728 + 644 + 1664 + 16 + 1280 and 11000 < tc < 11500+ assert cc == 30 * 1024 * 2304 + 13 * 4096 * 1024 # window rings + indexer value|gate rings: constant+ tp, _ = KB.total(KB.per_token(fp8=True, fp8_mtp=True, swa_ring=True, pool_bytes=2))+ assert tc - tp == 13 * 32 * 2 and tp < 10600+++def test_fp8_row_bytes_is_644():+ torch = pytest.importorskip("torch")+ kv_fp8 = _kv8()+ kv = kv_fp8.Fp8KV(10, 512, 64, "cpu")+ assert kv.nbytes() == 10 * 644+++def test_compact_sets_defaults_and_keeps_user_values(monkeypatch):+ src = _fn("tools/hy4/serve.py", "apply_env")+ ns = {"os": os, "SHIPPED_ENV": {}, "TREE": TREE, "glob": None}+ exec(compile(src, "apply_env", "exec"), ns)+ for k in ("HY4_KV_COMPACT", "HY4_KV_FP8", "HY4_KV_FP8_MTP", "HY4_SWA_RING"):+ monkeypatch.delenv(k, raising=False)+ ns["apply_env"](65536)+ assert not any(k in os.environ for k in ("HY4_KV_FP8", "HY4_KV_FP8_MTP", "HY4_SWA_RING")) # off by default+ monkeypatch.setenv("HY4_KV_COMPACT", "1")+ monkeypatch.setenv("HY4_SWA_RING", "2048") # a value set by hand wins+ ns["apply_env"](262144)+ assert os.environ["HY4_KV_FP8"] == "1" and os.environ["HY4_KV_FP8_MTP"] == "1" and os.environ["HY4_SWA_RING"] == "2048"+++def test_mtp_k_put_fp8_roundtrip():+ torch = pytest.importorskip("torch")+ kv_fp8 = _kv8()+ src = _fn("exllamav3/loader/mtp_head.py", "_kput")+ ns = {"_KV8": kv_fp8}+ exec(compile("class M:\n" + "\n".join(" " + ln for ln in src.splitlines()), "kput", "exec"), ns)+ m = ns["M"]()+ m.kbuf = kv_fp8.Fp8KV(16, 512, 64, "cpu")+ kn = torch.randn(3, 576)+ m._kput(torch.tensor([2, 5, 9]), kn)+ back = m.kbuf.dequant32()[[2, 5, 9]]+ assert (back[:, :512] - kn[:, :512]).abs().max() < 0.07 * kn[:, :512].abs().max()+ assert (back[:, 512:] - kn[:, 512:]).abs().max() < 0.02 * kn[:, 512:].abs().max()+ m.kbuf = torch.zeros(16, 576) # fp32 cache: the old index_copy_+ m._kput(torch.tensor([1, 4, 7]), kn)+ assert torch.equal(m.kbuf[[1, 4, 7]], kn)+++def test_mtp_fp8_needs_trunk_fp8_and_is_off_by_default():+ src = open(os.path.join(TREE, "exllamav3/loader/mtp_head.py")).read()+ assert 'os.environ.get("HY4_KV_FP8_MTP", "0") == "1" and os.environ.get("HY4_KV_FP8", "0") == "1"' in src+ assert "HY4_KV_FP8_MTP" in open(os.path.join(TREE, "tools/hy4/mu_engine.py")).read()diff --git a/tools/hy4/kv_bytes.py b/tools/hy4/kv_bytes.pynew file mode 100644index 0000000..99fc8e2--- /dev/null+++ b/tools/hy4/kv_bytes.py@@ -0,0 +1,34 @@+"""Hy4 persistent KV bytes per token, analytic from the model shapes and the allocation sites (the measured side: tools/hy4/kv_bytes_probe.py, runner job 50_k3_e_kvbytes).+Shapes (GGUF): 12 trunk full-attention (DSA) layers + the MTP draft layer, 30 window-512 layers, latent 512 + rope 64 per token, indexer: one 128-d key per 4 tokens (pool) and a+(value | gate) row of 2 x 128 per token (vgb). Sites: step_graph.GraphDecoder.prepare (kv / pool / vgb), mtp_head.Hy4MTP (kbuf), step_nosync.State (tok, ar), rope tables."""+FULL, MTP, SWA, R, P, KP, DIX = 12, 1, 30, 512, 64, 4, 128+RING_ROWS, VG_RING_ROWS = 1024, 4096+ROPE_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):+ """-> {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 rope+ d = {}+ d["trunk latent K (12 full layers)"] = (FULL * (lat8 if fp8 else lat32), 0)+ d["MTP layer K"] = (MTP * (lat8 if (fp8 and fp8_mtp) else lat32), 0)+ d["window layers K (30)"] = (0, SWA * RING_ROWS * lat32) if swa_ring else (SWA * lat32, 0)+ 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)+ return d+++def total(d):+ return sum(v[0] for v in d.values()), sum(v[1] for v in d.values())+++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))):+ d = per_token(**kw)+ t, c = total(d)+ print(f"== {name}: {t} B / token ({t / 1024:.1f} KB) + constant {c / 2**20:.0f} MiB")+ 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.pynew file mode 100644index 0000000..f97938f--- /dev/null+++ b/tools/hy4/kv_bytes_probe.py@@ -0,0 +1,80 @@+"""KV bytes per token, MEASURED (runner job 50_k3_e_kvbytes, GPU, one boot per context, no request): loads the engine at K3_CTXS (default 65536,131072,262144), reads+torch.cuda.memory_allocated() after load (GraphDecoder.prepare allocates every static K / indexer buffer at the full context) and walks the buffers by component.+SLOPE = (alloc(c2) - alloc(c1)) / (cap2 - cap1) in bytes / token must match tools/hy4/kv_bytes.py. 'FIRES kv <n> mtp <0|1>' counts the layers that hold an Fp8KV cache (trunk) and the MTP draft cache.+parent: python kv_bytes_probe.py (flags in the environment); it re-runs itself with K3_CHILD=<ctx> for each context (a fresh process frees the GPU)."""+import json, os, subprocess, sys, time++E = os.environ+here = os.path.dirname(os.path.abspath(__file__))+++def nb(t):+ if t is None:+ return 0+ if hasattr(t, "nbytes") and callable(t.nbytes):+ return int(t.nbytes())+ return int(t.numel() * t.element_size())+++def child(ctx):+ sys.path.insert(0, here)+ tree = os.path.dirname(os.path.dirname(here))+ sys.path.insert(0, tree)+ import serve+ serve.apply_env(ctx)+ from engine import Hy4Engine+ import torch+ eng = Hy4Engine(tree, E["GGUF"], ctx=ctx, k=3, chunk=8192, prime_rows=4096)+ 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+ st = 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())}+ fires = 0+ for i, b in st.kv.items():+ if isinstance(b, kv_fp8.Fp8KV):+ comp["kv_full_fp8"] += nb(b)+ fires += 1+ elif eng.M._layer(i).mla.swa:+ comp["kv_window"] += nb(b)+ else:+ comp["kv_full_fp32"] += nb(b)+ mt = eng.MT+ comp["mtp_k"] = nb(mt.kbuf)+ for ix in list(eng.M.ixf.values()) + [mt.ix]:+ comp["ix_pool"] += nb(ix.pool)+ 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")}}+ print("KVBYTES", json.dumps(out), flush=True)+ print(f"FIRES kv {fires} mtp {out['mtp_fp8']}", flush=True)+++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 = {}+ for arm in arms.split(";"):+ name, ctxs, kv = arm.split(":", 2)+ env = {**E, **dict(x.split("=", 1) for x in kv.split())}+ 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"))))+ if r.returncode:+ print(f"[{name}] ctx {c} rc={r.returncode} {r.stderr[-600:]}", flush=True)+ continue+ res.append(json.loads([ln for ln in r.stdout.splitlines() if ln.startswith("KVBYTES")][-1][8:]))+ print(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)+ allres[name] = res+ json.dump(allres, open(E.get("K3_OUT", "/tmp/kvbytes.json"), "w"))+++if __name__ == "__main__":+ child(int(E["K3_CHILD"])) if "K3_CHILD" in E else parent()diff --git a/tools/hy4/mu_engine.py b/tools/hy4/mu_engine.pyindex a9072dc..46a67af 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"): # 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"): # 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 36a6b0d..079ccd8 100644--- a/tools/hy4/serve.py+++ b/tools/hy4/serve.py@@ -90,6 +90,9 @@ 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")):+ 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)os.environ.setdefault("HY4_NOSYNC_CAP", str(((ctx + 64 + 511) // 512) * 512)) # K buffers / token history: fixed for the life of the process