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
7.9 KiB157 linesraw
1"""ROCm 7 and newer ship `amd-smi` and no `rocm-smi`, and the amdgpu driver's `product_name` is empty on gfx1201, so a
2report from a Radeon wrote the vendor as the card ("AMD Radeon", `...-standard-unknown-...`) and `runtime: not
3measured`. The strings below are the real output of `amd-smi static --asic --json`, `static --driver --json`,
4`list --json` and `-h` on one AI PRO R9700 (gfx1201) with ROCm 10.1, trimmed to the fields the probe reads."""
5from __future__ import annotations
6
7import json
8import os
9import tempfile
10import unittest
11from unittest import mock
12
13from strata_cli import bench_facts as bf
14
15ASIC = {"gpu_data": [{"gpu": 0, "asic": {"market_name": "AMD Radeon AI PRO R9700", "target_graphics_version": "gfx1201"}},
16                     {"gpu": 1, "asic": {"market_name": "AMD Radeon Graphics", "target_graphics_version": "gfx1036"}}]}
17DRIVER = {"gpu_data": [{"gpu": 0, "driver": {"name": "amdgpu", "version": "N/A",
18                                             "os_kernel_version": "7.3.0-rc6-2-cachyos-rc"}}]}
19LIST = [{"gpu": 0, "bdf": "0000:03:00.0", "node_id": 1}, {"gpu": 1, "bdf": "0000:7c:00.0", "node_id": 2}]
20HELP = "AMD System Management Interface | Version: 27.1.0+7da43026 | ROCm version: 10.1.0 |"
21BDF_TO_TOTAL = {"0000:03:00.0": "34208743424", "0000:7c:00.0": "805306368"}
22
23
24def run_cmd(cmd: list[str], timeout: float = 15) -> str:
25    """ROCm 10.1 answers, with `rocm-smi` missing entirely."""
26    if cmd[:1] == ["rocm-smi"]:
27        return ""
28    if cmd[:3] == ["amd-smi", "list", "--json"]:
29        return json.dumps(LIST)
30    if cmd[:2] == ["amd-smi", "static"]:
31        return json.dumps(DRIVER if "--driver" in cmd else ASIC)
32    if cmd == ["amd-smi", "-h"]:
33        return HELP
34    return ""
35
36
37@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch")
38class AmdSmiProbe(unittest.TestCase):
39    def setUp(self):
40        self.tmp = tempfile.TemporaryDirectory()
41        self.addCleanup(self.tmp.cleanup)
42        # /sys/class/drm/cardN/device is a symlink whose target's last component is the PCI address; the probe matches
43        # that address against `amd-smi list`, so the fake tree repeats the shape instead of the path
44        devices = []
45        for card, bdf in (("card1", "0000:03:00.0"), ("card2", "0000:7c:00.0")):
46            pci = os.path.join(self.tmp.name, "pci", bdf)
47            os.makedirs(pci)
48            with open(os.path.join(pci, "mem_info_vram_total"), "w", encoding="utf-8") as f:
49                f.write(BDF_TO_TOTAL[bdf] + "\n")
50            link = os.path.join(self.tmp.name, "drm", card, "device")
51            os.makedirs(os.path.dirname(link))
52            os.symlink(pci, link)
53            devices.append(link)
54        self.globs = mock.patch.object(bf.glob, "glob", lambda pattern: devices)
55        self.globs.start()
56        self.addCleanup(self.globs.stop)
57        self.cmds = mock.patch.object(bf, "run_cmd", run_cmd)
58        self.cmds.start()
59        self.addCleanup(self.cmds.stop)
60
61    def test_names_both_cards_with_their_vram(self):
62        cards, driver = bf.other_gpus()
63        self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700", "AMD Radeon Graphics"])
64        self.assertEqual([c["memory_bytes"] for c in cards], [34208743424, 805306368])
65        self.assertEqual([c["device_index"] for c in cards], [0, 1])
66
67    def test_a_stub_driver_version_stays_unmeasured(self):
68        # `amd-smi static --driver` says N/A when amdgpu is built into the kernel: that is not a version, so the report
69        # must keep saying it did not measure one instead of writing "N/A"
70        _, driver = bf.other_gpus()
71        self.assertIsNone(driver)
72
73    def test_an_asic_without_a_market_name_is_skipped(self):
74        blank = {"gpu_data": [{"gpu": 0, "asic": {"market_name": ""}},
75                              {"gpu": 1, "asic": {"market_name": "AMD Radeon AI PRO R9700"}}]}
76        with mock.patch.object(bf, "run_cmd", lambda cmd, timeout=15: json.dumps(blank) if "static" in cmd else ""):
77            cards, _ = bf.other_gpus()
78        self.assertEqual([c["name"] for c in cards], ["AMD Radeon AI PRO R9700"])
79
80    def test_rocm_version_comes_from_the_install(self):
81        base = os.path.join(self.tmp.name, "rocm")
82        os.makedirs(os.path.join(base, "core", ".info"))
83        with open(os.path.join(base, "core", ".info", "version"), "w", encoding="utf-8") as f:
84            f.write("10.1.0\n")
85        with mock.patch.object(bf.os, "environ", {"ROCM_PATH": base}):
86            self.assertEqual(bf.rocm_version(), "10.1.0")
87
88    def test_rocm_version_falls_back_to_the_help_text(self):
89        real_open = open
90
91        def refuse(path, *args, **kwargs):
92            if "/opt/rocm" in str(path):
93                raise OSError("no ROCm install here")
94            return real_open(path, *args, **kwargs)
95
96        env = {k: v for k, v in os.environ.items() if k != "ROCM_PATH"}
97        with mock.patch.object(bf.os, "environ", env), mock.patch("builtins.open", side_effect=refuse):
98            self.assertEqual(bf.rocm_version(), "10.1.0")
99
100
101@unittest.skipIf(os.name == "nt", "the probe is the non-Windows branch")
102class ServedName(unittest.TestCase):
103    """The server's `gpu` string is the driver's product_name, empty on gfx1201, so it degrades to the vendor. That
104    must not overwrite the card the local probe named, while a card only the server can see still wins."""
105
106    def cards(self):
107        return [{"device_index": 0, "name": "AMD Radeon AI PRO R9700", "memory_bytes": 34208743424,
108                 "memory_kind": "dedicated", "power_limit_w": None}]
109
110    def hardware(self, served_gpu):
111        with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \
112             mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)):
113            block, machine = bf.hardware(bf.Why(), selected=[], served_gpu=served_gpu, model_dir=None,
114                                         declared_background=[])
115        return block, machine
116
117    def test_a_vendor_only_name_does_not_replace_the_card(self):
118        block, machine = self.hardware("AMD Radeon")
119        self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon AI PRO R9700"])
120        self.assertEqual(block["gpus"][0]["memory_bytes"], 34208743424)
121
122    def test_a_card_only_the_server_lists_still_wins(self):
123        block, _ = self.hardware("AMD Radeon RX 7900 XTX")
124        self.assertEqual([c["name"] for c in block["gpus"]], ["AMD Radeon RX 7900 XTX"])
125        self.assertIsNone(block["gpus"][0]["memory_bytes"])
126
127    def test_the_rocm_runtime_reaches_the_report(self):
128        why = bf.Why()
129        with mock.patch.object(bf, "nvidia_gpus", lambda: ([], None, None)), \
130             mock.patch.object(bf, "other_gpus", lambda: (self.cards(), None)), \
131             mock.patch.object(bf, "rocm_version", lambda: "10.1.0"):
132            _, machine = bf.hardware(why, selected=[], served_gpu="AMD Radeon", model_dir=None,
133                                     declared_background=[])
134            software = bf.software(why, dict(machine), engine_version="0.1.46.2", build_options=None)
135        self.assertEqual(machine["rocm"], "10.1.0")
136        self.assertIn({"name": "rocm", "version": "10.1.0"}, software["runtime"])
137
138
139class MacStillReadsItsChip(unittest.TestCase):
140    """The amd-smi branch is for Linux; a Mac (os.name is posix there too) still takes its card from the chip name."""
141
142    def test_a_mac_is_not_sent_down_the_amd_smi_branch(self):
143        calls = []
144
145        def run(cmd, timeout=15):
146            calls.append(cmd[0])
147            return ""
148
149        with mock.patch.object(bf.os, "name", "posix"), mock.patch.object(bf.sys, "platform", "darwin"),                 mock.patch.object(bf, "run_cmd", run), mock.patch.object(bf, "cpu_name", lambda: "Apple M5 Max"),                 mock.patch.object(bf, "ram_bytes", lambda: 137438953472):
150            cards, driver = bf.other_gpus()
151        self.assertEqual([c["name"] for c in cards], ["Apple M5 Max"])
152        self.assertEqual(cards[0]["memory_kind"], "shared")
153        self.assertNotIn("amd-smi", calls)
154
155
156if __name__ == "__main__":
157    unittest.main()