okami.mom/strata

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

Niko1221Auto on HIP gfx1201 starts the MTP until the DFlash2 prompt stall is fixed (one entry: drafting.AUTO_MTP)aba4ddaca

main
22.1 KiB325 linesraw
1"""One drafter per run, from every way in (owner, 2026-11-02): DFlash2 alone or the MTP alone, never both.
2
3strata_control/drafting.py decides; the app (apps/host, through Control and serve/server.py) and the Terminal (strata launch, its Drafting step, a saved preset)
4both end at serve/server.py engine_args(). These tests lock in the engine arguments of every choice on the main backends, the old saved values, and the Terminal
5path from the launch settings to the argument list. (tests/terminal/test_drafting.py has the table, the flags and the downloads one by one.)
6"""
7
8from __future__ import annotations
9
10import tempfile
11import unittest
12from pathlib import Path
13from unittest import mock
14
15from strata_cli.launch import settings as S
16from strata_cli.launch.runner import derive_config
17from strata_control import drafting
18
19NAMES = {"qwen": "qwen3.8-flash-next-iq3_s", "gyro": "qwen3.8-flash-next-gyro-gyro-s", "unsloth": "qwen3.8-flash-next-unsloth-ud-q4_k_xl",
20         "coder": "qwen3.8-flash-next-coder-iq1_m", "nvfp4": "qwen3.8-flash-next-nvfp4-nvfp4", "swift": "qwen3.8-flash-next-swift-q4_k_m"}
21HARDWARE = (("cuda", ["sm_120"]), ("cuda", ["sm_86"]), ("cuda", ["sm_89"]), ("hip", ["gfx1151"]), ("hip", ["gfx1201"]), ("metal", []), ("sycl", ["arc_a"]))
22MTP_ONLY = ("--mtp", "--mtp-q4", "--batch-mtp", "--spec-min-p", "--mtp-draft-vocab")
23
24
25def flag(args, name):
26    return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else None
27
28
29def loaded(args):
30    """The drafters this argument list loads: 'dflash2' for `--draft dflash2`, 'mtp' for an MTP layer folder (`--mtp <folder>` with no DFlash2)."""
31    found = set()
32    if flag(args, "--draft") == "dflash2":
33        found.add("dflash2")
34    elif "--mtp" in args:
35        found.add("mtp")
36    return found
37
38
39class Base(unittest.TestCase):
40    def setUp(self):
41        self.tmp = tempfile.TemporaryDirectory()
42        self.addCleanup(self.tmp.cleanup)
43        self.data = Path(self.tmp.name) / "data"
44        (self.data / "dflash2").mkdir(parents=True)
45        (self.data / "mtp" / "rt").mkdir(parents=True)
46        (self.data / "packs" / "tag").mkdir(parents=True)
47        (self.data / "dflash2" / drafting.PACK_NAME).write_bytes(b"x" * (2 << 20))
48        (self.data / "dflash2" / drafting.VOCAB_NAME).write_bytes(b"v" * 100)
49        (self.data / "mtp" / "rt" / "experts.bin").write_bytes(b"e" * 100)
50        (self.data / "mtp" / "rt" / drafting.VOCAB_NAME).write_bytes(b"v" * 100)
51        self.exe = Path(self.tmp.name) / "strata-engine"
52        self.exe.write_bytes(b"--mtp-draft-vocab FILE (or --mtp DIR ... --draft-fallback")   # an engine of the usual form (rc1 and later)
53        self.args = ["--native", "m.gguf", "--pack", str(self.data / "packs" / "tag"), "--mtp", str(self.data / "mtp" / "rt"), "--spec", "4", "--batch-mtp",
54                     "--mtp-q4", "all", "--spec-min-p", "0.5", "--max-context", "131072"]
55
56    def cfg(self, family="qwen", **extra):
57        return {"model_name": NAMES[family], "args": list(self.args), **extra}
58
59    def apply(self, cfg, family="qwen", backend="cuda", archs=("sm_120",), **kw):
60        d = drafting.apply(cfg, data_dir=self.data, family=family, backend=backend, archs=list(archs), engine=self.exe, **kw)
61        return d, cfg["args"]
62
63
64class EveryChoiceOnEveryBackend(Base):
65    def test_auto_dflash2_and_the_unset_choice_load_dflash2_alone(self):
66        for backend, archs in HARDWARE:
67            for family in ("qwen", "gyro", "unsloth"):
68                for mode in (None, "auto", "dflash2"):
69                    cfg = self.cfg(family, **({} if mode is None else {"drafting": mode}))
70                    d, args = self.apply(cfg, family, backend, archs)
71                    where = (backend, archs, family, mode)
72                    if archs == ["gfx1201"] and mode != "dflash2":                         # Auto on gfx1201 is the MTP until PE-RDNA4's fix (drafting.AUTO_MTP)
73                        self.assertEqual((d.drafter, loaded(args)), ("mtp", {"mtp"}), where)
74                        continue
75                    if (backend, family) == ("metal", "qwen") and mode != "dflash2":       # IQ3_S on a Mac: the MTP until the owner says otherwise (drafting.SET_DEFAULTS)
76                        self.assertEqual((d.drafter, loaded(args)), ("mtp", {"mtp"}), where)
77                        continue
78                    self.assertEqual(d.drafter, "dflash2", where)
79                    self.assertEqual(loaded(args), {"dflash2"}, where)
80                    self.assertEqual(flag(args, "--draft-fallback"), "none", where)
81                    self.assertEqual(flag(args, "--draft-model"), str(drafting.pack_path(self.data, self.exe)), where)
82                    self.assertTrue(flag(args, "--mtp-draft-vocab"), where)
83                    for name in ("--mtp", "--mtp-q4", "--batch-mtp", "--spec-min-p"):
84                        self.assertNotIn(name, args, (name, where))
85
86    def test_mtp_loads_the_mtp_alone(self):
87        for backend, archs in HARDWARE:
88            for family in ("qwen", "gyro", "unsloth"):
89                d, args = self.apply(self.cfg(family, drafting="mtp"), family, backend, archs)
90                where = (backend, archs, family)
91                self.assertEqual((d.drafter, loaded(args)), ("mtp", {"mtp"}), where)
92                self.assertFalse([a for a in args if a.startswith("--draft")], where)
93                self.assertNotIn("dflash2", " ".join(args), where)
94
95    def test_off_loads_neither(self):
96        for backend, archs in HARDWARE:
97            d, args = self.apply(self.cfg(drafting="off"), "qwen", backend, archs)
98            self.assertEqual((d.drafter, loaded(args)), ("off", set()), (backend, archs))
99            self.assertFalse([a for a in args if a in MTP_ONLY or a.startswith("--draft")])
100
101    def test_no_engine_with_the_code_means_the_mtp_for_auto(self):
102        for backend in (None, "cpu"):
103            for mode in (None, "auto", "dflash2"):
104                d, args = self.apply(self.cfg(**({} if mode is None else {"drafting": mode})), "qwen", backend, ())
105                self.assertEqual((d.drafter, loaded(args)), ("mtp", {"mtp"}), (backend, mode))
106
107    def test_other_families_never_get_dflash2_whatever_is_saved(self):
108        for family in ("coder", "nvfp4", "swift"):
109            for mode in (None, "auto", "mtp", "dflash2"):
110                cfg = self.cfg(family, **({} if mode is None else {"drafting": mode}))
111                d, args = self.apply(cfg, family, "cuda", ("sm_120",))
112                self.assertNotIn("--draft", args, (family, mode))
113                self.assertEqual(loaded(args), {"mtp"}, (family, mode))
114
115    def test_several_requests_load_the_mtp_alone_for_auto(self):
116        for mode in (None, "auto"):
117            d, args = self.apply(self.cfg(**({} if mode is None else {"drafting": mode})), slots=4)
118            self.assertEqual((d.drafter, d.note, loaded(args)), ("mtp", drafting.NOT_HERE, {"mtp"}), mode)
119            self.assertFalse([a for a in args if a.startswith("--draft")])
120        d, args = self.apply(self.cfg(drafting="mtp"), slots=4)
121        self.assertEqual((d.drafter, d.note, loaded(args)), ("mtp", "", {"mtp"}))
122
123    def test_several_requests_keep_dflash2_when_the_person_chose_it_by_name(self):
124        """Owner 2026-11-03: the person's own choice wins (DFlash2 named + a number of requests = DFlash2 with that many), on every backend that runs it."""
125        for backend, archs in HARDWARE:
126            for slots in (2, 4, 8):
127                d, args = self.apply(self.cfg(drafting="dflash2"), "qwen", backend, archs, slots=slots)
128                if backend == "metal":
129                    # the Metal engine has no per-request drafters: DFlash2 beside request slots would draft nothing, so today's behaviour stays (owner 2026-11-03)
130                    self.assertEqual((d.drafter, d.note, loaded(args)), ("mtp", drafting.NOT_HERE, {"mtp"}), (backend, slots))
131                    self.assertFalse([a for a in args if a.startswith("--draft")])
132                    continue
133                self.assertEqual((d.drafter, d.note, loaded(args)), ("dflash2", "", {"dflash2"}), (backend, slots))
134                self.assertNotIn("--mtp", args)
135        d, args = self.apply(self.cfg(drafting="dflash2"), "qwen", "metal", (), slots=1)
136        self.assertEqual((d.drafter, d.note), ("dflash2", ""), "one request on Metal is DFlash2 as before")
137        self.assertTrue(drafting.blocked_by([], slots=4, named=True, backend="metal"))
138        self.assertTrue(drafting.blocked_by(["--batch", "3"], named=True, backend="Metal"))
139        self.assertFalse(drafting.blocked_by([], slots=4, named=True, backend="cuda"))
140
141    def test_a_layer_split_runs_dflash2_alone_like_one_card(self):
142        """Owner 2026-11-02: Auto is DFlash2 on a layer split over several cards too (the 0.1.56 engine runs it; paired decode 1.014 against the MTP)."""
143        for backend, archs in (("cuda", ["sm_120"]), ("cuda", ["sm_86"]), ("hip", ["gfx1151"]), ("hip", ["gfx1100"])):      # (gfx1201: Auto is the MTP for now, drafting.AUTO_MTP; test_drafting_auto_mtp.py)
144            for mode in (None, "auto", "dflash2"):
145                cfg = self.cfg(**({} if mode is None else {"drafting": mode}))
146                one, args_one = self.apply(dict(cfg, args=list(cfg["args"])), "qwen", backend, archs)
147                two, args_two = self.apply(dict(cfg, args=list(cfg["args"])), "qwen", backend, archs, split=True)
148                self.assertEqual((two.drafter, two.note, loaded(args_two)), ("dflash2", "", {"dflash2"}), (backend, mode))
149                self.assertEqual(args_two, args_one, "the same arguments as one card")
150                self.assertNotIn("--mtp", args_two)
151            d, args = self.apply(self.cfg(drafting="mtp"), "qwen", backend, archs, split=True)
152            self.assertEqual((d.drafter, d.note, loaded(args)), ("mtp", "", {"mtp"}), backend)
153            self.assertFalse([a for a in args if a.startswith("--draft")])
154        # a saved argument list that already names the layer split changes nothing either
155        d, args = self.apply(self.cfg(args=[*self.args, "--layer-split", "auto"], drafting="auto"))
156        self.assertEqual((d.drafter, loaded(args)), ("dflash2", {"dflash2"}))
157        self.assertEqual(flag(args, "--layer-split"), "auto")
158
159    def test_a_missing_file_runs_the_other_drafter_alone_and_says_so(self):
160        (self.data / "dflash2" / drafting.PACK_NAME).unlink()
161        for mode in (None, "auto", "dflash2"):
162            d, args = self.apply(self.cfg(**({} if mode is None else {"drafting": mode})))
163            self.assertEqual((d.drafter, d.note, loaded(args)), ("mtp", drafting.NOT_DOWNLOADED, {"mtp"}), mode)
164        (self.data / "dflash2" / drafting.PACK_NAME).write_bytes(b"x" * (2 << 20))
165        (self.data / "mtp" / "rt" / "experts.bin").unlink()
166        d, args = self.apply(self.cfg(drafting="mtp"))
167        self.assertEqual((d.drafter, d.note, loaded(args)), ("dflash2", drafting.NO_MTP, {"dflash2"}))
168
169
170class OldSavedValues(Base):
171    def test_a_value_nobody_writes_any_more_is_auto(self):
172        for old in ("both", "mtp+dflash2", "dflash2+mtp", "dflash", "", None, True, 1, "fastest"):
173            self.assertEqual(drafting.normalize(old), "auto", old)
174        for same in ("DFlash2", " dflash2 "):
175            self.assertEqual(drafting.normalize(same), "dflash2", same)
176        for same in ("MTP", " mtp "):
177            self.assertEqual(drafting.normalize(same), "mtp", same)
178
179    def test_every_old_value_loads_one_drafter(self):
180        for old in ("both", "mtp+dflash2", "dflash2+mtp", "dflash", "", None, True, "DFlash2", "MTP"):
181            d, args = self.apply(self.cfg(drafting=old))
182            self.assertEqual(len(loaded(args)), 1, old)
183            self.assertEqual(loaded(args), {"mtp"} if str(old).strip().lower() == "mtp" else {"dflash2"}, old)
184
185    def test_a_saved_argument_list_that_names_both_drafters_starts_with_the_one_chosen(self):
186        both = [*self.args, "--draft", "dflash2", "--draft-model", "old.pack", "--draft-fallback", "mtp", "--draft-conf", "0.5"]
187        for mode, want in ((None, "dflash2"), ("auto", "dflash2"), ("dflash2", "dflash2"), ("mtp", "mtp"), ("both", "dflash2")):
188            cfg = {"model_name": NAMES["qwen"], "args": list(both), **({} if mode is None else {"drafting": mode})}
189            d, args = self.apply(cfg)
190            self.assertEqual(loaded(args), {want}, mode)
191            if want == "dflash2":
192                self.assertEqual(flag(args, "--draft-fallback"), "none", mode)
193                self.assertNotIn("--mtp", args, mode)
194            else:
195                self.assertNotIn("--draft", args, mode)
196                self.assertNotIn("--draft-fallback", args, mode)
197
198    def test_the_mtp_switch_off_with_no_choice_is_no_drafter_but_a_choice_wins(self):
199        d, args = self.apply(self.cfg(mtp=False))
200        self.assertEqual((d.drafter, loaded(args)), ("off", set()))
201        d, args = self.apply(self.cfg(mtp=False, drafting="mtp"))
202        self.assertEqual((d.drafter, loaded(args)), ("mtp", {"mtp"}))
203        d, args = self.apply(self.cfg(mtp=False, drafting="dflash2"))
204        self.assertEqual((d.drafter, loaded(args)), ("dflash2", {"dflash2"}))
205
206
207class TheServerAndTheTerminalEndAtTheSameArguments(Base):
208    """serve/server.py engine_args() is where the app's Load (through Control's saved profile), `strata launch` and the Terminal's steps all arrive."""
209
210    def server_args(self, cfg, backend="cuda", archs=("sm_120",)):
211        from serve.server import engine_args
212        with mock.patch.object(drafting, "detect_hardware", return_value=(backend, list(archs))), mock.patch("serve.server.drafting_vram_mib", return_value=None), \
213                mock.patch.object(drafting, "installed_engine_exe", return_value=self.exe):
214            return engine_args(cfg, str(self.exe), announce=False)
215
216    def test_each_choice_through_the_server(self):
217        for backend, archs in HARDWARE:
218            for mode, want in ((None, {"dflash2"}), ("auto", {"dflash2"}), ("dflash2", {"dflash2"}), ("mtp", {"mtp"}), ("off", set())):
219                args = self.server_args(self.cfg(**({} if mode is None else {"drafting": mode})), backend, archs)
220                if backend == "metal" and mode in (None, "auto"):          # NAMES["qwen"] is IQ3_S: the MTP on a Mac (drafting.SET_DEFAULTS)
221                    want = {"mtp"}
222                if archs == ["gfx1201"] and mode in (None, "auto"):        # Auto on gfx1201 is the MTP until PE-RDNA4's fix (drafting.AUTO_MTP)
223                    want = {"mtp"}
224                self.assertEqual(loaded(args), want, (backend, archs, mode))
225                if want == {"dflash2"}:
226                    self.assertNotIn("--mtp", args)
227                elif want == {"mtp"}:
228                    self.assertFalse([a for a in args if a.startswith("--draft")])
229
230    def test_a_layer_split_through_the_server(self):
231        for backend, archs in (("cuda", ["sm_120"]), ("cuda", ["sm_86"]), ("hip", ["gfx1100"])):
232            for mode, want in ((None, {"dflash2"}), ("auto", {"dflash2"}), ("dflash2", {"dflash2"}), ("mtp", {"mtp"}), ("off", set())):
233                cfg = self.cfg(gpu=[0, 1], **({} if mode is None else {"drafting": mode}))
234                args = self.server_args(cfg, backend, archs)
235                where = (backend, archs, mode)
236                self.assertEqual(loaded(args), want, where)
237                self.assertIn("--layer-split", args, where)
238                if want == {"dflash2"}:
239                    self.assertEqual(flag(args, "--draft-fallback"), "none", where)
240                    self.assertNotIn("--mtp", args, where)
241                elif want == {"mtp"}:
242                    self.assertFalse([a for a in args if a.startswith("--draft")], where)
243
244    def test_a_layer_split_with_several_requests_is_the_mtp_alone_for_auto_and_dflash2_with_dflash2_by_name(self):
245        args = self.server_args(self.cfg(gpu=[0, 1], parallel=4, drafting="auto"))
246        self.assertEqual(loaded(args), {"mtp"}, "Auto")
247        self.assertFalse([a for a in args if a.startswith("--draft")], "Auto")
248        args = self.server_args(self.cfg(gpu=[0, 1], parallel=4, drafting="dflash2"))
249        self.assertEqual(loaded(args), {"dflash2"}, "named")
250        self.assertEqual((flag(args, "--draft-fallback"), flag(args, "--batch")), ("none", "4"))
251        self.assertIn("--layer-split", args)
252        self.assertNotIn("--mtp", args)
253
254    def test_metal_named_dflash2_with_requests_starts_the_mtp_exactly_as_0_2_10_did(self):
255        """Metal has no per-request drafters, so a DFlash2 chosen by name with several requests is the MTP there, with the MTP's own --batch-mtp (the saved one, or Expert mode's
256        wish, which the app adds to the arguments) kept: the same arguments the MTP chosen by name gets, which is what 0.2.10 started for this case."""
257        for parallel in (2, 4, 8):
258            named = self.server_args(self.cfg(drafting="dflash2", parallel=parallel), "metal", ())
259            self.assertEqual(named, self.server_args(self.cfg(drafting="mtp", parallel=parallel), "metal", ()), parallel)
260            self.assertEqual(named, self.server_args(self.cfg(parallel=parallel), "metal", ()), "and the same as Auto")
261            self.assertIn("--batch-mtp", named)
262            self.assertEqual((flag(named, "--batch"), flag(named, "--mtp"), "--draft" in named), (str(parallel), str(self.data / "mtp" / "rt"), False))
263        # the same saved arguments on CUDA: DFlash2 with the requests, the MTP's slot switch is taken out
264        cuda = self.server_args(self.cfg(drafting="dflash2", parallel=4))
265        self.assertEqual((loaded(cuda), "--batch-mtp" in cuda, flag(cuda, "--batch")), ({"dflash2"}, False, "4"))
266
267    def test_the_all_cards_split_engine_still_runs_its_mtp(self):
268        from tests.split import test_split_engine as TS
269        (Path(self.tmp.name) / "data").mkdir(exist_ok=True)
270        (Path(self.tmp.name) / "data" / "draft_vocab_en.bin").write_bytes(b"x")
271        for mode in (None, "auto", "mtp"):
272            cfg = {"exe": "component:strata-engine", "args": ["--pack", str(self.data / "packs" / "tag"), "--native", "/m/a-00001-of-00004.gguf", "--mtp", str(self.data / "mtp" / "rt"),
273                                                              "--max-context", "131072", "--layer-split", "auto"],
274                   "cwd": self.tmp.name, "tokenizer": "tok", "port": 8080, "gpu": [0, 1], "env": {}, "model_name": NAMES["qwen"]}
275            if mode:
276                cfg["drafting"] = mode
277            d = TS.S.apply_to_config(cfg, exe_for_cards=lambda n, cc=None: "/e/strata-split-2", system="linux", probe=lambda idx: TS.cards(), ram=lambda: (125.0, 80.0),
278                                     scan=lambda path: TS.udq4())
279            self.assertTrue(d.use_split, (mode, d.reasons))
280            args = self.server_args(cfg)
281            self.assertEqual(loaded(args), {"mtp"}, mode)
282            self.assertNotIn("--draft", args, mode)          # (the split engine's own --draft-vocab is its draft head file, not the DFlash2 drafter)
283        cfg = {"exe": "component:strata-engine", "args": ["--pack", str(self.data / "packs" / "tag"), "--native", "/m/a-00001-of-00004.gguf", "--mtp", str(self.data / "mtp" / "rt"), "--layer-split", "auto"],
284               "cwd": self.tmp.name, "tokenizer": "tok", "port": 8080, "gpu": [0, 1], "env": {}, "drafting": "dflash2", "model_name": NAMES["qwen"]}
285        d = TS.S.apply_to_config(cfg, exe_for_cards=lambda n, cc=None: "/e/strata-split-2", system="linux", probe=lambda idx: TS.cards(), ram=lambda: (125.0, 80.0),
286                                 scan=lambda path: TS.udq4())
287        self.assertFalse(d.use_split, "an explicit DFlash2 keeps the layer split, now with DFlash2")
288        self.assertEqual(loaded(self.server_args(cfg)), {"dflash2"})
289
290    def test_deepseek_gets_no_drafter_arguments(self):
291        cfg = {"model_name": "deepseek-v4.1-flash", "arch": "deepseek41", "args": ["--pack", "/d/ds", "--spec", "2"], "drafting": "dflash2"}
292        args = self.server_args(cfg)
293        self.assertEqual((loaded(args), [a for a in args if a.startswith("--draft")]), (set(), []))
294
295    def test_the_terminal_choices_reach_the_engine_alone(self):
296        base = {"exe": "component:strata-engine", "model_name": NAMES["qwen"], "port": 8080, "args": list(self.args)}
297        for choice, want in ((None, {"dflash2"}), ("auto", {"dflash2"}), ("dflash2", {"dflash2"}), ("mtp", {"mtp"}), ("off", set())):
298            with mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])):
299                cfg = derive_config(base, S.LaunchSettings(drafting=choice), bool_flags=frozenset())
300            args = self.server_args(cfg)
301            self.assertEqual(loaded(args), want, choice)
302
303    def test_auto_in_the_terminal_overrides_a_choice_the_app_saved_in_the_model_file(self):
304        """The app writes its Drafting choice into the model's own settings file; the Terminal derives its run config from that file. Choosing Auto in the Terminal's
305        Drafting step has to mean Auto, not the app's older choice (the step stores what modelstate.drafting_to_save says)."""
306        from strata_cli.launch import modelstate
307        for saved, key, want in (("mtp", "auto", {"dflash2"}), ("off", "auto", {"dflash2"}), ("dflash2", "mtp", {"mtp"}), ("mtp", "dflash2", {"dflash2"}),
308                                 ("mtp", "off", set()), (None, "auto", {"dflash2"}), ("auto", "auto", {"dflash2"}), (None, "mtp", {"mtp"})):
309            base = {"exe": "component:strata-engine", "model_name": NAMES["qwen"], "port": 8080, "args": list(self.args), **({} if saved is None else {"drafting": saved})}
310            with mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])):
311                cfg = derive_config(base, S.LaunchSettings(drafting=modelstate.drafting_to_save(key, saved)), bool_flags=frozenset())
312            self.assertEqual(loaded(self.server_args(cfg)), want, (saved, key))
313
314    def test_the_step_writes_nothing_for_auto_unless_the_file_holds_another_choice(self):
315        from strata_cli.launch import modelstate
316        for saved in (None, "auto", "AUTO", "both", "fastest", ""):
317            self.assertIsNone(modelstate.drafting_to_save("auto", saved) if drafting.normalize(saved) == "auto" else None, saved)
318        for saved in ("mtp", "dflash2", "off", "MTP"):
319            self.assertEqual(modelstate.drafting_to_save("auto", saved), "auto", saved)
320        for key in ("mtp", "dflash2", "off"):
321            self.assertEqual(modelstate.drafting_to_save(key, "mtp"), key)
322
323
324if __name__ == "__main__":
325    unittest.main()