okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-tuicfg (final c6dda74bf) into f-0213-int049ae1c67

main
11.6 KiB230 linesraw
1"""strata_control/intel_spec.py: --spec 2 for a run config on exactly two Arc B-series (Battlemage) cards.
2
3The rule changes only the generated default (--spec 4).  Single cards, Alchemist cards, three cards, a config with no draft
4layer and anything the person set stay as they are.  Also checks the two places that apply it: sycl/setup_intel.py's
5config rewrite (through apply_to_config) and the Intel server's engine_args wrapper."""
6import importlib.util
7import json
8import sys
9from pathlib import Path
10
11ROOT = Path(__file__).resolve().parent.parent.parent
12sys.path.insert(0, str(ROOT))
13from strata_control import intel_spec  # noqa: E402
14
15B65 = {"driver": "xe", "devid": "e222"}
16B70 = {"driver": "xe", "devid": "e223"}
17B50 = {"driver": "xe", "devid": "e212"}
18B580 = {"driver": "xe", "devid": "e20b"}
19A770 = {"driver": "xe", "devid": "56a0"}
20A750 = {"driver": "i915", "devid": "56a1"}
21IGPU = {"driver": "xe", "devid": "64a0"}
22ARGS = ["--pack", "/p", "--native", "/m.gguf", "--prefill", "auto", "--spec", "4", "--spec-min-p", "0.5", "--mtp", "/m/rt",
23        "--max-context", "32768", "--kv", "int8"]
24
25
26def spec_of(args):
27    return args[args.index("--spec") + 1]
28
29
30def test_battlemage_by_pci_id():
31    for c in (B65, B70, B50, B580, {"driver": "xe", "devid": "0xE223"}, {"driver": "xe", "devid": "E20C"}):
32        assert intel_spec.is_battlemage(c["driver"], c["devid"]), c
33    assert not intel_spec.is_battlemage("xe", "56a0")        # an A770 on xe is Alchemist
34    assert not intel_spec.is_battlemage("i915", "56a1")      # the A750
35    assert not intel_spec.is_battlemage("i915", "e223")      # the driver decides too
36    assert not intel_spec.is_battlemage("xe", "64a0")        # an integrated Xe2 part is not a B-series card
37    assert not intel_spec.is_battlemage("xe", "")
38    assert not intel_spec.is_battlemage("xe", "zzzz")
39
40
41def test_two_b_series_cards_get_spec_2():
42    for pair in ([B65, B65], [B70, B70], [B65, B50], [B580, B580]):
43        args, note = intel_spec.plan(ARGS, None, pair)
44        assert spec_of(args) == "2" and note, pair
45        assert spec_of(ARGS) == "4"                           # the input list is not changed
46    # nothing else moved
47    args, _ = intel_spec.plan(ARGS, None, [B65, B65])
48    assert [a for i, a in enumerate(args) if args[i - 1:i] != ["--spec"]] == [a for i, a in enumerate(ARGS) if ARGS[i - 1:i] != ["--spec"]]
49
50
51def test_everything_else_stays():
52    for cards in ([], [B65], [A750], [A770], [A750, A750], [A770, A770], [B65, A770], [A750, B65], [B65, IGPU],
53                  [B65, B65, B65], [B65, B65, B65, B65]):
54        args, note = intel_spec.plan(ARGS, None, cards)
55        assert args == ARGS and note == "", cards
56
57
58def test_the_persons_own_spec_wins():
59    # in user_args, whatever its value
60    for val in ("4", "3", "2", "6"):
61        args, note = intel_spec.plan(ARGS, ["--spec", val], [B65, B65])
62        assert args == ARGS and note == "", val
63    # unrelated user options do not stop the rule
64    args, note = intel_spec.plan(ARGS, ["--vram-reserve-mib", "800"], [B65, B65])
65    assert spec_of(args) == "2" and note
66    # a value in args that is not setup's own 4 was chosen by somebody
67    for val in ("3", "2", "5", "8"):
68        mine = list(ARGS)
69        mine[mine.index("--spec") + 1] = val
70        args, note = intel_spec.plan(mine, None, [B65, B65])
71        assert args == mine and note == "", val
72    # no --spec at all: nothing is added
73    no_spec = [a for a in ARGS if a not in ("--spec", "4")]
74    args, note = intel_spec.plan(no_spec, None, [B65, B65])
75    assert args == no_spec and note == ""
76
77
78def test_no_draft_layer_no_change():
79    no_mtp = ARGS[:ARGS.index("--mtp")] + ARGS[ARGS.index("--mtp") + 2:]
80    assert intel_spec.plan(no_mtp, None, [B65, B65]) == (no_mtp, "")
81    assert intel_spec.plan(ARGS, None, [B65, B65], mtp_off=True) == (ARGS, "")
82
83
84def test_apply_to_config_keeps_the_written_copy_in_step():
85    cfg = {"args": list(ARGS), "args_written": list(ARGS), "env": {}}
86    note = intel_spec.apply_to_config(cfg, [B65, B65])
87    assert note and spec_of(cfg["args"]) == "2" and spec_of(cfg["args_written"]) == "2"
88    # a second call (setup run again) changes nothing and says nothing
89    assert intel_spec.apply_to_config(cfg, [B65, B65]) == ""
90    # a config of the person's: user_args with --spec, "mtp": false, one card
91    own = {"args": list(ARGS), "args_written": list(ARGS), "user_args": ["--spec", "4"]}
92    assert intel_spec.apply_to_config(own, [B65, B65]) == "" and spec_of(own["args"]) == "4"
93    off = {"args": list(ARGS), "mtp": False}
94    assert intel_spec.apply_to_config(off, [B65, B65]) == "" and spec_of(off["args"]) == "4"
95    one = {"args": list(ARGS)}
96    assert intel_spec.apply_to_config(one, [B65]) == "" and spec_of(one["args"]) == "4"
97
98
99def test_sysfs_cards_in_card_order(tmp_path):
100    def card(n, vendor, devid, driver):
101        d = tmp_path / f"card{n}" / "device"
102        d.mkdir(parents=True)
103        (d / "vendor").write_text(vendor + "\n")
104        (d / "device").write_text(devid + "\n")
105        drv = tmp_path / "drivers" / driver
106        drv.mkdir(parents=True, exist_ok=True)
107        try:
108            (d / "driver").symlink_to(drv, target_is_directory=True)
109        except OSError:                                       # no symlinks (Windows without rights): nothing to read
110            return False
111        return True
112    ok = card(0, "0x8086", "0xe222", "xe")
113    card(1, "0x8086", "0xe222", "xe")
114    card(2, "0x10de", "0x2d05", "nvidia")
115    (tmp_path / "card0-DP-1").mkdir()
116    if not ok:
117        return
118    cards = intel_spec.sysfs_cards(tmp_path)
119    assert [c["devid"] for c in cards] == ["e222", "e222"] and [c["index"] for c in cards] == [0, 1]
120    assert intel_spec.exactly_two_battlemage(cards)
121
122
123def _server_intel():
124    sys.path.insert(0, str(ROOT / "sycl" / "serve"))
125    spec = importlib.util.spec_from_file_location("server_intel_under_test", ROOT / "sycl" / "serve" / "server_intel.py")
126    mod = importlib.util.module_from_spec(spec)
127    spec.loader.exec_module(mod)
128    return mod
129
130
131def _base_engine_args(cfg, exe=None, *, announce=True):
132    """The base server's signature (serve/server.py engine_args); test_wrapper_keeps_the_base_signature checks that it is still that."""
133    return list(cfg["args"])
134
135
136def test_wrapper_keeps_the_base_signature_and_forwards_exe_and_announce(monkeypatch, capsys):
137    """#5086: every SYCL start died with TypeError (unexpected keyword 'announce'): the wrapper took only cfg."""
138    import inspect
139    mod = _server_intel()
140    S = mod.S
141    shape = lambda f: [(p.name, p.kind, p.default) for p in inspect.signature(f).parameters.values()]   # noqa: E731
142    base = shape(S.engine_args)
143    seen = []
144
145    def spy(cfg, exe=None, *, announce=True):
146        seen.append((exe, announce))
147        return list(cfg["args"])
148    monkeypatch.setattr(S, "engine_args", spy)
149    monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(B65, index=0), dict(B65, index=1)])
150    mod.install_two_card_spec()
151    assert shape(S.engine_args) == base
152    cfg = {"backend": "sycl", "gpu": [0, 1], "args": list(ARGS)}
153    assert spec_of(S.engine_args(cfg, "/x/strata-engine")) == "2"
154    capsys.readouterr()
155    quiet = S.engine_args(cfg, "/x/strata-engine", announce=False)           # the budget check
156    assert spec_of(quiet) == "2" and capsys.readouterr().out == "", "a quiet build prints no line"
157    assert spec_of(S.engine_args(cfg, exe="/y/e")) == "2"
158    assert seen == [("/x/strata-engine", True), ("/x/strata-engine", False), ("/y/e", True)]
159
160
161def test_the_real_base_function_runs_under_the_wrapper_without_a_model(monkeypatch, capsys):
162    """The ordinary start and the quiet check, through serve/server.py's own engine_args (no model, no engine process)."""
163    from unittest import mock
164    mod = _server_intel()
165    S = mod.S
166    monkeypatch.setattr(S, "engine_args", S.engine_args)                       # restored after the test
167    monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(B65, index=0), dict(B65, index=1)])
168    mod.install_two_card_spec()
169    cfg = {"model_name": "qwen3.8-flash-next-iq3_s", "backend": "sycl", "gpu": [0, 1], "args": list(ARGS), "drafting": "mtp"}
170    with mock.patch.object(S.drafting, "detect_hardware", return_value=("sycl", [])), mock.patch.object(S, "drafting_vram_mib", return_value=None),             mock.patch.object(S.drafting, "mtp_ready", return_value=True):
171        started = S.engine_args(cfg, "/x/strata-engine")
172        out = capsys.readouterr().out
173        quiet = S.engine_args(cfg, "/x/strata-engine", announce=False)
174        quiet_out = capsys.readouterr().out
175    assert spec_of(started) == "2" and spec_of(quiet) == "2"
176    assert "[strata]" in out and quiet_out == ""
177
178
179def test_server_wrapper_applies_the_rule_at_start(monkeypatch):
180    mod = _server_intel()
181    S = mod.S
182    seen = []
183    monkeypatch.setattr(S, "engine_args", _base_engine_args)
184    monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(B65, index=0), dict(B65, index=1)])
185    mod.install_two_card_spec()
186    cfg = {"backend": "sycl", "gpu": [0, 1], "args": list(ARGS)}
187    assert spec_of(S.engine_args(cfg)) == "2"
188    assert spec_of(cfg["args"]) == "4"                        # the config in memory is not rewritten by a start
189    assert spec_of(S.engine_args({**cfg, "user_args": ["--spec", "4"]})) == "4"
190    assert spec_of(S.engine_args({**cfg, "gpu": 0})) == "4"   # one card
191    assert spec_of(S.engine_args({**cfg, "backend": "hip"})) == "4"
192    assert spec_of(S.engine_args({**cfg, "args": ARGS + ["--peer-device", "1"]})) == "4"   # not a layer split
193    assert spec_of(S.engine_args({**cfg, "mtp": False})) == "4"
194
195
196def test_server_wrapper_one_a_series_card_stays(monkeypatch):
197    mod = _server_intel()
198    S = mod.S
199    monkeypatch.setattr(S, "engine_args", _base_engine_args)
200    monkeypatch.setattr(intel_spec, "sysfs_cards", lambda *a, **k: [dict(B65, index=0), dict(A750, index=1)])
201    mod.install_two_card_spec()
202    cfg = {"backend": "sycl", "gpu": [0, 1], "args": list(ARGS)}
203    assert spec_of(S.engine_args(cfg)) == "4"
204
205
206
207def _derive(base, settings, cards):
208    from unittest import mock
209    from strata_cli.launch.runner import derive_config
210    with mock.patch.object(intel_spec, "sysfs_cards", lambda *a, **k: cards):
211        return derive_config(base, settings, bool_flags=frozenset())
212
213
214def test_launcher_writes_spec_2_for_two_b_series_cards():
215    from strata_cli.launch import settings as L
216    base = {"backend": "sycl", "gpu": [0, 1], "gpus_asked": True, "layer_split": "auto", "exe": "component:strata-engine",
217            "args": list(ARGS), "port": 8095}
218    two = [dict(B65, index=0), dict(B65, index=1)]
219    cfg = _derive(base, L.LaunchSettings(), two)
220    assert spec_of(cfg["args"]) == "2" and spec_of(base["args"]) == "4"            # the installed config is never edited
221    # the person's choices come after the rule and win: --set --spec 4 on the command line, user_args in the config
222    assert spec_of(_derive(base, L.LaunchSettings(extra={"--spec": "4"}), two)["args"]) == "4"
223    assert spec_of(_derive(base, L.LaunchSettings(extra={"--spec": "3"}), two)["args"]) == "3"
224    assert spec_of(_derive({**base, "user_args": ["--spec", "4"]}, L.LaunchSettings(), two)["args"]) == "4"
225    # no draft layer for this launch: nothing to pipeline, nothing changed
226    assert "--spec" not in _derive(base, L.LaunchSettings(mtp="off"), two)["args"] or         spec_of(_derive(base, L.LaunchSettings(mtp="off"), two)["args"]) == "4"
227    # one card, an A-series card in the pair, another backend
228    assert spec_of(_derive({**base, "gpu": 0}, L.LaunchSettings(), two)["args"]) == "4"
229    assert spec_of(_derive(base, L.LaunchSettings(), [dict(B65, index=0), dict(A750, index=1)])["args"]) == "4"
230    assert spec_of(_derive({**base, "backend": "hip"}, L.LaunchSettings(), two)["args"]) == "4"