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
5.4 KiB140 linesraw
1"""A picture reader that cannot start because its card has no room (serve/server.py vision_start_error, VisionNoRoom): the server names the cause
2instead of the last line of whatever a debugger printed.  The readers are small Python scripts run as real processes; their stderr is a log file, as the
3engine's log is in the product.
4
5    python -m serve.test_vision_no_room
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
18
19ALLOC = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory"
20BUFFER = "alloc_tensor_range: failed to allocate CUDA0 buffer of size 907524736"
21ASSERT = "ggml-backend.cpp:188: GGML_ASSERT(buffer) failed"
22
23
24def plain_popen(what, args, **kw):
25    kw.pop("role", None)
26    return subprocess.Popen(args, **kw)
27
28
29class NoRoom(unittest.TestCase):
30    def setUp(self):
31        self.tmp = tempfile.TemporaryDirectory()
32        self.addCleanup(self.tmp.cleanup)
33        self.procs = []
34        self.logs = []
35        self.addCleanup(self.stop_all)
36
37    def stop_all(self):
38        for p in self.procs:
39            if p.poll() is None:
40                p.kill()
41            p.wait(timeout=10)
42            for stream in (p.stdin, p.stdout):
43                with contextlib.suppress(OSError, ValueError):
44                    stream.close()
45        for f in self.logs:
46            with contextlib.suppress(OSError):
47                f.close()
48
49    def log(self, text=""):
50        path = Path(self.tmp.name) / ("engine%d.log" % len(self.logs))
51        path.write_text(text, encoding="utf-8")
52        f = open(path, "a", encoding="utf-8")
53        self.logs.append(f)
54        return f
55
56    def reader(self, body: str, log):
57        script = Path(self.tmp.name) / ("reader%d.py" % len(list(Path(self.tmp.name).glob("reader*.py"))))
58        script.write_text("import os, sys, time\n" + textwrap.dedent(body), encoding="utf-8")
59        v = server.Vision.__new__(server.Vision)
60        v.spawn = ([sys.executable, "-u", str(script)], log, None)
61        v.dir = Path(self.tmp.name)
62        v.stopped, v.proc = True, None
63        return v
64
65    def start(self, v):
66        error = None
67
68        def keep(what, args, **kw):
69            p = plain_popen(what, args, **kw)
70            self.procs.append(p)
71            return p
72
73        with mock.patch.object(server, "popen", keep), contextlib.redirect_stdout(io.StringIO()):
74            try:
75                v._start_reader()
76            except RuntimeError as e:
77                error = e
78        return error
79
80    OOM_READER = """
81        print("[New LWP 477206]", flush=True)
82        sys.stderr.write(%r + "\\n" + %r + "\\n" + %r + "\\n")
83        sys.stderr.flush()
84        print("Python Exception <class 'gdb.error'>: Couldn't get registers: No such process.", flush=True)
85        sys.exit(1)
86    """ % (ALLOC, BUFFER, ASSERT)
87
88    def test_the_v100_launch_in_miniature(self):
89        v = self.reader(self.OOM_READER, self.log())
90        error = self.start(v)
91        self.assertIsInstance(error, server.VisionNoRoom)
92        self.assertEqual(error.room.device, 0)
93        self.assertAlmostEqual(error.room.need_mib, 865.48, places=2)
94        text = str(error)
95        self.assertIn("the vision encoder did not start: the graphics card has no room for it", text)
96        self.assertIn("865 MiB", text)
97        self.assertIn("its card 0", text)
98        self.assertIn("cudaMalloc failed: out of memory", text)
99
100    def test_a_reader_without_a_log_that_prints_it_on_its_output_is_found_too(self):
101        v = self.reader("""
102            print(%r, flush=True)
103            sys.exit(1)
104        """ % ALLOC, None)
105        error = self.start(v)
106        self.assertIsInstance(error, server.VisionNoRoom)
107
108    def test_lines_an_earlier_start_left_in_the_shared_log_are_not_this_starts(self):
109        log = self.log(ALLOC + "\n" + BUFFER + "\n" + ASSERT + "\n")           # the last launch's failure, still in the file
110        v = self.reader("""
111            print("ERR cannot open the text model x.gguf (no such file)", flush=True)
112            sys.exit(1)
113        """, log)
114        error = self.start(v)
115        self.assertNotIsInstance(error, server.VisionNoRoom)
116        self.assertIn("ERR cannot open the text model", str(error))
117        self.assertNotIn("no room", str(error))
118
119    def test_a_card_that_is_not_there_is_not_a_full_card(self):
120        v = self.reader("""
121            sys.stderr.write("ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device\\n")
122            sys.exit(1)
123        """, self.log())
124        error = self.start(v)
125        self.assertNotIsInstance(error, server.VisionNoRoom)
126        self.assertNotIn("no room", str(error))
127
128    def test_the_message_function_alone(self):
129        log = self.log(ALLOC + "\n" + ASSERT + "\n")
130        text = server.vision_start_error("", log, 134)
131        self.assertIn("the graphics card has no room for it (it asked for 865 MiB on its card 0)", text)
132        self.assertEqual(server.vision_start_error("ERR no mmproj\n"), "the vision encoder did not start: ERR no mmproj")      # unchanged
133
134    def test_a_cause_the_server_names_already_keeps_its_own_words(self):
135        busy = server.vision_start_error("cudaMalloc failed: CUDA-capable device(s) is/are busy or unavailable")
136        self.assertIn("Exclusive_Process", busy)
137
138
139if __name__ == "__main__":
140    unittest.main()