Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
qualify: KV format auto-select (k6v6 vs tq6 vs tq5), kv_cache.json lane preset read by serve.py
YanissAmz81e56e260a08
diff --git a/tools/qualify/gpu_eval.py b/tools/qualify/gpu_eval.pyindex f84f4a3..609239c 100644--- a/tools/qualify/gpu_eval.py+++ b/tools/qualify/gpu_eval.py@@ -1,6 +1,7 @@"""Pack-side GPU measurements, run with the backend python (torch + exllamav3 on PYTHONPATH). CLI only; stages parse its JSON.gpu_eval.py parity PACK DOCS.pt REFDIR OUT.json KL / top-1 / dNLL per doc (fp16 KV) against the streamed reference logitsgpu_eval.py kv PACK DOCS.pt REFDIR OUT.json B1 B2 ... tail KL of symmetric quantized KV (k<b>v<b>) at the long doc, vs reference and vs k8v8+ gpu_eval.py kvmode PACK DOCS.pt OUT.json [N] decode-faithful KL vs k8v8 at the long doc of the KV formats k6v6 (quant), tq6, tq5 (TurboQuant + sink/window ring)KL maths and the real-quantizer forward are adapted from nanb kv_kl.py (drill 0)."""import gcimport json@@ -78,9 +79,66 @@ def kv(pack, docs, ref, out, bits):json.dump(res, open(out, "w"), indent=1)+def kvmode(pack, docs, out, n=256):+ """Prefill ids[:T-n] in 2048-row chunks (quantize-on-write, the KVWIN ring bound for the tq formats), then n teacher-forced decode steps+ through the engine's own decode path, once per KV format; KL of each format's log-probs against k8v8's. No BF16 reference needed."""+ import os+ from exllamav3 import Cache, CacheLayer_quant, Config, Model+ from exllamav3.cache import tq+ ids = torch.load(docs)["ids"][0]+ T = len(ids)+ e = T - n+ cfg = Config.from_directory(pack)+ m = Model.from_config(cfg)+ hd = cfg.head_dim+ fmts = [("k8v8", "quant", 8), ("k6v6", "quant", 6)] + [(f"tq{b}", "tq", b) for b in (6, 5) if hd > 0 and tq.supported(hd, b)]+ caches = {}+ for name, kind, b in fmts:+ os.environ.pop("EXL3_KVWIN", None)+ if kind == "tq":+ caches[name] = Cache(m, max_num_tokens=T + 256, max_batch_size=2, max_history=3, layer_type=tq.CacheLayer_tq, k_bits=b, v_bits=b)+ else:+ os.environ["EXL3_KVWIN"] = "0" # the production formats at >= 6 bits run without the window+ caches[name] = Cache(m, max_num_tokens=T + 256, max_batch_size=2, max_history=3, layer_type=CacheLayer_quant, k_bits=b, v_bits=b)+ os.environ.pop("EXL3_KVWIN")+ m.load(progressbar=False)+ x = torch.tensor([ids])+ npg = (T + 256) // 256+ bt = torch.arange(npg, dtype=torch.int32)[None]+ res, lps = {}, {}+ with torch.inference_mode():+ for name, kind, b in fmts:+ cache = caches[name]+ st = cache.get_new_state() if cache.recurrent_state_cls is not None else None+ def par(pos, t):+ p = {"attn_mode": "flash_attn", "cache": cache, "block_table": bt[:, : (pos + t + 255) // 256], "cache_seqlens": torch.tensor([pos], dtype=torch.int32)}+ if st is not None:+ p["recurrent_states"] = [st]+ return p+ for a in range(0, e, 2048):+ m.prefill(x[:, a: min(a + 2048, e)], par(a, min(a + 2048, e) - a))+ rows = []+ for j in range(n):+ lg = m.forward(x[:, e + j: e + j + 1], par(e + j, 1))+ rows.append(torch.log_softmax(lg.float().reshape(-1, lg.shape[-1])[-1], -1).half().cpu())+ if st is not None:+ st.free()+ lps[name] = torch.stack(rows).float()+ if name != "k8v8":+ r8 = lps["k8v8"]+ kl = (r8.exp() * (r8 - lps[name]).nan_to_num(0)).sum(-1)+ res[name] = dict(kl_vs_k8=kl.mean().item(), top1_vs_k8=(r8.argmax(-1) == lps[name].argmax(-1)).float().mean().item(),+ bits_per_val=(b + 0.5) if kind == "quant" else b + 16 / hd)+ print(name, res[name], flush=True)+ free(m, None)+ json.dump(res, open(out, "w"), indent=1)++if __name__ == "__main__":cmd = sys.argv[1]if cmd == "parity":parity(*sys.argv[2:6])elif cmd == "kv":kv(*sys.argv[2:6], [int(x) for x in sys.argv[6:]])+ elif cmd == "kvmode":+ kvmode(*sys.argv[2:5], *[int(x) for x in sys.argv[5:6]])diff --git a/tools/qualify/pack.py b/tools/qualify/pack.pyindex ef480e7..92504f6 100644--- a/tools/qualify/pack.py+++ b/tools/qualify/pack.py@@ -35,9 +35,10 @@ def kv_layers(t: dict) -> int:return n // iv if iv else n-def kv_bytes_per_token(meta: dict, k_bits: int, v_bits: int) -> float:+def kv_bytes_per_token(meta: dict, k_bits: int, v_bits: int, kv_mode: str = "quant") -> float:elems_k = meta["kv_layers"] * meta["kv_heads"] * meta["head_dim"]- return elems_k * ((k_bits + KV_SCALE_OVERHEAD_BITS) + (v_bits + KV_SCALE_OVERHEAD_BITS)) / 8+ ovh = 16 / meta["head_dim"] if kv_mode == "tq" else KV_SCALE_OVERHEAD_BITS # tq: one fp16 norm per head vector+ return elems_k * ((k_bits + ovh) + (v_bits + ovh)) / 8def weights_dir_bytes(p: Path) -> int:@@ -103,11 +104,13 @@ def draft_policy(meta: dict) -> str:def serve_flags(meta: dict, *, port: int, ctx: int, sessions: int, k_bits: int, v_bits: int, model_id: str = "qual",- draft: str | None = None) -> list[str]:+ draft: str | None = None, kv_mode: str = "quant") -> list[str]:"""argv of the server (after the python executable) for this pack. No hand flags: every value is derived."""f = [meta["serve_entry"], "--model", meta["path"], "--port", str(port), "--model-id", model_id, "-c", str(ctx),"--sessions", str(sessions), "--k-bits", str(k_bits), "--v-bits", str(v_bits),"--draft-policy", draft or draft_policy(meta)]+ if kv_mode != "quant":+ f += ["--kv-mode", kv_mode]if not meta["vision"]:f.append("--no-vision")if meta["template"]:diff --git a/tools/qualify/plan.py b/tools/qualify/plan.pyindex d0d7b6c..a24240b 100644--- a/tools/qualify/plan.py+++ b/tools/qualify/plan.py@@ -37,7 +37,7 @@ class Stage:cmd: list = field(default_factory=list)-RELEVANT = {"fetch": ("ref",), "meta": (), "autotune": ("sessions", "ctx_cap"), "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", "kv_modes", "kvmode_steps"), "maxctx": ("sessions", "ctx_cap"),"serve": ("sessions", "ctx_cap"), "smoke": ("smoke_tasks",), "report": ()}diff --git a/tools/qualify/qualify.py b/tools/qualify/qualify.pyindex 8667367..0f69fef 100644--- a/tools/qualify/qualify.py+++ b/tools/qualify/qualify.py@@ -36,6 +36,8 @@ def parse(argv=None) -> dict:ap.add_argument("--sessions", default="1,4", help="session counts for the max-ctx search; the largest is the served config (N=1..max matrix)")ap.add_argument("--kv-bits", default="8,6,4", help="symmetric KV bits measured by the kv stage (8 is the baseline)")ap.add_argument("--kv-kl-max", type=float, default=0.02)+ ap.add_argument("--no-kv-modes", dest="kv_modes", action="store_false", help="skip the KV format auto-select (k6v6 vs tq6 vs tq5, decode-faithful 32K KL vs k8v8) in the kv stage")+ ap.add_argument("--kvmode-steps", type=int, default=256, help="teacher-forced decode steps scored by the KV format auto-select")ap.add_argument("--ctx-cap", type=int, help="cap of the max-ctx search (default: the model's max_position_embeddings)")ap.add_argument("--disk-floor-gb", type=float, default=40)ap.add_argument("--hf", help="HF repo to download into --pack first (license/size/disk-floor checked)")diff --git a/tools/qualify/report.py b/tools/qualify/report.pyindex 4f73c9f..75858f7 100644--- a/tools/qualify/report.py+++ b/tools/qualify/report.py@@ -61,6 +61,10 @@ def render_md(j: dict) -> str:if kv:L += ["", f"## KV (chosen k{kv['chosen'][0]}v{kv['chosen'][1]}; {kv['rule']}, kl_max {kv['kl_max']})", "| bits | KL vs ref | top-1 vs ref | KL vs k8v8 |", "|---|---|---|---|"]L += [f"| k{b}v{b} | {x['kl_ref']:.4f} | {x['top1_ref']:.4f} | {fmt(x.get('kl_vs_k8'), 4)} |" for b, x in kv["table"].items()]+ if kv.get("modes"):+ L += ["", f"KV format (decode-faithful 32K, KL vs k8v8; Q6 rule: KL <= k6v6, then fewest bytes): **{kv.get('mode', 'quant')}**",+ "| format | KL vs k8v8 | top-1 vs k8v8 | bits/value |", "|---|---|---|---|"]+ L += [f"| {n} | {x['kl_vs_k8']:.5f} | {x['top1_vs_k8']:.4f} | {x['bits_per_val']:.2f} |" for n, x in kv["modes"].items()]if j["serve"]["ctx"]:L += ["", "## Max context (k%dv%d, no OOM on 2 distinct near-full prompts)" % tuple(j["serve"]["kv"]), "| sessions | max -c |", "|---|---|"] + [f"| {s} | {c} |" for s, c in j["serve"]["ctx"].items()]sp = j["speed"]diff --git a/tools/qualify/rules.py b/tools/qualify/rules.pyindex fef7347..6f9203d 100644--- a/tools/qualify/rules.py+++ b/tools/qualify/rules.py@@ -16,6 +16,13 @@ def choose_kv(kl_vs_k8: dict[int, float], kl_max: float = KV_KL_MAX) -> tuple[inreturn 8, 8+def choose_kv_mode(kl: dict[str, float], bits_per_val: dict[str, float], base: str = "k6v6") -> str:+ """Q6 rule for the KV format: any candidate (e.g. tq6, tq5) whose decode-faithful KL vs k8v8 is <= the k6v6 baseline's qualifies;+ the one with the fewest bytes per value wins (ties: lower KL), else k6v6. kl / bits_per_val: {format: value}, both holding `base`."""+ ok = [n for n in kl if n != base and n in bits_per_val and kl[n] <= kl[base]]+ return min(ok, key=lambda n: (bits_per_val[n], kl[n])) if ok else base++def verdict(q: dict, gates: dict | None = None) -> dict:"""q: assembled qualify data. Returns {pass, reasons[], unmeasured[]}. Missing measurements are listed, never counted as pass."""g = dict(kl_mean=0.15, top1_min=0.75, ctx_min=32768, smoke_min=0.8)@@ -32,7 +39,7 @@ def verdict(q: dict, gates: dict | None = None) -> dict:unmeasured.append("parity")kv = q.get("kv")if kv:- if min(kv["chosen"]) < KV_MIN_BITS:+ if min(kv["chosen"]) < KV_MIN_BITS and not kv.get("q6_equivalent"):reasons.append(f"KV below Q6: {kv['chosen']}")else:unmeasured.append("kv")diff --git a/tools/qualify/stages.py b/tools/qualify/stages.pyindex 4c83ce2..09317b9 100644--- a/tools/qualify/stages.py+++ b/tools/qualify/stages.py@@ -215,7 +215,36 @@ def job_kv(c: Ctx) -> dict:c.py("gpu_eval.py", "kv", c.meta["path"], d, refdir, c.out / "kv_raw.json", *bits)raw = json.loads((c.out / "kv_raw.json").read_text())kl8 = {int(b): v["kl_vs_k8"] for b, v in raw.items() if "kl_vs_k8" in v}- return dict(table=raw, chosen=list(rules.choose_kv(kl8, c.args["kv_kl_max"])), kl_max=c.args["kv_kl_max"], rule="smallest symmetric bits >= Q6 with KL vs k8v8 <= kl_max, else k8v8")+ out = dict(table=raw, chosen=list(rules.choose_kv(kl8, c.args["kv_kl_max"])), kl_max=c.args["kv_kl_max"], rule="smallest symmetric bits >= Q6 with KL vs k8v8 <= kl_max, else k8v8", mode="quant")+ if c.args.get("kv_modes", True) and tuple(out["chosen"]) == (6, 6):+ out.update(job_kvmode(c, d))+ write_kv_choice(c, out)+ return out+++def job_kvmode(c: Ctx, docs) -> dict:+ """KV format auto-select, ONCE per model: decode-faithful 32K KL vs k8v8 of k6v6 (quant), tq6, tq5 (TurboQuant + sink/window ring).+ Q6 rule (rules.choose_kv_mode): any tq format with KL <= k6v6's, then the fewest bytes per value; else k6v6."""+ with c.locks():+ c.py("gpu_eval.py", "kvmode", c.meta["path"], docs, c.out / "kvmode_raw.json", c.args.get("kvmode_steps", 256), timeout=14400)+ raw = json.loads((c.out / "kvmode_raw.json").read_text())+ kl = {n: v["kl_vs_k8"] for n, v in raw.items()}+ bpv = {n: v["bits_per_val"] for n, v in raw.items()}+ win = rules.choose_kv_mode(kl, bpv)+ if win == "k6v6":+ return dict(modes=raw, mode="quant")+ b = int(win[2:])+ return dict(modes=raw, mode="tq", chosen=[b, b], q6_equivalent=True, rule="Q6 rule: tq format with KL vs k8v8 <= k6v6's, fewest bytes per value")+++def write_kv_choice(c: Ctx, kv: dict) -> None:+ """The lane preset: <pack>/kv_cache.json, read by tools/qwen/serve.py when no --k-bits / --v-bits / --kv-mode is given."""+ k, v = kv["chosen"]+ doc = dict(schema=1, kv_mode=kv.get("mode", "quant"), k_bits=k, v_bits=v, engine_git=_git(c.repo), pack_index_sha=c.meta.get("index_sha"),+ kl_vs_k8=({n: x["kl_vs_k8"] for n, x in kv["modes"].items()} if kv.get("modes") else None))+ tmp = Path(c.meta["path"]) / "kv_cache.json.tmp"+ tmp.write_text(json.dumps(doc, indent=1))+ tmp.replace(Path(c.meta["path"]) / "kv_cache.json")def chosen_kv(c: Ctx) -> tuple:@@ -223,10 +252,14 @@ def chosen_kv(c: Ctx) -> tuple:return tuple(kv["chosen"]) if kv else (6, 6) # no reference: owner's Q6 minimum+def chosen_kv_mode(c: Ctx) -> str:+ return (c.data.get("kv") or {}).get("mode", "quant")++# ---------------------------------------------------------------- max ctxdef start_args(c: Ctx, ctx: int, sessions: int) -> list:k, v = chosen_kv(c)- return packmod.serve_flags(c.meta, port=c.args["port"], ctx=ctx, sessions=sessions, k_bits=k, v_bits=v)+ return packmod.serve_flags(c.meta, port=c.args["port"], ctx=ctx, sessions=sessions, k_bits=k, v_bits=v, kv_mode=chosen_kv_mode(c))def probe_factory(c: Ctx, sessions: int):@@ -262,7 +295,7 @@ def job_maxctx(c: Ctx) -> dict:with c.locks():free = backends.gpu_free_mib(c.args["backend"])for s in c.args["sessions"]:- bpt = packmod.kv_bytes_per_token(c.meta, k, v)+ bpt = packmod.kv_bytes_per_token(c.meta, k, v, chosen_kv_mode(c))free_b = (free * 2**20 if free else 24 * 2**30) - c.meta["weights_bytes"]hi = search.upper_bound(free_b, bpt, 2.5 * 2**30, c.args.get("ctx_cap") or c.meta["max_pos"])lo = min(hi, 8192)diff --git a/tools/qualify/tests/test_plan.py b/tools/qualify/tests/test_plan.pyindex 0e2a2e8..ab9501c 100644--- a/tools/qualify/tests/test_plan.py+++ b/tools/qualify/tests/test_plan.py@@ -235,5 +235,26 @@ class CliTests(unittest.TestCase):self.assertEqual([p.name for p in (Path(t) / "o").iterdir()], [])++class KvModeRule(unittest.TestCase):+ def test_choose_kv_mode(self):+ bpv = {"k6v6": 6.5, "tq6": 6.0625, "tq5": 5.0625}+ # tq5 and tq6 both at or below k6v6's KL: the cheaper one wins+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "tq6": 0.004, "tq5": 0.009}, bpv), "tq5")+ # only tq6 qualifies+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "tq6": 0.008, "tq5": 0.020}, bpv), "tq6")+ # none qualifies: the production format stays+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002, "tq6": 0.004, "tq5": 0.010}, bpv), "k6v6")+ # a model without tq support (head_dim not a power of two): only the baseline was measured+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002}, {"k6v6": 6.5}), "k6v6")++ def test_serve_flags_kv_mode(self):+ meta = dict(serve_entry="tools/qwen/serve.py", path="/p", vision=False, template=None, mtp_layers=0, kv_layers=16, kv_heads=4, head_dim=256)+ f = packmod.serve_flags(meta, port=1, ctx=4096, sessions=1, k_bits=5, v_bits=5, kv_mode="tq")+ self.assertEqual(f[f.index("--kv-mode") + 1], "tq")+ self.assertNotIn("--kv-mode", packmod.serve_flags(meta, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6))+ self.assertLess(packmod.kv_bytes_per_token(meta, 5, 5, "tq"), packmod.kv_bytes_per_token(meta, 6, 6))++if __name__ == "__main__":unittest.main()diff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex d8d3317..f604c19 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -2257,6 +2257,15 @@ def load_all(args: argparse.Namespace):model_dir = str(Path(args.model).expanduser())template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")defaults = load_defaults(model_dir, args)+ kvp = Path(model_dir) / "kv_cache.json" # lane preset written by tools/qualify (kv stage): used only when no KV flag is given+ if kvp.is_file() and not (args.k_bits or args.v_bits or args.cache_bits or args.kv_mode):+ try:+ kvj = json.loads(kvp.read_text())+ args.k_bits, args.v_bits, args.kv_mode = int(kvj["k_bits"]), int(kvj["v_bits"]), kvj.get("kv_mode", "quant")+ print(f"qserve: KV cache from {kvp.name}: {args.kv_mode} k{args.k_bits}v{args.v_bits}", flush=True)+ except (ValueError, KeyError, OSError) as e:+ print(f"qserve: ignoring {kvp}: {e}", flush=True)+ args.kv_mode = args.kv_mode or "quant"t0 = time.time()print(f"qserve: starting, model={model_dir} ctx={args.ctx} sessions={args.sessions} draft_policy={args.draft_policy} "f"defaults={ {k: v for k, v in defaults.items() if v is not None} }", flush=True)@@ -2309,7 +2318,7 @@ def main() -> None:help="bits per K/V element of the attention cache pages (0 = fp16, the default; 8 = packed int8, about 40 %% smaller pages, saves 2.6 GiB at 256K, greedy output differs from the 16-bit cache; with EXL3_ROW_INV_GROUPS=1 four parallel sessions matched solo runs, 16 of 16)")parser.add_argument("--k-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="K bits of the quantized attention cache (with --v-bits; overrides --cache-bits)")parser.add_argument("--v-bits", type=int, default=0, choices=(0, 2, 3, 4, 5, 6, 7, 8), help="V bits of the quantized attention cache")- parser.add_argument("--kv-mode", choices=("quant", "tq"), default="quant",+ parser.add_argument("--kv-mode", choices=("quant", "tq"), default=None,help="KV cache format with --k-bits / --v-bits: quant = per-32 scale pages (default); tq = TurboQuant pages (rotation + Lloyd-Max codebook + one fp16 norm per head vector, 4..6 bits) with the fp16 sink-4 + window-128 ring")parser.add_argument("--ndt", type=int, default=7, help="max draft tokens per round (default 7; the rule drafts up to 3 for most rounds, deeper only on confident chains)")parser.add_argument("--draft-policy", choices=("mix", "mtp", "dflash", "off"), default="mix",