okami.mom/strata

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

Niko1221Merge f-ds-out ac306afb2 into f-own-intaff3a132f

main
26.9 KiB403 linesraw
1"""The DFlash2 option: where the engine can run it, the window it is started with, and the download when there is no internet or the files are already here.
2(tests/terminal/test_drafting.py has the table, the Terminal flag and the pinned download.)"""
3
4from __future__ import annotations
5
6import hashlib
7import importlib.util
8import json
9import socket
10import sys
11import tempfile
12import time
13import unittest
14from pathlib import Path
15from unittest import mock
16
17from strata_control import drafting, drafting_fetch
18from tests.terminal.launch_support import run_cli
19
20ROOT = Path(__file__).resolve().parents[2]
21GYRO = "qwen3.8-flash-next-gyro-gyro-s"
22
23
24def serving_dflash2():
25    return mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", True)
26
27
28class IntelCardsAreToldByName(unittest.TestCase):
29    """The SYCL path gives no architecture: an Intel card is told by its Windows adapter name or its Linux PCI id. Arc A-series (A3xx / A5xx / A7xx) was measured (the A750)
30    and counts as tested; B-series (Battlemage), the Pro cards and integrated graphics keep "has not been tested on your graphics card yet"."""
31
32    def test_names(self):
33        k = drafting.sycl_arch_of_name
34        for name in ("Intel(R) Arc(TM) A750 Graphics", "Intel(R) Arc(TM) A380 Graphics", "Intel(R) Arc(TM) A770 Graphics", "Intel(R) Arc(TM) A580 Graphics",
35                     "Intel(R) Arc(TM) A770M Graphics", "Intel Arc A310"):
36            self.assertEqual(k(name), "arc_a", name)
37        for name in ("Intel(R) Arc(TM) B580 Graphics", "Intel(R) Arc(TM) Pro B60 Graphics", "Intel(R) Arc(TM) Pro B50", "Intel(R) Arc(TM) B570 Graphics"):
38            self.assertEqual(k(name), "arc_b", name)
39        for name in ("Intel(R) Arc(TM) Pro A60", "Intel(R) Arc(TM) Pro A40 Workstation"):
40            self.assertEqual(k(name), "arc_a_pro", name)
41        for name in ("Intel(R) Arc(TM) Graphics", "Intel(R) Iris(R) Xe Graphics", "Intel(R) UHD Graphics 770", "", None):
42            self.assertEqual(k(name), "intel_igpu", name)
43
44    def test_pci_ids(self):
45        k = drafting.sycl_arch_of_pci
46        for devid in ("56a0", "56a1", "56a2", "56a5", "56a6", "5690", "5692", "0x56a1"):
47            self.assertEqual(k("i915", devid), "arc_a", devid)
48        for devid in ("e20b", "e211", "e221", "e223"):
49            self.assertEqual(k("xe", devid), "arc_b", devid)
50        self.assertEqual(k("i915", "56b0"), "arc_a_pro")
51        for driver, devid in (("i915", "4680"), ("i915", "a7a0"), ("xe", "7d55"), ("i915", "zz"), ("", "")):
52            self.assertEqual(k(driver, devid), "intel_igpu", (driver, devid))
53
54    def test_a_series_is_tested_and_the_rest_is_not(self):
55        h = drafting.hardware_support
56        self.assertEqual(h("sycl", ["arc_a"]), drafting.Support(True, "tested", drafting.LINE_TESTED))
57        for arch in ("arc_b", "arc_a_pro", "intel_igpu"):
58            self.assertEqual(h("sycl", [arch]), drafting.Support(True, "untested", drafting.LINE_UNTESTED), arch)
59        self.assertEqual(h("sycl", []).line, drafting.LINE_UNTESTED, "no card named: the not-tested line")
60        self.assertNotIn("has not been tested", h("sycl", ["arc_a"]).line)
61
62    def test_the_probe_gives_the_card_class_on_a_sycl_computer(self):
63        from strata_control import engine_component
64        with mock.patch.object(drafting, "_HARDWARE", []), mock.patch.object(engine_component, "detect_backend", return_value=("sycl", "test")),                 mock.patch.object(engine_component, "cuda_archs_present", return_value=[]), mock.patch.object(engine_component, "hip_archs_present", return_value=[]),                 mock.patch.object(drafting, "sycl_archs_present", return_value=["arc_a"]):
65            self.assertEqual(drafting.detect_hardware(), ("sycl", ["arc_a"]))
66        with mock.patch.object(drafting, "_HARDWARE", []), mock.patch.object(engine_component, "detect_backend", return_value=("sycl", "test")),                 mock.patch.object(engine_component, "cuda_archs_present", return_value=[]), mock.patch.object(engine_component, "hip_archs_present", return_value=[]),                 mock.patch.object(drafting, "sycl_archs_present", return_value=["arc_b"]):
67            self.assertEqual(drafting.hardware_support(*drafting.detect_hardware()).level, "untested")
68
69    def test_the_adapters_of_a_windows_pc_and_the_sysfs_cards_of_a_linux_one(self):
70        from strata_control import engine_component, intel_spec
71        adapters = [{"vendor": "8086", "device": 0x56A1, "name": "Intel(R) Arc(TM) A750 Graphics"}, {"vendor": "10de", "device": 1, "name": "NVIDIA GeForce"},
72                    {"vendor": "8086", "device": 0x4680, "name": "Intel(R) UHD Graphics 770"}]
73        with mock.patch.object(drafting.os, "name", "nt"), mock.patch.object(engine_component, "windows_display_adapters", return_value=adapters):
74            self.assertEqual(drafting.sycl_archs_present(), ["arc_a", "intel_igpu"])
75        cards = [{"index": 0, "driver": "i915", "devid": "56a1"}, {"index": 1, "driver": "xe", "devid": "e223"}]
76        with mock.patch.object(drafting.os, "name", "posix"), mock.patch.object(intel_spec, "sysfs_cards", return_value=cards):
77            self.assertEqual(drafting.sycl_archs_present(), ["arc_a", "arc_b"])
78
79
80class WhereTheEngineCanRunIt(unittest.TestCase):
81    """DFlash2 exists in the engines of drafting.DFLASH2_BACKENDS (CUDA, HIP, Metal; CMakeLists.txt STRATA_HAVE_DFLASH2): the choice is offered, and applied, only there."""
82
83    def test_the_matrix(self):
84        h = drafting.hardware_support
85        for backend in ("", None, "cpu"):
86            self.assertEqual(h(backend, ["sm_120"]), drafting.Support(False, "none", ""), backend)
87        self.assertEqual(h("sycl", []).level, "untested")
88        self.assertEqual((h("cuda", ["sm_120"]).level, h("cuda", ["sm_121"]).level, h("hip", ["gfx1151"]).level, h("hip", ["gfx1201"]).level), ("tested",) * 4)
89        self.assertEqual(h("cuda", ["sm_86"]).level, "slower")
90        for backend, arch in (("cuda", "sm_75"), ("cuda", "sm_89"), ("cuda", "sm_90"), ("cuda", "sm_61"), ("hip", "gfx1100"), ("hip", "gfx1030"), ("cuda", None), ("metal", None)):
91            support = h(backend, [arch] if arch else [])
92            self.assertEqual((support.can_run, support.level, support.line), (True, "untested", drafting.LINE_UNTESTED), (backend, arch))
93        for backend, arch in (("cuda", "sm_120"), ("cuda", "sm_86"), ("cuda", "sm_75")):
94            self.assertTrue(h(backend, [arch]).line, "every card that is offered it gets one plain line")
95
96    def test_no_verdicts_in_the_lines(self):
97        for line in (drafting.LINE_TESTED, drafting.LINE_SLOWER, drafting.LINE_UNTESTED):
98            for word in ("recommend", "best", "better", "should", "avoid"):
99                self.assertNotIn(word, line.lower())
100
101    def test_a_build_without_the_code_keeps_the_mtp_and_downloads_nothing(self):
102        tmp = tempfile.TemporaryDirectory()
103        self.addCleanup(tmp.cleanup)
104        with serving_dflash2():
105            for backend in ("cpu",):
106                d = drafting.decide("dflash2", klass="other", model_name=GYRO, data_dir=tmp.name, backend=backend, archs=[])
107                self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_THIS_CARD), backend)
108                self.assertFalse(drafting.needs_pack("dflash2", klass="other", model_name=GYRO, data_dir=tmp.name, backend=backend, archs=[]), backend)
109            self.assertTrue(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=tmp.name, backend="cuda", archs=["sm_120"]))
110            self.assertEqual(drafting.decide("auto", klass="other", model_name=GYRO, data_dir=tmp.name, backend="cpu", archs=[]).note, "", "Auto never nags")
111
112    def test_a_window_or_confidence_the_person_set_by_hand_stays(self):
113        tmp = tempfile.TemporaryDirectory()
114        self.addCleanup(tmp.cleanup)
115        pack = drafting.pack_path(tmp.name)
116        pack.parent.mkdir(parents=True)
117        pack.write_bytes(b"x" * (2 << 20))
118        base = ["--pack", "/d/packs/g", "--mtp", "/d/mtp/rt", "--spec", "5", "--draft-conf", "0.5"]
119        with serving_dflash2():
120            c = {"model_name": GYRO, "drafting": "dflash2", "args": list(base), "user_args": ["--spec", "5", "--draft-conf", "0.5"]}
121            drafting.apply(c, klass="blackwell", data_dir=tmp.name, backend="cuda", archs=["sm_120"])
122            self.assertEqual(c["args"][c["args"].index("--spec") + 1], "5")
123            self.assertEqual(c["args"][c["args"].index("--draft-conf") + 1], "0.5")
124            self.assertEqual((c["args"].count("--spec"), c["args"].count("--draft-conf")), (1, 1))
125            layer = Path(tmp.name) / "mtp" / "rt"                  # the MTP layer is on this computer
126            layer.mkdir(parents=True)
127            (layer / "experts.bin").write_bytes(b"e")
128            base = [*base[:base.index("--mtp") + 1], str(layer), *base[base.index("--mtp") + 2:]]
129            c = {"model_name": GYRO, "drafting": "mtp", "args": [*base, "--draft", "dflash2", "--draft-model", "/p"]}
130            drafting.apply(c, klass="blackwell", data_dir=tmp.name, backend="cuda", archs=["sm_120"])
131            self.assertNotIn("--draft-conf", c["args"], "back to MTP: DFlash2's confidence goes with it")
132            self.assertEqual(c["args"][c["args"].index("--spec") + 1], "5", "and the MTP window is untouched")
133
134    def test_the_plan_reports_whether_this_computer_can_run_it(self):
135        tmp = tempfile.TemporaryDirectory()
136        self.addCleanup(tmp.cleanup)
137        for hardware, serves, level in ((("cuda", ["sm_120"]), True, "tested"), (("cpu", []), False, "none"), (("sycl", []), True, "untested"), (("metal", []), True, "untested"), (("hip", ["gfx1201"]), True, "tested")):
138            with mock.patch.object(drafting, "detect_hardware", return_value=hardware):
139                code, out, err = run_cli(["drafting", "plan", "--data-dir", tmp.name, "--mode", "auto", "--output", "json"])
140            self.assertEqual(code, 0, err)
141            payload = json.loads(out)
142            self.assertEqual((payload["serves"], payload["support"]), (serves, level), hardware)
143
144
145class ConfidenceFollowsTheSlots(unittest.TestCase):
146    """--draft-conf by the expert slots the card holds once the drafter's 0.8 GB is taken (drafting.CONF_STEPS, measured on l620 and the R9700)."""
147
148    def make(self, args, user_args=None):
149        tmp = tempfile.TemporaryDirectory()
150        self.addCleanup(tmp.cleanup)
151        pack = drafting.pack_path(tmp.name)
152        pack.parent.mkdir(parents=True)
153        pack.write_bytes(b"x" * (2 << 20))
154        c = {"model_name": GYRO, "drafting": "dflash2", "args": list(args), "user_args": list(user_args or [])}
155        return c, tmp.name
156
157    def conf(self, args, vram_mib=None, user_args=None, backend="cuda", archs=("sm_120",)):
158        c, data = self.make(args, user_args)
159        with serving_dflash2(), mock.patch.object(drafting, "detect_hardware", return_value=(backend, list(archs))):
160            drafting.apply(c, klass="blackwell", data_dir=data, backend=backend, archs=list(archs), vram_mib=vram_mib)
161        self.assertEqual(c["args"].count("--draft-conf"), 1)
162        return c["args"][c["args"].index("--draft-conf") + 1]
163
164    def test_the_steps(self):
165        f = drafting.conf_for_slots
166        self.assertEqual([f(n) for n in (24576, 12570, 12000, 11999, 7500, 7499, 5000, 3000, 2999, 1000, 300, 0)],
167                         [0.35, 0.35, 0.35, 0.5, 0.5, 0.7, 0.7, 0.7, 0.8, 0.8, 0.8, 0.8])
168        self.assertEqual(f(None), 0.35, "unknown: today's value")
169
170    def test_an_explicit_expert_cache_decides(self):
171        base = ["--spec", "4"]
172        for given, want in (("1000", "0.8"), ("300", "0.8"), ("5000", "0.7"), ("8000", "0.5"), ("12570", "0.35"), ("24576", "0.35")):
173            self.assertEqual(self.conf([*base, "--expert-cache", given]), want, given)
174        # the steps are in the ENGINE's slots, an --expert-cache N holds about 1.3 N of them (IQ3_S: N = 1,000 -> 1,283 slots, 2,000 -> 2,582, 5,000 -> 6,528, 8,000 -> 10,452)
175        for given, want in (("2000", "0.8"), ("2307", "0.8"), ("2308", "0.7"), ("2500", "0.7"), ("5000", "0.7"), ("5769", "0.7"), ("5770", "0.5"), ("9230", "0.5"), ("9231", "0.35"), ("12000", "0.35")):
176            self.assertEqual(self.conf([*base, "--expert-cache", given]), want, "--expert-cache " + given)
177        self.assertEqual(drafting.slots_of(["--expert-cache", "1000"]), 1300)
178        self.assertEqual(drafting.slots_of(["--expert-cache", "30000"]), drafting.MAX_SLOTS, "never more than every (layer, expert) pair")
179        self.assertEqual(self.conf([*base, "--expert-cache", "auto"]), "0.35", "auto with no card reading: today's value")
180        self.assertEqual(self.conf(base), "0.35", "nothing known: today's value")
181
182    def test_the_card_decides_when_the_cache_is_auto(self):
183        args = ["--expert-cache", "auto", "--max-context", "131072", "--kv", "int8"]
184        for vram, want in ((8192, "0.8"), (12288, "0.8"), (16384, "0.7"), (20480, "0.7"), (24564, "0.5"), (32768, "0.35"), (49152, "0.35"), (73415, "0.35")):
185            self.assertEqual(self.conf(args, vram_mib=vram), want, vram)
186        self.assertEqual(self.conf(args, vram_mib=32768, backend="hip", archs=("gfx1201",)), "0.35", "the R9700 (12,570 slots measured) keeps 0.35")
187
188    def test_the_estimate_matches_the_two_measured_starts(self):
189        n = drafting.expected_slots(32768, ["--max-context", "131072", "--kv", "int8"])
190        self.assertAlmostEqual(n, 12570, delta=0.1 * 12570)              # the R9700 start: the DFlash2 is the only drafter, it takes the draft layer's allowance
191        self.assertEqual(drafting.expected_slots(4096, []), 0, "a card that cannot hold the rest never goes negative")
192
193    def test_the_persons_own_confidence_stays(self):
194        self.assertEqual(self.conf(["--expert-cache", "300", "--draft-conf", "0.5"], user_args=["--draft-conf", "0.5"]), "0.5")
195
196    def test_a_smaller_context_leaves_more_room(self):
197        big = drafting.expected_slots(16384, ["--max-context", "131072"])
198        small = drafting.expected_slots(16384, ["--max-context", "32768"])
199        self.assertGreater(small, big)
200
201
202class OfflineAndReuse(unittest.TestCase):
203    """No internet is a plain sentence in seconds, never a hang; files that are already here are used, not fetched."""
204
205    @classmethod
206    def setUpClass(cls):
207        sys.path.insert(0, str(ROOT / "tools"))
208        spec = importlib.util.spec_from_file_location("t_pack2", ROOT / "tools" / "test_dflash2_pack.py")
209        cls.synth = importlib.util.module_from_spec(spec)
210        spec.loader.exec_module(cls.synth)
211
212    def setUp(self):
213        self.tmp = tempfile.TemporaryDirectory()
214        self.addCleanup(self.tmp.cleanup)
215        self.dir = Path(self.tmp.name)
216        self.synth.write_safetensors(self.dir / "m.safetensors", self.synth.tensors())
217        (self.dir / "c.json").write_text(json.dumps(self.synth.CFG))
218        self.blobs = {"config.json": (self.dir / "c.json").read_bytes(), "model.safetensors": (self.dir / "m.safetensors").read_bytes()}
219        self.files = tuple((n, len(b), hashlib.sha256(b).hexdigest()) for n, b in self.blobs.items())
220        self.data = self.dir / "data"
221        patcher = mock.patch.object(drafting, "pack_ready", lambda d: bool(d) and drafting.pack_path(d).is_file())
222        patcher.start()
223        self.addCleanup(patcher.stop)
224
225    def test_no_internet_is_a_plain_sentence_and_nothing_is_left_behind(self):
226        with mock.patch.object(drafting_fetch, "online", return_value=False), mock.patch.object(drafting_fetch.transfer, "download") as download:
227            with self.assertRaises(drafting_fetch.DraftingError) as ctx:
228                drafting_fetch.ensure(self.data, files=self.files)
229        self.assertEqual(str(ctx.exception), "There is no internet connection, so the DFlash2 drafter can't be downloaded now.")
230        download.assert_not_called()
231        self.assertFalse(drafting.pack_path(self.data).exists())
232
233    def test_the_reachability_check_gives_up_fast_on_a_connection_that_hangs(self):
234        hung = socket.socket()
235        hung.bind(("127.0.0.1", 0))
236        hung.listen(0)                                        # the kernel accepts the connection; nobody ever answers
237        self.addCleanup(hung.close)
238        started = time.monotonic()
239        self.assertFalse(drafting_fetch.online(f"http://127.0.0.1:{hung.getsockname()[1]}/x", timeout=1.0))
240        self.assertLess(time.monotonic() - started, 5)
241        self.assertFalse(drafting_fetch.online("http://127.0.0.1:9/x", timeout=1.0), "nothing listens: refused at once")
242
243    def test_verified_source_files_that_are_already_here_are_used_without_the_network(self):
244        src = drafting.pack_path(self.data).parent / "src"
245        src.mkdir(parents=True)
246        for name, blob in self.blobs.items():
247            (src / name).write_bytes(blob)
248        with mock.patch.object(drafting_fetch, "online", side_effect=AssertionError("no network needed")), \
249                mock.patch.object(drafting_fetch.transfer, "download", side_effect=AssertionError("nothing to download")):
250            out = drafting_fetch.ensure(self.data, files=self.files)
251        self.assertEqual(out.read_bytes()[:4], b"DF2P")
252        self.assertFalse(src.exists())
253
254    def test_a_copy_kept_by_the_hugging_face_tools_is_found_checked_and_never_deleted(self):
255        hub = self.dir / "hub"
256        hub.mkdir()
257        for name, blob in self.blobs.items():
258            (hub / name).write_bytes(blob)
259        self.assertEqual(set(drafting_fetch._present([hub], self.files)), {"config.json", "model.safetensors"})
260        (hub / "model.safetensors").write_bytes(b"corrupt")
261        self.assertNotIn("model.safetensors", drafting_fetch._present([hub], self.files), "a copy whose hash differs is never used")
262
263    def test_the_hub_folders_are_the_pinned_revision_only(self):
264        with mock.patch.dict("os.environ", {"HF_HOME": str(self.dir / "hf")}):
265            folders = drafting_fetch._hub_snapshots()
266        self.assertIn(self.dir / "hf" / "hub" / "models--incoai--Qwen3.8-Flash-Next-DFlash2" / "snapshots" / drafting.REVISION, folders)
267
268
269class OneRequestAtATime(unittest.TestCase):
270    """DFlash2 cannot run beside request slots (--batch); Strata fills slots in by itself, so a choice that means DFlash2 (named, or Auto) means one request."""
271
272    def test_the_choice_that_means_dflash2_on_a_computer_that_can_run_it(self):
273        want = drafting.wants_one_request
274        with serving_dflash2():
275            self.assertTrue(want("dflash2", model_name=GYRO, backend="cuda", archs=["sm_121"]))
276            self.assertTrue(want("DFlash2", family="qwen", backend="hip"))
277            for mode in ("auto", None):
278                self.assertTrue(want(mode, model_name=GYRO, backend="cuda", archs=["sm_121"]), mode)
279            for mode in ("mtp", "off"):
280                self.assertFalse(want(mode, model_name=GYRO, backend="cuda", archs=["sm_121"]), mode)
281            self.assertFalse(want("dflash2", model_name="qwen3.8-flash-next-coder-iq1_m", backend="cuda", archs=["sm_121"]))
282            self.assertTrue(want("auto", model_name=GYRO, backend="sycl", archs=[]), "Intel runs DFlash2 one request at a time")
283            self.assertFalse(want("auto", model_name=GYRO, backend="cpu", archs=[]))
284            self.assertTrue(want("auto", model_name=GYRO, backend="metal", archs=[]))
285        with mock.patch.object(drafting, "ENGINE_SERVES_DFLASH2", False):
286            self.assertFalse(want("dflash2", model_name=GYRO, backend="cuda", archs=["sm_121"]), "while the engine does not serve it")
287
288
289class TheQ4Pack(unittest.TestCase):
290    """The owner chose the Q4_0 pack (522 MB, same speed as Q8, less memory): made on the person's computer from the pinned download, checked, and an old Q8 pack keeps working."""
291
292    def test_the_pins(self):
293        self.assertEqual(drafting.PACK_NAME, "qwen3.8-flash-next-dflash2.q4_0.pack")
294        self.assertEqual(drafting.PACK_BYTES, 522458112)
295        self.assertEqual(len(drafting.PACK_SHA256), 64)
296        self.assertEqual(drafting.PACK_GB, 0.52)
297        self.assertEqual(drafting.LEGACY_PACK_NAME, "qwen3.8-flash-next-dflash2.q8.pack")
298
299    def test_an_old_q8_pack_is_used_and_never_fetched_again(self):
300        tmp = tempfile.TemporaryDirectory()
301        self.addCleanup(tmp.cleanup)
302        folder = Path(tmp.name) / drafting.FOLDER
303        folder.mkdir()
304        old = folder / drafting.LEGACY_PACK_NAME
305        old.write_bytes(b"x" * (2 << 20))
306        self.assertEqual(drafting.pack_path(tmp.name), old)
307        self.assertTrue(drafting.pack_ready(tmp.name))
308        with serving_dflash2():
309            self.assertFalse(drafting.needs_pack("dflash2", klass="blackwell", model_name=GYRO, data_dir=tmp.name))
310            self.assertEqual(drafting.decide("dflash2", model_name=GYRO, data_dir=tmp.name, backend="cuda").flags[3], str(old))
311        with mock.patch.object(drafting_fetch.transfer, "download", side_effect=AssertionError("no download for a pack that is here")):
312            self.assertEqual(drafting_fetch.ensure(tmp.name), old)
313        self.assertEqual(drafting.target_path(tmp.name), folder / drafting.PACK_NAME, "a new fetch would write the Q4_0 name")
314        (folder / drafting.PACK_NAME).write_bytes(b"y" * (2 << 20))
315        self.assertEqual(drafting.pack_path(tmp.name), folder / drafting.PACK_NAME, "when both are there, the Q4_0 pack is the one used")
316
317    def test_the_pack_is_made_q4_and_checked_against_its_pins(self):
318        sys.path.insert(0, str(ROOT / "tools"))
319        spec = importlib.util.spec_from_file_location("t_pack3", ROOT / "tools" / "test_dflash2_pack.py")
320        synth = importlib.util.module_from_spec(spec)
321        spec.loader.exec_module(synth)
322        tmp = tempfile.TemporaryDirectory()
323        self.addCleanup(tmp.cleanup)
324        d = Path(tmp.name)
325        synth.write_safetensors(d / "m.safetensors", synth.tensors())
326        (d / "c.json").write_text(json.dumps(synth.CFG))
327        files = tuple((n, (d / f).stat().st_size, hashlib.sha256((d / f).read_bytes()).hexdigest()) for n, f in (("config.json", "c.json"), ("model.safetensors", "m.safetensors")))
328        src = d / "data" / drafting.FOLDER / "src"
329        src.mkdir(parents=True)
330        (src / "config.json").write_bytes((d / "c.json").read_bytes())
331        (src / "model.safetensors").write_bytes((d / "m.safetensors").read_bytes())
332        # not the real pinned files (files=...): the pack is made Q4_0 but the real pins do not apply
333        with mock.patch.object(drafting, "pack_ready", lambda x: False):
334            out = drafting_fetch.ensure(d / "data", files=files)
335        blob = out.read_bytes()
336        self.assertEqual(out.name, drafting.PACK_NAME)
337        self.assertIn(b"q4_0", blob[:4096])
338        # with the real list (files=None) a pack whose bytes are not the pinned ones is deleted and the words are plain
339        (d / "data2").mkdir()
340        with mock.patch.object(drafting_fetch, "_present", lambda folders, spec: {"config.json": d / "c.json", "model.safetensors": d / "m.safetensors"}),                 mock.patch.object(drafting, "pack_ready", lambda x: False):
341            with self.assertRaises(drafting_fetch.DraftingError) as ctx:
342                drafting_fetch.ensure(d / "data2")
343        self.assertIn("did not pass the safety check", str(ctx.exception))
344        self.assertFalse(drafting.target_path(d / "data2").exists())
345        self.assertFalse(drafting.target_path(d / "data2").with_suffix(".tmp").exists())
346        # and with the pins set to what this pack really is, it is kept
347        pins = {"PACK_BYTES": len(blob), "PACK_SHA256": hashlib.sha256(blob).hexdigest()}
348        with mock.patch.object(drafting_fetch, "_present", lambda folders, spec: {"config.json": d / "c.json", "model.safetensors": d / "m.safetensors"}),                 mock.patch.object(drafting, "pack_ready", lambda x: False), mock.patch.multiple(drafting, **pins):
349            self.assertEqual(drafting_fetch.ensure(d / "data2").read_bytes(), blob)
350
351
352class TheTerminalStep(unittest.TestCase):
353    """strata launch: the Drafting step exists only where there is something to choose."""
354
355    def flow(self, family, hardware):
356        from types import SimpleNamespace
357        from strata_cli.launch.screens import flow_for
358        ctx = SimpleNamespace(computer=SimpleNamespace(usable_gpus=[0]), settings=SimpleNamespace(family=family))
359        with mock.patch.object(drafting, "detect_hardware", return_value=hardware), serving_dflash2():
360            return flow_for(ctx)
361
362    def test_only_flash_next_on_a_cuda_or_hip_engine_gets_the_step(self):
363        flow = self.flow("qwen", ("cuda", ["sm_120"]))
364        self.assertIn("drafting", flow)
365        self.assertEqual(flow.index("drafting"), flow.index("pictures") + 1)
366        self.assertIn("drafting", self.flow("gyro", ("hip", ["gfx1151"])))
367        self.assertIn("drafting", self.flow("unsloth", ("cuda", ["sm_120"])))
368        for family in ("swift", "coder", "nvfp4", "qwen36", None):
369            self.assertNotIn("drafting", self.flow(family, ("cuda", ["sm_120"])), family)
370        self.assertIn("drafting", self.flow("qwen", ("sycl", [])))
371        for hardware in (("cpu", []), (None, [])):
372            self.assertNotIn("drafting", self.flow("qwen", hardware), hardware)
373
374    def test_the_choice_is_saved_as_the_flag_would_and_auto_writes_nothing(self):
375        from types import SimpleNamespace
376        from strata_cli.launch import settings as S
377        from strata_cli.launch.screens import DraftingScreen
378        self.assertEqual([k for k, _ in DraftingScreen.CHOICES], list(S.DRAFTING_MODES))
379        for key, saved in (("dflash2", "dflash2"), ("auto", None), ("off", "off")):
380            fake = SimpleNamespace(ctx=SimpleNamespace(settings=S.LaunchSettings(), base_config=lambda: None), menu=lambda key=key: SimpleNamespace(current=SimpleNamespace(key=key)))
381            DraftingScreen.commit(fake)
382            self.assertEqual(fake.ctx.settings.drafting, saved)
383        # the model's file holds the app's older choice: Auto is written, so it wins; the other rows are as before
384        for key, in_file, saved in (("auto", {"drafting": "mtp"}, "auto"), ("auto", {"drafting": "auto"}, None), ("auto", {}, None), ("mtp", {"drafting": "dflash2"}, "mtp")):
385            fake = SimpleNamespace(ctx=SimpleNamespace(settings=S.LaunchSettings(), base_config=lambda in_file=in_file: in_file), menu=lambda key=key: SimpleNamespace(current=SimpleNamespace(key=key)))
386            DraftingScreen.commit(fake)
387            self.assertEqual(fake.ctx.settings.drafting, saved, (key, in_file))
388
389    def test_the_words_are_the_apps_words(self):
390        folder = ROOT / "apps" / "host" / "src" / "locales"
391        en = json.loads((folder / "df2-en.json").read_text(encoding="utf-8"))
392        self.assertEqual((en["df03"], en["df04"], en["df05"]), (drafting.LINE_TESTED, drafting.LINE_SLOWER, drafting.LINE_UNTESTED))
393        self.assertEqual(en["df21"], drafting.LINE_METAL)
394        self.assertEqual(en["df06"], drafting.mtp_line(drafting.NOT_THIS_CARD))
395        self.assertEqual(en["df07"], "There is no internet connection, so the DFlash2 drafter can't be downloaded now.")
396        self.assertEqual(en["df09"], drafting.ONE_REQUEST_NOTE)
397        self.assertEqual(en["df10"], drafting.line("off", drafting.NONE_HERE))
398        self.assertEqual(en["df11"], drafting.line("dflash2", drafting.NO_MTP))
399        self.assertEqual(en["df12"].replace("{0}", "1.2"), "Choosing DFlash2 downloads its drafter: about 1.2 GB, once.")
400
401
402if __name__ == "__main__":
403    unittest.main()