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.

37.0 KB
Raw Blame
"""CPU contract tests for the universal split core.

The placement rules, endcap allowlist, auto-N arithmetic and the layout-neutral
part0 reserve are pure Python/torch-device logic: they run without a GPU or the
compiled extension.  The integration gates (loads, determinism, needle) stay in
the strix_halo harnesses.
"""
from __future__ import annotations

import importlib.util
import os
import sys
import types
from pathlib import Path
from types import SimpleNamespace

import pytest
import torch

ROOT = Path(__file__).resolve().parents[1]


def _load_module(name: str, path: Path):
    spec = importlib.util.spec_from_file_location(name, path)
    assert spec is not None and spec.loader is not None
    module = importlib.util.module_from_spec(spec)
    sys.modules[name] = module
    spec.loader.exec_module(module)
    return module


@pytest.fixture(scope = "module")
def split_modules():
    added = []
    if "exllamav3" not in sys.modules:
        pkg = types.ModuleType("exllamav3")
        pkg.__path__ = [str(ROOT / "exllamav3")]
        sys.modules["exllamav3"] = pkg
        added.append("exllamav3")
    if "exllamav3.util" not in sys.modules:
        util = types.ModuleType("exllamav3.util")
        util.__path__ = [str(ROOT / "exllamav3" / "util")]
        sys.modules["exllamav3.util"] = util
        added.append("exllamav3.util")
    if "exllamav3.util.arch_list" not in sys.modules:
        _load_module("exllamav3.util.arch_list", ROOT / "exllamav3" / "util" / "arch_list.py")
        added.append("exllamav3.util.arch_list")
    dm = _load_module("exllamav3.device_map", ROOT / "exllamav3" / "device_map.py")
    bridge = _load_module("exllamav3.bridge", ROOT / "exllamav3" / "bridge.py")
    split = _load_module("exllamav3.serve_split", ROOT / "exllamav3" / "serve_split.py")
    yield dm, bridge, split
    for name in ("exllamav3.serve_split", "exllamav3.bridge", "exllamav3.device_map"):
        sys.modules.pop(name, None)
    for name in added:
        sys.modules.pop(name, None)


class FakeModule:
    def __init__(self, key, layer_idx = None, caps = None, numel = 0):
        self.key = key
        self.layer_idx = layer_idx
        self.caps = caps or {}
        self._numel = numel

    def weights_numel(self):
        return self._numel


class FakeModel:
    def __init__(self, modules):
        self.modules = modules


class FakeSTC:
    def __init__(self, sizes):
        self.sizes = sizes

    def get_tensor_sizes(self, key):
        return [self.sizes.get(key, 0)]


class FakeConfig:
    def __init__(self, sizes):
        self.stc = FakeSTC(sizes)


class FakeCacheLayer:
    def __init__(self, size):
        self.size = size
        self.device = None
        self.attention = SimpleNamespace(device = None)

    def storage_size(self):
        return self.size


class FakeRecurrent:
    def __init__(self, size, device):
        self.size = size
        self.device = device

    def storage_size(self):
        return self.size


class FakeCache:
    def __init__(self, per_layer = 0):
        self.layers = {}
        self.recurrent_layers = {}
        if per_layer:
            for i in range(16):
                self.layers[(i, 0)] = FakeCacheLayer(per_layer)


class FakeProps:
    def __init__(self, total):
        self.total_memory = total


def _devices(dm):
    return dm.Devices(
        part1 = torch.device("cuda", 0),
        part0 = torch.device("cuda", 1),
        part1_arch = "gfx1151",
        part0_arch = "gfx1201",
    )


def _infos(dm, *pairs):
    """Synthetic device inventory: (arch, optional name/uuid) per device index."""
    out = []
    for i, item in enumerate(pairs):
        if isinstance(item, str):
            arch, name, uuid = item, f"device-{i}", ""
        else:
            arch = item[0]
            name = item[1] if len(item) > 1 else f"device-{i}"
            uuid = item[2] if len(item) > 2 else ""
        out.append(dm.DeviceInfo(index = i, name = name, arch = arch, uuid = uuid))
    return out


@pytest.fixture(autouse = True)
def _disable_default_oom_guard(split_modules, monkeypatch):
    """The CPU placement tests are not guard tests: keep the pre-flight check off.

    The guard integration test passes an explicit guard, so it is unaffected.
    """
    dm = split_modules[0]
    monkeypatch.setattr(dm.GuardPolicy, "from_env",
                        classmethod(lambda cls, default_mode = "auto", explicit_mode = None:
                                    cls(mode = explicit_mode or "off")))


@pytest.fixture
def clean_split_env(monkeypatch):
    for key in ("KYOJIN_PART0_DEVICE", "KYOJIN_PART1_DEVICE", "KYOJIN_PART0_LAYERS", "KYOJIN_ENDCAPS"):
        monkeypatch.delenv(key, raising = False)


