okami.mom/strata

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

Niko1221launch: say once when the draft layer cannot be downloaded offline3dcdb99a7

main
15.2 KiB267 linesraw
1"""A first `strata launch` with Auto (no Drafting word) on a computer without the draft layer: setup is told the drafter the start will run, so the start has it.
2Found in the 0.2.14 real-use run on an RTX 5070 12 GB with IQ3_S (present since 0.2.13): Auto's start-time rule for that card class is the MTP
3(drafting.CLASS_DEFAULTS, the "streaming" class, read from the card's memory), but setup was told "--drafter dflash2" (Auto resolved without the model's set and
4the card's memory), skipped the draft layer, and the engine started with no drafter ("Drafting: off (no drafter is downloaded yet)"), at the next Auto launch too.
5The plan said "Nothing to download".  Nothing real is used (tests/snapshot/README.md: scratch HOME, data folder, install folder).
6
7  python -m pytest tests/snapshot/test_auto_drafter_fresh_install.py -q -p no:cacheprovider
8"""
9
10from __future__ import annotations
11
12import sys
13import unittest
14from pathlib import Path
15
16ROOT = Path(__file__).resolve().parents[2]
17if str(ROOT) not in sys.path:
18    sys.path.insert(0, str(ROOT))
19
20from tests.snapshot.driver import drive_launch  # noqa: E402
21from tests.snapshot.matrix import MACHINES, MODEL_SETS, machine as get_machine, model_set as get_set  # noqa: E402
22from tests.snapshot.normalize import normalize  # noqa: E402
23from tests.snapshot.world import World  # noqa: E402
24
25
26def fresh_world(m, s) -> World:
27    """A new install: the model files are there (setup's download is not what this is about), no run config and no draft layer yet."""
28    world = World(m, s).build()
29    world.config_path.unlink()
30    for f in (world.mtp / "experts.bin", world.mtp / "draft_vocab.bin", world.data / "mtp" / "mtp-q2_0.gguf"):
31        f.unlink()
32    world.mtp.rmdir()
33    return world
34
35
36def first_launches(m, s, n=2):
37    """`n` Auto launches without a Drafting word on a fresh install: the first runs setup, the later ones run it when ensure_model would (its own test)."""
38    world = fresh_world(m, s)
39    try:
40        out = []
41        for i in range(n):
42            with world.patched():
43                rec = drive_launch(world, (), setup_runs=True if i == 0 else "when_needed", fresh=True)
44            assert "failed" not in rec, rec.get("failed")
45            out.append(normalize(rec, world))
46        return out
47    finally:
48        world.close()
49
50
51def drafter(rec: dict) -> str:
52    a = rec["engine"]["argv"]
53    return "dflash2" if "--draft" in a else "mtp" if "--mtp" in a else "off"
54
55
56def setup_drafter(rec: dict) -> str | None:
57    a = rec["setup_args"]
58    return a[a.index("--drafter") + 1] if "--drafter" in a else None
59
60
61class AutoOnAFreshInstall(unittest.TestCase):
62    maxDiff = None
63
64    def test_12gb_iq3_s_auto_fetches_and_starts_the_mtp(self):
65        first, second = first_launches(get_machine("nv_12gb_streaming"), get_set("iq3_s"))
66        self.assertIsNone(setup_drafter(first), f"setup is told the MTP (no --drafter dflash2): {first['setup_args']}")
67        self.assertIn("mtp", first["plan_parts"], "the plan lists the draft layer's download")
68        self.assertIn({"call": "setup_mtp_layer"}, first["fetches"], "setup fetched the draft layer")
69        self.assertEqual(drafter(first), "mtp", f"the first Auto start runs the MTP: {first['engine']['argv']}")
70        self.assertEqual(drafter(second), "mtp", "the next Auto start too")
71        self.assertEqual(second["engine"]["argv"], first["engine"]["argv"])
72
73    def test_every_class_setup_is_told_the_drafter_the_start_runs(self):
74        for m in MACHINES:
75            if m.os == "macos":
76                continue                                     # a Mac's setup takes no --drafter or --mtp word (runner.setup_args)
77            for s in MODEL_SETS:
78                with self.subTest(machine=m.key, set=s.key):
79                    first, _second = first_launches(m, s)
80                    self.assertNotEqual(drafter(first), "off", f"a first Auto start has a drafter: {first['engine']['argv']}")
81                    self.assertEqual(setup_drafter(first) == "dflash2", drafter(first) == "dflash2",
82                                     f"setup {first['setup_args']} / start {first['engine']['argv']}")
83                    self.assertEqual("mtp" in first["plan_parts"], drafter(first) == "mtp", f"plan {first['plan_parts']}")
84
85
86def offline_launch(m, s, with_pack=False):
87    """A first Auto launch on a fresh install of a computer without internet: setup fetches no draft layer (setup.fetch_mtp offline goes on), the DFlash2
88    drafter cannot be downloaded either. `with_pack`: the DFlash2 drafter is on disk already."""
89    from unittest import mock
90    from strata_control import drafting_fetch
91    from tests.snapshot import driver
92    world = fresh_world(m, s)
93    try:
94        with world.patched():
95            if with_pack:
96                drafting_fetch.ensure(world.data)
97                world.fetches.clear()
98            with mock.patch.object(driver, "setup_fetches_layer", lambda *a, **k: None), mock.patch.object(drafting_fetch, "online", lambda *a, **k: False):
99                rec = drive_launch(world, (), setup_runs=True, fresh=True)
100        return rec if "failed" in rec else normalize(rec, world)
101    finally:
102        world.close()
103
104
105class PickedDrafterMissing(unittest.TestCase):
106    maxDiff = None
107
108    def test_12gb_layer_missing_with_the_dflash2_drafter_on_disk_starts_dflash2(self):
109        rec = offline_launch(get_machine("nv_12gb_streaming"), get_set("iq3_s"), with_pack=True)
110        self.assertNotIn("failed", rec)
111        self.assertEqual(drafter(rec), "dflash2", f"the other drafter stands in: {rec['engine']['argv']}")
112
113    def test_offline_with_nothing_on_disk_starts_without_a_drafter(self):
114        for key in ("nv_12gb_streaming", "r9700_linux"):
115            with self.subTest(machine=key):
116                rec = offline_launch(get_machine(key), get_set("iq3_s"))
117                self.assertNotIn("failed", rec, "an offline first launch never stops")
118                self.assertEqual(drafter(rec), "off")
119
120    def test_r9700_layer_missing_does_not_fall_back_to_dflash2(self):
121        # Auto keeps the MTP on gfx1201 because of the DFlash2 prompt stall (drafting.AUTO_MTP): DFlash2 is no stand-in there
122        rec = offline_launch(get_machine("r9700_linux"), get_set("iq3_s"), with_pack=True)
123        self.assertNotIn("failed", rec)
124        self.assertEqual(drafter(rec), "off")
125
126
127def net_launch(m, s, extra=(), offline=False, setup_disagrees=False):
128    """A first Auto launch on a fresh install where the start's decision finds no drafter on disk after setup (the start's safety net,
129    runner.fetch_missing_drafter). `setup_disagrees`: setup decides without the start's signals (as a card near a class line can), so it is told DFlash2
130    where the start runs the MTP. `offline`: setup's draft-layer step goes on without the layer, and the DFlash2 drafter cannot be downloaded either."""
131    from contextlib import ExitStack
132    from unittest import mock
133    from strata_cli.launch import runner as R
134    from strata_control import drafting_fetch
135    from tests.snapshot import driver
136    world = fresh_world(m, s)
137    try:
138        with world.patched(), ExitStack() as st:
139            if offline:
140                from strata_control import netpolicy
141                world.setup_said = ["  [X]  " + netpolicy.WORDS["offline"].format(host="huggingface.co", what="the draft layer")]   # tools/mtp_fetch.py's line
142                st.enter_context(mock.patch.object(driver, "setup_fetches_layer", lambda *a, **k: None))
143                st.enter_context(mock.patch.object(drafting_fetch, "online", lambda *a, **k: False))
144            if setup_disagrees == "blocked":
145                from strata_control import drafting
146                st.enter_context(mock.patch.object(drafting, "blocked_by", lambda *a, **k: True))
147            elif setup_disagrees:
148                st.enter_context(mock.patch.object(R, "auto_signals", lambda *a, **k: {}))
149            rec = drive_launch(world, tuple(extra), setup_runs=True, fresh=True)
150        return rec if "failed" in rec else normalize(rec, world)
151    finally:
152        world.close()
153
154
155class StartSafetyNet(unittest.TestCase):
156    maxDiff = None
157    # (1) several requests block DFlash2 at the start (drafting.blocked_by; a `--parallel` launch of the matrix runs DFlash2 one request at a time, so the block is
158    #     set directly): setup was told DFlash2, the start falls back to the MTP layer; (2) setup says DFlash2, the start says the MTP
159    CASES = (("blocked", "nv_resident", "iq3_s", (), "blocked"),
160             ("class line", "nv_12gb_streaming", "iq3_s", (), True))
161
162    def test_online_the_layer_is_fetched_and_the_mtp_runs(self):
163        for name, mkey, skey, extra, disagrees in self.CASES:
164            with self.subTest(case=name):
165                rec = net_launch(get_machine(mkey), get_set(skey), extra, setup_disagrees=disagrees)
166                self.assertNotIn("failed", rec)
167                self.assertIn({"call": "setup_mtp_layer"}, rec["fetches"], "setup ran again and fetched the layer")
168                self.assertEqual(drafter(rec), "mtp", rec["engine"]["argv"])
169
170    def test_offline_the_start_goes_on_without(self):
171        for name, mkey, skey, extra, disagrees in self.CASES:
172            with self.subTest(case=name):
173                rec = net_launch(get_machine(mkey), get_set(skey), extra, offline=True, setup_disagrees=disagrees)
174                self.assertNotIn("failed", rec, "no stop")
175                self.assertEqual(drafter(rec), "off")
176                from strata_control import drafting
177                self.assertEqual(rec["notices"].count(drafting.MTP_OFFLINE_NOTE), 1, f"the offline line, once: {rec['notices']}")
178
179    def test_the_offline_line_is_not_said_when_another_drafter_runs_or_off_was_chosen(self):
180        from strata_control import drafting
181        rec = net_launch(get_machine("nv_resident"), get_set("iq3_s"), ("--drafting", "off"), offline=True, setup_disagrees="blocked")
182        self.assertNotIn(drafting.MTP_OFFLINE_NOTE, rec["notices"])
183        rec = net_launch(get_machine("nv_12gb_streaming"), get_set("ud_q4_k_xl"), (), offline=True)          # Auto is DFlash2 there: its drafter runs
184        self.assertNotIn(drafting.MTP_OFFLINE_NOTE, rec["notices"])
185
186    def test_a_chosen_off_is_not_fetched_for(self):
187        rec = net_launch(get_machine("nv_resident"), get_set("iq3_s"), ("--drafting", "off"), setup_disagrees="blocked")
188        self.assertNotIn({"call": "setup_mtp_layer"}, rec["fetches"])
189        self.assertEqual(drafter(rec), "off")
190
191
192class MacSetupFetchesThePickedDrafter(unittest.TestCase):
193    # 0.2.14 SMOKE-1 (M5 Max, Q2_0, offline): the plan named DFlash2, setup fetched the MTP layer anyway (setup_args left --drafter out on a Mac) and stopped offline
194    def test_metal_sets(self):
195        from tests.snapshot.matrix import ModelSet
196        q2 = ModelSet("q2_0", "qwen", "Q2_0", "qwen3.8-flash-next-q2_0", ("Qwen3.8-Flash-Next-Q2_0-00001-of-00002.gguf", "Qwen3.8-Flash-Next-Q2_0-00002-of-00002.gguf"))
197        for mkey in ("mac_small", "mac_large"):
198            for s, want in ((get_set("iq3_s"), None), (q2, "dflash2"), (get_set("ud_q4_k_xl"), "dflash2"), (get_set("ud_iq4_xs_v31"), "dflash2")):
199                with self.subTest(machine=mkey, set=s.key):
200                    first, = first_launches(get_machine(mkey), s, n=1)
201                    self.assertEqual(setup_drafter(first), want, f"setup is told the drafter the start runs: {first['setup_args']}")
202                    self.assertEqual("mtp" in first["plan_parts"], want is None, f"plan {first['plan_parts']}")
203
204
205class MacOffFetchesNothing(unittest.TestCase):
206    # DF-REAL on an M5 Max (Q2_0): `--drafting off` on a fresh install fetched the 5.2 GB draft layer (setup_args left --mtp off out on a Mac), the plan said Nothing to download
207    def test_metal_off_on_a_fresh_install(self):
208        from tests.snapshot.matrix import ModelSet
209        q2 = ModelSet("q2_0", "qwen", "Q2_0", "qwen3.8-flash-next-q2_0", ("Qwen3.8-Flash-Next-Q2_0-00001-of-00002.gguf", "Qwen3.8-Flash-Next-Q2_0-00002-of-00002.gguf"))
210        for mkey in ("mac_small", "mac_large"):
211            for s in (get_set("iq3_s"), q2, get_set("ud_q4_k_xl")):
212                with self.subTest(machine=mkey, set=s.key):
213                    world = fresh_world(get_machine(mkey), s)
214                    try:
215                        with world.patched():
216                            rec = drive_launch(world, ("--drafting", "off"), setup_runs=True, fresh=True)
217                        self.assertNotIn("failed", rec)
218                        rec = normalize(rec, world)
219                    finally:
220                        world.close()
221                    a = rec["setup_args"]
222                    self.assertIn("--mtp", a, a)
223                    self.assertEqual(a[a.index("--mtp") + 1], "off", a)
224                    self.assertEqual(rec["fetches"], [], "nothing is fetched")
225                    self.assertNotIn("mtp", rec["plan_parts"])
226                    self.assertEqual(drafter(rec), "off")
227
228
229class SavedOffHolds(unittest.TestCase):
230    def test_a_saved_off_survives_a_start_without_a_drafting_word_when_setup_does_not_run(self):
231        # 0.2.14 real-use run, Strix T6: the installed copy was reused, the Off was only in the launch's own run config, the next start ran DFlash2
232        from tests.snapshot.test_drafting_round_trip import launches
233        for m in MACHINES:
234            for s in MODEL_SETS:
235                with self.subTest(machine=m.key, set=s.key):
236                    recs = launches(m, s, [("auto", False), ("off", False), (None, False), (None, False)])
237                    self.assertEqual(drafter(recs[1]), "off")
238                    for later in recs[2:]:
239                        self.assertEqual(later["engine"]["argv"], recs[1]["engine"]["argv"], "the Off of the launch before holds")
240                        self.assertEqual(later["config_file"].get("drafting"), "off", "the start without a word does not overwrite the saved Off")
241
242    def test_the_plan_after_a_saved_off_says_off(self):
243        # 0.2.14 OWNER-CELL, RTX 5070 IQ3_S: after `--drafting off`, the plan of a launch without a word said "drafting  MTP" and the engine loaded the MTP
244        from tests.snapshot.driver import run_cli
245        from tests.snapshot.test_drafting_round_trip import launches  # noqa: F401
246        from tests.snapshot.world import context_for
247        for mkey, skey in (("nv_12gb_streaming", "iq3_s"), ("strix_halo_win", "ud_q4_k_xl")):
248            with self.subTest(machine=mkey, set=skey):
249                m, s = get_machine(mkey), get_set(skey)
250                world = World(m, s).build()
251                try:
252                    with world.patched():
253                        self.assertNotIn("failed", drive_launch(world, ("--drafting", "off")))
254                        from strata_cli.launch import catalog as C
255                        from unittest import mock
256                        cat = C.Catalog(root=world.install, hardware=world.hardware_report())
257                        with mock.patch.object(C, "Catalog", lambda *a, **k: cat):
258                            code, out, _err = run_cli(["launch", "--model", s.model, "--plan", "--no-tui", "--context", str(context_for(m, s))])
259                    line = next((l for l in out.splitlines() if "rafting" in l), "")
260                    self.assertEqual(code, 0, out[-400:])
261                    self.assertIn("Off", line, out[-600:])
262                finally:
263                    world.close()
264
265
266if __name__ == "__main__":
267    unittest.main()