okami.mom/strata

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

Niko1221Merge f-draft-vocab 925d6fb05 into f-p4-int (the draft vocabulary is picked by the computer's languages; a renamed Flash-Next file starts the drafter)bc6f248ff

main
17.3 KiB269 linesraw
1"""A model file under a name setup does not write (renamed, a hand-written config, no name) is judged by what the file IS: its GGUF header (architecture, layers, hidden size,
2vocabulary size) against what the DFlash2 drafter pack records. A renamed Qwen3.8-Flash-Next file used to start the MTP with no word said (strata_control/drafting.py, apply)."""
3
4from __future__ import annotations
5
6import json
7import struct
8import tempfile
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from strata_control import drafting
14
15ROOT = Path(__file__).resolve().parents[2]
16REAL_HEADER = ROOT / "tests" / "terminal" / "data" / "flash_next_iq3s_header.gguf"   # the first 2,710 bytes of the Qwen3.8-Flash-Next IQ3_S file: the keys, no weights
17_HARDWARE = mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"]))
18
19
20def setUpModule():
21    _HARDWARE.start()
22
23
24def tearDownModule():
25    _HARDWARE.stop()
26
27
28def _s(text: str) -> bytes:
29    raw = text.encode()
30    return struct.pack("<Q", len(raw)) + raw
31
32
33def gguf_header(arch="qwen4exp", layers=48, hidden=2560, vocab=248320, tokens=True) -> bytes:
34    """A GGUF header with the keys the drafter's test reads; the vocabulary array is announced (its count) and not written."""
35    kvs = [(_s("general.architecture"), struct.pack("<I", 8) + _s(arch)),
36           (_s("general.name"), struct.pack("<I", 8) + _s("renamed")),
37           (_s(f"{arch}.block_count"), struct.pack("<I", 4) + struct.pack("<I", layers)),
38           (_s(f"{arch}.context_length"), struct.pack("<I", 4) + struct.pack("<I", 262144)),
39           (_s(f"{arch}.embedding_length"), struct.pack("<I", 4) + struct.pack("<I", hidden)),
40           (_s(f"{arch}.rope.dimension_sections"), struct.pack("<I", 9) + struct.pack("<IQ", 5, 4) + struct.pack("<4i", 11, 11, 10, 0))]
41    if tokens:
42        kvs.append((_s("tokenizer.ggml.tokens"), struct.pack("<I", 9) + struct.pack("<IQ", 8, vocab)))
43    body = b"".join(k + v for k, v in kvs)
44    return b"GGUF" + struct.pack("<IQQ", 3, 0, len(kvs)) + body
45
46
47def pack_with(**cfg) -> bytes:
48    """The start of a DFlash2 pack: "DF2P", version, index length, the text index with its cfg lines."""
49    lines = "".join(f"cfg {k} {v}\n" for k, v in cfg.items()) + "end\n"
50    index = lines.encode()
51    return b"DF2P" + struct.pack("<II", 1, len(index)) + index
52
53
54class ReadingTheHeader(unittest.TestCase):
55    def test_the_real_header_of_the_flash_next_file(self):
56        self.assertEqual(drafting.gguf_facts(REAL_HEADER), {"arch": "qwen4exp", "layers": 48, "hidden": 2560, "vocab": 248320})
57        self.assertEqual(drafting.file_fit(["--native", str(REAL_HEADER)]), "fits")
58
59    def test_a_synthetic_header_and_what_it_cannot_be(self):
60        with tempfile.TemporaryDirectory() as tmp:
61            p = Path(tmp) / "m.gguf"
62            p.write_bytes(gguf_header())
63            self.assertEqual(drafting.gguf_facts(p), {"arch": "qwen4exp", "layers": 48, "hidden": 2560, "vocab": 248320})
64            p.write_bytes(gguf_header(tokens=False))
65            self.assertEqual(drafting.gguf_facts(p)["vocab"], None, "no vocabulary key: not a reason to refuse")
66            self.assertEqual(drafting.file_fit(["--native", str(p)]), "fits")
67            p.write_bytes(b"not a gguf at all, just text" * 10)
68            self.assertIsNone(drafting.gguf_facts(p))
69            self.assertEqual(drafting.file_fit(["--native", str(p)]), "unknown")
70            p.write_bytes(b"GGUF" + b"\x03\x00\x00\x00" + b"\xff" * 40)
71            self.assertEqual(drafting.file_fit(["--native", str(p)]), "unknown", "a damaged header is no answer, never an error")
72            self.assertEqual(drafting.file_fit(["--native", str(Path(tmp) / "missing.gguf")]), "unknown")
73        self.assertEqual(drafting.file_fit([]), "unknown")
74
75    def test_the_fits_test_by_shape(self):
76        with tempfile.TemporaryDirectory() as tmp:
77            p = Path(tmp) / "m.gguf"
78            for kw, want in ((dict(), "fits"), (dict(hidden=4096), "family"), (dict(layers=40), "family"), (dict(layers=46), "fits"), (dict(layers=45), "family"),
79                              (dict(vocab=151936), "family"), (dict(arch="qwen35moe"), "other"), (dict(arch="llama"), "other")):
80                p.write_bytes(gguf_header(**kw))
81                self.assertEqual(drafting.file_fit(["--native", str(p)]), want, kw)
82
83    def test_the_pack_says_what_it_was_made_for(self):
84        with tempfile.TemporaryDirectory() as tmp:
85            data = Path(tmp)
86            self.assertEqual(drafting.pack_target(data), drafting.PACK_TARGET, "no pack here: what the code knows")
87            pack = drafting.target_path(data)
88            pack.parent.mkdir(parents=True)
89            pack.write_bytes(pack_with(hidden=3072, vocab=151936, taps="3,9,15") + b"\0" * 64)
90            self.assertEqual(drafting.pack_target(data), {"hidden": 3072, "vocab": 151936, "taps": (3, 9, 15)})
91            m = Path(tmp) / "m.gguf"
92            m.write_bytes(gguf_header())
93            self.assertEqual(drafting.file_fit(["--native", str(m)], data), "family", "the pack on this computer decides, not the table in the code")
94            m.write_bytes(gguf_header(hidden=3072, vocab=151936, layers=20))
95            self.assertEqual(drafting.file_fit(["--native", str(m)], data), "fits")
96
97
98class ARenamedFileAtStart(unittest.TestCase):
99    HARDWARE = (("cuda", ["sm_120"]), ("hip", ["gfx1151"]), ("metal", None))
100
101    def config(self, tmp, name, header, mode=None):
102        data = Path(tmp)
103        mtp = data / "mtp" / "rt"
104        mtp.mkdir(parents=True)
105        (mtp / "experts.bin").write_bytes(b"e")
106        (mtp / "draft_vocab.bin").write_bytes(b"v")
107        pack = drafting.pack_path(data)
108        pack.parent.mkdir(parents=True)
109        pack.write_bytes(b"x" * (2 << 20))
110        model = data / "my-copy.gguf"
111        model.write_bytes(header)
112        args = ["--pack", str(data / "packs" / "x"), "--native", str(model), "--mtp", str(mtp), "--spec", "4", "--spec-min-p", "0.5"]
113        cfg = {"args": args, **({} if name is None else {"model_name": name}), **({} if mode is None else {"drafting": mode})}
114        return cfg, data
115
116    def test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said(self):
117        for backend, archs in self.HARDWARE:
118            for name in ("my-copy", "Qwen3.8 Flash Next (my copy)", "", None, "qwen3.8-flash-next-unslothx-q8_0"):
119                for mode in (None, "auto", "dflash2"):
120                    with tempfile.TemporaryDirectory() as tmp:
121                        cfg, data = self.config(tmp, name, gguf_header(), mode)
122                        decision = drafting.apply(cfg, data_dir=data, backend=backend, archs=archs)
123                        self.assertEqual((decision.drafter, decision.note), ("dflash2", ""), (backend, name, mode))
124                        self.assertEqual(cfg["args"][cfg["args"].index("--draft") + 1], "dflash2")
125                        self.assertNotIn("--mtp", cfg["args"])
126
127    def test_the_names_setup_writes_are_decided_as_before(self):
128        """A supported name never reads the file: a name setup wrote is the answer, as in every release before."""
129        with tempfile.TemporaryDirectory() as tmp:
130            cfg, data = self.config(tmp, "qwen3.8-flash-next-iq3_s", b"")
131            with mock.patch.object(drafting, "file_fit", side_effect=AssertionError("the file is not read")):
132                self.assertEqual(drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"]).drafter, "dflash2")
133
134    def test_coder_nvfp4_and_swift_stay_out_whatever_the_file_says(self):
135        for name in ("qwen3.8-flash-next-coder-iq1_m", "qwen3.8-flash-next-nvfp4-nvfp4", "swift-1.5-iq2_xs", "My-Coder-copy"):
136            for mode in (None, "auto"):
137                with tempfile.TemporaryDirectory() as tmp:
138                    cfg, data = self.config(tmp, name, gguf_header(), mode)
139                    original = list(cfg["args"])
140                    decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"])
141                    self.assertEqual((decision.drafter, decision.note), ("mtp", ""), name)
142                    self.assertEqual(cfg["args"], original)
143
144    def test_a_flash_next_family_file_the_drafter_does_not_fit_starts_the_mtp_and_says_so(self):
145        for header in (gguf_header(hidden=4096), gguf_header(layers=36), gguf_header(vocab=262144)):
146            for name in ("my-copy", None):
147                with tempfile.TemporaryDirectory() as tmp:
148                    cfg, data = self.config(tmp, name, header, "auto")
149                    original = list(cfg["args"])
150                    decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"])
151                    self.assertEqual((decision.drafter, decision.note), ("mtp", drafting.NOT_SUPPORTED))
152                    self.assertEqual(drafting.summary_line(decision), "Drafting: MTP (DFlash2 is for Qwen3.8-Flash-Next only)")
153                    self.assertEqual(cfg["args"], original, "the MTP's own arguments")
154                    self.assertNotIn("--draft", cfg["args"])
155
156    def test_another_model_is_not_this_choices_business(self):
157        """A Qwen3.6 or Llama file under an unknown name: the MTP as before, no line (the drafter was never an option for it, so nothing is lost)."""
158        for arch in ("qwen35moe", "llama"):
159            with tempfile.TemporaryDirectory() as tmp:
160                cfg, data = self.config(tmp, "my-copy", gguf_header(arch=arch), "auto")
161                original = list(cfg["args"])
162                decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"])
163                self.assertEqual((decision.drafter, decision.note), ("mtp", ""), arch)
164                self.assertEqual(cfg["args"], original)
165
166    def test_an_unreadable_or_missing_file_is_what_it_was(self):
167        with tempfile.TemporaryDirectory() as tmp:
168            cfg, data = self.config(tmp, "my-copy", b"junk")
169            decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"])
170            self.assertEqual((decision.drafter, decision.note), ("mtp", ""))
171            cfg["args"][cfg["args"].index("--native") + 1] = str(Path(tmp) / "gone.gguf")
172            self.assertEqual(drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"]).note, "")
173
174    def test_dflash2_named_on_another_model_says_it_cannot(self):
175        with tempfile.TemporaryDirectory() as tmp:
176            cfg, data = self.config(tmp, "my-copy", gguf_header(arch="llama"), "dflash2")
177            decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"])
178            self.assertEqual((decision.drafter, decision.note), ("mtp", drafting.NOT_SUPPORTED))
179
180    def test_the_terminal_that_knows_the_family_does_not_read_the_file(self):
181        with tempfile.TemporaryDirectory() as tmp:
182            cfg, data = self.config(tmp, "my-copy", gguf_header(arch="llama"), "auto")
183            with mock.patch.object(drafting, "file_fit", side_effect=AssertionError("the family is the answer")):
184                self.assertEqual(drafting.apply(cfg, data_dir=data, family="qwen", backend="cuda", archs=["sm_120"]).drafter, "dflash2")
185                self.assertEqual(drafting.apply(dict(cfg), data_dir=data, family="coder", backend="cuda", archs=["sm_120"]).drafter, "mtp")
186
187
188class AKnownSetUnderAnotherName(unittest.TestCase):
189    """A renamed file that is EXACTLY one of data/gguf_fingerprints.json's sets (tensor count, payload bytes, expert formats over every shard) is treated under that set's own name, so it gets the set's table entry
190    (tuned pack, confidence); anything else keeps the general defaults. The layout guess (a fine-tune that only looks like a set) never counts."""
191
192    ROW = json.loads((ROOT / "data" / "gguf_fingerprints.json").read_text(encoding="utf-8"))["qwen/IQ3_S"]
193
194    def shards(self, tmp, names=("copy-00001-of-00002.gguf", "copy-00002-of-00002.gguf")):
195        for n in names:
196            (Path(tmp) / n).write_bytes(b"x")
197        return Path(tmp) / names[0]
198
199    def fake(self, tensors, payload, experts, arch="qwen4exp", second_arch=None):
200        """inspect_metadata of two shards: the totals are split between them; the second shard of a real split set has no architecture key (seen on the real IQ3_S files)."""
201        halves = iter(((tensors - tensors // 2, payload - payload // 2, experts, arch), (tensors // 2, payload // 2, set(), second_arch)))
202
203        def inspect(path):
204            t, p, e, a = next(halves)
205            return {"architecture": a, "expert_tensor_types": sorted(e), "tensor_count_scanned": t, "payload_bytes_required": p}
206        return mock.patch("strata_control.models.inspect_metadata", side_effect=inspect)
207
208    def test_the_header_of_a_set_names_it(self):
209        from strata_control import models
210        experts = set(self.ROW["expert_bytes"])
211        with tempfile.TemporaryDirectory() as tmp:
212            first = self.shards(tmp)
213            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts):
214                self.assertEqual(models.known_set_by_header(first), "qwen/IQ3_S")
215            with self.fake(self.ROW["tensors"], self.ROW["bytes"] + 1, experts):
216                self.assertIsNone(models.known_set_by_header(first), "one byte of payload more: not that set")
217            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts | {"Q8_0"}):
218                self.assertIsNone(models.known_set_by_header(first), "another expert format: not that set")
219            with self.fake(self.ROW["tensors"] - 1, self.ROW["bytes"], experts):
220                self.assertIsNone(models.known_set_by_header(first))
221            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts, arch="llama"):
222                self.assertIsNone(models.known_set_by_header(first))
223            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts, second_arch="qwen4exp"):
224                self.assertEqual(models.known_set_by_header(first), "qwen/IQ3_S", "a later shard may name the architecture too")
225            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts, second_arch="llama"):
226                self.assertIsNone(models.known_set_by_header(first), "a later shard of another architecture")
227            with mock.patch.object(models, "_candidate_by_layout", side_effect=AssertionError("the layout guess is never used")), self.fake(self.ROW["tensors"], self.ROW["bytes"] // 2, experts):
228                self.assertIsNone(models.known_set_by_header(first), "a file with the layout of a set is not that set")
229            (Path(tmp) / "copy-00002-of-00002.gguf").unlink()
230            with self.fake(self.ROW["tensors"], self.ROW["bytes"], experts):
231                self.assertIsNone(models.known_set_by_header(first), "a shard missing")
232            with mock.patch("strata_control.models.inspect_metadata", side_effect=OSError("unreadable")):
233                self.assertIsNone(models.known_set_by_header(first))
234        self.assertIsNone(models.known_set_by_header("/no/such/file.gguf"))
235
236    def test_the_name_setup_would_have_written(self):
237        for found, want in (("qwen/IQ3_S", "qwen3.8-flash-next-iq3_s"), ("unsloth/UD-Q4_K_XL", "qwen3.8-flash-next-unsloth-ud-q4_k_xl"), ("gyro/Gyro-S", "qwen3.8-flash-next-gyro-gyro-s"),
238                            ("unsloth/UD-IQ4_XS-v31", "qwen3.8-flash-next-unsloth-ud-iq4_xs-v31"), ("coder/IQ1_M", None), ("swift/IQ3_S", None), (None, None)):
239            drafting._known_names.clear()
240            with tempfile.TemporaryDirectory() as tmp:
241                model = Path(tmp) / "m.gguf"
242                model.write_bytes(b"x")
243                with mock.patch("strata_control.models.known_set_by_header", return_value=found) as call:
244                    self.assertEqual(drafting.known_name_of_file(["--native", str(model)]), want, found)
245                    self.assertEqual(drafting.known_name_of_file(["--native", str(model)]), want)
246                    self.assertEqual(call.call_count, 1, "read once per file, size and time")
247        self.assertIsNone(drafting.known_name_of_file([]))
248        self.assertIsNone(drafting.known_name_of_file(["--native", "/no/such/file.gguf"]))
249
250    def test_a_renamed_known_set_is_decided_under_its_own_name_and_any_other_under_the_general_one(self):
251        for known, want in ("qwen3.8-flash-next-iq3_s", "qwen3.8-flash-next-iq3_s"), (None, drafting.FILE_FITS_AS):
252            with tempfile.TemporaryDirectory() as tmp:
253                cfg, data = ARenamedFileAtStart("test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said").config(tmp, "my-copy", gguf_header(), "auto")
254                seen = []
255                real = drafting.tuned_applies
256                with mock.patch.object(drafting, "known_name_of_file", return_value=known),                         mock.patch.object(drafting, "tuned_applies", side_effect=lambda backend, name, *a, **k: (seen.append(name), real(backend, name, *a, **k))[1]):
257                    decision = drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"], vram_mib=73728)
258                self.assertEqual((decision.drafter, decision.note), ("dflash2", ""))
259                self.assertEqual(seen, [want])
260
261    def test_a_name_setup_wrote_never_reads_the_file_for_its_set(self):
262        with tempfile.TemporaryDirectory() as tmp:
263            cfg, data = ARenamedFileAtStart("test_a_renamed_flash_next_file_starts_dflash2_with_nothing_said").config(tmp, "qwen3.8-flash-next-iq3_s", gguf_header())
264            with mock.patch.object(drafting, "known_name_of_file", side_effect=AssertionError("not read")):
265                self.assertEqual(drafting.apply(cfg, data_dir=data, backend="cuda", archs=["sm_120"]).drafter, "dflash2")
266
267
268if __name__ == "__main__":
269    unittest.main()