Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.
Python amdapple-siliconcudadeepseekexl3exllamav3glminferencellmllm-inferencelocal-llmnvidiaopenai-apiquantizationqwenrocmstrix-halo
split: rebase the contiguous layer split onto main
Resynth57245b9e08c1
diff --git a/exllamav3/bridge.py b/exllamav3/bridge.pynew file mode 100644index 0000000..b2b7709--- /dev/null+++ b/exllamav3/bridge.py@@ -0,0 +1,190 @@+from __future__ import annotations++"""Async host-staged bridge for the contiguous layer split.++The iGPU (gfx1151) and the eGPU (gfx1201) have no working, fast peer path: a direct+device-to-device copy on this link class is both slow (under 1 GB/s observed on the+9070 side) and asymmetric. Every segment crossing therefore goes through pinned host+memory:++ 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, ``hop_ids`` the loop-closure token-id+variant, and ``hop_chunk`` the prefill-sized crossing. All three 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, main: torch.device, front: torch.device):+ self.main = torch.device(main)+ self.front = torch.device(front)+ 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.main, self.front++ def describe(self) -> str:+ return (f"host-staged async bridge {self.main} <-> {self.front} "+ 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_ids(self, ids: torch.Tensor, dst: torch.device) -> torch.Tensor:+ """The loop-closure variant: single-token / row ids cross the same bridge."""+ return self._hop(ids, 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+ slot.filled = torch.cuda.Event()+ 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)++ src_stream = torch.cuda.current_stream(src)+ 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:+ src_stream.wait_event(slot.read)++ hb = slot.buf[:numel].view(t.shape)++ with torch.cuda.stream(src_stream):+ hb.copy_(t, non_blocking = True)+ slot.filled.record(src_stream)++ with 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, main: torch.device, front: 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).+ """+ config.split_active = True+ existing = getattr(config, "device_bridge", None)+ if front is None or torch.device(main) == torch.device(front) or not bridge_enabled():+ return existing+ if existing is not None and existing.pair == (torch.device(main), torch.device(front)):+ return existing+ bridge = Bridge(main, front)+ config.device_bridge = bridge+ return bridgediff --git a/exllamav3/device_map.py b/exllamav3/device_map.pynew file mode 100644index 0000000..9aeb27b--- /dev/null+++ b/exllamav3/device_map.py@@ -0,0 +1,294 @@+from __future__ import annotations++"""+Contiguous layer split: resolve the two devices and map model modules to them.++The map is deliberately independent of the architecture: modules carrying a+``layer_idx`` are transformer layers and are assigned to the front device for+indices ``0 .. front_layers - 1`` and to the main device for the rest. Modules+without a ``layer_idx`` are the endcaps (embedding, hyper-connection drivers,+final norm, lm_head, and the separate MTP/vision components).++Endcaps ON puts the non-CPU endcaps on the front device; ENDCAPS OFF lets them+follow their natural neighbour (prologue with layer 0, epilogue with the last+layer). ``prefer_cpu`` modules, such as the GLM token embedding, always stay on+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+++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 Devices:+ main: torch.device+ front: torch.device | None+ main_arch: str+ front_arch: str | None+++def resolve_devices(front: str | None = None) -> Devices:+ """Resolve main/front by architecture.++ ``front`` (or KYOJIN_FRONT_DEVICE) accepts ``auto``, ``gfx1201``, ``cuda:N``+ or a device UUID / name substring. Auto selects the first gfx120/gfx12+ device that is not the gfx1151 main device.+ """+ if not torch.cuda.is_available():+ raise RuntimeError("layer split requires a HIP/CUDA device")+ n = torch.cuda.device_count()+ arch = {i: _arch_of(i) for i in range(n)}+ main_i = next((i for i, a in arch.items() if a == "gfx1151"), 0)+ req = (front if front is not None else os.environ.get("KYOJIN_FRONT_DEVICE", "auto") or "auto").strip().lower()++ if req in ("", "auto"):+ front_i = next((i for i, a in arch.items() if a.startswith("gfx12") and i != main_i), None)+ elif req.startswith("cuda:"):+ front_i = int(req.split(":", 1)[1])+ if front_i < 0 or front_i >= n:+ raise RuntimeError(f"KYOJIN_FRONT_DEVICE={req}: no such device")+ elif req.startswith("gfx"):+ front_i = next((i for i, a in arch.items() if a == req), None)+ else:+ key = req.replace("-", "")+ front_i = next((i for i in range(n)+ if key and (key in _device_uuid(i) or req in torch.cuda.get_device_properties(i).name.lower())), None)++ if front_i is None:+ raise RuntimeError(+ f"layer split requested but no front device matched {req!r}; "+ f"devices: {[(i, a) for i, a in arch.items()]}. "+ "Set KYOJIN_FRONT_DEVICE=gfx1201 (or cuda:N)."+ )+ if front_i == main_i:+ raise RuntimeError("layer split front device resolves to the main device")+ return Devices(+ main = torch.device("cuda", main_i),+ front = torch.device("cuda", front_i),+ main_arch = arch[main_i],+ front_arch = arch[front_i],+ )+++@dataclass+class LayerDeviceMap:+ main: torch.device+ front: torch.device | None+ front_layers: int+ endcaps: bool+ component: str = "text"+ layer_count: int = 0+ main_arch: str = ""+ front_arch: str | None = None+ reserve_bytes: dict[int, int] = field(default_factory = dict)+ endcap_keys: tuple[str, ...] = ()+ _positions: dict[int, int] = field(default_factory = dict, repr = False)+ _first_layer_pos: int = 0+ _last_layer_pos: int = -1++ @classmethod+ def from_model(+ cls,+ model,+ front_layers: int,+ endcaps: bool,+ devices: Devices,+ component: str = "text",+ front_reserve_gb: float = 1.2,+ main_reserve_gb: float = 0.0,+ ) -> "LayerDeviceMap":+ modules = list(model.modules)+ layers = [m for m in modules if getattr(m, "layer_idx", None) is not None]+ n_layers = len(layers)+ if component in ("mtp", "vision"):+ # These components are endcaps in their entirety: they have no trunk+ # boundary of their own, so ENDCAPS OFF leaves them on the main device.+ front_layers = n_layers if endcaps else 0+ front_layers = max(0, min(int(front_layers), n_layers))+ if devices.front is None:+ front_layers = 0+ positions = {id(m): i for i, m in enumerate(modules)}+ first = positions[id(layers[0])] if layers else 0+ last = positions[id(layers[-1])] if layers else -1++ # The front reserve caps the small card while its weights load. It is released before+ # the first main module (see Model._load_mapped): on ROCm the memory-fraction cap+ # changes the allocator's behavior process-wide and perturbs the main device's kernel+ # choices, which would make split outputs differ from a single-device baseline even+ # with zero front layers. The main device has ample headroom and is never capped.+ reserve: dict[int, int] = {}+ if devices.front is not None and front_layers > 0 and front_reserve_gb > 0:+ reserve[devices.front.index] = max(0, int(front_reserve_gb * GIB))+ if devices.main is not None and main_reserve_gb > 0:+ reserve[devices.main.index] = max(0, int(main_reserve_gb * GIB))++ return cls(+ main = devices.main,+ front = devices.front,+ front_layers = front_layers,+ endcaps = bool(endcaps) and front_layers > 0,+ component = component,+ layer_count = n_layers,+ main_arch = devices.main_arch,+ front_arch = devices.front_arch,+ reserve_bytes = reserve,+ endcap_keys = tuple(m.key for m in modules if getattr(m, "layer_idx", None) is None),+ _positions = positions,+ _first_layer_pos = first,+ _last_layer_pos = last,+ )++ @property+ def enabled(self) -> bool:+ return self.front is not None and self.front_layers > 0++ @property+ def boundary(self) -> int | None:+ if not self.enabled or self.layer_count == 0:+ return None+ return self.front_layers++ @property+ def used_devices(self) -> list[torch.device]:+ out = [self.main]+ if self.enabled and self.front is not None:+ out.append(self.front)+ return out++ 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:+ return self.front if idx < self.front_layers else self.main+ if not self.enabled:+ return self.main+ if self.endcaps:+ return self.front+ # ENDCAPS OFF: prologue follows layer 0, epilogue follows the last layer.+ pos = self._positions.get(id(module), 0)+ if pos < self._first_layer_pos:+ return self.front+ return self.front if self.front_layers >= self.layer_count else self.main++ def engage_budget(self) -> None:+ """Apply the per-device reserve once, before the first component loads."""+ if getattr(self, "_budget_engaged", False):+ return+ from .util.memory import set_memory_fraction_reserve+ for i, reserve in self.reserve_bytes.items():+ if reserve > 0:+ set_memory_fraction_reserve(reserve, i)+ self._budget_engaged = True++ def release_front_budget(self) -> None:+ """Release the front load cap before the first main module loads.++ A process-wide allocator cap on ROCm changes the main device's kernel/allocator+ behavior; the split must not carry that into the main segment (it would perturb+ outputs relative to a single-device run).+ """+ if not getattr(self, "_budget_engaged", False):+ return+ if self.front is None or self.front.index not in self.reserve_bytes:+ return+ from .util.memory import unset_memory_fraction+ unset_memory_fraction([self.front.index])+ self._budget_engaged = any(+ i != self.front.index and r > 0 for i, r in self.reserve_bytes.items())++ def release_budget(self) -> None:+ if not getattr(self, "_budget_engaged", False):+ return+ from .util.memory import unset_memory_fraction+ unset_memory_fraction(list(self.reserve_bytes.keys()))+ self._budget_engaged = False++ def describe(self) -> str:+ parts = [f"{self.component}: layers 0..{self.front_layers - 1} front, "+ f"{self.front_layers}..{self.layer_count - 1} main"]+ if self.endcaps:+ parts.append(f"endcaps front ({len(self.endcap_keys)} modules)")+ else:+ parts.append("endcaps follow neighbours")+ return "; ".join(parts)+++def _cache_bytes(cache) -> dict[torch.device, int]:+ table: dict[torch.device, int] = {}+ if cache is None:+ return table+ for cl in list(getattr(cache, "layers", {}).values()):+ dev = getattr(getattr(cl, "attention", None), "device", None)+ if dev is None:+ continue+ table[dev] = table.get(dev, 0) + int(cl.storage_size())+ for rl in list(getattr(cache, "recurrent_layers", {}).values()):+ dev = getattr(getattr(rl, "attention", 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: LayerDeviceMap,+ 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)+ allocated = torch.cuda.memory_allocated(dev)+ peak = torch.cuda.max_memory_allocated(dev)+ 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.front is not None:+ p = torch.cuda.get_device_properties(device_map.front)+ reserve = device_map.reserve_bytes.get(device_map.front.index, 0)+ print(f"[split] front {str(device_map.front)} {device_map.front_arch}: "+ f"{p.total_memory / GIB:.2f} GiB total, reserve {reserve / GIB:.2f} GiB, "+ f"budget {(p.total_memory - reserve) / GIB:.2f} GiB", flush=True)+ 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..42fbc1b 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,18 @@ 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."+ 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..3175532 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 front reserve caps+ the small card while its own segment loads, then is released at the first main+ module: on ROCm the memory-fraction cap perturbs the allocator process-wide, and+ the main segment must not inherit it. The caller releases whatever remains after+ the last component.+ """+ device_map.engage_budget()+ pin_all = config.infer_params.vision_pinned and getattr(self, "component", "text") == "vision"+ front_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 front_released and dev == device_map.main:+ device_map.release_front_budget()+ front_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, device_map.main, device_map.front)+ 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..70a4f30 100755--- a/exllamav3/model_init.py+++ b/exllamav3/model_init.py@@ -335,6 +335,27 @@ 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.+ front_layers = int(os.environ.get("KYOJIN_FRONT_LAYERS", "0") or 0)+ front_map = draft_map = None+ if front_layers:+ if args.tensor_parallel or single_device or split is not None:+ raise ValueError("KYOJIN_FRONT_LAYERS cannot be combined with tensor parallel, "+ "EXL3_LOAD_DEVICE or --gpu_split")+ from .device_map import LayerDeviceMap, print_split_table, resolve_devices+ devices = resolve_devices(os.environ.get("KYOJIN_FRONT_DEVICE"))+ endcaps = os.environ.get("KYOJIN_ENDCAPS", "1") != "0"+ reserve = float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2"))+ front_map = LayerDeviceMap.from_model(model, front_layers, endcaps, devices,+ component="text", front_reserve_gb=reserve)+ if draft_model is not None:+ draft_map = LayerDeviceMap.from_model(draft_model, 0, endcaps, devices,+ component="mtp", front_reserve_gb=reserve)+ draft_map.reserve_bytes.clear()+ front_map.engage_budget()+ printp(not quiet, f" -- layer split: {front_map.describe()}")+# Parallelism optionstp_options = {"moe_tensor_split": args.tp_moe_tensor_split@@ -359,7 +380,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 +393,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": front_map} if front_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 +407,12 @@ def init(**kwargs)+ if front_map is not None:+ print_split_table(model, cache, front_map,+ extra=[("mtp", draft_model, draft_cache)] if draft_model is not None else [],+ ctx=getattr(args, "cache_size", None))+ front_map.release_budget()+# Load tokenizerif load_tokenizer:printp(not quiet, f" -- Loading tokenizer...")diff --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/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/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.pyindex 1916125..7ce994f 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_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))+_fused_stable = {} # arch gate per device index; read on every KDA prefill chunk+++def _fused_output_stable(device=None) -> bool:+ """Whether the fused Triton KDA output path is run-to-run deterministic on this arch.++ Measured nondeterministic on gfx1201 (three loads produced three different greedy+ branches); gfx11.5 keeps it. Conservative default when the arch cannot be read: use+ the deterministic fla chain."""+ try:+ from exllamav3.util.arch_list import device_arch, device_index+ idx = device_index(device)+ ok = _fused_stable.get(idx)+ if ok is None:+ ok = _fused_stable[idx] = device_arch(idx) in _FUSED_STABLE_ARCHS+ 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,13 @@ 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 not _fused_output_stable(q.device):+ # A layer split runs KDA on both a gfx1151 main and a gfx12 front. The fused output+ # path is not run-to-run deterministic on gfx12, and the gfx11.5 HIP kernel cannot be+ # JIT-built there (kda_fused_h_hip.supported() declines, so _hip_ok already fell back+ # to the Triton fuse path). Force the deterministic fla chain on that arch only; keep+ # it here, split-side, until the gfx12 fused kernel lands.+ 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/tools/glm/serve.py b/tools/glm/serve.pyindex 52ab922..0e8e2f7 100644--- a/tools/glm/serve.py+++ b/tools/glm/serve.py@@ -677,7 +677,9 @@ 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,+ front_layers: int = 0, front_device: str | None = None,+ endcaps: bool = True, front_reserve_gb: float = 1.2):import torchfrom exllamav3 import Cache, Config, Generator, Job, Model, Tokenizerfrom exllamav3.generator import generator as GM@@ -707,6 +709,28 @@ class ResidentEngine:self.max_draft = num_draftself.config = Config.from_directory(model_path)self.model = Model.from_config(self.config)+ self.front_layers = max(0, int(front_layers or 0))+ self.front_device_arg = front_device+ self.endcaps = bool(endcaps)+ self.front_reserve_gb = float(front_reserve_gb)+ self.split_map = None+ self.split_devices = None+ if self.front_layers:+ from exllamav3.device_map import resolve_devices, LayerDeviceMap+ self.split_devices = resolve_devices(front_device)+ self.split_map = LayerDeviceMap.from_model(+ self.model, self.front_layers, self.endcaps, self.split_devices,+ component="text", front_reserve_gb=self.front_reserve_gb)+ if not self.split_map.enabled:+ raise ValueError("layer split requested but no usable front device")+ print(f"serve: layer split: {self.split_map.describe()}; "+ f"main {self.split_devices.main} ({self.split_devices.main_arch}), "+ f"front {self.split_devices.front} ({self.split_devices.front_arch}), "+ f"front reserve {self.front_reserve_gb:.2f} GiB", flush=True)+ if self.front_layers > 5 and max_ctx > 65536:+ print("serve: warning: front layers > 5 at -c > 65536 is measured to OOM the 16 GB "+ "front on long prefill (gfx1201 KDA fallback workspace); use "+ "--front-layers 5 for long-context split runs until auto-sizing lands", flush=True)self.tokenizer = Tokenizer.from_config(self.config)if os.environ.get("KYO_TOKCACHE", "8") == "0":self.pec = None@@ -746,13 +770,27 @@ 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_map is not None:+ self.model.load(device_map=self.split_map, 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())+ self.draft_map = Noneif 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_map is not None:+ from exllamav3.device_map import LayerDeviceMap+ self.draft_map = LayerDeviceMap.from_model(+ self.draft_model, 0, self.endcaps, self.split_devices,+ component="mtp", front_reserve_gb=self.front_reserve_gb)+ self.draft_map.reserve_bytes.clear() # the target map owns the budget+ self.draft_model.load(device_map=self.draft_map, progressbar=False,+ callback=startup_health.load_callback(), max_chunk_size=4096)+ 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@@ -766,8 +804,25 @@ class ResidentEngine:getattr(self.config, "vision_end_token_id", 0),env_fingerprint=self.env_fingerprint)if vision:+ self._vision_device = (self.split_devices.front+ if self.split_map is not None and self.endcaps+ else torch.device("cuda:0"))self.vision = self._load_vision()self.supports_vision = self.vision is not None+ if self.split_map is not None:+ from exllamav3.device_map import print_split_table+ extra = []+ if self.draft_model is not None:+ extra.append(("mtp", self.draft_model, self.draft_cache))+ if self.vision is not None:+ extra.append(("vision", self.vision, None))+ print_split_table(self.model, self.cache, self.split_map, extra=extra, ctx=ctx)+ bridge = getattr(self.config, "device_bridge", None)+ if bridge is not None:+ print(f"serve: {bridge.describe()}", flush=True)+ else:+ print("serve: layer split: bridge disabled (KYOJIN_BRIDGE=0); crossings use to_device()", flush=True)+ self.split_map.release_budget()self.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 +934,7 @@ 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())+ tower.load(device=self._vision_device, 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 +2189,17 @@ def main() -> None:parser.add_argument("--sessions", type=int, default=1,help=f"requests decoded together through the one Generator (1..{MAX_SESSIONS}); default 1 = one request at a time. ""The KV pool (-c) is shared by all sessions")+ parser.add_argument("--front-layers", type=int, default=None,+ help="contiguous layer split: first N transformer layers on the front (eGPU) device; "+ "0 = off (default: KYOJIN_FRONT_LAYERS, else 0)")+ parser.add_argument("--front-device", default=None,+ help="front device for the layer split: auto, gfx1201, cuda:N or a UUID/name substring "+ "(default: KYOJIN_FRONT_DEVICE, else auto)")+ parser.add_argument("--endcaps", choices=("on", "off"), default=None,+ help="with a layer split, keep embedding/norm/lm_head/MTP/vision on the front device "+ "(default: KYOJIN_ENDCAPS, else on)")+ parser.add_argument("--front-reserve-gb", type=float, default=None,+ help="VRAM to leave free on the front device for workspace (default: KYOJIN_FRONT_RESERVE_GB, else 1.2)")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 +2245,30 @@ def main() -> None:parser.add_argument("--default-reasoning-effort", choices=("low", "medium", "high", "max"), default=None,help="thinking effort when a request omits it (default: medium)")args = parser.parse_args()+ front_layers = args.front_layers if args.front_layers is not None else int(os.environ.get("KYOJIN_FRONT_LAYERS", "0") or 0)+ front_device = args.front_device or os.environ.get("KYOJIN_FRONT_DEVICE") or "auto"+ endcaps = (args.endcaps == "on") if args.endcaps is not None else os.environ.get("KYOJIN_ENDCAPS", "1") != "0"+ front_reserve_gb = (args.front_reserve_gb if args.front_reserve_gb is not None+ else float(os.environ.get("KYOJIN_FRONT_RESERVE_GB", "1.2")))+ if front_layers:+ # Phase 4: split mode runs eager. A whole-forward graph cannot span the+ # host-staged bridge between segments, and the per-block capture has no concept+ # of a segment boundary yet. Per-segment capture is Phase 6.+ forced = {+ "EXL3_BLOCK_GRAPH": "0",+ "EXL3_BLOCK_GRAPH_MLA": "0",+ "EXL3_BLOCK_GRAPH_VERIFY": "0",+ "EXL3_BLOCK_GRAPH_DRAFT": "0",+ "EXL3_BLOCK_GRAPH_ATTN": "0",+ "EXL3_BLOCK_GRAPH_DEC_MOE": "0",+ "EXL3_CUDA_GRAPH": "0",+ "EXL3_HIP_GRAPH": "0",+ }+ overridden = [f"{k}={os.environ[k]}" for k, v in forced.items()+ if os.environ.get(k) not in (None, "", v)]+ os.environ.update(forced)+ print("serve: layer split: graphs forced off for split mode (Phase 4; per-segment capture is Phase 6)"+ + (f"; overrode {', '.join(overridden)}" if overridden else ""), flush=True)if args.kv_mode == "fp16":args.cache_bits = 0elif args.cache_bits is None:@@ -2238,7 +2328,9 @@ 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,+ front_layers=front_layers, front_device=front_device,+ endcaps=endcaps, front_reserve_gb=front_reserve_gb)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/strix_halo/split_eval.py b/tools/strix_halo/split_eval.pynew file mode 100644index 0000000..0bd89a1--- /dev/null+++ b/tools/strix_halo/split_eval.py@@ -0,0 +1,338 @@+#!/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.++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+++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/hf/hub/models--NicSir--GLM-5.3-Flash-EXL3-2.72bpw/"+ "snapshots/db672fc5e61f1d61bdf6d641fb63538b80bb7613")+ p.add_argument("--baseline", action="store_true", help="single device (cuda:0), no layer split")+ p.add_argument("--front-layers", type=int, default=6)+ p.add_argument("--front-device", default="auto")+ p.add_argument("--endcaps", choices=("on", "off"), default="on")+ p.add_argument("--front-reserve-gb", type=float, default=1.2)+ p.add_argument("--main-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("--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")+ return p.parse_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 ("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"):+ 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.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)++ devices = None+ text_map = None+ if not args.baseline:+ from exllamav3.device_map import LayerDeviceMap, resolve_devices+ devices = resolve_devices(args.front_device)+ text_map = LayerDeviceMap.from_model(+ model, args.front_layers, args.endcaps == "on", devices,+ component = "text", front_reserve_gb = args.front_reserve_gb,+ main_reserve_gb = args.main_reserve_gb)+ if args.no_budget:+ text_map.reserve_bytes.clear()+ if args.front_layers > 0 and not text_map.enabled:+ raise SystemExit("split map not enabled (no front device)")++ 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++ 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 text_map is not None:+ draft_map = LayerDeviceMap.from_model(+ draft, 0, args.endcaps == "on", devices,+ component = "mtp", front_reserve_gb = args.front_reserve_gb)+ draft_map.reserve_bytes.clear()+ draft.load(device_map = draft_map, progressbar = True, max_chunk_size = 4096)+ 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")+ vdev = (devices.front if text_map is not None and args.endcaps == "on"+ else torch.device("cuda:0"))+ vision.load(device = vdev, progressbar = True)+ except Exception as exc: # noqa: BLE001+ print(f"[eval] vision not loaded: {type(exc).__name__}: {exc}", flush = True)+ vision = None++ if text_map is not None:+ from exllamav3.device_map import print_split_table+ print_split_table(model, cache, text_map,+ extra = [("mtp", draft, draft_cache)] if draft is not None else [],+ ctx = args.max_ctx)+ text_map.release_budget()++ 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,+ "front_layers": None if args.baseline else args.front_layers,+ "endcaps": None if args.baseline else args.endcaps,+ "ctx": args.max_ctx,+ "num_draft": args.num_draft,+ "graphs_off": args.no_graphs or not args.baseline,+ "load_s": load_s,+ "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)++ 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..4a29d52--- /dev/null+++ b/tools/strix_halo/split_load.py@@ -0,0 +1,133 @@+#!/usr/bin/env python3+"""Phase 3 loader gate: load the GLM pack across iGPU + eGPU and print the table.++No forward pass is run. Usage (from the repo root, after `source tools/strix_halo/env.sh`):++ python tools/strix_halo/split_load.py \+ -m /data/hf/hub/models--NicSir--GLM-5.3-Flash-EXL3-2.72bpw/snapshots/db672fc5e61f1d61bdf6d641fb63538b80bb7613 \+ --front-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("--front-layers", type=int, default=4)+ p.add_argument("--front-device", default="auto")+ p.add_argument("--endcaps", choices=("on", "off"), default="on")+ p.add_argument("--front-reserve-gb", type=float, default=1.2)+ 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 the main device, for the host-RAM comparison")+ args = p.parse_args()++ import torch+ from exllamav3 import Cache, CacheLayer_quant, Config, Model+ from exllamav3.device_map import LayerDeviceMap, print_split_table, 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"main 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.front_device)+ text_map = LayerDeviceMap.from_model(model, args.front_layers, endcaps, devices,+ component="text", front_reserve_gb=args.front_reserve_gb)+ if not text_map.enabled:+ raise SystemExit("split map is not enabled (no front device)")+ print(f"[split] {text_map.describe()}", flush=True)+ print(f"[split] main {devices.main} ({devices.main_arch}), "+ f"front {devices.front} ({devices.front_arch})", flush=True)++ t0 = time.perf_counter()+ model.load(device_map=text_map, progressbar=True, max_chunk_size=4096)+ t_model = time.perf_counter() - t0++ 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)+ draft_map = LayerDeviceMap.from_model(draft, 0, endcaps, devices,+ component="mtp", front_reserve_gb=args.front_reserve_gb)+ draft_map.reserve_bytes.clear() # text_map owns the budget+ t1 = time.perf_counter()+ draft.load(device_map=draft_map, progressbar=True, max_chunk_size=4096)+ 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")+ vdev = devices.front if endcaps else devices.main+ t1 = time.perf_counter()+ vision.load(device=vdev, progressbar=True)+ print(f"[split] vision loaded in {time.perf_counter() - t1:.1f} s on {vdev}", 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))+ print_split_table(model, cache, text_map, extra=extra, ctx=args.cache_size)+ text_map.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()