def _glm_model():
    embedding = FakeModule("model.language_model.embed_tokens", caps = {"prefer_cpu": True})
    expand = FakeModule("hc_expand")
    layers = [FakeModule(f"model.language_model.layers.{i}", layer_idx = i) for i in range(4)]
    norm = FakeModule("model.language_model.norm")
    head = FakeModule("lm_head", caps = {"logits_output": True})
    ngram = FakeModule("ngram", caps = {})
    return FakeModel([embedding, expand] + layers + [norm, head, ngram])


def test_component_policy_defaults(split_modules):
    dm, _bridge, _split = split_modules
    text = dm.component_policy("text")
    mtp = dm.component_policy("mtp")
    aux = dm.component_policy("ngram")
    assert text.kind == "text" and text.part0_eligible and text.endcaps_part0
    assert "RMSNorm" in text.endcap_types and "lm_head" in text.endcap_key_suffixes
    assert mtp.kind == "mtp" and mtp.whole_component and mtp.part0_eligible
    assert aux.kind == "aux" and not aux.part0_eligible


def test_text_placement_uses_endcap_allowlist_and_safe_unknown_default(split_modules):
    dm, _bridge, _split = split_modules
    model = _glm_model()
    cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text")
    devices = {m.key: cmap.device_for(m) for m in model.modules}

    assert devices["model.language_model.embed_tokens"] == torch.device("cpu")
    assert devices["hc_expand"] == torch.device("cuda", 1)
    assert devices["model.language_model.norm"] == torch.device("cuda", 1)
    assert devices["lm_head"] == torch.device("cuda", 1)
    assert devices["ngram"] == torch.device("cuda", 0)          # unknown non-layer: part1, warning default
    for i in range(4):
        assert devices[f"model.language_model.layers.{i}"] == torch.device("cuda", 1 if i < 2 else 0)


def test_endcaps_off_follows_neighbours_only_for_allowlisted_modules(split_modules):
    dm, _bridge, _split = split_modules
    model = _glm_model()
    cmap = dm.ComponentMap.from_model(model, 2, False, _devices(dm), component = "text")
    devices = {m.key: cmap.device_for(m) for m in model.modules}

    assert devices["hc_expand"] == torch.device("cuda", 1)      # prologue follows layer 0
    assert devices["model.language_model.norm"] == torch.device("cuda", 0)   # epilogue: last layer is part1
    assert devices["lm_head"] == torch.device("cuda", 0)
    assert devices["ngram"] == torch.device("cuda", 0)

    all_part0 = dm.ComponentMap.from_model(model, 4, False, _devices(dm), component = "text")
    devices = {m.key: all_part0.device_for(m) for m in model.modules}
    assert devices["model.language_model.norm"] == torch.device("cuda", 1)
    assert devices["lm_head"] == torch.device("cuda", 1)


def test_layer_device_map_alias_keeps_harness_api(split_modules):
    dm, _bridge, _split = split_modules
    model = _glm_model()
    cmap = dm.LayerDeviceMap.from_model(model, 2, True, _devices(dm), component = "text")
    assert isinstance(cmap, dm.ComponentMap)
    assert cmap.part0_layers == 2 and cmap.enabled


def test_whole_component_places_every_module_part0_only_with_endcaps(split_modules):
    dm, _bridge, _split = split_modules
    mtp = FakeModel([
        FakeModule("mtp.pre", caps = {}),
        FakeModule("mtp.block.0", layer_idx = 0),
        FakeModule("mtp.block.1", layer_idx = 1),
        FakeModule("mtp.head", caps = {}),
    ])
    on = dm.ComponentMap.from_model(mtp, 0, True, _devices(dm), component = "mtp")
    off = dm.ComponentMap.from_model(mtp, 0, False, _devices(dm), component = "mtp")
    assert all(on.device_for(m) == torch.device("cuda", 1) for m in mtp.modules)
    assert all(off.device_for(m) == torch.device("cuda", 0) for m in mtp.modules)


def test_whole_component_reports_only_placed_devices(split_modules):
    dm, _bridge, _split = split_modules
    mtp = FakeModel([
        FakeModule("mtp.embed", caps = {"prefer_cpu": True}),
        FakeModule("mtp.pre", caps = {}),
        FakeModule("mtp.block.0", layer_idx = 0),
        FakeModule("mtp.head", caps = {}),
    ])
    on = dm.ComponentMap.from_model(mtp, 0, True, _devices(dm), component = "mtp")
    off = dm.ComponentMap.from_model(mtp, 0, False, _devices(dm), component = "mtp")
    assert on.placed_devices == [torch.device("cuda", 1)]
    assert off.placed_devices == [torch.device("cuda", 0)]
    assert torch.device("cpu") not in on.placed_devices + off.placed_devices


