okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
28.2 KiB468 linesraw
1"""FIX3 (11-04): three launcher and planning bugs found in round 0211.
2
31. The draft-layer lookup walked up from the model file to a folder named "models" and looked only beside it. With the model folder outside the data
4   folder the plan asked for the 5.2 GB layer although <data-dir>/mtp/rt was there (a second download).
52. The all-cards split engine's fit counted each card's size. Cards other programs hold (8 GB free of 96) still got "split + MTP" and the 5.2 GB fetch; the fit
6   counts free memory minus the reserve now.
73. The plan's card line gave no way to tell the --gpu number (GPU 2 is card 1) and listed cards CUDA_VISIBLE_DEVICES hides. It counts from 1 like the screens and now adds the number --gpu takes:
8   "GPU 2 (--gpu 1)".
9All of it with fake cards and fake sysfs; nothing is started, probed or downloaded.
10"""
11
12from __future__ import annotations
13
14import json
15import os
16import subprocess
17import tempfile
18import unittest
19from pathlib import Path
20from unittest import mock
21
22from strata_cli.launch import cmd as launch_cmd
23from strata_cli.launch import modelstate
24from strata_cli.launch import settings as S
25from strata_cli.launch.catalog import Catalog
26from strata_cli.launch.runner import Runner
27from strata_control import discovery, gpu_roles, split_engine as SE
28from tests.terminal.launch_support import HW_12, Home, catalog, run_cli
29from tests.terminal.test_own_files import IQ3XXS, gguf_bytes
30
31
32class Base(unittest.TestCase):
33    one_card_pc = True                                  # the plan tests run on a fake one-card PC; the others hand their own hardware to catalog()
34
35    def setUp(self):
36        self.home = Home().__enter__()
37        self.addCleanup(self.home.__exit__, None, None, None)
38        if self.one_card_pc:
39            p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0))
40            p.start()
41            self.addCleanup(p.stop)
42        self.tmp = tempfile.TemporaryDirectory(prefix="strata-fix3-")
43        self.addCleanup(self.tmp.cleanup)
44        self.base = Path(self.tmp.name)
45
46    def model_files(self, folder: Path) -> Path:
47        folder.mkdir(parents=True, exist_ok=True)
48        for n in IQ3XXS:
49            (folder / n).write_bytes(gguf_bytes(["IQ3_XXS"]))
50        return folder
51
52    def layer_in(self, data: Path) -> Path:
53        rt = data / "mtp" / "rt"
54        rt.mkdir(parents=True, exist_ok=True)
55        (rt / "experts.bin").write_bytes(b"x")
56        return rt
57
58    def plan_text(self, *args):
59        code, out, err = run_cli(["launch", "--plan", *args])
60        self.assertEqual(code, 0, err or out)
61        return out
62
63
64# ----------------------------------------------------------------------------------------------------------------------- 1. the draft layer
65
66class DraftLayerInTheDataDir(Base):
67    def test_prepared_beside_looks_in_the_data_dir_when_the_model_folder_is_elsewhere(self):
68        data = self.base / "data"
69        rt = self.layer_in(data)
70        first = self.model_files(self.base / "ext" / "models" / "iq3_xxs") / IQ3XXS[0]
71        self.assertIsNone(discovery.prepared_beside(first)["mtp"], "the old lookup: only beside the models folder")
72        got = discovery.prepared_beside(first, [data])
73        self.assertEqual(got["mtp"], rt)
74        self.assertEqual(got["data_dir"], self.base / "ext", "the folder the model sits in is still what data_dir says")
75
76    def test_a_model_folder_with_no_models_ancestor_finds_it_too(self):
77        data = self.base / "data"
78        rt = self.layer_in(data)
79        first = self.model_files(self.base / "somewhere" / "IQ3_XXS") / IQ3XXS[0]
80        got = discovery.prepared_beside(first, [None, self.base / "nope", data])
81        self.assertEqual((got["mtp"], got["data_dir"]), (rt, None))
82
83    def test_the_layer_beside_the_models_folder_wins_and_nothing_is_invented(self):
84        beside, data = self.base / "ext", self.base / "data"
85        mine = self.layer_in(beside)
86        self.layer_in(data)
87        first = self.model_files(beside / "models" / "iq3_xxs") / IQ3XXS[0]
88        self.assertEqual(discovery.prepared_beside(first, [data])["mtp"], mine)
89        none = discovery.prepared_beside(self.model_files(self.base / "lone" / "models" / "x") / IQ3XXS[0], [self.base / "empty"])
90        self.assertEqual((none["mtp"], none["pack"]), (None, None))
91
92    def test_a_pack_in_the_data_dir_is_found_by_the_models_tag(self):
93        data = self.base / "data"
94        (data / "packs" / "iq3_xxs").mkdir(parents=True)
95        first = self.model_files(self.base / "ext" / "models" / "iq3_xxs") / IQ3XXS[0]
96        self.assertIsNone(discovery.prepared_beside(first)["pack"])
97        self.assertEqual(discovery.prepared_beside(first, [data])["pack"], data / "packs" / "iq3_xxs")
98
99    def test_assess_counts_no_draft_layer_when_data_dir_has_it(self):
100        data = self.base / "data"
101        (data / "packs" / "iq3_xxs").mkdir(parents=True)
102        self.layer_in(data)
103        folder = self.model_files(self.base / "ext" / "models" / "iq3_xxs")
104        c = catalog(HW_12)
105        with mock.patch.object(Catalog, "data_dir", return_value=self.base / "elsewhere"):
106            st = modelstate.assess(c, "qwen", "IQ3_XXS", vision="off", model_path=str(folder), data_dir=data)
107            self.assertEqual([p.kind for p in st.parts], [])
108            st = modelstate.assess(c, "qwen", "IQ3_XXS", vision="off", model_path=str(folder), data_dir=self.base / "empty")
109            self.assertEqual([p.kind for p in st.parts], [], "no pack anywhere: the draft layer is not counted either (as before)")
110            (self.base / "empty" / "packs" / "iq3_xxs").mkdir(parents=True)
111            st = modelstate.assess(c, "qwen", "IQ3_XXS", vision="off", model_path=str(folder), data_dir=self.base / "empty")
112        self.assertEqual([p.kind for p in st.parts], ["mtp"], "a pack but no layer anywhere: it is still asked for")
113
114    def test_assess_finds_the_picture_reader_in_the_data_dir_too(self):
115        data = self.base / "data"
116        (data / "packs" / "iq3_xxs").mkdir(parents=True)
117        self.layer_in(data)
118        folder = self.model_files(self.base / "ext" / "models" / "iq3_xxs")
119        with mock.patch.object(Catalog, "data_dir", return_value=self.base / "elsewhere"):
120            st = modelstate.assess(catalog(HW_12), "qwen", "IQ3_XXS", vision="gpu", model_path=str(folder), data_dir=data)
121            self.assertEqual([p.kind for p in st.parts], ["mmproj"], "a pack in the data dir but no reader anywhere: the reader is asked for")
122            (data / "models").mkdir()
123            (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x")
124            st = modelstate.assess(catalog(HW_12), "qwen", "IQ3_XXS", vision="gpu", model_path=str(folder), data_dir=data)
125        self.assertEqual([p.kind for p in st.parts], [])
126
127    def test_the_remembered_data_dir_counts_when_none_is_given(self):
128        remembered = self.base / "remembered"
129        (remembered / "packs" / "iq3_xxs").mkdir(parents=True)
130        self.layer_in(remembered)
131        folder = self.model_files(self.base / "ext" / "models" / "iq3_xxs")
132        with mock.patch.object(Catalog, "data_dir", return_value=remembered):
133            st = modelstate.assess(catalog(HW_12), "qwen", "IQ3_XXS", vision="off", model_path=str(folder))
134        self.assertEqual([p.kind for p in st.parts], [])
135
136    # the plan as `strata launch --plan` prints it (check (a))
137    def test_plan_says_nothing_to_download_for_a_model_folder_outside_the_data_dir(self):
138        data = self.base / "data"
139        self.layer_in(data)
140        folder = self.model_files(self.base / "ext" / "IQ3_XXS")
141        with mock.patch.object(Runner, "existing_data_dir", return_value=None), mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"):
142            out = self.plan_text("--model-path", str(folder), "--data-dir", str(data), "--vision", "off")
143        self.assertIn("download  Nothing to download: your model files are used where they are.", out)
144
145    def test_plan_with_a_models_ancestor_outside_the_data_dir_is_the_same(self):
146        data = self.base / "data"
147        self.layer_in(data)
148        folder = self.model_files(self.base / "ext" / "models" / "iq3_xxs")
149        with mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"):
150            out = self.plan_text("--model-path", str(folder), "--data-dir", str(data), "--vision", "off")
151        self.assertIn("download  Nothing to download: your model files are used where they are.", out)
152
153    def test_plan_still_asks_for_the_layer_when_no_data_dir_has_it(self):
154        folder = self.model_files(self.base / "ext" / "models" / "iq3_xxs")
155        with mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"),                 mock.patch.object(Runner, "intel_chosen", lambda self: False):       # an Intel Arc in the box that runs the test would plan its own engine
156            out = self.plan_text("--model-path", str(folder), "--data-dir", str(self.base / "data"), "--vision", "off")
157        self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB).", out)
158
159    def test_the_picture_reader_in_the_data_dir_is_found_too(self):
160        data = self.base / "data"
161        self.layer_in(data)
162        (data / "models").mkdir()
163        (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x")
164        folder = self.model_files(self.base / "ext" / "IQ3_XXS")
165        with mock.patch.object(Runner, "existing_data_dir", return_value=None), mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"):
166            out = self.plan_text("--model-path", str(folder), "--data-dir", str(data), "--vision", "on")
167        self.assertIn("download  Nothing to download", out)
168
169    def test_the_import_preview_sees_the_layer_in_the_data_folder_in_use(self):
170        from strata_control import models
171        data = self.base / "inuse"
172        rt = self.layer_in(data)
173        first = self.model_files(self.base / "ext" / "models" / "iq3_xxs") / IQ3XXS[0]
174        with mock.patch.object(discovery, "remembered_data_dirs", return_value=[data]):
175            got = models._already_set_up([first], {"family": "qwen", "model": "IQ3_XXS"})
176        self.assertEqual(got["mtp"], str(rt))
177
178    def test_remembered_data_dirs_reads_only_the_folders_that_exist(self):
179        with mock.patch.object(discovery, "data_dir_choices", return_value=[(self.base, "settings"), (self.base / "gone", "app"), (self.base, "documents")]):
180            self.assertEqual(discovery.remembered_data_dirs(), [self.base])
181
182    def test_dflash2_pack_is_looked_for_in_the_data_dir_that_was_named(self):
183        """The DFlash2 lookup was never tied to the model folder: it asks the data dir (the one named, else the run config's)."""
184        from strata_control import drafting
185        data = self.base / "data"
186        pack = drafting.target_path(data)
187        pack.parent.mkdir(parents=True)
188        with pack.open("wb") as f:
189            f.truncate((1 << 20) + 1)
190        self.assertTrue(drafting.pack_ready(data))
191        self.assertFalse(drafting.pack_ready(self.base / "ext"))
192        r = Runner(S.LaunchSettings(model_path=str(self.model_files(self.base / "ext" / "IQ3_XXS")), data_dir=str(data), drafting="dflash2", vision="off"),
193                   catalog=catalog(HW_12))
194        with mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_86"])):
195            want = r.drafting_inputs({})
196        self.assertEqual(Path(want["data_dir"]), data)
197        self.assertFalse(drafting.needs_pack(**want))
198
199
200# ----------------------------------------------------------------------------------------------------------------------- 2. free memory
201
202def card(i, total=98304, free=None, **kw):
203    spec = dict(name="NVIDIA RTX PRO 6000", vram_mib=total, cc=120, free_mib=free)
204    spec.update(kw)
205    return SE.Card(i, **spec)
206
207
208GIB = 1 << 30
209UDQ4 = SE.ModelFacts(routed_types={"Q4_K": 97, "Q5_K": 2, "Q5_1": 43, "Q8_0": 5}, routed_bytes=int(71.7 * GIB), embd_type="Q8_0", shexp_types={"Q8_0": 144},
210                     embd_ram_bytes=int(27.5 * GIB), layers=48, experts=512)
211
212
213def decide(cards, model=UDQ4, **kw):
214    return SE.decide(enabled=True, system="linux", cards=cards, ram_total_gib=500.0, ram_available_gib=400.0, model=model, **kw)
215
216
217class SplitFitCountsFreeMemory(unittest.TestCase):
218    def test_free_cards_decide_as_before(self):
219        before = decide([card(0), card(1)])                                   # free not known: the size counts
220        for free in (98304, 98000, 97500):                                    # an idle card shows a few hundred MiB in use
221            d = decide([card(0, free=free), card(1, free=free)])
222            self.assertEqual((d.use_split, d.reasons, d.need_vram_gib), (before.use_split, before.reasons, before.need_vram_gib), free)
223        self.assertTrue(before.use_split)
224
225    def test_cards_held_to_8_gb_free_do_not_fit_the_experts(self):
226        d = decide([card(0, free=8192), card(1, free=8192)])
227        self.assertFalse(d.use_split)
228        self.assertTrue(any("do not fit in the cards' memory" in r for r in d.reasons), d.reasons)
229        self.assertIn("has 7 GiB free)", " ".join(d.reasons), "free memory minus the 700 MiB reserve, and it says free")
230        old = decide([card(0, total=4096), card(1, total=4096)])
231        self.assertIn("has 4 GiB)", " ".join(old.reasons), "free memory not read: the old sentence, the size")
232
233    def test_one_busy_card_is_enough(self):
234        self.assertFalse(decide([card(0), card(1, free=8192)]).use_split)
235
236    def test_the_limit_is_free_minus_the_reserve(self):
237        need = decide([card(0), card(1)]).need_vram_gib * 1024
238        edge = int(need) + SE.FREE_RESERVE_MIB
239        self.assertTrue(decide([card(0, free=edge + 8), card(1, free=edge + 8)]).use_split)
240        self.assertFalse(decide([card(0, free=edge - 64), card(1, free=edge - 64)]).use_split)
241
242    def test_free_cannot_raise_a_card_above_its_size(self):
243        c = card(0, total=1000, free=5000)
244        self.assertEqual(c.room_mib, 1000 - SE.FREE_RESERVE_MIB)
245        self.assertEqual(card(0, total=1000).room_mib, 1000, "not known: the size")
246
247    def test_expected_is_false_on_busy_cards_and_true_on_free_ones(self):
248        ram = lambda: (500.0, 400.0)                                            # noqa: E731
249        probe = lambda cards_: (lambda idx: cards_)                              # noqa: E731
250        self.assertTrue(SE.expected({}, probe=probe([card(0, free=90000), card(1, free=90000)]), ram=ram, system="linux"))
251        self.assertFalse(SE.expected({}, probe=probe([card(0, free=8192), card(1, free=8192)]), ram=ram, system="linux"), "even a model not on disk needs the 9 GiB")
252        self.assertTrue(SE.expected({}, probe=probe([card(0), card(1)]), ram=ram, system="linux"))
253
254    def test_a_busy_start_is_quiet_in_auto_and_told_with_on(self):
255        busy = [card(0, free=8192), card(1, free=8192)]
256        for m, quiet in (("auto", True), ("on", False)):
257            cfg = {"args": ["--native", "/m/x.gguf", "--mtp", "/m/mtp/rt"], "exe": "/e/strata", "split_engine": m}
258            with mock.patch.object(SE, "scan_model", lambda p: UDQ4):
259                d = SE.apply_to_config(cfg, exe_for_cards=lambda n, cc=None: "/e/strata-split-2", system="linux", probe=lambda i: busy, ram=lambda: (500.0, 400.0))
260            self.assertEqual((d.use_split, d.quiet), (False, quiet), m)
261            self.assertNotIn("split_fallback", cfg, "the run config stays the layer split")
262
263    def test_the_nvidia_probe_reads_memory_free_in_the_same_call(self):
264        out = "0, NVIDIA RTX PRO 6000, 97887, 12.0, 8123\n1, NVIDIA RTX PRO 6000, 97887, 12.0, [N/A]\n"
265        seen = []
266
267        def fake(argv, **kw):
268            seen.append(argv)
269            return subprocess.CompletedProcess(argv, 0, stdout=out, stderr="")
270        with mock.patch("subprocess.run", fake), mock.patch.dict(os.environ):
271            os.environ.pop("CUDA_VISIBLE_DEVICES", None)
272            got = SE.probe_nvidia_cards()
273        self.assertEqual(len(seen), 1, "one nvidia-smi call, as before")
274        self.assertIn("memory.free", seen[0][1])
275        self.assertEqual([(c.index, c.vram_mib, c.free_mib) for c in got], [(0, 97887, 8123), (1, 97887, None)])
276
277    def test_an_old_four_column_answer_still_counts_the_size(self):
278        out = "0, NVIDIA RTX PRO 6000, 97887, 12.0\n1, NVIDIA RTX PRO 6000, 97887, 12.0\n"
279        with mock.patch("subprocess.run", lambda argv, **kw: subprocess.CompletedProcess(argv, 0, stdout=out, stderr="")), mock.patch.dict(os.environ):
280            os.environ.pop("CUDA_VISIBLE_DEVICES", None)
281            got = SE.probe_nvidia_cards()
282        self.assertEqual([c.free_mib for c in got], [None, None])
283        self.assertEqual(len(got), 2)
284
285    def test_the_amd_probe_reads_the_render_nodes_use(self):
286        with tempfile.TemporaryDirectory() as t:
287            root = Path(t)
288            for n, (minor, used) in enumerate(((128, 30 * (1 << 30)), (129, 1 << 20))):
289                node = root / f"class/kfd/kfd/topology/nodes/{n + 1}"
290                (node / "mem_banks/0").mkdir(parents=True)
291                (node / "properties").write_text(f"simd_count 128\ngfx_target_version 120001\nmarketing_name R9700\ndrm_render_minor {minor}\n")
292                (node / "mem_banks/0/properties").write_text(f"size_in_bytes {32 * (1 << 30)}\n")
293                dev = root / f"class/drm/renderD{minor}/device"
294                dev.mkdir(parents=True)
295                (dev / "mem_info_vram_used").write_text(str(used))
296            (root / "class/kfd/kfd/topology/nodes/0").mkdir(parents=True)
297            (root / "class/kfd/kfd/topology/nodes/0/properties").write_text("simd_count 0\n")
298            with mock.patch.dict(os.environ):
299                for k in ("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"):
300                    os.environ.pop(k, None)
301                got = SE.probe_amd_cards(root=str(root))
302        self.assertEqual([(c.index, c.vram_mib, c.free_mib) for c in got], [(0, 32768, 2048), (1, 32768, 32767)])
303
304    def test_the_amd_probe_without_a_render_node_leaves_free_unknown(self):
305        with tempfile.TemporaryDirectory() as t:
306            node = Path(t) / "class/kfd/kfd/topology/nodes/0"
307            (node / "mem_banks/0").mkdir(parents=True)
308            (node / "properties").write_text("simd_count 128\ngfx_target_version 120001\n")
309            (node / "mem_banks/0/properties").write_text(f"size_in_bytes {32 * (1 << 30)}\n")
310            with mock.patch.dict(os.environ):
311                for k in ("ROCR_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"):
312                    os.environ.pop(k, None)
313                got = SE.probe_amd_cards(root=t)
314        self.assertEqual([c.free_mib for c in got], [None])
315
316
317class PlanOnBusyCards(Base):
318    """The plan: busy cards get the layer split with DFlash2 and no 5.2 GB fetch; free cards still get the split with the MTP."""
319    one_card_pc = False
320
321    def runner(self, probe, **kw):
322        s = S.LaunchSettings(**{"family": "qwen", "model": "UD-Q4_K_XL", "context": 131072, "tune": "skip", "vision": "off", "gpus": [0, 1], **kw})
323        r = Runner(s, catalog=catalog({**HW_12, "ram_gb": 125.0, "engine_vendor": "nvidia",
324                                       "gpus": [{"index": i, "name": "NVIDIA RTX PRO 6000", "vram_gb": 96.0, "usable": True, "vendor": "nvidia"} for i in range(2)]}))
325        for p in (mock.patch.object(SE, "probe_cards", lambda idx=None: probe), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)),
326                  mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"])),
327                  mock.patch("sys.platform", "linux"),       # the all-cards split rule asks the host OS (Linux only): this fake PC is Linux
328                  mock.patch.object(Runner, "intel_chosen", lambda self: False)):       # and NVIDIA: the real box's Intel Arc must not make the launch an Intel one
329            p.start()
330            self.addCleanup(p.stop)
331        return r
332
333    def test_busy_cards_resolve_to_dflash2_and_fetch_no_draft_layer(self):
334        r = self.runner([card(0, free=8192), card(1, free=8192)])
335        self.assertFalse(r.split_expected())
336        self.assertEqual(r.resolved_drafting("qwen"), "dflash2")
337        kinds = [p["kind"] for p in r.download_plan()["parts"]]
338        self.assertNotIn("mtp", kinds)
339        self.assertNotIn("MTP", r.drafting_plan_line())
340
341    def test_free_cards_still_resolve_to_the_split_with_the_mtp(self):
342        r = self.runner([card(0, free=97000), card(1, free=97000)])
343        self.assertTrue(r.split_expected())
344        self.assertEqual(r.resolved_drafting("qwen"), "mtp")
345        self.assertIn("mtp", [p["kind"] for p in r.download_plan()["parts"]])
346        self.assertEqual(r.drafting_plan_line(), "Drafting: MTP (the all-cards split engine uses the MTP draft layer, 5.2 GB)")
347
348    def test_a_running_server_of_this_launch_is_not_busy_memory(self):
349        """build_config runs before the old server is stopped: the memory it holds is given back, so it must not turn the split down on a restart."""
350        busy = [card(0, free=8192), card(1, free=8192)]
351        r = self.runner(busy)
352        self.assertIsNone(r.card_probe(), "nothing of ours is running: the engine's own probe")
353        with mock.patch.object(Runner, "serving_launches", lambda self: [{"profile": self.profile, "name": "x", "port": 1, "choices": None}]):
354            r = self.runner(busy)
355            probe = r.card_probe()
356            self.assertTrue(r.split_expected())
357        self.assertEqual([c.free_mib for c in probe(None)], [None, None])
358
359    def test_another_launch_on_another_port_is_busy_memory(self):
360        r = self.runner([card(0, free=8192), card(1, free=8192)])
361        with mock.patch.object(Runner, "serving_launches", lambda self: [{"profile": "launch-other", "name": "other", "port": int(self.s.port) + 1, "choices": None}]):
362            self.assertIsNone(r.card_probe())
363
364
365class AppPlanWhileItsEngineRuns(Base):
366    """The desktop app asks `drafting plan` before it unloads the running model: `--engines-unloading` says that engine's memory is given back, as Runner.card_probe does."""
367    one_card_pc = False
368
369    def plan(self, *extra):
370        data = self.base / "d"
371        data.mkdir(exist_ok=True)
372        busy = [card(0, free=8192), card(1, free=8192)]
373        with mock.patch.object(SE, "probe_cards", lambda idx=None: busy), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)),                 mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"])),                 mock.patch("sys.platform", "linux"),                 mock.patch.object(Runner, "intel_chosen", lambda self: False):       # the split rule asks the host OS (Linux only) and the make: this fake PC is Linux and NVIDIA
374            code, out, err = run_cli(["drafting", "plan", "--family", "qwen", "--data-dir", str(data), "--mode", "auto", "--output", "json", *extra])
375        self.assertEqual(code, 0, err)
376        return json.loads(out)
377
378    def test_busy_cards_say_dflash2_unless_the_running_engine_is_about_to_be_unloaded(self):
379        p = self.plan()
380        self.assertEqual((p["split"], p["choice"]), (False, "dflash2"))
381        p = self.plan("--engines-unloading")
382        self.assertEqual((p["split"], p["choice"]), (True, "mtp"))
383
384
385# ----------------------------------------------------------------------------------------------------------------------- 3. the card numbers
386
387def four(vendor="nvidia"):
388    return [{"index": i, "name": "NVIDIA RTX A6000", "vram_gb": 48.0, "usable": True, "vendor": vendor} for i in range(4)]
389
390
391class CardNumbers(Base):
392    one_card_pc = False
393
394    def line(self, env=None, vendor="nvidia", cards=None, **kw):
395        s = S.LaunchSettings(**{"family": "qwen", "model": "UD-Q4_K_XL", **kw})
396        c = catalog({**HW_12, "engine_vendor": vendor, "gpus": cards or four(vendor=vendor)})
397        with mock.patch.dict(os.environ, env or {}):
398            return launch_cmd.roles_line(s, c)
399
400    def test_describe_keeps_the_screens_count_and_the_plan_adds_the_gpu_flag_number(self):
401        cs = [{"index": 0, "name": "RTX 3060", "vram_gb": 12}, {"index": 1, "name": "RTX 4070 Ti", "vram_gb": 12}]
402        self.assertEqual(gpu_roles.describe({0: "helper", 1: "main"}, cs), "Main: GPU 2 RTX 4070 Ti. Helper: GPU 1 RTX 3060.")
403        self.assertEqual(gpu_roles.describe({0: "helper", 1: "main"}, cs, card_numbers=True), "Main: GPU 2 (--gpu 1) RTX 4070 Ti. Helper: GPU 1 (--gpu 0) RTX 3060.")
404
405    def test_gpu_0_1_on_four_cards_with_cuda_visible_devices_0_1(self):
406        got = self.line({"CUDA_VISIBLE_DEVICES": "0,1"}, gpus=[0, 1])
407        self.assertEqual(got, "Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000.", "no Off cards for the ones the environment hides")
408
409    def test_without_the_variable_the_other_cards_are_off_with_their_own_numbers(self):
410        got = self.line({}, gpus=[0, 1])
411        self.assertEqual(got, "Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000. Off: GPU 3 (--gpu 2) RTX A6000, GPU 4 (--gpu 3) RTX A6000.")
412
413    def test_one_visible_card_named_by_number(self):
414        self.assertEqual(self.line({"CUDA_VISIBLE_DEVICES": "1"}, gpus=[1]), "Main: GPU 2 (--gpu 1) RTX A6000.")
415
416    def test_a_named_card_the_environment_hides_stays_because_the_server_sets_visibility_from_it(self):
417        self.assertEqual(self.line({"CUDA_VISIBLE_DEVICES": "1"}, gpus=[0]), "Main: GPU 1 (--gpu 0) RTX A6000. Off: GPU 2 (--gpu 1) RTX A6000.")
418
419    def test_roles_by_number(self):
420        got = self.line({"CUDA_VISIBLE_DEVICES": "2,3"}, gpu_roles={"2": "helper", "3": "main"})
421        self.assertEqual(got, "Main: GPU 4 (--gpu 3) RTX A6000. Helper: GPU 3 (--gpu 2) RTX A6000.")
422
423    def test_amd_honours_hip_and_rocr(self):
424        amd = four(vendor="amd")
425        self.assertEqual(self.line({"HIP_VISIBLE_DEVICES": "0,1"}, vendor="amd", cards=amd, gpus=[0, 1]), "Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000.")
426        # ROCR first (cards 1 and 3 of the box), then HIP numbers those: HIP 0 is box card 1
427        self.assertEqual(self.line({"ROCR_VISIBLE_DEVICES": "1,3", "HIP_VISIBLE_DEVICES": "0"}, vendor="amd", cards=amd, gpus=[1]), "Main: GPU 2 (--gpu 1) RTX A6000.")
428        self.assertEqual(self.line({"ROCR_VISIBLE_DEVICES": "1,3"}, vendor="amd", cards=amd, gpus=[1, 3]), "Main: GPU 4 (--gpu 3) RTX A6000. Helper: GPU 2 (--gpu 1) RTX A6000.")
429
430    def test_cuda_visible_devices_does_not_hide_amd_cards(self):
431        self.assertEqual(self.line({"CUDA_VISIBLE_DEVICES": "0"}, vendor="amd", cards=four(vendor="amd"), gpus=[0, 1]),
432                         "Main: GPU 2 (--gpu 1) RTX A6000. Helper: GPU 1 (--gpu 0) RTX A6000. Off: GPU 3 (--gpu 2) RTX A6000, GPU 4 (--gpu 3) RTX A6000.")
433
434
435class EnvVisible(unittest.TestCase):
436    def test_numbers_and_order(self):
437        ev = lambda v, env, **kw: gpu_roles.env_visible([0, 1, 2, 3], v, env, **kw)             # noqa: E731
438        self.assertIsNone(ev("nvidia", {}))
439        self.assertEqual(ev("nvidia", {"CUDA_VISIBLE_DEVICES": "1,0"}, alike=True), [1, 0])
440        self.assertEqual(ev("nvidia", {"CUDA_VISIBLE_DEVICES": ""}), [])
441        self.assertEqual(ev("nvidia", {"CUDA_VISIBLE_DEVICES": "0,9,1"}, alike=True), [0], "an entry that is no card ends the list, as CUDA reads it")
442
443    def test_a_uuid_or_an_ambiguous_order_is_not_guessed(self):
444        self.assertIsNone(gpu_roles.env_visible([0, 1], "nvidia", {"CUDA_VISIBLE_DEVICES": "GPU-1234"}, alike=True))
445        self.assertIsNone(gpu_roles.env_visible([0, 1], "nvidia", {"CUDA_VISIBLE_DEVICES": "1"}), "different cards, CUDA's own order: not the nvidia-smi numbers")
446        self.assertEqual(gpu_roles.env_visible([0, 1], "nvidia", {"CUDA_VISIBLE_DEVICES": "1", "CUDA_DEVICE_ORDER": "PCI_BUS_ID"}), [1])
447        self.assertIsNone(gpu_roles.env_visible([0, 1], "amd", {"ROCR_VISIBLE_DEVICES": "GPU-1234"}))
448        self.assertIsNone(gpu_roles.env_visible([0, 1], "intel", {"CUDA_VISIBLE_DEVICES": "0"}))
449
450
451class SplitProbeRespectsTheEnvironment(unittest.TestCase):
452    def probe(self, env, indexes=None):
453        smi = "".join(f"{i}, NVIDIA RTX A6000, 49140, 8.6, 48000\n" for i in range(4))
454        with mock.patch("subprocess.run", lambda argv, **kw: subprocess.CompletedProcess(argv, 0, stdout=smi, stderr="")), mock.patch.dict(os.environ):
455            os.environ.pop("CUDA_VISIBLE_DEVICES", None)
456            os.environ.update(env)
457            return [c.index for c in SE.probe_nvidia_cards(indexes)]
458
459    def test_hidden_cards_are_not_counted_when_none_is_named(self):
460        self.assertEqual(self.probe({"CUDA_VISIBLE_DEVICES": "0,1"}), [0, 1])
461        self.assertEqual(self.probe({}), [0, 1, 2, 3])
462
463    def test_named_cards_are_kept_as_named(self):
464        self.assertEqual(self.probe({"CUDA_VISIBLE_DEVICES": "0,1"}, [2, 3]), [2, 3])
465
466
467if __name__ == "__main__":
468    unittest.main()