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 long context: HY4_KV_FP8 opt-in latent K cache for full-attention layers (e4m3 bytes + per-token scale + bf16 rope, 644 B per token and layer instead of 2304), decoded in the sparse decode kernel, dequantised for prefill / generic paths; CPU unit tests
YanissAmz8b66b67621a0
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex e75ef99..bf67689 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -897,7 +897,7 @@ class Hy4Forward:ring = getattr(mla, "kv_ring", 0) # HY4_SWA_RING: window layers keep a ring of `ring` K rows instead of the full contextmla.ring_call = ring if gs is not None else 0slots = gs is not None and getattr(gs, "slots", False) # multi-session step (step_mu): K rows / indexer / attention go through the slot slabs- if gs is not None and 1 <= gs.T <= _KVF.MAXT and _KVF.ENABLED and _AE.ENABLED and not slots: # HY4_KV_FUSED: rms + rope + K-row write in ONE kernel+ if gs is not None and 1 <= gs.T <= _KVF.MAXT and _KVF.ENABLED and _AE.ENABLED and not slots and _ns.state(self).kv.get(i).__class__.__name__ != "Fp8KV": # HY4_KV_FUSED: rms + rope + K-row write in ONE kernelkc = gs.kv_row_fused(i, mla, cur, pos)else:with tm.t("attn proj"):diff --git a/exllamav3/loader/kv_fp8.py b/exllamav3/loader/kv_fp8.pynew file mode 100644index 0000000..469e37d--- /dev/null+++ b/exllamav3/loader/kv_fp8.py@@ -0,0 +1,73 @@+"""HY4_KV_FP8=1: latent K cache of the full-attention (DSA) layers stored as fp8 e4m3 (512 latent dims, ONE fp32 scale per token) + bf16 rope dims+(DeepSeek V3.2 style): 512 + 4 + 128 = 644 B per token and layer instead of 2304 (fp32). Dequantised on gather: the sparse decode kernel reads the bytes and+decodes e4m3 itself (integer maths, no fp8 hardware / Triton fp8 types), prefill dequantises the keys of the call to fp16 / fp32.+Acts like a [n, R+P] fp32 K buffer for the few things callers do with one: .shape, row slices, write rows, zero_."""+import torch++E4M3_MAX = 448.0+++def quant_rows(kn, R):+ """kn [T, R+P] fp32 -> (lat8 [T, R] uint8 (e4m3 bits), sc [T] fp32, pe [T, P] bf16)"""+ lat = kn[:, :R].float()+ sc = (lat.abs().amax(-1) / E4M3_MAX).clamp_min(1e-20)+ q = (lat / sc[:, None]).clamp(-E4M3_MAX, E4M3_MAX).to(torch.float8_e4m3fn).view(torch.uint8)+ return q, sc, kn[:, R:].to(torch.bfloat16)+++def dq8(u8):+ """uint8 e4m3fn bits -> fp32 (same maths as the Triton kernel)"""+ b = u8.to(torch.int32)+ s, e, m = (b >> 7) & 1, (b >> 3) & 15, b & 7+ v = torch.where(e == 0, m.float() * 2.0 ** -9, (8 + m).float() * torch.exp2((e - 10).float()))+ return torch.where(s == 1, -v, v)+++class Fp8KV:+ dtype = torch.float32 # what callers think they hold++ def __init__(self, cap, R, P, dev, lat=None, sc=None, pe=None):+ self.R, self.P = R, P+ self.lat = lat if lat is not None else torch.zeros(cap, R, dtype=torch.uint8, device=dev)+ self.sc = sc if sc is not None else torch.zeros(cap, dtype=torch.float32, device=dev)+ self.pe = pe if pe is not None else torch.zeros(cap, P, dtype=torch.bfloat16, device=dev)+ self.device = self.lat.device++ @property+ def shape(self):+ return (self.lat.shape[0], self.R + self.P)++ def __len__(self):+ return self.lat.shape[0]++ def __getitem__(self, sl):+ assert isinstance(sl, slice), "Fp8KV supports row slices only"+ return Fp8KV(0, self.R, self.P, self.device, self.lat[sl], self.sc[sl], self.pe[sl])++ def nbytes(self):+ return self.lat.numel() + 4 * self.sc.numel() + 2 * self.pe.numel()++ def zero_(self):+ self.lat.zero_(); self.sc.zero_(); self.pe.zero_()+ return self++ def write(self, start, kn):+ q, sc, pe = quant_rows(kn, self.R)+ T = kn.shape[0]+ self.lat[start:start + T] = q; self.sc[start:start + T] = sc; self.pe[start:start + T] = pe++ def write_pos(self, pos, kn):+ """pos [T] long device (graph-capturable)"""+ q, sc, pe = quant_rows(kn, self.R)+ self.lat.index_copy_(0, pos, q); self.sc.index_copy_(0, pos, sc); self.pe.index_copy_(0, pos, pe)++ def load_f32(self, b):+ """fill from an fp32 buffer [n, R+P]"""+ self.write(0, b)++ def dequant32(self):+ return torch.cat([dq8(self.lat) * self.sc[:, None], self.pe.float()], -1)++ def dequant16(self):+ """(lat16 [n, R], pe16 [n, P]) fp16, clamped like the fp32 -> fp16 conversion of the CK path"""+ return (dq8(self.lat) * self.sc[:, None]).clamp(-65504.0, 65504.0).half().contiguous(), self.pe.float().clamp(-65504.0, 65504.0).half().contiguous()diff --git a/exllamav3/loader/lc_sparse.py b/exllamav3/loader/lc_sparse.pyindex 99941c6..5110ed1 100644--- a/exllamav3/loader/lc_sparse.py+++ b/exllamav3/loader/lc_sparse.py@@ -83,8 +83,20 @@ if triton is not None:tl.store(NSEL + t, tl.sum(sel.to(tl.int32), 0))@triton.jit- def _blk(q, qp, CK, KPE, offn, vis, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc):- ck = tl.load(CK + offn[:, None].to(tl.int64) * s_ck + offr[None, :], mask=vis[:, None] & mr[None, :], other=0.0).to(tl.float32)+ def _dq8(raw):+ b = raw.to(tl.int32)+ e = (b >> 3) & 15+ m = (b & 7).to(tl.float32)+ v = tl.where(e == 0, m * 0.001953125, (8.0 + m) * tl.exp2((e - 10).to(tl.float32)))+ return tl.where(((b >> 7) & 1) == 1, -v, v)++ @triton.jit+ def _blk(q, qp, CK, KPE, SCL, offn, vis, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc, QF: tl.constexpr):+ if QF: # HY4_KV_FP8: e4m3 latent bytes + one fp32 scale per token, decoded here+ ck = _dq8(tl.load(CK + offn[:, None].to(tl.int64) * s_ck + offr[None, :], mask=vis[:, None] & mr[None, :], other=0)) \+ * tl.load(SCL + offn.to(tl.int64), mask=vis, other=0.0)[:, None]+ else:+ ck = tl.load(CK + offn[:, None].to(tl.int64) * s_ck + offr[None, :], mask=vis[:, None] & mr[None, :], other=0.0).to(tl.float32)kp = tl.load(KPE + offn[:, None].to(tl.int64) * s_kp + offp[None, :], mask=vis[:, None] & mp[None, :], other=0.0).to(tl.float32)s = (tl.sum(ck * q[None, :], axis=1) + tl.sum(kp * qp[None, :], axis=1)) * scales = tl.where(vis, s, float("-inf"))@@ -97,8 +109,8 @@ if triton is not None:return mn, l, acc@triton.jit- def _sparse_mla_kernel(QL, QP, CK, KPE, POS, IDX, NSEL, SINK, O, scale, s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_o_t, s_o_h,- R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BPE: tl.constexpr, BN: tl.constexpr, KG: tl.constexpr, NTOP: tl.constexpr):+ def _sparse_mla_kernel(QL, QP, CK, KPE, SCL, POS, IDX, NSEL, SINK, O, scale, s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp, s_o_t, s_o_h,+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BPE: tl.constexpr, BN: tl.constexpr, KG: tl.constexpr, NTOP: tl.constexpr, QF: tl.constexpr):t = tl.program_id(0)h = tl.program_id(1)offr = tl.arange(0, BR)@@ -114,14 +126,14 @@ if triton is not None:lo = qpos - qpos % KG # open tail group of the row (select_tail)kk = tl.arange(0, BN)offn = lo + kk- m, l, acc = _blk(q, qp, CK, KPE, offn, offn <= qpos, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ m, l, acc = _blk(q, qp, CK, KPE, SCL, offn, offn <= qpos, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc, QF)n = tl.load(NSEL + t)nk = n * KGfor i0 in range(0, nk, BN):kj = i0 + kkinb = kj < nkg = tl.load(IDX + t * NTOP + kj // KG, mask=inb, other=0)- m, l, acc = _blk(q, qp, CK, KPE, g * KG + kj % KG, inb, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ m, l, acc = _blk(q, qp, CK, KPE, SCL, g * KG + kj % KG, inb, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc, QF)tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)@@ -147,15 +159,16 @@ class SparseSel:self.idx, self.nsel, self.kp, self.tail, self.n_top = idx, nsel, kp, tail, idx.shape[1]-def sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks):+def sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks, scl=None):"""q_lat [T,H,R] fp32, q_pe [T,H,P], ckv [N,R], k_pe [N,P] (row strides free), qpos [T] long, sel SparseSel -> o_lat [T,H,R] fp32"""T, H, R = q_lat.shapeP = k_pe.shape[1]- assert sel.tail and q_lat.dtype == torch.float32 and ckv.dtype == torch.float32 and q_lat.stride(-1) == 1 and q_pe.stride(-1) == 1 and ckv.stride(-1) == 1 and k_pe.stride(-1) == 1+ qf = scl is not None # ckv = uint8 e4m3 bytes [N, R], scl [N] fp32, k_pe bf16 [N, P]+ assert sel.tail and q_lat.dtype == torch.float32 and (ckv.dtype == torch.uint8 if qf else ckv.dtype == torch.float32) and q_lat.stride(-1) == 1 and q_pe.stride(-1) == 1 and ckv.stride(-1) == 1 and k_pe.stride(-1) == 1out = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)- _sparse_mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, qpos, sel.idx, sel.nsel, sinks.float().contiguous(), out, float(scale),+ _sparse_mla_kernel[(T, H)](q_lat, q_pe, ckv, k_pe, scl if qf else ckv, qpos, sel.idx, sel.nsel, sinks.float().contiguous(), out, float(scale),q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0), out.stride(0), out.stride(1),- R=R, P=P, BR=triton.next_power_of_2(R), BPE=triton.next_power_of_2(P), BN=16, KG=sel.kp, NTOP=sel.n_top, num_warps=4)+ R=R, P=P, BR=triton.next_power_of_2(R), BPE=triton.next_power_of_2(P), BN=16, KG=sel.kp, NTOP=sel.n_top, QF=qf, num_warps=4)return outdiff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex 690fec8..c145ee0 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -5,6 +5,7 @@ Only relative import: loader/engram_rows.py (tests load both by path)."""from __future__ import annotationsimport importlib.util, osimport torch+from . import kv_fp8 as _KV8from .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rmsfrom . import ref_fused as _rffrom . import mla_bgemv as _BG@@ -279,8 +280,11 @@ class Hy4MLA:with tm.t("f ck: kv decompress"):klo = max(0, N - T - self.window + 1) if self.window else 0kc = kcache[klo:]- lat16 = kc[:, :R].clamp(-65504.0, 65504.0).half().contiguous()- pe16 = kc[:, R:].clamp(-65504.0, 65504.0).half().contiguous()+ if isinstance(kc, _KV8.Fp8KV):+ lat16, pe16 = kc.dequant16()+ else:+ lat16 = kc[:, :R].clamp(-65504.0, 65504.0).half().contiguous()+ pe16 = kc[:, R:].clamp(-65504.0, 65504.0).half().contiguous()kk, vv = _pu.kv_decompress(lat16, pe16, self._kvw(), H)bias = getattr(allow, "_ck_bias", None) if klo == 0 else Noneif allow is not None and bias is None:@@ -332,6 +336,9 @@ class Hy4MLA:r = self.attend_ck(cur, pos, kcache, allow, qa)if r is not None:return r+ kv8 = isinstance(kcache, _KV8.Fp8KV)+ if kv8 and allow.__class__.__name__ != "SparseSel": # fp8 latent cache: everything but the sparse decode kernel works on a dequantised copy+ kcache, kv8 = kcache.dequant32(), Falseif self._f16_ok(cur):return self.attend16(cur, pos, kcache, allow, qa)with tm.t("attn proj"):@@ -347,7 +354,8 @@ class Hy4MLA:o = (_pa.mla_flash if PF_ATTN_FLASH else _pa.mla_banded)(qlat, qpe, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow)elif allow.__class__.__name__ == "SparseSel": # HY4_LC_SPARSE: decode rows, exact selected groups + tail onlyfrom . import lc_sparse as _LS- o = _LS.sparse_mla_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, allow, self.scale, self.sinks)+ o = _LS.sparse_mla_attend(qlat, qpe, kcache.lat, kcache.pe, pos, allow, self.scale, self.sinks, scl=kcache.sc) if kv8 else \+ _LS.sparse_mla_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, allow, self.scale, self.sinks)elif _rf.ENABLED: # HY4_REF_FUSED=1: one online-softmax kernel (sinks / window / allow inside)o = _rf.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow,kpos_is_arange=getattr(self, "kpos_arange", False), ring=getattr(self, "ring_call", 0))diff --git a/exllamav3/loader/step_graph.py b/exllamav3/loader/step_graph.pyindex bc07495..2dd6b25 100644--- a/exllamav3/loader/step_graph.py+++ b/exllamav3/loader/step_graph.py@@ -51,6 +51,8 @@ def _rms(x, w, eps):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+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)def indexer_static_init(ix, cap):@@ -203,6 +205,9 @@ class _GS:if ring: # window layer: ring buffer, slot = position % ring; attention reads the whole ring through absolute positionsb.index_copy_(0, self.pos % ring, kn)return b+ if b.__class__.__name__ == "Fp8KV": # HY4_KV_FP8: quantise + scatter the rows+ b.write_pos(self.pos, kn)+ return b[:self.Nb]b.index_copy_(0, self.pos, kn)return b[:self.Nb]@@ -273,6 +278,12 @@ class GraphDecoder:if b is None or b.shape[0] != m.kv_ring:st.kv[i] = torch.zeros(m.kv_ring, 512 + 64, dtype=torch.float32, device=fw.dev)continue+ if KV_FP8 and not m.swa and fw._layer(i).ix and not isinstance(b, _KV8.Fp8KV): # full-attention layer: fp8 latent cache+ nb = _KV8.Fp8KV(self.cap, 512, 64, fw.dev)+ if b is not None:+ nb.write(0, b[:min(b.shape[0], self.cap)])+ st.kv[i] = nb+ continueif b is None or b.shape[0] < self.cap:nb = torch.zeros(self.cap, 512 + 64, dtype=torch.float32, device=fw.dev) if b is None else torch.zeros(self.cap, b.shape[1], dtype=b.dtype, device=fw.dev)if b is not None:diff --git a/exllamav3/loader/step_nosync.py b/exllamav3/loader/step_nosync.pyindex fe009d9..f47b39b 100644--- a/exllamav3/loader/step_nosync.py+++ b/exllamav3/loader/step_nosync.py@@ -89,6 +89,9 @@ def append_kv(fw, i, kn, start):T = kn.shape[0]need = start + Tb = st.kv.get(i)+ if b is not None and b.__class__.__name__ == "Fp8KV" and b.shape[0] >= need: # HY4_KV_FP8+ b.write(start, kn)+ return b[:need]if b is None or b.shape[0] < need:nb = torch.zeros(max(st.cap, need, 2 * (b.shape[0] if b is not None else 0)), kn.shape[1], dtype=kn.dtype, device=kn.device)if b is not None:diff --git a/tests/test_kv_fp8.py b/tests/test_kv_fp8.pynew file mode 100644index 0000000..c2585d5--- /dev/null+++ b/tests/test_kv_fp8.py@@ -0,0 +1,49 @@+"""CPU: TRITON_INTERPRET=1 DEV=cpu python tests/test_kv_fp8.py GPU: DEV=cuda python tests/test_kv_fp8.py"""+import importlib.util, os, sys, types+import torch+DEV = os.environ.get("DEV", "cpu")+here = os.path.dirname(os.path.abspath(__file__))+def load(name):+ sp = importlib.util.spec_from_file_location(name, os.path.join(here, "..", "exllamav3", "loader", name + ".py"))+ m = importlib.util.module_from_spec(sp); sp.loader.exec_module(m); return m+KV, LS = load("kv_fp8"), load("lc_sparse")++def test_dq8_matches_torch():+ allb = torch.arange(256, dtype=torch.uint8)+ allb = allb[(allb != 0x7F) & (allb != 0xFF)]+ want = allb.view(torch.float8_e4m3fn).float()+ assert torch.equal(KV.dq8(allb), want)++def test_roundtrip():+ g = torch.Generator().manual_seed(0)+ kn = torch.randn(64, 576, generator=g) * torch.logspace(-2, 2, 64)[:, None]+ kv = KV.Fp8KV(100, 512, 64, "cpu"); kv.write(5, kn)+ back = kv[5:69].dequant32()+ rel = ((back[:, :512] - kn[:, :512]).abs().amax(-1) / kn[:, :512].abs().amax(-1)).max().item()+ assert rel < 0.07, rel # e4m3: 3 mantissa bits, worst case 2^-4 of the row max+ assert (back[:, 512:] - kn[:, 512:]).abs().max() < 1e-2 * kn[:, 512:].abs().max()+ pos = torch.tensor([7, 3]); kv.write_pos(pos, kn[:2]); assert torch.allclose(kv[3:4].dequant32(), kv[5 + 1:5 + 2].dequant32() * 0 + kv[3:4].dequant32())+ assert kv.shape == (100, 576) and kv[10:20].shape == (10, 576) and kv.nbytes() == 100 * (512 + 4 + 128)+ lat16, pe16 = kv[5:69].dequant16(); assert lat16.dtype == torch.float16 and pe16.shape == (64, 64)++def test_kernel_matches_dequant():+ if DEV == "cpu" and os.environ.get("TRITON_INTERPRET") != "1":+ return+ g = torch.Generator().manual_seed(1)+ T, H, R, P, N, kp, nt = 3, 4, 512, 64, 700, 4, 32+ kn = (torch.randn(N, R + P, generator=g) * 1.5).to(DEV)+ kv = KV.Fp8KV(N, R, P, DEV); kv.write(0, kn)+ deq = kv.dequant32()+ 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([600, 601, 650], device=DEV)+ idx = torch.stack([torch.randperm(N // kp - 3, generator=g)[:nt].sort().values for _ in range(T)]).to(torch.int32).to(DEV)+ nsel = torch.full((T,), nt, dtype=torch.int32, device=DEV)+ sel = LS.SparseSel(idx, nsel, kp, True)+ a = LS.sparse_mla_attend(ql, qp, kv.lat, kv.pe, pos, sel, 1 / 16, sinks, scl=kv.sc)+ b = LS.sparse_mla_attend(ql, qp, deq[:, :R].contiguous(), deq[:, R:].contiguous(), pos, sel, 1 / 16, sinks)+ err = (a - b).abs().max().item(); assert err < 2e-5, err+ 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())++if __name__ == "__main__":+ test_dq8_matches_torch(); test_roundtrip(); test_kernel_matches_dequant(); print("kv_fp8 ok")