okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
45.5 KiB827 linesraw
1"""Tests for setup.py's choices that depend on the PC (no GPU, no network, nothing installed): the image encoder of a
2ready-made engine that has no code for the card (#331), --gguf-dir's shard count (#305), the experimental
3Pascal/Volta build (#295), the CPU image encoder with the AMD backend (#304).
4
5    python -m unittest tools.test_setup_choices
6"""
7from __future__ import annotations
8
9import contextlib
10import io
11import json
12import os
13import sys
14import tempfile
15import unittest
16from pathlib import Path
17from unittest import mock
18
19ROOT = Path(__file__).resolve().parents[1]
20sys.path.insert(0, str(ROOT))
21sys.path.insert(0, str(ROOT / "tools"))
22import setup  # noqa: E402
23
24
25def quiet(fn, *args, **kw):
26    out = io.StringIO()
27    with contextlib.redirect_stdout(out):
28        return fn(*args, **kw), out.getvalue()
29
30
31class PrebuiltVision(unittest.TestCase):
32    """#331: the 0.1.30/0.1.31 zip's encoder has no sm_75 code: an RTX 20 card gets the CPU encoder, not a compile."""
33    META = {"version": "0.1.31", "archs": [75, 86, 89, 120], "ptx": True, "vision_archs": [86, 89, 120]}
34
35    def test_a_card_the_encoder_has_no_code_for_gets_the_cpu_encoder(self):
36        got, out = quiet(setup.prebuilt_vision, self.META, {"arch": 75}, "gpu")
37        self.assertEqual(got, "cpu")
38        self.assertIn("runs on the CPU instead", out)
39
40    def test_covered_cards_keep_the_gpu_encoder(self):
41        for arch in (86, 89, 120):
42            self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": arch}, "gpu")[0], "gpu")
43        # a newer card than the newest encoder code: only with PTX in the zip
44        self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89]}, {"arch": 120}, "gpu")[0],
45                         "gpu")
46        self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [86, 89], "ptx": False},
47                               {"arch": 120}, "gpu")[0], "cpu")
48        # 0.1.32's zip: the encoder built with 75-real too
49        self.assertEqual(quiet(setup.prebuilt_vision, {**self.META, "vision_archs": [75, 86, 89, 120]},
50                               {"arch": 75}, "gpu")[0], "gpu")
51
52    def test_other_choices_are_left_alone(self):
53        for v in ("cpu", "none"):
54            self.assertEqual(quiet(setup.prebuilt_vision, self.META, {"arch": 75}, v), (v, ""))
55        # an older BUILD.json without vision_archs: the engine's archs
56        self.assertEqual(quiet(setup.prebuilt_vision, {"archs": [75, 86]}, {"arch": 75}, "gpu")[0], "gpu")
57
58
59class VisionArchsAsAString(unittest.TestCase):
60    """#3810: the packaging recipes write BUILD.json `vision_archs` as ONE string ("75;86;89;120"); 0.2.3 iterated it character by
61    character and setup stopped with int(';') on the released Windows CUDA package.  A string and a list mean the same."""
62    RELEASED = {"version": "0.2.3", "archs": [75, 86, 89, 120], "ptx": True, "cuda": "13.0", "vision": "gpu-cuda13",
63                "vision_archs": "75;86;89;120", "portable": True}
64
65    def test_the_released_package_manifest_is_read(self):
66        for arch in (75, 86, 89, 120):
67            self.assertEqual(quiet(setup.prebuilt_vision, self.RELEASED, {"arch": arch}, "gpu")[0], "gpu")
68
69    def test_a_card_the_string_does_not_list_gets_the_cpu_reader(self):
70        meta = {**self.RELEASED, "vision_archs": "86;89;120", "ptx": False}
71        got, out = quiet(setup.prebuilt_vision, meta, {"arch": 75}, "gpu")
72        self.assertEqual(got, "cpu")
73        self.assertIn("runs on the CPU instead", out)
74        self.assertEqual(quiet(setup.prebuilt_vision, {**meta, "ptx": True}, {"arch": 120}, "gpu")[0], "gpu")
75
76    def test_a_string_and_a_list_agree(self):
77        for value in ("75;86;89;120", [75, 86, 89, 120], ["sm_75", "86-real", "89", "compute_120"], "75,86 89;120"):
78            self.assertEqual(setup.arch_numbers(value), [75, 86, 89, 120], value)
79        self.assertEqual(setup.arch_numbers(None), [])
80        self.assertEqual(setup.arch_numbers(""), [])
81        self.assertEqual(setup.arch_names("gfx1100;gfx1201"), ["gfx1100", "gfx1201"])
82        self.assertEqual(setup.arch_names(["gfx1100"]), ["gfx1100"])
83        self.assertEqual(setup.arch_names(None), [])
84
85    def test_the_other_readers_of_the_manifest_take_a_string_too(self):
86        import tempfile
87        from pathlib import Path
88        from unittest import mock
89        with tempfile.TemporaryDirectory() as d:
90            (Path(d) / "BUILD.json").write_text('{"archs": "60;61;70", "ptx": true}', encoding="utf-8")
91            with mock.patch.object(setup, "engine_dir", return_value=Path(d)):
92                self.assertEqual(setup.engine_archs(), ([60, 61, 70], True))
93            (Path(d) / "BUILD.json").write_text('{"backend": "hip", "archs": ["gfx1100"], "vision_archs": "gfx1100;gfx1201"}', encoding="utf-8")
94            self.assertEqual(setup.reader_archs(Path(d)), ["gfx1100", "gfx1201"])
95            (Path(d) / "BUILD.json").write_text('{"backend": "hip", "archs": ["gfx1100", "gfx1201"]}', encoding="utf-8")
96            self.assertEqual(setup.reader_archs(Path(d)), ["gfx1100", "gfx1201"])
97        self.assertEqual(setup.reader_archs(Path(__file__).parent / "no-such-folder"), [])
98
99
100class GgufDirShards(unittest.TestCase):
101    """#305: --gguf-dir reads the shard count from the -of-N part of the name instead of assuming two."""
102
103    def shards(self, names, family="qwen", model="IQ3_XXS"):
104        with tempfile.TemporaryDirectory() as d:
105            for n in names:
106                (Path(d) / n).write_bytes(b"")
107            return [p.name for p in setup.gguf_dir_shards(Path(d), setup.FAMILIES[family], model)]
108
109    def test_the_published_two_shards(self):
110        names = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
111                 "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"]
112        self.assertEqual(self.shards(names), names)
113        self.assertEqual(self.shards(names[:1]), names)              # shard 2 missing: check_shards says so later
114        swift = ["Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf",
115                 "Swift-Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"]
116        self.assertEqual(self.shards(swift + ["mmproj-Swift-Qwen3.8-Flash-Next-BF16.gguf"], "swift", "Q2_0"), swift)
117
118    def test_four_unsloth_shards(self):
119        names = ["Qwen3.8-Flash-Next-UD-Q4_K_XL-%05d-of-00004.gguf" % i for i in range(1, 5)]
120        self.assertEqual(self.shards(names + ["mmproj-F16.gguf"], model="Q4_K_XL"), names)
121        self.assertEqual(self.shards(names[:1], model="Q4_K_XL"), names)   # the others named from the first
122
123    def test_another_split_of_a_setup_size(self):
124        names = ["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in range(1, 4)]
125        other = ["my-Q2_0-%05d-of-00002.gguf" % i for i in range(1, 3)]
126        self.assertEqual(self.shards(names + other), names)           # the one with the size in its name
127        self.assertEqual(self.shards(other, model="Q2_0"), other)
128
129    def test_nothing_recognisable_keeps_the_published_names(self):
130        want = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf",
131                "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00002-of-00002.gguf"]
132        self.assertEqual(self.shards([]), want)
133        self.assertEqual(self.shards(["a-00001-of-00002.gguf", "b-00001-of-00002.gguf"]), want)   # ambiguous
134
135
136class GgufDirUnsupported(unittest.TestCase):
137    """#444: --gguf-dir with GGUFs Strata cannot run (Unsloth's UD-IQ3_XXS, UD-Q2_K_XL) says so, names the files it
138    runs (ISTA-DASLab's GSQ-RCO, the Coder's, Unsloth's UD-Q4_K_XL) and the --family/--model of the usable ones."""
139    UD = ["Qwen3.8-Flash-Next-UD-IQ1_S-%05d-of-00003.gguf" % i for i in range(1, 4)] + \
140         ["Qwen3.8-Flash-Next-BF16-%05d-of-00008.gguf" % i for i in range(1, 4)]   # round 0214: UD-IQ3_XXS and UD-Q2_K_XL run now; UD-IQ1_S and BF16 do not
141
142    def problem(self, names, family="qwen", model="IQ3_XXS"):
143        with tempfile.TemporaryDirectory() as d:
144            for n in names:
145                (Path(d) / n).write_bytes(b"")
146            fam = setup.FAMILIES[family]
147            first = setup.gguf_dir_shards(Path(d), fam, model)[0]
148            p = setup.gguf_dir_problem(Path(d), first, fam, model)
149            return p and (p[0].replace(d, "<D>"), p[1])
150
151    def test_quant_names(self):
152        for name, want in (("Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf", "UD-IQ1_S"),
153                           ("Qwen3.8-Flash-Next-UD-Q2_K_XL-00001-of-00003.gguf", None),
154                           ("Qwen3.8-Flash-Next-UD-IQ3_XXS-00001-of-00004.gguf", None),
155                           ("model-Q4_K_M.gguf", "Q4_K_M"),
156                           ("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-00001-of-00002.gguf", None),
157                           ("Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", None),
158                           ("my-IQ3_XXS-00001-of-00003.gguf", None), ("mmproj-F16.gguf", None),
159                           ("a-00001-of-00002.gguf", None)):
160            self.assertEqual(setup.gguf_unsupported(name), want, name)
161
162    def test_an_unsloth_ud_file_is_not_taken_for_a_gsq_rco_size(self):
163        msg, hint = self.problem(self.UD[:3], "unsloth", "UD-IQ1_M")        # a UD-IQ1_S set asked for as UD-IQ1_M
164        self.assertIn("UD-IQ1_S", msg + hint)
165        self.assertIn("ISTA-DASLab's GSQ-RCO files", hint)
166
167    def test_a_folder_without_the_choice_names_what_is_there(self):
168        gsq = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M-%05d-of-00002.gguf" % i for i in (1, 2)]
169        msg, hint = self.problem(self.UD + gsq, "unsloth", "UD-Q4_K_XL")
170        self.assertEqual(msg, "<D> has no Qwen3.8-Flash-Next (Unsloth) UD-Q4_K_XL file")
171        self.assertIn("Not usable here: Qwen3.8-Flash-Next-BF16-00001-of-00008.gguf, "
172                      "Qwen3.8-Flash-Next-UD-IQ1_S-00001-of-00003.gguf", hint)
173        self.assertIn("Usable here: --family coder --model IQ1_M", hint)
174
175    def test_usable_folders_are_left_alone(self):
176        good = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-%05d-of-00002.gguf" % i for i in (1, 2)]
177        self.assertIsNone(self.problem(good + self.UD))
178        self.assertIsNone(self.problem(["my-IQ3_XXS-%05d-of-00003.gguf" % i for i in (1, 2, 3)]))
179        self.assertIsNone(self.problem([]))                 # nothing there: check_shards' "missing", as before
180
181    def test_the_size_of_another_family(self):
182        from test_setup_golden import PROFILES, install
183        ram, found = PROFILES["64GB-1x32GB"]
184        with tempfile.TemporaryDirectory() as d:
185            code, out, _, _ = install(ram, found, ["--gguf-dir", d, "--family", "unsloth", "--model", "IQ3_XXS"])
186        self.assertEqual(code, 1)
187        self.assertIn("has no IQ3_XXS model file", out)
188        self.assertIn("choose one of: UD-IQ4_XS, UD-Q4_K_XL, UD-Q5_K_XL, UD-Q6_K_XL, Q8_0, UD-IQ1_M, UD-Q2_0, UD-IQ2_XS, UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL, "
189                      "UD-IQ4_XS-v31 (or IQ3_XXS: --family qwen --model IQ3_XXS, --family swift --model IQ3_XXS)", out)
190        self.assertIn("Strata runs ISTA-DASLab's GSQ-RCO files", out)
191
192
193class ReadOnlyGgufDir(unittest.TestCase):
194    """--gguf-dir on a read-only folder (a share): whole shards without a finish mark still install, with a warning."""
195
196    def test_a_finish_mark_that_cannot_be_written_is_a_warning(self):
197        from test_setup_golden import PROFILES, install
198        ram, found = PROFILES["64GB-1x32GB"]
199        real_mark = setup.mark
200
201        def read_only_mark(path, text=""):
202            if "gguf_share" in str(path):
203                raise PermissionError(13, "Read-only file system")
204            real_mark(path, text)
205
206        with tempfile.TemporaryDirectory() as tmp:
207            d = Path(tmp) / "gguf_share"
208            d.mkdir()
209            for i in (1, 2):
210                (d / f"Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-{i:05d}-of-00002.gguf").write_bytes(b"")
211            code, out, cfg, _ = install(ram, found, ["--gguf-dir", str(d), "--family", "qwen", "--model", "Q2_0",
212                                                     "--no-start"],
213                                        extra=[mock.patch.object(setup, "whole_shard", lambda s: True),
214                                               mock.patch.object(setup, "mark", read_only_mark)])
215        self.assertEqual(code, 0, out)
216        self.assertIn("is whole but its finish mark cannot be written", out)
217
218
219    def test_mark_itself_never_stops_on_a_read_only_folder(self):
220        """#570: every finish mark (the SHA-256 result of a verified shard too), not only the one for a whole shard."""
221        with tempfile.TemporaryDirectory() as tmp, mock.patch.object(Path, "write_text",
222                                                                     side_effect=PermissionError(13, "read-only")):
223            setup.mark(Path(tmp) / "x.gguf", "sha256 abc")                   # no exception
224            self.assertFalse(setup.done(Path(tmp) / "x.gguf"))
225
226
227class ReadOnlyModelFolderMark(unittest.TestCase):
228    """0.2.10: a model folder Strata cannot write to (a read-only disk) keeps its finish marks under Strata's own folder, so the
229    SHA-256 of the 110 GB Engram is not computed again on every launch."""
230
231    def test_the_mark_is_kept_elsewhere_and_the_hash_is_not_repeated(self):
232        real_write = Path.write_text
233
234        def write(self, *a, **k):
235            if self.name.endswith(".done") and "strata_marks" not in str(self):
236                raise PermissionError(13, "read-only")
237            return real_write(self, *a, **k)
238
239        with tempfile.TemporaryDirectory() as tmp:
240            root, share = Path(tmp) / "strata_marks", Path(tmp) / "share"
241            share.mkdir()
242            f = share / "engram.gguf"
243            f.write_bytes(b"abc" * 10)
244            sha = "f" * 64
245            hashed = []
246
247            def fake_hash(path, size):
248                hashed.append(path)
249                return sha
250
251            with mock.patch.object(setup, "ROOT", root), mock.patch.object(Path, "write_text", write),                     mock.patch.object(setup, "_hash_file", fake_hash):
252                setup.verify_sha256(f, 30, sha)
253                self.assertEqual(len(hashed), 1)
254                self.assertFalse((share / "engram.gguf.done").exists())
255                self.assertTrue(setup.done(f))
256                setup.verify_sha256(f, 30, sha)                       # the second launch
257                self.assertEqual(len(hashed), 1, "the kept mark is found; nothing is hashed again")
258                f.write_bytes(b"abcd" * 10)                           # a changed file has no mark
259                self.assertFalse(setup.done(f))
260
261
262class OfflineStart(unittest.TestCase):
263    """0.2.10: a PC with every file and no internet starts a model that is already prepared."""
264
265    def test_preparing_a_model_never_fetches_llama_cpp(self):
266        """OWN-1B/2B: the preparation tools have their own GGUF code (tools/strata_gguf.py), so neither starting a prepared model nor running a
267        preparation tool reaches github.com, and the tools are not told to use gguf-py unless the user set STRATA_GGUF_PY."""
268        fetched = []
269        env = {k: v for k, v in os.environ.items() if k not in ("STRATA_GGUF_PY", "STRATA_GGML_DIR")}
270        with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(setup, "get_llama_cpp", lambda: fetched.append(1)):
271            self.assertIsNone(setup.llama_cpp_if_here(), "no override tree by default")
272            self.assertEqual(setup.gguf_py_dir(), setup.ROOT / "third_party" / "strata-gguf-py")
273            self.assertTrue((setup.gguf_py_dir() / "gguf").is_dir())
274            self.assertEqual(setup.gguf_py_env(), {}, "the tools use their own GGUF code by default")
275            with mock.patch.object(setup.subprocess, "run", lambda *a, **k: mock.Mock(returncode=0)), \
276                    mock.patch.object(setup.acquisition, "require", lambda *a, **k: None), mock.patch.object(setup, "CONTROL", False):
277                setup.run([sys.executable, "tools/x.py"], env=dict(os.environ, **setup.gguf_py_env()))
278            self.assertEqual(fetched, [], "nothing is downloaded")
279
280    def test_the_overrides_are_kept(self):
281        """STRATA_GGUF_PY and STRATA_GGML_DIR still name another copy (kept for two releases)."""
282        with tempfile.TemporaryDirectory() as tmp:
283            (Path(tmp) / "gguf").mkdir()
284            (Path(tmp) / "ggml").mkdir()
285            (Path(tmp) / "ggml" / "CMakeLists.txt").write_text("", encoding="utf-8")
286            with mock.patch.dict(os.environ, {"STRATA_GGUF_PY": tmp, "STRATA_GGML_DIR": tmp}):
287                self.assertEqual(setup.gguf_py_dir(), Path(tmp))
288                self.assertEqual(setup.gguf_py_env(), {"STRATA_GGUF_PY": tmp}, "the override is passed on to the tools")
289                self.assertEqual(setup.llama_override(), Path(tmp))
290                self.assertEqual(setup.ggml_defs(setup.llama_override()), [f"-DSTRATA_GGML_DIR={tmp}"])
291            self.assertEqual(setup.ggml_defs(None), [], "nothing is passed by default")
292
293    def test_a_pinned_file_copied_in_by_hand_is_checked_here_without_the_network(self):
294        with tempfile.TemporaryDirectory() as tmp:
295            f = Path(tmp) / "drafter.gguf"
296            f.write_bytes(b"abc" * 10)
297            url = "https://huggingface.co/x/y/resolve/main/drafter.gguf"
298            with mock.patch.object(setup, "file_pin", lambda u: (30, "a" * 64)), mock.patch.object(setup, "_hash_file", lambda p, n: "a" * 64),                     mock.patch.object(setup, "_urlopen", side_effect=OSError("no network")):
299                quiet(setup.download, url, f, "drafter")
300            self.assertTrue(setup.done(f))
301            self.assertIn("sha256 " + "a" * 64, setup.mark_text(f))
302
303
304
305class VsRange(unittest.TestCase):
306    """#985: Visual Studio 2026 (version 18) is looked for only with CUDA 13.3 or newer."""
307
308    def asked(self, cuda_v):
309        seen = []
310        with mock.patch.object(setup.Path, "exists", lambda self: True),                 mock.patch.object(setup, "out", lambda cmd, *a, **k: seen.append(cmd) or "C:/VS"):
311            setup.find_vcvars(cuda_v)
312        return seen[0][seen[0].index("-version") + 1] if "-version" in seen[0] else None
313
314    def test_the_range_follows_the_toolkit(self):
315        self.assertIsNone(self.asked(None))      # #881: without CUDA vswhere gets no version range
316        self.assertEqual(self.asked((13, 0)), "[17.0,18.0)")
317        self.assertEqual(self.asked((13, 2)), "[17.0,18.0)")
318        self.assertEqual(self.asked((13, 3)), "[17.0,19.0)")
319        self.assertEqual(self.asked((14, 0)), "[17.0,19.0)")
320
321
322    def test_vcvars_by_hand(self):
323        """#881: STRATA_VCVARS names a vcvars64.bat directly, for an install vswhere cannot use."""
324        import tempfile
325        with tempfile.TemporaryDirectory() as d:
326            bat = Path(d) / "vcvars64.bat"
327            bat.write_text("rem")
328            with mock.patch.dict(os.environ, {"STRATA_VCVARS": str(bat)}):
329                self.assertEqual(setup.find_vcvars(), bat)
330            with mock.patch.dict(os.environ, {"STRATA_VCVARS": str(Path(d) / "missing.bat")}):
331                self.assertIsNone(setup.find_vcvars())
332
333class ExperimentalSm60(unittest.TestCase):
334    """#295: Pascal (6.x) and Volta (7.0) only with STRATA_EXPERIMENTAL_SM60=1, built with -DSTRATA_EXPERIMENTAL_SM60=ON
335    and a CUDA 12.x toolkit; nothing changes without the variable."""
336
337    def card(self, arch):
338        return {"arch": arch, "vram_gb": 11.0, "index": 0, "name": "card"}
339
340    def test_the_gate(self):
341        with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": ""}):
342            for arch in ("60", "61", "70"):
343                p = setup.gpu_problem(self.card(arch))
344                self.assertIn("not supported", p)
345                self.assertIn("choose it with --gpu 0", p)              # the CUDA 12 engine (docs/OLDER_GPUS.md)
346            self.assertNotIn("--gpu", setup.gpu_problem(self.card("52")))
347            self.assertIsNone(setup.gpu_problem(self.card("75")))
348        with mock.patch.dict(os.environ, {"STRATA_EXPERIMENTAL_SM60": "1"}):
349            for arch in ("60", "61", "70", "75", "120"):
350                self.assertIsNone(setup.gpu_problem(self.card(arch)), arch)
351            for arch in ("52", "72"):
352                self.assertIsNotNone(setup.gpu_problem(self.card(arch)), arch)
353
354    def test_the_build_flag(self):
355        self.assertEqual(setup.engine_defs([61]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"])
356        self.assertEqual(setup.engine_defs([70, 86]), ["-DSTRATA_EXPERIMENTAL_SM60=ON"])
357        self.assertEqual(setup.engine_defs([75, 86, 120]), [])
358
359    def test_find_nvcc_below(self):
360        with tempfile.TemporaryDirectory() as d:
361            new, old = Path(d) / "13" / "nvcc", Path(d) / "12" / "bin" / "nvcc"
362            for p in (new, old):
363                p.parent.mkdir(parents=True)
364                p.write_bytes(b"")
365            versions = {str(new): "Cuda compilation tools, release 13.0, V13.0.88",
366                        str(old): "Cuda compilation tools, release 12.9, V12.9.86"}
367            with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: str(new)), \
368                    mock.patch.dict(os.environ, {"CUDA_PATH": str(Path(d) / "12")}), \
369                    mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")):  # #414
370                self.assertEqual(setup.find_nvcc(), (str(new), (13, 0)))
371                self.assertEqual(setup.find_nvcc(below=(13, 0)), (str(old), (12, 9)))
372                # #601: STRATA_NVCC is the only one considered; CUDA_HOME is a candidate like CUDA_PATH
373                with mock.patch.dict(os.environ, {"STRATA_NVCC": str(old)}):
374                    self.assertEqual(setup.find_nvcc(), (str(old), (12, 9)))
375                with mock.patch.dict(os.environ, {"STRATA_NVCC": str(new)}):
376                    got, text = quiet(setup.find_nvcc, below=(13, 0))
377                    self.assertEqual(got, (None, None))
378                    self.assertIn("needs one older than 13.0", text)
379                with mock.patch.dict(os.environ, {"STRATA_NVCC": str(Path(d) / "missing")}):
380                    got, text = quiet(setup.find_nvcc)
381                    self.assertEqual(got, (str(new), (13, 0)))
382                    self.assertIn("no such file", text)
383            with mock.patch.object(setup, "WIN", False), mock.patch.object(setup.shutil, "which", lambda n: None), \
384                    mock.patch.dict(os.environ, {"CUDA_HOME": str(Path(d) / "12")}), \
385                    mock.patch.object(setup, "out", lambda cmd: versions.get(cmd[0], "")):
386                os.environ.pop("CUDA_PATH", None)
387                got = setup.find_nvcc(below=(13, 0))
388                self.assertEqual(got, (str(old), (12, 9)))
389
390    def tools(self, archs, nvcc):
391        seen = []
392
393        def find(below=None):
394            seen.append(below)
395            return nvcc(below)
396
397        with mock.patch.object(setup, "find_nvcc", find), mock.patch.object(setup, "find_vcvars", lambda cuda_v=None: "vcvars"), \
398                mock.patch.object(setup.shutil, "which", lambda n: "/usr/bin/" + n):
399            got, _ = quiet(setup.install_build_tools, {"arch": str(archs[0]), "archs": archs}, True)
400        return got, seen
401
402    def test_pascal_takes_cuda_12(self):
403        got, seen = self.tools([61], lambda below: ("nvcc12", (12, 9)) if below == (13, 0) else ("nvcc13", (13, 0)))
404        self.assertEqual(got[0], "nvcc12")
405        self.assertEqual(seen, [(13, 0)])
406        got, seen = self.tools([86, 120], lambda below: ("nvcc13", (13, 0)))
407        self.assertEqual((got[0], seen), ("nvcc13", [None]))           # the default: unchanged
408
409    def test_cuda_132_on_sm120(self):
410        """#892 / #968: nvcc 13.2 for an RTX 50 card: an older 13.x is taken when there is one, else a warning; never an
411        error, and no other card or toolkit is touched."""
412        def nvcc(below):
413            return ("nvcc130", (13, 0)) if below == (13, 2) else ("nvcc132", (13, 2))
414
415        got, seen = self.tools([120], nvcc)
416        self.assertEqual(got[0], "nvcc130")
417        self.assertEqual(seen, [None, (13, 2)])
418        with mock.patch.dict(os.environ, {"STRATA_NVCC": "x"}):          # the user's own pick is kept
419            got, seen = self.tools([120], nvcc)
420            self.assertEqual((got[0], seen), ("nvcc132", [None]))
421        only132 = lambda below: (None, None) if below == (13, 2) else ("nvcc132", (13, 2))
422        with mock.patch.object(setup, "warn") as warn:                   # nothing older: the one found, with a warning
423            got, _ = self.tools([120], only132)
424        self.assertEqual(got[0], "nvcc132")
425        self.assertIn("#892", warn.call_args[0][0])
426        for archs in ([86], [89, 86]):                                   # not an sm_120 card: as before
427            got, seen = self.tools(archs, nvcc)
428            self.assertEqual((got[0], seen), ("nvcc132", [None]))
429
430    def test_pascal_without_cuda_12_stops(self):
431        for archs in ([61], [70, 120]):
432            with self.subTest(archs=archs), self.assertRaises(SystemExit):
433                self.tools(archs, lambda below: (None, None) if below else ("nvcc13", (13, 0)))
434
435
436class HipVision(unittest.TestCase):
437    """#304: --vision cpu with --backend hip builds the CPU image encoder beside the HIP engine."""
438
439    @mock.patch.object(setup, "WIN", False)
440    def test_the_choice(self):
441        self.assertEqual(quiet(setup.hip_vision, "cpu"), ("cpu", ""))
442        for asked in ("no", "none"):
443            self.assertEqual(quiet(setup.hip_vision, asked), ("none", ""))
444        for asked in (None, "yes", "gpu"):            # pictures are on by default; the engine folder's readers settle gpu vs cpu
445            self.assertEqual(quiet(setup.hip_vision, asked), ("gpu", ""))
446
447    def build(self, meta, vision, vexe=False):
448        """build_engine_hip with an engine that is already built: only the encoder can be missing."""
449        with tempfile.TemporaryDirectory() as d:
450            root = Path(d)
451            eng = root / "engine"
452            eng.mkdir()
453            (eng / setup.EXE).write_bytes(b"engine")
454            if vexe:
455                (eng / setup.VEXE).write_bytes(b"vision")
456            src, vsrc = "S", "V"
457            (eng / "BUILD.json").write_text(json.dumps({"backend": "hip", "archs": ["gfx1201"], "src": src, **meta}))
458            built = []
459
460            def cmake_build(src_dir, bdir, target, defs, vcvars, bat):
461                built.append((target, defs))
462                (bdir / "bin").mkdir(parents=True)
463                (bdir / "bin" / setup.VEXE).write_bytes(b"vision")
464
465            with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "cmake_build", cmake_build), \
466                    mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, False)), \
467                    mock.patch.object(setup, "source_hash", lambda paths: vsrc if paths == setup.VISION_SOURCES else src):
468                # an AVX2 CPU whatever the box has: on one without AVX2 (or one whose CPU flags cannot be read) the engine itself
469                # would be rebuilt with an ISA floor
470                quiet(setup.build_engine_hip, {"arch": "gfx1201"}, "llama", vision)
471            return built, json.loads((eng / "BUILD.json").read_text()), (eng / setup.VEXE).exists()
472
473    def test_the_cpu_encoder_is_built_once(self):
474        built, meta, have = self.build({}, "cpu")
475        self.assertEqual([t for t, _ in built], ["strata-vision"])
476        self.assertIn("-DSTRATA_VISION_CUDA=OFF", built[0][1])
477        self.assertIn("-DSTRATA_PORTABLE=OFF", built[0][1])            # built for this PC (#411: portable is the default)
478        self.assertEqual((meta["vision"], meta["vision_src"], have), ("cpu", "V", True))
479        built, meta, _ = self.build({"vision": "cpu", "vision_src": "V"}, "cpu", vexe=True)
480        self.assertEqual(built, [])                                    # built and unchanged: nothing to do
481        built, meta, _ = self.build({"vision": "cpu", "vision_src": "old"}, "cpu", vexe=True)
482        self.assertEqual([t for t, _ in built], ["strata-vision"])     # its source changed: again
483
484    def test_without_images_nothing_changes(self):
485        built, meta, have = self.build({}, "none")
486        self.assertEqual((built, have), ([], False))
487        self.assertNotIn("vision_src", meta)
488
489
490class RotationalDisk(unittest.TestCase):
491    """#605: a model on a rotational disk gets --ple-io ram when the n-gram table fits the RAM, else a warning."""
492
493    def install(self, ram, disk, platform_ok=False, model="Q2_0"):
494        from test_setup_golden import PROFILES, install
495        _, found = PROFILES["64GB-1x32GB"]
496        return install(ram, found, ["--family", "qwen", "--model", model, "--no-start"],
497                       extra=[mock.patch.object(setup, "rotational_disk", lambda p: disk),
498                              mock.patch.object(setup, "ple_ram_platform_ok", lambda: platform_ok)])
499
500    def test_fits(self):
501        code, out, cfg, _ = self.install(127.8, "sdb")
502        self.assertEqual(code, 0, out)
503        a = cfg["args"]
504        self.assertEqual(a[a.index("--ple-io") + 1], "ram")
505        self.assertIn("rotational disk (sdb)", out)
506
507    def test_does_not_fit(self):
508        code, out, cfg, _ = self.install(63.7, "sdb")
509        self.assertEqual(code, 0, out)
510        self.assertNotIn("--ple-io", cfg["args"])
511        self.assertIn("An SSD is recommended", out)
512
513    def test_ssd(self):
514        code, out, cfg, _ = self.install(127.8, None)
515        self.assertNotIn("--ple-io", cfg["args"])
516        self.assertNotIn("rotational", out)
517
518    def test_ssd_ram_to_spare(self):
519        # 147-verify (Linux): an SSD and RAM beyond the model's need + the table + 16 GB: the table in RAM too
520        code, out, cfg, _ = self.install(127.8, None, platform_ok=True)
521        self.assertEqual(code, 0, out)
522        a = cfg["args"]
523        self.assertEqual(a[a.index("--ple-io") + 1], "ram")
524        self.assertIn("kept in RAM (--ple-io ram)", out)
525        self.assertNotIn("rotational", out)
526
527    def test_ssd_little_ram_keeps_the_ssd(self):
528        # Q2_0 needs 48 GB + the 28.8 GB table + 16: a 64 GB / 92 GB PC keeps the SSD reads
529        for ram in (63.7, 92.0):
530            code, out, cfg, _ = self.install(ram, None, platform_ok=True)
531            self.assertEqual(code, 0, out)
532            self.assertNotIn("--ple-io", cfg["args"])
533
534    def test_ssd_ram_rule_follows_the_model(self):
535        # IQ3_S needs 62 GB: 96 GB is not enough to spare the table, 128 GB is
536        for ram, want in ((95.8, False), (127.8, True)):
537            code, out, cfg, _ = self.install(ram, None, platform_ok=True, model="IQ3_S")
538            self.assertEqual(code, 0, out)
539            self.assertEqual("--ple-io" in cfg["args"], want, (ram, cfg["args"]))
540
541    def test_sysfs(self):
542        if not sys.platform.startswith("linux"):
543            self.assertIsNone(setup.rotational_disk(__file__))   # Windows: never
544            return
545        self.assertIn(setup.rotational_disk(__file__), (None,) + tuple(os.listdir("/sys/block")))
546
547
548class VramReserve(unittest.TestCase):
549    """#493: --vram-reserve-mib N - VRAM the engine leaves free for other programs - goes into the config only when
550    given (the default config is tools/test_setup_golden.py's, unchanged), at setup and on a start."""
551
552    def setUp(self):
553        from test_setup_golden import PROFILES
554        self.ram, self.found = PROFILES["64GB-1x32GB"]
555
556    def install(self, *extra):
557        from test_setup_golden import install
558        return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra])
559
560    def test_given_at_setup(self):
561        code, out, cfg, _ = self.install("--vram-reserve-mib", "2048")
562        self.assertEqual(code, 0, out)
563        a = cfg["args"]
564        self.assertEqual(a.count("--vram-reserve-mib"), 1)
565        self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "2048")
566        self.assertIn("VRAM kept free for other programs: 2048 MiB", out)
567        code, out, cfg, _ = self.install("--vision", "no")
568        self.assertNotIn("--vram-reserve-mib", cfg["args"])          # not given: the engine's default, as before
569        code, out, cfg, _ = self.install("--vision", "cpu")
570        self.assertNotIn("--vram-reserve-mib", cfg["args"])          # the CPU reader needs no reserve
571        code, out, cfg, _ = self.install()
572        self.assertEqual(cfg["args"][cfg["args"].index("--vram-reserve-mib") + 1], "700")   # pictures on by default, GPU reader on a 32 GB card: its 700 MiB
573
574    def test_with_images_one_value(self):
575        code, out, cfg, _ = self.install("--vision", "cpu", "--vram-reserve-mib", "1500")
576        self.assertEqual(code, 0, out)
577        a = cfg["args"]
578        self.assertEqual(a.count("--vram-reserve-mib"), 1)
579        self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "1500")
580
581    def test_a_negative_value_is_refused(self):
582        with contextlib.redirect_stderr(io.StringIO()) as err:
583            code, out, cfg, _ = self.install("--vram-reserve-mib", "-1")
584        self.assertEqual(code, 2)
585        self.assertIn("--vram-reserve-mib takes a number of MiB", err.getvalue())
586
587    def test_kept_from_an_earlier_install(self):
588        with tempfile.TemporaryDirectory() as d:
589            p = Path(d) / "strata-q2_0.json"
590            p.write_text(json.dumps({"args": ["--max-context", "8192", "--vram-reserve-mib", "2048"]}))
591            self.assertEqual(setup.choices_from_config(p)["vram_reserve_mib"], 2048)
592            p.write_text(json.dumps({"args": ["--vision", "--vram-reserve-mib", "700"], "vision": {"gpu": True}}))
593            self.assertIsNone(setup.choices_from_config(p)["vram_reserve_mib"])   # the images' own reserve
594            p.write_text(json.dumps({"args": ["--max-context", "8192"]}))
595            self.assertIsNone(setup.choices_from_config(p)["vram_reserve_mib"])
596
597    def test_given_on_a_start(self):
598        with tempfile.TemporaryDirectory() as d:
599            exe = Path(d) / "strata.exe"
600            exe.write_bytes(b"")
601            p = Path(d) / "strata-q2_0.json"
602            p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True}))
603            call = mock.Mock(return_value=0)
604            with mock.patch.object(setup, "gpus", lambda: self.found), \
605                    mock.patch.object(setup, "is_wsl", lambda: False), \
606                    mock.patch.object(setup, "ensure_engine_for", lambda cards, path, cfg, yes: cfg), \
607                    mock.patch.object(setup.subprocess, "call", call):
608                for n in ("2048", "1024"):
609                    _, out = quiet(setup.start, p, None, None, False, True, None, {"vram_reserve_mib": int(n)})
610                    self.assertEqual(json.loads(p.read_text())["args"], ["--kv", "int8", "--vram-reserve-mib", n])
611        self.assertIn("1024 MiB of VRAM kept free", out)
612        self.assertTrue(call.called)
613
614
615class SmallCardTip(unittest.TestCase):
616    """#496: a card under 8 GB (a 6 GB laptop RTX 3060) gets a tip for when the start has no room for the expert cache;
617    the engine chooses its own reserve there, so the config is the one any card gets.  An 8 GB card: no tip."""
618
619    def install(self, vram, *extra):
620        from test_setup_golden import card, install
621        return install(63.7, [card(0, "NVIDIA GeForce RTX 3060 Laptop GPU", vram, "86")],
622                       ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra])
623
624    def test_a_6gb_card(self):
625        code, out, cfg, _ = self.install(6.0)
626        self.assertEqual(code, 0, out)
627        self.assertNotIn("--vram-reserve-mib", cfg["args"])          # the engine decides (no fixed reserve)
628        self.assertIn("no VRAM is left for the expert cache", out)
629        self.assertIn("--draft-vocab en", out)
630        self.assertIn("--mtp", cfg["args"])                          # the draft layer stays: the server needs it
631
632    def test_an_8gb_card_has_no_tip(self):
633        for vram in (8188 / 1024, 8.0):                               # nvidia-smi lists an 8 GB card as 8188 MiB
634            code, out, cfg, _ = self.install(vram)
635            self.assertEqual(code, 0, out)
636            self.assertNotIn("no VRAM is left for the expert cache", out)
637            self.assertNotIn("--vram-reserve-mib", cfg["args"])
638
639    def test_a_given_reserve_is_kept(self):
640        code, out, cfg, _ = self.install(6.0, "--vram-reserve-mib", "500")
641        self.assertEqual(code, 0, out)
642        a = cfg["args"]
643        self.assertEqual(a[a.index("--vram-reserve-mib") + 1], "500")
644
645    def test_the_tip(self):
646        self.assertIn("an 8K context", " ".join(setup.small_card_note(32768, None)))
647        self.assertIn("--draft-vocab en", " ".join(setup.small_card_note(32768, "cjk")))
648        tip = " ".join(setup.small_card_note(8192, "en"))
649        self.assertNotIn("--draft-vocab", tip)
650        self.assertIn("close other programs", tip)
651
652
653class DesktopReserveTip(unittest.TestCase):
654    """#560 #516: an AMD card on a Linux desktop gets a recommended reserve (3072 MiB) - a tip, the config is not
655    changed."""
656
657    def test_desktop_detection(self):
658        with mock.patch.object(setup.sys, "platform", "linux"):
659            self.assertTrue(setup.linux_desktop({"WAYLAND_DISPLAY": "wayland-0"}))
660            self.assertTrue(setup.linux_desktop({"DISPLAY": ":0"}))
661            self.assertFalse(setup.linux_desktop({}))                 # a headless box / ssh
662        with mock.patch.object(setup.sys, "platform", "win32"):
663            self.assertFalse(setup.linux_desktop({"DISPLAY": ":0"}))  # Windows counts the desktop itself (#497)
664
665    def test_the_tip(self):
666        tip = " ".join(setup.desktop_reserve_note())
667        self.assertIn("--vram-reserve-mib 3072", tip)
668        self.assertIn("desktop", tip)
669
670
671class CudaVision(unittest.TestCase):
672    """#411: the image encoder setup compiles beside the CUDA engine is built for this PC, not portable."""
673
674    def test_the_encoder_is_built_native(self):
675        for vision in ("gpu", "cpu"):
676            with self.subTest(vision), tempfile.TemporaryDirectory() as d:
677                root = Path(d)
678                eng = root / "engine"
679                eng.mkdir()
680                (eng / setup.EXE).write_bytes(b"engine")                 # the engine is built: only the encoder
681                (eng / "BUILD.json").write_text(json.dumps({"source": "local", "archs": [86], "src": "S"}))
682                built = []
683
684                def cmake_build(src_dir, bdir, target, defs, vcvars, bat):
685                    built.append((target, defs))
686                    (bdir / "bin").mkdir(parents=True)
687                    (bdir / "bin" / setup.VEXE).write_bytes(b"vision")
688
689                with mock.patch.object(setup, "ROOT", root), mock.patch.object(setup, "cmake_build", cmake_build), \
690                        mock.patch.object(setup, "source_hash", lambda p: "V" if p == setup.VISION_SOURCES else "S"), \
691                        mock.patch.object(setup, "install_build_tools", lambda gpu, yes: (str(root / "nvcc"), None)), \
692                        mock.patch.object(setup, "gpus", lambda: []), \
693                        mock.patch.object(setup, "cpu_info", lambda: ("Test CPU", True, False)), \
694                        mock.patch.object(setup, "source_version", lambda: "test"):      # no real card of the box (#4662), an AVX2 CPU
695                    quiet(setup.build_engine, {"arch": "86"}, vision, True, "llama")
696                self.assertEqual([t for t, _ in built], ["strata-vision"])
697                self.assertIn("-DSTRATA_PORTABLE=OFF", built[0][1])
698                self.assertIn(f"-DSTRATA_VISION_CUDA={'ON' if vision == 'gpu' else 'OFF'}", built[0][1])
699
700
701class ProxyHint(unittest.TestCase):
702    """0.2.10: a download that cannot reach its server says what to do behind a proxy."""
703
704    def test_the_hint_names_the_variable_and_notices_one_already_set(self):
705        names = ("HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy")
706        with mock.patch.dict(os.environ, {}, clear=False):
707            for n in names:
708                os.environ.pop(n, None)
709            self.assertIn("set HTTPS_PROXY", setup.proxy_hint())
710            os.environ["HTTPS_PROXY"] = "http://user:secret@proxy:3128"
711            hint = setup.proxy_hint()
712            self.assertIn("a proxy is set", hint)
713            self.assertNotIn("secret", hint)
714
715
716class SwiftIq3s(unittest.TestCase):
717    """#1651: Swift 1.5 has its own IQ3_S tier since 2026-10-08 (ukisai's Swift-1.5 GGUF repo) - the model choice
718    must not hide it behind the qwen family.  Names and sizes checked against the Hub listing when written."""
719
720    def test_iq3_s_is_a_swift_choice(self):
721        self.assertIn("swift", setup.MODELS["IQ3_S"].get("families", ("qwen", "swift")))
722
723    def test_the_published_file_names(self):
724        fam = setup.FAMILIES["swift"]
725        self.assertEqual(setup.model_shards(fam, "IQ3_S"), 2)
726        self.assertEqual([setup.model_file(fam, "IQ3_S", i) for i in (1, 2)],
727                         ["Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf",
728                          "Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf"])
729
730
731class HostCompilers(unittest.TestCase):
732    """#1645: CC / CXX / CUDAHOSTCXX name the build's compilers - handed to CMake as -D, so a build folder that is
733    already configured picks them up too (CXX alone reaches CMake only on the first configure: the reporter's
734    `CXX=g++-14` run died at the last step).  CUDAHOSTCXX is nvcc's host compiler and defaults to CXX."""
735
736    def test_env_names_the_compilers(self):
737        with mock.patch.dict(os.environ, {"CC": "gcc-14", "CXX": "g++-14", "CUDAHOSTCXX": "g++-14-alt"}):
738            self.assertEqual(setup.host_compiler_defs(True), ["-DCMAKE_C_COMPILER=gcc-14",
739                                                              "-DCMAKE_CXX_COMPILER=g++-14",
740                                                              "-DCMAKE_CUDA_HOST_COMPILER=g++-14-alt"])
741
742    def test_cudahostcxx_defaults_to_cxx_and_needs_cuda(self):
743        with mock.patch.dict(os.environ, {"CC": "", "CXX": "g++-14", "CUDAHOSTCXX": ""}):
744            self.assertEqual(setup.host_compiler_defs(True), ["-DCMAKE_CXX_COMPILER=g++-14",
745                                                              "-DCMAKE_CUDA_HOST_COMPILER=g++-14"])
746            self.assertEqual(setup.host_compiler_defs(False), ["-DCMAKE_CXX_COMPILER=g++-14"])   # a C++-only project
747
748    def test_unset_adds_nothing(self):
749        with mock.patch.dict(os.environ, {"CC": "", "CXX": "", "CUDAHOSTCXX": ""}):
750            self.assertEqual(setup.host_compiler_defs(True), [])
751
752    def test_the_defs_reach_cmake(self):
753        """The engine's and the CUDA encoder's configure both take them."""
754        with tempfile.TemporaryDirectory() as d:
755            root = Path(d)
756            eng = root / "engine"
757            eng.mkdir()
758            (eng / "BUILD.json").write_text(json.dumps({"source": "local", "archs": [86], "src": "old"}))
759            built = []
760
761            def cmake_build(src_dir, bdir, target, defs, vcvars, bat):
762                built.append((target, defs))
763                (bdir / "bin").mkdir(parents=True, exist_ok=True)
764                (bdir / "bin" / setup.VEXE).write_bytes(b"vision")
765                (bdir / setup.EXE).write_bytes(b"engine")
766
767            env = {"CC": "gcc-14", "CXX": "g++-14", "CUDAHOSTCXX": ""}
768            with mock.patch.dict(os.environ, env), mock.patch.object(setup, "ROOT", root), \
769                    mock.patch.object(setup, "cmake_build", cmake_build), \
770                    mock.patch.object(setup, "source_hash", lambda p: "V" if p == setup.VISION_SOURCES else "new"), \
771                    mock.patch.object(setup, "install_build_tools", lambda gpu, yes: (str(root / "nvcc"), None)), \
772                    mock.patch.object(setup, "source_version", lambda: "test"):
773                quiet(setup.build_engine, {"arch": "86"}, "gpu", True, "llama")
774        for target, defs in built:
775            self.assertIn("-DCMAKE_CXX_COMPILER=g++-14", defs, target)
776            self.assertIn("-DCMAKE_CUDA_HOST_COMPILER=g++-14", defs, target)
777
778
779if __name__ == "__main__":
780    unittest.main()
781
782
783class CalibrateWithModel(unittest.TestCase):
784    """#2036: --calibrate --model X tunes model X (it used to fall through to a plain re-setup); a model that is not
785    installed is an error that says so; --calibrate with --setup or --check says it does nothing."""
786
787    def run_main(self, *argv, installed=("iq3_xxs", "q2_0")):
788        tmp = tempfile.TemporaryDirectory()
789        self.addCleanup(tmp.cleanup)
790        cfgs = []
791        for tag in installed:
792            p = Path(tmp.name) / f"strata-{tag}.json"
793            p.write_text(json.dumps({"exe": "x", "args": ["--max-context", "8192"], "model_name": tag}))
794            cfgs.append(p)
795        tuned = []
796        with mock.patch.object(sys, "argv", ["setup.py", *argv]), \
797                mock.patch.object(setup, "installed_configs", lambda: cfgs), \
798                mock.patch.object(setup, "update_installed_engine", lambda *a, **k: None), \
799                mock.patch.object(setup, "calibrate_config", lambda c: tuned.append(c.name) or True), \
800                mock.patch.object(setup, "start", lambda *a, **k: 0), \
801                mock.patch.object(setup, "data_folder", lambda d, *a, **k: (Path(tmp.name), [])), \
802                mock.patch.object(setup, "step", side_effect=SystemExit("reached the plain setup")):
803            try:
804                code, out = quiet(setup.main)
805            except SystemExit as e:
806                code, out = e.code, ""
807        return code, tuned
808
809    def test_model_is_the_target(self):
810        code, tuned = self.run_main("--calibrate", "--model", "IQ3_XXS", "--yes", "--no-start")
811        self.assertEqual((code, tuned), (0, ["strata-iq3_xxs.json"]))
812
813    def test_a_model_not_installed_is_an_error(self):
814        code, tuned = self.run_main("--calibrate", "--model", "IQ3_S", "--yes", "--no-start")
815        self.assertEqual((code, tuned), (1, []))
816
817    def test_targets(self):
818        with tempfile.TemporaryDirectory() as d:
819            ps = []
820            for tag in ("iq3_xxs", "q2_0"):
821                p = Path(d) / f"strata-{tag}.json"
822                p.write_text(json.dumps({"args": []}))
823                ps.append(p)
824            self.assertEqual(setup.calibration_targets(ps, None, None), ps)
825            self.assertEqual(setup.calibration_targets(ps, "Q2_0", None), [ps[1]])
826            self.assertEqual(setup.calibration_targets(ps, "Q2_0", "qwen"), [ps[1]])
827            self.assertEqual(setup.calibration_targets(ps, "Q4_K_M", None), [])