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: fp8 cache sparse prefill reads a chunked fp16 dequantised cache; head-blocked split-K fp8 sparse attend (HY4_LC_HB, HY4_LC_HB_SPLIT) with the key-split combine, rows kernel parameters (HY4_MLA_HB_ROWS, off), model-free micro and paired A/B drivers
YanissAmz5d2ccf905db7
diff --git a/exllamav3/loader/kv_fp8.py b/exllamav3/loader/kv_fp8.pyindex 469e37d..5d92267 100644--- a/exllamav3/loader/kv_fp8.py+++ b/exllamav3/loader/kv_fp8.py@@ -71,3 +71,14 @@ class Fp8KV: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()++ def dequant16_cat(self, chunk=65536):+ """the whole cache as ONE fp16 [n, R+P] tensor (latent * scale, clamped like the fp32 -> fp16 cast; rope as is): the sparse prefill kernel reads it.+ torch fp8 cast (exact, same values as dq8), chunked so the fp32 temporaries stay small at 1M rows."""+ n, R = self.lat.shape[0], self.R+ out = torch.empty(n, R + self.P, dtype=torch.float16, device=self.device)+ for s in range(0, n, chunk):+ e = min(n, s + chunk)+ out[s:e, :R] = (self.lat[s:e].view(torch.float8_e4m3fn).float() * self.sc[s:e, None]).clamp(-65504.0, 65504.0).half()+ out[s:e, R:] = self.pe[s:e].float().clamp(-65504.0, 65504.0).half()+ return outdiff --git a/exllamav3/loader/lc_sparse.py b/exllamav3/loader/lc_sparse.pyindex 5110ed1..64f0411 100644--- a/exllamav3/loader/lc_sparse.py+++ b/exllamav3/loader/lc_sparse.py@@ -22,6 +22,10 @@ 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 = 16+HB_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 mask@@ -137,6 +141,97 @@ if triton is not None:tl.store(O + t * s_o_t + h * s_o_h + offr, acc / l, mask=mr)+ @triton.jit+ def _sparse_mla_hb_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,+ HB: tl.constexpr):+ """fp8 latent cache, HB heads per program: every key row is read and decoded ONCE for HB heads (the one-head kernel decodes it H times); scores and+ the value sum run on tl.dot (fp16 operands: e4m3 values are exact in fp16, the per-token scale is applied to the scores / probabilities in fp32)"""+ t = tl.program_id(0)+ offh = tl.program_id(1) * HB + tl.arange(0, HB)+ offr = tl.arange(0, BR)+ offp = tl.arange(0, BPE)+ mr = offr < R+ mp = offp < P+ q = tl.load(QL + t * s_ql_t + offh[:, None] * s_ql_h + offr[None, :], mask=mr[None, :], other=0.0).to(tl.float16)+ qp = tl.load(QP + t * s_qp_t + offh[:, None] * s_qp_h + offp[None, :], mask=mp[None, :], other=0.0).to(tl.float16)+ qpos = tl.load(POS + t)+ m = tl.load(SINK + offh).to(tl.float32)+ l = tl.zeros([HB], dtype=tl.float32) + 1.0+ acc = tl.zeros([HB, BR], dtype=tl.float32)+ lo = qpos - qpos % KG+ kk = tl.arange(0, BN)+ offn = lo + kk+ m, l, acc = _blk_hb(q, qp, CK, KPE, SCL, offn, offn <= qpos, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ n = tl.load(NSEL + t)+ nk = n * KG+ for i0 in range(0, nk, BN):+ kj = i0 + kk+ inb = kj < nk+ g = tl.load(IDX + t * NTOP + kj // KG, mask=inb, other=0)+ m, l, acc = _blk_hb(q, qp, CK, KPE, SCL, g * KG + kj % KG, inb, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ tl.store(O + t * s_o_t + offh[:, None] * s_o_h + offr[None, :], acc / l[:, None], mask=mr[None, :])++ @triton.jit+ def _blk_hb(q, qp, CK, KPE, SCL, offn, vis, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc):+ ck = _dq8(tl.load(CK + offn[:, None].to(tl.int64) * s_ck + offr[None, :], mask=vis[:, None] & mr[None, :], other=0)).to(tl.float16) # [BN, BR]+ sc = tl.load(SCL + offn.to(tl.int64), mask=vis, other=0.0)+ kp = tl.load(KPE + offn[:, None].to(tl.int64) * s_kp + offp[None, :], mask=vis[:, None] & mp[None, :], other=0.0).to(tl.float16)+ s = (tl.dot(q, tl.trans(ck)) * sc[None, :] + tl.dot(qp, tl.trans(kp))) * scale # [HB, BN]+ s = tl.where(vis[None, :], s, float("-inf"))+ mn = tl.maximum(m, tl.max(s, axis=1))+ mn_s = tl.where(mn == float("-inf"), 0.0, mn)+ alpha = tl.exp(m - mn_s)+ pr = tl.exp(s - mn_s[:, None])+ l = l * alpha + tl.sum(pr, axis=1)+ acc = acc * alpha[:, None] + tl.dot((pr * sc[None, :]).to(tl.float16), ck)+ return mn, l, acc+++ @triton.jit+ def _sparse_mla_hbs_kernel(QL, QP, CK, KPE, SCL, POS, IDX, NSEL, SINK, WA, WM, WL, scale, s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp,+ R: tl.constexpr, P: tl.constexpr, BR: tl.constexpr, BPE: tl.constexpr, BN: tl.constexpr, KG: tl.constexpr, NTOP: tl.constexpr,+ HB: tl.constexpr, S: tl.constexpr):+ """_sparse_mla_hb_kernel over one split of the selected keys: grid (T, H / HB, S). Split s walks its share of the BN-key blocks of the row's selected groups; split 0 also+ takes the open tail group and carries the sink (m = sink, l = 1), the others start empty (m = -1e30 finite, l = 0). Writes the unnormalised partial (acc [HB, R], m, l)+ for ref_fused._mla_hb_combine (layout ((t * NG + g) * S + s) major). The one-head kernel (T x H programs, each decoding every key) filled 32 of 40 CUs at T = 1."""+ t = tl.program_id(0)+ g = tl.program_id(1)+ sp = tl.program_id(2)+ NG = tl.num_programs(1)+ offh = g * HB + tl.arange(0, HB)+ offr = tl.arange(0, BR)+ offp = tl.arange(0, BPE)+ mr = offr < R+ mp = offp < P+ q = tl.load(QL + t * s_ql_t + offh[:, None] * s_ql_h + offr[None, :], mask=mr[None, :], other=0.0).to(tl.float16)+ qp = tl.load(QP + t * s_qp_t + offh[:, None] * s_qp_h + offp[None, :], mask=mp[None, :], other=0.0).to(tl.float16)+ qpos = tl.load(POS + t)+ first = (sp == 0)+ m = tl.where(first, tl.load(SINK + offh).to(tl.float32), -1e30)+ l = tl.where(first, 1.0, 0.0) + tl.zeros([HB], dtype=tl.float32)+ acc = tl.zeros([HB, BR], dtype=tl.float32)+ kk = tl.arange(0, BN)+ if first:+ lo = qpos - qpos % KG+ offn = lo + kk+ m, l, acc = _blk_hb(q, qp, CK, KPE, SCL, offn, offn <= qpos, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ nk = tl.load(NSEL + t) * KG+ nblk = (nk + BN - 1) // BN+ per = (nblk + S - 1) // S+ b0 = tl.minimum(nblk, sp * per)+ b1 = tl.minimum(nblk, b0 + per)+ for i0 in range(b0 * BN, b1 * BN, BN):+ kj = i0 + kk+ inb = kj < nk+ gg = tl.load(IDX + t * NTOP + kj // KG, mask=inb, other=0)+ m, l, acc = _blk_hb(q, qp, CK, KPE, SCL, gg * KG + kj % KG, inb, s_ck, s_kp, offr, offp, mr, mp, scale, m, l, acc)+ wi = (t * NG + g) * S + sp+ ar = tl.arange(0, HB)+ tl.store(WA + wi * (HB * BR) + ar[:, None] * BR + offr[None, :], acc, mask=mr[None, :])+ tl.store(WM + wi * HB + ar, m)+ tl.store(WL + wi * HB + ar, l)+def select_groups(iq, wt, pool, pos, Pb, n_top, kp, tail):"""iq [T, H, d] fp32 contiguous, wt [T, H] fp32, pool [>= Pb, d] fp32, pos [T] long (device) -> (idx [T, n_top] int32, nsel [T] int32)"""T, H, D = iq.shape@@ -166,6 +261,22 @@ def sparse_mla_attend(q_lat, q_pe, ckv, k_pe, qpos, sel, scale, sinks, scl=None)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)+ if qf and HB_ON and HB_SPLIT != 0 and H % HB == 0 and R == triton.next_power_of_2(R) and R <= 1024:+ from . import ref_fused as _rf+ ng, S = H // HB, (HB_SPLIT if HB_SPLIT > 0 else (16 if T <= 3 else 8)) # -1 = auto: the micro sweep (84_00_2a_mla_micro) best split per row count+ wa = torch.empty(T * ng * S * HB * R, dtype=torch.float32, device=q_lat.device)+ wm = torch.empty(T * ng * S * HB, dtype=torch.float32, device=q_lat.device)+ wl = torch.empty(T * ng * S * HB, dtype=torch.float32, device=q_lat.device)+ _sparse_mla_hbs_kernel[(T, ng, S)](q_lat, q_pe, ckv, k_pe, scl, qpos, sel.idx, sel.nsel, sinks.float().contiguous(), wa, wm, wl, 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),+ R=R, P=P, BR=R, BPE=triton.next_power_of_2(P), BN=HB_BN, KG=sel.kp, NTOP=sel.n_top, HB=HB, S=S, num_warps=4)+ _rf._mla_hb_combine[(T, ng)](wa, wm, wl, out, out.stride(0), out.stride(1), R=R, BH=HB, S=S, num_warps=4)+ return out+ if qf and HB_ON and H % HB == 0 and R <= 1024:+ _sparse_mla_hb_kernel[(T, H // HB)](q_lat, q_pe, ckv, k_pe, scl, 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=HB_BN, KG=sel.kp, NTOP=sel.n_top, HB=HB, num_warps=4)+ return out_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, QF=qf, num_warps=4)diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex c145ee0..6b61700 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -329,6 +329,8 @@ class Hy4MLA:qa, self._qa_pre = self._qa_pre, Noneif allow.__class__.__name__ == "PfSparse":if self._f16_ok(cur) and self.H % 32 == 0:+ if isinstance(kcache, _KV8.Fp8KV): # HY4_KV_FP8: the sparse prefill kernel reads fp16 rows+ kcache = kcache.dequant16_cat()return self.attend16(cur, pos, kcache, allow, qa)if not (PRIME_SPARSE and cur.is_cuda):allow = allow.to_dense() # else: generic path below, sparse gather (draft-cache fill at long context: a dense [T, N] mask costs O(T x N) and compiles N-sized kernels)diff --git a/exllamav3/loader/ref_fused.py b/exllamav3/loader/ref_fused.pyindex eb76358..d91b0cc 100644--- a/exllamav3/loader/ref_fused.py+++ b/exllamav3/loader/ref_fused.py@@ -16,6 +16,11 @@ ENABLED = os.environ.get("HY4_REF_FUSED", "0") == "1"HB = os.environ.get("HY4_MLA_HB", "0") == "1" # head-batched fp16 tl.dot decode attention (opt-in)HB_BN = int(os.environ.get("HY4_MLA_HB_BN", "16"))HB_NW = int(os.environ.get("HY4_MLA_HB_NW", "4"))+HB_ROWS = int(os.environ.get("HY4_MLA_HB_ROWS", "0")) # >= 2: verify rows (2..HB_ROWS) of a head group share ONE pass over the K rows (M = 16 heads x rows in the tl.dot; default 0 = off)+HB_ROWS_NW = int(os.environ.get("HY4_MLA_HB_ROWS_NW", "8"))+HB_ROWS_BN = int(os.environ.get("HY4_MLA_HB_ROWS_BN", "16"))+HB_ROWS_BH = int(os.environ.get("HY4_MLA_HB_ROWS_BH", "8")) # heads per program of the rows kernel (M = BH x RG; M = 64 spilled registers: 1.4 KB scratch per thread, dec7)+HB_ROWS_RG = int(os.environ.get("HY4_MLA_HB_ROWS_RG", "4")) # rows per program (power of two <= 4): more rows are split over the gridHB_SPLIT = int(os.environ.get("HY4_MLA_HB_SPLIT", "0")) # key splits per (row, head group): 0 = auto (fill the GPU: ~96 programs), 1 = off, n = fixedMAX_T = 16 # rows per call handled by the attention kernel (decode / short verify); more = prefill -> torch GEMMsCLAMP_MIN = 6.103515625e-5 # the old router's `sum.clamp(min=...)`@@ -266,6 +271,68 @@ if triton is not None:tl.store(WM + wi * BH + tl.arange(0, BH), m)tl.store(WL + wi * BH + tl.arange(0, BH), l)+ @triton.jit+ def _mla_hb_rows_split_kernel(QL, QP, CK, KP, QPOS, SINK, WA, WM, WL, T, N, scale, window,+ s_ql_t, s_ql_h, s_qp_t, s_qp_h, s_ck, s_kp,+ R: tl.constexpr, P: tl.constexpr, BH: tl.constexpr, RG: tl.constexpr, BN: tl.constexpr, HAS_WIN: tl.constexpr, RING: tl.constexpr,+ S: tl.constexpr):+ """_mla_hb_split_kernel with RG query rows per program: M = RG x BH tile rows (row i = (t0 + i // BH, head h0 + i % BH)); every K tile is loaded once for all RG rows (verify rows+ read the same latent K). Row t sees keys <= qpos[t] (and the window); padded rows (t >= T) see nothing. Grid (RGroups, H / BH, S); partials land in the layout of+ _mla_hb_combine ((t, g, split) major)."""+ M: tl.constexpr = RG * BH+ rg = tl.program_id(0)+ g = tl.program_id(1)+ sp = tl.program_id(2)+ NG = tl.num_programs(1)+ i = tl.arange(0, M)+ tt = rg * RG + i // BH+ hh = g * BH + i % BH+ tok = tt < T+ offr = tl.arange(0, R)+ offp = tl.arange(0, P)+ q = tl.load(QL + tt[:, None] * s_ql_t + hh[:, None] * s_ql_h + offr[None, :], mask=tok[:, None], other=0.0).to(tl.float16)+ qp = tl.load(QP + tt[:, None] * s_qp_t + hh[:, None] * s_qp_h + offp[None, :], mask=tok[:, None], other=0.0).to(tl.float16)+ qpos = tl.load(QPOS + tt, mask=tok, other=-1)+ first = (sp == 0)+ m = tl.where(first, tl.load(SINK + hh).to(tl.float32), -1e30)+ l = tl.where(first, 1.0, 0.0) + tl.zeros([M], dtype=tl.float32)+ acc = tl.zeros([M, R], dtype=tl.float32)+ qlast = tl.load(QPOS + tl.minimum(rg * RG + RG - 1, T - 1))+ qfirst = tl.load(QPOS + rg * RG)+ lo = 0+ hi = tl.minimum(N, qlast + 1)+ if HAS_WIN:+ lo = tl.maximum(0, qfirst - window + 1) // BN * BN+ nblk = tl.maximum(0, (hi - lo + BN - 1) // BN)+ per = (nblk + S - 1) // S+ b0 = tl.minimum(nblk, sp * per)+ b1 = tl.minimum(nblk, b0 + per)+ for n0 in range(lo + b0 * BN, lo + b1 * BN, BN):+ offn = n0 + tl.arange(0, BN)+ inb = offn < N+ vis = inb[None, :] & (offn[None, :] <= qpos[:, None])+ if HAS_WIN:+ vis = vis & ((qpos[:, None] - offn[None, :]) < window)+ if RING > 0:+ offs = offn % RING+ else:+ offs = offn+ ck = tl.load(CK + offs[:, None] * s_ck + offr[None, :], mask=inb[:, None], other=0.0).to(tl.float16)+ kp = tl.load(KP + offs[:, None] * s_kp + offp[None, :], mask=inb[:, None], other=0.0).to(tl.float16)+ s = (tl.dot(q, tl.trans(ck)) + tl.dot(qp, tl.trans(kp))) * scale+ s = tl.where(vis, s, float("-inf"))+ mn = tl.maximum(m, tl.max(s, axis=1))+ alpha = tl.exp(m - mn)+ pr = tl.exp(s - mn[:, None])+ l = l * alpha + tl.sum(pr, axis=1)+ acc = acc * alpha[:, None] + tl.dot(pr.to(tl.float16), ck)+ m = mn+ wi = (tt * NG + g) * S + sp+ tl.store(WA + wi[:, None] * (BH * R) + (i % BH)[:, None] * R + offr[None, :], acc, mask=tok[:, None])+ tl.store(WM + wi * BH + i % BH, m, mask=tok)+ tl.store(WL + wi * BH + i % BH, l, mask=tok)++@triton.jitdef _mla_hb_combine(WA, WM, WL, O, s_o_t, s_o_h, R: tl.constexpr, BH: tl.constexpr, S: tl.constexpr):"""grid (T, H / BH): merge the S key-split partials (flash-decoding combine): O = sum_s e^(m_s - M) acc_s / sum_s e^(m_s - M) l_s"""@@ -306,6 +373,21 @@ def mla_sink_attend(q_lat, q_pe, ckv, k_pe, qpos, kpos, scale, sinks=None, windoout = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)ng = H // 16S = HB_SPLIT if HB_SPLIT > 0 else min(16, max(1, -(-96 // (T * ng))))+ if HB_ROWS >= 2 and 2 <= T <= HB_ROWS:+ BHr = HB_ROWS_BH+ RG = min(HB_ROWS_RG, triton.next_power_of_2(T))+ nrg = -(-T // RG)+ ngr = H // BHr+ nblk = (-(-(window + RG) // HB_ROWS_BN) + 1) if window else -(-N // HB_ROWS_BN) # key blocks one program can walk: never more splits than blocks+ S = HB_SPLIT if HB_SPLIT > 0 else min(16, max(1, -(-96 // (nrg * ngr))), max(1, nblk // 2))+ wa = torch.empty(T * ngr * S * BHr * R, dtype=torch.float32, device=q_lat.device)+ wm = torch.empty(T * ngr * S * BHr, dtype=torch.float32, device=q_lat.device)+ wl = torch.empty(T * ngr * S * BHr, dtype=torch.float32, device=q_lat.device)+ _mla_hb_rows_split_kernel[(nrg, ngr, S)](q_lat, q_pe, ckv, k_pe, qpos, sinks.float().contiguous(), wa, wm, wl, T, (1 << 30) if ring else N, float(scale), int(window),+ q_lat.stride(0), q_lat.stride(1), q_pe.stride(0), q_pe.stride(1), ckv.stride(0), k_pe.stride(0),+ R=R, P=P, BH=BHr, RG=RG, BN=HB_ROWS_BN, HAS_WIN=bool(window), RING=int(ring), S=S, num_warps=HB_ROWS_NW)+ _mla_hb_combine[(T, ngr)](wa, wm, wl, out, out.stride(0), out.stride(1), R=R, BH=BHr, S=S, num_warps=4)+ return outif S > 1:wa = torch.empty(T * ng * S * 16 * R, dtype=torch.float32, device=q_lat.device)wm = torch.empty(T * ng * S * 16, dtype=torch.float32, device=q_lat.device)diff --git a/tests/test_kv_fp8.py b/tests/test_kv_fp8.pyindex c2585d5..461ded5 100644--- a/tests/test_kv_fp8.py+++ b/tests/test_kv_fp8.py@@ -26,6 +26,16 @@ def test_roundtrip():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_dequant16_cat():+ g = torch.Generator().manual_seed(1)+ kn = torch.randn(300, 576, generator=g) * torch.logspace(-2, 3, 300)[:, None]+ kv = KV.Fp8KV(300, 512, 64, DEV); kv.write(0, kn.to(DEV))+ a = kv.dequant16_cat(chunk=128)+ lat16, pe16 = kv.dequant16()+ assert a.dtype == torch.float16 and a.shape == (300, 576)+ assert torch.equal(a[:, :512], lat16) and torch.equal(a[:, 512:], pe16)+ assert torch.equal(kv[10:200].dequant16_cat(chunk=64), a[10:200])+def test_kernel_matches_dequant():if DEV == "cpu" and os.environ.get("TRITON_INTERPRET") != "1":return@@ -46,4 +56,4 @@ def test_kernel_matches_dequant():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")+ test_dq8_matches_torch(); test_roundtrip(); test_dequant16_cat(); test_kernel_matches_dequant(); print("kv_fp8 ok")diff --git a/tools/hy4/step/ab_mla.py b/tools/hy4/step/ab_mla.pynew file mode 100644index 0000000..d0e8f3c--- /dev/null+++ b/tools/hy4/step/ab_mla.py@@ -0,0 +1,55 @@+"""ab_mla.py: ONE load (cwd = tree; HY4_KV_FP8 etc. from the job env). Graph-replay verify-step wall at T = 1..6, ctx PCTXS, levers off (A) vs on (B), ABBA, graphs re-captured at every arm+switch; logits A vs B on the same tokens (KL(A||B), top-1). Levers (env ARMB, comma list): lchb = fp8 sparse attend head-blocked + split-K (lc_sparse.HB_ON, HB_SPLIT auto),+rows = HY4_MLA_HB_ROWS rows kernel (BH 16, RG 4). ARMB empty = A vs A (reference timing of the loaded flags). env: PCTXS (1000,4000,32000), PTS (1,2,3,4,5,6)."""+import json, os, statistics, sys, time+tree = os.getcwd()+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))+import serve+ctxs = [int(x) for x in os.environ.get("PCTXS", "1000,4000,32000").split(",")]+CAP = max(ctxs) + 2048+serve.apply_env(CAP)+import torch+from engine import Hy4Engine+GGUF = os.environ.get("GGUF", "/home/kamel/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf")+e = Hy4Engine(tree, GGUF, ctx=CAP, k=3)+e.load(print)+GR = e.GR+fwm = sys.modules[type(GR.fw).__module__]+rf = fwm._rf+from exllamav3.loader import lc_sparse as LS+def lchb(on):+ LS.HB_ON, LS.HB_SPLIT = bool(on), -1+def rows(on):+ rf.HB_ROWS, rf.HB_ROWS_BH, rf.HB_ROWS_RG, rf.HB_ROWS_NW = (8, 16, 4, 8) if on else (0, 16, 4, 8)+LEV = {"lchb": lchb, "rows": rows}+FL = [x for x in os.environ.get("ARMB", "lchb").split(",") if x]+def arm(fl):+ for k, f in LEV.items():+ f(k in fl)+ GR.clear()+wiki = json.load(open(os.environ.get("WIKI", "/home/kamel/scratch_w5/wiki_ids.json")))+pc, sync = time.perf_counter, torch.cuda.synchronize+print("ARMB", FL, "KV_FP8", os.environ.get("HY4_KV_FP8"), "LC_SPARSE", LS.ENABLED, "HB", rf.HB, flush=True)+Ts = [int(x) for x in os.environ.get("PTS", "1,2,3,4,5,6").split(",")]+res, logit = {}, {}+for ctxn in ctxs:+ e._t0 = pc(); e.reset(); e.prefill(wiki[:ctxn]); e.phase("decode")+ for a_ in ("A", "B", "B", "A"):+ arm(FL if a_ == "B" else [])+ for T in Ts:+ toks = wiki[ctxn:ctxn + T]+ for _ in range(3):+ GR.step_rows(toks); sync(); GR.rewind(ctxn)+ ts = []+ for _ in range(20):+ t = pc(); out = GR.step_rows(toks); sync(); ts.append((pc() - t) * 1000); GR.rewind(ctxn)+ res.setdefault((ctxn, T, a_), []).append(statistics.median(ts))+ if (ctxn, T, a_) not in logit:+ logit[(ctxn, T, a_)] = out[0].float().reshape(T, -1).clone()+ for T in Ts:+ a, b = res[(ctxn, T, "A")], res[(ctxn, T, "B")]+ la, lb = logit[(ctxn, T, "A")].log_softmax(-1), logit[(ctxn, T, "B")].log_softmax(-1)+ kl = (la.exp() * (la - lb)).sum(-1)+ agree = (la.argmax(-1) == lb.argmax(-1)).float().mean().item()+ print(f"AB ctx {ctxn} T {T}: A {a} B {b} ms delta {statistics.mean(b) - statistics.mean(a):+.2f} ms KL_mean {kl.mean().item():.2e} KL_max {kl.max().item():.2e} top1_agree {agree:.2f}", flush=True)+print("ABMLA_DONE", flush=True)diff --git a/tools/hy4/step/mla_micro.py b/tools/hy4/step/mla_micro.pynew file mode 100644index 0000000..291469f--- /dev/null+++ b/tools/hy4/step/mla_micro.py@@ -0,0 +1,135 @@+"""mla_micro.py (cwd = tree): MODEL-FREE micro A/B of the shipped Hy4 decode attention of the full-attention (indexer) layers (HY4_LC_SPARSE: lc_sparse.sparse_mla_attend):+H = 32 heads, R 512, P 64, rows T = 1..6, context N = 4K / 32K, selection like the indexer (512 groups of 4 keys per row, rows overlap ~90 %, + the open tail group).+Arms: f32 = fp32 K cache, q8 = fp8 cache with the one-head kernel (shipped HY4_KV_FP8), q8hb = fp8 cache head-blocked (HY4_LC_HB=1), plus any arm added below.+NL distinct layer caches are cycled (one cache re-read in a loop would sit in the 32 MB MALL). Prints ms per call and ms per verify round (x NL_ROUND layers) and the+max |diff| of every arm against dq32 (q8 must be 0.0: same dequantised values).+env: MLA_CPU=1 (TRITON_INTERPRET, tiny shapes, correctness only), MLA_NL (default 12), MLA_NS ("1000,4000,32000"), MLA_TS ("1,2,3,4,6"), MLA_ARMS ("f32,dq32,q8"), HY4_MLA_HB (shipped serve flag)."""+import os, sys, time+CPU = os.environ.get("MLA_CPU") == "1"+if CPU:+ os.environ["TRITON_INTERPRET"] = "1"+os.environ.setdefault("HY4_REF_FUSED", "1")+tree = os.getcwd()+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))+import torch+import engine as _eng+_eng._stub_package(tree)+from exllamav3.loader import ref_fused as rf, kv_fp8 as kv8, lc_sparse as LS+dev = torch.device("cpu" if CPU else "cuda")+R, P, H = 512, 64, 32+NL = 2 if CPU else int(os.environ.get("MLA_NL", "12"))+NS = [256] if CPU else [int(x) for x in os.environ.get("MLA_NS", "4000,32000").split(",")]+TS = [1, 3] if CPU else [int(x) for x in os.environ.get("MLA_TS", "1,2,3,4,6").split(",")]+ARMS = os.environ.get("MLA_ARMS", "f32,q8,q8hb,q8hbs2,q8hbs4,q8hbs8,q8hbs16").split(",")+LAYERS_PER_ROUND = 12+TOPK, KP = (64 if CPU else 2048), 4+torch.manual_seed(0)+++def ev(fn, n=20):+ if CPU:+ fn(); return 0.0+ for _ in range(2):+ fn()+ torch.cuda.synchronize()+ a, b = torch.cuda.Event(enable_timing=True), torch.cuda.Event(enable_timing=True)+ a.record()+ for _ in range(n):+ fn()+ b.record(); torch.cuda.synchronize()+ return a.elapsed_time(b) / n+++def make_sel(T, N, qpos):+ """SparseSel: per row n_top groups (rows share ~90 % of them), nsel all valid (groups below the open tail group)"""+ nt = TOPK // KP - 1+ base = torch.randperm(max(1, N // KP - 2), device=dev)[:nt]+ idx = torch.empty(T, TOPK // KP - 1, dtype=torch.int32, device=dev)+ for t in range(T):+ r = base.clone()+ k = nt // 10+ r[torch.randperm(nt, device=dev)[:k]] = torch.randint(0, max(1, int(qpos[t].item()) // KP - 1), (k,), device=dev)+ idx[t] = r.int()+ nsel = torch.full((T,), nt, dtype=torch.int32, device=dev)+ return LS.SparseSel(idx, nsel, KP, True)+++for N in NS:+ cap = N + 64+ caches = []+ for _ in range(NL):+ k = torch.randn(cap, R + P, device=dev) * 1.5+ f = kv8.Fp8KV(cap, R, P, dev)+ f.write(0, k)+ caches.append((k, f))+ sinks = torch.randn(H, device=dev)+ scale = (R + P) ** -0.5 * 1.7+ for T in TS:+ qpos = torch.arange(N - T, N, device=dev)+ q = torch.randn(T, H, R, device=dev) * 0.5+ qp = torch.randn(T, H, P, device=dev) * 0.5+ sel = make_sel(T, N, qpos)++ def run(arm, i):+ k, f = caches[i % NL]+ if arm == "f32":+ return LS.sparse_mla_attend(q, qp, k[:, :R], k[:, R:], qpos, sel, scale, sinks)+ LS.HB_ON = arm.startswith("q8hb")+ LS.HB_SPLIT = int(arm[5:]) if arm.startswith("q8hbs") else 0+ return LS.sparse_mla_attend(q, qp, f.lat, f.pe, qpos, sel, scale, sinks, scl=f.sc)++ ref = run("q8", 0)+ row = []+ for arm in ARMS:+ o = run(arm, 0)+ d = (o - ref).abs().max().item()+ cnt = [0]++ def f():+ run(arm, cnt[0]); cnt[0] += 1+ ms = ev(f)+ row.append(f"{arm} {ms:.3f} ms/layer ({ms * LAYERS_PER_ROUND:.2f}/round, maxdiff vs q8 {d:.1e})")+ print(f"N {N} T {T}: " + " | ".join(row), flush=True)+ del caches+++# ---- decode attention of the layers below the sparse threshold (allow None, HY4_MLA_HB kernels): shipped split kernel vs the rows kernel (HY4_MLA_HB_ROWS)+rf.HB = True+if os.environ.get("MLA_ROWS", "1") == "1":+ RARMS = os.environ.get("MLA_RARMS", "hb,r8x4,r8x2,r16x4,r16x2,r8x4n4").split(",")+ for (Hh, win, Nn) in ((64, int(os.environ.get("MLA_WIN", "128")), 1000), (32, 0, 1000), (32, 0, 2000)):+ cap = Nn + 64+ kc = [torch.randn(cap, R + P, device=dev) * 1.5 for _ in range(NL)]+ sinks = torch.randn(Hh, device=dev)+ kpos = torch.arange(cap, device=dev)+ for T in [t for t in TS if t >= 1]:+ qpos = torch.arange(Nn - T, Nn, device=dev)+ q = torch.randn(T, Hh, R, device=dev) * 0.5+ qp = torch.randn(T, Hh, P, device=dev) * 0.5+ scale = (R + P) ** -0.5 * 1.7++ def runr(arm, i):+ k = kc[i % NL]+ rf.HB_ROWS, rf.HB_ROWS_NW = 0, 4+ if arm != "hb": # rNxM[nW]: BH = N heads, RG = M rows per program, nW num_warps+ bh, rg = arm[1:].split("x")+ nw = 8+ if "n" in rg:+ rg, nw = rg.split("n")+ rf.HB_ROWS, rf.HB_ROWS_BH, rf.HB_ROWS_RG, rf.HB_ROWS_NW = 8, int(bh), int(rg), int(nw)+ return rf.mla_sink_attend(q, qp, k[:, :R], k[:, R:], qpos, kpos, scale, sinks, win, None, kpos_is_arange=True)++ ref = runr("hb", 0)+ row = []+ for arm in RARMS:+ if T == 1 and arm != "hb":+ continue+ o = runr(arm, 0)+ d = (o - ref).abs().max().item()+ cnt = [0]++ def f():+ runr(arm, cnt[0]); cnt[0] += 1+ ms = ev(f)+ row.append(f"{arm} {ms * 1000:.0f}us (diff {d:.1e})")+ print(f"ROWS H {Hh} win {win} N {Nn} T {T}: " + " | ".join(row), flush=True)