okami.mom/strata

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

Niko1221Merge f-0210-draftsw-dl: switching the model resets Drafting to Auto (Terminal and app); the Q4_0 selector pack is converted only for an engine that carries it45c71cf9c

main
14.8 KiB240 linesraw
1"""The DFlash2 pack with the Q4_0 selector (174 MiB less graphics memory): made on this computer from the checked Q4_0 pack, used only when it verifies and the engine reads it.
2
3The idea and the bytes are nazeshinjite's (https://huggingface.co/nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF, Apache-2.0): the community GGUF stores the selector's two
4codebooks as Q4_0, and tools/dflash2_pack.py --q4_0-selector writes exactly those bytes (checked against the GGUF with the real checkpoint: RESULTS-DF2MEM.md section 15).
5These tests use the small synthetic checkpoint of tools/test_dflash2_pack.py: the real pins cannot be exercised without the 1.2 GB download, so the pinned numbers are
6checked for consistency and the mechanism with pins of the synthetic pack.
7"""
8
9from __future__ import annotations
10
11import hashlib
12import importlib.util
13import json
14import os
15import sys
16import tempfile
17import unittest
18from pathlib import Path
19from unittest import mock
20
21from strata_control import drafting, drafting_fetch
22
23ROOT = Path(__file__).resolve().parents[2]
24VOCAB_REAL, RANK_REAL = 248320, 256
25
26
27def _load(name, rel):
28    spec = importlib.util.spec_from_file_location(name, ROOT / rel)
29    module = importlib.util.module_from_spec(spec)
30    sys.modules.setdefault(name, module)
31    spec.loader.exec_module(module)
32    return module
33
34
35class PinnedNumbers(unittest.TestCase):
36    def test_the_converted_pack_is_the_q4_pack_less_the_codebooks_difference(self):
37        """CONVERTED_BYTES follows from PACK_BYTES by arithmetic alone: two codebooks of 248,320 x 256 go from bf16 (2 bytes a value) to Q4_0 (18 bytes per 32 values)."""
38        bf16 = 2 * VOCAB_REAL * RANK_REAL * 2
39        q4 = 2 * VOCAB_REAL * (RANK_REAL // 32) * 18
40        self.assertEqual(drafting.PACK_BYTES - drafting.CONVERTED_BYTES, bf16 - q4)
41        self.assertEqual(bf16 - q4, 182763520)
42        self.assertEqual(len(drafting.CONVERTED_SHA256), 64)
43        self.assertNotEqual(drafting.CONVERTED_SHA256, drafting.PACK_SHA256)
44
45
46class SmallPacks(unittest.TestCase):
47    """A synthetic checkpoint packed as the Q4_0 pack, then converted."""
48
49    @classmethod
50    def setUpClass(cls):
51        cls.synth = _load("t_pack_sel", "tools/test_dflash2_pack.py")
52        cls.packer = _load("strata_dflash2_pack_sel", "tools/dflash2_pack.py")
53
54    def setUp(self):
55        self.tmp = tempfile.TemporaryDirectory()
56        self.addCleanup(self.tmp.cleanup)
57        self.dir = Path(self.tmp.name)
58        self.synth.write_safetensors(self.dir / "m.safetensors", self.synth.tensors())
59        (self.dir / "c.json").write_text(json.dumps(self.synth.CFG))
60        self.data = self.dir / "data"
61        self.q4 = drafting.target_path(self.data)
62        self.q4.parent.mkdir(parents=True)
63        self.packer.pack(str(self.dir / "m.safetensors"), str(self.dir / "c.json"), str(self.q4), say=lambda *_: None, q4=True)
64        self.src_pins = {"source_bytes": self.q4.stat().st_size, "source_sha256": hashlib.sha256(self.q4.read_bytes()).hexdigest()}
65        direct = self.dir / "direct.pack"
66        self.packer.pack(str(self.dir / "m.safetensors"), str(self.dir / "c.json"), str(direct), say=lambda *_: None, q4=True, q4_selector=True)
67        self.pins = {"size": direct.stat().st_size, "sha256": hashlib.sha256(direct.read_bytes()).hexdigest(), **self.src_pins}
68        self.direct = direct
69
70    def convert(self, **extra):
71        return drafting_fetch.convert_selector(self.data, **{**self.pins, **extra})
72
73    def test_the_conversion_reproduces_the_pinned_bytes(self):
74        """The pack converted from the finished Q4_0 pack is byte-identical to the one packed straight from the checkpoint with --q4_0-selector (the pinned hash)."""
75        out = self.convert()
76        self.assertEqual(out, drafting.converted_path(self.data))
77        self.assertEqual(out.read_bytes(), self.direct.read_bytes())
78        self.assertLess(out.stat().st_size, self.q4.stat().st_size)
79        self.assertTrue(drafting.converted_ok(self.data, size=self.pins["size"], sha256=self.pins["sha256"]))
80        self.assertTrue(self.q4.is_file(), "the Q4_0 pack stays: it is the fallback")
81
82    def test_every_tensor_but_the_two_codebooks_is_carried_over_unchanged(self):
83        out = self.convert()
84        a, b = self.q4.read_bytes(), out.read_bytes()
85
86        def table(blob):
87            n = int.from_bytes(blob[8:12], "little")
88            rows = {}
89            for line in blob[12:12 + n].decode().split("\n"):
90                w = line.split()
91                if w and w[0] == "t":
92                    rows[w[1]] = (w[2], int(w[5]), int(w[6]))
93            return rows, 12 + n
94        ta, base_a = table(a)
95        tb, base_b = table(b)
96        self.assertEqual(set(ta), set(tb))
97        books = {"candidate_selector.predecessor_codebook", "candidate_selector.successor_codebook"}
98        for name in ta:
99            ba = a[base_a + ta[name][1]: base_a + ta[name][1] + ta[name][2]]
100            bb = b[base_b + tb[name][1]: base_b + tb[name][1] + tb[name][2]]
101            if name in books:
102                self.assertEqual((ta[name][0], tb[name][0]), ("bf16", "q4_0"))
103                self.assertEqual(len(bb) * 32, len(ba) * 9, name)       # 18 bytes per 32 values against 2 bytes a value
104            else:
105                self.assertEqual(ba, bb, name)
106
107    def test_a_missing_corrupt_or_short_converted_pack_falls_back_to_the_q4_pack(self):
108        eng = self.dir / "engine"
109        eng.write_bytes(b"\0" * 64 + drafting._MARK_SELQ4 + b"\0" * 64)
110        self.assertEqual(drafting.pack_path(self.data, eng), self.q4, "not made yet")
111        out = self.convert()
112        with mock.patch.object(drafting, "CONVERTED_BYTES", self.pins["size"]), mock.patch.object(drafting, "CONVERTED_SHA256", self.pins["sha256"]):
113            self.assertEqual(drafting.pack_path(self.data, eng), out)
114            blob = bytearray(out.read_bytes())
115            blob[len(blob) // 2] ^= 0xFF                      # one flipped byte, the same size, and the marker still describes the old file
116            before = out.stat()
117            out.write_bytes(bytes(blob))
118            # (a real corruption happens long after the marker was written; on Linux the kernel's file clock ticks in ~4 ms steps, so a rewrite right away can keep the
119            #  same mtime_ns and the marker would still describe the file: let the clock move on, as it does in real life)
120            os.utime(out, ns=(before.st_atime_ns, before.st_mtime_ns + 1_000_000_000))
121            self.assertEqual(drafting.pack_path(self.data, eng), self.q4, "a corrupt file (the marker no longer matches it) is not used")
122            out.write_bytes(bytes(blob)[:-1000])
123            self.assertEqual(drafting.pack_path(self.data, eng), self.q4, "a short file is not used")
124            out.unlink()
125            self.assertEqual(drafting.pack_path(self.data, eng), self.q4, "a missing file is not used")
126
127    def test_a_q4_pack_that_is_not_the_pinned_one_is_left_alone(self):
128        self.assertIsNone(self.convert(source_sha256="0" * 64))
129        self.assertFalse(drafting.converted_path(self.data).exists())
130        self.assertTrue(self.q4.is_file())
131
132    def test_a_result_that_does_not_match_the_pin_is_deleted(self):
133        self.assertIsNone(self.convert(sha256="f" * 64))
134        self.assertFalse(drafting.converted_path(self.data).exists())
135        self.assertFalse(drafting.converted_path(self.data).with_suffix(".tmp").exists())
136
137    def test_a_failing_conversion_is_never_an_error_for_the_caller(self):
138        with mock.patch.object(drafting_fetch, "_packer", side_effect=RuntimeError("no numpy")):
139            self.assertIsNone(self.convert())
140        self.assertFalse(drafting.converted_path(self.data).exists())
141
142    def test_the_engine_must_read_the_pack_before_it_is_used(self):
143        out = self.convert()
144        old = self.dir / "old-engine"
145        old.write_bytes(b"\0" * 256)
146        new = self.dir / "new-engine"
147        new.write_bytes(b"\0" * 64 + drafting._MARK_SELQ4 + b"\0" * 64)
148        with mock.patch.object(drafting, "CONVERTED_BYTES", self.pins["size"]), mock.patch.object(drafting, "CONVERTED_SHA256", self.pins["sha256"]):
149            self.assertEqual(drafting.pack_path(self.data), self.q4, "no engine named: the pack every engine reads")
150            self.assertEqual(drafting.pack_path(self.data, old), self.q4, "an engine without the text would read the rows as garbage")
151            self.assertEqual(drafting.pack_path(self.data, self.dir / "none"), self.q4)
152            self.assertEqual(drafting.pack_path(self.data, new), out)
153
154    def test_auto_arguments_point_at_the_converted_pack(self):
155        self.convert()
156        new = self.dir / "new-engine"
157        new.write_bytes(b"\0" * 64 + drafting._MARK_SELQ4 + b"\0" * 64 + b"--draft-fallback" + b"--mtp-draft-vocab FILE (or --mtp DIR")
158        vocab = self.data / drafting.FOLDER / drafting.VOCAB_NAME
159        vocab.write_bytes(b"\1\0\0\0" * 8)
160        cfg = {"model_name": "qwen3.8-flash-next-iq3_s", "drafting": "dflash2", "args": ["--spec", "4", "--expert-cache", "1000"]}
161        with mock.patch.object(drafting, "CONVERTED_BYTES", self.pins["size"]), mock.patch.object(drafting, "CONVERTED_SHA256", self.pins["sha256"]), \
162                mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True), mock.patch.object(drafting, "pack_ready", return_value=True):
163            drafting.apply(cfg, klass="blackwell", data_dir=self.data, backend="cuda", archs=["sm_120"], engine=new)
164            args = cfg["args"]
165            self.assertEqual(args[args.index("--draft-model") + 1], str(drafting.converted_path(self.data)))
166            cfg2 = {"model_name": "qwen3.8-flash-next-iq3_s", "drafting": "dflash2", "args": ["--spec", "4", "--expert-cache", "1000"]}
167            drafting.apply(cfg2, klass="blackwell", data_dir=self.data, backend="cuda", archs=["sm_120"], engine=None)
168            self.assertEqual(cfg2["args"][cfg2["args"].index("--draft-model") + 1], str(self.q4), "an engine that is not known gets the pack every engine reads")
169
170    def test_needs_conversion_only_when_dflash2_is_chosen_and_the_q4_pack_is_here(self):
171        want = dict(mode="dflash2", model_name="qwen3.8-flash-next-iq3_s", data_dir=self.data, backend="cuda", archs=["sm_120"])
172        with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True), mock.patch.object(drafting, "_here", lambda p: Path(p).is_file()):
173            self.assertTrue(drafting.needs_conversion(**want))
174            self.assertFalse(drafting.needs_conversion(**{**want, "mode": "mtp"}))
175            self.assertFalse(drafting.needs_conversion(**{**want, "data_dir": self.dir / "empty"}))
176            self.convert()
177            with mock.patch.object(drafting, "CONVERTED_BYTES", self.pins["size"]), mock.patch.object(drafting, "CONVERTED_SHA256", self.pins["sha256"]):
178                self.assertFalse(drafting.needs_conversion(**want), "already made")
179
180    def test_setup_and_load_convert_a_start_does_not(self):
181        """ensure() (strata drafting fetch, setup) converts a pack that is already here, with no network; the serving side only reads."""
182        with mock.patch.object(drafting_fetch, "convert_selector") as convert, mock.patch.object(drafting, "pack_ready", return_value=True),                 mock.patch.object(drafting, "engine_has_selector_q4", return_value=True):
183            drafting_fetch.ensure(self.data)
184        convert.assert_called_once()
185        with mock.patch.object(drafting_fetch, "convert_selector") as convert, mock.patch.object(drafting, "pack_ready", return_value=True),                 mock.patch.object(drafting, "engine_has_selector_q4", return_value=False):
186            drafting_fetch.ensure(self.data)
187        convert.assert_not_called()          # an engine that cannot read the Q4_0 selector (the SYCL one) or none installed yet: the 340 MB file would never be used
188        source = (ROOT / "serve" / "server.py").read_text(encoding="utf-8")
189        self.assertNotIn("convert_selector", source)
190        self.assertNotIn("convert_selector", (ROOT / "strata_cli" / "launch" / "plan.py").read_text(encoding="utf-8") if (ROOT / "strata_cli" / "launch" / "plan.py").exists() else "")
191
192
193class TheTrueGraphicsMemory(unittest.TestCase):
194    """drafting.vram_gb: 0.72 GB with the converted pack (an engine that reads it), 0.89 GB otherwise; the plan and its text say the same number."""
195
196    def setUp(self):
197        self.tmp = tempfile.TemporaryDirectory()
198        self.addCleanup(self.tmp.cleanup)
199        self.dir = Path(self.tmp.name)
200        self.new = self.dir / "new-engine"
201        self.new.write_bytes(b"\0" * 64 + drafting._MARK_SELQ4 + b"\0" * 64)
202        self.old = self.dir / "old-engine"
203        self.old.write_bytes(b"\0" * 256)
204        self.data = self.dir / "data"
205        (self.data / drafting.FOLDER).mkdir(parents=True)
206
207    def pack(self, name):
208        (self.data / drafting.FOLDER / name).write_bytes(b"x" * ((1 << 20) + 1))
209
210    def test_the_table(self):
211        self.assertEqual((drafting.DRAFTER_MIB["dflash2"], drafting.DRAFTER_MIB["dflash2_selq4"], drafting.DRAFTER_MIB["mtp"]), (890, 715, 1082))
212        self.assertEqual((drafting.DRAFTER_GB["dflash2"], drafting.DRAFTER_GB["dflash2_selq4"], drafting.DRAFTER_GB["mtp"], drafting.DRAFTER_GB["off"]), (0.89, 0.72, 1.08, 0.0))
213        self.assertEqual(drafting.VRAM_GB, 0.89, "the bf16-selector figure stays the module constant")
214
215    def test_the_figure_follows_the_engine_and_the_pack(self):
216        self.pack(drafting.PACK_NAME)
217        self.assertEqual(drafting.vram_gb(self.data, self.new), 0.72)
218        self.assertEqual(drafting.vram_gb(self.data, self.old), 0.89, "an engine without the text keeps the bf16 selector")
219        self.assertEqual(drafting.vram_gb(self.data, None), 0.89, "an engine that is not known: the larger figure")
220        self.assertEqual(drafting.vram_gb(None, self.new), 0.72, "no data folder yet: the pack will be the Q4_0 one")
221
222    def test_a_q8_pack_of_an_earlier_strata_is_never_converted_so_the_figure_stays(self):
223        self.pack(drafting.LEGACY_PACK_NAME)
224        self.assertEqual(drafting.vram_gb(self.data, self.new), 0.89)
225        self.pack(drafting.PACK_NAME)                                        # the Q4_0 pack beside it wins (pack_path): the converted figure
226        self.assertEqual(drafting.vram_gb(self.data, self.new), 0.72)
227
228    def test_the_plan_says_the_same_number_in_words_and_in_the_fields(self):
229        plan = drafting_fetch.plan(self.data, self.new)
230        self.assertEqual((plan["vram_gb"], plan["selq4"]), (0.72, True))
231        self.assertIn("about 0.7 GB of graphics memory", plan["text"])
232        plan = drafting_fetch.plan(self.data, self.old)
233        self.assertEqual((plan["vram_gb"], plan["selq4"]), (0.89, False))
234        self.assertIn("about 0.9 GB of graphics memory", plan["text"])
235        plan = drafting_fetch.plan(self.data)
236        self.assertEqual((plan["vram_gb"], plan["selq4"]), (0.89, False))
237
238
239if __name__ == "__main__":
240    unittest.main()