okami.mom/strata

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

Niko1221Merge f-027-gh-ctl: GitHub setup, Docker, docs and bench items for 0.2.7538acd098

main
44.8 KiB745 linesraw
1"""Tests for setup.py's AMD card detection on a mocked KFD topology (/sys/class/kfd + /sys/class/drm): the arch
2names from gfx_target_version, the CPU node skipped, HIP numbering, product names, which cards are supported and
3which TheRock index each family installs from.  No GPU, no ROCm, no downloads.
4
5    python -m unittest tools.test_setup_amd
6"""
7from __future__ import annotations
8
9import sys
10import tempfile
11import unittest
12from unittest import mock
13from pathlib import Path
14
15ROOT = Path(__file__).resolve().parents[1]
16sys.path.insert(0, str(ROOT))
17import setup  # noqa: E402
18
19
20def fake_sysfs(root: Path, nodes: list) -> None:
21    """nodes: (gfx_target_version, simd_count, render_minor, product_name or None, vram_bytes)"""
22    for i, (ver, simd, minor, name, vram) in enumerate(nodes):
23        n = root / "class/kfd/kfd/topology/nodes" / str(i)
24        n.mkdir(parents=True)
25        (n / "properties").write_text(f"cpu_cores_count {0 if simd else 12}\nsimd_count {simd}\n"
26                                      f"gfx_target_version {ver}\ndrm_render_minor {minor}\n")
27        if simd:
28            d = root / f"class/drm/renderD{minor}/device"
29            d.mkdir(parents=True)
30            (d / "mem_info_vram_total").write_text(str(vram))
31            if name is not None:
32                (d / "product_name").write_text(name + "\n")
33
34
35class KfdDetection(unittest.TestCase):
36    def setUp(self):
37        self.tmp = tempfile.TemporaryDirectory()
38        self.root = Path(self.tmp.name)
39        self.win = setup.WIN
40        setup.WIN = False
41
42    def tearDown(self):
43        setup.WIN = self.win
44        self.tmp.cleanup()
45
46    def test_every_family(self):
47        fake_sysfs(self.root, [
48            (0, 0, 0, None, 0),                                   # the CPU node: skipped
49            (110001, 120, 128, "", 16 << 30),                     # gfx1101 without a product name
50            (120000, 64, 129, None, 16 << 30),                    # gfx1200, no product_name file
51            (120001, 128, 130, "AMD Radeon AI PRO R9700", 32 << 30),
52            (110002, 64, 131, None, 8 << 30),                     # gfx1102: supported, unvalidated (#938)
53            (100306, 4, 132, None, 512 << 20),                    # an integrated gfx1036: listed, not supported
54            (110000, 192, 133, "Radeon RX 7900 XTX", 24 << 30),
55        ])
56        g = setup.amd_gpus(str(self.root))
57        self.assertEqual([x["arch"] for x in g], ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1036", "gfx1100"])
58        self.assertEqual([x["index"] for x in g], [0, 1, 2, 3, 4, 5])          # HIP numbers: GPU nodes only
59        self.assertEqual(g[0]["name"], setup.AMD_NAMES["gfx1101"])
60        self.assertEqual(g[1]["name"], setup.AMD_NAMES["gfx1200"])
61        self.assertEqual(g[2]["name"], "AMD Radeon AI PRO R9700")
62        self.assertEqual(g[3]["name"], setup.AMD_NAMES["gfx1102"])
63        self.assertAlmostEqual(g[2]["vram_gb"], 32.0)
64        ok = [x["arch"] for x in g if setup.amd_problem(x) is None]
65        self.assertEqual(ok, ["gfx1101", "gfx1200", "gfx1201", "gfx1102", "gfx1100"])
66        self.assertIn("gfx1036", setup.amd_problem(g[4]))
67
68    def test_no_kfd(self):
69        self.assertEqual(setup.amd_gpus(str(self.root)), [])
70
71    def test_rocm_index_per_family(self):
72        for arch in setup.AMD_ARCHS:
73            self.assertIn(arch, setup.ROCM_INDEXES)
74        self.assertTrue(setup.ROCM_INDEXES["gfx1101"].endswith("/gfx110X-dgpu/"))
75        self.assertTrue(setup.ROCM_INDEXES["gfx1200"].endswith("/gfx120X-all/"))
76        self.assertEqual(setup.ROCM_INDEXES["gfx1101"], setup.ROCM_INDEXES["gfx1100"])
77        self.assertEqual(setup.ROCM_INDEXES["gfx1200"], setup.ROCM_INDEXES["gfx1201"])
78        # #524: the RX 6700 XT (gfx1031) takes the RDNA2 wheels, as the RX 6800 / 6900 (gfx1030)
79        self.assertEqual(setup.ROCM_INDEXES["gfx1031"], setup.ROCM_INDEXES["gfx1030"])
80        self.assertIsNone(setup.amd_problem({"arch": "gfx1031"}))
81
82
83class Rx6000Detection(KfdDetection):
84    """0.2.2: the RX 6000 engine package (gfx1030 / gfx1031). Setup names the cards, says the package is built and not tested on a real
85    RX 6000 card, and says it for these two architectures only."""
86
87    def test_rx6000_cards_by_gfx_target_version(self):
88        fake_sysfs(self.root, [
89            (100300, 80, 128, "AMD Radeon RX 6900 XT", 16 << 30),     # gfx1030
90            (100301, 40, 129, None, 12 << 30),                        # gfx1031 (RX 6700 XT), no product name
91            (100302, 28, 130, None, 8 << 30),                         # gfx1032 (RX 6600): not in the package
92        ])
93        g = setup.amd_gpus(str(self.root))
94        self.assertEqual([x["arch"] for x in g], ["gfx1030", "gfx1031", "gfx1032"])
95        self.assertEqual(g[1]["name"], setup.AMD_NAMES["gfx1031"])
96        self.assertEqual([setup.is_rdna2(x) for x in g], [True, True, False])
97        self.assertIsNone(setup.amd_problem(g[0]))
98        self.assertIsNone(setup.amd_problem(g[1]))
99
100    def test_the_note_is_for_gfx103x_only(self):
101        for arch in ("gfx1030", "gfx1031", "gfx1030:sramecc-:xnack-"):
102            lines = setup.rdna2_notes({"arch": arch})
103            self.assertEqual(len(lines), 1, arch)
104            self.assertIn("built, not tested on a real RX 6000 card", lines[0])
105            self.assertIn(arch.split(":")[0], lines[0])
106        for arch in ("gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1151", "gfx1032", "gfx103", "gfx10300", "", None):
107            self.assertEqual(setup.rdna2_notes({"arch": arch}), [], arch)
108        self.assertEqual(setup.rdna2_notes(None), [])
109        self.assertFalse(setup.is_rdna2({"arch": "gfx1030x"}))
110
111    def test_windows_ids_and_names(self):
112        for device, arch in ((0x73BF, "gfx1030"), (0x73AF, "gfx1030"), (0x73A5, "gfx1030"), (0x73DF, "gfx1031")):
113            self.assertEqual(setup.win_amd_arch(device, ""), arch)
114        self.assertEqual(setup.win_amd_arch(None, "AMD Radeon RX 6900 XT"), "gfx1030")
115        self.assertEqual(setup.win_amd_arch(0x744C, "AMD Radeon RX 7900 XTX"), "gfx1100")      # an RX 7000 card is not RDNA2
116
117
118class GpuLists(unittest.TestCase):
119    """--gpus with AMD cards: every chosen card must be supported; the first is the main one."""
120    AMD = [{"index": 0, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0, "arch": "gfx1201"},
121           {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"},
122           {"index": 2, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"},
123           {"index": 3, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 24.0, "arch": "gfx1100"}]
124
125    def setUp(self):
126        self.say = setup.say
127        setup.say = lambda *a, **k: None
128
129    def tearDown(self):
130        setup.say = self.say
131
132    def test_list_in_order(self):
133        self.assertEqual([g["index"] for g in setup.amd_parse_gpus("1,0", self.AMD)], [1, 0])
134        self.assertEqual([g["index"] for g in setup.amd_parse_gpus(" 0, 3 ", self.AMD)], [0, 3])
135
136    def test_all_is_every_supported_card_most_vram_first(self):
137        self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", self.AMD)], [1, 3, 0])
138
139    def test_all_leaves_out_the_apu_beside_two_cards(self):
140        """Strix Halo beside two discrete cards: "all" is the two cards (the APU shares the RAM and draws the desktop); with ONE card it is both
141        (two are needed for a split) and a number list still takes the APU as asked."""
142        apu = {"index": 0, "name": "AMD Radeon 8060S", "vram_gb": 64.0, "arch": "gfx1151", "uma": True}
143        r9700 = {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"}
144        r9070 = {"index": 2, "name": "AMD Radeon RX 9070 XT", "vram_gb": 16.0, "arch": "gfx1201"}
145        self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", [apu, r9700, r9070])], [1, 2])
146        self.assertEqual([g["index"] for g in setup.amd_parse_gpus("all", [apu, r9700])], [1, 0])
147        self.assertEqual([g["index"] for g in setup.amd_parse_gpus("0,1", [apu, r9700, r9070])], [0, 1])
148
149    def test_an_unused_apu_with_a_big_carve_out_is_said(self):
150        apu = {"index": 0, "name": "AMD Radeon 8060S", "vram_gb": 96.0, "arch": "gfx1151", "uma": True, "dedicated_gb": 64.0}
151        r9700 = {"index": 1, "name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "arch": "gfx1201"}
152        out = setup.unused_apu_notes([r9700], [apu, r9700], 62.0)
153        self.assertEqual(len(out), 1)
154        self.assertTrue(out[0].startswith("!") and "64 GB" in out[0] and "62 GB" in out[0])
155        self.assertEqual(setup.unused_apu_notes([apu, r9700], [apu, r9700], 62.0), [])            # in the run: not "unused"
156        self.assertEqual(setup.unused_apu_notes([r9700], [dict(apu, dedicated_gb=2.0), r9700], 120.0), [])   # a small carve-out: nothing to say
157        self.assertEqual(setup.unused_apu_notes([r9700], [r9700], 120.0), [])
158
159    def test_refusals(self):
160        for text in ("1,2", "1,7", "1", "1,1", "x,y"):
161            with self.assertRaises(SystemExit, msg=text):
162                setup.amd_parse_gpus(text, self.AMD)
163
164    def test_wheels_hold_one_family(self):
165        with tempfile.TemporaryDirectory() as d:        # no system ROCm there: the wheels would be needed
166            old = setup.os.environ.get("ROCM_PATH")
167            setup.os.environ["ROCM_PATH"] = d
168            try:
169                with self.assertRaises(SystemExit):
170                    setup.rocm_root(["gfx1100", "gfx1201"])
171            finally:
172                if old is None:
173                    del setup.os.environ["ROCM_PATH"]
174                else:
175                    setup.os.environ["ROCM_PATH"] = old
176
177    def test_runtime_only_system_rocm_falls_back_to_the_wheels(self):
178        """#446: a system ROCm 7 with hipcc and libhipblas but no HIP development files (no hip-lang CMake package, no
179        hip_runtime.h) is not used for the build: a warning says what is missing and the wheels path follows (here
180        it stops at the two-family check, which only the wheels path makes); with the files it is used as before."""
181        said = []
182        setup.say = lambda msg="": said.append(msg)          # tearDown puts the real one back
183        with tempfile.TemporaryDirectory() as d:
184            sysroot = Path(d)
185            for rel, text in (("bin/hipcc", ""), ("lib/libhipblas.so.3", ""),
186                              ("include/rocm-core/rocm_version.h",
187                               "#define ROCM_VERSION_MAJOR 7\n#define ROCM_VERSION_MINOR 14\n")):
188                (sysroot / rel).parent.mkdir(parents=True, exist_ok=True)
189                (sysroot / rel).write_text(text)
190            with mock.patch.dict(setup.os.environ, {"ROCM_PATH": d}):
191                with self.assertRaises(SystemExit):
192                    setup.rocm_root(["gfx1100", "gfx1201"])
193                self.assertIn(f"the ROCm in {sysroot} has no HIP development files (lib/cmake/hip-lang/hip-lang-"
194                              "config.cmake, include/hip/hip_runtime.h): using AMD's wheels", "\n".join(said))
195                self.assertIn("two GPU families", "\n".join(said))
196                for lib in ("lib64", "lib"):                 # either place CMake looks
197                    with self.subTest(lib=lib):
198                        cfg = sysroot / lib / "cmake/hip-lang/hip-lang-config.cmake"
199                        cfg.parent.mkdir(parents=True, exist_ok=True)
200                        cfg.write_text("")
201                        said.clear()
202                        with self.assertRaises(SystemExit):
203                            setup.rocm_root(["gfx1100", "gfx1201"])
204                        self.assertIn("(include/hip/hip_runtime.h)", "\n".join(said))
205                        (sysroot / "include/hip").mkdir(parents=True, exist_ok=True)
206                        (sysroot / "include/hip/hip_runtime.h").write_text("")
207                        self.assertEqual(setup.rocm_root(["gfx1100", "gfx1201"]), (sysroot, [str(sysroot / "lib")]))
208                        cfg.unlink()
209                        (sysroot / "include/hip/hip_runtime.h").unlink()
210
211    def test_build_for_every_arch(self):
212        """build_engine_hip compiles for the set of the chosen cards' archs and records it in BUILD.json."""
213        calls = {}
214        saved = {k: getattr(setup, k) for k in ("ROOT", "rocm_root", "cmake_build", "source_hash", "source_version",
215                                                "ok", "shutil")}
216        with tempfile.TemporaryDirectory() as d:
217            root = Path(d)
218
219            def fake_build(src, bdir, target, defs, vcvars, bat):
220                calls["defs"] = defs
221                (bdir).mkdir(parents=True, exist_ok=True)
222                (bdir / setup.EXE).write_text("engine")
223
224            class Sh:
225                which = staticmethod(lambda name: "/usr/bin/" + name)
226                copy2 = staticmethod(lambda a, b: Path(b).write_text(Path(a).read_text()))
227            setup.ROOT, setup.cmake_build, setup.ok, setup.shutil = root, fake_build, lambda *a: None, Sh
228            setup.source_hash, setup.source_version = (lambda *a: "h"), (lambda: "0.1.31")
229            setup.rocm_root = lambda archs: (calls.setdefault("archs", archs) and root, [str(root / "lib")])
230            try:
231                setup.build_engine_hip({"arch": "gfx1201", "archs": ["gfx1201", "gfx1100", "gfx1201"]}, root)
232                self.assertEqual(calls["archs"], ["gfx1100", "gfx1201"])
233                self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1100;gfx1201", calls["defs"])
234                import json
235                self.assertEqual(json.loads((root / "engine" / "BUILD.json").read_text())["archs"],
236                                 ["gfx1100", "gfx1201"])
237                calls.clear()                            # one of those cards alone: already built, no compile
238                setup.build_engine_hip({"arch": "gfx1100"}, root)
239                self.assertNotIn("defs", calls)
240                setup.build_engine_hip({"arch": "gfx1101"}, root)   # another arch: compiled again
241                self.assertIn("-DCMAKE_HIP_ARCHITECTURES=gfx1101", calls["defs"])
242            finally:
243                for k, v in saved.items():
244                    setattr(setup, k, v)
245
246
247class WindowsDetection(unittest.TestCase):
248    """Windows: the AMD cards from the display adapters (mocked Win32_VideoController rows and display-class registry
249    values), the HIP runtime's numbering from `strata-device --list-devices`, and the card setup chose matched to its
250    HIP ordinal (#325: an integrated Radeon is HIP's device 0)."""
251    ADAPTERS = [  # Win32_VideoController: name, PNPDeviceID, AdapterRAM (32-bit: at most 4 GB)
252        {"name": "NVIDIA GeForce RTX 5070", "pnp": r"PCI\VEN_10DE&DEV_2F04&SUBSYS_1234&REV_A1\4&1", "ram": 4293918720},
253        {"name": "AMD Radeon RX 9070 XT", "pnp": r"PCI\VEN_1002&DEV_7550&SUBSYS_0E3B1002&REV_C0\6&2", "ram": 4293918720},
254        {"name": "AMD Radeon(TM) Graphics", "pnp": r"PCI\VEN_1002&DEV_164E&SUBSYS_88771043&REV_C1\4&3", "ram": 536870912},
255        {"name": "AMD Radeon RX 7800 XT", "pnp": r"PCI\VEN_1002&DEV_7499&SUBSYS_0000&REV_C8\6&4", "ram": 4293918720},
256    ]
257    REGISTRY = [  # the display class's driver instances: 64-bit VRAM size (as int, or as bytes)
258        {"DriverDesc": "NVIDIA GeForce RTX 5070", "MatchingDeviceId": r"PCI\VEN_10DE&DEV_2F04",
259         "HardwareInformation.qwMemorySize": 12 << 30},
260        {"DriverDesc": "AMD Radeon RX 6600", "MatchingDeviceId": r"PCI\VEN_1002&DEV_73FF",     # a removed card
261         "HardwareInformation.qwMemorySize": 8 << 30},
262        {"DriverDesc": "AMD Radeon RX 9070 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7550&REV_C0",
263         "HardwareInformation.qwMemorySize": (16 << 30).to_bytes(8, "little"), "DriverVersion": "32.0.21013.1000"},
264        {"DriverDesc": "AMD Radeon(TM) Graphics", "MatchingDeviceId": r"PCI\VEN_1002&DEV_164E&REV_C1",
265         "HardwareInformation.qwMemorySize": 512 << 20},
266        {"DriverDesc": "AMD Radeon RX 7800 XT", "MatchingDeviceId": r"PCI\VEN_1002&DEV_7499",
267         "HardwareInformation.qwMemorySize": 16 << 30},
268    ]
269    LIST = ("device 0: AMD Radeon(TM) Graphics\n  arch gfx1036, 28.1 GiB, wave32\n"
270            "  cannot run: GPU 0 (AMD Radeon(TM) Graphics, gfx1036) is not an architecture this Strata engine was "
271            "compiled for (gfx1100,gfx1101,gfx1102,gfx1200,gfx1201,gfx1030); ...\n"
272            "device 1: AMD Radeon RX 9070 XT\n  arch gfx1201, 15.9 GiB, wave32\n"
273            "device 2: AMD Radeon RX 7800 XT\n  arch gfx1101, 16.0 GiB, wave32\n")
274
275    def test_adapters(self):
276        g = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY)
277        self.assertEqual([x["name"] for x in g], ["AMD Radeon RX 9070 XT", "AMD Radeon(TM) Graphics",
278                                                  "AMD Radeon RX 7800 XT"])     # AMD only, present only, in order
279        self.assertEqual([x["index"] for x in g], [0, 1, 2])
280        self.assertEqual(g[0]["arch"], "gfx1201")                               # by PCI device id
281        self.assertEqual(g[2]["arch"], "gfx1101")                               # an unlisted id: by its name
282        self.assertTrue(g[1]["arch"].startswith("unknown"))                     # the iGPU: listed, not supported
283        self.assertAlmostEqual(g[0]["vram_gb"], 16.0)                           # the registry's 64-bit size
284        self.assertEqual(g[0]["driver"], "32.0.21013.1000")
285        self.assertEqual([setup.amd_problem(x) is None for x in g], [True, False, True])
286
287    def test_rx_6800m_is_gfx1031(self):
288        """#881: PCI 73DF (RX 6700 XT / 6750 XT / 6800M) is gfx1031, not an unknown id."""
289        self.assertEqual(setup.win_amd_arch(0x73DF, "AMD Radeon RX 6800M"), "gfx1031")
290        self.assertIsNone(setup.amd_problem({"arch": "gfx1031"}))
291
292    def test_cpu_vision_build_uses_the_visual_studio_environment(self):
293        """#881: build_vision_cpu on Windows hands cmake_build the vcvars file and a real .bat name (it passed None and
294        an empty name before)."""
295        calls = []
296        with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "WIN", True),                 mock.patch.object(setup, "find_vcvars", return_value=Path("C:/vs/vcvars64.bat")),                 mock.patch.object(setup, "cmake_build", lambda *a: calls.append(a)),                 mock.patch.object(setup, "ROOT", Path(d)), mock.patch.object(setup.shutil, "copy2"):
297            eng = Path(d) / "engine"
298            eng.mkdir()
299            setup.build_vision_cpu(eng, eng / "BUILD.json", {}, Path("llama"), "src1")
300        self.assertEqual(calls[0][4], Path("C:/vs/vcvars64.bat"))
301        self.assertTrue(calls[0][5].endswith(".bat"))
302
303    def test_registry_alone(self):
304        """No WMI answer: the registry's own list (which can hold a removed card)."""
305        g = setup.amd_gpus_windows([], self.REGISTRY)
306        self.assertEqual([x["arch"] for x in g if not x["arch"].startswith("unknown")], ["gfx1201", "gfx1101"])
307
308    def test_arch_names(self):
309        for name, arch in (("AMD Radeon RX 9070 GRE", "gfx1201"), ("AMD Radeon AI PRO R9700", "gfx1201"),
310                           ("AMD Radeon RX 9060 XT", "gfx1200"), ("AMD Radeon RX 7900 GRE", "gfx1100"),
311                           ("AMD Radeon PRO W7800", "gfx1100"), ("AMD Radeon RX 7700 XT", "gfx1101"),
312                           ("AMD Radeon RX 7600", "gfx1102"), ("AMD Radeon RX 6950 XT", "gfx1030"),
313                           ("AMD Radeon RX 6800M", ""), ("AMD Radeon 780M Graphics", "gfx1103"), ("AMD Radeon RX 7700S", "")):
314            self.assertEqual(setup.win_amd_arch(None, name), arch, name)
315        self.assertEqual(setup.win_amd_arch(0x744C, "whatever"), "gfx1100")
316
317    def test_list_devices(self):
318        h = setup.hip_devices(text=self.LIST)
319        self.assertEqual([(x["index"], x["arch"]) for x in h], [(0, "gfx1036"), (1, "gfx1201"), (2, "gfx1101")])
320        self.assertAlmostEqual(h[1]["vram_gb"], 15.9)
321        self.assertIn("not an architecture", h[0]["cannot_run"])
322        self.assertIsNotNone(setup.amd_problem(h[0]))
323        self.assertIsNone(setup.amd_problem(h[1]))
324        cannot = setup.hip_devices(text="device 0: AMD Radeon RX 9070 XT\n  arch gfx1201, 15.9 GiB, wave32\n"
325                                        "  cannot run: GPU 0 runs wave64\n")
326        self.assertEqual(setup.amd_problem(cannot[0]), "GPU 0 runs wave64")   # the engine's own check counts
327        self.assertEqual(setup.hip_devices(text="(no GPU device)\n"), [])
328
329    def test_the_card_by_its_hip_ordinal(self):
330        """#325: setup's GPU 0 (the 9070 XT, display order) is HIP's device 1 behind the iGPU."""
331        listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY)
332        hip = setup.hip_devices(text=self.LIST)
333        self.assertEqual(setup.hip_match(listed[0], listed, hip)["index"], 1)
334        self.assertEqual(setup.hip_match(listed[2], listed, hip)["index"], 2)
335        two = [{"index": 0, "arch": "gfx1201"}, {"index": 1, "arch": "gfx1201"}]   # two of a kind: by rank
336        self.assertEqual(setup.hip_match(two[1], two, [{"index": 0, "arch": "gfx1036"}, {"index": 1, "arch": "gfx1201"},
337                                                       {"index": 2, "arch": "gfx1201"}])["index"], 2)
338        self.assertIsNone(setup.hip_match({"index": 0, "arch": "gfx1100"}, [{"index": 0, "arch": "gfx1100"}], hip))
339
340    def test_hip_card(self):
341        listed = setup.amd_gpus_windows(self.ADAPTERS, self.REGISTRY)
342        with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)), \
343                mock.patch.object(setup, "ok", lambda *a: None):
344            g = setup.hip_card(Path("engine"), listed[0], listed)
345        self.assertEqual((g["index"], g["count"], g["arch"], g["vram_gb"]), (1, 3, "gfx1201", 15.9))
346        with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: []), \
347                mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit):
348            setup.hip_card(Path("engine"), listed[0], listed)          # no AMD driver: stops before the download
349        with mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: setup_hip(self.LIST)[:1]), \
350                mock.patch.object(setup, "say", lambda *a, **k: None), self.assertRaises(SystemExit):
351            setup.hip_card(Path("engine"), listed[0], listed)          # HIP does not list the card
352
353    def test_windows_dispatch(self):
354        """amd_gpus() on Windows: HIP's numbering once the HIP engine answers, the display adapters before."""
355        with mock.patch.object(setup, "WIN", True), \
356                mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: None), \
357                mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]):
358            self.assertEqual(setup.amd_gpus(), ["display"])
359        with mock.patch.object(setup, "WIN", True), \
360                mock.patch.object(setup, "hip_devices", lambda probe=None, text=None: ["hip"]), \
361                mock.patch.object(setup, "amd_gpus_windows", lambda adapters=None, registry=None: ["display"]):
362            self.assertEqual(setup.amd_gpus(), ["hip"])
363
364    def test_probe_in_the_component_folder(self):
365        """#3418: the app keeps the engine in the component folder, not in control/engine; the cards must be numbered by the
366        HIP runtime there too (an iGPU on ordinal 0 made the display-order "GPU 0" the wrong card)."""
367        from strata_control import engine_component as EC
368        name = "strata-device.exe" if setup.WIN else "strata-device"
369        with tempfile.TemporaryDirectory() as d:
370            root, comp = Path(d) / "control", Path(d) / "components" / "0.2-hip"
371            root.mkdir()
372            comp.mkdir(parents=True)
373            (comp / name).write_text("x")
374            (comp / "engine-component.json").write_text('{"backend": "hip"}')      # no BUILD.json in this package
375            found = mock.Mock(root=comp)
376            with mock.patch.object(setup, "ROOT", root), mock.patch.object(EC, "resolve", return_value=found) as res:
377                self.assertEqual(setup.hip_probe_path(), comp / name)
378                self.assertEqual(res.call_args.kwargs["backend"], "hip")
379                ran = mock.Mock(returncode=0, stdout=self.LIST)
380                with mock.patch.object(setup.subprocess, "run", return_value=ran) as run, \
381                        mock.patch.object(setup, "hip_runtime_beside_exe", lambda *a: None):
382                    cards = setup.hip_devices()
383                self.assertEqual(run.call_args.args[0][0], str(comp / name))
384                self.assertEqual([c["index"] for c in cards], [0, 1, 2])
385            (root / "engine").mkdir()
386            (root / "engine" / name).write_text("x")
387            with mock.patch.object(setup, "ROOT", root), mock.patch.object(EC, "resolve", side_effect=AssertionError):
388                self.assertEqual(setup.hip_probe_path(), root / "engine" / name)    # a checkout's own engine wins
389            with mock.patch.object(setup, "ROOT", Path(d) / "none"), \
390                    mock.patch.object(EC, "resolve", side_effect=EC.EngineMissing("none")):
391                self.assertFalse(setup.hip_probe_path().exists())                  # no engine anywhere: no probe
392
393    def test_no_hip_engine_no_probe(self):
394        with tempfile.TemporaryDirectory() as d:
395            eng = Path(d)
396            (eng / "strata-device.exe").write_text("x")
397            (eng / "BUILD.json").write_text('{"backend": "cuda"}')     # an NVIDIA engine is never asked
398            self.assertIsNone(setup.hip_devices(eng / "strata-device.exe"))
399
400    def test_prebuilt_hip_zip(self):
401        """get_prebuilt_hip: a published zip (here a local folder) is unpacked into engine/; one without code for the
402        card, or older than the first Windows HIP release, is refused."""
403        import json
404        import zipfile
405        with tempfile.TemporaryDirectory() as d:
406            root = Path(d)
407            pub = root / "pub"
408            pub.mkdir()
409
410            def publish(meta):
411                with zipfile.ZipFile(pub / setup.WIN_HIP_ASSET, "w") as z:
412                    z.writestr(setup.EXE, "engine")       # #975: "strata" on Linux
413                    z.writestr("strata-device.exe", "probe")
414                    z.writestr("rocm/bin/amdhip64_7.dll", "dll")
415                    z.writestr("BUILD.json", json.dumps(meta))
416            ver = ".".join(map(str, setup.WIN_HIP_MIN_ENGINE))
417            good = {"source": "prebuilt", "backend": "hip", "version": ver, "archs": ["gfx1100", "gfx1201"],
418                    "lib_dirs": ["rocm/bin"]}
419            with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "say", lambda *a, **k: None), \
420                    mock.patch.object(setup, "ok", lambda *a: None), mock.patch.object(setup, "warn", lambda *a: None):
421                publish({**good, "archs": ["gfx1100"]})
422                self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}))
423                publish({**good, "version": "0.1.30"})
424                self.assertIsNone(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}))
425                publish(good)
426                eng = setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"})
427                self.assertEqual(eng, root / "engine")
428                self.assertTrue((eng / "rocm" / "bin" / "amdhip64_7.dll").exists())
429                self.assertEqual(setup.hip_lib_dirs(eng), [eng / "rocm" / "bin"])
430                (pub / setup.WIN_HIP_ASSET).unlink()           # installed: kept, nothing downloaded again
431                self.assertEqual(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1201"}), eng)
432
433    def test_prebuilt_hip_zip_archs_as_list_or_string(self):
434        """#3810 review: gfx names are names, not numbers - an installed ready-made engine is recognised (no download again) and a zip
435        is accepted whether BUILD.json writes archs as a list or as the ';'-separated string."""
436        import json
437        import zipfile
438        for archs in (["gfx1100", "gfx1151"], "gfx1100;gfx1151"):
439            with tempfile.TemporaryDirectory() as d:
440                root = Path(d)
441                pub = root / "pub"
442                pub.mkdir()
443                ver = ".".join(map(str, setup.WIN_HIP_MIN_ENGINE))
444                meta = {"source": "prebuilt", "backend": "hip", "version": ver, "archs": archs, "lib_dirs": ["rocm/bin"]}
445                with zipfile.ZipFile(pub / setup.WIN_HIP_ASSET, "w") as z:
446                    z.writestr(setup.EXE, "engine")
447                    z.writestr("strata-device.exe", "probe")
448                    z.writestr("rocm/bin/amdhip64_7.dll", "dll")
449                    z.writestr("BUILD.json", json.dumps(meta))
450                with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "say", lambda *a, **k: None),                         mock.patch.object(setup, "ok", lambda *a: None), mock.patch.object(setup, "warn", lambda *a: None):
451                    eng = setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1151"})
452                    self.assertEqual(eng, root / "engine", archs)
453                    (pub / setup.WIN_HIP_ASSET).unlink()           # installed: recognised, nothing downloaded again
454                    self.assertEqual(setup.get_prebuilt_hip(str(pub) + "/", {"arch": "gfx1151"}), eng, archs)
455                    self.assertEqual(setup.engine_archs_hip(), ["gfx1100", "gfx1151"], archs)
456
457
458_HIP_DEVICES = setup.hip_devices                      # the real parser, for the tests that mock setup.hip_devices
459
460
461def setup_hip(text):
462    return _HIP_DEVICES(text=text)
463
464
465class CalibrationKey(unittest.TestCase):
466    """#566: a calibration is saved and found again per PC and model (hardware_key).  A HIP config's cards are AMD's,
467    in HIP's numbering - nvidia-smi named them "?" (or another card with that number) before - and setup reuses a
468    saved calibration on Linux HIP.  The NVIDIA key and the settings file's format are unchanged."""
469    AMD = [{"index": 0, "name": "AMD Radeon RX 7900 XTX", "vram_gb": 23.98, "arch": "gfx1100"},
470           {"index": 1, "name": "AMD Radeon RX 7900 XT", "vram_gb": 19.98, "arch": "gfx1100"},
471           {"index": 2, "name": "AMD Radeon (gfx1201)", "vram_gb": 15.92, "arch": "gfx1201"},
472           {"index": 3, "name": "AMD Radeon (gfx1036)", "vram_gb": 0.5, "arch": "gfx1036"}]
473
474    def setUp(self):
475        self.patches = [mock.patch.object(setup, "amd_gpus", lambda *a, **k: [dict(g) for g in self.AMD]),
476                        mock.patch.object(setup, "cpu_info", lambda: ("AMD Ryzen 9 7950X", 16)),
477                        mock.patch.object(setup, "ram_gb", lambda: 63.6)]
478        for p in self.patches:
479            p.start()
480
481    def tearDown(self):
482        for p in self.patches:
483            p.stop()
484
485    @staticmethod
486    def cfg(gpu, backend="hip", ctx="32768"):
487        c = {"model_name": "qwen3.8-flash-next-iq3_xxs", "args": ["--max-context", ctx, "--kv", "int8"], "gpu": gpu}
488        if backend:
489            c["backend"] = backend
490        return c
491
492    def test_hip_key_names_the_amd_card_and_its_arch(self):
493        def no_nvidia(*a, **k):                     # a HIP config never asks nvidia-smi (a PC with both kinds)
494            raise AssertionError("gpu_info called for a HIP config")
495        with mock.patch.object(setup, "gpu_info", no_nvidia):
496            self.assertEqual(setup.hardware_key(self.cfg(0)),
497                             "AMD Radeon RX 7900 XTX (gfx1100)|24GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|"
498                             "32768|text")
499            # the arch is not repeated when the name already holds it (no product name in sysfs)
500            self.assertTrue(setup.hardware_key(self.cfg(2)).startswith("AMD Radeon (gfx1201)|16GB|"))
501
502    def test_two_cards_of_one_arch_are_two_keys(self):
503        keys = {setup.hardware_key(self.cfg(i)) for i in (0, 1, 2)}
504        self.assertEqual(len(keys), 3)
505
506    def test_a_split_names_every_card(self):
507        self.assertTrue(setup.hardware_key(self.cfg([1, 0])).startswith(
508            "AMD Radeon RX 7900 XT (gfx1100) + AMD Radeon RX 7900 XTX (gfx1100)|44GB|"))
509
510    def test_no_gpu_in_the_config_is_the_supported_card_with_the_most_vram(self):
511        self.assertTrue(setup.hardware_key(self.cfg(None)).startswith("AMD Radeon RX 7900 XTX (gfx1100)|24GB|"))
512
513    def test_a_card_that_is_gone_is_unknown(self):
514        self.assertTrue(setup.hardware_key(self.cfg(7)).startswith("?|0GB|"))
515
516    def test_nvidia_key_unchanged(self):
517        def amd(*a, **k):
518            raise AssertionError("amd_gpus called for an NVIDIA config")
519        with mock.patch.object(setup, "amd_gpus", amd), \
520                mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}):
521            self.assertEqual(setup.hardware_key(self.cfg(0, backend=None)),
522                             "NVIDIA GeForce RTX 5070|12GB|AMD Ryzen 9 7950X|64GB|qwen3.8-flash-next-iq3_xxs|32768|text")
523            self.assertEqual(setup.hardware_key(self.cfg([0, 1], backend="cuda")),
524                             "NVIDIA GeForce RTX 5070 + NVIDIA GeForce RTX 5070|24GB|AMD Ryzen 9 7950X|64GB|"
525                             "qwen3.8-flash-next-iq3_xxs|32768|text")
526
527    def test_nvidia_string_dual_keys_like_the_list(self):
528        """A dual config's string "0,1" keys like [0, 1] (calibrate died with "there is no GPU 0,1")."""
529        def amd(*a, **k):
530            raise AssertionError("amd_gpus called for an NVIDIA config")
531        with mock.patch.object(setup, "amd_gpus", amd), \
532                mock.patch.object(setup, "gpu_info", lambda i=None: {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}):
533            self.assertEqual(setup.hardware_key(self.cfg("0,1", backend="cuda")),
534                             setup.hardware_key(self.cfg([0, 1], backend="cuda")))
535            self.assertEqual(setup.gpu_sel("0,1"), [0, 1])
536            self.assertEqual(setup.gpu_sel("0"), [0])
537        asked = []
538        with mock.patch.object(setup, "amd_gpus", amd), \
539                mock.patch.object(setup, "gpu_info", lambda i=None: asked.append(i) or {"name": "NVIDIA GeForce RTX 5070", "vram_gb": 11.94}):
540            setup.hardware_key(self.cfg(1, backend="cuda"))      # a single card given as a number still asks for that card
541            self.assertEqual(asked, [1])
542
543    def test_setup_reuses_a_saved_calibration_on_linux_hip(self):
544        cfg = self.cfg(1)
545        saved = {"settings": {"pcie_frac": 0.0}, "tok_s": 40.1, "date": "2026-10-03"}
546        other = {"settings": {"pcie_frac": 0.5}, "tok_s": 50.0, "date": "2026-10-02"}
547        store = {"calibration": {setup.hardware_key(cfg): saved, setup.hardware_key(self.cfg(0)): other}}
548        with mock.patch.object(setup, "load_settings", lambda: store):
549            with mock.patch.object(setup, "WIN", False):
550                self.assertEqual(setup.setup_calibration(cfg, hip=True), saved)       # its own card's, not the XTX's
551                self.assertIsNone(setup.setup_calibration(self.cfg(2), hip=True))     # never tuned on that card
552            with mock.patch.object(setup, "WIN", True):
553                self.assertIsNone(setup.setup_calibration(cfg, hip=True))             # Windows HIP: defaults for now
554
555
556class HipVisionWish(unittest.TestCase):
557    """AMD pictures are on by default, on Linux and Windows: the wish is "gpu" (hip_reader() settles it against the readers the
558    engine folder carries: the HIP one, else the CPU one), "cpu" when asked for, "none" for no."""
559
560    def test_wish(self):
561        for win in (True, False):
562            with mock.patch.object(setup, "WIN", win):
563                self.assertEqual(setup.hip_vision(None), "gpu")
564                self.assertEqual(setup.hip_vision("yes"), "gpu")
565                self.assertEqual(setup.hip_vision("gpu"), "gpu")
566                self.assertEqual(setup.hip_vision("cpu"), "cpu")
567                self.assertEqual(setup.hip_vision("no"), "none")
568                self.assertEqual(setup.hip_vision("none"), "none")
569                # owner decision 2026-10-18: nothing asked / yes = the CPU reader under 24 GB, the GPU reader from 24 GB; gpu / cpu are kept
570                self.assertEqual(setup.hip_vision(None, 16.0), "cpu")
571                self.assertEqual(setup.hip_vision("yes", 16.0), "cpu")
572                self.assertEqual(setup.hip_vision("yes", 23.9), "gpu")
573                self.assertEqual(setup.hip_vision(None, 32.0), "gpu")
574                self.assertEqual(setup.hip_vision("gpu", 16.0), "gpu")
575                self.assertEqual(setup.hip_vision("cpu", 32.0), "cpu")
576
577    def test_reader_settled_against_the_engine_folder(self):
578        for win, suffix in ((False, ""), (True, ".exe")):
579            with tempfile.TemporaryDirectory() as d, mock.patch.object(setup, "WIN", win),                     mock.patch.object(setup, "warn", lambda *a: None):
580                eng = Path(d)
581                (eng / ("strata-vision" + suffix)).write_bytes(b"x")
582                self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1201"})[0], "cpu")        # no HIP reader: the CPU one
583                (eng / ("strata-vision-hip" + suffix)).write_bytes(b"x")
584                mode, r = setup.hip_reader(eng, "gpu", {"arch": "gfx1201"})
585                self.assertEqual((mode, r.exe.name, r.cpu_exe.name),
586                                 ("gpu", "strata-vision-hip" + suffix, "strata-vision" + suffix))
587                (eng / "BUILD.json").write_text('{"vision_archs": ["gfx1100"]}')
588                self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1201"})[0], "cpu")        # the card is not in its build
589                self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1100"})[0], "gpu")
590                self.assertEqual(setup.hip_reader(eng, "cpu", {"arch": "gfx1100"})[0], "cpu")
591                (eng / ("strata-vision" + suffix)).unlink()
592                (eng / ("strata-vision-hip" + suffix)).unlink()
593                self.assertEqual(setup.hip_reader(eng, "gpu", {"arch": "gfx1100"})[0], "none")
594
595
596class HipRuntimeBesideExe(unittest.TestCase):
597    """#468 #461: the bundled HIP runtime (and amd_comgr) goes next to strata.exe, so an AMD driver's System32 copy is
598    not found first; rocBLAS and the rest stay in rocm/bin."""
599
600    def test_copies_only_the_runtime(self):
601        import json
602        with tempfile.TemporaryDirectory() as d:
603            eng = Path(d)
604            rb = eng / "rocm" / "bin"
605            rb.mkdir(parents=True)
606            (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "lib_dirs": ["rocm/bin"]}))
607            for n, data in (("amdhip64_7.dll", b"hip-3686"), ("amd_comgr.dll", b"comgr"), ("rocblas.dll", b"blas")):
608                (rb / n).write_bytes(data)
609            setup.hip_runtime_beside_exe(eng)
610            self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3686")
611            self.assertEqual((eng / "amd_comgr.dll").read_bytes(), b"comgr")
612            self.assertFalse((eng / "rocblas.dll").exists())          # finds its kernels relative to rocm/bin
613            (rb / "amdhip64_7.dll").write_bytes(b"hip-3690-newer")    # a newer zip: replaced on the next start
614            setup.hip_runtime_beside_exe(eng)
615            self.assertEqual((eng / "amdhip64_7.dll").read_bytes(), b"hip-3690-newer")
616
617    def test_no_rocm_bin_is_a_no_op(self):
618        with tempfile.TemporaryDirectory() as d:
619            setup.hip_runtime_beside_exe(Path(d))                   # no BUILD.json (a CUDA or Linux engine)
620            self.assertEqual(list(Path(d).iterdir()), [])
621
622
623class DeviceAccess(unittest.TestCase):
624    """Linux AMD: /dev/kfd and the render nodes must be openable by the user; setup warns, never refuses."""
625
626    def dev(self, d, kfd=True, nodes=("renderD128",)):
627        root = Path(d)
628        (root / "dri").mkdir()
629        if kfd:
630            (root / "kfd").write_text("")
631        for n in nodes:
632            (root / "dri" / n).write_text("")
633        return str(root)
634
635    def test_accessible_is_silent(self):
636        with tempfile.TemporaryDirectory() as d:
637            self.assertIsNone(setup.amd_device_access_problem(self.dev(d), access=lambda p, m: True))
638
639    def test_no_kfd_is_not_this_problem(self):
640        with tempfile.TemporaryDirectory() as d:
641            self.assertIsNone(setup.amd_device_access_problem(self.dev(d, kfd=False), access=lambda p, m: False))
642
643    def test_kfd_denied_names_the_fix(self):
644        with tempfile.TemporaryDirectory() as d:
645            msg = setup.amd_device_access_problem(self.dev(d), access=lambda p, m: not p.endswith("kfd"))
646            self.assertIn("kfd", msg)
647            self.assertNotIn("renderD128", msg)
648            self.assertIn("sudo usermod -aG render,video $USER", msg)
649            self.assertIn("log out and in", msg)
650
651    def test_render_node_denied(self):
652        with tempfile.TemporaryDirectory() as d:
653            msg = setup.amd_device_access_problem(self.dev(d), access=lambda p, m: "renderD" not in p)
654            self.assertIn("renderD128", msg)
655            self.assertNotIn("/kfd", msg)
656
657    def test_engine_names_the_permission_not_another_program(self):
658        src = (Path(setup.__file__).resolve().parent / "src/program/generate.cpp").read_text(encoding="utf-8")
659        i = src.index("cannot open /dev/kfd")
660        guard = src[src.rindex("#if", 0, i):i]
661        self.assertIn("cudaGetDeviceCount", guard)
662        self.assertIn('access("/dev/kfd", R_OK | W_OK)', guard)
663        self.assertIn("STRATA_USE_HIP", guard)               # CUDA builds keep the "another program" text
664        self.assertIn("another program (or an engine that is still exiting)", src)
665
666
667class EngineLaunchEnv(unittest.TestCase):
668    """#2372: every engine program setup runs gets the ready-made HIP engine's rocm/bin on PATH, or Windows shows a
669    "hipblas.dll not found" dialog per DLL and `strata --families` prints nothing (setup then said the engine does
670    not run Qwen3.6)."""
671
672    def engine(self, tmp: Path) -> Path:
673        eng = tmp / "engine"
674        (eng / "rocm" / "bin").mkdir(parents=True)
675        (eng / "BUILD.json").write_text('{"backend": "hip", "lib_dirs": ["rocm/bin"]}', encoding="utf-8")
676        return eng
677
678    def test_engine_env_puts_rocm_bin_first_on_windows(self):
679        with tempfile.TemporaryDirectory() as t:
680            eng = self.engine(Path(t))
681            with mock.patch.dict("os.environ", {"PATH": "C:\\Windows"}), \
682                 mock.patch.object(setup.os, "name", "nt"):
683                env = setup.engine_env(eng)
684            self.assertEqual(env["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin"))
685            self.assertTrue(env["PATH"].endswith("C:\\Windows"))
686
687    def test_engine_env_puts_rocm_bin_first_on_ld_library_path(self):
688        with tempfile.TemporaryDirectory() as t:
689            eng = self.engine(Path(t))
690            with mock.patch.dict("os.environ", {"PATH": "/usr/bin", "LD_LIBRARY_PATH": "/usr/lib"}), \
691                 mock.patch.object(setup.os, "name", "posix"):
692                env = setup.engine_env(eng)
693            self.assertEqual(env["LD_LIBRARY_PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin"))
694            self.assertTrue(env["LD_LIBRARY_PATH"].endswith("/usr/lib"))
695            self.assertEqual(env["PATH"], "/usr/bin")
696
697    def test_engine_without_lib_dirs_keeps_the_environment(self):
698        with tempfile.TemporaryDirectory() as t:
699            with mock.patch.dict("os.environ", {"PATH": "/usr/bin"}):
700                self.assertEqual(setup.engine_env(Path(t))["PATH"], "/usr/bin")
701
702    def test_families_probe_runs_with_that_env(self):
703        seen = {}
704
705        def fake_run(cmd, **kw):
706            seen["cmd"], seen["env"] = cmd, kw.get("env")
707            return mock.Mock(stdout="qwen4exp qwen35moe\n")
708        with tempfile.TemporaryDirectory() as t:
709            eng = self.engine(Path(t))
710            with mock.patch.object(setup.subprocess, "run", fake_run), \
711                 mock.patch.object(setup.os, "name", "nt"):
712                names = setup.engine_families(eng)
713            self.assertEqual(names, {"qwen4exp", "qwen35moe"})
714            self.assertEqual(seen["cmd"][1], "--families")
715            self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin"))
716
717    def test_device_probe_runs_with_that_env(self):
718        seen = {}
719
720        def fake_run(cmd, **kw):
721            seen["env"] = kw.get("env")
722            return mock.Mock(returncode=0, stdout="device 0: AMD Radeon RX 7900 XT\n  arch gfx1100, 20.0 GiB, wave32\n")
723        with tempfile.TemporaryDirectory() as t:
724            eng = self.engine(Path(t))
725            probe = eng / ("strata-device.exe" if setup.WIN else "strata-device")
726            probe.write_text("x")
727            with mock.patch.object(setup.subprocess, "run", fake_run),                     mock.patch.object(setup, "hip_runtime_beside_exe", lambda d: None), mock.patch.object(setup.os, "name", "nt"):
728                found = setup.hip_devices(probe)
729            self.assertEqual(found[0]["arch"], "gfx1100")
730            self.assertEqual(seen["env"]["PATH"].split(setup.os.pathsep)[0], str(eng / "rocm" / "bin"))
731
732
733class TdrPointer(unittest.TestCase):
734    def test_setup_points_windows_gfx12_to_the_entry(self):
735        src = Path(setup.__file__).read_text(encoding="utf-8")
736        self.assertIn('WIN and str(gpu.get("arch") or "").startswith("gfx12")', src)
737        doc = (Path(setup.__file__).resolve().parent / "docs/TROUBLESHOOTING.md").read_text(encoding="utf-8")
738        self.assertIn("Windows AMD: the driver resets", doc)
739        for env in ("STRATA_PF_STEP_SYNC", "STRATA_KV_HOST_DMA"):
740            self.assertIn(env, doc)
741            self.assertIn(env, (Path(setup.__file__).resolve().parent / "src/prefill/prefill.cpp").read_text(encoding="utf-8"))
742
743
744if __name__ == "__main__":
745    unittest.main()