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 prefill: HY4_PF_F16=1 fp16 attention chain end to end (per-head q / o layout feeding the banded kernels and batched GEMMs without strided-view slow paths, fused rope + permute kernel, fused output-gate kernel, wq_a shared with the indexer), MoE grid-order option HY4_MOE_NFIRST and MoE sub-timers (flags default off); 8K chunk 23.0 s -> 18.1 s
YanissAmz0d6dd5745834
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.pyindex 5fe1f46..ab24294 100644--- a/exllamav3/loader/hy4_forward.py+++ b/exllamav3/loader/hy4_forward.py@@ -26,6 +26,7 @@ import torchfrom .engram_rows import F8Rows, Hy4Engram, load_dense, _dequant_q8_0, rmsfrom .mla_hy4 import Hy4MLA+from . import mla_hy4 as _mla_modfrom . import ref_fused as _rffrom . import step_nosync as _ns@@ -545,7 +546,7 @@ class Hy4Forward:with tm.t("routed experts"):k_ = _pk()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)+ rsp.nff, rsp.nout, (rsp.strides[0], rsp.strides[2]), rsp.ebytes, rsp.E, tm=tm)self.stats["prefill_moe_calls"] = self.stats.get("prefill_moe_calls", 0) + 1sel_l = []rs = self.res.get(i) if (T <= MMVQ_MAXR and dev.type == "cuda") else None@@ -658,6 +659,8 @@ class Hy4Forward:if L.ix:with tm.t("indexer / kpool"):qr = mla._q(cur, "wq_a") @ mla.wq_a.T+ if _mla_mod.pf_f16():+ mla._qa_pre = qrqr = _HCF.rmsw(qr, mla.q_a_norm, mla.eps) if _HCF is not None else rms(qr, mla.eps) * mla.q_a_normif os.environ.get("HY4_INDEXER_FUSED", "0") == "1" and self.dev.type == "cuda": # flag off: the old CPU path below, untouchedallow = self._indexer_fused(i).forward(cur, qr, N)diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.pyindex 917783e..d4fa24c 100644--- a/exllamav3/loader/mla_hy4.py+++ b/exllamav3/loader/mla_hy4.py@@ -11,6 +11,12 @@ from . import ref_fused as _rfPF_ATTN = os.environ.get("HY4_PREFILL_ATTN", "0") in ("1", "flash")PF_ATTN_FLASH = os.environ.get("HY4_PREFILL_ATTN", "0") == "flash" # 1 = prefill rows (T > PF_ATTN_MIN): flash-style MLA kernel (prefill_attn.py)PF_ATTN_MIN = 16+def pf_f16():+ return os.environ.get("HY4_PF_F16", "0") == "1"+++# HY4_PF_F16=1 (read live, per call): 1 = prefill attention chain in fp16 end to end (no fp32 [T, H, R] intermediates; same values, fewer passes)+PF_DENSE_ON = os.environ.get("HY4_PREFILL_DENSE", "0") == "1"def _sinks_mod():@@ -108,12 +114,13 @@ class Hy4MLA:pe = rope_norm(c[:, self.R:], pos, self.theta)return self._h(torch.cat([lat, pe], -1))- def q(self, cur, pos):+ def q(self, cur, pos, qa=None):"""-> 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.Htm = self.tmwith tm.t("f q: wq_a mm"):- qa = self._q(cur, "wq_a") @ self.wq_a.T+ if qa is None or self.q8_act:+ qa = self._q(cur, "wq_a") @ self.wq_a.Twith tm.t("f q: norm"):qr = rms(qa, self.eps) * self.q_a_normwith tm.t("f q: wq_b mm"):@@ -127,12 +134,62 @@ class Hy4MLA:qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))return self._h(qlat, "q"), self._h(qp, "q")+ _qa_pre = None # raw wq_a output of this call's rows, left by the indexer branch (same expression): reused instead of a second GEMM++ def _f16_ok(self, cur):+ T = cur.shape[0]+ return (pf_f16() and PF_ATTN and not PF_ATTN_FLASH and T > PF_ATTN_MIN and cur.is_cuda and getattr(self, "kpos_arange", False)+ and not self.f16_kv and not self.q8_act and os.environ.get("HY4_PREFILL_DENSE", "0") == "1" and T >= 1024+ and all(getattr(getattr(self, n), "ty", 0) == 8 for n in ("wq_a", "wq_b", "wgate", "wo")))++ def q16(self, cur, pos, qa=None):+ """prefill rows -> qc [H, T, R + rope] fp16 (saturated): [wk_b(q_nope) | rope(q_pe)] laid out per head, the layout the banded attention (ht=True) reads"""+ from . import prefill_kernels as _pk+ T, H = cur.shape[0], self.H+ tm = self.tm+ with tm.t("f q: wq_a mm"):+ if qa is None:+ qa = cur @ 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 = _pk.qdense_raw16(qr, self.wq_b.packed, tm)+ with tm.t("f q: rope"):+ P = self.rope_dim+ th = pos.double()[:, None] * (self.theta ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=pos.device) / P))[None, :]+ xh, qc = _pk.qprep(q, th.cos().float().contiguous(), th.sin().float().contiguous(), H, self.hd, self.nope, P, self.R)+ with tm.t("f q: wk_b bmm"):+ torch.bmm(xh, self._w16("wk_b").transpose(1, 2), out=qc[..., :self.R])+ return qc++ def attend16(self, cur, pos, kcache, allow, qa):+ from . import prefill_attn as _pa, prefill_kernels as _pk+ T, H = cur.shape[0], self.H+ tm = self.tm+ with tm.t("attn proj"):+ qcat = self.q16(cur, pos, qa)+ with tm.t("MLA core + sinks"):+ o = _pa.mla_banded(self.R, None, kcache, kcache.shape[0] - T, self.scale, self.sinks, self.window, allow, qcat=qcat, o16=True, ht=True) # [H, T, R] fp16+ with tm.t("attn proj"):+ with tm.t("f attend: wv_b bmm"):+ kv = torch.bmm(o, self._w16("wv_b").transpose(1, 2)) # [H, T, vd] fp16+ with tm.t("f gate: wgate mm + sigmoid"):+ gated = _pk.gate16(kv, _pk.qdense_raw16(cur, self.wgate.packed, tm))+ with tm.t("f gate: wo mm"):+ out = _pk.qdense_tm(gated, self.wo.packed, tm)+ with tm.t("f gate: post norm"):+ out = rms(out, self.eps) * self.post_norm if self.post_norm is not None else out+ return None, gated, out+def attend(self, cur, pos, kcache, kpos, allow=None):"""cur [T, n_embd] at positions pos; kcache [N, R+rope] at kpos (includes the T new rows). -> (kqv, gated, out)"""T, H = cur.shape[0], self.Htm = self.tm+ qa, self._qa_pre = self._qa_pre, None+ if self._f16_ok(cur):+ return self.attend16(cur, pos, kcache, allow, qa)with tm.t("attn proj"):- qlat, qpe = self.q(cur, pos)+ qlat, qpe = self.q(cur, pos, qa)with tm.t("MLA core + sinks"):if PF_ATTN and T > PF_ATTN_MIN and qlat.is_cuda and getattr(self, "kpos_arange", False):from . import prefill_attn as _pa # prefill rows: flash-style kernel, keys visited only inside the window / causal rangediff --git a/exllamav3/loader/prefill_attn.py b/exllamav3/loader/prefill_attn.pyindex 46a7a48..2ae1852 100644--- a/exllamav3/loader/prefill_attn.py+++ b/exllamav3/loader/prefill_attn.py@@ -115,8 +115,8 @@ def mla_flash(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None,# 2. P = softmax(S, sink) per row (Triton row kernel, fp16 out)# 3. O = P V (Triton GEMM, V = first R columns of the same K rows)@triton.jit-def _qk_kernel(Q, K, S, ALLOW, M, NK, NKP, row0, t0, qstart, klo, kbase, N, H, scale_l2,- D: tl.constexpr, WIN: tl.constexpr, HAS_ALLOW: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):+def _qk_kernel(Q, K, S, ALLOW, M, NK, NKP, row0, t0, qstart, klo, kbase, N, H, scale_l2, TT,+ D: tl.constexpr, WIN: tl.constexpr, HAS_ALLOW: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, HT: tl.constexpr):pid_m = tl.program_id(0)pid_n = tl.program_id(1)offs_m = pid_m * BM + tl.arange(0, BM)@@ -124,7 +124,11 @@ def _qk_kernel(Q, K, S, ALLOW, M, NK, NKP, row0, t0, qstart, klo, kbase, N, H, smm = offs_m < Mnn = offs_n < NKkb = tl.arange(0, BK)- qrow = (row0 + offs_m).to(tl.int64) * D+ if HT: # Q rows laid out [H, TT, D] (row = t * H + h)+ gq = (row0 + offs_m).to(tl.int64)+ qrow = ((gq % H) * TT + gq // H) * D+ else:+ qrow = (row0 + offs_m).to(tl.int64) * Dkrow = (klo - kbase + offs_n).to(tl.int64) * Dacc = tl.zeros((BM, BN), dtype=tl.float32)for d in range(0, D, BK):@@ -161,7 +165,7 @@ def _softmax_kernel(S, Pout, SINK, NKP, H, BLOCK: tl.constexpr, HAS_SINK: tl.con@triton.jit-def _pv_kernel(Pm, V, O, M, NK, NKP, row0, klo, kbase, D: tl.constexpr, R: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr):+def _pv_kernel(Pm, V, O, M, NK, NKP, row0, klo, kbase, H, TT, D: tl.constexpr, R: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, BK: tl.constexpr, O16: tl.constexpr, HT: tl.constexpr):pid_m = tl.program_id(0)pid_n = tl.program_id(1)offs_m = pid_m * BM + tl.arange(0, BM)@@ -174,7 +178,14 @@ def _pv_kernel(Pm, V, O, M, NK, NKP, row0, klo, kbase, D: tl.constexpr, R: tl.coa = tl.load(Pm + offs_m.to(tl.int64)[:, None] * NKP + kk[None, :], mask=mm[:, None] & (kk[None, :] < NKP), other=0.0)b = tl.load(V + (klo - kbase + kk).to(tl.int64)[:, None] * D + offs_n[None, :], mask=(kk[:, None] < NK), other=0.0)acc = tl.dot(a, b, acc)- tl.store(O + (row0 + offs_m).to(tl.int64)[:, None] * R + offs_n[None, :], acc, mask=mm[:, None])+ if O16: # saturating fp16 store (the consumer GEMM takes fp16 operands: same value as clamp + half of the fp32 result)+ acc = tl.minimum(tl.maximum(acc, -65504.0), 65504.0).to(tl.float16)+ go = (row0 + offs_m).to(tl.int64)+ if HT:+ orow = (go % H) * TT + go // H+ else:+ orow = go+ tl.store(O + orow[:, None] * R + offs_n[None, :], acc, mask=mm[:, None])BCFG = {"BM": 128, "BN": 128, "BK": 32, "warps": 8, "PBN": 128, "PBK": 32, "pwarps": 8, "S_BYTES": 48 << 20}@@ -185,19 +196,31 @@ 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"""+def mla_banded(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None, cfg=None, qcat=None, o16=False, ht=False):+ """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.+ qcat (fp16 [T, H, R + P], already saturated; q_lat = its first R columns, q_pe is None) skips the fp32 concat; o16 returns o_lat as saturated fp16."""c = cfg or (BCFG_SWA if window else BCFG_FULL)- T, H, R = q_lat.shape- Pd = q_pe.shape[-1]- D = R + Pd+ if qcat is not None:+ if ht:+ H, T, D = qcat.shape+ else:+ T, H, D = qcat.shape+ R = q_lat+ Pd = D - R+ else:+ T, H, R = q_lat.shape+ Pd = q_pe.shape[-1]+ D = R + PdN = kc.shape[0]assert N == qstart + T- dev = q_lat.device+ dev = kc.deviceklo_all = max(0, qstart - window + 1) if window else 0kc16 = kc[klo_all:].clamp(-65504.0, 65504.0).half().contiguous()- qcat = torch.cat([q_lat, q_pe], -1).clamp(-65504.0, 65504.0).half().reshape(T * H, D).contiguous()- o = torch.empty(T, H, R, dtype=torch.float32, device=dev)+ if qcat is None:+ qcat = torch.cat([q_lat, q_pe], -1).clamp(-65504.0, 65504.0).half().reshape(T * H, D).contiguous()+ else:+ qcat = qcat.reshape(T * H, D)+ o = torch.empty(*((H, T, R) if ht else (T, H, R)), dtype=torch.float16 if o16 else torch.float32, device=dev)al = allow.to(torch.int8).contiguous() if allow is not None else qcatsk = sinks.float().contiguous() if sinks is not None else qcatnk_max = min(N, (window + 0) if window else N) + 0@@ -227,11 +250,11 @@ def mla_banded(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None,sbuf = torch.empty(need, dtype=torch.float32, device=dev)pbuf = torch.empty(need, dtype=torch.float16, device=dev)row0 = t0 * H- _qk_kernel[(triton.cdiv(M, c["BM"]), triton.cdiv(NKP, c["BN"]))](qcat, kc16, sbuf, al, M, NK, NKP, row0, t0, qstart, lo, klo_all, N, H, float(scale) * 1.4426950408889634,- D=D, WIN=int(window), HAS_ALLOW=allow is not None, BM=c["BM"], BN=c["BN"], BK=c["BK"],+ _qk_kernel[(triton.cdiv(M, c["BM"]), triton.cdiv(NKP, c["BN"]))](qcat, kc16, sbuf, al, M, NK, NKP, row0, t0, qstart, lo, klo_all, N, H, float(scale) * 1.4426950408889634, T,+ D=D, WIN=int(window), HAS_ALLOW=allow is not None, BM=c["BM"], BN=c["BN"], BK=c["BK"], HT=ht,num_warps=c["warps"], num_stages=1)_softmax_kernel[(M,)](sbuf, pbuf, sk, NKP, H, BLOCK=triton.next_power_of_2(NKP), HAS_SINK=sinks is not None, num_warps=4)- _pv_kernel[(triton.cdiv(M, c["BM"]), triton.cdiv(R, c["PBN"]))](pbuf, kc16, o, M, NK, NKP, row0, lo, klo_all, D=D, R=R, BM=c["BM"], BN=c["PBN"], BK=c["PBK"],+ _pv_kernel[(triton.cdiv(M, c["BM"]), triton.cdiv(R, c["PBN"]))](pbuf, kc16, o, M, NK, NKP, row0, lo, klo_all, H, T, D=D, R=R, BM=c["BM"], BN=c["PBN"], BK=c["PBK"], O16=o16, HT=ht,num_warps=c["pwarps"], num_stages=1)t0 += Bqreturn odiff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.pyindex 1cec328..e793dd7 100644--- a/exllamav3/loader/prefill_kernels.py+++ b/exllamav3/loader/prefill_kernels.py@@ -8,6 +8,7 @@ accumulation fp32. Formats follow ggml: Q4_K 144 B / 256, Q3_K 110 B / 256, Q8_0"""from __future__ import annotationsimport contextlib+import osimport torchimport tritonimport triton.language as tl@@ -81,9 +82,9 @@ def _wtile(W, wrow, sb, FMT: tl.constexpr, BN: tl.constexpr):@triton.jitdef _gu_kernel(X, Wg, Wu, H, sorted_pairs, block_expert, P, topk, E, ebytes, lim,- K: tl.constexpr, N: tl.constexpr, ROWB: tl.constexpr, FMT: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr):- pid_m = tl.program_id(0)- pid_n = tl.program_id(1)+ K: tl.constexpr, N: tl.constexpr, ROWB: tl.constexpr, FMT: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, NF: tl.constexpr):+ pid_m = tl.program_id(1 if NF else 0) # NF: grid (N tiles, row blocks): the N tiles of one row block (and the blocks of one expert) run back to back+ pid_n = tl.program_id(0 if NF else 1)e = tl.load(block_expert + pid_m)if e < E:offs_m = pid_m * BM + tl.arange(0, BM)@@ -107,9 +108,9 @@ def _gu_kernel(X, Wg, Wu, H, sorted_pairs, block_expert, P, topk, E, ebytes, lim@triton.jitdef _down_kernel(Hin, Wd, Out, wts, sorted_pairs, block_expert, P, E, ebytes,- K: tl.constexpr, N: tl.constexpr, ROWB: tl.constexpr, FMT: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr):- pid_m = tl.program_id(0)- pid_n = tl.program_id(1)+ K: tl.constexpr, N: tl.constexpr, ROWB: tl.constexpr, FMT: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr, NF: tl.constexpr):+ pid_m = tl.program_id(1 if NF else 0)+ pid_n = tl.program_id(0 if NF else 1)e = tl.load(block_expert + pid_m)if e < E:offs_m = pid_m * BM + tl.arange(0, BM)@@ -432,6 +433,7 @@ def to_f16(x):return x.float().clamp(-F16MAX, F16MAX).half() if x.dtype != torch.float16 else x+MOE_NF = None # tests: force the grid order (None = env HY4_MOE_NFIRST)MOE_CFG = None # None = chosen from the rows per expert (see moe_cfg)DENSE_CFG = {"BM": 128, "BN": 128, "warps": 8, "stages": 1}@@ -466,7 +468,7 @@ def route_blocks(sel, E, BM):return sp, be, maxb-def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None):+def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None, tm=None):"""z [T, K] activations (fp32 / fp16), sel [T, topk] int, w [T, topk] fp32 routing weights.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.@@ -476,15 +478,21 @@ def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=NoneBM, BN = c["BM"], c["BN"]P = T * SK = z.shape[1]- sp, be, maxb = route_blocks(sel.to(torch.int64), E, BM)- x = to_f16(z).contiguous()+ t = tm.t if tm is not None and tm.on else (lambda n: contextlib.nullcontext())+ nf = c.get("NF", MOE_NF if MOE_NF is not None else os.environ.get("HY4_MOE_NFIRST", "0") == "1")+ with t("f moe: route + sort"):+ sp, be, maxb = route_blocks(sel.to(torch.int64), E, BM)+ x = to_f16(z).contiguous()H = torch.empty(maxb * BM, nff, dtype=torch.float16, device=z.device)- _gu_kernel[(maxb, nff // BN)](x, bufs[0], bufs[1], H, sp, be, P, S, E, ebytes[0], float(lim), K=K, N=nff, ROWB=rowb[0], FMT=fmts[0], BM=BM, BN=BN,- num_warps=c["warps"], num_stages=c["stages"])+ with t("f moe: gate+up kernel"):+ _gu_kernel[((nff // BN, maxb) if nf else (maxb, nff // BN))](x, bufs[0], bufs[1], H, sp, be, P, S, E, ebytes[0], float(lim), K=K, N=nff, ROWB=rowb[0], FMT=fmts[0], BM=BM, BN=BN,+ NF=nf, num_warps=c["warps"], num_stages=c["stages"])out = torch.empty(P, nout, dtype=torch.float32, device=z.device)- _down_kernel[(maxb, nout // BN)](H, bufs[2], out, w.reshape(-1).float().contiguous(), sp, be, P, E, ebytes[1], K=nff, N=nout, ROWB=rowb[1], FMT=fmts[1],- BM=BM, BN=BN, num_warps=c["warps"], num_stages=c["stages"])- return out.view(T, S, nout).sum(1)+ with t("f moe: down kernel"):+ _down_kernel[((nout // BN, maxb) if nf else (maxb, nout // BN))](H, bufs[2], out, w.reshape(-1).float().contiguous(), sp, be, P, E, ebytes[1], K=nff, N=nout, ROWB=rowb[1], FMT=fmts[1],+ BM=BM, BN=BN, NF=nf, num_warps=c["warps"], num_stages=c["stages"])+ with t("f moe: sum over topk"):+ return out.view(T, S, nout).sum(1)def qdense(x, packed, fmt, cfg=None):@@ -532,7 +540,7 @@ def quant_k(x):return q, d, s-def moe_prefill_i8(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None):+def moe_prefill_i8(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=None, tm=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.shapec = cfg or I8_CFG@@ -591,3 +599,75 @@ def qdense_tm(x, packed, tm=None):with t(f"f dense N={N} K={K}: float"):out = torch.nan_to_num(o.float(), nan=0.0, posinf=F16MAX, neginf=-F16MAX)return out.reshape(*lead, N)+++def _gate_kernel(KV, G, OUT, T, HV, VD: tl.constexpr, BC: tl.constexpr):+ """OUT[t, c] = KV[h, t, d] * sigmoid(G[t, c]) with c = h * VD + d: the Hy4 output gate on fp16 operands (fp32 maths, nan_to_num on the gate logits,+ saturating fp16 result); KV is the batch-over-heads GEMM output [H, T, VD], G / OUT are [T, H * VD]"""+ t = tl.program_id(0)+ c = tl.program_id(1) * BC + tl.arange(0, BC)+ cm = c < HV+ h = c // VD+ d = c % VD+ g = tl.load(G + t.to(tl.int64) * HV + c, mask=cm, other=0.0).to(tl.float32)+ g = tl.where(g != g, 0.0, tl.minimum(tl.maximum(g, -65504.0), 65504.0))+ kv = tl.load(KV + (h.to(tl.int64) * T + t) * VD + d, mask=cm, other=0.0).to(tl.float32)+ o = kv * (1.0 / (1.0 + tl.exp(-g)))+ o = tl.minimum(tl.maximum(o, -65504.0), 65504.0)+ tl.store(OUT + t.to(tl.int64) * HV + c, o.to(tl.float16), mask=cm)+++def gate16(kv, g):+ """kv [H, T, VD] fp16 (bmm output), g [T, H * VD] fp16 (raw gate GEMM output) -> gated [T, H * VD] fp16"""+ H, T, VD = kv.shape+ out = torch.empty(T, H * VD, dtype=torch.float16, device=kv.device)+ _gate_kernel[(T, triton.cdiv(H * VD, 1024))](kv, g, out, T, H * VD, VD=VD, BC=1024, num_warps=4)+ return out+++def qdense_raw16(x, packed, tm=None, tag=""):+ """qdense_tm without the fp32 upcast: x [M, K] (fp16 passes through, else saturating cast) -> raw fp16 GEMM output [M, N]"""+ N, nb, bb = packed.shape+ t = tm.t if tm is not None and tm.on else (lambda n: contextlib.nullcontext())+ with t(f"f dense N={N} K={nb * 32}: to_f16"):+ x2 = to_f16(x.reshape(-1, nb * 32)).contiguous()+ with t(f"f dense N={N} K={nb * 32}: dequant"):+ w16 = dequant_q8(packed)+ with t(f"f dense N={N} K={nb * 32}: mm"):+ return torch.mm(x2, w16)+++def _qprep_kernel(Q, COS, SIN, XH, QC, T, H, HD: tl.constexpr, NOPE: tl.constexpr, NOPEP: tl.constexpr, P: tl.constexpr, D: tl.constexpr, R: tl.constexpr):+ """one program = one (t, h) row of the wq_b output [T, H * HD] (fp16 raw GEMM output): q_nope -> XH [H, T, NOPE] fp16 (nan -> 0, saturating),+ q_pe -> rotary (consecutive pairs, cos / sin [T, P / 2] fp32) -> QC[h, t, R:R + P] fp16 (same rounding points as rope_norm + clamp + half)"""+ t = tl.program_id(0)+ h = tl.program_id(1)+ base = (t.to(tl.int64) * H + h) * HD+ dst = (h.to(tl.int64) * T + t)+ c = tl.arange(0, NOPEP)+ x = tl.load(Q + base + c, mask=c < NOPE, other=0.0).to(tl.float32)+ x = tl.where(x != x, 0.0, tl.minimum(tl.maximum(x, -65504.0), 65504.0))+ tl.store(XH + dst * NOPE + c, x.to(tl.float16), mask=c < NOPE)+ i = tl.arange(0, P // 2)+ x0 = tl.load(Q + base + NOPE + 2 * i).to(tl.float32)+ x1 = tl.load(Q + base + NOPE + 2 * i + 1).to(tl.float32)+ x0 = tl.where(x0 != x0, 0.0, tl.minimum(tl.maximum(x0, -65504.0), 65504.0))+ x1 = tl.where(x1 != x1, 0.0, tl.minimum(tl.maximum(x1, -65504.0), 65504.0))+ cs = tl.load(COS + t * (P // 2) + i)+ sn = tl.load(SIN + t * (P // 2) + i)+ o0 = tl.minimum(tl.maximum(x0 * cs - x1 * sn, -65504.0), 65504.0)+ o1 = tl.minimum(tl.maximum(x0 * sn + x1 * cs, -65504.0), 65504.0)+ tl.store(QC + dst * D + R + 2 * i, o0.to(tl.float16))+ tl.store(QC + dst * D + R + 2 * i + 1, o1.to(tl.float16))+++def qprep(q, cos, sin, H, hd, nope, P, R):+ """q [T, H * hd] fp16 (raw wq_b GEMM output) -> (xh [H, T, nope] fp16, qc [H, T, R + P] fp16 with the rotary q_pe in columns R:). The caller's batched GEMM+ fills qc[..., :R] (xh @ wk_b^T)."""+ T = q.shape[0]+ xh = torch.empty(H, T, nope, dtype=torch.float16, device=q.device)+ qc = torch.empty(H, T, R + P, dtype=torch.float16, device=q.device)+ _qprep_kernel[(T, H)](q, cos, sin, xh, qc, T, H, HD=hd, NOPE=nope, NOPEP=triton.next_power_of_2(nope), P=P, D=R + P, R=R, num_warps=2)+ return xh, qc