def test_module_bytes_uses_compile_or_alt_key_when_prefix_is_empty(split_modules):
    dm, _bridge, _split = split_modules
    stc = FakeSTC({"embed_tokens": 456})
    head = FakeModule("hc_head")
    head.get_compile_sizes = lambda s: [123]
    assert dm._module_bytes(head, stc) == 123
    tied = FakeModule("lm_head")
    tied.alt_key = "embed_tokens"
    assert dm._module_bytes(tied, stc) == 456


def test_policy_can_disable_endcap_part0(split_modules):
    dm, _bridge, _split = split_modules
    model = _glm_model()
    policy = dm.component_policy("text", endcaps_part0 = False)
    cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text", policy = policy)
    devices = {m.key: cmap.device_for(m) for m in model.modules}
    assert devices["hc_expand"] == torch.device("cuda", 0)
    assert devices["model.language_model.norm"] == torch.device("cuda", 0)
    assert devices["model.language_model.layers.0"] == torch.device("cuda", 1)


def test_recurrent_placement_audit_reads_state_device(split_modules):
    dm, _bridge, _split = split_modules
    model = FakeModel([FakeModule("layer.0", layer_idx = 0)])
    cache = FakeCache()
    cache.recurrent_layers[(0, 0)] = FakeRecurrent(1024, torch.device("cuda", 0))
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 1,
                        logger = lambda *_a: None)
    plan.add("text", model, cache = cache)
    plan.build()
    assert "text" in plan.audit_caches()

    cache.recurrent_layers[(0, 0)] = FakeRecurrent(1024, torch.device("cuda", 1))
    assert plan.audit_caches() == {}


def test_auto_n_is_capped_for_long_context(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    gib = dm.GIB
    model = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    cfg = FakeConfig({f"layer.{i}": gib for i in range(4)})
    monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25")
    monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(16 * gib))
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",
                        part0_reserve_gb = 1.0, auto_cap = 2, logger = lambda *_a: None)
    plan.add("text", model, config = cfg)
    plan.build()
    assert plan.part0_layers == 2


def test_auto_n_uses_actual_bytes_cache_and_reserve(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    gib = dm.GIB
    sizes = {f"layer.{i}": gib for i in range(4)}
    sizes["final_norm"] = gib // 10
    model = FakeModel([
        FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)
    ] + [FakeModule("final_norm")])
    cfg = FakeConfig(sizes)
    cache = FakeCache(per_layer = gib // 5)                    # 0.2 GiB per layer, only 16 keys exist
    monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25")       # pin the arithmetic below
    monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(6 * gib))

    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",
                        part0_reserve_gb = 1.0, logger = lambda *_a: None)
    plan.add("text", model, config = cfg, cache = cache)
    plan.build()

    # budget 6 - 1 reserve - 0.25 safety = 4.75 GiB; each layer is 1.0 weights +
    # 0.2 cache, endcap 0.1. N=3 -> 3.7, N=4 -> 4.9.
    assert plan.part0_layers == 3
    assert plan.map("text").part0_layers == 3

    plan_off = dm.SplitPlan(_devices(dm), endcaps = False, part0_layers = "auto",
                            part0_reserve_gb = 1.0, logger = lambda *_a: None)
    plan_off.add("text", model, config = cfg, cache = cache)
    plan_off.build()
    assert plan_off.part0_layers == 3


def test_auto_n_subtracts_a_predeclared_whole_component(split_modules, monkeypatch):
    """MTP/vision are declared before build() so auto-N can subtract them from part0."""
    dm, _bridge, _split = split_modules
    gib = dm.GIB
    text = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    text_cfg = FakeConfig({f"layer.{i}": gib for i in range(4)})
    mtp = FakeModel([FakeModule("mtp.block.0", layer_idx = 0), FakeModule("mtp.head")])
    mtp_cfg = FakeConfig({"mtp.block.0": 2 * gib, "mtp.head": gib // 2})
    mtp_cache = FakeCache()
    mtp_cache.layers[(0, 0)] = FakeCacheLayer(3 * gib // 4)     # one 0.75 GiB drafter layer
    monkeypatch.setenv("KYOJIN_AUTON_SAFETY_GB", "0.25")        # pin the arithmetic below
    monkeypatch.setattr(dm.torch.cuda, "get_device_properties", lambda dev: FakeProps(6 * gib))

    # Budget 6 - 1 reserve - 0.25 safety = 4.75 GiB: text alone fits all 4 layers.
    plain = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",
                         part0_reserve_gb = 1.0, logger = lambda *_a: None)
    plain.add("text", text, config = text_cfg)
    plain.build()
    assert plain.part0_layers == 4

    # The 2.5 GiB drafter is a whole component on part0 with endcaps on, so the text
    # map can only use 4.75 - 2.5 = 2.25 GiB -> N=2.
    with_mtp = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",
                            part0_reserve_gb = 1.0, logger = lambda *_a: None)
    with_mtp.add("mtp", mtp, config = mtp_cfg)
    with_mtp.add("text", text, config = text_cfg)
    with_mtp.build()
    assert with_mtp.part0_layers == 2
    assert with_mtp.map("mtp").part0_layers == 1

    # The drafter cache is part of the same footprint: 2.5 GiB weights + 0.75 GiB cache
    # leaves 1.5 GiB -> N=1.  A test with weights only would miss that second term.
    with_cache = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = "auto",
                              part0_reserve_gb = 1.0, logger = lambda *_a: None)
    with_cache.add("mtp", mtp, config = mtp_cfg, cache = mtp_cache)
    with_cache.add("text", text, config = text_cfg)
    with_cache.build()
    assert with_cache.part0_layers == 1

    # Endcaps off puts the drafter on part1, so it does not consume the text budget.
    off = dm.SplitPlan(_devices(dm), endcaps = False, part0_layers = "auto",
                       part0_reserve_gb = 1.0, logger = lambda *_a: None)
    off.add("mtp", mtp, config = mtp_cfg)
    off.add("text", text, config = text_cfg)
    off.build()
    assert off.part0_layers == 4
    assert not off.map("mtp").enabled


