okami.mom/strata

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

Niko1221Merge f-par-df2 f4accc5f4 into the batch 16 candidate (parallel requests with the second drafter)9a62d969f

main
18.7 KiB308 linesraw
1"""Auto with 2 requests at once on one large Blackwell card that holds every expert starts DFlash2 slot drafts (``--draft dflash2 --batch N``, no MTP layer);
2every other class and every other number of requests keeps the rule it had (the MTP loaded, slots with no drafts). strata_control/drafting.py slot_drafts_by_default."""
3
4from __future__ import annotations
5
6import os
7import tempfile
8import unittest
9from pathlib import Path
10from types import SimpleNamespace
11from unittest import mock
12
13from strata_control import drafting
14
15GYRO = "qwen3.8-flash-next-gyro-gyro-s"
16IQ3S = "qwen3.8-flash-next-iq3_s"
17PRO5000 = 73728.0          # MiB, the 72 GB card the rule was measured on (RTX PRO 5000)
18BASE = dict(mode="auto", backend="cuda", archs=["sm_120"], vram_mib=PRO5000, args=["--expert-cache", "auto"], slots=2)
19
20
21def rule(**over) -> bool:
22    kw = {**BASE, **over}
23    return drafting.slot_drafts_by_default(kw.pop("mode"), **kw)
24
25
26_HARDWARE = mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"]))
27
28
29def setUpModule():
30    _HARDWARE.start()
31
32
33def tearDownModule():
34    _HARDWARE.stop()
35
36
37class TheRule(unittest.TestCase):
38    def setUp(self):
39        env = {k: v for k, v in os.environ.items() if k not in ("STRATA_BATCH_DF2", "STRATA_BATCH_MTP")}
40        patch = mock.patch.dict(os.environ, env, clear=True)
41        patch.start()
42        self.addCleanup(patch.stop)
43
44    def test_two_requests_on_the_measured_class_get_slot_drafts(self):
45        self.assertTrue(rule(slots=2))
46        self.assertFalse(rule(slots=3), "3 clients: DFlash2 slot drafts were level with plain slots (73.5 / 74.5 against 74.1 / 73.3 requests per minute)")
47
48    def test_one_request_and_three_or_more_keep_their_rule(self):
49        for n in (0, 1, 3, 4, 5, 8):
50            self.assertFalse(rule(slots=n), n)
51
52    def test_the_number_can_be_in_the_arguments(self):
53        for flag in ("--batch", "--slots", "--parallel"):
54            self.assertTrue(rule(slots=0, args=["--expert-cache", "auto", flag, "2"]), flag)
55            self.assertFalse(rule(slots=0, args=["--expert-cache", "auto", flag, "3"]), flag)
56        self.assertEqual(drafting.request_count(["--batch", "2"], 3), 3, "the larger of the two")
57        self.assertEqual(drafting.request_count([], None), 0)
58        self.assertEqual(drafting.request_count(["--batch", "x"], True), 0)
59
60    def test_the_other_classes_stay_as_they_are(self):
61        self.assertFalse(rule(archs=["sm_121"], vram_mib=None), "the DGX Spark: one pool of memory")
62        self.assertFalse(rule(vram_mib=None), "several cards or a card that does not answer")
63        self.assertFalse(rule(archs=["sm_86"], vram_mib=49152.0), "Ampere: DFlash2 was slower there")
64        self.assertFalse(rule(archs=["sm_89"], vram_mib=49152.0))
65        self.assertFalse(rule(vram_mib=32768.0), "a consumer Blackwell card under 48 GB")
66        self.assertFalse(rule(args=["--expert-cache", "1000"]), "an expert cache that does not hold every expert (the streaming class)")
67        for backend, archs in (("hip", ["gfx1151"]), ("hip", ["gfx1100"]), ("hip", ["gfx1201"]), ("metal", []), ("sycl", ["arc_a"]), ("cpu", []), (None, None)):
68            self.assertFalse(rule(backend=backend, archs=archs, vram_mib=PRO5000 if backend == "hip" else None), (backend, archs))
69
70    def test_only_auto_is_decided_here(self):
71        for mode in ("mtp", "off", "dflash2"):
72            self.assertFalse(rule(mode=mode), mode)       # (DFlash2 by name already runs its slots: blocked_by named)
73        self.assertTrue(rule(mode=None), "no choice saved is Auto")
74
75    def test_a_layer_split_the_person_choices_and_the_way_back_stay_as_before(self):
76        self.assertFalse(rule(split=True))
77        for extra in (["--layer-split", "auto"], ["--batch-mtp"], ["--pipeline-windows", "2"]):
78            self.assertFalse(rule(args=["--expert-cache", "auto", *extra]), extra)
79        with mock.patch.dict(os.environ, {"STRATA_BATCH_MTP": "1"}):
80            self.assertFalse(rule(), "the person asked for the MTP's slot drafts")
81        with mock.patch.dict(os.environ, {"STRATA_BATCH_MTP": "0"}):
82            self.assertTrue(rule())
83        with mock.patch.dict(os.environ, {"STRATA_BATCH_DF2": "0"}):
84            self.assertFalse(rule(), "STRATA_BATCH_DF2=0 is the way back")
85        with mock.patch.dict(os.environ, {"STRATA_BATCH_DF2": "1"}):
86            self.assertTrue(rule())
87
88    def test_no_drafter_on_this_computer_changes_nothing(self):
89        self.assertFalse(rule(drafter_here=False), "no pack: the MTP stays, with its usual line")
90
91    def test_blocked_by_lets_it_through_like_a_named_dflash2(self):
92        self.assertTrue(drafting.blocked_by([], slots=2, backend="cuda"))
93        self.assertFalse(drafting.blocked_by([], slots=2, backend="cuda", slot_drafts=True))
94        self.assertTrue(drafting.blocked_by(["--pipeline-windows", "2"], slots=2, backend="cuda", slot_drafts=True))
95        self.assertTrue(drafting.blocked_by([], slots=2, backend="metal", slot_drafts=True), "Metal has no per-request drafters")
96
97
98class TheStart(unittest.TestCase):
99    ARGS = ["--pack", "/d/packs/gyro", "--native", "/d/m.gguf", "--mtp", "", "--spec", "4", "--spec-min-p", "0.5", "--expert-cache", "auto"]
100
101    def setUp(self):
102        env = {k: v for k, v in os.environ.items() if k not in ("STRATA_BATCH_DF2", "STRATA_BATCH_MTP")}
103        patch = mock.patch.dict(os.environ, env, clear=True)
104        patch.start()
105        self.addCleanup(patch.stop)
106        self.tmp = tempfile.TemporaryDirectory()
107        self.addCleanup(self.tmp.cleanup)
108        self.data = Path(self.tmp.name)
109        self.mtp = self.data / "mtp" / "rt"
110        self.args = list(self.ARGS)
111        self.args[self.args.index("--mtp") + 1] = str(self.mtp)
112        self.mtp.mkdir(parents=True)
113        (self.mtp / "experts.bin").write_bytes(b"e")
114        (self.mtp / "draft_vocab.bin").write_bytes(b"v")
115
116    def pack(self):
117        pack = drafting.pack_path(self.data)
118        pack.parent.mkdir(parents=True)
119        pack.write_bytes(b"x" * (2 << 20))
120        return pack
121
122    def cfg(self, **extra):
123        return {"model_name": GYRO, "args": list(self.args), **extra}
124
125    def apply(self, cfg, **kw):
126        return drafting.apply(cfg, data_dir=self.data, backend="cuda", archs=["sm_120"], vram_mib=PRO5000, **kw)
127
128    def test_auto_with_two_requests_is_dflash2_with_a_drafter_per_request(self):
129        pack = self.pack()
130        for n in (2,):
131            c = self.cfg()
132            d = self.apply(c, slots=n)
133            self.assertEqual((d.drafter, d.note), ("dflash2", ""), n)
134            a = c["args"]
135            self.assertEqual((a[a.index("--draft") + 1], a[a.index("--draft-model") + 1], a[a.index("--draft-fallback") + 1]), ("dflash2", str(pack), "none"), n)
136            for flag in ("--mtp", "--spec-min-p", "--batch-mtp"):
137                self.assertNotIn(flag, a, (n, flag, "never the MTP layer beside DFlash2"))
138
139    def test_auto_with_other_numbers_of_requests_is_the_mtp_as_before(self):
140        self.pack()
141        for n in (3, 4, 8):
142            c = self.cfg()
143            d = self.apply(c, slots=n)
144            self.assertEqual((d.drafter, d.note), ("mtp", drafting.NONE_IN_SLOTS), n)
145            self.assertEqual(c["args"], self.args, n)
146
147    def test_no_pack_is_the_mtp_with_the_usual_line(self):
148        c = self.cfg()
149        d = self.apply(c, slots=2)
150        self.assertEqual((d.drafter, d.note), ("mtp", drafting.NONE_IN_SLOTS))
151        self.assertEqual(c["args"], self.args)
152
153    def test_the_ways_back(self):
154        self.pack()
155        for kw, want in (({"drafting": "mtp"}, ("mtp", "")), ({"drafting": "off"}, ("off", ""))):
156            c = self.cfg(**kw)
157            d = self.apply(c, slots=2)
158            self.assertEqual((d.drafter, d.note), want, kw)
159            self.assertNotIn("--draft", c["args"], kw)
160        c = self.cfg()
161        with mock.patch.dict(os.environ, {"STRATA_BATCH_DF2": "0"}):
162            d = self.apply(c, slots=2)
163        self.assertEqual((d.drafter, d.note, c["args"]), ("mtp", drafting.NONE_IN_SLOTS, self.args))
164
165    def test_the_server_adds_the_slots_and_says_nothing_new(self):
166        from serve.server import engine_args
167        self.pack()
168        with mock.patch("serve.server.drafting_vram_mib", return_value=PRO5000), mock.patch.object(drafting, "data_dir_of", return_value=self.data):
169            for n in (2,):
170                got = engine_args(self.cfg(parallel=n))
171                self.assertEqual((got[got.index("--draft") + 1], got[got.index("--draft-fallback") + 1], got[got.index("--batch") + 1]), ("dflash2", "none", str(n)))
172                self.assertNotIn("--mtp", got)
173                self.assertEqual(drafting.take_note(), "", "no note: DFlash2 runs")
174            for n in (3, 4):
175                got = engine_args(self.cfg(parallel=n))
176                self.assertEqual((got[:len(self.args)], got[-2:]), (self.args, ["--batch", str(n)]), "%d requests: the MTP loaded, slots with no drafts, as today" % n)
177                self.assertEqual(drafting.take_note(), drafting.NONE_IN_SLOTS)
178            # one request at a time: the same arguments with the rule on or off, byte for byte
179            for parallel in (None, 1):
180                cfg = self.cfg() if parallel is None else self.cfg(parallel=parallel)
181                on = engine_args(cfg)
182                with mock.patch.dict(os.environ, {"STRATA_BATCH_DF2": "0"}):
183                    off = engine_args(cfg)
184                self.assertEqual(on, off, parallel)
185                self.assertNotIn("--batch", on)
186            # a card that does not say its memory (several cards): as before
187            with mock.patch("serve.server.drafting_vram_mib", return_value=None):
188                got = engine_args(self.cfg(parallel=2))
189                self.assertEqual(got[:len(self.args)], self.args)
190            drafting.take_note()
191
192    def lines(self, cfg, **env):
193        """The `[strata]` lines the server prints while it builds the engine arguments for this config (nothing is started)."""
194        import contextlib
195        import io
196        from serve.server import engine_args
197        out = io.StringIO()
198        with mock.patch("serve.server.drafting_vram_mib", return_value=PRO5000), mock.patch.object(drafting, "data_dir_of", return_value=self.data), \
199                mock.patch.dict(os.environ, env), contextlib.redirect_stdout(out):
200            engine_args(cfg)
201        drafting.take_note()
202        return [x for x in out.getvalue().splitlines() if "rafting" in x]
203
204    def test_the_server_says_what_each_kind_of_start_drafts(self):
205        self.pack()
206        old_slots, old_none = "[strata] Drafting: MTP (DFlash2 isn't available in this mode)", "[strata] drafting: DFlash2 alone"
207        # request slots that draft with DFlash2 (Auto on the measured class: 2 requests; or DFlash2 by name with any number of requests)
208        want = ["[strata] Drafting: DFlash2, one guess window per request slot (spare rows only)"]
209        self.assertEqual([x for x in self.lines(self.cfg(parallel=2)) if "vocab" not in x], want)
210        self.assertEqual([x for x in self.lines(self.cfg(parallel=4, drafting="dflash2")) if "vocab" not in x], want)
211        # request slots with no drafts: Auto with 3 or more requests, and the way back (STRATA_BATCH_DF2=0) with 2
212        none = ["[strata] Drafting: none in parallel slots (one token per request and step); a single request still drafts"]
213        self.assertEqual(self.lines(self.cfg(parallel=3)), none)
214        self.assertEqual(self.lines(self.cfg(parallel=2), STRATA_BATCH_DF2="0"), none)
215        # request slots whose slots carry MTP drafts (--batch-mtp, or STRATA_BATCH_MTP): the line that was always printed there stays, and it is true (the MTP drafts, DFlash2 is not the drafter)
216        self.assertEqual(self.lines(self.cfg(parallel=3, args=[*self.args, "--batch-mtp"])), [old_slots])
217        self.assertEqual(self.lines(self.cfg(parallel=3), STRATA_BATCH_MTP="1"), [old_slots])
218        # one request at a time: today's DFlash2 line, word for word (the conf is the card's)
219        for cfg in (self.cfg(), self.cfg(parallel=1), self.cfg(drafting="dflash2")):
220            got = [x for x in self.lines(cfg) if "vocab" not in x]
221            self.assertEqual(len(got), 1, cfg)
222            self.assertRegex(got[0], r"^\[strata\] drafting: DFlash2 alone \(--draft dflash2, --draft-conf [0-9.]+\)$")
223            self.assertNotIn("slot", got[0])
224        self.assertNotIn(old_none, "".join(self.lines(self.cfg(parallel=2))), "slots with drafts no longer say 'DFlash2 alone'")
225
226    def test_the_words_come_from_pure_functions(self):
227        flag = ["--batch-mtp"]
228        self.assertTrue(drafting.slots_draft_nothing([], 2) and drafting.slots_draft_nothing(["--batch", "4"], 0))
229        self.assertFalse(drafting.slots_draft_nothing([], 1) or drafting.slots_draft_nothing([], 0), "one request at a time is not slots")
230        self.assertFalse(drafting.slots_draft_nothing(flag, 3), "--batch-mtp: the slots carry MTP drafts")
231        self.assertFalse(drafting.slots_draft_nothing(["--pipeline-windows", "2"], 3))
232        with mock.patch.dict(os.environ, {"STRATA_BATCH_MTP": "1"}):
233            self.assertFalse(drafting.slots_draft_nothing([], 3))
234        with mock.patch.dict(os.environ, {"STRATA_BATCH_MTP": "0"}):
235            self.assertTrue(drafting.slots_draft_nothing([], 3))
236        self.assertTrue(drafting.slot_drafts_run([], 2) and drafting.slot_drafts_run(["--batch", "8"], 0))
237        self.assertFalse(drafting.slot_drafts_run([], 1) or drafting.slot_drafts_run([], 0))
238        self.assertFalse(drafting.slot_drafts_run([], 2, split=True) or drafting.slot_drafts_run(["--layer-split", "auto"], 2) or drafting.slot_drafts_run(["--pipeline-windows", "2"], 2))
239        with mock.patch.dict(os.environ, {"STRATA_BATCH_DF2": "0"}):
240            self.assertFalse(drafting.slot_drafts_run([], 2))
241        self.assertEqual(drafting.line("mtp", drafting.NONE_IN_SLOTS), "Drafting: none in parallel slots (one token per request and step); a single request still drafts")
242        self.assertEqual(drafting.line("mtp", drafting.NOT_HERE), "Drafting: MTP (DFlash2 isn't available in this mode)", "the other reasons keep their form")
243        self.assertEqual(drafting.engine_info(["--mtp", "/m", "--batch", "3"], note=drafting.NONE_IN_SLOTS)["drafting_note"], drafting.line("mtp", drafting.NONE_IN_SLOTS), "/metrics and the app")
244
245    def test_mtp_slot_drafts_keep_their_line_through_apply(self):
246        self.pack()
247        c = self.cfg(args=[*self.args, "--batch-mtp"])
248        d = self.apply(c, slots=3)
249        self.assertEqual((d.drafter, d.note), ("mtp", drafting.NOT_HERE))
250        self.assertIn("--batch-mtp", c["args"])
251
252    def plan_by_command(self, parallel, args=None, **env) -> str:
253        """The plan line `strata drafting plan` shows for this config (strata_cli/drafting_cmd.py: _inputs, then decide)."""
254        from strata_cli import drafting_cmd
255        cfg = {**self.cfg(), **({} if parallel is None else {"parallel": parallel}), "args": list(args if args is not None else self.args)}
256        path = self.data / "plan.json"
257        path.write_text(__import__("json").dumps(cfg), encoding="utf-8")
258        a = SimpleNamespace(config=str(path), data_dir=str(self.data), mode=None, family="qwen", model=None, no_split=True, engines_unloading=False, drafting_command="plan")
259        with mock.patch.object(drafting, "card_vram_mib", return_value=PRO5000), mock.patch.object(drafting_cmd, "_hardware", return_value=("cuda", ["sm_120"])), \
260                mock.patch.object(drafting_cmd, "_split_expected", return_value=False), mock.patch.dict(os.environ, env):
261            want = drafting_cmd._inputs(a)
262            sig = drafting_cmd._signals(a, want)
263            return drafting.summary_line(drafting.decide(**want, **sig))
264
265    def plan_by_launch(self, parallel, args=None, **env) -> str:
266        """The plan line the Terminal's `strata launch --plan` shows (runner.drafting_plan_line) for an installed config like this one."""
267        from strata_cli.launch import settings as S
268        from strata_cli.launch.runner import Runner
269        from tests.terminal.launch_support import HW_12, Home, catalog
270        cfg = {**self.cfg(), "args": list(args if args is not None else self.args)}
271        with Home():
272            runner = Runner(S.LaunchSettings(family="qwen", model="IQ3_S", context=32768, vision="off", parallel=parallel), catalog=catalog(HW_12))
273            runner._split_expected = False
274            with mock.patch.object(Runner, "installed_state", return_value=(None, cfg)), mock.patch.object(drafting, "detect_hardware", return_value=("cuda", ["sm_120"])), \
275                    mock.patch.object(drafting, "card_vram_mib", return_value=PRO5000), mock.patch.object(drafting, "data_dir_of", return_value=self.data), mock.patch.dict(os.environ, env):
276                return runner.drafting_plan_line()
277
278    def test_the_plan_line_says_what_the_server_says(self):
279        self.pack()
280        none = "Drafting: none in parallel slots (one token per request and step); a single request still drafts"
281        mtp_slots = "Drafting: MTP (DFlash2 isn't available in this mode)"
282        for how in (self.plan_by_command, self.plan_by_launch):
283            name = how.__name__
284            self.assertEqual(how(2), "Drafting: DFlash2", (name, "2 requests on the measured class: DFlash2 slot drafts"))
285            self.assertEqual(how(3), none, (name, "slots with no drafts"))
286            self.assertEqual(how(2, STRATA_BATCH_DF2="0"), none, (name, "the way back from the slot drafts"))
287            self.assertEqual(how(3, args=[*self.args, "--batch-mtp"]), mtp_slots, (name, "MTP slot drafts keep their line"))
288            self.assertEqual(how(3, STRATA_BATCH_MTP="1"), mtp_slots, (name, "MTP slot drafts through the environment"))
289            self.assertEqual(how(1), "Drafting: DFlash2", (name, "one request at a time"))
290            self.assertEqual(how(None), "Drafting: DFlash2", (name, "the number of requests is not known: today's line"))
291        # the plan and the server print the same words in the same case
292        self.assertEqual("[strata] " + self.plan_by_command(3), self.lines(self.cfg(parallel=3))[0])
293
294    def test_the_plan_agrees_with_the_start(self):
295        from strata_cli import drafting_cmd
296        self.pack()
297        cfg_path = self.data / "run.json"
298        for parallel, expect_blocked in ((2, False), (3, True), (4, True), (1, False)):
299            cfg_path.write_text(__import__("json").dumps({**self.cfg(), "parallel": parallel}), encoding="utf-8")
300            a = SimpleNamespace(config=str(cfg_path), data_dir=str(self.data), mode=None, family="qwen", model=None, no_split=True, engines_unloading=False, drafting_command="plan")
301            with mock.patch.object(drafting, "card_vram_mib", return_value=PRO5000), mock.patch.object(drafting_cmd, "_hardware", return_value=("cuda", ["sm_120"])), \
302                    mock.patch.object(drafting_cmd, "_split_expected", return_value=False):
303                want = drafting_cmd._inputs(a)
304            self.assertEqual(want["blocked"], expect_blocked, parallel)
305
306
307if __name__ == "__main__":
308    unittest.main()