okami.mom/strata

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

Niko1221Tests: the terminal suites know a linux-aarch64 host (fixture Terminal named for the host; HIP-only tests skip where there is no HIP engine); pins and locks tests list the new targetb0e897b41

main
7.6 KiB152 linesraw
1"""Things a user of the Terminal archive (no setup.py, no tools/calibrate.py, an engine package) hit on real boxes."""
2
3from __future__ import annotations
4
5import json
6import os
7import stat
8import sys
9import tempfile
10import unittest
11from pathlib import Path
12from unittest import mock
13
14ROOT = Path(__file__).resolve().parents[2]
15sys.path.insert(0, str(ROOT))
16
17from strata_control import calibration, tune_apply, tuning  # noqa: E402
18from strata_control.profiles import ProfileError  # noqa: E402
19from strata_control.targets import host_platform  # noqa: E402
20
21
22class BooleanFlags(unittest.TestCase):
23    def test_a_boolean_flag_is_on_or_absent_never_given_a_value(self):
24        self.assertEqual(tuning.flag_argv("--kv-grow", "1"), ["--kv-grow"])
25        self.assertEqual(tuning.flag_argv("--kv-grow", "0"), [])
26        self.assertEqual(tuning.flag_argv("--kv-grow", True), ["--kv-grow"])
27        self.assertEqual(tuning.flag_argv("--kv-grow", False), [])
28        self.assertEqual(tuning.flag_argv("--spec-min-p", "0.5"), ["--spec-min-p", "0.5"])
29        self.assertEqual(tuning.flag_argv("--spec", "1"), ["--spec", "1"])      # a numeric flag keeps its 1
30
31    def test_a_candidate_with_kv_grow_off_does_not_become_kv_grow_0(self):
32        self.assertEqual(tune_apply.args_to_argv({"--kv-grow": "0", "--kv": "int8"}), ["--kv", "int8"])
33        self.assertEqual(tune_apply.args_to_argv({"--kv-grow": "1"}), ["--kv-grow"])
34
35    def test_the_harness_argv_follows_the_same_rule(self):
36        from strata_control import tune_engine
37        harness = tune_engine.EngineHarness(Path("engine"), {"--kv-grow": "0", "--pool-workers": "0", "--host-core": "first"})
38        argv = harness._argv()
39        self.assertNotIn("--kv-grow", argv)
40        self.assertIn("--pool-workers", argv)
41        self.assertEqual(argv[argv.index("--pool-workers") + 1], "0")
42
43
44class EnginePackageEnv(unittest.TestCase):
45    def test_a_package_folder_goes_first_on_the_library_path(self):
46        with tempfile.TemporaryDirectory() as d:
47            folder = Path(d)
48            (folder / "engine-component.json").write_text("{}", encoding="utf-8")
49            (folder / "strata").write_text("x", encoding="utf-8")
50            with mock.patch.dict(os.environ, {"LD_LIBRARY_PATH": "/old", "PATH": "/old"}):
51                env = tuning.engine_env(folder / "strata")
52            var = "PATH" if os.name == "nt" else "LD_LIBRARY_PATH"
53            self.assertTrue(env[var].startswith(str(folder.resolve())))
54            self.assertTrue(env[var].endswith("/old") or env[var].endswith("old"))
55
56    def test_a_plain_engine_keeps_the_callers_environment(self):
57        with tempfile.TemporaryDirectory() as d:
58            (Path(d) / "strata").write_text("x", encoding="utf-8")
59            self.assertIsNone(tuning.engine_env(Path(d) / "strata"))
60
61
62class CalibrateWithoutAFullFolder(unittest.TestCase):
63    def test_missing_setup_is_a_refusal_in_words_not_a_traceback(self):
64        with mock.patch.dict(os.environ, {}, clear=False):
65            os.environ.pop("STRATA_INSTALL_DIR", None)
66            with mock.patch("importlib.import_module", side_effect=ImportError("no module")):
67                with self.assertRaises(ProfileError) as ctx:
68                    calibration._full_folder("tools.calibrate")
69        self.assertEqual(ctx.exception.code if hasattr(ctx.exception, "code") else 5, 5)
70        self.assertIn("STRATA_INSTALL_DIR", str(ctx.exception))
71        self.assertIn("tune run --mode api", str(ctx.exception))
72
73    def test_tool_availability_is_reported_for_the_plan(self):
74        with mock.patch.dict(os.environ, {}, clear=False):
75            os.environ.pop("STRATA_INSTALL_DIR", None)
76            with mock.patch("importlib.util.find_spec", return_value=None):
77                self.assertFalse(calibration._tools_available())
78            with tempfile.TemporaryDirectory() as d:
79                (Path(d) / "tools").mkdir()
80                (Path(d) / "setup.py").write_text("", encoding="utf-8")
81                (Path(d) / "tools" / "calibrate.py").write_text("", encoding="utf-8")
82                os.environ["STRATA_INSTALL_DIR"] = d
83                with mock.patch("importlib.util.find_spec", return_value=None):
84                    self.assertTrue(calibration._tools_available())
85
86
87@unittest.skipIf(host_platform() == "linux-aarch64", "there is no HIP engine for arm64 Linux (BACKEND_MATRIX)")
88class HipPackageForAnotherCard(unittest.TestCase):
89    """A HIP package built for gfx1200/gfx1201 must not be chosen for a Phoenix iGPU (gfx1103): P2006 resolved it as usable."""
90
91    def _kfd(self, root: Path, versions):
92        for number, value in enumerate(versions):
93            node = root / str(number)
94            node.mkdir()
95            (node / "properties").write_text("cpu_cores_count 1\ngfx_target_version " + value + "\n", encoding="utf-8")
96
97    def test_gfx_target_version_becomes_the_gfx_name(self):
98        from strata_control import engine_component as ec
99        with tempfile.TemporaryDirectory() as d:
100            self._kfd(Path(d), ["0", "110003", "120001", "90010", "100300"])
101            self.assertEqual(ec.hip_archs_present(d), ["gfx1103", "gfx1201", "gfx90a", "gfx1030"])
102        self.assertEqual(ec.hip_archs_present("/nonexistent/kfd"), [])
103
104    def test_a_package_without_the_cards_arch_is_not_chosen_and_one_with_it_is(self):
105        from strata_control import engine_component as ec
106        from tests.terminal.test_engine_component import make_package, rewrite
107        with tempfile.TemporaryDirectory() as d:
108            root = Path(d)
109            folder = make_package(root, backend="hip")
110            rewrite(folder, schema_version=2, archs=["gfx1200", "gfx1201"], build_id="test")
111            with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1103"]):
112                with self.assertRaises(ec.EngineMissing) as ctx:
113                    ec.resolve(root, backend="hip")
114            self.assertIn("gfx1103", str(ctx.exception))
115            self.assertIn("gfx1201", str(ctx.exception))
116            with mock.patch.object(ec, "hip_archs_present", return_value=["gfx1201"]):
117                self.assertEqual(ec.resolve(root, backend="hip").backend, "hip")
118            with mock.patch.object(ec, "hip_archs_present", return_value=[]):      # cannot tell: not a refusal
119                self.assertEqual(ec.resolve(root, backend="hip").backend, "hip")
120
121
122class DeviceAccess(unittest.TestCase):
123    def test_a_render_node_the_user_cannot_open_is_named(self):
124        from strata_control import doctor
125        if not sys.platform.startswith("linux"):
126            self.skipTest("Linux device nodes")
127        with tempfile.TemporaryDirectory() as d:
128            (Path(d) / "dri").mkdir()
129            node = Path(d) / "dri" / "renderD128"
130            node.write_text("", encoding="utf-8")
131            os.chmod(node, 0)
132            if os.access(node, os.R_OK):
133                self.skipTest("running as a user that can open anything")
134            issue = doctor._device_access_issue("sycl", d)
135            self.assertEqual(issue["code"], "GPU_DEVICE_ACCESS")
136            self.assertIn("render", issue["message"])
137            os.chmod(node, 0o666)
138            self.assertIsNone(doctor._device_access_issue("sycl", d))
139            self.assertIsNone(doctor._device_access_issue("cuda", d))
140            self.assertIsNone(doctor._device_access_issue("hip", tempfile.gettempdir() + "/none"))
141
142
143class ArchiveContents(unittest.TestCase):
144    def test_the_fingerprint_table_models_import_reads_is_in_the_payload(self):
145        sys.path.insert(0, str(ROOT / "packaging"))
146        import package_terminal
147        self.assertIn("data/gguf_fingerprints.json", package_terminal.PAYLOAD)
148        self.assertTrue((ROOT / "data" / "gguf_fingerprints.json").is_file())
149
150
151if __name__ == "__main__":
152    unittest.main()