def test_part0_reserve_is_a_slab_not_an_allocator_cap(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    model = _glm_model()
    cmap = dm.ComponentMap.from_model(model, 2, True, _devices(dm), component = "text",
                                      part0_reserve_gb = 0.5)
    calls = []

    def fake_empty(size, dtype = None, device = None):
        calls.append((size, dtype, device))
        return object()

    monkeypatch.setattr(dm.torch, "empty", fake_empty)
    monkeypatch.setattr(dm.torch.cuda, "set_per_process_memory_fraction",
                        lambda *_a, **_k: pytest.fail("the split must not cap the allocator"))
    cmap.engage_budget()
    assert len(calls) == 1
    assert calls[0][0] == int(0.5 * dm.GIB)
    assert calls[0][2] == torch.device("cuda", 1)
    cmap.release_part0_budget()
    assert cmap._reserve_slabs == {}


def test_bridge_installs_per_config_and_is_reused(split_modules, monkeypatch):
    dm, bridge_mod, _split = split_modules
    monkeypatch.setenv("KYOJIN_BRIDGE", "1")
    monkeypatch.setenv("KYOJIN_SPLIT_ACTIVE", "0")
    part1, part0 = torch.device("cuda", 0), torch.device("cuda", 1)
    cfg = SimpleNamespace()
    draft_cfg = SimpleNamespace()

    b1 = bridge_mod.install_bridge(cfg, part1 = part1, part0 = part0)
    b2 = bridge_mod.install_bridge(cfg, part1 = part1, part0 = part0)
    b3 = bridge_mod.install_bridge(draft_cfg, part1 = part1, part0 = part0)

    assert cfg.split_active is True and draft_cfg.split_active is True
    assert b1 is b2
    assert b1 is not b3
    assert b1.pair == (part1, part0)
    assert os.environ["KYOJIN_SPLIT_ACTIVE"] == "1"

    # The pair is keyword-only so a caller cannot silently pass (part1, part0) backwards.
    with pytest.raises(TypeError):
        bridge_mod.install_bridge(cfg, part1, part0)

    single = SimpleNamespace()
    assert bridge_mod.install_bridge(single, part1 = part1, part0 = None) is None
    assert single.split_active is False


def test_disabled_bridge_forces_host_bounce(split_modules, monkeypatch):
    _dm, bridge_mod, _split = split_modules
    from exllamav3.util import device_copy

    monkeypatch.setenv("KYOJIN_BRIDGE", "0")
    old = device_copy.FORCED
    device_copy.FORCED = None
    try:
        cfg = SimpleNamespace()
        assert bridge_mod.install_bridge(
            cfg, part1 = torch.device("cuda", 0), part0 = torch.device("cuda", 1)) is None
        assert cfg.split_active is True
        assert device_copy.FORCED is True
    finally:
        device_copy.FORCED = old


def test_named_preset_is_applied_by_the_plan(split_modules, monkeypatch):
    dm, _bridge, split = split_modules
    monkeypatch.setenv("EXL3_TEST_PRESET", "0")
    old = split.SPLIT_PRESETS.get("glm", {})
    split.SPLIT_PRESETS["glm"] = {"EXL3_TEST_PRESET": "1"}
    try:
        plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 1,
                            preset = "glm", logger = lambda *_a: None)
        plan.add("text", _glm_model())
        plan.build()
        assert os.environ["EXL3_TEST_PRESET"] == "1"
    finally:
        split.SPLIT_PRESETS["glm"] = old


