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 requant arms: shared ggml quantizer in dense_req, MTP draft head Q6_K / Q5_K arms, round_ms in the speed arms

YanissAmz2d7486d100ab
diff --git a/exllamav3/loader/dense_req.py b/exllamav3/loader/dense_req.py
index 0a44e1d..ab30133 100644
--- a/exllamav3/loader/dense_req.py
+++ b/exllamav3/loader/dense_req.py
@@ -22,6 +22,36 @@ _OWNERS: list = []
_EXT = []
+GGML_LIB = os.environ.get("GGML_LIB", "/path/to/libggml-base.so")
+_KIND_TY = {"q6_k": 14, "q5_k": 13} # ggml type ids
+_LIB = []
+
+
+def quantize_rows(w, kind, nth=12, rows_per=64):
+ """fp32 numpy [N, K] (K % 256 == 0) -> uint8 [N, K / 256 * bb]: ggml_quantize_chunk (libggml-base, no imatrix) = the bytes of llama-quantize --allow-requantize"""
+ import ctypes
+ from concurrent.futures import ThreadPoolExecutor
+ if not _LIB:
+ lib = ctypes.CDLL(GGML_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]
+ _LIB.append(lib)
+ lib = _LIB[0]
+ N, K = w.shape
+ rb = K // 256 * KQ[kind]["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(_KIND_TY[kind], 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)
+
+ with ThreadPoolExecutor(nth) as pool:
+ list(pool.map(run, range(0, N, rows_per)))
+ return dst
+
+
def register(owner):
if ENABLED:
_OWNERS.append(weakref.ref(owner))
@@ -179,3 +209,25 @@ def set_mode(mode, kern="gemv"):
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__)
+
+
+def head_arms(mt, kinds):
+ """MTP draft head (HY4_MTP_HEAD=q8: a Q8_0 copy of the trunk's bf16 vocab head): add K-quant copies quantised from the bf16 original. Returns bytes per mode."""
+ from .hy4_forward import QLinear
+ W = mt.fw.out_w
+ V, D = W.shape
+ mt.head_q8_orig, mt.head_alt = mt.head_q8, {}
+ for k in kinds:
+ arr = np.concatenate([quantize_rows(W[a:a + 8192].float().cpu().numpy(), k) for a in range(0, V, 8192)]).reshape(V, D // 256, KQ[k]["bb"])
+ mt.head_alt[k] = QLinear(torch.from_numpy(arr).to(W.device), _KIND_TY[k], (256, KQ[k]["bb"], "fq_gemv_" + k, _dq_fn(k)), _gemv(k, "gemv"), None)
+ return {"q8": mt.head_q8_orig.packed.numel(), **{k: v.packed.numel() for k, v in mt.head_alt.items()}}
+
+
+def set_head(mt, mg, mode):
+ """draft head bytes = `mode` ("q8" | "q6_k" | "q5_k"); the draft chain graphs are dropped (they bake the head kernel and pointer)"""
+ mt.head_q8 = mt.head_q8_orig if mode == "q8" else mt.head_alt[mode]
+ mg.graphs.clear()
+ mg.pool = torch.cuda.graph_pool_handle()
+ import gc
+ gc.collect()
+ torch.cuda.empty_cache()
diff --git a/tools/hy4/dense_requant.py b/tools/hy4/dense_requant.py
index 55bc3fb..0bf8da6 100644
--- a/tools/hy4/dense_requant.py
+++ b/tools/hy4/dense_requant.py
@@ -5,17 +5,14 @@ The bytes are what `llama-quantize --allow-requantize --tensor-type <name>=<type
[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):
@@ -34,33 +31,14 @@ def q8_0_to_f32(raw: np.ndarray, N: int, K: int) -> np.ndarray:
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]
+ from exllamav3.loader.dense_req import quantize_rows
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()):
@@ -77,7 +55,7 @@ def main():
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 = quantize_rows(w, k, nth)
q.tofile(p + ".tmp")
os.replace(p + ".tmp", p)
tot[k] += q.nbytes
diff --git a/tools/hy4/req_arms.py b/tools/hy4/req_arms.py
index 8101f84..fb457c1 100644
--- a/tools/hy4/req_arms.py
+++ b/tools/hy4/req_arms.py
@@ -116,12 +116,18 @@ if "speed" in ARMS:
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:
+ hb = DR.head_arms(e.MT, ["q6_k", "q5_k"]) if e.MT.head_q8 is not None else None
+ print("HEAD_BYTES", hb, flush=True)
+ order = [("q8", "gemv", "q8"), ("q6_k", "gemv", "q8"), ("q6_k", "mmvq", "q8"), ("q5_k", "gemv", "q8"), ("q5_k", "mmvq", "q8"),
+ ("q8", "gemv", "q6_k"), ("q8", "gemv", "q5_k"), ("q8", "gemv", "q8")] if hb else [("q8", "gemv", "q8")]
+ for mode, kern, head in order:
setmode(mode, kern)
+ if hb:
+ DR.set_head(e.MT, e.MG, head)
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("SRES", json.dumps(dict(mode=mode, kern=kern, head=head, plain_tok_s=round(tps, 2), spec_tok_s=round(tps2, 2), tau=round(st2["tau"], 2), rounds=st2["rounds"],
+ round_ms=[round(x, 1) for x in st2.get("round_ms", [])])), flush=True)
print("REQ_DONE", flush=True)