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 fp8 KV: head-blocked attend on by default only on the fp8 cache (HY4_LC_HB=0 off switch, auto split), fp8 KV stays off by default; sizing table and flag docs, changelog entry, CPU tests (sizing, per-row roundtrip, head-blocked kernels vs the one-head kernel, flag defaults)
YanissAmzd629637a47cb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffb4616..fd77889 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,10 @@ Hy4-flash server hotfix: tool calling, a quiet exit when the client leaves, requ- Docs: the README test command uses the right port per server (Hy4-flash is on 8300) and the Hy4 example answers directly (`reasoning_effort` `no_think`); README states that reasoning goes to `reasoning_content`; README version line, CHANGELOG 1.9.1 wording and the venv command (`python3.12`) are consistent across the install docs.- New: `tools/hy4/tool_smoke.py`, a served smoke test of tool calling and client disconnect. New CPU tests: `tests/test_hy4_tools_cpu.py`, `tests/test_hy4_compat_cpu.py`, `tests/test_strix_scripts_cpu.py`.+## Unreleased (1.9.3)++- 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.1Hy4-flash: faster prefill at every depth and faster decode on the same prompt (the 32K served decode cell reads lower than 1.9.0 because that prompt's tau and generated text differ; see the README table note), decensor preset, warm-up fix. Every lever below ships on and has its own switch: `HY4_<FLAG>=0` in the environment restores the 1.9.0 behaviour of that lever. The flag table is in `doc/env_vars.md`; numbers are in the release notes.diff --git a/doc/hy4.md b/doc/hy4.mdindex b759667..2439ff9 100644--- a/doc/hy4.md+++ b/doc/hy4.md@@ -63,6 +63,7 @@ The server speaks the OpenAI API (`/v1/chat/completions`, `/v1/completions`, bot| `HY4_NGRAM_EXT`, `HY4_NGRAM_MIN` | 4, 8 | prompt-lookup rows added to the MTP drafts when the last 8 tokens occurred before || `HY4_MTP_HEAD` | q5k | head of the MTP drafts || `HY4_MLA_HB` | 1 | decode attention: one kernel reads each K tile once for 16 heads (fp16 `tl.dot`); `HY4_MLA_HB_SPLIT` adds a key-split path for few-row steps |+| `HY4_KV_FP8` | 0 | opt-in fp8 e4m3 latent K cache of the full-attention layers for `-c 131072` / `-c 262144` (see "Long context option"); `HY4_LC_HB` (1) and `HY4_LC_HB_SPLIT` (-1) select the head-blocked sparse attend that reads it || `HY4_BG_DOT`, `HY4_HEAD_DOT` | 1 | k_b / v_b and output-head products of the verify rows on `tl.dot` (used from 5 rows for k_b / v_b, from 3 rows for the head) || `HY4_RG_F16` | 1 | fp16 resident router weights for the router mat-vec, fp32 accumulate || `HY4_KV_FUSED_MAXT` | 16 | the fused K-row / q-rope kernels take verify rows up to this count (was 1 row) |@@ -98,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`.+### 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.++Latent K cache, analytic (12 trunk full-attention layers in fp8 or fp32, the MTP layer in fp32, 30 window layers at 1024 rows; the 84.3 GiB of weights and 3 GiB of graph pools and activations are not included):++| `-c` | fp32 KV | fp8 KV |+|---|---|---|+| 65536 | 1.9 GiB | 0.7 GiB |+| 131072 | 3.7 GiB | 1.3 GiB |+| 262144 | 7.4 GiB | 2.5 GiB |++Estimated total memory with sparse prefill (chunk 8192 at 128K and 256K, fp32 indexer pool, full draft states): about 92 GiB at `-c 131072` and 97 GiB at `-c 262144` with fp8 KV. With fp32 KV and dense prefill the same model gives 101 and 114 GiB, and it read 100.9 GiB for the 128K row that measured 110.4 GiB of GTT: read the estimates as a lower bound. Quality, measured on the lane tree: fp8 KV + head-blocked attend, long-text NLL change -0.0025 +- 0.019 against a noise null of 0.0263. Not yet measured on this build: served speed, memory peak and passkey at 128K and 256K.+## Uncensor preset (opt-in)Off by default: the server runs the unmodified forward. The preset bundled in `presets/hy4-uncensor/` is a run-time edit of the attention and MLP / MoE outputs and changes no weights. Switch it on:diff --git a/exllamav3/loader/lc_sparse.py b/exllamav3/loader/lc_sparse.pyindex 64f0411..fcaeb06 100644--- a/exllamav3/loader/lc_sparse.py+++ b/exllamav3/loader/lc_sparse.py@@ -22,8 +22,8 @@ except Exception:CHECK = os.environ.get("HY4_LC_CHECK", "0") == "1" # eager (non-captured) calls also run the dense torch selection and count differing row sets (debug / gate)STATS = {"rows": 0, "diff_rows": 0, "diff_groups": 0, "max_gap": 0.0}-HB_ON = os.environ.get("HY4_LC_HB", "0") == "1" # fp8 cache: head-blocked sparse attend (one key decode for HB heads); 0 = the one-head kernel-HB_SPLIT = int(os.environ.get("HY4_LC_HB_SPLIT", "0")) # with HY4_LC_HB: key splits of the head-blocked kernel (flash-decoding combine); n >= 1 fixed, -1 auto (16 rows <= 3, else 8), 0 = one program per (row, head block)+HB_ON = os.environ.get("HY4_LC_HB", "1") == "1" # fp8 cache only (HY4_KV_FP8=1; the fp32 cache never reaches it): head-blocked sparse attend (one key decode for HB heads); HY4_LC_HB=0 = the one-head kernel+HB_SPLIT = int(os.environ.get("HY4_LC_HB_SPLIT", "-1")) # with HY4_LC_HB: key splits of the head-blocked kernel (flash-decoding combine); n >= 1 fixed, -1 auto (16 rows <= 3, else 8), 0 = one program per (row, head block)HB = 16HB_BN = int(os.environ.get("HY4_LC_HB_BN", "16"))ENABLED = os.environ.get("HY4_LC_SPARSE", "0") == "1" # decode: indexer layers use select_groups + sparse_mla_attend instead of the dense allow maskdiff --git a/tests/test_hy4_shipped_flags.py b/tests/test_hy4_shipped_flags.pyindex dbcc88c..fba8eff 100644--- a/tests/test_hy4_shipped_flags.py+++ b/tests/test_hy4_shipped_flags.py@@ -46,3 +46,25 @@ def test_apply_env_keeps_user_values():body = src[src.index("def apply_env"):]body = body[:body.index("\ndef ", 10)]assert "os.environ.setdefault(k, v)" in body+++# ---- 1.9.2: opt-in fp8 KV (long context) and the head-blocked attend that reads it+++def _read(path):+ return open(os.path.join(TREE, path)).read()+++def test_kv_fp8_is_off_by_default_and_not_shipped():+ """-c 65536 keeps the fp32 cache: HY4_KV_FP8 is not in SHIPPED_ENV and its code default is 0 (the long-context option is the user's env)"""+ assert "HY4_KV_FP8" not in _shipped_env()+ assert re.search(r'environ\.get\("HY4_KV_FP8", "0"\) == "1"', _read("exllamav3/loader/step_graph.py"))+++def test_head_blocked_attend_defaults_and_switches():+ """HY4_LC_HB defaults on and HY4_LC_HB=0 switches it off; it can only run on the fp8 cache (qf), so it is on by default only when HY4_KV_FP8 is on"""+ src = _read("exllamav3/loader/lc_sparse.py")+ assert re.search(r'HB_ON = os\.environ\.get\("HY4_LC_HB", "1"\) == "1"', src)+ assert re.search(r'HB_SPLIT = int\(os\.environ\.get\("HY4_LC_HB_SPLIT", "-1"\)\)', src)+ assert "HY4_LC_HB" not in _shipped_env() and "HY4_LC_HB_SPLIT" not in _shipped_env()+ assert len(re.findall(r"if qf and HB_ON", src)) == 2, "both head-blocked launches must be gated by the fp8 cache flag qf"diff --git a/tests/test_kv_fp8.py b/tests/test_kv_fp8.pyindex 461ded5..4617dc2 100644--- a/tests/test_kv_fp8.py+++ b/tests/test_kv_fp8.py@@ -55,5 +55,59 @@ def test_kernel_matches_dequant():c = LS.sparse_mla_attend(ql, qp, kn[:, :R].contiguous(), kn[:, R:].contiguous(), pos, sel, 1 / 16, sinks)print("fp8 vs exact attend max abs diff", (a - c).abs().max().item(), "out scale", c.abs().mean().item())+def test_head_blocked_matches_one_head():+ """HY4_LC_HB kernels (single pass and split-K with the combine) vs the one-head fp8 kernel on the same cache (Triton interpreter on CPU)"""+ if DEV == "cpu" and os.environ.get("TRITON_INTERPRET") != "1":+ return+ pkg = types.ModuleType("kvhb_pkg"); pkg.__path__ = [os.path.join(here, "..", "exllamav3", "loader")]; sys.modules["kvhb_pkg"] = pkg # package context for the relative import of ref_fused (combine kernel)+ import importlib+ LS = importlib.import_module("kvhb_pkg.lc_sparse")+ g = torch.Generator().manual_seed(2)+ T, H, R, P, N, kp, nt = 3, 16, 512, 64, 400, 4, 24+ kn = (torch.randn(N, R + P, generator=g) * 1.5).to(DEV)+ kv = KV.Fp8KV(N, R, P, DEV); kv.write(0, kn)+ ql = torch.randn(T, H, R, generator=g).to(DEV); qp = torch.randn(T, H, P, generator=g).to(DEV); sinks = torch.randn(H, generator=g).to(DEV)+ pos = torch.tensor([300, 301, 350], device=DEV)+ idx = torch.stack([torch.randperm(N // kp - 3, generator=g)[:nt].sort().values for _ in range(T)]).to(torch.int32).to(DEV)+ sel = LS.SparseSel(idx, torch.full((T,), nt, dtype=torch.int32, device=DEV), kp, True)+ old = (LS.HB_ON, LS.HB_SPLIT)+ try:+ LS.HB_ON = False+ ref = LS.sparse_mla_attend(ql, qp, kv.lat, kv.pe, pos, sel, 1 / 16, sinks, scl=kv.sc)+ for split in (0, -1, 3):+ LS.HB_ON, LS.HB_SPLIT = True, split+ out = LS.sparse_mla_attend(ql, qp, kv.lat, kv.pe, pos, sel, 1 / 16, sinks, scl=kv.sc)+ err = (out - ref).abs().max().item()+ assert err < 5e-3, (split, err) # fp16 operands of tl.dot vs the fp32 one-head kernel+ finally:+ LS.HB_ON, LS.HB_SPLIT = old++G = 2 ** 30++def kv_plan_gib(n, fp8, full=13, swa=30, ring=1024, lat=576):+ """latent K cache of Hy4-flash in GiB: `full` full-attention layers (12 trunk + the MTP layer, which stays fp32), `swa` window layers on a `ring` rows ring (fp32)"""+ k = (12 * n * KV.Fp8KV(1, 512, 64, "cpu").nbytes() + n * lat * 4) if fp8 else full * n * lat * 4+ return (k + swa * ring * lat * 4) / G++def test_sizing_math():+ assert KV.Fp8KV(1, 512, 64, "cpu").nbytes() == 644 # bytes per token and layer, fp32 is 2304+ got = {n: (round(kv_plan_gib(n, False), 1), round(kv_plan_gib(n, True), 1)) for n in (131072, 262144)}+ assert got == {131072: (3.7, 1.3), 262144: (7.4, 2.5)}, got # the doc table of doc/hy4.md+ assert kv_plan_gib(65536, True) < kv_plan_gib(65536, False) / 2.5+ for n in (65536, 131072, 262144): # -c 262144 with fp8 stays under the 128 GB machine with room for weights (84.3) + pools / activations (3)+ assert 84.3 + 3.0 + kv_plan_gib(n, True) < 100.0++def test_roundtrip_cpu_rows_and_scale():+ """quantise on write, per-row scale: a row of 1e-3 magnitudes and a row of 1e3 magnitudes both keep ~2^-4 relative accuracy; an all-zero row stays zero"""+ kn = torch.zeros(3, 576)+ g = torch.Generator().manual_seed(3)+ kn[0, :512] = torch.randn(512, generator=g) * 1e-3+ kn[1, :512] = torch.randn(512, generator=g) * 1e3+ kv = KV.Fp8KV(3, 512, 64, "cpu"); kv.write(0, kn)+ back = kv.dequant32()+ for r in (0, 1):+ assert ((back[r, :512] - kn[r, :512]).abs().max() / kn[r, :512].abs().max()) < 0.07+ assert torch.count_nonzero(back[2]) == 0+if __name__ == "__main__":- test_dq8_matches_torch(); test_roundtrip(); test_dequant16_cat(); test_kernel_matches_dequant(); print("kv_fp8 ok")+ test_dq8_matches_torch(); test_roundtrip(); test_dequant16_cat(); test_kernel_matches_dequant(); test_head_blocked_matches_one_head(); test_sizing_math(); test_roundtrip_cpu_rows_and_scale(); print("kv_fp8 ok")