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.

split: universal layer-split core and GLM adapter

Resynthcc781dc459dd
diff --git a/.gitignore b/.gitignore
index 8fab9e9..1d6b3e9 100644
--- a/.gitignore
+++ b/.gitignore
@@ -34,3 +34,6 @@ scratch/pfskip1/pfb1_results.json
tools/ds41/_ref/
tools/ds41/_scratch/
.check_logs/
+
+scratch
+docs-notes
diff --git a/doc/split-support-matrix.md b/doc/split-support-matrix.md
index 377af4c..6c7b550 100644
--- a/doc/split-support-matrix.md
+++ b/doc/split-support-matrix.md
@@ -1,9 +1,10 @@
# Layer-split support matrix
What the contiguous layer split (`exllamav3/device_map.py`, `exllamav3/bridge.py`,
-`Model.load(device_map=...)`) can place today, per model family and per serve flavor.
-Status as of the Stage 0 rebase (2026-11-10): GLM is measured on the Strix Halo / 9070 box;
-Qwen and DSV4 entries are code inventories, not load-tested.
+`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.
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
@@ -13,19 +14,22 @@ roadmap stage that must finish before that row is claimable.
| Component | Config | Placement | Notes |
| --- | --- | --- | --- |
-| text (`Model.from_config`) | shared | layers 0..N-1 front, N..44 main; endcaps per flag | measured N=4, N=6 at `-c 65536`; N=5 is the long-context setting until the gfx12 KDA kernel lands |
-| mtp (`component="mtp"`) | shared | all front when `--endcaps on`, else main | separate `LayerDeviceMap` (no own trunk), reserve owned by the text map |
-| vision (`component="vision"`) | shared | front when `--endcaps on`, else main | loaded with a plain `device=` argument; no bridge interaction |
+| text (`Model.from_config`) | shared | layers 0..N-1 front, N..44 main; endcaps per allowlist | measured N=4, N=6 at `-c 65536`; N=5 is the long-context setting until the gfx12 KDA kernel lands |
+| mtp (`component="mtp"`) | shared | all front when `--endcaps on`, else main | `ComponentPolicy(whole_component)` (no own trunk), reserve owned by the text map |
+| vision (`component="vision"`) | shared | all front when `--endcaps on`, else main | declared as a whole component; the same bridge/config covers it |
| `embed_tokens` | shared | cpu (`prefer_cpu` cap) | stays host-side by design |
-| KV cache (TQ 6-bit) | built per model/cache | each cache layer follows its block | measured 0.62 GiB main / 0.12 GiB front at 65K |
-| bridge | shared config | installed by `_load_mapped` for all three components | one `Bridge` per config; split_active defuses graphs |
+| text endcaps | shared | `hc_expand`/`hc_head`/norm/lm_head front per allowlist; unknown non-layer modules main | allowlist is class/key based (`TEXT_ENDCAP_TYPES`/`TEXT_ENDCAP_SUFFIXES`), no per-model placement in core |
+| KV/recurrent cache | built per model/cache | each cache/recurrent layer follows its block | measured 0.62 GiB main / 0.12 GiB front at 65K; placement audit after load |
+| 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`.
+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.
Known blockers: gfx12 fused KDA kernel (separate PR), MTP cross-device acceptance/determinism,
-endcaps currently moves every non-layer module to the front (GLM has no ngram/PLE/engram, so it
-never showed; the universal core replaces this with an allowlist — Stage 1).
+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.
## Code inventory — Qwen3.8-Flash-Next (`tools/qwen/serve.py`)
diff --git a/doc/split.md b/doc/split.md
index b8ac266..c3c4681 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -1,7 +1,9 @@
# Contiguous layer split (iGPU + eGPU)
-*Status: Stage 0 of the universal roadmap (see `.kilo/plans/1794309410242-universal-layer-split-roadmap.md`).
-This file is the durable user/ops reference; the roadmap owns the staging, and
+*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.*
## What it is
@@ -22,27 +24,52 @@ destination tensor is a fresh allocation, so callers may keep using it after the
| --- | --- | --- |
| `--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) |
-| `--endcaps on\|off` | `KYOJIN_ENDCAPS` | non-layer modules (norm/head/MTP/vision) follow the front; `auto` later |
-| `--front-reserve-gb` | `KYOJIN_FRONT_RESERVE_GB` | VRAM left free on the front for workspace (default 1.2) |
-| `--split-preset` | `KYOJIN_SPLIT_PRESET` | per-model unsafe-env preset (Stage 3+) |
-| `--split-graphs` | — | per-segment capture (Stage 6); until then split forces graphs off |
+| `--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) |
+| `--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 |
`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.
+## Core objects (Stage 1)
+
+- `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.
+- `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,
+ device resolution, plan/load/report orchestration, split-safe env. GLM is the first
+ adapter; the helper is pure stdlib at import so a server can apply `SPEED_ENV` first.
+- `model_init.py` uses the same plan for the `KYOJIN_FRONT_LAYERS` env-only path.
+
## Load-time effects worth knowing
-- The front reserve caps the front card while its segment loads and is **released at the
- first main module**: on ROCm a process-wide allocator cap perturbs main-device numerics
- (map-zero control diverged from baseline 3/6 until the release was added). Never cap main.
+- The front reserve is an **inert device slab**, not `set_per_process_memory_fraction`.
+ 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.
- `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
(`split_active`). Per-segment capture is Stage 6.
-- JIT HIP loaders compile per (device, defines); `kda_fused_h` is a gfx11.5 WMMA kernel and
- refuses other archs (`vendor/fla/hip/kda_fused_h_hip.py:supported`). gfx12 runs the
- deterministic fla chain (`EXL3_KDA_FUSE=0` forced there) — see PR C for the fused port.
+- Per-component load table and a cache/recurrent placement audit print after load: every
+ 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. 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.
## Determinism / verification policy
@@ -58,10 +85,11 @@ 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 0)
+## Known limitations (Stage 1)
-- Endcaps is still "all non-layer modules to the front" — replaced by an allowlist in Stage 1.
-- Auto-N uses the old tier assumptions; actual-byte sizing is Stage 5. For GLM: N=6 at ≤65K,
- N=5 for long context until the gfx12 KDA kernel lands.
+- 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.
- 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.
diff --git a/exllamav3/device_map.py b/exllamav3/device_map.py
index 9aeb27b..bc74bd4 100644
--- a/exllamav3/device_map.py
+++ b/exllamav3/device_map.py
@@ -1,17 +1,29 @@
from __future__ import annotations
"""
-Contiguous layer split: resolve the two devices and map model modules to them.
+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
``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 the endcaps (embedding, hyper-connection drivers,
-final norm, lm_head, and the separate MTP/vision components).
-
-Endcaps ON puts the non-CPU endcaps on the front device; ENDCAPS OFF lets them
-follow their natural neighbour (prologue with layer 0, epilogue with the last
-layer). ``prefer_cpu`` modules, such as the GLM token embedding, always stay on
+without a ``layer_idx`` are endcaps (embedding, hyper-connection drivers, final
+norm, lm_head, and the separate MTP/vision components).
+
+The universal core separates *policy* from *placement*:
+
+- ``ComponentPolicy`` says whether a component may use the front device and which
+ non-layer modules are safe to move there. The text prologue/epilogue allowlist
+ is norm/hc/lm_head-like modules only; anything the policy does not recognise is
+ an unknown non-layer module and stays on the main device.
+- ``ComponentMap`` resolves the contiguous boundary for one component.
+- ``SplitPlan`` owns every component of a process (target, MTP, vision, extra),
+ the front reserve, auto-N and the load/placement audit. Adapters declare their
+ components; the core contains no model-specific placement logic.
+
+Endcaps ON puts the allowlisted text endcaps on the front device. ENDCAPS OFF
+lets the allowlisted prologue follow layer 0 and the epilogue follow the last
+layer. ``prefer_cpu`` modules, such as the GLM token embedding, always stay on
the CPU: their upload path is part of the embedding design, not a tile to move.
"""
@@ -24,6 +36,19 @@ from .util.arch_list import device_arch
GIB = 1024 ** 3
+# 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.
+TEXT_ENDCAP_TYPES = frozenset((
+ "RMSNorm", "GatedRMSNorm", "LayerNorm", "HyperHead", "ExpandStreams",
+))
+TEXT_ENDCAP_SUFFIXES = (
+ "norm", "ln_f", "final_norm", "output_norm", "lm_head", "hc_head", "hc_expand",
+)
+
+# Components that are endcaps in their entirety (no trunk boundary of their own).
+WHOLE_COMPONENT_KINDS = frozenset(("mtp", "vision", "draft"))
+
def _arch_of(index: int) -> str:
# The shared helper owns the ROCm arch name and its card-name fallback.
@@ -89,21 +114,183 @@ def resolve_devices(front: str | None = None) -> Devices:
)
+# ---------------------------------------------------------------------------------------------------------
+# Component policy
+# ---------------------------------------------------------------------------------------------------------
+
+@dataclass(frozen = True)
+class ComponentPolicy:
+ """Placement policy for one component of a model process.
+
+ ``kind`` is one of ``text``, ``mtp``, ``vision``, ``draft``, ``aux`` or
+ ``unknown``. Whole-component kinds (MTP/vision/draft) put every module on
+ the front when endcaps are on, because they have no trunk boundary of their
+ own. Auxiliary components never visit the front implicitly.
+ """
+
+ name: str
+ kind: str = "aux"
+ front_eligible: bool = False
+ endcaps_front: bool = True
+ whole_component: bool = False
+ endcap_types: frozenset[str] = frozenset()
+ endcap_key_suffixes: tuple[str, ...] = ()
+ arch_gate: frozenset[str] | None = None
+ unsafe_env: tuple[tuple[str, str], ...] = ()
+
+ def allows_front(self, arch: str | None) -> bool:
+ if not self.front_eligible or arch is None:
+ return False
+ return self.arch_gate is None or arch in self.arch_gate
+
+
+def component_policy(name: str, **overrides) -> ComponentPolicy:
+ """Default policy for a component name; adapters may override any field."""
+ key = (name or "unknown").strip().lower()
+ if key == "text":
+ return ComponentPolicy(
+ name = name, kind = "text", front_eligible = True, endcaps_front = True,
+ endcap_types = TEXT_ENDCAP_TYPES, endcap_key_suffixes = TEXT_ENDCAP_SUFFIXES,
+ **overrides)
+ if key in WHOLE_COMPONENT_KINDS:
+ return ComponentPolicy(
+ name = name, kind = key, front_eligible = True, endcaps_front = True,
+ whole_component = True, **overrides)
+ return ComponentPolicy(name = name, kind = "aux", front_eligible = False,
+ endcaps_front = False, **overrides)
+
+
+def _type_name(module) -> str:
+ return type(module).__name__
+
+
+def _key_matches(key: str, suffixes) -> bool:
+ for s in suffixes:
+ if key == s or key.endswith("." + s):
+ return True
+ return False
+
+
+def is_front_endcap(module, policy: ComponentPolicy) -> bool:
+ """True for a non-layer module the text policy allows on the front device."""
+ if getattr(module, "caps", {}).get("prefer_cpu"):
+ return False
+ if getattr(module, "caps", {}).get("logits_output"):
+ return True
+ if _type_name(module) in policy.endcap_types:
+ return True
+ return _key_matches(getattr(module, "key", ""), policy.endcap_key_suffixes)
+
+
+def _module_bytes(module, stc = None) -> int:
+ """Actual stored bytes of a top-level module, before it is loaded.
+
+ The safetensors collection knows the file span of every tensor, which is the
+ number auto-N must use. A synthetic model without an stc falls back to its
+ element count at fp16.
+ """
+ if stc is not None and hasattr(stc, "get_tensor_sizes"):
+ try:
+ return int(sum(stc.get_tensor_sizes(module.key)))
+ except Exception: # noqa: BLE001 - fall back to a numel estimate
+ pass
+ try:
+ return int(module.weights_numel()) * 2
+ except Exception: # noqa: BLE001
+ return 0
+
+
+def _layer_bytes(model, stc = None) -> dict[int, int]:
+ out: dict[int, int] = {}
+ for module in model.modules:
+ idx = getattr(module, "layer_idx", None)
+ if idx is not None:
+ out[idx] = out.get(idx, 0) + _module_bytes(module, stc)
+ return out
+
+
+def _cache_bytes_for(cache, n_layers: int, upto: int | None = None) -> int:
+ """Cache/recurrent bytes whose layer index is below ``upto`` (all when None)."""
+ if cache is None:
+ return 0
+ total = 0
+ for key, cl in list(getattr(cache, "layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ if upto is not None and idx >= upto:
+ continue
+ try:
+ total += int(cl.storage_size())
+ except Exception: # noqa: BLE001
+ pass
+ for key, rl in list(getattr(cache, "recurrent_layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ if upto is not None and idx >= upto:
+ continue
+ try:
+ total += int(rl.storage_size())
+ except Exception: # noqa: BLE001
+ pass
+ return total
+
+
+def _cache_bytes_by_layer(cache) -> dict[int, int]:
+ out: dict[int, int] = {}
+ if cache is None:
+ return out
+ for key, cl in list(getattr(cache, "layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ try:
+ out[idx] = out.get(idx, 0) + int(cl.storage_size())
+ except Exception: # noqa: BLE001
+ pass
+ for key, rl in list(getattr(cache, "recurrent_layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ try:
+ out[idx] = out.get(idx, 0) + int(rl.storage_size())
+ except Exception: # noqa: BLE001
+ pass
+ return out
+
+
+# ---------------------------------------------------------------------------------------------------------
+# Component map
+# ---------------------------------------------------------------------------------------------------------
+
@dataclass
-class LayerDeviceMap:
+class ComponentMap:
+ """Contiguous layer placement for one component.
+
+ ``reserve_bytes`` is a per-device *slab* held for the duration of the load,
+ not a process-wide allocator cap: a cap changes the ROCm allocator's layout
+ and perturbs the main device's kernel choices (measured at 128K), while a
+ slab only removes bytes from the pool and releases them without changing the
+ allocator's policy.
+ """
+
main: torch.device
front: torch.device | None
front_layers: int
endcaps: bool
component: str = "text"
layer_count: int = 0
+ policy: ComponentPolicy | None = None
main_arch: str = ""
front_arch: str | None = None
reserve_bytes: dict[int, int] = field(default_factory = dict)
endcap_keys: tuple[str, ...] = ()
+ front_endcap_keys: tuple[str, ...] = ()
+ unknown_keys: tuple[str, ...] = ()
+ size_bytes: int = 0
+ load_order: int = 0
+ config: object | None = field(default = None, repr = False)
+ cache: object | None = field(default = None, repr = False)
_positions: dict[int, int] = field(default_factory = dict, repr = False)
_first_layer_pos: int = 0
_last_layer_pos: int = -1
+ _layer_bytes: dict[int, int] = field(default_factory = dict, repr = False)
+ _cache_by_layer: dict[int, int] = field(default_factory = dict, repr = False)
+ _module_refs: tuple = field(default_factory = tuple, repr = False)
+ _reserve_slabs: dict[int, torch.Tensor] = field(default_factory = dict, repr = False)
@classmethod
def from_model(
@@ -115,48 +302,102 @@ class LayerDeviceMap:
component: str = "text",
front_reserve_gb: float = 1.2,
main_reserve_gb: float = 0.0,
- ) -> "LayerDeviceMap":
+ config = None,
+ cache = None,
+ policy: ComponentPolicy | None = None,
+ load_order: int = 0,
+ ) -> "ComponentMap":
+ policy = policy or component_policy(component)
+ return cls.from_policy(model, front_layers, endcaps, devices, policy,
+ front_reserve_gb = front_reserve_gb,
+ main_reserve_gb = main_reserve_gb,
+ config = config, cache = cache, load_order = load_order)
+
+ @classmethod
+ def from_policy(
+ cls,
+ model,
+ front_layers: int | str,
+ endcaps: bool,
+ devices: Devices,
+ policy: ComponentPolicy,
+ front_reserve_gb: float = 1.2,
+ main_reserve_gb: float = 0.0,
+ config = None,
+ cache = None,
+ load_order: int = 0,
+ ) -> "ComponentMap":
modules = list(model.modules)
layers = [m for m in modules if getattr(m, "layer_idx", None) is not None]
n_layers = len(layers)
- if component in ("mtp", "vision"):
+ auto = front_layers in ("auto", -1) or (isinstance(front_layers, str) and front_layers.strip().lower() == "auto")
+ front_layers = 0 if auto else int(front_layers)
+ if policy.whole_component:
# These components are endcaps in their entirety: they have no trunk
# boundary of their own, so ENDCAPS OFF leaves them on the main device.
front_layers = n_layers if endcaps else 0
front_layers = max(0, min(int(front_layers), n_layers))
- if devices.front is None:
+ if devices.front is None or not policy.allows_front(devices.front_arch):
front_layers = 0
positions = {id(m): i for i, m in enumerate(modules)}
first = positions[id(layers[0])] if layers else 0
last = positions[id(layers[-1])] if layers else -1
+ stc = getattr(config, "stc", None) if config is not None else None
- # The front reserve caps the small card while its weights load. It is released before
- # the first main module (see Model._load_mapped): on ROCm the memory-fraction cap
- # changes the allocator's behavior process-wide and perturbs the main device's kernel
- # choices, which would make split outputs differ from a single-device baseline even
- # with zero front layers. The main device has ample headroom and is never capped.
+ # The front reserve caps the small card while its weights load. It is released
+ # before the first main module (see Model._load_mapped): the main device has ample
+ # headroom and is never capped. A component other than the budget owner clears
+ # reserve_bytes after construction (SplitPlan does this).
reserve: dict[int, int] = {}
if devices.front is not None and front_layers > 0 and front_reserve_gb > 0:
reserve[devices.front.index] = max(0, int(front_reserve_gb * GIB))
if devices.main is not None and main_reserve_gb > 0:
reserve[devices.main.index] = max(0, int(main_reserve_gb * GIB))
+ layer_bytes = _layer_bytes(model, stc)
+ cache_by_layer = _cache_bytes_by_layer(cache)
+ front_endcaps = tuple(
+ m.key for m in modules
+ if getattr(m, "layer_idx", None) is None and is_front_endcap(m, policy)
+ )
+ all_endcaps = tuple(m.key for m in modules if getattr(m, "layer_idx", None) is None)
+ unknown = tuple(
+ m.key for m in modules
+ if getattr(m, "layer_idx", None) is None
+ and not getattr(m, "caps", {}).get("prefer_cpu")
+ and not is_front_endcap(m, policy)
+ )
+ size = (sum(layer_bytes.values()) +
+ sum(_module_bytes(m, stc) for m in modules if getattr(m, "layer_idx", None) is None))
+
return cls(
main = devices.main,
front = devices.front,
front_layers = front_layers,
endcaps = bool(endcaps) and front_layers > 0,
- component = component,
+ component = policy.name,
layer_count = n_layers,
+ policy = policy,
main_arch = devices.main_arch,
front_arch = devices.front_arch,
reserve_bytes = reserve,
- endcap_keys = tuple(m.key for m in modules if getattr(m, "layer_idx", None) is None),
+ endcap_keys = all_endcaps,
+ front_endcap_keys = front_endcaps,
+ unknown_keys = unknown,
+ size_bytes = int(size),
+ load_order = load_order,
+ config = config,
+ cache = cache,
_positions = positions,
_first_layer_pos = first,
_last_layer_pos = last,
+ _layer_bytes = layer_bytes,
+ _cache_by_layer = cache_by_layer,
+ _module_refs = tuple(modules),
)
+ # -- placement ---------------------------------------------------------
+
@property
def enabled(self) -> bool:
return self.front is not None and self.front_layers > 0
@@ -174,74 +415,437 @@ class LayerDeviceMap:
out.append(self.front)
return out
+ @property
+ def policy_or_default(self) -> ComponentPolicy:
+ return self.policy or component_policy(self.component)
+
+ def _endcap_allowed(self, module) -> bool:
+ return is_front_endcap(module, self.policy_or_default)
+
def device_for(self, module) -> torch.device:
if getattr(module, "caps", {}).get("prefer_cpu"):
return torch.device("cpu")
idx = getattr(module, "layer_idx", None)
if idx is not None:
+ if not self.enabled:
+ return self.main
+ if self.policy_or_default.whole_component:
+ return self.front
return self.front if idx < self.front_layers else self.main
if not self.enabled:
return self.main
+ if self.policy_or_default.whole_component:
+ # MTP/vision/draft have no trunk boundary: all their modules share the
+ # component's endcaps verdict.
+ return self.front if self.endcaps else self.main
+ if not self._endcap_allowed(module):
+ # Unknown / auxiliary non-layer module: always safe, never moved implicitly.
+ return self.main
if self.endcaps:
return self.front
- # ENDCAPS OFF: prologue follows layer 0, epilogue follows the last layer.
+ # ENDCAPS OFF: allowlisted prologue follows layer 0, epilogue follows the last layer.
pos = self._positions.get(id(module), 0)
if pos < self._first_layer_pos:
- return self.front
- return self.front if self.front_layers >= self.layer_count else self.main
+ return self.front if self.front_layers > 0 else self.main
+ if pos > self._last_layer_pos:
+ return self.front if self.front_layers >= self.layer_count else self.main
+ return self.main
+
+ # -- load-time budget --------------------------------------------------
def engage_budget(self) -> None:
- """Apply the per-device reserve once, before the first component loads."""
+ """Hold the front reserve as a slab (never a process-wide allocator cap)."""
if getattr(self, "_budget_engaged", False):
return
- from .util.memory import set_memory_fraction_reserve
for i, reserve in self.reserve_bytes.items():
- if reserve > 0:
- set_memory_fraction_reserve(reserve, i)
+ if reserve <= 0:
+ continue
+ try:
+ # An inert slab: it removes bytes from the pool without changing the
+ # allocator's configuration or the numerics of any later kernel.
+ self._reserve_slabs[i] = torch.empty(reserve, dtype = torch.uint8,
+ device = torch.device("cuda", i))
+ except Exception as exc: # noqa: BLE001
+ print(f"[split] warning: could not hold the {reserve / GIB:.2f} GiB reserve "
+ f"on cuda:{i} ({type(exc).__name__}: {exc}); continuing without it",
+ flush = True)
self._budget_engaged = True
def release_front_budget(self) -> None:
- """Release the front load cap before the first main module loads.
+ """Release the front slab before the first main module loads.
- A process-wide allocator cap on ROCm changes the main device's kernel/allocator
- behavior; the split must not carry that into the main segment (it would perturb
- outputs relative to a single-device run).
+ The slab is dropped; the caching allocator keeps the freed block for the
+ forward workspace, so the headroom is preserved without a cap.
"""
if not getattr(self, "_budget_engaged", False):
return
- if self.front is None or self.front.index not in self.reserve_bytes:
+ if self.front is None:
return
- from .util.memory import unset_memory_fraction
- unset_memory_fraction([self.front.index])
- self._budget_engaged = any(
- i != self.front.index and r > 0 for i, r in self.reserve_bytes.items())
+ self._reserve_slabs.pop(self.front.index, None)
+ self._budget_engaged = any(i != self.front.index and r > 0 for i, r in self.reserve_bytes.items())
def release_budget(self) -> None:
- if not getattr(self, "_budget_engaged", False):
- return
- from .util.memory import unset_memory_fraction
- unset_memory_fraction(list(self.reserve_bytes.keys()))
+ self._reserve_slabs.clear()
self._budget_engaged = False
+ # -- sizing / reporting ------------------------------------------------
+
+ def layer_weight_bytes(self, idx: int) -> int:
+ return int(self._layer_bytes.get(idx, 0))
+
+ def layer_cache_bytes(self, idx: int) -> int:
+ return int(self._cache_by_layer.get(idx, 0))
+
+ def front_cost(self, n: int, endcaps: bool | None = None) -> int:
+ """Estimated front bytes for n text layers plus the policy's front endcaps."""
+ n = max(0, min(n, self.layer_count))
+ endcaps = self.endcaps if endcaps is None else bool(endcaps)
+ cost = sum(self.layer_weight_bytes(i) for i in range(n))
+ cost += sum(self.layer_cache_bytes(i) for i in range(n))
+ if not endcaps:
+ return cost
+ stc = getattr(self.config, "stc", None)
+ if self.policy_or_default.whole_component:
+ return cost + sum(_module_bytes(m, stc)
+ for m in self._module_refs if getattr(m, "layer_idx", None) is None
+ and not getattr(m, "caps", {}).get("prefer_cpu"))
+ allowed = set(self.front_endcap_keys)
+ return cost + sum(_module_bytes(m, stc) for m in self._module_refs if m.key in allowed)
+
def describe(self) -> str:
parts = [f"{self.component}: layers 0..{self.front_layers - 1} front, "
f"{self.front_layers}..{self.layer_count - 1} main"]
if self.endcaps:
- parts.append(f"endcaps front ({len(self.endcap_keys)} modules)")
+ parts.append(f"endcaps front ({len(self.front_endcap_keys)} modules)")
else:
parts.append("endcaps follow neighbours")
return "; ".join(parts)
+# Backwards-compatible name for the Stage 0 callers and the strix_halo harnesses.
+LayerDeviceMap = ComponentMap
+
+
+# ---------------------------------------------------------------------------------------------------------
+# Split plan
+# ---------------------------------------------------------------------------------------------------------
+
+@dataclass
+class ComponentLoad:
+ component: str
+ seconds: float
+ front_layers: int
+ layer_count: int
+ device_map: ComponentMap | None
+ weight_bytes: int = 0
+ cache_bytes: int = 0
+ warnings: tuple[str, ...] = ()
+
+
+class SplitPlan:
+ """Every component the process places, the reserve and the placement audit."""
+
+ def __init__(
+ self,
+ devices: Devices,
+ endcaps: bool = True,
+ front_layers: int | str = 0,
+ front_reserve_gb: float = 1.2,
+ main_reserve_gb: float = 0.0,
+ preset: str = "auto",
+ logger = print,
+ ):
+ self.devices = devices
+ self.endcaps = bool(endcaps)
+ self.requested_front_layers = front_layers
+ self.auto = isinstance(front_layers, str) and front_layers.strip().lower() == "auto" or front_layers == -1
+ self.front_layers = 0 if self.auto else max(0, int(front_layers or 0))
+ self.front_reserve_gb = float(front_reserve_gb)
+ self.main_reserve_gb = float(main_reserve_gb)
+ self.preset = (preset or "auto").strip().lower()
+ self.logger = logger
+ self.maps: dict[str, ComponentMap] = {}
+ self._decls: dict[str, tuple] = {}
+ self.configs: list[object] = []
+ self.records: list[ComponentLoad] = []
+ self.audit: dict[str, object] = {}
+ self._owner: str | None = None
+ self._budget_engaged_once = False
+ self._built = False
+
+ # -- declarations ------------------------------------------------------
+
+ def add(
+ self,
+ component: str,
+ model,
+ config = None,
+ cache = None,
+ policy: ComponentPolicy | None = None,
+ front_layers: int | str | None = None,
+ load_order: int | None = None,
+ ) -> ComponentMap:
+ was_built = self._built
+ policy = policy or component_policy(component)
+ layer = self.requested_front_layers if front_layers is None else front_layers
+ self._decls[component] = (model, config, cache, policy, layer, load_order)
+ if config is not None:
+ self.register_config(config)
+ cmap = ComponentMap.from_policy(
+ model, layer, self.endcaps, self.devices, policy,
+ front_reserve_gb = self.front_reserve_gb,
+ main_reserve_gb = self.main_reserve_gb,
+ config = config, cache = cache,
+ load_order = load_order if load_order is not None else len(self._decls),
+ )
+ self.maps[component] = cmap
+ if self._owner is None or (policy.kind == "text" and self._owner != "text"):
+ self._owner = component
+ if component != self._owner:
+ # Only the target/text map owns the load reserve.
+ cmap.reserve_bytes.clear()
+ # A late component (vision/MTP after the target load) must not reset the
+ # already-chosen auto-N plan.
+ self._built = was_built
+ return cmap
+
+ def register_config(self, config) -> None:
+ if config is not None and all(c is not config for c in self.configs):
+ self.configs.append(config)
+
+ # -- sizing ------------------------------------------------------------
+
+ def build(self) -> "SplitPlan":
+ if not self._decls:
+ self._built = True
+ return self
+ text = next((k for k, d in self._decls.items() if d[3].kind == "text"), None)
+ if self.auto:
+ n = self._auto_n(text)
+ 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)")
+ for name, (model, config, cache, policy, layer, load_order) in self._decls.items():
+ if self.auto and policy.kind == "text":
+ layer = self.front_layers
+ self.maps[name] = ComponentMap.from_policy(
+ model, layer, self.endcaps, self.devices, policy,
+ front_reserve_gb = self.front_reserve_gb,
+ main_reserve_gb = self.main_reserve_gb,
+ config = config, cache = cache,
+ load_order = load_order if load_order is not None else 0,
+ )
+ self._assign_owner()
+ self.apply_policies()
+ self._built = True
+ return self
+
+ def apply_policies(self) -> None:
+ """Apply (and log) every adapter-declared unsafe env lever."""
+ for name, cmap in self.maps.items():
+ for key, value in cmap.policy_or_default.unsafe_env:
+ old = os.environ.get(key)
+ if old != value:
+ self.logger(f"[split] {name}: unsafe env {key}={value}"
+ + (f" (was {old})" if old is not None else ""))
+ os.environ[key] = value
+
+ def _assign_owner(self) -> None:
+ owner = "text" if "text" in self.maps else (self._owner or next(iter(self.maps), None))
+ self._owner = owner
+ for name, cmap in self.maps.items():
+ if name != owner:
+ # Only the target/text map owns the load reserve.
+ cmap.reserve_bytes.clear()
+
+ def _auto_budget(self) -> int:
+ if self.devices.front is None:
+ return 0
+ total = int(torch.cuda.get_device_properties(self.devices.front).total_memory)
+ safety = int(float(os.environ.get("KYOJIN_AUTON_SAFETY_GB", "0.25")) * GIB)
+ return max(0, total - int(self.front_reserve_gb * GIB) - safety)
+
+ def _auto_n(self, text: str | None) -> int:
+ if text is None or text not in self.maps:
+ return 0
+ cmap = self.maps[text]
+ if cmap.layer_count == 0:
+ return 0
+ budget = self._auto_budget()
+ # Components that are endcaps in their entirety and already declared.
+ other = sum(
+ m.size_bytes + _cache_bytes_for(m.cache, m.layer_count)
+ for name, m in self.maps.items()
+ if name != text and m.enabled and m.policy_or_default.whole_component and self.endcaps)
+ for n in range(cmap.layer_count, -1, -1):
+ if self.endcaps:
+ cost = other + cmap.front_cost(n, self.endcaps)
+ else:
+ # Prologue follows layer 0; epilogue only when every layer is front.
+ cost = other + cmap.front_cost(n, self.endcaps)
+ if n > 0:
+ cost += self._prologue_bytes(cmap)
+ if n >= cmap.layer_count:
+ cost += self._epilogue_bytes(cmap)
+ if cost <= budget:
+ return n
+ return 0
+
+ def _prologue_bytes(self, cmap: ComponentMap) -> int:
+ stc = getattr(cmap.config, "stc", None)
+ out = 0
+ for m in cmap._module_refs:
+ if getattr(m, "layer_idx", None) is not None or not is_front_endcap(m, cmap.policy_or_default):
+ continue
+ if cmap._positions.get(id(m), 0) < cmap._first_layer_pos:
+ out += _module_bytes(m, stc)
+ return out
+
+ def _epilogue_bytes(self, cmap: ComponentMap) -> int:
+ stc = getattr(cmap.config, "stc", None)
+ out = 0
+ for m in cmap._module_refs:
+ if getattr(m, "layer_idx", None) is not None or not is_front_endcap(m, cmap.policy_or_default):
+ continue
+ if cmap._positions.get(id(m), 0) > cmap._last_layer_pos:
+ out += _module_bytes(m, stc)
+ return out
+
+ # -- runtime -----------------------------------------------------------
+
+ def map(self, component: str) -> ComponentMap | None:
+ return self.maps.get(component)
+
+ @property
+ def enabled(self) -> bool:
+ return any(m.enabled for m in self.maps.values())
+
+ def engage_budget(self) -> None:
+ # One reserve for the whole load sequence (target + drafter + vision). After
+ # the owner releases the slab at its first main module, a later component must
+ # not allocate a second one.
+ if self._budget_engaged_once:
+ return
+ if self._owner is not None and self._owner in self.maps:
+ self.maps[self._owner].engage_budget()
+ self._budget_engaged_once = True
+
+ def install_bridges(self) -> None:
+ """Install one bridge per config (target, separate draft config, vision, extra)."""
+ if not self.enabled:
+ return
+ from .bridge import install_bridge
+ for config in self.configs:
+ install_bridge(config, self.devices.main, self.devices.front)
+
+ def record_load(self, component: str, seconds: float, warnings = ()) -> None:
+ cmap = self.maps.get(component)
+ if cmap is None:
+ return
+ cache_bytes = _cache_bytes_for(cmap.cache, cmap.layer_count)
+ self.records.append(ComponentLoad(
+ component = component, seconds = float(seconds),
+ front_layers = cmap.front_layers, layer_count = cmap.layer_count,
+ device_map = cmap, weight_bytes = int(cmap.size_bytes),
+ cache_bytes = cache_bytes, warnings = tuple(warnings)))
+
+ def audit_caches(self) -> dict[str, list[str]]:
+ """Check every cache/recurrent tensor against the component that owns its layer."""
+ issues: dict[str, list[str]] = {}
+ for name, cmap in self.maps.items():
+ cache = cmap.cache
+ if cache is None:
+ continue
+ bad: list[str] = []
+ for key, cl in list(getattr(cache, "layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ expected = self._expected_layer_device(cmap, idx)
+ actual = getattr(cl, "device", None) or getattr(getattr(cl, "attention", None), "device", None)
+ if actual is not None and expected is not None and torch.device(actual) != torch.device(expected):
+ bad.append(f"cache layer {idx}: {actual} != {expected}")
+ for key, rl in list(getattr(cache, "recurrent_layers", {}).items()):
+ idx = key[0] if isinstance(key, tuple) else key
+ expected = self._expected_layer_device(cmap, idx)
+ actual = getattr(getattr(rl, "attention", None), "device", None)
+ if actual is not None and expected is not None and torch.device(actual) != torch.device(expected):
+ bad.append(f"recurrent layer {idx}: {actual} != {expected}")
+ if bad:
+ issues[name] = bad
+ self.audit = issues
+ return issues
+
+ @staticmethod
+ def _expected_layer_device(cmap: ComponentMap, idx: int):
+ if not cmap.enabled:
+ return cmap.main
+ if cmap.policy_or_default.whole_component:
+ return cmap.front if cmap.endcaps else cmap.main
+ return cmap.front if idx < cmap.front_layers else cmap.main
+
+ def report(self, model, cache, extra: list[tuple[str, object, object]] | None = None,
+ ctx: int | None = None) -> None:
+ if not self.enabled:
+ return
+ self.install_bridges()
+ if self._owner in self.maps:
+ print_split_table(model, cache, self.maps[self._owner], extra = extra, ctx = ctx)
+ self.print_component_table()
+ for name, cmap in self.maps.items():
+ if cmap.unknown_keys and cmap.policy_or_default.kind == "text":
+ self.logger(f"[split] {name}: unknown non-layer modules kept on the main device: "
+ f"{', '.join(cmap.unknown_keys)}")
+ issues = self.audit_caches()
+ for name, bad in issues.items():
+ self.logger(f"[split] {name}: cache placement mismatch: " + "; ".join(bad[:8]))
+ if not issues:
+ self.logger("[split] cache/recurrent placement: all tensors follow their layer")
+ bridge = next((getattr(c, "device_bridge", None) for c in self.configs
+ if getattr(c, "device_bridge", None) is not None), None)
+ if bridge is not None:
+ self.logger(f"[split] {bridge.describe()}")
+ self.logger(bridge.summary())
+ else:
+ self.logger("[split] bridge disabled (KYOJIN_BRIDGE=0); crossings use to_device()")
+
+ def print_component_table(self) -> None:
+ if not self.records:
+ return
+ self.logger("[split] component load table:")
+ for r in sorted(self.records, key = lambda x: (x.device_map.load_order if x.device_map else 0, x.component)):
+ d = r.device_map
+ if d is None:
+ continue
+ front = f"0..{r.front_layers - 1}" if r.front_layers else "-"
+ main = f"{r.front_layers}..{r.layer_count - 1}" if r.layer_count else "-"
+ self.logger(f"[split] {r.component:7s} {r.seconds:7.1f}s front {front:>10s} "
+ f"main {main:>10s} weights {r.weight_bytes / GIB:7.2f} GiB "
+ f"cache {r.cache_bytes / GIB:6.2f} GiB devices "
+ f"{', '.join(str(x) for x in d.used_devices)}")
+ for w in r.warnings:
+ self.logger(f"[split] warning: {w}")
+
+ def release_budget(self) -> None:
+ for cmap in self.maps.values():
+ cmap.release_budget()
+
+
+# ---------------------------------------------------------------------------------------------------------
+# Tables
+# ---------------------------------------------------------------------------------------------------------
+
def _cache_bytes(cache) -> dict[torch.device, int]:
table: dict[torch.device, int] = {}
if cache is None:
return table
for cl in list(getattr(cache, "layers", {}).values()):
- dev = getattr(getattr(cl, "attention", None), "device", None)
+ dev = getattr(cl, "device", None) or getattr(getattr(cl, "attention", None), "device", None)
if dev is None:
continue
- table[dev] = table.get(dev, 0) + int(cl.storage_size())
+ try:
+ table[dev] = table.get(dev, 0) + int(cl.storage_size())
+ except Exception: # noqa: BLE001 - a state type without a byte count
+ pass
for rl in list(getattr(cache, "recurrent_layers", {}).values()):
dev = getattr(getattr(rl, "attention", None), "device", None)
if dev is None:
@@ -260,7 +864,7 @@ def _gib(n: int) -> str:
def print_split_table(
model,
cache,
- device_map: LayerDeviceMap,
+ device_map: ComponentMap,
extra: list[tuple[str, object, object]] | None = None,
ctx: int | None = None,
) -> None:
@@ -275,20 +879,27 @@ def print_split_table(
for dev, n in _cache_bytes(c).items():
cache_b[dev] = cache_b.get(dev, 0) + n
- print(f"[split] {device_map.describe()}" + (f"; -c {ctx}" if ctx else ""), flush=True)
- for dev in sorted(device_map.used_devices, key=lambda d: (d.type, d.index or 0)):
+ print(f"[split] {device_map.describe()}" + (f"; -c {ctx}" if ctx else ""), flush = True)
+ for dev in sorted(device_map.used_devices, key = lambda d: (d.type, d.index or 0)):
cache_bytes = cache_b.get(dev, 0)
- allocated = torch.cuda.memory_allocated(dev)
- peak = torch.cuda.max_memory_allocated(dev)
+ try:
+ allocated = torch.cuda.memory_allocated(dev)
+ peak = torch.cuda.max_memory_allocated(dev)
+ except Exception: # noqa: BLE001 - CPU-only test/table
+ allocated = peak = 0
weights = allocated - cache_bytes
print(f"[split] {str(dev):9s} weights {_gib(weights)} cache {_gib(cache_bytes)} "
- f"allocated {_gib(allocated)} peak {_gib(peak)}", flush=True)
+ f"allocated {_gib(allocated)} peak {_gib(peak)}", flush = True)
if device_map.front is not None:
- p = torch.cuda.get_device_properties(device_map.front)
+ try:
+ p = torch.cuda.get_device_properties(device_map.front)
+ total = p.total_memory
+ except Exception: # noqa: BLE001
+ total = 0
reserve = device_map.reserve_bytes.get(device_map.front.index, 0)
print(f"[split] front {str(device_map.front)} {device_map.front_arch}: "
- f"{p.total_memory / GIB:.2f} GiB total, reserve {reserve / GIB:.2f} GiB, "
- f"budget {(p.total_memory - reserve) / GIB:.2f} GiB", flush=True)
+ f"{total / GIB:.2f} GiB total, reserve {reserve / GIB:.2f} GiB, "
+ f"budget {(total - reserve) / GIB:.2f} GiB", flush = True)
cpu = [m.key for m in model.modules if getattr(m, "caps", {}).get("prefer_cpu")]
if cpu:
- print(f"[split] cpu-resident modules: {', '.join(cpu)}", flush=True)
+ print(f"[split] cpu-resident modules: {', '.join(cpu)}", flush = True)
diff --git a/exllamav3/model/model.py b/exllamav3/model/model.py
index 42fbc1b..af25a49 100644
--- a/exllamav3/model/model.py
+++ b/exllamav3/model/model.py
@@ -504,6 +504,8 @@ class Model(Model_TPMixin, Model_LSMixin):
assert device is None and not reserve_per_device and not use_per_device, \
"device_map cannot be combined with device/reserve_per_device/use_per_device."
assert not tensor_p, "device_map cannot be combined with tensor_p."
+ assert not os.environ.get("EXL3_LOAD_SPLIT"), \
+ "device_map cannot be combined with the legacy EXL3_LOAD_SPLIT budget"
self._load_mapped(progressbar, device_map, self.config, self.modules, verbose,
callback, max_chunk_size)
self.output_device = self.modules[-1].device
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.py
index 3175532..00286e1 100644
--- a/exllamav3/model/model_ls.py
+++ b/exllamav3/model/model_ls.py
@@ -79,10 +79,10 @@ class Model_LSMixin(ABC):
):
"""Load every top-level module straight to the device the map assigns it.
- No autosplit measuring forwards: the boundary is explicit. The front reserve caps
- the small card while its own segment loads, then is released at the first main
- module: on ROCm the memory-fraction cap perturbs the allocator process-wide, and
- the main segment must not inherit it. The caller releases whatever remains after
+ No autosplit measuring forwards: the boundary is explicit. The front reserve is a
+ held device slab while its segment loads, then is dropped at the first main module
+ (the freed block stays available to the workspace without changing the allocator's
+ policy or the main segment's numerics). The caller releases whatever remains after
the last component.
"""
device_map.engage_budget()
diff --git a/exllamav3/model_init.py b/exllamav3/model_init.py
index 70a4f30..f941b8f 100755
--- a/exllamav3/model_init.py
+++ b/exllamav3/model_init.py
@@ -337,24 +337,37 @@ def init(
# Explicit contiguous layer split. GLM serve has its own CLI; this env-only path
# keeps examples/chat.py and the eval tools able to exercise the split.
- front_layers = int(os.environ.get("KYOJIN_FRONT_LAYERS", "0") or 0)
+ from .serve_split import parse_front_layers
+ front_layers = parse_front_layers(os.environ.get("KYOJIN_FRONT_LAYERS", "0"))
+ split_plan = None
front_map = draft_map = None
if front_layers:
if args.tensor_parallel or single_device or split is not None:
raise ValueError("KYOJIN_FRONT_LAYERS cannot be combined with tensor parallel, "
"EXL3_LOAD_DEVICE or --gpu_split")
- from .device_map import LayerDeviceMap, print_split_table, resolve_devices
+ 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"))
endcaps = os.environ.get("KYOJIN_ENDCAPS", "1") != "0"
reserve = float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2"))
- front_map = LayerDeviceMap.from_model(model, front_layers, endcaps, devices,
- component="text", front_reserve_gb=reserve)
+ split_plan = SplitPlan(devices, endcaps = endcaps, front_layers = front_layers,
+ front_reserve_gb = reserve,
+ preset = os.environ.get("KYOJIN_SPLIT_PRESET", "auto"),
+ logger = lambda m: printp(not quiet, m))
+ split_plan.add("text", model, config = config, cache = cache, load_order = 0)
if draft_model is not None:
- draft_map = LayerDeviceMap.from_model(draft_model, 0, endcaps, devices,
- component="mtp", front_reserve_gb=reserve)
- draft_map.reserve_bytes.clear()
- front_map.engage_budget()
- printp(not quiet, f" -- layer split: {front_map.describe()}")
+ split_plan.add("mtp", draft_model, config = draft_config,
+ cache = draft_cache, load_order = 1)
+ split_plan.build()
+ split_plan.install_bridges()
+ split_plan.engage_budget()
+ front_map = split_plan.map("text")
+ draft_map = split_plan.map("mtp") if draft_model is not None else None
+ if front_map is not None:
+ printp(not quiet, f" -- layer split: {front_map.describe()}")
+ if split_plan.auto:
+ printp(not quiet, f" -- layer split: auto chose {front_map.front_layers} front layer(s)")
# Parallelism options
tp_options = {
@@ -407,11 +420,14 @@ def init(
**kwargs
)
- if front_map is not None:
- print_split_table(model, cache, front_map,
+ if split_plan is not None:
+ split_plan.record_load("text", 0.0)
+ if draft_model is not None:
+ split_plan.record_load("mtp", 0.0)
+ split_plan.report(model, cache,
extra=[("mtp", draft_model, draft_cache)] if draft_model is not None else [],
ctx=getattr(args, "cache_size", None))
- front_map.release_budget()
+ split_plan.release_budget()
# Load tokenizer
if load_tokenizer:
diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
index 1443b86..2506617 100644
--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py
+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
@@ -74,10 +74,12 @@ def qsa_prefill_hip(q, k, v, indices, sm_scale, block_table, page_size, out = No
npages = block_table.shape[-1]
ntok = k.shape[0]
assert v.shape[0] == ntok
- fn = _load(defs, q.device)
+ device = q.device
+ fn = _load(defs, device)
+ select_device(device)
cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, k, v, block_table, indices, out)] + \
[ctypes.c_int(x) for x in (q.stride(0), out.stride(0), bt_stride, k.stride(0), ntok, npages)] + [ctypes.c_float(sm_scale)]
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
- r = _state["lib"].hipModuleLaunchKernel(fn, R * 2, 1, 1, 32, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)
+ r = _state["lib"].hipModuleLaunchKernel(fn, R * 2, 1, 1, 32, 1, 1, 0, torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0: raise RuntimeError(f"qsa_prefill_hip: launch failed ({r})")
return out
diff --git a/exllamav3/modules/dsv41_fn/ds41_pf.py b/exllamav3/modules/dsv41_fn/ds41_pf.py
index a1a7c94..74f3544 100644
--- a/exllamav3/modules/dsv41_fn/ds41_pf.py
+++ b/exllamav3/modules/dsv41_fn/ds41_pf.py
@@ -64,7 +64,9 @@ def _launch(name, grid, block, args):
else:
cargs.append(ctypes.c_int(a))
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
- r = _state["lib"].hipModuleLaunchKernel(fn, grid, 1, 1, block, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)
+ select_device(device)
+ r = _state["lib"].hipModuleLaunchKernel(fn, grid, 1, 1, block, 1, 1, 0,
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"ds41_pf: launch of {name} failed ({r})")
@@ -105,7 +107,8 @@ def sparse_attention(q, kv, sink, idx, scale):
fn = _fn("ds41_sparse_attn_pf", q.device)
cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, kv, idx, sink, o)] + [ctypes.c_int(K), ctypes.c_int(N), ctypes.c_float(scale)]
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
- r = _state["lib"].hipModuleLaunchKernel(fn, R, 1, 1, 512, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)
+ r = _state["lib"].hipModuleLaunchKernel(fn, R, 1, 1, 512, 1, 1, 0,
+ torch.cuda.current_stream(q.device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"ds41_pf: launch failed ({r})")
return o
diff --git a/exllamav3/modules/dsv41_fn/dsv41_fuse.py b/exllamav3/modules/dsv41_fn/dsv41_fuse.py
index 6ba7b2c..b5ce8a6 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_fuse.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_fuse.py
@@ -47,8 +47,9 @@ def _launch(name, grid, block, args):
device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
fn = _load(device)[name]
cargs, params = H._pack(args)
+ select_device(device)
r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], 1, 1, block, 1, 1, 0,
- torch.cuda.current_stream().cuda_stream, params, None)
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"dsv41_fuse: launch of {name} failed ({r})")
diff --git a/exllamav3/modules/dsv41_fn/dsv41_hip.py b/exllamav3/modules/dsv41_fn/dsv41_hip.py
index 7ddd685..7021d1b 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_hip.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_hip.py
@@ -82,8 +82,9 @@ def _go(name, g, block, params, device=None):
if emu:
return emu(name, g, block, params)
fn = _load(device)[name]
+ select_device(device)
r = _state["lib"].hipModuleLaunchKernel(fn, g[0], g[1], g[2], block, 1, 1, 0,
- torch.cuda.current_stream().cuda_stream, params, None)
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"dsv41_hip: launch of {name} failed ({r})")
diff --git a/exllamav3/modules/dsv41_fn/dsv41_idx.py b/exllamav3/modules/dsv41_fn/dsv41_idx.py
index 501c02a..f5e0e2f 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_idx.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_idx.py
@@ -45,8 +45,9 @@ def _launch(name, grid, block, args):
device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
fn = _load(device)[name]
cargs, params = H._pack(args)
+ select_device(device)
r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], grid[1], 1, block, 1, 1, 0,
- torch.cuda.current_stream().cuda_stream, params, None)
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"dsv41_idx: launch of {name} failed ({r})")
diff --git a/exllamav3/modules/dsv41_fn/dsv41_moe.py b/exllamav3/modules/dsv41_fn/dsv41_moe.py
index eaaca3b..1979c5a 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_moe.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_moe.py
@@ -75,6 +75,7 @@ class _L:
def __init__(self, name, grid, block, args):
device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ self.device = device
self.fn = _load(device)[name]
self.grid, self.block = tuple(grid) + (1,) * (3 - len(grid)), block
self._keep = [a for a in args if isinstance(a, torch.Tensor)]
@@ -85,6 +86,7 @@ class _L:
return self
def __call__(self, stream):
+ select_device(self.device)
r = _state["lib"].hipModuleLaunchKernel(self.fn, self.grid[0], self.grid[1], self.grid[2], self.block, 1, 1, 0,
stream, self.params, None)
if r != 0:
diff --git a/exllamav3/modules/gr_fn/gr_mix_hip.py b/exllamav3/modules/gr_fn/gr_mix_hip.py
index 658a515..79244e2 100644
--- a/exllamav3/modules/gr_fn/gr_mix_hip.py
+++ b/exllamav3/modules/gr_fn/gr_mix_hip.py
@@ -3,7 +3,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
-from exllamav3.util.arch_list import device_arch, select_device
+from exllamav3.util.arch_list import device_arch, device_supported, select_device, GFX115_ARCHS
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gr_mix.hip")
@@ -48,11 +48,19 @@ def _load(defs="", device=None):
def _launch(fn, grid, block, args):
P = ctypes.c_void_p
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ select_device(device)
cargs = [P(a.data_ptr()) if isinstance(a, torch.Tensor) else ctypes.c_int(a) for a in args]
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
- r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], grid[1], 1, block, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)
+ r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], grid[1], 1, block, 1, 1, 0,
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0: raise RuntimeError(f"gr_mix_hip: launch failed ({r})")
+def supported(device=None):
+ """gr_mix.hip is a gfx11.5 WMMA kernel; gfx12 uses its own path."""
+ return device_supported(device, GFX115_ARCHS)
+
+
def _tile(defs, name):
d = dict(x.split("=") for x in defs.split() if "=" in x and not x.startswith("-"))
if name in d: return int(d[name])
diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.py
index 64b0e21..9bec12e 100644
--- a/exllamav3/modules/ple_fn/ple_hip.py
+++ b/exllamav3/modules/ple_fn/ple_hip.py
@@ -3,7 +3,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
-from exllamav3.util.arch_list import device_arch, select_device
+from exllamav3.util.arch_list import device_arch, device_supported, select_device, GFX115_ARCHS
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ple_hip.hip")
@@ -70,16 +70,29 @@ def _launch(name, grid, block, args):
cargs.append(ctypes.c_int(a))
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
g = tuple(grid) + (1,) * (3 - len(grid))
+ select_device(device)
r = _state["lib"].hipModuleLaunchKernel(fn, g[0], g[1], g[2], block, 1, 1, 0,
- torch.cuda.current_stream().cuda_stream, params, None)
+ torch.cuda.current_stream(device).cuda_stream, params, None)
if r != 0:
raise RuntimeError(f"ple_hip: launch of {name} failed ({r})")
-def supported(key, value, streams, conv_state, norm_w, conv_w, constant_scale, hc_mult, hidden):
- """Shapes and dtypes the kernels were proved for (everything else keeps the torch reference)."""
+def supported(*args, **kwargs):
+ """Device gate when called with a device, otherwise the proved-shape gate.
+
+ ``supported(device)`` is the per-device capability test used by the split
+ audit; ``supported(key, value, ...)`` is the original shape/dtype test and
+ additionally refuses devices other than gfx11.5.
+ """
+ if not args or not torch.is_tensor(args[0]):
+ device = args[0] if args else kwargs.get("device")
+ return device_supported(device, GFX115_ARCHS)
+ key, value, streams, conv_state, norm_w, conv_w, constant_scale, hc_mult, hidden = args
+ # Shapes and dtypes the kernels were proved for (everything else keeps the torch reference).
if hc_mult != HS or hidden != DD or constant_scale != 1.0:
return False
+ if not device_supported(key.device, GFX115_ARCHS):
+ return False
ts = (key, value, streams, conv_w) + tuple(norm_w)
if not all(t.is_cuda and t.is_contiguous() and t.data_ptr() % 16 == 0 for t in ts):
return False
diff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.py
index 150c19b..eacd44f 100644
--- a/exllamav3/modules/qsa_indexer.py
+++ b/exllamav3/modules/qsa_indexer.py
@@ -58,18 +58,23 @@ def _rope(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor
return torch.cat((x_rope * cos + rot * sin, x_pass), dim = -1)
-_PF_HIP = {"ok": None}
-def _pf_hip_ready() -> bool:
- """EXL3_QSA_PF_HIP (default 1, 0 = Triton pair): first use loads the proven HIP prefill kernel; a missing compiler or proof disables it with a warning."""
- if _PF_HIP["ok"] is None:
+_PF_HIP = {"ok": {}}
+def _pf_hip_ready(device) -> bool:
+ """EXL3_QSA_PF_HIP (default 1, 0 = Triton pair): per-device first use loads the
+ proven HIP prefill kernel; a missing compiler or proof disables it only on that device."""
+ from exllamav3.util.arch_list import device_index
+ idx = device_index(device)
+ ok = _PF_HIP["ok"].get(idx)
+ if ok is None:
try:
from .attention_fn.qsa_prefill_hip import _load
- _load()
- _PF_HIP["ok"] = True
+ _load("", device)
+ ok = True
except Exception as e:
- print(f" !! QSA prefill HIP kernel unavailable, using the Triton pair: {str(e)[:200]}")
- _PF_HIP["ok"] = False
- return _PF_HIP["ok"]
+ print(f" !! QSA prefill HIP kernel unavailable on cuda:{idx}, using the Triton pair: {str(e)[:200]}")
+ ok = False
+ _PF_HIP["ok"][idx] = ok
+ return ok
def tile_candidates(scores, tile_idx, t0):
@@ -885,7 +890,7 @@ class QSAIndexer(Module):
q_rows = tq.rotate(q_rows)
if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and qc is None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
- and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready()):
+ and q_rows.dtype == torch.half and k_arg.dtype == torch.half and _pf_hip_ready(q.device)):
# one wave per (row, kv head) HIP kernel, bit-identical to the Triton pair (fp16 cache, prefill chunks only)
from .attention_fn.qsa_prefill_hip import qsa_prefill_hip
o = qsa_prefill_hip(q_rows, k_arg, v_arg, indices, attn.sm_scale, block_table[0].int().contiguous(), page_size)
@@ -893,7 +898,7 @@ class QSAIndexer(Module):
if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
and tq is None and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4
and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
- and q_rows.dtype == torch.half and _pf_hip_ready()):
+ and q_rows.dtype == torch.half and _pf_hip_ready(q.device)):
# stage the used pages as rotated-domain fp16 (one elementwise pass), run the proven fp16 HIP kernel on q rotated by H32/sqrt(32), rotate the output back
from .attention_fn.qdeq_triton import qsa_prefill_q8
n_used = (int(cache_seqlens_cpu.max().item()) + seq + page_size - 1) // page_size
@@ -902,7 +907,7 @@ class QSAIndexer(Module):
if (os.environ.get("EXL3_QSA_PF_HIP", "1") == "1" and os.environ.get("EXL3_QSA_PF_DEQ", "1") == "1" and qc is not None
and tq is not None and bsz == 1 and seq >= 64 and seq <= 4096 * 4
and (attn.num_q_heads, attn.num_kv_heads, attn.head_dim, page_size, indices.shape[1]) == (24, 2, 256, 256, 2080)
- and q_rows.dtype == torch.half and _pf_hip_ready()):
+ and q_rows.dtype == torch.half and _pf_hip_ready(q.device)):
# TurboQuant prefill chunk: stage the used pages as rotated-domain fp16 (codebook lookup, one pass), run the fp16 HIP kernel
# on the rotated q, rotate the output back (the Triton split kernel below is ~70x slower per chunk on this shape)
from .attention_fn.qsa_prefill_hip import qsa_prefill_hip
diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.py
new file mode 100644
index 0000000..8e9d502
--- /dev/null
+++ b/exllamav3/serve_split.py
@@ -0,0 +1,242 @@
+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.
+"""
+
+import argparse
+import os
+import time
+from dataclasses import dataclass
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from exllamav3.device_map import ComponentMap, ComponentPolicy, SplitPlan
+
+# 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.
+GRAPH_ENV_OFF = {
+ "EXL3_BLOCK_GRAPH": "0",
+ "EXL3_BLOCK_GRAPH_MLA": "0",
+ "EXL3_BLOCK_GRAPH_VERIFY": "0",
+ "EXL3_BLOCK_GRAPH_DRAFT": "0",
+ "EXL3_BLOCK_GRAPH_ATTN": "0",
+ "EXL3_BLOCK_GRAPH_DEC_MOE": "0",
+ "EXL3_CUDA_GRAPH": "0",
+ "EXL3_HIP_GRAPH": "0",
+}
+
+# Per-model unsafe-env presets. Stage 1 only needs the GLM adapter; the empty
+# entries are the declared slots for the later adapters.
+SPLIT_PRESETS: dict[str, dict[str, str]] = {
+ "none": {},
+ "auto": {},
+ "glm": {},
+ "qwen": {},
+ "ds41": {},
+}
+
+
+def parse_front_layers(value) -> int | str:
+ if value is None:
+ return 0
+ if isinstance(value, int):
+ return "auto" if value == -1 else max(0, value)
+ v = str(value).strip().lower()
+ if v in ("", "0", "off", "none"):
+ return 0
+ if v == "auto":
+ return "auto"
+ try:
+ return max(0, int(v))
+ except ValueError as exc:
+ raise ValueError(f"front layers must be 0, N or auto, not {value!r}") from exc
+
+
+@dataclass
+class SplitSettings:
+ front_layers: int | str = 0
+ front_device: str = "auto"
+ endcaps: bool = True
+ front_reserve_gb: float = 1.2
+ preset: str = "auto"
+ split_graphs: str = "auto"
+
+ @property
+ def enabled(self) -> bool:
+ return self.front_layers == "auto" or (isinstance(self.front_layers, int) and self.front_layers > 0)
+
+ @property
+ def auto(self) -> bool:
+ return self.front_layers == "auto"
+
+ def describe(self) -> str:
+ return (f"front_layers={self.front_layers} 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}")
+
+
+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("--front-device", default = None,
+ help = "front device: auto, gfx1201, cuda:N or a UUID/name substring "
+ "(default: KYOJIN_FRONT_DEVICE, else auto)")
+ 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)")
+ 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,
+ help = "per-segment graphs (Stage 6); auto forces graphs off for now")
+
+
+def settings_from_namespace(args) -> SplitSettings:
+ raw = getattr(args, "front_layers", None)
+ if raw is None:
+ raw = os.environ.get("KYOJIN_FRONT_LAYERS", "0")
+ endcaps = getattr(args, "endcaps", None)
+ if endcaps is None:
+ endcaps = os.environ.get("KYOJIN_ENDCAPS", "1") != "0"
+ else:
+ endcaps = endcaps == "on"
+ preset = getattr(args, "split_preset", None) or os.environ.get("KYOJIN_SPLIT_PRESET", "auto")
+ 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"))
+ return SplitSettings(
+ front_layers = parse_front_layers(raw),
+ front_device = getattr(args, "front_device", None) or os.environ.get("KYOJIN_FRONT_DEVICE") or "auto",
+ endcaps = bool(endcaps),
+ front_reserve_gb = float(reserve),
+ preset = (preset or "auto").strip().lower(),
+ split_graphs = graphs,
+ )
+
+
+def apply_split_env(settings: SplitSettings, logger = print) -> list[str]:
+ """Force the split-safe environment and return the overridden ``KEY=value`` list."""
+ if not settings.enabled:
+ return []
+ preset = SPLIT_PRESETS.get(settings.preset)
+ if preset is None:
+ raise ValueError(f"unknown split preset {settings.preset!r}; choose one of {sorted(SPLIT_PRESETS)}")
+ forced = dict(GRAPH_ENV_OFF)
+ forced.update(preset)
+ if settings.split_graphs == "on":
+ # Stage 6 has no per-segment capture yet: honouring "on" would let a graph
+ # span the bridge and silently break the split.
+ logger("[split] --split-graphs on is not implemented yet (Stage 6); forcing graphs off")
+ overridden = [f"{k}={os.environ[k]}" for k, v in forced.items()
+ if os.environ.get(k) not in (None, "", v)]
+ os.environ.update(forced)
+ logger("[split] graphs forced off for split mode (per-segment capture is Stage 6)"
+ + (f"; overrode {', '.join(overridden)}" if overridden else ""))
+ return overridden
+
+
+class SplitController:
+ """The adapter-facing wrapper around ``SplitPlan``.
+
+ The controller resolves devices when split is enabled, owns the plan, and
+ times/audits each component load. Split off is a no-op: no device lookup,
+ no env change, no map, so the split-off path stays byte-identical.
+ """
+
+ def __init__(self, settings: SplitSettings, logger = print):
+ self.settings = settings
+ self.logger = logger
+ self.devices = None
+ self.plan = None
+ if settings.enabled:
+ from exllamav3.device_map import resolve_devices
+ self.devices = resolve_devices(settings.front_device)
+
+ @property
+ def enabled(self) -> bool:
+ return self.settings.enabled
+
+ def build_plan(self):
+ if not self.enabled:
+ return None
+ if self.plan is None:
+ from exllamav3.device_map import SplitPlan
+ self.plan = SplitPlan(
+ self.devices,
+ endcaps = self.settings.endcaps,
+ front_layers = self.settings.front_layers,
+ front_reserve_gb = self.settings.front_reserve_gb,
+ preset = self.settings.preset,
+ logger = self.logger,
+ )
+ return self.plan
+
+ def add(self, component: str, model, config = None, cache = None,
+ policy: "ComponentPolicy | None" = None, load_order: int | None = None):
+ plan = self.build_plan()
+ if plan is None:
+ return None
+ if policy is None:
+ from exllamav3.device_map import component_policy
+ policy = component_policy(component)
+ cmap = plan.add(component, model, config = config, cache = cache,
+ policy = policy, load_order = load_order)
+ plan.apply_policies()
+ plan.install_bridges()
+ return cmap
+
+ def register_config(self, config) -> None:
+ plan = self.build_plan()
+ if plan is not None:
+ plan.register_config(config)
+ plan.install_bridges()
+
+ def build(self) -> None:
+ if self.plan is not None:
+ self.plan.build()
+ self.plan.install_bridges()
+
+ def map(self, component: str):
+ return self.plan.map(component) if self.plan is not None else None
+
+ def engage_budget(self) -> None:
+ if self.plan is not None:
+ self.plan.engage_budget()
+
+ def load(self, component: str, model, **load_kwargs) -> bool:
+ """Load one component through its map; returns False when split is off."""
+ if not self.enabled:
+ return False
+ if self.plan is not None and self.plan.auto and not self.plan._built and not self.plan.records:
+ self.build()
+ cmap = self.map(component)
+ if cmap is None:
+ raise RuntimeError(f"split: component {component!r} was not declared")
+ # The owner map holds the front reserve for the whole load sequence; repeated
+ # calls are idempotent (ComponentMap.engage_budget).
+ self.plan.engage_budget()
+ t0 = time.perf_counter()
+ model.load(device_map = cmap, **load_kwargs)
+ self.plan.record_load(component, time.perf_counter() - t0)
+ return True
+
+ def register_extra_components(self, components: list[tuple[str, object, object, object]]) -> None:
+ """Declare ``(name, model, config, cache)`` after the target plan exists."""
+ for name, model, config, cache in components:
+ self.add(name, model, config = config, cache = cache)
+
+ def finalize(self, model, cache, extra: list[tuple[str, object, object]] | None = None,
+ ctx: int | None = None) -> None:
+ if self.plan is None:
+ return
+ self.plan.report(model, cache, extra = extra, ctx = ctx)
+ self.plan.release_budget()
diff --git a/tests/test_multi_device_jit.py b/tests/test_multi_device_jit.py
index 11ead67..46869b5 100644
--- a/tests/test_multi_device_jit.py
+++ b/tests/test_multi_device_jit.py
@@ -57,7 +57,7 @@ GFX115 = arch_list.GFX115_ARCHS
# name -> (module, load(device), arch gate)
CASES = {
"gr_mix_hip": (gr_mix, lambda m, d: m._load("", d), GFX115),
- "ple_hip": (ple, lambda m, d: m._load(d), None),
+ "ple_hip": (ple, lambda m, d: m._load(d), GFX115),
"qsa_prefill_hip": (qsa, lambda m, d: m._load("", d), GFX115),
"ds41_pf": (ds41_pf, lambda m, d: m._fn("ds41_gather_sum", d), GFX115),
"dsv41_hip": (dsv41_hip, lambda m, d: m._load(d), None),
@@ -69,7 +69,7 @@ CASES = {
"kda_fused_h_hip": (kda_fused, lambda m, d: m._load("", d), GFX115),
"kda_hf_hip": (kda_hf, lambda m, d: m._load("", d), GFX115),
}
-SUPPORTED = {"gdn_hf", "gdn_fused_h_hip", "kda_fused_h_hip", "kda_hf_hip"}
+SUPPORTED = {"gr_mix_hip", "ple_hip", "gdn_hf", "gdn_fused_h_hip", "kda_fused_h_hip", "kda_hf_hip"}
class FakeCuda:
diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.py
new file mode 100644
index 0000000..fbcb75d
--- /dev/null
+++ b/tests/test_split_plan_cpu.py
@@ -0,0 +1,284 @@
+"""CPU contract tests for the universal split core.
+
+The placement rules, endcap allowlist, auto-N arithmetic and the layout-neutral
+front reserve are pure Python/torch-device logic: they run without a GPU or the
+compiled extension. The integration gates (loads, determinism, needle) stay in
+the strix_halo harnesses.
+"""
+from __future__ import annotations
+
+import importlib.util
+import os
+import sys
+import types
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+def _load_module(name: str, path: Path):
+ spec = importlib.util.spec_from_file_location(name, path)
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
[email protected](scope = "module")
+def split_modules():
+ added = []
+ if "exllamav3" not in sys.modules:
+ pkg = types.ModuleType("exllamav3")
+ pkg.__path__ = [str(ROOT / "exllamav3")]
+ sys.modules["exllamav3"] = pkg
+ added.append("exllamav3")
+ if "exllamav3.util" not in sys.modules:
+ util = types.ModuleType("exllamav3.util")
+ util.__path__ = [str(ROOT / "exllamav3" / "util")]
+ sys.modules["exllamav3.util"] = util
+ added.append("exllamav3.util")
+ if "exllamav3.util.arch_list" not in sys.modules:
+ _load_module("exllamav3.util.arch_list", ROOT / "exllamav3" / "util" / "arch_list.py")
+ added.append("exllamav3.util.arch_list")
+ dm = _load_module("exllamav3.device_map", ROOT / "exllamav3" / "device_map.py")
+ bridge = _load_module("exllamav3.bridge", ROOT / "exllamav3" / "bridge.py")
+ split = _load_module("exllamav3.serve_split", ROOT / "exllamav3" / "serve_split.py")
+ yield dm, bridge, split
+ for name in ("exllamav3.serve_split", "exllamav3.bridge", "exllamav3.device_map"):
+ sys.modules.pop(name, None)
+ for name in added:
+ sys.modules.pop(name, None)
+
+
+class FakeModule:
+ def __init__(self, key, layer_idx = None, caps = None, numel = 0):
+ self.key = key
+ self.layer_idx = layer_idx
+ self.caps = caps or {}
+ self._numel = numel
+
+ def weights_numel(self):
+ return self._numel
+
+
+class FakeModel:
+ def __init__(self, modules):
+ self.modules = modules
+
+
+class FakeSTC:
+ def __init__(self, sizes):
+ self.sizes = sizes
+
+ def get_tensor_sizes(self, key):
+ return [self.sizes.get(key, 0)]
+
+
+class FakeConfig:
+ def __init__(self, sizes):
+ self.stc = FakeSTC(sizes)
+
+
+class FakeCacheLayer:
+ def __init__(self, size):
+ self.size = size
+ self.device = None
+ self.attention = SimpleNamespace(device = None)
+
+ def storage_size(self):
+ return self.size
+
+
+class FakeCache:
+ def __init__(self, per_layer = 0):
+ self.layers = {}
+ self.recurrent_layers = {}
+ if per_layer:
+ for i in range(16):
+ self.layers[(i, 0)] = FakeCacheLayer(per_layer)
+
+
+class FakeProps:
+ def __init__(self, total):
+ self.total_memory = total
+
+
+def _devices(dm):
+ return dm.Devices(
+ main = torch.device("cuda", 0),
+ front = torch.device("cuda", 1),
+ main_arch = "gfx1151",
+ front_arch = "gfx1201",
+ )
+
+
+def _glm_model():
+ embedding = FakeModule("model.language_model.embed_tokens", caps = {"prefer_cpu": True})
+ expand = FakeModule("hc_expand")
+ layers = [FakeModule(f"model.language_model.layers.{i}", layer_idx = i) for i in range(4)]
+ norm = FakeModule("model.language_model.norm")
+ head = FakeModule("lm_head", caps = {"logits_output": True})
+ ngram = FakeModule("ngram", caps = {})
+ return FakeModel([embedding, expand] + layers + [norm, head, ngram])
+
+
+def test_component_policy_defaults(split_modules):
+ dm, _bridge, _split = split_modules
+ text = dm.component_policy("text")
+ mtp = dm.component_policy("mtp")
+ aux = dm.component_policy("ngram")
+ assert text.kind == "text" and text.front_eligible and text.endcaps_front
+ assert "RMSNorm" in text.endcap_types and "lm_head" in text.endcap_key_suffixes
+ assert mtp.kind == "mtp" and mtp.whole_component and mtp.front_eligible
+ assert aux.kind == "aux" and not aux.front_eligible
+
+
+def test_text_placement_uses_endcap_allowlist_and_safe_unknown_default(split_modules):
+ dm, _bridge, _split = split_modules
+ model = _glm_model()
+ cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text")
+ devices = {m.key: cmap.device_for(m) for m in model.modules}
+
+ assert devices["model.language_model.embed_tokens"] == torch.device("cpu")
+ assert devices["hc_expand"] == torch.device("cuda", 1)
+ assert devices["model.language_model.norm"] == torch.device("cuda", 1)
+ assert devices["lm_head"] == torch.device("cuda", 1)
+ assert devices["ngram"] == torch.device("cuda", 0) # unknown non-layer: main, warning default
+ for i in range(4):
+ assert devices[f"model.language_model.layers.{i}"] == torch.device("cuda", 1 if i < 2 else 0)
+
+
+def test_endcaps_off_follows_neighbours_only_for_allowlisted_modules(split_modules):
+ dm, _bridge, _split = split_modules
+ model = _glm_model()
+ cmap = dm.ComponentMap.from_model(model, 2, False, _devices(dm), component = "text")
+ devices = {m.key: cmap.device_for(m) for m in model.modules}
+
+ assert devices["hc_expand"] == torch.device("cuda", 1) # prologue follows layer 0
+ assert devices["model.language_model.norm"] == torch.device("cuda", 0) # epilogue: last layer is main
+ assert devices["lm_head"] == torch.device("cuda", 0)
+ assert devices["ngram"] == torch.device("cuda", 0)
+
+ all_front = dm.ComponentMap.from_model(model, 4, False, _devices(dm), component = "text")
+ devices = {m.key: all_front.device_for(m) for m in model.modules}
+ assert devices["model.language_model.norm"] == torch.device("cuda", 1)
+ assert devices["lm_head"] == torch.device("cuda", 1)
+
+
+def test_layer_device_map_alias_keeps_harness_api(split_modules):
+ dm, _bridge, _split = split_modules
+ model = _glm_model()
+ cmap = dm.LayerDeviceMap.from_model(model, 2, True, _devices(dm), component = "text")
+ assert isinstance(cmap, dm.ComponentMap)
+ assert cmap.front_layers == 2 and cmap.enabled
+
+
+def test_whole_component_places_every_module_front_only_with_endcaps(split_modules):
+ dm, _bridge, _split = split_modules
+ mtp = FakeModel([
+ FakeModule("mtp.pre", caps = {}),
+ FakeModule("mtp.block.0", layer_idx = 0),
+ FakeModule("mtp.block.1", layer_idx = 1),
+ FakeModule("mtp.head", caps = {}),
+ ])
+ on = dm.ComponentMap.from_model(mtp, 0, True, _devices(dm), component = "mtp")
+ off = dm.ComponentMap.from_model(mtp, 0, False, _devices(dm), component = "mtp")
+ assert all(on.device_for(m) == torch.device("cuda", 1) for m in mtp.modules)
+ assert all(off.device_for(m) == torch.device("cuda", 0) for m in mtp.modules)
+
+
+def test_auto_n_uses_actual_bytes_cache_and_reserve(split_modules, monkeypatch):
+ dm, _bridge, _split = split_modules
+ gib = dm.GIB
+ sizes = {f"layer.{i}": gib for i in range(4)}
+ sizes["final_norm"] = gib // 10
+ model = FakeModel([
+ FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)
+ ] + [FakeModule("final_norm")])
+ cfg = FakeConfig(sizes)
+ cache = FakeCache(per_layer = gib // 5) # 0.2 GiB per layer, only 16 keys exist
+ monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(6 * gib))
+
+ plan = dm.SplitPlan(_devices(dm), endcaps = True, front_layers = "auto",
+ front_reserve_gb = 1.0, logger = lambda *_a: None)
+ plan.add("text", model, config = cfg, cache = cache)
+ plan.build()
+
+ # budget 6 - 1 reserve - 0.25 safety = 4.75 GiB; each layer is 1.0 weights +
+ # 0.2 cache, endcap 0.1. N=3 -> 3.7, N=4 -> 4.9.
+ assert plan.front_layers == 3
+ assert plan.map("text").front_layers == 3
+
+ plan_off = dm.SplitPlan(_devices(dm), endcaps = False, front_layers = "auto",
+ front_reserve_gb = 1.0, logger = lambda *_a: None)
+ plan_off.add("text", model, config = cfg, cache = cache)
+ plan_off.build()
+ assert plan_off.front_layers == 3
+
+
+def test_front_reserve_is_a_slab_not_an_allocator_cap(split_modules, monkeypatch):
+ dm, _bridge, _split = split_modules
+ model = _glm_model()
+ cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text",
+ front_reserve_gb = 0.5)
+ calls = []
+
+ def fake_empty(size, dtype = None, device = None):
+ calls.append((size, dtype, device))
+ return object()
+
+ monkeypatch.setattr(dm.torch, "empty", fake_empty)
+ monkeypatch.setattr(dm.torch.cuda, "set_per_process_memory_fraction",
+ lambda *_a, **_k: pytest.fail("the split must not cap the allocator"))
+ cmap.engage_budget()
+ assert len(calls) == 1
+ assert calls[0][0] == int(0.5 * dm.GIB)
+ assert calls[0][2] == torch.device("cuda", 1)
+ cmap.release_front_budget()
+ assert cmap._reserve_slabs == {}
+
+
+def test_bridge_installs_per_config_and_is_reused(split_modules, monkeypatch):
+ dm, bridge_mod, _split = split_modules
+ monkeypatch.setenv("KYOJIN_BRIDGE", "1")
+ main, front = torch.device("cuda", 0), torch.device("cuda", 1)
+ cfg = SimpleNamespace()
+ draft_cfg = SimpleNamespace()
+
+ b1 = bridge_mod.install_bridge(cfg, main, front)
+ b2 = bridge_mod.install_bridge(cfg, main, front)
+ b3 = bridge_mod.install_bridge(draft_cfg, main, front)
+
+ assert cfg.split_active is True and draft_cfg.split_active is True
+ assert b1 is b2
+ assert b1 is not b3
+ assert b1.pair == (main, front)
+
+
+def test_adapter_unsafe_env_is_applied_and_logged(split_modules, monkeypatch):
+ dm, _bridge, _split = split_modules
+ monkeypatch.setenv("EXL3_TEST_UNSAFE", "0")
+ policy = dm.component_policy("text", unsafe_env = (("EXL3_TEST_UNSAFE", "1"),))
+ plan = dm.SplitPlan(_devices(dm), endcaps = True, front_layers = 1, logger = lambda *_a: None)
+ plan.add("text", _glm_model(), policy = policy)
+ plan.build()
+ assert os.environ["EXL3_TEST_UNSAFE"] == "1"
+
+
+def test_split_settings_off_is_a_noop(split_modules, monkeypatch):
+ _dm, _bridge, split = split_modules
+ monkeypatch.setenv("EXL3_BLOCK_GRAPH", "1")
+ off = split.SplitSettings(front_layers = 0)
+ assert off.enabled is False
+ assert split.apply_split_env(off) == []
+ assert os.environ["EXL3_BLOCK_GRAPH"] == "1"
+
+ on = split.SplitSettings(front_layers = "auto")
+ assert on.enabled is True and on.auto is True
+ split.apply_split_env(on)
+ assert os.environ["EXL3_BLOCK_GRAPH"] == "0"
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 0e8e2f7..2c29c7f 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -25,6 +25,11 @@ from jinja2.sandbox import ImmutableSandboxedEnvironment
sys.path.append(str(Path(__file__).resolve().parent.parent))
import startup_health # noqa: E402 (GET /health with load progress while the model loads)
+# Shared split helper: pure stdlib at import, it loads exllamav3 lazily after SPEED_ENV.
+from kyojin_serve_split import ( # noqa: E402
+ SplitController, SplitSettings, add_split_arguments, apply_split_env, parse_front_layers,
+ settings_from_namespace,
+)
from loopguard import AnswerTap, loop_guard_default # noqa: E402 (answer-phase loop guard shared with the Qwen server)
import serve_compat # noqa: E402 (vLLM-style token-id prompts, cache_salt, /tokenize, usage details)
from l21_prompt_encode_cache import PromptEncodeCache # noqa: E402 (incremental prompt encode)
@@ -678,8 +683,9 @@ class ResidentEngine:
image_cache_dir: str | None = IMAGE_CACHE_DIR_DEFAULT,
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 = 0, front_device: str | None = None,
- endcaps: bool = True, front_reserve_gb: float = 1.2):
+ front_layers: int | str = 0, front_device: str | None = None,
+ endcaps: bool = True, front_reserve_gb: float = 1.2,
+ split_settings: SplitSettings | None = None):
import torch
from exllamav3 import Cache, Config, Generator, Job, Model, Tokenizer
from exllamav3.generator import generator as GM
@@ -709,28 +715,29 @@ class ResidentEngine:
self.max_draft = num_draft
self.config = Config.from_directory(model_path)
self.model = Model.from_config(self.config)
- self.front_layers = max(0, int(front_layers or 0))
- self.front_device_arg = front_device
- self.endcaps = bool(endcaps)
- self.front_reserve_gb = float(front_reserve_gb)
+ if split_settings is None:
+ split_settings = SplitSettings(
+ front_layers = parse_front_layers(front_layers),
+ front_device = front_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.front_layers = split_settings.front_layers
+ self.endcaps = split_settings.endcaps
+ self.front_reserve_gb = split_settings.front_reserve_gb
self.split_map = None
- self.split_devices = None
- if self.front_layers:
- from exllamav3.device_map import resolve_devices, LayerDeviceMap
- self.split_devices = resolve_devices(front_device)
- self.split_map = LayerDeviceMap.from_model(
- self.model, self.front_layers, self.endcaps, self.split_devices,
- component="text", front_reserve_gb=self.front_reserve_gb)
- if not self.split_map.enabled:
+ self.split_devices = self.split.devices
+ if self.split.enabled:
+ plan = self.split.build_plan()
+ if plan is None or plan.devices.front is None:
raise ValueError("layer split requested but no usable front device")
- print(f"serve: layer split: {self.split_map.describe()}; "
- f"main {self.split_devices.main} ({self.split_devices.main_arch}), "
- f"front {self.split_devices.front} ({self.split_devices.front_arch}), "
- f"front reserve {self.front_reserve_gb:.2f} GiB", flush=True)
- if self.front_layers > 5 and max_ctx > 65536:
+ 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 isinstance(self.front_layers, int) and self.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 until auto-sizing lands", flush=True)
+ "--front-layers 5 for long-context split runs until auto sizing accounts for "
+ "the KDA workspace", flush=True)
self.tokenizer = Tokenizer.from_config(self.config)
if os.environ.get("KYO_TOKCACHE", "8") == "0":
self.pec = None
@@ -770,8 +777,16 @@ class ResidentEngine:
kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first start
jit_log.install() # EXL3_LOG_JIT=1: one line per Triton compile
startup_health.stage("target weights")
- if self.split_map is not None:
- self.model.load(device_map=self.split_map, progressbar=False,
+ if self.split.enabled:
+ # Auto-N needs the cache sizes and the target's actual bytes; the cache exists now.
+ self.split_map = self.split.add("text", self.model, config=self.config,
+ cache=self.cache, load_order=0)
+ self.split.build()
+ 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)")
+ self.split.engage_budget()
+ self.split.load("text", self.model, progressbar=False,
callback=startup_health.load_callback(), max_chunk_size=4096)
else:
self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
@@ -781,14 +796,11 @@ class ResidentEngine:
self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx + 4096,
max_history=max_history, max_batch_size=slots, **qkw)
startup_health.stage("drafter weights")
- if self.split_map is not None:
- from exllamav3.device_map import LayerDeviceMap
- self.draft_map = LayerDeviceMap.from_model(
- self.draft_model, 0, self.endcaps, self.split_devices,
- component="mtp", front_reserve_gb=self.front_reserve_gb)
- self.draft_map.reserve_bytes.clear() # the target map owns the budget
- self.draft_model.load(device_map=self.draft_map, progressbar=False,
- callback=startup_health.load_callback(), max_chunk_size=4096)
+ if self.split.enabled:
+ self.draft_map = 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:
self.draft_model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())
else: # --num-draft 0: plain decode, no drafter
@@ -804,25 +816,18 @@ class ResidentEngine:
getattr(self.config, "vision_end_token_id", 0),
env_fingerprint=self.env_fingerprint)
if vision:
- self._vision_device = (self.split_devices.front
- if self.split_map is not None and self.endcaps
+ self._vision_device = (self.split.devices.front
+ if self.split.enabled and self.endcaps
else torch.device("cuda:0"))
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
- if self.split_map is not None:
- from exllamav3.device_map import print_split_table
+ if self.split.enabled:
extra = []
if self.draft_model is not None:
extra.append(("mtp", self.draft_model, self.draft_cache))
if self.vision is not None:
extra.append(("vision", self.vision, None))
- print_split_table(self.model, self.cache, self.split_map, extra=extra, ctx=ctx)
- bridge = getattr(self.config, "device_bridge", None)
- if bridge is not None:
- print(f"serve: {bridge.describe()}", flush=True)
- else:
- print("serve: layer split: bridge disabled (KYOJIN_BRIDGE=0); crossings use to_device()", flush=True)
- self.split_map.release_budget()
+ self.split.finalize(self.model, self.cache, extra=extra, ctx=ctx)
self.vocab_size = int(self.config.vocab_size or self.tokenizer.actual_vocab_size) # rows of the embedding table
self.Generator = Generator
# The loaded model and tokenizer are 1.1 M Python objects and every later gc.collect() walks them all: the Generator
@@ -934,7 +939,12 @@ class ResidentEngine:
try:
startup_health.stage("vision tower")
tower = Model.from_config(self.config, component="vision")
- tower.load(device=self._vision_device, progressbar=False, callback=startup_health.load_callback())
+ if self.split.enabled:
+ self.split.add("vision", tower, config=self.config, load_order=2)
+ self.split.load("vision", tower, progressbar=False,
+ callback=startup_health.load_callback())
+ else:
+ tower.load(device=self._vision_device, progressbar=False, callback=startup_health.load_callback())
except Exception as exc: # noqa: BLE001
print(f"serve: vision tower not loaded ({type(exc).__name__}: {exc}); image input disabled", flush=True)
return None
@@ -2189,17 +2199,7 @@ def main() -> None:
parser.add_argument("--sessions", type=int, default=1,
help=f"requests decoded together through the one Generator (1..{MAX_SESSIONS}); default 1 = one request at a time. "
"The KV pool (-c) is shared by all sessions")
- parser.add_argument("--front-layers", type=int, default=None,
- help="contiguous layer split: first N transformer layers on the front (eGPU) device; "
- "0 = off (default: KYOJIN_FRONT_LAYERS, else 0)")
- parser.add_argument("--front-device", default=None,
- help="front device for the layer split: auto, gfx1201, cuda:N or a UUID/name substring "
- "(default: KYOJIN_FRONT_DEVICE, else auto)")
- parser.add_argument("--endcaps", choices=("on", "off"), default=None,
- help="with a layer split, keep embedding/norm/lm_head/MTP/vision on the front device "
- "(default: KYOJIN_ENDCAPS, else on)")
- parser.add_argument("--front-reserve-gb", type=float, default=None,
- help="VRAM to leave free on the front device for workspace (default: KYOJIN_FRONT_RESERVE_GB, else 1.2)")
+ add_split_arguments(parser)
parser.add_argument("--kv-mode", choices=("tq", "quant", "fp16"), default="tq",
help="latent cache format. tq (default): TurboQuant, rotated Lloyd-Max codes + one scale per token, 6 bits unless --cache-bits says otherwise "
"(KL below the quant cache, same decode speed); quant: packed per-32 group scales (--cache-bits 4/5/6/8, 8 if none given); fp16: the unpacked 16-bit pages")
@@ -2245,30 +2245,9 @@ def main() -> None:
parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "high", "max"), default=None,
help="thinking effort when a request omits it (default: medium)")
args = parser.parse_args()
- front_layers = args.front_layers if args.front_layers is not None else int(os.environ.get("KYOJIN_FRONT_LAYERS", "0") or 0)
- front_device = args.front_device or os.environ.get("KYOJIN_FRONT_DEVICE") or "auto"
- endcaps = (args.endcaps == "on") if args.endcaps is not None else os.environ.get("KYOJIN_ENDCAPS", "1") != "0"
- front_reserve_gb = (args.front_reserve_gb if args.front_reserve_gb is not None
- else float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2")))
- if front_layers:
- # Phase 4: split mode runs eager. A whole-forward graph cannot span the
- # host-staged bridge between segments, and the per-block capture has no concept
- # of a segment boundary yet. Per-segment capture is Phase 6.
- forced = {
- "EXL3_BLOCK_GRAPH": "0",
- "EXL3_BLOCK_GRAPH_MLA": "0",
- "EXL3_BLOCK_GRAPH_VERIFY": "0",
- "EXL3_BLOCK_GRAPH_DRAFT": "0",
- "EXL3_BLOCK_GRAPH_ATTN": "0",
- "EXL3_BLOCK_GRAPH_DEC_MOE": "0",
- "EXL3_CUDA_GRAPH": "0",
- "EXL3_HIP_GRAPH": "0",
- }
- overridden = [f"{k}={os.environ[k]}" for k, v in forced.items()
- if os.environ.get(k) not in (None, "", v)]
- os.environ.update(forced)
- print("serve: layer split: graphs forced off for split mode (Phase 4; per-segment capture is Phase 6)"
- + (f"; overrode {', '.join(overridden)}" if overridden else ""), flush=True)
+ split_settings = settings_from_namespace(args)
+ if split_settings.enabled:
+ apply_split_env(split_settings, logger=lambda m: print(f"serve: {m}", flush=True))
if args.kv_mode == "fp16":
args.cache_bits = 0
elif args.cache_bits is None:
@@ -2329,8 +2308,7 @@ def main() -> None:
image_cache_format=args.image_cache_format,
image_cache_dir=args.image_cache_dir, image_cache_dir_max_gb=args.image_cache_dir_max_gb,
image_cache_dir_lock_s=args.image_cache_dir_lock_s,
- front_layers=front_layers, front_device=front_device,
- endcaps=endcaps, front_reserve_gb=front_reserve_gb)
+ split_settings=split_settings)
engine.row_budget = (5 if args.row_budget is None else args.row_budget) if args.sessions > 1 else 0
template = Path(args.chat_template or DEFAULT_TEMPLATE).expanduser().read_text(encoding="utf-8")
print(mem_line("loaded"), flush=True)
diff --git a/tools/kyojin_serve_split.py b/tools/kyojin_serve_split.py
new file mode 120000
index 0000000..5dcebfe
--- /dev/null
+++ b/tools/kyojin_serve_split.py
@@ -0,0 +1 @@
+../exllamav3/serve_split.py
\ No newline at end of file