okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
31.0 KiB561 linesraw
1"""Tests for setup.py's recognition of AMD Strix Halo (Ryzen AI Max, Radeon 8060S / 8050S / 8040S, gfx1151): the exact
2arch check (never a prefix: gfx1150 / gfx1152 are other chips), the PCI ids and marketing names, the unified-memory
3sizing, which card setup picks beside a discrete one, and the Windows engine zip (a zip without gfx1151 code is never used).
4
5The Linux fixture is Aurora's real answer (the maintainers' Strix Halo box, read-only):
6  KFD node 1: gfx_target_version 110501, simd_count 80, vendor_id 4098, device_id 5510 (0x1586), drm_render_minor 128
7  /sys/class/drm/card1/device: vendor 0x1002, device 0x1586, mem_info_vram_total 2147483648 (a 2 GiB BIOS carve-out),
8                               mem_info_gtt_total 120259084288 (112 GiB: ttm.pages_limit=29360128), no product_name
9  lspci -nn: c6:00.0 Display controller [0380]: AMD/ATI Strix Halo [Radeon Graphics / Radeon 8050S Graphics /
10             Radeon 8060S Graphics] [1002:1586] (rev c1);  MemTotal 127098456 kB
11The other chips are synthetic (their KFD gfx_target_version and pci.ids ids).  No GPU, no ROCm, no downloads.
12
13    python -m unittest tools.test_setup_strix_halo
14"""
15from __future__ import annotations
16
17import hashlib
18import io
19import json
20import re
21import sys
22import tempfile
23import unittest
24import zipfile
25from pathlib import Path
26from unittest import mock
27
28ROOT = Path(__file__).resolve().parents[1]
29sys.path.insert(0, str(ROOT))
30import setup  # noqa: E402
31
32AURORA_RAM_GB = 127098456 * 1024 / 2 ** 30          # /proc/meminfo MemTotal on Aurora: 121.2 GiB
33GIB = 1 << 30
34
35
36def fake_gpu(root: Path, node: int, ver: int, simd: int, minor: int, pci_id: int, vram: int, gtt: int,
37             product: str | None = None, card: int | None = None) -> None:
38    """One KFD GPU node + its drm device, laid out as the kernel does (see the module docstring)."""
39    n = root / "class/kfd/kfd/topology/nodes" / str(node)
40    n.mkdir(parents=True, exist_ok=True)
41    (n / "properties").write_text(f"cpu_cores_count 0\nsimd_count {simd}\nmem_banks_count 1\n"
42                                  f"gfx_target_version {ver}\nvendor_id 4098\ndevice_id {pci_id}\n"
43                                  f"drm_render_minor {minor}\nlocal_mem_size 0\n")
44    d = root / f"class/drm/renderD{minor}/device"
45    d.mkdir(parents=True, exist_ok=True)
46    for name, val in (("vendor", "0x1002"), ("device", f"0x{pci_id:04x}"), ("mem_info_vram_total", str(vram)),
47                      ("mem_info_gtt_total", str(gtt))):
48        (d / name).write_text(val + "\n")
49    if product:
50        (d / "product_name").write_text(product + "\n")
51    if card is not None:                              # /sys/class/drm/card<N>/device (what amd_pci_devices reads)
52        c = root / f"class/drm/card{card}/device"
53        c.mkdir(parents=True, exist_ok=True)
54        for name in ("vendor", "device", "mem_info_vram_total", "mem_info_gtt_total"):
55            (c / name).write_text((d / name).read_text())
56
57
58def cpu_node(root: Path, node: int = 0) -> None:
59    n = root / "class/kfd/kfd/topology/nodes" / str(node)
60    n.mkdir(parents=True, exist_ok=True)
61    (n / "properties").write_text("cpu_cores_count 32\nsimd_count 0\ngfx_target_version 0\nvendor_id 0\ndevice_id 0\n")
62
63
64class LinuxBase(unittest.TestCase):
65    def setUp(self):
66        self.tmp = tempfile.TemporaryDirectory()
67        self.root = Path(self.tmp.name)
68        self.win = setup.WIN
69        setup.WIN = False
70        p = mock.patch.object(setup, "ram_gb", return_value=AURORA_RAM_GB)
71        p.start()
72        self.addCleanup(p.stop)
73
74    def tearDown(self):
75        setup.WIN = self.win
76        self.tmp.cleanup()
77
78    def aurora(self, node=1, minor=128, card=1):
79        fake_gpu(self.root, node, 110501, 80, minor, 0x1586, 2 * GIB, 120259084288, None, card)
80
81
82class ExactArch(unittest.TestCase):
83    def test_gfx1151_is_exact(self):
84        self.assertTrue(setup.gfx_arch_is("gfx1151", "gfx1151"))
85        self.assertTrue(setup.gfx_arch_is("gfx1151:sramecc-:xnack-", "gfx1151"))     # gcnArchName
86        for other in ("gfx1150", "gfx1152", "gfx115", "gfx11510", "gfx1103", "gfx1100", "gfx1201", "gfx1030", "", None):
87            self.assertFalse(setup.gfx_arch_is(other, "gfx1151"), other)
88            self.assertFalse(setup.is_strix_halo({"arch": other}), other)
89        self.assertFalse(setup.gfx_arch_is("gfx1151", "gfx115"))                     # no prefix match either way
90        self.assertFalse(setup.is_strix_halo({}))
91
92    def test_matches_the_engines_header(self):
93        """include/strata/kernels/gfx_arch.hpp is the reference: gfx1151 has the WMMA kernels and the gfx1151 defaults;
94        gfx1103 (Radeon 780M/760M, 0.1.44) shares the gfx11 WMMA kernels; gfx1152 is outside the list."""
95        hpp = (ROOT / "include/strata/kernels/gfx_arch.hpp").read_text(encoding="utf-8")
96        wmma = re.search(r"gfx_arch_is_gfx11_wmma.*?\n}", hpp, re.S).group(0)
97        listed = set(re.findall(r'"(gfx\d+)"', wmma))
98        self.assertIn("gfx1151", listed)
99        self.assertIn("gfx1103", listed)          # 0.1.44: the 780M runs the gfx11 WMMA kernels (decode x1.53)
100        self.assertNotIn("gfx1152", listed)
101        self.assertIn('gfx_arch_is(gcn, "gfx1151")', hpp)
102        self.assertEqual(setup.STRIX_HALO_ARCH, "gfx1151")
103
104    def test_arch_lists(self):
105        self.assertIn("gfx1151", setup.AMD_ARCHS)
106        self.assertIn("gfx1151", setup.ROCM_INDEXES)
107        self.assertTrue(setup.ROCM_INDEXES["gfx1151"].endswith("/gfx1151/"))
108        for a in ("gfx1150", "gfx1152", "gfx1103"):                                  # never supported by accident
109            self.assertNotIn(a, setup.AMD_ARCHS)
110        self.assertIn("docs/STRIX_HALO.md", setup.AMD_CARDS)
111
112# gfx1151 arch defaults that setup does not copy to gfx1103 / gfx1150: HCD_EXACT copies the gfx1151 hipBLASLt table's
113# solutions, TOPK_REG_MIN_BLOCKS (#1943: the top-k register-kernel line at 4096 blocks, the crossover with the
114# cooperative scan) was measured on gfx1151 only
115_NOT_COPIED = ("STRATA_HCD_EXACT", "STRATA_TOPK_REG_MIN_BLOCKS")
116
117
118
119class Gfx1103Switches(unittest.TestCase):
120    def test_is_the_gfx1151_defaults_less_hcd_exact(self):
121        """GFX1103_SWITCHES is the gfx1151 arch-default set (src/core/arch_defaults.cpp) minus STRATA_HCD_EXACT, which
122        copies the gfx1151 hipBLASLt table's solutions 1176 / 1177 and so does not apply beside a gfx1103 table.  The
123        engine keeps gfx1103 out of its own arch defaults, so setup writes this set."""
124        src = (ROOT / "src/core/arch_defaults.cpp").read_text(encoding="utf-8")
125        tail = src.split("gfx_arch_is_gfx1151(gcn_arch)) return t;", 1)[1].split("bool igpu_prompt_defaults_arch", 1)[0]   # the gfx1151 function only, not the iGPU set below it
126        block = tail.rsplit("t = {", 1)[1].split("};", 1)[0]              # the gfx1151 switch table
127        gfx1151 = dict(re.findall(r'\{"(STRATA_[A-Z0-9_]+)",\s*"([^"]+)"\}', block))
128        self.assertIn("STRATA_HCD_EXACT", gfx1151)                       # the parse found the gfx1151 block
129        self.assertEqual(setup.GFX1103_SWITCHES,
130                         {k: v for k, v in gfx1151.items() if k not in _NOT_COPIED})
131        self.assertNotIn("STRATA_HCD_EXACT", setup.GFX1103_SWITCHES)
132        for k in setup.GFX1103_SWITCHES:                                 # setup's own: a re-run refreshes them
133            self.assertIn(k, setup.SETUP_ENV)
134
135
136class Gfx1150Switches(unittest.TestCase):
137    def test_is_the_gfx1151_defaults_less_hcd_exact(self):
138        """GFX1150_SWITCHES is the gfx1151 arch-default set (src/core/arch_defaults.cpp) minus STRATA_HCD_EXACT, which
139        copies the gfx1151 hipBLASLt table's solutions 1176 / 1177 and so does not apply beside a gfx1150 table.  The
140        engine keeps gfx1150 out of its own arch defaults (src/core/arch_defaults_test.cpp), so setup writes this set."""
141        src = (ROOT / "src/core/arch_defaults.cpp").read_text(encoding="utf-8")
142        tail = src.split("gfx_arch_is_gfx1151(gcn_arch)) return t;", 1)[1].split("bool igpu_prompt_defaults_arch", 1)[0]   # the gfx1151 function only, not the iGPU set below it
143        block = tail.rsplit("t = {", 1)[1].split("};", 1)[0]              # the gfx1151 switch table
144        gfx1151 = dict(re.findall(r'\{"(STRATA_[A-Z0-9_]+)",\s*"([^"]+)"\}', block))
145        self.assertIn("STRATA_HCD_EXACT", gfx1151)                       # the parse found the gfx1151 block
146        self.assertEqual(setup.GFX1150_SWITCHES,
147                         {k: v for k, v in gfx1151.items() if k not in _NOT_COPIED})
148        self.assertNotIn("STRATA_HCD_EXACT", setup.GFX1150_SWITCHES)
149        for k in setup.GFX1150_SWITCHES:                                 # setup's own: a re-run refreshes them
150            self.assertIn(k, setup.SETUP_ENV)
151        self.assertIn('arch_default_env("gfx1150").empty()',
152                      (ROOT / "src/core/arch_defaults_test.cpp").read_text(encoding="utf-8"))
153
154
155class PciIds(unittest.TestCase):
156    def test_strix_halo_id(self):
157        # pci.ids: one id for every Strix Halo part (8060S, 8050S, 8040S share it; they differ by CU count)
158        self.assertEqual(setup.STRIX_HALO_PCI_IDS, {0x1586})
159        self.assertEqual(setup.AMD_IGPU_PCI[0x1586], "gfx1151")
160
161    def test_other_igpus_are_not_strix_halo(self):
162        for did, arch in ((0x150E, "gfx1150"), (0x1114, "gfx1152"), (0x1902, "gfx1152"), (0x15BF, "gfx1103"),
163                          (0x15C8, "gfx1103"), (0x164F, "gfx1103"), (0x1900, "gfx1103"), (0x1901, "gfx1103")):
164            self.assertEqual(setup.AMD_IGPU_PCI[did], arch)
165            self.assertNotIn(did, setup.STRIX_HALO_PCI_IDS)
166        self.assertEqual([a for a in setup.AMD_IGPU_PCI.values() if a == "gfx1151"], ["gfx1151"])
167
168    def test_windows_id_then_name(self):
169        f = setup.win_amd_arch
170        self.assertEqual(f(0x1586, ""), "gfx1151")
171        self.assertEqual(f(0x1586, "AMD Radeon(TM) Graphics"), "gfx1151")           # the generic name Windows may show
172        for name in ("AMD Radeon(TM) 8060S Graphics", "AMD Radeon(TM) 8050S Graphics", "AMD Radeon(TM) 8040S Graphics"):
173            self.assertEqual(f(None, name), "gfx1151", name)                          # an id we do not know: by name
174        self.assertEqual(f(0x150E, "AMD Radeon(TM) 890M Graphics"), "gfx1150")
175        self.assertEqual(f(None, "AMD Radeon(TM) 880M Graphics"), "gfx1150")
176        self.assertEqual(f(None, "AMD Radeon(TM) 860M Graphics"), "gfx1152")
177        self.assertEqual(f(None, "AMD Radeon(TM) 840M Graphics"), "gfx1152")
178        self.assertEqual(f(0x15BF, "AMD Radeon(TM) 780M Graphics"), "gfx1103")
179        self.assertEqual(f(None, "AMD Radeon(TM) 760M Graphics"), "gfx1103")
180        # the discrete cards keep their own arch
181        self.assertEqual(f(0x744C, "AMD Radeon RX 7900 XTX"), "gfx1100")
182        self.assertEqual(f(None, "AMD Radeon RX 7900 XTX"), "gfx1100")
183        self.assertEqual(f(0x7550, "AMD Radeon RX 9070 XT"), "gfx1201")
184        self.assertEqual(f(None, "AMD Radeon RX 7600M XT"), "gfx1102")                # not the 780M rule
185        self.assertEqual(f(None, "AMD Radeon RX 6800M"), "")
186
187
188class AuroraFixture(LinuxBase):
189    def test_aurora(self):
190        cpu_node(self.root, 0)
191        self.aurora()
192        g = setup.amd_gpus(str(self.root))
193        self.assertEqual(len(g), 1)
194        g = g[0]
195        self.assertEqual((g["index"], g["arch"], g["pci_id"]), (0, "gfx1151", 0x1586))
196        self.assertEqual(g["name"], "AMD Radeon 8060S (Ryzen AI Max, Strix Halo, gfx1151)")     # 80 SIMDs = 40 CUs
197        self.assertIsNone(setup.amd_problem(g))
198        self.assertTrue(g["uma"] and setup.is_strix_halo(g))
199        self.assertAlmostEqual(g["dedicated_gb"], 2.0)                                # the BIOS carve-out
200        self.assertAlmostEqual(g["shared_gb"], 112.0)                                 # GTT, below RAM - 6
201        self.assertAlmostEqual(g["vram_gb"], 114.0)
202        self.assertAlmostEqual(setup.low_ram_vram(g), 2.0)                            # the shared pool is the RAM itself
203        self.assertIn("unified memory", setup.amd_mem_text(g))
204
205    def test_marketing_name_by_cu_count(self):
206        for simd, name in ((80, "8060S"), (64, "8050S"), (32, "8040S")):
207            root = Path(tempfile.mkdtemp(dir=self.root))
208            fake_gpu(root, 0, 110501, simd, 128, 0x1586, 2 * GIB, 112 * GIB)
209            g = setup.amd_gpus(str(root))[0]
210            self.assertIn(name, g["name"])
211            self.assertEqual(g["arch"], "gfx1151")
212        root = Path(tempfile.mkdtemp(dir=self.root))
213        fake_gpu(root, 0, 110501, 48, 128, 0x1586, 2 * GIB, 112 * GIB)                  # an unknown CU count
214        self.assertEqual(setup.amd_gpus(str(root))[0]["name"], setup.AMD_NAMES["gfx1151"])
215
216    def test_name_from_sysfs_is_kept(self):
217        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 120259084288, "AMD Radeon 8060S")
218        self.assertEqual(setup.amd_gpus(str(self.root))[0]["name"], "AMD Radeon 8060S")
219
220    def test_pci_scan(self):
221        self.aurora()
222        d = setup.amd_pci_devices(str(self.root))
223        self.assertEqual([(x["pci_id"], x["arch"]) for x in d], [(0x1586, "gfx1151")])
224        self.assertAlmostEqual(d[0]["gtt_gb"], 112.0)
225        self.assertIn(d[0]["pci_id"], setup.STRIX_HALO_PCI_IDS)
226
227    def test_gtt_never_exceeds_the_ram(self):
228        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 512 << 20, 200 * GIB)         # a bogus 200 GiB GTT
229        g = setup.amd_gpus(str(self.root))[0]
230        self.assertAlmostEqual(g["shared_gb"], AURORA_RAM_GB - setup.UMA_OS_LEFT_GB)
231
232    def test_no_gtt_file_means_half_the_ram(self):
233        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 0)
234        g = setup.amd_gpus(str(self.root))[0]
235        self.assertAlmostEqual(g["shared_gb"], AURORA_RAM_GB / 2)
236
237    def test_big_carve_out(self):
238        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 96 * GIB, 24 * GIB)           # 96 GB carve-out, 32 GB left
239        with mock.patch.object(setup, "ram_gb", return_value=30.0):
240            g = setup.amd_gpus(str(self.root))[0]
241        self.assertAlmostEqual(g["dedicated_gb"], 96.0)
242        self.assertAlmostEqual(g["vram_gb"], 96.0 + 24.0)
243        self.assertAlmostEqual(setup.low_ram_vram(g), 96.0)                           # that memory is extra to the RAM
244        notes = setup.strix_halo_notes(g, 30.0)
245        self.assertTrue(any(n.startswith("!") and "carve-out" in n for n in notes))
246
247    def test_small_carve_out(self):
248        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 512 << 20, 60 * GIB)          # 512 MB carve-out
249        g = setup.amd_gpus(str(self.root))[0]
250        self.assertAlmostEqual(g["dedicated_gb"], 0.5)
251
252
253class OtherChips(LinuxBase):
254    """Synthetic KFD nodes: gfx_target_version as the kernel reports it."""
255
256    def one(self, ver, pci, vram, gtt=0):
257        root = Path(tempfile.mkdtemp(dir=self.root))
258        fake_gpu(root, 0, ver, 64, 128, pci, vram, gtt)
259        return setup.amd_gpus(str(root))[0]
260
261    def test_strix_point(self):
262        g = self.one(110500, 0x150E, 512 << 20, 60 * GIB)
263        self.assertEqual(g["arch"], "gfx1150")
264        self.assertFalse(setup.is_strix_halo(g) or g.get("uma"))
265        self.assertIn("gfx1150", setup.amd_problem(g))
266        self.assertIn("not Strix Halo", setup.amd_problem(g))
267        self.assertIn("890M", g["name"])
268
269    def test_krackan(self):
270        g = self.one(110502, 0x1114, 512 << 20, 30 * GIB)
271        self.assertEqual(g["arch"], "gfx1152")
272        self.assertFalse(g.get("uma"))
273        self.assertIn("gfx1152", setup.amd_problem(g))
274        self.assertIn("860M", g["name"])
275
276    def test_phoenix_hawk_point(self):
277        g = self.one(110003, 0x15BF, 512 << 20, 30 * GIB)
278        self.assertEqual(g["arch"], "gfx1103")
279        self.assertFalse(g.get("uma"))
280        self.assertIn("gfx1103", setup.amd_problem(g))
281        self.assertIn("780M", g["name"])
282
283    def test_discrete_cards(self):
284        for ver, arch, pci, vram in ((110000, "gfx1100", 0x744C, 24), (110001, "gfx1101", 0x747E, 16),
285                                     (110002, "gfx1102", 0x7480, 8), (120001, "gfx1201", 0x7550, 16),
286                                     (100300, "gfx1030", 0x73BF, 16)):
287            g = self.one(ver, pci, vram * GIB, 32 * GIB)
288            self.assertEqual(g["arch"], arch)
289            self.assertFalse(g.get("uma"), arch)
290            self.assertFalse(setup.is_strix_halo(g), arch)
291            self.assertAlmostEqual(g["vram_gb"], vram)                                # a card's VRAM is not changed
292            self.assertEqual(setup.low_ram_vram(g), vram)
293            self.assertIsNone(setup.amd_problem(g), arch)
294
295
296class DualGpu(LinuxBase):
297    def test_strix_halo_with_a_discrete_card(self):
298        cpu_node(self.root, 0)
299        fake_gpu(self.root, 1, 110501, 80, 128, 0x1586, 2 * GIB, 112 * GIB, None, 1)
300        fake_gpu(self.root, 2, 110000, 192, 129, 0x744C, 24 * GIB, 16 * GIB, "AMD Radeon RX 7900 XTX", 2)
301        g = setup.amd_gpus(str(self.root))
302        self.assertEqual([(x["index"], x["arch"]) for x in g], [(0, "gfx1151"), (1, "gfx1100")])
303        self.assertTrue(g[0]["uma"] and not g[1].get("uma"))
304        self.assertTrue(g[0]["vram_gb"] > g[1]["vram_gb"])                           # 114 GB of unified memory vs 24
305        self.assertEqual(min(g, key=setup.amd_rank)["arch"], "gfx1100")              # the card with its own memory
306        self.assertEqual([x["arch"] for x in setup.amd_parse_gpus("all", g)], ["gfx1100", "gfx1151"])
307        self.assertEqual([x["arch"] for x in setup.amd_parse_gpus("0,1", g)], ["gfx1151", "gfx1100"])
308        self.assertEqual(sorted(a for a in {x["arch"] for x in g}), ["gfx1100", "gfx1151"])   # compiled for both if split
309        # two TheRock families: a split needs a system ROCm (rocm_root says so); one card does not
310        self.assertNotEqual(setup.ROCM_INDEXES["gfx1100"], setup.ROCM_INDEXES["gfx1151"])
311
312    def test_strix_halo_with_strix_point_is_impossible_but_not_confused(self):
313        cpu_node(self.root, 0)
314        fake_gpu(self.root, 1, 110500, 32, 128, 0x150E, 512 << 20, 30 * GIB)
315        fake_gpu(self.root, 2, 110501, 80, 129, 0x1586, 2 * GIB, 112 * GIB)
316        g = setup.amd_gpus(str(self.root))
317        self.assertEqual([x["arch"] for x in g], ["gfx1150", "gfx1151"])
318        self.assertEqual([bool(setup.amd_problem(x)) for x in g], [True, False])
319        self.assertEqual([bool(x.get("uma")) for x in g], [False, True])
320        usable = [x for x in g if setup.amd_problem(x) is None]
321        self.assertEqual(min(usable, key=setup.amd_rank)["index"], 1)
322
323    def test_two_strix_halo_ranked_by_index(self):
324        fake_gpu(self.root, 0, 110501, 80, 128, 0x1586, 2 * GIB, 112 * GIB)
325        fake_gpu(self.root, 1, 110501, 80, 129, 0x1586, 2 * GIB, 112 * GIB)
326        g = setup.amd_gpus(str(self.root))
327        self.assertEqual(min(g, key=setup.amd_rank)["index"], 0)
328
329
330class WindowsDetection(unittest.TestCase):
331    def setUp(self):
332        self.win = setup.WIN
333        setup.WIN = True
334        p = mock.patch.object(setup, "ram_gb", return_value=96.0)
335        p.start()
336        self.addCleanup(p.stop)
337        self.addCleanup(lambda: setattr(setup, "WIN", self.win))
338
339    def adapters(self):
340        return ([{"name": "AMD Radeon(TM) 8060S Graphics", "pnp": r"PCI\VEN_1002&DEV_1586&SUBSYS_1C3E1D05&REV_C1\4&2",
341                  "ram": 4294967295}],
342                [{"DriverDesc": "AMD Radeon(TM) 8060S Graphics",
343                  "MatchingDeviceId": r"PCI\VEN_1002&DEV_1586&REV_C1", "HardwareInformation.qwMemorySize": 4 * GIB,
344                  "DriverVersion": "32.0.21013.1000"}])
345
346    def test_strix_halo(self):
347        ad, reg = self.adapters()
348        g = setup.amd_gpus_windows(ad, reg)
349        self.assertEqual(len(g), 1)
350        self.assertEqual((g[0]["arch"], g[0]["pci_id"]), ("gfx1151", 0x1586))
351        self.assertIsNone(setup.amd_problem(g[0]))
352        self.assertTrue(g[0]["uma"])
353        self.assertAlmostEqual(g[0]["dedicated_gb"], 4.0)                              # the registry's carve-out
354        self.assertAlmostEqual(g[0]["shared_gb"], 48.0)                                # Windows: half the RAM
355        self.assertAlmostEqual(g[0]["vram_gb"], 52.0)
356        self.assertEqual(g[0]["name"], "AMD Radeon(TM) 8060S Graphics")
357
358    def test_strix_halo_and_a_7900_xtx(self):
359        ad, reg = self.adapters()
360        ad.append({"name": "AMD Radeon RX 7900 XTX", "pnp": r"PCI\VEN_1002&DEV_744C&SUBSYS_1&REV_C8\4&3", "ram": 0})
361        reg.append({"DriverDesc": "AMD Radeon RX 7900 XTX", "MatchingDeviceId": r"PCI\VEN_1002&DEV_744C&REV_C8",
362                    "HardwareInformation.qwMemorySize": 24 * GIB, "DriverVersion": "32.0.21013.1000"})
363        g = setup.amd_gpus_windows(ad, reg)
364        self.assertEqual([x["arch"] for x in g], ["gfx1151", "gfx1100"])
365        self.assertTrue(g[0]["uma"] and not g[1].get("uma"))
366        self.assertEqual(min(g, key=setup.amd_rank)["arch"], "gfx1100")
367
368    def test_other_integrated_radeons(self):
369        for did, name, arch in ((0x150E, "AMD Radeon(TM) 890M Graphics", "gfx1150"),
370                                (0x1114, "AMD Radeon(TM) 860M Graphics", "gfx1152"),
371                                (0x15BF, "AMD Radeon(TM) 780M Graphics", "gfx1103")):
372            ad = [{"name": name, "pnp": rf"PCI\VEN_1002&DEV_{did:04X}&REV_C1\4&2", "ram": 512 << 20}]
373            g = setup.amd_gpus_windows(ad, [])[0]
374            self.assertEqual(g["arch"], arch)
375            self.assertFalse(g.get("uma"))
376            self.assertIsNotNone(setup.amd_problem(g))
377
378    def test_hip_listing_of_strix_halo(self):
379        """Once the HIP engine is installed the cards are numbered as HIP lists them; the carve-out still comes from the
380        registry, and an APU's HIP figure never lowers the GPU's memory."""
381        ad, reg = self.adapters()
382        text = "device 0: AMD Radeon(TM) 8060S Graphics\n  arch gfx1151, 64.0 GiB\ndevice 1: AMD Radeon RX 7900 XTX\n  arch gfx1100, 24.0 GiB\n"
383        hip = setup.hip_devices(text=text)
384        self.assertEqual([x["arch"] for x in hip], ["gfx1151", "gfx1100"])
385        with mock.patch.object(setup, "hip_devices", return_value=hip), \
386                mock.patch.object(setup, "amd_gpus_windows", return_value=setup.amd_gpus_windows(ad, reg)):
387            g = setup.amd_gpus_win()
388        self.assertTrue(g[0]["uma"])
389        self.assertAlmostEqual(g[0]["dedicated_gb"], 4.0)
390        self.assertGreaterEqual(g[0]["vram_gb"], 64.0)
391        self.assertFalse(g[1].get("uma"))
392        self.assertAlmostEqual(g[1]["vram_gb"], 24.0)
393
394
395class WindowsZip(unittest.TestCase):
396    """get_prebuilt_hip never installs a zip with no code for the card; for a Strix Halo it says why and what to do."""
397
398    def setUp(self):
399        self.tmp = tempfile.TemporaryDirectory()
400        self.addCleanup(self.tmp.cleanup)
401        self.root = Path(self.tmp.name)
402        self.warnings: list[str] = []
403        for p in (mock.patch.object(setup, "ROOT", self.root), mock.patch.object(setup, "warn", self.warnings.append),
404                  mock.patch.object(setup, "say", lambda *a, **k: None), mock.patch.object(setup, "ok", lambda *a, **k: None),
405                  mock.patch.object(setup, "download", self.fake_download),
406                  mock.patch.object(setup, "engine_digest", self.fake_digest),
407                  mock.patch.object(setup.netpolicy, "urlopen", lambda *a, **k: io.BytesIO(b"")),
408                  mock.patch.object(setup, "hip_runtime_beside_exe", lambda eng: None)):
409            p.start()
410            self.addCleanup(p.stop)
411        self.archs = ["gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1030"]      # the 0.1.39 zip
412
413    def fake_download(self, url, dest, label=""):
414        with zipfile.ZipFile(dest, "w") as z:
415            z.writestr("BUILD.json", json.dumps({"source": "prebuilt", "backend": "hip", "platform": "windows-x64",
416                                                  "version": ".".join(map(str, setup.MIN_ENGINE)), "archs": self.archs, "lib_dirs": []}))
417            z.writestr(setup.EXE, "x")
418
419
420    def fake_digest(self, asset, base):
421        """The size and SHA-256 of whatever the mocked download just wrote.
422
423        The engine archive is checked against a published digest before it is unpacked, so a test that
424        mocks the download has to say what the hash is or it never reaches the part it is about. This
425        hashes the real bytes the fake download produced, so the check still runs.
426        """
427        p = self.root / "engine" / asset
428        data = p.read_bytes() if p.exists() else b""
429        return len(data), hashlib.sha256(data).hexdigest()
430
431    def halo(self):
432        return {"index": 0, "name": setup.AMD_NAMES["gfx1151"], "vram_gb": 52.0, "arch": "gfx1151", "uma": True,
433                "dedicated_gb": 4.0, "shared_gb": 48.0, "vendor": "amd", "driver": "amd"}
434
435    def test_zip_without_gfx1151_is_refused_with_the_reason(self):
436        self.assertIsNone(setup.get_prebuilt_hip("https://example.invalid/", self.halo()))
437        self.assertEqual(len(self.warnings), 1)
438        msg = self.warnings[0]
439        self.assertIn("no gfx1151 code", msg)
440        self.assertIn("docs/STRIX_HALO.md", msg)
441        self.assertIn("build_windows.bat", msg)
442        self.assertFalse((self.root / "engine" / "strata-windows-x64-hip.zip").exists())   # dropped
443        self.assertFalse((self.root / "engine" / setup.EXE).exists())                      # nothing installed
444
445    def test_zip_with_gfx1151_is_installed(self):
446        self.archs = self.archs + ["gfx1151"]
447        eng = setup.get_prebuilt_hip("https://example.invalid/", self.halo())
448        self.assertEqual(eng, self.root / "engine")
449        self.assertEqual(self.warnings, [])
450        meta = json.loads((eng / "BUILD.json").read_text(encoding="utf-8"))
451        self.assertIn("gfx1151", meta["archs"])
452
453    def test_a_7900_xtx_still_takes_the_old_zip(self):
454        g = {"index": 0, "name": "x", "vram_gb": 24.0, "arch": "gfx1100", "vendor": "amd", "driver": "amd"}
455        self.assertIsNotNone(setup.get_prebuilt_hip("https://example.invalid/", g))
456
457    def test_windows_build_script_lists_gfx1151(self):
458        bat = (ROOT / "tools/hip/build_windows.bat").read_text(encoding="utf-8")
459        m = re.search(r'if not defined STRATA_HIP_ARCHS set "STRATA_HIP_ARCHS=([^"]+)"', bat)
460        self.assertIn("gfx1151", m.group(1).split(";"))
461        self.assertTrue({"gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201", "gfx1030"} <= set(m.group(1).split(";")))
462
463
464class Recommendation(unittest.TestCase):
465    def halo(self, carve=2.0):
466        return {"arch": "gfx1151", "uma": True, "dedicated_gb": carve, "shared_gb": 100.0, "vram_gb": carve + 100.0}
467
468    def test_ud_iq4_xs_with_enough_memory(self):
469        self.assertEqual((setup.STRIX_HALO_FAMILY, setup.STRIX_HALO_MODEL), ("unsloth", "UD-IQ4_XS"))
470        self.assertIn(setup.STRIX_HALO_MODEL, setup.MODELS)
471        self.assertIn(setup.STRIX_HALO_FAMILY, setup.FAMILIES)
472        self.assertTrue(setup.strix_halo_recommends(self.halo(), AURORA_RAM_GB))
473        self.assertTrue(setup.strix_halo_recommends(self.halo(), 128.0))
474        self.assertTrue(setup.strix_halo_recommends(self.halo(32.0), 60.0))             # 32 GB carve-out + 60 GB RAM
475        self.assertFalse(setup.strix_halo_recommends(self.halo(), 62.0))                # a 64 GB box: no recommendation
476        self.assertFalse(setup.strix_halo_recommends(self.halo(), 30.0))
477        self.assertFalse(setup.strix_halo_recommends({"arch": "gfx1100", "vram_gb": 24.0}, 256.0))
478        self.assertFalse(setup.strix_halo_recommends({"arch": "gfx1150", "vram_gb": 0.5}, 256.0))
479
480    def test_the_recommended_model_is_a_regular_choice_on_amd(self):
481        m = setup.MODELS[setup.STRIX_HALO_MODEL]
482        self.assertFalse(m.get("nvidia_only"))
483        self.assertFalse(m.get("experimental"))
484
485    def test_notes_are_recommendations(self):
486        win = setup.WIN
487        try:
488            setup.WIN = False
489            g = {**self.halo(), "shared_gb": 60.0, "vram_gb": 62.0}
490            notes = setup.strix_halo_notes(g, AURORA_RAM_GB)
491            joined = "\n".join(notes)
492            self.assertIn("docs/STRIX_HALO.md", joined)
493            self.assertIn("UD-IQ4_XS", joined)
494            self.assertTrue(any(n.startswith("!") and "ttm.pages_limit" in n for n in notes))   # a small GTT: a warning
495            self.assertIn("changes no host setting", joined)
496            big = {**self.halo(), "shared_gb": 112.0, "vram_gb": 114.0}
497            self.assertFalse(any(n.startswith("!") for n in setup.strix_halo_notes(big, AURORA_RAM_GB)))
498        finally:
499            setup.WIN = win
500
501    def test_hipblaslt_table_for_gfx1151(self):
502        t = setup.hipblaslt_table("gfx1151", [], 100401)
503        self.assertIsNotNone(t)
504        self.assertEqual(t.name, "gfx1151-hipblaslt-100401.txt")
505
506
507class LowRamUsesTheCarveOutOnly(unittest.TestCase):
508    def test_apu_memory_is_not_double_counted(self):
509        halo = {"arch": "gfx1151", "uma": True, "dedicated_gb": 2.0, "shared_gb": 112.0, "vram_gb": 114.0, "index": 0}
510        card = {"arch": "gfx1100", "vram_gb": 24.0, "index": 0}
511        self.assertEqual(setup.low_ram_vram(halo), 2.0)
512        self.assertEqual(setup.low_ram_vram(card), 24.0)
513        # a 32 GB-RAM Strix Halo: the smallest model is not "made to fit" by counting the GPU's shared memory as extra
514        self.assertFalse(setup.low_ram_fits("IQ1_M", 24.0, setup.low_ram_vram(halo)))
515        self.assertTrue(setup.low_ram_fits("IQ1_M", 24.0, 40.0))                            # a 40 GB dedicated card does
516
517
518class IgpuTextIsArchExact(unittest.TestCase):
519    """The owner's rule: setup never takes one AMD iGPU for another.  gfx1103 (Radeon 780M / 760M) gets its own text,
520    never the Strix Halo (gfx1151) lines; gfx1151 keeps its."""
521
522    def gpu(self, arch, name):
523        return {"arch": arch, "name": name, "uma": True, "dedicated_gb": 2.0, "shared_gb": 30.0, "vram_gb": 32.0}
524
525    def test_gfx1103_never_gets_strix_halo_text(self):
526        for win in (False, True):
527            with mock.patch.object(setup, "WIN", win):
528                text = chr(10).join(setup.igpu_notes(self.gpu("gfx1103", "AMD Radeon 780M Graphics"), 61.0))
529            self.assertIn("gfx1103", text)
530            self.assertIn("STRATA_EXPERIMENTAL_GFX1103=1", text)
531            self.assertIn("RADEON_780M.md", text)
532            for bad in ("gfx1151", "Ryzen AI Max", "STRIX_HALO", "Recommended model"):
533                self.assertNotIn(bad, text)
534            self.assertNotIn("Strix Halo (gfx1151", text)
535            self.assertNotIn("compiled here for gfx1151", text)
536
537    def test_gfx1151_keeps_strix_halo_text(self):
538        with mock.patch.object(setup, "WIN", False):
539            text = chr(10).join(setup.igpu_notes(self.gpu("gfx1151", "AMD Radeon 8060S"), 121.0))
540        self.assertIn("Strix Halo (gfx1151, Ryzen AI Max)", text)
541        self.assertIn("compiled here for gfx1151", text)
542        self.assertIn("docs/STRIX_HALO.md", text)
543        self.assertNotIn("gfx1103", text)
544
545    def test_other_chips_get_nothing(self):
546        for a in ("gfx1150", "gfx1152", "gfx1100", "gfx1201"):
547            self.assertEqual(setup.igpu_notes(self.gpu(a, "x"), 64.0), [])
548
549    def test_no_strix_halo_model_recommendation_for_gfx1103(self):
550        g = self.gpu("gfx1103", "AMD Radeon 780M Graphics")
551        self.assertFalse(setup.strix_halo_recommends(g, 128.0))
552        self.assertTrue(setup.strix_halo_recommends(self.gpu("gfx1151", "x"), 128.0))
553
554    def test_setup_prints_notes_through_the_exact_helper(self):
555        src = Path(setup.__file__).read_text(encoding="utf-8")
556        self.assertIn("igpu_notes(gpu, ram_gb())", src)
557        self.assertNotIn("strix_halo_notes(gpu, ram_gb())", src)
558
559
560if __name__ == "__main__":
561    unittest.main()