Skip to content

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.

Hy4 prefill: int8 grouped MoE kernels (Q8_K activations, behind HY4_PREFILL_MOE=i8), Q8_0 dequant + vendor fp16 GEMM for large dense rows, router fp16 option, per-window banded attention configs, fine timers and diagnostics (all flags default off)

YanissAmzb60f79ddb217
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 6429a74..f8de453 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -116,10 +116,13 @@ GG_GROUPED = {12: (0, 256, 144), 13: (1, 256, 176), 14: (2, 256, 210), 23: (3, 2
GROUPED_UG = (0, 1, 2, 3, 4, 5, 8)
EXPERT_PREAD = os.environ.get("HY4_EXPERT_PREAD", "0") == "1" # 1 = old path: experts pread from the GGUF every step ((1a) mmvq)
RESIDENT_GB = float(os.environ.get("HY4_EXPERT_RESIDENT_GB", "72")) # VRAM byte budget for resident routed experts (stored bytes)
-PF_MOE = os.environ.get("HY4_PREFILL_MOE", "0") in ("1", "ref") # 1 = prefill rows (T > MMVQ_MAXR) of resident experts: sorted-token fused dequant GEMM (prefill_kernels.py)
+PF_MOE = os.environ.get("HY4_PREFILL_MOE", "0") in ("1", "i8", "ref") # 1 = prefill rows (T > MMVQ_MAXR) of resident experts: sorted-token fused dequant GEMM (prefill_kernels.py)
+PF_MOE_I8 = os.environ.get("HY4_PREFILL_MOE", "0") == "i8" # i8 = Q8_K activations on int8 WMMA (llama.cpp mmq style)
PF_MOE_REF = os.environ.get("HY4_PREFILL_MOE", "0") == "ref" # ref = exact fp32 torch math on batched-dequantised resident experts (quality reference, same maths as the pread path)
PF_DENSE = os.environ.get("HY4_PREFILL_DENSE", "0") in ("1", "i8") # 1 = prefill rows of stored Q8_0 dense matrices: fused dequant fp16 GEMM; i8 = Q8 activations on int8 WMMA (prefill_kernels.py)
PF_DENSE_I8 = os.environ.get("HY4_PREFILL_DENSE", "0") == "i8"
+PF_DIAG = os.environ.get("HY4_PREFILL_DIAG", "0") == "1" # log fast-path vs exact error of every prefill dense matmul (debug)
+PF_ROUTER = os.environ.get("HY4_PREFILL_ROUTER", "0") == "1" # 1 = router logits of prefill rows as an fp16 GEMM (fp32 accumulate): fp32 matmul runs at 2.7 TFLOPS here
def _pk():
@@ -238,7 +241,15 @@ class QLinear:
if self.stats is not None:
self.stats["dense_gemv"] = self.stats.get("dense_gemv", 0) + 1
elif PF_DENSE and self.ty == 8 and x2.is_cuda:
- out = _pk().qdense_i8(x2, self.packed) if PF_DENSE_I8 else _pk().qdense(x2, self.packed, _pk().FMT_Q8)
+ k_ = _pk()
+ out = k_.qdense_i8(x2, self.packed) if PF_DENSE_I8 else (k_.qdense_tm(x2, self.packed) if x2.shape[0] >= k_.DENSE_TM_MIN_M else k_.qdense(x2, self.packed, k_.FMT_Q8))
+ if PF_DIAG:
+ ex = x2.float() @ self.dense().T
+ df = out.float() - ex
+ rr = df.norm(dim=1) / ex.norm(dim=1).clamp_min(1e-30)
+ w_ = int(rr.argmax())
+ print(f"DIAG dense N={N} K={K} M={x2.shape[0]} rel={float(df.norm() / ex.norm()):.2e} worst_row={w_} {float(rr[w_]):.2e} row0={float(rr[0]):.2e} max|x|={float(x2.abs().max()):.3e} "
+ f"clamped_in={int((x2.abs() > 65504).sum())} max|out|={float(ex.abs().max()):.3e} out_over={int((ex.abs() > 65504).sum())}", flush=True)
if self.stats is not None:
self.stats["dense_pf"] = self.stats.get("dense_pf", 0) + 1
else:
@@ -504,7 +515,12 @@ class Hy4Forward:
sel, w = _rf.router_select(x @ L.router.T, L.rbias, self.topk, self.w_scale)
sel_l = [] if (pf or (self.res.get(i) is not None and T <= MMVQ_MAXR and dev.type == "cuda")) else sorted(set(sel.flatten().tolist()))
else:
- p = torch.sigmoid(x @ L.router.T)
+ if PF_ROUTER and T > MMVQ_MAXR and dev.type == "cuda":
+ if getattr(L, "router16", None) is None:
+ L.router16 = L.router.half().contiguous()
+ p = torch.sigmoid(_pk().mm_f32(_pk().to_f16(x), L.router16.T))
+ else:
+ p = torch.sigmoid(x @ L.router.T)
sel = torch.topk(p + L.rbias, self.topk, dim=-1).indices
w = torch.gather(p, 1, sel)
w = w / w.sum(-1, keepdim=True).clamp(min=6.103515625e-5) * self.w_scale
@@ -521,7 +537,7 @@ class Hy4Forward:
elif pf:
with tm.t("routed experts"):
k_ = _pk()
- lat = k_.moe_prefill(z, sel, w, (rsp.bufs["gate"], rsp.bufs["up"], rsp.bufs["down"]), (k_.FROM_GROUPED[rsp.fu], k_.FROM_GROUPED[rsp.fd]), lim,
+ lat = (k_.moe_prefill_i8 if PF_MOE_I8 else k_.moe_prefill)(z, sel, w, (rsp.bufs["gate"], rsp.bufs["up"], rsp.bufs["down"]), (k_.FROM_GROUPED[rsp.fu], k_.FROM_GROUPED[rsp.fd]), lim,
rsp.nff, rsp.nout, (rsp.strides[0], rsp.strides[2]), rsp.ebytes, rsp.E)
self.stats["prefill_moe_calls"] = self.stats.get("prefill_moe_calls", 0) + 1
sel_l = []
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index 95ed087..33d1b2e 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -93,21 +93,31 @@ class Hy4MLA:
def kv(self, cur, pos):
"""cur [T, n_embd], pos [T] -> K cache rows [T, R + rope] = [rms(kv_a)*w | rope(k_pe)] (V is the first R columns)"""
- c = self._q(cur, "wkv_a") @ self.wkv_a.T
- lat = rms(c[:, :self.R], self.eps) * self.kv_a_norm
- pe = rope_norm(c[:, self.R:], pos, self.theta)
- return self._h(torch.cat([lat, pe], -1))
+ tm = self.tm
+ with tm.t("f kv: wkv_a mm"):
+ c = self._q(cur, "wkv_a") @ self.wkv_a.T
+ with tm.t("f kv: norm+rope"):
+ lat = rms(c[:, :self.R], self.eps) * self.kv_a_norm
+ pe = rope_norm(c[:, self.R:], pos, self.theta)
+ return self._h(torch.cat([lat, pe], -1))
def q(self, cur, pos):
"""-> q_lat [T,H,R], q_pe [T,H,rope] (q_nope absorbed with k_b; rope on the pe part)"""
T, H = cur.shape[0], self.H
- qr = rms(self._q(cur, "wq_a") @ self.wq_a.T, self.eps) * self.q_a_norm
- q = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)
- qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)
- if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda: # prefill rows: fp16 batched GEMM over heads (fp32 einsum is ~3x slower)
- qlat = torch.bmm(self._w16("wk_b"), self._f16(qn).permute(1, 2, 0)).permute(2, 0, 1).float()
- else:
- qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))
+ tm = self.tm
+ with tm.t("f q: wq_a mm"):
+ qa = self._q(cur, "wq_a") @ self.wq_a.T
+ with tm.t("f q: norm"):
+ qr = rms(qa, self.eps) * self.q_a_norm
+ with tm.t("f q: wq_b mm"):
+ q = (self._q(qr, "wq_b") @ self.wq_b.T).view(T, H, self.hd)
+ with tm.t("f q: rope"):
+ qn, qp = q[..., :self.nope], rope_norm(q[..., self.nope:].contiguous(), pos, self.theta)
+ with tm.t("f q: wk_b bmm"):
+ if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda: # prefill rows: fp16 batched GEMM over heads (fp32 einsum is ~3x slower)
+ qlat = torch.bmm(self._w16("wk_b"), self._f16(qn).permute(1, 2, 0)).permute(2, 0, 1).float()
+ else:
+ qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))
return self._h(qlat, "q"), self._h(qp, "q")
def attend(self, cur, pos, kcache, kpos, allow=None):
@@ -126,18 +136,23 @@ class Hy4MLA:
else:
o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window, allow)
with tm.t("attn proj"):
- if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda:
- kqv = torch.bmm(self._w16("wv_b"), self._f16(o).permute(1, 2, 0)).permute(2, 0, 1).float().reshape(T, H * self.vd)
- else:
- kqv = torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb")).reshape(T, H * self.vd)
+ with tm.t("f attend: wv_b bmm"):
+ if PF_ATTN and T > PF_ATTN_MIN and cur.is_cuda:
+ kqv = torch.bmm(self._w16("wv_b"), self._f16(o).permute(1, 2, 0)).permute(2, 0, 1).float().reshape(T, H * self.vd)
+ else:
+ kqv = torch.einsum("hdr,thr->thd", self.wv_b, self._q(o, "vb")).reshape(T, H * self.vd)
gated, out = self.gate_out(cur, kqv)
return kqv, gated, out
def gate_out(self, cur, kqv):
"""isolated tail (gate, then wo, then post norm): oracle attn_kqv + cur -> (gated, out)"""
- gated = self.S.sigmoid_gate(kqv, self._q(cur, "wgate") @ self.wgate.T)
- out = self._q(gated, "wo") @ self.wo.T
- return gated, (rms(out, self.eps) * self.post_norm if self.post_norm is not None else out)
+ tm = self.tm
+ with tm.t("f gate: wgate mm + sigmoid"):
+ gated = self.S.sigmoid_gate(kqv, self._q(cur, "wgate") @ self.wgate.T)
+ with tm.t("f gate: wo mm"):
+ out = self._q(gated, "wo") @ self.wo.T
+ with tm.t("f gate: post norm"):
+ return gated, (rms(out, self.eps) * self.post_norm if self.post_norm is not None else out)
POST_NORM = "post_attention_norm.weight"
diff --git a/exllamav3/loader/prefill_attn.py b/exllamav3/loader/prefill_attn.py
index 30975a9..46a7a48 100644
--- a/exllamav3/loader/prefill_attn.py
+++ b/exllamav3/loader/prefill_attn.py
@@ -180,9 +180,14 @@ def _pv_kernel(Pm, V, O, M, NK, NKP, row0, klo, kbase, D: tl.constexpr, R: tl.co
BCFG = {"BM": 128, "BN": 128, "BK": 32, "warps": 8, "PBN": 128, "PBK": 32, "pwarps": 8, "S_BYTES": 48 << 20}
+# measured (test_pf2, 2048 queries): sliding window H=64 best 7.9 TFLOPS at S=8 MiB; full + allow mask H=32 best 17.7 at S=16 MiB with a 64-wide key tile
+BCFG_SWA = dict(BCFG, S_BYTES=8 << 20)
+BCFG_FULL = dict(BCFG, S_BYTES=16 << 20, BN=64, PBK=64)
+
+
def mla_banded(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None, cfg=None):
"""same contract as mla_flash: q_lat [T, H, R], q_pe [T, H, P], kc [N, R + P] (N = qstart + T) -> o_lat [T, H, R] fp32"""
- c = cfg or BCFG
+ c = cfg or (BCFG_SWA if window else BCFG_FULL)
T, H, R = q_lat.shape
Pd = q_pe.shape[-1]
D = R + Pd
diff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.py
index d6ea9af..255ba85 100644
--- a/exllamav3/loader/prefill_kernels.py
+++ b/exllamav3/loader/prefill_kernels.py
@@ -187,17 +187,181 @@ def _dense_i8_kernel(XQ, XD, W, Out, M, N, K: tl.constexpr, ROWB: tl.constexpr,
tl.store(Out + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], acc, mask=mm[:, None] & nm[None, :])
+# ------------------------------------------------------------------------------------------------ int8 grouped MoE (llama.cpp mmq style: Q8_K activations)
+def _quant_k_kernel(X, XQ, XD, XS, M, K, BM: tl.constexpr):
+ """Q8_K-like activation quantisation: per row and 256-block d = amax / 127, q = round(x / d); also the int sum of q per 32-block (the mins term of Q4_K)"""
+ pid_m = tl.program_id(0)
+ kb = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ c = tl.arange(0, 256)
+ mm = offs_m < M
+ rows = offs_m.to(tl.int64)
+ x = tl.load(X + rows[:, None] * K + kb * 256 + c[None, :], mask=mm[:, None], other=0.0).to(tl.float32)
+ amax = tl.max(tl.abs(x), 1)
+ d = amax / 127.0
+ inv = tl.where(d > 0.0, 1.0 / d, 0.0)
+ v = x * inv[:, None]
+ q = tl.where(v >= 0.0, v + 0.5, v - 0.5).to(tl.int8)
+ tl.store(XQ + rows[:, None] * K + kb * 256 + c[None, :], q, mask=mm[:, None])
+ tl.store(XD + rows * (K // 256) + kb, d, mask=mm)
+ qs = tl.sum(tl.reshape(q.to(tl.int32), (BM, 8, 32)), 2)
+ s8 = tl.arange(0, 8)
+ tl.store(XS + rows[:, None] * (K // 32) + kb * 8 + s8[None, :], qs, mask=mm[:, None])
+
+
+def _quant_h_kernel(G, U, XQ, XD, XS, M, K, BM: tl.constexpr):
+ """h = silu(g) * u (g, u fp16, already clamped) then the same Q8_K quantisation: the down-projection input without a separate h tensor"""
+ pid_m = tl.program_id(0)
+ kb = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ c = tl.arange(0, 256)
+ mm = offs_m < M
+ rows = offs_m.to(tl.int64)
+ ptr = rows[:, None] * K + kb * 256 + c[None, :]
+ g = tl.load(G + ptr, mask=mm[:, None], other=0.0).to(tl.float32)
+ u = tl.load(U + ptr, mask=mm[:, None], other=0.0).to(tl.float32)
+ x = g / (1.0 + tl.exp(-g)) * u
+ amax = tl.max(tl.abs(x), 1)
+ d = amax / 127.0
+ inv = tl.where(d > 0.0, 1.0 / d, 0.0)
+ v = x * inv[:, None]
+ q = tl.where(v >= 0.0, v + 0.5, v - 0.5).to(tl.int8)
+ tl.store(XQ + ptr, q, mask=mm[:, None])
+ tl.store(XD + rows * (K // 256) + kb, d, mask=mm)
+ qs = tl.sum(tl.reshape(q.to(tl.int32), (BM, 8, 32)), 2)
+ s8 = tl.arange(0, 8)
+ tl.store(XS + rows[:, None] * (K // 32) + kb * 8 + s8[None, :], qs, mask=mm[:, None])
+
+
+def _w4_i8(W, wrow, kb, s, BN: tl.constexpr):
+ """Q4_K sub-block s of superblock kb: nibbles as int8 [BN, 32] (0..15), scale / min as int32 [BN]"""
+ lane = tl.arange(0, 32)
+ blk = wrow + kb * 144
+ j = s % 4
+ x0 = _b(W, blk + 4 + j)
+ x4 = _b(W, blk + 8 + j)
+ x8 = _b(W, blk + 12 + j)
+ hi = s >= 4
+ sc = tl.where(hi, (x8 & 15) | ((x0 >> 6) << 4), x0 & 63)
+ mn = tl.where(hi, (x8 >> 4) | ((x4 >> 6) << 4), x4 & 63)
+ qs = tl.load(W + blk[:, None] + (16 + (s // 2) * 32) + lane[None, :]).to(tl.int32)
+ wq = ((qs >> ((s % 2) * 4)) & 15).to(tl.int8)
+ return wq, sc, mn
+
+
+def _w3_i8(W, wrow, kb, s, BN: tl.constexpr):
+ """Q3_K sub-block s of superblock kb: int8 [BN, 32] = (q - 4 (1 - hb)) * scale (scale folded in; |value| <= 128 is clamped to 127)"""
+ lane = tl.arange(0, 32)
+ blk = wrow + kb * 110
+ half = s // 4
+ j = s % 4
+ mA = 2 * s
+ mB = 2 * s + 1
+ lA = (_b(W, blk + 96 + (mA & 7)) >> (4 * (mA >> 3))) & 15
+ hA = (_b(W, blk + 104 + (mA & 3)) >> (2 * (mA >> 2))) & 3
+ lB = (_b(W, blk + 96 + (mB & 7)) >> (4 * (mB >> 3))) & 15
+ hB = (_b(W, blk + 104 + (mB & 3)) >> (2 * (mB >> 2))) & 3
+ scA = (lA | (hA << 4)) - 32
+ scB = (lB | (hB << 4)) - 32
+ sc = tl.where(lane[None, :] < 16, scA[:, None], scB[:, None])
+ qs = tl.load(W + blk[:, None] + (32 + half * 32) + lane[None, :]).to(tl.int32)
+ hm = tl.load(W + blk[:, None] + lane[None, :]).to(tl.int32)
+ qv = ((qs >> (2 * j)) & 3) + 4 * ((hm >> s) & 1) - 4
+ return tl.minimum(tl.maximum(qv * sc, -127), 127).to(tl.int8)
+
+
+def _gmm_i8_kernel(XQ, XD, XS, W, OUT, wts, sorted_pairs, block_expert, P, topk, E, ebytes, lim,
+ K: tl.constexpr, N: tl.constexpr, ROWB: tl.constexpr, FMT: tl.constexpr, MODE: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr):
+ """grouped (sorted-token) int8 GEMM over one stored expert tensor. MODE 0: gate (x row = pair // topk, min(acc, lim) -> fp16 at the padded row),
+ 1: up (clamp +-lim -> fp16), 2: down (x row = padded row, acc * wts[pair] -> fp32 at row `pair`)."""
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ e = tl.load(block_expert + pid_m)
+ if e < E:
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ pair = tl.load(sorted_pairs + offs_m)
+ valid = pair < P
+ if MODE == 2:
+ xr = offs_m.to(tl.int64)
+ else:
+ xr = (pair // topk).to(tl.int64)
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ wrow = e.to(tl.int64) * ebytes + offs_n.to(tl.int64) * ROWB
+ lane = tl.arange(0, 32)
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for kb in range(0, K // 256):
+ acc_i = tl.zeros((BM, BN), dtype=tl.int32)
+ if FMT == 0:
+ mn_i = tl.zeros((BM, BN), dtype=tl.int32)
+ for s in range(0, 8):
+ xq = tl.load(XQ + xr[:, None] * K + (kb * 8 + s) * 32 + lane[None, :], mask=valid[:, None], other=0)
+ if FMT == 0:
+ wq, sc, mn = _w4_i8(W, wrow, kb, s, BN)
+ ai = tl.dot(xq, tl.trans(wq), out_dtype=tl.int32)
+ acc_i += ai * sc[None, :]
+ xs = tl.load(XS + xr * (K // 32) + kb * 8 + s, mask=valid, other=0)
+ mn_i += xs[:, None] * mn[None, :]
+ else:
+ wq = _w3_i8(W, wrow, kb, s, BN)
+ acc_i = tl.dot(xq, tl.trans(wq), acc_i, out_dtype=tl.int32)
+ dx = tl.load(XD + xr * (K // 256) + kb, mask=valid, other=0.0)
+ if FMT == 0:
+ d = _f16(W, wrow + kb * 144)
+ dm = _f16(W, wrow + kb * 144 + 2)
+ acc += dx[:, None] * (d[None, :] * acc_i.to(tl.float32) - dm[None, :] * mn_i.to(tl.float32))
+ else:
+ d = _f16(W, wrow + kb * 110 + 108)
+ acc += dx[:, None] * d[None, :] * acc_i.to(tl.float32)
+ if MODE == 0:
+ tl.store(OUT + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], tl.minimum(acc, lim).to(tl.float16))
+ elif MODE == 1:
+ tl.store(OUT + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], tl.minimum(tl.maximum(acc, -lim), lim).to(tl.float16))
+ else:
+ w = tl.load(wts + pair, mask=valid, other=0.0)
+ tl.store(OUT + pair[:, None].to(tl.int64) * N + offs_n[None, :], acc * w[:, None], mask=valid[:, None])
+
+
+def _deq_q8_kernel(W, OUT, N, K: tl.constexpr, ROWB: tl.constexpr, BN: tl.constexpr, SPP: tl.constexpr):
+ """stored Q8_0 [N, K/32, 34] -> fp16 [N, K]; one program = BN rows x SPP sub-blocks"""
+ pid_n = tl.program_id(0)
+ pid_k = tl.program_id(1)
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ nm = offs_n < N
+ wrow = tl.where(nm, offs_n, 0).to(tl.int64) * ROWB
+ lane = tl.arange(0, 32)
+ for i in range(0, SPP):
+ sb = pid_k * SPP + i
+ w = _wtile(W, wrow, sb, 2, BN)
+ tl.store(OUT + offs_n.to(tl.int64)[:, None] * K + sb * 32 + lane[None, :], w, mask=nm[:, None])
+
+
# ------------------------------------------------------------------------------------------------ host side
F16MAX = 65504.0
def to_f16(x):
"""saturating fp32 / fp16 -> fp16 (hidden streams keep the clamp)"""
- return x.float().clamp_(-F16MAX, F16MAX).half() if x.dtype != torch.float16 else x
+ return x.float().clamp(-F16MAX, F16MAX).half() if x.dtype != torch.float16 else x
+
+
+MOE_CFG = None # None = chosen from the rows per expert (see moe_cfg)
+DENSE_CFG = {"BM": 128, "BN": 128, "warps": 8, "stages": 1}
-MOE_CFG = {"BM": 64, "BN": 64, "warps": 4, "stages": 1}
-DENSE_CFG = {"BM": 64, "BN": 64, "warps": 4, "stages": 1}
+def moe_cfg(T, S, E):
+ """tile rows follow the expected rows per expert (tokens * topk / experts): a 128-row tile on 64 rows wastes half the MMA work"""
+ r = T * S / max(E, 1)
+ if r >= 96:
+ return {"BM": 128, "BN": 64, "warps": 8, "stages": 1}
+ if r >= 40:
+ return {"BM": 64, "BN": 64, "warps": 4, "stages": 1}
+ return {"BM": 32, "BN": 64, "warps": 4, "stages": 1}
def route_blocks(sel, E, BM):
@@ -225,9 +389,9 @@ def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None
bufs = (gate, up, down) raw uint8 expert buffers (expert-major, row-major, stored blocks), fmts = (fmt gate/up, fmt down) as FMT ids,
rowb = (row bytes gate/up, row bytes down), ebytes = (bytes per expert gate/up, down), nff = rows of gate / up (= K of down), nout = rows of down.
Returns sum_k w[t, k] * down_e(silu(min(gate_e z, lim)) * clamp(up_e z, +-lim)) as fp32 [T, nout]."""
- c = cfg or MOE_CFG
- BM, BN = c["BM"], c["BN"]
T, S = sel.shape
+ c = cfg or MOE_CFG or moe_cfg(T, S, E)
+ BM, BN = c["BM"], c["BN"]
P = T * S
K = z.shape[1]
sp, be, maxb = route_blocks(sel.to(torch.int64), E, BM)
@@ -270,3 +434,71 @@ def qdense_i8(x, packed, cfg=None):
_dense_i8_kernel[(triton.cdiv(M, c["BM"]), triton.cdiv(N, c["BN"]))](xq, xd, packed, out, M, N, K=K, ROWB=nb * bb, BM=c["BM"], BN=c["BN"],
num_warps=c["warps"], num_stages=c["stages"])
return out.reshape(*lead, N)
+
+
+I8_CFG = {"BM": 64, "BN": 64, "warps": 8, "stages": 1}
+
+
+def quant_k(x):
+ """x [M, K] -> (q int8 [M, K], d fp32 [M, K/256], sums int32 [M, K/32]); K a multiple of 256"""
+ M, K = x.shape
+ x = x.contiguous()
+ q = torch.empty(M, K, dtype=torch.int8, device=x.device)
+ d = torch.empty(M, K // 256, dtype=torch.float32, device=x.device)
+ s = torch.empty(M, K // 32, dtype=torch.int32, device=x.device)
+ _quant_k_kernel[(triton.cdiv(M, 8), K // 256)](x, q, d, s, M, K, BM=8, num_warps=4)
+ return q, d, s
+
+
+def moe_prefill_i8(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None):
+ """same contract as moe_prefill; activations quantised to Q8_K (llama.cpp's vec_dot_type for k-quants), int8 WMMA, scales applied per superblock"""
+ T, S = sel.shape
+ c = cfg or I8_CFG
+ BM, BN = c["BM"], c["BN"]
+ P = T * S
+ K = z.shape[1]
+ sp, be, maxb = route_blocks(sel.to(torch.int64), E, BM)
+ zq, zd, zs = quant_k(z.float())
+ rows = maxb * BM
+ G = torch.empty(rows, nff, dtype=torch.float16, device=z.device)
+ U = torch.empty(rows, nff, dtype=torch.float16, device=z.device)
+ kw = dict(num_warps=c["warps"], num_stages=c["stages"])
+ _gmm_i8_kernel[(maxb, nff // BN)](zq, zd, zs, bufs[0], G, G, sp, be, P, S, E, ebytes[0], float(lim), K=K, N=nff, ROWB=rowb[0], FMT=fmts[0], MODE=0, BM=BM, BN=BN, **kw)
+ _gmm_i8_kernel[(maxb, nff // BN)](zq, zd, zs, bufs[1], U, U, sp, be, P, S, E, ebytes[0], float(lim), K=K, N=nff, ROWB=rowb[0], FMT=fmts[0], MODE=1, BM=BM, BN=BN, **kw)
+ hq = torch.empty(rows, nff, dtype=torch.int8, device=z.device)
+ hd = torch.empty(rows, nff // 256, dtype=torch.float32, device=z.device)
+ hs = torch.empty(rows, nff // 32, dtype=torch.int32, device=z.device)
+ _quant_h_kernel[(triton.cdiv(rows, 8), nff // 256)](G, U, hq, hd, hs, rows, nff, BM=8, num_warps=4)
+ out = torch.empty(P, nout, dtype=torch.float32, device=z.device)
+ _gmm_i8_kernel[(maxb, nout // BN)](hq, hd, hs, bufs[2], out, w.reshape(-1).float().contiguous(), sp, be, P, S, E, ebytes[1], float(lim), K=nff, N=nout, ROWB=rowb[1],
+ FMT=fmts[1], MODE=2, BM=BM, BN=BN, **kw)
+ return out.view(T, S, nout).sum(1)
+
+
+DENSE_TM_MIN_M = 1024 # rows from which dequantise-to-fp16 + vendor GEMM beats the fused kernel (the dequant pass is ~1 % of the GEMM at M = 8192)
+
+
+def mm_f32(a, b):
+ """a [M, K] fp16 @ b [K, N] fp16 -> fp32 [M, N]. fp16 GEMM output (fp32 accumulation inside) upcast with the saturating clamp: the out_dtype=float32
+ variant of torch.mm falls off the fast kernel on this box (measured: attention projections 1.7 TFLOPS instead of 15-35)."""
+ return torch.nan_to_num(torch.mm(a, b).float(), nan=0.0, posinf=F16MAX, neginf=-F16MAX)
+
+
+def dequant_q8(packed):
+ """stored Q8_0 [N, K/32, 34] uint8 -> fp16 [N, K]"""
+ N, nb, bb = packed.shape
+ K = nb * 32
+ out = torch.empty(N, K, dtype=torch.float16, device=packed.device)
+ spp = 8 if nb % 8 == 0 else 1
+ _deq_q8_kernel[(triton.cdiv(N, 64), nb // spp)](packed, out, N, K=K, ROWB=nb * bb, BN=64, SPP=spp, num_warps=4)
+ return out
+
+
+def qdense_tm(x, packed):
+ """x [.., K] -> [.., N] fp32 = x @ W.T: dequantise the stored Q8_0 weight to fp16 once per call, then the vendor fp16 GEMM"""
+ N, nb, bb = packed.shape
+ K = nb * 32
+ lead = x.shape[:-1]
+ x2 = to_f16(x.reshape(-1, K)).contiguous()
+ out = mm_f32(x2, dequant_q8(packed).T)
+ return out.reshape(*lead, N)