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
split: account for MTP/vision in auto-N and bound the workspace
Resynth71bd03b74281
diff --git a/doc/split.md b/doc/split.mdindex 83d1d38..4379c7a 100644--- a/doc/split.md+++ b/doc/split.md@@ -53,6 +53,11 @@ there is capacity, not only speed. Acceptance samples are 50-114 drafted tokenstreat the differences as overlapping intervals rather than a trend. Stage 2a's longer256-token acceptance run measured 64.6% split vs 66.0% single-device at 8K.+Auto-N measured at 8K: MTP+vision chose N=5, MTP only N=6, vision only N=7. At 32K,+MTP+vision chose N=5 under the 2 GiB default and matched manual N=5 on placement, peaks+and n-gram-off greedy text. The 32K safety boundary is 1.0 GiB -> N=6 (warm-up OOM),+1.5 GiB -> N=5; the default is 2 GiB.+## Quick startThe GLM server and the split harnesses accept the flags below. The environment-only path@@ -147,6 +152,8 @@ defect.a mixed-architecture pair is not bitwise.- `tools/strix_halo/split_sessions_smoke.py` sends N concurrent requests at a runningserver and checks that every response succeeds and that the requests overlap.+- `tools/strix_halo/split_startup_health.py` polls `/health` during load and checks the+ stage trace; run it with and without `--no-vision` and with `--num-draft 0`.## Known limitations@@ -167,8 +174,12 @@ defect.`--num-draft 0` for configs outside this measured set.- Per-segment graphs are not implemented. Split runs eager; measured GLM decode is -3.4%at 8K and +1.3% to +8.1% at 32K/128K versus single device with MTP on.-- Auto-N uses text bytes, cache and text endcaps, but does not yet subtract components- declared after the target load (MTP/vision). Leave headroom or set N explicitly.+- Auto-N subtracts the MTP drafter and vision tower when the adapter predeclares them+ before load (the GLM server does). The default 2 GiB safety covers the measured 32K+ MTP+vision warm-up (1 GiB still chose N=6 and OOMed; 1.5/2/3 GiB chose N=5), but it is+ a fixed stopgap. Stage 5 sizes the forward workspace from the context and cache so+ short context can use more part0 layers and long context reserves more;+ `KYOJIN_AUTON_SAFETY_GB` remains the override.- Qwen QSA sparse attention has an illegal-access report in the `gfx12` top-k path on`gfx1201`; keep QSA cache pages off `part0` until that kernel is fixed.- Reverse orientation with MTP on is validated at 32K (N=42, endcaps off, MTP ondiff --git a/exllamav3/device_map.py b/exllamav3/device_map.pyindex 6b32e74..dfb9cd0 100644--- a/exllamav3/device_map.py+++ b/exllamav3/device_map.py@@ -833,9 +833,10 @@ class SplitPlan:if self.devices.part0 is None:return 0total = int(torch.cuda.get_device_properties(self.devices.part0).total_memory)- # Allocator slack, not an architecture rule; Stage 5 replaces it with measured- # load/forward headroom.- safety = int(float(os.environ.get("KYOJIN_AUTON_SAFETY_GB", "0.25")) * GIB)+ # Measured stopgap, not an architecture rule: 2 GiB covers the 32K MTP+vision+ # warm-up on a 16 GiB part0 (1.0 GiB still chose N=6 and OOMed). Stage 5 replaces+ # it with a context-aware workspace/headroom budget.+ safety = int(float(os.environ.get("KYOJIN_AUTON_SAFETY_GB", "2.0")) * GIB)return max(0, total - int(self.part0_reserve_gb * GIB) - safety)def _auto_n(self, text: str | None) -> int:diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.pyindex 934922e..d48e233 100644--- a/tests/test_split_plan_cpu.py+++ b/tests/test_split_plan_cpu.py@@ -278,6 +278,7 @@ def test_auto_n_is_capped_for_long_context(split_modules, monkeypatch):gib = dm.GIBmodel = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])cfg = FakeConfig({f"layer.{i}": gib for i in range(4)})+ monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25")monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(16 * gib))plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",part0_reserve_gb = 1.0, auto_cap = 2, logger = lambda *_a: None)@@ -296,6 +297,7 @@ def test_auto_n_uses_actual_bytes_cache_and_reserve(split_modules, monkeypatch):] + [FakeModule("final_norm")])cfg = FakeConfig(sizes)cache = FakeCache(per_layer = gib // 5) # 0.2 GiB per layer, only 16 keys exist+ monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25") # pin the arithmetic belowmonkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(6 * gib))plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",@@ -315,6 +317,55 @@ def test_auto_n_uses_actual_bytes_cache_and_reserve(split_modules, monkeypatch):assert plan_off.part0_layers == 3+def test_auto_n_subtracts_a_predeclared_whole_component(split_modules, monkeypatch):+ """MTP/vision are declared before build() so auto-N can subtract them from part0."""+ dm, _bridge, _split = split_modules+ gib = dm.GIB+ text = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])+ text_cfg = FakeConfig({f"layer.{i}": gib for i in range(4)})+ mtp = FakeModel([FakeModule("mtp.block.0", layer_idx = 0), FakeModule("mtp.head")])+ mtp_cfg = FakeConfig({"mtp.block.0": 2 * gib, "mtp.head": gib // 2})+ mtp_cache = FakeCache()+ mtp_cache.layers[(0, 0)] = FakeCacheLayer(3 * gib // 4) # one 0.75 GiB drafter layer+ monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25") # pin the arithmetic below+ monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(6 * gib))++ # Budget 6 - 1 reserve - 0.25 safety = 4.75 GiB: text alone fits all 4 layers.+ plain = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",+ part0_reserve_gb = 1.0, logger = lambda *_a: None)+ plain.add("text", text, config = text_cfg)+ plain.build()+ assert plain.part0_layers == 4++ # The 2.5 GiB drafter is a whole component on part0 with endcaps on, so the text+ # map can only use 4.75 - 2.5 = 2.25 GiB -> N=2.+ with_mtp = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",+ part0_reserve_gb = 1.0, logger = lambda *_a: None)+ with_mtp.add("mtp", mtp, config = mtp_cfg)+ with_mtp.add("text", text, config = text_cfg)+ with_mtp.build()+ assert with_mtp.part0_layers == 2+ assert with_mtp.map("mtp").part0_layers == 1++ # The drafter cache is part of the same footprint: 2.5 GiB weights + 0.75 GiB cache+ # leaves 1.5 GiB -> N=1. A test with weights only would miss that second term.+ with_cache = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",+ part0_reserve_gb = 1.0, logger = lambda *_a: None)+ with_cache.add("mtp", mtp, config = mtp_cfg, cache = mtp_cache)+ with_cache.add("text", text, config = text_cfg)+ with_cache.build()+ assert with_cache.part0_layers == 1++ # Endcaps off puts the drafter on part1, so it does not consume the text budget.+ off = dm.SplitPlan(_devices(dm), endcaps = False, part0_layers = "auto",+ part0_reserve_gb = 1.0, logger = lambda *_a: None)+ off.add("mtp", mtp, config = mtp_cfg)+ off.add("text", text, config = text_cfg)+ off.build()+ assert off.part0_layers == 4+ assert not off.map("mtp").enabled++def test_part0_reserve_is_a_slab_not_an_allocator_cap(split_modules, monkeypatch):dm, _bridge, _split = split_modulesmodel = _glm_model()diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 562d5ff..f5f7b3a 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -796,6 +796,30 @@ class ResidentEngine:tune_cache.install_pack(model_path) # <pack>/tuning: GEMM autotune winners from qualify --stage autotunekernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first startjit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile+ # Auto-N must see every whole component that will share part0 before it picks N.+ # Model.from_config builds the module trees only (no weights) and Cache allocates+ # when its model loads. Declaring MTP/vision here, instead of after build(), is+ # what makes auto-N subtract the drafter and vision tower from the part0 budget.+ draft_model = draft_cache = None+ if num_draft > 0:+ draft_model = Model.from_config(self.config, component="mtp")+ draft_cache = Cache(draft_model, max_num_tokens=ctx + 4096,+ max_history=max_history, max_batch_size=slots, **qkw)+ if self.split.enabled:+ self.split.add("mtp", draft_model, config=self.config,+ cache=draft_cache, load_order=1)+ vision_tower = None+ vision_error = None+ if vision:+ try:+ vision_tower = Model.from_config(self.config, component="vision")+ except Exception as exc: # noqa: BLE001 - a pack without vision is optional+ vision_error = exc+ else:+ if self.split.enabled:+ # A placement/sizing error is a split error, not a missing tower: let it+ # fail startup rather than leave a partial SplitPlan declaration behind.+ self.split.add("vision", vision_tower, config=self.config, load_order=2)startup_health.stage("target weights")if self.split.enabled:# Auto-N needs the cache sizes and the target's actual bytes; the cache exists now.@@ -821,13 +845,10 @@ class ResidentEngine:else:self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())if num_draft > 0:- self.draft_model = Model.from_config(self.config, component="mtp")- self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx + 4096,- max_history=max_history, max_batch_size=slots, **qkw)+ self.draft_model = draft_model+ self.draft_cache = draft_cachestartup_health.stage("drafter weights")if self.split.enabled:- self.split.add("mtp", self.draft_model, config=self.config,- cache=self.draft_cache, load_order=1)self.split.load("mtp", self.draft_model, progressbar=False,callback=startup_health.load_callback(), max_chunk_size=4096)else:@@ -844,8 +865,11 @@ class ResidentEngine:getattr(self.config, "vision_start_token_id", 0),getattr(self.config, "vision_end_token_id", 0),env_fingerprint=self.env_fingerprint)- if vision:- self.vision = self._load_vision()+ if vision and vision_error is None:+ self.vision = self._load_vision(vision_tower)+ elif vision_error is not None:+ print(f"serve: vision tower not loaded ({type(vision_error).__name__}: {vision_error}); image input disabled",+ flush=True)self.supports_vision = self.vision is not Noneif self.split.enabled:extra = []@@ -958,15 +982,17 @@ class ResidentEngine:else:await asyncio.get_running_loop().run_in_executor(None, self._rebuild_generator)- def _load_vision(self):+ def _load_vision(self, tower = None):"""The vision tower (model.visual.*, fp16) next to the text model; None, with a log line, when the pack has none."""from exllamav3 import Modelt0 = time.perf_counter()try:startup_health.stage("vision tower")- tower = Model.from_config(self.config, component="vision")+ if tower is None:+ tower = Model.from_config(self.config, component="vision")if self.split.enabled:- self.split.add("vision", tower, config=self.config, load_order=2)+ if self.split.map("vision") is None:+ self.split.add("vision", tower, config=self.config, load_order=2)self.split.load("vision", tower, progressbar=False,callback=startup_health.load_callback())else:@@ -2319,7 +2345,9 @@ def main() -> None: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")) > 0- stages = ["target weights", "drafter weights"] + ([] if args.no_vision else ["vision tower"]) + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else [])+ stages = (["target weights"] + (["drafter weights"] if args.num_draft > 0 else [])+ + ([] if args.no_vision else ["vision tower"])+ + (["warm-up"] if warm else []) + (["dense GEMM tuning"] if tune else []))startup_health.check_model_dir("serve", args.model, ("config.json",))# A start with the dense GEMM tuning already cached is much shorter than the first one: keep their timings apart.startup_health.start("glm", stages, args.host, args.port, routes=ROUTES,diff --git a/tools/strix_halo/split_startup_health.py b/tools/strix_halo/split_startup_health.pynew file mode 100644index 0000000..62ace44--- /dev/null+++ b/tools/strix_halo/split_startup_health.py@@ -0,0 +1,100 @@+#!/usr/bin/env python3+"""Poll a starting server's /health and record the load-stage sequence.++The split load is the long pole, so the stage trace is the evidence that the+server's early listener reports load progress. Start the server separately, then+run this against its port while it loads:++ python tools/glm/serve.py ... --port 8299 > /tmp/serve.log 2>&1 &+ python tools/strix_halo/split_startup_health.py --port 8299 \+ --expect "target weights,drafter weights,vision tower,warm-up" \+ --out /tmp/health-vision.json++With --no-vision the expected list is "target weights,drafter weights,warm-up".+Exits non-zero if the server never answers, never finishes, or a requested stage+never appears.+"""+from __future__ import annotations++import argparse+import json+import time+import urllib.error+import urllib.request+++def read_health(port: int):+ url = f"http://127.0.0.1:{port}/health"+ try:+ with urllib.request.urlopen(url, timeout = 2) as r:+ return r.status, json.loads(r.read())+ except urllib.error.HTTPError as exc:+ # The early listener answers 503 with a JSON "loading" body; urlopen raises on+ # that status, so read it explicitly instead of treating the poll as unreachable.+ body = exc.read()+ if exc.code == 503 and body:+ return exc.code, json.loads(body)+ raise+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--port", type = int, default = 8299)+ ap.add_argument("--timeout", type = float, default = 900.0)+ ap.add_argument("--interval", type = float, default = 0.25)+ ap.add_argument("--expect", default = None,+ help = "comma-separated stages that must appear in the trace")+ ap.add_argument("--out", default = None)+ args = ap.parse_args()++ expected = [s.strip() for s in (args.expect or "").split(",") if s.strip()]+ t0 = time.perf_counter()+ trace = []+ last_stage = object()+ final = None+ while time.perf_counter() - t0 < args.timeout:+ try:+ status, body = read_health(args.port)+ except Exception as exc: # noqa: BLE001 - the listener may not be up yet+ if trace:+ trace.append({"t_s": round(time.perf_counter() - t0, 2),+ "stage": None, "status": f"unreachable: {type(exc).__name__}"})+ time.sleep(args.interval)+ continue+ stage = body.get("stage")+ if stage != last_stage:+ trace.append({+ "t_s": round(time.perf_counter() - t0, 2),+ "stage": stage,+ "stage_index": body.get("stage_index"),+ "stage_count": body.get("stage_count"),+ "progress": body.get("progress"),+ "status": body.get("status"),+ })+ last_stage = stage+ if body.get("status") != "loading":+ final = body+ break+ time.sleep(args.interval)++ elapsed = round(time.perf_counter() - t0, 2)+ stages = [e["stage"] for e in trace if e.get("stage")]+ print(f"[health] {elapsed} s, stages: {stages}", flush = True)+ if final is None:+ print("[health] server did not finish loading", flush = True)+ else:+ print(f"[health] final: status={final.get('status')} stage={final.get('stage')}", flush = True)+ missing = [s for s in expected if s not in stages]+ if args.out:+ with open(args.out, "w", encoding = "utf8") as f:+ json.dump({"elapsed_s": elapsed, "stages": stages, "trace": trace,+ "final": final, "expected": expected, "missing": missing}, f, indent = 1)+ print(f"[health] wrote {args.out}", flush = True)+ if final is None:+ raise SystemExit("health trace did not reach a finished state")+ if missing:+ raise SystemExit(f"health trace missing stage(s): {missing}")+++if __name__ == "__main__":+ main()