okami.mom/strata

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

Niko1221Trial2 merge f-0291-pr-nv (97b3d614f)1306424be

main
18.1 KiB364 linesraw
1"""0.2.2: "use my own model files" accepts every layout 0.1.45's `setup.py --gguf-dir` accepted (issues #3316 #3292 #3190 #3209 #3331).
2
3The checker in front of setup (strata_control/models.plan_import) used to be stricter than setup itself: a split set whose first shard
4holds only the metadata (Unsloth's), a link to the file (Hugging Face cache, Ollama), a folder holding several sizes, a folder above the
5model folder (a whole repository, a 0.1.45 data folder), more than 128 files in a folder. Tiny GGUF files with the real shard names
6stand for the real ones (the shard names and the expert types are what the table checks)."""
7
8from __future__ import annotations
9
10import json
11import os
12import struct
13import tempfile
14import unittest
15from pathlib import Path
16
17from strata_control import gguf_preflight, models
18from strata_control.profiles import ProfileError
19from tools.gguf_reader import BLOCK_GEOMETRY
20
21TYPE_IDS = {"Q8_0": 8, "IQ3_S": 21, "IQ4_NL": 20, "IQ4_XS": 23, "IQ3_XXS": 18, "Q2_0": 42, "IQ2_S": 22, "IQ2_XS": 17,
22            "I8": 24, "I16": 25, "I32": 26, "I64": 27}
23# One value per block. Kept here rather than read from the reader's table: the test has to build such a file whether or
24# not that table sizes the type, and a wrong row there must fail the test instead of moving the fixture with it.
25INTEGER_BYTES = {"I8": 1, "I16": 2, "I32": 4, "I64": 8}
26
27
28def string(value: str) -> bytes:
29    raw = value.encode()
30    return struct.pack("<Q", len(raw)) + raw
31
32
33def gguf_bytes(experts: list[str], *, metadata: bool = True) -> bytes:
34    """A tiny qwen4exp GGUF with one routed-expert tensor per type named; `experts=[]` is the metadata-only first shard of a split set."""
35    pairs = [("general.architecture", 8, string("qwen4exp")), ("tokenizer.ggml.model", 8, string("gpt2")),
36             ("tokenizer.ggml.tokens", 9, struct.pack("<IQ", 8, 1) + string("a")),
37             ("tokenizer.ggml.merges", 9, struct.pack("<IQ", 8, 1) + string("a b"))] if metadata else []
38    header = b"GGUF" + struct.pack("<IQQ", 3, len(experts), len(pairs)) + \
39        b"".join(string(k) + struct.pack("<I", kind) + value for k, kind, value in pairs)
40    offset = 0
41    for i, name in enumerate(experts):
42        block, size = (1, INTEGER_BYTES[name]) if name in INTEGER_BYTES else BLOCK_GEOMETRY[name]
43        header += string(f"blk.{i}.ffn_gate_exps.weight") + struct.pack("<IQIQ", 1, block, TYPE_IDS[name], offset)
44        offset += -(-size // 32) * 32
45    header += b"\x00" * (-len(header) % 32)
46    return header + b"\x00" * offset
47
48
49UNSLOTH_Q4 = ["Qwen3.8-Flash-Next-UD-Q4_K_XL-0000%d-of-00004.gguf" % i for i in (1, 2, 3, 4)]
50UNSLOTH_IQ4 = ["Qwen3.8-Flash-Next-UD-IQ4_XS-0000%d-of-00003.gguf" % i for i in (1, 2, 3)]
51Q2 = ["Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-0000%d-of-00002.gguf" % i for i in (1, 2)]
52IQ3XXS = ["Qwen3.8-Flash-Next-GSQ-RCO-IQ3_XXS-0000%d-of-00002.gguf" % i for i in (1, 2)]
53
54
55class Base(unittest.TestCase):
56    def setUp(self):
57        self.tmp = tempfile.TemporaryDirectory(prefix="strata-own-")
58        self.addCleanup(self.tmp.cleanup)
59        self.base = Path(self.tmp.name)
60
61    def put(self, folder: Path, names: list[str], experts: list[str]) -> Path:
62        folder.mkdir(parents=True, exist_ok=True)
63        for n in names:
64            (folder / n).write_bytes(gguf_bytes(experts))
65        return folder
66
67    def gsq(self, folder: Path, names: list[str], kind: str) -> Path:
68        return self.put(folder, names, [kind])
69
70    def unsloth(self, folder: Path, names: list[str], kinds: list[str]) -> Path:
71        """The first shard has only the metadata (what llama.cpp's gguf-split makes), the others carry tensors."""
72        folder.mkdir(parents=True, exist_ok=True)
73        (folder / names[0]).write_bytes(gguf_bytes([]))
74        for n in names[1:]:
75            (folder / n).write_bytes(gguf_bytes(kinds, metadata=False))
76        return folder
77
78
79class MetadataOnlyFirstShard(Base):
80    def test_unsloth_split_set_is_recognised(self):
81        folder = self.unsloth(self.base / "u", UNSLOTH_Q4, ["IQ4_NL"])
82        plan = models.plan_import(str(folder))
83        # the tiny files carry IQ4_NL experts, which UD-Q4_K_XL does not list: the set is found, the quantization is what is flagged
84        self.assertNotIn("unsupported_or_missing_architecture", plan["issues"])
85        self.assertNotIn("unsupported_or_incomplete_tokenizer_metadata", plan["issues"])
86        self.assertNotIn("GGUF tensor or metadata count", " ".join(plan["issues"]))
87        self.assertEqual((plan["candidate_selection"]["family"], plan["candidate_selection"]["model"]), ("unsloth", "UD-Q4_K_XL"))
88
89    def test_unsloth_iq4_xs_passes_with_its_real_expert_types(self):
90        folder = self.unsloth(self.base / "u", UNSLOTH_IQ4, ["IQ3_S", "IQ4_NL", "IQ4_XS", "Q8_0"])
91        plan = models.plan_import(str(folder))
92        self.assertEqual(plan["issues"], [])
93        self.assertEqual(plan["candidate_selection"]["model"], "UD-IQ4_XS")
94        self.assertEqual(plan["model_dir"], str(folder))
95
96    def test_a_shard_with_no_tensors_and_no_metadata_is_still_refused(self):
97        f = self.base / "x.gguf"
98        f.write_bytes(gguf_bytes([], metadata=False))
99        plan = models.plan_import(str(f))
100        self.assertIn("unsupported_or_missing_architecture", plan["issues"])
101
102
103class Links(Base):
104    def make_links(self):
105        blobs = self.base / "blobs"
106        snap = self.base / "snapshots" / "abc" / "Q2_0"
107        blobs.mkdir()
108        snap.mkdir(parents=True)
109        for i, n in enumerate(Q2):
110            (blobs / f"sha{i}").write_bytes(gguf_bytes(["Q2_0"]))
111            try:
112                os.symlink(blobs / f"sha{i}", snap / n)
113            except (OSError, NotImplementedError):
114                self.skipTest("this account cannot create symbolic links")
115        return snap
116
117    def test_a_hugging_face_cache_snapshot_is_used_through_its_links(self):
118        snap = self.make_links()
119        plan = models.plan_import(str(snap))
120        self.assertEqual(plan["issues"], [])
121        self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
122        self.assertEqual(plan["file_count"], 2)
123
124    def test_a_link_to_the_folder_is_followed(self):
125        real = self.gsq(self.base / "real", Q2, "Q2_0")
126        link = self.base / "link"
127        try:
128            os.symlink(real, link, target_is_directory=True)
129        except (OSError, NotImplementedError):
130            self.skipTest("this account cannot create symbolic links")
131        self.assertEqual(models.plan_import(str(link))["issues"], [])
132
133    def test_a_link_to_a_file_that_is_gone_says_so(self):
134        snap = self.base / "s"
135        snap.mkdir()
136        try:
137            os.symlink(self.base / "gone", snap / Q2[0])
138        except (OSError, NotImplementedError):
139            self.skipTest("this account cannot create symbolic links")
140        with self.assertRaises(ProfileError) as ctx:
141            gguf_preflight.real_model_file(snap / Q2[0])
142        self.assertIn("link to a file that is not there", str(ctx.exception))
143
144    def test_a_missing_file_is_missing_not_a_link(self):
145        with self.assertRaises(ProfileError) as ctx:
146            gguf_preflight.real_model_file(self.base / "nope.gguf")
147        self.assertIn("is missing", str(ctx.exception))
148
149    def test_run_configs_keep_the_no_link_rule(self):
150        cfg = self.base / "real.json"
151        cfg.write_text("{}")
152        link = self.base / "strata-x.json"
153        try:
154            os.symlink(cfg, link)
155        except (OSError, NotImplementedError):
156            self.skipTest("this account cannot create symbolic links")
157        with self.assertRaises(ProfileError) as ctx:
158            models._read(link)                               # noqa: SLF001
159        self.assertIn("symlink", str(ctx.exception))
160
161
162class IntegerTensors(Base):
163    """The ISTA-DAS DeepSeek-V4.1 first shard keeps the Engram's hash parameters as integer tensors instead of metadata
164    (tools/dsv41/pack_gguf.py: I32 and I64), so the table in front of setup and the app sizes them instead of refusing the file."""
165
166    def test_a_tensor_directory_with_integer_tensors_is_read(self):
167        p = self.base / "DeepSeek-V4.1-Flash-IST-DAS-2.00bpw-00001-of-00004.gguf"
168        p.write_bytes(gguf_bytes(["I32", "I64"]))
169        self.assertEqual(gguf_preflight.inspect_metadata(p)["tensor_types"], {"I32": 1, "I64": 1})
170
171    def test_each_integer_type_is_sized_at_one_value_a_block(self):
172        for kind, size in INTEGER_BYTES.items():
173            p = self.base / f"integer-{kind}.gguf"
174            p.write_bytes(gguf_bytes([kind]))
175            self.assertEqual(gguf_preflight.inspect_metadata(p)["payload_bytes_required"], size, kind)
176
177
178class Folders(Base):
179    def test_many_other_gguf_files_in_the_folder_do_not_refuse(self):
180        folder = self.gsq(self.base / "m", Q2, "Q2_0")
181        for i in range(140):
182            (folder / f"other-{i:03d}.gguf").write_bytes(b"GGUF")
183        plan = models.plan_import(str(folder))
184        self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
185        self.assertEqual(plan["file_count"], 2)
186
187    def test_strata_draft_layer_beside_a_model_is_not_a_second_model(self):
188        # #4693: "the folder holds 2 models" for a model and the mtp-q2_0.gguf beside it
189        folder = self.base / "own"
190        folder.mkdir(parents=True)
191        (folder / "My-Finetune-IQ3_S-00001-of-00001.gguf").write_bytes(gguf_bytes(["IQ3_S"]))
192        (folder / "mtp-q2_0.gguf").write_bytes(gguf_bytes(["Q2_0"]))
193        plan = models.plan_import(str(folder))
194        self.assertNotIn("multiple_model_groups", plan["issues"])
195        self.assertEqual([f["name"] for f in plan["files"]], ["My-Finetune-IQ3_S-00001-of-00001.gguf"])
196
197    def test_several_sizes_in_one_folder_name_them_and_ask_for_one_file(self):
198        folder = self.gsq(self.base / "many", Q2, "Q2_0")
199        self.gsq(folder, IQ3XXS, "IQ3_XXS")
200        plan = models.plan_import(str(folder))
201        self.assertEqual(plan["issues"], ["multiple_model_groups"])
202        self.assertIsNone(plan["candidate_selection"])
203        self.assertEqual(sorted(h["model"] for h in plan["folder_holds"]), ["IQ3_XXS", "Q2_0"])
204        self.assertTrue(any("holds 2 models" in m and "type the path of its .gguf file" in m for m in plan["messages"]))
205
206    def test_one_known_size_among_other_files_is_used_and_the_rest_is_named(self):
207        folder = self.gsq(self.base / "mix", Q2, "Q2_0")
208        (folder / "some-other-model-Q4_K_M.gguf").write_bytes(gguf_bytes(["IQ3_S"]))
209        plan = models.plan_import(str(folder))
210        self.assertEqual(plan["issues"], [])
211        self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
212        self.assertEqual(plan["file_count"], 2)
213        self.assertTrue(any("some-other-model-Q4_K_M.gguf" in m and "leaves the others alone" in m for m in plan["messages"]))
214
215    def test_a_shard_file_picks_its_set_out_of_a_folder_of_several(self):
216        folder = self.gsq(self.base / "many", Q2, "Q2_0")
217        self.gsq(folder, IQ3XXS, "IQ3_XXS")
218        plan = models.plan_import(str(folder / IQ3XXS[1]))
219        self.assertEqual(plan["issues"], [])
220        self.assertEqual(plan["candidate_selection"]["model"], "IQ3_XXS")
221        self.assertEqual(plan["model_dir"], str(folder))
222
223    def test_a_folder_above_the_model_folder_is_searched(self):
224        data = self.base / "Strata-data"
225        self.gsq(data / "models" / "q2_0", Q2, "Q2_0")
226        (data / "packs").mkdir()
227        for start in (data, data / "models"):
228            plan = models.plan_import(str(start))
229            self.assertEqual(plan["issues"], [], start)
230            self.assertEqual(plan["model_dir"], str(data / "models" / "q2_0"))
231            self.assertTrue(any("The model files are in" in m for m in plan["messages"]))
232
233    def test_a_whole_repository_with_one_folder_per_size_asks_which(self):
234        repo = self.base / "repo"
235        self.gsq(repo / "Q2_0", Q2, "Q2_0")
236        self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
237        plan = models.plan_import(str(repo))
238        self.assertIn("multiple_model_groups", plan["issues"])
239        self.assertEqual(sorted((Path(h["folder"]).name, h["model"]) for h in plan["folder_holds"]),
240                         [("IQ3_XXS", "IQ3_XXS"), ("Q2_0", "Q2_0")])
241        self.assertTrue(plan["file_set_status"] == "invalid_or_incomplete")
242
243    def test_one_known_folder_next_to_unrelated_ones_is_used(self):
244        top = self.base / "all"
245        self.gsq(top / "models" / "q2_0", Q2, "Q2_0")
246        (top / "stuff").mkdir()
247        (top / "stuff" / "notes.txt").write_text("x")
248        plan = models.plan_import(str(top))
249        self.assertEqual(plan["candidate_selection"]["model"], "Q2_0")
250
251    def test_a_folder_with_no_gguf_anywhere_says_so(self):
252        (self.base / "empty" / "a" / "b").mkdir(parents=True)
253        with self.assertRaises(ProfileError) as ctx:
254            models.plan_import(str(self.base / "empty"))
255        self.assertIn("no GGUF files found", str(ctx.exception))
256
257    def test_a_folder_name_with_spaces_and_a_second_drive_style_path(self):
258        folder = self.gsq(self.base / "my models" / "Qwen 3.8 files", Q2, "Q2_0")
259        self.assertEqual(models.plan_import(str(folder))["issues"], [])
260
261    def test_a_missing_second_shard_is_one_plain_issue(self):
262        folder = self.put(self.base / "half", Q2[:1], ["Q2_0"])
263        plan = models.plan_import(str(folder))
264        self.assertEqual(plan["issues"], ["incomplete_or_invalid_shard_set"])
265
266
267class Launcher(Base):
268    """`strata launch --model-path` and the TUI's "use my own files" (strata_cli/launch/runner.py, screens.py)."""
269
270    def runner(self, **kw):
271        from strata_cli.launch import settings as S
272        from strata_cli.launch.catalog import Catalog
273        from strata_cli.launch.runner import Runner
274        from tests.terminal.launch_support import HW_12
275        return Runner(S.LaunchSettings(**kw), catalog=Catalog(hardware=HW_12))
276
277    def test_a_folder_above_the_model_is_resolved_to_the_model_folder(self):
278        data = self.base / "Strata-data"
279        self.gsq(data / "models" / "q2_0", Q2, "Q2_0")
280        r = self.runner(model_path=str(data))
281        r.resolve_own_files()
282        self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0"))
283        self.assertEqual(Path(r.s.model_path), data / "models" / "q2_0")
284        argv = r.setup_args()
285        self.assertEqual(Path(argv[argv.index("--gguf-dir") + 1]), data / "models" / "q2_0")
286
287    def test_a_named_model_in_a_folder_of_several_sizes_is_never_refused_here(self):
288        folder = self.gsq(self.base / "many", Q2, "Q2_0")
289        self.gsq(folder, IQ3XXS, "IQ3_XXS")
290        r = self.runner(model_path=str(folder), family="qwen", model="IQ3_XXS")
291        r.resolve_own_files()
292        self.assertEqual(Path(r.s.model_path), folder)               # setup picks the IQ3_XXS files by name, as in 0.1.45
293        self.assertEqual((r.s.family, r.s.model), ("qwen", "IQ3_XXS"))
294
295    def test_a_named_model_is_found_in_the_folder_that_holds_it(self):
296        repo = self.base / "repo"
297        self.gsq(repo / "Q2_0", Q2, "Q2_0")
298        self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
299        r = self.runner(model_path=str(repo), family="qwen", model="IQ3_XXS")
300        r.resolve_own_files()
301        self.assertEqual(Path(r.s.model_path), repo / "IQ3_XXS")
302
303    def test_two_models_and_none_named_says_which_in_plain_words(self):
304        from strata_cli.launch.runner import LaunchError
305        repo = self.base / "repo"
306        self.gsq(repo / "Q2_0", Q2, "Q2_0")
307        self.gsq(repo / "IQ3_XXS", IQ3XXS, "IQ3_XXS")
308        r = self.runner(model_path=str(repo))
309        with self.assertRaises(LaunchError) as ctx:
310            r.resolve_own_files()
311        text = str(ctx.exception)
312        self.assertIn("more than one model", text)
313        self.assertIn("holds 2 models", text)
314
315    def test_a_linked_model_file_keeps_its_name(self):
316        snap = Links.make_links(self)
317        r = self.runner(model_path=str(snap / Q2[0]))
318        r.resolve_own_files()
319        self.assertEqual((r.s.family, r.s.model), ("qwen", "Q2_0"))
320        self.assertEqual(Path(r.s.model_path).name, Q2[0])           # not the blob's hash name
321
322
323class Words(unittest.TestCase):
324    def test_a_file_problem_names_the_file_and_says_why(self):
325        self.assertEqual(models.plain_issue("model-00002-of-00002.gguf: GGUF metadata is truncated"),
326                         "model-00002-of-00002.gguf: the file is cut short (a download or copy that did not finish)")
327        self.assertIn("shorter than its own header", models.plain_issue("a.gguf: GGUF tensor payload is shorter than its directory requires"))
328        self.assertIn("old format (version 2)", models.plain_issue("a.gguf: Strata metadata preflight requires GGUF v3"))
329        self.assertEqual(models.plain_issue("incomplete_or_invalid_shard_set"), "some parts of the model are missing")
330
331    def test_the_plan_carries_the_words(self):
332        with tempfile.TemporaryDirectory() as tmp:
333            f = Path(tmp) / Q2[0]
334            f.write_bytes(gguf_bytes(["Q2_0"])[:60])
335            plan = models.plan_import(str(f))
336        self.assertTrue(plan["plain_issues"])
337        self.assertTrue(any(x.startswith(Q2[0] + ":") or x.startswith(Q2[1] + ":") for x in plan["plain_issues"]), plan["plain_issues"])
338
339
340class Table(unittest.TestCase):
341    def test_every_size_setup_installs_is_in_the_table(self):
342        """Setup can install it from --gguf-dir, so the checker in front of it must know it too (0.2.0 knew 7 of 10)."""
343        import importlib.util
344        spec = importlib.util.spec_from_file_location("strata_setup_for_test", models.ROOT / "setup.py")
345        setup = importlib.util.module_from_spec(spec)
346        spec.loader.exec_module(setup)
347        table = json.loads((models.ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))
348        missing = []
349        for family, fam in setup.FAMILIES.items():
350            if fam.get("ready"):
351                continue
352            for model, row in setup.MODELS.items():
353                if family not in row.get("families", ("qwen", "swift")):
354                    continue
355                names = {setup.model_file(fam, model, i) for i in range(1, setup.model_shards(fam, model) + 1)}
356                key = f"{family}/{model}"
357                have = {Path(n).name for n in (table.get(key) or {}).get("files", [])}
358                if key not in models.SUPPORTED_SELECTIONS or have != names:
359                    missing.append(key)
360        self.assertEqual(missing, [])
361
362
363if __name__ == "__main__":
364    unittest.main()