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: fused dequant GEMM kernels (Q4_K / Q3_K sorted-token MoE, Q8_0 dense fp16 and int8), banded MLA attention, Engram prefetch (flags default off)

YanissAmzc4f12eb8045e
diff --git a/exllamav3/loader/engram_gpu.py b/exllamav3/loader/engram_gpu.py
new file mode 100644
index 0000000..f582a5b
--- /dev/null
+++ b/exllamav3/loader/engram_gpu.py
@@ -0,0 +1,119 @@
+"""GPU Engram for hy4_forward (flag HY4_ENGRAM_GPU=1, patched in by hy4/patch_engram.py).
+
+Same maths as engram_rows.Hy4Engram.apply, but nothing of the hidden state leaves the device:
+ * the big row table stays on the CPU side (pread of the DISTINCT needed rows only, threaded, one pinned staging buffer),
+ * the raw bytes are copied to the device once per call and decoded there (E4M3 [* E8M0 scale] table gather, exact),
+ * engram_kv stays as stored bytes (QLinear, GEMV kernel for small T) when `lin` gives one, else a dense matrix on the device,
+ * norms / gate / signal are torch ops on the device (no x.cpu(), no .to(dev) round trip).
+The hash (integer, token ids only) stays on the CPU: it never touches activations.
+Generic: config comes from the GGUF header keys, the row form from F8Rows.layout; nothing keyed on a model name.
+"""
+from __future__ import annotations
+from concurrent.futures import ThreadPoolExecutor
+import numpy as np
+import torch
+
+from .engram_rows import Hy4Engram, F8Rows, load_dense, rms, E4M3, E8M0, QB
+
+_POOL = ThreadPoolExecutor(max_workers=16)
+_TABS: dict = {}
+
+
+def _tabs(dev):
+ k = str(dev)
+ if k not in _TABS:
+ _TABS[k] = (E4M3.to(dev), E8M0.to(dev))
+ return _TABS[k]
+
+
+def fetch_rows_host(table: F8Rows, ids):
+ """CPU half of fetch_rows: distinct rows pread once (threaded) into one pinned buffer. -> (shape, uniq, inv, buf). Safe to run in a worker thread."""
+ ids = np.asarray(torch.as_tensor(ids, dtype=torch.int64).numpy())
+ uniq, inv = np.unique(ids.reshape(-1), return_inverse=True)
+ rb = table.row_bytes
+ buf = torch.empty(len(uniq), rb, dtype=torch.uint8).pin_memory() if torch.cuda.is_available() else torch.empty(len(uniq), rb, dtype=torch.uint8)
+ view = buf.numpy()
+
+ def one(a):
+ j, r = a
+ view[j] = table.raw_row(int(r))
+ if len(uniq) > 8:
+ list(_POOL.map(one, enumerate(uniq)))
+ else:
+ for a in enumerate(uniq):
+ one(a)
+ return ids.shape, uniq, inv, buf
+
+
+def rows_to_dev(table: F8Rows, host, dev) -> torch.Tensor:
+ """device half of fetch_rows: one H2D copy + exact E4M3 [* E8M0] decode + gather -> float32 [*shape, width]"""
+ shape, uniq, inv, buf = host
+ u = buf.to(dev, non_blocking=True)
+ t4, t8 = _tabs(dev)
+ w = table.width
+ if table.layout == "plain":
+ rows = t4[u.long()]
+ else: # width e4m3 values, then width/32 e8m0 scales (same as F8Rows.decode_raw)
+ rows = (t4[u[:, :w].long()].reshape(len(uniq), -1, QB) * t8[u[:, w:].long()][:, :, None]).reshape(len(uniq), w)
+ sel = torch.from_numpy(inv.astype(np.int64)).to(dev)
+ return rows[sel].reshape(*shape, w)
+
+
+def fetch_rows(table: F8Rows, ids, dev) -> torch.Tensor:
+ """ids (any int shape) -> float32 [*shape, width] on `dev`. Distinct rows are pread once (threaded), copied once, decoded on `dev`."""
+ return rows_to_dev(table, fetch_rows_host(table, ids), dev)
+
+
+class Hy4EngramGPU:
+ def __init__(self, g, layer: int, dev, table: F8Rows | None = None, lin=None, eps: float = 1.1920929e-07):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ pl = list(m[p + "ple.layers"])
+ self.layer, self.e, self.dev, self.eps = layer, pl.index(layer), torch.device(dev), eps
+ self.n_gram, self.n_head = m[p + "ple.ngram_size"], m[p + "ple.heads_per_ngram"]
+ self.n_cols = (self.n_gram - 1) * self.n_head
+ e, nc, ng = self.e, self.n_cols, self.n_gram
+ self.mult = list(m[p + "ple.layer_multipliers"])[e * ng:(e + 1) * ng]
+ self.primes = list(m[p + "ple.head_vocab_sizes"])[e * nc:(e + 1) * nc]
+ self.offs = list(m[p + "ple.head_offsets"])[e * nc:(e + 1) * nc]
+ self.token_map, self.pad_id = m[p + "engram.token_map"], m[p + "engram.pad_token_id"]
+ self.head_dim = m[p + "embedding_length_per_layer_input"]
+ self.n_embd, self.hc = m[p + "embedding_length"], m[p + "hyper_connection.count"]
+ b = f"blk.{layer}."
+ f = lambda n: load_dense(g, b + n).to(self.dev)
+ kv = lin(b + "engram_kv.weight") if lin is not None else load_dense(g, b + "engram_kv.weight")
+ self.kv = kv if not torch.is_tensor(kv) else kv.to(self.dev)
+ self.kv_b, self.lookup_norm, self.gate = f("engram_kv_b.weight"), f("engram_lookup_norm.weight"), f("engram_gate.weight")
+ self.hc_scale, self.pre_gamma = f("engram_hc_scale.weight"), f("engram_pre_gamma.weight")
+ self.table = table if table is not None else F8Rows(g)
+ assert self.table.width == self.head_dim
+
+ row_ids = Hy4Engram.row_ids
+
+ def _kv(self, r):
+ return self.kv(r) if callable(self.kv) else r @ self.kv.T
+
+ def apply(self, x, rows, valid):
+ T, eps = x.shape[0], self.eps
+ r = rms(rows, eps) * self.lookup_norm * valid[:, :, None]
+ r = r.reshape(T, -1)
+ kv = self._kv(r).reshape(T, self.hc + 1, self.n_embd) + self.kv_b
+ key, value = kv[:, :self.hc], kv[:, self.hc]
+ dot = (rms(x, eps) * rms(key, eps) * self.gate).sum(-1) / self.n_embd ** 0.5
+ mag = dot.abs().clamp_min(1e-6).sqrt()
+ sign = 1.0 - 2.0 * (-dot > 0).float()
+ gate = torch.sigmoid(mag * sign)
+ signal = rms(value, eps) * self.pre_gamma
+ delta = signal[:, None, :] * (gate[:, :, None] + self.hc_scale)
+ anyv = (valid.sum(-1) > 0).float()
+ return x + delta * anyv[:, None, None]
+
+ def host_rows(self, tokens, start: int, n: int):
+ """CPU part for positions start..start+n-1: hash + row pread. -> (valid, host) for rows_to_dev. Worker-thread safe (no CUDA compute)."""
+ ids, valid = self.row_ids(tokens, start, n)
+ return valid, fetch_rows_host(self.table, ids)
+
+ def __call__(self, x: torch.Tensor, tokens, start: int = 0, pre=None) -> torch.Tensor:
+ valid, host = pre if pre is not None else self.host_rows(tokens, start, x.shape[0])
+ rows = rows_to_dev(self.table, host, self.dev)
+ return self.apply(x, rows, valid.to(self.dev, non_blocking=True))
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
new file mode 100644
index 0000000..6429a74
--- /dev/null
+++ b/exllamav3/loader/hy4_forward.py
@@ -0,0 +1,738 @@
+"""Hy4-flash (hy_v4_flash) WHOLE-MODEL forward, slow but correct: torch only, no extension kernel, runs on CPU or any torch device.
+
+Composition of the registry blocks' reference maths (embedding, engram_hy4 + f8_rows, hyper_connection, mla + mla_window_sinks +
+mla_output_gate, dsa_kpool_indexer, dense / latent_moe + router_score_bias, hyper_head, output_norm + output); the trunk is
+block_count - nextn_predict_layers layers (blk 42, the MTP block, is never read). Only active when the GGUF plan selects those blocks
+(`is_hy4_plan`); nothing else imports this file.
+
+ weights non-expert tensors are dequantised once per layer (Q8_0 / F32 / BF16) into `wdtype` on `device` (kept when cache_weights);
+ routed experts stay raw in the GGUF (page cache): per call only the experts the router picked are read by offset,
+ dequantised (Q4_K / Q3_K torch paths) and dropped. The two-limit SwiGLU clamp (gate min 10, up +-10) is the torch path.
+ streams [T, hc, n_embd] fp32 between layers; HC identity comb (no cross-stream mix); engram before hc_pre on ple.layers.
+ cache per layer the MLA K rows [N, kv_lora + rope] (V = first kv_lora columns), full length (window layers mask, sinks always);
+ per full layer one KPoolIndexer (CPU) whose selected rows become the attention mask (all-causal selections skip the mask).
+ decode Hy4Forward.step(ids) appends to the caches; generate() = one prefill + greedy steps.
+Activations are NOT Q8-quantised (llama.cpp CPU quantises them): small numeric differences vs the oracle are expected."""
+from __future__ import annotations
+import contextlib
+import importlib.util
+import os
+import sys
+import time
+from types import SimpleNamespace
+
+import numpy as np
+import torch
+
+from .engram_rows import F8Rows, Hy4Engram, load_dense, _dequant_q8_0, rms
+from .mla_hy4 import Hy4MLA
+from . import ref_fused as _rf
+from . import step_nosync as _ns
+
+_HCF = None
+if os.environ.get("HY4_HC_FUSED", "0") == "1": # fused hyper-connection sites (loader/hc_fused.py)
+ from . import hc_fused as _HCF
+
+_HERE = os.path.dirname(os.path.abspath(__file__))
+_NEED = {"mla", "mla_window_sinks", "hyper_connection", "latent_moe", "engram_hy4"}
+
+
+def is_hy4_plan(plan) -> bool:
+ """registry predicate: the plan selected the Hy4 block set (a plain llama / qwen plan never does)"""
+ names = set()
+ for i in range(len(plan.layers)):
+ names |= set(plan.blocks_at(i))
+ return _NEED <= names and "hyper_head" in set(plan.glob.get("head_mod", []))
+
+
+def _kpool_mod():
+ sp = importlib.util.spec_from_file_location("exl_kpool_indexer", os.path.join(os.path.dirname(_HERE), "modules", "kpool_indexer.py"))
+ m = importlib.util.module_from_spec(sp)
+ sys.modules["exl_kpool_indexer"] = m
+ sp.loader.exec_module(m)
+ return m
+
+
+# ------------------------------------------------------------------------------------------------ dequant (any device)
+def _raw(raw, dev):
+ return raw.to(dev) if torch.is_tensor(raw) else torch.from_numpy(np.ascontiguousarray(raw)).to(dev)
+
+
+def dq_q4k(raw, N, K, dev="cpu"):
+ """Q4_K (144 B / 256: fp16 d, fp16 dmin, 12 B 6-bit scales / mins, 128 B nibbles) -> fp32 [N, K] (ggml dequantize_row_q4_K)"""
+ nb = K // 256
+ r = _raw(raw, dev).reshape(N * nb, 144)
+ d = r[:, 0:2].contiguous().view(torch.float16).float().reshape(-1, 1)
+ dm = r[:, 2:4].contiguous().view(torch.float16).float().reshape(-1, 1)
+ s = r[:, 4:16].int()
+ sc = torch.cat([s[:, 0:4] & 63, (s[:, 8:12] & 15) | ((s[:, 0:4] >> 6) << 4)], 1).float()
+ mn = torch.cat([s[:, 4:8] & 63, (s[:, 8:12] >> 4) | ((s[:, 4:8] >> 6) << 4)], 1).float()
+ qs = r[:, 16:].int().reshape(-1, 4, 32)
+ out = torch.empty(N * nb, 8, 32, device=r.device)
+ for j in range(4):
+ out[:, 2 * j] = (qs[:, j] & 15).float() * (d * sc[:, 2 * j:2 * j + 1]) - dm * mn[:, 2 * j:2 * j + 1]
+ out[:, 2 * j + 1] = (qs[:, j] >> 4).float() * (d * sc[:, 2 * j + 1:2 * j + 2]) - dm * mn[:, 2 * j + 1:2 * j + 2]
+ return out.reshape(N, K)
+
+
+def dq_q3k(raw, N, K, dev="cpu"):
+ """Q3_K (110 B / 256: hmask 32, qs 64, 12 B packed 6-bit scales, fp16 d) -> fp32 [N, K] (ggml dequantize_row_q3_K)"""
+ nb = K // 256
+ b = _raw(raw, dev).reshape(N * nb, 110)
+ d = b[:, 108:110].contiguous().view(torch.float16).float().reshape(-1, 1, 1, 1)
+ s = b[:, 96:108].long()
+ a0 = (s[:, 0:4] % 16) | (((s[:, 8:12] // 1) % 4) * 16)
+ a1 = (s[:, 4:8] % 16) | (((s[:, 8:12] // 4) % 4) * 16)
+ a2 = ((s[:, 0:4] // 16) % 16) | (((s[:, 8:12] // 16) % 4) * 16)
+ a3 = ((s[:, 4:8] // 16) % 16) | (((s[:, 8:12] // 64) % 4) * 16)
+ sc = (torch.cat([a0, a1, a2, a3], 1) - 32).float().reshape(-1, 2, 4, 2).repeat_interleave(16, dim=3) # [nb, half, j, 32]
+ sh = (2 * torch.arange(4, device=b.device)).reshape(1, 1, 4, 1)
+ q = (b[:, 32:96].long().reshape(-1, 2, 1, 32) >> sh) % 4
+ bit = (torch.arange(2, device=b.device).reshape(2, 1) * 4 + torch.arange(4, device=b.device).reshape(1, 4)).reshape(1, 2, 4, 1)
+ hm = (b[:, 0:32].long().reshape(-1, 1, 1, 32) >> bit) % 2
+ return (d * sc * (q - 4 * (1 - hm)).float()).reshape(N, K)
+
+
+def dq_expert(raw, ty, N, K, dev):
+ if ty == 12:
+ return dq_q4k(raw, N, K, dev)
+ if ty == 11:
+ return dq_q3k(raw, N, K, dev)
+ raise ValueError(f"routed expert tensor type {ty} not handled (Q4_K=12, Q3_K=11)")
+
+
+# ggml type id -> (format name, block elements): the SAME names foreign_linear._MMVQ_FN uses; the kernel is getattr(ext, "fq_mmvq_" + name)
+# (llama.cpp mmvq port, fq_mmvq.cu, bound in bindings.cpp). Generic: keyed on the stored ggml type + K only, nothing model specific.
+GG_MMVQ = {2: ("q4_0", 32), 3: ("q4_1", 32), 6: ("q5_0", 32), 7: ("q5_1", 32), 11: ("q3_k", 256), 12: ("q4_k", 256), 13: ("q5_k", 256),
+ 14: ("q6_k", 256), 16: ("iq2_xxs", 256), 17: ("iq2_xs", 256), 18: ("iq3_xxs", 256), 20: ("iq4_nl", 32), 21: ("iq3_s", 256),
+ 22: ("iq2_s", 256), 23: ("iq4_xs", 256)}
+MMVQ_MAXR = 16 # decode rows per expert served by the row kernels (foreign_linear: rows < FUSED_ROWS_MAX), launched <= 4 columns at a time
+_EXT = []
+
+# ggml type id -> (grouped-kernel fmt id, block elements, block bytes): the fq_moe_kq_grouped_mixed_q8 table (fq_moe_kq.cu kFmtBytes). Generic: keyed on the stored type only.
+# gate/up kernels exist for ids 0-5 and 8; down for 0-8.
+GG_GROUPED = {12: (0, 256, 144), 13: (1, 256, 176), 14: (2, 256, 210), 23: (3, 256, 136), 18: (4, 256, 98), 22: (5, 256, 82), 8: (6, 32, 34),
+ 7: (7, 32, 24), 11: (8, 256, 110)}
+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_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"
+
+
+def _pk():
+ from . import prefill_kernels
+ return prefill_kernels
+
+
+def moe_ref(z, sel, w, rsp, lim, group=16):
+ """exact fp32 reference of the prefill MoE on the resident stored bytes: experts dequantised `group` at a time (torch dq_q4k / dq_q3k, same values as
+ the pread path), per-expert fp32 matmuls, weighted index_add. Slow (host sync for the counts); for quality gates only."""
+ ty = {0: 12, 8: 11}
+ T, S = sel.shape
+ dev = z.device
+ nff, nout, E, K = rsp.nff, rsp.nout, rsp.E, z.shape[1]
+ lat = torch.zeros(T, nout, device=dev)
+ flat = sel.reshape(-1)
+ order = torch.argsort(flat, stable=True)
+ counts = torch.bincount(flat, minlength=E).tolist()
+ starts = [0]
+ for c in counts:
+ starts.append(starts[-1] + c)
+ wf = w.reshape(-1)
+ for e0 in range(0, E, group):
+ e1 = min(E, e0 + group)
+ if starts[e1] == starts[e0]:
+ continue
+ n = e1 - e0
+ Wg = dq_expert(rsp.bufs["gate"][e0 * rsp.ebytes[0]:e1 * rsp.ebytes[0]], ty[rsp.fu], n * nff, K, dev).view(n, nff, K)
+ Wu = dq_expert(rsp.bufs["up"][e0 * rsp.ebytes[0]:e1 * rsp.ebytes[0]], ty[rsp.fu], n * nff, K, dev).view(n, nff, K)
+ Wd = dq_expert(rsp.bufs["down"][e0 * rsp.ebytes[1]:e1 * rsp.ebytes[1]], ty[rsp.fd], n * nout, nff, dev).view(n, nout, nff)
+ for e in range(e0, e1):
+ if counts[e] == 0:
+ continue
+ pr = order[starts[e]:starts[e + 1]]
+ rows = pr // S
+ x = z[rows]
+ hh = torch.nn.functional.silu((x @ Wg[e - e0].T).clamp(max=lim)) * (x @ Wu[e - e0].T).clamp(-lim, lim)
+ lat.index_add_(0, rows, (hh @ Wd[e - e0].T) * wf[pr].unsqueeze(-1))
+ return lat
+
+
+def _ext():
+ """the compiled extension: $HY4_EXT_DIR/exllamav3_ext*.so if set (a tree built for THIS torch, e.g. the HIP tree on the Strix), else the tree root"""
+ if not _EXT:
+ try:
+ import glob
+ d = os.environ.get("HY4_EXT_DIR") or os.path.dirname(os.path.dirname(_HERE))
+ f = sorted(glob.glob(os.path.join(d, "exllamav3_ext*.so")))[0]
+ sp = importlib.util.spec_from_file_location("exllamav3_ext", f)
+ e = importlib.util.module_from_spec(sp)
+ sys.modules["exllamav3_ext"] = e
+ sp.loader.exec_module(e)
+ _EXT.append(e)
+ except Exception as ex: # noqa: BLE001
+ sys.modules.pop("exllamav3_ext", None)
+ print("hy4_forward: extension unavailable:", repr(ex)[:160], flush=True)
+ _EXT.append(None)
+ return _EXT[0]
+
+
+def mmvq_fn(ty, K):
+ """kernel for stored ggml type `ty` with row length K, or None (-> torch dequant path)"""
+ f = GG_MMVQ.get(int(ty))
+ e = _ext()
+ if f is None or e is None or K % f[1] != 0 or not hasattr(e, "fq_mmvq_" + f[0]):
+ return None
+ return getattr(e, "fq_mmvq_" + f[0])
+
+
+def _dq_q8_0_t(packed):
+ """stored Q8_0 blocks [N, nb, 34] uint8 (any device) -> fp32 [N, nb*32] (fp16 d, 32 int8): exact, same values as engram_rows._dequant_q8_0"""
+ d = packed[:, :, 0:2].contiguous().view(torch.float16).float()
+ q = packed[:, :, 2:].contiguous().view(torch.int8).float()
+ return (q * d).reshape(packed.shape[0], -1)
+
+
+# DENSE table (move 3): stored ggml type id -> (block elems, bytes per block, decode GEMV name in the extension, torch dequant [N, nb, bb] -> fp32 [N, K]).
+# Generic: keyed on the stored ggml type + K only, nothing model specific. A dense matrix whose type is here stays as stored bytes on the GPU;
+# rows <= DENSE_MAXR run the extension GEMV (activation quantised to q8_1 inside, like llama.cpp), more rows dequantise per call (no resident fp32 copy).
+GG_DENSE = {8: (32, 34, "fq_gemv_q8_0", _dq_q8_0_t)}
+DENSE_MAXR = 16
+DENSE_DQ = os.environ.get("HY4_DENSE_DQ", "0") == "1" # 1 = old path: dense matrices dequantised once to fp32 and kept resident
+
+
+def dense_fn(ty, K):
+ """(spec, GEMV or None) for stored type `ty` with row length K, or None when the type is not in GG_DENSE / K is not a block multiple"""
+ spec = GG_DENSE.get(int(ty))
+ if spec is None or K % spec[0] != 0:
+ return None
+ e = _ext()
+ return spec, (getattr(e, spec[2], None) if e is not None else None)
+
+
+class QLinear:
+ """a dense [N, K] matrix kept as STORED bytes on the device; `x @ q.T` / q(x) = x [.., K] -> [.., N]"""
+
+ def __init__(self, packed, ty, spec, gemv, stats=None):
+ self.packed, self.ty, self.spec, self.gemv, self.stats = packed, int(ty), spec, gemv, stats
+ self.shape = (packed.shape[0], packed.shape[1] * spec[0])
+
+ @property
+ def T(self):
+ return _QT(self)
+
+ def dense(self):
+ return self.spec[3](self.packed)
+
+ def __call__(self, x):
+ K, N = self.shape[1], self.shape[0]
+ lead = x.shape[:-1]
+ x2 = x.reshape(-1, K)
+ if x2.shape[0] <= DENSE_MAXR and self.gemv is not None:
+ xf = x2.float().contiguous()
+ out = torch.empty(xf.shape[0], N, dtype=torch.float32, device=x.device)
+ self.gemv(xf, self.packed, out)
+ 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)
+ if self.stats is not None:
+ self.stats["dense_pf"] = self.stats.get("dense_pf", 0) + 1
+ else:
+ out = x2.float() @ self.dense().T
+ if self.stats is not None:
+ self.stats["dense_dq"] = self.stats.get("dense_dq", 0) + 1
+ return out.to(x.dtype).reshape(*lead, N)
+
+
+class _QT:
+ def __init__(self, q):
+ self.q = q
+
+ def __rmatmul__(self, x):
+ return self.q(x)
+
+
+def load_linear(g, name, dev, stats=None):
+ """Q8_0 (any type in GG_DENSE) dense tensor as QLinear on a cuda device when its GEMV exists and HY4_DENSE_DQ != 1; else None (caller dequantises)"""
+ ty, dims, off = g.infos[name]
+ if DENSE_DQ or torch.device(dev).type != "cuda" or len(dims) != 2:
+ return None
+ f = dense_fn(ty, dims[0])
+ if f is None or f[1] is None:
+ return None
+ spec, fn = f
+ K, N = dims[0], dims[1]
+ raw = np.ascontiguousarray(g._pread(off, N * (K // spec[0]) * spec[1]))
+ return QLinear(torch.from_numpy(raw).reshape(N, K // spec[0], spec[1]).to(dev), ty, spec, fn, stats)
+
+
+HEAD_CHUNK = 8192
+
+
+def head_gemm(h, W, chunk=HEAD_CHUNK):
+ """output head, generic by dtype: h [R, D] fp32, W [V, D] bf16 / f16 / f32 (resident on h.device) -> logits [R, V] fp32.
+ Per vocab chunk W is upcast to fp32 and multiplied (R == 1 = the same mat-vec the old CPU head used; R > 1 = one GEMM per chunk)."""
+ V = W.shape[0]
+ out = torch.empty(h.shape[0], V, dtype=torch.float32, device=h.device)
+ for a in range(0, V, chunk):
+ w = W[a:a + chunk].float()
+ if h.shape[0] == 1:
+ out[0, a:a + chunk] = w @ h[0]
+ else:
+ out[:, a:a + chunk] = h @ w.T
+ return out
+
+
+class _Tm:
+ """per-class synchronised wall timers (off unless .on)"""
+ CLASSES = ("attn proj", "MLA core + sinks", "indexer / kpool", "router", "routed experts", "shared expert", "Engram", "hc / norms", "head", "other")
+
+ def __init__(self):
+ self.on, self.acc = False, {}
+
+ def reset(self):
+ self.acc = {}
+
+ @contextlib.contextmanager
+ def t(self, name):
+ if not self.on:
+ yield
+ return
+ torch.cuda.synchronize()
+ t0 = time.time()
+ yield
+ torch.cuda.synchronize()
+ self.acc[name] = self.acc.get(name, 0.0) + time.time() - t0
+
+
+def _mv(o, dev, dtype=None):
+ for k, v in list(vars(o).items()):
+ if torch.is_tensor(v) and v.is_floating_point():
+ setattr(o, k, v.to(dev, dtype) if (dtype is not None and v.dim() > 1) else v.to(dev))
+ return o
+
+
+# ------------------------------------------------------------------------------------------------ the model
+class Hy4Forward:
+ def __init__(self, g, device="cpu", n_layers=None, cache_weights=False, hook=None, wdtype=torch.float32, use_indexer=True, q8_act=False):
+ m = g.meta
+ p = m["general.architecture"] + "."
+ self.g, self.dev, self.hook, self.cache_weights, self.wdtype = g, torch.device(device), hook, cache_weights, wdtype
+ self.n_trunk = m[p + "block_count"] - m.get(p + "nextn_predict_layers", 0)
+ self.n_layers = n_layers or self.n_trunk
+ assert self.n_layers <= self.n_trunk
+ self.D, self.hc = m[p + "embedding_length"], m[p + "hyper_connection.count"]
+ self.eps, self.hc_eps = float(m[p + "attention.layer_norm_rms_epsilon"]), float(m[p + "hyper_connection.epsilon"])
+ self.magnitude = float(m[p + "hyper_connection.magnitude"])
+ self.n_dense = m[p + "leading_dense_block_count"]
+ self.topk, self.w_scale = m[p + "expert_used_count"], float(m[p + "expert_weights_scale"])
+ self.clamp = list(m[p + "swiglu_clamp_exp"])
+ self.ple = set(m[p + "ple.layers"])
+ self.idx_types = list(m[p + "attention.indexer.types"])
+ self.swa = list(m[p + "attention.sliding_window_pattern"])
+ self.ixc = dict(n_head=m[p + "attention.indexer.head_count"], head_dim=m[p + "attention.indexer.key_length"],
+ top_k=m[p + "attention.indexer.top_k"], kpool=m[p + "attention.indexer.kpool"],
+ select_tail=bool(m[p + "attention.indexer.kpool_select_tail"]), rope_dim=m[p + "rope.dimension_count"],
+ rope_base=float(m[p + "rope.freq_base"]), eps=self.eps)
+ self.use_indexer, self.q8_act = use_indexer, q8_act
+ self.tm = _Tm()
+ self.expert_dq = os.environ.get("HY4_EXPERT_DQ", "0") == "1" # 1 = old path (torch dequant) for decode rows too
+ self.dense_dq = DENSE_DQ
+ self.head_cpu = os.environ.get("HY4_HEAD_CPU", "0") == "1" or self.dev.type != "cuda" # 1 = old path: head on the CPU, last position only
+ self.table = F8Rows(g)
+ self.kp = _kpool_mod()
+ self.kc = [None] * self.n_layers
+ self.ix, self.eng, self._lc = {}, {}, {}
+ self.tokens: list[int] = []
+ self.n = 0
+ self.stats = {"layer_s": 0.0}
+ ty, dims, off = g.infos["token_embd.weight"]
+ assert ty == 8 and dims[0] % 32 == 0
+ self._emb = (off, dims[0])
+ self.out_norm = load_dense(g, "output_norm.weight").to(self.dev)
+ self.hh = [load_dense(g, f"output_hc_{k}.weight").to(self.dev) for k in ("fn", "base", "scale")]
+ self.out_w = g.get_tensor("output.weight", allow_bf16=True) # [vocab, n_embd] bf16 (or f32)
+ assert tuple(self.out_w.shape) == (m[p + "vocab_size"], self.D), self.out_w.shape
+ if not self.head_cpu:
+ self.out_w = self.out_w.to(self.dev) # resident in its stored dtype (bf16: 0.74 GB)
+ self._load_resident()
+
+ def _load_resident(self):
+ '''routed experts of every MoE layer (while the byte budget lasts) resident on the GPU in their STORED bytes; decode rows then go through
+ fq_moe_kq_grouped_mixed_q8 (one launch set per layer). Layers whose formats are not in the grouped table, or past the budget, keep the pread path.'''
+ self.res, self.res_bytes = {}, 0
+ self.stats["resident_layers"], self.stats["resident_gib"] = 0, 0.0
+ if EXPERT_PREAD or self.expert_dq or self.dev.type != "cuda":
+ return
+ e = _ext()
+ if e is None or not hasattr(e, "fq_moe_kq_grouped_mixed_q8") or not hasattr(e, "fq_moe_kq_set_swiglu_limit"):
+ print("hy4_forward: grouped kernel unavailable -> experts stay on the pread path", flush=True)
+ return
+ g, dev, budget, skipped = self.g, self.dev, int(RESIDENT_GB * 2**30), []
+ for i in range(self.n_dense, self.n_layers):
+ info = {n: g.infos[f"blk.{i}.ffn_{n}_exps.weight"] for n in ("gate", "up", "down")}
+ f = {n: GG_GROUPED.get(int(info[n][0])) for n in info}
+ if None in f.values() or f["gate"][0] != f["up"][0] or f["gate"][0] not in GROUPED_UG or info["gate"][1] != info["up"][1]:
+ skipped.append((i, "format"))
+ continue
+ if any(info[n][1][0] % f[n][1] or (f[n][0] < 6 and info[n][1][0] % 256) for n in info):
+ skipped.append((i, "shape"))
+ continue
+ rows = {n: (info[n][1][1], info[n][1][0] // f[n][1] * f[n][2], info[n][1][2]) for n in info} # (rows, row bytes, experts)
+ need = sum(r * rb * E for r, rb, E in rows.values())
+ if self.res_bytes + need > budget:
+ skipped.append((i, "budget"))
+ break
+ bufs, ptrs, strides = {}, {}, {}
+ for n in ("gate", "up", "down"):
+ r, rb, E = rows[n]
+ tot = r * rb * E
+ buf = torch.empty(tot, dtype=torch.uint8, device=dev)
+ off = info[n][2]
+ for o in range(0, tot, 1 << 27):
+ c = min(1 << 27, tot - o)
+ buf[o:o + c].copy_(torch.from_numpy(g._pread(off + o, c)))
+ bufs[n], strides[n] = buf, rb
+ ptrs[n] = torch.arange(E, dtype=torch.int64, device=dev) * (r * rb) + buf.data_ptr()
+ self.res[i] = SimpleNamespace(bufs=bufs, ptrs=(ptrs["gate"], ptrs["up"], ptrs["down"]), strides=(strides["gate"], strides["up"], strides["down"]),
+ fu=f["gate"][0], fd=f["down"][0], nff=rows["gate"][0], nout=rows["down"][0], E=rows["gate"][2],
+ ebytes=(rows["gate"][0] * rows["gate"][1], rows["down"][0] * rows["down"][1]))
+ self.res_bytes += need
+ for fd in getattr(g, "fds", []):
+ try:
+ os.posix_fadvise(fd, 0, 0, os.POSIX_FADV_DONTNEED)
+ except Exception: # noqa: BLE001
+ pass
+ self.stats["resident_layers"], self.stats["resident_gib"] = len(self.res), round(self.res_bytes / 2**30, 3)
+ print(f"hy4_forward: resident experts {len(self.res)} layers {self.res_bytes / 2**30:.2f} GiB (budget {RESIDENT_GB} GiB) skipped={skipped[:3]}", flush=True)
+
+ # -- weights
+ def _w(self, name):
+ q = load_linear(self.g, name, self.dev, self.stats)
+ return q if q is not None else load_dense(self.g, name).to(self.dev, self.wdtype)
+
+ def _lin(self, name):
+ q = load_linear(self.g, name, self.dev, self.stats)
+ return q if q is not None else load_dense(self.g, name)
+
+ def _layer(self, i):
+ if i in self._lc:
+ return self._lc[i]
+ g, b, dev = self.g, f"blk.{i}.", self.dev
+ L = SimpleNamespace()
+ L.mla = Hy4MLA(g, i, q8_act=self.q8_act, lin=self._lin)
+ _mv(L.mla, dev, self.wdtype)
+ L.mla.tm = self.tm
+ L.mla.kpos_arange = True # layer(): kpos is torch.arange(N) (ref_fused window / causal block skip)
+ if os.environ.get("HY4_ATTN_GROUPED", "0") == "1": # flag off: nothing below runs, the old path is untouched
+ from .attn_grouped import install as _attn_group
+ _attn_group(L.mla)
+ L.mla.post_norm, L.mla.sinks = L.mla.post_norm.to(dev), L.mla.sinks.to(dev)
+ for tag in ("hca", "hcf"):
+ s = "attn" if tag == "hca" else "ffn"
+ setattr(L, tag, [load_dense(g, f"{b}hc_{s}_{k}.weight").to(dev) for k in ("fn", "base", "scale")])
+ L.attn_norm, L.ffn_norm, L.post_ffw = (load_dense(g, b + n).to(dev) for n in ("attn_norm.weight", "ffn_norm.weight", "post_ffw_norm.weight"))
+ if i < self.n_dense:
+ L.dense = [self._w(f"{b}ffn_{n}.weight") for n in ("gate", "up", "down")]
+ else:
+ L.router = g.get_tensor(b + "ffn_gate_inp.weight").float().to(dev)
+ L.rbias = g.get_tensor(b + "exp_probs_b.bias").float().to(dev)
+ L.rdown, L.rup = self._w(b + "ffn_routed_down.weight"), self._w(b + "ffn_routed_up.weight")
+ L.shexp = [self._w(f"{b}ffn_{n}_shexp.weight") for n in ("gate", "up", "down")]
+ L.ety = g.infos[b + "ffn_gate_exps.weight"][0]
+ L.ety_down = g.infos[b + "ffn_down_exps.weight"][0]
+ L.ix = bool(self.use_indexer and self.idx_types[i] and not self.swa[i] and (b + "indexer.attn_k.weight") in g.infos)
+ if self.cache_weights:
+ self._lc[i] = L
+ return L
+
+ def _indexer(self, i):
+ if i not in self.ix:
+ g, b = self.g, f"blk.{i}."
+ names = {"attn_k": "indexer.attn_k.weight", "k_norm": "indexer.k_norm.weight", "q_b": "indexer.attn_q_b.weight",
+ "proj": "indexer.proj.weight", "value": "indexer_compressor_value.weight", "gate": "indexer_compressor_gate.weight",
+ "ape": "indexer_compressor_ape.weight", "pool_norm": "indexer_compressor_norm.weight"}
+ w = {k: load_dense(g, b + s) for k, s in names.items()}
+ q8 = tuple(k for k, s in names.items() if g.infos[b + s][0] == 8)
+ self.ix[i] = self.kp.KPoolIndexer(w, q8_weights=q8, **self.ixc)
+ return self.ix[i]
+
+ def _indexer_fused(self, i):
+ fx = self.__dict__.setdefault("ixf", {})
+ if i not in fx:
+ from .indexer_fused import FusedKPoolIndexer
+ g, b = self.g, f"blk.{i}."
+ big = {"attn_k": "indexer.attn_k.weight", "q_b": "indexer.attn_q_b.weight",
+ "value": "indexer_compressor_value.weight", "gate": "indexer_compressor_gate.weight"}
+ small = {"k_norm": "indexer.k_norm.weight", "proj": "indexer.proj.weight",
+ "ape": "indexer_compressor_ape.weight", "pool_norm": "indexer_compressor_norm.weight"}
+ w = {k: self._lin(b + s) for k, s in big.items()} # QLinear (stored Q8 bytes) or fp32 tensor; `x @ w.T` works for both
+ w.update({k: load_dense(g, b + s).to(self.dev) for k, s in small.items()})
+ w = {k: (v.to(self.dev) if isinstance(v, torch.Tensor) else v) for k, v in w.items()}
+ fx[i] = FusedKPoolIndexer(w, self.dev, **self.ixc)
+ return fx[i]
+
+ # -- pieces
+ def _site(self, x, hw):
+ fn, base, scale = hw
+ T, H = x.shape[0], self.hc
+ mix = rms(x.reshape(T, -1), self.eps) @ fn.T
+ pre = torch.sigmoid(mix[:, :H] * scale[0] + base[:H]) + self.hc_eps
+ post = self.magnitude * torch.sigmoid(mix[:, H:] * scale[1] + base[H:]) + self.hc_eps
+ return pre, post
+
+ def _mm(self, x, w):
+ if isinstance(w, QLinear):
+ return w(x).float()
+ return (x.to(w.dtype) @ w.T).float()
+
+ def _ffn(self, i, L, x):
+ tm = self.tm
+ if i < self.n_dense:
+ gt, up, dn = L.dense
+ with tm.t("other"):
+ return self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn), None
+ T, dev = x.shape[0], self.dev
+ rsp = self.res.get(i)
+ pf = bool(PF_MOE and T > MMVQ_MAXR and dev.type == "cuda" and rsp is not None and rsp.fu in _pk().FROM_GROUPED and rsp.fd in _pk().FROM_GROUPED)
+ with tm.t("router"):
+ if _rf.ENABLED: # HY4_REF_FUSED=1: one router kernel; the host sync (tolist) only where the pread loop needs it
+ 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)
+ 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
+ sel_l = [] if (pf or _ns.skip_host_ids(self, i, T, MMVQ_MAXR)) else sorted(set(sel.flatten().tolist()))
+ with tm.t("other"):
+ z = self._mm(x, L.rdown)
+ lat = torch.zeros(T, z.shape[1], device=dev)
+ lim, N = float(self.clamp[i]), z.shape[1]
+ b = f"blk.{i}."
+ if pf and PF_MOE_REF:
+ with tm.t("routed experts"):
+ lat = moe_ref(z, sel, w, rsp, lim)
+ sel_l = []
+ 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,
+ 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 = []
+ rs = self.res.get(i) if (T <= MMVQ_MAXR and dev.type == "cuda") else None
+ if rs is not None:
+ with tm.t("routed experts"):
+ ext, S = _ext(), sel.shape[1]
+ if getattr(self, "_gpart", None) is None or self._gpart.shape[1] != N:
+ self._gpart = torch.empty(MMVQ_MAXR * S, N, dtype=torch.float32, device=dev)
+ self._gout = torch.empty(MMVQ_MAXR, N, dtype=torch.float32, device=dev)
+ ext.fq_moe_kq_set_swiglu_limit(lim)
+ ext.fq_moe_kq_grouped_mixed_q8(z.half().contiguous(), sel.contiguous(), w.half().contiguous(), *rs.ptrs, *rs.strides, rs.fu, rs.fd,
+ self._gpart[:T * S], self._gout[:T])
+ lat = self._gout[:T].clone()
+ self.stats["grouped_calls"] = self.stats.get("grouped_calls", 0) + 1
+ sel_l = [] # the per-expert pread loop below runs zero times
+ kg, kd = (None, None) if (self.expert_dq or T > MMVQ_MAXR or dev.type != "cuda") else (mmvq_fn(L.ety, N), mmvq_fn(L.ety_down, N))
+ use_k = kg is not None or kd is not None # per tensor: a stored type without a kernel keeps the torch dequant for that tensor only
+ with tm.t("routed experts"):
+ if use_k:
+ ext, di = _ext(), (dev.index if dev.index is not None else torch.cuda.current_device())
+ for e in sel_l:
+ rows, slot = (sel == e).nonzero(as_tuple=True)
+ zi = z[rows]
+ R = zi.shape[0]
+ raw = {n: self.g.get_tensor(f"{b}ffn_{n}_exps.e{e}.weight") for n in ("gate", "up", "down")}
+ ty = {"gate": L.ety, "up": L.ety, "down": L.ety_down}
+ fk = {"gate": kg, "up": kg, "down": kd}
+
+ def mv(xr, n):
+ """x [R,K] . W_n.T -> [R,N] fp32: mmvq on the stored bytes if the type has a kernel, else torch dequant (old path)"""
+ self.stats["mmvq_calls" if fk[n] is not None else "dq_calls"] = self.stats.get("mmvq_calls" if fk[n] is not None else "dq_calls", 0) + 1
+ if fk[n] is None:
+ return xr @ dq_expert(raw[n], ty[n], N, N, dev).T
+ Wb = _raw(raw[n], dev).reshape(N, -1).contiguous()
+ qb = ext.fq_q8_scratch(di, R, N)
+ ext.fq_quant_q8_1_rows(xr.half().contiguous(), qb)
+ o = torch.empty(R, N, dtype=torch.float32, device=dev)
+ for a0 in range(0, R, 4):
+ fk[n](qb[a0:a0 + 4], Wb, o[a0:a0 + 4])
+ return o
+ ga, upv = mv(zi, "gate"), mv(zi, "up")
+ h = torch.nn.functional.silu(ga.clamp(max=lim)) * upv.clamp(-lim, lim)
+ dn_o = mv(h, "down")
+ lat.index_add_(0, rows, dn_o * w[rows, slot].unsqueeze(-1))
+ with tm.t("other"):
+ y = self._mm(lat, L.rup)
+ gt, up, dn = L.shexp
+ with tm.t("shared expert"):
+ sh = self._mm(torch.nn.functional.silu(self._mm(x, gt)) * self._mm(x, up), dn)
+ return y + sh, lat
+
+ def _engram(self, i, x, ids, start):
+ if os.environ.get("HY4_ENGRAM_GPU", "0") in ("1", "2") and self.dev.type == "cuda": # flag off: the old CPU path below, untouched
+ if i not in self.eng:
+ from .engram_gpu import Hy4EngramGPU
+ self.eng[i] = Hy4EngramGPU(self.g, i, self.dev, table=self.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else self._lin) # 2 = dense fp32 kv (bit-exact vs CPU path)
+ with self.tm.t("Engram"):
+ fut = getattr(self, "_eng_pf", {}).pop((i, start, x.shape[0]), None)
+ return self.eng[i](x, ids, start, pre=fut.result() if fut is not None else None)
+ if i not in self.eng:
+ self.eng[i] = Hy4Engram(self.g, i, table=self.table)
+ with self.tm.t("Engram"):
+ return self.eng[i](x.cpu(), ids, start).to(self.dev)
+
+ def prefetch_engram(self, ids_all, chunk):
+ """HY4_ENGRAM_PREFETCH=1: the Engram row ids depend on token ids only, so hash + pread of every (chunk, Engram layer) of a known prompt run in a
+ background thread, in consumption order, while the GPU works on earlier layers / chunks. Consumed by _engram (entries are dropped when used)."""
+ if os.environ.get("HY4_ENGRAM_PREFETCH", "0") != "1" or os.environ.get("HY4_ENGRAM_GPU", "0") not in ("1", "2") or self.dev.type != "cuda":
+ return
+ from concurrent.futures import ThreadPoolExecutor
+ from .engram_gpu import Hy4EngramGPU
+ layers = sorted(i for i in self.ple if i < self.n_layers)
+ for i in layers:
+ if i not in self.eng:
+ self.eng[i] = Hy4EngramGPU(self.g, i, self.dev, table=self.table, lin=None if os.environ.get("HY4_ENGRAM_GPU") == "2" else self._lin)
+ toks = [int(t) for t in ids_all]
+ self._eng_pf = {}
+ ex = ThreadPoolExecutor(max_workers=2)
+ for s in range(self.n, len(toks), chunk):
+ n = min(chunk, len(toks) - s)
+ for i in layers:
+ self._eng_pf[(i, s, n)] = ex.submit(self.eng[i].host_rows, toks, s, n)
+ ex.shutdown(wait=False)
+
+ def _hk(self, name, i, t):
+ if self.hook is not None:
+ self.hook(name, i, t)
+
+ def layer(self, i, x, pos, ids, start):
+ L = self._layer(i)
+ T = x.shape[0]
+ if i in self.ple:
+ x = self._engram(i, x, ids, start)
+ self._hk("engram_out", i, x)
+ tm = self.tm
+ with tm.t("hc / norms"):
+ if _HCF is not None and _HCF.ok(x, L.hca, self.hc):
+ post, cur = _HCF.site(x, L.hca, L.attn_norm, self.eps, self.hc_eps, self.magnitude)
+ else:
+ pre, post = self._site(x, L.hca)
+ cur = rms((x * pre[:, :, None]).sum(1), self.eps) * L.attn_norm
+ mla = L.mla
+ with tm.t("attn proj"):
+ kn = mla.kv(cur, pos)
+ kc = _ns.append_kv(self, i, kn, start) if _ns.active(self) else (torch.cat([self.kc[i], kn]) if self.kc[i] is not None else kn)
+ N = kc.shape[0]
+ allow = None
+ if L.ix:
+ with tm.t("indexer / kpool"):
+ qr = mla._q(cur, "wq_a") @ mla.wq_a.T
+ qr = _HCF.rmsw(qr, mla.q_a_norm, mla.eps) if _HCF is not None else rms(qr, mla.eps) * mla.q_a_norm
+ if os.environ.get("HY4_INDEXER_FUSED", "0") == "1" and self.dev.type == "cuda": # flag off: the old CPU path below, untouched
+ allow = self._indexer_fused(i).forward(cur, qr, N)
+ else:
+ sel = self._indexer(i).forward(cur.cpu(), qr.cpu())
+ if any(len(r) < int(pp) + 1 for r, pp in zip(sel.rows, pos.tolist())):
+ allow = torch.zeros(T, N, dtype=torch.bool)
+ for t, r in enumerate(sel.rows):
+ allow[t, r.long()] = True
+ allow = allow.to(self.dev)
+ kqv, gated, out = mla.attend(cur, pos, kc, _ns.kpos(self, N) if _ns.active(self) else torch.arange(N, device=self.dev), allow)
+ self.kc[i] = kc
+ self._hk("attn_kqv", i, kqv)
+ self._hk("attn_gated", i, gated)
+ self._hk("attn_out", i, out)
+ with tm.t("hc / norms"):
+ if _HCF is not None and _HCF.ok(x, L.hcf, self.hc) and out.shape == (T, self.D):
+ s1, post2, cur2 = _HCF.res_site(x, out, post, L.hcf, L.ffn_norm, self.eps, self.hc_eps, self.magnitude)
+ else:
+ s1 = x + post[:, :, None] * out[:, None, :]
+ pre2, post2 = self._site(s1, L.hcf)
+ cur2 = rms((s1 * pre2[:, :, None]).sum(1), self.eps) * L.ffn_norm
+ f, lat = self._ffn(i, L, cur2)
+ if lat is not None:
+ self._hk("ffn_moe_out", i, lat)
+ with tm.t("hc / norms"):
+ if _HCF is not None and _HCF.ok(s1, L.hcf, self.hc) and f.shape == (T, self.D):
+ s2 = _HCF.resid(s1, f, post2, L.post_ffw, self.eps)
+ else:
+ f = rms(f, self.eps) * L.post_ffw
+ s2 = s1 + post2[:, :, None] * f[:, None, :]
+ self._hk("l_out", i, s2)
+ return s2
+
+ def embed(self, ids):
+ off, K = self._emb
+ rb = K // 32 * 34
+ rows = [_dequant_q8_0(self.g._pread(off + int(t) * rb, rb), K, 1) for t in ids]
+ return torch.cat(rows).to(self.dev)
+
+ def head(self, x, all_pos=False):
+ """x [T, hc, n_embd] -> logits of the LAST position [vocab] (all_pos: [T, vocab])"""
+ with self.tm.t("head"):
+ return self._head(x, all_pos)
+
+ def _head(self, x, all_pos=False):
+ fn, base, scale = self.hh
+ xl = x if all_pos else x[-1:]
+ R = xl.shape[0]
+ if _HCF is not None and self.hook is None and _HCF.ok(xl, self.hh, self.hc):
+ h = _HCF.site(xl, self.hh, self.out_norm, self.eps, self.hc_eps, self.magnitude)[1]
+ else:
+ mix = rms(xl.reshape(R, -1), self.eps) @ fn.T
+ pre = torch.sigmoid(mix * scale[0] + base) + self.hc_eps
+ col = (xl * pre[:, :, None]).sum(1)
+ self._hk("hc_head", -1, col)
+ h = rms(col, self.eps) * self.out_norm
+ if self.head_cpu:
+ h = h.cpu()
+ out = head_gemm(h.float(), self.out_w)
+ return out if all_pos else (out[0] if getattr(self, "_ns_dev", False) else out[0].cpu())
+
+ def step(self, ids, all_pos=False):
+ """append ids (prefill = all prompt ids at once, decode = one id), return last-position logits (None on a truncated stack)"""
+ if _ns.active(self):
+ return _ns.step(self, ids, all_pos)
+ if self.tm.on:
+ torch.cuda.synchronize()
+ base = sum(self.tm.acc.values())
+ t0 = time.time()
+ start = self.n
+ self.tokens += [int(t) for t in ids]
+ pos = torch.arange(start, start + len(ids), device=self.dev)
+ e = self.embed(ids)
+ x = e[:, None, :].expand(-1, self.hc, -1).contiguous()
+ for i in range(self.n_layers):
+ x = self.layer(i, x, pos, self.tokens, start)
+ self.n += len(ids)
+ self._x = x
+ lg = self.head(x, all_pos) if self.n_layers == self.n_trunk else None
+ if self.tm.on:
+ torch.cuda.synchronize()
+ tot = time.time() - t0
+ self.tm.acc["other"] = self.tm.acc.get("other", 0.0) + max(0.0, tot - (sum(self.tm.acc.values()) - base))
+ self.tm.last_total = tot
+ self.stats["layer_s"] += time.time() - t0
+ return lg
+
+ def generate(self, ids, n_new):
+ if _ns.active(self):
+ return _ns.generate(self.step, ids, n_new)
+ t0 = time.time()
+ lg = self.step(ids)
+ t1 = time.time()
+ first, out = lg, []
+ for _ in range(n_new):
+ nxt = int(lg.argmax())
+ out.append(nxt)
+ if len(out) == n_new:
+ break
+ lg = self.step([nxt])
+ t2 = time.time()
+ return first, out, {"prefill_s": t1 - t0, "decode_s": t2 - t1, "decode_steps": max(len(out) - 1, 0)}
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index cea356e..95ed087 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -6,6 +6,11 @@ from __future__ import annotations
import importlib.util, os
import torch
from .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rms
+from . import ref_fused as _rf
+
+PF_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 _sinks_mod():
@@ -26,8 +31,8 @@ def _dense3(g, name, h):
def rope_norm(x: torch.Tensor, pos: torch.Tensor, base: float) -> torch.Tensor:
"""ggml_rope_ext mode NORM (consecutive pairs), n_dims = x.shape[-1], no scaling / yarn: x [T, ..., P], pos [T]"""
P = x.shape[-1]
- th = pos.double()[:, None] * (base ** (-2.0 * torch.arange(P // 2, dtype=torch.float64) / P))[None, :] # [T, P/2]
- c, s = th.cos().float(), th.sin().float()
+ th = pos.double()[:, None] * (base ** (-2.0 * torch.arange(P // 2, dtype=torch.float64, device=pos.device) / P))[None, :] # [T, P/2]
+ c, s = th.cos().float().to(x.device), th.sin().float().to(x.device)
shp = (x.shape[0],) + (1,) * (x.dim() - 2) + (P // 2,)
c, s = c.view(shp), s.view(shp)
x0, x1 = x[..., 0::2], x[..., 1::2]
@@ -39,11 +44,12 @@ def rope_norm(x: torch.Tensor, pos: torch.Tensor, base: float) -> torch.Tensor:
class Hy4MLA:
"""One attention layer: cur [T, n_embd] (normed collapsed stream) -> kqv / gated / out, with a K cache the caller keeps."""
- def __init__(self, g, layer: int, q8_act: bool = False, f16_kv: bool = False):
+ def __init__(self, g, layer: int, q8_act: bool = False, f16_kv: bool = False, lin=None):
m = g.meta
p = m["general.architecture"] + "."
b = f"blk.{layer}."
self.layer, self.q8_act, self.f16_kv = layer, q8_act, f16_kv
+ lin = lin or (lambda n: load_dense(g, n)) # lin(name) -> fp32 [N, K] or a QLinear (stored bytes, hy4_forward.py)
self.H = int(list(m[p + "attention.head_count"])[layer])
self.hd, self.vd = m[p + "attention.key_length_mla"], m[p + "attention.value_length_mla"]
self.rope_dim, self.R = m[p + "rope.dimension_count"], m[p + "attention.kv_lora_rank"]
@@ -54,17 +60,18 @@ class Hy4MLA:
self.theta = float(m[p + ("rope.freq_base_swa" if self.swa else "rope.freq_base")])
self.eps = float(m[p + "attention.layer_norm_rms_epsilon"])
self.scale = 1.0 / float(self.hd) ** 0.5
- self.wq_a, self.q_a_norm = load_dense(g, b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
- self.wq_b = load_dense(g, b + "attn_q_b.weight")
- self.wkv_a, self.kv_a_norm = load_dense(g, b + "attn_kv_a_mqa.weight"), load_dense(g, b + "attn_kv_a_norm.weight")
+ self.wq_a, self.q_a_norm = lin(b + "attn_q_a.weight"), load_dense(g, b + "attn_q_a_norm.weight")
+ self.wq_b = lin(b + "attn_q_b.weight")
+ self.wkv_a, self.kv_a_norm = lin(b + "attn_kv_a_mqa.weight"), load_dense(g, b + "attn_kv_a_norm.weight")
self.wk_b, self.wv_b = _dense3(g, b + "attn_k_b.weight", self.H), _dense3(g, b + "attn_v_b.weight", self.H)
- self.wo, self.wgate = load_dense(g, b + "attn_output.weight"), load_dense(g, b + "attn_gate.weight")
+ self.wo, self.wgate = lin(b + "attn_output.weight"), lin(b + "attn_gate.weight")
pn = b + POST_NORM
self.post_norm = load_dense(g, pn) if pn in g.infos else None
sk = b + "attn_sinks.weight"
self.sinks = load_dense(g, sk) if sk in g.infos else None
self.S = _sinks_mod()
+ tm = type("_NoTm", (), {"t": staticmethod(lambda n: __import__("contextlib").nullcontext())})() # replaced by Hy4Forward._Tm
q8_skip: tuple = () # matmul tags (wq_a wq_b wkv_a kb vb wgate wo) whose activation is NOT quantised (diagnostics)
f16_parts: tuple = ("q", "k")
@@ -74,6 +81,16 @@ class Hy4MLA:
def _h(self, x, part="k"):
return x.half().float() if self.f16_kv and part in self.f16_parts else x
+ def _w16(self, name):
+ c = self.__dict__.setdefault("_w16c", {})
+ if name not in c:
+ c[name] = getattr(self, name).clamp(-65504.0, 65504.0).half().contiguous()
+ return c[name]
+
+ @staticmethod
+ def _f16(x):
+ return x.clamp(-65504.0, 65504.0).half()
+
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
@@ -87,16 +104,33 @@ class Hy4MLA:
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)
- qlat = torch.einsum("hrk,thk->thr", self.wk_b, self._q(qn, "kb"))
+ 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):
+ 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.H
- qlat, qpe = self.q(cur, pos)
- o = self.S.mla_sink_attend(qlat, qpe, kcache[:, :self.R], kcache[:, self.R:], pos, kpos, self.scale, self.sinks, self.window)
- 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)
+ tm = self.tm
+ with tm.t("attn proj"):
+ qlat, qpe = self.q(cur, pos)
+ 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 range
+ 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 _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))
+ 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)
+ gated, out = self.gate_out(cur, kqv)
return kqv, gated, out
def gate_out(self, cur, kqv):
diff --git a/exllamav3/loader/prefill_attn.py b/exllamav3/loader/prefill_attn.py
new file mode 100644
index 0000000..30975a9
--- /dev/null
+++ b/exllamav3/loader/prefill_attn.py
@@ -0,0 +1,232 @@
+"""Flash-style MLA prefill attention (Triton, absorbed latent form): one program = one query position x a block of heads.
+
+scores[h, t, j] = scale * (q_lat[t, h] . ckv[j] + q_pe[t, h] . k_pe[j]); visible: kpos[j] <= qpos[t], window (0 = none), optional bool mask `allow` [T, N];
+a per-head sink joins the softmax denominator only (running max / sum start at the sink logit); o[t, h] = softmax . ckv.
+The latent K rows [N, R + P] are shared by every head (MQA form): the same tile is the key (all R + P columns) and the value (first R columns).
+Same maths as modules/attention_fn/mla_sinks.mla_sink_attend; fp16 operands, fp32 accumulation / softmax. Keys are visited only inside
+[qpos - window + 1, qpos], so a sliding-window layer costs O(window), not O(N). Generic by (R, P, H, window); nothing model specific.
+"""
+from __future__ import annotations
+import torch
+import triton
+import triton.language as tl
+
+LOG2E = tl.constexpr(1.4426950408889634)
+CFG = {"HB": 32, "BK": 32, "warps": 4, "stages": 1}
+
+
+def _mla_kernel(Q, QP, KC, SINK, ALLOW, O, T, N, qstart, kbase, H, scale,
+ R: tl.constexpr, P: tl.constexpr, HB: tl.constexpr, BK: tl.constexpr, WIN: tl.constexpr,
+ HAS_ALLOW: tl.constexpr, HAS_SINK: tl.constexpr):
+ # R = 4 * DC: the latent dim is walked in 4 chunks (q / k loaded per chunk, 4 separate fp32 accumulators): keeps the dot-operand fragments
+ # of one chunk live instead of the whole [rows, R] tile (a full-width tile needs ~256 VGPRs of duplicated WMMA operand fragments -> spills)
+ DC: tl.constexpr = R // 4
+ t = tl.program_id(0)
+ hb = tl.program_id(1)
+ pos = qstart + t # absolute position of this query
+ h = hb * HB + tl.arange(0, HB)
+ rowq = (t * H + h).to(tl.int64)
+ cd = tl.arange(0, DC)
+ cp = tl.arange(0, P)
+ qp = tl.load(QP + rowq[:, None] * P + cp[None, :])
+ if HAS_SINK:
+ m = tl.load(SINK + h).to(tl.float32) * LOG2E
+ l = tl.full((HB,), 1.0, dtype=tl.float32)
+ else:
+ m = tl.full((HB,), -1e30, dtype=tl.float32)
+ l = tl.zeros((HB,), dtype=tl.float32)
+ a0 = tl.zeros((HB, DC), dtype=tl.float32)
+ a1 = tl.zeros((HB, DC), dtype=tl.float32)
+ a2 = tl.zeros((HB, DC), dtype=tl.float32)
+ a3 = tl.zeros((HB, DC), dtype=tl.float32)
+ hi = pos + 1
+ lo = 0
+ if WIN > 0:
+ lo = tl.maximum(0, pos - WIN + 1)
+ lo = (lo // BK) * BK
+ sc = scale * LOG2E
+ for k0 in range(lo, hi, BK):
+ kidx = k0 + tl.arange(0, BK)
+ kin = (kidx < hi) & (kidx >= 0)
+ krow = (kidx - kbase).to(tl.int64) * (R + P)
+ kp = tl.load(KC + krow[:, None] + R + cp[None, :], mask=kin[:, None], other=0.0) # [BK, P]
+ s = tl.dot(qp, tl.trans(kp))
+ for c in tl.static_range(4):
+ qc = tl.load(Q + rowq[:, None] * R + c * DC + cd[None, :], volatile=True)
+ kc = tl.load(KC + krow[:, None] + c * DC + cd[None, :], mask=kin[:, None], other=0.0)
+ s = tl.dot(qc, tl.trans(kc), s)
+ s = s * sc
+ vis = kin
+ if WIN > 0:
+ vis = vis & (kidx > pos - WIN)
+ if HAS_ALLOW:
+ al = tl.load(ALLOW + t.to(tl.int64) * N + kidx, mask=kin, other=0)
+ vis = vis & (al != 0)
+ s = tl.where(vis[None, :], s, -1e30)
+ mn = tl.maximum(m, tl.max(s, 1))
+ alpha = tl.exp2(m - mn)
+ p = tl.exp2(s - mn[:, None])
+ p = tl.where(vis[None, :], p, 0.0)
+ l = l * alpha + tl.sum(p, 1)
+ p16 = p.to(tl.float16)
+ v0 = tl.load(KC + krow[:, None] + 0 * DC + cd[None, :], mask=kin[:, None], other=0.0)
+ a0 = tl.dot(p16, v0, a0 * alpha[:, None])
+ v1 = tl.load(KC + krow[:, None] + 1 * DC + cd[None, :], mask=kin[:, None], other=0.0)
+ a1 = tl.dot(p16, v1, a1 * alpha[:, None])
+ v2 = tl.load(KC + krow[:, None] + 2 * DC + cd[None, :], mask=kin[:, None], other=0.0)
+ a2 = tl.dot(p16, v2, a2 * alpha[:, None])
+ v3 = tl.load(KC + krow[:, None] + 3 * DC + cd[None, :], mask=kin[:, None], other=0.0)
+ a3 = tl.dot(p16, v3, a3 * alpha[:, None])
+ m = mn
+ inv = 1.0 / tl.maximum(l, 1e-30)
+ tl.store(O + rowq[:, None] * R + 0 * DC + cd[None, :], a0 * inv[:, None])
+ tl.store(O + rowq[:, None] * R + 1 * DC + cd[None, :], a1 * inv[:, None])
+ tl.store(O + rowq[:, None] * R + 2 * DC + cd[None, :], a2 * inv[:, None])
+ tl.store(O + rowq[:, None] * R + 3 * DC + cd[None, :], a3 * inv[:, None])
+
+
+def mla_flash(q_lat, q_pe, kc, qstart, scale, sinks=None, window=0, allow=None, cfg=None):
+ """q_lat [T, H, R], q_pe [T, H, P] (any float dtype), kc [N, R + P] latent K rows of ALL positions 0..N-1 (N = qstart + T), qstart = position of query 0,
+ sinks [H] or None, window 0 / int, allow bool [T, N] or None -> o_lat [T, H, R] fp32"""
+ c = cfg or CFG
+ T, H, R = q_lat.shape
+ P = q_pe.shape[-1]
+ N = kc.shape[0]
+ HB = min(c["HB"], H)
+ assert H % HB == 0 and N == qstart + T
+ klo = max(0, qstart - window + 1) if window else 0
+ klo = (klo // c["BK"]) * c["BK"]
+ kc16 = kc[klo:].clamp(-65504.0, 65504.0).half().contiguous()
+ q16 = q_lat.clamp(-65504.0, 65504.0).half().contiguous()
+ qp16 = q_pe.clamp(-65504.0, 65504.0).half().contiguous()
+ o = torch.empty(T, H, R, dtype=torch.float32, device=q_lat.device)
+ sk = sinks.float().contiguous() if sinks is not None else q16
+ al = allow.to(torch.int8).contiguous() if allow is not None else q16
+ _mla_kernel[(T, H // HB)](q16, qp16, kc16, sk, al, o, T, N, qstart, klo, H, float(scale), R=R, P=P, HB=HB, BK=c["BK"], WIN=int(window),
+ HAS_ALLOW=allow is not None, HAS_SINK=sinks is not None, num_warps=c["warps"], num_stages=c["stages"])
+ return o
+
+
+# ------------------------------------------------------------------------------------------------ banded pipeline (default)
+# The one-pass flash kernel above needs a [rows, 512] accumulator plus dot-operand fragments of the whole latent width: it spills hundreds of VGPRs on
+# gfx11. Pipeline instead, per block of Bq query positions (all heads as rows, keys = the visible band [klo, last position]):
+# 1. S = scale * Q K^T (fp32, Triton GEMM over the concatenated [latent | rope] width, visibility mask -> -inf)
+# 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)
+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):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ mm = offs_m < M
+ nn = offs_n < NK
+ kb = tl.arange(0, BK)
+ qrow = (row0 + offs_m).to(tl.int64) * D
+ krow = (klo - kbase + offs_n).to(tl.int64) * D
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for d in range(0, D, BK):
+ a = tl.load(Q + qrow[:, None] + d + kb[None, :], mask=mm[:, None], other=0.0)
+ b = tl.load(K + krow[None, :] + d + kb[:, None], mask=nn[None, :], other=0.0)
+ acc = tl.dot(a, b, acc)
+ pos = qstart + t0 + offs_m // H
+ kabs = klo + offs_n
+ vis = nn[None, :] & (kabs[None, :] <= pos[:, None]) & mm[:, None]
+ if WIN > 0:
+ vis = vis & (kabs[None, :] > pos[:, None] - WIN)
+ if HAS_ALLOW:
+ al = tl.load(ALLOW + (t0 + offs_m // H).to(tl.int64)[:, None] * N + kabs[None, :], mask=vis, other=0)
+ vis = vis & (al != 0)
+ s = tl.where(vis, acc * scale_l2, float("-inf"))
+ tl.store(S + offs_m.to(tl.int64)[:, None] * NKP + offs_n[None, :], s, mask=mm[:, None] & (offs_n[None, :] < NKP))
+
+
+def _softmax_kernel(S, Pout, SINK, NKP, H, BLOCK: tl.constexpr, HAS_SINK: tl.constexpr):
+ r = tl.program_id(0)
+ c = tl.arange(0, BLOCK)
+ cm = c < NKP
+ x = tl.load(S + r.to(tl.int64) * NKP + c, mask=cm, other=float("-inf"))
+ m = tl.max(x, 0)
+ if HAS_SINK:
+ sk = tl.load(SINK + r % H).to(tl.float32) * 1.4426950408889634
+ m = tl.maximum(m, sk)
+ e = tl.exp2(x - m)
+ den = tl.sum(e, 0)
+ if HAS_SINK:
+ den = den + tl.exp2(sk - m)
+ tl.store(Pout + r.to(tl.int64) * NKP + c, (e / den).to(tl.float16), mask=cm)
+
+
+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):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ mm = offs_m < M
+ kb = tl.arange(0, BK)
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for k0 in range(0, NKP, BK):
+ kk = k0 + kb
+ a = 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])
+
+
+BCFG = {"BM": 128, "BN": 128, "BK": 32, "warps": 8, "PBN": 128, "PBK": 32, "pwarps": 8, "S_BYTES": 48 << 20}
+
+
+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
+ T, H, R = q_lat.shape
+ Pd = q_pe.shape[-1]
+ D = R + Pd
+ N = kc.shape[0]
+ assert N == qstart + T
+ dev = q_lat.device
+ klo_all = max(0, qstart - window + 1) if window else 0
+ kc16 = 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)
+ al = allow.to(torch.int8).contiguous() if allow is not None else qcat
+ sk = sinks.float().contiguous() if sinks is not None else qcat
+ nk_max = min(N, (window + 0) if window else N) + 0
+ t0 = 0
+ sbuf = pbuf = None
+ while t0 < T:
+ # block of Bq positions: S [Bq*H, nkp] fp32 must stay under S_BYTES
+ last_pos0 = qstart + t0
+ nk_guess = (min(last_pos0 + 1, window + 0 if window else last_pos0 + 1))
+ Bq = 1
+ while Bq < T - t0:
+ nb = Bq * 2
+ hi_ = min(N, qstart + t0 + nb)
+ lo_ = max(0, qstart + t0 - window + 1) if window else 0
+ nkp_ = ((hi_ - lo_ + 63) // 64) * 64
+ if nb * H * nkp_ * 4 > c["S_BYTES"]:
+ break
+ Bq = nb
+ Bq = min(Bq, T - t0)
+ hi = min(N, qstart + t0 + Bq)
+ lo = max(0, qstart + t0 - window + 1) if window else 0
+ NK = hi - lo
+ NKP = ((NK + 63) // 64) * 64
+ M = Bq * H
+ need = M * NKP
+ if sbuf is None or sbuf.numel() < need:
+ 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"],
+ 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"],
+ num_warps=c["pwarps"], num_stages=1)
+ t0 += Bq
+ return o
diff --git a/exllamav3/loader/prefill_kernels.py b/exllamav3/loader/prefill_kernels.py
new file mode 100644
index 0000000..d6ea9af
--- /dev/null
+++ b/exllamav3/loader/prefill_kernels.py
@@ -0,0 +1,272 @@
+"""Prefill kernels (Triton, ROCm gfx11 WMMA through tl.dot): fused dequant + GEMM on the STORED bytes of GGUF weights.
+
+ moe_prefill grouped / sorted-token MoE experts: tokens sorted by expert, one launch for gate+up(+SwiGLU), one for down(+weight);
+ Q4_K / Q3_K blocks are dequantised in registers once per (weight tile, expert block), never per token.
+ qdense dense Q8_0 [N, K/32, 34] bytes x [M, K] -> [M, N] fp32 (prefill rows; decode rows keep the GEMV kernels).
+Generic by stored format (FMT constexpr) and shape; nothing keyed on a model name. Activations are fp16 (saturating clamp on the cast),
+accumulation fp32. Formats follow ggml: Q4_K 144 B / 256, Q3_K 110 B / 256, Q8_0 34 B / 32.
+"""
+from __future__ import annotations
+import torch
+import triton
+import triton.language as tl
+
+FMT_Q4K, FMT_Q3K, FMT_Q8 = 0, 1, 2
+BLK_BYTES = {FMT_Q4K: 144, FMT_Q3K: 110, FMT_Q8: 34}
+BLK_ELEMS = {FMT_Q4K: 256, FMT_Q3K: 256, FMT_Q8: 32}
+# kyojin grouped-kernel fmt id (fq_moe_kq_grouped_mixed_q8) -> FMT here
+FROM_GROUPED = {0: FMT_Q4K, 8: FMT_Q3K}
+
+
+def _b(W, off):
+ return tl.load(W + off).to(tl.int32)
+
+
+def _f16(W, off):
+ return tl.load((W + off).to(tl.pointer_type(tl.float16))).to(tl.float32)
+
+
+def _wtile(W, wrow, sb, FMT: tl.constexpr, BN: tl.constexpr):
+ """dequantised fp16 weight tile [BN, 32] of sub-block `sb` (runtime index, 32 K values) of the [BN] rows at byte offsets wrow.
+ Q4_K / Q3_K: sb = 8 * superblock + s; Q8_0: sb = block. Runtime (not unrolled) so the register footprint stays one sub-block."""
+ lane = tl.arange(0, 32)
+ if FMT == 0: # Q4_K: fp16 d, fp16 dmin, 12 scale bytes, 128 nibble bytes
+ kb = sb // 8
+ s = sb % 8
+ blk = wrow + kb * 144
+ d = _f16(W, blk)
+ dm = _f16(W, blk + 2)
+ 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).to(tl.float32)
+ mn = tl.where(hi, (x8 >> 4) | ((x4 >> 6) << 4), x4 & 63).to(tl.float32)
+ qs = tl.load(W + blk[:, None] + (16 + (s // 2) * 32) + lane[None, :]).to(tl.int32)
+ q = ((qs >> ((s % 2) * 4)) & 15).to(tl.float32)
+ w = (q * (d * sc)[:, None] - (dm * mn)[:, None]).to(tl.float16)
+ elif FMT == 1: # Q3_K: 32 high-bit bytes, 64 2-bit bytes, 12 scale bytes, fp16 d
+ kb = sb // 8
+ s = sb % 8
+ half = s // 4
+ j = s % 4
+ blk = wrow + kb * 110
+ d = _f16(W, blk + 108)
+ 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).to(tl.float32)
+ scB = ((lB | (hB << 4)) - 32).to(tl.float32)
+ 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)
+ q = ((qs >> (2 * j)) & 3).to(tl.float32)
+ hb = ((hm >> s) & 1).to(tl.float32)
+ w = ((q - 4.0 * (1.0 - hb)) * sc * d[:, None]).to(tl.float16)
+ else: # Q8_0: fp16 d, 32 int8
+ blk = wrow + sb * 34
+ d = _f16(W, blk)
+ q = tl.load(W + blk[:, None] + 2 + lane[None, :]).to(tl.int8).to(tl.float32)
+ w = (q * d[:, None]).to(tl.float16)
+ return w
+
+
+def _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)
+ 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
+ xrow = (pair // topk).to(tl.int64) * K
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ wrow = e.to(tl.int64) * ebytes + offs_n.to(tl.int64) * ROWB
+ ag = tl.zeros((BM, BN), dtype=tl.float32)
+ au = tl.zeros((BM, BN), dtype=tl.float32)
+ lane = tl.arange(0, 32)
+ for sb in range(0, K // 32):
+ x = tl.load(X + xrow[:, None] + sb * 32 + lane[None, :], mask=valid[:, None], other=0.0)
+ ag = tl.dot(x, tl.trans(_wtile(Wg, wrow, sb, FMT, BN)), ag)
+ au = tl.dot(x, tl.trans(_wtile(Wu, wrow, sb, FMT, BN)), au)
+ g = tl.minimum(ag, lim)
+ u = tl.minimum(tl.maximum(au, -lim), lim)
+ h = g / (1.0 + tl.exp(-g)) * u
+ tl.store(H + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], h.to(tl.float16))
+
+
+def _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)
+ 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
+ xrow = offs_m.to(tl.int64) * K
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ wrow = e.to(tl.int64) * ebytes + offs_n.to(tl.int64) * ROWB
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ lane = tl.arange(0, 32)
+ for sb in range(0, K // 32):
+ x = tl.load(Hin + xrow[:, None] + sb * 32 + lane[None, :], mask=valid[:, None], other=0.0)
+ acc = tl.dot(x, tl.trans(_wtile(Wd, wrow, sb, FMT, BN)), acc)
+ 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 _dense_kernel(X, W, Out, M, N, K: 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)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ mm = offs_m < M
+ xrow = offs_m.to(tl.int64) * K
+ offs_n = pid_n * BN + tl.arange(0, BN)
+ nm = offs_n < N
+ wrow = tl.where(nm, offs_n, 0).to(tl.int64) * ROWB
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ lane = tl.arange(0, 32)
+ for sb in range(0, K // 32):
+ x = tl.load(X + xrow[:, None] + sb * 32 + lane[None, :], mask=mm[:, None], other=0.0)
+ acc = tl.dot(x, tl.trans(_wtile(W, wrow, sb, FMT, BN)), acc)
+ tl.store(Out + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], acc, mask=mm[:, None] & nm[None, :])
+
+
+# ------------------------------------------------------------------------------------------------ int8 path (MMQ-like): Q8_0 weights x Q8 activations on int8 WMMA
+def _quant_x_kernel(X, XQ, XD, M, K, BM: tl.constexpr):
+ """per row and 32-block: d = amax / 127, q = round(x / d) (half away from zero, like ggml quantize_row_q8_0); X [M, K] fp16 / fp32"""
+ pid_m = tl.program_id(0)
+ sb = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ lane = tl.arange(0, 32)
+ mm = offs_m < M
+ x = tl.load(X + offs_m.to(tl.int64)[:, None] * K + sb * 32 + lane[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 + offs_m.to(tl.int64)[:, None] * K + sb * 32 + lane[None, :], q, mask=mm[:, None])
+ tl.store(XD + offs_m.to(tl.int64) * (K // 32) + sb, d, mask=mm)
+
+
+def _dense_i8_kernel(XQ, XD, W, Out, M, N, K: tl.constexpr, ROWB: tl.constexpr, BM: tl.constexpr, BN: tl.constexpr):
+ pid_m = tl.program_id(0)
+ pid_n = tl.program_id(1)
+ offs_m = pid_m * BM + tl.arange(0, BM)
+ mm = offs_m < M
+ xrow = offs_m.to(tl.int64) * K
+ xdrow = offs_m.to(tl.int64) * (K // 32)
+ 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)
+ acc = tl.zeros((BM, BN), dtype=tl.float32)
+ for sb in range(0, K // 32):
+ xq = tl.load(XQ + xrow[:, None] + sb * 32 + lane[None, :], mask=mm[:, None], other=0)
+ dx = tl.load(XD + xdrow + sb, mask=mm, other=0.0)
+ blk = wrow + sb * 34
+ dw = _f16(W, blk)
+ wq = tl.load(W + blk[:, None] + 2 + lane[None, :]).to(tl.int8)
+ ai = tl.dot(xq, tl.trans(wq))
+ acc += ai.to(tl.float32) * dx[:, None] * dw[None, :]
+ tl.store(Out + offs_m[:, None].to(tl.int64) * N + offs_n[None, :], acc, mask=mm[:, None] & 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
+
+
+MOE_CFG = {"BM": 64, "BN": 64, "warps": 4, "stages": 1}
+DENSE_CFG = {"BM": 64, "BN": 64, "warps": 4, "stages": 1}
+
+
+def route_blocks(sel, E, BM):
+ """sel [T, topk] expert ids -> (sorted_pairs int32 [maxb*BM] padded with P, block_expert int32 [maxb] (E = idle block), maxb). No host sync."""
+ T, S = sel.shape
+ P = T * S
+ ex = sel.reshape(-1)
+ order = torch.argsort(ex, stable=True)
+ counts = torch.bincount(ex, minlength=E)
+ nblk = (counts + (BM - 1)) // BM
+ csum = torch.cumsum(nblk, 0)
+ bstart = csum - nblk
+ cstart = torch.cumsum(counts, 0) - counts
+ es = ex[order]
+ ppos = bstart[es] * BM + (torch.arange(P, device=sel.device) - cstart[es])
+ maxb = (P + BM - 1) // BM + E
+ sp = torch.full((maxb * BM,), P, dtype=torch.int32, device=sel.device)
+ sp[ppos] = order.to(torch.int32)
+ be = torch.searchsorted(csum, torch.arange(maxb, device=sel.device), right=True).to(torch.int32)
+ return sp, be, maxb
+
+
+def moe_prefill(z, sel, w, bufs, fmts, lim, nff, nout, rowb, ebytes, E, cfg=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.
+ 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
+ P = T * S
+ K = z.shape[1]
+ 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"])
+ 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)
+
+
+def qdense(x, packed, fmt, cfg=None):
+ """x [.., K] -> [.., N] fp32 = x @ W.T, W stored as packed [N, K/blk, bytes] (uint8)"""
+ c = cfg or DENSE_CFG
+ N, nb, bb = packed.shape
+ K = nb * BLK_ELEMS[fmt]
+ lead = x.shape[:-1]
+ x2 = to_f16(x.reshape(-1, K)).contiguous()
+ M = x2.shape[0]
+ out = torch.empty(M, N, dtype=torch.float32, device=x.device)
+ grid = (triton.cdiv(M, c["BM"]), triton.cdiv(N, c["BN"]))
+ _dense_kernel[grid](x2, packed, out, M, N, K=K, ROWB=nb * bb, FMT=fmt, BM=c["BM"], BN=c["BN"], num_warps=c["warps"], num_stages=c["stages"])
+ return out.reshape(*lead, N)
+
+
+def qdense_i8(x, packed, cfg=None):
+ """x [.., K] -> [.., N] fp32 = x @ W.T for stored Q8_0 W [N, K/32, 34]: activations quantised to Q8 (per row, 32-block) and multiplied on int8 WMMA"""
+ c = cfg or DENSE_CFG
+ N, nb, bb = packed.shape
+ K = nb * 32
+ lead = x.shape[:-1]
+ x2 = x.reshape(-1, K).contiguous()
+ M = x2.shape[0]
+ xq = torch.empty(M, K, dtype=torch.int8, device=x.device)
+ xd = torch.empty(M, nb, dtype=torch.float32, device=x.device)
+ _quant_x_kernel[(triton.cdiv(M, 32), nb)](x2, xq, xd, M, K, BM=32, num_warps=1)
+ out = torch.empty(M, N, dtype=torch.float32, device=x.device)
+ _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)