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.

qualify: day-0 autotune stage (shape replay), per-pack GEMM tuning cache loaded at serve start, cold-vs-tuned A/B and oracle tools

YanissAmzeed4388cf412
diff --git a/exllamav3/util/tune_cache.py b/exllamav3/util/tune_cache.py
new file mode 100644
index 0000000..cc21460
--- /dev/null
+++ b/exllamav3/util/tune_cache.py
@@ -0,0 +1,125 @@
+"""Per-pack tuning cache for the EXL3 GEMM autotuner (day-0 autotune, qualify --stage autotune).
+
+The cooperative GEMM autotuner (exllamav3_ext/quant/coop_autotune.cu) times its candidate kernels on the first call of every
+(row class, K, N, bits, dtype, device, cc, SMs, codebook) and appends the winner to a disk cache (EXLLAMAV3_TUNE_CACHE, default
+~/.cache/exllamav3/autotune/coop_autotune_v1.bin). A model with new shapes pays that timing inside its first requests / graph warm-up.
+The qualify autotune stage runs the tuner for every shape of a pack ahead of time and ships the winners next to the pack:
+
+ <pack>/tuning/<signature>.bin same record format as the live cache (32-byte records, header EX3ATUNE)
+ <pack>/tuning/<signature>.json manifest: device, shapes, per-shape timings, engine version
+
+install_pack(model_dir) merges the file whose signature matches this device into the live cache before the first GEMM
+(records already present win; nothing is overwritten). A record is validated against the live candidates by the C++ loader
+(tag, block_dim, SM count, concurrency), and the key is salted with COOP_AUTOTUNE_VERSION, so a stale or foreign file only misses.
+EXL3_PACK_TUNE=0 turns the merge off (cold-cache A/B).
+"""
+from __future__ import annotations
+import json, os, re, struct
+from pathlib import Path
+
+MAGIC = b"EX3ATUNE"
+FORMAT = 1
+REC = struct.Struct("<Q4i2I") # hash, tag, block_dim, num_sms, concurrency, reserved x2 (DiskCacheRecordV1)
+HDR = struct.Struct("<8sII") # magic, format, record_size
+TUNING_DIR = "tuning"
+
+
+def live_cache_path() -> Path:
+ """Same resolution as disk_cache_path() in coop_autotune.cu (POSIX)."""
+ o = os.environ.get("EXLLAMAV3_TUNE_CACHE")
+ if o:
+ p = Path(o)
+ return p / "coop_autotune_v1.bin" if p.is_dir() else p
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path(os.environ.get("HOME", "/tmp")) / ".cache")
+ return Path(base) / "exllamav3" / "autotune" / "coop_autotune_v1.bin"
+
+
+def read_records(path) -> dict:
+ """hash -> record bytes. Tolerates an embedded header (two first writers) and a torn tail, like the C++ reader."""
+ p = Path(path)
+ if not p.is_file():
+ return {}
+ b = p.read_bytes()
+ if len(b) < HDR.size:
+ return {}
+ magic, fmt, rsz = HDR.unpack_from(b, 0)
+ if magic != MAGIC or fmt != FORMAT or rsz < REC.size:
+ return {}
+ out, off = {}, HDR.size
+ while off + rsz <= len(b):
+ chunk = b[off:off + rsz]
+ if chunk[:8] == MAGIC: # embedded header: skip it, keep reading records after it
+ off += HDR.size
+ continue
+ out[struct.unpack_from("<Q", chunk)[0]] = chunk[:REC.size]
+ off += rsz
+ return out
+
+
+def write_records(path, recs: dict) -> None:
+ """Atomic rewrite (tmp + rename), header first."""
+ p = Path(path)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ tmp = p.with_name(p.name + f".tmp{os.getpid()}")
+ tmp.write_bytes(HDR.pack(MAGIC, FORMAT, REC.size) + b"".join(recs.values()))
+ os.replace(tmp, p)
+
+
+def decode(rec: bytes) -> dict:
+ h, tag, bd, sms, conc, _, _ = REC.unpack(rec)
+ return dict(hash=f"{h:016x}", tag=tag, block_dim=bd, num_sms=sms, concurrency=conc)
+
+
+def signature(device: int | None = None) -> dict:
+ """What a tuned record depends on besides its (salted) key: the device model, compute capability and SM/CU count."""
+ import torch
+ d = torch.cuda.current_device() if device is None else device
+ pr = torch.cuda.get_device_properties(d)
+ arch = getattr(pr, "gcnArchName", None)
+ cc = arch.split(":")[0] if arch else f"sm{pr.major}{pr.minor}"
+ slug = re.sub(r"[^a-z0-9]+", "-", pr.name.lower()).strip("-")
+ return dict(name=pr.name, cc=cc, sms=pr.multi_processor_count, device_index=d,
+ backend="rocm" if arch else "cuda", file=f"{cc}-{pr.multi_processor_count}sm-{slug}")
+
+
+def pack_files(model_dir, sig: dict | None = None) -> list[Path]:
+ d = Path(model_dir) / TUNING_DIR
+ if not d.is_dir():
+ return []
+ sig = sig or signature()
+ p = d / f"{sig['file']}.bin"
+ return [p] if p.is_file() else []
+
+
+def merge_into(dst, srcs) -> int:
+ """Add the records of srcs missing from dst (never overwrites). Returns the number added."""
+ have = read_records(dst)
+ new = {}
+ for s in srcs:
+ for k, v in read_records(s).items():
+ if k not in have and k not in new:
+ new[k] = v
+ if not new:
+ return 0
+ if have: # append, like the C++ writer: concurrent servers keep working
+ with open(dst, "ab") as f:
+ f.write(b"".join(new.values()))
+ else:
+ write_records(dst, new)
+ return len(new)
+
+
+def install_pack(model_dir, log=print) -> int:
+ """Call before the first GEMM of the process (the C++ cache is read once, lazily). Returns records added to the live cache."""
+ if os.environ.get("EXL3_PACK_TUNE", "1") == "0":
+ return 0
+ try:
+ files = pack_files(model_dir)
+ if not files:
+ return 0
+ n = merge_into(live_cache_path(), files)
+ log(f"tune cache: {n} records from {files[0].name} merged into {live_cache_path()}")
+ return n
+ except Exception as e: # noqa: BLE001 a bad tuning file must never stop a serve start
+ log(f"tune cache: pack cache ignored ({e})")
+ return 0
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 615a448..bc51bd6 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -700,7 +700,8 @@ class ResidentEngine:
self.lookup_stats: dict[str, int] = {}
self.cache = Cache(self.model, max_num_tokens=ctx + 4096,
max_history=max_history, max_batch_size=slots)
- from exllamav3.util import jit_log, kernel_seed
+ from exllamav3.util import jit_log, kernel_seed, tune_cache
+ tune_cache.install_pack(model_path) # <pack>/tuning: GEMM autotune winners from qualify --stage autotune
kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first start
jit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile
startup_health.stage("target weights")
diff --git a/tools/qualify/ab_autotune.py b/tools/qualify/ab_autotune.py
new file mode 100644
index 0000000..d58e584
--- /dev/null
+++ b/tools/qualify/ab_autotune.py
@@ -0,0 +1,90 @@
+"""One arm of the cold-vs-tuned A/B: serve the pack with a FRESH tune cache, with or without the pack's shipped tuning, and time the
+start-up and the first requests (where an untuned shape pays its timing) against the steady state. Run under the GPU lock by the caller.
+
+ python ab_autotune.py {cold|tuned} PACK OUT.json [--repo DIR] [--ctx 16384] [--sessions 4] [--port 8591]
+
+cold : EXL3_PACK_TUNE=0, empty EXLLAMAV3_TUNE_CACHE -> every shape is timed at first use (what a new model does today)
+tuned : same empty live cache, pack tuning merged at serve start (qualify --stage autotune output)
+Both arms share everything else (flags, prompts, order). The A/B shares nothing through ~/.cache (dense20: an A/B must not share one tune cache).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+import sys
+import tempfile
+import time
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE))
+
+import backends # noqa: E402
+import load # noqa: E402
+import pack as packmod # noqa: E402
+from server import oom_in, running_server # noqa: E402
+
+
+def records_in(d: Path) -> int:
+ p = d / "coop_autotune_v1.bin"
+ return max(0, (p.stat().st_size - 16) // 32) if p.is_file() else 0
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("arm", choices=["cold", "tuned"])
+ ap.add_argument("pack")
+ ap.add_argument("out")
+ ap.add_argument("--backend", default="cuda")
+ ap.add_argument("--repo", default=str(HERE.parents[1]))
+ ap.add_argument("--ctx", type=int, default=16384)
+ ap.add_argument("--sessions", type=int, default=4)
+ ap.add_argument("--port", type=int, default=8591)
+ a = ap.parse_args()
+ meta = packmod.read_pack(a.pack)
+ prof = backends.profile(a.backend, a.repo)
+ cache = Path(tempfile.mkdtemp(prefix=f"at0_{a.arm}_"))
+ prof["env"] = {**prof["env"], "EXLLAMAV3_TUNE_CACHE": str(cache), "EXL3_PACK_TUNE": "0" if a.arm == "cold" else "1"}
+ argv = packmod.serve_flags(meta, port=a.port, ctx=a.ctx, sessions=a.sessions, k_bits=4, v_bits=4)
+ log = Path(a.out).with_suffix(".srv.log")
+ res = dict(arm=a.arm, pack=a.pack, ctx=a.ctx, sessions=a.sessions, cmd=argv, cache_dir=str(cache), seq=[])
+ t0 = time.time()
+ with running_server(prof, Path(a.repo), argv, a.port, log, logf=print) as (p, ok):
+ res["load_s"] = round(time.time() - t0, 1)
+ res["records_after_load"] = records_in(cache)
+ if not ok:
+ res["error"] = "server not ready"
+ Path(a.out).write_text(json.dumps(res, indent=1))
+ return 1
+ cl = load.Client(a.port)
+ cl.calibrate(1000) # also the very first request of the process (the cold arm pays tuning here)
+ res["records_after_calibrate"] = records_in(cache)
+ plan = [("short128", 128, 128)] * 2 + [("p1k", 1024, 192)] * 3 + [("p4k", 4096, 128)] * 4 + [("p8k", 8192, 64)] * 2
+ for i, (name, ptok, new) in enumerate(plan):
+ r = cl.stream(cl.prompt(ptok, i), new)
+ res["seq"].append(dict(i=i, name=name, ptok=r["ptok"], ntok=r["ntok"], ttft=r["ttft"], dec_tps=r["dec_tps"], total=r["total"], err=r["err"]))
+ print(res["seq"][-1], flush=True)
+ n4 = [cl.concurrent(a.sessions, 1024, 128) for _ in range(3)]
+ res["n4"] = [dict(agg=x["agg_dec_tps"], per=x["dec_tps"], ttft=x["ttft"], err=x["errors"]) for x in n4]
+ res["records_end"] = records_in(cache)
+ res["oom"] = oom_in(log)
+ by = lambda n: [s for s in res["seq"] if s["name"] == n]
+ med = lambda xs: round(statistics.median(xs), 3) if xs else None
+ res["summary"] = dict(
+ first_request_ttft=res["seq"][0]["ttft"], first_decode_tps=res["seq"][0]["dec_tps"],
+ steady_decode_tps=med([s["dec_tps"] for s in by("p4k")[1:] if s["dec_tps"]]),
+ p1k_ttft_first=by("p1k")[0]["ttft"], p1k_ttft_steady=med([s["ttft"] for s in by("p1k")[1:]]),
+ p4k_ttft_first=by("p4k")[0]["ttft"], p4k_ttft_steady=med([s["ttft"] for s in by("p4k")[1:]]),
+ p4k_prefill_tps_steady=med([s["ptok"] / s["ttft"] for s in by("p4k")[1:] if s["ptok"]]),
+ p8k_prefill_tps_steady=med([s["ptok"] / s["ttft"] for s in by("p8k")[1:] if s["ptok"]]),
+ n4_agg_steady=med([x["agg"] for x in res["n4"][1:] if x["agg"]]),
+ runtime_tuned_records=res["records_end"] - res["records_after_load"],
+ )
+ Path(a.out).write_text(json.dumps(res, indent=1))
+ print(json.dumps(res["summary"]))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tools/qualify/autotune.py b/tools/qualify/autotune.py
new file mode 100644
index 0000000..19019d4
--- /dev/null
+++ b/tools/qualify/autotune.py
@@ -0,0 +1,148 @@
+"""Day-0 autotune of one pack on this device (qualify stage `autotune`).
+
+Reads every tensor shape of the pack from its safetensors headers (no weights are loaded), runs the engine's GEMM autotuner for each
+distinct (in, out, K, codebook) at every row class a request can reach, and writes the winners next to the pack:
+ <pack>/tuning/<device signature>.bin (+ .json manifest with per-shape timings)
+Serve start merges that file into the live cache (exllamav3/util/tune_cache.install_pack), so the first request of a new head_dim /
+hidden size / expert count runs on tuned kernels with no hand work.
+
+Pure helpers (shapes, row classes, manifest) are CPU-testable; `run()` needs the engine venv and a free GPU.
+ python autotune.py PACK [--dtypes half,float] [--rows 1,2,4,...] [--out DIR] [--repeat 20]
+"""
+from __future__ import annotations
+
+import argparse
+import collections
+import glob
+import json
+import os
+import struct
+import sys
+import time
+from pathlib import Path
+
+# Row classes of the GEMM autotune key (exl3_gemm.cu gemm_autotune_hash): <=16 -> next pow2, 17..24 -> 24, then 16-steps capped at 64.
+# The BC path (CUDA/ROCm exl3_gemm) serves rows <= AUTO_RECONSTRUCT_THRESHOLD (192 CUDA / 144 ROCm); beyond that reconstruct + dense GEMM.
+ROW_CLASSES = (1, 2, 4, 8, 16, 24, 32, 48, 64)
+
+
+def row_class(m: int) -> int:
+ """Python mirror of the row term in gemm_autotune_hash (size_m is clamped to >= 2 by the caller)."""
+ m = max(m, 2)
+ if m <= 16:
+ c = 1
+ while c < m:
+ c <<= 1
+ return c
+ return 24 if m <= 24 else min(-(-m // 16) * 16, 64)
+
+
+def pack_shapes(pack: str | os.PathLike) -> dict:
+ """{(in, out, K, mcg, mul1): count} for every dense EXL3 tensor, from the safetensors headers. Expert stacks are reported apart."""
+ dense, experts = collections.Counter(), collections.Counter()
+ for f in sorted(glob.glob(str(Path(pack) / "*.safetensors"))):
+ with open(f, "rb") as fh:
+ n = struct.unpack("<Q", fh.read(8))[0]
+ hdr = json.loads(fh.read(n))
+ for k, v in hdr.items():
+ if not k.endswith(".trellis"):
+ continue
+ shp = v["shape"]
+ base = k[:-len(".trellis")]
+ if len(shp) == 3:
+ key = (shp[0] * 16, shp[1] * 16, shp[2] / 16, (base + ".mcg") in hdr, (base + ".mul1") in hdr)
+ (experts if ".experts." in k else dense)[key] += 1
+ else:
+ experts[("stack", tuple(shp))] += 1
+ return dict(dense=dict(dense), experts=dict(experts))
+
+
+def tune_plan(shapes: dict, rows=ROW_CLASSES, dtypes=("half", "float")) -> list:
+ """Ordered list of (in, out, K, mcg, mul1, rows, dtype) the tuner must run (integral K only: half-integer K takes the Python path)."""
+ out = []
+ for (i, o, K, mcg, mul1), _n in sorted(shapes["dense"].items(), key=lambda kv: (-kv[0][0] * kv[0][1], kv[0])):
+ if float(K) != int(K):
+ continue
+ for dt in dtypes:
+ for r in rows:
+ out.append((i, o, int(K), mcg, mul1, r, dt))
+ return out
+
+
+def run(pack: str, out_dir: str | None = None, dtypes=("half", "float"), rows=ROW_CLASSES, repeat: int = 20, log=print) -> dict:
+ """Tune every shape. The tuner is pointed at a scratch cache (EXLLAMAV3_TUNE_CACHE) so the file holds exactly this pack's winners."""
+ t0 = time.time()
+ pack = str(pack)
+ out = Path(out_dir) if out_dir else Path(pack) / "tuning"
+ out.mkdir(parents=True, exist_ok=True)
+ scratch = out / f".scratch-{os.getpid()}.bin"
+ scratch.unlink(missing_ok=True)
+ os.environ["EXLLAMAV3_TUNE_CACHE"] = str(scratch) # before the first GEMM: the C++ side reads the path once, lazily
+ import torch
+ from exllamav3.util import tune_cache
+ from exllamav3.modules.quant.exl3 import LinearEXL3
+ sig = tune_cache.signature()
+ shapes = pack_shapes(pack)
+ plan = tune_plan(shapes, rows, dtypes)
+ log(f"autotune {pack}: {len(shapes['dense'])} dense shapes, {len(plan)} (shape,rows,dtype) points on {sig['name']} ({sig['cc']}, {sig['sms']} SMs)")
+ res = []
+ dev = torch.device("cuda", sig["device_index"])
+ torch.manual_seed(0)
+ cur = None
+ for (i, o, K, mcg, mul1, r, dt) in plan:
+ if cur is None or cur[0] != (i, o, K, mcg, mul1):
+ tr = torch.randint(-32768, 32767, (i // 16, o // 16, 16 * K), dtype=torch.int16, device=dev)
+ suh = (torch.randint(0, 2, (i,), device=dev) * 2 - 1).half()
+ svh = (torch.randint(0, 2, (o,), device=dev) * 2 - 1).half()
+ mc = torch.tensor(0xC0DE, dtype=torch.int32, device=dev) if mcg else None
+ m1 = torch.tensor(0xC0DE, dtype=torch.int32, device=dev) if mul1 else None
+ cur = ((i, o, K, mcg, mul1), LinearEXL3(None, i, o, suh=suh, svh=svh, trellis=tr, mcg=mc, mul1=m1))
+ lin = cur[1]
+ x = torch.randn(r, i, dtype=torch.half, device=dev) * 0.1
+ f32 = dt == "float"
+ torch.cuda.synchronize()
+ t1 = time.perf_counter()
+ lin.bc.run_alloc(x, o, f32) # first call at this key: the autotuner times its candidates here
+ torch.cuda.synchronize()
+ first_ms = (time.perf_counter() - t1) * 1e3
+ t1 = time.perf_counter()
+ for _ in range(repeat):
+ lin.bc.run_alloc(x, o, f32)
+ torch.cuda.synchronize()
+ steady_us = (time.perf_counter() - t1) / repeat * 1e6
+ res.append(dict(i=i, o=o, K=K, mcg=mcg, mul1=mul1, rows=r, dtype=dt, first_ms=round(first_ms, 2), steady_us=round(steady_us, 1)))
+ recs = tune_cache.read_records(scratch)
+ dst = out / f"{sig['file']}.bin"
+ tune_cache.write_records(dst, recs)
+ scratch.unlink(missing_ok=True)
+ man = dict(schema=1, signature=sig, records=len(recs), plan_points=len(plan), wall_s=round(time.time() - t0, 1),
+ shapes=[dict(i=k[0], o=k[1], K=k[2], mcg=k[3], mul1=k[4], tensors=n) for k, n in shapes["dense"].items()],
+ experts_not_tuned=len(shapes["experts"]), points=res, torch=torch.__version__,
+ engine_git=_git(Path(__file__).resolve().parents[2]))
+ (out / f"{sig['file']}.json").write_text(json.dumps(man, indent=1))
+ log(f"autotune: {len(recs)} records -> {dst} in {man['wall_s']} s")
+ return man
+
+
+def _git(repo: Path) -> str | None:
+ import subprocess
+ try:
+ return subprocess.run(["git", "-C", str(repo), "rev-parse", "--short", "HEAD"], capture_output=True, text=True, timeout=10).stdout.strip() or None
+ except Exception: # noqa: BLE001
+ return None
+
+
+if __name__ == "__main__":
+ if "--signature" in sys.argv: # device signature of this process (the stage runs it with the backend's python)
+ from exllamav3.util import tune_cache
+ print(json.dumps(tune_cache.signature()))
+ sys.exit(0)
+ ap = argparse.ArgumentParser()
+ ap.add_argument("pack")
+ ap.add_argument("--out")
+ ap.add_argument("--dtypes", default="half,float")
+ ap.add_argument("--rows", default=",".join(map(str, ROW_CLASSES)))
+ ap.add_argument("--repeat", type=int, default=20)
+ a = ap.parse_args()
+ m = run(a.pack, a.out, tuple(a.dtypes.split(",")), tuple(int(x) for x in a.rows.split(",")), a.repeat)
+ print(json.dumps({k: m[k] for k in ("records", "plan_points", "wall_s")}))
diff --git a/tools/qualify/oracle_gemm.py b/tools/qualify/oracle_gemm.py
new file mode 100644
index 0000000..e04ae29
--- /dev/null
+++ b/tools/qualify/oracle_gemm.py
@@ -0,0 +1,85 @@
+"""Quality check of a tuning cache: per (shape, row class), time the cached autotuner choice against an exhaustive grid of forced kernel
+shapes (exl3_gemm force_shape_idx 1..N x force_num_sms in {all SMs, half}). tuned/oracle ~ 1.0 means the cache picks what a hand sweep would.
+
+ EXLLAMAV3_TUNE_CACHE=<file with the pack's winners> python oracle_gemm.py PACK OUT.json [--rows 1,2,...] [--dtype half]
+Run under the GPU lock. Needs the engine venv (PYTHONPATH = engine checkout).
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import statistics
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import autotune # noqa: E402
+
+
+def run(pack, out, rows, dtype="half", repeat=60, log=print):
+ import torch
+ from exllamav3.ext import exllamav3_ext as ext
+ from exllamav3.util import tune_cache
+ sig = tune_cache.signature()
+ dev = torch.device("cuda", sig["device_index"])
+ shapes = autotune.pack_shapes(pack)
+ nshape = ext.exl3_gemm_num_kernel_shapes()
+ res = []
+ torch.manual_seed(0)
+
+ def timeit(fn):
+ for _ in range(3):
+ fn()
+ torch.cuda.synchronize()
+ best = []
+ for _ in range(5): # median of 5 bursts: robust to a neighbour's clock changes
+ t = time.perf_counter()
+ for _ in range(repeat):
+ fn()
+ torch.cuda.synchronize()
+ best.append((time.perf_counter() - t) / repeat * 1e6)
+ return statistics.median(best)
+
+ for (i, o, K, mcg, mul1), _n in sorted(shapes["dense"].items(), key=lambda kv: -kv[0][0] * kv[0][1]):
+ if float(K) != int(K):
+ continue
+ K = int(K)
+ tr = torch.randint(-32768, 32767, (i // 16, o // 16, 16 * K), dtype=torch.int16, device=dev)
+ suh = (torch.randint(0, 2, (i,), device=dev) * 2 - 1).half()
+ svh = (torch.randint(0, 2, (o,), device=dev) * 2 - 1).half()
+ for r in rows:
+ x = torch.randn(r, i, dtype=torch.half, device=dev) * 0.1
+ xh = torch.empty_like(x)
+ y = torch.empty(r, o, dtype=torch.float if dtype == "float" else torch.half, device=dev)
+ tuned_tag = ext.exl3_gemm(x, tr, y, suh, xh, svh, -1, mcg, mul1, 0)
+ tuned = timeit(lambda: ext.exl3_gemm(x, tr, y, suh, xh, svh, -1, mcg, mul1, 0))
+ grid = {}
+ for s in range(1, nshape + 1):
+ if not ext.exl3_gemm_shape_compat(s, r, i, o, K):
+ continue
+ for sms in (sig["sms"], sig["sms"] // 2):
+ try:
+ grid[f"{s}x{sms}"] = timeit(lambda: ext.exl3_gemm(x, tr, y, suh, xh, svh, s, mcg, mul1, sms))
+ except Exception: # noqa: BLE001 a candidate that cannot launch at this shape is not part of the grid
+ pass
+ best = min(grid, key=grid.get) if grid else None
+ res.append(dict(i=i, o=o, K=K, rows=r, tuned_tag=int(tuned_tag), tuned_us=round(tuned, 1), oracle=best,
+ oracle_us=round(grid[best], 1) if best else None, ratio=round(tuned / grid[best], 3) if best else None))
+ log(res[-1])
+ ratios = [x["ratio"] for x in res if x["ratio"]]
+ summ = dict(points=len(res), median_ratio=round(statistics.median(ratios), 3), worst_ratio=max(ratios), over_1_05=sum(1 for q in ratios if q > 1.05))
+ Path(out).write_text(json.dumps(dict(summary=summ, points=res), indent=1))
+ log(json.dumps(summ))
+ return summ
+
+
+if __name__ == "__main__":
+ ap = argparse.ArgumentParser()
+ ap.add_argument("pack")
+ ap.add_argument("out")
+ ap.add_argument("--rows", default="1,2,4,8,16,24,32,48,64")
+ ap.add_argument("--dtype", default="half")
+ ap.add_argument("--repeat", type=int, default=60)
+ a = ap.parse_args()
+ run(a.pack, a.out, [int(x) for x in a.rows.split(",")], a.dtype, a.repeat)
diff --git a/tools/qualify/plan.py b/tools/qualify/plan.py
index 436b362..51f1579 100644
--- a/tools/qualify/plan.py
+++ b/tools/qualify/plan.py
@@ -14,6 +14,7 @@ from pathlib import Path
STAGE_TABLE = {
"fetch": dict(job="cpu", needs=[], est=60, gpu=False),
"meta": dict(job="cpu", needs=["fetch"], est=5, gpu=False),
+ "autotune": dict(job="autotune", needs=["meta"], est=180, gpu=True),
"parity": dict(job="parity", needs=["meta"], est=900, gpu=True),
"kv": dict(job="kv", needs=["meta", "parity"], est=900, gpu=True),
"maxctx": dict(job="maxctx", needs=["meta", "kv"], est=1500, gpu=True),
@@ -36,7 +37,7 @@ class Stage:
cmd: list = field(default_factory=list)
-RELEVANT = {"fetch": ("ref",), "meta": (), "parity": ("ref",), "kv": ("ref", "kv_kl_max", "kv_bits"), "maxctx": ("sessions", "ctx_cap"),
+RELEVANT = {"fetch": ("ref",), "meta": (), "autotune": ("sessions", "ctx_cap"), "parity": ("ref",), "kv": ("ref", "kv_kl_max", "kv_bits"), "maxctx": ("sessions", "ctx_cap"),
"serve": ("sessions", "ctx_cap"), "smoke": ("smoke_tasks",), "report": ()}
diff --git a/tools/qualify/qualify.py b/tools/qualify/qualify.py
index 5ce8082..8667367 100644
--- a/tools/qualify/qualify.py
+++ b/tools/qualify/qualify.py
@@ -96,7 +96,7 @@ def main(argv=None) -> int:
names = [x.name for x in todo if x.name in ("serve", "smoke")]
runner = lambda: _split_serve(c, "serve" in names, "smoke" in names)
else:
- runner = {"fetch": lambda: st.stage_fetch(c), "meta": lambda: st.stage_meta(c), "parity": lambda: st.job_parity(c),
+ runner = {"fetch": lambda: st.stage_fetch(c), "meta": lambda: st.stage_meta(c), "autotune": lambda: st.job_autotune(c), "parity": lambda: st.job_parity(c),
"kv": lambda: st.job_kv(c), "maxctx": lambda: st.job_maxctx(c), "report": None}[s.name]
if s.name == "report":
continue
diff --git a/tools/qualify/replay.py b/tools/qualify/replay.py
new file mode 100644
index 0000000..b984988
--- /dev/null
+++ b/tools/qualify/replay.py
@@ -0,0 +1,65 @@
+"""Day-0 autotune by shape replay: start the pack's real server (same flags as the qualify serve stage) on a FRESH tune cache and drive a
+fixed sweep of row counts through it, so the engine's own autotuner times every kernel the model reaches in the served path: fused
+qkv / gate-up multi-GEMMs, MoE expert GEMMs, lm_head, CUDA-graph captures, whatever the architecture is. The winners it appends are
+exactly the cache for this pack on this device; `finish()` copies them to <pack>/tuning/<signature>.bin (+ manifest).
+
+The sweep covers the rows a request can put through a GEMM (the autotune key's row classes 2,4,8,16,24,32,48,64, then the dense path):
+ - prompts of exact token counts (token-id prompts on /v1/completions): single forward of L rows, and L-row tails behind a full chunk
+ - N concurrent decodes, N = 2..sessions (batched decode rows, speculative verify rows ride on the same classes)
+Pure planning (sweep_requests, signature file name) is CPU-testable; the driver needs a server.
+"""
+from __future__ import annotations
+
+import json
+import random
+import threading
+import time
+import urllib.request
+from pathlib import Path
+
+PROMPT_ROWS = (2, 3, 4, 6, 8, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 128, 160, 192, 200, 256)
+CHUNK = 2048 # serve.py --max-chunk-size default: a prompt of CHUNK + r tokens ends in an r-row forward
+TAILS = (3, 5, 9, 17, 25, 33, 49, 65, 100)
+
+
+def sweep_requests(sessions: int, ctx: int, chunk: int = CHUNK) -> list[dict]:
+ """Ordered sweep. Every entry: {kind, tokens, conc, max_tokens}. Lengths never exceed ctx - 64."""
+ cap = ctx - 64
+ out = [dict(kind="prompt", tokens=r, conc=1, max_tokens=8) for r in PROMPT_ROWS if r <= cap]
+ out += [dict(kind="tail", tokens=chunk + r, conc=1, max_tokens=4) for r in TAILS if chunk + r <= cap]
+ for n in range(2, sessions + 1):
+ out.append(dict(kind="decode", tokens=48, conc=n, max_tokens=24))
+ out.append(dict(kind="prompt", tokens=min(4096, cap), conc=1, max_tokens=16)) # full chunks: the dense/reconstruct path warms too
+ return out
+
+
+def token_prompt(n: int, seed: int, vocab: int = 30000) -> list[int]:
+ """n distinct-ish ordinary token ids (random in [1000, vocab)): no shared prefix between requests, no special tokens."""
+ rng = random.Random(seed)
+ return [rng.randrange(1000, vocab) for _ in range(n)]
+
+
+def complete(port: int, ids: list[int], max_tokens: int, model: str = "qual", timeout: int = 1800) -> dict:
+ body = json.dumps({"model": model, "prompt": ids, "max_tokens": max_tokens, "temperature": 0.0, "ignore_eos": True}).encode()
+ req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/completions", body, {"Content-Type": "application/json", "Authorization": "Bearer x"})
+ t0 = time.time()
+ try:
+ r = json.loads(urllib.request.urlopen(req, timeout=timeout).read())
+ return dict(ok=True, s=round(time.time() - t0, 3), usage=r.get("usage"))
+ except Exception as e: # noqa: BLE001
+ return dict(ok=False, s=round(time.time() - t0, 3), err=repr(e)[:200])
+
+
+def run_sweep(port: int, sessions: int, ctx: int, log=print, model: str = "qual") -> list[dict]:
+ res = []
+ for i, rq in enumerate(sweep_requests(sessions, ctx)):
+ out = [None] * rq["conc"]
+
+ def one(j):
+ out[j] = complete(port, token_prompt(rq["tokens"], seed=i * 100 + j), rq["max_tokens"], model)
+ th = [threading.Thread(target=one, args=(j,)) for j in range(rq["conc"])]
+ t0 = time.time()
+ [t.start() for t in th]; [t.join() for t in th]
+ res.append(dict(**rq, wall_s=round(time.time() - t0, 2), ok=all(o["ok"] for o in out), err=next((o["err"] for o in out if not o["ok"]), None)))
+ log(res[-1])
+ return res
diff --git a/tools/qualify/report.py b/tools/qualify/report.py
index ba2065c..a4adf7a 100644
--- a/tools/qualify/report.py
+++ b/tools/qualify/report.py
@@ -17,7 +17,7 @@ def assemble(meta: dict, args: dict, stages: dict, repo: Path) -> dict:
ctxs = {k: v for k, v in (d.get("maxctx") or {}).items() if k.isdigit()}
sv = d.get("serve") or {}
sm = d.get("smoke")
- q = dict(parity=d.get("parity"), kv=d.get("kv"), maxctx=ctxs or None, serve=sv or None, smoke=sm)
+ q = dict(autotune=d.get("autotune"), parity=d.get("parity"), kv=d.get("kv"), maxctx=ctxs or None, serve=sv or None, smoke=sm)
kv = (d.get("kv") or {}).get("chosen") or [6, 6]
try:
git = subprocess.run(["git", "-C", str(repo), "rev-parse", "--short", "HEAD"], capture_output=True, text=True).stdout.strip()
@@ -29,6 +29,7 @@ def assemble(meta: dict, args: dict, stages: dict, repo: Path) -> dict:
stages={n: dict(status=s.get("status"), wall_s=s.get("wall_s")) for n, s in stages.items()},
serve=dict(cmd=(d.get("serve") or {}).get("cmd") or (d.get("smoke") or {}).get("cmd"), kv=kv, ctx=ctxs, draft_policy=meta.get("draft_policy"),
template=meta["template"]),
+ tuning={k: (d.get("autotune") or {}).get(k) for k in ("tuning_dir", "files", "records", "plan_points", "wall_s")} if d.get("autotune") else None,
quality=dict(parity=d.get("parity"), kv=d.get("kv")),
speed={k: sv.get(k) for k in ("decode_tps_median", "prefill_8k_tps", "curve", "agg")} if sv else None,
sha=sv.get("sha"), smoke=sm,
diff --git a/tools/qualify/stages.py b/tools/qualify/stages.py
index e488536..f648d0a 100644
--- a/tools/qualify/stages.py
+++ b/tools/qualify/stages.py
@@ -86,6 +86,63 @@ def stage_meta(c: Ctx) -> dict:
return m
+# ---------------------------------------------------------------- autotune
+def _tune_cache_mod():
+ """exllamav3/util/tune_cache.py by path: the cache file format needs no torch (the package import does)."""
+ import importlib.util
+ f = Path(__file__).resolve().parents[2] / "exllamav3/util/tune_cache.py"
+ spec = importlib.util.spec_from_file_location("tune_cache", f)
+ m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)
+ return m
+
+
+def job_autotune(c: Ctx) -> dict:
+ """Day-0 autotune by shape replay (replay.py): serve the pack on a FRESH tune cache, drive the row sweep through the real served path,
+ keep the winners the engine's autotuner wrote -> <pack>/tuning/<device signature>.bin (+ .json), loaded at serve start."""
+ import shutil
+ import replay
+ tc = _tune_cache_mod()
+ c.need_ram()
+ tdir = Path(c.meta["path"]) / "tuning"
+ scratch = c.out / "tune_scratch"
+ shutil.rmtree(scratch, ignore_errors=True); scratch.mkdir(parents=True)
+ sessions = max(c.args["sessions"])
+ ctx = min(c.args.get("ctx_cap") or 16384, 16384, c.meta["max_pos"])
+ prof = {**c.prof, "env": {**c.prof["env"], "EXLLAMAV3_TUNE_CACHE": str(scratch), "EXL3_PACK_TUNE": "0"}}
+ k, v = chosen_kv(c)
+ argv = packmod.serve_flags(c.meta, port=c.args["port"], ctx=ctx, sessions=sessions, k_bits=k, v_bits=v)
+ log = c.out / "srv_autotune.log"
+ with c.locks():
+ sig = json.loads(c.py("autotune.py", "--signature").strip().splitlines()[-1])
+ t0 = time.time()
+ with running_server(prof, c.repo, argv, c.args["port"], log, logf=c.log) as (p, ok):
+ if not ok:
+ raise RuntimeError("autotune: server did not start: " + (log.read_text(errors="replace").strip().splitlines() or [""])[-1][:200])
+ load_s = time.time() - t0
+ at_load = len(tc.read_records(scratch / "coop_autotune_v1.bin"))
+ sweep = replay.run_sweep(c.args["port"], sessions, ctx, log=c.log)
+ if oom_in(log):
+ raise RuntimeError("autotune: OOM in the server log")
+ recs = tc.read_records(scratch / "coop_autotune_v1.bin")
+ if not recs:
+ raise RuntimeError("autotune: the replay produced no tuning records (does this build have the GEMM autotuner?)")
+ tdir.mkdir(exist_ok=True)
+ tc.write_records(tdir / f"{sig['file']}.bin", recs)
+ man = dict(schema=1, signature=sig, records=len(recs), records_at_load=at_load, load_s=round(load_s, 1), wall_s=round(time.time() - t0, 1),
+ sessions=sessions, ctx=ctx, sweep=sweep, cmd=argv, engine_git=_git(c.repo), pack_index_sha=c.meta.get("index_sha"))
+ (tdir / f"{sig['file']}.json").write_text(json.dumps(man, indent=1))
+ c.log(f"autotune: {len(recs)} records ({at_load} at load) -> {tdir / (sig['file'] + '.bin')}")
+ return dict(tuning_dir=str(tdir), files=sorted(p.name for p in tdir.glob("*.bin")), records=len(recs), records_at_load=at_load,
+ plan_points=len(sweep), wall_s=man["wall_s"], sweep_failed=[s for s in sweep if not s["ok"]])
+
+
+def _git(repo) -> str | None:
+ try:
+ return subprocess.run(["git", "-C", str(repo), "rev-parse", "--short", "HEAD"], capture_output=True, text=True, timeout=10).stdout.strip() or None
+ except Exception: # noqa: BLE001
+ return None
+
+
# ---------------------------------------------------------------- parity / kv
SQNR = re.compile(r"Quantized: model\.layers\.(\d+)\s+bpw:\s*([\d.]+)\s+rfn:\s*([\d.]+)\s+cos:\s*([\d.]+)\s+sqnr:\s*([\d.]+)")
diff --git a/tools/qualify/tests/fake_serve.py b/tools/qualify/tests/fake_serve.py
index e6fd40e..ad7ef58 100644
--- a/tools/qualify/tests/fake_serve.py
+++ b/tools/qualify/tests/fake_serve.py
@@ -26,6 +26,9 @@ class H(BaseHTTPRequestHandler):
if self.path == "/apply-template":
m = b["messages"]; p = "TOOLMARK " + m[0]["content"] + " " + m[1]["content"]
self.send_response(200); self.end_headers(); self.wfile.write(json.dumps({"prompt": p}).encode()); return
+ if self.path == "/v1/completions":
+ self.send_response(200); self.end_headers()
+ self.wfile.write(json.dumps({"usage": {"prompt_tokens": len(b["prompt"]), "completion_tokens": b["max_tokens"]}}).encode()); return
text = b["messages"][-1]["content"]
pt = max(1, len(text) // 4); mt = b["max_tokens"]
self.send_response(200); self.send_header("Content-Type", "text/event-stream"); self.end_headers()
diff --git a/tools/qualify/tests/test_autotune.py b/tools/qualify/tests/test_autotune.py
new file mode 100644
index 0000000..06d731f
--- /dev/null
+++ b/tools/qualify/tests/test_autotune.py
@@ -0,0 +1,135 @@
+"""CPU tests of the day-0 autotune: shape enumeration from safetensors headers, row classes, tuning-cache file format/merge, planner."""
+from __future__ import annotations
+
+import json
+import struct
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent))
+sys.path.insert(0, str(HERE.parents[2]))
+
+import autotune # noqa: E402
+import plan as planmod # noqa: E402
+
+import importlib.util # noqa: E402
+_spec = importlib.util.spec_from_file_location("tune_cache", HERE.parents[2] / "exllamav3/util/tune_cache.py")
+tc = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(tc) # no torch needed for the file format
+
+
+def write_st(path: Path, tensors: dict):
+ hdr = {k: {"dtype": "I16", "shape": list(v), "data_offsets": [0, 0]} for k, v in tensors.items()}
+ b = json.dumps(hdr).encode()
+ path.write_bytes(struct.pack("<Q", len(b)) + b)
+
+
+def rec(h, tag=1, bd=128, sms=82, conc=1):
+ return tc.REC.pack(h, tag, bd, sms, conc, 0, 0)
+
+
+class T(unittest.TestCase):
+ def test_row_class_mirrors_hash(self):
+ self.assertEqual([autotune.row_class(m) for m in (1, 2, 3, 5, 9, 16, 17, 24, 25, 33, 64, 65, 192)], [2, 2, 4, 8, 16, 16, 24, 24, 32, 48, 64, 64, 64])
+ self.assertEqual(sorted({autotune.row_class(m) for m in autotune.ROW_CLASSES}), [2, 4, 8, 16, 24, 32, 48, 64])
+
+ def test_shapes_from_headers(self):
+ with tempfile.TemporaryDirectory() as d:
+ t = {"m.layers.0.q.trellis": (448, 448, 64), "m.layers.0.q.mul1": (), "m.layers.1.q.trellis": (448, 448, 64), "m.layers.1.q.mul1": (),
+ "m.layers.0.g.trellis": (448, 1376, 96), "m.layers.0.g.mcg": (), "m.layers.0.e.experts.3.trellis": (64, 64, 48), "m.embed.weight": (10, 10)}
+ write_st(Path(d) / "a.safetensors", t)
+ s = autotune.pack_shapes(d)
+ self.assertEqual(s["dense"], {(7168, 7168, 4.0, False, True): 2, (7168, 22016, 6.0, True, False): 1})
+ self.assertEqual(len(s["experts"]), 1)
+ p = autotune.tune_plan(s)
+ self.assertEqual(len(p), 2 * len(autotune.ROW_CLASSES) * 2)
+ self.assertEqual(p[0][:2], (7168, 22016)) # biggest first
+
+ def test_half_integer_k_skipped(self):
+ p = autotune.tune_plan({"dense": {(128, 128, 2.5, False, True): 1}, "experts": {}})
+ self.assertEqual(p, [])
+
+ def test_cache_roundtrip_and_merge(self):
+ with tempfile.TemporaryDirectory() as d:
+ d = Path(d)
+ tc.write_records(d / "pack.bin", {1: rec(1), 2: rec(2, tag=5)})
+ self.assertEqual(sorted(tc.read_records(d / "pack.bin")), [1, 2])
+ self.assertEqual(tc.merge_into(d / "live.bin", [d / "pack.bin"]), 2) # empty live: file created with header
+ self.assertEqual(tc.merge_into(d / "live.bin", [d / "pack.bin"]), 0) # idempotent
+ tc.write_records(d / "p2.bin", {2: rec(2, tag=9), 3: rec(3)})
+ self.assertEqual(tc.merge_into(d / "live.bin", [d / "p2.bin"]), 1) # live wins, only key 3 is new
+ r = tc.read_records(d / "live.bin")
+ self.assertEqual(sorted(r), [1, 2, 3])
+ self.assertEqual(tc.decode(r[2])["tag"], 5)
+
+ def test_reader_skips_embedded_header_and_torn_tail(self):
+ with tempfile.TemporaryDirectory() as d:
+ f = Path(d) / "c.bin"
+ hdr = tc.HDR.pack(tc.MAGIC, tc.FORMAT, tc.REC.size)
+ f.write_bytes(hdr + rec(1) + hdr + rec(2) + b"\x01\x02\x03")
+ self.assertEqual(sorted(tc.read_records(f)), [1, 2])
+ f.write_bytes(b"garbage" * 10)
+ self.assertEqual(tc.read_records(f), {})
+
+ def test_install_off_switch_and_missing_dir(self):
+ import os
+ with tempfile.TemporaryDirectory() as d:
+ os.environ["EXLLAMAV3_TUNE_CACHE"] = str(Path(d) / "live.bin")
+ try:
+ self.assertEqual(tc.install_pack(d), 0) # no tuning dir: no-op
+ os.environ["EXL3_PACK_TUNE"] = "0"
+ self.assertEqual(tc.install_pack(d), 0)
+ finally:
+ os.environ.pop("EXL3_PACK_TUNE", None); os.environ.pop("EXLLAMAV3_TUNE_CACHE", None)
+
+ def test_stage_in_plan(self):
+ self.assertIn("autotune", planmod.ORDER)
+ self.assertLess(planmod.ORDER.index("meta"), planmod.ORDER.index("autotune"))
+ self.assertLess(planmod.ORDER.index("autotune"), planmod.ORDER.index("serve"))
+
+
+if __name__ == "__main__":
+ unittest.main()
+
+
+class TestReplay(unittest.TestCase):
+ def test_sweep_covers_every_row_class(self):
+ import replay
+ rq = replay.sweep_requests(sessions=4, ctx=16384)
+ rows = {autotune.row_class(r["tokens"]) for r in rq if r["kind"] == "prompt"} | {autotune.row_class(r["tokens"] - replay.CHUNK) for r in rq if r["kind"] == "tail"}
+ rows |= {autotune.row_class(r["conc"]) for r in rq if r["kind"] == "decode"}
+ self.assertEqual(rows, {2, 4, 8, 16, 24, 32, 48, 64})
+ self.assertEqual([r["conc"] for r in rq if r["kind"] == "decode"], [2, 3, 4])
+ self.assertTrue(all(r["tokens"] <= 16384 - 64 for r in rq))
+
+ def test_sweep_respects_small_ctx(self):
+ import replay
+ rq = replay.sweep_requests(sessions=1, ctx=512)
+ self.assertTrue(all(r["tokens"] <= 448 for r in rq))
+ self.assertFalse(any(r["kind"] == "decode" for r in rq))
+
+ def test_token_prompts_distinct_and_ordinary(self):
+ import replay
+ a, b = replay.token_prompt(64, 1), replay.token_prompt(64, 2)
+ self.assertNotEqual(a[:8], b[:8])
+ self.assertEqual(a, replay.token_prompt(64, 1))
+ self.assertTrue(all(1000 <= t < 30000 for t in a))
+
+ def test_run_sweep_against_fake_server(self):
+ import replay
+ import subprocess, time, urllib.request
+ port = 8597
+ p = subprocess.Popen([sys.executable, str(HERE / "fake_serve.py"), "--port", str(port), "-c", "4096", "--sessions", "3"])
+ try:
+ for _ in range(50):
+ try:
+ if urllib.request.urlopen(f"http://127.0.0.1:{port}/health").status == 200:
+ break
+ except Exception:
+ time.sleep(0.2)
+ res = replay.run_sweep(port, 3, 4096, log=lambda *_: None)
+ self.assertTrue(all(r["ok"] for r in res), [r for r in res if not r["ok"]][:2])
+ finally:
+ p.terminate(); p.wait(10)
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index 5d85877..4c33204 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -774,7 +774,8 @@ class QwenEngine:
if os.environ.get("EXL3_WARM_DENSE", "1") != "0":
from exllamav3.model.dense_warmup import seed_dense_tune
seed_dense_tune()
- from exllamav3.util import jit_log, kernel_seed
+ from exllamav3.util import jit_log, kernel_seed, tune_cache
+ tune_cache.install_pack(model_path) # <pack>/tuning: GEMM autotune winners from qualify --stage autotune
kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first start
jit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile
startup_health.stage("target weights")