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.

Release 1.8.2

Yaniss Amazouze2f37564bbae
diff --git a/README.strix-halo.md b/README.strix-halo.md
index c65506b..29b1b0f 100644
--- a/README.strix-halo.md
+++ b/README.strix-halo.md
@@ -240,6 +240,9 @@ source tools/strix_halo/env.sh # runtime env (LD_PRELOAD Ubuntu
python tools/strix_halo/bench_mtp.py -n 128 -ndt 2 -dds -g
```
+Optional prefill attention (CK `fmha_fwd`, hd128/hd256, +24-62 % kernel, ~-7 % TTFT at 108K): `CK_FETCH=1 tools/strix_halo/ck_fmha/build.sh`
+(~33 s, built into the Docker image; `EXL3_PF_CK=auto` uses it when `libckpf.so` exists, else Triton silently; `0` = off).
+
Build and bench in **separate shells** — `env.sh build` exports `ROCM_PATH`/`HIP_PATH`/
`PYTORCH_ROCM_ARCH` and a bench in the same shell fails model load with a spurious
"Insufficient VRAM".
diff --git a/docker/Dockerfile b/docker/Dockerfile
index b6b71df..3dc86a2 100644
--- a/docker/Dockerfile
+++ b/docker/Dockerfile
@@ -61,6 +61,12 @@ RUN --mount=type=cache,target=/root/.cache/pip \
&& ./build.sh \
&& python -c "import torch, exllamav3_ext" \
&& rm -rf build .rebuild.* .sdk-deps /tmp/*
+# --- Layer B2: Composable Kernel prefill attention (EXL3_PF_CK=auto, ~33 s). Optional: a failed fetch/build leaves no library and the
+# server silently keeps the Triton prefill kernel. Invalidated only by the ck_fmha sources.
+COPY tools/strix_halo/ck_fmha/ ./tools/strix_halo/ck_fmha/
+ENV EXL3_PF_CK_SO=/opt/kyojin/ck-fmha/libckpf.so
+RUN (CK_FETCH=1 EXL3_CK_OUT=$EXL3_PF_CK_SO CK_JOBS=$(nproc) tools/strix_halo/ck_fmha/build.sh \
+ || echo "ck_fmha build skipped: prefill attention stays on Triton")
# --- Layer C: everything else (python, tools, docker/). Python-only edits land here. ---
COPY . ./
RUN python -c "import torch, exllamav3_ext"
diff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.py
index 82ba5fd..0e40a67 100644
--- a/exllamav3/ext_fallbacks.py
+++ b/exllamav3/ext_fallbacks.py
@@ -691,6 +691,11 @@ def dequant_cache_paged_window(
bonus_len: int, compand_a: float = 0.0,
) -> None:
"""Dequantize mapped pages into compact batch/page scratch storage in place."""
+ if torch.version.hip and os.environ.get("EXL3_DEQ_WINDOW_TRITON", "1") != "0":
+ from .modules.attention_fn.qdeq_window_triton import dequant_window_supported, dequant_window
+ if dequant_window_supported(k_in, k_in_scales, k_out, v_in, v_in_scales, v_out, cache_seqlens, block_table, page_size, compand_a):
+ dequant_window(k_in, k_in_scales, k_out, v_in, v_in_scales, v_out, cache_seqlens, block_table, bonus_len)
+ return
_dequant_cache_paged(k_in, k_in_scales, k_out, v_in, v_in_scales, v_out, cache_seqlens, block_table, page_size, compand_a, -1, bonus_len, True)
diff --git a/exllamav3/modules/attention_fn/qdeq_window_triton.py b/exllamav3/modules/attention_fn/qdeq_window_triton.py
new file mode 100644
index 0000000..43a6334
--- /dev/null
+++ b/exllamav3/modules/attention_fn/qdeq_window_triton.py
@@ -0,0 +1,89 @@
+"""Paged quantized cache (k/v bits 2..8, 32-value groups) -> compact fp16 staging window, one launch per plane.
+Same arithmetic and operation order as the PyTorch fallback of dequant_cache_paged_window (ext_fallbacks.py): codes from the
+high-to-low power-of-two bit planes, (code - (mid - 0.5)) * ((scale * r32) / mid) in fp32, then the unnormalised H32 butterfly
+(widths 1..16, the writer's _h32_stage), rounded once to fp16. Page p of batch row b lands at row b * pages_per_seq * 256 of
+the scratch; rows at or past cache_seqlens + bonus_len are left untouched."""
+import torch
+import triton
+import triton.language as tl
+from .qwrite_triton import _h32_stage
+
+BT = 4 # tokens per program
+
+
+def _deq_window_kernel(q, sc, out, seqlens, btable, bonus, pps,
+ G: tl.constexpr, BITS: tl.constexpr, BT: tl.constexpr):
+ tb = tl.program_id(0)
+ b = tl.program_id(1)
+ lim = tl.minimum(tl.maximum(tl.load(seqlens + b) + bonus, 0), pps * 256)
+ if tb * BT >= lim:
+ return
+ R: tl.constexpr = BT * G
+ r = tl.arange(0, R)
+ tok = tb * BT + r // G
+ g = r % G
+ valid = tok < lim
+ page = tl.load(btable + b * pps + tok // 256, mask = valid, other = 0).to(tl.int64)
+ src = page * 256 + tok % 256
+ dst = b.to(tl.int64) * pps * 256 + tok
+ codes = tl.zeros((R, 32), dtype = tl.int32)
+ base = (src * (G * BITS) + g * BITS)[:, None]
+ po = 0
+ if BITS & 8:
+ w = tl.load(q + base + po + tl.arange(0, 8)[None, :], mask = valid[:, None], other = 0)
+ x = (w[:, :, None] >> ((tl.arange(0, 4) * 8)[None, None, :])) & 255
+ codes = (codes << 8) | tl.reshape(x, (R, 32))
+ po += 8
+ if BITS & 4:
+ w = tl.load(q + base + po + tl.arange(0, 4)[None, :], mask = valid[:, None], other = 0)
+ x = (w[:, :, None] >> ((tl.arange(0, 8) * 4)[None, None, :])) & 15
+ codes = (codes << 4) | tl.reshape(x, (R, 32))
+ po += 4
+ if BITS & 2:
+ w = tl.load(q + base + po + tl.arange(0, 2)[None, :], mask = valid[:, None], other = 0)
+ x = (w[:, :, None] >> ((tl.arange(0, 16) * 2)[None, None, :])) & 3
+ codes = (codes << 2) | tl.reshape(x, (R, 32))
+ po += 2
+ if BITS & 1:
+ w = tl.load(q + base + po + tl.arange(0, 1)[None, :], mask = valid[:, None], other = 0)
+ x = (w[:, :, None] >> (tl.arange(0, 32)[None, None, :])) & 1
+ codes = (codes << 1) | tl.reshape(x, (R, 32))
+ MID: tl.constexpr = float(1 << (BITS - 1))
+ s = tl.load(sc + src * G + g, mask = valid, other = 0.0).to(tl.float32)
+ mult = tl.math.div_rn(s * 0.17677669529663688, tl.full((R,), MID, tl.float32))
+ v = (codes.to(tl.float32) - (MID - 0.5)) * mult[:, None]
+ v = _h32_stage(v, R, 1)
+ v = _h32_stage(v, R, 2)
+ v = _h32_stage(v, R, 4)
+ v = _h32_stage(v, R, 8)
+ v = _h32_stage(v, R, 16)
+ o = (dst * (G * 32) + g * 32)[:, None] + tl.arange(0, 32)[None, :]
+ tl.store(out + o, v.to(tl.float16), mask = valid[:, None])
+
+
+def dequant_window_supported(k_in, k_sc, k_out, v_in, v_sc, v_out, cache_seqlens, block_table, page_size, compand_a):
+ if compand_a != 0.0 or page_size != 256 or not torch.cuda.is_available():
+ return False
+ if not (k_in.is_cuda and k_in.dim() == 3 and v_in.dim() == 3 and k_out.dim() in (3, 4)):
+ return False
+ G = k_sc.shape[-1]
+ if G < 1 or G > 64 or G & (G - 1) or k_out[0].numel() != page_size * G * 32 or v_out[0].numel() != page_size * G * 32:
+ return False
+ kb, vb = k_in.shape[-1] // G, v_in.shape[-1] // G
+ return (2 <= kb <= 8 and 2 <= vb <= 8 and k_in.shape[-1] == G * kb and v_in.shape[-1] == G * vb and
+ k_in.dtype == torch.int32 and v_in.dtype == torch.int32 and k_sc.dtype == torch.float16 and v_sc.dtype == torch.float16 and
+ k_out.dtype == torch.float16 and v_out.dtype == torch.float16 and
+ k_in.is_contiguous() and v_in.is_contiguous() and k_sc.is_contiguous() and v_sc.is_contiguous() and
+ k_out.is_contiguous() and v_out.is_contiguous() and block_table.dtype == torch.int32 and
+ block_table.is_contiguous() and cache_seqlens.is_cuda and k_in.shape[:2] == k_sc.shape[:2] == v_in.shape[:2])
+
+
+def dequant_window(k_in, k_sc, k_out, v_in, v_sc, v_out, cache_seqlens, block_table, bonus_len):
+ bsz, pps = block_table.shape
+ G = k_sc.shape[-1]
+ grid = (triton.cdiv(pps * 256, BT), bsz)
+ seq32 = cache_seqlens if cache_seqlens.dtype == torch.int32 else cache_seqlens.to(torch.int32)
+ for q, sc, out in ((k_in, k_sc, k_out), (v_in, v_sc, v_out)):
+ _deq_window_kernel[grid](q, sc, out, seq32, block_table, int(bonus_len), pps,
+ G = G, BITS = q.shape[-1] // G, BT = BT, num_warps = 4, num_stages = 1, enable_fp_fusion = False)
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 6520a02..8cc0f9e 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -742,6 +742,53 @@ def _prefill_fa2_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):
out[:, s:e].copy_(o.transpose(1, 2))
return out
+# ROCm gfx1151, staged quantized-cache prefill, head_dim 128 / 256, one sequence: after the staging pass the window is contiguous fp16,
+# so the chunk runs as one Composable Kernel fmha_fwd call (stock gfx115 128x64 tiles, causal bottom-right, GQA) over past + chunk keys.
+# Qwen3.8 geometry (hd 256, 24q/4kv), 4096-row chunk at 4K/32K/120K past: 27.3/158.9/571.7 -> 21.6/122.8/461.7 ms (x1.26/1.29/1.24, 22 ->
+# 28 TFLOPS); hd 128 32q/4kv x1.4-1.6; error vs an fp32 reference equal to the Triton kernel's. Served Qwen27 k4v4, 108K-token prompt (74K new):
+# TTFT 270.6/271.4 -> 252.2/251.7 s (-7 %), 35K prompt -1.4 %. Needs the library built by tools/strix_halo/ck_fmha/build.sh (EXL3_PF_CK_SO
+# overrides the path). EXL3_PF_CK=auto (default): used when the library exists, silently Triton otherwise; 1 = required (warns if missing); 0 = off.
+# Any miss falls back to the Triton kernel
+_pf_ck_mode = os.environ.get("EXL3_PF_CK", "auto")
+_pf_ck = _pf_ck_mode != "0" and bool(torch.version.hip)
+_pf_ck_fn = None
+
+
+def _pf_ck_load():
+ global _pf_ck_fn, _pf_ck
+ if _pf_ck_fn is None:
+ import ctypes
+ from pathlib import Path
+ so = Path(os.environ.get("EXL3_PF_CK_SO") or Path(os.environ.get("XDG_CACHE_HOME", Path.home() / ".cache")) / "kyojin" / "ck-fmha" / "libckpf.so")
+ try:
+ fn = ctypes.CDLL(str(so)).ckpf_fwd
+ except OSError as e:
+ if _pf_ck_mode == "1":
+ print(f" !! EXL3_PF_CK=1 but {so} cannot be loaded ({e}); using the Triton prefill kernel")
+ _pf_ck = False
+ return None
+ fn.restype = ctypes.c_float
+ fn.argtypes = [ctypes.c_void_p] * 4 + [ctypes.c_int] * 7 + [ctypes.c_float, ctypes.c_int, ctypes.c_void_p, ctypes.c_int]
+ _pf_ck_fn = fn
+ return _pf_ck_fn
+
+
+def _prefill_ck_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):
+ """CK fmha_fwd over the contiguous fp16 staged window; None if the kernel declines (caller keeps the Triton path)."""
+ fn = _pf_ck_load()
+ if fn is None:
+ return None
+ q_len = q.shape[1]
+ k1 = kd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]
+ v1 = vd.view(1, -1, n_kvh, head_dim)[:, :past + q_len]
+ r = fn(q.data_ptr(), k1.data_ptr(), v1.data_ptr(), out.data_ptr(), 1, q_len, past + q_len, q.shape[2], n_kvh,
+ head_dim, head_dim, float(scale), 1, torch.cuda.current_stream(q.device).cuda_stream, 0)
+ if r >= 0 and not getattr(_prefill_ck_contig, "_logged", False):
+ _prefill_ck_contig._logged = True
+ print(f" -- EXL3_PF_CK: CK fmha_fwd prefill attention active (head_dim {head_dim}, {q.shape[2]}q/{n_kvh}kv)")
+ return out if r >= 0 else None
+
+
def _get_h32(device):
if device not in _h32_cache:
h = torch.ones(1, 1, dtype = torch.float32)
@@ -2076,6 +2123,16 @@ def paged_attn_triton_prefill(
if out is None:
out = torch.empty_like(q)
return _prefill_fa2_contig(q, kd, vd, max_kv_len, n_kvh, head_dim, softmax_scale, out)
+ if (_pf_ck and bsz == 1 and kv_append_len == q_len
+ and head_dim in (128, 256) and v_dim == head_dim
+ and window_left < 0 and window_right < 0 and not softcap and not has_sinks
+ and num_splits is None and block_m is None and q.is_contiguous() and tq is None):
+ if out is None:
+ out = torch.empty_like(q)
+ # ROCm callers leave max_kv_len unset outside QSA: read the past from the device copy (one tiny sync per call)
+ past = max_kv_len if max_kv_len is not None else int(cache_seqlens[0].item())
+ if _prefill_ck_contig(q, kd, vd, past, n_kvh, head_dim, softmax_scale, out) is not None:
+ return out
else:
k_scales, v_scales, qck, qcv = q, q, 0, 0
h32 = q
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index e330196..bddd33b 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -19,6 +19,9 @@ from .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_at
_qkv_slice_enable = os.environ.get("EXL3_QKV_SLICE", "1") != "0"
_shared_proj = os.environ.get("EXL3_ATTN_SHARED_PROJ", "1") != "0"
_shared_check = os.environ.get("EXL3_ATTN_SHARED_CHECK", "0") != "0"
+# EXL3_ATTN_BATCH_QSA (default on): in the row-invariant multi-job step, when every sequence takes the sparse (QSA) path the plane update, the KV append and
+# the gathered attention launch once over all sequences (their kernels give each row the bits of the one-sequence launch); the selection stays per sequence
+_batch_qsa = os.environ.get("EXL3_ATTN_BATCH_QSA", "1") != "0"
_SHARED_STATS = [0, 0]
_QKV_IG_MULTI = os.environ.get("EXL3_ATTN_QKV_IG_MULTI", "1") != "0" # (q|gate, k, v one launch)
@@ -1512,7 +1515,15 @@ class Attention(Module):
)
outs = []
- for b in range(bsz):
+ bsz_loop = bsz
+ if _batch_qsa and qsa_cpu is not None and bsz > 1:
+ thr = self.qsa_indexer.sparse_threshold()
+ if all(int(qsa_cpu[b]) + seqlen > thr for b in range(bsz)):
+ q_idx = self.qsa_indexer.update_planes(qsa_layer, x, self.rope, block_table, qsa_cpu, params)
+ qsa_layer.update_kv_direct(cache_seqlens, block_table, k, v, seqlen)
+ outs.append(self.qsa_indexer.sparse_attend(qsa_layer, self, q, q_idx, block_table, qsa_cpu))
+ bsz_loop = 0
+ for b in range(bsz_loop):
sl = slice(b, b + 1)
bt_b, cs_b = block_table[sl], cache_seqlens[sl]
if qsa_cpu is not None:
diff --git a/exllamav3/version.py b/exllamav3/version.py
index bea8946..5228a4c 100644
--- a/exllamav3/version.py
+++ b/exllamav3/version.py
@@ -1 +1 @@
-__version__ = "1.8.1"
\ No newline at end of file
+__version__ = "1.8.2"
\ No newline at end of file
diff --git a/tests/test_prefill_ck.py b/tests/test_prefill_ck.py
new file mode 100644
index 0000000..86939c9
--- /dev/null
+++ b/tests/test_prefill_ck.py
@@ -0,0 +1,54 @@
+import os
+import pytest
+import torch
+
+pytestmark = pytest.mark.skipif(not torch.cuda.is_available() or torch.version.hip is None, reason = "ROCm only")
+
+from exllamav3.modules.attention_fn import triton_paged as tp
+
+_SO = os.environ.get("EXL3_PF_CK_SO") or os.path.expanduser("~/.cache/kyojin/ck-fmha/libckpf.so")
+
+
+def _reference(q, k, v, past, scale, rows):
+ # fp32 attention for the selected query rows, queries aligned to the end of the keys, GQA by repeat
+ q_len, n_heads, hd = q.shape
+ n_kv = k.shape[1]
+ out = []
+ for r in rows:
+ n = past + r + 1
+ kf = k[:n].float().repeat_interleave(n_heads // n_kv, dim = 1)
+ vf = v[:n].float().repeat_interleave(n_heads // n_kv, dim = 1)
+ s = torch.einsum("hd,khd->hk", q[r].float(), kf) * scale
+ out.append(torch.einsum("hk,khd->hd", s.softmax(-1), vf))
+ return torch.stack(out)
+
+
[email protected](not os.path.isfile(_SO), reason = "libckpf.so not built (tools/strix_halo/ck_fmha/build.sh)")
[email protected]("hd, n_heads", [(256, 24), (128, 32)])
[email protected]("q_len, past", [(300, 0), (1024, 0), (2500, 3000), (4096, 5000), (777, 2001), (4096, 0)])
+def test_ck_matches_fp32_reference_and_triton(monkeypatch, hd, n_heads, q_len, past):
+ monkeypatch.setenv("EXL3_PF_CK_SO", _SO)
+ torch.manual_seed(0)
+ n_kv = 4
+ q = torch.randn(1, q_len, n_heads, hd, device = "cuda", dtype = torch.half)
+ kd = (torch.randn(1, past + q_len + 100, n_kv, hd, device = "cuda") * .5).half()
+ vd = torch.randn(1, past + q_len + 100, n_kv, hd, device = "cuda", dtype = torch.half)
+ scale = hd ** -0.5
+ out = torch.zeros_like(q)
+ assert tp._prefill_ck_contig(q, kd, vd, past, n_kv, hd, scale, out) is out
+ rows = sorted({0, 1, q_len // 2, q_len - 1})
+ ref = _reference(q[0], kd[0], vd[0], past, scale, rows)
+ assert (out[0, rows].float() - ref).abs().max().item() / ref.abs().max().item() < 2e-3
+ # same K/V through the Triton kernel (paged, identity table): both are fp16-noise away from the reference
+ page = 256
+ pages = (past + q_len + page - 1) // page
+ kc = torch.zeros(pages, page, n_kv, hd, device = "cuda", dtype = torch.half)
+ vc = torch.zeros_like(kc)
+ kc.view(-1, n_kv, hd)[:past + q_len] = kd[0, :past + q_len]
+ vc.view(-1, n_kv, hd)[:past + q_len] = vd[0, :past + q_len]
+ bt = torch.arange(pages, dtype = torch.int32, device = "cuda")[None]
+ sl = torch.tensor([past], dtype = torch.int32, device = "cuda")
+ tri = tp.paged_attn_triton_prefill(q, None, None, kc, vc, bt, sl, causal = True, softmax_scale = scale,
+ k_new = kd[:, past:past + q_len].contiguous(), v_new = vd[:, past:past + q_len].contiguous(),
+ max_kv_len = past)
+ assert (out.float() - tri.float()).abs().max().item() < 5e-3
diff --git a/tests/test_prefill_ck_fallback.py b/tests/test_prefill_ck_fallback.py
new file mode 100644
index 0000000..b19d218
--- /dev/null
+++ b/tests/test_prefill_ck_fallback.py
@@ -0,0 +1,31 @@
+import pytest
+import torch
+
+from exllamav3.modules.attention_fn import triton_paged as tp
+
+
+def no_lib(monkeypatch, tmp_path):
+ monkeypatch.setenv("EXL3_PF_CK_SO", str(tmp_path / "absent" / "libckpf.so"))
+ monkeypatch.setattr(tp, "_pf_ck_fn", None)
+ monkeypatch.setattr(tp, "_pf_ck", True)
+
+
+def _call():
+ q = torch.zeros(1, 8, 24, 256, dtype = torch.half)
+ kv = torch.zeros(1, 16, 4, 256, dtype = torch.half)
+ return tp._prefill_ck_contig(q, kv, kv, 0, 4, 256, 0.0625, torch.zeros_like(q))
+
+
+def test_auto_missing_library_falls_back_silently(monkeypatch, no_lib, capsys):
+ monkeypatch.setattr(tp, "_pf_ck_mode", "auto")
+ assert _call() is None # caller keeps the Triton kernel
+ assert tp._pf_ck is False # not retried on every chunk
+ out = capsys.readouterr()
+ assert out.out == "" and out.err == ""
+
+
+def test_forced_missing_library_warns_and_falls_back(monkeypatch, no_lib, capsys):
+ monkeypatch.setattr(tp, "_pf_ck_mode", "1")
+ assert _call() is None
+ assert "EXL3_PF_CK=1" in capsys.readouterr().out
diff --git a/tools/depth/rows_scan.py b/tools/depth/rows_scan.py
index fa5481e..c520c24 100644
--- a/tools/depth/rows_scan.py
+++ b/tools/depth/rows_scan.py
@@ -14,7 +14,7 @@ synthetic data once; each sequence owns its pages, at position --depth.
--exact compare the logits of every sequence in the batched step with the same sequence decoded alone with the same W
rows (W <= 8: the exact paths), and row 0 with the plain one-token decode; bitwise (torch.equal) and max |diff|
--kernels stamp a time window around 4 steps of each config (tools/depth/kernels.py joins them with a rocprofv3 trace)
-Output JSON is rewritten after every config. Run through ~/hermes-work/bin/gpurun (needs ~110 GiB free for GLM).
+Output JSON is rewritten after every config. Needs ~110 GiB free for GLM.
"""
import argparse, ast, json, os, sys, time
diff --git a/tools/qualify/DESIGN.md b/tools/qualify/DESIGN.md
index 1f5973b..a0b5f1c 100644
--- a/tools/qualify/DESIGN.md
+++ b/tools/qualify/DESIGN.md
@@ -54,3 +54,18 @@ GDN/MoE/MLA reference adapters (only dense Llama), MLX profile, Strix real run,
- `standard_cal_data` is also the quantizer's calibration source: the domain docs use late offsets (held-out in practice, not by construction). A truly
held-out set is a v2 item.
- The Hermes smoke needs an eval suite with `lib/taskdefs.py`: point `QUALIFY_EVAL_DIR` at it.
+
+## oneshot additions (feat/oneshot, 26/10): the new-model path with zero hand step
+Stage order is now `[convert] fetch meta parity kv draft autotune maxctx soak serve smoke report`.
+- `convert` (only with `--convert-from BF16_DIR` and no complete pack; `convert_job.py`): runs `convert.py -b --bits -hb --head-bits` under the GPU locks with an own-process-group
+ SIGSTOP/SIGCONT memory guard (`--conv-pause-gib 6` / `--conv-resume-gib 10`), resumes from the work dir, keeps the converter log as `<pack>/convert.log` (per-layer SQNR for `parity`),
+ carries the chat template into the pack (source `chat_template.jinja`, else the one embedded in `tokenizer_config.json`), checks the disk floor against ~0.95 x source size.
+- `backends.find_python`: the interpreter whose torch matches the backend (cuda/hip), found in the engine checkout's venv, `$VIRTUAL_ENV`, `$QUALIFY_WORK_ROOT/*/{venv,.venv}`; `QUALIFY_PYTHON` overrides.
+- `kv` without a BF16 reference: the pack-only decode-faithful `kvmode` KL vs the pack's own k8v8 decides Q6 vs k8v8 and k6v6 vs kw6 (before, the stage was skipped and the lane fell back to k6v6 unmeasured).
+- `draft` (head-less packs; a pack with its own MTP head keeps `mix`): `drafter.py` finds a DFlash drafter structurally compatible with the target (local `--drafter`, `<pack>/dflash`, `~/models/drafters/*`,
+ else a HF search `<model stem> dflash`, `exllamav3` branch preferred, downloaded under the disk floor), then an ABBA plain/drafted/drafted/plain served A/B on code/chat/agentic (warm-up dropped).
+ Kept only if chat >= 0.97x and some kind >= 1.10x (`rules.choose_draft`); adaptive depth (`--dflash-adapt on`). Later stages (autotune, maxctx, soak, serve) run WITH the winner, because the drafter's VRAM changes the safe -c.
+- `soak`: for each session count, the max-ctx result is served and driven by `--soak-s` seconds of agent-shaped load (70 % short, 25 % medium, 5 % near-full share, distinct prompts); any error / OOM line steps -c down 8 % and reruns.
+ The soak value replaces the search value in `qualify.json`.
+- Report: `serve.lane.cmd` is the full command to ship (kv mode, -c, sessions, draft path, tuning cache in the pack, prefix disk env, CUDA graphs, reply budget), `serve.hermes` the provider block
+ (`model.context_length` = -c, `compression.threshold` = 0.8 of one session's share of -c).
diff --git a/tools/qualify/backends.py b/tools/qualify/backends.py
index 4175226..a1fef62 100644
--- a/tools/qualify/backends.py
+++ b/tools/qualify/backends.py
@@ -7,29 +7,64 @@ import sys
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
-PYTHON = os.environ.get("QUALIFY_PYTHON", sys.executable)
+PYTHON = os.environ.get("QUALIFY_PYTHON") # None: found per backend by find_python()
ENGINE = os.environ.get("QUALIFY_ENGINE", str(REPO))
# Optional GPU lock files (os.pathsep-separated), taken in this order before each server start
LOCKS = [p for p in os.environ.get("QUALIFY_LOCKS", "").split(os.pathsep) if p]
PROFILES = {
"cuda": dict(
- python=PYTHON, engine=ENGINE, locks=LOCKS, env={"EXL3_CUDA_GRAPH": "1"},
+ python=None, engine=ENGINE, locks=LOCKS, env={"EXL3_CUDA_GRAPH": "1"},
gpu_used_mib="nvidia-smi", host_peak_note="NVIDIA device memory",
),
"rocm": dict(
- python=PYTHON, engine=ENGINE, locks=LOCKS, env={},
+ python=None, engine=ENGINE, locks=LOCKS, env={},
gpu_used_mib="/sys/class/drm/card1/device/mem_info_gtt_used", host_peak_note="Strix unified memory",
+ ctx_cap_default=65536, # ~120 GB of unified memory: the free-memory bound is ~1M tokens and a near-full probe at 500K would run for hours; --ctx-cap raises it
),
}
+_TORCH_PROBE = "import torch,sys; sys.exit(0 if (torch.version.{attr} and torch.__version__) else 3)"
+
+
+def find_python(backend: str, repo: str | None = None) -> str:
+ """The interpreter whose torch matches the backend (cuda: torch.version.cuda, rocm: torch.version.hip): QUALIFY_PYTHON, then the
+ engine checkout's own venv, $VIRTUAL_ENV, then every $QUALIFY_WORK_ROOT/*/{venv,.venv} (if set) and the current interpreter. No hand flag:
+ drill 0 tried the system python first (no torch) and had to be told which venv the lanes use."""
+ import glob
+ import subprocess
+ if PYTHON:
+ return PYTHON
+ attr = "cuda" if backend == "cuda" else "hip"
+ cands = []
+ if repo:
+ cands += [f"{repo}/.venv/bin/python", f"{repo}/venv/bin/python"]
+ if os.environ.get("VIRTUAL_ENV"):
+ cands.append(os.environ["VIRTUAL_ENV"] + "/bin/python")
+ root = os.environ.get("QUALIFY_WORK_ROOT")
+ if root:
+ root = os.path.expanduser(root)
+ cands += sorted(glob.glob(f"{root}/*/venv/bin/python") + glob.glob(f"{root}/*/.venv/bin/python"))
+ cands.append(sys.executable)
+ for c in cands:
+ if not os.path.exists(c):
+ continue
+ try:
+ if subprocess.run([c, "-I", "-c", _TORCH_PROBE.format(attr=attr)], capture_output=True, timeout=120).returncode == 0:
+ return c
+ except Exception: # noqa: BLE001
+ continue
+ raise SystemExit(f"no python with a {attr} torch found (set QUALIFY_PYTHON)")
+
+
def profile(name: str, repo: str | None = None) -> dict:
"""repo = the engine checkout with the built extension (PYTHONPATH and cwd of every server, as the lanes run them)."""
if name not in PROFILES:
raise SystemExit(f"unknown backend {name!r}: {sorted(PROFILES)}")
p = dict(PROFILES[name])
p["env"] = {**p["env"], "PYTHONPATH": repo or p["engine"]}
+ p["python"] = p["python"] or find_python(name, repo)
return p
diff --git a/tools/qualify/convert_job.py b/tools/qualify/convert_job.py
new file mode 100644
index 0000000..74b008e
--- /dev/null
+++ b/tools/qualify/convert_job.py
@@ -0,0 +1,121 @@
+"""Conversion as a qualify step (drill-0 gap 3). Drill 0 did this by hand for 2 h 40: a wrapper script (lock, resume flag, setsid), a second script that
+SIGSTOPped/CONTed the converter when MemAvailable fell, milestone lines, a zombie to reap, the chat template copied into the pack by hand and the
+converter log (per-layer SQNR) lost. Here: one call, own-PID pause/resume guard, <pack>/convert.log, template carried over, resume on rerun."""
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import shutil
+import signal
+import subprocess
+import threading
+import time
+from pathlib import Path
+
+import backends
+import pack as packmod
+
+
+def pack_complete(pack: str | os.PathLike) -> bool:
+ p = Path(pack).expanduser()
+ return (p / "config.json").exists() and (p / "quantization_config.json").exists() and not packmod.verify_shards(p)
+
+
+def carry_template(src: Path, pack: Path) -> str | None:
+ """The pack must hold the working chat template (serve reads --chat-template from it): copy the source's chat_template.jinja, or write the
+ one embedded in tokenizer_config.json. Returns where it came from, None when the source has none (qualify.meta then reports it)."""
+ dst = pack / "chat_template.jinja"
+ if dst.exists():
+ return "pack"
+ if (src / "chat_template.jinja").exists():
+ shutil.copy2(src / "chat_template.jinja", dst)
+ return "source file"
+ try:
+ t = json.loads((src / "tokenizer_config.json").read_text()).get("chat_template")
+ except (OSError, ValueError):
+ t = None
+ if isinstance(t, str) and t.strip():
+ dst.write_text(t)
+ return "tokenizer_config"
+ return None
+
+
+class MemGuard(threading.Thread):
+ """SIGSTOP the converter's process group when MemAvailable < pause_gib, SIGCONT at >= resume_gib (own group only, never a name match)."""
+
+ def __init__(self, pgid: int, pause_gib: float, resume_gib: float, log, poll_s: float = 5.0):
+ super().__init__(daemon=True)
+ self.pgid, self.pause, self.resume, self.log, self.poll = pgid, pause_gib, resume_gib, log, poll_s
+ self.stop_ev, self.stopped, self.paused_s, self.pauses = threading.Event(), False, 0.0, 0
+
+ def run(self):
+ t_stop = 0.0
+ while not self.stop_ev.wait(self.poll):
+ a = backends.mem_available_gib()
+ try:
+ if not self.stopped and a < self.pause:
+ os.killpg(self.pgid, signal.SIGSTOP); self.stopped, t_stop = True, time.time(); self.pauses += 1
+ self.log(f"convert: PAUSED (MemAvailable {a:.1f} GiB < {self.pause})")
+ elif self.stopped and a >= self.resume:
+ os.killpg(self.pgid, signal.SIGCONT); self.stopped = False; self.paused_s += time.time() - t_stop
+ self.log(f"convert: RESUMED (MemAvailable {a:.1f} GiB)")
+ except ProcessLookupError:
+ return
+
+ def finish(self):
+ self.stop_ev.set()
+ if self.stopped:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(self.pgid, signal.SIGCONT)
+
+
+def convert_argv(src: str, work: str, pack: str, bits: float, head_bits: int, resume: bool, extra: list[str]) -> list[str]:
+ a = ["convert.py", "-i", src, "-w", work, "-o", pack, "-b", str(bits), "-hb", str(head_bits)]
+ return a + (["-r"] if resume else []) + list(extra)
+
+
+def disk_need_gb(src: str) -> float:
+ """Converter work files + output: drill 0 saw 41 GB of work + 18 GB pack for a 62 GB source, i.e. ~0.95 x the source size."""
+ return 0.95 * sum(f.stat().st_size for f in Path(src).glob("*.safetensors")) / 1e9
+
+
+def run_convert(prof: dict, repo: Path, a: dict, out: Path, log) -> dict:
+ src, pack = Path(a["convert_from"]).expanduser(), Path(a["pack"])
+ work = Path(a.get("conv_work") or out / "conv_work")
+ problems = packmod.verify_shards(src)
+ if problems:
+ raise RuntimeError(f"convert: source {src} is not a complete checkpoint: {problems[:2]}")
+ free, need = packmod.disk_free_gb(pack), disk_need_gb(str(src))
+ if free - need < a["disk_floor_gb"]:
+ raise RuntimeError(f"convert: needs ~{need:.0f} GB of work + output, {free:.0f} GB free, floor {a['disk_floor_gb']} GB")
+ resume = (work / "state.json").exists()
+ argv = convert_argv(str(src), str(work), str(pack), a["bits"], a["head_bits"], resume, a.get("conv_extra", "").split())
+ env = {**os.environ, **prof["env"]}
+ pack.parent.mkdir(parents=True, exist_ok=True)
+ logf = pack.parent / f"{pack.name}.convert.log" if not pack.exists() else pack / "convert.log"
+ t0 = time.time()
+ with open(logf, "ab") as fh:
+ p = subprocess.Popen([prof["python"], "-u", *argv], cwd=repo, env=env, stdout=fh, stderr=subprocess.STDOUT, start_new_session=True)
+ g = MemGuard(p.pid, a["conv_pause_gib"], a["conv_resume_gib"], log)
+ g.start()
+ last = 0.0
+ try:
+ while p.poll() is None:
+ if time.time() - last > 1200: # a milestone line every 20 min (fleet rule)
+ last = time.time(); log(f"convert: running {time.time()-t0:.0f} s, MemAvailable {backends.mem_available_gib():.0f} GiB, paused {g.paused_s:.0f} s")
+ time.sleep(5)
+ finally:
+ g.finish()
+ if p.poll() is None:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(p.pid, signal.SIGTERM)
+ if p.returncode:
+ raise RuntimeError(f"convert.py rc={p.returncode}; see {logf}")
+ if logf.parent != pack: # the converter created the pack dir: move the log into it
+ shutil.move(str(logf), str(pack / "convert.log"))
+ tmpl = carry_template(src, pack)
+ if not a.get("keep_work"):
+ shutil.rmtree(work, ignore_errors=True)
+ return dict(wall_s=round(time.time() - t0, 1), paused_s=round(g.paused_s, 1), pauses=g.pauses, resumed=resume, template_from=tmpl, cmd=[prof["python"], *argv],
+ bits=a["bits"], head_bits=a["head_bits"])
diff --git a/tools/qualify/drafter.py b/tools/qualify/drafter.py
new file mode 100644
index 0000000..a723fba
--- /dev/null
+++ b/tools/qualify/drafter.py
@@ -0,0 +1,94 @@
+"""Draft-path discovery (drill-0 gap 6: the vendor DFlash2 drafter was found, downloaded, checked and wired by hand).
+Pure helpers + an HF search; the A/B that decides the policy is stages.job_draft, the rule is rules.choose_draft.
+
+A candidate is accepted only when its config matches the target STRUCTURALLY (DFlash architecture, same hidden size, tapped layers inside the
+target's depth, same vocabulary when the drafter states one), whatever it is called."""
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+DRAFTER_HOME = Path("~/models/drafters").expanduser()
+
+
+def norm(s: str) -> str:
+ return re.sub(r"[^a-z0-9]", "", s.lower())
+
+
+def stem(pack_name: str) -> str:
+ """Model stem of a pack directory name: everything before the quantization suffix (nanbeige43-33b-exl3-4.0 -> nanbeige43-33b)."""
+ return re.split(r"[-_.](?:exl\d|gptq|awq|gguf|mlx|\d+(?:\.\d+)?bpw)", pack_name, maxsplit=1, flags=re.I)[0]
+
+
+def validate(d: str | Path, meta: dict) -> list[str]:
+ """Problems that make the drafter unusable for this pack (empty list = compatible)."""
+ d = Path(d).expanduser()
+ try:
+ cfg = json.loads((d / "config.json").read_text())
+ except (OSError, ValueError):
+ return ["no readable config.json"]
+ bad = []
+ if not any("dflash" in a.lower() for a in cfg.get("architectures") or []):
+ bad.append(f"architecture {cfg.get('architectures')} is not a DFlash drafter")
+ if cfg.get("hidden_size") != meta.get("hidden"):
+ bad.append(f"hidden_size {cfg.get('hidden_size')} != target {meta.get('hidden')}")
+ taps = (cfg.get("dflash_config") or {}).get("target_layer_ids") or []
+ if not taps or max(taps) >= meta.get("layers", 0):
+ bad.append(f"target_layer_ids {taps} outside the target's {meta.get('layers')} layers")
+ if cfg.get("vocab_size") and meta.get("vocab") and cfg["vocab_size"] != meta["vocab"]:
+ bad.append(f"vocab_size {cfg['vocab_size']} != target {meta['vocab']}")
+ if not list(d.glob("*.safetensors")):
+ bad.append("no safetensors weights")
+ return bad
+
+
+def find_local(meta: dict, explicit: str | None = None) -> tuple[str | None, list[str]]:
+ """(dir, notes): --drafter DIR, <pack>/dflash, then every dir under ~/models/drafters that validates. A checkpoint that states its tap
+ convention (dflash_config.tap_shift, the exllamav3 export) wins over one that does not. Notes list the rejected candidates."""
+ notes, ok = [], []
+ cands = [Path(explicit).expanduser()] if explicit else []
+ cands.append(Path(meta["path"]) / "dflash")
+ if DRAFTER_HOME.is_dir():
+ cands += sorted(p for p in DRAFTER_HOME.iterdir() if p.is_dir())
+ for p in cands:
+ if not p.is_dir():
+ continue
+ bad = validate(p, meta)
+ if bad:
+ notes.append(f"{p}: {'; '.join(bad)}")
+ else:
+ ok.append(p)
+ explicit_ok = [p for p in ok if explicit and p == Path(explicit).expanduser()]
+ if explicit_ok:
+ return str(explicit_ok[0]), notes
+ ok.sort(key=lambda p: "tap_shift" not in ((json.loads((p / "config.json").read_text()).get("dflash_config")) or {}))
+ return (str(ok[0]) if ok else None), notes
+
+
+def hf_revision(repo: str) -> str:
+ """The 'exllamav3' branch when the repo has one (it carries the export this engine reads), else main."""
+ try:
+ from huggingface_hub import HfApi
+ if "exllamav3" in [b.name for b in HfApi().list_repo_refs(repo).branches]:
+ return "exllamav3"
+ except Exception: # noqa: BLE001
+ pass
+ return "main"
+
+
+def search_hf(meta: dict, limit: int = 300) -> list[str]:
+ """HF repos named <model stem> + 'dflash' (ids only; nothing is downloaded). Network errors -> []."""
+ try:
+ from huggingface_hub import HfApi
+ ids = [m.id for m in HfApi().list_models(search="dflash", limit=limit)]
+ except Exception: # noqa: BLE001
+ return []
+ s = norm(stem(meta["name"]))
+ return [i for i in ids if s and s in norm(i.split("/", 1)[-1])]
+
+
+def pick_hf(ids: list[str]) -> str | None:
+ """Prefer the plainest name (shortest id, then alphabetical): 'X-DFlash2' over 'X-DFlash2-GGUF'; GGUF/MLX/quantized variants never."""
+ ok = [i for i in ids if not re.search(r"gguf|mlx|nvfp4|fp8|awq|gptq|exl\d", i, re.I)]
+ return sorted(ok, key=lambda i: (len(i), i))[0] if ok else None
diff --git a/tools/qualify/gpu_eval.py b/tools/qualify/gpu_eval.py
index 587135e..a60afb1 100644
--- a/tools/qualify/gpu_eval.py
+++ b/tools/qualify/gpu_eval.py
@@ -80,10 +80,12 @@ def kv(pack, docs, ref, out, bits):
json.dump(res, open(out, "w"), indent=1)
-def kvmode(pack, docs, out, n=256):
+def kvmode(pack, docs, out, n=256, only=None):
"""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.
- One model load per format: a 33B pack on a 24 GB card has no room for several 32K caches at once."""
+ One model load per format: a 33B pack on a 24 GB card has no room for several 32K caches at once.
+ `only` = one format name: measure just that one (the stage takes the GPU lock per format so no hold exceeds one load + one 32K pass); the k8v8
+ log-probs are kept in <out>.k8v8.pt for the others and the result json is merged."""
import os
from exllamav3 import Cache, CacheLayer_quant, Config, Model
from exllamav3.cache import tq
@@ -97,7 +99,13 @@ def kvmode(pack, docs, out, n=256):
npg = (T + 256) // 256
bt = torch.arange(npg, dtype=torch.int32)[None]
res, lps = {}, {}
+ if os.path.exists(out):
+ res = json.load(open(out))
+ if os.path.exists(out + ".k8v8.pt"):
+ lps["k8v8"] = torch.load(out + ".k8v8.pt").float()
for name, kind, b in fmts:
+ if only and name != only:
+ continue
m = Model.from_config(Config.from_directory(pack))
os.environ.pop("EXL3_KVWIN", None)
if kind == "tq":
@@ -125,6 +133,8 @@ def kvmode(pack, docs, out, n=256):
if st is not None:
st.free()
lps[name] = torch.stack(rows).float()
+ if name == "k8v8":
+ torch.save(lps[name].half(), out + ".k8v8.pt")
free(m, cache)
if name != "k8v8":
r8 = lps["k8v8"]
@@ -142,4 +152,4 @@ if __name__ == "__main__":
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]])
+ kvmode(*sys.argv[2:5], *[int(x) for x in sys.argv[5:6]], only=sys.argv[6] if len(sys.argv) > 6 else None)
diff --git a/tools/qualify/load.py b/tools/qualify/load.py
index ecd5087..b4cd2af 100644
--- a/tools/qualify/load.py
+++ b/tools/qualify/load.py
@@ -5,8 +5,11 @@ from __future__ import annotations
import hashlib
import json
+import random
+import re
import threading
import time
+import urllib.error
import urllib.request
from pathlib import Path
@@ -18,6 +21,17 @@ FR = ["Explique en quatre ou cinq phrases pourquoi le ciel est bleu, puis donne
NOTHINK = {"chat_template_kwargs": {"enable_thinking": False}, "enable_thinking": False}
+# Decode-speed prompt kinds of the draft A/B (nanbdf bench kinds): drafters gain on copy-heavy agentic output, little on free chat.
+CODE_Q = "Write a Python module with an LRU cache class (get/put/evict, O(1)), type hints, docstrings and 5 pytest tests. Output only code."
+CHAT_Q = ["Raconte-moi une histoire courte sur un phare et un renard, avec des dialogues.", "Quels sont les avantages et les inconvénients du télétravail ? Réponds en un paragraphe argumenté."]
+
+
+def agentic_prompt(n_lines: int = 70) -> str:
+ """Copy-heavy turn typical of tool use: re-emit a file with two renamed identifiers (most output tokens repeat the input)."""
+ src = "\n".join(f"def handler_{i}(request, ctx):\n value = ctx.get('key_{i}', {i})\n return {{'id': {i}, 'ok': value is not None}}\n" for i in range(n_lines // 3))
+ return f"Voici un fichier Python.\n\n```python\n{src}```\n\nRéécris ce fichier en entier, à l'identique, mais en renommant handler_3 en process_three et handler_7 en process_seven. Donne uniquement le code."
+
+
class Client:
def __init__(self, port: int, model: str = "qual", corpus_dir: Path = CAL_DIR):
self.url = f"http://127.0.0.1:{port}"
@@ -49,6 +63,8 @@ class Client:
s = (d.get("content") or "") + (d.get("reasoning_content") or "")
if s:
first = first or time.time(); txt.append(s)
+ except urllib.error.HTTPError as e:
+ err = f"HTTP {e.code}: {e.read().decode(errors='replace')[:240]}"
except Exception as e:
err = repr(e)[:300]
te = time.time(); ct = (usage or {}).get("completion_tokens", 0)
@@ -56,6 +72,9 @@ class Client:
dec_tps=round((ct - 1) / (te - first), 2) if first and te > first and ct > 1 else None,
sha=hashlib.sha1("".join(txt).encode()).hexdigest()[:10], err=err, t0=t0, first=first, end=te)
+ def kind_prompts(self) -> dict:
+ return dict(code=[CODE_Q], chat=CHAT_Q, agentic=[agentic_prompt()])
+
def prompt(self, tokens: int, slot: int) -> str:
"""~tokens of corpus text, distinct for every (slot, call): fresh offsets so no prefix cache can answer."""
self.salt += 1
@@ -73,20 +92,31 @@ class Client:
return self.cpt
def near_full(self, ctx: int, slot: int, fill: float = 0.97, reply: int = 32) -> dict:
- """One request whose prompt is `fill` of -c (rounded down so prompt + reply < ctx)."""
- want = int(ctx * fill) - reply
- r = self.stream(self.prompt(want, slot), reply)
- if r["ptok"] and not r["err"] and r["ptok"] < 0.9 * want: # calibration drift: top up once
- r = self.stream(self.prompt(int(want * want / r["ptok"]), slot), reply)
+ """One request whose prompt is `fill` of -c (rounded down so prompt + reply < ctx). Corpora differ in chars/token (code and CJK are denser), so a
+ refused prompt (HTTP 400 context overflow) is shrunk and a short one is topped up, up to 4 times, from the server's own usage.prompt_tokens."""
+ return self.fit(int(ctx * fill) - reply, slot, reply)
+
+ def fit(self, want: int, slot: int, reply: int, topup: bool = True) -> dict:
+ """Stream a prompt of `want` tokens: corpora differ in chars/token (46K tokens came back for a 35K ask), so on HTTP 400 the length is
+ rescaled from the server's stated count and, with topup, a short prompt is lengthened (up to 4 tries)."""
+ n = want
+ for _ in range(4):
+ r = self.stream(self.prompt(n, slot), reply)
+ if r["err"] and "400" in r["err"] and n > 256:
+ m = re.search(r"prompt is (\d+) tokens", r["err"])
+ n = int(n * want / int(m.group(1)) * 0.99) if m else int(n * 0.9) # the server states the real count: rescale at once
+ elif topup and not r["err"] and r["ptok"] and r["ptok"] < 0.9 * want:
+ n = int(n * want / r["ptok"])
+ else:
+ break
return r
def concurrent(self, n: int, tokens: int, max_tokens: int = 128) -> dict:
res = [None] * n
- prompts = [self.prompt(tokens, i) for i in range(n)]
bar = threading.Barrier(n)
def run(i):
- bar.wait(); res[i] = self.stream(prompts[i], max_tokens)
+ bar.wait(); res[i] = self.fit(tokens, i, max_tokens, topup=False)
th = [threading.Thread(target=run, args=(i,)) for i in range(n)]
[t.start() for t in th]; [t.join() for t in th]
ok = [r for r in res if not r["err"] and r["dec_tps"]]
@@ -94,6 +124,38 @@ class Client:
return dict(n=n, ptok=[r["ptok"] for r in res], ttft=[r["ttft"] for r in res], dec_tps=[r["dec_tps"] for r in res],
agg_dec_tps=round(sum(r["ntok"] - 1 for r in ok) / span, 1) if span > 0 else None, errors=[r["err"] for r in res if r["err"]])
+ def soak(self, sessions: int, ctx: int, seconds: float, seed: int = 7, vram=None) -> dict:
+ """Agent-shaped load against a running server: `sessions` workers loop for `seconds` over a mixed prompt-length distribution
+ (70 % short 200-3K, 25 % medium up to half a share, 5 % a near-full share), short replies, so every size follows every other.
+ Drill 0: the synthetic near-full probes passed, the real agent mix OOMed 1-3 h later (duel: Nanbeige -c 73,728 x3 -> 61,440 x2 -> 57,344)."""
+ share = max(1024, ctx // sessions - 512)
+ rng = random.Random(seed)
+ lock = threading.Lock()
+ res, curve = [], []
+ end = time.time() + seconds
+
+ def pick():
+ with lock:
+ u = rng.random()
+ if u < 0.70:
+ return rng.randint(200, min(3000, share))
+ if u < 0.95:
+ return rng.randint(min(3000, share), max(3000, share // 2))
+ return int(share * 0.95)
+
+ def worker(i):
+ while time.time() < end:
+ n = pick()
+ r = self.fit(n, 10 + i, 48, topup=False)
+ with lock:
+ res.append(dict(want=n, ptok=r["ptok"], err=r["err"], ttft=r["ttft"]))
+ if vram and len(res) % 5 == 0:
+ curve.append(vram())
+ th = [threading.Thread(target=worker, args=(i,)) for i in range(sessions)]
+ [t.start() for t in th]; [t.join() for t in th]
+ errs = [r["err"] for r in res if r["err"]]
+ return dict(requests=len(res), errors=errs[:3], n_errors=len(errs), ptok_max=max((r["ptok"] or 0) for r in res), vram_curve=curve, seconds=seconds)
+
def sha_set(self) -> list:
return [{k: r[k] for k in ("sha", "ntok", "dec_tps", "err")} for r in (self.stream(p, 256) for p in FR)]
diff --git a/tools/qualify/locks.py b/tools/qualify/locks.py
index 0c62241..4c4c20c 100644
--- a/tools/qualify/locks.py
+++ b/tools/qualify/locks.py
@@ -8,6 +8,7 @@ import signal
import time
MIN_MEM_GIB = 4.0
+LIGHT_GIB = 4.0 # an untimed step whose server needs less device memory than this takes no exclusive GPU lock
def _blocking_flock(fd: int, wait_s: float, path: str) -> None:
diff --git a/tools/qualify/pack.py b/tools/qualify/pack.py
index 3b5dfc0..d01502e 100644
--- a/tools/qualify/pack.py
+++ b/tools/qualify/pack.py
@@ -19,6 +19,21 @@ FAMILIES = {
"Qwen3_5ForConditionalGeneration": dict(family="hybrid_gdn", serve="tools/qwen/serve.py", ref=None, vision=True),
"Qwen3_5ForCausalLM": dict(family="hybrid_gdn", serve="tools/qwen/serve.py", ref=None, vision=False),
}
+# Architectures not listed above resolve by the config's model_type prefix (any Qwen-family pack is served by the qwen entry:
+# Qwen4Exp / future Qwen releases need no new hard-coded name). Same prefix rule as docker/kyojin_args.TYPE_HINTS.
+FAMILY_BY_MODEL_TYPE = (
+ ("qwen", dict(family="hybrid_gdn", serve="tools/qwen/serve.py", ref=None, vision=True)),
+)
+
+
+def resolve_family(arch: str, cfg: dict) -> dict:
+ if arch in FAMILIES:
+ return FAMILIES[arch]
+ mt = str(cfg.get("model_type") or _text_cfg(cfg).get("model_type") or "").lower()
+ for prefix, fam in FAMILY_BY_MODEL_TYPE:
+ if mt.startswith(prefix):
+ return fam
+ return dict(family="unknown", serve=None, ref=None, vision=False)
def _text_cfg(cfg: dict) -> dict:
@@ -50,7 +65,7 @@ def read_pack(path: str | os.PathLike) -> dict:
cfg = json.loads((p / "config.json").read_text())
t = _text_cfg(cfg)
arch = (cfg.get("architectures") or ["?"])[0]
- fam = FAMILIES.get(arch, dict(family="unknown", serve=None, ref=None, vision=False))
+ fam = resolve_family(arch, cfg)
heads = t["num_attention_heads"]
qc = {}
for name in ("quantization_config.json",):
@@ -66,13 +81,20 @@ def read_pack(path: str | os.PathLike) -> dict:
quant=qc.get("quant_method"), bpw=qc.get("bits"), head_bits=qc.get("head_bits"),
vision=bool(fam["vision"] and cfg.get("vision_config") and not cfg.get("language_model_only")),
mtp_layers=int(t.get("mtp_num_hidden_layers") or t.get("num_nextn_predict_layers") or 0),
- weights_bytes=weights_dir_bytes(p), index_sha=hashlib.sha1(idx.read_bytes()).hexdigest()[:12] if idx.exists() else None,
+ weights_bytes=weights_dir_bytes(p), index_sha=_index_sha(p, idx),
license=_license(p), template=str(p / "chat_template.jinja") if (p / "chat_template.jinja").exists() else None,
)
meta["problems"] = problems(meta)
return meta
+def _index_sha(p: Path, idx: Path) -> str | None:
+ if idx.exists():
+ return hashlib.sha1(idx.read_bytes()).hexdigest()[:12]
+ one = p / "model.safetensors" # single shard: size + mtime stand in for the index (stage keys, tuning/kv presets)
+ return hashlib.sha1(f"{one.stat().st_size}:{int(one.stat().st_mtime)}".encode()).hexdigest()[:12] if one.exists() else None
+
+
def _license(p: Path) -> str | None:
for f in ("LICENSE", "LICENSE.md", "LICENSE.txt"):
if (p / f).exists():
@@ -104,11 +126,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, kv_mode: str = "quant", kvwin: str | None = None) -> list[str]:
+ draft: str | None = None, kv_mode: str = "quant", kvwin: str | None = None, dflash_dir: 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 dflash_dir and (draft or "") == "dflash":
+ f += ["--dflash-dir", dflash_dir]
if kv_mode != "quant":
f += ["--kv-mode", kv_mode]
if kvwin:
@@ -124,8 +148,9 @@ def verify_shards(path: str | os.PathLike) -> list[str]:
"""Problems found when comparing the shard files with model.safetensors.index.json (names + existence + non-empty)."""
p = Path(path).expanduser()
idx = p / "model.safetensors.index.json"
- if not idx.exists():
- return [f"{p}: no model.safetensors.index.json"]
+ if not idx.exists(): # a small model converts to ONE shard and has no index (Qwen3.5-0.8B)
+ one = p / "model.safetensors"
+ return [] if one.exists() and one.stat().st_size else [f"{p}: no model.safetensors.index.json and no model.safetensors"]
files = sorted(set(json.loads(idx.read_text())["weight_map"].values()))
bad = []
for f in files:
diff --git a/tools/qualify/plan.py b/tools/qualify/plan.py
index a24240b..1229044 100644
--- a/tools/qualify/plan.py
+++ b/tools/qualify/plan.py
@@ -14,11 +14,13 @@ 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),
- "serve": dict(job="serve", needs=["meta", "kv", "maxctx"], est=1500, gpu=True),
+ "draft": dict(job="draft", needs=["meta", "kv"], est=600, gpu=True),
+ "autotune": dict(job="autotune", needs=["meta", "draft"], est=180, gpu=True),
+ "maxctx": dict(job="maxctx", needs=["meta", "kv", "draft"], est=1500, gpu=True),
+ "soak": dict(job="soak", needs=["meta", "maxctx"], est=900, gpu=True),
+ "serve": dict(job="serve", needs=["meta", "kv", "maxctx", "soak"], est=1500, gpu=True),
"smoke": dict(job="serve", needs=["serve"], est=900, gpu=True),
"report": dict(job="cpu", needs=["meta"], est=2, gpu=False),
}
@@ -37,8 +39,8 @@ 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", "kv_modes", "kvmode_steps"), "maxctx": ("sessions", "ctx_cap"),
- "serve": ("sessions", "ctx_cap"), "smoke": ("smoke_tasks",), "report": ()}
+RELEVANT = {"fetch": ("ref",), "meta": (), "draft": ("drafter", "no_hf_drafter"), "autotune": ("sessions", "ctx_cap"), "parity": ("ref",), "kv": ("ref", "kv_kl_max", "kv_bits", "kv_modes", "kvmode_steps"), "maxctx": ("sessions", "ctx_cap"),
+ "soak": ("sessions", "soak_s"), "serve": ("sessions", "ctx_cap"), "smoke": ("smoke_tasks",), "report": ()}
def fingerprint(stage: str, meta: dict, args: dict) -> str:
@@ -77,10 +79,11 @@ def build_plan(meta: dict, args: dict, state: dict, only: list | None = None, re
st.status, st.note = "skip", "no --ref BF16 dir: parity unmeasured"
elif name == "parity" and not meta.get("ref_adapter"):
st.status, st.note = "skip", f"no reference adapter for family {meta.get('family')}: parity unmeasured"
- elif name == "kv" and not args.get("ref"):
- st.status, st.note = "skip", "kv KL needs the BF16 reference tail (--ref): falling back to k6v6 (Q6 rule)"
- elif name == "kv" and not meta.get("ref_adapter"):
- st.status, st.note = "skip", f"no reference adapter for family {meta.get('family')}: falling back to k6v6"
+ elif name == "kv" and not (args.get("ref") and meta.get("ref_adapter")):
+ if args.get("kv_modes", True):
+ st.note = "no BF16 reference (--ref / family adapter): KV format picked from the pack-only decode-faithful KL vs k8v8 (kvmode)"
+ else:
+ st.status, st.note = "skip", "kv KL needs the BF16 reference tail (--ref) or the kvmode measure: falling back to k6v6 (Q6 rule)"
d = state.get(name)
if st.status == "todo" and d and d.get("status") == "done" and d.get("key") == fingerprint(name, meta, args) and name not in redo:
st.status, st.note = "done", f"resumed ({d.get('wall_s')} s)"
diff --git a/tools/qualify/qualify.py b/tools/qualify/qualify.py
index 0f69fef..73e9b98 100644
--- a/tools/qualify/qualify.py
+++ b/tools/qualify/qualify.py
@@ -17,6 +17,7 @@ HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import backends # noqa: E402
+import convert_job # noqa: E402
import pack as packmod # noqa: E402
import plan as planmod # noqa: E402
import report # noqa: E402
@@ -38,8 +39,20 @@ def parse(argv=None) -> dict:
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("--drafter", help="DFlash drafter directory (default: <pack>/dflash, ~/models/drafters/*, else a HF search '<model stem> dflash')")
+ ap.add_argument("--no-hf-drafter", action="store_true", help="never search / download a drafter from HF")
+ ap.add_argument("--soak-s", type=float, default=360, help="seconds of mixed agent-shaped load per session count at the max-ctx result (soak stage); on any error -c steps down 8 %% and the soak reruns")
+ ap.add_argument("--min-share", type=int, default=24576, help="tokens one session must get for the shipped session count (default 24,576: Hermes' live preamble is 15-30K)")
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("--convert-from", help="BF16 checkpoint directory: convert it into --pack first when the pack is missing/incomplete (own-PID memory guard, resume, convert.log + chat template carried into the pack)")
+ ap.add_argument("--bits", type=float, default=4.0, help="conversion bits per weight")
+ ap.add_argument("--head-bits", type=int, default=6)
+ ap.add_argument("--conv-work", help="converter work dir (default <out>/conv_work; kept until the conversion succeeds, deleted then unless --keep-work)")
+ ap.add_argument("--conv-extra", default="", help="extra converter flags, e.g. '-hq'")
+ ap.add_argument("--conv-pause-gib", type=float, default=6.0, help="SIGSTOP the converter when MemAvailable falls below this")
+ ap.add_argument("--conv-resume-gib", type=float, default=10.0)
+ ap.add_argument("--keep-work", action="store_true")
ap.add_argument("--hf", help="HF repo to download into --pack first (license/size/disk-floor checked)")
ap.add_argument("--conv-log", help="converter log (per-layer SQNR); default <pack>/convert.log")
ap.add_argument("--smoke-tasks", default="", help="hermes_opt/eval task ids (default: 4 spread over the suite)")
@@ -49,7 +62,8 @@ def parse(argv=None) -> dict:
a = vars(ap.parse_args(argv))
a["sessions"] = sorted({int(x) for x in a["sessions"].split(",")})
a["kv_bits"] = [int(x) for x in a["kv_bits"].split(",")]
- a["pack"] = str(Path(a["pack"]).expanduser())
+ a["pack"] = str(Path(a["pack"]).expanduser().resolve())
+ a["repo"] = str(Path(a["repo"]).expanduser().resolve())
if a["ref"]:
a["ref"] = str(Path(a["ref"]).expanduser())
a["out"] = str(Path(a["out"]).expanduser() if a["out"] else Path(a["repo"]) / "qualify_out" / Path(a["pack"]).name / a["backend"])
@@ -68,6 +82,14 @@ def logger(out: Path):
def main(argv=None) -> int:
a = parse(argv)
out = Path(a["out"]); out.mkdir(parents=True, exist_ok=True)
+ if a["convert_from"] and not convert_job.pack_complete(a["pack"]):
+ if a["dry_run"]:
+ print("convert stage: " + " ".join(convert_job.convert_argv(a["convert_from"], a.get("conv_work") or str(out / "conv_work"), a["pack"], a["bits"], a["head_bits"],
+ False, a["conv_extra"].split())) + f"\n(needs ~{convert_job.disk_need_gb(a['convert_from']):.0f} GB; then the plan below on the new pack)")
+ return 0
+ _convert(a, out)
+ if a["ctx_cap"] is None:
+ a["ctx_cap"] = backends.PROFILES[a["backend"]].get("ctx_cap_default")
meta = packmod.read_pack(a["pack"])
state = planmod.load_state(out)
only = a["stage"].split(",") if a["stage"] else None
@@ -98,8 +120,8 @@ 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), "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]
+ runner = {"fetch": lambda: st.stage_fetch(c), "meta": lambda: st.stage_meta(c), "autotune": lambda: st.job_autotune(c), "draft": lambda: st.job_draft(c), "parity": lambda: st.job_parity(c),
+ "kv": lambda: st.job_kv(c), "maxctx": lambda: st.job_maxctx(c), "soak": lambda: st.job_soak(c), "report": None}[s.name]
if s.name == "report":
continue
t0 = time.time(); log(f"stage {s.name} start")
@@ -124,13 +146,25 @@ def main(argv=None) -> int:
return 0
+def _convert(a, out):
+ """Stage 0 (only with --convert-from and no complete pack): runs before the pack metadata exists, under the GPU locks."""
+ from locks import gpu_locks
+ log = logger(out)
+ prof = backends.profile(a["backend"], a["repo"])
+ log(f"stage convert start ({a['convert_from']} -> {a['pack']}, {a['bits']} bpw, head {a['head_bits']})")
+ with gpu_locks(prof["locks"], log):
+ r = convert_job.run_convert(prof, Path(a["repo"]), a, out, log)
+ (out / "convert.json").write_text(json.dumps(r, indent=1))
+ log(f"stage convert done in {r['wall_s']:.0f} s (paused {r['paused_s']:.0f} s, {r['pauses']} pauses, template from {r['template_from']})")
+
+
def _split_serve(c, do_serve, do_smoke):
r = st.job_serve(c, do_serve, do_smoke)
out = {}
if do_serve:
- out["serve"] = {**r["serve"], "cmd": r["cmd"]}
+ out["serve"] = {**r["serve"], "cmd": r["cmd"], "lock_hold_max_s": r.get("lock_hold_max_s")}
if do_smoke:
- out["smoke"] = {**(r["smoke"] or {}), "cmd": r["cmd"]}
+ out["smoke"] = {**(r["smoke"] or {}), "cmd": r.get("smoke_cmd") or r["cmd"], "lock_hold_max_s": r.get("lock_hold_max_s")}
return out
diff --git a/tools/qualify/report.py b/tools/qualify/report.py
index 184dee9..58f74a3 100644
--- a/tools/qualify/report.py
+++ b/tools/qualify/report.py
@@ -15,8 +15,10 @@ def assemble(meta: dict, args: dict, stages: dict, repo: Path) -> dict:
"""stages: name -> {status, wall_s, data}. Builds the qualify.json document."""
d = {n: s.get("data") for n, s in stages.items() if s.get("status") == "done"}
ctxs = {k: v for k, v in (d.get("maxctx") or {}).items() if k.isdigit()}
+ ctxs.update({k: v for k, v in ((d.get("soak") or {}).get("ctx") or {}).items()}) # the soak-validated value replaces the search result
sv = d.get("serve") or {}
sm = d.get("smoke")
+ dr = d.get("draft") or {}
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:
@@ -27,9 +29,10 @@ def assemble(meta: dict, args: dict, stages: dict, repo: Path) -> dict:
schema=SCHEMA, at=time.strftime("%F %T"), git=git, backend=args["backend"],
pack={k: meta[k] for k in ("name", "arch", "family", "layers", "kv_layers", "kv_heads", "head_dim", "quant", "bpw", "head_bits", "index_sha", "license", "mtp_layers", "vision")},
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,
+ serve=dict(cmd=(d.get("serve") or {}).get("cmd") or (d.get("smoke") or {}).get("cmd"), kv=kv, ctx=ctxs, draft_policy=dr.get("policy") or meta.get("draft_policy"),
+ dflash_dir=dr.get("dflash_dir"), template=meta["template"], lane=lane(meta, args, ctxs, kv, d), hermes=hermes(args, ctxs)),
+ draft=dr or None, soak=d.get("soak"),
+ tuning={k: (d.get("autotune") or {}).get(k) for k in ("tuning_dir", "files", "records", "plan_points", "wall_s", "skipped", "reason", "dense_lines")} 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,
@@ -37,6 +40,52 @@ def assemble(meta: dict, args: dict, stages: dict, repo: Path) -> dict:
)
+LANE_ENV_CUDA = {"EXL3_CUDA_GRAPH": "1"}
+LANE_MAX_TOKENS = 32768 # lane recipe (rtx1/SERVE.md): a reply budget so a runaway think cannot hold a session forever
+
+
+MIN_SHARE = 24576 # tokens one Hermes session needs: the live preamble (SOUL + skills + toolsets) is 15-30K before any work (duel 25/10)
+
+
+def served_config(args: dict, ctxs: dict) -> tuple:
+ """(sessions, -c) of the lane: the largest measured session count whose share of -c holds a Hermes session (--min-share), else a single session
+ at its max -c. Drill 0 picked this by hand (3 x 24K at -c 73,728, then 2 x ... after the OOMs)."""
+ share = args.get("min_share") or MIN_SHARE
+ ok = [(int(k), v) for k, v in ctxs.items() if v and int(k) in args["sessions"]]
+ for s, c in sorted(ok, reverse=True):
+ if c // s >= share:
+ return s, c
+ one = [(s, c) for s, c in ok if s == 1]
+ return one[0] if one else (None, None)
+
+
+def lane(meta: dict, args: dict, ctxs: dict, kv: list, d: dict) -> dict | None:
+ """The command to ship, with the lane-level choices that are not measured per pack (prefix disk, CUDA graphs, reply budget)."""
+ sess, ctx = served_config(args, ctxs)
+ if not ctx:
+ return None
+ import pack as packmod
+ dr = d.get("draft") or {}
+ kvd = d.get("kv") or {}
+ argv = packmod.serve_flags(meta, port=8000, ctx=ctx, sessions=sess, k_bits=kv[0], v_bits=kv[1], draft=dr.get("policy"), dflash_dir=dr.get("dflash_dir"),
+ kv_mode=kvd.get("mode", "quant"), kvwin=kvd.get("kvwin")) + ["--default-max-tokens", str(LANE_MAX_TOKENS)]
+ env = {**(LANE_ENV_CUDA if args["backend"] == "cuda" else {}), "EXL3_PREFIX_DISK_DIR": f"~/cache/prefix-{meta['name']}"}
+ py = (d.get("serve") or {}).get("cmd", [None])[0] or "python"
+ repo = str(args.get("repo") or ".")
+ return dict(sessions=sess, ctx=ctx, env=env, argv=argv, python=py, repo=repo,
+ cmd=f"cd {repo} && env PYTHONPATH={repo} " + " ".join(f"{k}={v}" for k, v in env.items()) + f" {py} -u " + " ".join(argv))
+
+
+def hermes(args: dict, ctxs: dict) -> dict | None:
+ """Hermes provider block for the lane (drill 0: context_length = the lane's real -c, auto-compaction BEFORE the server limit)."""
+ sess, ctx = served_config(args, ctxs)
+ if not ctx:
+ return None
+ share = ctx // sess
+ return dict(model_context_length=ctx, per_session_share=share, compression_threshold=round(min(0.9, 0.8 / sess), 2),
+ note="model.context_length = -c; compression.threshold = 0.8 of one session's share of -c (0.9 max); aux models stay on cloud")
+
+
def fmt(x, nd=3):
return "-" if x is None else (f"{x:.{nd}f}" if isinstance(x, float) else str(x))
@@ -47,26 +96,43 @@ def render_md(j: dict) -> str:
f"{p['arch']} ({p['family']}), {p['layers']} layers ({p['kv_layers']} with KV), {p['quant']} {p['bpw']} bpw, git {j['git']}, {j['at']}", ""]
if v["reasons"]:
L += ["Failed gates: " + "; ".join(v["reasons"])]
+ if v.get("warnings"):
+ L += ["Warnings: " + "; ".join(v["warnings"])]
if v["unmeasured"]:
L += ["Unmeasured (not counted as pass): " + ", ".join(v["unmeasured"])]
L += ["", "## Stages", "| stage | status | wall s |", "|---|---|---|"] + [f"| {n} | {s['status']} | {fmt(s['wall_s'], 0)} |" for n, s in j["stages"].items()]
if j.get("tuning"):
t = j["tuning"]
- L += ["", f"## Day-0 autotune", f"{t['records']} GEMM tuning records ({t['plan_points']} sweep points, {t['wall_s']} s on the device, lock wait excluded) in {t['tuning_dir']}: " + ", ".join(t["files"] or [])]
+ L += ["", "## Day-0 autotune"]
+ if t.get("skipped"):
+ L += [f"skipped: {t.get('reason')}"]
+ if j.get("tuning") and not j["tuning"].get("skipped"):
+ t = j["tuning"]
+ L += [f"{t['records']} GEMM tuning records + {t.get('dense_lines') or 0} dense-GEMM lines ({t['plan_points']} sweep points, {t['wall_s']} s on the device, lock wait excluded) in {t['tuning_dir']}: " + ", ".join(t["files"] or [])]
par = j["quality"]["parity"]
if par:
L += ["", "## Parity vs streamed BF16", f"mean KL {par['kl_mean']:.4f}, top-1 {par['top1_mean']:.4f}, dNLL {par['dnll_mean']:+.4f}; SQNR: {par['sqnr']}", "",
"| domain | KL | top-1 | dNLL |", "|---|---|---|---|"] + [f"| {d} | {x['kl']:.4f} | {x['top1']:.4f} | {x['dnll']:+.4f} |" for d, x in par["by_domain"].items()]
kv = j["quality"]["kv"]
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()]
+ L += ["", f"## KV (chosen k{kv['chosen'][0]}v{kv['chosen'][1]}; {kv['rule']}, kl_max {kv['kl_max']})"]
+ if kv["table"]:
+ L += ["| 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: 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()]
+ dr = j.get("draft")
+ if dr:
+ L += ["", f"## Draft path: **{dr['policy']}**" + (f" ({dr['dflash_dir']})" if dr.get("dflash_dir") else ""), f"{dr.get('reason')}" + (f"; speedup drafted/plain {dr['speedup']} (ABBA, warm-up dropped)" if dr.get("speedup") else "")]
+ if dr.get("notes"):
+ L += ["rejected candidates: " + " | ".join(dr["notes"])]
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()]
+ sk = j.get("soak")
+ if sk:
+ L += ["", "## Soak (mixed agent-shaped load at the max-ctx result; -c steps down 8 % on any error)"] + [f"- {k}: {v}" for k, v in sk["runs"].items()]
sp = j["speed"]
if sp:
L += ["", f"## Speed: decode {fmt(sp['decode_tps_median'],1)} tok/s, prefill 8K {fmt(sp['prefill_8k_tps'],0)} tok/s", "", "| prompt tok | ttft s | prefill tok/s | decode tok/s |", "|---|---|---|---|"]
@@ -75,8 +141,15 @@ def render_md(j: dict) -> str:
if j["sha"]:
L += ["", "Greedy sha: " + ", ".join(x["sha"] for x in j["sha"])]
if j["smoke"]:
- L += ["", f"## Hermes smoke ({j['smoke']['kind']}): {j['smoke']['passed']}/{j['smoke']['total']} passed"]
- L += ["", "## Serve command (no hand flags)", "`" + " ".join(j["serve"]["cmd"] or []) + "`"]
+ L += ["", f"## Hermes smoke ({j['smoke']['kind']}): {j['smoke']['passed']}/{j['smoke']['total']} passed" + (f", mean score {j['smoke']['score_mean']}" if j['smoke'].get('score_mean') is not None else "")]
+ L += [f"- {t.get('task') or t.get('id')}: score {t.get('score')}, {t.get('wall_s')} s, {t.get('tool_calls')} tool calls, {t.get('notes')}" for t in j["smoke"].get("tasks") or []]
+ ln = j["serve"].get("lane")
+ if ln:
+ L += ["", f"## Ship this (sessions {ln['sessions']}, -c {ln['ctx']}, kv k{j['serve']['kv'][0]}v{j['serve']['kv'][1]}, draft {j['serve']['draft_policy']})", "```", ln["cmd"], "```"]
+ h = j["serve"].get("hermes")
+ if h:
+ L += ["", f"Hermes: `model.context_length: {h['model_context_length']}`, `compression.threshold: {h['compression_threshold']}` ({h['note']})"]
+ L += ["", "## Serve command as measured (qualify)", "`" + " ".join(j["serve"]["cmd"] or []) + "`"]
return "\n".join(L) + "\n"
diff --git a/tools/qualify/rules.py b/tools/qualify/rules.py
index a0d6191..27e2433 100644
--- a/tools/qualify/rules.py
+++ b/tools/qualify/rules.py
@@ -23,8 +23,11 @@ KV_DEFAULT_FORMATS = ("k6v6", "kw6") # tq6 / tq5 are measured and reported bu
KV_WIN_SPEC = "4:128" # kw6 = k6v6 + the fp16 sink-4 / window-128 ring
+KV_MODE_MAX_SLOWDOWN = 1.10 # a format whose decode step is > 10 % slower than k6v6's is not a free quality win (Qwen3.5-0.8B on ROCm: kw6 0.0090 vs 0.0068 s/tok)
+
+
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:
+ allowed: tuple = KV_DEFAULT_FORMATS, dec_s: dict | None = None, max_slowdown: float = KV_MODE_MAX_SLOWDOWN) -> 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."""
@@ -32,14 +35,37 @@ def choose_kv_mode(kl: dict[str, float], bits_per_val: dict[str, float], base: s
# 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]
+ if dec_s and dec_s.get(base):
+ ok = [n for n in ok if not dec_s.get(n) or dec_s[n] <= max_slowdown * dec_s[base]]
return min(ok, key=lambda n: (bits_per_val[n], kl[n])) if ok else base
+DRAFT_CHAT_MIN = 0.97 # the adaptive policy must never leave chat slower than plain decode (box-lead 26/10 08:35 gate)
+DRAFT_GAIN_MIN = 1.10 # best kind (code / agentic) must gain at least this to justify the drafter's VRAM (2.2 GiB on the 3090)
+
+
+def choose_draft(speedup: dict[str, float], chat_min: float = DRAFT_CHAT_MIN, gain_min: float = DRAFT_GAIN_MIN) -> tuple[bool, str]:
+ """speedup: {kind: drafted tok/s / plain tok/s} (kinds code / chat / agentic). -> (use_drafter, reason)."""
+ if not speedup:
+ return False, "no measurement"
+ chat = speedup.get("chat")
+ if chat is not None and chat < chat_min:
+ return False, f"chat {chat:.2f}x < {chat_min}"
+ best = max(speedup.values())
+ if best < gain_min:
+ return False, f"best kind {best:.2f}x < {gain_min}"
+ return True, f"best {best:.2f}x, chat {fmt_x(chat)}"
+
+
+def fmt_x(x) -> str:
+ return "-" if x is None else f"{x:.2f}x"
+
+
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)
g.update(gates or {})
- reasons, unmeasured = [], []
+ reasons, unmeasured, warnings = [], [], []
par = q.get("parity")
if par:
if par["kl_mean"] > g["kl_mean"]:
@@ -65,17 +91,23 @@ def verdict(q: dict, gates: dict | None = None) -> dict:
sv = q.get("serve")
if sv:
if not sv.get("sha_self_equal", False):
- reasons.append("greedy sha differs between two identical runs")
+ nd, tot = sv.get("sha_n_diff"), len(sv.get("sha") or [])
+ if nd is not None and tot and 0 < nd < tot: # the repeat runs on a warm prefix cache and, with a drafter, a different verify batch: near-tie numerics (REPORT-27 class)
+ warnings.append(f"greedy sha differs in {nd}/{tot} prompts between the cold run and the repeat (near-tie numerics of the cached-prefix / R-row verify path)")
+ else:
+ reasons.append("greedy sha differs between two identical runs")
if sv.get("oom"):
reasons.append("out of memory in the server log")
- if sv.get("conformance") and not sv["conformance"].get("ok", False):
- reasons.append("template/tool conformance failed: " + sv["conformance"].get("detail", ""))
+ if sv.get("conformance") and not sv["conformance"].get("ok", False): # the vendor chose its own order and trained on it: a warning, not a gate
+ warnings.append("template renders the system text before the tools (" + sv["conformance"].get("detail", "") + "): sessions with different system prompts do not share the tool-schema prefix cache")
else:
unmeasured.append("serve")
sm = q.get("smoke")
if sm:
- if sm["total"] and sm["passed"] / sm["total"] < g["smoke_min"]:
- reasons.append(f"smoke {sm['passed']}/{sm['total']} < {g['smoke_min']:.0%}")
+ if sm["total"]: # graded suite: the mean score decides (a partial 0.4 on a trap task is not a failure of the lane); scripted fallback: pass rate
+ val = sm["score_mean"] if sm.get("score_mean") is not None else sm["passed"] / sm["total"]
+ if val < g["smoke_min"]:
+ reasons.append(f"smoke {'mean score' if sm.get('score_mean') is not None else 'pass rate'} {val:.2f} ({sm['passed']}/{sm['total']}) < {g['smoke_min']:.0%}")
else:
unmeasured.append("smoke")
- return dict(pass_=not reasons and not unmeasured, reasons=reasons, unmeasured=unmeasured)
+ return dict(pass_=not reasons and not unmeasured, reasons=reasons, unmeasured=unmeasured, warnings=warnings)
diff --git a/tools/qualify/server.py b/tools/qualify/server.py
index a7d6772..ff89b1d 100644
--- a/tools/qualify/server.py
+++ b/tools/qualify/server.py
@@ -22,6 +22,28 @@ def health(port: int) -> int:
return 0
+def pick_port(preferred: int, span: int = 200) -> int:
+ """First port >= preferred that nothing listens on (other workers' servers run on 859x too: a fixed port made a soak 'not start')."""
+ import socket
+ for p in range(preferred, preferred + span):
+ with socket.socket() as s:
+ s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ s.bind(("127.0.0.1", p))
+ return p
+ except OSError:
+ continue
+ raise RuntimeError(f"no free port in {preferred}..{preferred + span}")
+
+
+def own_ready(log: Path, port: int) -> bool:
+ """The server we spawned printed 'READY on http://127.0.0.1:<port>' (tools/qwen/serve.py); a foreign server answering /health does not count."""
+ try:
+ return f"READY on http://127.0.0.1:{port}" in log.read_text(errors="replace")
+ except OSError:
+ return False
+
+
def oom_in(log: Path) -> bool:
try:
t = log.read_text(errors="replace").lower()
@@ -31,8 +53,17 @@ def oom_in(log: Path) -> bool:
@contextlib.contextmanager
-def running_server(prof: dict, repo: Path, argv: list[str], port: int, log: Path, ready_s: int = 1500, logf=print):
- """Yield (proc, started) when /health is 200; started=False (proc exited or timeout) lets the caller treat it as 'does not fit'."""
+def running_server(prof: dict, repo: Path, argv: list[str], port: int, log: Path, ready_s: int = 1500, logf=print, args: dict | None = None):
+ """Yield (proc, started) when /health is 200 AND the log says this very process is READY on its port; started=False (proc exited or timeout)
+ lets the caller treat it as 'does not fit'.
+ The port is re-picked HERE, right before the spawn (after the GPU lock wait: another worker's server may have taken the one chosen earlier,
+ and a /health 200 from THEIR server must never pass for ours: 27/10 an autotune sweep went to a foreign server). `args['port']` follows."""
+ new = pick_port(port)
+ if new != port and "--port" in argv:
+ argv = list(argv); argv[argv.index("--port") + 1] = str(new)
+ port = new
+ if args is not None:
+ args["port"] = port
env = {**os.environ, **prof["env"]}
fh = open(log, "wb")
p = subprocess.Popen([prof["python"], "-u", *argv], cwd=repo, env=env, stdout=fh, stderr=subprocess.STDOUT, start_new_session=True)
@@ -42,7 +73,7 @@ def running_server(prof: dict, repo: Path, argv: list[str], port: int, log: Path
while time.time() - t0 < ready_s:
if p.poll() is not None:
break
- if health(port) == 200:
+ if health(port) == 200 and own_ready(log, port):
ok = True; break
time.sleep(3)
logf(f"server pid {p.pid} {'ready' if ok else 'NOT ready'} after {time.time()-t0:.0f} s")
diff --git a/tools/qualify/smoke.py b/tools/qualify/smoke.py
index 8ac9121..cbeb0cb 100644
--- a/tools/qualify/smoke.py
+++ b/tools/qualify/smoke.py
@@ -13,7 +13,20 @@ import time
import urllib.request
from pathlib import Path
-EVAL_DIRS = [Path(os.environ["QUALIFY_EVAL_DIR"])] if os.environ.get("QUALIFY_EVAL_DIR") else []
+def _eval_dirs() -> list:
+ """QUALIFY_EVAL_DIR, then the suite's usual places under $QUALIFY_WORK_ROOT (if set)."""
+ import glob
+ found = [Path(os.environ["QUALIFY_EVAL_DIR"])] if os.environ.get("QUALIFY_EVAL_DIR") else []
+ root = os.environ.get("QUALIFY_WORK_ROOT")
+ if not root:
+ return found
+ home = os.path.expanduser(root)
+ for pat in ("*/*/*/*/harness/eval", "*/hermes_opt/eval", "*/harness/eval"):
+ found += [Path(x) for x in sorted(glob.glob(f"{home}/{pat}"))]
+ return found
+
+
+EVAL_DIRS = _eval_dirs()
DEFAULT_TASKS = "" # filled by pick_tasks from the suite's own task list
@@ -25,17 +38,28 @@ def find_eval() -> Path | None:
return None
-def run_hermes_eval(eval_dir: Path, port: int, model: str, tasks: str, arm: str, timeout: int = 3600) -> dict:
+def run_hermes_eval(eval_dir: Path, port: int, model: str, tasks: str, arm: str, timeout: int = 3600, keep: Path | None = None) -> dict:
env = {**os.environ, "EVAL_API_KEY": "x"}
cmd = ["bash", str(eval_dir / "run_arm.sh"), arm, "-", f"http://127.0.0.1:{port}/v1", model, "1", "--allow-local", "--jobs", "1"] + (["--tasks", tasks] if tasks else [])
r = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=timeout)
f = eval_dir / "runs" / arm / "rep1.json"
if not f.exists():
return dict(kind="hermes_eval", total=0, passed=0, error=(r.stdout + r.stderr)[-400:])
- data = json.loads(f.read_text())
- rows = data if isinstance(data, list) else data.get("results") or data.get("tasks") or []
- ok = [x for x in rows if isinstance(x, dict) and x.get("success")]
- return dict(kind="hermes_eval", total=len(rows), passed=len(ok), tasks=[{k: x.get(k) for k in ("id", "task", "score", "success", "tool_calls")} for x in rows])
+ res = parse_eval(json.loads(f.read_text()))
+ keep = (keep or Path(tempfile.gettempdir())) / f"smoke_{arm}" # the suite writes its runs inside its own checkout: move them out
+ shutil.rmtree(keep, ignore_errors=True)
+ shutil.move(str(f.parent), str(keep))
+ res["runs_dir"] = str(keep)
+ return res
+
+
+def parse_eval(data) -> dict:
+ """run_suite.py's rep json: {"arm", "cells": [{task, status, score, success, wall_s, tool_calls, ...}]} (older shapes: a bare list / results / tasks)."""
+ rows = data if isinstance(data, list) else data.get("cells") or data.get("results") or data.get("tasks") or []
+ rows = [x for x in rows if isinstance(x, dict)]
+ ok = [x for x in rows if x.get("success")]
+ return dict(kind="hermes_eval", total=len(rows), passed=len(ok), score_mean=round(sum(x.get("score") or 0 for x in rows) / len(rows), 3) if rows else None,
+ tasks=[{k: x.get(k) for k in ("task", "id", "score", "success", "wall_s", "tool_calls", "api_turns", "notes")} for x in rows])
_BUGGY = '''def parse_line(line):
diff --git a/tools/qualify/stages.py b/tools/qualify/stages.py
index 58cefd2..8ecc476 100644
--- a/tools/qualify/stages.py
+++ b/tools/qualify/stages.py
@@ -2,6 +2,7 @@
GPU stages run inside job functions that hold the backend locks; every server is started and killed by PID."""
from __future__ import annotations
+import contextlib
import json
import os
import re
@@ -15,11 +16,12 @@ import backends
import docs as docs_mod
import load
import pack as packmod
+import drafter as drafter_mod
import rules
import search
import smoke
-from locks import MIN_MEM_GIB, gpu_locks
-from server import oom_in, running_server
+from locks import LIGHT_GIB, MIN_MEM_GIB, gpu_locks
+from server import oom_in, pick_port, running_server
@dataclass
@@ -31,6 +33,7 @@ class Ctx:
prof: dict
log: callable = print
data: dict = field(default_factory=dict) # stage name -> data (done in this run or resumed)
+ holds: list = field(default_factory=list) # (label, seconds) of every GPU-lock hold of this run
def py(self, script: str, *a, env_extra: dict | None = None, timeout: int = 7200) -> str:
import os
@@ -41,13 +44,36 @@ class Ctx:
raise RuntimeError(f"{script} rc={r.returncode}: {(r.stderr or r.stdout)[-600:]}")
return r.stdout
+ def fresh_port(self) -> int:
+ """Re-pick the server port before every start (kept in args['port']; the first value asked for stays the search base)."""
+ base = self.args.setdefault("port0", self.args["port"])
+ self.args["port"] = pick_port(base)
+ return self.args["port"]
+
def need_ram(self):
a = backends.mem_available_gib()
if a < MIN_MEM_GIB:
raise RuntimeError(f"MemAvailable {a:.1f} GiB < {MIN_MEM_GIB} GiB: not starting a GPU job")
- def locks(self):
- return gpu_locks(self.prof["locks"], self.log)
+ def light_gib(self, ctx: int) -> float:
+ """Upper bound of the device memory a server of this pack needs at -c ctx: weights + the k8v8 cache (the widest default) + 1 GiB of runtime."""
+ return (self.meta["weights_bytes"] + packmod.kv_bytes_per_token(self.meta, 8, 8) * ctx) / 2**30 + 1.0
+
+ @contextlib.contextmanager
+ def locks(self, label: str = "", light_ctx: int | None = None):
+ """GPU locks for ONE unit of work (a server load + its measurements, one KV format, one probe): every hold is timed in c.holds so the
+ stage data can show that none ran long while other workers queued (lead rule 27/10: no stage holds a lock for more than ~15 min).
+ light_ctx = the unit is not a timed measurement (agent-bound smoke) and its server is small (light_gib < LIGHT_GIB): it runs WITHOUT the
+ exclusive GPU locks, so a 0 %-GPU step never queues another worker's cell (box-lead 27/10 08:18)."""
+ light = light_ctx is not None and self.light_gib(light_ctx) < LIGHT_GIB
+ if light:
+ self.log(f"light step '{label}': est. {self.light_gib(light_ctx):.1f} GiB < {LIGHT_GIB:.0f} GiB, not timed: no exclusive GPU lock")
+ with (contextlib.nullcontext() if light else gpu_locks(self.prof["locks"], self.log)):
+ t0 = time.time()
+ try:
+ yield
+ finally:
+ self.holds.append((label, round(time.time() - t0, 1)))
# ---------------------------------------------------------------- cpu stages
@@ -65,17 +91,17 @@ def stage_fetch(c: Ctx) -> dict:
return d
-def fetch_hf(repo: str, dest: str, floor_gb: float) -> dict:
+def fetch_hf(repo: str, dest: str, floor_gb: float, revision: str = "main") -> dict:
"""Download under the disk floor (drill-0 gap 1: license + size + floor were checked by hand)."""
from huggingface_hub import HfApi, snapshot_download
- info = HfApi().model_info(repo, files_metadata=True)
+ info = HfApi().model_info(repo, revision=revision, files_metadata=True)
size = sum(s.size or 0 for s in info.siblings) / 1e9
lic = next((t.split(":", 1)[1] for t in (info.tags or []) if t.startswith("license:")), None)
free = packmod.disk_free_gb(dest)
if free - size < floor_gb:
raise RuntimeError(f"{repo}: {size:.1f} GB would leave {free-size:.1f} GB free < floor {floor_gb} GB")
- snapshot_download(repo, local_dir=dest)
- return dict(repo=repo, size_gb=round(size, 1), license=lic)
+ snapshot_download(repo, revision=revision, local_dir=dest)
+ return dict(repo=repo, revision=revision, size_gb=round(size, 1), license=lic)
def stage_meta(c: Ctx) -> dict:
@@ -112,14 +138,16 @@ def job_autotune(c: Ctx) -> dict:
prof = {**c.prof, "env": {**c.prof["env"], "EXLLAMAV3_TUNE_CACHE": str(scratch), "EXL3_PACK_TUNE": "0",
"EXL3_DENSE_GEMM_TUNE_FILE": str(scratch / "dense_gemm_tune.txt")}}
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)
+ pol, ddir = chosen_draft(c)
+ c.fresh_port()
+ argv = packmod.serve_flags(c.meta, port=c.args["port"], ctx=ctx, sessions=sessions, k_bits=k, v_bits=v, draft=pol, dflash_dir=ddir)
if "--no-vision" not in argv:
argv.append("--no-vision") # the tower is another model (no GEMM autotune keys of the text path) and costs VRAM
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):
+ with running_server(prof, c.repo, argv, c.args["port"], log, logf=c.log, args=c.args) 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
@@ -128,18 +156,20 @@ def job_autotune(c: Ctx) -> dict:
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)
dense_new = _new_dense_lines(scratch / "dense_gemm_tune.txt", Path(__file__).resolve().parents[2] / "exllamav3/model/dense_gemm_tune_seed.txt")
+ if not recs and not dense_new:
+ return dict(skipped=True, reason="the replay produced no tuning record on this backend/build (no coop GEMM autotuner call, no new dense-GEMM line): nothing to ship", plan_points=len(sweep),
+ sweep_failed=[x for x in sweep if not x["ok"]], wall_s=round(time.time() - t0, 1))
if dense_new: # lines the shipped seed did not hold (serve start copies the seed into the scratch file)
(tdir / f"{sig['file']}.dense.txt").write_text("\n".join(dense_new) + "\n")
- tc.write_records(tdir / f"{sig['file']}.bin", recs)
+ if recs: # ROCm serves most shapes through the dense path: no coop records there is normal
+ 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,
+ return dict(tuning_dir=str(tdir), files=sorted(p.name for p in tdir.glob(f"{sig['file']}*")), records=len(recs), records_at_load=at_load, dense_lines=len(dense_new),
plan_points=len(sweep), wall_s=man["wall_s"], sweep_failed=[s for s in sweep if not s["ok"]])
@@ -209,16 +239,26 @@ def job_kv(c: Ctx) -> dict:
if not d.exists():
c.py("docs.py", "long", c.meta["path"], d)
bits = c.args["kv_bits"]
- with c.locks():
- refdir = c.out / "ref_long"
- if not (refdir / "logits_long.pt").exists():
- run_ref(c, d, refdir, tail=1024)
- 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}
- 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))
+ have_ref = bool(c.args.get("ref") and c.meta.get("ref_adapter"))
+ if have_ref:
+ with c.locks():
+ refdir = c.out / "ref_long"
+ if not (refdir / "logits_long.pt").exists():
+ run_ref(c, d, refdir, tail=1024)
+ 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}
+ 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))
+ else: # no BF16 reference on disk (the pack is all there is): the pack-only kvmode measure decides, KL against the pack's own k8v8
+ km = job_kvmode(c, d)
+ k6 = rules.choose_kv({6: km["modes"]["k6v6"]["kl_vs_k8"]}, c.args["kv_kl_max"])
+ out = dict(table={}, chosen=list(k6), kl_max=c.args["kv_kl_max"], mode="quant", rule="no BF16 reference: Q6 if kvmode KL(k6v6 vs k8v8) <= kl_max else k8v8; Q6 format by the kvmode rule")
+ if k6 == (6, 6):
+ out.update(km)
+ else:
+ out["modes"] = km["modes"]
write_kv_choice(c, out)
return out
@@ -227,12 +267,16 @@ def job_kvmode(c: Ctx, docs) -> dict:
"""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)
+ for f in (c.out / "kvmode_raw.json", c.out / "kvmode_raw.json.k8v8.pt"):
+ f.unlink(missing_ok=True)
+ for fmt in ("k8v8", "k6v6", "kw6", "tq6", "tq5"): # one lock take per format (each is a model load + a 32K pass)
+ with c.locks(f"kvmode {fmt}"):
+ c.py("gpu_eval.py", "kvmode", c.meta["path"], docs, c.out / "kvmode_raw.json", c.args.get("kvmode_steps", 256), fmt, 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, allowed=rules.KV_DEFAULT_FORMATS + (("tq6", "tq5") if os.environ.get("QUALIFY_KV_TQ") == "1" else ()))
+ dec = {n: v.get("decode_s_per_tok") for n, v in raw.items()}
+ win = rules.choose_kv_mode(kl, bpv, dec_s=dec, 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":
@@ -246,9 +290,14 @@ def write_kv_choice(c: Ctx, kv: dict) -> None:
k, v = kv["chosen"]
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))
- tmp.replace(Path(c.meta["path"]) / "kv_cache.json")
+ be = c.args.get("backend", "cuda")
+ doc["backend"] = be
+ for name in (f"kv_cache.{be}.json", "kv_cache.json"): # per-backend file (serve.py reads it first); the plain one stays for older servers
+ if name == "kv_cache.json" and (Path(c.meta["path"]) / name).exists() and json.loads((Path(c.meta["path"]) / name).read_text()).get("backend") not in (None, be):
+ continue # never overwrite another backend's choice
+ tmp = Path(c.meta["path"]) / (name + ".tmp")
+ tmp.write_text(json.dumps(doc, indent=1))
+ tmp.replace(Path(c.meta["path"]) / name)
def chosen_kv(c: Ctx) -> tuple:
@@ -256,6 +305,12 @@ def chosen_kv(c: Ctx) -> tuple:
return tuple(kv["chosen"]) if kv else (6, 6) # no reference: owner's Q6 minimum
+def chosen_draft(c: Ctx) -> tuple:
+ """(policy, dflash dir) the later stages serve with: the draft stage's A/B winner, else the pack's own policy (vendor MTP head or off)."""
+ d = c.data.get("draft") or {}
+ return d.get("policy") or packmod.draft_policy(c.meta), d.get("dflash_dir")
+
+
def chosen_kvwin(c: Ctx) -> str | None:
return (c.data.get("kv") or {}).get("kvwin")
@@ -264,10 +319,83 @@ def chosen_kv_mode(c: Ctx) -> str:
return (c.data.get("kv") or {}).get("mode", "quant")
+# ---------------------------------------------------------------- draft path
+def locate_drafter(c: Ctx) -> dict:
+ """Local candidates first (--drafter, <pack>/dflash, ~/models/drafters), then one HF search by model stem (+ download under the disk floor)."""
+ d, notes = drafter_mod.find_local(c.meta, c.args.get("drafter"))
+ if d or c.args.get("no_hf_drafter"):
+ return dict(dir=d, notes=notes, source="local" if d else None)
+ repo = drafter_mod.pick_hf(drafter_mod.search_hf(c.meta))
+ if not repo:
+ return dict(dir=None, notes=notes + ["no HF repo named <model stem> + dflash"], source=None)
+ dest = drafter_mod.DRAFTER_HOME / repo.split("/", 1)[-1]
+ info = fetch_hf(repo, str(dest), c.args["disk_floor_gb"], drafter_mod.hf_revision(repo))
+ bad = drafter_mod.validate(dest, c.meta)
+ if bad:
+ return dict(dir=None, notes=notes + [f"{repo}: " + "; ".join(bad)], source=None, hf=info)
+ return dict(dir=str(dest), notes=notes, source="hf", hf=info)
+
+
+def draft_variants() -> list:
+ """ABBA: plain, drafted, drafted, plain (both orders, so a warm-up or thermal drift hits both policies equally)."""
+ return ["plain", "dflash", "dflash", "plain"]
+
+
+def speedups(runs: list) -> dict:
+ """runs: [{variant, tps: {kind: [tok/s ...]}}] -> {kind: mean drafted tok/s / mean plain tok/s} (warm-up already dropped).
+ A kind with no data point in some variant (a request that returned no decode rate) is left out, not fatal."""
+ out = {}
+ for kind in runs[0]["tps"]:
+ m = {v: [x for r in runs if r["variant"] == v for x in r["tps"].get(kind, [])] for v in ("plain", "dflash")}
+ if m["plain"] and m["dflash"]:
+ out[kind] = round(statistics.mean(m["dflash"]) / statistics.mean(m["plain"]), 3)
+ return out
+
+
+def job_draft(c: Ctx) -> dict:
+ base = packmod.draft_policy(c.meta)
+ if base != "off" or c.meta.get("mtp_layers"): # the pack's own MTP head is the draft path; vendor drafters are for head-less packs
+ return dict(policy=base, dflash_dir=None, reason=f"pack has {c.meta['mtp_layers']} MTP layer(s): policy {base}")
+ loc = locate_drafter(c)
+ if not loc["dir"]:
+ return dict(policy=base, dflash_dir=None, reason="no compatible drafter found", **{k: loc[k] for k in ("notes",)})
+ c.need_ram()
+ k, v = chosen_kv(c)
+ ctx = min(12288, c.meta["max_pos"])
+ runs = []
+ for i, var in enumerate(draft_variants()):
+ with c.locks(f"draft {var}"):
+ c.fresh_port()
+ argv = packmod.serve_flags(c.meta, port=c.args["port"], ctx=ctx, sessions=1, k_bits=k, v_bits=v, kv_mode=chosen_kv_mode(c), kvwin=chosen_kvwin(c),
+ draft="dflash" if var == "dflash" else "off", dflash_dir=loc["dir"] if var == "dflash" else None)
+ log = c.out / f"srv_draft_{i}_{var}.log"
+ with running_server(c.prof, c.repo, argv, c.args["port"], log, logf=c.log, args=c.args) as (p, ok):
+ if not ok:
+ raise RuntimeError(f"draft: {var} server did not start: " + (log.read_text(errors="replace").strip().splitlines() or [""])[-1][:200])
+ cl = load.Client(c.args["port"], "qual")
+ tps, errs = {}, {}
+ for kind, prompts in cl.kind_prompts().items():
+ cl.stream(prompts[0], 64) # warm-up (graphs, caches) discarded
+ rs = [cl.stream(pr, 256) for pr in prompts for _ in range(2)]
+ tps[kind] = [r["dec_tps"] for r in rs if r["dec_tps"]]
+ if len(tps[kind]) < len(rs):
+ errs[kind] = [r["err"] or f"ntok={r['ntok']}" for r in rs if not r["dec_tps"]][:2]
+ runs.append(dict(variant=var, tps=tps, errs=errs, oom=oom_in(log)))
+ c.log(f"draft: {var}: " + ", ".join(f"{k_} {statistics.mean(x):.1f}" for k_, x in tps.items() if x) + " tok/s" + (f"; unmeasured {errs}" if errs else ""))
+ sp = speedups(runs)
+ use, why = rules.choose_draft(sp)
+ return dict(policy="dflash" if use else base, dflash_dir=loc["dir"] if use else None, drafter=loc["dir"], source=loc["source"], speedup=sp, reason=why, runs=runs,
+ lock_hold_max_s=max((h for _, h in c.holds), default=None),
+ note="adaptive depth (--dflash-adapt on)" if use else "drafter measured but not kept")
+
+
# ---------------------------------------------------------------- max ctx
def start_args(c: Ctx, ctx: int, sessions: int) -> list:
+ c.fresh_port()
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), kvwin=chosen_kvwin(c))
+ pol, ddir = chosen_draft(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),
+ draft=pol, dflash_dir=ddir)
def probe_factory(c: Ctx, sessions: int):
@@ -275,11 +403,16 @@ def probe_factory(c: Ctx, sessions: int):
state = {"cal": False}
def probe(ctx: int):
+ with c.locks(f"maxctx s{sessions} c{ctx}"): # one lock take per probe: a probe is a load + 2 near-full prompts (+ rounds)
+ return probe_locked(ctx)
+
+ def probe_locked(ctx: int):
log = c.out / f"srv_maxctx_s{sessions}_c{ctx}.log"
- with running_server(c.prof, c.repo, start_args(c, ctx, sessions), c.args["port"], log, logf=c.log) as (p, ok):
+ with running_server(c.prof, c.repo, start_args(c, ctx, sessions), c.args["port"], log, logf=c.log, args=c.args) as (p, ok):
if not ok:
tail = log.read_text(errors="replace").strip().splitlines()[-1:] or [""]
return False, "no start: " + tail[0][:160]
+ cl.url = f"http://127.0.0.1:{c.args['port']}"
if not state["cal"]:
cl.calibrate(); state["cal"] = True
for slot in (0, 1): # 2 distinct near-full prompts back to back
@@ -300,62 +433,127 @@ def job_maxctx(c: Ctx) -> dict:
c.need_ram()
out = {}
k, v = chosen_kv(c)
- with c.locks():
+ with c.locks("maxctx free-memory read"): # the free-memory bound is only meaningful while nobody else holds the device
free = backends.gpu_free_mib(c.args["backend"])
- for s in c.args["sessions"]:
- 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)
- c.log(f"maxctx sessions={s}: KV {bpt/1024:.1f} KB/token, search [{lo}, {hi}]")
- r = search.bisect_max(lo, hi, probe_factory(c, s))
- out[str(s)] = r["best"]
- out[f"tried_s{s}"] = r["tried"]
+ for s in c.args["sessions"]:
+ 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)
+ c.log(f"maxctx sessions={s}: KV {bpt/1024:.1f} KB/token, search [{lo}, {hi}]")
+ r = search.bisect_max(lo, hi, probe_factory(c, s))
+ out[str(s)] = r["best"]
+ out[f"tried_s{s}"] = r["tried"]
+ out["lock_hold_max_s"] = max((h for _, h in c.holds), default=None)
+ return out
+
+
+def served_ctx(c: Ctx) -> dict:
+ """{sessions: -c} the lanes get: the soak-validated value where the soak ran, else the max-ctx search result."""
+ mc = {k: v for k, v in (c.data.get("maxctx") or {}).items() if k.isdigit()}
+ mc.update({k: v for k, v in ((c.data.get("soak") or {}).get("ctx") or {}).items() if v})
+ return mc
+
+
+def gpu_used_mib(c: Ctx):
+ f = backends.gpu_free_mib(c.args["backend"])
+ return None if f is None else round(f, 0)
+
+
+def job_soak(c: Ctx) -> dict:
+ """Mixed-load validation of each max-ctx result (drill 0 gap: synthetic probes passed, real agent load OOMed hours later). Per session count:
+ serve at the search result, run `--soak-s` seconds of load.Client.soak; any error or OOM line -> -c x 0.92 (rounded to 2048), up to 4 steps.
+ One lock take per attempt (a load + the soak seconds)."""
+ c.need_ram()
+ out = dict(ctx={}, runs={})
+ mc = {k: v for k, v in (c.data.get("maxctx") or {}).items() if k.isdigit() and v}
+ for s_ in c.args["sessions"]:
+ ctx = mc.get(str(s_))
+ if not ctx:
+ continue
+ for attempt in range(4):
+ log = c.out / f"srv_soak_s{s_}_c{ctx}.log"
+ with c.locks(f"soak s{s_} c{ctx}"):
+ with running_server(c.prof, c.repo, start_args(c, ctx, s_), c.args["port"], log, logf=c.log, args=c.args) as (p, ok):
+ if not ok:
+ r = dict(ok=False, why="no start")
+ else:
+ cl = load.Client(c.args["port"], "qual"); cl.calibrate()
+ r = cl.soak(s_, ctx, c.args["soak_s"], vram=lambda: gpu_used_mib(c))
+ r["ok"] = not r["n_errors"] and not oom_in(log) and r["requests"] > 0
+ r["oom_log"] = oom_in(log)
+ out["runs"][f"s{s_}_c{ctx}"] = {k: v for k, v in r.items() if k != "vram_curve"} | dict(free_mib_min=min((x for x in r.get("vram_curve", []) if x is not None), default=None))
+ c.log(f"soak sessions={s_} -c {ctx}: {'ok' if r['ok'] else 'FAILED'} {out['runs'][f's{s_}_c{ctx}']}")
+ if r["ok"]:
+ out["ctx"][str(s_)] = ctx
+ break
+ ctx = int(ctx * 0.92) // 2048 * 2048
+ else:
+ out["ctx"][str(s_)] = None
+ out["lock_hold_max_s"] = max((h for _, h in c.holds), default=None)
return out
# ---------------------------------------------------------------- serve + smoke (one server load)
def job_serve(c: Ctx, do_serve: bool, do_smoke: bool) -> dict:
c.need_ram()
- mc = c.data.get("maxctx") or {}
+ mc = served_ctx(c)
sess = max(c.args["sessions"])
ctx = mc.get(str(sess)) or max((v for k, v in mc.items() if k.isdigit() and v), default=None)
if not ctx:
ctx = c.args.get("ctx_cap") or 32768
c.log(f"serve: no max-ctx result, using {ctx}")
sess_eff = sess if mc.get(str(sess)) else 1
+ import report
+ ship_s, ship_c = report.served_config(c.args, mc) # the smoke runs on the config that would ship (a real Hermes preamble is 15-30K)
+ ship_s, ship_c = (ship_s, ship_c) if ship_c else (sess_eff, ctx)
out = dict(serve={}, smoke=None)
- with c.locks():
- log = c.out / "srv_serve.log"
- argv = start_args(c, ctx, sess_eff)
- out["cmd"] = [c.prof["python"], *argv]
- with running_server(c.prof, c.repo, argv, c.args["port"], log, logf=c.log) as (p, ok):
- if not ok:
- raise RuntimeError("serve: server did not become ready; see " + str(log))
- cl = load.Client(c.args["port"], "qual")
- cl.calibrate()
- s = {}
- if do_serve:
- s["conformance"] = cl.conformance()
- s["decode_short"] = [cl.stream(cl.prompt(300, i), 256) for i in range(3)]
- s["prefill_8k"] = [cl.stream(cl.prompt(8000, i + 3), 1) for i in range(3)]
- curve, t = [], 2048
- while t <= int(ctx * 0.9):
- r = cl.stream(cl.prompt(t, 7), 64)
- curve.append(dict(prompt=r["ptok"], ttft=r["ttft"], prefill_tps=round(r["ptok"] / r["ttft"], 1) if r["ptok"] and r["ttft"] else None, dec_tps=r["dec_tps"], err=r["err"]))
- t *= 4
- s["curve"] = curve
- s["agg"] = [cl.concurrent(n, min(4096, ctx // max(4, sess_eff) - 256), 128) for n in range(1, sess_eff + 1)]
- a, b = cl.sha_set(), cl.sha_set()
- s["sha"], s["sha_self_equal"] = a, [x["sha"] for x in a] == [x["sha"] for x in b]
- s["oom"] = oom_in(log)
- for r in s["decode_short"] + s["prefill_8k"]:
- r.pop("t0", None); r.pop("first", None); r.pop("end", None)
- s["decode_tps_median"] = statistics.median(r["dec_tps"] for r in s["decode_short"] if r["dec_tps"])
- s["prefill_8k_tps"] = statistics.median(r["ptok"] / r["ttft"] for r in s["prefill_8k"] if r["ptok"] and r["ttft"])
- out["serve"] = s
- if do_smoke:
- out["smoke"] = run_smoke(c)
+
+ def on_server(label, ctx_, sess_, fn, light=False):
+ """One lock take = one server load + one group of measurements (bounded hold: the lead's rule, no stage holds a GPU lock for long).
+ light=True: a small model's untimed step (the Hermes smoke) takes no exclusive lock (Ctx.locks)."""
+ with c.locks(label, light_ctx=ctx_ if light else None):
+ log = c.out / f"srv_{label}.log"
+ argv = start_args(c, ctx_, sess_)
+ with running_server(c.prof, c.repo, argv, c.args["port"], log, logf=c.log, args=c.args) as (p, ok):
+ if not ok:
+ raise RuntimeError(f"{label}: server did not become ready; see {log}")
+ cl = load.Client(c.args["port"], "qual")
+ cl.calibrate()
+ return fn(cl, log), [c.prof["python"], *argv]
+
+ if do_serve:
+ def quick(cl, log):
+ s = {"conformance": cl.conformance()}
+ s["decode_short"] = [cl.stream(cl.prompt(300, i), 256) for i in range(3)]
+ s["prefill_8k"] = [cl.fit(8000, i + 3, 1, topup=False) for i in range(3)]
+ a, b = cl.sha_set(), cl.sha_set()
+ s["sha"], s["sha_self_equal"] = a, [x["sha"] for x in a] == [x["sha"] for x in b]
+ s["sha_repeat"] = [x["sha"] for x in b]
+ s["sha_n_diff"] = sum(x["sha"] != y["sha"] for x, y in zip(a, b))
+ s["oom"] = oom_in(log)
+ for r in s["decode_short"] + s["prefill_8k"]:
+ r.pop("t0", None); r.pop("first", None); r.pop("end", None)
+ s["decode_tps_median"] = statistics.median(r["dec_tps"] for r in s["decode_short"] if r["dec_tps"])
+ s["prefill_8k_tps"] = statistics.median(r["ptok"] / r["ttft"] for r in s["prefill_8k"] if r["ptok"] and r["ttft"])
+ return s
+
+ def deep(cl, log):
+ curve, t = [], 2048
+ while t <= int(ctx * 0.9):
+ r = cl.fit(t, 7, 64, topup=False)
+ curve.append(dict(prompt=r["ptok"], ttft=r["ttft"], prefill_tps=round(r["ptok"] / r["ttft"], 1) if r["ptok"] and r["ttft"] else None, dec_tps=r["dec_tps"], err=r["err"]))
+ t *= 4
+ return dict(curve=curve, agg=[cl.concurrent(n, min(4096, ctx // max(4, sess_eff) - 256), 128) for n in range(1, sess_eff + 1)], oom=oom_in(log))
+ s, out["cmd"] = on_server("serve", ctx, sess_eff, quick)
+ d, _ = on_server("serve_deep", ctx, sess_eff, deep)
+ s.update(curve=d["curve"], agg=d["agg"], oom=s["oom"] or d["oom"])
+ out["serve"] = s
+ if do_smoke: # always on the config that would ship, in its own load
+ out["smoke"], out["smoke_cmd"] = on_server("smoke", ship_c, ship_s, lambda cl, log: run_smoke(c), light=True)
+ if not do_serve:
+ out["cmd"] = out["smoke_cmd"]
+ out["lock_hold_max_s"] = max((h for _, h in c.holds), default=None)
return out
@@ -370,7 +568,7 @@ def run_smoke(c: Ctx) -> dict:
ev = smoke.find_eval()
if ev:
tasks = c.args.get("smoke_tasks") or pick_tasks(ev, 4)
- res = smoke.run_hermes_eval(ev, c.args["port"], "qual", tasks, f"qualify_{c.meta['name']}")
+ res = smoke.run_hermes_eval(ev, c.args["port"], "qual", tasks, f"qualify_{c.meta['name']}", keep=c.out)
if res["total"]:
return res
c.log("smoke: hermes eval gave no result, falling back to the scripted tool loop: " + str(res.get("error"))[:200])
diff --git a/tools/qualify/tests/fake_serve.py b/tools/qualify/tests/fake_serve.py
index ad7ef58..a8095b1 100644
--- a/tools/qualify/tests/fake_serve.py
+++ b/tools/qualify/tests/fake_serve.py
@@ -40,4 +40,6 @@ class H(BaseHTTPRequestHandler):
self.wfile.write(b"data: " + json.dumps({"choices": [], "usage": {"prompt_tokens": pt, "completion_tokens": min(mt, 20)}}).encode() + b"\n\ndata: [DONE]\n\n")
-ThreadingHTTPServer(("127.0.0.1", a.port), H).serve_forever()
+srv = ThreadingHTTPServer(("127.0.0.1", a.port), H)
+print(f"qserve: READY on http://127.0.0.1:{a.port} model=fake", flush=True)
+srv.serve_forever()
diff --git a/tools/qualify/tests/test_convert.py b/tools/qualify/tests/test_convert.py
new file mode 100644
index 0000000..89dbb29
--- /dev/null
+++ b/tools/qualify/tests/test_convert.py
@@ -0,0 +1,78 @@
+"""CPU tests of the conversion step: template carry-over, argv, memory guard pause/resume on a real child process."""
+from __future__ import annotations
+
+import json
+import os
+import signal
+import subprocess
+import sys
+import tempfile
+import time
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent))
+
+import backends # noqa: E402
+import convert_job as cj # noqa: E402
+
+
+class ConvertTests(unittest.TestCase):
+ def test_argv_resume_and_extra(self):
+ a = cj.convert_argv("/s", "/w", "/p", 4.0, 6, True, ["-hq"])
+ self.assertEqual(a, ["convert.py", "-i", "/s", "-w", "/w", "-o", "/p", "-b", "4.0", "-hb", "6", "-r", "-hq"])
+
+ def test_template_carried_from_file_then_tokenizer_config(self):
+ with tempfile.TemporaryDirectory() as t:
+ t = Path(t); src, pack = t / "src", t / "pack"; src.mkdir(); pack.mkdir()
+ (src / "tokenizer_config.json").write_text(json.dumps({"chat_template": "{{ x }}"}))
+ self.assertEqual(cj.carry_template(src, pack), "tokenizer_config")
+ self.assertEqual((pack / "chat_template.jinja").read_text(), "{{ x }}")
+ self.assertEqual(cj.carry_template(src, pack), "pack") # never overwrites the pack's own
+ (pack / "chat_template.jinja").unlink(); (src / "chat_template.jinja").write_text("FILE")
+ self.assertEqual(cj.carry_template(src, pack), "source file")
+ (pack / "chat_template.jinja").unlink(); (src / "chat_template.jinja").unlink(); (src / "tokenizer_config.json").write_text("{}")
+ self.assertIsNone(cj.carry_template(src, pack))
+
+ def test_pack_complete_needs_config_quant_index_and_shards(self):
+ with tempfile.TemporaryDirectory() as t:
+ p = Path(t)
+ self.assertFalse(cj.pack_complete(p))
+ (p / "config.json").write_text("{}"); (p / "quantization_config.json").write_text("{}")
+ (p / "model.safetensors.index.json").write_text(json.dumps({"weight_map": {"a": "s.safetensors"}}))
+ self.assertFalse(cj.pack_complete(p)) # shard missing
+ (p / "s.safetensors").write_bytes(b"x")
+ self.assertTrue(cj.pack_complete(p))
+
+ def test_single_shard_pack_without_index_is_complete(self):
+ with tempfile.TemporaryDirectory() as t:
+ p = Path(t)
+ (p / "config.json").write_text("{}"); (p / "quantization_config.json").write_text("{}")
+ self.assertFalse(cj.pack_complete(p))
+ (p / "model.safetensors").write_bytes(b"x")
+ self.assertTrue(cj.pack_complete(p))
+
+ def test_memguard_stops_and_continues_only_its_group(self):
+ proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"], start_new_session=True)
+ real = backends.mem_available_gib
+ try:
+ logs = []
+ backends.mem_available_gib = lambda: 1.0 # below the pause line
+ g = cj.MemGuard(proc.pid, 6, 10, logs.append, poll_s=0.05); g.start()
+ time.sleep(0.4)
+ self.assertTrue(g.stopped)
+ self.assertIn("T", Path(f"/proc/{proc.pid}/stat").read_text().split(") ")[1][:1]) # state T = stopped
+ backends.mem_available_gib = lambda: 50.0
+ time.sleep(0.4)
+ self.assertFalse(g.stopped)
+ self.assertNotIn("T", Path(f"/proc/{proc.pid}/stat").read_text().split(") ")[1][:1])
+ self.assertEqual(g.pauses, 1)
+ g.finish(); g.join(1)
+ finally:
+ backends.mem_available_gib = real
+ os.killpg(proc.pid, signal.SIGKILL); proc.wait()
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/qualify/tests/test_draft.py b/tools/qualify/tests/test_draft.py
new file mode 100644
index 0000000..5ce8e6f
--- /dev/null
+++ b/tools/qualify/tests/test_draft.py
@@ -0,0 +1,202 @@
+"""CPU tests of the draft-path discovery (drafter.py), the draft rule and the draft A/B arithmetic."""
+from __future__ import annotations
+
+import json
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+HERE = Path(__file__).resolve().parent
+sys.path.insert(0, str(HERE.parent))
+
+import drafter # noqa: E402
+import pack as packmod # noqa: E402
+import plan as planmod # noqa: E402
+import rules # noqa: E402
+import stages # noqa: E402
+from test_plan import args, fake_pack # noqa: E402
+
+
+def fake_drafter(d: Path, hidden=128, taps=(1, 3), arch="DFlash2DraftModel", tap_shift=None, vocab=None):
+ d.mkdir(parents=True, exist_ok=True)
+ dc = {"block_size": 8, "target_layer_ids": list(taps)}
+ if tap_shift is not None:
+ dc["tap_shift"] = tap_shift
+ cfg = {"architectures": [arch], "hidden_size": hidden, "dflash_config": dc}
+ if vocab:
+ cfg["vocab_size"] = vocab
+ (d / "config.json").write_text(json.dumps(cfg))
+ (d / "model.safetensors").write_bytes(b"x")
+ return d
+
+
+class DrafterTests(unittest.TestCase):
+ def setUp(self):
+ self.t = tempfile.TemporaryDirectory()
+ self.root = Path(self.t.name)
+ (self.root / "my-model-33b-exl3-4.0").mkdir()
+ self.pack = fake_pack(self.root / "my-model-33b-exl3-4.0")
+ self.meta = packmod.read_pack(self.pack)
+
+ def tearDown(self):
+ self.t.cleanup()
+
+ def test_stem_strips_the_quantization_suffix(self):
+ self.assertEqual(drafter.stem("nanbeige43-33b-exl3-4.0"), "nanbeige43-33b")
+ self.assertEqual(drafter.stem("qwen38-27b-exl3-td-sc4.0"), "qwen38-27b")
+ self.assertEqual(drafter.stem("Foo-7B-4.0bpw"), "Foo-7B")
+ self.assertIn(drafter.norm("nanbeige43-33b"), drafter.norm("Nanbeige4.3-33B-DFlash2"))
+
+ def test_structural_validation(self):
+ ok = fake_drafter(self.root / "ok")
+ self.assertEqual(drafter.validate(ok, self.meta), [])
+ self.assertTrue(drafter.validate(fake_drafter(self.root / "w", hidden=64), self.meta))
+ self.assertTrue(drafter.validate(fake_drafter(self.root / "t", taps=(1, 9)), self.meta)) # layer 9 >= 4 layers
+ self.assertTrue(drafter.validate(fake_drafter(self.root / "a", arch="Qwen3ForCausalLM"), self.meta))
+ self.assertTrue(drafter.validate(fake_drafter(self.root / "v", vocab=999), self.meta))
+ self.assertEqual(drafter.validate(self.root / "nowhere", self.meta), ["no readable config.json"])
+
+ def test_find_local_prefers_the_explicit_export_and_pack_dir(self):
+ a = fake_drafter(self.root / "dr" / "a")
+ b = fake_drafter(self.root / "dr" / "b", tap_shift=0)
+ old = drafter.DRAFTER_HOME
+ drafter.DRAFTER_HOME = self.root / "dr"
+ try:
+ self.assertEqual(drafter.find_local(self.meta)[0], str(b)) # states its tap convention
+ self.assertEqual(drafter.find_local(self.meta, str(a))[0], str(a)) # explicit --drafter wins
+ fake_drafter(self.pack / "dflash") # a pack-side dir is a candidate too; the stated export still wins
+ self.assertEqual(drafter.find_local(self.meta)[0], str(b))
+ finally:
+ drafter.DRAFTER_HOME = old
+
+ def test_pick_hf_skips_quantized_variants(self):
+ ids = ["x/M-DFlash2-GGUF", "x/M-DFlash2", "y/M-DFlash-long"]
+ self.assertEqual(drafter.pick_hf(ids), "x/M-DFlash2")
+ self.assertIsNone(drafter.pick_hf(["x/M-DFlash2-GGUF", "x/M-DFlash-mlx"]))
+
+
+class RuleTests(unittest.TestCase):
+ def test_adaptive_drafter_kept_when_chat_holds_and_agentic_gains(self):
+ self.assertEqual(rules.choose_draft({"code": 1.23, "chat": 1.0, "agentic": 2.28})[0], True)
+
+ def test_chat_loss_or_no_gain_refuses(self):
+ self.assertEqual(rules.choose_draft({"code": 1.5, "chat": 0.94, "agentic": 2.3})[0], False)
+ self.assertEqual(rules.choose_draft({"code": 1.05, "chat": 1.0, "agentic": 1.08})[0], False)
+ self.assertEqual(rules.choose_draft({})[0], False)
+
+ def test_speedups_are_means_over_both_orders(self):
+ runs = [dict(variant="plain", tps={"chat": [10.0, 10.0]}), dict(variant="dflash", tps={"chat": [20.0, 20.0]}),
+ dict(variant="dflash", tps={"chat": [22.0, 22.0]}), dict(variant="plain", tps={"chat": [12.0, 12.0]})]
+ self.assertEqual(stages.speedups(runs), {"chat": 1.909})
+ self.assertEqual(stages.draft_variants(), ["plain", "dflash", "dflash", "plain"])
+
+
+class PlanOrderTests(unittest.TestCase):
+ def test_draft_runs_before_autotune_and_maxctx(self):
+ o = planmod.ORDER
+ self.assertLess(o.index("kv"), o.index("draft"))
+ self.assertLess(o.index("draft"), o.index("autotune"))
+ self.assertLess(o.index("autotune"), o.index("maxctx"))
+
+ def test_serve_flags_carry_the_drafter(self):
+ with tempfile.TemporaryDirectory() as t:
+ m = packmod.read_pack(fake_pack(Path(t)))
+ f = packmod.serve_flags(m, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6, draft="dflash", dflash_dir="/d")
+ self.assertEqual((f[f.index("--draft-policy") + 1], f[f.index("--dflash-dir") + 1]), ("dflash", "/d"))
+ self.assertNotIn("--dflash-dir", packmod.serve_flags(m, port=1, ctx=4096, sessions=1, k_bits=6, v_bits=6))
+
+
+class LockUnitTests(unittest.TestCase):
+ def test_every_lock_take_is_timed_and_released_between_units(self):
+ with tempfile.TemporaryDirectory() as t:
+ m = packmod.read_pack(fake_pack(Path(t)))
+ c = stages.Ctx(m, args(), Path(t), Path(t), {"locks": [str(Path(t) / "x.lock")]}, lambda *_: None)
+ for i in range(3):
+ with c.locks(f"unit {i}"):
+ pass
+ self.assertEqual([h[0] for h in c.holds], ["unit 0", "unit 1", "unit 2"])
+ self.assertTrue(all(h[1] >= 0 for h in c.holds))
+
+
+ def test_light_untimed_step_takes_no_exclusive_lock_but_a_big_model_does(self):
+ import fcntl
+ import os
+ with tempfile.TemporaryDirectory() as t:
+ lk = str(Path(t) / "x.lock")
+ m = packmod.read_pack(fake_pack(Path(t)))
+ logs = []
+ c = stages.Ctx(m, args(), Path(t), Path(t), {"locks": [lk]}, logs.append)
+ fd = os.open(lk, os.O_RDWR | os.O_CREAT, 0o644); fcntl.flock(fd, fcntl.LOCK_EX) # another worker's cell holds the device
+ try:
+ m["weights_bytes"] = 1 << 30
+ with c.locks("smoke", light_ctx=8192): # would block forever if it took the lock
+ pass
+ self.assertTrue(any("no exclusive GPU lock" in x for x in logs))
+ self.assertEqual(c.holds[0][0], "smoke")
+ m["weights_bytes"] = 8 << 30 # not light: the unit goes through the lock path
+ self.assertGreater(c.light_gib(8192), stages.LIGHT_GIB)
+ m["weights_bytes"] = 1 << 30
+ self.assertLess(c.light_gib(8192), stages.LIGHT_GIB)
+ finally:
+ os.close(fd)
+ with c.locks("timed"): # no light_ctx: always locked (lock free again here)
+ pass
+ self.assertTrue(any("lock held" in x for x in logs))
+
+
+class PortTests(unittest.TestCase):
+ def test_pick_port_skips_a_busy_port(self):
+ import socket
+ import server
+ with socket.socket() as s:
+ s.bind(("127.0.0.1", 0)); busy = s.getsockname()[1]
+ s.listen(1)
+ self.assertNotEqual(server.pick_port(busy), busy)
+
+
+class KvPresetTests(unittest.TestCase):
+ def test_preset_is_written_per_backend_and_never_overwrites_another_backend(self):
+ with tempfile.TemporaryDirectory() as t:
+ m = packmod.read_pack(fake_pack(Path(t)))
+ kv = dict(chosen=[6, 6], mode="quant")
+ c1 = stages.Ctx(m, args(backend="cuda"), Path(t), Path(t), {}, print)
+ stages.write_kv_choice(c1, kv)
+ c2 = stages.Ctx(m, args(backend="rocm"), Path(t), Path(t), {}, print)
+ stages.write_kv_choice(c2, dict(chosen=[8, 8], mode="quant"))
+ self.assertEqual(json.loads((Path(t) / "kv_cache.cuda.json").read_text())["k_bits"], 6)
+ self.assertEqual(json.loads((Path(t) / "kv_cache.rocm.json").read_text())["k_bits"], 8)
+ self.assertEqual(json.loads((Path(t) / "kv_cache.json").read_text())["backend"], "cuda") # the neutral file keeps the first writer
+
+
+class SmokeParseTests(unittest.TestCase):
+ def test_run_suite_rep_json_cells(self):
+ import smoke
+ d = {"arm": "a", "cells": [dict(task="fix_bug_py", score=1.0, success=True, wall_s=69.0, tool_calls=7, notes="+hidden5/5"),
+ dict(task="trap_readonly", score=0.2, success=False, wall_s=39.0, tool_calls=3, notes="-tree_unchanged")]}
+ r = smoke.parse_eval(d)
+ self.assertEqual((r["total"], r["passed"], r["score_mean"]), (2, 1, 0.6))
+ self.assertEqual(smoke.parse_eval([])["total"], 0)
+
+
+class LaneTests(unittest.TestCase):
+ def test_lane_command_and_hermes_block_come_from_the_measured_config(self):
+ import report
+ with tempfile.TemporaryDirectory() as t:
+ m = packmod.read_pack(fake_pack(Path(t)))
+ a = args(sessions=[1, 3])
+ ctxs = {"1": 65536, "3": 49152}
+ d = {"draft": dict(policy="dflash", dflash_dir="/d"), "kv": dict(mode="quant", kvwin="4:128")}
+ ln = report.lane(m, a, ctxs, [6, 6], d)
+ self.assertEqual((ln["sessions"], ln["ctx"]), (1, 65536)) # 49152/3 = 16K < 24K share: ship one session
+ a = args(sessions=[1, 3], min_share=8192)
+ ln = report.lane(m, a, ctxs, [6, 6], d)
+ self.assertEqual((ln["sessions"], ln["ctx"]), (3, 49152))
+ self.assertIn("--dflash-dir /d", ln["cmd"]); self.assertIn("--kvwin 4:128", ln["cmd"]); self.assertIn("EXL3_PREFIX_DISK_DIR", ln["cmd"])
+ h = report.hermes(a, ctxs)
+ self.assertEqual((h["model_context_length"], h["per_session_share"], h["compression_threshold"]), (49152, 16384, 0.27))
+ self.assertIsNone(report.lane(m, a, {"1": None}, [6, 6], {}))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tools/qualify/tests/test_plan.py b/tools/qualify/tests/test_plan.py
index b0b8b24..c35db95 100644
--- a/tools/qualify/tests/test_plan.py
+++ b/tools/qualify/tests/test_plan.py
@@ -50,6 +50,17 @@ class PackTests(unittest.TestCase):
self.assertEqual(f[f.index("--chat-template") + 1], str(Path(t) / "chat_template.jinja"))
self.assertEqual(m["problems"], [])
+ def test_unlisted_qwen_arch_resolves_by_model_type(self):
+ qx = {"model_type": "qwen4_exp", "text_config": {"num_hidden_layers": 8, "num_attention_heads": 8, "num_key_value_heads": 2, "head_dim": 16,
+ "hidden_size": 128, "layer_types": ["linear_attention"] * 3 + ["full_attention"] + ["linear_attention"] * 3 + ["full_attention"]}}
+ with tempfile.TemporaryDirectory() as t:
+ m = packmod.read_pack(fake_pack(Path(t), arch="Qwen4ExpForConditionalGeneration", extra=qx))
+ self.assertEqual((m["family"], m["serve_entry"], m["kv_layers"]), ("hybrid_gdn", "tools/qwen/serve.py", 2))
+ self.assertEqual(m["problems"], [])
+ with tempfile.TemporaryDirectory() as t: # a genuinely unknown model_type still refuses
+ m = packmod.read_pack(fake_pack(Path(t), arch="FooForCausalLM", extra={"model_type": "foo"}))
+ self.assertTrue(any("no serve entry" in x for x in m["problems"]))
+
def test_mtp_head_selects_mix(self):
with tempfile.TemporaryDirectory() as t:
m = packmod.read_pack(fake_pack(Path(t), mtp=1))
@@ -89,9 +100,14 @@ class PlanTests(unittest.TestCase):
def names(self, plan, status):
return [s.name for s in plan if s.status == status]
- def test_full_plan_without_ref_skips_parity_and_kv_with_reason(self):
+ def test_full_plan_without_ref_skips_parity_but_kv_runs_pack_only(self):
p = planmod.build_plan(self.meta(), args(), {})
self.assertEqual([s.name for s in p], planmod.ORDER)
+ self.assertEqual(self.names(p, "skip"), ["parity"])
+ self.assertIn("kvmode", next(s for s in p if s.name == "kv").note)
+
+ def test_no_ref_and_no_kv_modes_skips_kv_with_reason(self):
+ p = planmod.build_plan(self.meta(), args(kv_modes=False), {})
self.assertEqual(self.names(p, "skip"), ["parity", "kv"])
self.assertIn("k6v6", next(s for s in p if s.name == "kv").note)
@@ -241,6 +257,13 @@ class KvModeRule(unittest.TestCase):
BPV = {"k6v6": 6.5, "kw6": 6.5, "tq6": 6.0625, "tq5": 5.0625}
TQ = ("k6v6", "kw6", "tq6", "tq5")
+ def test_kv_mode_refuses_a_format_with_a_slower_decode_step(self):
+ bpv = {"k6v6": 6.5, "kw6": 6.5, "tq6": 6.06, "tq5": 5.06}
+ kl = {"k6v6": 0.0007, "kw6": 0.00035, "tq6": 0.0004, "tq5": 0.0009}
+ self.assertEqual(rules.choose_kv_mode(kl, bpv), "kw6")
+ self.assertEqual(rules.choose_kv_mode(kl, bpv, dec_s={"k6v6": 0.0068, "kw6": 0.0090, "tq6": 0.0118, "tq5": 0.0070}), "k6v6") # ROCm 0.8B: ring +32 %
+ self.assertEqual(rules.choose_kv_mode(kl, bpv, dec_s={"k6v6": 0.0068, "kw6": 0.0071}), "kw6")
+
def test_choose_kv_mode(self):
bpv = self.BPV
# tq opt-in (default): tq6 / tq5 never win, kw6 does when it beats k6v6 by the margin
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index b44fb65..7e54ded 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -2257,7 +2257,12 @@ 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
+ # lane preset written by tools/qualify (kv stage): used only when no KV flag is given. One file per backend (the CUDA and ROCm
+ # runs of the same pack choose independently), kv_cache.json as the backend-neutral fallback
+ import torch
+ kvp = Path(model_dir) / f"kv_cache.{'rocm' if torch.version.hip else 'cuda'}.json"
+ if not kvp.is_file():
+ kvp = Path(model_dir) / "kv_cache.json"
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())
diff --git a/tools/strix_halo/ck_fmha/build.sh b/tools/strix_halo/ck_fmha/build.sh
new file mode 100755
index 0000000..0f9ac7c
--- /dev/null
+++ b/tools/strix_halo/ck_fmha/build.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# Build libckpf.so: Composable Kernel fmha_fwd (stock gfx115 fp16 tiles, hd128 + hd256, batch mode, causal/none) behind
+# a C ABI (ckpf_fwd) used by EXL3_PF_CK (auto: used when the library exists). CK_SRC is a local ROCm/composable_kernel checkout
+# (tested at 6f44fdf90f69adee742ec3660b95d32963b9bd2d); with CK_FETCH=1 and no CK_SRC that commit is fetched (shallow) into a temp dir.
+# Output: $EXL3_CK_OUT (default ~/.cache/kyojin/ck-fmha/libckpf.so). ~33 s on 8 cores.
+# Compiler: ROCM_CLANG, else amdclang++ of the rocm-sdk-devel wheel ($EXL3_ROCM_SDK), else /opt/rocm. GCC_DIR = libstdc++ install dir (default 13).
+set -euo pipefail
+CK_PIN=6f44fdf90f69adee742ec3660b95d32963b9bd2d
+if [ -z "${CK_SRC:-}" ] && [ "${CK_FETCH:-0}" = 1 ]; then
+ CK_SRC=$(mktemp -d); FETCHED=$CK_SRC
+ git -C "$CK_SRC" init -q && git -C "$CK_SRC" fetch -q --depth 1 https://github.com/ROCm/composable_kernel.git "$CK_PIN" \
+ && git -C "$CK_SRC" checkout -q FETCH_HEAD
+fi
+: "${CK_SRC:?set CK_SRC to a composable_kernel checkout (or CK_FETCH=1)}"
+HERE=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
+OUT=${EXL3_CK_OUT:-${XDG_CACHE_HOME:-$HOME/.cache}/kyojin/ck-fmha/libckpf.so}
+CXX=${ROCM_CLANG:-}
+for c in "${EXL3_ROCM_SDK:-/nonexistent}/lib/llvm/bin/amdclang++" "${EXL3_ROCM_SDK:-/nonexistent}/llvm/bin/amdclang++" /opt/rocm/bin/amdclang++; do
+ if [ -z "$CXX" ] && [ -x "$c" ]; then CXX=$c; fi
+done
+: "${CXX:?no amdclang++ found: set ROCM_CLANG}"
+GCC_DIR=${GCC_DIR:-/usr/lib/gcc/x86_64-linux-gnu/13}
+F=$CK_SRC/example/ck_tile/01_fmha
+B=$(mktemp -d); trap 'rm -rf "$B" "${FETCHED:-}"' EXIT
+mkdir -p "$B/gen" "$B/obj" "$(dirname "$OUT")"
+python3 "$F/generate.py" --targets gfx1151 --api fwd --optdim 128,256 -r 0 \
+ -f "*fp16*batch*_nlogits_nbias_*_nlse_ndropout_nskip_nqscale*_nsink*" -o "$B/gen" >/dev/null
+FLAGS="--gcc-install-dir=$GCC_DIR -std=c++20 -O3 -fPIC -x hip --offload-arch=gfx1151 -I$CK_SRC/include -I$F -I$B/gen \
+ -DCK_TILE_FMHA_FWD_FAST_EXP2=1 -fgpu-flush-denormals-to-zero -DCK_TILE_FMHA_FWD_SPLITKV_API=0 -DCK_TILE_FMHA_FWD_APPENDKV_API=0 \
+ -DCK_TILE_FMHA_FWD_PAGEDKV_API=0 -DCK_TILE_FMHA_FWD_BATCH_PREFILL_API=0 -w"
+ls "$B"/gen/*.cpp "$HERE/ckpf_shim.cpp" | xargs -P "${CK_JOBS:-8}" -I{} sh -c "$CXX $FLAGS -c {} -o $B/obj/\$(basename {} .cpp).o"
+"$CXX" --gcc-install-dir="$GCC_DIR" -shared -fPIC --offload-arch=gfx1151 "$B"/obj/*.o -o "$OUT"
+echo "built $OUT"
diff --git a/tools/strix_halo/ck_fmha/ckpf_shim.cpp b/tools/strix_halo/ck_fmha/ckpf_shim.cpp
new file mode 100644
index 0000000..193fd30
--- /dev/null
+++ b/tools/strix_halo/ck_fmha/ckpf_shim.cpp
@@ -0,0 +1,36 @@
+// ckpf: C ABI over CK fmha_fwd (batch mode, bshd, fp16, GQA, causal bottom-right)
+#include <cmath>
+#include <cstdint>
+#include <hip/hip_runtime.h>
+#include "bias.hpp"
+#include "fmha_fwd.hpp"
+#include "mask.hpp"
+
+extern "C" float ckpf_fwd(const void* q, const void* k, const void* v, void* o,
+ int batch, int sq, int sk, int hq, int hk, int dq, int dv,
+ float scale, int causal, hipStream_t stream, int time_it)
+{
+ fmha_fwd_traits t{};
+ t.hdim_q = dq; t.hdim_v = dv; t.data_type = "fp16"; t.is_group_mode = false;
+ t.is_v_rowmajor = true; t.has_logits_soft_cap = false;
+ t.mask_type = causal ? mask_enum::mask_bottom_right : mask_enum::no_mask;
+ t.bias_type = bias_enum::no_bias; t.has_lse = false; t.has_dropout = false;
+ t.qscale_type = quant_scale_enum::no_scale;
+ fmha_fwd_args a{};
+ a.q_ptr = q; a.k_ptr = k; a.v_ptr = v; a.o_ptr = o;
+ a.seqlen_q = sq; a.seqlen_k = sk; a.batch = batch; a.max_seqlen_q = sq;
+ a.hdim_q = dq; a.hdim_v = dv; a.nhead_q = hq; a.nhead_k = hk;
+ a.scale_s = scale; a.logits_soft_cap = 0.f;
+ a.stride_q = hq * dq; a.stride_k = hk * dq; a.stride_v = hk * dv; a.stride_o = hq * dv;
+ a.nhead_stride_q = dq; a.nhead_stride_k = dq; a.nhead_stride_v = dv; a.nhead_stride_o = dv;
+ a.batch_stride_q = (ck_tile::index_t)sq * hq * dq;
+ a.batch_stride_k = (ck_tile::index_t)sk * hk * dq;
+ a.batch_stride_v = (ck_tile::index_t)sk * hk * dv;
+ a.batch_stride_o = (ck_tile::index_t)sq * hq * dv;
+ a.window_size_left = -1; a.window_size_right = causal ? 0 : -1;
+ a.mask_type = static_cast<ck_tile::index_t>(t.mask_type);
+ a.p_drop = 0.f; a.s_randval = false;
+ a.drop_seed_offset = std::pair<uint64_t, uint64_t>{0, 0};
+ ck_tile::stream_config cfg{stream, time_it != 0, 0, 0, 1, false};
+ return fmha_fwd(t, a, cfg);
+}