okami.mom/strata

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

Niko1221rc1 merge split switch (15fb6ffe3): strata_cli/launch/cmd.py conflicted at --drafting help text; df2-primary's help kept, SFNX's --split-engine argument keptabd9b4581

main
6.8 KiB140 linesraw
1"""serve/server.py start_engine_or_fallback: a config for the all-cards split engine starts the normal layer split, with one plain line,
2when the split engine refuses or fails to come up; any other config starts exactly as before and its failures stay failures."""
3from __future__ import annotations
4
5import contextlib
6import io
7import os
8import sys
9import unittest
10from pathlib import Path
11from unittest import mock
12
13sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14import serve.server as S  # noqa: E402
15
16
17NORMAL = os.path.abspath("/e/strata")
18
19
20class FakeEngine:
21    started = []
22    fail_exes = set()
23
24    def __init__(self, exe, args, cwd=None, log=None, env=None, lazy=False, **kw):
25        FakeEngine.started.append((exe, list(args), cwd, dict(env or {})))
26        if exe in FakeEngine.fail_exes:
27            raise S.EngineDied("the engine exited before it was ready: card 0 is compute capability 8.9 and this build is for sm_86")
28        self.info = {}
29
30
31def split_cfg():
32    return {"exe": "/e/strata-split-2", "args": ["--native", "/m/a.gguf", "--batch", "6"], "cwd": "/x", "tokenizer": "/t", "port": 8080,
33            "env": {"FNX_ARENA": "0", "FNX_EXPERT_RAM_GIB": "off"},
34            "split_fallback": {"exe": NORMAL, "args": ["--pack", "/p", "--native", "/m/a.gguf", "--layer-split", "auto"],
35                               "env": {"STRATA_X": "1"}, "layer_split": "auto"}}
36
37
38class Fallback(unittest.TestCase):
39    def setUp(self):
40        FakeEngine.started, FakeEngine.fail_exes = [], set()
41        self.p = [mock.patch.object(S, "StrataEngine", FakeEngine), mock.patch.object(S, "effort_end_args", lambda cfg, exe, tok: None),
42                  mock.patch.object(S, "configure_batch_telemetry_env", lambda env, cfg, override: None)]
43        for p in self.p:
44            p.start()
45
46    def tearDown(self):
47        for p in self.p:
48            p.stop()
49
50    def run_start(self, cfg):
51        out = io.StringIO()
52        with contextlib.redirect_stdout(out):
53            engine = S.start_engine_or_fallback(cfg, cfg["exe"], [], {"A": "1"}, False, None)
54        return engine, out.getvalue()
55
56    def test_a_split_engine_that_starts_is_used(self):
57        engine, out = self.run_start(split_cfg())
58        self.assertEqual(len(FakeEngine.started), 1)
59        self.assertEqual(FakeEngine.started[0][0], "/e/strata-split-2")
60        self.assertNotIn("split_fallback", engine.info)
61        self.assertEqual(out, "")
62
63    def test_a_split_engine_that_fails_is_replaced_by_the_normal_layer_split_with_one_line(self):
64        FakeEngine.fail_exes = {"/e/strata-split-2"}
65        engine, out = self.run_start(split_cfg())
66        self.assertEqual([s[0] for s in FakeEngine.started], ["/e/strata-split-2", NORMAL])
67        exe, args, cwd, env = FakeEngine.started[1]
68        self.assertIn("--layer-split", args)
69        self.assertNotIn("--batch", args)
70        self.assertEqual(env.get("STRATA_X"), "1")
71        self.assertNotIn("FNX_ARENA", env)
72        self.assertTrue(engine.info.get("split_fallback"))
73        lines = [ln for ln in out.splitlines() if ln.strip()]
74        self.assertEqual(len(lines), 1)
75        self.assertIn("all-cards split engine could not start", lines[0])
76        self.assertIn("normal layer split", lines[0])
77
78    def test_the_engines_own_reason_is_in_the_line_and_its_log_is_kept(self):
79        import tempfile
80        log = os.path.join(tempfile.mkdtemp(), "engine.log")
81        Path(log).write_text("sfnx: failed: the all-cards split engine does not read this model's routed experts (blk.0.ffn_gate_exps.weight is ggml type 14); use the normal layer split\n")
82        cfg = split_cfg()
83        cfg["log"] = log
84
85        class Refusing(FakeEngine):
86            def __init__(self, exe, args, cwd=None, log=None, env=None, lazy=False, **kw):
87                FakeEngine.started.append((exe, list(args), cwd, dict(env or {})))
88                if exe == "/e/strata-split-2":
89                    raise S.EngineDied("the engine exited before it was ready (see x)\n" + Path(log).read_text())
90                self.info = {}
91        with mock.patch.object(S, "StrataEngine", Refusing):
92            engine, out = self.run_start(cfg)
93        lines = [ln for ln in out.splitlines() if ln.strip()]
94        self.assertEqual(len(lines), 1)
95        self.assertIn("does not read this model's routed experts", lines[0])
96        self.assertNotIn("exited before it was ready", lines[0])
97        self.assertTrue(os.path.exists(log + ".split-engine"))          # the normal engine will overwrite the log; the refusal stays readable
98        self.assertEqual([s[0] for s in FakeEngine.started], ["/e/strata-split-2", NORMAL])
99
100    def test_a_split_config_keeps_its_arguments_through_the_drafter_step(self):
101        """strata_control/split_engine.split_config writes "drafting": "mtp" (what the split engine runs), so the drafter step, which resolves Auto to
102        DFlash2 where the engine has it, adds no DFlash2 flag to the split engine's arguments (it would refuse them and every start would fall back)."""
103        from strata_control import split_engine as SE
104
105        base = {"exe": NORMAL, "args": ["--pack", "/p", "--native", "/m/a.gguf", "--mtp", "/d/mtp/rt", "--layer-split", "auto"], "cwd": "/x",
106                "tokenizer": "/t", "port": 8080}
107        decision = SE.Decision(True, [], 2)
108        cfg = SE.split_config(base, decision, exe="/e/strata-split-2", native="/m/a.gguf", mtp_dir="/d/mtp/rt", draft_vocab="/d/v.bin", context=131072)
109        args = S.engine_args(cfg)
110        self.assertEqual(args[:2], ["--native", "/m/a.gguf"])
111        self.assertNotIn("--draft", args)
112        self.assertNotIn("--draft-model", args)
113        self.assertEqual(args[args.index("--mtp") + 1], "/d/mtp/rt")
114        self.assertEqual(args[args.index("--spec") + 1], "6")
115        self.assertNotIn("--layer-split", args)
116        # the layer split that starts instead keeps the person's drafting word, or none (Auto)
117        self.assertNotIn("drafting", cfg["split_fallback"])
118        cfg = SE.split_config({**base, "drafting": "auto"}, decision, exe="/e/strata-split-2", native="/m/a.gguf", mtp_dir="/d/mtp/rt",
119                              draft_vocab="/d/v.bin", context=131072)
120        self.assertEqual(cfg["split_fallback"]["drafting"], "auto")
121        self.assertEqual(cfg["drafting"], "mtp")
122
123    def test_without_a_fallback_the_failure_stays_a_failure(self):
124        cfg = split_cfg()
125        del cfg["split_fallback"]
126        FakeEngine.fail_exes = {"/e/strata-split-2"}
127        with self.assertRaises(S.EngineDied):
128            self.run_start(cfg)
129        self.assertEqual(len(FakeEngine.started), 1)
130
131    def test_a_normal_config_is_untouched(self):
132        cfg = {"exe": "/e/strata", "args": ["--pack", "/p"], "cwd": "/x", "tokenizer": "/t"}
133        FakeEngine.fail_exes = {"/e/strata"}
134        with self.assertRaises(S.EngineDied):
135            self.run_start(cfg)
136        self.assertEqual(len(FakeEngine.started), 1)
137
138
139if __name__ == "__main__":
140    unittest.main()