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.

Run-time A/B knobs: exllamav3.util.knobs (call-time reads, set_knobs drops captured graphs and per-shape state) and an opt-in loopback POST /admin/knobs (--admin-knobs) in the Qwen and GLM servers

YanissAmzb90e96d8c502
diff --git a/exllamav3/ext_fallbacks.py b/exllamav3/ext_fallbacks.py
index 0e40a67..7b7f21c 100644
--- a/exllamav3/ext_fallbacks.py
+++ b/exllamav3/ext_fallbacks.py
@@ -12,6 +12,7 @@ from __future__ import annotations
from typing import Any
import os
+from .util.knobs import knob_on
import torch
import torch.nn.functional as F
@@ -691,7 +692,7 @@ 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":
+ if torch.version.hip and knob_on("EXL3_DEQ_WINDOW_TRITON"):
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)
diff --git a/exllamav3/modules/attention_fn/qdec_cuda.py b/exllamav3/modules/attention_fn/qdec_cuda.py
index 3256a1d..22b40eb 100644
--- a/exllamav3/modules/attention_fn/qdec_cuda.py
+++ b/exllamav3/modules/attention_fn/qdec_cuda.py
@@ -10,12 +10,14 @@ import math
import os
import torch
+
+from ...util.knobs import knob, knob_int, knob_on, on_change
import triton
_SRC = os.path.join(os.path.dirname(__file__), "cu", "qdec.cu")
_SRC_ROWS = os.path.join(os.path.dirname(__file__), "cu", "qdec_rows.cu") # many-row kernel (verify steps), see qdec_rows.cu
_COMMON = os.path.join(os.path.dirname(__file__), "cu", "qdec_common.cuh")
-ROWS_MODE = os.environ.get("EXL3_QDEC_ROWS", "1") # 0: no many-row kernel, 1: only where qdec.cu cannot, 2: always
+ROWS_MODE = knob("EXL3_QDEC_ROWS", "1") # 0: no many-row kernel, 1: only where qdec.cu cannot, 2: always
_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exl3_qdec"))
_kernels = {}
@@ -76,10 +78,10 @@ def _compile(cfg):
PAGE=cfg["page"], NW=cfg["nw"], ST=cfg["st"], CAUSAL=int(cfg["causal"]), BLOCK_ROWS=cfg["block_rows"],
HD_PAD=triton.next_power_of_2(cfg["hd"]), SCALE=repr(float(cfg["scale"])) + "f", KEY_LO=cfg.get("key_lo", 0),
TQ=int(cfg.get("tq", False)))
- defs["L2HINT"] = int(os.environ.get("EXL3_QDEC_L2HINT", "1")) # L2 evict_first on K/V, evict_last on the scales
- defs["FASTDQ"] = 1 if cfg.get("tq") else int(os.environ.get("EXL3_QDEC_FASTDQ", "1")) # permuted-order PRMT/LOP3 bit-plane unpack (qdec.cu)
- if os.environ.get("EXL3_QDEC_ABL"):
- defs["ABL"] = int(os.environ["EXL3_QDEC_ABL"])
+ defs["L2HINT"] = knob_int("EXL3_QDEC_L2HINT", 1) # L2 evict_first on K/V, evict_last on the scales
+ defs["FASTDQ"] = 1 if cfg.get("tq") else knob_int("EXL3_QDEC_FASTDQ", 1) # permuted-order PRMT/LOP3 bit-plane unpack (qdec.cu)
+ if knob("EXL3_QDEC_ABL"):
+ defs["ABL"] = int(knob("EXL3_QDEC_ABL"))
src = "#define INFINITY __int_as_float(0x7f800000)\n" + open(_COMMON).read() + "\n" + \
open(_SRC_ROWS if cfg.get("rows_kernel") else _SRC).read()
major, minor = torch.cuda.get_device_capability()
@@ -147,8 +149,13 @@ class _Kernel:
assert r == driver.CUresult.CUDA_SUCCESS, r
+def _compile_knobs():
+ """the switches _compile bakes into the cubin: part of the kernel cache key, so a run-time flip picks (or builds) the other kernel"""
+ return (knob("EXL3_QDEC_L2HINT", "1"), knob("EXL3_QDEC_FASTDQ", "1"), knob("EXL3_QDEC_ABL"))
+
+
def get_kernel(cfg):
- key = tuple(sorted(cfg.items()))
+ key = tuple(sorted(cfg.items())) + (_compile_knobs(),)
k = _kernels.get(key)
if k is None:
k = _kernels[key] = _Kernel(cfg)
@@ -157,7 +164,7 @@ def get_kernel(cfg):
def rows_nw(hd):
"""warps per CTA of the many-row kernel (each takes hd/32/nw 32-dim groups)"""
- return int(os.environ.get("EXL3_QDEC_RNW", "0")) or (4 if (hd // 32) % 4 == 0 else 2)
+ return knob_int("EXL3_QDEC_RNW", 0) or (4 if (hd // 32) % 4 == 0 else 2)
def static_smem(cfg) -> int:
@@ -171,7 +178,7 @@ def pick_nw_st(cfg):
c = dict(cfg)
if cfg.get("rows_kernel"):
c.update(nw=rows_nw(cfg["hd"]))
- for st in ((int(os.environ["EXL3_QDEC_RST"]),) if os.environ.get("EXL3_QDEC_RST") else (3, 2, 1)):
+ for st in ((int(knob("EXL3_QDEC_RST")),) if knob("EXL3_QDEC_RST") else (3, 2, 1)):
c.update(st=st)
if geometry(c)["shared"] <= 99 * 1024:
return c["nw"], st
@@ -184,9 +191,17 @@ def pick_nw_st(cfg):
raise QdecUnsupported("no ring configuration fits")
-ENABLED = os.environ.get("EXL3_QDEC", "1") != "0" and not torch.version.hip
+ENABLED = knob_on("EXL3_QDEC") and not torch.version.hip
# graph (BC) path switch (EXL3_QDEC_GRAPH=0 keeps the Triton split kernel in captured graphs)
-GRAPH_ENABLED = os.environ.get("EXL3_QDEC_GRAPH", "1") != "0"
+GRAPH_ENABLED = knob_on("EXL3_QDEC_GRAPH")
+
+
+@on_change
+def _refresh_knobs():
+ global ROWS_MODE, ENABLED, GRAPH_ENABLED
+ ROWS_MODE = knob("EXL3_QDEC_ROWS", "1")
+ ENABLED = knob_on("EXL3_QDEC") and not torch.version.hip
+ GRAPH_ENABLED = knob_on("EXL3_QDEC_GRAPH")
_sm = {}
@@ -232,10 +247,10 @@ def split_cap(cfg, device, programs):
"""kv splits per program: one full wave of resident CTAs (the many-row kernel's CTAs are small and several fit an SM;
qdec.cu keeps one CTA's share per SM)"""
sm = sm_count(device)
- if cfg.get("rows_kernel") and not os.environ.get("EXL3_QDEC_SPL"):
+ if cfg.get("rows_kernel") and not knob("EXL3_QDEC_SPL"):
sm *= get_kernel(cfg).blocks_per_sm()
- elif os.environ.get("EXL3_QDEC_SPL"):
- return int(os.environ["EXL3_QDEC_SPL"])
+ elif knob("EXL3_QDEC_SPL"):
+ return int(knob("EXL3_QDEC_SPL"))
return max(1, sm // programs)
diff --git a/exllamav3/modules/attention_fn/qdec_hip.py b/exllamav3/modules/attention_fn/qdec_hip.py
index 9ce5ff7..374b227 100644
--- a/exllamav3/modules/attention_fn/qdec_hip.py
+++ b/exllamav3/modules/attention_fn/qdec_hip.py
@@ -13,9 +13,18 @@ import subprocess
import torch
+from ...util.knobs import knob, knob_int, knob_on, on_change
+
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qdec.hip")
_CACHE = os.path.expanduser(os.environ.get("EXL3_QDEC_CACHE", "~/.cache/exllamav3"))
-ENABLED = bool(torch.version.hip) and os.environ.get("EXL3_QDEC_HIP", "1") != "0"
+ENABLED = bool(torch.version.hip) and knob_on("EXL3_QDEC_HIP")
+
+
+@on_change
+def _refresh_knobs():
+ global ENABLED
+ ENABLED = bool(torch.version.hip) and knob_on("EXL3_QDEC_HIP")
+
_kernels = {}
_bufs = {}
_lib = None
@@ -33,11 +42,11 @@ def _hip():
def pick_dw(hd, nt, nw):
"""waves per stream splitting the head dim: the smallest count that keeps the O accumulators (NT * HD/16 * 8 / DW floats) in budget"""
- if os.environ.get("EXL3_QDEC_HIP_DW"):
- dw = int(os.environ["EXL3_QDEC_HIP_DW"])
+ if knob("EXL3_QDEC_HIP_DW"):
+ dw = int(knob("EXL3_QDEC_HIP_DW"))
return dw if dw in (1, 2, 4) and nw % dw == 0 and hd // 16 // dw >= 4 else None
for dw in (1, 2, 4):
- if nw % dw == 0 and hd // 16 // dw >= 4 and nt * (hd // 16) * 8 // dw <= int(os.environ.get("EXL3_QDEC_HIP_MAXO", "96")):
+ if nw % dw == 0 and hd // 16 // dw >= 4 and nt * (hd // 16) * 8 // dw <= knob_int("EXL3_QDEC_HIP_MAXO", 96):
return dw
return None
@@ -63,7 +72,7 @@ def make_cfg(q_len, n_q_heads, n_kv_heads, head_dim, k_bits, v_bits, page_size,
return None
if head_dim not in (128, 256) or n_q_heads % n_kv_heads != 0 or page_size % 16 != 0:
return None
- nw = int(os.environ.get("EXL3_QDEC_HIP_NW", "0")) or 4
+ nw = knob_int("EXL3_QDEC_HIP_NW", 0) or 4
nt = (q_len * (n_q_heads // n_kv_heads) + 15) // 16
dw = pick_dw(head_dim, nt, nw)
if dw is None:
@@ -79,7 +88,7 @@ def _compile(cfg, arch):
from exllamav3.util import hip_compiler
defs = dict(HD=cfg["hd"], KB=cfg["kb"], VB=cfg["vb"], NKV=cfg["nkv"], NQH=cfg["nqh"], QLEN=cfg["qlen"], PAGE=cfg["page"],
NW=cfg["nw"], DW=cfg["dw"], CAUSAL=int(cfg["causal"]), HAS_SINKS=int(cfg["sinks"]), KEY_LO=cfg["key_lo"], TQ=int(cfg.get("tq", False)), SCALE=repr(float(cfg["scale"])) + "f")
- extra = [f"-D{k}={v}" for k, v in defs.items()] + os.environ.get("EXL3_QDEC_HIP_FLAGS", "").split()
+ extra = [f"-D{k}={v}" for k, v in defs.items()] + knob("EXL3_QDEC_HIP_FLAGS", "").split()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off", "--no-gpu-bundle-output"] + extra
gcc = os.environ.get("EXL3_GCC_INSTALL_DIR", "/usr/lib/gcc/x86_64-linux-gnu/13")
if os.path.isdir(gcc):
@@ -123,7 +132,7 @@ class _Kernel:
def get_kernel(cfg, device):
- key = (device.index, tuple(sorted(cfg.items())))
+ key = (device.index, tuple(sorted(cfg.items())), knob("EXL3_QDEC_HIP_FLAGS", ""))
k = _kernels.get(key)
if k is None:
k = _kernels[key] = _Kernel(cfg, device)
diff --git a/exllamav3/modules/attention_fn/triton_paged.py b/exllamav3/modules/attention_fn/triton_paged.py
index 8cc0f9e..70c90a7 100644
--- a/exllamav3/modules/attention_fn/triton_paged.py
+++ b/exllamav3/modules/attention_fn/triton_paged.py
@@ -7,6 +7,7 @@ import triton
import triton.language as tl
from .common import AttnArgs, get_non_causal_span_arglist
+from ...util.knobs import knob, knob_int, on_change
def _is_power_of_2(x: int) -> bool:
@@ -723,7 +724,7 @@ _pf_fa2_rows = int(os.environ.get("EXL3_PF_FA2_ROWS", "1024"))
_pf_row_slice = int(os.environ.get("EXL3_PF_ROW_SLICE", "256" if torch.version.hip else "0"))
# ROCm waves_per_eu launch hint of the fp16 prefill kernel (hd <= 256); 0 = compiler default
-_pf_waves_per_eu = int(os.environ.get("EXL3_PF_WAVES_PER_EU", "2"))
+_pf_waves_per_eu = knob_int("EXL3_PF_WAVES_PER_EU", 2)
def _prefill_fa2_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):
from torch.nn.attention import sdpa_kernel, SDPBackend
@@ -749,11 +750,21 @@ def _prefill_fa2_contig(q, kd, vd, past, n_kvh, head_dim, scale, out):
# 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_mode = knob("EXL3_PF_CK", "auto")
_pf_ck = _pf_ck_mode != "0" and bool(torch.version.hip)
_pf_ck_fn = None
+@on_change
+def _refresh_pf_knobs():
+ """EXL3_PF_CK / EXL3_PF_WAVES_PER_EU switched at run time (util.knobs.set_knobs): re-derive the module state. A library that
+ failed to load is retried (the next _pf_ck_load decides again)."""
+ global _pf_ck_mode, _pf_ck, _pf_waves_per_eu
+ _pf_ck_mode = knob("EXL3_PF_CK", "auto")
+ _pf_ck = _pf_ck_mode != "0" and bool(torch.version.hip)
+ _pf_waves_per_eu = knob_int("EXL3_PF_WAVES_PER_EU", 2)
+
+
def _pf_ck_load():
global _pf_ck_fn, _pf_ck
if _pf_ck_fn is None:
@@ -1179,6 +1190,12 @@ from . import qdec_hip as _qh
_QDEC_HIP = _qh.ENABLED
+@on_change
+def _refresh_qdec_hip():
+ global _QDEC_HIP
+ _QDEC_HIP = _qh.ENABLED # also re-arms a kernel that was switched off after a launch failure
+
+
_QDEC_HIP_DEBUG = os.environ.get("EXL3_QDEC_HIP_DEBUG") == "1"
_qdec_hip_stats = {}
diff --git a/exllamav3/modules/attn.py b/exllamav3/modules/attn.py
index e330196..0241b2f 100644
--- a/exllamav3/modules/attn.py
+++ b/exllamav3/modules/attn.py
@@ -10,7 +10,7 @@ from .multilinear import MultiLinear, SlicedMultiLinear
from .quant.exl3 import MAX_BSZN_GEMV_R, row_pad_pitch
from ..ext import exllamav3_ext as ext
from ..model.model_tp_alloc import TPAllocation
-from ..util import profile_opt
+from ..util import profile_opt, knobs
import os
from .attention_fn.bc_attn import bc_attn_enable as _bc_attn_enable, build_bc_attn, MAX_BSZ as _bc_max_bsz, MAX_QLEN as _bc_max_qlen
@@ -459,7 +459,9 @@ class Attention(Module):
self.multi_qg = None
self.tp_reduce = False
self.dispatch_cache = {}
+ knobs.clear_on_change(self, "dispatch_cache") # the kernel picked per call shape may depend on a knob
self.bc_attn = {}
+ knobs.clear_on_change(self, "bc_attn") # BCAttn objects bake knob values (EXL3_QDEC_GRAPH, EXL3_BC_KVWIN...)
self.q_norm_tensor = None
self.k_norm_tensor = None
@@ -645,6 +647,7 @@ class Attention(Module):
super().unload()
self.bc_attn = {}
+ knobs.clear_on_change(self, "bc_attn") # BCAttn objects bake knob values (EXL3_QDEC_GRAPH, EXL3_BC_KVWIN...)
for cl in self.cache_layers:
cl.free()
diff --git a/exllamav3/util/knobs.py b/exllamav3/util/knobs.py
new file mode 100644
index 0000000..ce25d64
--- /dev/null
+++ b/exllamav3/util/knobs.py
@@ -0,0 +1,103 @@
+"""Run-time switchable A/B knobs.
+
+knob(name, default) reads os.environ when it is called (never at import), so one server can flip a switch between requests.
+set_knobs({name: value}) is the only writer: it sets or unsets the environment, and when a value really changed it drops everything
+that may have baked the old one in (captured CUDA graphs, block graphs, per-shape kernel caches registered with on_change).
+Only names in KNOBS are accepted; the table holds the default each call site passes, so the effective value of an unset knob is known.
+"""
+import os
+import weakref
+from typing import Callable, Optional
+
+# name -> default (str). The call sites pass the same default to knob(); tests/test_knobs.py checks the two agree.
+KNOBS = {
+ "EXL3_DEQ_WINDOW_TRITON": "1",
+ "EXL3_GEMV_TRI": "1",
+ "EXL3_BC_KVWIN": "1",
+ "EXL3_CUDA_GRAPH_RING": "1",
+ "EXL3_DEC_MOE_KBS_A": "0",
+ "EXL3_DEC_MOE_KBS_B": "0",
+ "EXL3_PF_CK": "auto",
+ "EXL3_PF_WAVES_PER_EU": "2",
+ "EXL3_QDEC": "1",
+ "EXL3_QDEC_HIP": "1",
+ "EXL3_QDEC_GRAPH": "1",
+ "EXL3_QDEC_ROWS": "1",
+ "EXL3_QDEC_L2HINT": "1",
+ "EXL3_QDEC_FASTDQ": "1",
+ "EXL3_QDEC_RNW": "0",
+ "EXL3_QDEC_RST": "",
+ "EXL3_QDEC_SPL": "",
+ "EXL3_QDEC_ABL": "",
+ "EXL3_QDEC_HIP_NW": "0",
+ "EXL3_QDEC_HIP_DW": "",
+ "EXL3_QDEC_HIP_MAXO": "96",
+ "EXL3_QDEC_HIP_FLAGS": "",
+}
+
+_hooks: list = []
+_tracked: list = [] # (weakref to an object, attribute name of a dict it caches knob-dependent state in)
+
+
+def knob(name: str, default: Optional[str] = None) -> Optional[str]:
+ return os.environ.get(name, default)
+
+
+def knob_int(name: str, default: int) -> int:
+ v = os.environ.get(name)
+ return default if v is None or v == "" else int(v)
+
+
+def knob_on(name: str, default: str = "1") -> bool:
+ """True unless the value is '0' (the 'X != "0"' idiom of the switches)"""
+ return os.environ.get(name, default) != "0"
+
+
+def on_change(fn: Callable[[], None]) -> Callable[[], None]:
+ """Register a cache clearer that set_knobs runs after a value changed. Decorator-friendly."""
+ _hooks.append(fn)
+ return fn
+
+
+def clear_on_change(obj, attr: str) -> None:
+ """obj.<attr> (a dict) holds objects built from knob values (for example the per-layer BC attention graphs): set_knobs empties it."""
+ _tracked[:] = [t for t in _tracked if t[0]() is not None]
+ if not any(t[0]() is obj and t[1] == attr for t in _tracked):
+ _tracked.append((weakref.ref(obj), attr))
+
+
+def effective(names=None) -> dict:
+ return {n: os.environ.get(n, KNOBS[n]) for n in (names or KNOBS)}
+
+
+def invalidate() -> None:
+ """Drop every captured graph and registered per-shape cache. Graphs are imported lazily: a CPU-only process has none."""
+ import sys
+ for modname, fn in (("exllamav3.model.cuda_graph", "purge"), ("exllamav3.modules.block_graph", "purge")):
+ m = sys.modules.get(modname)
+ if m is not None:
+ getattr(m, fn)()
+ for ref, attr in _tracked:
+ obj = ref()
+ if obj is not None:
+ getattr(obj, attr).clear()
+ for h in list(_hooks):
+ h()
+
+
+def set_knobs(values: dict) -> dict:
+ """Apply {name: value} (None unsets). Returns the effective values of ALL knobs. Raises ValueError, nothing applied, on an
+ unknown name. Graphs and caches are dropped only when an effective value changed."""
+ bad = [n for n in values if n not in KNOBS]
+ if bad:
+ raise ValueError("unknown knob(s): " + ", ".join(sorted(bad)) + "; known: " + ", ".join(sorted(KNOBS)))
+ before = effective()
+ for n, v in values.items():
+ if v is None:
+ os.environ.pop(n, None)
+ else:
+ os.environ[n] = str(v)
+ after = effective()
+ if after != before:
+ invalidate()
+ return after
diff --git a/tests/test_knobs.py b/tests/test_knobs.py
new file mode 100644
index 0000000..85d7dfb
--- /dev/null
+++ b/tests/test_knobs.py
@@ -0,0 +1,174 @@
+"""CPU checks of run-time A/B knobs (exllamav3.util.knobs) and POST /admin/knobs (tools/admin_knobs.py)."""
+import asyncio
+import contextlib
+import os
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+from exllamav3.util import knobs
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "tools"))
+
+
[email protected](autouse = True)
+def clean_env():
+ saved = {n: os.environ.get(n) for n in knobs.KNOBS}
+ for n in knobs.KNOBS:
+ os.environ.pop(n, None)
+ knobs.set_knobs({})
+ yield
+ for n, v in saved.items():
+ if v is None:
+ os.environ.pop(n, None)
+ else:
+ os.environ[n] = v
+ knobs.invalidate()
+
+
+def test_defaults_match_call_sites():
+ """the default each knob()/knob_int()/knob_on() call passes is the one the table advertises"""
+ pat = re.compile(r'knob(?:_int|_on)?\(\s*"(EXL3_[A-Z0-9_]+)"(?:\s*,\s*([^)]*?))?\s*\)')
+ seen = {}
+ for p in (ROOT / "exllamav3").rglob("*.py"):
+ for name, dflt in pat.findall(p.read_text()):
+ if name in knobs.KNOBS and dflt:
+ seen.setdefault(name, set()).add(dflt.strip().strip('"'))
+ for name, dflts in seen.items():
+ assert dflts == {knobs.KNOBS[name]}, (name, dflts, knobs.KNOBS[name])
+ assert {"EXL3_PF_CK", "EXL3_QDEC_ROWS", "EXL3_PF_WAVES_PER_EU"} <= set(seen)
+
+
+def test_every_knob_is_read_through_the_helper():
+ """no module reads a switchable knob with a bare os.environ (it would not follow set_knobs)"""
+ bare = []
+ for p in (ROOT / "exllamav3").rglob("*.py"):
+ if p.name == "knobs.py":
+ continue
+ for n in knobs.KNOBS:
+ if re.search(r'os\.environ(?:\.get)?[\[(]\s*"%s"' % n, p.read_text()):
+ bare.append((p.name, n))
+ assert not bare, bare
+
+
+def test_module_state_follows_and_restores():
+ from exllamav3.modules.attention_fn import bc_attn, qdec_cuda, triton_paged as tp
+ base = (bc_attn._kvwin_bc, qdec_cuda.ENABLED, qdec_cuda.ROWS_MODE, qdec_cuda.GRAPH_ENABLED, tp._pf_waves_per_eu, tp._pf_ck_mode)
+ eff = knobs.set_knobs({"EXL3_BC_KVWIN": "0", "EXL3_QDEC": "0", "EXL3_QDEC_ROWS": "2", "EXL3_QDEC_GRAPH": "0",
+ "EXL3_PF_WAVES_PER_EU": 4, "EXL3_PF_CK": "0"})
+ assert (eff["EXL3_BC_KVWIN"], eff["EXL3_PF_WAVES_PER_EU"]) == ("0", "4")
+ assert (bc_attn._kvwin_bc, qdec_cuda.ENABLED, qdec_cuda.ROWS_MODE, qdec_cuda.GRAPH_ENABLED, tp._pf_waves_per_eu, tp._pf_ck_mode) \
+ == (False, False, "2", False, 4, "0")
+ assert tp._pf_ck is False
+ knobs.set_knobs({n: None for n in eff})
+ assert (bc_attn._kvwin_bc, qdec_cuda.ENABLED, qdec_cuda.ROWS_MODE, qdec_cuda.GRAPH_ENABLED, tp._pf_waves_per_eu, tp._pf_ck_mode) == base
+ assert knobs.effective() == knobs.KNOBS
+
+
+def test_call_time_reads():
+ from exllamav3.modules.attention_fn import qdec_cuda
+ assert knobs.knob("EXL3_GEMV_TRI", "1") == "1"
+ knobs.set_knobs({"EXL3_GEMV_TRI": 0, "EXL3_QDEC_FASTDQ": 0})
+ assert knobs.knob("EXL3_GEMV_TRI", "1") == "0"
+ assert qdec_cuda._compile_knobs()[1] == "0" # part of the kernel cache key: the flipped cubin is its own entry
+
+
+def test_unknown_knob_applies_nothing():
+ with pytest.raises(ValueError, match="EXL3_NOPE"):
+ knobs.set_knobs({"EXL3_GEMV_TRI": "0", "EXL3_NOPE": "1"})
+ assert "EXL3_GEMV_TRI" not in os.environ
+
+
+def test_invalidate_only_on_a_real_change(monkeypatch):
+ calls = []
+ monkeypatch.setattr(knobs, "invalidate", lambda: calls.append(1))
+ knobs.set_knobs({"EXL3_GEMV_TRI": "1"}) # equals the default: nothing changes
+ knobs.set_knobs({"EXL3_GEMV_TRI": "0"})
+ knobs.set_knobs({"EXL3_GEMV_TRI": "0"})
+ knobs.set_knobs({"EXL3_GEMV_TRI": None})
+ assert len(calls) == 2
+
+
+def test_invalidate_runs_graph_purges_and_hooks(monkeypatch):
+ import exllamav3.model.cuda_graph as cg
+ import exllamav3.modules.block_graph as bg
+ hit = []
+ monkeypatch.setattr(cg, "purge", lambda model = None: hit.append("cuda"))
+ monkeypatch.setattr(bg, "purge", lambda: hit.append("block"))
+ knobs.on_change(lambda: hit.append("hook"))
+ try:
+ knobs.set_knobs({"EXL3_DEC_MOE_KBS_A": 9})
+ assert hit == ["cuda", "block", "hook"]
+ finally:
+ knobs._hooks.pop()
+
+
+def _serve(handler_engine, exclusive, calls):
+ from aiohttp import web
+ from aiohttp.test_utils import TestClient, TestServer
+ import admin_knobs
+ app = web.Application()
+ h = admin_knobs.make_handler(handler_engine, exclusive)
+ app.router.add_get("/admin/knobs", h)
+ app.router.add_post("/admin/knobs", h)
+ return TestClient(TestServer(app))
+
+
+def test_admin_endpoint():
+ order = []
+
+ class Engine:
+ async def run_exclusive(self, fn, *a):
+ order.append("run")
+ return fn(*a)
+
+ async def reset_prefix_cache(self):
+ order.append("reset")
+
+ @contextlib.asynccontextmanager
+ async def exclusive():
+ order.append("drain")
+ yield
+ order.append("release")
+
+ async def go():
+ async with _serve(Engine(), exclusive, order) as c:
+ r = await c.get("/admin/knobs")
+ assert (await r.json())["effective"] == knobs.KNOBS
+ r = await c.post("/admin/knobs", json = {"EXL3_GEMV_TRI": 0, "EXL3_BC_KVWIN": False})
+ eff = (await r.json())["effective"]
+ assert r.status == 200 and eff["EXL3_GEMV_TRI"] == "0" and eff["EXL3_BC_KVWIN"] == "0"
+ assert order == ["drain", "run", "reset", "release"] and (await r.json())["prefix_cache_reset"] is True
+ order.clear()
+ r = await c.post("/admin/knobs", json = {"EXL3_GEMV_TRI": 0}) # no change: no reset
+ assert order == ["drain", "run", "release"] and (await r.json())["prefix_cache_reset"] is False
+ r = await c.post("/admin/knobs", json = {"EXL3_GEMV_TRI": None})
+ assert (await r.json())["effective"]["EXL3_GEMV_TRI"] == "1"
+ r = await c.post("/admin/knobs", json = {"EXL3_NOPE": 1})
+ assert r.status == 400 and "EXL3_NOPE" in (await r.json())["error"]["message"]
+ r = await c.post("/admin/knobs", data = b"[1]")
+ assert r.status == 400
+ r = await c.post("/admin/knobs", json = {"EXL3_GEMV_TRI": 0}, headers = {"X-Forwarded-For": "10.0.0.2"})
+ assert r.status == 403 and os.environ.get("EXL3_GEMV_TRI") is None
+ asyncio.run(go())
+
+
+def test_tracked_dicts_are_emptied_on_a_change():
+ class Holder:
+ def __init__(self):
+ self.cache = {"built": 1}
+ h = Holder()
+ knobs.clear_on_change(h, "cache")
+ knobs.clear_on_change(h, "cache") # registered once
+ assert sum(1 for r, a in knobs._tracked if r() is h) == 1
+ knobs.set_knobs({"EXL3_GEMV_TRI": "1"}) # same as the default: kept
+ assert h.cache
+ knobs.set_knobs({"EXL3_GEMV_TRI": "0"})
+ assert h.cache == {}
+ del h
+ import gc
+ gc.collect()
+ knobs.set_knobs({"EXL3_GEMV_TRI": None}) # a dead object is skipped, not an error
diff --git a/tools/admin_knobs.py b/tools/admin_knobs.py
new file mode 100644
index 0000000..53e558d
--- /dev/null
+++ b/tools/admin_knobs.py
@@ -0,0 +1,71 @@
+"""POST /admin/knobs for tools/qwen/serve.py and tools/glm/serve.py (opt-in: --admin-knobs).
+
+Body {"EXL3_X": "1", "EXL3_Y": null, ...} sets (or, with null, unsets) A/B knobs of exllamav3.util.knobs in the running server, waits
+until no request is running, then applies them on the engine's driver thread (captured graphs and per-shape caches are dropped there)
+and answers {"effective": {every knob: value}, "prefix_cache_reset": bool}. A value that really changed also resets the engine's prefix cache
+(disk copies included): prompts cached under the old value must not feed the new one. GET answers the effective values. Loopback clients only, whatever --host says.
+"""
+from __future__ import annotations
+
+import asyncio
+import ipaddress
+import json
+from typing import Any, AsyncContextManager, Callable
+
+from aiohttp import web
+
+
+def _loopback(request: web.Request) -> bool:
+ if request.headers.get("X-Forwarded-For") or request.headers.get("Forwarded"):
+ return False # behind a proxy: the peer is the proxy, not the client
+ try:
+ return ipaddress.ip_address(request.remote or "").is_loopback
+ except ValueError:
+ return False
+
+
+def _text(v: Any) -> str | None:
+ if v is None:
+ return None
+ if isinstance(v, bool):
+ return "1" if v else "0"
+ if isinstance(v, (int, float, str)):
+ return str(v)
+ raise ValueError("knob values must be strings, numbers, booleans or null")
+
+
+def make_handler(engine: Any, exclusive: Callable[[], AsyncContextManager]) -> Callable:
+ """exclusive(): async context manager inside which no request runs (the servers' slot-action drain)."""
+ from exllamav3.util import knobs
+
+ def err(status: int, message: str) -> web.Response:
+ return web.json_response({"error": {"code": status, "message": message, "type": "invalid_request_error"}}, status=status)
+
+ async def handler(request: web.Request) -> web.Response:
+ if not _loopback(request):
+ return err(403, "/admin/knobs answers loopback clients only")
+ if request.method == "GET":
+ return web.json_response({"effective": knobs.effective()})
+ try:
+ body = await request.json()
+ if not isinstance(body, dict):
+ raise ValueError("body must be a JSON object {knob: value}")
+ values = {k: _text(v) for k, v in body.items()}
+ unknown = [k for k in values if k not in knobs.KNOBS]
+ if unknown:
+ raise ValueError("unknown knob(s): " + ", ".join(sorted(unknown)))
+ except (ValueError, json.JSONDecodeError) as exc:
+ return err(400, str(exc))
+ async with exclusive():
+ before = knobs.effective()
+ if hasattr(engine, "run_exclusive"):
+ effective = await engine.run_exclusive(knobs.set_knobs, values)
+ else:
+ effective = await asyncio.get_running_loop().run_in_executor(None, knobs.set_knobs, values)
+ # a changed knob may change the bits a prefill writes: the cached prompt prefixes (and their disk copies) belong to the old value
+ reset = effective != before and hasattr(engine, "reset_prefix_cache")
+ if reset:
+ await engine.reset_prefix_cache()
+ return web.json_response({"effective": effective, "prefix_cache_reset": bool(reset)})
+
+ return handler
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index bc51bd6..3fe9325 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -1321,10 +1321,10 @@ def prime_dense_tune(budget_s: float = 600.0) -> tuple[int, float]:
# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.
-ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}
+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/metrics": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",), "/admin/knobs": ("GET", "POST")}
-def create_app(engine: Any, model_id: str, template: str) -> web.Application:
+def create_app(engine: Any, model_id: str, template: str, admin_knobs: bool = False) -> web.Application:
"""Build the HTTP layer around a resident engine (also accepts a fake engine in tests)."""
queue: asyncio.Queue[tuple[dict[str, Any], asyncio.Queue, dict[str, Any]]] = asyncio.Queue()
lock = asyncio.Lock() # serializes generation with slot save/restore
@@ -2046,6 +2046,11 @@ def create_app(engine: Any, model_id: str, template: str) -> web.Application:
if getattr(engine, "slot_store", None) is not None:
app.router.add_get("/slots", slots)
app.router.add_post("/slots/{id}", slot_action)
+ if admin_knobs:
+ import admin_knobs as _admin
+ h = _admin.make_handler(engine, exclusive)
+ app.router.add_get("/admin/knobs", h)
+ app.router.add_post("/admin/knobs", h)
app.router.add_get("/health", health)
app.router.add_get("/v1/models", models)
app.router.add_get("/metrics", metrics_view)
@@ -2064,6 +2069,7 @@ def main() -> None:
parser.add_argument("--model", default=DEFAULT_MODEL)
parser.add_argument("--no-vision", action="store_true", help="do not load the vision tower (saves memory; image requests get HTTP 400)")
parser.add_argument("--no-uncensor", action="store_true", help="ignore a bundled uncensor_spec.json in the model directory (same as EXL3_ABLIT_RUNTIME=off)")
+ parser.add_argument("--admin-knobs", action="store_true", help="opt in to POST /admin/knobs (loopback clients only): switch the A/B knobs of exllamav3.util.knobs without a reload")
parser.add_argument("--model-id", default="glm-5.3-exl3")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8000)
@@ -2217,7 +2223,7 @@ def main() -> None:
except BaseException as exc: # noqa: BLE001
startup_health.abort(f"{type(exc).__name__}: {exc}")
raise
- app = create_app(engine, args.model_id, template)
+ app = create_app(engine, args.model_id, template, admin_knobs=args.admin_knobs)
# Which run this is, in the log itself: ctx, sessions and the image-cache budget are what a later
# "why was this request slow" question turns on, and they are not visible in the client's request.
reqlog = app["reqlog"]
diff --git a/tools/qwen/serve.py b/tools/qwen/serve.py
index b44fb65..c966f86 100644
--- a/tools/qwen/serve.py
+++ b/tools/qwen/serve.py
@@ -1484,11 +1484,11 @@ def format_logprobs(entries: list, token_ids: list[int], token_str, chat: bool)
# Every route of create_app(), for the early /health listener (404 / 405 while loading); a test keeps it in step.
-ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",)}
+ROUTES = {"/health": ("GET",), "/v1/models": ("GET",), "/slots": ("GET",), "/v1/chat/completions": ("POST",), "/apply-template": ("POST",), "/tokenize": ("POST",), "/completion": ("POST",), "/v1/completions": ("POST",), "/slots/{id}": ("POST",), "/admin/knobs": ("GET", "POST")}
def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, Any] | None = None,
- default_max_tokens: int | None = None) -> web.Application:
+ default_max_tokens: int | None = None, admin_knobs: bool = False) -> web.Application:
"""HTTP layer around a resident engine (also accepts a fake engine in tests)."""
defaults = defaults or load_defaults("/nonexistent")
queue: asyncio.Queue = asyncio.Queue()
@@ -2206,6 +2206,25 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, An
except (ValueError, FileNotFoundError, RuntimeError, json.JSONDecodeError) as exc:
return err(400, f"{type(exc).__name__}: {exc}")
+ @contextlib.asynccontextmanager
+ async def exclusive():
+ """No request runs inside: every session permit is held (the slot-action drain)."""
+ async with lock:
+ held = 0
+ try:
+ for _ in range(sessions):
+ await gate.acquire()
+ held += 1
+ yield
+ finally:
+ for _ in range(held):
+ gate.release()
+
+ if admin_knobs:
+ import admin_knobs as _admin
+ h = _admin.make_handler(engine, exclusive)
+ app.router.add_get("/admin/knobs", h)
+ app.router.add_post("/admin/knobs", h)
app.router.add_get("/v1/models", models)
app.router.add_get("/health", health)
app.router.add_post("/v1/chat/completions", lifecycle.wrapped(completions))
@@ -2315,6 +2334,7 @@ def main() -> None:
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8000)
parser.add_argument("--model", default=DEFAULT_MODEL, help="pack directory")
+ parser.add_argument("--admin-knobs", action="store_true", help="opt in to POST /admin/knobs (loopback clients only): switch the A/B knobs of exllamav3.util.knobs without a reload")
parser.add_argument("--model-id", default=DEFAULT_MODEL_ID, help="id shown by /v1/models and expected in requests")
parser.add_argument("--ctx", "-c", type=int, default=65536, help="KV cache size in tokens (default 65536)")
parser.add_argument("--cache-bits", type=int, default=0, choices=(0, 8),
@@ -2393,7 +2413,7 @@ def main() -> None:
except BaseException as exc: # noqa: BLE001
startup_health.abort(f"{type(exc).__name__}: {exc}")
raise
- app = create_app(engine, args.model_id, template, defaults, args.default_max_tokens)
+ app = create_app(engine, args.model_id, template, defaults, args.default_max_tokens, admin_knobs=args.admin_knobs)
print(f"qserve: {app['ping'].describe()}", flush=True)
print(f"qserve: {app['reqlog'].describe()}", flush=True)
diff --git a/tools/test_admin_knobs.py b/tools/test_admin_knobs.py
new file mode 100644
index 0000000..f974572
--- /dev/null
+++ b/tools/test_admin_knobs.py
@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""POST /admin/knobs on the Qwen and GLM servers: off unless --admin-knobs, loopback only, drains the requests, switches the knob.
+
+ python -m unittest tools.test_admin_knobs (model-free: a fake engine, like tools/test_serve_logging.py)
+"""
+from __future__ import annotations
+
+import asyncio
+import os
+import sys
+import unittest
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+from test_serve_logging import FakeEngine, load_server # noqa: E402
+
+
+class Engine(FakeEngine):
+ def __init__(self) -> None:
+ super().__init__()
+ self.calls: list[str] = []
+
+ async def run_exclusive(self, fn, *args):
+ self.calls.append("run")
+ return fn(*args)
+
+ async def reset_prefix_cache(self) -> None:
+ self.calls.append("reset")
+
+
+class AdminKnobs(unittest.TestCase):
+ def setUp(self) -> None:
+ for n in ("EXL3_GEMV_TRI",):
+ os.environ.pop(n, None)
+
+ def tearDown(self) -> None:
+ os.environ.pop("EXL3_GEMV_TRI", None)
+
+ def test_both_servers(self) -> None:
+ for name in ("qwen", "glm"):
+ with self.subTest(server=name):
+ os.environ.pop("EXL3_GEMV_TRI", None)
+ serve = load_server(name)
+ self.assertIn("/admin/knobs", serve.ROUTES)
+
+ async def go() -> None:
+ from aiohttp.test_utils import TestClient, TestServer
+ eng = Engine()
+ off = TestClient(TestServer(serve.create_app(eng, "m", "{{ messages[0].content }}")))
+ await off.start_server()
+ try:
+ self.assertEqual((await off.get("/admin/knobs")).status, 404) # opt-in
+ finally:
+ await off.close()
+ on = TestClient(TestServer(serve.create_app(eng, "m", "{{ messages[0].content }}", admin_knobs=True)))
+ await on.start_server()
+ try:
+ r = await on.post("/admin/knobs", json={"EXL3_GEMV_TRI": 0})
+ body = await r.json()
+ self.assertEqual(r.status, 200)
+ self.assertEqual(body["effective"]["EXL3_GEMV_TRI"], "0")
+ self.assertEqual(os.environ["EXL3_GEMV_TRI"], "0")
+ self.assertEqual(eng.calls, ["run", "reset"])
+ r = await on.post("/admin/knobs", json={"EXL3_GEMV_TRI": 0}, headers={"X-Forwarded-For": "1.2.3.4"})
+ self.assertEqual(r.status, 403)
+ r = await on.post("/admin/knobs", json={"NOPE": 1})
+ self.assertEqual(r.status, 400)
+ r = await on.get("/admin/knobs")
+ self.assertEqual((await r.json())["effective"]["EXL3_GEMV_TRI"], "0")
+ finally:
+ await on.close()
+
+ asyncio.run(go())
+
+
+if __name__ == "__main__":
+ unittest.main()