okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
19.0 KiB343 linesraw
1"""The picture files of a model that is already installed (strata_control/pictures.py): found or downloaded once, the data folder and the model's
2other files left exactly as they are, no internet answered in a sentence, and the run config's ``vision`` section worked out for the engine in use.
3
4The file is pinned (size and SHA-256), so the tests swap in a tiny pinned file of their own and a folder on disk for the download address."""
5
6from __future__ import annotations
7
8import hashlib
9import io
10import json
11import os
12import sys
13import tempfile
14import unittest
15from contextlib import redirect_stdout
16from pathlib import Path
17from unittest import mock
18
19import setup
20from strata_control import acquisition, pictures
21
22ROOT = Path(__file__).resolve().parents[2]
23BODY = b"mmproj-bytes-" * 5000
24TINY = pictures.Projector("mmproj-Tiny.gguf", len(BODY), hashlib.sha256(BODY).hexdigest(), "owner/repo", "rev1")
25NAME = TINY.name
26
27
28def tree(root: Path) -> dict:
29    """Every file under root with its size and modified time: what must not change."""
30    out = {}
31    for p in sorted(root.rglob("*")):
32        if p.is_file():
33            st = p.stat()
34            out[p.relative_to(root).as_posix()] = (st.st_size, st.st_mtime_ns)
35    return out
36
37
38class Layout:
39    """A model in its own folder (not <data>/models/<tag>) with its pack and draft layer in a data folder that is not the models folder."""
40
41    def __init__(self, base: Path, *, ordinary: bool = False, with_vision: bool = False):
42        self.base = base
43        self.data = base / ("Strata-data" if ordinary else "own-data")
44        self.model_dir = (self.data / "models" / "IQ3_S") if ordinary else (base / "downloads" / "IQ3_S")
45        self.model_dir.mkdir(parents=True)
46        self.gguf = self.model_dir / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf"
47        self.gguf.write_bytes(b"GGUF")
48        (self.model_dir / "Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf").write_bytes(b"GGUF")
49        self.pack = self.data / "packs" / "iq3_s"
50        (self.pack / "tokenizer").mkdir(parents=True)
51        (self.pack / "native_experts.txt").write_text("x")
52        self.mtp = self.data / "mtp" / "rt"
53        self.mtp.mkdir(parents=True)
54        (self.mtp / "experts.bin").write_bytes(b"e")
55        (self.data / "mtp" / "mtp-q2_0.gguf").write_bytes(b"m")
56        self.engine = base / "engine"
57        self.engine.mkdir()
58        exe = "strata-vision.exe" if os.name == "nt" else "strata-vision"
59        (self.engine / exe).write_bytes(b"x")
60        self.reader = self.engine / exe
61        self.config = base / "install" / "strata-iq3_s.json"
62        self.config.parent.mkdir()
63        cfg = {"exe": "component:strata-engine", "model_name": "qwen3.8-flash-next-iq3_s",
64               "args": ["--pack", str(self.pack), "--native", str(self.gguf), "--mtp", str(self.mtp), "--max-context", "8192"]}
65        if with_vision:
66            cfg["vision"] = {"exe": str(self.reader), "mmproj": str(self.data / "models" / NAME), "model": str(self.gguf), "gpu": False, "max_tokens": 450}
67        self.config.write_text(json.dumps(cfg))
68        self.mirror = base / "mirror"
69        served = self.mirror / "owner" / "repo" / "resolve" / "rev1"
70        served.mkdir(parents=True)
71        (served / NAME).write_bytes(BODY)
72
73    def fetch(self, **kw):
74        kw.setdefault("engine_dir", self.engine)
75        kw.setdefault("hardware", {"vram_gb": 12, "make": "nvidia", "arch": 120})
76        kw.setdefault("endpoint", self.mirror.as_uri())
77        kw.setdefault("online", lambda url: True)
78        with mock.patch.dict(pictures.PROJECTOR_BY_FAMILY, {"qwen": TINY}), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": ""}):
79            return pictures.fetch(self.config, **kw)
80
81
82class FetchInOwnFolder(unittest.TestCase):
83    def setUp(self):
84        self._tmp = tempfile.TemporaryDirectory()
85        self.addCleanup(self._tmp.cleanup)
86        self.base = Path(self._tmp.name)
87
88    def test_the_file_goes_to_the_data_folder_of_the_run_config_and_nothing_else_changes(self):
89        lay = Layout(self.base)
90        before = tree(lay.data) | {f"gguf/{k}": v for k, v in tree(lay.model_dir).items()}
91        cfg_before = lay.config.read_bytes()
92        seen = []
93        result = lay.fetch(progress=lambda step, d, t: seen.append((step, d, t)))
94        self.assertTrue(result["fetched"])
95        self.assertEqual(Path(result["mmproj"]), lay.data / "models" / NAME, "beside the pack and draft layer the model uses, not the app's models folder")
96        self.assertEqual(result["data_dir"], str(lay.data))
97        self.assertEqual((lay.data / "models" / NAME).read_bytes(), BODY)
98        self.assertFalse((lay.data / "models" / (NAME + ".part")).exists())
99        self.assertIn("Downloading the picture files…", [s for s, _d, _t in seen])
100        after = tree(lay.data) | {f"gguf/{k}": v for k, v in tree(lay.model_dir).items()}
101        added = sorted(set(after) - set(before))
102        self.assertEqual(added, [f"models/{NAME}", f"models/{NAME}.done"], "only the picture file and its finish mark")
103        for key, value in before.items():
104            self.assertEqual(after[key], value, f"{key} was left alone")
105        self.assertEqual(lay.config.read_bytes(), cfg_before, "the run config is the caller's to write")
106        self.assertFalse((self.base / "Strata-data").exists(), "no second data folder")
107
108    def test_the_section_is_the_one_setup_writes_for_this_card(self):
109        lay = Layout(self.base)
110        small = lay.fetch(hardware={"vram_gb": 12, "make": "nvidia", "arch": 120})["vision"]
111        self.assertEqual((small["gpu"], small["max_tokens"]), (False, 300), "under 24 GB the CPU reader")
112        self.assertEqual(small["exe"], str(lay.reader))
113        self.assertEqual(small["model"], str(lay.gguf))
114        self.assertEqual(small["mmproj"], str(lay.data / "models" / NAME))
115        self.assertGreaterEqual(small["threads"], 1)
116        big = lay.fetch(hardware={"vram_gb": 48, "make": "nvidia", "arch": 86})["vision"]
117        self.assertEqual((big["gpu"], big["max_tokens"]), (True, 1024), "from 24 GB the GPU reader")
118        self.assertNotIn("threads", big)
119        cpu = lay.fetch(asked="cpu", hardware={"vram_gb": 48, "make": "nvidia", "arch": 86})["vision"]
120        self.assertFalse(cpu["gpu"], "what the person asked for is kept")
121
122    def test_a_copy_already_on_the_computer_is_used_where_it_is(self):
123        lay = Layout(self.base)
124        lay.model_dir.parent.joinpath(NAME).write_bytes(BODY)       # one folder up from the model files: the repository layout
125        result = lay.fetch(online=lambda url: self.fail("no network for a file that is here"))
126        self.assertFalse(result["fetched"])
127        self.assertEqual(Path(result["mmproj"]), lay.model_dir.parent / NAME)
128        self.assertFalse((lay.data / "models").exists(), "nothing is written")
129
130    def test_a_copy_with_the_wrong_bytes_is_not_used_and_not_deleted(self):
131        lay = Layout(self.base)
132        wrong = lay.data / "models" / NAME
133        wrong.parent.mkdir()
134        wrong.write_bytes(b"x" * len(BODY))                          # right size, wrong content
135        result = lay.fetch()
136        self.assertTrue(result["fetched"], "downloaded because the copy there is not the pinned file")
137        self.assertEqual(wrong.read_bytes(), BODY, "the bad copy was replaced by the checked download")
138
139    def test_the_path_the_run_config_names_is_kept_when_its_folder_is_there(self):
140        lay = Layout(self.base, with_vision=True)
141        named = Path(json.loads(lay.config.read_text())["vision"]["mmproj"])
142        named.parent.mkdir(parents=True, exist_ok=True)
143        result = lay.fetch()
144        self.assertEqual(Path(result["mmproj"]), named)
145        self.assertEqual(result["vision"]["max_tokens"], 450, "what the person set for the same reader is kept")
146        cfg = json.loads(lay.config.read_text())
147        cfg["vision"]["gpu"] = True                                  # an earlier value for the other reader does not carry over
148        lay.config.write_text(json.dumps(cfg))
149        self.assertEqual(lay.fetch()["vision"]["max_tokens"], 300)
150
151    def test_an_ordinary_install_keeps_the_file_in_its_own_models_folder(self):
152        lay = Layout(self.base, ordinary=True)
153        result = lay.fetch()
154        self.assertEqual(Path(result["mmproj"]), lay.data / "models" / NAME)
155        self.assertEqual(result["data_dir"], str(lay.data))
156
157    def test_the_data_folder_from_the_caller_is_used_when_the_config_names_none(self):
158        lay = Layout(self.base)
159        cfg = json.loads(lay.config.read_text())
160        cfg["args"] = ["--native", str(lay.gguf)]                    # no --pack, no --mtp: nothing says where the data folder is
161        lay.config.write_text(json.dumps(cfg))
162        elsewhere = self.base / "chosen"
163        elsewhere.mkdir()
164        result = lay.fetch(data_dir=elsewhere)
165        self.assertEqual(Path(result["mmproj"]), elsewhere / "models" / NAME)
166
167    def test_no_internet_is_a_sentence_after_one_short_probe_and_nothing_is_written(self):
168        lay = Layout(self.base)
169        before = tree(lay.base)
170        with self.assertRaises(pictures.PicturesError) as caught:
171            lay.fetch(online=lambda url: False)
172        self.assertEqual(caught.exception.code, "offline")
173        self.assertEqual(str(caught.exception), "There is no internet connection, so the picture files can't be downloaded now.")
174        self.assertEqual(tree(lay.base), before, "not even an empty file or folder")
175
176    def test_a_download_that_does_not_match_is_deleted_and_said(self):
177        lay = Layout(self.base)
178        (lay.mirror / "owner" / "repo" / "resolve" / "rev1" / NAME).write_bytes(b"y" * len(BODY))
179        with self.assertRaises(pictures.PicturesError) as caught:
180            lay.fetch()
181        self.assertEqual(caught.exception.code, "checksum")
182        self.assertFalse((lay.data / "models" / NAME).exists())
183        self.assertFalse((lay.data / "models" / (NAME + ".part")).exists())
184
185    def test_a_half_download_is_continued(self):
186        lay = Layout(self.base)
187        partial = lay.data / "models" / (NAME + ".part")
188        partial.parent.mkdir()
189        partial.write_bytes(BODY[:1000])
190        lay.fetch()
191        self.assertEqual((lay.data / "models" / NAME).read_bytes(), BODY)
192
193    def test_not_enough_disk_is_said_before_anything_is_fetched(self):
194        lay = Layout(self.base)
195        full = mock.Mock(free=10)
196        with mock.patch.object(pictures.shutil, "disk_usage", return_value=full), self.assertRaises(pictures.PicturesError) as caught:
197            lay.fetch(online=lambda url: self.fail("the space is checked first"))
198        self.assertEqual(caught.exception.code, "disk")
199        self.assertIn("1 GB", str(caught.exception))
200
201    def test_a_start_never_downloads(self):
202        lay = Layout(self.base)
203        with mock.patch.dict(pictures.PROJECTOR_BY_FAMILY, {"qwen": TINY}), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "1"}):
204            with self.assertRaises(acquisition.AcquisitionRefused):
205                pictures.fetch(lay.config, engine_dir=lay.engine, endpoint=lay.mirror.as_uri(), online=lambda url: True)
206        self.assertFalse((lay.data / "models").exists())
207
208    def test_a_model_this_step_does_not_know_is_left_alone(self):
209        lay = Layout(self.base)
210        cfg = json.loads(lay.config.read_text())
211        cfg["model_name"] = "qwen3.6-35b-a3b-ud-q4_k_xl"
212        lay.config.write_text(json.dumps(cfg))
213        with self.assertRaises(pictures.PicturesError) as caught:
214            lay.fetch()
215        self.assertEqual(caught.exception.code, "unsupported")
216        cfg.update({"model_name": "x", "arch": "deepseek41"})
217        lay.config.write_text(json.dumps(cfg))
218        with self.assertRaises(pictures.PicturesError) as caught:
219            lay.fetch()
220        self.assertEqual(caught.exception.code, "unsupported")
221
222    def test_an_engine_without_a_picture_reader_is_a_clear_answer(self):
223        lay = Layout(self.base)
224        lay.reader.unlink()
225        with self.assertRaises(pictures.PicturesError) as caught:
226            lay.fetch()
227        self.assertEqual(caught.exception.code, "no_reader")
228
229
230class Families(unittest.TestCase):
231    def test_the_family_comes_from_the_catalog_or_from_the_names(self):
232        g = Path("Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf")
233        self.assertEqual(pictures.family_of({}, g, "swift"), "swift")
234        self.assertEqual(pictures.family_of({}, g, "qwen36"), None)
235        self.assertEqual(pictures.family_of({}, g, "nvfp4"), None)
236        self.assertEqual(pictures.family_of({"model_name": "iq3_s"}, g), "qwen", "a hand-made name still gets the original's file")
237        self.assertEqual(pictures.family_of({"model_name": "swift-1.5-iq3_s"}, g), "swift")
238        self.assertEqual(pictures.family_of({}, Path("Swift-Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf")), "swift")
239        self.assertIsNone(pictures.family_of({"model_name": "qwen3.6-35b-a3b-q8_0"}, Path("Qwen3.6-35B-A3B-Q8_0.gguf")))
240        self.assertIsNone(pictures.family_of({"arch": "deepseek41"}, None))
241
242    def test_the_pins_are_the_ones_setup_downloads(self):
243        for name, projector, repo in (("qwen", pictures.QWEN, "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF"), ("swift", pictures.SWIFT, "ukisai/Swift-1.5-Qwen3.8-Flash-Next-GSQ-RCO-GGUF")):
244            fam = setup.FAMILIES[name]
245            self.assertEqual(projector.name, fam["mmproj"])
246            self.assertEqual(projector.repo, repo)
247            self.assertEqual(projector.revision, setup.HF_REVISIONS[repo])
248            self.assertEqual(fam["mmproj_hf"], f"{setup.hf_endpoint()}/{repo}/resolve/{projector.revision}/")
249            pins = {**setup.ISTA_FILES, **setup.SWIFT_FILES}[projector.name]
250            self.assertEqual((projector.size, projector.sha256), tuple(pins))
251        for name in ("coder", "unsloth", "gyro"):
252            self.assertEqual(setup.FAMILIES[name]["mmproj"], pictures.PROJECTOR_BY_FAMILY[name].name, name)
253            self.assertEqual(tuple(setup.CODER_FILES[pictures.QWEN.name]), (pictures.QWEN.size, pictures.QWEN.sha256), "the Coder's file is the original's")
254
255    def test_the_address_follows_hf_endpoint_like_setup(self):
256        with mock.patch.dict(os.environ, {"HF_ENDPOINT": "http://127.0.0.1:9/"}):
257            self.assertEqual(pictures.QWEN.url(), f"http://127.0.0.1:9/{pictures.QWEN.repo}/resolve/{pictures.QWEN.revision}/{pictures.QWEN.name}")
258        with mock.patch.dict(os.environ, {"HF_ENDPOINT": ""}):
259            self.assertTrue(pictures.QWEN.url().startswith("https://huggingface.co/"))
260
261
262class RunFolder(unittest.TestCase):
263    def foot(self, *args):
264        from strata_control import discovery
265        return discovery.footprint({"args": list(args)})
266
267    def test_the_folder_comes_from_where_the_pack_and_the_draft_layer_are(self):
268        self.assertEqual(pictures.run_folder(self.foot("--pack", "/d/packs/iq3_s", "--native", "/other/IQ3_S/a.gguf")), Path("/d"))
269        self.assertEqual(pictures.run_folder(self.foot("--mtp", "/x/mtp/rt", "--native", "/other/a.gguf")), Path("/x"))
270        self.assertEqual(pictures.run_folder(self.foot("--native", "/data/models/IQ3_S/a.gguf")), Path("/data"))
271
272    def test_a_pack_in_a_folder_of_another_shape_says_nothing_about_the_data_folder(self):
273        self.assertIsNone(pictures.run_folder(self.foot("--pack", "/d/my-pack", "--native", "/other/IQ3_S/a.gguf")))
274        self.assertIsNone(pictures.run_folder(self.foot("--mtp", "/x/draft", "--native", "/other/a.gguf")))
275        self.assertIsNone(pictures.run_folder(self.foot("--mtp", "7")), "a draft depth is not a folder")
276
277
278class ReaderRule(unittest.TestCase):
279    def setUp(self):
280        self._tmp = tempfile.TemporaryDirectory()
281        self.addCleanup(self._tmp.cleanup)
282        self.engine = Path(self._tmp.name)
283        self.cpu = "strata-vision.exe" if os.name == "nt" else "strata-vision"
284        self.hip = "strata-vision-hip.exe" if os.name == "nt" else "strata-vision-hip"
285
286    def make(self, *names, build=None):
287        for n in names:
288            (self.engine / n).write_bytes(b"x")
289        if build is not None:
290            (self.engine / "BUILD.json").write_text(json.dumps(build))
291
292    def section(self, asked="yes", **hw):
293        return pictures.reader_section(self.engine, Path("/m/mm.gguf"), Path("/m/a.gguf"), asked, hw)
294
295    def test_amd_gets_the_gpu_reader_with_the_cpu_one_behind_it_from_24_gb(self):
296        self.make(self.cpu, self.hip, build={"vision_archs": "gfx1201;gfx1100"})
297        s, _ = self.section(vram_gb=32, make="amd", arch="gfx1201")
298        self.assertEqual((s["gpu"], Path(s["exe"]).name, Path(s["cpu_exe"]).name), (True, self.hip, self.cpu))
299        s, _ = self.section(vram_gb=16, make="amd", arch="gfx1201")
300        self.assertEqual((s["gpu"], Path(s["exe"]).name), (False, self.cpu), "a 16 GB card reads on the CPU")
301        s, note = self.section("gpu", vram_gb=32, make="amd", arch="gfx1030")
302        self.assertFalse(s["gpu"])
303        self.assertIn("gfx1030", note)
304
305    def test_nvidia_reader_the_build_has_no_code_for_runs_on_the_cpu(self):
306        self.make(self.cpu, build={"vision_archs": "86;89", "ptx": False})
307        s, note = self.section("gpu", vram_gb=48, make="nvidia", arch=75)
308        self.assertFalse(s["gpu"])
309        self.assertIn("sm_75", note)
310        s, _ = self.section("gpu", vram_gb=48, make="nvidia", arch=86)
311        self.assertTrue(s["gpu"])
312
313    def test_off_and_no_reader(self):
314        self.make()
315        self.assertEqual(self.section("yes", vram_gb=12, make="nvidia")[0], None)
316        self.make(self.cpu)
317        self.assertIsNone(pictures.reader_section(self.engine, Path("m"), Path("g"), "no", {})[0])
318
319
320class Command(unittest.TestCase):
321    def test_the_command_speaks_json_lines_and_exits_with_the_sentence(self):
322        with tempfile.TemporaryDirectory() as tmp:
323            lay = Layout(Path(tmp))
324            out = io.StringIO()
325            with mock.patch.dict(pictures.PROJECTOR_BY_FAMILY, {"qwen": TINY}), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "", "HF_ENDPOINT": ""}), \
326                    mock.patch.object(pictures, "_online", return_value=False), redirect_stdout(out):
327                code = pictures.main(["fetch", "--config", str(lay.config), "--engine-dir", str(lay.engine), "--vision", "yes", "--vram-gb", "12", "--make", "nvidia", "--arch", "120"])
328            self.assertEqual(code, 5)
329            last = json.loads(out.getvalue().strip().splitlines()[-1])
330            self.assertEqual(last["ok"], False)
331            self.assertEqual(last["error"]["code"], "offline")
332            out = io.StringIO()
333            with mock.patch.dict(pictures.PROJECTOR_BY_FAMILY, {"qwen": TINY}), mock.patch.dict(os.environ, {"STRATA_NO_ACQUIRE": "", "HF_ENDPOINT": lay.mirror.as_uri()}), \
334                    mock.patch.object(pictures, "_online", return_value=True), redirect_stdout(out):
335                code = pictures.main(["fetch", "--config", str(lay.config), "--engine-dir", str(lay.engine), "--vram-gb", "12", "--make", "nvidia", "--arch", "120"])
336            lines = [json.loads(line) for line in out.getvalue().strip().splitlines()]
337            self.assertEqual(code, 0, lines[-1])
338            self.assertEqual([l["event"] for l in lines[:-1]], ["progress"] * (len(lines) - 1))
339            self.assertTrue(lines[-1]["ok"] and lines[-1]["event"] == "result" and lines[-1]["fetched"])
340
341
342if __name__ == "__main__":
343    unittest.main()