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.

Convert layer split to be GPU arch agnostic. It had become a bit gfx12 specialised!

Resynthc80458410e35
diff --git a/doc/split-support-matrix.md b/doc/split-support-matrix.md
index 6c7b550..aa510b4 100644
--- a/doc/split-support-matrix.md
+++ b/doc/split-support-matrix.md
@@ -2,13 +2,19 @@
What the contiguous layer split (`exllamav3/device_map.py`, `exllamav3/bridge.py`,
`exllamav3/serve_split.py`, `Model.load(device_map=...)`) can place today, per model family
-and per serve flavor. Stage 1 (2026-11-10): the core is policy-driven, GLM is the first
-adapter, and the front reserve is a layout-neutral slab; GLM's Phase 4 gate replay is the
-measured baseline. Qwen and DSV4 entries remain code inventories, not load-tested.
+and per serve flavor. Stage 1.5 (2026-11-10): the core is policy-driven, devices are
+selected by position rather than architecture, GLM is the first adapter, and the front
+reserve is a layout-neutral slab; GLM's Phase 4 gate replay is the measured baseline.
+Qwen and DSV4 entries remain code inventories, not load-tested.
-Legend — placement: **front** (mapped to the front eGPU), **main** (mapped to the main GPU),
-**cpu**, **host** (never enters the map: CPU/streamed by design). Stage links point at the
-roadmap stage that must finish before that row is claimable.
+Legend — placement: **front** (mapped to the front device), **main** (mapped to the main
+device), **cpu**, **host** (never enters the map: CPU/streamed by design). Stage links
+point at the roadmap stage that must finish before that row is claimable.
+
+**Measured configuration.** RX 9070 (gfx1201, 15.92 GiB) over USB4 as the front and a
+118 GiB Strix Halo iGPU (gfx1151) as the main. Numbers below and in
+`docs-notes/split-log.md` are measurements from that pair; the interface does not assume
+either architecture or role.
## Measured — GLM-5.3-Flash (`tools/glm/serve.py`, `tools/strix_halo/split_*`)
@@ -23,13 +29,14 @@ roadmap stage that must finish before that row is claimable.
| bridge | shared config | installed by `SplitPlan.install_bridges` for every config | one `Bridge` per config; split_active defuses graphs |
Gate status (Stage 0 replay): N=6 65K load with MTP+vision front 13.68/13.94 GiB, plain split
-run-to-run deterministic; results appended in `docs-notes/split-log.md`. Stage 1 core changes
-are CPU-contract-tested and the GPU gate (N=4/6 load, plain determinism, 120K needle N=5,
-split-off regression) is the next checkpoint run.
+run-to-run deterministic; results appended in `docs-notes/split-log.md`. Stage 1.5 selection
+changes are CPU-tested; the GPU gate (N=4/6 load in both device positions, plain determinism,
+120K needle N=5, split-off regression) is the next checkpoint run.
Known blockers: gfx12 fused KDA kernel (separate PR), MTP cross-device acceptance/determinism,
auto-N not yet subtracting components declared after the target (Stage 5), 128K determinism
-must be re-verified with the slab reserve on the box.
+must be re-verified with the slab reserve on the box. GLM's auto-N long-context cap applies
+only on a gfx12 front (adapter tuning, not a split rule).
## Code inventory — Qwen3.8-Flash-Next (`tools/qwen/serve.py`)
diff --git a/doc/split.md b/doc/split.md
index b3d97b4..be07916 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -1,16 +1,17 @@
-# Contiguous layer split (iGPU + eGPU)
+# Contiguous layer split (front + main devices)
-*Status: Stage 1 of the universal roadmap (see `.kilo/plans/1794309410242-universal-layer-split-roadmap.md`).
-The core is now policy-driven (`SplitPlan`/`ComponentPolicy`), the GLM server is the
-first adapter, and the front reserve is a layout-neutral slab. This file is the
-durable user/ops reference; the roadmap owns the staging, and
-`docs-notes/split-log.md` (untracked) owns raw measurements.*
+*Status: Stage 1.5 of the universal roadmap (see `.kilo/plans/1794309410242-universal-layer-split-roadmap.md`).
+The core is policy-driven (`SplitPlan`/`ComponentPolicy`), devices are selected by
+position rather than by architecture, the GLM server is the first adapter, and the front
+reserve is a layout-neutral slab. This file is the durable user/ops reference; the
+roadmap owns the staging, and `docs-notes/split-log.md` (untracked) owns raw
+measurements.*
## What it is
-One process places the first N transformer layers plus the small endcaps of a model on the
-fast "front" GPU (the 15.92 GiB RX 9070 over USB4) and the rest on the "main" GPU (the 118 GiB
-Strix Halo iGPU), with an asynchronous host-staged bridge on every crossing:
+One process places the first N transformer layers plus the small endcaps of a model on
+one GPU (the "front") and the rest on another (the "main"), with an asynchronous
+host-staged bridge on every crossing:
src tensor --D2H--> pinned slot ring --H2D--> dst tensor
@@ -18,28 +19,48 @@ Both legs are enqueued on the two devices' own compute streams; the host never b
destination tensor is a fresh allocation, so callers may keep using it after the slot cycles.
`KYOJIN_BRIDGE=0` falls back to `to_device` (split still runs, crossings block).
+Devices are not tied to a role. Either device may be the front or the main one, and the
+split is not restricted to a particular architecture pair. Kernel support remains
+per-arch: the split owns placement and transport, not kernel ports.
+
+**Measured configuration.** The development box is an RX 9070 (gfx1201, 15.92 GiB) over
+USB4 as the front and a 118 GiB Strix Halo iGPU (gfx1151) as the main. All numbers in
+`docs-notes/split-log.md` and the support matrix come from that pair unless a note says
+otherwise; they are measurements, not assumptions of the interface.
+
## Interface
| Flag (CLI) | Env fallback | Meaning |
| --- | --- | --- |
| `--front-layers auto\|N` | `KYOJIN_FRONT_LAYERS` | first N transformer layers on the front device; 0 = off |
-| `--front-device auto\|gfx1201\|cuda:N\|uuid` | `KYOJIN_FRONT_DEVICE` | front device selection (auto = first gfx12 device) |
+| `--main-device auto\|cuda:N\|gfxXXXX\|uuid\|name` | `KYOJIN_MAIN_DEVICE` | main device selection (`auto` = `cuda:0`) |
+| `--front-device auto\|cuda:N\|gfxXXXX\|uuid\|name` | `KYOJIN_FRONT_DEVICE` | front device selection (`auto` = the only other device when two are visible; otherwise a selector is required) |
| `--endcaps on\|off` | `KYOJIN_ENDCAPS` | move the text allowlist (norm/hc/lm_head-like) and whole MTP/vision components to the front (default on) |
-| `--front-reserve-gb` | `KYOJIN_FRONT_RESERVE_GB` | VRAM held as a load-time slab on the front for workspace (default 1.2) |
+| `--front-reserve-gb` | `KYOJIN_FRONT_RESERVE_GB` | VRAM held as a load-time slab on the front for workspace (default 1.2; a tuning value, size it to the card) |
| `--split-preset auto\|glm\|qwen\|ds41\|none` | `KYOJIN_SPLIT_PRESET` | per-model unsafe-env preset slot; GLM needs none today |
| `--split-graphs auto\|on\|off` | — | per-segment capture (Stage 6); split forces graphs off until then |
+`cuda:N` is the torch device index **after** `HIP_VISIBLE_DEVICES`, not the `rocm-smi`
+index. Explicit selectors win in either position: `front=cuda:1/main=cuda:0` and
+`front=cuda:0/main=cuda:1` are both valid. A front-only selector keeps working when it
+lands on `cuda:0`: with exactly two devices, `main=auto` takes the other device. Two
+explicit selectors that resolve to the same device fail, and a one-device split fails with
+a clear error. With more than two visible devices, `auto` for either role requires an
+explicit selector and prints the inventory.
+
`KYOJIN_FRONT_LAYERS=…` without CLI flags also works in `model_init.init` paths
-(examples/eval tools). The legacy `EXL3_LOAD_SPLIT` budget knob is **not** part of this
-interface; combining it with the new map must error.
+(examples/eval tools); `KYOJIN_MAIN_DEVICE` is honoured there too. The legacy
+`EXL3_LOAD_SPLIT` budget knob is **not** part of this interface; combining it with the
+new map must error.
-## Core objects (Stage 1)
+## Core objects (Stage 1.5)
- `exllamav3/device_map.py`: `SplitPlan` owns every component the process places.
`ComponentPolicy` declares `front_eligible`, `endcaps_front`, the endcap allowlist,
arch gate and unsafe env. `ComponentMap` resolves one component's contiguous boundary.
- Unknown non-layer modules are logged and kept on main; auxiliary components never move
- front implicitly.
+ `resolve_devices(front, main, devices=None)` selects by position; `DeviceInfo` lets the
+ selection tests run without a GPU. Unknown non-layer modules are logged and kept on
+ main; auxiliary components never move front implicitly.
- `exllamav3/bridge.py`: one bridge per *config*, installed by `SplitPlan.install_bridges`
for the target, a separate draft config, vision and any extra config.
- `exllamav3/serve_split.py` (shared with `tools/kyojin_serve_split.py`): CLI/env parsing,
@@ -53,7 +74,9 @@ interface; combining it with the new map must error.
The Stage 0 replay showed a process-wide allocator cap makes 128K split runs bimodal;
the slab removes bytes from the pool and is dropped at the first main module (or after
the last component), leaving the freed block available to the workspace without
- changing the allocator's policy or the main device's numerics.
+ changing the allocator's policy or the main device's numerics. The 1.2 GiB default is
+ a tuning value for a small front card, not an architecture rule; Stage 5 derives it
+ from the device total.
- `prepare_for_device` routes CUDA↔CUDA moves through the bridge once
`config.split_active` is set; CPU moves keep the pinned/async path.
- Graphs: split mode declines whole-forward, lag-1, `prepare_inputs` and per-block captures
@@ -62,23 +85,29 @@ interface; combining it with the new map must error.
cache layer must sit on the device its owning layer was mapped to.
- Auto-N is a Stage 1 skeleton: it uses actual safetensors bytes for each layer, the
cache/recurrent sizes for layers below N, the front endcap bytes and the reserve, with
- a `KYOJIN_AUTON_SAFETY_GB` margin (default 0.25) for allocator slack. GLM caps auto at
- five layers for `-c > 65536` until the gfx1201 KDA prefill workspace is part of the
- budget. Components declared after the target (GLM's MTP/vision) are not yet subtracted
- before the target load; Stage 5 owns cross-component/pre-load auto sizing.
+ a `KYOJIN_AUTON_SAFETY_GB` margin (default 0.25) for allocator slack. Adapter tuning
+ stays in the adapter: GLM caps auto at five layers for `-c > 65536` only on a gfx12
+ front, where the deterministic split KDA chain adds a prefill workspace the byte budget
+ does not yet know. Components declared after the target (GLM's MTP/vision) are not yet
+ subtracted before the target load; Stage 5 owns cross-component/pre-load auto sizing.
- JIT HIP loaders compile per (device, defines) and launch on the tensor's device stream;
`kda_fused_h`, `gdn_*`, `gr_mix` and `ple_hip` are gfx11.5 WMMA/CI paths and refuse other
- archs. gfx12 runs the deterministic fla chain (`EXL3_KDA_FUSE=0` forced there) — see PR C
- for the fused port. `qsa_prefill_hip` readiness is cached per device, and all audited
- dsv41/gr/ple loaders select the calling device before every launch.
+ archs. In split mode, gfx12 runs the deterministic fla KDA chain (`EXL3_KDA_FUSE=0`
+ forced there); other arches keep the fused path. See PR C for the fused gfx12 port.
+ `qsa_prefill_hip` readiness is cached per device, and all audited dsv41/gr/ple loaders
+ select the calling device before every launch.
## Determinism / verification policy
-- Split **off** must stay byte-identical to `main` (outputs and the serve env block).
+- Split **off** must stay byte-identical to `main` (outputs and the serve env block), and
+ must not enumerate devices or mutate split env.
- Split **on** is judged by run-to-run determinism (plain greedy), KLD/task metrics and the
- needle probe — cross-arch (gfx1201 vs gfx1151) is not expected to be bitwise.
+ needle probe — a mixed-arch pair is not expected to be bitwise.
- `tools/strix_halo/split_eval.py` (GLM) runs the battery: `--baseline`, `--front-layers`,
- `--needle-depth`, `--num-draft`, `--perf-tokens/--perf-reps`, `--compare a.json b.json`.
+ `--main-device`/`--front-device`, `--needle-depth`, `--num-draft`,
+ `--perf-tokens/--perf-reps`, `--compare a.json b.json`. Its context-dependent front-layer
+ default is harness tuning exposed as `--long-ctx-front-layers`/`--short-ctx-front-layers`,
+ not a property of the split.
## Model support
@@ -86,11 +115,13 @@ See `doc/split-support-matrix.md` (GLM measured; Qwen and DSV4 adapters staged;
best-effort inheritors of the generic `Model` path). Core placement is model-agnostic:
adapters declare components and policies, unknown non-layer modules default to main.
-## Known limitations (Stage 1)
+## Known limitations (Stage 1.5)
- Auto-N uses actual text bytes/cache/endcaps but not components declared after the target
- load; Stage 5 finishes cross-component, pre-load sizing. For GLM: N=6 at ≤65K, N=5 for
- long context until the gfx12 KDA kernel lands.
+ load; Stage 5 finishes cross-component, pre-load sizing. On the measured 16 GB gfx12
+ front: N=6 at ≤65K, N=5 for long context until the gfx12 KDA kernel lands.
- MTP on the split is not yet deterministic (`--num-draft 0` remains the deterministic mode).
- No per-segment graphs (Stage 6); split runs eager and pays ~0.95× decode (GLM, MTP).
- Qwen3.8 and DSV4 adapters are Stage 3/4; their component inventories are code-level only.
+- Same-arch and RDNA3/3.5 pairs are selection-tested only until such hardware is available.
+ A missing kernel fallback on a new arch is a model/kernel support issue, not a split defect.
diff --git a/exllamav3/bridge.py b/exllamav3/bridge.py
index 2011ada..c8d019e 100644
--- a/exllamav3/bridge.py
+++ b/exllamav3/bridge.py
@@ -2,10 +2,11 @@ from __future__ import annotations
"""Async host-staged bridge for the contiguous layer split.
-The iGPU (gfx1151) and the eGPU (gfx1201) have no working, fast peer path: a direct
-device-to-device copy on this link class is both slow (under 1 GB/s observed on the
-9070 side) and asymmetric. Every segment crossing therefore goes through pinned host
-memory:
+The front and main devices may be any two supported ROCm devices in either
+position. On the measured mixed configuration (RX 9070 front over USB4 + Strix
+Halo main) there is no working, fast peer path: a direct device-to-device copy on
+that link class is both slow (under 1 GB/s observed on the 9070 side) and
+asymmetric. Every segment crossing therefore goes through pinned host memory:
src tensor --D2H--> pinned slot --H2D--> dst tensor
diff --git a/exllamav3/device_map.py b/exllamav3/device_map.py
index fac5342..5282b64 100644
--- a/exllamav3/device_map.py
+++ b/exllamav3/device_map.py
@@ -4,7 +4,16 @@ from __future__ import annotations
Contiguous layer split: resolve the two devices, declare per-component policies and
map model modules to them.
-The map is deliberately independent of the architecture: modules carrying a
+Devices are selected by position, never by architecture. ``main`` defaults to
+``cuda:0``; ``front`` defaults to the only other visible device when exactly two
+devices are present. A front-only selector keeps working when it lands on
+``cuda:0``: main auto then takes the other device. Either position accepts
+``cuda:N``, ``gfxXXXX``, a device UUID or a device-name substring, and either
+device may serve either position. ``cuda:N`` is the torch index after
+``HIP_VISIBLE_DEVICES``, not the ``rocm-smi`` index. More than two visible devices
+require an explicit selector.
+
+The map itself is deliberately independent of the architecture: modules carrying a
``layer_idx`` are transformer layers and are assigned to the front device for
indices ``0 .. front_layers - 1`` and to the main device for the rest. Modules
without a ``layer_idx`` are endcaps (embedding, hyper-connection drivers, final
@@ -36,6 +45,12 @@ from .util.arch_list import device_arch
GIB = 1024 ** 3
+# Default load-time slab on the front device. A tuning value, not an architecture
+# assumption: size it to the front card. Stage 5 derives it from the device total.
+DEFAULT_FRONT_RESERVE_GB = 1.2
+DEFAULT_MAIN_DEVICE = "auto"
+DEFAULT_FRONT_DEVICE = "auto"
+
# Text prologue/epilogue modules that are safe to place on the front device. The
# list is by class name and key suffix, not by model: an adapter can extend it in
# its ComponentPolicy. Modules outside this list default to the main device.
@@ -63,54 +78,163 @@ def _device_uuid(index: int) -> str:
return str(u).lower().replace("-", "")
+@dataclass(frozen = True)
+class DeviceInfo:
+ """One visible device as the selector sees it.
+
+ ``arch`` is a ROCm arch name when the runtime exposes one; an unknown or
+ non-ROCm device keeps an empty string so selection by ``cuda:N``/name still
+ works. The inventory is injectable so selection tests need no GPU.
+ """
+
+ index: int
+ name: str = ""
+ arch: str = ""
+ uuid: str = ""
+
+ def describe(self) -> str:
+ parts = [f"cuda:{self.index}"]
+ if self.arch:
+ parts.append(self.arch)
+ if self.name:
+ parts.append(self.name)
+ return " ".join(parts)
+
+
@dataclass(frozen = True)
class Devices:
main: torch.device
front: torch.device | None
main_arch: str
front_arch: str | None
+ inventory: tuple[DeviceInfo, ...] = ()
-def resolve_devices(front: str | None = None) -> Devices:
- """Resolve main/front by architecture.
+def _device_info(index: int) -> DeviceInfo:
+ name = ""
+ try:
+ name = torch.cuda.get_device_name(index)
+ except Exception: # noqa: BLE001 - inventory is best effort
+ pass
+ try:
+ arch = _arch_of(index)
+ except Exception: # noqa: BLE001 - selection does not need an arch
+ arch = ""
+ try:
+ uuid = _device_uuid(index)
+ except Exception: # noqa: BLE001
+ uuid = ""
+ return DeviceInfo(index = index, name = name, arch = arch, uuid = uuid)
- ``front`` (or KYOJIN_FRONT_DEVICE) accepts ``auto``, ``gfx1201``, ``cuda:N``
- or a device UUID / name substring. Auto selects the first gfx120/gfx12
- device that is not the gfx1151 main device.
- """
+
+def probe_devices() -> list[DeviceInfo]:
+ """Inventory the visible devices; the only GPU-dependent step in selection."""
if not torch.cuda.is_available():
- raise RuntimeError("layer split requires a HIP/CUDA device")
- n = torch.cuda.device_count()
- arch = {i: _arch_of(i) for i in range(n)}
- main_i = next((i for i, a in arch.items() if a == "gfx1151"), 0)
- req = (front if front is not None else os.environ.get("KYOJIN_FRONT_DEVICE", "auto") or "auto").strip().lower()
-
- if req in ("", "auto"):
- front_i = next((i for i, a in arch.items() if a.startswith("gfx12") and i != main_i), None)
- elif req.startswith("cuda:"):
- front_i = int(req.split(":", 1)[1])
- if front_i < 0 or front_i >= n:
- raise RuntimeError(f"KYOJIN_FRONT_DEVICE={req}: no such device")
- elif req.startswith("gfx"):
- front_i = next((i for i, a in arch.items() if a == req), None)
+ raise RuntimeError("layer split requires two HIP/CUDA devices")
+ return [_device_info(i) for i in range(torch.cuda.device_count())]
+
+
+def _format_inventory(infos: list[DeviceInfo]) -> str:
+ return ", ".join(d.describe() for d in infos) or "none"
+
+
+def _select_device(req: str, role: str, infos: list[DeviceInfo], env_name: str) -> int:
+ req = (req or "").strip().lower()
+ indexes = {d.index for d in infos}
+ if req.startswith("cuda:"):
+ try:
+ index = int(req.split(":", 1)[1])
+ except ValueError as exc:
+ raise RuntimeError(f"{role} device selector {req!r} is not a valid cuda:N") from exc
+ if index not in indexes:
+ raise RuntimeError(f"{role} device {req!r}: no such device; available: "
+ f"{_format_inventory(infos)}")
+ return index
+ if req.startswith("gfx"):
+ matches = [d.index for d in infos if (d.arch or "").lower() == req]
else:
key = req.replace("-", "")
- front_i = next((i for i in range(n)
- if key and (key in _device_uuid(i) or req in torch.cuda.get_device_properties(i).name.lower())), None)
-
- if front_i is None:
+ matches = [
+ d.index for d in infos
+ if (key and key in (d.uuid or "").lower().replace("-", ""))
+ or (req and req in (d.name or "").lower())
+ ]
+ if len(matches) > 1:
+ raise RuntimeError(f"{role} device {req!r} matched several devices; use cuda:N or "
+ f"a more specific selector; available: {_format_inventory(infos)}")
+ if not matches:
+ raise RuntimeError(f"{role} device {req!r} did not match any device; available: "
+ f"{_format_inventory(infos)}. Set {env_name}=cuda:N "
+ f"(or gfxXXXX/uuid/name).")
+ return matches[0]
+
+
+def resolve_devices(
+ front: str | None = None,
+ main: str | None = None,
+ devices: list[DeviceInfo] | None = None,
+) -> Devices:
+ """Resolve the front/main pair by position, never by architecture.
+
+ ``main`` (or KYOJIN_MAIN_DEVICE) defaults to ``auto`` = ``cuda:0``. ``front``
+ (or KYOJIN_FRONT_DEVICE) defaults to the only other visible device when exactly
+ two are visible; with one device the split cannot run, and with more than two an
+ explicit selector is required. If the front is explicit and occupies ``cuda:0``
+ while main is ``auto`` with exactly two devices visible, main takes the other
+ device so a front-only selector keeps working. Both selectors accept
+ ``cuda:N``, ``gfxXXXX``, a device UUID or a device-name substring; either
+ position may be either device.
+
+ ``devices`` injects a synthetic inventory; production callers omit it and probe
+ the runtime. Selection itself does not depend on an architecture.
+ """
+ infos = list(devices) if devices is not None else probe_devices()
+ if len(infos) < 2:
raise RuntimeError(
- f"layer split requested but no front device matched {req!r}; "
- f"devices: {[(i, a) for i, a in arch.items()]}. "
- "Set KYOJIN_FRONT_DEVICE=gfx1201 (or cuda:N)."
- )
+ f"layer split needs two devices; visible: {_format_inventory(infos)}. "
+ "Unset KYOJIN_FRONT_LAYERS / --front-layers to run on one device.")
+
+ main_req = main if main is not None else os.environ.get("KYOJIN_MAIN_DEVICE", DEFAULT_MAIN_DEVICE)
+ front_req = front if front is not None else os.environ.get("KYOJIN_FRONT_DEVICE", DEFAULT_FRONT_DEVICE)
+ main_req = (main_req or DEFAULT_MAIN_DEVICE).strip().lower()
+ front_req = (front_req or DEFAULT_FRONT_DEVICE).strip().lower()
+ main_auto = main_req in ("", "auto")
+
+ if main_auto:
+ main_i = min(d.index for d in infos)
+ else:
+ main_i = _select_device(main_req, "main", infos, "KYOJIN_MAIN_DEVICE")
+
+ if front_req in ("", "auto"):
+ if len(infos) != 2:
+ raise RuntimeError(
+ f"front device is 'auto' but {len(infos)} devices are visible; set "
+ f"KYOJIN_FRONT_DEVICE (or --front-device) to one of: {_format_inventory(infos)}")
+ front_i = next(d.index for d in infos if d.index != main_i)
+ else:
+ front_i = _select_device(front_req, "front", infos, "KYOJIN_FRONT_DEVICE")
+ if main_auto and front_i == main_i:
+ # An explicit front selector must keep working when it lands on cuda:0:
+ # main auto takes the only other device. With more devices the choice
+ # is ambiguous, so ask for the main selector instead of guessing.
+ if len(infos) == 2:
+ main_i = next(d.index for d in infos if d.index != front_i)
+ else:
+ raise RuntimeError(
+ f"main device is 'auto' (cuda:{main_i}) and equals the explicit front; "
+ f"with {len(infos)} devices visible set KYOJIN_MAIN_DEVICE (or --main-device)")
+
if front_i == main_i:
- raise RuntimeError("layer split front device resolves to the main device")
+ raise RuntimeError(f"layer split main and front resolve to the same device "
+ f"(cuda:{main_i}); choose a different --front-device/--main-device")
+ by_index = {d.index: d for d in infos}
+ main_info, front_info = by_index[main_i], by_index[front_i]
return Devices(
main = torch.device("cuda", main_i),
front = torch.device("cuda", front_i),
- main_arch = arch[main_i],
- front_arch = arch[front_i],
+ main_arch = main_info.arch or "",
+ front_arch = front_info.arch or "",
+ inventory = tuple(infos),
)
@@ -316,7 +440,7 @@ class ComponentMap:
endcaps: bool,
devices: Devices,
component: str = "text",
- front_reserve_gb: float = 1.2,
+ front_reserve_gb: float = DEFAULT_FRONT_RESERVE_GB,
main_reserve_gb: float = 0.0,
config = None,
cache = None,
@@ -337,7 +461,7 @@ class ComponentMap:
endcaps: bool,
devices: Devices,
policy: ComponentPolicy,
- front_reserve_gb: float = 1.2,
+ front_reserve_gb: float = DEFAULT_FRONT_RESERVE_GB,
main_reserve_gb: float = 0.0,
config = None,
cache = None,
@@ -562,7 +686,7 @@ class SplitPlan:
devices: Devices,
endcaps: bool = True,
front_layers: int | str = 0,
- front_reserve_gb: float = 1.2,
+ front_reserve_gb: float = DEFAULT_FRONT_RESERVE_GB,
main_reserve_gb: float = 0.0,
preset: str = "auto",
auto_cap: int | None = None,
@@ -641,7 +765,7 @@ class SplitPlan:
self.front_layers = n
self.logger(f"[split] auto-N: {n} front layer(s) "
f"(budget {self._auto_budget() / GIB:.2f} GiB, "
- f"reserve {self.front_reserve_gb:.2f} GiB)")
+ f"reserve {self.front_reserve_gb:.2f} GiB tuning slab)")
for name, (model, config, cache, policy, layer, load_order) in self._decls.items():
if self.auto and policy.kind == "text":
layer = self.front_layers
@@ -690,6 +814,8 @@ class SplitPlan:
if self.devices.front is None:
return 0
total = int(torch.cuda.get_device_properties(self.devices.front).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)
return max(0, total - int(self.front_reserve_gb * GIB) - safety)
diff --git a/exllamav3/model_init.py b/exllamav3/model_init.py
index a29ac02..bf1441a 100755
--- a/exllamav3/model_init.py
+++ b/exllamav3/model_init.py
@@ -349,7 +349,8 @@ def init(
if os.environ.get("EXL3_LOAD_SPLIT"):
raise ValueError("KYOJIN_FRONT_LAYERS cannot be combined with the legacy EXL3_LOAD_SPLIT budget")
from .device_map import SplitPlan, resolve_devices
- devices = resolve_devices(os.environ.get("KYOJIN_FRONT_DEVICE"))
+ devices = resolve_devices(os.environ.get("KYOJIN_FRONT_DEVICE"),
+ os.environ.get("KYOJIN_MAIN_DEVICE"))
endcaps = os.environ.get("KYOJIN_ENDCAPS", "1") != "0"
reserve = float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2"))
split_plan = SplitPlan(devices, endcaps = endcaps, front_layers = front_layers,
diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.py
index 6206783..aab336a 100644
--- a/exllamav3/serve_split.py
+++ b/exllamav3/serve_split.py
@@ -3,8 +3,14 @@ from __future__ import annotations
"""Shared serve-side helper for the contiguous layer split.
Adapters (``tools/glm`` first, then Qwen/DSV4) parse the same flags, resolve the
-same devices and hand their components to ``SplitPlan``. No placement logic
-lives here: a component is declared with a name and, optionally, a policy.
+same devices and hand their components to ``SplitPlan``. No placement logic or
+hardware-specific default lives here: a component is declared with a name and,
+optionally, a policy. Devices are chosen by position (``cuda:N``, ``gfxXXXX``,
+UUID or name); either device may be the front or the main one.
+
+This module stays pure stdlib at import: adapters must be able to apply their
+serving environment before ``exllamav3`` (and therefore torch) is imported, so the
+exllamav3 imports are deliberately deferred to call time.
"""
import argparse
@@ -16,6 +22,10 @@ from typing import TYPE_CHECKING
if TYPE_CHECKING:
from exllamav3.device_map import ComponentMap, ComponentPolicy, SplitPlan
+# Load-time slab held on the front device. A tuning value, not a hardware rule:
+# size it to the front card (Stage 5 derives it from the device total).
+DEFAULT_FRONT_RESERVE_GB = 1.2
+
# Split mode runs eager until per-segment capture lands (Stage 6). A whole-forward
# or per-block graph must never span the host-staged bridge between segments.
# Deferred prefill residual fusions keep a pending state on the producing stream;
@@ -69,8 +79,9 @@ def parse_front_layers(value) -> int | str:
class SplitSettings:
front_layers: int | str = 0
front_device: str = "auto"
+ main_device: str = "auto"
endcaps: bool = True
- front_reserve_gb: float = 1.2
+ front_reserve_gb: float = DEFAULT_FRONT_RESERVE_GB
preset: str = "auto"
split_graphs: str = "auto"
@@ -83,7 +94,8 @@ class SplitSettings:
return self.front_layers == "auto"
def describe(self) -> str:
- return (f"front_layers={self.front_layers} front_device={self.front_device} "
+ return (f"front_layers={self.front_layers} main_device={self.main_device} "
+ f"front_device={self.front_device} "
f"endcaps={'on' if self.endcaps else 'off'} "
f"reserve={self.front_reserve_gb:.2f}GiB preset={self.preset} "
f"graphs={self.split_graphs}")
@@ -93,15 +105,20 @@ def add_split_arguments(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--front-layers", default = None,
help = "contiguous layer split: first N transformer layers on the front device; "
"auto = fit from actual bytes; 0 = off (default: KYOJIN_FRONT_LAYERS, else 0)")
+ parser.add_argument("--main-device", default = None,
+ help = "main device: auto, gfxXXXX, cuda:N or a UUID/name substring "
+ "(default: KYOJIN_MAIN_DEVICE, else auto = cuda:0)")
parser.add_argument("--front-device", default = None,
- help = "front device: auto, gfx1201, cuda:N or a UUID/name substring "
- "(default: KYOJIN_FRONT_DEVICE, else auto)")
+ help = "front device: auto, gfxXXXX, cuda:N or a UUID/name substring "
+ "(default: KYOJIN_FRONT_DEVICE, else auto = the only other device). "
+ "cuda:N is the torch index after HIP_VISIBLE_DEVICES; either device "
+ "may be the front or the main one")
parser.add_argument("--endcaps", choices = ("on", "off"), default = None,
help = "with a layer split, keep allowlisted embedding/norm/lm_head/MTP/vision "
"modules on the front device (default: KYOJIN_ENDCAPS, else on)")
parser.add_argument("--front-reserve-gb", type = float, default = None,
- help = "VRAM held as a load-time slab on the front device for workspace "
- "(default: KYOJIN_FRONT_RESERVE_GB, else 1.2)")
+ help = "VRAM held as a load-time slab on the front device for workspace; a "
+ "tuning value, not a hardware rule (default: KYOJIN_FRONT_RESERVE_GB, else 1.2)")
parser.add_argument("--split-preset", choices = tuple(SPLIT_PRESETS), default = None,
help = "per-model split preset (default: KYOJIN_SPLIT_PRESET, else auto)")
parser.add_argument("--split-graphs", choices = ("auto", "on", "off"), default = None,
@@ -121,9 +138,10 @@ def settings_from_namespace(args) -> SplitSettings:
graphs = getattr(args, "split_graphs", None) or "auto"
reserve = getattr(args, "front_reserve_gb", None)
if reserve is None:
- reserve = float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2"))
+ reserve = float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", str(DEFAULT_FRONT_RESERVE_GB)))
return SplitSettings(
front_layers = parse_front_layers(raw),
+ main_device = getattr(args, "main_device", None) or os.environ.get("KYOJIN_MAIN_DEVICE") or "auto",
front_device = getattr(args, "front_device", None) or os.environ.get("KYOJIN_FRONT_DEVICE") or "auto",
endcaps = bool(endcaps),
front_reserve_gb = float(reserve),
@@ -169,7 +187,7 @@ class SplitController:
self.plan = None
if settings.enabled:
from exllamav3.device_map import resolve_devices
- self.devices = resolve_devices(settings.front_device)
+ self.devices = resolve_devices(settings.front_device, settings.main_device)
@property
def enabled(self) -> bool:
diff --git a/exllamav3/util/arch_list.py b/exllamav3/util/arch_list.py
index 704f597..8e072eb 100644
--- a/exllamav3/util/arch_list.py
+++ b/exllamav3/util/arch_list.py
@@ -59,6 +59,25 @@ def select_device(device=None) -> int:
GFX115_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))
+
+# Arches where the fused KDA output path is known nondeterministic in split mode.
+# gfx12 today; the split gate and the adapters that size the fallback workspace
+# must use this one predicate so they cannot drift.
+KDA_FUSED_UNSTABLE_PREFIXES = ("gfx12",)
+
+
+def kda_fused_output_unstable(arch: str | None, unknown: bool = True) -> bool:
+ """Whether the fused KDA output path is known unsafe on this arch.
+
+ An unreadable/empty arch is conservatively treated as unstable by default, so
+ split mode takes the deterministic chain and adapters size its workspace.
+ """
+ key = (arch or "").strip().lower()
+ if not key:
+ return bool(unknown)
+ return key.startswith(KDA_FUSED_UNSTABLE_PREFIXES)
+
+
_support_cache = {}
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 98f128b..d1fefc9 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -44,22 +44,22 @@ def _hip_ok(q, k, v, beta, Akk, Aqk, h0):
and (h0 is None or h0.is_contiguous()))
-_FUSED_STABLE_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))
_fused_stable = {} # arch gate per device index; read on every KDA prefill chunk
def _fused_output_stable(device=None) -> bool:
"""Whether the fused Triton KDA output path is run-to-run deterministic on this arch.
- Measured nondeterministic on gfx1201 (three loads produced three different greedy
- branches); gfx11.5 keeps it. Conservative default when the arch cannot be read: use
- the deterministic fla chain."""
+ Measured nondeterministic on gfx12 (RDNA4): three loads produced three different
+ greedy branches. Other supported archs keep the fused path. An unreadable arch
+ is conservatively treated as unstable, so split mode uses the deterministic
+ chain."""
try:
- from exllamav3.util.arch_list import device_arch, device_index
+ from exllamav3.util.arch_list import device_arch, device_index, kda_fused_output_unstable
idx = device_index(device)
ok = _fused_stable.get(idx)
if ok is None:
- ok = _fused_stable[idx] = device_arch(idx) in _FUSED_STABLE_ARCHS
+ ok = _fused_stable[idx] = not kda_fused_output_unstable(device_arch(idx))
return ok
except Exception: # noqa: BLE001
return False
@@ -205,11 +205,12 @@ def chunk_kda(
# keep the fla chain: the one-program-per-head fused loop is ~0.14 ms slower there (T=255 sweep).
fuse = int(os.environ.get("EXL3_KDA_FUSE", "3")) if K <= 128 and chunk_size == 64 and T >= 512 else 0
if fuse and os.environ.get("KYOJIN_SPLIT_ACTIVE", "0") != "0" and not _fused_output_stable(q.device):
- # A layer split runs KDA on both a gfx1151 main and a gfx12 front. The fused output
- # path is not run-to-run deterministic on gfx12, and the gfx11.5 HIP kernel cannot be
- # JIT-built there (kda_fused_h_hip.supported() declines, so _hip_ok already fell back
- # to the Triton fuse path). Force the deterministic fla chain on that arch only; keep
- # it here, split-side, until the gfx12 fused kernel lands.
+ # A layer split can run KDA on a gfx12 front and a different main device in one
+ # process. The fused output path is not run-to-run deterministic on gfx12, and
+ # its gfx11.5 HIP kernel cannot be JIT-built there (kda_fused_h_hip.supported()
+ # declines, so _hip_ok already fell back to the Triton fuse path). Force the
+ # deterministic fla chain on that arch only; keep it here, split-side, until the
+ # gfx12 fused kernel lands.
fuse = 0
if fuse:
# EXL3_KDA_HF=1 (default off, read per call): 16-row-chunk WY kernel (hip/kda_hf.hip, derived from hipfire's GDN kernel,
diff --git a/tests/test_arch_list.py b/tests/test_arch_list.py
index a1e6583..e947177 100644
--- a/tests/test_arch_list.py
+++ b/tests/test_arch_list.py
@@ -68,3 +68,14 @@ Name: gfx1100
arch_list.maybe_set_arch_list_env()
assert arch_list.os.environ["PYTORCH_ROCM_ARCH"] == "gfx1201;gfx1100;gfx1030"
+
+
+def test_kda_fused_output_unstable_is_shared_and_conservative():
+ assert arch_list.kda_fused_output_unstable("gfx1201")
+ assert arch_list.kda_fused_output_unstable("gfx1200")
+ assert not arch_list.kda_fused_output_unstable("gfx1151")
+ assert not arch_list.kda_fused_output_unstable("gfx1100")
+ # An unreadable arch is conservative by default, explicit opt-out for callers.
+ assert arch_list.kda_fused_output_unstable("")
+ assert arch_list.kda_fused_output_unstable(None)
+ assert not arch_list.kda_fused_output_unstable("", unknown = False)
diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.py
index 28e81f9..87ddd5c 100644
--- a/tests/test_split_plan_cpu.py
+++ b/tests/test_split_plan_cpu.py
@@ -126,6 +126,26 @@ def _devices(dm):
)
+def _infos(dm, *pairs):
+ """Synthetic device inventory: (arch, optional name/uuid) per device index."""
+ out = []
+ for i, item in enumerate(pairs):
+ if isinstance(item, str):
+ arch, name, uuid = item, f"device-{i}", ""
+ else:
+ arch = item[0]
+ name = item[1] if len(item) > 1 else f"device-{i}"
+ uuid = item[2] if len(item) > 2 else ""
+ out.append(dm.DeviceInfo(index = i, name = name, arch = arch, uuid = uuid))
+ return out
+
+
+def clean_split_env(monkeypatch):
+ for key in ("KYOJIN_FRONT_DEVICE", "KYOJIN_MAIN_DEVICE", "KYOJIN_FRONT_LAYERS", "KYOJIN_ENDCAPS"):
+ monkeypatch.delenv(key, raising = False)
+
+
def _glm_model():
embedding = FakeModule("model.language_model.embed_tokens", caps = {"prefer_cpu": True})
expand = FakeModule("hc_expand")
@@ -340,6 +360,145 @@ def test_named_preset_is_applied_by_the_plan(split_modules, monkeypatch):
split.SPLIT_PRESETS["glm"] = old
+ ("gfx1100", "gfx1101"), # RDNA3
+ ("gfx1150", "gfx1151"), # RDNA3.5
+ ("gfx1200", "gfx1201"), # RDNA4
+ ("gfx1151", "gfx1100"), # mixed, reversed
+ ("gfx1201", "gfx1201"), # same arch
+ ("gfx1100", "gfx1100"),
+ ("", "sm_90"), # unknown / CUDA-style names: selection only
+])
+def test_auto_selection_is_positional_and_arch_independent(split_modules, clean_split_env, archs):
+ dm, _bridge, _split = split_modules
+ devices = dm.resolve_devices(devices = _infos(dm, *archs))
+ assert devices.main == torch.device("cuda", 0)
+ assert devices.front == torch.device("cuda", 1)
+ assert devices.main_arch == archs[0] and devices.front_arch == archs[1]
+ assert [d.index for d in devices.inventory] == [0, 1]
+
+
+def test_explicit_selectors_support_both_positions(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ infos = _infos(dm, "gfx1151", "gfx1201")
+
+ mixed = dm.resolve_devices("cuda:1", "cuda:0", devices = infos)
+ assert (mixed.main_arch, mixed.front_arch) == ("gfx1151", "gfx1201")
+
+ reversed_pair = dm.resolve_devices("gfx1151", "gfx1201", devices = infos)
+ assert reversed_pair.main == torch.device("cuda", 1)
+ assert reversed_pair.front == torch.device("cuda", 0)
+ assert (reversed_pair.main_arch, reversed_pair.front_arch) == ("gfx1201", "gfx1151")
+
+ by_name_uuid = dm.resolve_devices("device-1", "device-0", devices = infos)
+ assert by_name_uuid.main == torch.device("cuda", 0)
+ assert by_name_uuid.front == torch.device("cuda", 1)
+
+
+def test_explicit_front_with_auto_main_uses_the_other_device(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ infos = _infos(dm, "gfx1151", "gfx1201")
+
+ by_index = dm.resolve_devices("cuda:0", devices = infos)
+ assert by_index.main == torch.device("cuda", 1)
+ assert by_index.front == torch.device("cuda", 0)
+
+ by_arch = dm.resolve_devices("gfx1151", devices = infos)
+ assert by_arch.main == torch.device("cuda", 1)
+ assert by_arch.front == torch.device("cuda", 0)
+
+ many = _infos(dm, "gfx1100", "gfx1151", "gfx1201")
+ with pytest.raises(RuntimeError, match = "set KYOJIN_MAIN_DEVICE"):
+ dm.resolve_devices("cuda:0", devices = many)
+
+
+def test_uuid_and_name_substring_selectors(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ infos = _infos(
+ dm,
+ ("gfx1201", "AMD Radeon RX 9070 XT", "aa-bb-cc"),
+ ("gfx1151", "AMD Radeon 8060S", "dd-ee-ff"),
+ )
+ dev = dm.resolve_devices("aa-bb-cc", "8060s", devices = infos)
+ assert dev.main == torch.device("cuda", 1)
+ assert dev.front == torch.device("cuda", 0)
+
+
+def test_main_device_env_is_honoured(split_modules, clean_split_env, monkeypatch):
+ dm, _bridge, _split = split_modules
+ monkeypatch.setenv("KYOJIN_MAIN_DEVICE", "cuda:1")
+ dev = dm.resolve_devices(devices = _infos(dm, "gfx1151", "gfx1201"))
+ assert dev.main == torch.device("cuda", 1)
+ assert dev.front == torch.device("cuda", 0)
+
+
+def test_one_device_fails_clearly(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ with pytest.raises(RuntimeError, match = "two devices"):
+ dm.resolve_devices(devices = _infos(dm, "gfx1151"))
+
+
+def test_three_devices_require_an_explicit_front(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ infos = _infos(dm, "gfx1100", "gfx1151", "gfx1201")
+ with pytest.raises(RuntimeError, match = "3 devices.*--front-device"):
+ dm.resolve_devices(devices = infos)
+ dev = dm.resolve_devices("cuda:2", "cuda:1", devices = infos)
+ assert dev.main == torch.device("cuda", 1)
+ assert dev.front == torch.device("cuda", 2)
+
+
+def test_same_device_and_bad_selectors_fail_clearly(split_modules, clean_split_env):
+ dm, _bridge, _split = split_modules
+ infos = _infos(dm, "gfx1151", "gfx1201")
+ with pytest.raises(RuntimeError, match = "same device"):
+ dm.resolve_devices("cuda:0", "cuda:0", devices = infos)
+ with pytest.raises(RuntimeError, match = "no such device"):
+ dm.resolve_devices("cuda:9", devices = infos)
+ with pytest.raises(RuntimeError, match = "did not match any device"):
+ dm.resolve_devices("gfx9999", devices = infos)
+
+
+def test_settings_parse_main_device_and_keep_split_off_off(split_modules, clean_split_env, monkeypatch):
+ dm, _bridge, split = split_modules
+ monkeypatch.setenv("KYOJIN_MAIN_DEVICE", "cuda:1")
+ args = SimpleNamespace(front_layers = None, front_device = None, main_device = None,
+ endcaps = None, split_preset = None, split_graphs = None,
+ front_reserve_gb = None)
+ settings = split.settings_from_namespace(args)
+ assert settings.main_device == "cuda:1"
+ assert settings.enabled is False
+
+ args.main_device = "gfx1100"
+ args.front_device = "gfx1151"
+ args.front_layers = "2"
+ settings = split.settings_from_namespace(args)
+ assert (settings.main_device, settings.front_device) == ("gfx1100", "gfx1151")
+ assert settings.enabled is True
+
+
+def test_split_off_does_not_touch_device_selection(split_modules, monkeypatch):
+ dm, _bridge, split = split_modules
+
+ def boom(*_a, **_k):
+ pytest.fail("split off must not enumerate or resolve devices")
+
+ monkeypatch.setattr(dm, "resolve_devices", boom)
+ controller = split.SplitController(split.SplitSettings(front_layers = 0,
+ main_device = "cuda:9",
+ front_device = "cuda:9"),
+ logger = lambda *_a: None)
+ assert controller.devices is None
+ assert controller.plan is None
+
+
+def test_split_core_and_help_name_no_hardware(split_modules):
+ for rel in ("exllamav3/device_map.py", "exllamav3/serve_split.py"):
+ text = (ROOT / rel).read_text()
+ for name in ("gfx1151", "gfx1201", "gfx1100", "9070", "8060S", "Strix", "eGPU", "iGPU", "USB4"):
+ assert name not in text, f"{rel} still names {name}"
+
+
def _load_split_eval():
path = ROOT / "tools" / "strix_halo" / "split_eval.py"
spec = importlib.util.spec_from_file_location("split_eval_harness", path)
@@ -362,6 +521,16 @@ def test_harness_default_front_layers_depends_on_context(monkeypatch):
assert mod.parse_args().front_layers == expected
+def test_harness_front_layers_are_explicit_flags(monkeypatch):
+ mod = _load_split_eval()
+ monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072", "--front-layers", "7"])
+ assert mod.parse_args().front_layers == 7
+ monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072",
+ "--long-ctx-front-layers", "3"])
+ args = mod.parse_args()
+ assert args.front_layers == 3 and args.front_layers_defaulted is True
+
+
def test_adapter_unsafe_env_is_applied_and_logged(split_modules, monkeypatch):
dm, _bridge, _split = split_modules
monkeypatch.setenv("EXL3_TEST_UNSAFE", "0")
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index c237ce6..6306ec7 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -51,6 +51,21 @@ EH_SIDECAR_DEFAULT = "~/models/glm53-mtp-eh-proj-bf16.safetensors"
# Name inside the model folder. Not *.safetensors, so the weight loader never indexes it as model weights
# (same layout trick as uncensor_direction.st); the file is a normal safetensors file.
EH_SIDECAR_IN_PACK = "mtp_eh_proj.st"
+# GLM adapter tuning, deliberately outside the split core: on RDNA4 (gfx12) the
+# split runs the deterministic fla KDA chain, whose long-context prefill workspace
+# is not yet part of auto-N. Measured on a 16 GB gfx12 front card. This is a
+# property of this adapter/front pair, not of the split; explicit --front-layers
+# always wins.
+GLM_LONG_CTX = 65536
+GLM_LONG_CTX_AUTO_CAP = 5
+
+
+def _glm_small_kda_front(front_arch: str | None) -> bool:
+ """True when this front runs the deterministic split KDA chain."""
+ from exllamav3.util.arch_list import kda_fused_output_unstable
+ return kda_fused_output_unstable(front_arch)
+
+
# --sessions > 1 (several requests decode in one step): plain steps take the R-row exact paths (union MoE on the device table, R-row
# GEMV, batched router) instead of per-expert eager loops, and 2..8-row verify blocks replay as graphs. Box 4 requests, same prompts:
# plain 26.1 -> 40.7 tok/s aggregate, speculative 38.1 -> 42.5; one request alone and speculative text equal to the solo run unchanged.
@@ -684,6 +699,7 @@ class ResidentEngine:
image_cache_dir_max_gb: float = IMAGE_CACHE_DIR_MAX_GB,
image_cache_dir_lock_s: float = IMAGE_CACHE_DIR_LOCK_S,
front_layers: int | str = 0, front_device: str | None = None,
+ main_device: str | None = None,
endcaps: bool = True, front_reserve_gb: float = 1.2,
split_settings: SplitSettings | None = None):
import torch
@@ -719,6 +735,7 @@ class ResidentEngine:
split_settings = SplitSettings(
front_layers = parse_front_layers(front_layers),
front_device = front_device or "auto",
+ main_device = main_device or "auto",
endcaps = bool(endcaps), front_reserve_gb = float(front_reserve_gb))
self.split = SplitController(split_settings, logger = lambda m: print(f"serve: {m}", flush=True))
self.split_map = None
@@ -729,12 +746,18 @@ class ResidentEngine:
print(f"serve: layer split: {split_settings.describe()}; "
f"main {plan.devices.main} ({plan.devices.main_arch}), "
f"front {plan.devices.front} ({plan.devices.front_arch})", flush=True)
- if split_settings.auto and max_ctx > 65536:
- # Auto-N's byte budget does not yet know the gfx12 KDA prefill
- # workspace; keep the measured-safe long-context cap until it does.
- plan.auto_cap = 5
- print("serve: layer split: auto-N capped at 5 layers for -c > 65536 "
- "(gfx1201 KDA prefill workspace)", flush=True)
+ if split_settings.auto:
+ if _glm_small_kda_front(plan.devices.front_arch) and max_ctx > GLM_LONG_CTX:
+ # Auto-N's byte budget does not yet know the split KDA prefill
+ # workspace; keep the measured-safe long-context cap until it does.
+ plan.auto_cap = GLM_LONG_CTX_AUTO_CAP
+ print(f"serve: layer split: auto-N capped at {GLM_LONG_CTX_AUTO_CAP} layers for "
+ f"-c > {GLM_LONG_CTX} on this gfx12 front: the split KDA prefill workspace "
+ "is not in the byte budget (adapter tuning; pass --front-layers N to "
+ "override)", flush=True)
+ else:
+ print("serve: layer split: auto-N uncapped (front does not need the split "
+ "KDA long-context reserve)", flush=True)
self.tokenizer = Tokenizer.from_config(self.config)
if os.environ.get("KYO_TOKCACHE", "8") == "0":
self.pec = None
@@ -782,10 +805,16 @@ class ResidentEngine:
self.split_map = self.split.map("text")
if self.split_map is not None and not self.split_map.enabled:
raise ValueError("layer split requested but no usable front device (or auto-N found no layer that fits)")
- if self.split_map is not None and self.split_map.front_layers > 5 and max_ctx > 65536:
- print("serve: warning: front layers > 5 at -c > 65536 is measured to OOM the 16 GB "
- "front on long prefill (gfx1201 KDA fallback workspace); use "
- "--front-layers 5 for long-context split runs", flush=True)
+ if split_settings.auto and self.split_map is not None:
+ print(f"serve: layer split: auto-N chose {self.split_map.front_layers} front layer(s) "
+ f"for -c {ctx}", flush=True)
+ if (self.split_map is not None and self.split_map.front_layers > GLM_LONG_CTX_AUTO_CAP
+ and max_ctx > GLM_LONG_CTX
+ and _glm_small_kda_front(plan.devices.front_arch)):
+ print(f"serve: warning: front layers > {GLM_LONG_CTX_AUTO_CAP} at -c > {GLM_LONG_CTX} "
+ "is measured to OOM a 16 GB gfx12 front on long prefill (split KDA fallback "
+ f"workspace); use --front-layers {GLM_LONG_CTX_AUTO_CAP} for long-context split runs",
+ flush=True)
self.split.engage_budget()
self.split.load("text", self.model, progressbar=False,
callback=startup_health.load_callback(), max_chunk_size=4096)
diff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.py
index 798c476..617541c 100644
--- a/tools/strix_halo/split_eval.py
+++ b/tools/strix_halo/split_eval.py
@@ -6,6 +6,11 @@ baseline (--baseline), saves the greedy token ids to JSON, and optionally compar
saved runs token-for-token. It also measures decode t/s under --num-draft and can run a
long-context needle probe.
+The split works on any two supported devices; use --main-device/--front-device to put
+either device in either position. The context-dependent --front-layers default is
+harness tuning for a small front card, not a property of the split; pass --front-layers
+to choose N explicitly.
+
Usage (from the repo root, after `source tools/strix_halo/env.sh`):
python tools/strix_halo/split_eval.py -m <pack> --out /tmp/split.json
@@ -61,7 +66,15 @@ def parse_args() -> argparse.Namespace:
p.add_argument("-m", "--model", default="/data/models/NicSir--GLM-5.3-Flash-EXL3-2.72bpw")
p.add_argument("--baseline", action="store_true", help="single device (cuda:0), no layer split")
p.add_argument("--front-layers", type=int, default=None)
+ p.add_argument("--main-device", default="auto")
p.add_argument("--front-device", default="auto")
+ p.add_argument("--long-ctx-threshold", type=int, default=65536,
+ help="context above which the harness default front-layer count changes")
+ p.add_argument("--long-ctx-front-layers", type=int, default=5,
+ help="harness default for contexts above --long-ctx-threshold; measured on a "
+ "small front card, not a property of the split")
+ p.add_argument("--short-ctx-front-layers", type=int, default=6,
+ help="harness default at or below --long-ctx-threshold")
p.add_argument("--endcaps", choices=("on", "off"), default="on")
p.add_argument("--front-reserve-gb", type=float, default=1.2)
p.add_argument("--main-reserve-gb", type=float, default=0.0)
@@ -79,9 +92,12 @@ def parse_args() -> argparse.Namespace:
help="compare two saved runs: prompt ids and decode numbers")
p.add_argument("--no-perf", action="store_true", help="skip the 3 decode timing prompts")
args = p.parse_args()
+ args.front_layers_defaulted = args.front_layers is None
if args.front_layers is None:
- # N=6 is measured to OOM the 16 GiB front above 65K (gfx1201 KDA workspace).
- args.front_layers = 5 if args.max_ctx > 65536 else 6
+ # Harness tuning for memory, not a split property: a small front card cannot
+ # hold N=6 plus the long-context workspace. Both values are explicit flags.
+ args.front_layers = (args.long_ctx_front_layers if args.max_ctx > args.long_ctx_threshold
+ else args.short_ctx_front_layers)
return args
@@ -166,6 +182,10 @@ def build_needle(depth: int, tokenizer):
def main() -> None:
args = parse_args()
+ if args.front_layers_defaulted and not args.baseline:
+ print(f"[harness] no --front-layers given: using N={args.front_layers} at -c "
+ f"{args.max_ctx} (harness tuning, not a split property; override with "
+ f"--front-layers N or --long-ctx-front-layers N)", flush=True)
if args.compare:
compare(args.compare[0], args.compare[1])
return
@@ -194,7 +214,7 @@ def main() -> None:
text_map = None
if not args.baseline:
from exllamav3.device_map import SplitPlan, resolve_devices
- devices = resolve_devices(args.front_device)
+ devices = resolve_devices(args.front_device, args.main_device)
plan = SplitPlan(
devices, endcaps = args.endcaps == "on", front_layers = args.front_layers,
front_reserve_gb = 0.0 if args.no_budget else args.front_reserve_gb,
diff --git a/tools/strix_halo/split_load.py b/tools/strix_halo/split_load.py
index f6d4b37..d33e930 100644
--- a/tools/strix_halo/split_load.py
+++ b/tools/strix_halo/split_load.py
@@ -1,7 +1,9 @@
#!/usr/bin/env python3
-"""Phase 3 loader gate: load the GLM pack across iGPU + eGPU and print the table.
+"""Phase 3 loader gate: load the GLM pack across two devices and print the table.
-No forward pass is run. Usage (from the repo root, after `source tools/strix_halo/env.sh`):
+No forward pass is run. Either device may be the front or the main one; select
+them with --main-device/--front-device (cuda:N, gfxXXXX, UUID or name).
+Usage (from the repo root, after `source tools/strix_halo/env.sh`):
python tools/strix_halo/split_load.py \
-m /data/models/NicSir--GLM-5.3-Flash-EXL3-2.72bpw \
@@ -29,6 +31,7 @@ def main() -> None:
p = argparse.ArgumentParser()
p.add_argument("-m", "--model", required=True)
p.add_argument("--front-layers", type=int, default=4)
+ p.add_argument("--main-device", default="auto")
p.add_argument("--front-device", default="auto")
p.add_argument("--endcaps", choices=("on", "off"), default="on")
p.add_argument("--front-reserve-gb", type=float, default=1.2)
@@ -79,7 +82,7 @@ def main() -> None:
f"MemAvailable {host_before:.1f} -> {mem_available_gib():.1f} GiB", flush=True)
return
- devices = resolve_devices(args.front_device)
+ devices = resolve_devices(args.front_device, args.main_device)
plan = SplitPlan(devices, endcaps=endcaps, front_layers=args.front_layers,
front_reserve_gb=args.front_reserve_gb)
plan.add("text", model, config=config, cache=cache, load_order=0)