okami.mom/strata

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

Niko1221Merge f-023-fix3: drafting network code loads only when used, rollback tests wait for the restored start, Arc B-series runs with pictures on164dd3bbe

main
17.3 KiB321 linesraw
1"""Tests for setup.py --backend sycl, the experimental Intel Arc engine (sycl/, PR #423): it warns, stops with a clear
2message on Windows, and on Linux hands the run to sycl/setup_intel.py without its --backend flag. The CUDA / HIP
3paths never see it. No GPU, no network.
4
5    python -m unittest tools.test_setup_sycl
6"""
7from __future__ import annotations
8
9import contextlib
10import io
11import re
12import sys
13import tempfile
14import unittest
15from pathlib import Path
16from unittest import mock
17
18ROOT = Path(__file__).resolve().parents[1]
19sys.path.insert(0, str(ROOT))
20import setup  # noqa: E402
21
22
23def run(argv, win):
24    out = io.StringIO()
25    with mock.patch.object(setup, "WIN", win), mock.patch.object(setup.subprocess, "call", return_value=0) as call, \
26            contextlib.redirect_stdout(out):
27        try:
28            rc = setup.sycl_setup(argv)
29        except SystemExit as e:
30            rc = ("exit", e.code)
31    return rc, out.getvalue(), call
32
33
34class SyclBackend(unittest.TestCase):
35    def test_windows_stops_with_the_docs_pointer(self):
36        rc, out, call = run(["--backend", "sycl"], win=True)
37        self.assertEqual(rc, ("exit", 1))
38        self.assertIn("supported since 0.1.40.2", out)
39        self.assertIn("docs/INTEL_ARC.md", out)
40        call.assert_not_called()
41
42    def test_linux_hands_over_to_setup_intel_without_the_backend_flag(self):
43        rc, out, call = run(["--model", "IQ2_XS", "--backend", "sycl", "--port", "8085"], win=False)
44        self.assertEqual(rc, 0)
45        self.assertIn("supported since 0.1.40.2", out)
46        self.assertIn("built from source", out)
47        cmd = call.call_args[0][0]
48        self.assertTrue(cmd[1].endswith(str(Path("sycl") / "setup_intel.py")))
49        self.assertEqual(cmd[2:], ["--model", "IQ2_XS", "--port", "8085"])
50
51    def test_backend_equals_form_is_dropped_too(self):
52        _, _, call = run(["--backend=sycl", "--check"], win=False)
53        self.assertEqual(call.call_args[0][0][2:], ["--check"])
54
55    def test_the_parser_accepts_sycl(self):
56        src = (ROOT / "setup.py").read_text(encoding="utf-8")
57        self.assertRegex(src, r'"--backend", choices=\["cuda", "hip", "sycl"\]')
58
59    def test_setup_intel_finds_the_setup_functions_it_replaces(self):
60        """sycl/setup_intel.py swaps these steps; setup.py must still have them (it stops with a message otherwise)."""
61        src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8")
62        names = re.search(r'for name in \(([^)]*)\):', src).group(1)
63        for name in re.findall(r'"(\w+)"', names):
64            self.assertTrue(callable(getattr(setup, name, None)), name)
65
66    def test_setup_intel_replacements_take_every_argument_of_the_function_they_replace(self):
67        """#870: setup.py grew write_run_script's fourth argument and the port's replacement still took three, so
68        setup died with a TypeError after the download.  Every `S.<name> = <replacement>` in setup_intel.py must accept
69        all the parameters of setup.<name> (or take *args / **kwargs)."""
70        import ast
71        import inspect
72        tree = ast.parse((ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8"))
73        defs = {n.name: n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef)}
74        checked = 0
75        for n in ast.walk(tree):
76            if not (isinstance(n, ast.Assign) and len(n.targets) == 1 and isinstance(n.targets[0], ast.Attribute)
77                    and isinstance(n.targets[0].value, ast.Name) and n.targets[0].value.id == "S"):
78                continue
79            name = n.targets[0].attr
80            fn = n.value if isinstance(n.value, ast.Lambda) else defs.get(getattr(n.value, "id", ""))
81            orig = getattr(setup, name, None)
82            if fn is None or not callable(orig):
83                continue
84            a = fn.args
85            if a.vararg is not None and a.kwarg is not None:
86                checked += 1
87                continue
88            have = {x.arg for x in a.posonlyargs + a.args + a.kwonlyargs}
89            for param in inspect.signature(orig).parameters.values():
90                if param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
91                    continue
92                self.assertIn(param.name, have, f"setup_intel's {name} lacks setup.{name}'s `{param.name}`")
93            checked += 1
94        self.assertGreaterEqual(checked, 8)
95
96    def test_arc_pro_b60_is_known_under_both_pci_ids(self):
97        src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8")
98        self.assertIn('"e211": ("Arc Pro B60", 24.0)', src)
99        self.assertIn('"e221": ("Arc Pro B60", 24.0)', src)
100
101
102class CMakeOption(unittest.TestCase):
103    def test_sycl_is_off_by_default_and_exclusive(self):
104        src = (ROOT / "CMakeLists.txt").read_text(encoding="utf-8-sig")
105        self.assertIn('option(STRATA_ENABLE_SYCL "EXPERIMENTAL', src)
106        self.assertRegex(src, r'option\(STRATA_ENABLE_SYCL "[^"]*" OFF\)')
107        self.assertIn("add_subdirectory(sycl)", src)
108
109
110class SyclVersion(unittest.TestCase):
111    def setUp(self):
112        from sycl import setup_intel
113        self.mod = setup_intel
114
115    def test_version_matches_the_source_and_satisfies_native_models(self):
116        version = self.mod.sycl_version()
117        self.assertNotEqual(version, "0")
118        self.assertEqual(version, setup.source_version())
119        numbers = tuple(int(x) for x in version.split("."))
120        for model in ("UD-IQ4_XS", "UD-Q4_K_XL"):
121            with self.subTest(model=model):
122                self.assertGreaterEqual(numbers, setup.MODELS[model].get("engine", setup.UNSLOTH_ENGINE))
123
124    def test_version_follows_a_source_hotfix_with_a_variable_sycl_project(self):
125        with tempfile.TemporaryDirectory() as d:
126            root = Path(d)
127            (root / "CMakeLists.txt").write_text("project(strata VERSION 0.1.41.2 LANGUAGES CXX)\n", encoding="utf-8")
128            (root / "sycl").mkdir()
129            (root / "sycl" / "CMakeLists.txt").write_text(
130                "set(STRATA_SYCL_VERSION 0.1.40.2)\n"
131                "project(strata_sycl VERSION ${STRATA_SYCL_VERSION} LANGUAGES C CXX)\n", encoding="utf-8")
132            with mock.patch.object(self.mod, "ROOT", root), mock.patch.object(setup, "ROOT", root):
133                self.assertEqual(self.mod.sycl_version(), "0.1.41.2")
134
135
136class IntelIds(unittest.TestCase):
137    """sycl/setup_intel.py names a card by its PCI device id. The Arc Pro B60s measured on 2x B60 (`lspci -nn` 8086:e211,
138    bmg-g21) must not fall through to "Intel GPU e211 (xe)" with a guessed VRAM size."""
139
140    @staticmethod
141    def table():
142        import importlib.util
143        spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py")
144        mod = importlib.util.module_from_spec(spec)
145        spec.loader.exec_module(mod)
146        return mod.INTEL_ARC
147
148    def test_b60_e211_is_named_with_its_vram(self):
149        self.assertEqual(self.table()["e211"], ("Arc Pro B60", 24.0))
150
151    def test_the_ids_that_were_listed_before_are_kept(self):
152        t = self.table()
153        self.assertEqual(t["e223"][0], "Arc Pro B70")
154        self.assertEqual(t["e221"][0], "Arc Pro B60")
155
156
157class ToSycl(unittest.TestCase):
158    """The config sycl/setup_intel.py writes: an explicit --vram-reserve-mib is kept, the B-series streams its experts,
159    the A-series (i915) cannot (a single pinned host allocation above a few GB fails there) and loads them into RAM."""
160
161    @staticmethod
162    def mod():
163        import importlib.util
164        spec = importlib.util.spec_from_file_location("setup_intel", ROOT / "sycl" / "setup_intel.py")
165        m = importlib.util.module_from_spec(spec)
166        spec.loader.exec_module(m)
167        return m
168
169    def cfg(self, m, extra=()):
170        base = m.MOUNT
171        return {"exe": "x", "cwd": "y", "args": ["--pack", str(base / "d" / "pack"), "--native", str(base / "d" / "a.gguf"),
172                                                 "--expert-cache", "auto", "--prefill", "auto", "--max-context", "32768",
173                                                 "--kv", "int8", *extra]}
174
175    def test_b_series_streams_and_defaults_the_reserve(self):
176        m = self.mod()
177        c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
178        self.assertIn("--stream-experts", c["args"])
179        self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "1024")
180        self.assertNotIn("STRATA_VERIFY_NO_HOST", c.get("env", {}))
181
182    def test_xe_ranks_the_experts_with_the_sycl_profile_and_i915_keeps_the_shipped_one(self):
183        m = self.mod()
184        shipped = str(m.MOUNT / "data" / "expert-profile.bin")
185        other = str(m.MOUNT / "mine" / "learned.bin")
186        c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
187        self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile-sycl.bin"))
188        c = m.to_sycl(self.cfg(m, ["--expert-profile", other]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
189        self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("learned.bin"))   # the user's own file stays
190        c = m.to_sycl(self.cfg(m, ["--expert-profile", shipped]), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915")
191        self.assertTrue(c["args"][c["args"].index("--expert-profile") + 1].endswith("expert-profile.bin"))   # the CPU computes the misses there
192
193    def test_an_explicit_reserve_is_kept_on_both_drivers(self):
194        m = self.mod()
195        for vram, drv in ((32.0, "xe"), (8.0, "i915")):
196            c = m.to_sycl(self.cfg(m, ["--vram-reserve-mib", "500"]), m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, vram, drv)
197            self.assertEqual(c["args"].count("--vram-reserve-mib"), 1)
198            self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "500")
199
200    def test_a_series_loads_experts_into_ram_and_leaves_no_host_off(self):
201        m = self.mod()
202        c = m.to_sycl(self.cfg(m), m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915")
203        self.assertNotIn("--stream-experts", c["args"])
204        self.assertEqual(c["args"][c["args"].index("--ple-io") + 1], "ram")
205        self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "300")
206        self.assertEqual(c["env"]["STRATA_VERIFY_NO_HOST"], "0")
207        self.assertEqual(c["env"]["STRATA_SYCL_BIN"], "build-sycl/strata")
208
209    def test_gyro_memory_warning_reads_the_real_ram(self):
210        # setup's RAM rule is fed 1024 GB on the Intel path; Gyro counts VRAM + RAM, so it must see the real RAM
211        m = self.mod()
212        import importlib.util
213        spec = importlib.util.spec_from_file_location("setup_for_test", ROOT / "setup.py")
214        s = importlib.util.module_from_spec(spec)
215        spec.loader.exec_module(s)
216        have = m.real_mem_have(s.mem_have, 16.0, 1024.0)
217        self.assertEqual(have("Gyro-S", 1024.0, 8.0), 24.0)              # 16 GB RAM + 8 GB VRAM: below Gyro-S's 27.6, setup warns
218        self.assertLess(have("Gyro-S", 1024.0, 8.0), s.MODELS["Gyro-S"]["ram_gb"])
219        self.assertEqual(have("Gyro-S", 40.0, 8.0), 48.0)                # a real RAM figure passes through
220        self.assertEqual(have("Q2_0", 1024.0, 8.0), 16.0)                # the other sizes count RAM only, as before
221
222    def test_a_series_keeps_gyros_ngram_table_on_the_ssd(self):
223        # Gyro's table is half of the 58-92 GB file: --ple-io ram would not fit beside the experts' arena on a 64 GB PC
224        m = self.mod()
225        cfg = self.cfg(m)
226        cfg["args"][cfg["args"].index("--native") + 1] = str(m.MOUNT / "d" / "Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf")
227        c = m.to_sycl(cfg, m.ROOT / "build-sycl" / "strata", 64.0, {}, 8.0, "i915")
228        self.assertNotIn("--ple-io", c["args"])
229        self.assertEqual(c["env"]["STRATA_VERIFY_NO_HOST"], "0")
230
231    def test_split_short_rule(self):
232        # #1980: 2x B60 24 GB - IQ3_XXS (42.9 GB) was refused under NO_HOST=1, IQ2_XS (35.5 GB) loads fully
233        m = self.mod()
234        self.assertTrue(m.split_likely_short(42.9, [24.0, 24.0]))
235        self.assertFalse(m.split_likely_short(35.5, [24.0, 24.0]))
236        self.assertFalse(m.split_likely_short(50.3, [32.0, 32.0]))   # IQ3_S on 2x B70: 79%
237        self.assertTrue(m.split_likely_short(77.0, [32.0, 32.0]))
238        self.assertFalse(m.split_likely_short(0, [24.0]))
239        self.assertFalse(m.split_likely_short(40.0, []))
240
241    def test_small_card_rule(self):
242        m = self.mod()
243        self.assertTrue(m.small_card(8.0, "i915"))
244        self.assertTrue(m.small_card(24.0, "i915"))
245        self.assertTrue(m.small_card(10.0, "xe"))
246        self.assertFalse(m.small_card(32.0, "xe"))
247
248    def test_pictures_follow_the_one_reader_rule_and_the_vision_section_survives(self):
249        """Intel Arc: pictures on gives the CPU reader (strata-vision) on the host under 24 GB and, until a 24 GB+ Arc has run the SYCL reader,
250        also from 24 GB; only --vision gpu asks for the SYCL reader (strata_control/vision_reader.py is the one place for the rule)."""
251        m = self.mod()
252        for asked in (None, "yes", "cpu", "on"):
253            self.assertEqual(m.intel_vision(asked, 8.0), "cpu")
254            self.assertEqual(m.intel_vision(asked, 32.0), "cpu")
255        self.assertEqual(m.intel_vision("gpu", 8.0), "gpu")
256        self.assertEqual(m.intel_vision("gpu", 32.0), "gpu")
257        for asked in ("no", "none", "off"):
258            self.assertEqual(m.intel_vision(asked, 32.0), "none")
259        section = {"exe": "/h/engine-sycl/strata-vision", "mmproj": "/h/models/mmproj.gguf", "model": "/h/models/m.gguf", "gpu": False,
260                   "max_tokens": 300}
261        cfg = self.cfg(m, ["--vision"])
262        cfg["vision"] = section
263        c = m.to_sycl(cfg, m.ROOT / "build-sycl-aot" / "strata", 64.0, {}, 32.0, "xe")
264        self.assertEqual(c["vision"], section)                              # host paths: the reader runs on the host, not in the container
265        self.assertIn("--vision", c["args"])
266
267    def test_pictures_are_on_by_default_on_every_arc_and_a_battlemage_is_told_it_is_new(self):
268        """Owner decision 2026-10-22: an Arc B-series card runs like any Arc. The first picture on the Arc Pro B70 reset the GPU (xe, 2026-10-19) is a
269        known risk, not a refusal: pictures are on (the CPU reader) and setup prints one plain line about it."""
270        m = self.mod()
271        for driver, devid in (("i915", "56a1"), ("i915", ""), ("xe", "56a0"), ("xe", "e223"), ("xe", "e20b"), ("xe", "e211"), ("xe", "")):
272            self.assertTrue(m.pictures_on_by_default(driver, devid), (driver, devid))
273        self.assertTrue(m.is_b_series("xe", "e223"))                        # B70
274        self.assertTrue(m.is_b_series("xe", "e20b"))                        # B580
275        self.assertFalse(m.is_b_series("i915", "56a1"))                     # A750
276        self.assertFalse(m.is_b_series("xe", "56a0"))                       # A770 on xe
277        self.assertIn("new to Strata", m.B_SERIES_LINE)
278        self.assertIn("issues", m.B_SERIES_LINE)
279        src = (ROOT / "sycl" / "setup_intel.py").read_text(encoding="utf-8")
280        self.assertIn("B_SERIES_LINE", src)
281        self.assertNotIn('sys.argv += ["--vision", "none"]', src)          # no B-series card has pictures switched off for it
282        self.assertIn("S.hip_vision = intel_vision", src)
283        self.assertIn("S.build_vision_cpu(", src)                           # the CPU reader is compiled by setup's own step
284        self.assertIn("build_vision_sycl(", src)                            # --vision gpu: the SYCL reader, when the oneAPI compiler is there
285
286    def test_the_sycl_reader_is_built_only_when_asked_and_the_cpu_reader_stays_without_the_compiler(self):
287        from unittest import mock
288        m = self.mod()
289        with mock.patch.object(m, "oneapi_compiler", return_value=None), mock.patch.object(m.S, "warn") as warn:
290            self.assertFalse(m.build_vision_sycl_reader(Path("/nonexistent"), "/llama"))
291        self.assertIn("oneAPI compiler", warn.call_args[0][0])
292        self.assertIn("pictures are read on the CPU", warn.call_args[0][0])
293
294    def test_the_container_shares_dev_shm_with_the_server_for_the_embeddings(self):
295        sh = (ROOT / "sycl" / "serve" / "strata-sycl.sh").read_text(encoding="utf-8")
296        self.assertIn("-v /dev/shm:/dev/shm", sh)
297        self.assertIn("STRATA_SYCL_SHM", sh)
298
299    def test_a_picture_that_cannot_reach_the_container_is_said_once(self):
300        import importlib.util
301        spec = importlib.util.spec_from_file_location("server_intel_t", ROOT / "sycl" / "serve" / "server_intel.py")
302        src = (ROOT / "sycl" / "serve" / "server_intel.py").read_text(encoding="utf-8")
303        self.assertIn("install_shared_embeddings()", src.split('if __name__ == "__main__":')[1])
304        sys.path.insert(0, str(ROOT / "sycl" / "serve"))
305        try:
306            m = importlib.util.module_from_spec(spec)
307            spec.loader.exec_module(m)
308        except ImportError as e:                                           # no oneAPI / xe telemetry import here: the source check above stands
309            self.skipTest(str(e))
310        finally:
311            sys.path.pop(0)
312        out = io.StringIO()
313        with mock.patch.object(m.S, "combined_embeddings_path", lambda d, n: Path("/tmp/x/req.sve")), contextlib.redirect_stdout(out):
314            m.install_shared_embeddings()
315            m.S.combined_embeddings_path(Path("/tmp/x"), 10)
316            m.S.combined_embeddings_path(Path("/tmp/x"), 10)
317        self.assertEqual(out.getvalue().count("/dev/shm has no room"), 1)
318
319
320if __name__ == "__main__":
321    unittest.main()