Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Servers: pick up draft2s.st from the model folder; GLM MLA VALU decode on by default
YanissAmz9e5aad188b57
diff --git a/doc/env_vars.md b/doc/env_vars.mdindex 23cff2f..46162b0 100644--- a/doc/env_vars.md+++ b/doc/env_vars.md@@ -101,6 +101,12 @@ Prefill strategy for MLA layers: `mha` up-projects past latent tiles from the coand attends in MHA form (~2.8× fewer FLOPs per query-past pair); `absorbed` restores thesingle-kernel absorbed-form prefill for A/B testing.+### `EXL3_MLA_DEC_VALU` (default: `1` on HIP)++Decode and verify rows (up to 8) of the MLA absorb and unfold run on the VALU dot2-chain kernels. The output is+bitwise equal to the Triton path. `0` turns it off. If the extension build lacks the kernels, the Triton path is used and+one log line says so.+### `EXL3_PREFER_FA2` (default: `0`)Put the flash-attn-2 backends ahead of the built-in Triton attention kernels in the dispatch@@ -831,6 +837,13 @@ draft acceptance without changing target token ids. `0` turns it off; a path thastops the load. The GLM server looks for the file itself in three places, listed in[tools/glm/SERVE.md](../tools/glm/SERVE.md).+#### `EXL3_DRAFT2S` (default: `<model folder>/draft2s.st` when present and matching)++Two-stage draft head for the MTP drafters: it finds the draft argmax in two steps instead of one pass over the full+vocabulary. Every draft is still verified, so the output does not change. The GLM and Qwen servers pick up+`draft2s.st` from the model folder when its header (vocabulary size, hidden width) matches `config.json`. A path in the+variable wins; `0`, `off` or an empty value uses the full head. Sampled jobs always use the full head.+#### `EXL3_MIMO_LOSSLESS` (default: `1`)`0` restores the fast MiMo verify that is not token-identical. With it on, speculative outputdiff --git a/exllamav3/modules/attention_fn/mla_triton.py b/exllamav3/modules/attention_fn/mla_triton.pyindex e965c78..5ad2b69 100644--- a/exllamav3/modules/attention_fn/mla_triton.py+++ b/exllamav3/modules/attention_fn/mla_triton.py@@ -1264,10 +1264,23 @@ def _mla_ext():return exllamav3_ext+_DEC_VALU_WARNED = False++def _dec_valu_on() -> bool:- """EXL3_MLA_DEC_VALU=1 (default off, read per call): decode / verify rows (R <= 8) of the MLA absorb and unfold run on the- VALU dot2-chain kernels (ext.mla_absorb_dec / mla_unfold_dec). Bit-identical to the Triton WMMA kernels."""- return os.environ.get("EXL3_MLA_DEC_VALU", "0") == "1" and torch.version.hip is not None+ """Decode / verify rows (R <= 8) of the MLA absorb and unfold run on the VALU dot2-chain kernels (ext.mla_absorb_dec /+ mla_unfold_dec), bit-identical to the Triton WMMA kernels. On by default (HIP); EXL3_MLA_DEC_VALU=0 turns it off (read per+ call). An extension build without the kernels falls back to the Triton path with one log line."""+ global _DEC_VALU_WARNED+ if os.environ.get("EXL3_MLA_DEC_VALU", "1") == "0" or torch.version.hip is None:+ return False+ ext = _mla_ext()+ if not (hasattr(ext, "mla_absorb_dec") and hasattr(ext, "mla_unfold_dec")):+ if not _DEC_VALU_WARNED:+ _DEC_VALU_WARNED = True+ print(" -- MLA VALU decode kernels not in this extension build: using the Triton path (rebuild the extension to enable them)")+ return False+ return Truedef _dec_valu_ok(R, w_uk_flat, H, qk_nope, qk_dim, q) -> bool:diff --git a/tools/glm/SERVE.md b/tools/glm/SERVE.mdindex 0486ba5..22824d9 100644--- a/tools/glm/SERVE.md+++ b/tools/glm/SERVE.md@@ -67,6 +67,16 @@ To build it yourself from the official GLM-5.3 checkpoint:python tools/glm/mtp_eh_sidecar.py <official GLM-5.3 checkpoint dir> <model folder>/mtp_eh_proj.st```+### Two-stage draft head (faster drafting)++If `draft2s.st` is in the model folder and its header matches `config.json` (vocabulary size and hidden width), the+server uses it as the two-stage draft head. No flag needed. It changes only how the draft is found; target token ids+stay equal. Sampled jobs keep the full head. One log line says which source was used. `EXL3_DRAFT2S=<path>` picks+another pack; `EXL3_DRAFT2S=off` turns it off. Build one with `tools/qwen/draft2s_pack.py`.++The GLM MLA decode kernels (VALU path, bitwise equal to the Triton path) are also on by default.+`EXL3_MLA_DEC_VALU=0` turns them off.+## Endpoints### `GET /health`diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 37c94d7..2b8274c 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -129,6 +129,50 @@ def apply_eh_sidecar_default(model_dir: str | None = None) -> str:return "absent"+DRAFT2S_IN_PACK = "draft2s.st" # safetensors layout, but not *.safetensors so the weight loader never indexes it+++def _draft2s_pack_matches(path: Path, model_dir: Path) -> bool:+ """True when the pack header (tools/qwen/draft2s_pack.py metadata) was built for this model's vocabulary and width."""+ import struct+ try:+ with open(path, "rb") as fh:+ meta = json.loads(fh.read(struct.unpack("<Q", fh.read(8))[0])).get("__metadata__") or {}+ cfg = json.loads((model_dir / "config.json").read_text())+ cfg = cfg.get("text_config", cfg)+ return meta.get("format") == "draft2s-v1" and int(meta["vocab"]) == cfg["vocab_size"] \+ and int(meta["in_features"]) == cfg["hidden_size"]+ except (OSError, ValueError, KeyError, struct.error):+ return False+++def apply_draft2s_default(model_dir: str | None = None) -> str:+ """Pick the optional two-stage draft head pack (EXL3_DRAFT2S, exllamav3/modules/draft2s.py) and log which source is used.++ Order: explicit EXL3_DRAFT2S (never touched; "", "0" or "off" = off) > DRAFT2S_IN_PACK inside the model folder when its+ header matches the model (vocab_size, hidden_size) > absent. The head only changes how the draft argmax is found, never+ the output (every draft is verified). Returns the source: "explicit", "off", "pack", "mismatch" or "absent".+ """+ if "EXL3_DRAFT2S" in os.environ:+ if os.environ["EXL3_DRAFT2S"].strip().lower() in ("", "0", "off"):+ os.environ["EXL3_DRAFT2S"] = ""+ print("serve: two-stage draft head: off (EXL3_DRAFT2S)", flush=True)+ return "off"+ print(f"serve: two-stage draft head: EXL3_DRAFT2S={os.environ['EXL3_DRAFT2S']} (explicit)", flush=True)+ return "explicit"+ if model_dir:+ path = Path(model_dir).expanduser() / DRAFT2S_IN_PACK+ if path.is_file():+ if not _draft2s_pack_matches(path, Path(model_dir).expanduser()):+ print(f"serve: two-stage draft head: {path} does not match this model (vocab / width): not used", flush=True)+ return "mismatch"+ os.environ["EXL3_DRAFT2S"] = str(path)+ print(f"serve: two-stage draft head: {path} (model folder)", flush=True)+ return "pack"+ print(f"serve: two-stage draft head: none ({DRAFT2S_IN_PACK} not in the model folder): full draft head", flush=True)+ return "absent"++# The template deliberately uses a zero-width space so normal prose does not trigger tools.TOOL_OPEN = "<tool_call>"TOOL_CLOSE = "</tool_call>"@@ -1478,6 +1522,7 @@ def main() -> None:os.environ.setdefault(key, value)os.environ.setdefault("EXL3_MOE_UNION_V2", "1")apply_eh_sidecar_default(args.model)+ apply_draft2s_default(args.model)warm = os.environ.get("EXL3_SERVE_WARMUP", "1") != "0"tune = warm and os.environ["EXL3_DENSE_GEMM_TUNE"] != "0" and float(os.environ.get("EXL3_SERVE_DTUNE_PRIME_S", "600")) > 0stages = ["target weights", "drafter weights"] + ([] if args.no_vision else ["vision tower"]) + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])diff --git a/tools/glm/test_serve.py b/tools/glm/test_serve.pyindex f91e899..7e8cb17 100644--- a/tools/glm/test_serve.py+++ b/tools/glm/test_serve.py@@ -12,6 +12,14 @@ sys.path.insert(0, str(Path(__file__).parent))import serve++def _write_draft2s_pack(path, vocab, width):+ """A header-only draft2s pack (tools/qwen/draft2s_pack.py metadata layout) for the sidecar tests."""+ import json as _json, struct+ hdr = _json.dumps({"__metadata__": {"format": "draft2s-v1", "vocab": str(vocab), "in_features": str(width), "m": "512"}}).encode()+ path.write_bytes(struct.pack("<Q", len(hdr)) + hdr)++class FakeGenerator:num_draft_tokens = 2 # /metrics derives the round count from the engine's window@@ -120,6 +128,33 @@ class ServeTests(unittest.TestCase):self.assertNotIn("EXL3_MTP_EH_FP16", serve.SPEED_ENV)self.assertFalse(serve.EH_SIDECAR_IN_PACK.endswith(".safetensors"))+ def test_draft2s_sidecar_source_order(self):+ import os, tempfile+ from unittest import mock+ with tempfile.TemporaryDirectory() as d, mock.patch.dict(os.environ, {}):+ pack = Path(d)+ (pack / "config.json").write_text(json.dumps({"text_config": {"vocab_size": 154880, "hidden_size": 4096}}))+ os.environ.pop("EXL3_DRAFT2S", None)+ self.assertEqual(serve.apply_draft2s_default(str(pack)), "absent")+ self.assertNotIn("EXL3_DRAFT2S", os.environ)+ # a pack built for another model (Qwen's head) is not used+ _write_draft2s_pack(pack / serve.DRAFT2S_IN_PACK, 248320, 2560)+ self.assertEqual(serve.apply_draft2s_default(str(pack)), "mismatch")+ self.assertNotIn("EXL3_DRAFT2S", os.environ)+ _write_draft2s_pack(pack / serve.DRAFT2S_IN_PACK, 154880, 4096)+ self.assertEqual(serve.apply_draft2s_default(str(pack)), "pack")+ self.assertEqual(os.environ["EXL3_DRAFT2S"], str(pack / "draft2s.st"))+ # explicit path never touched; "0" / "off" / "" = off (empty, so the engine's truthiness check skips the head)+ os.environ["EXL3_DRAFT2S"] = "/nope/x.st"+ self.assertEqual(serve.apply_draft2s_default(str(pack)), "explicit")+ self.assertEqual(os.environ["EXL3_DRAFT2S"], "/nope/x.st")+ for value in ("0", "off", ""):+ os.environ["EXL3_DRAFT2S"] = value+ self.assertEqual(serve.apply_draft2s_default(str(pack)), "off")+ self.assertEqual(os.environ["EXL3_DRAFT2S"], "")+ self.assertNotIn("EXL3_DRAFT2S", serve.SPEED_ENV)+ self.assertFalse(serve.DRAFT2S_IN_PACK.endswith(".safetensors"))+def test_stream_engine_error_still_ends_with_finish_reason(self):from aiohttp.test_utils import TestClient, TestServerdiff --git a/tools/qwen/SERVE.md b/tools/qwen/SERVE.mdindex def0ba5..3dc4610 100644--- a/tools/qwen/SERVE.md+++ b/tools/qwen/SERVE.md@@ -57,6 +57,13 @@ scales (`EXL3_GR_GS=1`; `hc_gs_sidecar.safetensors` in the model directory is pienvironment wins. The engine modules read several of these when they are imported, so the server refuses to start if`exllamav3` was imported before they were set.+## Two-stage draft head++If `draft2s.st` is in the model directory and its header matches `config.json` (vocabulary size and hidden width), qserve+uses it as the two-stage draft head and logs it at start-up. No flag needed. Output does not change (every draft is+verified); sampled jobs keep the full head. `EXL3_DRAFT2S=<path>` picks another pack; `EXL3_DRAFT2S=off` turns it off.+The pack is tied to one set of weights: download it from the same model repo.+## API- `POST /v1/chat/completions`: stream (SSE) and non-stream, `tools` and `tool_calls`, `tool` role messages, images asdiff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 3aca19e..ae09de7 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -589,6 +589,37 @@ def configure_hc_sidecar(model_path: str) -> str:return f"hc mixer: group scales, plain rounding (no {HC_GS_SIDECAR} in the model directory)"+DRAFT2S_IN_PACK = "draft2s.st" # safetensors layout, but not *.safetensors so the weight loader never indexes it+++def configure_draft2s(model_path: str) -> str:+ """Point EXL3_DRAFT2S (two-stage draft head, exllamav3/modules/draft2s.py) at <model_path>/draft2s.st when the+ variable is unset, the file exists and its header was built for this model (vocab_size, hidden_size). "", "0" or "off" =+ off. The head only changes how the draft argmax is found, never the output (every draft is verified). Returns the log line."""+ env = os.environ.get("EXL3_DRAFT2S")+ if env is not None:+ if env.strip().lower() in ("", "0", "off"):+ os.environ["EXL3_DRAFT2S"] = ""+ return "draft head: full head (EXL3_DRAFT2S off)"+ return f"draft head: two-stage, pack {env} (EXL3_DRAFT2S)"+ f = Path(model_path).expanduser() / DRAFT2S_IN_PACK+ if not f.is_file():+ return f"draft head: full head (no {DRAFT2S_IN_PACK} in the model directory)"+ import struct+ try:+ with open(f, "rb") as fh:+ meta = json.loads(fh.read(struct.unpack("<Q", fh.read(8))[0])).get("__metadata__") or {}+ cfg = json.loads((Path(model_path).expanduser() / "config.json").read_text())+ cfg = cfg.get("text_config", cfg)+ ok = meta.get("format") == "draft2s-v1" and int(meta["vocab"]) == cfg["vocab_size"] \+ and int(meta["in_features"]) == cfg["hidden_size"]+ except (OSError, ValueError, KeyError, struct.error):+ ok = False+ if not ok:+ return f"draft head: full head ({f} does not match this model: not used)"+ os.environ["EXL3_DRAFT2S"] = str(f)+ return f"draft head: two-stage, pack {f}"+def _env_flag(name: str, default: str, off: tuple = ("", "0")) -> bool:return os.environ.get(name, default) not in off@@ -633,6 +664,7 @@ class QwenEngine:os.environ.setdefault(k, v)check_latched_env()print("qserve:", configure_hc_sidecar(model_path), flush=True)+ print("qserve:", configure_draft2s(model_path), flush=True)import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizertorch.set_grad_enabled(False)diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 54968fa..64237a9 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -14,6 +14,14 @@ sys.path.insert(0, str(Path(__file__).parent))import serve++def _write_draft2s_pack(path, vocab, width):+ """A header-only draft2s pack (tools/qwen/draft2s_pack.py metadata layout) for the sidecar tests."""+ import json as _json, struct+ hdr = _json.dumps({"__metadata__": {"format": "draft2s-v1", "vocab": str(vocab), "in_features": str(width), "m": "512"}}).encode()+ path.write_bytes(struct.pack("<Q", len(hdr)) + hdr)++class SharedModuleTests(unittest.TestCase):def test_serve_metrics_resolves_next_to_the_server(self):# serve.py loads tools/mimo/serve.py, which imports serve_metrics from the sys.path of this folder@@ -81,6 +89,31 @@ def sse_events(raw: str):class ParserTests(unittest.TestCase):+ def test_draft2s_sidecar(self):+ import tempfile+ from unittest import mock+ with tempfile.TemporaryDirectory() as d, mock.patch.dict(os.environ, {}):+ pack = Path(d)+ (pack / "config.json").write_text(json.dumps({"vocab_size": 248320, "hidden_size": 2560}))+ os.environ.pop("EXL3_DRAFT2S", None)+ self.assertIn("no draft2s.st", serve.configure_draft2s(str(pack)))+ self.assertNotIn("EXL3_DRAFT2S", os.environ)+ _write_draft2s_pack(pack / serve.DRAFT2S_IN_PACK, 154880, 4096) # GLM's head: not this model+ self.assertIn("does not match", serve.configure_draft2s(str(pack)))+ self.assertNotIn("EXL3_DRAFT2S", os.environ)+ _write_draft2s_pack(pack / serve.DRAFT2S_IN_PACK, 248320, 2560)+ self.assertIn("two-stage", serve.configure_draft2s(str(pack)))+ self.assertEqual(os.environ["EXL3_DRAFT2S"], str(pack / "draft2s.st"))+ os.environ["EXL3_DRAFT2S"] = "/nope/x.st"+ self.assertIn("/nope/x.st", serve.configure_draft2s(str(pack)))+ self.assertEqual(os.environ["EXL3_DRAFT2S"], "/nope/x.st")+ for value in ("0", "off", ""):+ os.environ["EXL3_DRAFT2S"] = value+ self.assertIn("full head", serve.configure_draft2s(str(pack)))+ self.assertEqual(os.environ["EXL3_DRAFT2S"], "")+ self.assertNotIn("EXL3_DRAFT2S", dict(serve.SERVE_ENV))+ self.assertFalse(serve.DRAFT2S_IN_PACK.endswith(".safetensors"))+def test_reasoning_first_split(self):m = serve.split_completion("let me think\nmore\n</think>\n\nThe answer.\n", True, None)self.assertEqual(m["reasoning_content"], "let me think\nmore")