okami.mom/strata

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

Niko1221Merge f-own-int 5aa7f1d88 into f-p4-int747642c2c

main
13.3 KiB255 linesraw
1"""A GPU picture reader whose start failed in its CUDA context ("CUDA error: out of memory ... in function ggml_cuda_init") on a Linux Arm machine with shared
2CPU / GPU memory (DGX Spark) is started again before the CPU reader takes over: a new spawn may start only while less than 18 s have passed since the first one
3started, and at most 12 times.  Every other failure goes the way it went.
4
5    python -m serve.test_vision_ctx_retry
6"""
7import tempfile
8import threading
9import time
10import unittest
11from pathlib import Path
12from unittest import mock
13
14import serve.server as server
15from strata_control import vision_reader as VR
16
17CTX = ("CUDA error: out of memory\n  current device: 0, in function ggml_cuda_init at ggml/src/ggml-cuda/ggml-cuda.cu:367\n"
18       "ggml/src/ggml-cuda/ggml-cuda.cu:108: CUDA error\n")
19ALLOC = "ggml_backend_cuda_buffer_type_alloc_buffer: allocating 865.48 MiB on device 0: cudaMalloc failed: out of memory\n"
20DIED = "the vision encoder did not start (killed by signal 6)"
21
22
23def rule(text=CTX, retries_done=0, next_start_s=0.0, **kw):
24    args = dict(linux=True, arm=True, hip=False)
25    args.update(kw)
26    return VR.retry_gpu_start(text=text, retries_done=retries_done, next_start_s=next_start_s, **args)
27
28
29class Rule(unittest.TestCase):
30    def test_the_constants(self):
31        self.assertEqual((VR.CONTEXT_RETRIES, VR.CONTEXT_RETRY_WAIT_S, VR.CONTEXT_RETRY_BUDGET_S), (12, 1.0, 18.0))
32
33    def test_the_count_cap_ends_it(self):
34        for done in range(12):
35            self.assertTrue(rule(retries_done=done))
36        self.assertFalse(rule(retries_done=12))
37        self.assertFalse(rule(retries_done=20))
38
39    def test_the_time_bound_is_the_start_of_the_next_spawn(self):
40        self.assertTrue(rule(next_start_s=0.0))
41        self.assertTrue(rule(next_start_s=17.9))
42        self.assertFalse(rule(next_start_s=18.0))
43        self.assertFalse(rule(next_start_s=40.0))
44
45    def test_the_own_tower_wording_counts_too(self):
46        self.assertTrue(rule("strata-vision: Strata's picture reader did not start (cannot use GPU 0: out of memory)"))
47
48    def test_other_platforms_never_retry(self):
49        self.assertFalse(rule(linux=False))           # Windows, Mac
50        self.assertFalse(rule(arm=False))             # a PC with a card of its own
51        self.assertFalse(rule(hip=True))              # the AMD reader
52
53    def test_other_errors_never_retry(self):
54        for text in (ALLOC,                                               # a card another program filled: no retry helps (reader_room reports it)
55                     CTX + ALLOC,
56                     "failed to allocate CUDA0 buffer of size 1048576 out of memory",
57                     "CUDA error: device kernel image is invalid\n  in function ggml_cuda_init",
58                     "CUDA error: CUDA-capable device(s) is/are busy or unavailable\n  in function ggml_cuda_init",
59                     "ggml_cuda_init: failed to initialize CUDA: no CUDA-capable device is detected",
60                     "the vision encoder did not start: it said nothing for 300 s",
61                     "out of memory"):                                     # no sign of the context
62            with self.subTest(text=text[:50]):
63                self.assertFalse(rule(text))
64
65
66def make_vision(args=("/engine/strata-vision", "--gpu"), log_text=""):
67    f = tempfile.NamedTemporaryFile("w+", suffix=".log", delete=False)
68    f.write(log_text)
69    f.flush()
70    v = server.Vision.__new__(server.Vision)
71    v.spawn = (list(args), f, None)
72    return v, f
73
74
75class Clock:
76    """A fake monotonic clock: `sleep` and every spawn (`attempt_s` long) move it.  It belongs to the thread that made it (the test's): `server.time` is the
77    process-wide `time` module, so while it is patched any other thread of the pytest process that sleeps or reads the clock (on Windows a watcher or job thread
78    that an earlier test left running) would call these.  Those threads get the real `time.sleep` / `time.monotonic` and are neither counted nor allowed to move the clock.
79    Make it before patching, so the real functions it keeps are the unpatched ones."""
80
81    def __init__(self):
82        self.now = 0.0
83        self.sleeps = []
84        self.owner = threading.get_ident()
85        self._real_sleep, self._real_monotonic = time.sleep, time.monotonic
86
87    def monotonic(self):
88        return self.now if threading.get_ident() == self.owner else self._real_monotonic()
89
90    def sleep(self, s):
91        if threading.get_ident() != self.owner:
92            return self._real_sleep(s)
93        self.sleeps.append(s)
94        self.now += s
95
96
97class Spawn(unittest.TestCase):
98    def run_start(self, outcomes, args=("/engine/strata-vision", "--gpu"), system="linux", machine="aarch64", logged=CTX, attempt_s=1.4, hook=None):
99        """_start_gpu_reader with `_start_reader` giving `outcomes` in turn (the last one repeats; an exception is raised, anything else returned) and taking `attempt_s`
100        on a fake clock; returns (clock, calls, result or error)."""
101        v, f = make_vision(args)
102        self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
103        clock, calls = Clock(), []
104
105        def start_reader():
106            calls.append(clock.now)             # when this spawn started
107            if hook is not None:
108                hook()
109            clock.now += attempt_s
110            o = outcomes[min(len(calls) - 1, len(outcomes) - 1)]
111            if isinstance(o, Exception):
112                f.write(logged)
113                f.flush()
114                raise o
115            return o
116
117        v._start_reader = start_reader
118        with mock.patch.object(server.sys, "platform", system), mock.patch.object(server.platform, "machine", return_value=machine), \
119                mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic):
120            try:
121                res = v._start_gpu_reader()
122            except RuntimeError as e:
123                res = e
124        return clock, calls, res
125
126    def test_a_start_that_works_the_first_time_is_not_delayed(self):
127        clock, calls, res = self.run_start([None])
128        self.assertEqual((len(calls), clock.sleeps), (1, []))
129
130    def test_a_success_ends_it_at_once(self):
131        clock, calls, res = self.run_start([RuntimeError(DIED)] * 3 + [None])       # the measured case: 3 failures, the 4th spawn works
132        self.assertEqual((len(calls), clock.sleeps, res), (4, [1.0, 1.0, 1.0], None))
133        for got, want in zip(calls, [0.0, 2.4, 4.8, 7.2]):
134            self.assertAlmostEqual(got, want)
135
136    def test_the_five_measured_failures_are_covered(self):
137        clock, calls, res = self.run_start([RuntimeError(DIED)] * 5 + [None])
138        self.assertEqual((len(calls), res), (6, None))
139        self.assertLess(calls[-1], 18.0)
140
141    def test_a_context_that_never_works_ends_by_the_time_bound_and_raises_as_before(self):
142        err = RuntimeError(DIED)
143        clock, calls, res = self.run_start([err])
144        self.assertIs(res, err)
145        self.assertEqual(len(calls), 8)                       # spawns start at 0, 2.4, ... 16.8 s; the next would start at 19.2 s
146        self.assertLess(calls[-1], 18.0)
147        self.assertLess(clock.now, 20.0)                      # the worst wait before the CPU reader takes over
148
149    def test_fast_attempts_end_by_the_count_cap(self):
150        err = RuntimeError(DIED)
151        clock, calls, res = self.run_start([err], attempt_s=0.1)
152        self.assertIs(res, err)
153        self.assertEqual((len(calls), len(clock.sleeps)), (13, 12))       # 1 spawn + 12 retries, 13.3 s: the cap, not the clock
154        self.assertLess(clock.now, 18.0)
155
156    def test_another_thread_that_sleeps_meanwhile_is_not_counted_and_does_not_move_the_clock(self):
157        """`server.time` is the process-wide module: a thread of another part of the process that sleeps while the test has it patched (a winjob / watcher thread left
158        by an earlier test on Windows counted 232,838 sleeps) must get the real sleep.  Here a thread sleeps in a loop and every spawn waits until it has slept once more."""
159        stop, slept = threading.Event(), threading.Event()
160
161        def other():
162            while not stop.is_set():
163                time.sleep(0.0002)              # the fake one when it is patched, and it must not count
164                slept.set()
165
166        def hook():
167            slept.clear()
168            slept.wait(2)
169
170        t = threading.Thread(target=other, daemon=True)
171        t.start()
172        try:
173            clock, calls, res = self.run_start([RuntimeError(DIED)], attempt_s=0.1, hook=hook)
174        finally:
175            stop.set()
176            t.join(2)
177        self.assertEqual((len(calls), len(clock.sleeps)), (13, 12))
178        self.assertAlmostEqual(clock.now, 13 * 0.1 + 12 * 1.0)      # only this thread's pauses and spawns moved it
179
180    def test_a_spawn_that_would_start_at_17_9_s_is_allowed_and_one_at_18_0_s_is_not(self):
181        clock, calls, res = self.run_start([RuntimeError(DIED), None], attempt_s=16.9)        # fails at 16.9, next starts at 17.9
182        self.assertEqual((len(calls), res), (2, None))
183        self.assertAlmostEqual(calls[1], 17.9)
184        clock, calls, res = self.run_start([RuntimeError(DIED), None], attempt_s=17.0)        # fails at 17.0, next would start at 18.0
185        self.assertEqual(len(calls), 1)
186        self.assertIsInstance(res, RuntimeError)
187
188    def test_the_diagnostic_line_only_with_STRATA_VIT_PROF_and_only_after_a_retry(self):
189        for env, outcomes, expect in (({"STRATA_VIT_PROF": "1"}, [RuntimeError(DIED)] * 3 + [None], ["vit-prof: GPU reader started after 3 retries, 8.60 s"]),
190                                      ({"STRATA_VIT_PROF": "1"}, [None], []),
191                                      ({}, [RuntimeError(DIED)] * 3 + [None], []),
192                                      ({"STRATA_VIT_PROF": "1"}, [RuntimeError(DIED)], ["vit-prof: GPU reader did not start after 7 retries, 18.20 s"])):
193            with self.subTest(env=env, n=len(outcomes)), mock.patch.dict(server.os.environ, env), mock.patch("builtins.print") as pr:
194                server.os.environ.pop("STRATA_VIT_PROF", None) if not env else None
195                self.run_start(outcomes)
196            # (print is patched for the whole process: only this module's diagnostic lines count, whatever another thread prints meanwhile)
197            self.assertEqual([c.args[0] for c in pr.call_args_list if c.args and str(c.args[0]).startswith("vit-prof")], expect)
198
199    def test_no_room_is_not_retried(self):
200        err = server.VisionNoRoom("the vision encoder did not start: the graphics card has no room for it", None)
201        clock, calls, res = self.run_start([err], logged=ALLOC)
202        self.assertEqual((len(calls), clock.sleeps), (1, []))
203        self.assertIs(res, err)
204
205    def test_a_failure_that_is_not_the_context_is_not_retried(self):
206        err = RuntimeError("the vision encoder did not start: ERR cannot open the model")
207        clock, calls, res = self.run_start([err], logged="ERR cannot open the model\n")
208        self.assertEqual((len(calls), clock.sleeps), (1, []))
209
210    def test_other_systems_are_not_retried(self):
211        err = RuntimeError("the vision encoder did not start")
212        for kw in ({"system": "win32"}, {"system": "darwin"}, {"machine": "x86_64"}, {"machine": "AMD64"},
213                   {"args": ("/engine/strata-vision-hip", "--gpu")}):
214            with self.subTest(kw=kw):
215                clock, calls, res = self.run_start([err], **kw)
216                self.assertEqual((len(calls), clock.sleeps), (1, []))
217
218    def test_an_old_failure_in_a_shared_log_does_not_count(self):
219        v, f = make_vision(log_text=CTX)       # an earlier start's lines are in the file already
220        self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
221        v._start_reader = mock.Mock(side_effect=RuntimeError("the vision encoder did not start: ERR cannot open the model"))
222        clock = Clock()
223        with mock.patch.object(server.sys, "platform", "linux"), mock.patch.object(server.platform, "machine", return_value="aarch64"), \
224                mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic):
225            with self.assertRaises(RuntimeError):
226                v._start_gpu_reader()
227        self.assertEqual(v._start_reader.call_count, 1)
228        self.assertEqual(clock.sleeps, [])                    # no retry: this thread never slept
229
230    def test_start_falls_back_to_the_cpu_reader_after_the_last_retry(self):
231        v, f = make_vision()
232        self.addCleanup(lambda: (f.close(), Path(f.name).unlink()))
233        v.fallback = (["/engine/strata-vision"], f, None)
234        v.on_cpu, v.elastic = False, False
235        starts = []
236        clock = Clock()
237
238        def start_reader():
239            starts.append(v.on_cpu)
240            if not v.on_cpu:
241                f.write(CTX)
242                f.flush()
243                raise RuntimeError(DIED)
244
245        v._start_reader = start_reader
246        v.not_started_note = lambda: "note"
247        with mock.patch.object(server.sys, "platform", "linux"), mock.patch.object(server.platform, "machine", return_value="aarch64"), \
248                mock.patch.object(server.time, "sleep", clock.sleep), mock.patch.object(server.time, "monotonic", clock.monotonic), mock.patch("builtins.print"):
249            v._start()
250        self.assertEqual(starts, [False] * 13 + [True])        # fast attempts (the clock moves only by the pauses): the count cap
251        self.assertTrue(v.on_cpu)
252
253
254if __name__ == "__main__":
255    unittest.main()