Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
Universal contiguous layer split pt 1 (#190)
resynth5bd9b34ca94c
diff --git a/.gitignore b/.gitignoreindex 8fab9e9..1d6b3e9 100644--- a/.gitignore+++ b/.gitignore@@ -34,3 +34,6 @@ scratch/pfskip1/pfb1_results.jsontools/ds41/_ref/tools/ds41/_scratch/.check_logs/++scratch+docs-notesdiff --git a/doc/roc_hip_decode.md b/doc/roc_hip_decode.mdindex 2036167..11fad52 100644--- a/doc/roc_hip_decode.md+++ b/doc/roc_hip_decode.md@@ -180,13 +180,17 @@ model that fits the visible device (use the layer-split sibling for larger packs```sh# Whole-model chat-path coherence gate: 8 prompts x greedy/default, EOS, production# loop guard and 20-gram repetition checks.-HIP_VISIBLE_DEVICES=1 python tools/strix_halo/coherence_suite.py -m <model> -n 192+python tools/strix_halo/coherence_suite.py -m <model> -n 192# Per-shape GEMV timings and one streaming pass over every linear; --gemm A/Bs# ext.exl3_gemm when the tree exports it.-HIP_VISIBLE_DEVICES=1 python tools/strix_halo/gemv_perf_ab.py -m <model> --mode both --gemm+python tools/strix_halo/gemv_perf_ab.py -m <model> --mode both --gemm```+On the single-gfx1151 target no device variable is needed. With several GPUs+visible, set `HIP_VISIBLE_DEVICES` to the index whose `gcnArchName` matches; the+enumeration order is a driver/boot property, so do not hardcode an index.+`tests/hip_gemv_logits_oracle.py` is the forced fallback-vs-GEMV logits oracle.`EXL3_ORACLE_STEPS` sets the trace length (default 16); `EXL3_ORACLE_FREE=1` adds theunforced diagnostic pass. Both the oracle and worker read the step variable.diff --git a/doc/split.md b/doc/split.mdnew file mode 100644index 0000000..1529dca--- /dev/null+++ b/doc/split.md@@ -0,0 +1,131 @@+# Contiguous layer split++The layer split places the first N transformer layers of a model on one GPU (`part0`) and+the remaining layers on another (`part1`) in a single process. It is for models that do not+fit on one device, or for pairing a small fast card with a large unified-memory device.++Status: GLM-5.3-Flash is measured and supported by the GLM server. Qwen3.8-Flash-Next and+DeepSeek-V4.1-Flash adapters are staged; Flint and Mimo use the generic model path. See+[Model support](#model-support).++## How it works++ part0: layers 0..N-1 + endcaps part1: layers N..last+ \______________________________________/+ host-staged crossings++`part0` and `part1` are positions in the layer order, not device indices. Either physical+device can serve either part; MTP-on in the reverse orientation has a current JIT+limitation, noted under Known limitations.++Every tensor that crosses the split goes through an asynchronous host-staged bridge:++ src tensor --D2H--> pinned slot ring --H2D--> dst tensor++Both legs are enqueued on the two devices' compute streams, so the host does not wait. The+destination is a fresh allocation. `KYOJIN_BRIDGE=0` disables the bridge; cross-device+moves then use `to_device` with a blocking host bounce instead of probing or using a direct+peer copy. An explicit `EXLLAMA_NO_P2P_COPY` still wins.++Measured configuration: an RX 9070 (`gfx1201`, 15.92 GiB) over USB4 as `part0` and a+118 GiB Strix Halo iGPU (`gfx1151`) as `part1`. The numbers below are measurements from+that pair, not assumptions of the interface.++## Quick start++The GLM server and the split harnesses accept the flags below. The environment-only path+is useful for wrappers that cannot pass CLI flags:++```sh+KYOJIN_PART0_LAYERS=6 \+KYOJIN_PART0_DEVICE=gfx1201 \+KYOJIN_PART1_DEVICE=gfx1151 \+ python tools/glm/serve.py --model /path/to/model+```++## Interface++| Flag | Environment fallback | Meaning |+| --- | --- | --- |+| `--part0-layers auto\|N` | `KYOJIN_PART0_LAYERS` | first N transformer layers on `part0`; 0 = split off |+| `--part1-device auto\|cuda:N\|gfxXXXX\|uuid\|name` | `KYOJIN_PART1_DEVICE` | `part1` device (`auto` = `cuda:0`) |+| `--part0-device auto\|cuda:N\|gfxXXXX\|uuid\|name` | `KYOJIN_PART0_DEVICE` | `part0` device (`auto` = the only other device when two are visible) |+| `--endcaps on\|off` | `KYOJIN_ENDCAPS` | keep text endcaps and whole MTP/vision components on `part0` (default on) |+| `--part0-reserve-gb` | `KYOJIN_PART0_RESERVE_GB` | VRAM held as a load-time slab on `part0` for workspace (default 1.2) |+| `--split-preset auto\|glm\|qwen\|ds41\|none` | `KYOJIN_SPLIT_PRESET` | per-model unsafe-environment preset; GLM needs none today |+| `--split-graphs auto\|on\|off` | - | reserved for per-segment capture; split currently runs graphs off |++`cuda:N` is the torch device index **after** `HIP_VISIBLE_DEVICES`, not the `rocm-smi`+index. Explicit selectors win in either position: `part0=cuda:1/part1=cuda:0` and+`part0=cuda:0/part1=cuda:1` are both valid. With exactly two visible devices, a part0-only+selector still works and `part1=auto` takes the other device. Two selectors that resolve to+the same device fail, and a one-device split fails with a clear error. With more than two+visible devices, `auto` requires an explicit selector and prints the inventory.++`KYOJIN_PART0_LAYERS` and `KYOJIN_PART1_DEVICE` also work in `model_init.init` paths+(examples and evaluation tools) without CLI flags. The legacy `EXL3_LOAD_SPLIT` budget knob+is not part of this interface and must not be combined with the new map.++## What gets placed++| Where | Contents |+| --- | --- |+| `part0` | first N text layers; with `--endcaps on`, the text allowlist (norm/hc/lm_head-like) and whole non-CPU MTP/vision components |+| `part1` | remaining text layers; MTP/vision when endcaps are off; unknown non-layer modules |+| CPU | the shared `embed_tokens` (`prefer_cpu`) stays host-side by design |+| cache | each KV/recurrent layer follows its owning layer; a placement audit prints after load |+| bridge | one bridge per config, covering the target, drafter and vision |++Text endcaps are selected by a class/key allowlist, not by per-model placement in the core.+“Whole component” means all non-CPU modules of that component.++## Memory and capacity++- The `part0` reserve is an inert load-time slab, not a process-wide allocator cap. It+ removes bytes from the pool while the model loads and is released at the first `part1`+ module. Size it to the part0 card.+- Split mode runs eager. Whole-forward and per-block graphs are disabled; per-segment+ capture is not implemented yet.+- Use `util/memguard.py` when loading near the limit. It help save you from the dreaded OOM but slight adverse+ performance effects have been noted (to be investigated further.)++## Model support++| Model | Status | Notes |+| --- | --- | --- |+| GLM-5.3-Flash | measured | text, MTP and vision; on a 16 GiB `gfx12` `part0`, N=6 at ≤65K and N=5 for long context |+| Qwen3.8-Flash-Next | staged, not load-tested | QSA/GDN/PLE components; separate dflash drafter config; QSA `gfx12` caveat below |+| DeepSeek-V4.1-Flash | staged | uses the DSV4 engine, not `Model.load` |+| Flint, Mimo | best effort | generic `Model` path; no dedicated adapter |++Kernel support is per architecture. The split owns placement and transport, not kernel+ports; a missing kernel fallback on a new architecture is a model/kernel issue, not a split+defect.++## Verification++- Split **off** must remain byte-identical to the parent branch, including outputs and the+ serve environment block. It must not enumerate devices or mutate split settings.+- Split **on** is judged by run-to-run determinism with plain greedy decoding, KLD/task+ metrics and the needle probe. A mixed-architecture pair is not expected to be bitwise.+- `tools/strix_halo/split_eval.py` runs the battery: `--baseline`, `--part0-layers`,+ `--part1-device`/`--part0-device`, `--needle-depth`, `--bench-depth`, `--num-draft`,+ `--perf-tokens`/`--perf-reps` and `--compare a.json b.json`. Its context-dependent part0+ default is harness tuning, not a split property; override it with `--part0-layers` or the+ `--long-ctx-part0-layers`/`--short-ctx-part0-layers` flags.++## Known limitations++- MTP on the split is not deterministic. `--num-draft 0` remains the deterministic mode.+- Per-segment graphs are not implemented. Split runs eager and pays about 0.95x decode on+ GLM with MTP.+- Auto-N uses text bytes, cache and text endcaps, but does not yet subtract components+ declared after the target load (MTP/vision). Leave headroom or set N explicitly.+- Qwen QSA sparse attention has an illegal-access report in the `gfx12` top-k path on+ `gfx1201`; keep QSA cache pages off `part0` until that kernel is fixed.+- Reverse orientation with MTP on currently fails on the eGPU + iGPU device order with a+ Triton `no kernel image is available` error when the MTP block lands on the eGPU.+ Forward split is unaffected. Treat either-device MTP-on placement as requiring this JIT+ fix; MTP-off reverse placement is validated.+- Same-architecture and RDNA3/3.5 pairs are selection-tested only until such hardware is+ available.diff --git a/exllamav3/architecture/qwen4_exp.py b/exllamav3/architecture/qwen4_exp.pyindex 0127efd..7925d45 100644--- a/exllamav3/architecture/qwen4_exp.py+++ b/exllamav3/architecture/qwen4_exp.py@@ -64,7 +64,9 @@ class Qwen4ExpConfig(Qwen3_5VLMoeBaseConfig):# Gated-residual hyper-connectionsself.hc_mult = self.read_cfg(int, pfx("hc_count"), 4)- # QSA indexer+ # QSA indexer.+ # Split caveat: the gfx12 QSA sparse top-k path has an illegal-access report on+ # gfx1201; keep QSA cache pages off part0 until that kernel is fixed.self.indexer_n_heads = self.read_cfg(int, pfx("indexer_n_heads"), no_default)self.indexer_kv_heads = self.read_cfg(int, pfx("indexer_kv_heads"), 1)self.indexer_head_dim = self.read_cfg(int, pfx("indexer_head_dim"), no_default)diff --git a/exllamav3/bridge.py b/exllamav3/bridge.pynew file mode 100644index 0000000..65e8277--- /dev/null+++ b/exllamav3/bridge.py@@ -0,0 +1,208 @@+from __future__ import annotations++"""Async host-staged bridge for the contiguous layer split.++The part0 and part1 devices may be any two supported ROCm devices in either+position. On the measured mixed configuration (RX 9070 as part0 over USB4 ++Strix Halo as part1) there is no working, fast peer path: a direct device-to-device copy on+that link class is both slow (under 1 GB/s observed on the 9070 side) and+asymmetric. Every segment crossing therefore goes through pinned host memory:++ src tensor --D2H--> pinned slot --H2D--> dst tensor++Both legs are enqueued asynchronously on the two devices' current compute streams, so+the host thread never waits for the copy. An event carries the dependency from the+D2H leg to the H2D leg; a second event per ring slot lets the next hop reuse a pinned+slot without overwriting data that the destination has not read yet. The destination+tensor is a fresh allocation, so the caller may keep using it after the slot cycles.++``hop`` is the generic hidden-state crossing and ``hop_chunk`` the prefill-sized+crossing. Both share the same double-buffered channels (one channel per device+pair, one slot ring per dtype).++Set ``KYOJIN_BRIDGE=0`` to fall back to ``util.device_copy.to_device``; the split then+still runs, but every crossing is a blocking or direct copy.+"""++import os+import torch+++_ROUND = 2 # pinned slots per (device pair, dtype): reuse is stream-ordered, never host-blocking+++class _Slot:+ __slots__ = ("buf", "cap", "filled", "read", "read_valid")++ def __init__(self):+ self.buf = None+ self.cap = 0+ self.filled = None+ self.read = None+ self.read_valid = False+++class _Channel:+ __slots__ = ("src", "dst", "slots", "next")++ def __init__(self, src: torch.device, dst: torch.device):+ self.src = src+ self.dst = dst+ self.slots: dict[torch.dtype, list[_Slot]] = {}+ self.next = 0+++class Bridge:++ def __init__(self, *, part1: torch.device, part0: torch.device):+ self.part1 = torch.device(part1)+ self.part0 = torch.device(part0)+ self.channels: dict[tuple[int, int], _Channel] = {}+ self.stats = {"hops": 0, "bytes": 0, "chunk_hops": 0, "chunk_bytes": 0, "reallocs": 0}++ # -- configuration -----------------------------------------------------++ @property+ def pair(self) -> tuple[torch.device, torch.device]:+ return self.part1, self.part0++ def describe(self) -> str:+ return (f"host-staged async bridge {self.part1} <-> {self.part0} "+ f"(pinned slots x{_ROUND})")++ def summary(self) -> str:+ return (f"[split] bridge: {self.stats['hops']} hops, "+ f"{self.stats['bytes'] / 2**20:.1f} MiB total "+ f"({self.stats['chunk_hops']} chunk hops, "+ f"{self.stats['chunk_bytes'] / 2**20:.1f} MiB)")++ # -- public API --------------------------------------------------------++ def hop(self, t: torch.Tensor, dst: torch.device) -> torch.Tensor:+ """Move ``t`` to ``dst`` through pinned host staging, asynchronously."""+ return self._hop(t, dst, chunk = False)++ def hop_chunk(self, t: torch.Tensor, dst: torch.device) -> torch.Tensor:+ """Prefill-sized crossing. Double-buffered like every hop; reported separately."""+ return self._hop(t, dst, chunk = True)++ # -- implementation ----------------------------------------------------++ def _channel(self, src: torch.device, dst: torch.device) -> _Channel:+ key = (src.index or 0, dst.index or 0)+ ch = self.channels.get(key)+ if ch is None:+ ch = self.channels[key] = _Channel(src, dst)+ return ch++ def _slot(self, ch: _Channel, dtype: torch.dtype) -> _Slot:+ slots = ch.slots.get(dtype)+ if slots is None:+ slots = ch.slots[dtype] = [_Slot() for _ in range(_ROUND)]+ slot = slots[ch.next % _ROUND]+ ch.next = (ch.next + 1) % _ROUND+ return slot++ def _drain(self, ch: _Channel) -> None:+ """A slot is about to be reallocated: let both devices finish using it first.+ Only happens while the pinned pool grows, i.e. once on the first prefill chunk."""+ torch.cuda.synchronize(ch.src)+ torch.cuda.synchronize(ch.dst)++ def _grow(self, ch: _Channel, slot: _Slot, dtype: torch.dtype, numel: int) -> None:+ self._drain(ch)+ slot.buf = torch.empty(numel, dtype = dtype, pin_memory = True)+ slot.cap = numel+ slot.read_valid = False+ # CUDA/HIP events belong to the device that records them. The channel is+ # directional, so create each event on its own endpoint; creating both on+ # the ambient device fails on the first large (32K) growth with+ # "Event device N does not match recording stream's device".+ with torch.cuda.device(ch.src):+ slot.filled = torch.cuda.Event()+ with torch.cuda.device(ch.dst):+ slot.read = torch.cuda.Event()+ self.stats["reallocs"] += 1++ def _hop(self, t: torch.Tensor, dst: torch.device, chunk: bool) -> torch.Tensor:+ dst = torch.device(dst)+ if t.device == dst:+ return t+ if t.device.type != "cuda" or dst.type != "cuda":+ # CPU <-> device moves already have their own pinned/async paths+ return t.to(dst)+ if not t.is_contiguous():+ t = t.contiguous()++ src = t.device+ ch = self._channel(src, dst)+ slot = self._slot(ch, t.dtype)+ numel = t.numel()+ if numel > slot.cap:+ self._grow(ch, slot, t.dtype, numel)++ with torch.cuda.device(src):+ src_stream = torch.cuda.current_stream(src)+ with torch.cuda.device(dst):+ dst_stream = torch.cuda.current_stream(dst)++ # Reusing a host slot: the source must not overwrite it until the destination+ # finished reading it. This is a cross-device stream wait, not a host wait.+ if slot.read_valid:+ with torch.cuda.device(src):+ src_stream.wait_event(slot.read)++ hb = slot.buf[:numel].view(t.shape)++ with torch.cuda.device(src), torch.cuda.stream(src_stream):+ hb.copy_(t, non_blocking = True)+ slot.filled.record(src_stream)++ with torch.cuda.device(dst), torch.cuda.stream(dst_stream):+ dst_stream.wait_event(slot.filled)+ out = hb.to(dst, non_blocking = True)+ slot.read.record(dst_stream)+ slot.read_valid = True++ nbytes = numel * t.element_size()+ if chunk:+ self.stats["chunk_hops"] += 1+ self.stats["chunk_bytes"] += nbytes+ self.stats["hops"] += 1+ self.stats["bytes"] += nbytes+ return out+++def bridge_enabled() -> bool:+ return os.environ.get("KYOJIN_BRIDGE", "1") != "0"+++def install_bridge(config, *, part1: torch.device, part0: torch.device | None) -> Bridge | None:+ """Attach the bridge to a config and mark the model as split.++ The config is shared by the target, the drafter and the vision tower, so one call+ covers every component. ``split_active`` also defuses the graph paths: a whole-+ forward or per-block graph must not span the bridge (Phase 6 owns per-segment+ capture).+ """+ split_active = part0 is not None and torch.device(part1) != torch.device(part0)+ config.split_active = split_active+ if not split_active:+ return getattr(config, "device_bridge", None)+ # Kernel-level fallbacks that must apply only in split mode (the gfx12 KDA+ # determinant fallback) read this; split off stays on the default code path.+ os.environ["KYOJIN_SPLIT_ACTIVE"] = "1"+ existing = getattr(config, "device_bridge", None)+ if not bridge_enabled():+ # The direct P2P fallback can poison the context on links that only pretend to+ # support peer copies. With the bridge explicitly disabled, keep the fallback+ # safe by forcing a host bounce; an explicit EXLLAMA_NO_P2P_COPY still wins.+ from .util import device_copy+ if device_copy.FORCED is None:+ device_copy.FORCED = True+ return existing+ if existing is not None and existing.pair == (torch.device(part1), torch.device(part0)):+ return existing+ bridge = Bridge(part1 = part1, part0 = part0)+ config.device_bridge = bridge+ return bridgediff --git a/exllamav3/device_map.py b/exllamav3/device_map.pynew file mode 100644index 0000000..6b32e74--- /dev/null+++ b/exllamav3/device_map.py@@ -0,0 +1,1080 @@+from __future__ import annotations++"""+Contiguous layer split: resolve the two devices, declare per-component policies and+map model modules to them.++``part0`` is the first part of the layer stack (the first ``part0_layers``+transformer layers plus its endcaps); ``part1`` is the rest of the component.+Devices are selected by position, never by architecture: ``part1`` defaults to+``cuda:0`` and ``part0`` to the only other visible device when exactly two are+present. A part0-only selector keeps working when it lands on ``cuda:0``: part1+auto then takes the other device. Either position accepts ``cuda:N``,+``gfxXXXX``, a device UUID or a device-name substring, and either device may+serve either part. ``cuda:N`` is the torch index after ``HIP_VISIBLE_DEVICES``,+not the ``rocm-smi`` index. More than two visible devices require an explicit+selector.++The map itself is deliberately independent of the architecture: modules carrying a+``layer_idx`` are transformer layers and are assigned to ``part0`` for indices+``0 .. part0_layers - 1`` and to ``part1`` for the rest. Modules 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 ``part0`` 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 ``part1``.+- ``ComponentMap`` resolves the contiguous boundary for one component.+- ``SplitPlan`` owns every component of a process (target, MTP, vision, extra),+ the part0 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 ``part0``. 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.+"""++import os+from dataclasses import dataclass, field++import torch++from .util.arch_list import device_arch++GIB = 1024 ** 3++# Default load-time slab on the part0 device. A tuning value, not an architecture+# assumption: size it to the part0 card. Stage 5 derives it from the device total.+DEFAULT_PART0_RESERVE_GB = 1.2+DEFAULT_PART1_DEVICE = "auto"+DEFAULT_PART0_DEVICE = "auto"++# Text prologue/epilogue modules that are safe to place on part0. 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 part1.+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.+ return device_arch(index)+++def _device_uuid(index: int) -> str:+ p = torch.cuda.get_device_properties(index)+ u = getattr(p, "uuid", None) or getattr(p, "device_uuid", None) or ""+ if isinstance(u, bytes):+ return u.hex().lower()+ return str(u).lower().replace("-", "")+++@dataclass(frozen = True)+class DeviceInfo:+ """One visible device as the selector sees it.++ ``arch`` is a ROCm arch name when the runtime exposes one; an unknown or+ non-ROCm device keeps an empty string so selection by ``cuda:N``/name still+ works. The inventory is injectable so selection tests need no GPU.+ """++ index: int+ name: str = ""+ arch: str = ""+ uuid: str = ""++ def describe(self) -> str:+ parts = [f"cuda:{self.index}"]+ if self.arch:+ parts.append(self.arch)+ if self.name:+ parts.append(self.name)+ return " ".join(parts)+++@dataclass(frozen = True)+class Devices:+ part1: torch.device+ part0: torch.device | None+ part1_arch: str+ part0_arch: str | None+ inventory: tuple[DeviceInfo, ...] = ()+++def _device_info(index: int) -> DeviceInfo:+ name = ""+ try:+ name = torch.cuda.get_device_name(index)+ except Exception: # noqa: BLE001 - inventory is best effort+ pass+ try:+ arch = _arch_of(index)+ except Exception: # noqa: BLE001 - selection does not need an arch+ arch = ""+ try:+ uuid = _device_uuid(index)+ except Exception: # noqa: BLE001+ uuid = ""+ return DeviceInfo(index = index, name = name, arch = arch, uuid = uuid)+++def probe_devices() -> list[DeviceInfo]:+ """Inventory the visible devices; the only GPU-dependent step in selection."""+ if not torch.cuda.is_available():+ raise RuntimeError("layer split requires two HIP/CUDA devices")+ return [_device_info(i) for i in range(torch.cuda.device_count())]+++def _format_inventory(infos: list[DeviceInfo]) -> str:+ return ", ".join(d.describe() for d in infos) or "none"+++def _select_device(req: str, role: str, infos: list[DeviceInfo], env_name: str) -> int:+ req = (req or "").strip().lower()+ indexes = {d.index for d in infos}+ if req.startswith("cuda:"):+ try:+ index = int(req.split(":", 1)[1])+ except ValueError as exc:+ raise RuntimeError(f"{role} device selector {req!r} is not a valid cuda:N") from exc+ if index not in indexes:+ raise RuntimeError(f"{role} device {req!r}: no such device; available: "+ f"{_format_inventory(infos)}")+ return index+ if req.startswith("gfx"):+ matches = [d.index for d in infos if (d.arch or "").lower() == req]+ else:+ key = req.replace("-", "")+ matches = [+ d.index for d in infos+ if (key and key in (d.uuid or "").lower().replace("-", ""))+ or (req and req in (d.name or "").lower())+ ]+ if len(matches) > 1:+ raise RuntimeError(f"{role} device {req!r} matched several devices; use cuda:N or "+ f"a more specific selector; available: {_format_inventory(infos)}")+ if not matches:+ raise RuntimeError(f"{role} device {req!r} did not match any device; available: "+ f"{_format_inventory(infos)}. Set {env_name}=cuda:N "+ f"(or gfxXXXX/uuid/name).")+ return matches[0]+++def resolve_devices(+ part0: str | None = None,+ part1: str | None = None,+ devices: list[DeviceInfo] | None = None,+) -> Devices:+ """Resolve the part0/part1 pair by position, never by architecture.++ ``part1`` (or KYOJIN_PART1_DEVICE) defaults to ``auto`` = ``cuda:0``. ``part0``+ (or KYOJIN_PART0_DEVICE) defaults to the only other visible device when exactly+ two are visible; with one device the split cannot run, and with more than two an+ explicit selector is required. If part0 is explicit and occupies ``cuda:0``+ while part1 is ``auto`` with exactly two devices visible, part1 takes the other+ device so a part0-only selector keeps working. Both selectors accept+ ``cuda:N``, ``gfxXXXX``, a device UUID or a device-name substring; either+ position may be either device.++ ``devices`` injects a synthetic inventory; production callers omit it and probe+ the runtime. Selection itself does not depend on an architecture.+ """+ infos = list(devices) if devices is not None else probe_devices()+ if len(infos) < 2:+ raise RuntimeError(+ f"layer split needs two devices; visible: {_format_inventory(infos)}. "+ "Unset KYOJIN_PART0_LAYERS / --part0-layers to run on one device.")++ part1_req = part1 if part1 is not None else os.environ.get("KYOJIN_PART1_DEVICE", DEFAULT_PART1_DEVICE)+ part0_req = part0 if part0 is not None else os.environ.get("KYOJIN_PART0_DEVICE", DEFAULT_PART0_DEVICE)+ part1_req = (part1_req or DEFAULT_PART1_DEVICE).strip().lower()+ part0_req = (part0_req or DEFAULT_PART0_DEVICE).strip().lower()+ part1_auto = part1_req in ("", "auto")++ if part1_auto:+ part1_i = min(d.index for d in infos)+ else:+ part1_i = _select_device(part1_req, "part1", infos, "KYOJIN_PART1_DEVICE")++ if part0_req in ("", "auto"):+ if len(infos) != 2:+ raise RuntimeError(+ f"part0 device is 'auto' but {len(infos)} devices are visible; set "+ f"KYOJIN_PART0_DEVICE (or --part0-device) to one of: {_format_inventory(infos)}")+ part0_i = next(d.index for d in infos if d.index != part1_i)+ else:+ part0_i = _select_device(part0_req, "part0", infos, "KYOJIN_PART0_DEVICE")+ if part1_auto and part0_i == part1_i:+ # An explicit part0 selector must keep working when it lands on cuda:0:+ # part1 auto takes the only other device. With more devices the choice+ # is ambiguous, so ask for the part1 selector instead of guessing.+ if len(infos) == 2:+ part1_i = next(d.index for d in infos if d.index != part0_i)+ else:+ raise RuntimeError(+ f"part1 device is 'auto' (cuda:{part1_i}) and equals the explicit part0; "+ f"with {len(infos)} devices visible set KYOJIN_PART1_DEVICE (or --part1-device)")++ if part0_i == part1_i:+ raise RuntimeError(f"layer split part0 and part1 resolve to the same device "+ f"(cuda:{part1_i}); choose a different --part0-device/--part1-device")+ by_index = {d.index: d for d in infos}+ part1_info, part0_info = by_index[part1_i], by_index[part0_i]+ return Devices(+ part1 = torch.device("cuda", part1_i),+ part0 = torch.device("cuda", part0_i),+ part1_arch = part1_info.arch or "",+ part0_arch = part0_info.arch or "",+ inventory = tuple(infos),+ )+++# ---------------------------------------------------------------------------------------------------------+# 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+ part0 when endcaps are on, because they have no trunk boundary of their own.+ Auxiliary components never visit part0 implicitly.+ """++ name: str+ kind: str = "aux"+ part0_eligible: bool = False+ endcaps_part0: 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_part0(self, arch: str | None) -> bool:+ if not self.part0_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":+ defaults = dict(+ name = name, kind = "text", part0_eligible = True, endcaps_part0 = True,+ endcap_types = TEXT_ENDCAP_TYPES, endcap_key_suffixes = TEXT_ENDCAP_SUFFIXES)+ elif key in WHOLE_COMPONENT_KINDS:+ defaults = dict(+ name = name, kind = key, part0_eligible = True, endcaps_part0 = True,+ whole_component = True)+ else:+ defaults = dict(name = name, kind = "aux", part0_eligible = False,+ endcaps_part0 = False)+ defaults.update(overrides)+ return ComponentPolicy(**defaults)+++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_part0_endcap(module, policy: ComponentPolicy) -> bool:+ """True for a non-layer module the text policy allows on part0."""+ 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:+ sizes = stc.get_tensor_sizes(module.key)+ if sum(sizes):+ return int(sum(sizes))+ # HyperHead's tensors are underscore-joined (hc_head_fn) and a tied+ # lm_head has no lm_head.* span; both need the module's own names.+ compile_sizes = getattr(module, "get_compile_sizes", None)+ if compile_sizes is not None:+ sizes = compile_sizes(stc)+ if sum(sizes):+ return int(sum(sizes))+ alt = getattr(module, "alt_key", None)+ if alt:+ keys = alt if isinstance(alt, (list, tuple)) else (alt,)+ total = sum(sum(stc.get_tensor_sizes(k)) for k in keys)+ if total:+ return int(total)+ 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 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 part1 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.+ """++ part1: torch.device+ part0: torch.device | None+ part0_layers: int+ endcaps: bool+ component: str = "text"+ layer_count: int = 0+ policy: ComponentPolicy | None = None+ part1_arch: str = ""+ part0_arch: str | None = None+ reserve_bytes: dict[int, int] = field(default_factory = dict)+ part0_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(+ cls,+ model,+ part0_layers: int,+ endcaps: bool,+ devices: Devices,+ component: str = "text",+ part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GB,+ part1_reserve_gb: float = 0.0,+ config = None,+ cache = None,+ policy: ComponentPolicy | None = None,+ load_order: int = 0,+ ) -> "ComponentMap":+ policy = policy or component_policy(component)+ return cls.from_policy(model, part0_layers, endcaps, devices, policy,+ part0_reserve_gb = part0_reserve_gb,+ part1_reserve_gb = part1_reserve_gb,+ config = config, cache = cache, load_order = load_order)++ @classmethod+ def from_policy(+ cls,+ model,+ part0_layers: int | str,+ endcaps: bool,+ devices: Devices,+ policy: ComponentPolicy,+ part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GB,+ part1_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)+ auto = part0_layers in ("auto", -1) or (isinstance(part0_layers, str) and part0_layers.strip().lower() == "auto")+ part0_layers = 0 if auto else int(part0_layers)+ endcaps = bool(endcaps and policy.endcaps_part0)+ 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 part1.+ part0_layers = n_layers if endcaps else 0+ part0_layers = max(0, min(int(part0_layers), n_layers))+ if devices.part0 is None or not policy.allows_part0(devices.part0_arch):+ part0_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 part0 reserve caps the small card while its weights load. It is released+ # before the first part1 module (see Model._load_mapped): the part1 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.part0 is not None and part0_layers > 0 and part0_reserve_gb > 0:+ reserve[devices.part0.index] = max(0, int(part0_reserve_gb * GIB))+ if devices.part1 is not None and part1_reserve_gb > 0:+ reserve[devices.part1.index] = max(0, int(part1_reserve_gb * GIB))++ layer_bytes = _layer_bytes(model, stc)+ cache_by_layer = _cache_bytes_by_layer(cache)+ part0_endcaps = tuple(+ m.key for m in modules+ if getattr(m, "layer_idx", None) is None and is_part0_endcap(m, policy)+ )+ 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_part0_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(+ part1 = devices.part1,+ part0 = devices.part0,+ part0_layers = part0_layers,+ endcaps = bool(endcaps) and part0_layers > 0,+ component = policy.name,+ layer_count = n_layers,+ policy = policy,+ part1_arch = devices.part1_arch,+ part0_arch = devices.part0_arch,+ reserve_bytes = reserve,+ part0_endcap_keys = part0_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.part0 is not None and self.part0_layers > 0++ @property+ def used_devices(self) -> list[torch.device]:+ out = [self.part1]+ if self.enabled and self.part0 is not None:+ out.append(self.part0)+ return out++ @property+ def placed_devices(self) -> list[torch.device]:+ """Devices that actually hold tensors for this component.++ ``used_devices`` is the configured part1/part0 pair; a whole component with+ endcaps on has no tensors on part1 even though that pair still contains it.+ CPU-resident modules (the shared embedding) are reported separately.+ """+ out: list[torch.device] = []+ for module in self._module_refs:+ if getattr(module, "caps", {}).get("prefer_cpu"):+ continue+ device = self.device_for(module)+ if device.type == "cuda" and device not in out:+ out.append(device)+ return sorted(out, key = lambda d: d.index or 0)++ @property+ def policy_or_default(self) -> ComponentPolicy:+ return self.policy or component_policy(self.component)++ def _endcap_allowed(self, module) -> bool:+ return is_part0_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.part1+ if self.policy_or_default.whole_component:+ return self.part0+ return self.part0 if idx < self.part0_layers else self.part1+ if not self.enabled:+ return self.part1+ 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.part0 if self.endcaps else self.part1+ if not self._endcap_allowed(module):+ # Unknown / auxiliary non-layer module: always safe, never moved implicitly.+ return self.part1+ if not self.policy_or_default.endcaps_part0:+ return self.part1+ if self.endcaps:+ return self.part0+ # 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.part0+ if pos > self._last_layer_pos:+ return self.part0 if self.part0_layers >= self.layer_count else self.part1+ return self.part1++ # -- load-time budget --------------------------------------------------++ def engage_budget(self) -> None:+ """Hold the part0 reserve as a slab (never a process-wide allocator cap)."""+ if getattr(self, "_budget_engaged", False):+ return+ for i, reserve in self.reserve_bytes.items():+ 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_part0_budget(self) -> None:+ """Release the part0 slab before the first part1 module loads.++ 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.part0 is None:+ return+ self._reserve_slabs.pop(self.part0.index, None)+ self._budget_engaged = any(i != self.part0.index and r > 0 for i, r in self.reserve_bytes.items())++ def release_budget(self) -> None:+ 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 part0_cost(self, n: int, endcaps: bool | None = None) -> int:+ """Estimated part0 bytes for n text layers plus the policy's part0 endcaps."""+ n = max(0, min(n, self.layer_count))+ endcaps = self.endcaps if endcaps is None else bool(endcaps)+ endcaps = endcaps and self.policy_or_default.endcaps_part0+ 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.part0_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.part0_layers - 1} part0, "+ f"{self.part0_layers}..{self.layer_count - 1} part1"]+ if self.endcaps:+ parts.append(f"endcaps part0 ({len(self.part0_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+ part0_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,+ part0_layers: int | str = 0,+ part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GB,+ part1_reserve_gb: float = 0.0,+ preset: str = "auto",+ auto_cap: int | None = None,+ logger = print,+ ):+ self.devices = devices+ self.endcaps = bool(endcaps)+ self.requested_part0_layers = part0_layers+ self.auto = isinstance(part0_layers, str) and part0_layers.strip().lower() == "auto" or part0_layers == -1+ self.part0_layers = 0 if self.auto else max(0, int(part0_layers or 0))+ self.part0_reserve_gb = float(part0_reserve_gb)+ self.part1_reserve_gb = float(part1_reserve_gb)+ self.preset = (preset or "auto").strip().lower()+ self.auto_cap = None if auto_cap is None else max(0, int(auto_cap))+ 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,+ part0_layers: int | str | None = None,+ load_order: int | None = None,+ ) -> ComponentMap:+ was_built = self._built+ policy = policy or component_policy(component)+ layer = self.requested_part0_layers if part0_layers is None else part0_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,+ part0_reserve_gb = self.part0_reserve_gb,+ part1_reserve_gb = self.part1_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)+ if self.auto_cap is not None:+ n = min(n, self.auto_cap)+ self.part0_layers = n+ self.logger(f"[split] auto-N: {n} part0 layer(s) "+ f"(budget {self._auto_budget() / GIB:.2f} GiB, "+ f"reserve {self.part0_reserve_gb:.2f} GiB tuning slab)")+ for name, (model, config, cache, policy, layer, load_order) in self._decls.items():+ if self.auto and policy.kind == "text":+ layer = self.part0_layers+ self.maps[name] = ComponentMap.from_policy(+ model, layer, self.endcaps, self.devices, policy,+ part0_reserve_gb = self.part0_reserve_gb,+ part1_reserve_gb = self.part1_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) the named preset and every adapter-declared unsafe env lever."""+ if self.preset not in ("auto", "none"):+ from .serve_split import SPLIT_PRESETS+ preset = SPLIT_PRESETS.get(self.preset)+ if preset is None:+ raise ValueError(f"unknown split preset {self.preset!r}; choose one of {sorted(SPLIT_PRESETS)}")+ for key, value in preset.items():+ old = os.environ.get(key)+ if old != value:+ self.logger(f"[split] preset {self.preset}: {key}={value}"+ + (f" (was {old})" if old is not None else ""))+ os.environ[key] = value+ 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.part0 is None:+ return 0+ total = int(torch.cuda.get_device_properties(self.devices.part0).total_memory)+ # Allocator slack, not an architecture rule; Stage 5 replaces it with measured+ # load/forward headroom.+ safety = int(float(os.environ.get("KYOJIN_AUTON_SAFETY_GB", "0.25")) * GIB)+ return max(0, total - int(self.part0_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.part0_cost(n, self.endcaps)+ else:+ # Prologue follows layer 0; epilogue only when every layer is part0.+ cost = other + cmap.part0_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_part0_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_part0_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 part1 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, part1 = self.devices.part1, part0 = self.devices.part0)++ 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),+ part0_layers = cmap.part0_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(rl, "device", None) or+ getattr(getattr(rl, "module", 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.part1+ if cmap.policy_or_default.whole_component:+ return cmap.part0 if cmap.endcaps else cmap.part1+ return cmap.part0 if idx < cmap.part0_layers else cmap.part1++ 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 part1 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+ part0 = f"0..{r.part0_layers - 1}" if r.part0_layers else "-"+ part1 = (f"{r.part0_layers}..{r.layer_count - 1}"+ if r.part0_layers < r.layer_count else "-")+ placed = ", ".join(str(x) for x in d.placed_devices) or "-"+ self.logger(f"[split] {r.component:7s} {r.seconds:7.1f}s part0 {part0:>10s} "+ f"part1 {part1:>10s} weights {r.weight_bytes / GIB:7.2f} GiB "+ f"cache {r.cache_bytes / GIB:6.2f} GiB devices {placed}")+ 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(cl, "device", None) or getattr(getattr(cl, "attention", None), "device", None)+ if dev is None:+ continue+ 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(rl, "device", None) or+ getattr(getattr(rl, "module", None), "device", None))+ if dev is None:+ continue+ try:+ table[dev] = table.get(dev, 0) + int(rl.storage_size())+ except Exception: # noqa: BLE001 - a state type without a byte count+ pass+ return table+++def _gib(n: int) -> str:+ return f"{n / GIB:7.2f} GiB"+++def print_split_table(+ model,+ cache,+ device_map: ComponentMap,+ extra: list[tuple[str, object, object]] | None = None,+ ctx: int | None = None,+) -> None:+ """Print the per-device memory table that Gate 3 uses as ground truth.++ Weights are reported as the device allocator sees them (which is what the+ budget actually has to hold); the cache column is the sum of the allocated+ cache layer storage on that device.+ """+ cache_b: dict[torch.device, int] = {}+ for c in [cache] + [c for _, _, c in (extra or []) if c is not None]:+ 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)):+ cache_bytes = cache_b.get(dev, 0)+ 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)+ if device_map.part0 is not None:+ try:+ p = torch.cuda.get_device_properties(device_map.part0)+ total = p.total_memory+ except Exception: # noqa: BLE001+ total = 0+ reserve = device_map.reserve_bytes.get(device_map.part0.index, 0)+ print(f"[split] part0 {str(device_map.part0)} {device_map.part0_arch}: "+ 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)diff --git a/exllamav3/model/model.py b/exllamav3/model/model.pyindex 8e6daad..af25a49 100644--- a/exllamav3/model/model.py+++ b/exllamav3/model/model.py@@ -67,6 +67,16 @@ class Model(Model_TPMixin, Model_LSMixin):return self._get_cache_layers+ @property+ def split_active(self) -> bool:+ """True when this model was loaded through a contiguous layer split device map.++ A graph must never span the bridge, and a whole-forward graph would. Per-segment+ capture comes with the split graphs stage; until then split mode runs eager.+ """+ return bool(getattr(self.config, "split_active", False))++@propertydef recurrent_state_cls(self):"""The job state class. A model with no recurrent state of its own (plain attention) whose attention modules declare@@ -262,7 +272,7 @@ class Model(Model_TPMixin, Model_LSMixin):advance_recurrent_states(input_ids, params, self)return yelse:- if _cuda_graph.CUDA_GRAPH_ENABLED:+ if _cuda_graph.CUDA_GRAPH_ENABLED and not self.split_active:# opt-in whole-forward CUDA graph (decode only); None = declined, run eager belowy = _cuda_graph.maybe_forward(self, x, params)if y is not None:@@ -283,7 +293,7 @@ class Model(Model_TPMixin, Model_LSMixin):self._lag_tbl = Nonetry:from ..modules import Embedding, NGramEmbedding- if self.loaded_tp or not torch.cuda.is_available() or self._get_prefetch_layers or getattr(self.config, "moe_cpu_hosts", None):+ if self.split_active or self.loaded_tp or not torch.cuda.is_available() or self._get_prefetch_layers or getattr(self.config, "moe_cpu_hosts", None):return Noneif any(type(m).__name__ in ("PLE", "PerLayerEmbedding") or isinstance(m, NGramEmbedding) for m in self.modules):return None@@ -319,7 +329,7 @@ class Model(Model_TPMixin, Model_LSMixin):graph can take them (its GPU embedding table), a decline returns None. Otherwise the eager layers run from a device-sideembedding gather (lag_table). Same arithmetic as forward(): the table rows are the rows Embedding.forward reads."""if _cuda_graph.CUDA_GRAPH_ENABLED and (not torch.version.hip or _cuda_graph.HIP_GRAPH):- if self.loaded_tp or not torch.cuda.is_available():+ if self.split_active or self.loaded_tp or not torch.cuda.is_available():return Nonex = self.prepare_inputs(input_ids, params)if params.get("recurrent_states") is not None and "recurrent_slots" not in params:@@ -364,6 +374,7 @@ class Model(Model_TPMixin, Model_LSMixin):tp_output_device: torch.device | str | int | None = None,reserve_per_device: list[float] | float | None = None,use_per_device: list[float] | float | None = None,+ device_map = None,tensor_p: bool = False,progressbar: bool = False,max_chunk_size: int = 2048,@@ -384,6 +395,12 @@ class Model(Model_TPMixin, Model_LSMixin)::param device:(optional) If specified, load to single device, e.g. "cuda:0"+ :param device_map:+ (optional) LayerDeviceMap from exllamav3.device_map. Assigns each top-level+ module to a device (contiguous front layers plus optional endcaps) and streams+ weights directly there. The caller releases the map's memory budget after the+ last component (target, drafter, vision) has loaded.+:param tp_output_device:(optional) If loading with tensor_p == True, device on which to gather output logits. Must be one ofthe active devices in the split. Default is first device in split@@ -481,8 +498,20 @@ class Model(Model_TPMixin, Model_LSMixin):assert max_output_size >= 1, "max_output_size must be positive"assert max_output_factor >= 1, "max_output_factor must be positive"+ # Explicit contiguous layer split. The map owns the per-device budget; the+ # caller releases it after the last component (target/drafter/vision).+ if device_map is not None:+ 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+# Load to single device- if device is not None:+ elif device is not None:assert not bool(reserve_per_device) and not bool(use_per_device), \"Cannot specify reserve_per_device or use_per_device when loading to single device."assert not tensor_p, \diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.pyindex b2c5f61..d3b222c 100644--- a/exllamav3/model/model_ls.py+++ b/exllamav3/model/model_ls.py@@ -67,6 +67,61 @@ class Model_LSMixin(ABC):return {"input_ids": torch.zeros((1, chunk_size), dtype = torch.long)}+ def _load_mapped(+ self,+ progressbar: bool,+ device_map,+ config: Config,+ modules: list,+ verbose: bool,+ callback = None,+ max_chunk_size: int = 2048,+ ):+ """Load every top-level module straight to the device the map assigns it.++ No autosplit measuring forwards: the boundary is explicit. The part0 reserve is a+ held device slab while its segment loads, then is dropped at the first part1 module+ (the freed block stays available to the workspace without changing the allocator's+ policy or the part1 segment's numerics). The caller releases whatever remains after+ the last component.+ """+ device_map.engage_budget()+ pin_all = config.infer_params.vision_pinned and getattr(self, "component", "text") == "vision"+ part0_released = not device_map.enabled+ with ProgressBar(f"Loading (split)" if progressbar else None, len(modules)) as progress:+ for idx, module in enumerate(modules):+ if callback: callback(idx, len(modules))+ dev = device_map.device_for(module)+ if not part0_released and dev == device_map.part1:+ device_map.release_part0_budget()+ part0_released = True+ defer = module.can_defer_load()+ if defer:+ # Pinned modules leave the arena alone (see _load_single)+ config.stc.begin_deferred_load(arena = not pin_all)+ module.load(dev, max_chunk_size = max_chunk_size)+ if defer:+ config.stc.end_deferred_load()+ if pin_all:+ module.pin_linears()+ for h in getattr(config, "moe_cpu_hosts", {}).values():+ h.commit_module(module.key)+ progress.update(idx + 1)+ if callback: callback(len(modules), len(modules))+ config.stc.close()+ self.active_devices = [d.index for d in device_map.used_devices if d.type == "cuda"]+ self.output_device = modules[-1].device++ # The config reaches the drafter and the vision tower too: one bridge (and the+ # split-active marker that defuses graph capture) covers every component that+ # shares it.+ if device_map.enabled:+ from ..bridge import install_bridge+ bridge = install_bridge(config, part1 = device_map.part1, part0 = device_map.part0)+ if bridge is not None and verbose:+ print(f" -- split: {bridge.describe()}")++def _load_autosplit(self,progressbar: bool,diff --git a/exllamav3/model_init.py b/exllamav3/model_init.pyindex 0c4d6fa..01471e6 100755--- a/exllamav3/model_init.py+++ b/exllamav3/model_init.py@@ -335,6 +335,55 @@ def init(else:single_device = None+ # 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.+ from .serve_split import parse_part0_layers+ part0_layers = parse_part0_layers(os.environ.get("KYOJIN_PART0_LAYERS", "0"))+ split_plan = None+ draft_component = None+ text_map = draft_map = None+ if part0_layers:+ if args.tensor_parallel or single_device or split is not None:+ raise ValueError("KYOJIN_PART0_LAYERS cannot be combined with tensor parallel, "+ "EXL3_LOAD_DEVICE or --gpu_split")+ if os.environ.get("EXL3_LOAD_SPLIT"):+ raise ValueError("KYOJIN_PART0_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_PART0_DEVICE"),+ os.environ.get("KYOJIN_PART1_DEVICE"))+ endcaps = os.environ.get("KYOJIN_ENDCAPS", "1") != "0"+ reserve = float(os.environ.get("KYOJIN_PART0_RESERVE_GB", "1.2"))+ split_plan = SplitPlan(devices, endcaps = endcaps, part0_layers = part0_layers,+ part0_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:+ if use_mtp:+ draft_component = "mtp"+ split_plan.add("mtp", draft_model, config = draft_config,+ cache = draft_cache, load_order = 1)+ else:+ # A separate text drafter has its own trunk; do not treat it as a+ # whole-component MTP and place it entirely on the part0 card.+ from .device_map import ComponentPolicy+ draft_component = "draft"+ split_plan.add("draft", draft_model, config = draft_config,+ cache = draft_cache,+ policy = ComponentPolicy(name = "draft", kind = "aux",+ part0_eligible = False,+ endcaps_part0 = False),+ part0_layers = 0, load_order = 1)+ split_plan.build()+ split_plan.install_bridges()+ split_plan.engage_budget()+ text_map = split_plan.map("text")+ draft_map = split_plan.map(draft_component) if draft_component is not None else None+ if text_map is not None:+ printp(not quiet, f" -- layer split: {text_map.describe()}")+ if split_plan.auto:+ printp(not quiet, f" -- layer split: auto chose {text_map.part0_layers} part0 layer(s)")+# Parallelism optionstp_options = {"moe_tensor_split": args.tp_moe_tensor_split@@ -359,7 +408,8 @@ def init(if draft_model_dir:printp(not quiet, f" -- Loading {draft_model_dir}")draft_model.load(- **({"device": single_device} if single_device else {"use_per_device": split}),+ **({"device_map": draft_map} if draft_map else+ ({"device": single_device} if single_device else {"use_per_device": split})),progressbar = progress,verbose = args.load_verbose,max_batch_size = args.autosplit_max_batch_size,@@ -371,7 +421,8 @@ def init(# Load modelprintp(not quiet, f" -- Loading {args.model_dir}")model.load(- **({"device": single_device} if single_device else {"use_per_device": split}),+ **({"device_map": text_map} if text_map else+ ({"device": single_device} if single_device else {"use_per_device": split})),tensor_p = args.tensor_parallel,progressbar = progress,tp_dev_limits = tp_dev_limits,@@ -384,6 +435,15 @@ def init(**kwargs)+ if split_plan is not None:+ split_plan.record_load("text", 0.0)+ if draft_model is not None:+ split_plan.record_load(draft_component, 0.0)+ split_plan.report(model, cache,+ extra=[(draft_component, draft_model, draft_cache)] if draft_model is not None else [],+ ctx=getattr(args, "cache_size", None))+ split_plan.release_budget()+# Load tokenizerif load_tokenizer:printp(not quiet, f" -- Loading tokenizer...")diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.pyindex 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 = Nonpages = 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 outdiff --git a/exllamav3/modules/block_graph.py b/exllamav3/modules/block_graph.pyindex bc75f88..f3452ec 100644--- a/exllamav3/modules/block_graph.py+++ b/exllamav3/modules/block_graph.py@@ -723,6 +723,10 @@ def maybe_graph_forward(block, x: torch.Tensor, params: dict):to decline (caller then runs the eager forward)."""if not BLOCK_GRAPH_ENABLED:return None # dynamic check: the flag may be toggled mid-process for qualification+ if getattr(getattr(block, "config", None), "split_active", False):+ # A contiguous layer split moves the state across a host-staged bridge between+ # segments; a per-block graph must not span that boundary.+ return Nonerunner = getattr(block, "block_graph_runner", None)if runner is None:# the verdict depends on BLOCK_GRAPH_MLA, which may be toggled mid-process: key itdiff --git a/exllamav3/modules/block_sparse_mlp.py b/exllamav3/modules/block_sparse_mlp.pyindex 66305cd..3fb8e27 100644--- a/exllamav3/modules/block_sparse_mlp.py+++ b/exllamav3/modules/block_sparse_mlp.py@@ -223,7 +223,11 @@ _side_state: dict = {}def _side(device):st = _side_state.get(device)if st is None:- st = _side_state[device] = (torch.cuda.Stream(device = device), torch.cuda.Event(), torch.cuda.Event())+ # Events belong to the device that records them. Creating them on the+ # ambient device breaks a split layer whose side stream is on the other GPU.+ with torch.cuda.device(device):+ st = (torch.cuda.Stream(device = device), torch.cuda.Event(), torch.cuda.Event())+ _side_state[device] = streturn stdiff --git a/exllamav3/modules/dsv41_fn/ds41_pf.py b/exllamav3/modules/dsv41_fn/ds41_pf.pyindex 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 odiff --git a/exllamav3/modules/dsv41_fn/dsv41_fuse.py b/exllamav3/modules/dsv41_fn/dsv41_fuse.pyindex 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.pyindex 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.pyindex 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.pyindex 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 = deviceself.fn = _load(device)[name]self.grid, self.block = tuple(grid) + (1,) * (3 - len(grid)), blockself._keep = [a for a in args if isinstance(a, torch.Tensor)]@@ -85,6 +86,7 @@ class _L:return selfdef __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/embedding.py b/exllamav3/modules/embedding.pyindex e893ee2..1b6f02a 100644--- a/exllamav3/modules/embedding.py+++ b/exllamav3/modules/embedding.py@@ -33,6 +33,7 @@ class Embedding(Module):self.hidden_size = hidden_sizeself.out_dtype = out_dtypeself._pinned_staging = {}+ self._narrow_ev_device = Noneself._numel = vocab_size * hidden_sizeself.normalize = normalizeself.multiplier = multiplier@@ -212,6 +213,7 @@ class Embedding(Module):buf = torch.empty((n, self.hidden_size), dtype = w.dtype, pin_memory = True)self._narrow_buf = bufself._narrow_ev = None+ self._narrow_ev_device = Noney = buf[:n]torch.index_select(w, 0, ids.reshape(-1), out = y)if self.multiplier != 1.0:@@ -222,9 +224,16 @@ class Embedding(Module):"""Upload the pinned 16-bit rows without blocking the host and widen on the device (exact for bf16/fp16 -> fp32, the sameround-to-nearest the host conversion does for bf16 -> fp16). The rows stay cached for the MTP block (forward_device)."""d = y.to(device, non_blocking = True)- if self._narrow_ev is None:- self._narrow_ev = torch.cuda.Event()- self._narrow_ev.record()+ # A CPU-resident embedding is shared by the target's first layer and the MTP+ # block, which a split places on different devices. The event belongs to the+ # stream it is recorded on, so recreate it when the upload device changes.+ d_device = torch.device(device)+ if getattr(self, "_narrow_ev", None) is None or getattr(self, "_narrow_ev_device", None) != d_device:+ with torch.cuda.device(d_device):+ self._narrow_ev = torch.cuda.Event()+ self._narrow_ev_device = d_device+ with torch.cuda.device(d_device):+ self._narrow_ev.record()self._dev_rows = (ids.clone(), d) # consumed by forward_device (the MTP block), else replaced by the next chunkreturn d if d.dtype == out_dtype else d.to(out_dtype)diff --git a/exllamav3/modules/gr_fn/gr_mix_hip.py b/exllamav3/modules/gr_fn/gr_mix_hip.pyindex 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, subprocessimport torchfrom 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_ARCHSfrom 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/module.py b/exllamav3/modules/module.pyindex 3cbcf2a..1c7a8c3 100644--- a/exllamav3/modules/module.py+++ b/exllamav3/modules/module.py@@ -102,12 +102,21 @@ class Module(ABC):def prepare_for_device(self, x: torch.Tensor, params: dict) -> torch.Tensor:select_exec_device(self.device)if x.device != self.device:- # Pinned CPU sources (e.g. the generator's staged input IDs) upload without- # blocking the host; the copy is stream-ordered ahead of the consuming kernels.- # Device-to-device moves go through to_device, which bounces them via host memory- # on platforms where peer copies corrupt data (probed, or EXLLAMA_NO_P2P_COPY)- nb = x.device.type == "cpu" and x.is_pinned()- x = to_device(x, self.device, non_blocking = nb)+ dev = torch.device(self.device) if self.device is not None else None+ # The contiguous layer split installs a bridge on the config: a front<->main+ # crossing is host-staged on the devices' own compute streams and never blocks+ # the host (see exllamav3/bridge.py).+ bridge = getattr(self.config, "device_bridge", None) if dev is not None else None+ if bridge is not None and x.device.type == "cuda" and dev.type == "cuda":+ nbytes = x.numel() * x.element_size()+ x = bridge.hop_chunk(x, dev) if nbytes >= 2 ** 20 else bridge.hop(x, dev)+ else:+ # Pinned CPU sources (e.g. the generator's staged input IDs) upload without+ # blocking the host; the copy is stream-ordered ahead of the consuming kernels.+ # Device-to-device moves go through to_device, which bounces them via host memory+ # on platforms where peer copies corrupt data (probed, or EXLLAMA_NO_P2P_COPY)+ nb = x.device.type == "cpu" and x.is_pinned()+ x = to_device(x, self.device, non_blocking = nb)return xdef get_qmaps(self):diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.pyindex 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, subprocessimport torchfrom 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_ARCHSfrom 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 Falsets = (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 Falsediff --git a/exllamav3/modules/qsa_indexer.py b/exllamav3/modules/qsa_indexer.pyindex 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.Tensorreturn 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 = Trueexcept 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 okdef 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 * 4and (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_hipo = 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 Noneand tq is None and qc[2] == 8 and qc[3] == 8 and bsz == 1 and seq >= 64 and seq <= 4096 * 4and (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 backfrom .attention_fn.qdeq_triton import qsa_prefill_q8n_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 Noneand tq is not None and bsz == 1 and seq >= 64 and seq <= 4096 * 4and (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_hipdiff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.pynew file mode 100644index 0000000..c6b20a4--- /dev/null+++ b/exllamav3/serve_split.py@@ -0,0 +1,259 @@+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 or+hardware-specific default lives here: a component is declared with a name and,+optionally, a policy. Devices are chosen by position (``cuda:N``, ``gfxXXXX``,+UUID or name); either device may serve ``part0`` or ``part1``.++This module stays pure stdlib at import: adapters must be able to apply their+serving environment before ``exllamav3`` (and therefore torch) is imported, so the+exllamav3 imports are deliberately deferred to call time.+"""++import argparse+import os+import time+from dataclasses import dataclass+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from exllamav3.device_map import ComponentMap, ComponentPolicy, SplitPlan++# Load-time slab held on the part0 device. A tuning value, not a hardware rule:+# size it to the part0 card (Stage 5 derives it from the device total).+DEFAULT_PART0_RESERVE_GB = 1.2++# Split mode runs eager until per-segment capture lands (Stage 6). A whole-forward+# or per-block graph must never span the host-staged bridge between segments.+# Deferred prefill residual fusions keep a pending state on the producing stream;+ # the next block may be on the other device, beyond the bridge. Split mode runs+ # the unfused path (same numerics, no cross-stream pending tensor).+SPLIT_UNSAFE_ENV = {+ "EXL3_PF_HC_FUSE": "0",+ "EXL3_PF_GR_FUSE": "0",+ "EXL3_GR_PF_FUSE": "0",+}++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_part0_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"part0 layers must be 0, N or auto, not {value!r}") from exc+++@dataclass+class SplitSettings:+ part0_layers: int | str = 0+ part0_device: str = "auto"+ part1_device: str = "auto"+ endcaps: bool = True+ part0_reserve_gb: float = DEFAULT_PART0_RESERVE_GB+ preset: str = "auto"+ split_graphs: str = "auto"++ @property+ def enabled(self) -> bool:+ return self.part0_layers == "auto" or (isinstance(self.part0_layers, int) and self.part0_layers > 0)++ @property+ def auto(self) -> bool:+ return self.part0_layers == "auto"++ def describe(self) -> str:+ return (f"part0_layers={self.part0_layers} part1_device={self.part1_device} "+ f"part0_device={self.part0_device} "+ f"endcaps={'on' if self.endcaps else 'off'} "+ f"reserve={self.part0_reserve_gb:.2f}GiB preset={self.preset} "+ f"graphs={self.split_graphs}")+++def add_split_arguments(parser: argparse.ArgumentParser) -> None:+ parser.add_argument("--part0-layers", default = None,+ help = "contiguous layer split: first N transformer layers on the part0 device; "+ "auto = fit from actual bytes; 0 = off (default: KYOJIN_PART0_LAYERS, else 0)")+ parser.add_argument("--part1-device", default = None,+ help = "part1 device (the rest of the layers): auto, gfxXXXX, cuda:N or a "+ "UUID/name substring (default: KYOJIN_PART1_DEVICE, else auto = cuda:0)")+ parser.add_argument("--part0-device", default = None,+ help = "part0 device (the first N layers): auto, gfxXXXX, cuda:N or a UUID/name "+ "substring (default: KYOJIN_PART0_DEVICE, else auto = the only other device). "+ "cuda:N is the torch index after HIP_VISIBLE_DEVICES; either device may "+ "serve part0 or part1")+ 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 part0 device (default: KYOJIN_ENDCAPS, else on)")+ parser.add_argument("--part0-reserve-gb", type = float, default = None,+ help = "VRAM held as a load-time slab on the part0 device for workspace; a "+ "tuning value, not a hardware rule (default: KYOJIN_PART0_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, "part0_layers", None)+ if raw is None:+ raw = os.environ.get("KYOJIN_PART0_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, "part0_reserve_gb", None)+ if reserve is None:+ reserve = float(os.environ.get("KYOJIN_PART0_RESERVE_GB", str(DEFAULT_PART0_RESERVE_GB)))+ return SplitSettings(+ part0_layers = parse_part0_layers(raw),+ part1_device = getattr(args, "part1_device", None) or os.environ.get("KYOJIN_PART1_DEVICE") or "auto",+ part0_device = getattr(args, "part0_device", None) or os.environ.get("KYOJIN_PART0_DEVICE") or "auto",+ endcaps = bool(endcaps),+ part0_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(SPLIT_UNSAFE_ENV)+ forced.update(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 and deferred residual fusions forced off for split mode"+ + (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.part0_device, settings.part1_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,+ part0_layers = self.settings.part0_layers,+ part0_reserve_gb = self.settings.part0_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 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 part0 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 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/exllamav3/util/arch_list.py b/exllamav3/util/arch_list.pyindex 704f597..8e072eb 100644--- a/exllamav3/util/arch_list.py+++ b/exllamav3/util/arch_list.py@@ -59,6 +59,25 @@ def select_device(device=None) -> int:GFX115_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))++# Arches where the fused KDA output path is known nondeterministic in split mode.+# gfx12 today; the split gate and the adapters that size the fallback workspace+# must use this one predicate so they cannot drift.+KDA_FUSED_UNSTABLE_PREFIXES = ("gfx12",)+++def kda_fused_output_unstable(arch: str | None, unknown: bool = True) -> bool:+ """Whether the fused KDA output path is known unsafe on this arch.++ An unreadable/empty arch is conservatively treated as unstable by default, so+ split mode takes the deterministic chain and adapters size its workspace.+ """+ key = (arch or "").strip().lower()+ if not key:+ return bool(unknown)+ return key.startswith(KDA_FUSED_UNSTABLE_PREFIXES)++_support_cache = {}diff --git a/exllamav3/util/device_copy.py b/exllamav3/util/device_copy.pyindex 6fb11a3..7f4ffee 100644--- a/exllamav3/util/device_copy.py+++ b/exllamav3/util/device_copy.py@@ -20,6 +20,11 @@ whether the copy can go direct or has to bounce through host memory:EXLLAMA_NO_P2P_COPY=0 -> always direct, never probeBoth directions of a pair are probed together, since the fabric can fail one way only.+A probe that raises (some drivers reject the peer copy instead of corrupting) counts as+a failed verdict and the pair bounces through host memory. A later direct-copy failure+also caches the bounce verdict and retries through the host. A device OOM is re-raised+from both the probe and the direct copy: bouncing through host memory would not help an+exhausted device, so no verdict is cached for it."""_env = os.environ.get("EXLLAMA_NO_P2P_COPY")@@ -32,16 +37,36 @@ stats = {"direct": 0, "bounced": 0, "probes": 0}def _probe_direct(src: torch.device, dst: torch.device) -> tuple[bool, bool]:"""Move random data src -> dst -> src. Returns (src->dst ok, dst->src ok), each judged on- the host so the verdict never depends on a peer copy itself."""- a = torch.rand(64, dtype = torch.float32, device = src)- b = a.to(dst)- c = b.to(src)- torch.cuda.synchronize(src)- torch.cuda.synchronize(dst)- a_h = a.cpu()- fwd_ok = torch.equal(a_h, b.cpu())- bwd_ok = fwd_ok and torch.equal(a_h, c.cpu())- return fwd_ok, bwd_ok+ the host so the verdict never depends on a peer copy itself.++ A probe is diagnostic. Some drivers raise instead of silently corrupting when the+ peer path is broken; treat any probe failure as "bounce" rather than letting the+ diagnostic turn the first real cross-device move into a crash. A device OOM is+ re-raised (and caches no verdict): bouncing cannot help an exhausted device.+ """+ try:+ a = torch.rand(64, dtype = torch.float32, device = src)+ b = a.to(dst)+ c = b.to(src)+ torch.cuda.synchronize(src)+ torch.cuda.synchronize(dst)+ a_h = a.cpu()+ fwd_ok = torch.equal(a_h, b.cpu())+ bwd_ok = fwd_ok and torch.equal(a_h, c.cpu())+ return fwd_ok, bwd_ok+ except (torch.OutOfMemoryError, torch.cuda.OutOfMemoryError):+ raise # let a real OOM surface, do not cache a verdict+ except Exception as exc: # noqa: BLE001 - diagnostic must not crash+ print(f" !! P2P probe between {src} and {dst} failed "+ f"({type(exc).__name__}: {exc}); routing through system memory "+ f"(see EXLLAMA_NO_P2P_COPY)")+ return False, False+++def _mark_bounce(src: torch.device, dst: torch.device) -> None:+ with _lock:+ _verdicts[(src.index, dst.index)] = True+ _verdicts[(dst.index, src.index)] = Truedef needs_bounce(src: torch.device, dst: torch.device) -> bool:@@ -82,7 +107,21 @@ def to_device(t: torch.Tensor, device: torch.device | str | int, non_blocking: bif needs_bounce(t.device, device):stats["bounced"] += 1return t.cpu().to(device)+ try:+ out = t.to(device, non_blocking = non_blocking)+ except (torch.OutOfMemoryError, torch.cuda.OutOfMemoryError):+ raise # device OOM is not a fabric fault+ except RuntimeError as exc:+ # A probe can pass and a later direct copy can still fail on a flaky link.+ # Cache the safe verdict and retry through host memory.+ _mark_bounce(t.device, device)+ stats["bounced"] += 1+ print(f" !! Direct copy {t.device} -> {device} failed "+ f"({type(exc).__name__}: {exc}); routing through system memory "+ f"(see EXLLAMA_NO_P2P_COPY)")+ return t.cpu().to(device)stats["direct"] += 1+ return outreturn t.to(device, non_blocking = non_blocking)diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.pyindex 1916125..d1fefc9 100644--- a/exllamav3/vendor/fla/__init__.py+++ b/exllamav3/vendor/fla/__init__.py@@ -43,6 +43,28 @@ def _hip_ok(q, k, v, beta, Akk, Aqk, h0):return (all(t.dtype == bf and t.is_contiguous() for t in ts)and (h0 is None or h0.is_contiguous()))++_fused_stable = {} # arch gate per device index; read on every KDA prefill chunk+++def _fused_output_stable(device=None) -> bool:+ """Whether the fused Triton KDA output path is run-to-run deterministic on this arch.++ Measured nondeterministic on gfx12 (RDNA4): three loads produced three different+ greedy branches. Other supported archs keep the fused path. An unreadable arch+ is conservatively treated as unstable, so split mode uses the deterministic+ chain."""+ try:+ from exllamav3.util.arch_list import device_arch, device_index, kda_fused_output_unstable+ idx = device_index(device)+ ok = _fused_stable.get(idx)+ if ok is None:+ ok = _fused_stable[idx] = not kda_fused_output_unstable(device_arch(idx))+ return ok+ except Exception: # noqa: BLE001+ return False++# 1 / ln(2) as fla defines it (best fp32 approximation); gates are pre-scaled so the kernels use exp2RCP_LN2 = 1.4426950216@@ -182,6 +204,14 @@ def chunk_kda(# or if hipcc/module load fails; default 3, step 12). Chunks under 512 tokens# keep the fla chain: the one-program-per-head fused loop is ~0.14 ms slower there (T=255 sweep).fuse = int(os.environ.get("EXL3_KDA_FUSE", "3")) if K <= 128 and chunk_size == 64 and T >= 512 else 0+ if fuse and os.environ.get("KYOJIN_SPLIT_ACTIVE", "0") != "0" and not _fused_output_stable(q.device):+ # A layer split can run KDA on a gfx12 front and a different main device in one+ # process. The fused output path is not run-to-run deterministic on gfx12, and+ # its gfx11.5 HIP kernel cannot be JIT-built there (kda_fused_h_hip.supported()+ # declines, so _hip_ok already fell back to the Triton fuse path). Force the+ # deterministic fla chain on that arch only; keep it here, split-side, until the+ # gfx12 fused kernel lands.+ fuse = 0if fuse:# EXL3_KDA_HF=1 (default off, read per call): 16-row-chunk WY kernel (hip/kda_hf.hip, derived from hipfire's GDN kernel,# diagonal blocks computed in the kernel); replaces the intra kernels + kda_fused_h_o, incl. the prefix-cachediff --git a/tests/test_arch_list.py b/tests/test_arch_list.pyindex a1e6583..e947177 100644--- a/tests/test_arch_list.py+++ b/tests/test_arch_list.py@@ -68,3 +68,14 @@ Name: gfx1100arch_list.maybe_set_arch_list_env()assert arch_list.os.environ["PYTORCH_ROCM_ARCH"] == "gfx1201;gfx1100;gfx1030"+++def test_kda_fused_output_unstable_is_shared_and_conservative():+ assert arch_list.kda_fused_output_unstable("gfx1201")+ assert arch_list.kda_fused_output_unstable("gfx1200")+ assert not arch_list.kda_fused_output_unstable("gfx1151")+ assert not arch_list.kda_fused_output_unstable("gfx1100")+ # An unreadable arch is conservative by default, explicit opt-out for callers.+ assert arch_list.kda_fused_output_unstable("")+ assert arch_list.kda_fused_output_unstable(None)+ assert not arch_list.kda_fused_output_unstable("", unknown = False)diff --git a/tests/test_device_copy_.py b/tests/test_device_copy_.pyindex afa2632..84838a5 100644--- a/tests/test_device_copy_.py+++ b/tests/test_device_copy_.py@@ -61,6 +61,40 @@ to_device(y, d0)assert dc._verdicts == {(1, 0): False, (0, 1): True}, dc._verdictsdc._probe_direct = orig_probe+# 2c. a probe that raises is a bounce verdict, not a crash on the first real move+reset()+class _RaisingTensor:+ def to(self, *_args, **_kwargs):+ raise RuntimeError("hipErrorInvalidValue")++orig_rand = dc.torch.rand+dc.torch.rand = lambda *_args, **_kwargs: _RaisingTensor()+try:+ z = to_device(x, d1)+finally:+ dc.torch.rand = orig_rand+assert torch.equal(x.cpu(), z.cpu())+assert dc._verdicts == {(0, 1): True, (1, 0): True}, dc._verdicts+assert dc.stats == {"probes": 1, "bounced": 1, "direct": 0}, dc.stats++# 2d. a direct copy that raises after a passed probe is retried and cached as bounce+reset()+dc.FORCED = False+class _DirectFail:+ device = torch.device("cuda", 0)++ def to(self, _device, non_blocking = False):+ raise RuntimeError("hipErrorInvalidValue")++ def cpu(self):+ return torch.ones(8, dtype = torch.float32)++out = to_device(_DirectFail(), d1)+assert out.device == d1+assert dc._verdicts == {(0, 1): True, (1, 0): True}, dc._verdicts+assert dc.stats == {"probes": 0, "bounced": 1, "direct": 0}, dc.stats+dc.FORCED = None+# 3. the real probe agrees with the verdict recorded in 1reset()fwd_ok, bwd_ok = dc._probe_direct(d0, d1)diff --git a/tests/test_device_copy_oom_cpu.py b/tests/test_device_copy_oom_cpu.pynew file mode 100644index 0000000..ba5c52d--- /dev/null+++ b/tests/test_device_copy_oom_cpu.py@@ -0,0 +1,87 @@+"""CPU contract tests for util/device_copy.to_device's out-of-memory handling.++A device OOM must be re-raised (and cache no bounce verdict), not mistaken for a+broken P2P fabric: bouncing through host memory would not help an exhausted device,+so a cached verdict would be wrong and would stick for the process lifetime.+Runs without a GPU or the built extension.+"""+from __future__ import annotations++import sys+import types+from pathlib import Path++import pytest+import torch++ROOT = Path(__file__).resolve().parents[1]++[email protected](scope = "module")+def dc():+ 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")+ from exllamav3.util import device_copy as dc++ yield dc++ sys.modules.pop("exllamav3.util.device_copy", None)+ for name in added:+ sys.modules.pop(name, None)+++def clean(dc):+ old_forced = dc.FORCED+ dc.reset_verdicts()+ for k in dc.stats:+ dc.stats[k] = 0+ yield+ dc.FORCED = old_forced+ dc.reset_verdicts()+++def test_direct_copy_oom_re_raises_no_verdict(dc, clean):+ dc.FORCED = False++ class _OOMTensor:+ device = torch.device("cuda", 0)++ def to(self, _device, non_blocking = False):+ raise torch.OutOfMemoryError("CUDA out of memory")++ with pytest.raises(torch.OutOfMemoryError):+ dc.to_device(_OOMTensor(), torch.device("cuda", 1))++ assert dc._verdicts == {}+ assert dc.stats["probes"] == 0+ assert dc.stats["bounced"] == 0+ assert dc.stats["direct"] == 0+++def test_probe_oom_re_raises_no_verdict(dc, clean, monkeypatch):+ dc.FORCED = None++ class _Src:+ device = torch.device("cuda", 0)++ def _oom_rand(*_args, **_kwargs):+ raise torch.OutOfMemoryError("CUDA out of memory")++ monkeypatch.setattr(dc.torch, "rand", _oom_rand)+ with pytest.raises(torch.OutOfMemoryError):+ dc.to_device(_Src(), torch.device("cuda", 1))++ # needs_bounce bumps `probes` before the probe runs; the raise happens inside it,+ # before any verdict is stored.+ assert dc._verdicts == {}+ assert dc.stats["probes"] == 1\ No newline at end of filediff --git a/tests/test_embedding_event.py b/tests/test_embedding_event.pynew file mode 100644index 0000000..cb760eb--- /dev/null+++ b/tests/test_embedding_event.py@@ -0,0 +1,158 @@+"""CPU regression test for the shared CPU-embedding upload event.++A split places the target's first layer and the MTP block on different devices while+both gather from the same CPU-resident embedding table. `_narrow_ev` must belong to+the device it is recorded on, so it has to be recreated when the upload device changes.+The test fakes `torch.cuda.Event`/`torch.cuda.device`, so it runs without a GPU: the+bug was a torch-side device mismatch, not a kernel issue.+"""+from __future__ import annotations++import importlib.util+import sys+import types+from pathlib import Path+from types import SimpleNamespace++import pytest+import torch++ROOT = Path(__file__).resolve().parents[1]+++def _package(name: str, path: Path):+ module = types.ModuleType(name)+ module.__path__ = [str(path)]+ return module+++def _registered(name: str, **attrs):+ module = types.ModuleType(name)+ for key, value in attrs.items():+ setattr(module, key, value)+ sys.modules[name] = module+ return module+++class _StubModule:+ def __init__(self, config, key, layer_idx = None):+ self.config = config+ self.key = key+ self.layer_idx = layer_idx+ self.caps = {}+ self.device = None++[email protected](scope = "module")+def embedding_module():+ """Load `embedding.py` with stub exllamav3 packages (the real package pulls in the extension)."""+ saved = dict(sys.modules)+ try:+ sys.modules["exllamav3"] = _package("exllamav3", ROOT / "exllamav3")+ modules = _package("exllamav3.modules", ROOT / "exllamav3" / "modules")+ modules.Module = _StubModule+ sys.modules["exllamav3.modules"] = modules+ sys.modules["exllamav3.model"] = _package("exllamav3.model", ROOT / "exllamav3" / "model")+ sys.modules["exllamav3.util"] = _package("exllamav3.util", ROOT / "exllamav3" / "util")+ sys.modules["exllamav3.tokenizer"] = _package(+ "exllamav3.tokenizer", ROOT / "exllamav3" / "tokenizer")+ _registered("exllamav3.model.config", Config = object)+ _registered("exllamav3.model.model_tp_alloc", TPAllocation = object)+ _registered("exllamav3.util.tensor", to2 = lambda x, *_a, **_k: x)+ _registered("exllamav3.util.device_copy", to_device = lambda x, device: x.to(device))+ _registered("exllamav3.tokenizer.mm_embedding",+ FIRST_MM_EMBEDDING_INDEX = 1, mm_rows = None)++ spec = importlib.util.spec_from_file_location(+ "exllamav3.modules.embedding", ROOT / "exllamav3" / "modules" / "embedding.py")+ assert spec is not None and spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ sys.modules[spec.name] = module+ spec.loader.exec_module(module)+ yield module+ finally:+ sys.modules.clear()+ sys.modules.update(saved)+++def _embedding(module):+ return module.Embedding(config = None, key = "model.embed_tokens",+ vocab_size = 16, hidden_size = 4)+++class _FakeTransfer:+ """The only tensor API `_upload_narrow` uses."""+ dtype = torch.float16++ def to(self, *_args, **_kwargs):+ return self+++def _fake_cuda(monkeypatch, created, contexts):+ class Event:+ def __init__(self):+ self.records = 0++ def record(self):+ self.records += 1++ class DeviceContext:+ def __init__(self, device):+ self.device = torch.device(device)++ def __enter__(self):+ contexts.append(self.device)++ def __exit__(self, *_exc):+ return False++ def make_event(*_args, **_kwargs):+ created.append(Event())+ return created[-1]++ monkeypatch.setattr(torch.cuda, "Event", make_event)+ monkeypatch.setattr(torch.cuda, "device", DeviceContext)+++def test_upload_event_is_recreated_when_device_changes(embedding_module, monkeypatch):+ emb = _embedding(embedding_module)+ created, contexts = [], []+ _fake_cuda(monkeypatch, created, contexts)+ ids = torch.zeros(4, dtype = torch.long)+ y = _FakeTransfer()++ emb._upload_narrow(y, ids, torch.float16, torch.device("cuda:0"))+ first = emb._narrow_ev+ assert len(created) == 1 and first.records == 1+ assert emb._narrow_ev_device == torch.device("cuda:0")++ # Same device: reuse the event (the steady-state upload path).+ emb._upload_narrow(y, ids, torch.float16, torch.device("cuda:0"))+ assert len(created) == 1 and first.records == 2++ # The MTP block's device differs: the old event would fail to record on it.+ emb._upload_narrow(y, ids, torch.float16, torch.device("cuda:1"))+ second = emb._narrow_ev+ assert len(created) == 2 and second is not first+ assert first.records == 2 and second.records == 1+ assert emb._narrow_ev_device == torch.device("cuda:1")++ emb._upload_narrow(y, ids, torch.float16, torch.device("cuda:1"))+ assert len(created) == 2 and second.records == 2+ assert contexts == [torch.device("cuda:0")] * 3 + [torch.device("cuda:1")] * 3+++def test_gather_reallocation_forgets_the_event_device(embedding_module, monkeypatch):+ emb = _embedding(embedding_module)+ emb.embedding = SimpleNamespace(weight = torch.zeros(16, 4, dtype = torch.float16))+ emb._narrow_buf = None+ emb._narrow_ev = object()+ emb._narrow_ev_device = torch.device("cuda:0")++ buf = torch.empty((2, 4), dtype = torch.float16)+ monkeypatch.setattr(torch, "empty", lambda *_a, **_k: buf)+ monkeypatch.setattr(torch, "index_select", lambda _w, _dim, _idx, out = None: out)++ emb._gather_narrow(torch.zeros(2, dtype = torch.long))+ assert emb._narrow_ev is None+ assert emb._narrow_ev_device is Nonediff --git a/tests/test_multi_device_jit.py b/tests/test_multi_device_jit.pyindex 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.pynew file mode 100644index 0000000..fe1610e--- /dev/null+++ b/tests/test_split_plan_cpu.py@@ -0,0 +1,597 @@+"""CPU contract tests for the universal split core.++The placement rules, endcap allowlist, auto-N arithmetic and the layout-neutral+part0 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 FakeRecurrent:+ def __init__(self, size, device):+ self.size = size+ self.device = device++ 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(+ part1 = torch.device("cuda", 0),+ part0 = torch.device("cuda", 1),+ part1_arch = "gfx1151",+ part0_arch = "gfx1201",+ )+++def _infos(dm, *pairs):+ """Synthetic device inventory: (arch, optional name/uuid) per device index."""+ out = []+ for i, item in enumerate(pairs):+ if isinstance(item, str):+ arch, name, uuid = item, f"device-{i}", ""+ else:+ arch = item[0]+ name = item[1] if len(item) > 1 else f"device-{i}"+ uuid = item[2] if len(item) > 2 else ""+ out.append(dm.DeviceInfo(index = i, name = name, arch = arch, uuid = uuid))+ return out+++def clean_split_env(monkeypatch):+ for key in ("KYOJIN_PART0_DEVICE", "KYOJIN_PART1_DEVICE", "KYOJIN_PART0_LAYERS", "KYOJIN_ENDCAPS"):+ monkeypatch.delenv(key, raising = False)+++def _glm_model():+ embedding = FakeModule("model.language_model.embed_tokens", caps = {"prefer_cpu": True})+ expand = FakeModule("hc_expand")+ 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.part0_eligible and text.endcaps_part0+ assert "RMSNorm" in text.endcap_types and "lm_head" in text.endcap_key_suffixes+ assert mtp.kind == "mtp" and mtp.whole_component and mtp.part0_eligible+ assert aux.kind == "aux" and not aux.part0_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: part1, 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 part1+ assert devices["lm_head"] == torch.device("cuda", 0)+ assert devices["ngram"] == torch.device("cuda", 0)++ all_part0 = dm.ComponentMap.from_model(model, 4, False, _devices(dm), component = "text")+ devices = {m.key: all_part0.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.part0_layers == 2 and cmap.enabled+++def test_whole_component_places_every_module_part0_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_whole_component_reports_only_placed_devices(split_modules):+ dm, _bridge, _split = split_modules+ mtp = FakeModel([+ FakeModule("mtp.embed", caps = {"prefer_cpu": True}),+ FakeModule("mtp.pre", caps = {}),+ FakeModule("mtp.block.0", layer_idx = 0),+ 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 on.placed_devices == [torch.device("cuda", 1)]+ assert off.placed_devices == [torch.device("cuda", 0)]+ assert torch.device("cpu") not in on.placed_devices + off.placed_devices+++def test_module_bytes_uses_compile_or_alt_key_when_prefix_is_empty(split_modules):+ dm, _bridge, _split = split_modules+ stc = FakeSTC({"embed_tokens": 456})+ head = FakeModule("hc_head")+ head.get_compile_sizes = lambda s: [123]+ assert dm._module_bytes(head, stc) == 123+ tied = FakeModule("lm_head")+ tied.alt_key = "embed_tokens"+ assert dm._module_bytes(tied, stc) == 456+++def test_policy_can_disable_endcap_part0(split_modules):+ dm, _bridge, _split = split_modules+ model = _glm_model()+ policy = dm.component_policy("text", endcaps_part0 = False)+ cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text", policy = policy)+ devices = {m.key: cmap.device_for(m) for m in model.modules}+ assert devices["hc_expand"] == torch.device("cuda", 0)+ assert devices["model.language_model.norm"] == torch.device("cuda", 0)+ assert devices["model.language_model.layers.0"] == torch.device("cuda", 1)+++def test_recurrent_placement_audit_reads_state_device(split_modules):+ dm, _bridge, _split = split_modules+ model = FakeModel([FakeModule("layer.0", layer_idx = 0)])+ cache = FakeCache()+ cache.recurrent_layers[(0, 0)] = FakeRecurrent(1024, torch.device("cuda", 0))+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 1,+ logger = lambda *_a: None)+ plan.add("text", model, cache = cache)+ plan.build()+ assert "text" in plan.audit_caches()++ cache.recurrent_layers[(0, 0)] = FakeRecurrent(1024, torch.device("cuda", 1))+ assert plan.audit_caches() == {}+++def test_auto_n_is_capped_for_long_context(split_modules, monkeypatch):+ dm, _bridge, _split = split_modules+ gib = dm.GIB+ model = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])+ cfg = FakeConfig({f"layer.{i}": gib for i in range(4)})+ monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(16 * gib))+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",+ part0_reserve_gb = 1.0, auto_cap = 2, logger = lambda *_a: None)+ plan.add("text", model, config = cfg)+ plan.build()+ assert plan.part0_layers == 2+++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, part0_layers = "auto",+ part0_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.part0_layers == 3+ assert plan.map("text").part0_layers == 3++ plan_off = dm.SplitPlan(_devices(dm), endcaps = False, part0_layers = "auto",+ part0_reserve_gb = 1.0, logger = lambda *_a: None)+ plan_off.add("text", model, config = cfg, cache = cache)+ plan_off.build()+ assert plan_off.part0_layers == 3+++def test_part0_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",+ part0_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_part0_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")+ monkeypatch.setenv("KYOJIN_SPLIT_ACTIVE", "0")+ part1, part0 = torch.device("cuda", 0), torch.device("cuda", 1)+ cfg = SimpleNamespace()+ draft_cfg = SimpleNamespace()++ b1 = bridge_mod.install_bridge(cfg, part1 = part1, part0 = part0)+ b2 = bridge_mod.install_bridge(cfg, part1 = part1, part0 = part0)+ b3 = bridge_mod.install_bridge(draft_cfg, part1 = part1, part0 = part0)++ 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 == (part1, part0)+ assert os.environ["KYOJIN_SPLIT_ACTIVE"] == "1"++ # The pair is keyword-only so a caller cannot silently pass (part1, part0) backwards.+ with pytest.raises(TypeError):+ bridge_mod.install_bridge(cfg, part1, part0)++ single = SimpleNamespace()+ assert bridge_mod.install_bridge(single, part1 = part1, part0 = None) is None+ assert single.split_active is False+++def test_disabled_bridge_forces_host_bounce(split_modules, monkeypatch):+ _dm, bridge_mod, _split = split_modules+ from exllamav3.util import device_copy++ monkeypatch.setenv("KYOJIN_BRIDGE", "0")+ old = device_copy.FORCED+ device_copy.FORCED = None+ try:+ cfg = SimpleNamespace()+ assert bridge_mod.install_bridge(+ cfg, part1 = torch.device("cuda", 0), part0 = torch.device("cuda", 1)) is None+ assert cfg.split_active is True+ assert device_copy.FORCED is True+ finally:+ device_copy.FORCED = old+++def test_named_preset_is_applied_by_the_plan(split_modules, monkeypatch):+ dm, _bridge, split = split_modules+ monkeypatch.setenv("EXL3_TEST_PRESET", "0")+ old = split.SPLIT_PRESETS.get("glm", {})+ split.SPLIT_PRESETS["glm"] = {"EXL3_TEST_PRESET": "1"}+ try:+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 1,+ preset = "glm", logger = lambda *_a: None)+ plan.add("text", _glm_model())+ plan.build()+ assert os.environ["EXL3_TEST_PRESET"] == "1"+ finally:+ split.SPLIT_PRESETS["glm"] = old++[email protected]("archs", [+ ("gfx1100", "gfx1101"), # RDNA3+ ("gfx1150", "gfx1151"), # RDNA3.5+ ("gfx1200", "gfx1201"), # RDNA4+ ("gfx1151", "gfx1100"), # mixed, reversed+ ("gfx1201", "gfx1201"), # same arch+ ("gfx1100", "gfx1100"),+ ("", "sm_90"), # unknown / CUDA-style names: selection only+])+def test_auto_selection_is_positional_and_arch_independent(split_modules, clean_split_env, archs):+ dm, _bridge, _split = split_modules+ devices = dm.resolve_devices(devices = _infos(dm, *archs))+ assert devices.part1 == torch.device("cuda", 0)+ assert devices.part0 == torch.device("cuda", 1)+ assert devices.part1_arch == archs[0] and devices.part0_arch == archs[1]+ assert [d.index for d in devices.inventory] == [0, 1]+++def test_explicit_selectors_support_both_positions(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ infos = _infos(dm, "gfx1151", "gfx1201")++ mixed = dm.resolve_devices("cuda:1", "cuda:0", devices = infos)+ assert (mixed.part1_arch, mixed.part0_arch) == ("gfx1151", "gfx1201")++ reversed_pair = dm.resolve_devices("gfx1151", "gfx1201", devices = infos)+ assert reversed_pair.part1 == torch.device("cuda", 1)+ assert reversed_pair.part0 == torch.device("cuda", 0)+ assert (reversed_pair.part1_arch, reversed_pair.part0_arch) == ("gfx1201", "gfx1151")++ by_name_uuid = dm.resolve_devices("device-1", "device-0", devices = infos)+ assert by_name_uuid.part1 == torch.device("cuda", 0)+ assert by_name_uuid.part0 == torch.device("cuda", 1)+++def test_explicit_part0_with_auto_part1_uses_the_other_device(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ infos = _infos(dm, "gfx1151", "gfx1201")++ by_index = dm.resolve_devices("cuda:0", devices = infos)+ assert by_index.part1 == torch.device("cuda", 1)+ assert by_index.part0 == torch.device("cuda", 0)++ by_arch = dm.resolve_devices("gfx1151", devices = infos)+ assert by_arch.part1 == torch.device("cuda", 1)+ assert by_arch.part0 == torch.device("cuda", 0)++ many = _infos(dm, "gfx1100", "gfx1151", "gfx1201")+ with pytest.raises(RuntimeError, match = "set KYOJIN_PART1_DEVICE"):+ dm.resolve_devices("cuda:0", devices = many)+++def test_uuid_and_name_substring_selectors(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ infos = _infos(+ dm,+ ("gfx1201", "AMD Radeon RX 9070 XT", "aa-bb-cc"),+ ("gfx1151", "AMD Radeon 8060S", "dd-ee-ff"),+ )+ dev = dm.resolve_devices("aa-bb-cc", "8060s", devices = infos)+ assert dev.part1 == torch.device("cuda", 1)+ assert dev.part0 == torch.device("cuda", 0)+++def test_part1_device_env_is_honoured(split_modules, clean_split_env, monkeypatch):+ dm, _bridge, _split = split_modules+ monkeypatch.setenv("KYOJIN_PART1_DEVICE", "cuda:1")+ dev = dm.resolve_devices(devices = _infos(dm, "gfx1151", "gfx1201"))+ assert dev.part1 == torch.device("cuda", 1)+ assert dev.part0 == torch.device("cuda", 0)+++def test_one_device_fails_clearly(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ with pytest.raises(RuntimeError, match = "two devices"):+ dm.resolve_devices(devices = _infos(dm, "gfx1151"))+++def test_three_devices_require_an_explicit_part0(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ infos = _infos(dm, "gfx1100", "gfx1151", "gfx1201")+ with pytest.raises(RuntimeError, match = "3 devices.*--part0-device"):+ dm.resolve_devices(devices = infos)+ dev = dm.resolve_devices("cuda:2", "cuda:1", devices = infos)+ assert dev.part1 == torch.device("cuda", 1)+ assert dev.part0 == torch.device("cuda", 2)+++def test_same_device_and_bad_selectors_fail_clearly(split_modules, clean_split_env):+ dm, _bridge, _split = split_modules+ infos = _infos(dm, "gfx1151", "gfx1201")+ with pytest.raises(RuntimeError, match = "same device"):+ dm.resolve_devices("cuda:0", "cuda:0", devices = infos)+ with pytest.raises(RuntimeError, match = "no such device"):+ dm.resolve_devices("cuda:9", devices = infos)+ with pytest.raises(RuntimeError, match = "did not match any device"):+ dm.resolve_devices("gfx9999", devices = infos)+++def test_settings_parse_part1_device_and_keep_split_off_off(split_modules, clean_split_env, monkeypatch):+ dm, _bridge, split = split_modules+ monkeypatch.setenv("KYOJIN_PART1_DEVICE", "cuda:1")+ args = SimpleNamespace(part0_layers = None, part0_device = None, part1_device = None,+ endcaps = None, split_preset = None, split_graphs = None,+ part0_reserve_gb = None)+ settings = split.settings_from_namespace(args)+ assert settings.part1_device == "cuda:1"+ assert settings.enabled is False++ args.part1_device = "gfx1100"+ args.part0_device = "gfx1151"+ args.part0_layers = "2"+ settings = split.settings_from_namespace(args)+ assert (settings.part1_device, settings.part0_device) == ("gfx1100", "gfx1151")+ assert settings.enabled is True+++def test_split_off_does_not_touch_device_selection(split_modules, monkeypatch):+ dm, _bridge, split = split_modules++ def boom(*_a, **_k):+ pytest.fail("split off must not enumerate or resolve devices")++ monkeypatch.setattr(dm, "resolve_devices", boom)+ controller = split.SplitController(split.SplitSettings(part0_layers = 0,+ part1_device = "cuda:9",+ part0_device = "cuda:9"),+ logger = lambda *_a: None)+ assert controller.devices is None+ assert controller.plan is None+++def test_split_core_and_help_name_no_hardware(split_modules):+ for rel in ("exllamav3/device_map.py", "exllamav3/serve_split.py"):+ text = (ROOT / rel).read_text()+ for name in ("gfx1151", "gfx1201", "gfx1100", "9070", "8060S", "Strix", "eGPU", "iGPU", "USB4"):+ assert name not in text, f"{rel} still names {name}"+++def _load_split_eval():+ path = ROOT / "tools" / "strix_halo" / "split_eval.py"+ spec = importlib.util.spec_from_file_location("split_eval_harness", path)+ assert spec is not None and spec.loader is not None+ mod = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(mod)+ return mod+++def test_harness_graph_env_matches_shared_list(split_modules):+ _dm, _bridge, split = split_modules+ mod = _load_split_eval()+ assert set(mod.GRAPH_ENV_OFF) == set(split.GRAPH_ENV_OFF)+++def test_harness_default_part0_layers_depends_on_context(monkeypatch):+ mod = _load_split_eval()+ for ctx, expected in ((131072, 5), (65536, 6)):+ monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", str(ctx)])+ assert mod.parse_args().part0_layers == expected+++def test_harness_part0_layers_are_explicit_flags(monkeypatch):+ mod = _load_split_eval()+ monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072", "--part0-layers", "7"])+ assert mod.parse_args().part0_layers == 7+ monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072",+ "--long-ctx-part0-layers", "3"])+ args = mod.parse_args()+ assert args.part0_layers == 3 and args.part0_layers_defaulted is True+++def test_adapter_unsafe_env_is_applied_and_logged(split_modules, monkeypatch):+ dm, _bridge, _split = split_modules+ monkeypatch.setenv("EXL3_TEST_UNSAFE", "0")+ policy = dm.component_policy("text", unsafe_env = (("EXL3_TEST_UNSAFE", "1"),))+ plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_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")+ for _k in ("EXL3_PF_HC_FUSE", "EXL3_PF_GR_FUSE", "EXL3_GR_PF_FUSE"):+ monkeypatch.setenv(_k, "1")+ off = split.SplitSettings(part0_layers = 0)+ assert off.enabled is False+ assert split.apply_split_env(off) == []+ assert os.environ["EXL3_BLOCK_GRAPH"] == "1"++ on = split.SplitSettings(part0_layers = "auto")+ assert on.enabled is True and on.auto is True+ split.apply_split_env(on)+ assert os.environ["EXL3_BLOCK_GRAPH"] == "0"+ # Deferred residual fusions cannot cross the host-staged bridge.+ assert os.environ["EXL3_PF_HC_FUSE"] == "0"+ assert os.environ["EXL3_PF_GR_FUSE"] == "0"+ assert os.environ["EXL3_GR_PF_FUSE"] == "0"diff --git a/tools/glm/serve.py b/tools/glm/serve.pyindex 52ab922..562d5ff 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -25,6 +25,11 @@ from jinja2.sandbox import ImmutableSandboxedEnvironmentsys.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_part0_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)@@ -46,6 +51,21 @@ EH_SIDECAR_DEFAULT = "~/models/glm53-mtp-eh-proj-bf16.safetensors"# Name inside the model folder. Not *.safetensors, so the weight loader never indexes it as model weights# (same layout trick as uncensor_direction.st); the file is a normal safetensors file.EH_SIDECAR_IN_PACK = "mtp_eh_proj.st"+# GLM adapter tuning, deliberately outside the split core: on RDNA4 (gfx12) the+# split runs the deterministic fla KDA chain, whose long-context prefill workspace+# is not yet part of auto-N. Measured on a 16 GB gfx12 part0 card. This is a+# property of this adapter/part0 pair, not of the split; explicit --part0-layers+# always wins.+GLM_LONG_CTX = 65536+GLM_LONG_CTX_AUTO_CAP = 5+++def _glm_small_kda_part0(part0_arch: str | None) -> bool:+ """True when this part0 device runs the deterministic split KDA chain."""+ from exllamav3.util.arch_list import kda_fused_output_unstable+ return kda_fused_output_unstable(part0_arch)++# --sessions > 1 (several requests decode in one step): plain steps take the R-row exact paths (union MoE on the device table, R-row# GEMV, batched router) instead of per-expert eager loops, and 2..8-row verify blocks replay as graphs. Box 4 requests, same prompts:# plain 26.1 -> 40.7 tok/s aggregate, speculative 38.1 -> 42.5; one request alone and speculative text equal to the solo run unchanged.@@ -677,7 +697,11 @@ class ResidentEngine:image_cache_format: str = "fp32",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):+ image_cache_dir_lock_s: float = IMAGE_CACHE_DIR_LOCK_S,+ part0_layers: int | str = 0, part0_device: str | None = None,+ part1_device: str | None = None,+ endcaps: bool = True, part0_reserve_gb: float = 1.2,+ split_settings: SplitSettings | None = None):import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizerfrom exllamav3.generator import generator as GM@@ -707,6 +731,33 @@ class ResidentEngine:self.max_draft = num_draftself.config = Config.from_directory(model_path)self.model = Model.from_config(self.config)+ if split_settings is None:+ split_settings = SplitSettings(+ part0_layers = parse_part0_layers(part0_layers),+ part0_device = part0_device or "auto",+ part1_device = part1_device or "auto",+ endcaps = bool(endcaps), part0_reserve_gb = float(part0_reserve_gb))+ self.split = SplitController(split_settings, logger = lambda m: print(f"serve: {m}", flush=True))+ self.split_map = None+ if self.split.enabled:+ plan = self.split.build_plan()+ if plan is None or plan.devices.part0 is None:+ raise ValueError("layer split requested but no usable part0 device")+ print(f"serve: layer split: {split_settings.describe()}; "+ f"part1 {plan.devices.part1} ({plan.devices.part1_arch}), "+ f"part0 {plan.devices.part0} ({plan.devices.part0_arch})", flush=True)+ if split_settings.auto:+ if _glm_small_kda_part0(plan.devices.part0_arch) and max_ctx > GLM_LONG_CTX:+ # Auto-N's byte budget does not yet know the split KDA prefill+ # workspace; keep the measured-safe long-context cap until it does.+ plan.auto_cap = GLM_LONG_CTX_AUTO_CAP+ print(f"serve: layer split: auto-N capped at {GLM_LONG_CTX_AUTO_CAP} layers for "+ f"-c > {GLM_LONG_CTX} on this gfx12 part0: the split KDA prefill workspace "+ "is not in the byte budget (adapter tuning; pass --part0-layers N to "+ "override)", flush=True)+ else:+ print("serve: layer split: auto-N uncapped (part0 does not need the split "+ "KDA long-context reserve)", flush=True)self.tokenizer = Tokenizer.from_config(self.config)if os.environ.get("KYO_TOKCACHE", "8") == "0":self.pec = None@@ -746,13 +797,41 @@ class ResidentEngine:kernel_seed.install() # shipped Triton kernels for this Triton version: nothing to compile on a first startjit_log.install() # EXL3_LOG_JIT=1: one line per Triton compilestartup_health.stage("target weights")- self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())+ 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 part0 device (or auto-N found no layer that fits)")+ if split_settings.auto and self.split_map is not None:+ print(f"serve: layer split: auto-N chose {self.split_map.part0_layers} part0 layer(s) "+ f"for -c {ctx}", flush=True)+ if (self.split_map is not None and self.split_map.part0_layers > GLM_LONG_CTX_AUTO_CAP+ and max_ctx > GLM_LONG_CTX+ and _glm_small_kda_part0(plan.devices.part0_arch)):+ print(f"serve: warning: part0 layers > {GLM_LONG_CTX_AUTO_CAP} at -c > {GLM_LONG_CTX} "+ "is measured to OOM a 16 GB gfx12 part0 on long prefill (split KDA fallback "+ f"workspace); use --part0-layers {GLM_LONG_CTX_AUTO_CAP} for long-context split runs",+ flush=True)+ self.split.engage_budget()+ self.split.load("text", self.model, progressbar=False,+ callback=startup_health.load_callback(), max_chunk_size=4096)+ else:+ self.model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())if num_draft > 0:self.draft_model = Model.from_config(self.config, component="mtp")self.draft_cache = Cache(self.draft_model, max_num_tokens=ctx + 4096,max_history=max_history, max_batch_size=slots, **qkw)startup_health.stage("drafter weights")- self.draft_model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())+ if self.split.enabled:+ self.split.add("mtp", self.draft_model, config=self.config,+ cache=self.draft_cache, load_order=1)+ self.split.load("mtp", self.draft_model, progressbar=False,+ callback=startup_health.load_callback(), max_chunk_size=4096)+ else:+ self.draft_model.load(device="cuda:0", progressbar=False, callback=startup_health.load_callback())else: # --num-draft 0: plain decode, no drafterself.draft_model = self.draft_cache = Noneself.vision = None@@ -768,6 +847,13 @@ class ResidentEngine:if vision:self.vision = self._load_vision()self.supports_vision = self.vision is not None+ 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))+ 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 tableself.Generator = Generator# The loaded model and tokenizer are 1.1 M Python objects and every later gc.collect() walks them all: the Generator@@ -879,7 +965,13 @@ class ResidentEngine:try:startup_health.stage("vision tower")tower = Model.from_config(self.config, component="vision")- tower.load(device="cuda:0", 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="cuda:0", progressbar=False,+ callback=startup_health.load_callback())except Exception as exc: # noqa: BLE001print(f"serve: vision tower not loaded ({type(exc).__name__}: {exc}); image input disabled", flush=True)return None@@ -2134,6 +2226,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")+ 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")@@ -2179,6 +2272,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()+ 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 = 0elif args.cache_bits is None:@@ -2238,7 +2334,8 @@ def main() -> None:image_cache_bytes=image_cache_bytes, image_cache_items=args.image_cache_items,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)+ image_cache_dir_lock_s=args.image_cache_dir_lock_s,+ split_settings=split_settings)engine.row_budget = (5 if args.row_budget is None else args.row_budget) if args.sessions > 1 else 0template = 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.pynew file mode 120000index 0000000..5dcebfe--- /dev/null+++ b/tools/kyojin_serve_split.py@@ -0,0 +1 @@+../exllamav3/serve_split.py\ No newline at end of filediff --git a/tools/strix_halo/coherence_suite.py b/tools/strix_halo/coherence_suite.pyindex eb8d99b..aa00d83 100644--- a/tools/strix_halo/coherence_suite.py+++ b/tools/strix_halo/coherence_suite.py@@ -9,7 +9,11 @@ reason, the loop-guard verdicts used by tools/qwen/serve.py, the worst 20-gramrepetition count and whether EOS was reached.python tools/strix_halo/coherence_suite.py -m <model>- HIP_VISIBLE_DEVICES=1 python tools/strix_halo/coherence_suite.py -m <model> -n 512+ python tools/strix_halo/coherence_suite.py -m <model> -n 512++On the single-gfx1151 target no device variable is needed. On a multi-GPU box set+HIP_VISIBLE_DEVICES to the index whose gcnArchName matches the intended device; the+index order is a driver/boot property, so do not assume a fixed value.The model must fit the visible device (use the layer-split sibling for larger packs).diff --git a/tools/strix_halo/env.sh b/tools/strix_halo/env.shindex 9d7cf03..1a88c12 100755--- a/tools/strix_halo/env.sh+++ b/tools/strix_halo/env.sh@@ -94,19 +94,39 @@ if [ "${1:-}" = "--check" ]; thenexit 1fi"$EXL3_VENV/bin/python" - <<'PY'+import sysimport torch-p = torch.cuda.get_device_properties(0)print(f"torch {torch.__version__} hip {torch.version.hip}")-print(f"{p.name} / {p.gcnArchName} / warp={p.warp_size} / {p.total_memory/2**30:.1f} GiB / {p.multi_processor_count} CUs")-a = torch.randn(512, 512, dtype=torch.float16, device="cuda")+n = torch.cuda.device_count()+if n == 0:+ print("no HIP devices visible")+ sys.exit(1)++def key_of(p):+ # ROCm: gcnArchName ("gfx1151"); CUDA: sm_XY from major/minor.+ arch = getattr(p, "gcnArchName", "") or ""+ arch = arch.split(":", 1)[0]+ return arch or f"sm_{p.major}{p.minor}"++keys = []+for i in range(n):+ p = torch.cuda.get_device_properties(i)+ keys.append(key_of(p))+ warp = getattr(p, "warp_size", None)+ extra = f" / warp={warp}" if warp else ""+ print(f"[{i}] {p.name} / {keys[-1]}{extra} / "+ f"{p.total_memory/2**30:.1f} GiB / {p.multi_processor_count} CUs")+# gfx1151 is the primary target; with an eGPU visible it is not necessarily device 0.+target = keys.index("gfx1151") if "gfx1151" in keys else 0+print(f"checking device [{target}] ({keys[target]})")+a = torch.randn(512, 512, dtype=torch.float16, device=f"cuda:{target}")(a @ a).sum().item()torch.cuda.synchronize()print("GPU compute: OK")try:import exllamav3_extprint("exllamav3_ext: OK")- print("exl3_gemv_supported(0):", exllamav3_ext.exl3_gemv_supported(0),- "<- False on gfx1151 => reconstruct+hgemm fallback (expected)")+ print(f"exl3_gemv_supported({target}):", exllamav3_ext.exl3_gemv_supported(target))except ImportError as e:print("exllamav3_ext: NOT BUILT --", e)import exllamav3diff --git a/tools/strix_halo/gemv_perf_ab.py b/tools/strix_halo/gemv_perf_ab.pyindex 9171a4f..020508b 100644--- a/tools/strix_halo/gemv_perf_ab.py+++ b/tools/strix_halo/gemv_perf_ab.py@@ -64,8 +64,11 @@ launch as well as per config, so no first-launch-time decision can see aninherited value.Example:- HIP_VISIBLE_DEVICES=1 python tools/strix_halo/gemv_perf_ab.py \+ python tools/strix_halo/gemv_perf_ab.py \-m <model> --mode both --census --top 40 --sweep --verify --repeats 6++Select the GPU with HIP_VISIBLE_DEVICES=<index> if several are visible; pick the+index whose gcnArchName matches. Enumeration order is a driver/boot property."""import argparseimport contextlibdiff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.pynew file mode 100644index 0000000..27a6bf3--- /dev/null+++ b/tools/strix_halo/split_eval.py@@ -0,0 +1,420 @@+#!/usr/bin/env python3+"""Phase 4 correctness + first-decode-numbers harness for the contiguous layer split.++Runs the same fixed prompt battery through either the split (default) or a single-device+baseline (--baseline), saves the greedy token ids to JSON, and optionally compares two+saved runs token-for-token. It also measures decode t/s under --num-draft and can run a+long-context needle probe.++The split works on any two supported devices; use --part1-device/--part0-device to put+either device in either position. The context-dependent --part0-layers default is+harness tuning for a small part0 card, not a property of the split; pass --part0-layers+to choose N explicitly.++Usage (from the repo root, after `source tools/strix_halo/env.sh`):++ python tools/strix_halo/split_eval.py -m <pack> --out /tmp/split.json+ python tools/strix_halo/split_eval.py -m <pack> --baseline --no-graphs --out /tmp/base.json+ python tools/strix_halo/split_eval.py --compare /tmp/base.json /tmp/split.json+ python tools/strix_halo/split_eval.py -m <pack> --needle-depth 120000 --out /tmp/needle.json++The split run forces the graph paths off before exllamav3 is imported (Phase 4 owns+correctness; per-segment capture is Phase 6).+"""+from __future__ import annotations++import argparse+import json+import os+import sys+import time+++# Kept in sync with exllamav3/serve_split.py:GRAPH_ENV_OFF; the consistency test+# asserts the key sets match so a new graph flag cannot silently bypass this gate.+GRAPH_ENV_OFF = (+ "EXL3_BLOCK_GRAPH", "EXL3_BLOCK_GRAPH_MLA", "EXL3_BLOCK_GRAPH_VERIFY",+ "EXL3_BLOCK_GRAPH_DRAFT", "EXL3_BLOCK_GRAPH_ATTN", "EXL3_BLOCK_GRAPH_DEC_MOE",+ "EXL3_CUDA_GRAPH", "EXL3_HIP_GRAPH",+)++PROMPTS = [+ "What is the capital of France? Answer in one sentence.",+ "Write a Python function that reverses a linked list, with comments.",+ "Explain in three short sentences why the sky is blue.",+ "List five prime numbers between 50 and 100, separated by commas.",+ "A train leaves at 14:35 and arrives at 17:20. How long is the trip? Show your reasoning.",+ "Summarize the plot of Romeo and Juliet in exactly two sentences.",+]+PERF_PROMPTS = [+ "Explain in detail how the attention mechanism in a transformer works, including "+ "queries, keys, values and multi-head attention.",+ "Write a Python implementation of a binary heap with push, pop and heapify, with comments.",+ "Write a detailed summary of the causes and consequences of the Industrial Revolution.",+]+NEEDLE = "KX-4817-QM"+FILLER = (+ "The archive room was quiet except for the soft hum of the ventilation and the slow "+ "turning of a clock on the far wall. Shelves of ledgers ran from floor to ceiling, each "+ "volume labelled in a hand that had not been seen in decades. Visitors rarely came this "+ "far, and those who did usually left with more questions than they had brought. "+)+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser()+ p.add_argument("-m", "--model", default="/data/models/NicSir--GLM-5.3-Flash-EXL3-2.72bpw")+ p.add_argument("--baseline", action="store_true", help="single device (cuda:0), no layer split")+ p.add_argument("--part0-layers", type=int, default=None)+ p.add_argument("--part1-device", default="auto")+ p.add_argument("--part0-device", default="auto")+ p.add_argument("--long-ctx-threshold", type=int, default=65536,+ help="context above which the harness default part0-layer count changes")+ p.add_argument("--long-ctx-part0-layers", type=int, default=5,+ help="harness default for contexts above --long-ctx-threshold; measured on a "+ "small part0 card, not a property of the split")+ p.add_argument("--short-ctx-part0-layers", type=int, default=6,+ help="harness default at or below --long-ctx-threshold")+ p.add_argument("--endcaps", choices=("on", "off"), default="on")+ p.add_argument("--part0-reserve-gb", type=float, default=1.2)+ p.add_argument("--part1-reserve-gb", type=float, default=0.0)+ p.add_argument("-c", "--max-ctx", type=int, default=131072)+ p.add_argument("--num-draft", type=int, default=2)+ p.add_argument("--no-vision", action="store_true")+ p.add_argument("--no-graphs", action="store_true", help="force block/whole-forward graphs off (both modes)")+ p.add_argument("--no-budget", action="store_true", help="do not cap the per-device allocator (diagnostic: isolates reserve effects)")+ p.add_argument("--tokens", type=int, default=128)+ p.add_argument("--perf-tokens", type=int, default=256)+ p.add_argument("--perf-reps", type=int, default=1)+ p.add_argument("--needle-depth", type=int, default=0, help="run one needle probe at this many prompt tokens")+ p.add_argument("--bench-depth", type=int, default=0,+ help="also decode --perf-tokens at this prompt depth and report prefill/decode/acceptance")+ p.add_argument("--out", default=None, help="write the full JSON here")+ p.add_argument("--compare", nargs=2, metavar=("BASE", "SPLIT"),+ help="compare two saved runs: prompt ids and decode numbers")+ p.add_argument("--no-perf", action="store_true", help="skip the 3 decode timing prompts")+ args = p.parse_args()+ args.part0_layers_defaulted = args.part0_layers is None+ if args.part0_layers is None:+ # Harness tuning for memory, not a split property: a small part0 card cannot+ # hold N=6 plus the long-context workspace. Both values are explicit flags.+ args.part0_layers = (args.long_ctx_part0_layers if args.max_ctx > args.long_ctx_threshold+ else args.short_ctx_part0_layers)+ return args+++def configure_env(args: argparse.Namespace) -> None:+ """Set everything exllamav3 reads at import time, before the first import."""+ if args.no_graphs or not args.baseline:+ for k in GRAPH_ENV_OFF:+ os.environ[k] = "0"+ os.environ.setdefault("EXL3_MOE_CFG", "2")+ os.environ.setdefault("EXL3_HIP_PREFILL_MIN_ROWS", "2")+ # serve.py's SPEED_ENV: no dense-GEMM screening, so every run takes the same+ # (untuned, default) path instead of a per-process autotune winner.+ os.environ.setdefault("EXL3_DENSE_GEMM_TUNE", "0")+ os.environ.setdefault("EXL3_MOE_UNION_V2", "1")+ # Same optional unquantized MTP eh_proj as serve.py: raises draft acceptance, never output.+ if "EXL3_MTP_EH_FP16" not in os.environ:+ for path in (os.path.join(args.model, "mtp_eh_proj.st"),+ os.path.expanduser("~/models/glm53-mtp-eh-proj-bf16.safetensors")):+ if os.path.isfile(path):+ os.environ["EXL3_MTP_EH_FP16"] = path+ break+++def ids_of(text: str, tokenizer) -> torch.Tensor:+ p = f"[gMASK]<sop><|user|>\n{text}<|assistant|>\n"+ return tokenizer.encode(p, encode_special_tokens = True)+++def run_job(gen, job_cls, ids, n: int):+ import torch+ from exllamav3.generator.sampler import GreedySampler+ job = job_cls(input_ids = ids, max_new_tokens = n, sampler = GreedySampler(),+ stop_conditions = gen.model.config.eos_token_id_list)+ gen.enqueue(job)+ t0 = time.perf_counter()+ first = last = None+ toks = []+ text = ""+ accepted = rejected = 0+ while gen.num_remaining_jobs():+ for r in gen.iterate():+ if r.get("error"):+ raise RuntimeError(f"job error: {r['error']}")+ tid = r.get("token_ids")+ if tid is not None and tid.numel():+ if first is None:+ first = time.perf_counter()+ last = time.perf_counter()+ toks.append(tid.cpu())+ text += r.get("text", "")+ accepted += int(r.get("accepted_draft_tokens", 0))+ rejected += int(r.get("rejected_draft_tokens", 0))+ ttft = (first - t0) if first is not None else None+ ntok = sum(t.numel() for t in toks)+ return {+ "ids": torch.cat(toks, dim = -1).flatten().tolist() if toks else [],+ "text": text,+ "ttft_s": ttft,+ "decode_s": (last - first) if first is not None and last is not None and ntok > 1 else None,+ "tokens": ntok,+ "accepted": accepted,+ "rejected": rejected,+ }+++def build_needle(depth: int, tokenizer):+ """Prompt of about `depth` tokens with the passkey in the middle."""+ import torch+ head = "Read the document and answer the question that follows.\n\n"+ tail = "\n\nQuestion: What is the secret passkey in the document above? Reply with the passkey only.\n"+ p = tokenizer.encode(f"[gMASK]<sop><|user|>\n{head}", encode_special_tokens = True).flatten()+ q = tokenizer.encode(tail + "<|assistant|>\n", encode_special_tokens = True).flatten()+ filler_ids = tokenizer.encode(FILLER, encode_special_tokens = False).flatten()+ target = max(64, depth - int(p.numel() + q.numel()))+ reps = target // max(1, filler_ids.numel()) + 1+ ids = filler_ids.repeat(reps)[:target].clone()+ marker = tokenizer.encode(f"\nThe secret passkey is {NEEDLE}.\n", encode_special_tokens = False).flatten()+ mid = ids.numel() // 2+ ids = torch.cat((ids[:mid], marker, ids[mid:]), dim = -1)+ return torch.cat((p, ids, q), dim = -1).unsqueeze(0), NEEDLE+++def main() -> None:+ args = parse_args()+ if args.part0_layers_defaulted and not args.baseline:+ print(f"[harness] no --part0-layers given: using N={args.part0_layers} at -c "+ f"{args.max_ctx} (harness tuning, not a split property; override with "+ f"--part0-layers N or --long-ctx-part0-layers N)", flush=True)+ if args.compare:+ compare(args.compare[0], args.compare[1])+ return++ configure_env(args)++ import torch+ from exllamav3 import Cache, CacheLayer_quant, Config, Generator, Job, Model, Tokenizer+ from exllamav3.generator import generator as GM++ torch.set_grad_enabled(False)++ config = Config.from_directory(args.model)+ tokenizer = Tokenizer.from_config(config)+ model = Model.from_config(config)++ qkw = dict(layer_type = CacheLayer_quant, k_bits = 6, v_bits = 6)+ from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported+ if tq_supported(512, 6):+ qkw = dict(layer_type = CacheLayer_tq, k_bits = 6, v_bits = 6)+ max_history = max(args.num_draft, 1)+ cache = Cache(model, max_num_tokens = args.max_ctx + 4096, max_history = max_history,+ max_batch_size = 1, **qkw)++ plan = None+ text_map = None+ if not args.baseline:+ from exllamav3.device_map import SplitPlan, resolve_devices+ devices = resolve_devices(args.part0_device, args.part1_device)+ plan = SplitPlan(+ devices, endcaps = args.endcaps == "on", part0_layers = args.part0_layers,+ part0_reserve_gb = 0.0 if args.no_budget else args.part0_reserve_gb,+ part1_reserve_gb = args.part1_reserve_gb)+ plan.add("text", model, config = config, cache = cache, load_order = 0)+ plan.build()+ text_map = plan.map("text")+ if args.part0_layers > 0 and (text_map is None or not text_map.enabled):+ raise SystemExit("split map not enabled (no part0 device)")+ plan.install_bridges()+ plan.engage_budget()++ t0 = time.perf_counter()+ if text_map is not None:+ model.load(device_map = text_map, progressbar = True, max_chunk_size = 4096)+ else:+ model.load(device = "cuda:0", progressbar = True)+ load_s = time.perf_counter() - t0+ if plan is not None:+ plan.record_load("text", load_s)++ draft = draft_cache = None+ if args.num_draft > 0:+ draft = Model.from_config(config, component = "mtp")+ draft_cache = Cache(draft, max_num_tokens = args.max_ctx + 4096, max_history = max_history,+ max_batch_size = 1, **qkw)+ t1 = time.perf_counter()+ if plan is not None:+ plan.add("mtp", draft, config = config, cache = draft_cache, load_order = 1)+ draft.load(device_map = plan.map("mtp"), progressbar = True, max_chunk_size = 4096)+ plan.record_load("mtp", time.perf_counter() - t1)+ else:+ draft.load(device = "cuda:0", progressbar = True)+ print(f"[eval] drafter loaded in {time.perf_counter() - t1:.1f} s", flush = True)++ vision = None+ if not args.no_vision:+ try:+ vision = Model.from_config(config, component = "vision")+ if plan is not None:+ plan.add("vision", vision, config = config, load_order = 2)+ t1 = time.perf_counter()+ vision.load(device_map = plan.map("vision"), progressbar = True)+ plan.record_load("vision", time.perf_counter() - t1)+ else:+ vision.load(device = "cuda:0", progressbar = True)+ except Exception as exc: # noqa: BLE001+ print(f"[eval] vision not loaded: {type(exc).__name__}: {exc}", flush = True)+ vision = None++ if plan is not None:+ extra = [("mtp", draft, draft_cache)] if draft is not None else []+ if vision is not None:+ extra.append(("vision", vision, None))+ plan.report(model, cache, extra = extra, ctx = args.max_ctx)+ plan.release_budget()++ devs = [torch.device(f"cuda:{i}") for i in range(torch.cuda.device_count())]+ after_load = {str(d): round(torch.cuda.memory_allocated(d) / 2**30, 2) for d in devs}+ device_info = {}+ for i, d in enumerate(devs):+ p = torch.cuda.get_device_properties(i)+ device_info[str(d)] = {+ "name": p.name, "arch": getattr(p, "gcnArchName", ""),+ "total_gib": round(p.total_memory / 2**30, 2),+ }++ GM.MTP_FUSE_CATCHUP = 2+ gen = Generator(model = model, cache = cache, tokenizer = tokenizer,+ draft_model = draft, draft_cache = draft_cache,+ num_draft_tokens = args.num_draft or None,+ record_draft_stats = True)++ result = {+ "mode": "baseline" if args.baseline else "split",+ "model": args.model,+ "part0_layers": None if args.baseline else args.part0_layers,+ "part0_device": None if args.baseline else args.part0_device,+ "part1_device": None if args.baseline else args.part1_device,+ "part0_reserve_gb": None if args.baseline else args.part0_reserve_gb,+ "endcaps": None if args.baseline else args.endcaps,+ "ctx": args.max_ctx,+ "cache_tokens": args.max_ctx + 4096,+ "num_draft": args.num_draft,+ "graphs_off": args.no_graphs or not args.baseline,+ "load_s": load_s,+ "devices": device_info,+ "after_load_gib": after_load,+ "prompts": [],+ "perf": [],+ }++ for prompt in PROMPTS:+ ids = ids_of(prompt, tokenizer)+ r = run_job(gen, Job, ids, args.tokens)+ r["prompt"] = prompt+ r["prompt_tokens"] = int(ids.numel())+ result["prompts"].append(r)+ print(f"[eval] {prompt[:44]!r}: {r['tokens']} tokens"+ + (f", ttft {r['ttft_s']:.2f} s" if r["ttft_s"] else "")+ + (f", decode {r['tokens'] / r['decode_s']:.2f} t/s"+ if r["decode_s"] and r["tokens"] > 1 else ""), flush = True)++ if not args.no_perf:+ for i, prompt in enumerate(PERF_PROMPTS):+ ids = ids_of(prompt, tokenizer)+ reps = []+ for rep in range(max(1, args.perf_reps)):+ r = run_job(gen, Job, ids, args.perf_tokens)+ tps = (r["tokens"] - 1) / r["decode_s"] if r["decode_s"] and r["tokens"] > 1 else None+ reps.append({"tokens": r["tokens"], "ttft_s": r["ttft_s"], "decode_s": r["decode_s"],+ "decode_tps": tps, "accepted": r["accepted"], "rejected": r["rejected"]})+ print(f"[eval] perf {i}.{rep}: ttft {r['ttft_s']:.2f} s, decode {tps:.2f} t/s"+ f" (acc {r['accepted']} / rej {r['rejected']})", flush = True)+ good = [x["decode_tps"] for x in reps if x["decode_tps"]]+ result["perf"].append({+ "prompt": prompt, "prompt_tokens": int(ids.numel()), "reps": reps,+ "decode_tps": (sum(good) / len(good)) if good else None,+ })++ if args.needle_depth > 0:+ ids, needle = build_needle(min(args.needle_depth, args.max_ctx - 1024), tokenizer)+ r = run_job(gen, Job, ids, 24)+ found = needle.lower() in r["text"].lower()+ result["needle"] = {+ "depth": int(ids.numel()), "needle": needle, "found": found,+ "text": r["text"], "ttft_s": r["ttft_s"], "tokens": r["tokens"],+ }+ print(f"[eval] needle depth {ids.numel()}: {'FOUND' if found else 'MISSING'}"+ f" (ttft {r['ttft_s']:.1f} s) text={r['text'][:120]!r}", flush = True)++ if args.bench_depth > 0:+ ids, _ = build_needle(min(args.bench_depth, args.max_ctx - 1024), tokenizer)+ r = run_job(gen, Job, ids, args.perf_tokens)+ tps = (r["tokens"] - 1) / r["decode_s"] if r["decode_s"] and r["tokens"] > 1 else None+ acc, rej = r["accepted"], r["rejected"]+ result["long"] = {+ "depth": int(ids.numel()), "ttft_s": r["ttft_s"], "tokens": r["tokens"],+ "decode_s": r["decode_s"], "decode_tps": tps,+ "accepted": acc, "rejected": rej,+ "acceptance": round(100 * acc / (acc + rej), 2) if acc + rej else None,+ "text": r["text"],+ }+ if r["ttft_s"] is None or tps is None:+ print(f"[eval] long depth {ids.numel()}: incomplete run "+ f"({r['tokens']} tokens, ttft={r['ttft_s']}, decode_tps={tps}, "+ f"accept {acc}/{rej})", flush = True)+ else:+ print(f"[eval] long depth {ids.numel()}: ttft {r['ttft_s']:.1f} s, "+ f"prefill {ids.numel() / r['ttft_s']:.2f} t/s, decode {tps:.2f} t/s, "+ f"accept {acc}/{rej}", flush = True)++ for d in devs:+ result["devices"][str(d)].update({+ "allocated_gib": round(torch.cuda.memory_allocated(d) / 2**30, 2),+ "peak_gib": round(torch.cuda.max_memory_allocated(d) / 2**30, 2),+ "reserved_gib": round(torch.cuda.memory_reserved(d) / 2**30, 2),+ })++ bridge = getattr(config, "device_bridge", None)+ if bridge is not None:+ print(bridge.summary(), flush = True)+ result["bridge"] = bridge.stats++ if args.out:+ tmp = args.out + ".tmp"+ with open(tmp, "w", encoding = "utf8") as f:+ json.dump(result, f, indent = 1)+ os.replace(tmp, args.out)+ print(f"[eval] wrote {args.out}", flush = True)+++def compare(base_path: str, split_path: str) -> None:+ base = json.load(open(base_path, encoding = "utf8"))+ split = json.load(open(split_path, encoding = "utf8"))+ n = min(len(base.get("prompts", [])), len(split.get("prompts", [])))+ same = 0+ for i in range(n):+ a = base["prompts"][i]["ids"]+ b = split["prompts"][i]["ids"]+ ok = a == b+ same += ok+ print(f"[compare] prompt {i}: {'IDENTICAL' if ok else 'DIVERGED'} "+ f"({len(a)} vs {len(b)} ids)")+ if not ok:+ d = next((j for j, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))+ print(f"[compare] first divergence at {d}: "+ f"{a[d:d + 8]} vs {b[d:d + 8]}")+ print(f"[compare] {same}/{n} greedy prompts identical")+ if base.get("perf") and split.get("perf"):+ for i, (a, b) in enumerate(zip(base["perf"], split["perf"])):+ if a.get("decode_tps") and b.get("decode_tps"):+ print(f"[compare] perf {i}: baseline {a['decode_tps']:.2f} t/s, "+ f"split {b['decode_tps']:.2f} t/s "+ f"({b['decode_tps'] / a['decode_tps']:.3f}x)")+ if "needle" in split:+ print(f"[compare] needle: {'found' if split['needle']['found'] else 'MISSING'}")+++if __name__ == "__main__":+ main()diff --git a/tools/strix_halo/split_load.py b/tools/strix_halo/split_load.pynew file mode 100644index 0000000..0bff538--- /dev/null+++ b/tools/strix_halo/split_load.py@@ -0,0 +1,140 @@+#!/usr/bin/env python3+"""Phase 3 loader gate: load the GLM pack across two devices and print the table.++No forward pass is run. Either device may serve part0 or part1; select them with+--part1-device/--part0-device (cuda:N, gfxXXXX, UUID or name).+Usage (from the repo root, after `source tools/strix_halo/env.sh`):++ python tools/strix_halo/split_load.py \+ -m /data/models/NicSir--GLM-5.3-Flash-EXL3-2.72bpw \+ --part0-layers 4 --endcaps on -c 65536+"""+from __future__ import annotations++import argparse+import os+import resource+import time+++def mem_available_gib() -> float:+ try:+ for line in open("/proc/meminfo", encoding="ascii"):+ if line.startswith("MemAvailable:"):+ return int(line.split()[1]) / 1024 ** 2+ except OSError:+ pass+ return 0.0+++def main() -> None:+ p = argparse.ArgumentParser()+ p.add_argument("-m", "--model", required=True)+ p.add_argument("--part0-layers", type=int, default=4)+ p.add_argument("--part1-device", default="auto")+ p.add_argument("--part0-device", default="auto")+ p.add_argument("--endcaps", choices=("on", "off"), default="on")+ p.add_argument("--part0-reserve-gb", type=float, default=1.2)+ p.add_argument("-c", "--cache-size", type=int, default=65536)+ p.add_argument("--num-draft", type=int, default=2)+ p.add_argument("--no-vision", action="store_true")+ p.add_argument("--baseline", action="store_true", help="load everything on cuda:0, for the host-RAM comparison")+ args = p.parse_args()++ import torch+ from exllamav3 import Cache, CacheLayer_quant, Config, Model+ from exllamav3.device_map import SplitPlan, resolve_devices++ torch.set_grad_enabled(False)+ endcaps = args.endcaps == "on"+ host_before = mem_available_gib()++ config = Config.from_directory(args.model)+ model = Model.from_config(config)++ # Same cache format as tools/glm/serve.py defaults: TurboQuant 6-bit latent.+ qkw = dict(layer_type=CacheLayer_quant, k_bits=6, v_bits=6)+ from exllamav3.cache.tq import CacheLayer_tq, supported as tq_supported+ if tq_supported(512, 6):+ qkw = dict(layer_type=CacheLayer_tq, k_bits=6, v_bits=6)+ max_history = max(args.num_draft, 1)+ cache = Cache(model, max_num_tokens=args.cache_size + 4096,+ max_history=max_history, max_batch_size=1, **qkw)++ if args.baseline:+ t0 = time.perf_counter()+ model.load(device="cuda:0", progressbar=True)+ draft = Model.from_config(config, component="mtp") if args.num_draft > 0 else None+ if draft is not None:+ draft.load(device="cuda:0", progressbar=True)+ vision = None+ if not args.no_vision:+ try:+ vision = Model.from_config(config, component="vision")+ vision.load(device="cuda:0", progressbar=True)+ except Exception as exc: # noqa: BLE001+ print(f"[baseline] vision not loaded: {type(exc).__name__}: {exc}", flush=True)+ print(f"[baseline] load {time.perf_counter() - t0:.1f} s; "+ f"cuda:0 allocated {torch.cuda.memory_allocated(torch.device('cuda:0')) / 2**30:.2f} GiB; "+ f"peak {torch.cuda.max_memory_allocated(torch.device('cuda:0')) / 2**30:.2f} GiB", flush=True)+ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 ** 2+ print(f"[baseline] host RSS peak {peak:.2f} GiB; "+ f"MemAvailable {host_before:.1f} -> {mem_available_gib():.1f} GiB", flush=True)+ return++ devices = resolve_devices(args.part0_device, args.part1_device)+ plan = SplitPlan(devices, endcaps=endcaps, part0_layers=args.part0_layers,+ part0_reserve_gb=args.part0_reserve_gb)+ plan.add("text", model, config=config, cache=cache, load_order=0)+ plan.build()+ text_map = plan.map("text")+ if text_map is None or not text_map.enabled:+ raise SystemExit("split map is not enabled (no part0 device)")+ plan.install_bridges()+ plan.engage_budget()++ t0 = time.perf_counter()+ model.load(device_map=text_map, progressbar=True, max_chunk_size=4096)+ t_model = time.perf_counter() - t0+ plan.record_load("text", t_model)++ draft = draft_cache = None+ if args.num_draft > 0:+ draft = Model.from_config(config, component="mtp")+ draft_cache = Cache(draft, max_num_tokens=args.cache_size + 4096,+ max_history=max_history, max_batch_size=1, **qkw)+ plan.add("mtp", draft, config=config, cache=draft_cache, load_order=1)+ t1 = time.perf_counter()+ draft.load(device_map=plan.map("mtp"), progressbar=True, max_chunk_size=4096)+ plan.record_load("mtp", time.perf_counter() - t1)+ print(f"[split] drafter loaded in {time.perf_counter() - t1:.1f} s", flush=True)++ vision = None+ if not args.no_vision:+ try:+ vision = Model.from_config(config, component="vision")+ plan.add("vision", vision, config=config, load_order=2)+ t1 = time.perf_counter()+ vision.load(device_map=plan.map("vision"), progressbar=True)+ plan.record_load("vision", time.perf_counter() - t1)+ print(f"[split] vision loaded in {time.perf_counter() - t1:.1f} s "+ f"on {plan.map('vision').placed_devices}", flush=True)+ except Exception as exc: # noqa: BLE001+ print(f"[split] vision not loaded: {type(exc).__name__}: {exc}", flush=True)+ vision = None++ extra = []+ if draft is not None:+ extra.append(("mtp", draft, draft_cache))+ if vision is not None:+ extra.append(("vision", vision, None))+ plan.report(model, cache, extra=extra, ctx=args.cache_size)+ plan.release_budget()++ peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024 ** 2+ print(f"[split] target load {t_model:.1f} s; host RSS peak {peak:.2f} GiB; "+ f"MemAvailable {host_before:.1f} -> {mem_available_gib():.1f} GiB", flush=True)+++if __name__ == "__main__":+ main()