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
Qwen serve: the start-up VRAM guard counts the draft-head subset that is built while serving
YanissAmz760fce7fc677
diff --git a/exllamav3/architecture/qwen3_5_mtp.py b/exllamav3/architecture/qwen3_5_mtp.pyindex bf76eb3..46893eb 100644--- a/exllamav3/architecture/qwen3_5_mtp.py+++ b/exllamav3/architecture/qwen3_5_mtp.py@@ -273,6 +273,21 @@ class Qwen3_5MTPModel(Model):return subreturn exl3_block_subhead(inner, blocks)+ def lazy_vram_bytes(self):+ """Device memory the adaptive draft-head subset takes at its first build (about 2048 draft rows into the first request),+ at most EXL3_DRAFT_VOCAB rows of the head. 0 when off, not plain, or already built. The start-up VRAM guard counts it:+ measured 3090 Qwen3.8-27B (98304 rows): 150 MiB that appeared during the first 32K request and tipped the second+ distinct 32K prompt into CUDA out of memory, 48 MiB short."""+ if int(os.environ.get("EXL3_DRAFT_VOCAB", "0") or 0) < 128 or os.environ.get("EXL3_DRAFT_ADAPT", "1") == "0":+ return 0+ model = self.attached_model()+ lm = model.modules[model.logit_layer_idx]+ if not self._head_plain(lm) or (self.__dict__.get("_dad") or {}).get("sub") is not None:+ return 0+ inner = lm.inner+ n = min(int(os.environ.get("EXL3_DRAFT_VOCAB", "0")) // 128 * 128, lm.out_features)+ return inner.trellis.numel() * inner.trellis.element_size() * n // lm.out_features + n * inner.svh.element_size()+def _adapt_state(self, lm):"""Adaptive draft-head subset (EXL3_DRAFT_ADAPT, default on when EXL3_DRAFT_VOCAB is set; 0 = the fixed prefix).Counts the head's own argmax ids per 128-id block (every step while the full head runs, the probe steps while the@@ -316,6 +331,7 @@ class Qwen3_5MTPModel(Model):k = max(int(os.environ.get("EXL3_DRAFT_MINROWS", "49152") or 0) // 128, k) # a short calibration under-counts the tailk = max(2, min(k + (k & 1), cap, order.numel())) # an even number of blocks: the 1-2 row int8 GEMV needs n % 256 == 0blocks = torch.sort(order[:k]).values+ st["sub"] = st["gmap"] = Nonesub = self._draft_subhead(lm, blocks)if sub is None:return False@@ -377,6 +393,7 @@ class Qwen3_5MTPModel(Model):adapt["counts"].index_add_(0, (fids.reshape(-1) // 128), torch.ones(rows, device = fids.device))adapt["seen"] += rowsif adapt["seen"] - adapt["built_at"] >= adapt["warm"]:+ sub = None # a rebuild must not hold the old subset while the new one is made (another 150 MiB at 98304 rows)self._adapt_build(lm, adapt)if params.get("export_draft_conf"):params["draft_conf"] = fconfdiff --git a/tools/qwen/serve.py b/tools/qwen/serve.pyindex 5d85877..57c3592 100644--- a/tools/qwen/serve.py+++ b/tools/qwen/serve.py@@ -2182,9 +2182,12 @@ def create_app(engine: Any, model_id: str, template: str, defaults: dict[str, AnMIN_FREE_MIB = 1536 # VRAM that must stay free after load: a 2048-row prefill chunk and the multi-row graph pools come on top of the resident state (measured 3090 Qwen3.8-27B: the first prefills raise the use by 1.3-1.4 GiB; 1024 let -c 262144 sessions 3, 1369 MiB free, start and then die with CUDA out of memory on the third distinct prompt)-def vram_headroom_problem(free_mib: float, ctx: int, kv_mib_per_token: float, sessions: int, min_free_mib: float = MIN_FREE_MIB) -> str | None:+def vram_headroom_problem(free_mib: float, ctx: int, kv_mib_per_token: float, sessions: int, min_free_mib: float = MIN_FREE_MIB, lazy_mib: float = 0.0) -> str | None:"""None when the memory left after load covers the first real request, else the start-up error with the context that fits.- 3090, Qwen3.8-27B K4V4: sessions 3 at -c 262144 left 0.47 GiB and every cold prefill died with CUDA out of memory while /health said ok."""+ 3090, Qwen3.8-27B K4V4: sessions 3 at -c 262144 left 0.47 GiB and every cold prefill died with CUDA out of memory while /health said ok.+ lazy_mib: persistent buffers that only appear while serving (the adaptive draft-head subset): k6v6 sessions 3 -c 183040 left 1551 MiB+ after load, passed the 1536 floor, then lost 150 MiB to the subset during the first 32K prompt and died on the second distinct one."""+ free_mib -= lazy_mibif free_mib >= min_free_mib:return Nonefits = max(0, int(ctx - (min_free_mib - free_mib) / kv_mib_per_token) // 256 * 256) if kv_mib_per_token > 0 else 0@@ -2226,8 +2229,9 @@ def load_all(args: argparse.Namespace):if engine.torch.cuda.is_available() and not engine.torch.version.hip and os.environ.get("EXL3_MIN_FREE_MIB", "") != "0":free_mib = free_vram_mib(engine.torch)kv = sum(l.storage_size() for c in (engine.cache, engine.draft_cache) if c is not None for l in c.layers.values()) / 2**20 / args.ctx- print(f"qserve: VRAM left after load: {free_mib:.0f} MiB (ctx={args.ctx}, sessions={args.sessions})", flush=True)- bad = vram_headroom_problem(free_mib, args.ctx, kv, args.sessions, float(os.environ.get("EXL3_MIN_FREE_MIB") or MIN_FREE_MIB))+ lazy = getattr(engine.draft_model, "lazy_vram_bytes", lambda: 0)() / 2**20 if engine.draft_model is not None else 0.0+ print(f"qserve: VRAM left after load: {free_mib:.0f} MiB, {lazy:.0f} MiB of it taken later by the draft-head subset (ctx={args.ctx}, sessions={args.sessions})", flush=True)+ bad = vram_headroom_problem(free_mib, args.ctx, kv, args.sessions, float(os.environ.get("EXL3_MIN_FREE_MIB") or MIN_FREE_MIB), lazy)if bad:raise RuntimeError(bad)if os.environ.get("EXL3_SWAP_IN", "1") != "0":diff --git a/tools/qwen/test_oom_sequence.py b/tools/qwen/test_oom_sequence.pynew file mode 100644index 0000000..85d5c62--- /dev/null+++ b/tools/qwen/test_oom_sequence.py@@ -0,0 +1,86 @@+#!/usr/bin/env python3+"""GPU regression: the driver sequence that ended in CUDA out of memory on the second distinct 32K prompt (3090, Qwen3.8-27B,+k6v6, --sessions 3, -c 183040: 1551 MiB left after load, the 150 MiB draft-head subset appears during the first 32K request).+A start that the VRAM guard accepts must survive it; a start the guard refuses must name a -c that survives it.+Opt-in: EXL3_GPU_TEST_MODEL=<pack dir> [EXL3_GPU_TEST_CTX=183040] [EXL3_GPU_TEST_SESSIONS=3] [EXL3_GPU_TEST_KV=6] [EXL3_GPU_TEST_FULL=1] [EXL3_GPU_TEST_PYTHON=...] python3 tools/qwen/test_oom_sequence.py"""+import json, os, re, socket, subprocess, sys, tempfile, time, unittest, urllib.request+from pathlib import Path++ROOT = Path(__file__).resolve().parents[2]+MODEL = os.environ.get("EXL3_GPU_TEST_MODEL", "")+CTX = int(os.environ.get("EXL3_GPU_TEST_CTX", "183040"))+SESSIONS = os.environ.get("EXL3_GPU_TEST_SESSIONS", "3")+KV = os.environ.get("EXL3_GPU_TEST_KV", "6") # K and V bits+++def _text() -> str:+ return "\n".join(p.read_text(errors="replace") for p in sorted((ROOT / "exllamav3").rglob("*.py")))+++def _ask(port: int, text: str, i: int, chars: int, max_new: int) -> dict:+ off = 7000 * (i + 1) * 3+ body = {"model": "t", "temperature": 0, "top_k": 1, "max_tokens": max_new, "stream": True, "chat_template_kwargs": {"enable_thinking": False},+ "messages": [{"role": "user", "content": f"[SEQ{i}] Explain this extract:\n\n{text[off:off + chars]}"}]}+ req = urllib.request.Request(f"http://127.0.0.1:{port}/v1/chat/completions", json.dumps(body).encode(), {"Content-Type": "application/json", "Authorization": "Bearer x"})+ err, got = None, 0+ for line in urllib.request.urlopen(req, timeout=900):+ line = line.decode().strip()+ if not line.startswith("data:") or line.endswith("[DONE]"):+ continue+ ev = json.loads(line[5:])+ err = ev.get("error") or err+ got += sum(len((c.get("delta") or {}).get("content") or "") for c in ev.get("choices", []))+ return {"error": err, "chars": got}++[email protected](MODEL, "set EXL3_GPU_TEST_MODEL to a Qwen3.8-27B EXL3 pack to run the GPU sequence")+class OomSequence(unittest.TestCase):+ def start(self, ctx: int):+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0)); port = s.getsockname()[1]+ log = tempfile.NamedTemporaryFile("w+", suffix=".log")+ cmd = [os.environ.get("EXL3_GPU_TEST_PYTHON", sys.executable), "-u", str(ROOT / "tools/qwen/serve.py"), "--model", MODEL, "--port", str(port), "-c", str(ctx),+ "--k-bits", KV, "--v-bits", KV, "--sessions", SESSIONS, "--model-id", "t", "--default-max-tokens", "512"]+ proc = subprocess.Popen(cmd, stdout=log, stderr=subprocess.STDOUT, env=dict(os.environ, EXL3_CUDA_GRAPH="1", PYTHONPATH=str(ROOT)), cwd=ROOT)+ self.addCleanup(lambda: (proc.terminate(), proc.wait(timeout=60)))+ for _ in range(400):+ if proc.poll() is not None:+ log.seek(0); return None, log.read()+ try:+ if urllib.request.urlopen(f"http://127.0.0.1:{port}/health", timeout=3).status == 200:+ return port, log+ except OSError:+ pass+ time.sleep(3)+ self.fail("server did not become healthy")++ def test_distinct_32k_prompts_after_the_short_and_4k_warm_up(self):+ port, log = self.start(CTX)+ ctx = CTX+ for _ in range(4): # the guard refused: it must name a context that works (each refusal lowers it, the figure is measured after load)+ if port is not None:+ break+ m = re.findall(r"Start with -c (\d+)", log)+ self.assertTrue(m, log[-800:])+ self.assertLess(int(m[-1]), ctx)+ ctx = int(m[-1])+ port, log = self.start(ctx)+ self.assertIsNotNone(port, log)+ print(f"FINAL_CTX={ctx} sessions={SESSIONS} kv={KV}", flush=True)+ text = _text()+ for i in range(3):+ self.assertIsNone(_ask(port, text, i, 700, 256)["error"])+ for i in range(3):+ self.assertIsNone(_ask(port, text, 10 + i, 10000, 256)["error"])+ for i in range(3): # 80K chars is about 31K tokens; the third one is the one the lane sequence never reached+ r = _ask(port, text, 20 + i, 80000, 256)+ self.assertIsNone(r["error"], f"32K prompt {i}")+ if os.environ.get("EXL3_GPU_TEST_FULL"): # two distinct prompts that fill the context (1 session k6v6 -c 262144 died on the second one)+ for i in range(2):+ r = _ask(port, text, 40 + i, int((ctx - 1500) * 2.2), 64)+ self.assertIsNone(r["error"], f"full-context prompt {i}")+ log.seek(0); self.assertNotIn("out of memory", log.read())+++if __name__ == "__main__":+ unittest.main()diff --git a/tools/qwen/test_serve.py b/tools/qwen/test_serve.pyindex 1d05474..d29c542 100644--- a/tools/qwen/test_serve.py+++ b/tools/qwen/test_serve.py@@ -9,6 +9,7 @@ import osimport sysimport typesimport unittest+import unittest.mockfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).parent))@@ -1297,6 +1298,35 @@ class VramHeadroomTests(unittest.TestCase):def test_196608_sessions_3_is_accepted(self):self.assertIsNone(serve.vram_headroom_problem(2600, 196608, 0.0182, 3)) # measured: ~2.6 GiB left, 50 calls clean in realA+ def test_lazy_draft_head_subset_counts_against_the_floor(self):+ # measured on the 24 GB 3090, Qwen3.8-27B k6v6 sessions 3 -c 183040: 1551 MiB left after load passed the 1536 floor, the 150 MiB+ # draft-head subset appeared in the first 32K request and the second distinct 32K prompt died with CUDA out of memory (48 MiB short)+ self.assertIsNone(serve.vram_headroom_problem(1551, 183040, 0.0182, 3))+ msg = serve.vram_headroom_problem(1551, 183040, 0.0182, 3, lazy_mib=150)+ self.assertIn("-c ", msg)+ fits = int(msg.split("-c ")[1].split()[0])+ self.assertLessEqual(fits, 183040 - (1536 - 1401) / 0.0182)+ self.assertIsNone(serve.vram_headroom_problem(1551 + 150, 183040, 0.0182, 3, lazy_mib=150))++ def test_lazy_bytes_of_the_draft_subset(self):+ import torch+ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+ from exllamav3.architecture.qwen3_5_mtp import Qwen3_5MTPModel as M+ inner = type("LinearEXL3", (), {})()+ inner.trellis, inner.svh, inner.K, inner.bias = torch.zeros(256, 1024, 16, dtype=torch.int16), torch.zeros(16384, dtype=torch.float16), 4, None+ lm = types.SimpleNamespace(inner=inner, out_features=16384, pre_scale=1.0, post_scale=1.0, softcap=0.0)+ model = types.SimpleNamespace(modules=[lm], logit_layer_idx=0)+ mtp = types.SimpleNamespace(attached_model=lambda: model, _head_plain=staticmethod(M._head_plain), __dict__={})+ env = {"EXL3_DRAFT_VOCAB": "4096"}+ with unittest.mock.patch.dict(os.environ, env):+ self.assertEqual(M.lazy_vram_bytes(mtp), 256 * 1024 * 16 * 2 // 4 + 4096 * 2) # a quarter of the head rows+ with unittest.mock.patch.dict(os.environ, {"EXL3_DRAFT_ADAPT": "0"}):+ self.assertEqual(M.lazy_vram_bytes(mtp), 0)+ mtp.__dict__["_dad"] = {"sub": object()}+ self.assertEqual(M.lazy_vram_bytes(mtp), 0) # already built: it is in the measured free figure+ with unittest.mock.patch.dict(os.environ, {"EXL3_DRAFT_VOCAB": "0"}):+ self.assertEqual(M.lazy_vram_bytes(types.SimpleNamespace(__dict__={})), 0)+if __name__ == "__main__":unittest.main()