@pytest.mark.parametrize("archs", [
    ("gfx1100", "gfx1101"),                 # RDNA3
    ("gfx1150", "gfx1151"),                 # RDNA3.5
    ("gfx1200", "gfx1201"),                 # RDNA4
    ("gfx1151", "gfx1100"),                 # mixed, reversed
    ("gfx1201", "gfx1201"),                 # same arch
    ("gfx1100", "gfx1100"),
    ("", "sm_90"),                          # unknown / CUDA-style names: selection only
])
def test_auto_selection_is_positional_and_arch_independent(split_modules, clean_split_env, archs):
    dm, _bridge, _split = split_modules
    devices = dm.resolve_devices(devices = _infos(dm, *archs))
    assert devices.part1 == torch.device("cuda", 0)
    assert devices.part0 == torch.device("cuda", 1)
    assert devices.part1_arch == archs[0] and devices.part0_arch == archs[1]
    assert [d.index for d in devices.inventory] == [0, 1]


def test_explicit_selectors_support_both_positions(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    infos = _infos(dm, "gfx1151", "gfx1201")

    mixed = dm.resolve_devices("cuda:1", "cuda:0", devices = infos)
    assert (mixed.part1_arch, mixed.part0_arch) == ("gfx1151", "gfx1201")

    reversed_pair = dm.resolve_devices("gfx1151", "gfx1201", devices = infos)
    assert reversed_pair.part1 == torch.device("cuda", 1)
    assert reversed_pair.part0 == torch.device("cuda", 0)
    assert (reversed_pair.part1_arch, reversed_pair.part0_arch) == ("gfx1201", "gfx1151")

    by_name_uuid = dm.resolve_devices("device-1", "device-0", devices = infos)
    assert by_name_uuid.part1 == torch.device("cuda", 0)
    assert by_name_uuid.part0 == torch.device("cuda", 1)


def test_explicit_part0_with_auto_part1_uses_the_other_device(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    infos = _infos(dm, "gfx1151", "gfx1201")

    by_index = dm.resolve_devices("cuda:0", devices = infos)
    assert by_index.part1 == torch.device("cuda", 1)
    assert by_index.part0 == torch.device("cuda", 0)

    by_arch = dm.resolve_devices("gfx1151", devices = infos)
    assert by_arch.part1 == torch.device("cuda", 1)
    assert by_arch.part0 == torch.device("cuda", 0)

    many = _infos(dm, "gfx1100", "gfx1151", "gfx1201")
    with pytest.raises(RuntimeError, match = "set KYOJIN_PART1_DEVICE"):
        dm.resolve_devices("cuda:0", devices = many)


def test_uuid_and_name_substring_selectors(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    infos = _infos(
        dm,
        ("gfx1201", "AMD Radeon RX 9070 XT", "aa-bb-cc"),
        ("gfx1151", "AMD Radeon 8060S", "dd-ee-ff"),
    )
    dev = dm.resolve_devices("aa-bb-cc", "8060s", devices = infos)
    assert dev.part1 == torch.device("cuda", 1)
    assert dev.part0 == torch.device("cuda", 0)


def test_part1_device_env_is_honoured(split_modules, clean_split_env, monkeypatch):
    dm, _bridge, _split = split_modules
    monkeypatch.setenv("KYOJIN_PART1_DEVICE", "cuda:1")
    dev = dm.resolve_devices(devices = _infos(dm, "gfx1151", "gfx1201"))
    assert dev.part1 == torch.device("cuda", 1)
    assert dev.part0 == torch.device("cuda", 0)


def test_one_device_fails_clearly(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    with pytest.raises(RuntimeError, match = "two devices"):
        dm.resolve_devices(devices = _infos(dm, "gfx1151"))


def test_three_devices_require_an_explicit_part0(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    infos = _infos(dm, "gfx1100", "gfx1151", "gfx1201")
    with pytest.raises(RuntimeError, match = "3 devices.*--part0-device"):
        dm.resolve_devices(devices = infos)
    dev = dm.resolve_devices("cuda:2", "cuda:1", devices = infos)
    assert dev.part1 == torch.device("cuda", 1)
    assert dev.part0 == torch.device("cuda", 2)


def test_same_device_and_bad_selectors_fail_clearly(split_modules, clean_split_env):
    dm, _bridge, _split = split_modules
    infos = _infos(dm, "gfx1151", "gfx1201")
    with pytest.raises(RuntimeError, match = "same device"):
        dm.resolve_devices("cuda:0", "cuda:0", devices = infos)
    with pytest.raises(RuntimeError, match = "no such device"):
        dm.resolve_devices("cuda:9", devices = infos)
    with pytest.raises(RuntimeError, match = "did not match any device"):
        dm.resolve_devices("gfx9999", devices = infos)


def test_settings_parse_part1_device_and_keep_split_off_off(split_modules, clean_split_env, monkeypatch):
    dm, _bridge, split = split_modules
    monkeypatch.setenv("KYOJIN_PART1_DEVICE", "cuda:1")
    args = SimpleNamespace(part0_layers = None, part0_device = None, part1_device = None,
                           endcaps = None, split_preset = None, split_graphs = None,
                           part0_reserve_gb = None)
    settings = split.settings_from_namespace(args)
    assert settings.part1_device == "cuda:1"
    assert settings.enabled is False

    args.part1_device = "gfx1100"
    args.part0_device = "gfx1151"
    args.part0_layers = "2"
    settings = split.settings_from_namespace(args)
    assert (settings.part1_device, settings.part0_device) == ("gfx1100", "gfx1151")
    assert settings.enabled is True


def test_split_off_does_not_touch_device_selection(split_modules, monkeypatch):
    dm, _bridge, split = split_modules

    def boom(*_a, **_k):
        pytest.fail("split off must not enumerate or resolve devices")

    monkeypatch.setattr(dm, "resolve_devices", boom)
    controller = split.SplitController(split.SplitSettings(part0_layers = 0,
                                                           part1_device = "cuda:9",
                                                           part0_device = "cuda:9"),
                                       logger = lambda *_a: None)
    assert controller.devices is None
    assert controller.plan is None


def test_split_core_and_help_name_no_hardware(split_modules):
    for rel in ("exllamav3/device_map.py", "exllamav3/serve_split.py"):
        text = (ROOT / rel).read_text()
        for name in ("gfx1151", "gfx1201", "gfx1100", "9070", "8060S", "Strix", "eGPU", "iGPU", "USB4"):
            assert name not in text, f"{rel} still names {name}"


def _load_split_eval():
    path = ROOT / "tools" / "strix_halo" / "split_eval.py"
    spec = importlib.util.spec_from_file_location("split_eval_harness", path)
    assert spec is not None and spec.loader is not None
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def test_harness_graph_env_matches_shared_list(split_modules):
    _dm, _bridge, split = split_modules
    mod = _load_split_eval()
    assert set(mod.GRAPH_ENV_OFF) == set(split.GRAPH_ENV_OFF)


def test_harness_default_part0_layers_depends_on_context(monkeypatch):
    mod = _load_split_eval()
    for ctx, expected in ((131072, 5), (65536, 6)):
        monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", str(ctx)])
        assert mod.parse_args().part0_layers == expected


def test_harness_part0_layers_are_explicit_flags(monkeypatch):
    mod = _load_split_eval()
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072", "--part0-layers", "7"])
    assert mod.parse_args().part0_layers == 7
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--max-ctx", "131072",
                                      "--long-ctx-part0-layers", "3"])
    args = mod.parse_args()
    assert args.part0_layers == 3 and args.part0_layers_defaulted is True


def test_harness_acceptance_flags_and_interval(monkeypatch):
    mod = _load_split_eval()
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--bench-depth", "8192",
                                      "--bench-acceptance", "--bench-prompt", "summary"])
    args = mod.parse_args()
    assert args.bench_depth == 8192 and args.bench_acceptance
    assert args.bench_prompt == "summary"
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--vision-image", "doc/cat.png"])
    assert mod.parse_args().vision_image == "doc/cat.png"
    # Wilson interval: 0/0 has no interval, a larger sample is tighter than a small one.
    assert mod.acceptance_ci95(0, 0) is None
    small = mod.acceptance_ci95(1, 1)
    large = mod.acceptance_ci95(500, 500)
    assert small[0] < large[0] <= large[1] < small[1]
    lo, hi = mod.acceptance_ci95(75, 25)
    assert 65.0 < lo < 75.0 < hi < 85.0


def test_harness_acceptance_needs_depth(monkeypatch):
    mod = _load_split_eval()
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--bench-acceptance"])
    with pytest.raises(SystemExit):
        mod.parse_args()


def test_harness_vision_image_rejects_no_vision(monkeypatch):
    mod = _load_split_eval()
    monkeypatch.setattr(sys, "argv", ["split_eval.py", "--vision-image", "doc/cat.png",
                                      "--no-vision"])
    with pytest.raises(SystemExit):
        mod.parse_args()


def test_harness_compare_checks_every_summary_run(tmp_path, capsys):
    import json
    mod = _load_split_eval()
    long = lambda ids_b: {
        "prompt": "summary-set", "ids": [1, 2], "accepted": 90, "rejected": 10,
        "acceptance": 90.0,
        "runs": [
            {"instruction": "first", "ids": [1, 2]},
            {"instruction": "second", "ids": ids_b},
        ],
    }
    a = {"prompts": [], "long": long([3, 4])}
    b = {"prompts": [], "long": long([3, 5])}
    for name, rec in (("a.json", a), ("b.json", b)):
        (tmp_path / name).write_text(json.dumps(rec))
    mod.compare(str(tmp_path / "a.json"), str(tmp_path / "b.json"))
    out = capsys.readouterr().out
    assert "long run 1 DIVERGED" in out
    assert "long runs: IDENTICAL" not in out


def test_harness_compare_skips_small_acceptance_samples(tmp_path, capsys):
    import json
    mod = _load_split_eval()
    rec = {"prompts": [], "long": {
        "prompt": "summary-set", "ids": [1], "accepted": 40, "rejected": 10,
        "acceptance": 80.0, "runs": [{"instruction": "only", "ids": [1]}]}}
    (tmp_path / "a.json").write_text(json.dumps(rec))
    (tmp_path / "b.json").write_text(json.dumps(rec))
    mod.compare(str(tmp_path / "a.json"), str(tmp_path / "b.json"))
    out = capsys.readouterr().out
    assert "acceptance: sample too small" in out
    assert "acceptance: first" not in out

    passkey = {"prompts": [], "long": {
        "prompt": "passkey", "ids": [1], "accepted": 15, "rejected": 1,
        "acceptance": 93.75, "runs": None}}
    (tmp_path / "a.json").write_text(json.dumps(passkey))
    (tmp_path / "b.json").write_text(json.dumps(passkey))
    mod.compare(str(tmp_path / "a.json"), str(tmp_path / "b.json"))
    out = capsys.readouterr().out
    assert "acceptance: skipped (passkey" in out


def test_adapter_unsafe_env_is_applied_and_logged(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    monkeypatch.setenv("EXL3_TEST_UNSAFE", "0")
    policy = dm.component_policy("text", unsafe_env = (("EXL3_TEST_UNSAFE", "1"),))
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 1, logger = lambda *_a: None)
    plan.add("text", _glm_model(), policy = policy)
    plan.build()
    assert os.environ["EXL3_TEST_UNSAFE"] == "1"


def test_split_settings_off_is_a_noop(split_modules, monkeypatch):
    _dm, _bridge, split = split_modules
    monkeypatch.setenv("EXL3_BLOCK_GRAPH", "1")
    for _k in ("EXL3_PF_HC_FUSE", "EXL3_PF_GR_FUSE", "EXL3_GR_PF_FUSE"):
        monkeypatch.setenv(_k, "1")
    off = split.SplitSettings(part0_layers = 0)
    assert off.enabled is False
    assert split.apply_split_env(off) == []
    assert os.environ["EXL3_BLOCK_GRAPH"] == "1"

    on = split.SplitSettings(part0_layers = "auto")
    assert on.enabled is True and on.auto is True
    split.apply_split_env(on)
    assert os.environ["EXL3_BLOCK_GRAPH"] == "0"
    # Deferred residual fusions cannot cross the host-staged bridge.
    assert os.environ["EXL3_PF_HC_FUSE"] == "0"
    assert os.environ["EXL3_PF_GR_FUSE"] == "0"
    assert os.environ["EXL3_GR_PF_FUSE"] == "0"


def _fake_guard_probe(dm, monkeypatch, *, mg, part0_total=16 * 1024 ** 3,
                      part1_total=118 * 1024 ** 3, host_available=120 * 1024 ** 3):
    monkeypatch.setattr(dm.torch.cuda, "is_available", lambda: True)
    monkeypatch.setattr(dm, "device_total_bytes",
                        lambda i: part0_total if i == 1 else part1_total)
    monkeypatch.setattr(dm, "device_free_bytes",
                        lambda i: part0_total if i == 1 else part1_total)
    monkeypatch.setattr(dm, "device_reusable_bytes",
                        lambda i: part0_total if i == 1 else part1_total)
    monkeypatch.setattr(mg, "is_unified_device", lambda i: i == 0)
    monkeypatch.setattr(dm, "host_available_bytes", lambda: host_available)


def test_split_plan_guard_passes_or_refuses_before_allocation(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])
    gib = dm.GIB

    small = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    small_cfg = FakeConfig({f"layer.{i}": gib // 2 for i in range(4)})
    _fake_guard_probe(dm, monkeypatch, mg=mg)
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
                        guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
                                            logger = lambda *_a: None),
                        logger = lambda *_a: None)
    plan.add("text", small, config = small_cfg)
    plan.build()
    assert plan.guard_report is not None and plan.guard_report.ok
    footprints = {r.footprint.index: r.footprint for r in plan.guard_report.device_results}
    # cuda:0 is the unified part1: configured workspace plus the host check.
    assert footprints[0].unified and footprints[0].workspace_bytes == 2 * gib
    # cuda:1 is a dedicated part0: no workspace, only the hard-fit device cap.
    assert not footprints[1].unified and footprints[1].workspace_bytes == 0
    assert plan.guard_report.host_result is not None

    huge = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    huge_cfg = FakeConfig({f"layer.{i}": 40 * gib for i in range(4)})
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
                        guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
                                            logger = lambda *_a: None),
                        logger = lambda *_a: None)
    plan.add("text", huge, config = huge_cfg)
    with pytest.raises(mg.OOMGuardError, match = "pre-flight OOM guard"):
        plan.build()

    # off skips the check entirely.
    off = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
                       guard = dm.OOMGuard(dm.GuardPolicy(mode = "off"),
                                           logger = lambda *_a: None),
                       logger = lambda *_a: None)
    off.add("text", huge, config = huge_cfg)
    off.build()
    assert off.guard_report is None


