okami.mom/strata

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

Niko1221Merge f-own-3v 6ccf276d2 into f-own-int (round 16: our picture reader as the default, llama.cpp's selectable)c7ea3ac6a

main
16.9 KiB311 linesraw
1"""The picture reader choice for an AMD engine folder (strata_control/vision_reader.py) and the server's fallback from the GPU
2reader to the CPU reader (serve/server.py, Vision._start): hip present, hip missing, hip start failure, then cpu.
3
4    python -m unittest tools.test_vision_reader
5"""
6from __future__ import annotations
7
8import io
9import tempfile
10import unittest
11from pathlib import Path
12from types import SimpleNamespace
13from unittest import mock
14
15from strata_control import vision_reader as VR
16import serve.server as server
17
18
19def folder(*names: str) -> Path:
20    d = Path(tempfile.mkdtemp(prefix="vr-"))
21    for n in names:
22        (d / n).write_bytes(b"x")
23    return d
24
25
26class Choose(unittest.TestCase):
27    def test_the_default_reader_by_card_memory_is_one_rule_for_every_make(self):
28        self.assertEqual(VR.default_mode(12), "cpu")
29        self.assertEqual(VR.default_mode(16), "cpu")
30        self.assertEqual(VR.default_mode(23.5), "gpu")
31        self.assertEqual(VR.default_mode(24), "gpu")
32        self.assertEqual(VR.default_mode(32), "gpu")
33        self.assertEqual(VR.default_mode(None), "gpu")                  # memory unknown: the GPU reader falls back by itself
34        for asked, vram, want in ((None, 16, "cpu"), ("yes", 12, "cpu"), ("on", 32, "gpu"), ("gpu", 12, "gpu"), ("cpu", 32, "cpu"),
35                                  ("no", 32, "none"), ("off", 12, "none")):
36            self.assertEqual(VR.wanted(asked, vram), want, (asked, vram))
37
38    def test_an_intel_arc_keeps_the_cpu_reader_by_default_and_gpu_is_asked_for(self):
39        """The one exception to the 24 GB rule: the SYCL reader has run on a 8 GB A750 only (INTEL_GPU_READER_BY_DEFAULT)."""
40        self.assertFalse(VR.INTEL_GPU_READER_BY_DEFAULT)
41        for vram in (8, 16, 24, 32):
42            self.assertEqual(VR.default_mode(vram, "intel"), "cpu")
43            self.assertEqual(VR.wanted("yes", vram, "intel"), "cpu")
44            self.assertEqual(VR.wanted("gpu", vram, "intel"), "gpu")
45        self.assertEqual(VR.wanted("yes", 32), "gpu")                        # other makes: unchanged
46        with mock.patch.object(VR, "INTEL_GPU_READER_BY_DEFAULT", True):
47            self.assertEqual(VR.default_mode(32, "intel"), "gpu")
48            self.assertEqual(VR.default_mode(8, "intel"), "cpu")              # with the exception off, the 24 GB rule is the same as for every make
49
50    def test_the_sycl_reader_is_the_gpu_reader_of_an_intel_folder(self):
51        d = folder("strata-vision", "strata-vision-sycl")
52        r = VR.choose(d, "gpu", windows=False)
53        self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name), ("gpu", "strata-vision-sycl", "strata-vision"))
54        self.assertEqual(VR.vision_section(r, {"mmproj": "m"})["gpu"], True)
55        r = VR.choose(folder("strata-vision"), "gpu", windows=False)         # no SYCL reader built: the CPU one, said
56        self.assertEqual((r.mode, r.exe.name), ("cpu", "strata-vision"))
57        self.assertIn("no GPU picture reader", r.note)
58        self.assertEqual(VR.choose(d, "cpu", windows=False).exe.name, "strata-vision")
59
60    def test_hip_present_gives_the_gpu_reader_with_the_cpu_one_to_fall_back_on(self):
61        d = folder("strata-vision", "strata-vision-hip")
62        for ask in ("yes", "on", "gpu"):
63            r = VR.choose(d, ask, windows=False, gpu_arch="gfx1201", archs=["gfx1200", "gfx1201"])
64            self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name), ("gpu", "strata-vision-hip", "strata-vision"), ask)
65            self.assertEqual(r.note, "")
66
67    def test_hip_missing_gives_the_cpu_reader(self):
68        d = folder("strata-vision")
69        r = VR.choose(d, "yes", windows=False, gpu_arch="gfx1201")
70        self.assertEqual((r.mode, r.exe.name, r.cpu_exe), ("cpu", "strata-vision", None))
71        self.assertEqual(r.note, "")                               # "yes" never asked for the GPU in particular
72        self.assertIn("no GPU picture reader", VR.choose(d, "gpu", windows=False).note)   # --vision gpu: said once
73
74    def test_card_not_in_the_build_gives_the_cpu_reader(self):
75        d = folder("strata-vision", "strata-vision-hip")
76        r = VR.choose(d, "yes", windows=False, gpu_arch="gfx1100", archs=["gfx1200", "gfx1201"])
77        self.assertEqual((r.mode, r.exe.name), ("cpu", "strata-vision"))
78        self.assertIn("gfx1100", r.note)
79
80    def test_unknown_card_tries_the_gpu_reader(self):
81        d = folder("strata-vision", "strata-vision-hip")
82        self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="", archs=["gfx1201"]).mode, "gpu")
83        self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="gfx1100", archs=None).mode, "gpu")
84
85    def test_gcn_arch_names_with_features_match(self):
86        self.assertEqual(VR.gfx_of("gfx1201:sramecc-:xnack-"), "gfx1201")
87        d = folder("strata-vision", "strata-vision-hip")
88        self.assertEqual(VR.choose(d, "yes", windows=False, gpu_arch="gfx1151:sramecc+:xnack-", archs=["gfx1151"]).mode, "gpu")
89
90    def test_cpu_asked_and_off(self):
91        d = folder("strata-vision", "strata-vision-hip")
92        self.assertEqual(VR.choose(d, "cpu", windows=False).exe.name, "strata-vision")
93        for ask in ("no", "none", "off", None):
94            self.assertEqual(VR.choose(d, ask, windows=False).mode, "none")
95
96    def test_no_reader_at_all(self):
97        d = folder("strata")
98        for ask in ("yes", "cpu", "gpu"):
99            r = VR.choose(d, ask, windows=False)
100            self.assertEqual(r.mode, "none", ask)
101            self.assertIn("no picture reader", r.note)
102
103    def test_windows_names(self):
104        d = folder("strata-vision.exe", "strata-vision-hip.exe")
105        r = VR.choose(d, "yes", windows=True, gpu_arch="gfx1201", archs=["gfx1201"])
106        self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name), ("gpu", "strata-vision-hip.exe", "strata-vision.exe"))
107        self.assertEqual(VR.choose(folder("strata-vision-hip"), "yes", windows=True).mode, "none")   # a Linux name on Windows
108
109    def test_run_config_section(self):
110        d = folder("strata-vision", "strata-vision-hip")
111        base = {"mmproj": "m.gguf", "model": "t.gguf", "max_tokens": 1024}
112        sec = VR.vision_section(VR.choose(d, "yes", windows=False), base)
113        self.assertTrue(sec["gpu"])
114        self.assertEqual(Path(sec["exe"]).name, "strata-vision-hip")
115        self.assertEqual(Path(sec["cpu_exe"]).name, "strata-vision")
116        cpu = VR.cpu_fallback(sec)
117        self.assertFalse(cpu["gpu"])
118        self.assertEqual(Path(cpu["exe"]).name, "strata-vision")
119        self.assertNotIn("cpu_exe", cpu)
120        self.assertEqual(cpu["mmproj"], "m.gguf")
121        cpu_only = VR.vision_section(VR.choose(folder("strata-vision"), "yes", windows=False), base)
122        self.assertFalse(cpu_only["gpu"])
123        self.assertNotIn("cpu_exe", cpu_only)
124        self.assertIsNone(VR.cpu_fallback(cpu_only))
125        self.assertIsNone(VR.cpu_fallback({**sec, "cpu_exe": ""}))
126        self.assertIsNone(VR.cpu_fallback({"exe": "strata-vision", "gpu": True}))   # an NVIDIA config has no fallback
127        # an on-demand reader (vision.elastic) always has one: the NVIDIA program without --gpu, with the same picture tokens
128        nv = VR.cpu_fallback({"exe": "/e/strata-vision", "gpu": True, "max_tokens": 1024, "elastic": True}, same_program=True)
129        self.assertEqual((nv["exe"], nv["gpu"], nv["max_tokens"], "elastic" in nv), ("/e/strata-vision", False, 1024, False))
130        self.assertIsNotNone(VR.cpu_fallback({"exe": "C:/e/strata-vision.exe", "gpu": True}, same_program=True))
131        self.assertIsNone(VR.cpu_fallback({"exe": "/e/strata-vision-hip", "gpu": True}, same_program=True))   # AMD names its own
132        self.assertIsNone(VR.cpu_fallback({"exe": "/e/strata-vision", "gpu": False}, same_program=True))
133
134
135class MacReader(unittest.TestCase):
136    """A Mac has one picture program, strata-vision with Metal built in: --gpu reads on the GPU, without it on the CPU."""
137
138    def test_a_mac_reads_on_the_gpu_by_default_whatever_its_memory(self):
139        for ram in (16, 32, 64, 128, None):
140            self.assertEqual(VR.default_mode(ram, unified=True), "gpu", ram)
141            self.assertEqual(VR.wanted(None, ram, unified=True), "gpu", ram)
142            self.assertEqual(VR.wanted("yes", ram, unified=True), "gpu", ram)
143        self.assertEqual(VR.wanted("cpu", 32, unified=True), "cpu")             # asked for: kept
144        self.assertEqual(VR.wanted("off", 32, unified=True), "none")
145        self.assertEqual(VR.default_mode(16), "cpu")                           # a 16 GB card of a PC still follows the 24 GB rule
146
147    def test_the_one_program_is_both_readers_and_its_own_fallback(self):
148        d = folder("strata", "strata-vision")
149        for ask in ("yes", "on", "gpu"):
150            r = VR.choose(d, ask, windows=False, mac=True)
151            self.assertEqual((r.mode, r.exe.name, r.cpu_exe.name, r.note), ("gpu", "strata-vision", "strata-vision", ""), ask)
152        sec = VR.vision_section(VR.choose(d, "yes", windows=False, mac=True), {"mmproj": "m.gguf", "model": "t.gguf", "max_tokens": 1024})
153        self.assertTrue(sec["gpu"])
154        self.assertEqual(sec["exe"], sec["cpu_exe"])
155        fallback = VR.cpu_fallback(sec)
156        self.assertFalse(fallback["gpu"])
157        self.assertEqual(fallback["exe"], sec["exe"])
158
159    def test_cpu_asked_is_kept_with_the_time_it_takes(self):
160        r = VR.choose(folder("strata-vision"), "cpu", windows=False, mac=True)
161        self.assertEqual((r.mode, r.exe.name, r.cpu_exe), ("cpu", "strata-vision", None))
162        self.assertIn("50 seconds", r.note)
163        self.assertFalse(VR.vision_section(r, {})["gpu"])
164
165    def test_an_engine_without_the_reader_gets_pictures_off(self):
166        for ask in ("yes", "gpu", "cpu"):
167            r = VR.choose(folder("strata"), ask, windows=False, mac=True)
168            self.assertEqual(r.mode, "none", ask)
169            self.assertIn("no picture reader", r.note)
170        self.assertEqual(VR.choose(folder("strata-vision"), "off", windows=False, mac=True).mode, "none")
171
172    def test_a_hip_program_is_not_a_mac_reader(self):
173        r = VR.choose(folder("strata-vision-hip"), "yes", windows=False, mac=True)
174        self.assertEqual(r.mode, "none")
175
176
177class FakeProc:
178    def __init__(self, first_line: str):
179        self.stdin, self.stdout = io.StringIO(), io.StringIO(first_line)
180        self.killed = False
181
182    def kill(self):
183        self.killed = True
184
185    def wait(self, timeout=None):
186        return 0
187
188    def poll(self):
189        return None
190
191
192def make_vision(cfg: dict) -> "server.Vision":
193    with mock.patch.object(server.Vision, "work_dir", staticmethod(lambda: Path(tempfile.gettempdir()))):
194        return server.Vision(cfg, lazy=True)
195
196
197class Fallback(unittest.TestCase):
198    CFG = {"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision", "gpu": True, "mmproj": "/m/mm.gguf",
199           "model": "/m/t.gguf", "max_tokens": 1024, "threads": 6}
200
201    def run_start(self, answers: dict, cfg: dict | None = None):
202        """answers: exe name -> its first stdout line, or an exception to raise from popen."""
203        started = []
204
205        def popen(what, args, **kw):
206            name = Path(args[0]).name
207            started.append(args)
208            a = answers[name]
209            if isinstance(a, Exception):
210                raise a
211            return FakeProc(a)
212
213        v = make_vision(cfg or self.CFG)
214        out = io.StringIO()
215        with mock.patch.object(server, "popen", popen), mock.patch("builtins.print", lambda *a, **k: out.write(" ".join(map(str, a)) + "\n")):
216            err = None
217            try:
218                v._start()
219            except RuntimeError as e:
220                err = e
221        return v, started, out.getvalue(), err
222
223    def test_hip_present_and_starts(self):
224        v, started, log, err = self.run_start({"strata-vision-hip": "READY 2048\n"})
225        self.assertIsNone(err)
226        self.assertEqual([Path(a[0]).name for a in started], ["strata-vision-hip"])
227        self.assertIn("--gpu", started[0])
228        self.assertEqual(log, "")
229        self.assertFalse(v.stopped)
230
231    def test_hip_start_failure_falls_back_to_cpu_with_one_line(self):
232        v, started, log, err = self.run_start({"strata-vision-hip": "ERR this GPU (gfx1100) is not in the picture reader's build (gfx1200,gfx1201)\n",
233                                               "strata-vision": "READY 2048\n"})
234        self.assertIsNone(err)
235        self.assertEqual([Path(a[0]).name for a in started], ["strata-vision-hip", "strata-vision"])
236        self.assertNotIn("--gpu", started[1])
237        self.assertIn("--threads", started[1])
238        self.assertEqual(log.count("\n"), 1)
239        self.assertIn("gfx1100", log)
240        self.assertIn("CPU", log)
241        self.assertFalse(v.stopped)
242        self.assertIsNone(v.fallback)
243
244    def test_hip_process_that_dies_silently_falls_back(self):                  # a GPU runtime that aborts: stdout closes empty
245        v, started, log, err = self.run_start({"strata-vision-hip": "", "strata-vision": "READY 2048\n"})
246        self.assertIsNone(err)
247        self.assertEqual(len(started), 2)
248        self.assertEqual(log.count("\n"), 1)
249
250    def test_hip_missing_file_falls_back(self):                               # popen raises (exe gone, not executable)
251        v, started, log, err = self.run_start({"strata-vision-hip": FileNotFoundError("strata-vision-hip"),
252                                               "strata-vision": "READY 2048\n"})
253        self.assertIsNone(err)
254        self.assertEqual(len(started), 2)
255
256    def test_restart_after_a_fallback_stays_on_the_cpu_reader(self):
257        v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n", "strata-vision": "READY 2048\n"})
258        started.clear()
259        with mock.patch.object(server, "popen", lambda what, args, **kw: started.append(args) or FakeProc("READY 2048\n")):
260            v.restart()
261        self.assertEqual([Path(a[0]).name for a in started], ["strata-vision"])
262
263    def test_cpu_failure_after_the_fallback_is_an_error(self):
264        v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n", "strata-vision": "ERR cannot load the vision encoder\n"})
265        self.assertIsNotNone(err)
266        self.assertIn("cannot load", str(err))
267
268    def test_a_config_without_cpu_exe_has_no_fallback(self):                  # NVIDIA: the error is shown as before
269        cfg = {k: v for k, v in self.CFG.items() if k != "cpu_exe"}
270        v, started, log, err = self.run_start({"strata-vision-hip": "ERR nope\n"}, cfg)
271        self.assertIsNotNone(err)
272        self.assertEqual(len(started), 1)
273        self.assertEqual(log, "")
274
275    def test_the_ready_line_names_the_reader_and_older_readers_still_start(self):
276        """strata-vision says which reader runs ("READY <n> own" / "READY <n> mtmd"); an older one says "READY <n>" and starts as before."""
277        cpu = {"exe": "/e/strata-vision", "gpu": False, "mmproj": "/m/mm.gguf", "model": "/m/t.gguf"}
278        for line, reader in (("READY 2560 own\n", "own"), ("READY 2560 mtmd\n", "mtmd"), ("READY 2048\n", None)):
279            v, started, log, err = self.run_start({"strata-vision": line}, cpu)
280            self.assertIsNone(err, line)
281            self.assertEqual(v.reader, reader, line)
282            self.assertEqual(log, "", line)                              # nothing said when the chosen reader started
283
284    def test_a_fallback_to_llama_cpps_reader_is_said_once(self):
285        cpu = {"exe": "/e/strata-vision", "gpu": False, "mmproj": "/m/mm.gguf", "model": "/m/t.gguf"}
286        v, started, log, err = self.run_start({"strata-vision": "READY 2560 mtmd fallback\n"}, cpu)
287        self.assertIsNone(err)
288        self.assertEqual((v.reader, len(started)), ("mtmd", 1))           # the same process: no second start
289        self.assertEqual(log.count("[strata] Strata's picture reader did not start; pictures are read with llama.cpp's reader."), 1)
290
291    def test_the_reader_choice_reaches_the_reader_through_the_run_configs_env(self):
292        """The settings write STRATA_VISION_TOWER=mtmd into the model's run config "env" (strata_control/speed_switches.py picture_reader); the server
293        hands that env to the picture reader as to the engine, so no reader argument changes (an older reader ignores the variable)."""
294        cfg = {"env": {"STRATA_VISION_TOWER": "mtmd"}, "vision": {"exe": "/e/strata-vision", "mmproj": "/m/mm.gguf", "model": "/m/t.gguf"}}
295        env = server.vision_env(cfg, server.child_env(cfg))
296        self.assertEqual(env.get("STRATA_VISION_TOWER"), "mtmd")
297        self.assertNotIn("--tower", server.Vision.reader_args(cfg["vision"]))
298        with mock.patch.dict("os.environ", {}, clear=False):
299            import os
300            os.environ.pop("STRATA_VISION_TOWER", None)
301            self.assertNotIn("STRATA_VISION_TOWER", server.vision_env({}, server.child_env({})))   # a default file carries nothing
302
303    def test_cpu_config_is_unchanged(self):
304        cfg = {"exe": "/e/strata-vision", "gpu": False, "mmproj": "/m/mm.gguf", "model": "/m/t.gguf"}
305        v, started, log, err = self.run_start({"strata-vision": "READY 2048\n"}, cfg)
306        self.assertIsNone(err)
307        self.assertNotIn("--gpu", started[0])
308
309
310if __name__ == "__main__":
311    unittest.main()