okami.mom/strata

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

Niko1221Merge main dbb2d168c (picture-reader fix, GGML_NO_BACKTRACE) into f-own-int2503b206b

main
9.6 KiB229 linesraw
1"""The picture reader reads on the processor instead of ending the launch (owner, 2026-11-10): the NVIDIA reader (strata-vision) is the CPU reader too,
2without --gpu, so a GPU reader that does not start - resident or on demand, whatever the cause - falls back to it, with one log line; when the cause was a
3card with no room, the words for the Terminal's summary go with it (Vision.cpu_note, /metrics engine.vision_note, Runner.report_vision).
4
5    python -m serve.test_vision_cpu_fallback
6"""
7import contextlib
8import io
9import subprocess
10import sys
11import tempfile
12import textwrap
13import unittest
14from pathlib import Path
15from unittest import mock
16
17import serve.server as server
18from strata_cli.launch import runner as R
19
20ALLOC = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory"
21NOTE = ("Pictures are read on the processor, which is slower: graphics card 2 has no room for the picture reader "
22        "(it needs about 1.5 GB; 0.1 GB are free). To read them on the card, close the other programs that use it and start again.")
23
24
25def plain_popen(what, args, **kw):
26    kw.pop("role", None)
27    return subprocess.Popen(args, **kw)
28
29
30class Construction(unittest.TestCase):
31    def make(self, **vision):
32        cfg = {"exe": "/engine/strata-vision", "mmproj": "/m/mmproj.gguf", "model": "/m/model.gguf", "gpu": True, **vision}
33        with mock.patch.object(server.Vision, "work_dir", return_value=Path(tempfile.gettempdir())):
34            return server.Vision(cfg, lazy=True)
35
36    def test_the_nvidia_reader_has_the_cpu_reader_in_every_mode(self):
37        for extra in ({}, {"elastic": True}, {"elastic": False}, {"cuda_device": 1}):
38            with self.subTest(extra=extra):
39                v = self.make(**extra)
40                self.assertIn("--gpu", v.spawn[0])
41                self.assertIsNotNone(v.fallback)
42                self.assertNotIn("--gpu", v.fallback[0])
43                self.assertTrue(v.fallback[0][0].endswith("strata-vision"))
44                self.assertIsNone(v.cpu_note)
45
46    def test_the_persons_image_limit_goes_with_it(self):
47        v = self.make(max_tokens=1024)
48        self.assertEqual(v.fallback[0][v.fallback[0].index("--max-tokens") + 1], "1024")
49
50    def test_a_cpu_reader_has_nothing_to_fall_back_to(self):
51        self.assertIsNone(self.make(gpu=False).fallback)
52
53    def test_amd_readers_keep_their_own_cpu_reader(self):
54        self.assertIsNone(self.make(exe="/engine/strata-vision-hip").fallback)                       # no cpu_exe next to it: nothing to fall back to
55        v = self.make(exe="/engine/strata-vision-hip", cpu_exe="/engine/strata-vision")
56        self.assertTrue(v.fallback[0][0].endswith("strata-vision"))
57
58
59class Fallback(unittest.TestCase):
60    def setUp(self):
61        self.tmp = tempfile.TemporaryDirectory()
62        self.addCleanup(self.tmp.cleanup)
63        self.procs, self.logs = [], []
64        self.addCleanup(self.stop_all)
65
66    def stop_all(self):
67        for p in self.procs:
68            if p.poll() is None:
69                p.kill()
70            p.wait(timeout=10)
71            for stream in (p.stdin, p.stdout):
72                with contextlib.suppress(OSError, ValueError):
73                    stream.close()
74        for f in self.logs:
75            with contextlib.suppress(OSError):
76                f.close()
77
78    def script(self, body):
79        path = Path(self.tmp.name) / ("reader%d.py" % len(list(Path(self.tmp.name).glob("reader*.py"))))
80        path.write_text("import os, sys, time\n" + textwrap.dedent(body), encoding="utf-8")
81        return [sys.executable, "-u", str(path)]
82
83    def vision(self, gpu_body, cpu_body, env=None):
84        path = Path(self.tmp.name) / "engine.log"
85        path.write_text("", encoding="utf-8")
86        log = open(path, "a", encoding="utf-8")
87        self.logs.append(log)
88        v = server.Vision.__new__(server.Vision)
89        v.spawn = (self.script(gpu_body), log, env)
90        v.fallback = (self.script(cpu_body), log, env)
91        v.gpu_spawn, v.cpu_spawn = v.spawn, v.fallback
92        v.dir = Path(self.tmp.name)
93        v.stopped, v.proc, v.on_cpu, v.cpu_note, v.elastic = True, None, False, None, False
94        return v
95
96    def start(self, v):
97        out, error = io.StringIO(), None
98
99        def keep(what, args, **kw):
100            p = plain_popen(what, args, **kw)
101            self.procs.append(p)
102            return p
103
104        with mock.patch.object(server, "popen", keep), mock.patch.object(server, "card_free_mib", lambda index, amd=False: 114), contextlib.redirect_stdout(out):
105            try:
106                v._start()
107            except RuntimeError as e:
108                error = e
109        return error, out.getvalue()
110
111    OOM = """
112        sys.stderr.write(%r + "\\n")
113        sys.stderr.flush()
114        print("[New LWP 5]", flush=True)
115        sys.exit(1)
116    """ % ALLOC
117    READY = """
118        print("READY 2560", flush=True)
119        sys.stdin.readline()
120    """
121
122    def test_a_full_card_reads_on_the_processor_and_says_so(self):
123        v = self.vision(self.OOM, self.READY, env={"CUDA_VISIBLE_DEVICES": "2,3"})
124        error, said = self.start(v)
125        self.assertIsNone(error)
126        self.assertTrue(v.on_cpu)
127        self.assertTrue(v.alive())
128        self.assertEqual(v.cpu_note, NOTE)                       # card 2: the reader's card 0 of "2,3"; 114 MiB free read after it failed
129        self.assertIn("[strata] the GPU picture reader did not start", said)
130        self.assertIn("pictures are read on the CPU", said)
131
132    def test_the_need_in_the_note_follows_the_image_limit(self):
133        v = self.vision(self.OOM, self.READY, env={"CUDA_VISIBLE_DEVICES": "2,3"})
134        v.max_tokens = 16384
135        self.start(v)
136        self.assertIn("(it needs about 3.6 GB; 0.1 GB are free)", v.cpu_note)
137
138    def test_a_reader_that_starts_changes_nothing(self):
139        v = self.vision(self.READY, self.OOM)
140        error, said = self.start(v)
141        self.assertIsNone(error)
142        self.assertFalse(v.on_cpu)
143        self.assertIsNone(v.cpu_note)
144        self.assertNotIn("did not start", said)
145
146    def test_another_cause_falls_back_too_without_the_full_card_words(self):
147        v = self.vision("""
148            print("ERR cannot load the vision encoder x.gguf", flush=True)
149            sys.exit(1)
150        """, self.READY)
151        error, said = self.start(v)
152        self.assertIsNone(error)
153        self.assertTrue(v.on_cpu)
154        self.assertIn("ERR cannot load the vision encoder", said)
155        self.assertEqual(v.cpu_note, "Pictures are read on the processor, which is slower: the picture reader could not start on graphics card 0. "
156                                     "The reason is in the engine's log: " + self.logs[0].name + ".")
157
158    def test_the_card_in_that_sentence_is_the_first_one_the_reader_is_shown(self):
159        v = self.vision("""
160            print("ERR cannot load the vision encoder x.gguf", flush=True)
161            sys.exit(1)
162        """, self.READY, env={"CUDA_VISIBLE_DEVICES": "3,1"})
163        self.start(v)
164        self.assertIn("could not start on graphics card 3. The reason", v.cpu_note)
165
166    def test_on_a_mac_there_is_no_card_number(self):
167        v = self.vision("""
168            print("ERR cannot load the vision encoder x.gguf", flush=True)
169            sys.exit(1)
170        """, self.READY)
171        with mock.patch.object(server.sys, "platform", "darwin"):
172            self.start(v)
173        self.assertTrue(v.cpu_note.startswith("Pictures are read on the processor, which is slower: the picture reader could not start. The reason is in"))
174
175    def test_the_cpu_reader_failing_too_ends_it_with_its_own_error(self):
176        v = self.vision(self.OOM, """
177            print("ERR cannot open the text model x.gguf (no such file)", flush=True)
178            sys.exit(1)
179        """)
180        error, _ = self.start(v)
181        self.assertIsNotNone(error)
182        self.assertIn("ERR cannot open the text model", str(error))
183
184    def test_the_card_is_unknown_when_the_reader_saw_no_such_card(self):
185        v = self.vision(self.OOM, self.READY, env={"CUDA_VISIBLE_DEVICES": ""})
186        v.spawn = (v.spawn[0], v.spawn[1], {"CUDA_VISIBLE_DEVICES": "GPU-8c3f"})
187        error, _ = self.start(v)
188        self.assertIsNone(error)
189        self.assertEqual(v.cpu_note, "Pictures are read on the processor, which is slower: the graphics card has no room for the picture reader "
190                                     "(it needs about 1.5 GB). To read them on the card, close the other programs that use it and start again.")
191
192    def test_an_on_demand_reader_that_goes_up_again_loses_the_note(self):
193        v = self.vision(self.OOM, self.READY, env={"CUDA_VISIBLE_DEVICES": "2,3"})
194        v.elastic = True
195        self.start(v)
196        self.assertEqual(v.cpu_note, NOTE)
197        v.close = lambda: None
198        v.unload()
199        self.assertIsNone(v.cpu_note)
200
201
202class ShownInTheSummary(unittest.TestCase):
203    def runner(self):
204        r = R.Runner.__new__(R.Runner)
205        r.notices, r.events = [], []
206        r.emit = lambda stage, text, pct=None, level="info", **data: r.events.append((stage, text, level))
207        return r
208
209    def test_the_note_from_the_server_is_a_notice_and_an_event(self):
210        r = self.runner()
211        r.report_vision({"vision_note": NOTE})
212        self.assertEqual(r.notices, [NOTE])
213        self.assertEqual(r.events, [("start", NOTE, "warn")])
214
215    def test_it_is_said_once(self):
216        r = self.runner()
217        r.report_vision({"vision_note": NOTE})
218        r.report_vision({"vision_note": NOTE})
219        self.assertEqual(len(r.notices), 1)
220
221    def test_no_note_no_line(self):
222        r = self.runner()
223        r.report_vision({})
224        r.report_vision({"vision_note": None})
225        self.assertEqual((r.notices, r.events), ([], []))
226
227
228if __name__ == "__main__":
229    unittest.main()