def test_preload_guard_uses_raw_free_not_allocator_cached(split_modules, monkeypatch):
    """Before a target is resident, cached blocks do not make a load fit."""
    dm, _bridge, _split = split_modules
    mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])
    gib = dm.GIB

    text = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    text_cfg = FakeConfig({f"layer.{i}": gib // 2 for i in range(4)})
    _fake_guard_probe(dm, monkeypatch, mg=mg)
    monkeypatch.setattr(dm, "device_free_bytes", lambda _i: gib // 10)
    monkeypatch.setattr(dm, "device_reusable_bytes", lambda _i: 16 * gib)

    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
                        guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
                                            logger = lambda *_a: None),
                        logger = lambda *_a: None)
    plan.add("text", text, config = text_cfg)
    with pytest.raises(mg.OOMGuardError, match = "deficit"):
        plan.build()


def test_late_component_uses_allocator_cached_bytes(split_modules, monkeypatch):
    """After the target load, reuse the allocator's cached blocks, not raw free."""
    dm, _bridge, _split = split_modules
    mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])
    gib = dm.GIB

    text = FakeModel([FakeModule(f"layer.{i}", layer_idx = i) for i in range(4)])
    text_cfg = FakeConfig({f"layer.{i}": gib // 2 for i in range(4)})
    mtp = FakeModel([FakeModule("mtp.block.0", layer_idx = 0), FakeModule("mtp.head")])
    mtp_cfg = FakeConfig({"mtp.block.0": 3 * gib, "mtp.head": gib})

    _fake_guard_probe(dm, monkeypatch, mg=mg)
    plan = dm.SplitPlan(_devices(dm), endcaps = True, part0_layers = 2,
                        guard = dm.OOMGuard(dm.GuardPolicy(mode = "auto"),
                                            logger = lambda *_a: None),
                        logger = lambda *_a: None)
    plan.add("text", text, config = text_cfg)
    plan.build()
    assert plan.guard_report is not None and plan.guard_report.ok
    plan.record_load("text", 1.0)

    # Driver-free is 1 GiB, but the allocator holds 15 GiB of reusable cached blocks.
    raw_free = 1 * gib
    monkeypatch.setattr(dm, "device_free_bytes", lambda _i: raw_free)
    monkeypatch.setattr(dm, "device_reusable_bytes", lambda _i: 16 * gib)
    plan.add("mtp", mtp, config = mtp_cfg)
    assert plan.guard_report is not None and plan.guard_report.ok
    part0 = next(r for r in plan.guard_report.device_results if r.footprint.index == 1)
    assert part0.footprint.need_bytes > raw_free
    assert part0.capacity_bytes == 16 * gib

    # The same component is refused when only raw free is reported.
    monkeypatch.setattr(dm, "device_reusable_bytes", lambda _i: raw_free)
    with pytest.raises(mg.OOMGuardError, match = "deficit"):
        plan.check_guard()

def test_guard_mode_is_normalized_from_env_style_values(split_modules):
    _dm, _bridge, split = split_modules
    assert split.SplitSettings(part0_layers = 1, oom_guard = "OFF").guard_mode == "off"


def test_single_device_guard_includes_extra_components(split_modules, monkeypatch):
    dm, _bridge, _split = split_modules
    mg = __import__("exllamav3.memory_guard", fromlist = ["OOMGuardError"])
    gib = dm.GIB
    monkeypatch.setattr(dm.torch.cuda, "is_available", lambda: True)
    monkeypatch.setattr(mg, "device_total_bytes", lambda _i: 118 * gib)
    monkeypatch.setattr(mg, "device_free_bytes", lambda _i: 118 * gib)
    monkeypatch.setattr(mg, "host_available_bytes", lambda: 120 * gib)
    monkeypatch.setattr(mg, "is_unified_device", lambda _i: True)

    target = FakeModel([FakeModule("layer.0", layer_idx = 0)])
    target_cfg = FakeConfig({"layer.0": 1 * gib})
    extra = FakeModel([FakeModule("mtp.0")])
    extra_cfg = FakeConfig({"mtp.0": 116 * gib})

    dm.check_single_device_guard(target, target_cfg, None, 0, guard_mode = "auto",
                                 logger = lambda *_a: None)
    with pytest.raises(mg.OOMGuardError, match = "refused the load"):
        dm.check_single_device_guard(target, target_cfg, None, 0, guard_mode = "auto",
                                     extra_components = [(extra, extra_cfg, None)],
                                     logger = lambda *_a: None)