Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

split: address universal-core review findings

Resynth9a1cddbc0326
diff --git a/doc/split.md b/doc/split.md
index c3c4681..b3d97b4 100644
--- a/doc/split.md
+++ b/doc/split.md
@@ -62,9 +62,10 @@ interface; combining it with the new map must error.
cache layer must sit on the device its owning layer was mapped to.
- Auto-N is a Stage 1 skeleton: it uses actual safetensors bytes for each layer, the
cache/recurrent sizes for layers below N, the front endcap bytes and the reserve, with
- a `KYOJIN_AUTON_SAFETY_GB` margin (default 0.25) for allocator slack. Components declared
- after the target (GLM's MTP/vision) are not yet subtracted before the target load;
- Stage 5 owns cross-component/pre-load auto sizing.
+ a `KYOJIN_AUTON_SAFETY_GB` margin (default 0.25) for allocator slack. GLM caps auto at
+ five layers for `-c > 65536` until the gfx1201 KDA prefill workspace is part of the
+ budget. Components declared after the target (GLM's MTP/vision) are not yet subtracted
+ before the target load; Stage 5 owns cross-component/pre-load auto sizing.
- JIT HIP loaders compile per (device, defines) and launch on the tensor's device stream;
`kda_fused_h`, `gdn_*`, `gr_mix` and `ple_hip` are gfx11.5 WMMA/CI paths and refuse other
archs. gfx12 runs the deterministic fla chain (`EXL3_KDA_FUSE=0` forced there) — see PR C
diff --git a/exllamav3/bridge.py b/exllamav3/bridge.py
index b2b7709..167d242 100644
--- a/exllamav3/bridge.py
+++ b/exllamav3/bridge.py
@@ -15,9 +15,9 @@ D2H leg to the H2D leg; a second event per ring slot lets the next hop reuse a p
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).
+``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.
@@ -81,10 +81,6 @@ class Bridge:
"""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)
@@ -179,9 +175,15 @@ def install_bridge(config, main: torch.device, front: torch.device | None) -> Br
forward or per-block graph must not span the bridge (Phase 6 owns per-segment
capture).
"""
- config.split_active = True
+ split_active = front is not None and torch.device(main) != torch.device(front)
+ 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 main code path.
+ os.environ["KYOJIN_SPLIT_ACTIVE"] = "1"
existing = getattr(config, "device_bridge", None)
- if front is None or torch.device(main) == torch.device(front) or not bridge_enabled():
+ if not bridge_enabled():
return existing
if existing is not None and existing.pair == (torch.device(main), torch.device(front)):
return existing
diff --git a/exllamav3/device_map.py b/exllamav3/device_map.py
index bc74bd4..fac5342 100644
--- a/exllamav3/device_map.py
+++ b/exllamav3/device_map.py
@@ -148,16 +148,18 @@ def component_policy(name: str, **overrides) -> ComponentPolicy:
"""Default policy for a component name; adapters may override any field."""
key = (name or "unknown").strip().lower()
if key == "text":
- return ComponentPolicy(
+ defaults = dict(
name = name, kind = "text", front_eligible = True, endcaps_front = True,
- endcap_types = TEXT_ENDCAP_TYPES, endcap_key_suffixes = TEXT_ENDCAP_SUFFIXES,
- **overrides)
- if key in WHOLE_COMPONENT_KINDS:
- return ComponentPolicy(
+ endcap_types = TEXT_ENDCAP_TYPES, endcap_key_suffixes = TEXT_ENDCAP_SUFFIXES)
+ elif key in WHOLE_COMPONENT_KINDS:
+ defaults = dict(
name = name, kind = key, front_eligible = True, endcaps_front = True,
- whole_component = True, **overrides)
- return ComponentPolicy(name = name, kind = "aux", front_eligible = False,
- endcaps_front = False, **overrides)
+ whole_component = True)
+ else:
+ defaults = dict(name = name, kind = "aux", front_eligible = False,
+ endcaps_front = False)
+ defaults.update(overrides)
+ return ComponentPolicy(**defaults)
def _type_name(module) -> str:
@@ -191,7 +193,22 @@ def _module_bytes(module, stc = None) -> int:
"""
if stc is not None and hasattr(stc, "get_tensor_sizes"):
try:
- return int(sum(stc.get_tensor_sizes(module.key)))
+ 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:
@@ -277,7 +294,6 @@ class ComponentMap:
main_arch: str = ""
front_arch: str | None = None
reserve_bytes: dict[int, int] = field(default_factory = dict)
- endcap_keys: tuple[str, ...] = ()
front_endcap_keys: tuple[str, ...] = ()
unknown_keys: tuple[str, ...] = ()
size_bytes: int = 0
@@ -332,6 +348,7 @@ class ComponentMap:
n_layers = len(layers)
auto = front_layers in ("auto", -1) or (isinstance(front_layers, str) and front_layers.strip().lower() == "auto")
front_layers = 0 if auto else int(front_layers)
+ endcaps = bool(endcaps and policy.endcaps_front)
if policy.whole_component:
# These components are endcaps in their entirety: they have no trunk
# boundary of their own, so ENDCAPS OFF leaves them on the main device.
@@ -360,7 +377,6 @@ class ComponentMap:
m.key for m in modules
if getattr(m, "layer_idx", None) is None and is_front_endcap(m, policy)
)
- all_endcaps = tuple(m.key for m in modules if getattr(m, "layer_idx", None) is None)
unknown = tuple(
m.key for m in modules
if getattr(m, "layer_idx", None) is None
@@ -381,7 +397,6 @@ class ComponentMap:
main_arch = devices.main_arch,
front_arch = devices.front_arch,
reserve_bytes = reserve,
- endcap_keys = all_endcaps,
front_endcap_keys = front_endcaps,
unknown_keys = unknown,
size_bytes = int(size),
@@ -402,12 +417,6 @@ class ComponentMap:
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]
@@ -441,12 +450,14 @@ class ComponentMap:
if not self._endcap_allowed(module):
# Unknown / auxiliary non-layer module: always safe, never moved implicitly.
return self.main
+ if not self.policy_or_default.endcaps_front:
+ return self.main
if self.endcaps:
return self.front
# ENDCAPS OFF: allowlisted prologue follows layer 0, epilogue follows the last layer.
pos = self._positions.get(id(module), 0)
if pos < self._first_layer_pos:
- return self.front if self.front_layers > 0 else self.main
+ return self.front
if pos > self._last_layer_pos:
return self.front if self.front_layers >= self.layer_count else self.main
return self.main
@@ -500,6 +511,7 @@ class ComponentMap:
"""Estimated front bytes for n text layers plus the policy's front endcaps."""
n = max(0, min(n, self.layer_count))
endcaps = self.endcaps if endcaps is None else bool(endcaps)
+ endcaps = endcaps and self.policy_or_default.endcaps_front
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:
@@ -553,6 +565,7 @@ class SplitPlan:
front_reserve_gb: float = 1.2,
main_reserve_gb: float = 0.0,
preset: str = "auto",
+ auto_cap: int | None = None,
logger = print,
):
self.devices = devices
@@ -563,6 +576,7 @@ class SplitPlan:
self.front_reserve_gb = float(front_reserve_gb)
self.main_reserve_gb = float(main_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] = {}
@@ -622,6 +636,8 @@ class SplitPlan:
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.front_layers = n
self.logger(f"[split] auto-N: {n} front layer(s) "
f"(budget {self._auto_budget() / GIB:.2f} GiB, "
@@ -642,7 +658,18 @@ class SplitPlan:
return self
def apply_policies(self) -> None:
- """Apply (and log) every adapter-declared unsafe env lever."""
+ """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)
@@ -767,7 +794,8 @@ class SplitPlan:
for key, rl in list(getattr(cache, "recurrent_layers", {}).items()):
idx = key[0] if isinstance(key, tuple) else key
expected = self._expected_layer_device(cmap, idx)
- actual = getattr(getattr(rl, "attention", None), "device", None)
+ 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:
@@ -847,7 +875,8 @@ def _cache_bytes(cache) -> dict[torch.device, int]:
except Exception: # noqa: BLE001 - a state type without a byte count
pass
for rl in list(getattr(cache, "recurrent_layers", {}).values()):
- dev = getattr(getattr(rl, "attention", None), "device", None)
+ dev = (getattr(rl, "device", None) or
+ getattr(getattr(rl, "module", None), "device", None))
if dev is None:
continue
try:
diff --git a/exllamav3/model_init.py b/exllamav3/model_init.py
index f941b8f..a29ac02 100755
--- a/exllamav3/model_init.py
+++ b/exllamav3/model_init.py
@@ -340,6 +340,7 @@ def init(
from .serve_split import parse_front_layers
front_layers = parse_front_layers(os.environ.get("KYOJIN_FRONT_LAYERS", "0"))
split_plan = None
+ draft_component = None
front_map = draft_map = None
if front_layers:
if args.tensor_parallel or single_device or split is not None:
@@ -357,13 +358,26 @@ def init(
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:
- split_plan.add("mtp", draft_model, config = draft_config,
- cache = draft_cache, load_order = 1)
+ 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 front 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",
+ front_eligible = False,
+ endcaps_front = False),
+ front_layers = 0, load_order = 1)
split_plan.build()
split_plan.install_bridges()
split_plan.engage_budget()
front_map = split_plan.map("text")
- draft_map = split_plan.map("mtp") if draft_model is not None else None
+ draft_map = split_plan.map(draft_component) if draft_component is not None else None
if front_map is not None:
printp(not quiet, f" -- layer split: {front_map.describe()}")
if split_plan.auto:
@@ -423,9 +437,9 @@ def init(
if split_plan is not None:
split_plan.record_load("text", 0.0)
if draft_model is not None:
- split_plan.record_load("mtp", 0.0)
+ split_plan.record_load(draft_component, 0.0)
split_plan.report(model, cache,
- extra=[("mtp", draft_model, draft_cache)] if draft_model is not None else [],
+ extra=[(draft_component, draft_model, draft_cache)] if draft_model is not None else [],
ctx=getattr(args, "cache_size", None))
split_plan.release_budget()
diff --git a/exllamav3/serve_split.py b/exllamav3/serve_split.py
index 8e9d502..47bd6a9 100644
--- a/exllamav3/serve_split.py
+++ b/exllamav3/serve_split.py
@@ -194,12 +194,6 @@ class SplitController:
plan.install_bridges()
return cmap
- def register_config(self, config) -> None:
- plan = self.build_plan()
- if plan is not None:
- plan.register_config(config)
- plan.install_bridges()
-
def build(self) -> None:
if self.plan is not None:
self.plan.build()
@@ -229,11 +223,6 @@ class SplitController:
self.plan.record_load(component, time.perf_counter() - t0)
return True
- def register_extra_components(self, components: list[tuple[str, object, object, object]]) -> None:
- """Declare ``(name, model, config, cache)`` after the target plan exists."""
- for name, model, config, cache in components:
- self.add(name, model, config = config, cache = cache)
-
def finalize(self, model, cache, extra: list[tuple[str, object, object]] | None = None,
ctx: int | None = None) -> None:
if self.plan is None:
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 7ce994f..98f128b 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -204,7 +204,7 @@ 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):
+ if fuse and os.environ.get("KYOJIN_SPLIT_ACTIVE", "0") != "0" and not _fused_output_stable(q.device):
# A layer split runs KDA on both a gfx1151 main and a gfx12 front. The fused output
# path is not run-to-run deterministic on gfx12, and the gfx11.5 HIP kernel cannot be
# JIT-built there (kda_fused_h_hip.supported() declines, so _hip_ok already fell back
diff --git a/tests/test_split_plan_cpu.py b/tests/test_split_plan_cpu.py
index fbcb75d..18e9187 100644
--- a/tests/test_split_plan_cpu.py
+++ b/tests/test_split_plan_cpu.py
@@ -94,6 +94,15 @@ class FakeCacheLayer:
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 = {}
@@ -192,6 +201,56 @@ def test_whole_component_places_every_module_front_only_with_endcaps(split_modul
assert all(off.device_for(m) == torch.device("cuda", 0) for m in mtp.modules)
+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_front(split_modules):
+ dm, _bridge, _split = split_modules
+ model = _glm_model()
+ policy = dm.component_policy("text", endcaps_front = 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, front_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, front_layers = "auto",
+ front_reserve_gb = 1.0, auto_cap = 2, logger = lambda *_a: None)
+ plan.add("text", model, config = cfg)
+ plan.build()
+ assert plan.front_layers == 2
+
+
def test_auto_n_uses_actual_bytes_cache_and_reserve(split_modules, monkeypatch):
dm, _bridge, _split = split_modules
gib = dm.GIB
@@ -246,6 +305,7 @@ def test_front_reserve_is_a_slab_not_an_allocator_cap(split_modules, monkeypatch
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")
main, front = torch.device("cuda", 0), torch.device("cuda", 1)
cfg = SimpleNamespace()
draft_cfg = SimpleNamespace()
@@ -258,6 +318,48 @@ def test_bridge_installs_per_config_and_is_reused(split_modules, monkeypatch):
assert b1 is b2
assert b1 is not b3
assert b1.pair == (main, front)
+ assert os.environ["KYOJIN_SPLIT_ACTIVE"] == "1"
+
+ single = SimpleNamespace()
+ assert bridge_mod.install_bridge(single, main, None) is None
+ assert single.split_active is False
+
+
+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, front_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
+
+
+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_front_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().front_layers == expected
def test_adapter_unsafe_env_is_applied_and_logged(split_modules, monkeypatch):
diff --git a/tools/glm/serve.py b/tools/glm/serve.py
index 2c29c7f..c237ce6 100644
--- a/tools/glm/serve.py
+++ b/tools/glm/serve.py
@@ -721,11 +721,7 @@ class ResidentEngine:
front_device = front_device or "auto",
endcaps = bool(endcaps), front_reserve_gb = float(front_reserve_gb))
self.split = SplitController(split_settings, logger = lambda m: print(f"serve: {m}", flush=True))
- self.front_layers = split_settings.front_layers
- self.endcaps = split_settings.endcaps
- self.front_reserve_gb = split_settings.front_reserve_gb
self.split_map = None
- self.split_devices = self.split.devices
if self.split.enabled:
plan = self.split.build_plan()
if plan is None or plan.devices.front is None:
@@ -733,11 +729,12 @@ class ResidentEngine:
print(f"serve: layer split: {split_settings.describe()}; "
f"main {plan.devices.main} ({plan.devices.main_arch}), "
f"front {plan.devices.front} ({plan.devices.front_arch})", flush=True)
- if isinstance(self.front_layers, int) and self.front_layers > 5 and max_ctx > 65536:
- print("serve: warning: front layers > 5 at -c > 65536 is measured to OOM the 16 GB "
- "front on long prefill (gfx1201 KDA fallback workspace); use "
- "--front-layers 5 for long-context split runs until auto sizing accounts for "
- "the KDA workspace", flush=True)
+ if split_settings.auto and max_ctx > 65536:
+ # Auto-N's byte budget does not yet know the gfx12 KDA prefill
+ # workspace; keep the measured-safe long-context cap until it does.
+ plan.auto_cap = 5
+ print("serve: layer split: auto-N capped at 5 layers for -c > 65536 "
+ "(gfx1201 KDA prefill workspace)", flush=True)
self.tokenizer = Tokenizer.from_config(self.config)
if os.environ.get("KYO_TOKCACHE", "8") == "0":
self.pec = None
@@ -785,20 +782,23 @@ class ResidentEngine:
self.split_map = self.split.map("text")
if self.split_map is not None and not self.split_map.enabled:
raise ValueError("layer split requested but no usable front device (or auto-N found no layer that fits)")
+ if self.split_map is not None and self.split_map.front_layers > 5 and max_ctx > 65536:
+ print("serve: warning: front layers > 5 at -c > 65536 is measured to OOM the 16 GB "
+ "front on long prefill (gfx1201 KDA fallback workspace); use "
+ "--front-layers 5 for long-context split runs", flush=True)
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())
- self.draft_map = None
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")
if self.split.enabled:
- self.draft_map = self.split.add("mtp", self.draft_model, config=self.config,
- cache=self.draft_cache, load_order=1)
+ self.split.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:
@@ -816,9 +816,6 @@ 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.enabled and self.endcaps
- else torch.device("cuda:0"))
self.vision = self._load_vision()
self.supports_vision = self.vision is not None
if self.split.enabled:
@@ -944,7 +941,8 @@ class ResidentEngine:
self.split.load("vision", tower, progressbar=False,
callback=startup_health.load_callback())
else:
- tower.load(device=self._vision_device, progressbar=False, callback=startup_health.load_callback())
+ tower.load(device=torch.device("cuda:0"), progressbar=False,
+ callback=startup_health.load_callback())
except Exception as exc: # noqa: BLE001
print(f"serve: vision tower not loaded ({type(exc).__name__}: {exc}); image input disabled", flush=True)
return None
diff --git a/tools/strix_halo/split_eval.py b/tools/strix_halo/split_eval.py
index da8e962..798c476 100644
--- a/tools/strix_halo/split_eval.py
+++ b/tools/strix_halo/split_eval.py
@@ -25,6 +25,14 @@ 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.",
@@ -52,7 +60,7 @@ 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("--front-layers", type=int, default=6)
+ p.add_argument("--front-layers", type=int, default=None)
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)
@@ -70,15 +78,17 @@ def parse_args() -> argparse.Namespace:
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()
+ args = p.parse_args()
+ if args.front_layers is None:
+ # N=6 is measured to OOM the 16 GiB front above 65K (gfx1201 KDA workspace).
+ args.front_layers = 5 if args.max_ctx > 65536 else 6
+ 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 ("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"):
+ 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")
@@ -180,19 +190,22 @@ def main() -> None:
cache = Cache(model, max_num_tokens = args.max_ctx + 4096, max_history = max_history,
max_batch_size = 1, **qkw)
- devices = None
+ plan = None
text_map = None
if not args.baseline:
- from exllamav3.device_map import LayerDeviceMap, resolve_devices
+ from exllamav3.device_map import SplitPlan, 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,
+ plan = SplitPlan(
+ devices, endcaps = args.endcaps == "on", front_layers = args.front_layers,
+ front_reserve_gb = 0.0 if args.no_budget else args.front_reserve_gb,
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:
+ plan.add("text", model, config = config, cache = cache, load_order = 0)
+ plan.build()
+ text_map = plan.map("text")
+ if args.front_layers > 0 and (text_map is None or not text_map.enabled):
raise SystemExit("split map not enabled (no front device)")
+ plan.install_bridges()
+ plan.engage_budget()
t0 = time.perf_counter()
if text_map is not None:
@@ -200,6 +213,8 @@ def main() -> None:
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:
@@ -207,12 +222,10 @@ def main() -> None:
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)
+ 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)
@@ -221,19 +234,23 @@ def main() -> 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)
+ 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 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()
+ 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()
GM.MTP_FUSE_CATCHUP = 2
gen = Generator(model = model, cache = cache, tokenizer = tokenizer,
diff --git a/tools/strix_halo/split_load.py b/tools/strix_halo/split_load.py
index 566bb33..f6d4b37 100644
--- a/tools/strix_halo/split_load.py
+++ b/tools/strix_halo/split_load.py
@@ -40,7 +40,7 @@ def main() -> None:
import torch
from exllamav3 import Cache, CacheLayer_quant, Config, Model
- from exllamav3.device_map import LayerDeviceMap, print_split_table, resolve_devices
+ from exllamav3.device_map import SplitPlan, resolve_devices
torch.set_grad_enabled(False)
endcaps = args.endcaps == "on"
@@ -80,38 +80,42 @@ def main() -> None:
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:
+ plan = SplitPlan(devices, endcaps=endcaps, front_layers=args.front_layers,
+ front_reserve_gb=args.front_reserve_gb)
+ plan.add("text", model, config=config, cache=cache, load_order=0)
+ 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 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)
+ 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)
- 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
+ plan.add("mtp", draft, config=config, cache=draft_cache, load_order=1)
t1 = time.perf_counter()
- draft.load(device_map=draft_map, progressbar=True, max_chunk_size=4096)
+ 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")
- vdev = devices.front if endcaps else devices.main
+ plan.add("vision", vision, config=config, load_order=2)
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)
+ 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').used_devices}", flush=True)
except Exception as exc: # noqa: BLE001
print(f"[split] vision not loaded: {type(exc).__name__}: {exc}", flush=True)
vision = None
@@ -121,8 +125,8 @@ def main() -> 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()
+ 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; "