okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
41.1 KiB715 linesraw
1"""The all-cards split engine and the parallel setting: no collision, and the number means the split's lanes.
2
3The split's run config (strata_control/split_engine.split_config) always carries `--batch N`.  The launcher used to write a launch-profile override
4`parallel=<card fit>` beside it even when nobody asked, and `strata serve --profile` (strata_cli/cli.py _effective) refuses a parallel override next to
5--batch: every 2-card NVIDIA start with the split on Auto stopped with "parallel override conflicts with --batch/--slots in run config args".
6Now: the launcher writes no parallel override when the run config holds the slots; `--parallel N` is the split's lanes; the app's Concurrent requests
7(a profile override on the saved run config) is accepted for a split config and sets --batch in the engine's arguments.  Nothing is started.
8"""
9
10from __future__ import annotations
11
12import contextlib
13import copy
14import io
15import json
16import tempfile
17import unittest
18from pathlib import Path
19from unittest import mock
20
21from strata_cli import cli
22from strata_cli.launch import settings as S
23from strata_cli.launch.runner import Runner
24from strata_control import profiles, split_engine as SE
25from tests.terminal.launch_support import HW_12, Home, catalog
26import serve.server  # noqa: F401  imported before any test patches sys.platform: serve/lifeline.py runs Linux-only libc code when it is imported as Linux
27
28A6000 = {"name": "NVIDIA RTX A6000", "vram_gb": 48.0, "usable": True, "vendor": "nvidia"}
29HW_2XA6000 = {**HW_12, "ram_gb": 125.0, "disk_free_gb": 900.0, "engine_vendor": "nvidia", "gpus": [{**A6000, "index": i} for i in range(2)]}
30R9700 = {"name": "AMD Radeon AI PRO R9700", "vram_gb": 32.0, "usable": True, "vendor": "amd", "arch": "gfx1201"}
31HW_4XR9700 = {**HW_12, "ram_gb": 251.0, "disk_free_gb": 900.0, "engine_vendor": "amd", "gpus": [{**R9700, "index": i} for i in range(4)]}
32
33SPLIT_ARGS = ["--native", "/m/x-00001.gguf", "--mtp", "/m/mtp/rt", "--draft-vocab", "/e/draft_vocab_en.bin", "--max-context", "131072",
34              "--spec", "6", "--lookup", "15", "--conversation-cache-mib", "4096", "--batch", "6"]
35LAYER_ARGS = ["--pack", "/m/packs/x", "--native", "/m/x-00001.gguf", "--spec", "4", "--mtp", "/m/mtp/rt"]
36
37
38def split_cfg(lanes: int = 6, **more) -> dict:
39    args = list(SPLIT_ARGS)
40    args[args.index("--batch") + 1] = str(lanes)
41    return {"exe": "/e/strata-split-2-sm120", "args": args, "tokenizer": "/m/tokenizer", "model_name": "m", "port": 8080,
42            "split_engine_note": "Using the all-cards split engine on 2 cards.", "drafting": "mtp", **more}
43
44
45def layer_cfg(**more) -> dict:
46    return {"exe": "/e/strata", "args": list(LAYER_ARGS), "tokenizer": "/m/tokenizer", "model_name": "m", "port": 8080, **more}
47
48
49class Base(unittest.TestCase):
50    hw = HW_2XA6000
51
52    def setUp(self):
53        self.home = Home().__enter__()
54        self.addCleanup(self.home.__exit__, None, None, None)
55        # the all-cards split rule asks the host OS and is Linux only (strata_control/split_engine.expected): these fake cards are a Linux PC
56        plat = mock.patch("sys.platform", "linux")
57        plat.start()
58        self.addCleanup(plat.stop)
59        # and NVIDIA: an Intel Arc in the box that runs the test would make the launch an Intel one (Runner.intel_chosen reads the real machine)
60        intel = mock.patch.object(Runner, "intel_chosen", lambda self: False)
61        intel.start()
62        self.addCleanup(intel.stop)
63
64    def profile_for(self, cfg: dict, *, parallel=None, hw=None, four_card=None) -> dict:
65        """What Runner.ensure_profile saves as the launch profile's overrides for this written run config."""
66        cfgfile = Path(self.home.base) / "cfg.json"
67        cfgfile.write_text(json.dumps(cfg), encoding="utf-8")
68        s = S.LaunchSettings(family="qwen", model="UD-Q4_K_XL", context=131072, tune="skip", parallel=parallel)
69        r = Runner(s, catalog=catalog(hw or self.hw))
70        if four_card is not None:
71            r.four_card_parallel = four_card
72        r.ensure_profile(cfgfile)
73        prof, _rev = profiles.load(r.profile)
74        return dict(prof.get("overrides") or {})
75
76
77class TerminalPath(Base):
78    def test_the_split_run_config_gets_no_parallel_override_by_default(self):
79        """The 2-card Auto start: before, the card-fit default (4) was written beside the split's --batch and the server refused to start."""
80        ov = self.profile_for(split_cfg())
81        self.assertNotIn("parallel", ov)
82        values, _o = cli._effective(split_cfg(), {"overrides": ov}, None)      # the check that refused the start
83        self.assertEqual(values["parallel"], None)
84
85    def test_a_layer_split_run_config_keeps_the_fitted_default(self):
86        ov = self.profile_for(layer_cfg())
87        self.assertEqual(ov.get("parallel"), 4, "48 GB card: the fitted default is unchanged on the layer split")
88        cli._effective(layer_cfg(), {"overrides": ov}, None)
89
90    def test_parallel_n_on_the_split_is_not_a_profile_override_either(self):
91        ov = self.profile_for(split_cfg(lanes=3), parallel=3)
92        self.assertNotIn("parallel", ov)
93        cli._effective(split_cfg(lanes=3), {"overrides": ov}, None)
94
95    def test_the_amd_four_card_default_does_not_collide_with_the_split(self):
96        """AMD gfx1201 x4 starts the split by itself too; amd_four_card.apply put parallel=8 in the run config and the launcher mirrored it into the profile."""
97        cfg = split_cfg(lanes=8, parallel=8, exe="/e/strata-split-4-amd")
98        ov = self.profile_for(cfg, hw=HW_4XR9700, four_card=8)
99        self.assertNotIn("parallel", ov)
100        values, origins = cli._effective(cfg, {"overrides": ov}, None)
101        self.assertEqual((values["parallel"], origins["parallel"]), (8, "run_config"))
102
103    def test_the_conflict_check_still_stops_a_plain_batch_config(self):
104        """Only the split's run config is exempt: another config with its own --batch and a parallel override is still refused."""
105        cfg = layer_cfg(args=LAYER_ARGS + ["--batch", "6"])
106        with self.assertRaises(profiles.ProfileError):
107            cli._effective(cfg, {"overrides": {"parallel": 4}}, None)
108
109
110class LanesFromTheFlag(Base):
111    def run_apply(self, parallel, use_split):
112        """Runner.apply_split_engine with the rule stubbed: what the rule sees in the config, and what is left of it afterwards."""
113        seen = {}
114
115        def fake(cfg, **_kw):
116            seen["parallel"] = cfg.get("parallel")
117            if use_split:
118                new = split_cfg(lanes=int(cfg.get("parallel") or 6), parallel=cfg.get("parallel"))
119                cfg.clear()
120                cfg.update(new)
121            return SE.Decision(use_split, ["Using the all-cards split engine on 2 cards."] if use_split else ["no"], 2, quiet=not use_split)
122
123        s = S.LaunchSettings(family="qwen", model="UD-Q4_K_XL", context=131072, tune="skip", parallel=parallel)
124        r = Runner(s, catalog=catalog(self.hw))
125        mtp = Path(self.home.base) / "mtp" / "rt"                     # the draft layer is on disk
126        mtp.mkdir(parents=True, exist_ok=True)
127        (mtp / "dense.bin").write_bytes(b"x")
128        cfg = layer_cfg(args=LAYER_ARGS[:-1] + [str(mtp)])
129        with mock.patch.object(SE, "apply_to_config", fake), contextlib.redirect_stdout(io.StringIO()):
130            r.apply_split_engine(cfg)
131        self.layer_args = LAYER_ARGS[:-1] + [str(mtp)]
132        return seen["parallel"], cfg
133
134    def test_parallel_n_reaches_the_rule_and_becomes_the_lane_count(self):
135        seen, cfg = self.run_apply(3, True)
136        self.assertEqual(seen, 3)
137        self.assertEqual(cfg["args"][cfg["args"].index("--batch") + 1], "3")
138
139    def test_without_the_flag_the_rule_sees_nothing_and_the_default_lanes_stay(self):
140        seen, cfg = self.run_apply(None, True)
141        self.assertIsNone(seen)
142        self.assertEqual(cfg["args"][cfg["args"].index("--batch") + 1], "6")
143
144    def test_a_refusal_leaves_the_layer_split_config_without_the_extra_key(self):
145        seen, cfg = self.run_apply(3, False)
146        self.assertEqual(seen, 3)
147        self.assertNotIn("parallel", cfg)
148        self.assertEqual(cfg["args"], self.layer_args)
149
150
151class DraftLayerMissing(Base):
152    """The plan for Auto downloads DFlash2's drafter and not the draft layer; the split needs the draft layer (--mtp) and exits at start without it
153    ("sfnx: --native and --mtp are required"), so the server fell back to the layer split after a failed start and a misleading line.  Now the launcher
154    does not pick the split when the draft layer's folder is not on disk."""
155
156    def run_apply(self, mode, mtp_exists):
157        called = []
158        mtp = Path(self.home.base) / "mtp" / "rt"
159        if mtp_exists:
160            mtp.mkdir(parents=True)
161            (mtp / "dense.bin").write_bytes(b"x")
162        cfg = layer_cfg(args=LAYER_ARGS[:-1] + [str(mtp)], **({"split_engine": mode} if mode else {}))
163
164        def fake(c, **_kw):
165            called.append(True)
166            return SE.Decision(False, ["no"], 2, quiet=True)
167
168        r = Runner(S.LaunchSettings(family="qwen", model="UD-Q4_K_XL", context=131072, tune="skip"), catalog=catalog(self.hw))
169        with mock.patch.object(SE, "apply_to_config", fake), contextlib.redirect_stdout(io.StringIO()):
170            r.apply_split_engine(cfg)
171        return bool(called), r.notices
172
173    def test_without_the_folder_auto_stays_on_the_layer_split_without_a_word(self):
174        called, notices = self.run_apply(None, False)
175        self.assertEqual((called, notices), (False, []))
176
177    def test_without_the_folder_on_says_how_to_get_it(self):
178        called, notices = self.run_apply("on", False)
179        self.assertFalse(called)
180        self.assertEqual(len(notices), 1)
181        self.assertIn("--drafting mtp", notices[0])
182
183    def test_with_the_folder_the_rule_is_asked_as_before(self):
184        self.assertEqual(self.run_apply(None, True), (True, []))
185
186    def test_off_never_asks(self):
187        self.assertEqual(self.run_apply("off", True), (False, []))
188
189
190def cards(n, cc=120, vendor="nvidia", arch=""):
191    return [SE.Card(i, "RTX PRO 6000" if vendor == "nvidia" else "R9700", 98304 if vendor == "nvidia" else 32768, cc if vendor == "nvidia" else 0, vendor, arch)
192            for i in range(n)]
193
194
195class AutoFetchesTheDraftLayer(Base):
196    """The owner's default: the split engine on 2 cards (sm_86 / sm_120) and on 4 x gfx1201.  It runs the MTP draft layer and nothing else, so where Auto will pick it the plan and
197    the fetch are for the MTP (5.2 GB), not DFlash2's drafter; a person's own DFlash2 / off keeps the layer split; one card, other cards and --split-engine off keep DFlash2."""
198
199    def settings(self, **kw):
200        return S.LaunchSettings(**{"family": "qwen", "model": "UD-Q4_K_XL", "context": 131072, "tune": "skip", "vision": "off", **kw})
201
202    def runner(self, probe, **kw):
203        r = Runner(self.settings(**kw), catalog=catalog(self.hw))
204        self.patches = [mock.patch.object(SE, "probe_cards", lambda idx=None: probe), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)),
205                        mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"]))]
206        for p in self.patches:
207            p.start()
208            self.addCleanup(p.stop)
209        return r
210
211    def test_two_cards_on_auto_resolve_to_the_mtp_and_the_plan_says_why(self):
212        r = self.runner(cards(2), gpus=[0, 1])
213        self.assertEqual(r.resolved_drafting("qwen"), "mtp")
214        self.assertEqual(r.drafting_plan_line(), "Drafting: MTP (the all-cards split engine uses the MTP draft layer, 5.2 GB)")
215        kinds = [p["kind"] for p in r.download_plan()["parts"]]
216        self.assertIn("mtp", kinds)
217        self.assertNotIn("dflash2", kinds)
218
219    def test_the_size_in_the_plan_is_the_size_setup_fetches(self):
220        """tools/mtp_fetch.py reads the same 31 pinned tensors of the checkpoint for every set (5.214 GB) and packs them into the 0.9 GB layer the engine loads; the plan, the
221        plan line, `strata drafting plan` and setup's own disk check all use that one number."""
222        from strata_control.discovery import MTP_FETCH_GB
223        r = self.runner(cards(2), gpus=[0, 1])
224        part = next(p for p in r.download_plan()["parts"] if p["kind"] == "mtp")
225        self.assertEqual(part["gb"], MTP_FETCH_GB)
226        self.assertIn(f"{MTP_FETCH_GB:g} GB", r.drafting_plan_line())
227        setup_text = (Path(__file__).resolve().parents[2] / "setup.py").read_text(encoding="utf-8")
228        self.assertIn(f"mtp_fetch = {MTP_FETCH_GB} if", setup_text, "setup.py counts the layer with the same number")
229        self.assertEqual(MTP_FETCH_GB, 5.2)
230
231    def test_the_inputs_of_the_fetch_are_the_mtp_so_the_dflash2_drafter_is_not_fetched(self):
232        from strata_control import drafting
233        r = self.runner(cards(2), gpus=[0, 1])
234        want = r.drafting_inputs({"model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "args": []})
235        self.assertEqual(want["mode"], "mtp")
236        self.assertFalse(drafting.needs_pack(**want))
237        self.assertFalse(drafting.wants_one_request(**want), "the split has its lanes: no 'one request at a time'")
238
239    def test_a_persons_own_choice_off_or_one_card_or_an_other_card_keeps_dflash2(self):
240        for name, probe, kw in (("their own DFlash2", cards(2), {"gpus": [0, 1], "drafting": "dflash2"}),
241                                ("split-engine off", cards(2), {"gpus": [0, 1], "split_engine": "off"}),
242                                ("one card", cards(1), {"gpus": [0]}),
243                                ("sm_89 cards", cards(2, cc=89), {"gpus": [0, 1]}),
244                                ("three cards", cards(3), {"gpus": [0, 1, 2]})):
245            with self.subTest(name):
246                r = self.runner(probe, **kw)
247                self.assertEqual(r.resolved_drafting("qwen"), "dflash2")
248                self.assertNotIn("mtp", [p["kind"] for p in r.download_plan()["parts"]])
249
250    def test_dflash2_by_name_with_the_split_engine_on_fetches_the_dflash2_drafter_not_the_layer(self):
251        """Owner 2026-11-03: both choices are the person's own (--drafting dflash2 --split-engine on): the split engine runs, with DFlash2's drafter."""
252        r = self.runner(cards(2), gpus=[0, 1], drafting="dflash2", split_engine="on")
253        self.assertTrue(r.split_expected())
254        self.assertEqual(r.resolved_drafting("qwen"), "dflash2")
255        kinds = [p["kind"] for p in r.download_plan()["parts"]]
256        self.assertIn("dflash2", kinds)
257        self.assertNotIn("mtp", kinds)
258        want = r.drafting_inputs({"model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "args": []})
259        self.assertEqual(want["mode"], "dflash2")
260        self.assertNotIn("MTP", r.drafting_plan_line())
261        # the same name with the split engine on Auto stays the layer split (and a number of requests changes nothing about which drafter)
262        r = self.runner(cards(2), gpus=[0, 1], drafting="dflash2")
263        self.assertFalse(r.split_expected())
264        r = self.runner(cards(2), gpus=[0, 1], drafting="dflash2", split_engine="on", parallel=4)
265        want = r.drafting_inputs({"model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "args": []})
266        self.assertEqual((want["mode"], want["blocked"]), ("dflash2", False), "the person's own number of requests no longer blocks a DFlash2 they named")
267
268    def test_amd_four_gfx1201_is_the_mtp_two_are_not(self):
269        self.hw = HW_4XR9700
270        r = self.runner(cards(4, vendor="amd", arch="gfx1201"), gpus=[0, 1, 2, 3])
271        self.assertEqual(r.resolved_drafting("qwen"), "mtp")
272        r2 = self.runner(cards(2, vendor="amd", arch="gfx1201"), gpus=[0, 1])
273        self.assertEqual(r2.resolved_drafting("qwen"), "dflash2")
274
275    def test_the_rule_answers_without_files_and_says_no_to_what_it_would_refuse(self):
276        self.assertTrue(SE.expected({}, indexes=[0, 1], probe=lambda i: cards(2), ram=lambda: (500.0, 400.0), system="linux"))
277        self.assertFalse(SE.expected({"split_engine": "off"}, probe=lambda i: cards(2), ram=lambda: (500.0, 400.0), system="linux"))
278        self.assertFalse(SE.expected({"drafting": "dflash2"}, probe=lambda i: cards(2), ram=lambda: (500.0, 400.0), system="linux"))
279        self.assertTrue(SE.expected({"drafting": "dflash2", "split_engine": "on"}, probe=lambda i: cards(2), ram=lambda: (500.0, 400.0), system="linux"), "named and asked for: both are the person's own")
280        self.assertFalse(SE.expected({}, probe=lambda i: cards(2), ram=lambda: (500.0, 400.0), system="darwin"))
281        self.assertFalse(SE.expected({}, probe=lambda i: cards(2), ram=lambda: (500.0, 4.0), system="linux"), "not enough RAM for the locked tables")
282
283    def test_the_apps_drafting_plan_follows_the_same_rule(self):
284        from strata_cli import drafting_cmd
285        cfg = {"gpu": [0, 1], "args": ["--native", "/nowhere/x-00001.gguf", "--max-context", "131072"]}
286        self.runner(cards(2))
287        self.assertTrue(drafting_cmd._split_expected(cfg, cfg["args"]))
288        self.assertFalse(drafting_cmd._split_expected({**cfg, "split_engine": "off"}, cfg["args"]))
289        self.assertFalse(drafting_cmd._split_expected({**cfg, "drafting": "dflash2"}, cfg["args"]))
290
291
292class SummaryTellsWhatRuns(Base):
293    """The server falls back to the normal layer split when the split engine exits at start (serve/server.py start_engine_or_fallback; metrics engine.split_fallback).
294    The launcher's summary used to keep the line written before the start, "Using the all-cards split engine on 2 cards"."""
295
296    def runner(self, log_name="e.log"):
297        cfgfile = Path(self.home.base) / "cfg.json"
298        log = Path(self.home.base) / log_name
299        cfgfile.write_text(json.dumps({"log": str(log), "args": []}), encoding="utf-8")
300        r = Runner(S.LaunchSettings(family="qwen", model="UD-Q4_K_XL", context=131072, tune="skip", port=18999), catalog=catalog(self.hw))
301        r.config_path = cfgfile
302        r.notices.append("Using the all-cards split engine on 2 cards. Turn it off with: strata launch --split-engine off.")
303        return r, log
304
305    def metrics(self, engine):
306        resp = mock.MagicMock()
307        resp.read.return_value = json.dumps({"engine": engine}).encode()
308        resp.__enter__.return_value = resp
309        return mock.patch("urllib.request.urlopen", lambda *a, **k: resp)
310
311    def test_a_fallback_replaces_the_line_and_gives_the_engines_reason(self):
312        r, log = self.runner()
313        Path(str(log) + ".split-engine").write_text("[strata] engine started: x\nsfnx: --native and --mtp are required\n", encoding="utf-8")
314        with self.metrics({"split_fallback": True}), contextlib.redirect_stdout(io.StringIO()):
315            r.report_drafting()
316        self.assertEqual(r.notices, ["The all-cards split engine could not start (sfnx: --native and --mtp are required); running the normal layer split."])
317
318    def test_a_fallback_without_a_reason_in_the_log_still_says_it(self):
319        r, _log = self.runner()
320        with self.metrics({"split_fallback": True}), contextlib.redirect_stdout(io.StringIO()):
321            r.report_drafting()
322        self.assertEqual(r.notices, ["The all-cards split engine could not start; running the normal layer split."])
323
324    def test_when_the_split_runs_the_line_stays(self):
325        r, _log = self.runner()
326        with self.metrics({}), contextlib.redirect_stdout(io.StringIO()):
327            r.report_drafting()
328        self.assertEqual(len(r.notices), 1)
329        self.assertTrue(r.notices[0].startswith("Using the all-cards split engine"))
330
331
332class PlanTellsTheApp(Base):
333    """`strata drafting plan` is what the app reads (native-control.mjs): with the split taking the start it says choice mtp and split true."""
334
335    def plan(self, probe, *extra):
336        from tests.terminal.launch_support import run_cli
337        data = Path(self.home.base) / "d"
338        data.mkdir(exist_ok=True)
339        with mock.patch.object(SE, "probe_cards", lambda idx=None: probe), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)),                 mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"])):
340            code, out, err = run_cli(["drafting", "plan", "--family", "qwen", "--data-dir", str(data), "--output", "json", *extra])
341        self.assertEqual(code, 0, err)
342        return json.loads(out)
343
344    def test_two_cards_on_auto_say_split_and_the_mtp(self):
345        p = self.plan(cards(2), "--mode", "auto")
346        self.assertEqual((p["split"], p["choice"], p["needed"]), (True, "mtp", False))
347
348    def test_one_card_or_a_chosen_dflash2_do_not(self):
349        for probe, mode in ((cards(1), "auto"), (cards(2), "dflash2")):
350            p = self.plan(probe, "--mode", mode)
351            self.assertFalse(p["split"], (len(probe), mode))
352            self.assertEqual(p["choice"], "dflash2")
353
354
355@contextlib.contextmanager
356def tempdir():
357    with tempfile.TemporaryDirectory() as tmp:
358        yield tmp
359
360
361def app_cfg(tmp: str, **more) -> dict:
362    """The run config the app hands to Control at a Load (native-control.mjs buildConfig): the installed model's layer-split config with the app's own keys
363    (host, port, api_key, the card list, parallel 4 where nobody chose a number) and the draft layer on disk."""
364    root = Path(tmp)
365    (root / "data").mkdir(exist_ok=True)
366    (root / "data" / "draft_vocab_en.bin").write_bytes(b"x")
367    mtp = root / "mtp" / "rt"
368    mtp.mkdir(parents=True, exist_ok=True)
369    (mtp / "dense.bin").write_bytes(b"x")
370    cfg = {"exe": "/e/strata", "args": ["--pack", "/m/packs/x", "--native", "/m/x-00001.gguf", "--spec", "4", "--mtp", str(mtp), "--max-context", "131072",
371                                        "--kv", "int8", "--vram-reserve-mib", "1536"],
372           "cwd": tmp, "tokenizer": "/m/tokenizer", "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "host": "127.0.0.1", "port": 18500, "api_key": "k", "gpu": [0, 1], "layer_split": "auto",
373           "open_browser": False, "parallel": 4, "fit_max_tokens": True, "env": {}}
374    cfg.update(more)
375    return cfg
376
377
378def set_arg(cfg: dict, flag: str, value: str) -> None:
379    cfg["args"][cfg["args"].index(flag) + 1] = value
380
381
382def flag_of(cfg: dict, flag: str) -> str:
383    return cfg["args"][cfg["args"].index(flag) + 1]
384
385
386class AppPlanEqualsTerminalPlan(Base):
387    """0.2.10.1: the app asks `strata drafting plan` / `fetch` WITHOUT --no-split, so its plan is the Terminal's: where the split rule says yes, Auto is the split with the MTP draft
388    layer (fetched through the app's existing MTP step), and a person's DFlash2 or Off keeps the layer split."""
389
390    def plan(self, probe, *extra, config=None):
391        from tests.terminal.launch_support import run_cli
392        data = Path(self.home.base) / "d"
393        data.mkdir(exist_ok=True)
394        argv = ["drafting", "plan", "--data-dir", str(data), "--output", "json", *extra]
395        if config is not None:
396            path = Path(self.home.base) / "cfg-plan.json"
397            path.write_text(json.dumps(config), encoding="utf-8")
398            argv += ["--config", str(path)]
399        else:
400            argv += ["--family", "qwen"]
401        with mock.patch.object(SE, "probe_cards", lambda idx=None: probe), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)), \
402                mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"])):
403            code, out, err = run_cli(argv)
404        self.assertEqual(code, 0, err)
405        return json.loads(out)
406
407    def terminal(self, probe, **kw):
408        """What the Terminal's launch decides for the same machine and choice: the drafter, the split word and the parts of its download plan."""
409        s = S.LaunchSettings(**{"family": "qwen", "model": "UD-Q4_K_XL", "context": 131072, "tune": "skip", "vision": "off", **kw})
410        r = Runner(s, catalog=catalog(self.hw))
411        with mock.patch.object(SE, "probe_cards", lambda idx=None: probe), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)), \
412                mock.patch("strata_control.drafting.detect_hardware", lambda: ("cuda", ["sm_120"])):
413            return r.resolved_drafting("qwen"), r.split_expected(), [p["kind"] for p in r.download_plan()["parts"]]
414
415    def test_the_apps_plan_on_two_cards_is_the_terminals_split_and_the_mtp(self):
416        p = self.plan(cards(2), "--mode", "auto")
417        drafter, split, kinds = self.terminal(cards(2), gpus=[0, 1])
418        self.assertEqual((p["split"], p["choice"], p["needed"]), (True, "mtp", False))
419        self.assertEqual((drafter, split), ("mtp", True))
420        self.assertIn("mtp", kinds)
421        self.assertNotIn("dflash2", kinds)
422
423    def test_without_the_mtp_layer_the_plan_asks_for_it(self):
424        """The draft layer is not on disk (a DFlash2 install leaves it out): mtp_needed with its size, and nothing for DFlash2."""
425        from strata_control.discovery import MTP_FETCH_GB
426        with tempdir() as tmp:
427            cfg = app_cfg(tmp)
428            set_arg(cfg, "--mtp", str(Path(tmp) / "nowhere" / "rt"))
429            p = self.plan(cards(2), "--mode", "auto", config=cfg)
430        self.assertEqual((p["split"], p["choice"], p["needed"], p["mtp_needed"], p["mtp_gb"]), (True, "mtp", False, True, MTP_FETCH_GB))
431        self.assertIn("all-cards split engine", p["line"])
432        self.assertIn(f"{MTP_FETCH_GB:g} GB", p["line"])
433
434    def test_the_plan_line_is_the_terminals_line(self):
435        from strata_control.discovery import MTP_FETCH_GB
436        self.assertEqual(SE.split_plan_line(MTP_FETCH_GB), f"Drafting: MTP (the all-cards split engine uses the MTP draft layer, {MTP_FETCH_GB:g} GB)")
437        self.assertEqual(SE.split_plan_line(), "Drafting: MTP (the all-cards split engine uses the MTP draft layer)")
438
439    def test_a_persons_dflash2_or_off_or_one_card_is_the_same_in_the_app_and_the_terminal(self):
440        for name, probe, mode, config, kw in (("their DFlash2", cards(2), "dflash2", None, {"gpus": [0, 1], "drafting": "dflash2"}),
441                                              ("split-engine off", cards(2), "auto", {"split_engine": "off", "model_name": "qwen3.8-flash-next-unsloth-ud-q4_k_xl", "args": []}, {"gpus": [0, 1], "split_engine": "off"}),
442                                              ("one card", cards(1), "auto", None, {"gpus": [0]})):
443            with self.subTest(name):
444                p = self.plan(probe, "--mode", mode, config=config)
445                drafter, split, kinds = self.terminal(probe, **kw)
446                self.assertFalse(p["split"])
447                self.assertEqual(p["choice"], "dflash2")
448                self.assertEqual((drafter, split), ("dflash2", False))
449                self.assertNotIn("mtp", kinds)
450
451    def test_a_saved_dflash2_is_overridden_by_the_auto_the_screen_carries(self):
452        """The Models screen's Load with Auto on a model whose settings file still says dflash2: the choice in hand is Auto, so the rule is asked with Auto."""
453        with tempdir() as tmp:
454            cfg = app_cfg(tmp, drafting="dflash2")
455            p_auto = self.plan(cards(2), "--mode", "auto", config=cfg)
456            p_saved = self.plan(cards(2), config=cfg)
457        self.assertTrue(p_auto["split"])
458        self.assertFalse(p_saved["split"])
459        self.assertEqual(p_saved["choice"], "dflash2")
460
461    def test_an_explicit_mtp_is_the_split_too_as_in_the_terminal(self):
462        p = self.plan(cards(2), "--mode", "mtp")
463        _, split, _ = self.terminal(cards(2), gpus=[0, 1], drafting="mtp")
464        self.assertEqual((p["split"], p["choice"]), (True, "mtp"))
465        self.assertTrue(split)
466
467    def test_four_r9700_in_the_app_are_the_split_and_the_mtp_too(self):
468        p = self.plan(cards(4, vendor="amd", arch="gfx1201"), "--mode", "auto")
469        self.assertEqual((p["split"], p["choice"]), (True, "mtp"))
470        p2 = self.plan(cards(2, vendor="amd", arch="gfx1201"), "--mode", "auto")
471        self.assertEqual((p2["split"], p2["choice"]), (False, "dflash2"))
472
473    def test_a_conversation_memory_other_than_int8_is_not_the_split_in_the_plan_either(self):
474        with tempdir() as tmp:
475            cfg = app_cfg(tmp)
476            set_arg(cfg, "--kv", "q4_0")
477            p = self.plan(cards(2), "--mode", "auto", config=cfg)
478        self.assertFalse(p["split"])
479        self.assertEqual(p["choice"], "dflash2")
480
481    def test_no_split_stays_for_a_person_and_for_the_failed_layer_fetch(self):
482        from tests.terminal.launch_support import run_cli
483        p = self.plan(cards(2), "--mode", "auto", "--no-split")
484        self.assertEqual((p["split"], p["choice"], p["mtp_needed"]), (False, "dflash2", False))
485        self.assertTrue(p["needed"], "DFlash2's drafter is what the plan fetches then")
486        for sub in ("plan", "fetch"):
487            code, out, _ = run_cli(["drafting", sub, "--help"])
488            self.assertIn("--no-split", out)
489
490    def test_the_hosts_calls_only_carry_no_split_when_it_is_told_to(self):
491        """The app (apps/host/server/control-runtime.mjs) adds --no-split only after the split's draft layer could not be downloaded."""
492        text = (Path(__file__).resolve().parents[2] / "apps/host/server/control-runtime.mjs").read_text(encoding="utf-8")
493        self.assertNotIn("'--no-split', '--output', 'json'", text)
494        self.assertNotIn("'--no-split', '--if-needed'", text)
495        self.assertEqual(text.count("...(noSplit ? ['--no-split'] : [])"), 2)
496
497
498class AppStartsTheSplit(Base):
499    """The app's engine start (apps/host: buildConfig, then `profile` + `runtime start`) never went through the Terminal's apply_split_engine; Control now answers it
500    (`strata split-engine apply`, strata_control/split_engine.apply_run_config) from the same rule, engine package and draft layer."""
501
502    @staticmethod
503    def model():
504        return SE.ModelFacts(routed_types={"Q4_K": 97, "Q5_K": 2, "Q5_1": 43, "Q8_0": 5}, routed_bytes=int(71.7 * (1 << 30)), embd_type="Q8_0", shexp_types={"Q8_0": 144},
505                             embd_ram_bytes=int(27.5 * (1 << 30)), layers=48, experts=512)
506
507    def apply(self, cfg, *, probe=None, avail=400.0, exe="/e/strata-split-2-sm120", system="linux"):
508        probe = probe or cards(2)
509        return SE.apply_run_config(cfg, exe_for_cards=lambda n, cc=None, arch=None: exe, system=system, probe=lambda idx: probe, ram=lambda: (500.0, avail),
510                                   scan=lambda path: self.model())
511
512    def test_the_apps_default_of_four_slots_is_the_splits_four_lanes(self):
513        with tempdir() as tmp:
514            cfg = app_cfg(tmp)
515            d, line, warn = self.apply(cfg)
516            self.assertTrue(d.use_split, d.reasons)
517            self.assertEqual(flag_of(cfg, "--batch"), "4")
518            self.assertEqual(cfg["exe"], "/e/strata-split-2-sm120")
519            self.assertEqual(cfg["drafting"], "mtp")
520            self.assertIn("all-cards split engine on 2 cards", line)
521            self.assertFalse(warn)
522            # the app's own keys ride along, and the normal layer split is kept whole for the server's fallback
523            for key in ("host", "port", "api_key", "tokenizer", "model_name", "fit_max_tokens", "parallel"):
524                self.assertIn(key, cfg, key)
525            self.assertEqual(cfg["split_fallback"]["exe"], "/e/strata")
526            self.assertIn("--vram-reserve-mib", cfg["split_fallback"]["args"])
527            self.assertNotIn("--vram-reserve-mib", cfg["args"], "the layer split's own flags are not given to the split engine")
528
529    def test_a_number_the_person_chose_is_the_lanes_and_never_more_than_eight(self):
530        for chosen, want in ((1, "1"), (3, "3"), (8, "8"), (12, "8")):
531            with self.subTest(chosen), tempdir() as tmp:
532                cfg = app_cfg(tmp, parallel=chosen)
533                d, _, _ = self.apply(cfg)
534                self.assertTrue(d.use_split)
535                self.assertEqual(flag_of(cfg, "--batch"), want)
536
537    def test_no_number_at_all_gives_the_splits_own_default_lanes(self):
538        with tempdir() as tmp:
539            cfg = app_cfg(tmp)
540            del cfg["parallel"]
541            self.apply(cfg)
542            self.assertEqual(flag_of(cfg, "--batch"), "6")
543
544    def test_vision_is_passed_when_the_app_reads_pictures(self):
545        with tempdir() as tmp:
546            cfg = app_cfg(tmp, vision={"exe": "/e/strata-vision", "mmproj": "/m/mm.gguf"})
547            self.apply(cfg)
548            self.assertIn("--vision", cfg["args"])
549        with tempdir() as tmp:
550            cfg = app_cfg(tmp)
551            self.apply(cfg)
552            self.assertNotIn("--vision", cfg["args"])
553
554    def test_every_no_leaves_the_apps_run_config_alone_and_auto_says_nothing(self):
555        cases = {"a person's DFlash2": ({"drafting": "dflash2"}, {}), "drafting off": ({"drafting": "off"}, {}), "the switch off": ({"split_engine": "off"}, {}),
556                 "engine arguments of their own": ({"user_args": ["--x", "1"]}, {}), "one card": ({"gpu": 0}, {"probe": cards(1)}),
557                 "two other cards": ({}, {"probe": cards(2, cc=89)}), "too little RAM": ({}, {"avail": 10.0}), "no split engine in the package": ({}, {"exe": None}),
558                 "Windows": ({}, {"system": "windows"})}
559        for name, (more, kw) in cases.items():
560            with self.subTest(name), tempdir() as tmp:
561                cfg = app_cfg(tmp, **more)
562                before = copy.deepcopy(cfg)
563                d, line, _ = self.apply(cfg, **kw)
564                self.assertFalse(d.use_split, name)
565                self.assertEqual(cfg, before, name)
566                self.assertEqual(line, "", f"{name}: Auto says nothing")
567        with tempdir() as tmp:                                # a conversation memory other than int8 is refused by the rule itself
568            cfg = app_cfg(tmp)
569            set_arg(cfg, "--kv", "q4_0")
570            before = copy.deepcopy(cfg)
571            d, line, _ = self.apply(cfg)
572            self.assertFalse(d.use_split)
573            self.assertEqual((cfg, line), (before, ""))
574
575    def test_a_missing_draft_layer_is_a_quiet_layer_split_and_on_says_how_to_get_it(self):
576        with tempdir() as tmp:
577            cfg = app_cfg(tmp)
578            set_arg(cfg, "--mtp", str(Path(tmp) / "nowhere" / "rt"))
579            d, line, _ = self.apply(cfg)
580            self.assertFalse(d.use_split)
581            self.assertEqual(line, "")
582            self.assertNotIn("split_fallback", cfg)
583            cfg2 = app_cfg(tmp, split_engine="on")
584            set_arg(cfg2, "--mtp", str(Path(tmp) / "nowhere" / "rt"))
585            d2, line2, warn2 = self.apply(cfg2)
586            self.assertFalse(d2.use_split)
587            self.assertIn("draft layer", line2)
588            self.assertTrue(warn2)
589
590    def test_the_command_writes_the_split_config_only_on_a_yes_and_never_touches_the_input(self):
591        from tests.terminal.launch_support import run_cli
592        with tempdir() as tmp:
593            src = Path(tmp) / "layer.json"
594            out = Path(tmp) / "split.json"
595            cfg = app_cfg(tmp)
596            src.write_text(json.dumps(cfg), encoding="utf-8")
597            before = src.read_text(encoding="utf-8")
598            with mock.patch.object(SE, "probe_cards", lambda idx=None: cards(2)), mock.patch.object(SE, "ram_gib", lambda: (500.0, 400.0)), \
599                    mock.patch.object(SE, "scan_model", lambda path: self.model()), \
600                    mock.patch.object(SE, "exe_finder", lambda c: (lambda n, cc=None, arch=None: "/e/strata-split-2-sm120")), \
601                    mock.patch("sys.platform", "linux"):
602                code, text, err = run_cli(["split-engine", "apply", "--config", str(src), "--out", str(out), "--output", "json"])
603                self.assertEqual(code, 0, err)
604                got = json.loads(text)
605                self.assertTrue(got["ok"] and got["split"], got)
606                self.assertEqual(got["cards"], 2)
607                written = json.loads(out.read_text(encoding="utf-8"))
608                self.assertEqual(flag_of(written, "--batch"), "4")
609                self.assertEqual(src.read_text(encoding="utf-8"), before)
610                out.unlink()
611                src.write_text(json.dumps({**cfg, "drafting": "dflash2"}), encoding="utf-8")
612                code, text, err = run_cli(["split-engine", "apply", "--config", str(src), "--out", str(out), "--output", "json"])
613                got = json.loads(text)
614                self.assertEqual((code, got["split"], got["written"]), (0, False, None))
615                self.assertFalse(out.exists())
616                src.write_text("not json", encoding="utf-8")
617                code, text, _ = run_cli(["split-engine", "apply", "--config", str(src), "--out", str(out), "--output", "json"])
618                self.assertNotEqual(code, 0)
619                self.assertFalse(json.loads(text)["ok"])
620
621    def test_the_fallback_layer_split_keeps_the_apps_slots_and_its_own_drafting_choice(self):
622        """If the split engine will not come up, the server starts the layer split from split_fallback (serve/server.py start_engine_or_fallback) with the app's parallel."""
623        from serve.server import SPLIT_KEYS
624        with tempdir() as tmp:
625            cfg = app_cfg(tmp)
626            self.apply(cfg)
627            cfg2 = {k: v for k, v in cfg.items() if k not in SPLIT_KEYS + ("exe", "args", "env", "layer_split", "replicas", "user_args", "drafting")}
628            cfg2.update(cfg["split_fallback"])
629            self.assertEqual(cfg2["parallel"], 4)
630            self.assertEqual(cfg2["exe"], "/e/strata")
631            self.assertNotIn("drafting", cfg2)
632
633
634class LaneClamp(Base):
635    """The engine runs 1..8 lanes ("sfnx: --batch must be 1..8"): the AMD four-card default PARALLEL 32, a layer config's own --batch and an app profile's parallel
636    are cut to 8 in the split's run config and in the server's --batch."""
637
638    def split_args(self, lanes):
639        d = SE.Decision(True, [], 2)
640        cfg = SE.split_config({"tokenizer": "/t", "port": 1}, d, exe="/e/strata-split-2-sm86", native="/m/x-00001.gguf", mtp_dir="/m/mtp/rt", draft_vocab="/e/v.bin",
641                              context=131072, lanes=lanes)
642        return cfg["args"]
643
644    def test_split_config_cuts_the_lanes_to_1_through_8(self):
645        for lanes, want in ((32, "8"), (9, "8"), (8, "8"), (5, "5"), (1, "1"), (0, "1")):
646            a = self.split_args(lanes)
647            self.assertEqual(a[a.index("--batch") + 1], want, lanes)
648
649    def stubbed(self, cfg, probe, mode_="on", exe="/e/strata-split-2-sm86"):
650        data = Path(self.home.base) / "vocab"
651        data.mkdir(exist_ok=True)
652        (data / "draft_vocab_en.bin").write_bytes(b"v")
653        return SE.apply_to_config(cfg, exe_for_cards=lambda n, cc=None, arch=None: exe, system="linux", probe=lambda i: probe, ram=lambda: (500.0, 400.0),
654                                  scan=lambda p: SE.ASSUMED_MODEL, data_dir=str(data), mode_=mode_)
655
656    def test_iq3_s_on_two_cards_with_a_layer_config_batch_32_starts_with_8(self):
657        native = Path(self.home.base) / "x-00001.gguf"
658        native.write_bytes(b"g")
659        cfg = {"gpu": [0, 1], "split_engine": "on", "args": ["--pack", "/p", "--native", str(native), "--mtp", "/m/mtp/rt", "--max-context", "131072", "--batch", "32"]}
660        d = self.stubbed(cfg, cards(2, cc=86))
661        self.assertTrue(d.use_split, d.reasons)
662        self.assertEqual(cfg["args"][cfg["args"].index("--batch") + 1], "8")
663
664    def test_the_amd_four_card_default_parallel_32_starts_with_8(self):
665        native = Path(self.home.base) / "x-00001.gguf"
666        native.write_bytes(b"g")
667        cfg = {"gpu": [0, 1, 2, 3], "parallel": 32, "args": ["--pack", "/p", "--native", str(native), "--mtp", "/m/mtp/rt", "--max-context", "131072"]}
668        d = self.stubbed(cfg, cards(4, vendor="amd", arch="gfx1201"), mode_="auto", exe="/e/strata-split-4-amd")
669        self.assertTrue(d.use_split, d.reasons)
670        self.assertEqual(cfg["args"][cfg["args"].index("--batch") + 1], "8")
671
672    def test_a_profile_parallel_of_16_gives_the_servers_batch_8(self):
673        from serve.server import parallel_args
674        for n, want in ((16, "8"), (32, "8"), (3, "3"), (8, "8")):
675            args = list(SPLIT_ARGS)
676            parallel_args(split_cfg(parallel=n), args)
677            self.assertEqual(args[args.index("--batch") + 1], want, n)
678
679
680class AppPath(Base):
681    """The app's Settings 'Concurrent requests = N' is a profile override on the saved run config (strata_control/profiles); `strata serve --profile` reads it."""
682
683    def engine_argv(self, cfg: dict, overrides: dict) -> list[str]:
684        from serve.server import engine_args
685        values, _o = cli._effective(cfg, {"overrides": overrides}, None)
686        eff = {**cfg, "args": list(cfg["args"])}
687        if values["parallel"] is not None:
688            eff["parallel"] = values["parallel"]
689        with contextlib.redirect_stdout(io.StringIO()):
690            return engine_args(eff)
691
692    def test_concurrent_requests_on_a_split_config_sets_its_lanes(self):
693        argv = self.engine_argv(split_cfg(lanes=6), {"host": "127.0.0.1", "port": 8080, "parallel": 3})
694        self.assertEqual(argv.count("--batch"), 1)
695        self.assertEqual(argv[argv.index("--batch") + 1], "3")
696
697    def test_no_override_keeps_the_lanes_the_launcher_wrote(self):
698        argv = self.engine_argv(split_cfg(lanes=5), {"host": "127.0.0.1", "port": 8080})
699        self.assertEqual(argv[argv.index("--batch") + 1], "5")
700
701    def test_the_servers_parallel_flag_is_accepted_for_the_split_and_still_refused_beside_another_batch(self):
702        """`strata serve --profile` hands the profile's parallel to the server as --parallel N; the server refused it next to any --batch in the saved args."""
703        from serve.server import parallel_flag_conflicts
704        self.assertFalse(parallel_flag_conflicts(split_cfg()))
705        self.assertFalse(parallel_flag_conflicts(layer_cfg()))
706        self.assertTrue(parallel_flag_conflicts(layer_cfg(args=LAYER_ARGS + ["--batch", "6"])))
707        self.assertTrue(parallel_flag_conflicts(layer_cfg(args=LAYER_ARGS + ["--slots", "6"])))
708
709    def test_the_layer_split_still_takes_its_batch_from_parallel(self):
710        argv = self.engine_argv(layer_cfg(), {"host": "127.0.0.1", "port": 8080, "parallel": 3})
711        self.assertEqual(argv[argv.index("--batch") + 1], "3")
712
713
714if __name__ == "__main__":
715    unittest.main()