okami.mom/strata

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

Niko1221Merge f-clean-2 (c94ef2375): drafting and plan test fixtures no longer read the box's real Intel GPU (9 failures on the Arc box)6a7187997

main
20.7 KiB418 linesraw
1"""0.2.2 flow walk, second round (phaseA-tests/flow-findings-022.md): what `strata launch` says and does with your own model files, the
2plan, the download figure, the long silent step and a tuning result that already exists."""
3
4from __future__ import annotations
5
6import json
7import os
8import tempfile
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from strata_cli.launch import settings as S
14from strata_cli.launch.catalog import Catalog
15from strata_cli.launch.runner import LaunchError, Runner
16from tests.terminal.launch_support import HW_12, Home, run_cli
17from tests.terminal.test_own_files import IQ3XXS, Q2, gguf_bytes
18
19
20class Base(unittest.TestCase):
21    def setUp(self):
22        self.home = Home().__enter__()
23        self.addCleanup(self.home.__exit__, None, None, None)
24        p = mock.patch.object(Catalog, "hardware", lambda self, fresh=False: dict(HW_12, disk_free_gb=500.0))
25        p.start()
26        self.addCleanup(p.stop)
27        self.tmp = tempfile.TemporaryDirectory(prefix="strata-flow2-")
28        self.addCleanup(self.tmp.cleanup)
29        self.base = Path(self.tmp.name)
30
31    def files(self, folder: Path, names: list[str], kind: str) -> Path:
32        folder.mkdir(parents=True, exist_ok=True)
33        for n in names:
34            (folder / n).write_bytes(gguf_bytes([kind]))
35        return folder
36
37    def runner(self, **kw) -> Runner:
38        return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12))
39
40
41class MissingOwnFiles(Base):
42    """Finding 2: a --model-path that is not there, or holds no model, is said in plain words before anything starts."""
43
44    def test_a_folder_that_does_not_exist_is_named_and_nothing_is_promised(self):
45        missing = self.base / "models"
46        code, out, err = run_cli(["launch", "--plan", "--model-path", str(missing)])
47        self.assertEqual(code, 2)
48        self.assertIn(f"This folder does not exist: {missing}", err)
49        self.assertNotIn("Qwen", err)
50        self.assertNotIn("continues where it stopped", err)
51        self.assertNotIn("could not be installed", err)
52
53    def test_a_missing_file_says_file(self):
54        code, out, err = run_cli(["launch", "--plan", "--model-path", str(self.base / "x-00001-of-00002.gguf")])
55        self.assertEqual(code, 2)
56        self.assertIn("This file does not exist", err)
57
58    def test_an_empty_folder_says_there_are_no_gguf_files(self):
59        empty = self.base / "empty"
60        empty.mkdir()
61        code, out, err = run_cli(["launch", "--plan", "--model", "q2_0", "--model-path", str(empty)])
62        self.assertEqual(code, 2)
63        self.assertIn("no .gguf model files", err)
64        self.assertIn("...-00001-of-00002.gguf", err)
65
66    def test_machine_output_carries_the_same_words(self):
67        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(self.base / "gone")])
68        self.assertEqual(code, 2)
69        self.assertIn("This folder does not exist", json.loads(out)["error"]["message"])
70
71    def test_the_engine_is_not_touched_for_a_wrong_path(self):
72        r = self.runner(model_path=str(self.base / "gone"))
73        with mock.patch.object(Runner, "ensure_engine", side_effect=AssertionError("engine step must not start")):
74            with self.assertRaises(LaunchError) as ctx:
75                r.run()
76        self.assertEqual(ctx.exception.code, 2)
77        self.assertIn("does not exist", ctx.exception.text)
78
79    def test_the_failure_hint_of_own_files_promises_no_download(self):
80        r = self.runner(model_path=str(self.files(self.base / "m", Q2, "Q2_0")), family="qwen", model="Q2_0")
81        proc = mock.Mock()
82        proc.stdout = iter(["=== Step 5: Getting the model files ===", "[X] missing /m/x.gguf"])
83        proc.wait.return_value = 1
84        with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None):
85            with self.assertRaises(LaunchError) as ctx:
86                r.ensure_model()
87        self.assertNotIn("download", ctx.exception.next)
88        self.assertIn("finished steps are skipped", ctx.exception.next)
89
90    def test_the_screens_say_the_same(self):
91        from strata_control import models
92        text, nxt = models.own_path_problem(str(self.base / "nope"))
93        self.assertIn("This folder does not exist", text)
94        self.assertIn("Nothing was downloaded", nxt)
95        self.assertIsNone(models.own_path_problem(str(self.files(self.base / "ok", IQ3XXS, "IQ3_XXS"))))
96
97    def test_a_folder_one_level_above_the_files_is_not_called_empty(self):
98        self.files(self.base / "repo" / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
99        from strata_control import models
100        self.assertIsNone(models.own_path_problem(str(self.base / "repo")))
101
102
103class LinkedShards(Base):
104    """Finding 3: shards that are links are accepted with no --model, as with --model, and a problem is said once."""
105
106    def links(self, names: list[str], real: bool = True) -> Path:
107        blobs = self.base / "blobs"
108        snap = self.base / "snap"
109        blobs.mkdir(exist_ok=True)
110        snap.mkdir(exist_ok=True)
111        for i, n in enumerate(names):
112            target = blobs / f"sha{i}"
113            if real:
114                target.write_bytes(gguf_bytes(["Q2_0"]))
115            try:
116                os.symlink(target, snap / n)
117            except (OSError, NotImplementedError):
118                self.skipTest("this account cannot create symbolic links")
119        return snap
120
121    def test_linked_shards_without_a_model_name_are_used(self):
122        snap = self.links(Q2)
123        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model-path", str(snap)])
124        self.assertEqual(code, 0, err or out)
125        s = json.loads(out)["plan"]["settings"]
126        self.assertEqual((s["family"], s["model"]), ("qwen", "Q2_0"))
127        self.assertEqual(Path(s["model_path"]), snap)                       # the link names stay (the shard names are what setup reads)
128
129    def test_linked_shards_with_the_model_named_give_the_same_folder(self):
130        snap = self.links(Q2)
131        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--model-path", str(snap)])
132        self.assertEqual(code, 0, err or out)
133        self.assertEqual(Path(json.loads(out)["plan"]["settings"]["model_path"]), snap)
134
135    def test_links_to_nothing_are_one_sentence_not_one_per_file(self):
136        snap = self.links(Q2, real=False)
137        code, out, err = run_cli(["launch", "--plan", "--model-path", str(snap)])
138        self.assertEqual(code, 5)
139        self.assertEqual(err.count("shortcut"), 1, err)
140        self.assertIn(Q2[0], err)
141        self.assertIn(Q2[1], err)
142
143    def test_the_same_problem_for_many_files_is_said_once(self):
144        from strata_control import models
145        issues = [f"m-0000{i}-of-00005.gguf: GGUF metadata is truncated" for i in range(1, 6)] + ["incomplete_or_invalid_shard_set"]
146        words = models.problem_words(issues)
147        self.assertEqual(words.count("the file is cut short"), 1)
148        self.assertIn("m-00001-of-00005.gguf, m-00002-of-00005.gguf and 3 more files", words)
149        self.assertEqual(models.problem_words(["a.gguf: GGUF metadata is truncated", "b.gguf: GGUF metadata is truncated"]),
150                         "a.gguf and b.gguf: the file is cut short (a download or copy that did not finish)")
151        self.assertEqual(models.problem_words(["multiple_model_groups", "unrecognized_or_unsupported_model_variant"]),
152                         "the folder holds more than one model")
153        many = [f"unsupported_or_missing_architecture", "incomplete_or_invalid_shard_set", "multiple_model_groups",
154                "unsupported_or_incomplete_tokenizer_metadata", "missing_or_unexpected_expert_quantization"]
155        self.assertTrue(models.problem_words(many).endswith("and 2 more problems"))
156
157
158
159class PlanWords(Base):
160    """Findings 1 and 7: --plan shows the real model, the picture setting, a copyable line, and what would be downloaded."""
161
162    def setUp(self):
163        super().setUp()
164        from tests.terminal.launch_support import not_intel
165        not_intel(self)
166
167    def plan_text(self, *args):
168        code, out, err = run_cli(["launch", "--plan", *args])
169        self.assertEqual(code, 0, err or out)
170        return out
171
172    def test_own_files_show_the_model_they_are(self):
173        folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
174        out = self.plan_text("--model-path", str(folder))
175        self.assertIn("Plan for 'IQ3_XXS", out)
176        self.assertNotIn("model default", out)
177        self.assertNotIn("None", out)
178        self.assertIn("Qwen3.8-Flash-Next IQ3_XXS", out)
179        self.assertIn(f"your files in {folder}", out)
180        self.assertRegex(out, r"pictures (on|off)")
181        self.assertIn("--model iq3_xxs", out.split("same as")[1])         # the copyable line names the model too
182        self.assertIn(f'--model-path "{folder}"', out.split("same as")[1])
183
184    def test_a_named_catalog_model_shows_its_size_and_the_download(self):
185        out = self.plan_text("--model", "q2_0")
186        self.assertIn("Qwen3.8-Flash-Next Q2_0, 66 GB", out)
187        self.assertRegex(out, r"download\s+About 7\d\.\d GB to download: the model \(66\.4 GB\), the draft layer \(5\.2 GB\)")
188        self.assertIn("The engine for your graphics card is downloaded first", out)
189
190    def test_nothing_is_downloaded_when_everything_is_here(self):
191        folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
192        data = self.base / "Strata" 
193        (data / "models" / "x").mkdir(parents=True)
194        (data / "mtp" / "rt").mkdir(parents=True)
195        (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x")
196        (data / "models" / "mmproj-Qwen3.8-Flash-Next-BF16.gguf").write_bytes(b"x")
197        # the files sit under <data>/models/<tag>: the draft layer and the picture reader are found beside them
198        moved = data / "models" / "iq3_xxs"
199        folder.rename(moved)
200        out = self.plan_text("--model-path", str(moved))
201        self.assertIn("download  Nothing to download: your model files are used where they are.", out)
202
203    def test_own_files_with_no_draft_layer_say_what_is_fetched(self):
204        folder = self.files(self.base / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
205        with mock.patch.object(Runner, "existing_data_dir", return_value=None),                 mock.patch.object(Catalog, "data_dir", return_value=self.base / "emptydata"):
206            out = self.plan_text("--model-path", str(folder), "--vision", "off")
207        self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). Your model files are used where they are.", out)
208
209    def test_a_model_whose_files_are_all_on_disk_does_not_list_a_zero_download(self):
210        from strata_cli.launch.modelstate import ModelState, Part
211        data = self.base / "d"
212        (data / "mtp" / "rt").mkdir(parents=True)
213        (data / "mtp" / "rt" / "experts.bin").write_bytes(b"x")
214        whole = ModelState(installed=False, parts=[Part("weights", "the model", 0.0)], on_disk_gb=66.4, total_gb=66.4)
215        with mock.patch.object(Runner, "model_state", return_value=whole):
216            out = self.plan_text("--model", "q2_0", "--data-dir", str(data), "--vision", "off")
217            self.assertIn("download  Nothing to download: the model is already on this computer.", out)
218            out = self.plan_text("--model", "q2_0", "--data-dir", str(self.base / "other"), "--vision", "off")
219        self.assertIn("About 5.2 GB to download: the draft layer (5.2 GB). 66 GB of the model is already in its folder.", out)
220        self.assertNotIn("0.0 GB", out)
221
222    def test_json_plan_carries_the_numbers(self):
223        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--mtp", "off", "--vision", "off"])
224        self.assertEqual(code, 0, err)
225        plan = json.loads(out)["plan"]
226        self.assertEqual(plan["model"]["title"], "Qwen3.8-Flash-Next Q2_0")
227        self.assertEqual(plan["model"]["model_gb"], 66.4)
228        self.assertEqual(plan["download"]["gb"], 66.4)
229        self.assertEqual([p["kind"] for p in plan["download"]["parts"]], ["weights"])
230
231
232
233class DownloadTotal(Base):
234    """Finding 4: the figure counts every shard (and the picture reader), in the folder the setup is really given."""
235
236    def run_lines(self, runner: Runner, lines: list[str]) -> list[str]:
237        seen: list[str] = []
238        runner.emit_cb = lambda ev: seen.append(ev.text)
239        proc = mock.Mock()
240        proc.stdout = iter(lines)
241        proc.wait.return_value = 1                               # stop after the lines: the failure path is not what is looked at
242        with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None):
243            with self.assertRaises(LaunchError):
244                runner.ensure_model()
245        return seen
246
247    def test_the_total_is_the_whole_model_in_the_chosen_data_folder(self):
248        data = self.base / "mydata"
249        folder = data / "models" / "Q2_0"
250        folder.mkdir(parents=True)
251        first = folder / (Q2[0] + ".part")
252        first.write_bytes(bytes(100_000_000))
253        r = self.runner(family="qwen", model="Q2_0", data_dir=str(data), vision="on", context=32768)
254        job = r.progress_job()
255        self.assertEqual(Path(job["folder"]), folder)
256        self.assertEqual(len(job["files"]), 3)                                   # two shards and the picture reader
257        seen = self.run_lines(r, ["=== Step 5: Getting the model files ===", f"{Q2[0]}: 0.10 / 37.60 GB (0%)"])
258        text = [x for x in seen if "GB" in x]
259        self.assertTrue(text, seen)
260        self.assertIn("of 67.3 GB", text[-1])                                     # 66.4 GB of shards + 0.9 GB picture reader
261        self.assertNotIn("37.6", " ".join(text))
262
263    def test_the_default_data_folder_is_used_when_none_was_chosen(self):
264        r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768)
265        self.assertEqual(Path(r.progress_job()["folder"]).parts[-2:], ("models", "Q2_0"))
266        self.assertEqual(len(r.progress_job()["files"]), 2)
267
268
269
270class QuietStep(Base):
271    """Finding 5: setup step 6 (packing) prints nothing for minutes: the person sees the plain sentence and a 'still working' line."""
272
273    def slow(self, steps):
274        import time
275        for delay, line in steps:
276            time.sleep(delay)
277            yield line + "\n"
278
279    def run_steps(self, steps, heartbeat=0.3):
280        r = self.runner(family="qwen", model="Q2_0", vision="off", context=32768)
281        r.HEARTBEAT_S = heartbeat
282        seen = []
283        r.emit_cb = lambda ev: seen.append(ev.text)
284        proc = mock.Mock()
285        proc.stdout = self.slow(steps)
286        proc.wait.return_value = 1
287        with mock.patch.object(Runner, "_spawn", return_value=proc), mock.patch.object(Runner, "adopt_prepared_files", return_value=None):
288            with self.assertRaises(LaunchError):
289                r.ensure_model()
290        return seen
291
292    def test_a_silent_pack_step_says_what_it_does_and_that_it_is_still_going(self):
293        seen = self.run_steps([(0, "=== Step 5: Getting the model files ==="), (0, "all model files present"),
294                               (0, "=== Step 6: Preparing the model for Strata ==="),
295                               (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin"), (1.6, "[X] stopped for the test")])
296        pack = [x for x in seen if x.startswith("Packing the experts into one file")]
297        self.assertTrue(pack, seen)
298        self.assertEqual(pack[0], "Packing the experts into one file for low-memory mode (one time)")
299        beats = [x for x in pack if "still working" in x]
300        self.assertGreaterEqual(len(beats), 2, seen)                    # a line every interval of silence
301        self.assertNotIn("Setup step 6", " ".join(seen))
302
303    def test_no_heartbeat_while_lines_keep_coming(self):
304        seen = self.run_steps([(0, "=== Step 6: Preparing the model for Strata ==="), (0, "> python tools/iq_pack.py --gguf x --out y --experts-bin")] +
305                              [(0.1, f"  layer {i}") for i in range(5)] + [(0, "[X] stopped")], heartbeat=2.0)
306        self.assertFalse([x for x in seen if "still working" in x])
307
308    def test_the_plain_printer_shows_each_heartbeat(self):
309        import io
310        from strata_cli.launch import cmd
311        from strata_cli.launch.runner import Event
312        buf = io.StringIO()
313        with mock.patch.object(cmd.sys, "stdout", buf):
314            emit = cmd._printer()
315            emit(Event("model", "Packing (still working, 30 s so far)"))
316            emit(Event("model", "Packing (still working, 60 s so far)"))
317            emit(Event("model", "Packing (still working, 60 s so far)"))
318        self.assertEqual(buf.getvalue().count("still working"), 2)
319
320
321
322class StoredTuning(Base):
323    """Finding 6: a run by flags (no saved preset) reuses the tuning result stored for the same model, choices and computer."""
324
325    IDENT = {"hardware": {"hard": {"gpus": ["RTX 5070"], "cpu": "test", "logical": 16, "ram_gib": 64}, "soft": {}},
326             "engine": {"backend": "cuda"}, "model": {"sha256_shard1": "abc"}}
327
328    def setUp(self):
329        super().setUp()
330        from strata_control import presets
331        self.presets = presets
332        self.cfg_path = self.base / "launch.json"
333        self.cfg = {"args": ["--native", "x/model-00001-of-00002.gguf", "--max-context", "32768", "--kv", "int8"], "model_name": "qwen"}
334        self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8")
335        self.ident = json.loads(json.dumps(self.IDENT))
336        p = mock.patch.object(presets, "current_identity", lambda cfg, **kw: self.ident)
337        p.start()
338        self.addCleanup(p.stop)
339
340    def store(self):
341        return self.presets.create({"settings": {"args": {}, "env": {}, "per_request": {}}, "outcome": "improved"},
342                                   choices=self.presets.choices_from_config(self.cfg), identity=self.ident, name="Q2 32K - Full speed")
343
344    def runner_for_tune(self, retune=False):
345        r = self.runner(family="qwen", model="Q2_0", tune="quick")
346        r.retune = retune
347        r.config_path = self.cfg_path
348        return r
349
350    def run_tune(self, r):
351        seen = []
352        r.emit_cb = lambda ev: seen.append(ev.text)
353        with mock.patch.object(Runner, "_spawn", side_effect=RuntimeError("the tuner started")) as spawn:
354            try:
355                r.tune()
356                started = False
357            except RuntimeError:
358                started = True
359        return seen, started
360
361    def test_nothing_stored_means_it_is_measured(self):
362        seen, started = self.run_tune(self.runner_for_tune())
363        self.assertTrue(started)
364
365    def test_a_big_model_gets_a_longer_start_wait_by_itself(self):                    # #3949 #3459
366        r = self.runner_for_tune()
367        row = type("Row", (), {"family": r.s.family, "model": r.s.model, "download_gb": 20.0})
368        with mock.patch.object(r.catalog, "rows", return_value=[row]):
369            self.assertEqual(r.start_wait(), 600)                                    # a small model keeps ten minutes
370        row.download_gb = 250.0
371        with mock.patch.object(r.catalog, "rows", return_value=[row]):
372            self.assertEqual(r.start_wait(), 1800)                                   # 600 + 210 x 8, capped at 30 minutes
373        row.download_gb = 83.0
374        with mock.patch.object(r.catalog, "rows", return_value=[row]):
375            self.assertEqual(r.start_wait(), 944)
376
377    def test_a_stored_result_is_used_and_said(self):
378        saved = self.store()
379        r = self.runner_for_tune()
380        seen, started = self.run_tune(r)
381        self.assertFalse(started)
382        text = seen[-1]
383        self.assertIn("already tuned for this computer", text)
384        self.assertIn("Add --retune to measure again", text)
385        self.assertIn("Q2 32K - Full speed", text)
386        self.assertIn("--retune", text)
387        self.assertEqual(r.s.tuned_preset, saved["id"])
388        self.assertTrue(r.s.is_tuned)
389
390    def test_retune_measures_again(self):
391        self.store()
392        seen, started = self.run_tune(self.runner_for_tune(retune=True))
393        self.assertTrue(started)
394
395    def test_another_context_is_another_result(self):
396        self.store()
397        self.cfg["args"][3] = "65536"
398        self.cfg_path.write_text(json.dumps(self.cfg), encoding="utf-8")
399        seen, started = self.run_tune(self.runner_for_tune())
400        self.assertTrue(started)
401
402    def test_a_changed_graphics_card_is_measured_again(self):
403        self.store()
404        self.ident["hardware"]["hard"]["gpus"] = ["RTX 4090"]
405        seen, started = self.run_tune(self.runner_for_tune())
406        self.assertTrue(started)
407
408    def test_the_flag_asks_for_a_new_measurement_and_implies_quick(self):
409        code, out, err = run_cli(["launch", "--plan", "--output", "json", "--model", "q2_0", "--retune"])
410        self.assertEqual(code, 0, err)
411        self.assertEqual(json.loads(out)["plan"]["settings"]["tune"], "quick")
412        code, out, err = run_cli(["launch", "--help"])
413        self.assertIn("--retune", out)
414
415
416
417if __name__ == "__main__":
418    unittest.main()