okami.mom/strata

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

Niko1221Merge f-0213-fixux (82d3a0345): user screenshots - a data folder on an external drive under /run/media is no longer refused as a system folder (real system folders still are; the doubled sentence is gone); one fit label everywhere (owner 11-08): 'fits' when the model files without the n-gram/PLE/Engram table fit graphics memory plus RAM, else 'may run slower' (the Unsloth sets were measured against RAM only; DeepSeek Needs shows the whole size; no-card PCs and small Macs say 'may run slower'; NVFP4-QAD sized by its 76.8 GB pack)b7bcbcde9

main
32.7 KiB535 linesraw
1"""Round 0214: Unsloth's v3.1 Qwen3.8-Flash-Next sets (revision d9620119, 2026-11-04) in setup.py's catalog: UD-IQ1_M, UD-Q2_0, UD-IQ2_XS,
2UD-Q2_K_XL, UD-IQ3_XXS, UD-Q3_K_XL and the new UD-IQ4_XS (catalog name UD-IQ4_XS-v31), the pinned UD-Q4_K_XL / UD-IQ4_XS / UD-Q5_K_XL /
3UD-Q6_K_XL / Q8_0 unchanged at 38bb39ee, UD-Q4_K_XL's second (four-shard, n-gram table last) layout taken from local files, the manual-load
4rule (#444), and a header regression for every set of the repository.  The tensor directories are tests/fixtures/unsloth_v31/headers.json.gz
5(the first 4 MB of each shard, read with HTTP range requests; tools/unsloth_v31_fixture.py).  Mocked: no GPU, no downloads.
6
7    python -m pytest tools/test_setup_unsloth_v31.py
8"""
9from __future__ import annotations
10
11import re
12import sys
13import tempfile
14import types
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
23import unsloth_v31_fixture as FX  # noqa: E402
24from test_setup_unsloth import Base, FakeGGUF  # noqa: E402
25
26DOC = FX.load()
27REV31 = "d96201194f103c906994f283f504209dc8d2a10c"
28REV_OLD = "38bb39ee97821de2c9009abb7e93950eec396e66"
29NEW = ["UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS-v31"]
30HUB = {m: ("UD-IQ4_XS" if m == "UD-IQ4_XS-v31" else m) for m in NEW}     # the name on the Hub
31FAM = setup.FAMILIES["unsloth"]
32TABLE_BYTES = 28800138432             # per_layer_token_embd in IQ4_NL: the last shard of every set below Q5
33Q5_0_DOWN = {"UD-IQ2_XS", "UD-Q2_K_XL", "UD-Q3_K_XL", "UD-IQ4_XS-v31"}
34
35
36def shards_of(set_name):
37    return DOC["sets"][set_name]["shards"]
38
39
40def pins_of(set_name):
41    return {s["name"]: (s["bytes"], s["sha256"]) for s in shards_of(set_name)}
42
43
44class Catalog(unittest.TestCase):
45    def test_every_new_set_is_pinned_by_the_hub_files(self):
46        for model in NEW:
47            with self.subTest(model=model):
48                d, shards = setup.MODELS[model], shards_of(HUB[model])
49                self.assertEqual(d["shards"], len(shards))
50                names = [setup.model_file(FAM, model, i) for i in range(1, d["shards"] + 1)]
51                self.assertEqual(names, [s["name"] for s in shards])
52                for s in shards:
53                    self.assertEqual(FAM["sha256"][s["name"]], (s["bytes"], s["sha256"]), s["name"])
54                    self.assertEqual(setup.UNSLOTH_V31_SHARDS[s["name"]], (s["bytes"], s["sha256"]))
55                    self.assertRegex(s["sha256"], r"^[0-9a-f]{64}$")
56                self.assertEqual(d["download_gb"], round(sum(s["bytes"] for s in shards) / 1e9, 1))
57                self.assertEqual(d["revision"], REV31)
58                self.assertEqual(d["quant"], HUB[model])
59                self.assertEqual(d["families"], ("unsloth",))
60                self.assertTrue(d["budget"] and d["vision"] is True)
61                self.assertEqual(d["engine"], (0, 1, 57))
62                self.assertEqual(d["ram_gb"], setup.UNSLOTH_MIN_RAM_GB)          # the RAM-budget floor of UD-Q4_K_XL and UD-IQ4_XS
63                self.assertEqual(setup.model_quant(model), HUB[model])
64
65    def test_arena_is_the_routed_experts_bytes_of_the_headers(self):
66        for model in NEW:
67            with self.subTest(model=model):
68                exp = 0
69                for s in shards_of(HUB[model]):
70                    for name, type_id, shape, _off in (s["header"] or {"tensors": []})["tensors"]:
71                        if name.endswith("_exps.weight") and "shexp" not in name:
72                            t = FX.G.TensorInfo(name, shape, type_id, FX.G.GGML_TYPES[type_id], 0)
73                            exp += t.expected_bytes()
74                self.assertEqual(setup.MODELS[model]["arena_gb"], round(exp / 1e9, 1))
75
76    def test_the_pinned_sets_stay_at_their_commit(self):
77        self.assertEqual(setup.HF_REVISIONS[setup.UNSLOTH_REPO], REV_OLD)
78        self.assertEqual(setup.UNSLOTH_V31_REVISION, REV31)
79        self.assertEqual(setup.hf(setup.UNSLOTH_REPO), f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV_OLD}/")
80        for model in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):
81            self.assertNotIn("revision", setup.MODELS[model], model)
82            self.assertEqual(setup.model_hf(FAM, model), f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV_OLD}/{model}/")
83        self.assertEqual(setup.model_file(FAM, "UD-IQ4_XS", 3), "Qwen3.8-Flash-Next-UD-IQ4_XS-00003-of-00003.gguf")
84        for model in NEW:
85            self.assertEqual(setup.model_hf(FAM, model), f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV31}/{HUB[model]}/")
86
87    def test_the_old_pins_are_untouched(self):
88        self.assertEqual(sum(b for b, _ in setup.UNSLOTH_SHARDS.values()), 111334654784)
89        self.assertEqual(sum(b for b, _ in setup.UNSLOTH_IQ4_XS_SHARDS.values()), 93682584224)
90        self.assertEqual(setup.UNSLOTH_IQ4_XS_SHARDS["Qwen3.8-Flash-Next-UD-IQ4_XS-00002-of-00003.gguf"][1],
91                         "577a38a2392b40ca2193cea502e1d92f60b8cd370675d308e0ec21885d9daaa7")
92        # Q5 / Q6 / Q8 were not re-uploaded: the Hub's files at d9620119 are the pinned ones
93        for set_name in ("UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):
94            for n, pin in pins_of(set_name).items():
95                self.assertEqual(setup.UNSLOTH_BIG_SHARDS[n], pin, n)
96        # no name is pinned twice with different bytes except UD-Q4_K_XL's, which are the alternative layout
97        for n in setup.UNSLOTH_V31_SHARDS:
98            self.assertNotIn(n, setup.UNSLOTH_SHARDS)
99            self.assertNotIn(n, setup.UNSLOTH_IQ4_XS_SHARDS)
100            self.assertNotIn(n, setup.UNSLOTH_BIG_SHARDS)
101
102    def test_a_file_is_pinned_by_the_commit_its_url_names(self):
103        n = "Qwen3.8-Flash-Next-UD-IQ1_M-00002-of-00003.gguf"
104        self.assertEqual(setup.file_pin(setup.model_hf(FAM, "UD-IQ1_M") + n), setup.UNSLOTH_V31_SHARDS[n])
105        q4 = "Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf"
106        self.assertEqual(setup.file_pin(setup.model_hf(FAM, "UD-Q4_K_XL") + q4), setup.UNSLOTH_SHARDS[q4])
107        self.assertEqual(setup.file_pin(setup.hf(setup.UNSLOTH_REPO).replace(REV_OLD, REV31) + "UD-Q4_K_XL/" + q4),
108                         setup.UNSLOTH_Q4_V31_SHARDS[q4])
109        self.assertNotEqual(setup.UNSLOTH_SHARDS[q4], setup.UNSLOTH_Q4_V31_SHARDS[q4])
110        self.assertIsNone(setup.file_pin("https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/" + REV31 + "/UD-IQ1_S/x-00001-of-00003.gguf"))
111
112    def test_the_model_names_resolve_in_both_directions(self):
113        self.assertEqual(setup.FAMILIES["unsloth"]["tag"] + "UD-IQ4_XS-v31", "unsloth-UD-IQ4_XS-v31")
114        with tempfile.TemporaryDirectory() as t:
115            for stem, model in (("strata-unsloth-ud-iq4_xs-v31", "UD-IQ4_XS-v31"), ("strata-unsloth-ud-iq4_xs", "UD-IQ4_XS"),
116                                ("strata-unsloth-ud-iq1_m", "UD-IQ1_M"), ("strata-unsloth-ud-q3_k_xl", "UD-Q3_K_XL")):
117                p = Path(t) / (stem + ".json")
118                p.write_text('{"args": ["--max-context", "8192"]}')
119                ch = setup.choices_from_config(p)
120                self.assertEqual((ch["family"], ch["model"]), ("unsloth", model), stem)
121
122    def test_budget_model_tells_the_three_and_the_four_shard_iq4_xs_apart(self):
123        for model in NEW:
124            first = "/m/" + setup.model_file(FAM, model, 1)
125            self.assertEqual(setup.budget_model({"args": ["--native", first]}), model, model)
126        self.assertEqual(setup.budget_model({"args": ["--native", "/m/Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf"]}), "UD-IQ4_XS")
127        self.assertEqual(setup.budget_model({"args": ["--native", "/m/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf"]}), "UD-Q4_K_XL")
128        self.assertEqual(setup.budget_model({"args": ["--native", "/m/Qwen3.8-Flash-Next-Q8_0-00001-of-00006.gguf"]}), "Q8_0")
129
130    def test_the_budget_rule_for_the_smaller_sets(self):
131        # every expert in RAM where the experts and 16 GiB more fit; the budget mode below that
132        self.assertFalse(setup.unsloth_budget("UD-IQ1_M", 64))
133        self.assertTrue(setup.unsloth_budget("UD-IQ4_XS-v31", 64))
134        self.assertFalse(setup.unsloth_budget("UD-IQ4_XS-v31", 96))
135        self.assertEqual(setup.resident_budget_gib("UD-IQ3_XXS", 63.7), 40)
136        self.assertEqual(setup.resident_budget_gib("UD-IQ1_M", 96), 32)            # at most all of them (34.8 GB = 32.4 GiB)
137        self.assertAlmostEqual(setup.unsloth_split_need_gb("UD-Q3_K_XL"), 89.5 + setup.UNSLOTH_RAM_LEFT_GB)
138
139    def test_vision_is_on_like_the_other_unsloth_sets(self):
140        for model in NEW:
141            self.assertTrue(setup.images_default(model, "unsloth", 64.0))
142
143
144class LastShardHoldsTheTable(unittest.TestCase):
145    """The n-gram table (per_layer_token_embd, IQ4_NL) is a shard of its own, the LAST one, in every set below Q5."""
146
147    def test_the_table_is_the_last_shard_and_shard_1_holds_no_tensor(self):
148        for set_name in ("UD-IQ1_M", "UD-IQ1_S", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS", "UD-Q4_K_XL"):
149            with self.subTest(set=set_name):
150                shards = shards_of(set_name)
151                last = shards[-1]
152                self.assertEqual(last["bytes"], TABLE_BYTES)
153                self.assertEqual([t[0] for t in last["header"]["tensors"]], ["per_layer_token_embd.weight"])
154                self.assertEqual(last["header"]["tensors"][0][1], 20)                 # IQ4_NL
155                self.assertEqual(last["header"]["tensors"][0][2], [160, 320001536])
156                for s in shards[1:-1]:
157                    self.assertNotIn("per_layer_token_embd.weight", [t[0] for t in s["header"]["tensors"]])
158                self.assertIsNone(shards[0]["header"])                              # metadata and tokenizer only (longer than the 4 MB read)
159
160    def test_the_table_shard_is_the_same_bytes_in_each_layout(self):
161        by_count = {}
162        for set_name in ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS", "UD-Q4_K_XL"):
163            shards = shards_of(set_name)
164            by_count.setdefault(len(shards), set()).add(shards[-1]["sha256"])
165        self.assertEqual({k: len(v) for k, v in by_count.items()}, {3: 1, 4: 1})     # one file for the 3-shard sets, one for the 4-shard sets (they differ in the split header)
166
167
168class FinalShardGGUF(FakeGGUF):
169    """gguf_reader.GGUFFile for a set whose LAST shard holds the table."""
170    def __init__(self, path):
171        m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", str(path))
172        names = ["per_layer_token_embd.weight"] if m and m.group(1) == m.group(2) else ["blk.0.ffn_up_exps.weight"]
173        self.tensors = [types.SimpleNamespace(name=n) for n in names]
174
175
176class Install(Base):
177    """setup.main() for each new set: the files of the commit it names, their pins, the pack from shard 1, the table found in the last shard."""
178
179    def test_each_new_set_installs_from_its_commit(self):
180        for model in NEW:
181            with self.subTest(model=model), mock.patch.dict(sys.modules, {"gguf_reader": types.SimpleNamespace(GGUFFile=FinalShardGGUF)}):
182                self.setUp()
183                code, out, cfg = self._main(model)
184                self.assertEqual(code, 0, out)
185                hub, d = HUB[model], setup.MODELS[model]
186                base = f"https://huggingface.co/unsloth/Qwen3.8-Flash-Next-GGUF/resolve/{REV31}/{hub}/"
187                names = [s["name"] for s in shards_of(hub)]
188                self.assertEqual(self.downloads[:-1], [base + n for n in names])
189                self.assertIn("mmproj", self.downloads[-1])
190                self.assertEqual(self.verified, [(n, *pins_of(hub)[n]) for n in names])
191                packs = [r for r in self.runs if r[1].endswith("iq_pack.py")]
192                self.assertEqual(len(packs), 1, self.runs)
193                self.assertIn("--compat-bf16", packs[0])
194                self.assertNotIn("--experts-bin", packs[0])
195                self.assertTrue(packs[0][packs[0].index("--gguf") + 1].endswith(names[0]))
196                args = cfg["args"]
197                self.assertTrue(args[args.index("--native") + 1].endswith(names[0]))
198                self.assertNotIn("--ple-gguf", args)                                # more than two shards: the engine finds the table by its tensor name
199                self.assertEqual(cfg["model_name"], "qwen3.8-flash-next-unsloth-" + model.lower())
200                self.assertEqual(args[args.index("--pack") + 1], str(self.t / "data" / "packs" / ("unsloth-" + model.lower())))
201                self.assertEqual(setup.budget_model(cfg), model)
202                self.assertIn("--vision", args)
203                self.tmp.cleanup()
204
205    def _main(self, model, **kw):
206        return self.main(["--context", "8192"], version="0.1.57", m=model, **kw)
207
208    def test_an_engine_older_than_0157_stops_before_the_download(self):
209        code, out, cfg = self.main(["--context", "8192"], version="0.1.56", m="UD-IQ1_M")
210        self.assertEqual(code, 1, out)
211        self.assertIn("needs engine 0.1.57 or newer", out)
212        self.assertEqual(self.downloads, [])
213
214    def test_the_pinned_ones_still_download_from_38bb39ee(self):
215        for model in ("UD-IQ4_XS", "UD-Q4_K_XL"):
216            self.setUp()
217            code, out, cfg = self.main(["--context", "8192"], version="0.1.57", m=model)
218            self.assertEqual(code, 0, out)
219            self.assertTrue(all(f"/resolve/{REV_OLD}/{model}/" in u for u in self.downloads[:-1]), self.downloads)
220            self.tmp.cleanup()
221
222    def test_check_lists_the_new_sets(self):
223        code, out, _cfg = self.main(["--check"], model=False, family=False)
224        self.assertIn(code, (0, None), out)
225        for model in NEW:
226            self.assertRegex(out, rf"(?m){re.escape(model)}\s+needs ~\d+ GB of RAM \+ VRAM: (fits|may run slower)$")
227
228
229class FitLabels(Base):
230    """0.2.13 (owner): the weight files without the lookup table against the RAM and the card's memory together: "fits" or "may run slower", in the size menu,
231    in --check and in the install's RAM warning.  The screenshot PC: a V100 32 GB with 31 GB of RAM (63 GB)."""
232
233    def _line(self, out, model):
234        return next(x for x in out.splitlines() if re.search(rf"\d\) {re.escape(model)} ", x))
235
236    def test_the_menu_labels_and_the_warning_follow_the_one_rule(self):
237        code, out, _cfg = self.main(["--context", "8192"], ram=31.0, vram=32.0, version="0.1.57", m="UD-IQ1_M")
238        self.assertEqual(code, 0, out)
239        for m in ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL"):      # 39 to 61 GB of files (download minus the 28.8 GB table), 63 GB here
240            self.assertTrue(self._line(out, m).endswith("   <- fits"), (m, self._line(out, m)))
241        for m in ("UD-IQ4_XS-v31", "UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):         # UD-IQ4_XS-v31 is 64.9 GB
242            self.assertTrue(self._line(out, m).endswith("   <- may run slower"), (m, self._line(out, m)))
243        self.assertNotIn("<- needs 48 GB RAM", out)                          # the RAM-floor line is gone
244        self.assertNotIn("single-digit tokens/s", out)                       # UD-IQ1_M fits: the install does not warn against it
245        self.tmp.cleanup()
246        self.setUp()
247        code, out, _cfg = self.main(["--context", "8192"], ram=31.0, vram=11.9, version="0.1.57", m="UD-IQ1_M")   # 43 GB: 39 GB of files fit, UD-IQ3_XXS (55) does not
248        self.assertEqual(code, 0, out)
249        self.assertTrue(self._line(out, "UD-IQ1_M").endswith("   <- fits"))
250        self.assertTrue(self._line(out, "UD-IQ3_XXS").endswith("   <- may run slower"))
251        self.tmp.cleanup()
252        self.setUp()
253        code, out, _cfg = self.main(["--context", "8192"], ram=20.0, vram=11.9, version="0.1.57", m="UD-IQ1_M")   # 32 GB: 39 GB of files do not
254        self.assertTrue(self._line(out, "UD-IQ1_M").endswith("   <- may run slower"))
255        self.assertIn("single-digit tokens/s", out)                          # the install's own warning stays where the set does not fit
256
257    def test_check_says_fits_or_may_run_slower(self):
258        code, out, _cfg = self.main(["--check"], ram=31.0, vram=32.0, model=False, family=False)
259        self.assertIn(code, (0, None), out)
260        for model in ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL"):
261            self.assertRegex(out, rf"(?m){re.escape(model)}\s+needs ~\d+ GB of RAM \+ VRAM: fits$")
262        self.assertRegex(out, r"(?m)UD-IQ4_XS-v31\s+needs ~65 GB of RAM \+ VRAM: may run slower$")
263        for model in ("UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):
264            self.assertRegex(out, rf"(?m){re.escape(model)}\s+needs ~\d+ GB of RAM \+ VRAM: may run slower$")
265        for old in ("fits, a bit slower", "does not fit", "slow here", "low-RAM mode", "in RAM, the rest"):
266            self.assertNotIn(old, out)
267
268
269class OwnFiles(unittest.TestCase):
270    """#444: strata launch --model-path and the app's "Use a local GGUF" go through gguf_dir_shards / gguf_choice / gguf_unsupported."""
271
272    def test_the_new_files_are_no_longer_refused(self):
273        for model in NEW:
274            for s in shards_of(HUB[model]):
275                self.assertIsNone(setup.gguf_unsupported(s["name"]), s["name"])
276            first = shards_of(HUB[model])[0]["name"]
277            self.assertEqual(setup.gguf_choice(first), ("unsloth", model), first)
278
279    def test_the_approved_texts(self):
280        want = {"UD-IQ1_M": "~1-bit (Unsloth Dynamic v3.1), the smallest download", "UD-Q2_0": "2-bit (Unsloth Dynamic v3.1)",
281                "UD-IQ2_XS": "2-bit i-quant (Unsloth Dynamic v3.1)", "UD-Q2_K_XL": "2-bit (Unsloth Dynamic v3.1) with some 3-bit experts",
282                "UD-IQ3_XXS": "3-bit i-quant (Unsloth Dynamic v3.1)", "UD-Q3_K_XL": "3-bit (Unsloth Dynamic v3.1) with some 4-bit experts",
283                "UD-IQ4_XS-v31": "~4-bit i-quant (Unsloth Dynamic v3.1), a newer file than UD-IQ4_XS with other tensor types"}
284        from strata_control import mac_fit
285        sys.path.insert(0, str(ROOT / "tools"))
286        import strata_mcp
287        for m, a in want.items():
288            self.assertEqual(setup.MODELS[m]["about"], a)
289            self.assertEqual(mac_fit.MAC_ABOUT[m], a)
290            self.assertEqual(strata_mcp.FALLBACK_MODELS[m]["about"], a)
291        for m in ("UD-IQ1_M", "UD-Q2_0", "UD-IQ2_XS", "UD-Q2_K_XL", "UD-IQ3_XXS", "UD-Q3_K_XL", "UD-IQ4_XS", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL", "Q8_0"):
292            self.assertIn(m, setup.SUPPORTED_GGUFS)
293        self.assertIn("(Unsloth's UD-IQ1_S, other K-quant files) cannot be used", setup.SUPPORTED_GGUFS)
294        self.assertEqual(setup.UNSUPPORTED_WHY["UD-IQ1_S"], "UD-IQ1_S mixes two expert formats in one layer, which Strata cannot load; UD-IQ1_M is the 1-bit choice")
295
296    def test_q3_k_xl_really_has_some_4_bit_experts(self):
297        n = sum(1 for s in shards_of("UD-Q3_K_XL") for t in (s["header"] or {"tensors": []})["tensors"]
298                if t[0].endswith("ffn_gate_exps.weight") and FX.G.GGML_TYPES[t[1]] == "IQ4_XS")
299        self.assertEqual(n, 6)
300
301    def test_ud_iq1_s_stays_refused(self):
302        for s in shards_of("UD-IQ1_S"):
303            self.assertEqual(setup.gguf_unsupported(s["name"]), "UD-IQ1_S")
304        self.assertNotIn("UD-IQ1_S", setup.MODELS)
305        self.assertIsNone(setup.gguf_choice(shards_of("UD-IQ1_S")[0]["name"]))
306
307    def test_the_bf16_and_other_unsloth_files_stay_refused(self):
308        self.assertEqual(setup.gguf_unsupported("Qwen3.8-Flash-Next-BF16-00001-of-00008.gguf"), "BF16")
309        self.assertIsNone(setup.gguf_unsupported("mmproj-BF16.gguf"))
310
311    def _folder(self, t, set_name, only=None):
312        for s in shards_of(set_name):
313            if only is None or s["name"] in only:
314                (Path(t) / s["name"]).write_bytes(b"")
315        return Path(t)
316
317    def test_gguf_dir_shards_finds_all_shards_by_the_count_in_the_name(self):
318        for model in NEW:
319            with tempfile.TemporaryDirectory() as t:
320                folder = self._folder(t, HUB[model])
321                got = setup.gguf_dir_shards(folder, FAM, model)
322                self.assertEqual([p.name for p in got], [s["name"] for s in shards_of(HUB[model])], model)
323
324    def test_the_v31_iq4_xs_is_not_taken_for_the_pinned_one(self):
325        with tempfile.TemporaryDirectory() as t:
326            folder = self._folder(t, "UD-IQ4_XS")                                   # the four-shard files
327            got = setup.gguf_dir_shards(folder, FAM, "UD-IQ4_XS")                   # asked for the three-shard set
328            self.assertEqual(got[0].name, "Qwen3.8-Flash-Next-UD-IQ4_XS-00001-of-00003.gguf")
329            self.assertFalse(got[0].exists())
330            problem = setup.gguf_dir_problem(folder, got[0], FAM, "UD-IQ4_XS")
331            self.assertIsNotNone(problem)
332            self.assertIn("--family unsloth --model UD-IQ4_XS-v31", problem[1])
333            ok = setup.gguf_dir_shards(folder, FAM, "UD-IQ4_XS-v31")
334            self.assertTrue(all(p.exists() for p in ok))
335            self.assertIsNone(setup.gguf_dir_problem(folder, ok[0], FAM, "UD-IQ4_XS-v31"))
336
337    def test_ud_iq1_s_in_a_folder_is_named_as_not_usable(self):
338        with tempfile.TemporaryDirectory() as t:
339            folder = self._folder(t, "UD-IQ1_S")
340            first = setup.gguf_dir_shards(folder, FAM, "UD-IQ1_M")[0]
341            problem = setup.gguf_dir_problem(folder, first, FAM, "UD-IQ1_M")
342            self.assertIsNotNone(problem)
343            self.assertIn("UD-IQ1_S", problem[0] + problem[1])
344            self.assertIn(setup.UNSUPPORTED_WHY["UD-IQ1_S"], problem[1])
345            msg, hint = setup.gguf_dir_problem(folder, shards_of("UD-IQ1_S")[0]["name"] and (Path(t) / shards_of("UD-IQ1_S")[0]["name"]), FAM, "UD-IQ1_S")
346            self.assertIn(setup.UNSUPPORTED_WHY["UD-IQ1_S"], hint)
347
348
349class SecondQ4Layout(unittest.TestCase):
350    """UD-Q4_K_XL at d9620119: the same tensors, the table in a shard of its own.  The pinned files stay what setup downloads; this layout is accepted from files already here."""
351
352    def test_the_names_are_the_pinned_ones_and_the_pins_differ_in_every_shard(self):
353        self.assertEqual(sorted(setup.UNSLOTH_Q4_V31_SHARDS), sorted(setup.UNSLOTH_SHARDS))
354        for n, pin in setup.UNSLOTH_Q4_V31_SHARDS.items():
355            self.assertEqual(pins_of("UD-Q4_K_XL")[n], pin)
356            self.assertNotEqual(pin[0], setup.UNSLOTH_SHARDS[n][0], n)                # the shard boundaries moved: no size is shared
357            self.assertEqual(FAM["sha256"][n], setup.UNSLOTH_SHARDS[n])               # the family's pin (what is downloaded) stays the old one
358            self.assertEqual(FAM["sha256_alt"][n], (pin,))
359        self.assertEqual(sum(b for b, _ in setup.UNSLOTH_Q4_V31_SHARDS.values()), sum(s["bytes"] for s in shards_of("UD-Q4_K_XL")))
360
361    @staticmethod
362    def _file(name, size, exists=True):
363        return types.SimpleNamespace(name=name, exists=lambda: exists, stat=lambda: types.SimpleNamespace(st_size=size))
364
365    def test_fam_pin_picks_the_layout_by_the_size_on_the_disk(self):
366        for n, old in setup.UNSLOTH_SHARDS.items():
367            new = setup.UNSLOTH_Q4_V31_SHARDS[n]
368            self.assertEqual(setup.fam_pin(FAM, self._file(n, old[0])), old, n)
369            self.assertEqual(setup.fam_pin(FAM, self._file(n, new[0])), new, n)
370            self.assertEqual(setup.fam_pin(FAM, self._file(n, 123)), old, n)                  # neither: the pinned one (verify_sha256 then reports it)
371            self.assertEqual(setup.fam_pin(FAM, self._file(n, new[0], exists=False)), old, n)   # nothing there yet: the download's pin
372        other = "Qwen3.8-Flash-Next-UD-IQ1_M-00003-of-00003.gguf"
373        self.assertEqual(setup.fam_pin(FAM, self._file(other, 1)), setup.UNSLOTH_V31_SHARDS[other])
374
375    def test_the_catalog_reads_both_layouts_as_ud_q4_k_xl(self):
376        self.assertEqual(setup.gguf_choice(shards_of("UD-Q4_K_XL")[0]["name"]), ("unsloth", "UD-Q4_K_XL"))
377        self.assertIsNone(setup.gguf_unsupported(shards_of("UD-Q4_K_XL")[0]["name"]))
378
379    def test_verify_sha256_takes_the_second_layout_from_the_users_folder(self):
380        """--gguf-dir with the new files: each is checked against ITS pin; the old pin would have said 'not the published file'."""
381        with tempfile.TemporaryDirectory() as t:
382            f = Path(t) / "Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf"
383            f.write_bytes(b"x" * 100)
384            alt = (100, "ab" * 32)
385            fam = {"sha256": {f.name: setup.UNSLOTH_SHARDS[f.name]}, "sha256_alt": {f.name: (alt,)}}
386            self.assertEqual(setup.fam_pin(fam, f), alt)
387            with mock.patch.object(setup, "_hash_file", return_value=alt[1]):
388                setup.verify_sha256(f, *setup.fam_pin(fam, f), own=True)
389            self.assertIn("sha256 " + alt[1], f.with_name(f.name + ".done").read_text())
390
391
392class Pinning(Base):
393    def test_the_install_checks_the_files_with_fam_pin(self):
394        calls = []
395        real = setup.fam_pin
396        with mock.patch.object(setup, "fam_pin", lambda fam, s: calls.append(s.name) or real(fam, s)):
397            code, out, cfg = self.main(["--context", "8192"], version="0.1.57", m="UD-Q4_K_XL")
398        self.assertEqual(code, 0, out)
399        self.assertEqual(calls, list(setup.UNSLOTH_SHARDS))
400
401
402class FileSetsAndSplit(unittest.TestCase):
403    """strata_control: the known-file-set table the app's "Use a local GGUF" reads, and the split engine's clean decline."""
404
405    def test_known_file_sets(self):
406        from strata_control import models
407        for model in NEW:
408            self.assertIn("unsloth/" + model, models.SUPPORTED_SELECTIONS)
409            got = models._candidate_selection([Path("/m") / s["name"] for s in shards_of(HUB[model])])
410            self.assertEqual((got["family"], got["model"]), ("unsloth", model), model)
411            self.assertEqual(got["expected_tensor_count"], 1224)
412        three = [Path("/m") / n for n in setup.UNSLOTH_IQ4_XS_SHARDS]
413        self.assertEqual(models._candidate_selection(three)["model"], "UD-IQ4_XS")
414        q4 = [Path("/m") / n for n in setup.UNSLOTH_Q4_V31_SHARDS]
415        self.assertEqual(models._candidate_selection(q4)["model"], "UD-Q4_K_XL")
416
417    def _facts(self, set_name):
418        from strata_control import split_engine
419        with tempfile.TemporaryDirectory() as t:
420            first = None
421            for i, s in enumerate(shards_of(set_name)):
422                if s["header"]:
423                    p = FX.materialize(s, Path(t) / s["name"], first=(i == 0))
424                else:
425                    p = FX.materialize({"header": {"split": [0, len(shards_of(set_name)), 1224], "tensors": []}}, Path(t) / s["name"], first=True)
426                first = first or p
427            return split_engine.scan_model(first)
428
429    def _decide(self, facts):
430        from strata_control import split_engine as se
431        cards = [se.Card(index=i, name="RTX A6000", vram_mib=49140, cc=86) for i in range(2)]
432        return se.decide(enabled=True, system="linux", cards=cards, ram_total_gib=128, ram_available_gib=100, model=facts)
433
434    def test_the_split_engine_declines_what_it_cannot_read(self):
435        for model, bad in (("UD-IQ1_M", "IQ2_XXS"), ("UD-Q2_0", "IQ2_XXS"), ("UD-IQ2_XS", "IQ2_XXS"), ("UD-Q2_K_XL", "IQ2_XXS"),
436                           ("UD-Q3_K_XL", "Q5_0"), ("UD-IQ4_XS-v31", "Q5_0")):
437            with self.subTest(model=model):
438                d = self._decide(self._facts(HUB[model]))
439                self.assertFalse(d.use_split)
440                self.assertTrue(any("routed experts use" in r and bad in r for r in d.reasons), d.reasons)
441                self.assertTrue(d.line.startswith("Using the normal layer split"))
442
443    def test_the_split_engine_reads_the_sets_whose_types_it_knows(self):
444        for model in ("UD-IQ3_XXS", "UD-Q4_K_XL"):
445            d = self._decide(self._facts(HUB.get(model, model)))
446            self.assertFalse(any("routed experts use" in r for r in d.reasons), (model, d.reasons))
447
448
449class HeaderRegression(unittest.TestCase):
450    """Every set of the repository at d9620119: the pins and the tensor directories agree with each other."""
451
452    def test_thirteen_sets(self):
453        self.assertEqual(sorted(DOC["sets"]), sorted(["BF16", "Q8_0", "UD-IQ1_M", "UD-IQ1_S", "UD-IQ2_XS", "UD-IQ3_XXS", "UD-IQ4_XS", "UD-Q2_0",
454                                                      "UD-Q2_K_XL", "UD-Q3_K_XL", "UD-Q4_K_XL", "UD-Q5_K_XL", "UD-Q6_K_XL"]))
455        self.assertEqual(DOC["revision"], REV31)
456
457    def test_split_keys_and_tensor_counts(self):
458        for set_name, d in DOC["sets"].items():
459            with self.subTest(set=set_name):
460                shards = d["shards"]
461                m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", shards[0]["name"])
462                self.assertEqual(len(shards), int(m.group(2)))
463                names = [s["name"] for s in shards]
464                self.assertEqual(names, sorted(names))
465                for i, s in enumerate(shards, 1):
466                    self.assertIn("-%05d-of-%05d.gguf" % (i, len(shards)), s["name"])
467                    h = s["header"]
468                    if h is None:
469                        continue
470                    self.assertEqual(h["split"], [i - 1, len(shards), 1224], s["name"])
471                have = [s for s in shards if s["header"]]
472                if len(have) == len(shards) - 1 and shards[0]["header"] is None:       # every shard but the metadata shard was read
473                    seen = [t[0] for s in have for t in s["header"]["tensors"]]
474                    self.assertEqual(len(seen), len(set(seen)))
475                    self.assertEqual(len(seen), 1224)
476
477    def test_every_tensor_lies_inside_its_pinned_shard(self):
478        for set_name, d in DOC["sets"].items():
479            for s in d["shards"]:
480                h = s["header"]
481                if not h:
482                    continue
483                with self.subTest(shard=s["name"]):
484                    end = 0
485                    for name, type_id, shape, off in h["tensors"]:
486                        t = FX.G.TensorInfo(name, shape, type_id, FX.G.GGML_TYPES.get(type_id, "?"), off)
487                        self.assertIsNotNone(t.expected_bytes(), f"{name}: type {type_id}")
488                        end = max(end, off + t.expected_bytes())
489                    self.assertLessEqual(h["data_start"] + end, s["bytes"])
490                    self.assertGreaterEqual(h["data_start"] + end, s["bytes"] - 64)     # (the file ends where its last tensor does)
491
492    def test_the_catalog_sets_have_the_tensor_mix_of_the_plan(self):
493        """PLAN-QUANTS section 2: routed gate/up types by layer, down types, the Q5_0 downs that decide the Mac and the split engine."""
494        want = {
495            "UD-IQ1_M": ({"IQ2_XXS": 23, "IQ2_S": 18, "IQ2_XS": 7}, {"Q2_0": 46, "IQ4_NL": 2}),
496            "UD-Q2_0": ({"IQ2_XXS": 18, "IQ2_S": 30}, {"Q2_0": 39, "IQ4_NL": 9}),
497            "UD-IQ2_XS": ({"IQ2_XXS": 8, "IQ2_S": 40}, {"IQ4_NL": 24, "Q2_0": 23, "Q5_0": 1}),
498            "UD-Q2_K_XL": ({"IQ2_XXS": 5, "IQ2_S": 26, "IQ3_XXS": 17}, {"IQ4_NL": 31, "Q2_0": 16, "Q5_0": 1}),
499            "UD-IQ3_XXS": ({"IQ2_S": 26, "IQ3_XXS": 21, "IQ4_XS": 1}, {"IQ4_NL": 45, "Q2_0": 3}),
500            "UD-Q3_K_XL": ({"IQ2_S": 4, "IQ3_XXS": 38, "IQ4_XS": 6}, {"IQ4_NL": 26, "Q5_0": 20, "Q2_0": 2}),
501            "UD-IQ4_XS": ({"IQ3_XXS": 28, "IQ4_XS": 17, "IQ2_S": 3}, {"Q5_0": 33, "IQ4_NL": 13, "Q2_0": 2}),
502            "UD-Q4_K_XL": ({"Q4_K": 47, "Q5_K": 1}, {"Q5_1": 43, "Q8_0": 5}),
503            "UD-Q5_K_XL": ({"Q5_K": 47, "Q6_K": 1}, {"Q8_0": 48}),
504            "UD-Q6_K_XL": ({"Q6_K": 47, "Q8_0": 1}, {"Q8_0": 48}),
505        }
506        for set_name, (gu, down) in want.items():
507            gate, d = {}, {}
508            for s in shards_of(set_name):
509                for name, type_id, _shape, _off in (s["header"] or {"tensors": []})["tensors"]:
510                    ty = FX.G.GGML_TYPES[type_id]
511                    if re.fullmatch(r"blk\.\d+\.ffn_gate_exps\.weight", name):
512                        gate[ty] = gate.get(ty, 0) + 1
513                    elif re.fullmatch(r"blk\.\d+\.ffn_down_exps\.weight", name):
514                        d[ty] = d.get(ty, 0) + 1
515            with self.subTest(set=set_name):
516                self.assertEqual(gate, gu)
517                self.assertEqual(d, down)
518
519    def test_ud_iq1_s_layer_18_has_different_gate_and_up_types(self):
520        types_ = {}
521        for s in shards_of("UD-IQ1_S"):
522            for name, type_id, _shape, _off in (s["header"] or {"tensors": []})["tensors"]:
523                if name in ("blk.18.ffn_gate_exps.weight", "blk.18.ffn_up_exps.weight"):
524                    types_[name] = FX.G.GGML_TYPES[type_id]
525        self.assertEqual(types_, {"blk.18.ffn_gate_exps.weight": "IQ2_S", "blk.18.ffn_up_exps.weight": "IQ2_XXS"})
526
527    def test_the_unchanged_sets_have_the_pinned_shards_at_the_new_commit(self):
528        for set_name, table in (("UD-Q5_K_XL", None), ("UD-Q6_K_XL", None), ("Q8_0", None)):
529            self.assertTrue(all(setup.UNSLOTH_BIG_SHARDS[n] == p for n, p in pins_of(set_name).items()))
530        # and the three-shard UD-IQ4_XS at the pinned commit is not the four-shard set at the new one
531        self.assertTrue(set(pins_of("UD-IQ4_XS")).isdisjoint(setup.UNSLOTH_IQ4_XS_SHARDS))
532
533
534if __name__ == "__main__":
535    unittest.main()