okami.mom/strata

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

Niko1221Merge branch 'f-021-iA' into f-021-int34e7c5cb1

main
16.1 KiB289 linesraw
1"""Tests for what setup keeps in a model's run config when it runs again (#629), the browser choice (#609) and the
2image-token flag (#625).  Every outside effect is mocked (tools/test_setup_golden.py's install()).
3
4    python -m unittest tools.test_setup_config
5"""
6from __future__ import annotations
7
8import contextlib
9import io
10import json
11import sys
12import tempfile
13import unittest
14import unittest.mock
15from pathlib import Path
16
17ROOT = Path(__file__).resolve().parents[1]
18sys.path.insert(0, str(ROOT))
19sys.path.insert(0, str(ROOT / "tools"))
20import setup  # noqa: E402
21from test_setup_golden import PROFILES, install  # noqa: E402
22
23
24def quiet(fn, *args, **kw):
25    out = io.StringIO()
26    with contextlib.redirect_stdout(out):
27        return fn(*args, **kw), out.getvalue()
28
29
30USER = {"sampling": {"temperature": 1.0, "top_p": 0.95, "top_k": 20, "min_p": 0.0},
31        "mcp_servers": {"files": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]}},
32        "mcp": {"timeout_s": 60, "max_result_chars": 16000, "max_rounds": 8},
33        "cors_origins": ["http://localhost:3000"], "reasoning_effort": "low"}
34
35
36class CarryOver(unittest.TestCase):
37    """#629: setup run again (a different --context) keeps the keys it does not write and keeps the old file as .bak."""
38
39    def setUp(self):
40        self.ram, self.found = PROFILES["64GB-1x32GB"]
41
42    def run_setup(self, *extra, configs=()):
43        return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra],
44                       configs=configs)
45
46    def test_user_keys_survive_a_rerun(self):
47        code, out, first, _ = self.run_setup("--context", "65536")
48        self.assertEqual(code, 0, out)
49        old = {**first, **USER, "args": first["args"] + ["--hand-option", "7"]}
50        code, out, cfg, _ = self.run_setup("--context", "131072", configs=[("strata-q2_0.json", old)])
51        self.assertEqual(code, 0, out)
52        for k, v in USER.items():
53            self.assertEqual(cfg[k], v, k)
54        a = cfg["args"]
55        self.assertEqual(a[a.index("--max-context") + 1], "131072")       # the new choice is used
56        self.assertEqual(a[a.index("--hand-option") + 1], "7")             # an option added by hand is kept (#3216)...
57        self.assertEqual(cfg["user_args"], ["--hand-option", "7"])         # ...and recorded as the person's
58        self.assertIn("kept from your earlier strata-q2_0.json: sampling, mcp_servers, mcp, cors_origins, "
59                      "reasoning_effort", out)
60        self.assertIn("kept as strata-q2_0.json.bak", out)
61        self.assertIn("args --hand-option", out)                           # ...and the run says it was kept
62
63    def test_a_first_install_is_unchanged(self):
64        code, out, cfg, _ = self.run_setup()
65        self.assertEqual(code, 0, out)
66        self.assertNotIn("kept from", out)
67        self.assertNotIn(".bak", out)
68        self.assertFalse(set(cfg) - setup.SETUP_KEYS)                     # setup writes only its own keys
69
70    def test_setup_keys_are_rewritten(self):
71        code, out, first, _ = self.run_setup()
72        old = {**first, "model_name": "renamed", "port": 9999, "draft_vocab": "en", "host": "0.0.0.0"}
73        code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", old)])
74        self.assertEqual(code, 0, out)
75        self.assertEqual(cfg["model_name"], first["model_name"])
76        self.assertEqual(cfg["port"], first["port"])
77        self.assertNotIn("host", cfg)                                     # as before: --host is given to setup
78        self.assertEqual(cfg["draft_vocab"], "en")                        # kept by its own rule (saved_draft_vocab)
79        self.assertNotIn("kept from", out)
80
81    def test_write_setup_config(self):
82        with tempfile.TemporaryDirectory() as d:
83            p = Path(d) / "strata-x.json"
84            mm = Path(d) / "mmproj-Q8_0.gguf"
85            mm.write_bytes(b"")
86            old = {"exe": "e", "args": ["--kv", "int8", "--threads", "8"], "sampling": {"temperature": 0.7},
87                   "env": {"STRATA_RESIDENT_PIN": "0", "MY_VAR": "1"},
88                   "vision": {"exe": "v", "mmproj": str(mm), "gpu": False, "max_tokens": 300, "min_tokens": 64}}
89            p.write_text(json.dumps(old), encoding="utf-8")
90            new = {"exe": "e2", "args": ["--kv", "int8"],
91                   "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False, "max_tokens": 300}}
92            _, out = quiet(setup.write_setup_config, p, new)
93            got = json.loads(p.read_text(encoding="utf-8"))
94            self.assertEqual(got["sampling"], {"temperature": 0.7})
95            self.assertEqual(got["env"], {"MY_VAR": "1"})                 # setup's own env entry is setup's to write
96            self.assertEqual(got["vision"]["mmproj"], str(mm))            # a Q8_0 mmproj of the user's own (#625)
97            self.assertEqual(got["vision"]["min_tokens"], 64)
98            self.assertEqual(got["exe"], "e2")
99            self.assertEqual(json.loads((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8")), old)
100            self.assertIn("--threads", out)
101            # the same again: nothing changes, so no new copy is made
102            (Path(d) / "strata-x.json.bak").unlink()
103            again = {"exe": "e2", "args": ["--kv", "int8"],
104                     "vision": {"exe": "v2", "mmproj": str(Path(d) / "mmproj-BF16.gguf"), "gpu": False,
105                                "max_tokens": 300}}
106            quiet(setup.write_setup_config, p, again)
107            self.assertFalse((Path(d) / "strata-x.json.bak").exists())
108            self.assertEqual(json.loads(p.read_text(encoding="utf-8")), got)
109
110    def test_an_unreadable_earlier_config_is_replaced_with_a_copy(self):
111        with tempfile.TemporaryDirectory() as d:
112            p = Path(d) / "strata-x.json"
113            p.write_text("{cut off", encoding="utf-8")
114            quiet(setup.write_setup_config, p, {"exe": "e", "args": []})
115            self.assertEqual(json.loads(p.read_text(encoding="utf-8")), {"exe": "e", "args": [], "args_written": []})
116            self.assertEqual((Path(d) / "strata-x.json.bak").read_text(encoding="utf-8"), "{cut off")
117
118    def test_display_tip_and_typed_ahead_flush(self):
119        # #779: the tip only when nvidia-smi says the card drives a display; #841: typed-ahead keys are dropped on a tty
120        with unittest.mock.patch.object(setup, "out", lambda cmd: "Enabled\n"):
121            self.assertTrue(setup.gpu_drives_display({"index": 0}))
122        with unittest.mock.patch.object(setup, "out", lambda cmd: "Disabled\n"), unittest.mock.patch.object(setup, "out") as o:
123            o.return_value = "Disabled\n"
124            self.assertFalse(setup.gpu_drives_display({"index": 1}))
125            self.assertIn("1", o.call_args[0][0])
126        with unittest.mock.patch.object(setup, "out", lambda cmd: ""):
127            self.assertFalse(setup.gpu_drives_display({"index": 0}))
128        with unittest.mock.patch.object(setup.sys, "stdin") as stdin:
129            stdin.isatty.return_value = False
130            setup.flush_typed_ahead()                      # a pipe: nothing touched
131            stdin.fileno.assert_not_called()
132
133    def test_a_learned_expert_profile_is_carried(self):
134        # #775: --expert-profile / --expert-profile-save added by hand survive a setup run
135        with tempfile.TemporaryDirectory() as d:
136            mine = Path(d) / "learned.bin"
137            mine.write_bytes(b"x")
138            old = {"args": ["--kv", "int8", "--expert-profile", str(mine), "--expert-profile-save", str(mine)]}
139            new = {"args": ["--kv", "int8", "--expert-profile", "/data/expert-profile.bin", "--expert-cache", "auto"]}
140            self.assertEqual(setup.carry_over(old, new), ["args --expert-profile", "args --expert-profile-save"])
141            self.assertEqual(setup.flag_value(new["args"], "--expert-profile"), str(mine))
142            self.assertEqual(setup.flag_value(new["args"], "--expert-profile-save"), str(mine))
143            # the shipped profile named again, or a file that is gone: setup's own stays
144            gone = {"args": ["--expert-profile", str(Path(d) / "gone.bin")]}
145            new = {"args": ["--expert-profile", "/data/expert-profile.bin"]}
146            self.assertEqual(setup.carry_over(gone, new), [])
147            self.assertEqual(new["args"], ["--expert-profile", "/data/expert-profile.bin"])
148            same = {"args": ["--expert-profile", "/old/expert-profile.bin"]}
149            self.assertEqual(setup.carry_over(same, new), [])
150
151    def test_mtp_off_is_the_users_and_survives_a_setup_run_that_writes_the_draft_layer_back(self):
152        old = {"args": ["--spec", "4", "--spec-min-p", "0.5"], "mtp": False}
153        new = {"args": ["--spec", "4", "--spec-min-p", "0.5", "--mtp", "/m/rt", "--max-context", "32768"]}
154        kept = setup.carry_over(old, new)
155        self.assertIs(new["mtp"], False)
156        self.assertEqual(new["args"], ["--spec", "4", "--max-context", "32768"])
157        self.assertTrue(any(k.startswith("mtp off") for k in kept))
158        on = {"args": ["--mtp", "/m/rt"]}
159        setup.carry_over({"args": [], "mtp": True}, on)
160        self.assertEqual(on["args"], ["--mtp", "/m/rt"])                           # on: setup's own arguments stay
161
162    def test_a_missing_mmproj_is_not_carried(self):
163        old = {"vision": {"mmproj": "/nowhere/mmproj-Q8_0.gguf", "gpu": True}}
164        new = {"vision": {"mmproj": "/data/mmproj-BF16.gguf", "gpu": True}}
165        self.assertEqual(setup.carry_over(old, new), [])
166        self.assertEqual(new["vision"]["mmproj"], "/data/mmproj-BF16.gguf")
167
168    def test_a_copy_set_up_like_the_last_one_keeps_them_too(self):
169        with tempfile.TemporaryDirectory() as d:
170            src = Path(d) / "other" / "strata-x.json"
171            src.parent.mkdir()
172            src.write_text(json.dumps({"exe": "old", "mcp_servers": {"a": {"command": "x"}}}), encoding="utf-8")
173            p = Path(d) / "strata-x.json"
174            quiet(setup.write_setup_config, p, {"exe": "new"}, src)
175            self.assertEqual(json.loads(p.read_text(encoding="utf-8")),
176                             {"exe": "new", "mcp_servers": {"a": {"command": "x"}}})
177            self.assertFalse((Path(d) / "strata-x.json.bak").exists())   # nothing here was replaced
178
179
180class NoBrowser(unittest.TestCase):
181    """#609 (#631): --no-browser keeps the chat page from opening: "open_browser": false in the run config, no --open
182    on the start's server command or in run-<model>.bat/.sh.  Without the flag nothing changes."""
183
184    def setUp(self):
185        self.ram, self.found = PROFILES["64GB-1x32GB"]
186
187    def run_setup(self, *extra, configs=()):
188        return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra],
189                       configs=configs)
190
191    def test_at_setup(self):
192        code, out, cfg, _ = self.run_setup("--no-browser")
193        self.assertEqual(code, 0, out)
194        self.assertIs(cfg["open_browser"], False)
195        code, out, cfg, _ = self.run_setup()
196        self.assertNotIn("open_browser", cfg)                             # not given: the config as before
197        # setup run again without the flag keeps the choice (#629); --browser undoes it
198        code, out, cfg, _ = self.run_setup(configs=[("strata-q2_0.json", {"open_browser": False})])
199        self.assertIs(cfg["open_browser"], False)
200        code, out, cfg, _ = self.run_setup("--browser", configs=[("strata-q2_0.json", {"open_browser": False})])
201        self.assertIs(cfg["open_browser"], True)
202
203    def test_run_script(self):
204        with tempfile.TemporaryDirectory() as d, unittest.mock.patch.object(setup, "ROOT", Path(d)):
205            text = lambda p: p.read_text(encoding="utf-8")   # noqa: E731
206            self.assertIn('"--open"', text(setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080)))
207            script = setup.write_run_script("Q2_0", Path(d) / "strata-q2_0.json", 8080, False)
208            self.assertNotIn("--open", text(script))
209            self.assertIn('"--port" "8080"', text(script))
210
211    def start_cmd(self, cfg, keep=None):
212        with tempfile.TemporaryDirectory() as d:
213            exe = Path(d) / "strata.exe"
214            exe.write_bytes(b"")
215            p = Path(d) / "strata-q2_0.json"
216            p.write_text(json.dumps({"exe": str(exe), "args": ["--kv", "int8"], "gpu": 0, "gpus_asked": True, **cfg}))
217            call = unittest.mock.Mock(return_value=0)
218            with unittest.mock.patch.object(setup, "gpus", lambda: self.found), \
219                    unittest.mock.patch.object(setup, "is_wsl", lambda: False), \
220                    unittest.mock.patch.object(setup, "ensure_engine_for", lambda cards, path, c, yes: c), \
221                    unittest.mock.patch.object(setup.subprocess, "call", call):
222                _, out = quiet(setup.start, p, None, None, True, True, None, keep)
223            return call.call_args[0][0], out, json.loads(p.read_text())
224
225    def test_on_a_start(self):
226        cmd, out, _ = self.start_cmd({})
227        self.assertIn("--open", cmd)                                      # the default, as before
228        self.assertIn("the browser opens when it is ready", out)
229        cmd, out, _ = self.start_cmd({"open_browser": False})
230        self.assertNotIn("--open", cmd)
231        self.assertNotIn("the browser opens", out)
232        self.assertIn("no browser", out)                                  # the Settings line says so
233        cmd, out, saved = self.start_cmd({}, {"open_browser": False})     # START-HERE --no-browser: kept from now on
234        self.assertNotIn("--open", cmd)
235        self.assertIs(saved["open_browser"], False)
236        self.assertIn("saved for this model: no browser", out)
237        cmd, out, saved = self.start_cmd({"open_browser": False}, {"open_browser": True})
238        self.assertIn("--open", cmd)
239        self.assertIs(saved["open_browser"], True)
240
241
242class VisionTokens(unittest.TestCase):
243    """#625: --vision-tokens N sets the config's vision.max_tokens (the most image tokens a picture becomes); a setup
244    run again keeps it for the same encoder device; without it the device's default, as before."""
245
246    def setUp(self):
247        self.ram, self.found = PROFILES["64GB-1x32GB"]
248
249    def run_setup(self, *extra, configs=()):
250        return install(self.ram, self.found, ["--family", "qwen", "--model", "Q2_0", "--no-start", *extra],
251                       configs=configs)
252
253    def test_the_flag(self):
254        code, out, cfg, _ = self.run_setup("--vision", "cpu")
255        self.assertEqual(code, 0, out)
256        self.assertEqual(cfg["vision"]["max_tokens"], 300)               # the default, as before
257        self.assertNotIn("--vision-tokens", out)
258        code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768")
259        self.assertEqual(code, 0, out)
260        self.assertEqual(cfg["vision"]["max_tokens"], 768)
261        self.assertIn("up to 768 image tokens", out)
262        self.assertIn("longer to encode", out)                            # a note, not a cap
263        code, out, cfg, _ = self.run_setup("--vision", "gpu", "--vision-tokens", "2048")
264        self.assertEqual(cfg["vision"]["max_tokens"], 2048)
265        self.assertIn("more VRAM", out)
266
267    def test_kept_when_setup_runs_again(self):
268        code, out, first, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "768")
269        old = [("strata-q2_0.json", first)]
270        code, out, cfg, _ = self.run_setup("--vision", "cpu", "--context", "65536", configs=old)
271        self.assertEqual(cfg["vision"]["max_tokens"], 768)
272        code, out, cfg, _ = self.run_setup("--vision", "cpu", "--vision-tokens", "300", configs=old)
273        self.assertEqual(cfg["vision"]["max_tokens"], 300)               # given again: the new value
274        code, out, cfg, _ = self.run_setup("--vision", "gpu", configs=old)
275        self.assertEqual(cfg["vision"]["max_tokens"], 1024)              # another device: its own default
276
277    def test_refused_and_unused(self):
278        with contextlib.redirect_stderr(io.StringIO()) as err:
279            code, out, cfg, _ = self.run_setup("--vision-tokens", "0")
280        self.assertEqual(code, 2)
281        self.assertIn("--vision-tokens takes a number", err.getvalue())
282        code, out, cfg, _ = self.run_setup("--vision", "no", "--vision-tokens", "768")
283        self.assertEqual(code, 0, out)
284        self.assertNotIn("vision", cfg)
285        self.assertIn("images are off", out)
286
287
288if __name__ == "__main__":
289    unittest.main()