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 dense: Q6_K / Q5_K requant arms for the Q8_0 dense matrices (HY4_DENSE_REQ_ARMS): offline ggml requant tool, run-time mode switch, quality + speed arm script

YanissAmz5720f390f9af
diff --git a/exllamav3/loader/attn_grouped.py b/exllamav3/loader/attn_grouped.py
index edba632..b0a9f62 100644
--- a/exllamav3/loader/attn_grouped.py
+++ b/exllamav3/loader/attn_grouped.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import torch
from .hy4_forward import QLinear, DENSE_MAXR
+from . import dense_req as _DR
# attribute names of the MLA object that read the layer input `cur` (wq_a, wkv_a, wgate); keyed by role, not by model
INPUT_SHARED = ("wq_a", "wkv_a", "wgate")
@@ -22,6 +23,10 @@ class _Group:
self.K, self.gemv, self.stats = lins[0].shape[1], lins[0].gemv, lins[0].stats
self.packed = torch.cat([q.packed for q in lins], 0)
self.ref = None # (x, x._version, outs)
+ self.ty, self.spec, self.shape = lins[0].ty, lins[0].spec, (sum(self.sizes), self.K)
+ self.gnames = [q.gname for q in lins] if all(q.gname for q in lins) else None
+ self.members = []
+ _DR.register(self)
def run(self, x):
r = self.ref
@@ -73,7 +78,8 @@ def group_linears(lins):
if any((q.shape[1], q.ty, q.gemv) != k for q in lins) or len({q.packed.device for q in lins}) != 1:
return None
grp = _Group(lins)
- return [GroupedView(q, grp, i, grp.packed[o:o + n]) for i, (q, o, n) in enumerate(zip(lins, grp.offs, grp.sizes))]
+ grp.members = [GroupedView(q, grp, i, grp.packed[o:o + n]) for i, (q, o, n) in enumerate(zip(lins, grp.offs, grp.sizes))]
+ return grp.members
def install(mla, names=INPUT_SHARED):
diff --git a/exllamav3/loader/dense_req.py b/exllamav3/loader/dense_req.py
new file mode 100644
index 0000000..0a44e1d
--- /dev/null
+++ b/exllamav3/loader/dense_req.py
@@ -0,0 +1,181 @@
+"""HY4_DENSE_REQ_ARMS=1: the dense Q8_0 matrices of the Hy4 trunk (attention + shared / latent projections) can be switched at run time to
+Q6_K or Q5_K bytes (requantised offline by tools/hy4/dense_requant.py, same bytes as llama-quantize --allow-requantize --tensor-type) to measure
+the quality cost and the decode gain of reading fewer weight bytes per token. Default off: nothing here is imported or registered.
+
+ register(owner) called by QLinear / attn_grouped._Group when the flag is set (weak references)
+ prepare(kinds) read OUTDIR/<kind>/<tensor>.bin for every registered owner whose tensors all have a file; owners without one stay Q8_0
+ set_mode(mode, kern) mode "q8" | "q6_k" | "q5_k" for every prepared owner; kern "gemv" (fq_gemv_*_q8) | "mmvq" (fq_mmvq_*) picks the decode kernel.
+ Rows <= DENSE_MAXR run the K-quant GEMV on q8_1 activations; more rows (prefill) dequantise the weight to fp16 per call.
+The caller drops the captured graphs (they bake the kernels and the weight pointers)."""
+from __future__ import annotations
+
+import os
+import weakref
+
+import numpy as np
+import torch
+
+ENABLED = os.environ.get("HY4_DENSE_REQ_ARMS", "0") == "1"
+ALT_DIR = os.environ.get("HY4_DENSE_ALT", "/path/to/alt")
+KQ = {"q6_k": dict(bb=210, blk=256), "q5_k": dict(bb=176, blk=256)}
+_OWNERS: list = []
+_EXT = []
+
+
+def register(owner):
+ if ENABLED:
+ _OWNERS.append(weakref.ref(owner))
+
+
+def _ext():
+ from . import hy4_forward as hf
+ return hf._ext()
+
+
+def _dq_fn(kind):
+ """torch dequant [N, K/256, bb] uint8 -> fp32 [N, K] (the QLinear.dense() spec slot): the extension's fp16 dequant kernel"""
+ name = "fq_dequant_" + kind
+
+ def f(packed):
+ N, nb, bb = packed.shape
+ out = torch.empty(N, nb * 256, dtype=torch.float16, device=packed.device)
+ getattr(_ext(), name)(packed.reshape(N, -1).contiguous(), out)
+ return out.float()
+ return f
+
+
+def dequant16(lin):
+ """fp16 [K, N] (the layout torch.mm(x, w) wants) of a K-quant QLinear, one dequant launch"""
+ N, nb, bb = lin.packed.shape
+ out = torch.empty(N, nb * 256, dtype=torch.float16, device=lin.packed.device)
+ getattr(_ext(), "fq_dequant_" + {210: "q6_k", 176: "q5_k"}[bb])(lin.packed.reshape(N, -1), out)
+ return out.t()
+
+
+def _pk():
+ from . import prefill_kernels
+ return prefill_kernels
+
+
+def raw16(lin, x, tm=None):
+ """prefill dense: x [M, K] -> raw fp16 GEMM output [M, N] (qdense_raw16 for stored Q8_0, fp16 dequant + GEMM for a requantised weight)"""
+ pk = _pk()
+ if lin.ty == 8:
+ return pk.qdense_raw16(x, lin.packed, tm)
+ x2 = pk.to_f16(x.reshape(-1, lin.shape[1])).contiguous()
+ return torch.mm(x2, dequant16(lin))
+
+
+def full(lin, x, tm=None):
+ """prefill dense: x [.., K] -> [.., N] fp32 (qdense_tm for stored Q8_0)"""
+ pk = _pk()
+ if lin.ty == 8:
+ return pk.qdense_tm(x, lin.packed, tm)
+ return qdense_kq(lin, x)
+
+
+def qdense_kq(lin, x):
+ pk = _pk()
+ lead = x.shape[:-1]
+ x2 = pk.to_f16(x.reshape(-1, lin.shape[1])).contiguous()
+ o = torch.mm(x2, dequant16(lin))
+ out = torch.nan_to_num(o.float(), nan=0.0, posinf=pk.F16MAX, neginf=-pk.F16MAX)
+ return out.reshape(*lead, lin.shape[0])
+
+
+def _gemv(kind, kern):
+ """decode GEMV with the QLinear signature (xf [M, K] fp32, packed [N, nb, bb], out [M, N] fp32): q8_1 quantisation of x, then the K-quant dot"""
+ fg = "fq_gemv_%s_q8" % kind
+ fm = "fq_mmvq_" + kind
+
+ def f(x, packed, out):
+ e = _ext()
+ M, K = x.shape
+ qb = e.fq_q8_scratch(x.get_device(), M, K)
+ e.fq_quant_q8_1_rows(x, qb)
+ p2 = packed.reshape(packed.shape[0], -1)
+ # Q5_K has no multi-row GEMV kernel (rows 2..16 re-read the weights once per row): rows >= 2 use the mmvq kernel
+ if kern == "mmvq" or (kind == "q5_k" and M >= 2):
+ for a in range(0, M, 8):
+ getattr(e, fm)(qb[a:a + 8], p2, out[a:a + 8])
+ else:
+ getattr(e, fg)(qb, p2, out)
+ return f
+
+
+def _owners():
+ out = []
+ for r in _OWNERS:
+ o = r()
+ if o is not None and type(o).__name__ != "GroupedView":
+ out.append(o)
+ return out
+
+
+def prepare(kinds, alt_dir=None):
+ """load the requantised bytes of every eligible owner to its device; returns (n_owners, n_prepared, {kind: bytes})"""
+ alt_dir = alt_dir or ALT_DIR
+ n_all = n_ok = 0
+ tot = {k: 0 for k in kinds}
+ seen = set()
+ for o in _owners():
+ if id(o) in seen:
+ continue
+ seen.add(id(o))
+ n_all += 1
+ names = list(getattr(o, "gnames", None) or ([o.gname] if getattr(o, "gname", None) else []))
+ if not names or o.ty != 8 or "alt" in o.__dict__:
+ continue
+ alts = {}
+ for k in kinds:
+ parts = []
+ for n in names:
+ p = os.path.join(alt_dir, k, n + ".bin")
+ if not os.path.exists(p):
+ parts = None
+ break
+ parts.append(np.fromfile(p, dtype=np.uint8))
+ if parts is None:
+ alts = None
+ break
+ K = o.shape[1]
+ arr = np.concatenate(parts).reshape(-1, K // 256, KQ[k]["bb"])
+ if arr.shape[0] != o.packed.shape[0]:
+ alts = None
+ break
+ alts[k] = torch.from_numpy(arr).to(o.packed.device)
+ tot[k] += arr.nbytes
+ if alts:
+ o.alt = alts
+ o.alt_q8 = (o.packed, o.ty, o.spec, o.gemv)
+ n_ok += 1
+ return n_all, n_ok, tot
+
+
+def _apply(o, packed, ty, spec, gemv):
+ o.packed, o.ty, o.spec, o.gemv = packed, ty, spec, gemv
+ o.shape = (packed.shape[0], packed.shape[1] * spec[0])
+ if hasattr(o, "members"): # an attn_grouped._Group: re-point the member views and drop the cached outputs
+ o.ref = None
+ for m, off, n in zip(o.members, o.offs, o.sizes):
+ m.packed, m.ty, m.spec, m.gemv = packed[off:off + n], ty, spec, gemv
+ m.shape = (n, o.shape[1])
+
+
+def set_mode(mode, kern="gemv"):
+ """switch every prepared owner to `mode`; returns the number switched"""
+ n = 0
+ for o in _owners():
+ if "alt" not in o.__dict__:
+ continue
+ if mode == "q8":
+ _apply(o, *o.alt_q8)
+ else:
+ _apply(o, o.alt[mode], {"q6_k": 14, "q5_k": 13}[mode], (256, KQ[mode]["bb"], "fq_gemv_" + mode, _dq_fn(mode)), _gemv(mode, kern))
+ n += 1
+ return n
+
+
+def resident_bytes(mode):
+ """dense weight bytes the decode step reads for the current mode (prepared owners only)"""
+ return sum(o.packed.numel() for o in _owners() if "alt" in o.__dict__)
diff --git a/exllamav3/loader/hy4_forward.py b/exllamav3/loader/hy4_forward.py
index 923aa9a..36cfad3 100644
--- a/exllamav3/loader/hy4_forward.py
+++ b/exllamav3/loader/hy4_forward.py
@@ -34,6 +34,7 @@ from . import head_bf16 as _HB
from . import attn_eager as _AE
from . import router_gemv as _RG
from . import mla_hy4 as _mla_mod
+from . import dense_req as _DR
_HCF = None
if os.environ.get("HY4_HC_FUSED", "0") == "1": # fused hyper-connection sites (loader/hc_fused.py)
@@ -248,6 +249,8 @@ class QLinear:
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])
+ self.gname = None
+ _DR.register(self)
@property
def T(self):
@@ -266,6 +269,8 @@ class QLinear:
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 in (13, 14) and x2.is_cuda: # requantised dense (HY4_DENSE_REQ_ARMS): fp16 dequant + fp16 GEMM, like the Q8_0 prefill path
+ out = _DR.qdense_kq(self, x2)
elif PF_DENSE and self.ty == 8 and x2.is_cuda:
k_ = _pk()
out = k_.qdense_i8(x2, self.packed) if PF_DENSE_I8 else (k_.qdense_tm(x2, self.packed, _TM_HOLD[0]) if x2.shape[0] >= k_.DENSE_TM_MIN_M else k_.qdense(x2, self.packed, k_.FMT_Q8))
@@ -304,7 +309,9 @@ def load_linear(g, name, dev, stats=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)
+ q = QLinear(torch.from_numpy(raw).reshape(N, K // spec[0], spec[1]).to(dev), ty, spec, fn, stats)
+ q.gname = name
+ return q
HEAD_CHUNK = 8192
diff --git a/exllamav3/loader/mla_hy4.py b/exllamav3/loader/mla_hy4.py
index 337aca9..6c2ab42 100644
--- a/exllamav3/loader/mla_hy4.py
+++ b/exllamav3/loader/mla_hy4.py
@@ -9,6 +9,7 @@ from .engram_rows import load_dense, _dequant_q8_0, q8_0_roundtrip, rms
from . import ref_fused as _rf
from . import mla_bgemv as _BG
from . import attn_eager as _ae
+from . import dense_req as _DR
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)
@@ -164,7 +165,7 @@ class Hy4MLA:
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)
+ q = _DR.raw16(self.wq_b, qr, tm)
with tm.t("f q: rope"):
P = self.rope_dim
rc = pos.__dict__.setdefault("_rope_tabs", {}) # the tables depend only on (positions, theta): one fp64 evaluation per step, not per layer
@@ -188,9 +189,9 @@ class Hy4MLA:
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))
+ gated = _pk.gate16(kv, _DR.raw16(self.wgate, cur, tm))
with tm.t("f gate: wo mm"):
- out = _pk.qdense_tm(gated, self.wo.packed, tm)
+ out = _DR.full(self.wo, gated, 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
diff --git a/tools/hy4/dense_requant.py b/tools/hy4/dense_requant.py
new file mode 100644
index 0000000..55bc3fb
--- /dev/null
+++ b/tools/hy4/dense_requant.py
@@ -0,0 +1,91 @@
+"""dense_requant.py GGUF OUTDIR KINDS [THREADS]: requantize the dense Q8_0 2-D tensors of a GGUF to Q6_K / Q5_K, CPU only (no GPU, no lock).
+
+The bytes are what `llama-quantize --allow-requantize --tensor-type <name>=<type>` writes for these tensors without an imatrix: ggml_quantize_chunk
+(libggml-base) on the fp32 dequantisation of the stored Q8_0 blocks. One file per tensor: OUTDIR/<kind>/<gguf tensor name>.bin = rows of
+[K / 256] blocks (Q6_K 210 B, Q5_K 176 B). Converted: 2-D Q8_0 tensors with K % 256 == 0 (not token_embd: a lookup, requant costs quality and saves no bytes
+per token). Skipped (stay Q8_0): K % 256 != 0 (k_b, compressors), 3-D tensors.
+Used by exllamav3/loader/dense_req.py (HY4_DENSE_REQ_ARMS=1). KINDS = q6_k,q5_k."""
+import ctypes
+import os
+import sys
+import time
+import types
+from concurrent.futures import ThreadPoolExecutor
+
+import numpy as np
+
+KIND = {"q6_k": (14, 210), "q5_k": (13, 176)} # ggml type id, bytes per 256-element block
+LIB = os.environ.get("GGML_LIB", "/path/to/libggml-base.so")
+
+
+def _collection(tree):
+ for n, s in (("exllamav3", ""), ("exllamav3.loader", "loader")):
+ m = types.ModuleType(n)
+ m.__path__ = [os.path.join(tree, "exllamav3", s)]
+ sys.modules[n] = m
+ from exllamav3.loader.gguf_collection import GGUFCollection
+ return GGUFCollection
+
+
+def q8_0_to_f32(raw: np.ndarray, N: int, K: int) -> np.ndarray:
+ b = raw.reshape(N, K // 32, 34)
+ d = np.ascontiguousarray(b[:, :, :2]).view(np.float16)[:, :, 0].astype(np.float32)
+ q = np.ascontiguousarray(b[:, :, 2:]).view(np.int8).astype(np.float32)
+ return (q * d[:, :, None]).reshape(N, K)
+
+
+def quantize(lib, kind, w: np.ndarray, pool, rows_per=64) -> np.ndarray:
+ ty, bb = KIND[kind]
+ N, K = w.shape
+ rb = K // 256 * bb
+ dst = np.empty((N, rb), dtype=np.uint8)
+ w = np.ascontiguousarray(w, dtype=np.float32)
+
+ def run(r0):
+ r1 = min(N, r0 + rows_per)
+ n = lib.ggml_quantize_chunk(ty, ctypes.c_void_p(w[r0:].ctypes.data), ctypes.c_void_p(dst[r0:].ctypes.data), 0, r1 - r0, K, None)
+ assert n == (r1 - r0) * rb, (n, r1 - r0, rb)
+
+ list(pool.map(run, range(0, N, rows_per)))
+ return dst
+
+
+def main():
+ gguf, out, kinds = sys.argv[1], sys.argv[2], sys.argv[3].split(",")
+ nth = int(sys.argv[4]) if len(sys.argv) > 4 else 8
+ tree = os.environ.get("TREE") or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ g = _collection(tree)(gguf)
+ lib = ctypes.CDLL(LIB)
+ lib.ggml_quantize_chunk.restype = ctypes.c_size_t
+ lib.ggml_quantize_chunk.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int64, ctypes.c_int64, ctypes.c_int64, ctypes.c_void_p]
+ for k in kinds:
+ os.makedirs(os.path.join(out, k), exist_ok=True)
+ pool = ThreadPoolExecutor(nth)
+ t0, tot_in, tot = time.time(), 0, {k: 0 for k in kinds}
+ done = skipped = 0
+ for name, (ty, dims, off) in sorted(g.infos.items()):
+ if ty != 8 or len(dims) != 2 or dims[0] % 256 or name == "token_embd.weight":
+ if ty == 8:
+ skipped += 1
+ continue
+ K, N = dims
+ raw = np.asarray(g._pread(off, N * (K // 32) * 34))
+ w = q8_0_to_f32(raw, N, K)
+ tot_in += raw.nbytes
+ for k in kinds:
+ p = os.path.join(out, k, name + ".bin")
+ if os.path.exists(p) and os.path.getsize(p) == N * (K // 256) * KIND[k][1]:
+ tot[k] += os.path.getsize(p)
+ continue
+ q = quantize(lib, k, w, pool)
+ q.tofile(p + ".tmp")
+ os.replace(p + ".tmp", p)
+ tot[k] += q.nbytes
+ done += 1
+ if done % 25 == 0:
+ print(f"{time.time() - t0:.0f}s {done} tensors", flush=True)
+ print(f"DONE tensors={done} skipped_q8={skipped} q8_bytes={tot_in / 1e9:.3f} GB " + " ".join(f"{k}={v / 1e9:.3f} GB" for k, v in tot.items()) + f" in {time.time() - t0:.0f}s", flush=True)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/hy4/req_arms.py b/tools/hy4/req_arms.py
new file mode 100644
index 0000000..8101f84
--- /dev/null
+++ b/tools/hy4/req_arms.py
@@ -0,0 +1,127 @@
+"""req_arms.py: dense Q8_0 -> Q6_K / Q5_K requant arms in ONE load (run inside the box job.sh with HY4_DENSE_REQ_ARMS=1, cwd = tree).
+
+ ARMS=quality teacher-forced wiki windows (llama-perplexity protocol: ctx 512, first half is context, second half scored; same wiki_ids.json): per arm NLL / PPL,
+ paired delta vs the Q8_0 reference, KL(ref || arm) per position, top-1 agreement; null band = two Q8_0 arms with 1e-6 embedding noise.
+ ARMS=speed plain graph and speculative decode tok/s per (mode, kernel), q8 first and last (drift check).
+Every arm switches dense_req.set_mode and drops the captured graphs."""
+import json, os, sys, time
+import numpy as np
+tree = os.getcwd()
+sys.path.insert(0, os.path.join(tree, "tools", "hy4"))
+import serve
+serve.apply_env(16384)
+import torch
+from engine import Hy4Engine
+import serve_core as C
+GGUF = "/path/to/models/hy4-flash-gguf/Hy4-flash-Q3_K-00001-of-00002.gguf"
+OUT = "out"
+e = Hy4Engine(tree, GGUF, ctx=16384, k=3)
+e.load(print)
+hf, SG, GR = e.hf, e.SG, e.GR
+from exllamav3.loader import dense_req as DR
+assert DR.ENABLED, "set HY4_DENSE_REQ_ARMS=1"
+t0 = time.time()
+n_all, n_ok, tot = DR.prepare(["q6_k", "q5_k"])
+print(f"prepared owners {n_ok}/{n_all} bytes {tot} in {time.time() - t0:.1f}s", flush=True)
+q8_bytes = sum(o.packed.numel() for o in DR._owners() if "alt" in o.__dict__)
+print("DENSE_BYTES q8", q8_bytes, {k: v for k, v in tot.items()}, flush=True)
+V = C.Vocab(e.meta)
+wiki = json.load(open("/path/to/wiki_ids.json"))
+ARMS = os.environ.get("ARMS", "quality").split(",")
+dev = e.dev
+
+
+def setmode(mode, kern="gemv"):
+ DR.set_mode(mode, kern)
+ GR.clear()
+
+
+# ---- sanity: dequant / GEMV of each requantised encoding against the Q8_0 weight it came from
+own = [o for o in DR._owners() if "alt" in o.__dict__ and type(o).__name__ == "QLinear"][:3]
+for o in own:
+ x = torch.randn(1, o.shape[1], device=dev)
+ res = {}
+ for m in ("q8", "q6_k", "q5_k"):
+ DR.set_mode(m)
+ w = o.dense()
+ res[m] = (w, torch.empty(1, o.shape[0], device=dev))
+ o.gemv(x.contiguous(), o.packed, res[m][1])
+ w8, y8 = res["q8"][0], res["q8"][1]
+ print("CHECK", o.gname, {m: dict(w_rel=round(float((res[m][0] - w8).norm() / w8.norm()), 5), y_rel=round(float((res[m][1] - y8).norm() / y8.norm()), 5)) for m in ("q6_k", "q5_k")}, flush=True)
+setmode("q8")
+
+# ---- quality
+W = int(os.environ.get("WIN", "6")); CTX, HALF, R = 512, 256, 4
+
+
+def run_arm(name, ref=None, seed=None):
+ SG.PERT = None if seed is None else (torch.randn(GR.cap, e.M.D, generator=torch.Generator().manual_seed(seed)) * 1e-6).to(dev)
+ GR.clear()
+ nl, kl, same, lps = [], [], [], []
+ t = time.time()
+ for w in range(W):
+ ids = wiki[w * CTX:w * CTX + CTX + 1]
+ e._t0 = time.perf_counter(); e.reset(); e.prefill(ids[:HALF]); e.phase("decode")
+ for i in range(0, CTX - HALF, R):
+ lg, _am, _x, _h = GR.step_rows(ids[HALF + i:HALF + i + R])
+ lp = torch.log_softmax(lg.reshape(R, -1).float(), -1)
+ tgt = torch.tensor(ids[HALF + i + 1:HALF + i + R + 1], device=dev)
+ nl.extend((-lp[torch.arange(R, device=dev), tgt]).tolist())
+ if ref is None:
+ lps.append(lp.cpu())
+ else:
+ lr = ref[len(nl) - R:len(nl)].to(dev)
+ kl.extend((lr.exp() * (lr - lp)).sum(-1).tolist())
+ same.extend((lr.argmax(-1) == lp.argmax(-1)).tolist())
+ SG.PERT = None
+ GR.clear()
+ nl = np.array(nl)
+ r = dict(arm=name, n=len(nl), nll=round(float(nl.mean()), 5), ppl=round(float(np.exp(nl.mean())), 4), secs=round(time.time() - t, 1))
+ return nl, kl, same, (torch.cat(lps) if ref is None else None), r
+
+
+def report(name, nl, ref_nl, kl, same, r):
+ if ref_nl is not None:
+ d = nl - ref_nl
+ r.update(d_nll=round(float(d.mean()), 5), d_se=round(float(d.std(ddof=1) / np.sqrt(len(d))), 5),
+ kl_mean=round(float(np.mean(kl)), 6), kl_p99=round(float(np.percentile(kl, 99)), 5), top1_same=round(float(np.mean(same)), 4))
+ print("QRES", json.dumps(r), flush=True)
+ return r
+
+
+if "quality" in ARMS:
+ res = {}
+ nl_ref, _, _, lp_ref, r = run_arm("q8_ref")
+ report("q8_ref", nl_ref, None, None, None, r)
+ json.dump({"q8_ref": nl_ref.tolist()}, open(f"{OUT}/req_nll_ref.json", "w"))
+ plan = [("q8_noise1", "q8", 1), ("q8_noise2", "q8", 2)] + [(f"{m}_{k}", m, None) for m, k in (("q6_k", "gemv"), ("q5_k", "gemv"))]
+ for name, mode, seed in plan:
+ setmode(mode)
+ nl, kl, same, _, r = run_arm(name, lp_ref, seed)
+ res[name] = report(name, nl, nl_ref, kl, same, r)
+ json.dump({"nll": nl.tolist(), "kl": kl}, open(f"{OUT}/req_nll_{name}.json", "w"))
+ nz = [res[k]["kl_mean"] for k in res if "noise" in k]
+ for k in res:
+ if "noise" not in k and nz:
+ print("QKL_VS_NOISE", k, "kl", res[k]["kl_mean"], "x noise-null", round(res[k]["kl_mean"] / max(max(nz), 1e-12), 1), flush=True)
+ setmode("q8")
+
+# ---- speed
+if "speed" in ARMS:
+ ids = V.encode(V.template.render([{"role": "user", "content": "Explain in a few short paragraphs why the sky is blue and why sunsets are red."}], None, True, reasoning_effort="no_think"))
+ NT = int(os.environ.get("NT", "100"))
+
+ def gen(spec, n):
+ out = []
+ st = e.generate(ids, n, lambda t: out.extend(t) or False, speculative=spec)
+ return out, st["decode_tokens"] / st["decode_s"], st
+
+ order = [("q8", "gemv"), ("q6_k", "gemv"), ("q6_k", "mmvq"), ("q5_k", "gemv"), ("q5_k", "mmvq"), ("q8", "gemv")]
+ for mode, kern in order:
+ setmode(mode, kern)
+ gen(False, 20)
+ _, tps, st = gen(False, NT)
+ gen(True, 30)
+ _, tps2, st2 = gen(True, 150)
+ print("SRES", json.dumps(dict(mode=mode, kern=kern, plain_tok_s=round(tps, 2), spec_tok_s=round(tps2, 2), tau=round(st2["tau"], 2), rounds=st2["rounds"])), flush=True)
+print("REQ_DONE", flush=True)