okami.mom/strata

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

Niko1221Merge f-clean-1c (3c32937a2): launcher speed settings become engine defaults (parallel stack, GDN stack, gfx12 chunked scan, HC_Q8 on UD files, Metal fp16 for resident IQ3_S/Q2_0, hipBLASLt table on gfx1151 only); row 8 held (cleanup step 1c)ddbfa1d5c

main
20.6 KiB389 linesraw
1"""The hipBLASLt tuning tables in the AMD engine packages: what a package holds per card family, and the one rule that decides at a start
2whether a table is used (strata_control/hipblaslt_tuning.py). Folders are throwaways; no GPU tool is run.
3
4The packages' hipBLASLt versions below are the ones the 0.2.x release packages bundle (docs/AMD_HIP.md, Ready-made packages): Windows ROCm
510.2.0a20260930 carries 1.5.0 (100500), the Linux 7.10.0a20251120 wheels 1.2.0 (100200), Linux Strix Halo's 7.14.1 1.4.1 (100401)."""
6from __future__ import annotations
7
8import contextlib
9import io
10import json
11import os
12import sys
13import tempfile
14import unittest
15from pathlib import Path
16from unittest import mock
17
18from strata_control import hipblaslt_tuning as ht
19
20ROOT = Path(__file__).resolve().parents[2]
21TABLES = ROOT / "tools" / "hip"
22sys.path.insert(0, str(ROOT / "packaging"))
23import package_engine  # noqa: E402
24import stage_tuning  # noqa: E402
25
26#: (platform, variant) -> (archs of the package, hipBLASLt version it bundles, architectures that must carry a table)
27PACKAGES = {
28    ("windows-x86_64", "rx9070"): (("gfx1200", "gfx1201"), 100500, {"gfx1201"}),
29    ("windows-x86_64", "rdna3"): (("gfx1100", "gfx1101", "gfx1102", "gfx1151"), 100500, {"gfx1100", "gfx1151"}),
30    ("linux-x86_64", "rx9070"): (("gfx1200", "gfx1201"), 100200, set()),                    # no table for 1.2.0 on RDNA4 (docs/AMD_HIP.md)
31    ("linux-x86_64", "rx7900"): (("gfx1100", "gfx1101", "gfx1102"), 100200, {"gfx1100"}),
32    ("linux-x86_64", "halo"): (("gfx1151",), 100401, {"gfx1151"}),
33    # 0.2.2 RX 6000 packages: hipBLASLt ships no gfx1030 / gfx1031 kernels at any version, so no table, plain hipBLAS
34    ("windows-x86_64", "rdna2"): (("gfx1030", "gfx1031"), 100500, set()),
35    ("linux-x86_64", "rx6000"): (("gfx1030", "gfx1031"), 100400, set()),
36}
37
38
39ON = {ht.SWITCH: "on"}            # the switch that uses a matching table whatever "auto" does
40AUTO = {}
41
42
43def fake_table(folder: Path, arch: str, version: int, *, header: str | None = None) -> Path:
44    folder.mkdir(parents=True, exist_ok=True)
45    path = folder / ht.table_name(arch, version)
46    path.write_text(f"# solution ids are scoped to this hipBLASLt version and device architecture\n"
47                    f"{header or f'{ht.HEADER} {arch} {version}'}\nbf16 128 2560 128 4096 73754\n", encoding="utf-8")
48    return path
49
50
51def fake_package(root: Path, *, version: int | None = 100500, tables=(("gfx1201", 100500),), build=True) -> Path:
52    folder = root / "0.2.1-pkg"
53    folder.mkdir(parents=True)
54    meta = {"version": "0.2.1", "backend": "hip"}
55    if version is not None:
56        meta["hipblaslt_version"] = version
57    if build:
58        (folder / "BUILD.json").write_text(json.dumps(meta), encoding="utf-8")
59    for arch, ver in tables:
60        fake_table(folder / ht.TABLE_DIR, arch, ver)
61    return folder
62
63
64class TempDir(unittest.TestCase):
65    def setUp(self):
66        self.dir = tempfile.TemporaryDirectory()
67        self.addCleanup(self.dir.cleanup)
68        self.root = Path(self.dir.name)
69
70
71class Decision(TempDir):
72    """Match, mismatch, switch, the person's own choice."""
73
74    def test_a_table_for_this_card_and_this_hipblaslt_is_used(self):
75        pkg = fake_package(self.root)
76        d = ht.resolve(pkg, ["gfx1201"], environ=ON)
77        self.assertEqual(d.path, pkg / "tuning" / "gfx1201-hipblaslt-100500.txt")
78        self.assertIn("gfx1201-hipblaslt-100500.txt", d.message)
79        self.assertIn(ht.SWITCH, d.message)               # the line tells how to turn it off
80        self.assertEqual(d.level, "info")
81
82    def test_a_table_for_another_hipblaslt_version_is_not_used_and_the_log_says_why(self):
83        pkg = fake_package(self.root, version=100200, tables=(("gfx1201", 100500),))
84        d = ht.resolve(pkg, ["gfx1201"], environ=ON)
85        self.assertIsNone(d.path)
86        self.assertEqual(d.level, "warn")
87        self.assertIn("100200", d.message)
88        self.assertIn("100500", d.message)
89        self.assertIn("plain hipBLAS", d.message)
90
91    def test_a_card_without_a_table_in_the_package_gets_plain_hipblas_and_one_line(self):
92        pkg = fake_package(self.root)
93        d = ht.resolve(pkg, ["gfx1200"], environ=ON)
94        self.assertIsNone(d.path)
95        self.assertIn("none for gfx1200", d.message)
96
97    def test_the_card_that_has_a_table_is_found_among_several(self):
98        pkg = fake_package(self.root, tables=(("gfx1100", 100500), ("gfx1151", 100500)))
99        self.assertEqual(ht.resolve(pkg, ["gfx1101", "gfx1151"], environ=ON).path.name, "gfx1151-hipblaslt-100500.txt")
100
101    def test_a_package_that_does_not_say_its_hipblaslt_is_not_guessed_at(self):
102        pkg = fake_package(self.root, version=None)
103        d = ht.resolve(pkg, ["gfx1201"], environ=ON)
104        self.assertIsNone(d.path)
105        self.assertEqual(d.level, "warn")
106        self.assertIn("hipblaslt_version", d.message)
107
108    def test_an_unreadable_card_is_a_note_not_a_guess(self):
109        d = ht.resolve(fake_package(self.root), [], environ=ON)
110        self.assertIsNone(d.path)
111        self.assertIn("could not be read", d.message)
112
113    def test_a_table_whose_header_disagrees_with_its_name_is_not_used(self):
114        pkg = fake_package(self.root, tables=())
115        fake_table(pkg / "tuning", "gfx1201", 100500, header=f"{ht.HEADER} gfx1201 100401")
116        d = ht.resolve(pkg, ["gfx1201"], environ=ON)
117        self.assertIsNone(d.path)
118        self.assertIn("header", d.message)
119
120    def test_the_switch_turns_it_off_in_the_environment_and_in_the_run_config(self):
121        pkg = fake_package(self.root)
122        for word in ("off", "OFF", "0", "no", "false", "none"):
123            d = ht.resolve(pkg, ["gfx1201"], environ={ht.SWITCH: word})
124            self.assertIsNone(d.path, word)
125            self.assertIn("off", d.message)
126        self.assertIsNone(ht.resolve(pkg, ["gfx1201"], environ=AUTO, cfg={"hipblaslt_table": False}).path)
127        self.assertIsNotNone(ht.resolve(pkg, ["gfx1201"], environ=AUTO, cfg={"hipblaslt_table": True}).path)
128        self.assertIsNone(ht.resolve(pkg, ["gfx1201"], environ={ht.SWITCH: "off"}, cfg={"hipblaslt_table": True}).path)   # the environment wins
129        for word in ("on", "ON", "1", "yes", "true"):
130            self.assertIsNotNone(ht.resolve(pkg, ["gfx1201"], environ={ht.SWITCH: word}).path, word)
131
132    def test_auto_follows_the_one_constant_and_says_what_is_available(self):
133        pkg = fake_package(self.root)
134        with mock.patch.object(ht, "AUTO_USES_TABLE", False):
135            d = ht.resolve(pkg, ["gfx1201"], environ=AUTO)
136            self.assertIsNone(d.path)
137            self.assertIn("gfx1201-hipblaslt-100500.txt", d.message)
138            self.assertIn(f"{ht.SWITCH}=on", d.message)
139            self.assertEqual(ht.mode(AUTO), "auto")
140        with mock.patch.object(ht, "AUTO_USES_TABLE", True):
141            d = ht.resolve(pkg, ["gfx1201"], environ=AUTO)
142            self.assertEqual(d.path, pkg / "tuning" / "gfx1201-hipblaslt-100500.txt")
143            self.assertIsNone(ht.resolve(pkg, ["gfx1201"], environ={ht.SWITCH: "off"}).path)
144
145    def test_the_default_is_the_owners_decision(self):
146        """A table changes the bits of the prompt's dense GEMMs (notes-021-hip.md); the owner chose: on by default for Strix Halo only."""
147        self.assertFalse(ht.AUTO_USES_TABLE)
148        self.assertEqual(ht.AUTO_ARCHS, ("gfx1151",))
149
150    def test_auto_uses_the_table_on_strix_halo_only(self):
151        for arch, used in (("gfx1151", True), ("gfx1201", False), ("gfx1100", False)):
152            root = self.root / arch
153            root.mkdir()
154            pkg = fake_package(root, tables=((arch, 100500),))
155            d = ht.resolve(pkg, [arch], environ=AUTO)
156            self.assertEqual(d.path is not None, used, (arch, d.message))
157            self.assertIsNone(ht.resolve(pkg, [arch], environ={ht.SWITCH: "off"}).path)
158
159    def test_a_table_the_person_set_is_never_replaced(self):
160        pkg = fake_package(self.root)
161        mine = str(self.root / "mine.txt")
162        for environ, cfg in (({ht.ENGINE_VAR: mine}, {}), ({}, {"env": {ht.ENGINE_VAR: mine}})):
163            d = ht.resolve(pkg, ["gfx1201"], environ=environ, cfg=cfg)
164            self.assertIsNone(d.path)
165            self.assertIn(mine, d.message)
166            out = ht.apply({"backend": "hip", **cfg}, pkg, ["gfx1201"], environ=environ, say=lambda line: None)
167            self.assertEqual((out.get("env") or {}).get(ht.ENGINE_VAR, mine), mine)
168
169
170class Apply(TempDir):
171    def test_apply_says_so_once_and_leaves_the_table_to_the_engine(self):
172        pkg = fake_package(self.root)
173        cfg = {"backend": "hip", "env": {"STRATA_RESIDENT_PIN": "0"}}
174        lines = []
175        out = ht.apply(cfg, pkg, ["gfx1201"], environ=ON, say=lines.append)
176        self.assertIs(out, cfg)                            # the engine finds tuning/ beside itself: no path in the config
177        self.assertNotIn(ht.ENGINE_VAR, out["env"])
178        self.assertEqual(len(lines), 1)
179        self.assertTrue(lines[0].startswith("[strata] hipBLASLt tuning table"))
180
181    def test_a_config_level_switch_reaches_the_engine_as_the_env_variable(self):
182        pkg = fake_package(self.root)
183        for value, word in ((False, "off"), (True, "on")):
184            cfg = {"backend": "hip", "hipblaslt_table": value, "env": {"STRATA_RESIDENT_PIN": "0"}}
185            out = ht.apply(cfg, pkg, ["gfx1201"], environ={}, say=lambda line: None)
186            self.assertEqual(out["env"][ht.SWITCH], word)
187            self.assertEqual(out["env"]["STRATA_RESIDENT_PIN"], "0")
188            self.assertNotIn(ht.SWITCH, cfg["env"])        # the caller's config is untouched
189        # the shell's own switch, or a table the person named, is not overridden
190        cfg = {"backend": "hip", "hipblaslt_table": False}
191        self.assertIs(ht.apply(cfg, pkg, ["gfx1201"], environ={ht.SWITCH: "on"}, say=lambda line: None), cfg)
192        self.assertIs(ht.apply(cfg, pkg, ["gfx1201"], environ={ht.ENGINE_VAR: "x.txt"}, say=lambda line: None), cfg)
193
194    def test_apply_with_a_mismatch_leaves_the_config_alone_and_warns(self):
195        pkg = fake_package(self.root, version=100200)
196        cfg = {"backend": "hip"}
197        lines = []
198        self.assertIs(ht.apply(cfg, pkg, ["gfx1201"], environ=ON, say=lines.append), cfg)
199        self.assertEqual(len(lines), 1)
200        self.assertIn("note", lines[0])
201
202    def test_other_backends_and_packages_without_tables_are_silent(self):
203        lines = []
204        pkg = fake_package(self.root)
205        cfg = {"backend": "cuda"}
206        self.assertIs(ht.apply(cfg, pkg, ["gfx1201"], environ=ON, say=lines.append), cfg)
207        bare = self.root / "cuda-pkg"
208        bare.mkdir()
209        (bare / "BUILD.json").write_text(json.dumps({"version": "0.2.1"}), encoding="utf-8")
210        out = ht.apply({"backend": "hip"}, bare, ["gfx1201"], environ=ON, say=lines.append)
211        self.assertNotIn("env", out)
212        self.assertEqual(lines, [])
213
214    def test_the_server_start_applies_it_for_a_component_engine(self):
215        from serve import server
216        pkg = fake_package(self.root)
217        (pkg / "strata").write_text("x", encoding="utf-8")
218        cfg = {"exe": "component:strata-engine", "backend": "hip"}
219        out = io.StringIO()
220        with mock.patch.object(server.engine_component, "expand", return_value=str(pkg / "strata")), \
221                mock.patch.object(ht, "present_archs", return_value=["gfx1201"]), \
222                mock.patch.dict(os.environ, {}, clear=False), contextlib.redirect_stdout(out):
223            os.environ.pop(ht.SWITCH, None)
224            os.environ.pop(ht.ENGINE_VAR, None)
225            self.assertNotIn(ht.ENGINE_VAR, server.child_env(server.with_component_engine(cfg)))     # "auto" is off by default
226            os.environ[ht.SWITCH] = "on"
227            started = server.with_component_engine(cfg)
228            env = server.child_env(started)
229            self.assertNotIn(ht.ENGINE_VAR, env)           # the engine finds the table beside itself; the shell's switch reaches it
230            self.assertEqual(env[ht.SWITCH], "on")
231            os.environ[ht.SWITCH] = "off"
232            self.assertNotIn(ht.ENGINE_VAR, server.child_env(server.with_component_engine(cfg)))
233        self.assertIn("hipBLASLt tuning table", out.getvalue())
234
235    def test_present_archs_picks_the_configured_card_on_linux(self):
236        with mock.patch("strata_control.engine_component.hip_archs_present", return_value=["gfx1100", "gfx1201"]):
237            if os.name != "nt":
238                self.assertEqual(ht.present_archs({"gpu": 1}), ["gfx1201"])
239                self.assertEqual(ht.present_archs({"gpu": [1, 0]}), ["gfx1201", "gfx1100"])
240            self.assertEqual(ht.present_archs({}), ["gfx1100", "gfx1201"])
241
242
243class PackageContents(TempDir):
244    """What each package of the release matrix carries, from the real tables of tools/hip."""
245
246    def test_every_release_package_carries_the_tables_its_cards_have(self):
247        for (platform, variant), (archs, version, wanted) in PACKAGES.items():
248            stage = self.root / f"{platform}-{variant}"
249            stage.mkdir()
250            copied = ht.stage_tables(stage, archs, version, TABLES)
251            self.assertEqual({n.split("-")[0] for n in copied}, wanted, (platform, variant))
252            on_disk = {p.name for p in (stage / "tuning").glob("*.txt")} if (stage / "tuning").is_dir() else set()
253            self.assertEqual(on_disk, set(copied), (platform, variant))
254            for arch in wanted:                           # the file the engine start will pick is there and its own header agrees
255                self.assertTrue(ht.header_ok(stage / "tuning" / ht.table_name(arch, version), arch, version), (platform, arch))
256
257    def test_the_missing_report_names_the_architectures_without_a_table(self):
258        left = ht.missing_report(("gfx1100", "gfx1101", "gfx1102"), 100200, TABLES)
259        self.assertEqual(sorted(left), ["gfx1101", "gfx1102"])
260        self.assertEqual(ht.missing_report(("gfx1201",), 100200, TABLES), {"gfx1201": [100202, 100500]})
261
262    def test_every_table_in_the_repo_has_a_header_that_matches_its_name(self):
263        tables = ht.tables_in(TABLES)
264        self.assertGreater(len(tables), 8)
265        for (arch, version), path in tables.items():
266            self.assertTrue(ht.header_ok(path, arch, version), path.name)
267
268    def test_version_from_header_reads_the_rocm_tree(self):
269        inc = self.root / "include" / "hipblaslt"
270        inc.mkdir(parents=True)
271        (inc / "hipblaslt-version.h").write_text("#define HIPBLASLT_VERSION_MAJOR 1\n#define HIPBLASLT_VERSION_MINOR 5\n"
272                                                 "#define HIPBLASLT_VERSION_PATCH 0\n", encoding="utf-8")
273        self.assertEqual(ht.version_from_header(self.root), 100500)
274        self.assertIsNone(ht.version_from_header(self.root / "nowhere"))
275
276    def test_stage_tuning_writes_the_version_and_the_tables(self):
277        stage = self.root / "stage"
278        stage.mkdir()
279        (stage / "BUILD.json").write_text(json.dumps({"version": "0.2.1", "archs": ["gfx1151"]}), encoding="utf-8")
280        with contextlib.redirect_stdout(io.StringIO()):
281            self.assertEqual(stage_tuning.main(["--stage", str(stage), "--archs", "gfx1151", "--version", "100401"]), 0)
282        meta = json.loads((stage / "BUILD.json").read_text(encoding="utf-8"))
283        self.assertEqual(meta["hipblaslt_version"], 100401)
284        self.assertEqual(meta["archs"], ["gfx1151"])      # what was there stays
285        self.assertTrue((stage / "tuning" / "gfx1151-hipblaslt-100401.txt").is_file())
286
287    def test_stage_tuning_can_demand_a_table(self):
288        stage = self.root / "stage"
289        stage.mkdir()
290        with contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit) as caught:
291            stage_tuning.main(["--stage", str(stage), "--archs", "gfx1201", "--version", "100200", "--expect", "gfx1201"])
292        self.assertIn("gfx1201", str(caught.exception))
293
294    def test_stage_tuning_refuses_a_rocm_whose_version_it_cannot_read(self):
295        stage = self.root / "stage"
296        stage.mkdir()
297        with self.assertRaises(SystemExit):
298            stage_tuning.main(["--stage", str(stage), "--archs", "gfx1201", "--rocm", str(self.root / "no-rocm")])
299
300
301class PackagedAndHashed(TempDir):
302    """packaging/package_engine.py: the tables are files of the package (hashed, so signed with it) and a bad AMD stage is refused."""
303
304    def stage(self, **kw):
305        src = self.root / "src"
306        src.mkdir()
307        (src / "strata").write_bytes(b"engine" * 100)
308        (src / "libamdhip64.so.7").write_bytes(b"hip" * 100)
309        (src / "BUILD.json").write_text(json.dumps({"version": "0.2.1", **kw}), encoding="utf-8")
310        return src
311
312    def build(self, src, archs=("gfx1201",), tree=False):
313        out = self.root / "out"
314        out.mkdir(exist_ok=True)
315        with mock.patch.object(package_engine, "_bundle_missing_libraries", return_value=[]):
316            return package_engine.build(src, "hip", "0.2.1", "linux-x86_64", out, entry="strata", archs=archs, build_id="t", tree=tree,
317                                        variant="rx9070")
318
319    def test_the_tables_are_listed_and_hashed_in_the_manifest_even_without_tree(self):
320        src = self.stage(hipblaslt_version=100500)
321        fake_table(src / "tuning", "gfx1201", 100500)
322        folder = self.build(src)
323        listed = {f["path"]: f for f in json.loads((folder / "engine-component.json").read_text(encoding="utf-8"))["files"]}
324        self.assertIn("tuning/gfx1201-hipblaslt-100500.txt", listed)
325        self.assertEqual(len(listed["tuning/gfx1201-hipblaslt-100500.txt"]["sha256"]), 64)
326        (folder / "tuning" / "gfx1201-hipblaslt-100500.txt").write_text("changed", encoding="utf-8")   # a swapped table fails the start's hash check
327        from strata_control import engine_component as ec
328        with self.assertRaises(ec.ComponentProblem):
329            ec.verify(ec.read_manifest(folder), full=True)
330
331    def test_an_amd_stage_without_a_hipblaslt_version_is_refused(self):
332        src = self.stage()
333        with self.assertRaises(SystemExit) as caught:
334            self.build(src)
335        self.assertIn("hipblaslt_version", str(caught.exception))
336
337    def test_a_table_for_another_version_or_card_than_the_package_is_refused(self):
338        src = self.stage(hipblaslt_version=100500)
339        fake_table(src / "tuning", "gfx1201", 100202)
340        with self.assertRaises(SystemExit) as caught:
341            self.build(src)
342        self.assertIn("100202", str(caught.exception))
343        other = self.root / "other"
344        other.mkdir()
345        src2 = other / "src"
346        src2.mkdir()
347        (src2 / "strata").write_bytes(b"e")
348        (src2 / "BUILD.json").write_text(json.dumps({"hipblaslt_version": 100500}), encoding="utf-8")
349        fake_table(src2 / "tuning", "gfx1100", 100500)
350        with mock.patch.object(package_engine, "_bundle_missing_libraries", return_value=[]), self.assertRaises(SystemExit) as caught:
351            package_engine.build(src2, "hip", "0.2.1", "linux-x86_64", other / "out", entry="strata", archs=("gfx1201",), build_id="t")
352        self.assertIn("gfx1100", str(caught.exception))
353
354    def test_a_cuda_package_needs_no_hipblaslt_version(self):
355        src = self.stage()
356        out = self.root / "out"
357        out.mkdir()
358        with mock.patch.object(package_engine, "_bundle_missing_libraries", return_value=[]):
359            package_engine.build(src, "cuda", "0.2.1", "linux-x86_64", out, entry="strata", archs=("sm_86",), build_id="t")
360
361
362class SetupFindsThePackageTable(TempDir):
363    """setup.py outside the app (a git checkout, or the old Windows zip that START-HERE unpacks): the engine folder's own tuning/ comes first."""
364
365    def load_setup(self):
366        import importlib.util
367        spec = importlib.util.spec_from_file_location("setup_hipblaslt_copy", ROOT / "setup.py")
368        module = importlib.util.module_from_spec(spec)
369        spec.loader.exec_module(module)
370        return module
371
372    def test_the_engine_folders_table_wins_over_tools_hip_and_the_switch_turns_it_off(self):
373        setup = self.load_setup()
374        pkg = self.root / "engine"
375        fake_table(pkg / "tuning", "gfx1201", 100500)
376        seen = []
377        with mock.patch.object(setup, "ok", seen.append), mock.patch.object(setup, "say", seen.append), \
378                mock.patch.object(setup, "warn", seen.append), mock.patch.dict(os.environ, {}, clear=False):
379            os.environ.pop(ht.SWITCH, None)
380            self.assertEqual(setup.hipblaslt_table("gfx1201", [], 100500, [pkg / "tuning"]), pkg / "tuning" / "gfx1201-hipblaslt-100500.txt")
381            self.assertEqual(setup.hipblaslt_table("gfx1201", [], 100500), TABLES / "gfx1201-hipblaslt-100500.txt")
382            self.assertIsNone(setup.hipblaslt_table("gfx1201", [], 100200, [pkg / "tuning"]))      # no table for 1.2.0: warned, plain
383            os.environ[ht.SWITCH] = "off"
384            self.assertIsNone(setup.hipblaslt_table("gfx1201", [], 100500, [pkg / "tuning"]))
385        self.assertTrue(any("no hipBLASLt tuning table" in str(line) for line in seen))
386
387
388if __name__ == "__main__":
389    unittest.main()