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: kw6 (k6v6 + sink/window ring) is a KV auto-select candidate and the default where it beats k6v6's KL by 10 %; tq stays opt-in

YanissAmzad29255feea2
diff --git a/doc/kv_tq.md b/doc/kv_tq.md
index cba8c3d..279db4e 100644
--- a/doc/kv_tq.md
+++ b/doc/kv_tq.md
@@ -30,9 +30,14 @@ The default (`--kv-mode quant` or nothing) is unchanged. A pack that went throug
per-vector scale is folded into the scores (K) and the probabilities (V) instead of multiplying every dequantized pair. Prefill: the
existing staging, with `tq_dequant_window` filling the fp16 scratch (rotated domain) before the fp16 attention kernel. The BC graph
attention declines tq layers.
-* `tools/qualify` (kv stage) measures the decode-faithful 32K KL against k8v8 of k6v6, tq6 and tq5 once per model and keeps the cheapest
- format whose KL is <= 0.9 x k6v6's (a 256-step doc scatters 10-30 %: a tie stays on k6v6), and a narrower format only if every wider tq
- format qualifies too; `--no-kv-modes` skips it.
+* `tools/qualify` (kv stage) measures the decode-faithful 32K KL against k8v8 of k6v6, kw6 (k6v6 + the fp16 sink-4 / window-128 ring) and
+ tq6 / tq5 once per model. The default format is kw6 when its KL is <= 0.9 x k6v6's (a 256-step doc scatters 10-30 %: a tie stays on
+ k6v6), written to `kv_cache.json` as `kvwin: "4:128"` (`serve.py --kvwin`, sets `EXL3_KVWIN` before the model is built). tq6 / tq5 are
+ measured and reported but stay opt-in (`--kv-mode tq`); `QUALIFY_KV_TQ=1` lets them win (fewest bytes among the formats within the
+ margin, a narrower one only if every wider one qualifies). `--no-kv-modes` skips the stage. The report also lists decode s/token per format.
+
+Qualify cells, RTX 3090, one 256-step 32K doc, KL vs k8v8 (decode s/tok): Nanbeige k6v6 .00495 (.0356) | kw6 .00267 (.0361) | tq6 .00251 | tq5 .00456
+-> kw6. Qwen27 k6v6 .00515 | kw6 .0478 | tq6 .0293 | tq5 .0061 -> k6v6 (one doc, noisy: the same doc gave tq6 .0125 before the kernel change).
## Measured (Qwen3.8-27B EXL3, RTX 3090, graphs on, drafts off, decode tok/s, median of 3)
@@ -49,3 +54,7 @@ k6v6 .00062 / .043, tq6 .00060 / .026, tq5 .00115 / .100.
Nanbeige (Llama arch, no recurrent slots): the sink/window ring now binds there too (KVWinState). 32K KL vs k8v8, p1 / p2: k6v6 (production, no
window at 6 bits) .0536 / .0156, tq6 .0319 / .0088, tq5 .0544 / .0182, **k6v6 + the same ring .0216 / .0084**. Most of tq's gain over the
production k6v6 on that model is the ring, not the codebook; k6v6 + ring is as good in KL and a little faster to decode (0.0309 vs 0.0318 s/tok).
+
+Served A/B, same session (decode tok/s, median of 3): 4K / 32K / 120K k6v6 46.29 / 44.20 / 37.45 | kw6 46.13 / 43.75 / 38.02 | tq6 45.68 / 43.33 / 37.24
+(tq6 vs kw6: -1.0 / -1.0 / -2.1 %). One 32K decode step is 27.2 ms of GPU time; tq6 adds ~0.32 ms over the same ring (q/k/v rotation 0.14, writer 0.10
+more than the quant writer, qdec 0.08), the ring itself ~0.30 ms in both kw6 and tq6.
diff --git a/tools/qualify/gpu_eval.py b/tools/qualify/gpu_eval.py
index 7d14179..587135e 100644
--- a/tools/qualify/gpu_eval.py
+++ b/tools/qualify/gpu_eval.py
@@ -1,11 +1,12 @@
"""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 logits
gpu_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)
+ 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), kw6 (k6v6 + sink/window ring), tq6, tq5 (TurboQuant + ring)
KL maths and the real-quantizer forward are adapted from nanb kv_kl.py (drill 0)."""
import gc
import json
import sys
+import time
import torch
@@ -91,7 +92,7 @@ def kvmode(pack, docs, out, n=256):
e = T - n
cfg = Config.from_directory(pack)
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)]
+ fmts = [("k8v8", "quant", 8), ("k6v6", "quant", 6), ("kw6", "quant", 6)] + [(f"tq{b}", "tq", b) for b in (6, 5) if hd > 0 and tq.supported(hd, b)]
x = torch.tensor([ids])
npg = (T + 256) // 256
bt = torch.arange(npg, dtype=torch.int32)[None]
@@ -102,7 +103,7 @@ def kvmode(pack, docs, out, n=256):
if kind == "tq":
cache = 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
+ os.environ["EXL3_KVWIN"] = "4:128" if name == "kw6" else "0" # the production formats at >= 6 bits run without the window; kw6 = the same cache with the ring
cache = 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)
@@ -116,9 +117,11 @@ def kvmode(pack, docs, out, n=256):
for a in range(0, e, 2048):
m.prefill(x[:, a: min(a + 2048, e)], par(a, min(a + 2048, e) - a))
rows = []
+ t_dec = time.time()
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())
+ t_dec = (time.time() - t_dec) / n
if st is not None:
st.free()
lps[name] = torch.stack(rows).float()
@@ -127,7 +130,7 @@ def kvmode(pack, docs, out, n=256):
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)
+ bits_per_val=(b + 0.5) if kind == "quant" else b + 16 / hd, decode_s_per_tok=t_dec)
print(name, res[name], flush=True)
json.dump(res, open(out, "w"), indent=1)
diff --git a/tools/qualify/pack.py b/tools/qualify/pack.py
index 92504f6..3b5dfc0 100644
--- a/tools/qualify/pack.py
+++ b/tools/qualify/pack.py
@@ -104,13 +104,15 @@ 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, kv_mode: str = "quant") -> list[str]:
+ draft: str | None = None, kv_mode: str = "quant", kvwin: str | None = None) -> 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 kvwin:
+ f += ["--kvwin", kvwin]
if not meta["vision"]:
f.append("--no-vision")
if meta["template"]:
diff --git a/tools/qualify/report.py b/tools/qualify/report.py
index 75858f7..184dee9 100644
--- a/tools/qualify/report.py
+++ b/tools/qualify/report.py
@@ -62,9 +62,9 @@ def render_md(j: dict) -> str:
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()]
+ L += ["", f"KV format (decode-faithful 32K, KL vs k8v8; Q6 rule: kw6 if KL <= 0.9 x k6v6, tq opt-in): **{kv.get('mode', 'quant')}{' + ring ' + kv['kvwin'] if kv.get('kvwin') else ''}**",
+ "| format | KL vs k8v8 | top-1 vs k8v8 | bits/value | decode s/tok |", "|---|---|---|---|---|"]
+ L += [f"| {n} | {x['kl_vs_k8']:.5f} | {x['top1_vs_k8']:.4f} | {x['bits_per_val']:.2f} | {fmt(x.get('decode_s_per_tok'), 4)} |" 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.py
index 31397e0..a0d6191 100644
--- a/tools/qualify/rules.py
+++ b/tools/qualify/rules.py
@@ -19,12 +19,19 @@ def choose_kv(kl_vs_k8: dict[int, float], kl_max: float = KV_KL_MAX) -> tuple[in
KV_MODE_MARGIN = 0.9 # one 256-step doc is noisy (two docs of one model scatter by 10-30 %): a candidate has to beat k6v6 by this factor
-def choose_kv_mode(kl: dict[str, float], bits_per_val: dict[str, float], base: str = "k6v6", margin: float = KV_MODE_MARGIN) -> str:
- """Q6 rule for the KV format: any candidate (e.g. tq6, tq5) whose decode-faithful KL vs k8v8 is <= margin x 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`."""
+KV_DEFAULT_FORMATS = ("k6v6", "kw6") # tq6 / tq5 are measured and reported but stay opt-in (--kv-mode tq) in 1.8.1
+KV_WIN_SPEC = "4:128" # kw6 = k6v6 + the fp16 sink-4 / window-128 ring
+
+
+def choose_kv_mode(kl: dict[str, float], bits_per_val: dict[str, float], base: str = "k6v6", margin: float = KV_MODE_MARGIN,
+ allowed: tuple = KV_DEFAULT_FORMATS) -> str:
+ """Q6 rule for the KV format: any candidate (kw6, and with `allowed` extended tq6, tq5) whose decode-faithful KL vs k8v8 is <= margin x 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`. The wider-must-qualify check looks at every measured format, `allowed` or not."""
ok = [n for n in kl if n != base and n in bits_per_val and kl[n] <= margin * kl[base]]
# sanity: more bits can only help, so a format with fewer bits that beats the baseline while a wider tq format does not is measurement noise
ok = [n for n in ok if all(m in ok for m in kl if m != base and bits_per_val.get(m, 0) > bits_per_val[n])]
+ ok = [n for n in ok if n in allowed]
return min(ok, key=lambda n: (bits_per_val[n], kl[n])) if ok else base
diff --git a/tools/qualify/stages.py b/tools/qualify/stages.py
index 732195e..58cefd2 100644
--- a/tools/qualify/stages.py
+++ b/tools/qualify/stages.py
@@ -3,6 +3,7 @@ GPU stages run inside job functions that hold the backend locks; every server is
from __future__ import annotations
import json
+import os
import re
import statistics
import subprocess
@@ -223,16 +224,19 @@ def job_kv(c: Ctx) -> dict:
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 <= 0.9 x k6v6's, then the fewest bytes per value; else k6v6."""
+ """KV format auto-select, ONCE per model: decode-faithful 32K KL vs k8v8 of k6v6 (quant), kw6 (k6v6 + sink/window ring), tq6, tq5 (TurboQuant + ring).
+ Q6 rule (rules.choose_kv_mode): kw6 when its KL <= 0.9 x k6v6's, else k6v6; the tq formats are measured and reported, opt-in only
+ (QUALIFY_KV_TQ=1 lets them win: any tq format with KL <= 0.9 x k6v6's, then the fewest bytes per value)."""
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)
+ win = rules.choose_kv_mode(kl, bpv, allowed=rules.KV_DEFAULT_FORMATS + (("tq6", "tq5") if os.environ.get("QUALIFY_KV_TQ") == "1" else ()))
if win == "k6v6":
return dict(modes=raw, mode="quant")
+ if win == "kw6":
+ return dict(modes=raw, mode="quant", chosen=[6, 6], kvwin=rules.KV_WIN_SPEC, rule="Q6 rule: k6v6 + sink/window ring when its KL vs k8v8 <= 0.9 x k6v6's")
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")
@@ -240,7 +244,7 @@ def job_kvmode(c: Ctx, docs) -> dict:
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"),
+ doc = dict(schema=1, kv_mode=kv.get("mode", "quant"), k_bits=k, v_bits=v, kvwin=kv.get("kvwin"), 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))
@@ -252,6 +256,10 @@ def chosen_kv(c: Ctx) -> tuple:
return tuple(kv["chosen"]) if kv else (6, 6) # no reference: owner's Q6 minimum
+def chosen_kvwin(c: Ctx) -> str | None:
+ return (c.data.get("kv") or {}).get("kvwin")
+
+
def chosen_kv_mode(c: Ctx) -> str:
return (c.data.get("kv") or {}).get("mode", "quant")
@@ -259,7 +267,7 @@ def chosen_kv_mode(c: Ctx) -> str:
# ---------------------------------------------------------------- max ctx
def 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, kv_mode=chosen_kv_mode(c))
+ 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), kvwin=chosen_kvwin(c))
def probe_factory(c: Ctx, sessions: int):
diff --git a/tools/qualify/tests/test_plan.py b/tools/qualify/tests/test_plan.py
index 8f64b93..b0b8b24 100644
--- a/tools/qualify/tests/test_plan.py
+++ b/tools/qualify/tests/test_plan.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+import os
import sys
import tempfile
import unittest
@@ -237,20 +238,21 @@ class CliTests(unittest.TestCase):
class KvModeRule(unittest.TestCase):
+ BPV = {"k6v6": 6.5, "kw6": 6.5, "tq6": 6.0625, "tq5": 5.0625}
+ TQ = ("k6v6", "kw6", "tq6", "tq5")
+
def test_choose_kv_mode(self):
- bpv = {"k6v6": 6.5, "tq6": 6.0625, "tq5": 5.0625}
- # tq5 and tq6 both within the margin (<= 0.9 x k6v6 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")
- # tq5 below k6v6 but tq6 above it: noise, the baseline stays
- self.assertEqual(rules.choose_kv_mode({"k6v6": 0.005, "tq6": 0.0125, "tq5": 0.0048}, bpv), "k6v6")
- # 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")
- # 3090 Nanbeige doc: tq5 .00456 vs k6v6 .00495 is inside the noise, only tq6 clearly beats the baseline
- self.assertEqual(rules.choose_kv_mode({"k6v6": 0.00495, "tq6": 0.00251, "tq5": 0.00456}, bpv), "tq6")
+ bpv = self.BPV
+ # tq opt-in (default): tq6 / tq5 never win, kw6 does when it beats k6v6 by the margin
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.0536, "kw6": 0.0216, "tq6": 0.0319, "tq5": 0.0544}, bpv), "kw6") # Nanbeige 32K p1
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.0095, "tq6": 0.004, "tq5": 0.009}, bpv), "k6v6") # kw6 inside the noise
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002}, {"k6v6": 6.5}), "k6v6") # nothing else measured
+ # with tq allowed (QUALIFY_KV_TQ=1): the old rule, fewest bytes among the qualifying formats
+ kw = dict(allowed=self.TQ)
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.005, "tq6": 0.004, "tq5": 0.009}, bpv, **kw), "tq5")
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.010, "kw6": 0.005, "tq6": 0.008, "tq5": 0.020}, bpv, **kw), "tq6")
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.005, "kw6": 0.006, "tq6": 0.0125, "tq5": 0.0048}, bpv, **kw), "k6v6")
+ self.assertEqual(rules.choose_kv_mode({"k6v6": 0.002, "kw6": 0.0021, "tq6": 0.004, "tq5": 0.010}, bpv, **kw), "k6v6")
def test_job_kvmode_glue(self):
"""kv stage -> job_kvmode -> kv_cache.json: the winner is written as the lane preset, serve flags follow it"""
@@ -260,18 +262,32 @@ class KvModeRule(unittest.TestCase):
t = Path(t)
out = t / "out"; out.mkdir(); (t / "pack").mkdir()
raw = {"tq6": dict(kl_vs_k8=0.004, top1_vs_k8=0.99, bits_per_val=6.0625), "tq5": dict(kl_vs_k8=0.020, top1_vs_k8=0.97, bits_per_val=5.0625),
- "k6v6": dict(kl_vs_k8=0.010, top1_vs_k8=0.98, bits_per_val=6.5)}
+ "kw6": dict(kl_vs_k8=0.006, top1_vs_k8=0.99, bits_per_val=6.5), "k6v6": dict(kl_vs_k8=0.010, top1_vs_k8=0.98, bits_per_val=6.5)}
def py(script, *a, **kw):
self.assertEqual((script, a[0]), ("gpu_eval.py", "kvmode"))
(out / "kvmode_raw.json").write_text(json.dumps({k: v for k, v in raw.items()}))
- c = SimpleNamespace(out=out, args=dict(kvmode_steps=64), meta=dict(path=str(t / "pack"), index_sha="x"), py=py, locks=contextlib.nullcontext,
- repo=t, data={})
+ c = SimpleNamespace(out=out, args=dict(kvmode_steps=64), meta=dict(path=str(t / "pack"), index_sha="x", serve_entry="tools/qwen/serve.py", vision=False,
+ template=None, mtp_layers=0), py=py, locks=contextlib.nullcontext, repo=t, data={})
stages._git = lambda repo: "deadbeef"
+ # default: tq stays opt-in, kw6 wins (6 <= 0.9 x 10)
kv = stages.job_kvmode(c, out / "docs.pt")
- self.assertEqual((kv["mode"], kv["chosen"]), ("tq", [6, 6]))
+ self.assertEqual((kv["mode"], kv["chosen"], kv["kvwin"]), ("quant", [6, 6], "4:128"))
stages.write_kv_choice(c, kv)
j = json.loads((t / "pack" / "kv_cache.json").read_text())
- self.assertEqual((j["kv_mode"], j["k_bits"], j["v_bits"]), ("tq", 6, 6))
+ self.assertEqual((j["kv_mode"], j["k_bits"], j["v_bits"], j["kvwin"]), ("quant", 6, 6, "4:128"))
+ c.data = dict(kv=kv)
+ self.assertEqual((stages.chosen_kv_mode(c), stages.chosen_kvwin(c)), ("quant", "4:128"))
+ f = packmod.serve_flags(c.meta, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6, kvwin=stages.chosen_kvwin(c))
+ self.assertEqual(f[f.index("--kvwin") + 1], "4:128")
+ # QUALIFY_KV_TQ=1: tq6 wins the same table (fewer bytes than kw6; tq5 fails the margin)
+ os.environ["QUALIFY_KV_TQ"] = "1"
+ try:
+ kv = stages.job_kvmode(c, out / "docs.pt")
+ finally:
+ del os.environ["QUALIFY_KV_TQ"]
+ self.assertEqual((kv["mode"], kv["chosen"]), ("tq", [6, 6]))
+ stages.write_kv_choice(c, kv)
+ self.assertEqual(json.loads((t / "pack" / "kv_cache.json").read_text())["kv_mode"], "tq")
c.data = dict(kv=kv)
self.assertEqual(stages.chosen_kv_mode(c), "tq")
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index f604c19..b44fb65 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -2262,10 +2262,13 @@ def load_all(args: argparse.Namespace):
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)
+ args.kvwin = args.kvwin or kvj.get("kvwin")
+ print(f"qserve: KV cache from {kvp.name}: {args.kv_mode} k{args.k_bits}v{args.v_bits}" + (f" ring {args.kvwin}" if args.kvwin else ""), flush=True)
except (ValueError, KeyError, OSError) as e:
print(f"qserve: ignoring {kvp}: {e}", flush=True)
args.kv_mode = args.kv_mode or "quant"
+ if args.kvwin:
+ os.environ.setdefault("EXL3_KVWIN", args.kvwin) # before the model is built: the attention modules declare the ring state from it
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)
@@ -2320,6 +2323,8 @@ def main() -> None:
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=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("--kvwin", default=None, metavar="SINK:WINDOW",
+ help="fp16 sink + window ring of the quantized cache (EXL3_KVWIN, e.g. 4:128; an EXL3_KVWIN already set wins); written by tools/qualify as the kw6 choice")
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",
help="mix = shipped rule (MTP + n-gram lookup, lossless), mtp = fixed MTP chain, dflash = DFlash2 block drafter "