okami.mom/strata

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

waveringanaserve tests: bring back the DeepSeek V4.1 cases upstream cut with the enginecded60248

main
20.7 KiB375 linesraw
1"""The elastic image encoder (the vision section's "elastic": true with "vram_elastic"): the first picture makes the
2expert cache keep the encoder's VRAM free and then starts it, later pictures use it as it is, an idle encoder stops and
3the cache takes its VRAM back, a POST /v1/vram reserve stacks on the encoder's share, and the engine's load never starts
4it on its own."""
5import contextlib
6import io
7import tempfile
8import time
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from serve.frontend import ChatTemplate
14from serve.server import ByteTokenizer, EngineDied, Service, Vision
15from serve.test_vram import VramEngine
16
17ROOT = Path(__file__).resolve().parents[1]
18IMAGE = {"type": "image", "source": "x.png"}
19
20
21class ElasticVision:
22    """An encoder process stand-in: starts, stops, and turns every picture into three image tokens."""
23    def __init__(self, d, elastic=True):
24        self.elastic, self.elastic_mib, self.elastic_idle_s = elastic, 2048, 60.0
25        self.up, self.starts, self.unloads = False, 0, 0
26        self.dir = Path(d)
27        self.rows = self.dir / "img.sve"
28        self.rows.write_bytes(b"rows")
29
30    def alive(self):
31        return self.up
32
33    def restart(self):
34        self.up, self.starts = True, self.starts + 1
35
36    def unload(self):
37        self.up, self.unloads = False, self.unloads + 1
38
39    def encode(self, source):
40        assert self.up, "a picture reached an encoder that was not started"
41        return self.rows, 3
42
43
44class Elastic(unittest.TestCase):
45    def setUp(self):
46        d = tempfile.mkdtemp()
47        self.tok = ByteTokenizer()
48        self.engine = VramEngine(self.tok)
49        self.engine.loaded = True
50        self.vision = ElasticVision(d)
51        self.svc = Service(self.engine, self.tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=self.vision)
52        self.svc.free_vram_mib = lambda: None               # (not this PC's card)
53        self.addCleanup(self.drop_embeddings)
54
55    def drop_embeddings(self):
56        path = getattr(getattr(self.svc, "embeddings", None), "path", None)
57        if path is not None:
58            path.unlink(missing_ok=True)
59
60    def picture(self):
61        self.svc.prepare([{"role": "user", "content": [{"type": "text", "text": "what is it"}, IMAGE]}], None, {})
62
63    def test_the_first_picture_makes_room_then_starts_the_encoder(self):
64        self.picture()
65        self.assertEqual(self.engine.calls, [2048])         # the cache keeps the encoder's share free first
66        self.assertEqual(self.vision.starts, 1)
67        self.assertTrue(self.svc.vision_held)
68        self.picture()                                      # the next one uses the running encoder
69        self.assertEqual(self.engine.calls, [2048])
70        self.assertEqual(self.vision.starts, 1)
71
72    def test_an_idle_encoder_stops_and_the_cache_grows_back_whole(self):
73        self.picture()
74        self.assertEqual(self.svc._vision_idle_down(), "busy")             # a picture came just now
75        self.svc.last_image_at = time.time() - 61
76        with self.svc.fifo:                                                # a request holds the turn
77            self.assertEqual(self.svc._vision_idle_down(), "busy")
78        self.assertEqual(self.svc._vision_idle_down(), "down")
79        self.assertFalse(self.vision.up)
80        self.assertFalse(self.svc.vision_held)
81        self.assertEqual(self.engine.calls, [2048, 0])      # 0, not None: the full size, not the start's reserve
82        self.assertEqual(self.svc._vision_idle_down(), "nothing")
83        self.picture()                                      # and the next picture starts it again
84        self.assertEqual(self.vision.starts, 2)
85        self.assertEqual(self.engine.calls, [2048, 0, 2048])
86
87    def test_a_vram_reserve_stacks_on_the_encoders_share(self):
88        self.svc.vram(4000)
89        self.picture()
90        self.assertEqual(self.engine.calls, [4000, 6048])
91        self.svc.vram(1000)                                 # asked while the encoder runs
92        self.assertEqual(self.engine.calls[-1], 3048)
93        self.svc.last_image_at = 0
94        self.svc._vision_idle_down()
95        self.assertEqual(self.engine.calls[-1], 1000)       # back to the asked reserve, not to 0
96
97    def test_an_engine_that_cannot_shrink_still_gets_its_encoder(self):
98        self.engine.elastic = False
99        self.picture()
100        self.assertEqual(self.vision.starts, 1)
101        self.assertFalse(self.svc.vision_held)
102        self.svc.last_image_at = 0
103        self.assertEqual(self.svc._vision_idle_down(), "down")
104        self.assertEqual(self.engine.calls, [2048])         # the refused shrink only: nothing to give back
105
106    def test_an_encoder_that_fails_to_start_is_a_503_not_a_dropped_connection(self):
107        def fail():
108            raise RuntimeError("the vision encoder did not start: cudaMalloc failed: out of memory")
109        self.vision.restart = fail
110        with self.assertRaises(EngineDied) as e:            # the handlers answer EngineDied with a 503
111            self.picture()
112        self.assertIn("the image encoder failed to start", str(e.exception))
113        self.svc.last_image_at = 0
114        self.assertEqual(self.svc._vision_idle_down(), "down")
115        self.assertEqual(self.engine.calls, [2048, 0])      # the share made for it goes back
116
117    def test_the_stop_is_logged_when_the_cache_never_made_room(self):
118        self.engine.elastic = False                         # a layer split: the engine refuses --vram-elastic
119        self.picture()
120        self.svc.last_image_at = 0
121        out = io.StringIO()
122        with contextlib.redirect_stdout(out):
123            self.assertEqual(self.svc._vision_idle_down(), "down")
124        self.assertIn("the image encoder stopped after 60 s without a picture", out.getvalue())
125        self.assertNotIn("expert cache", out.getvalue())
126
127    def test_the_load_never_starts_an_elastic_encoder(self):
128        self.assertFalse(self.svc._vision_down())
129        self.svc.vision = ElasticVision(tempfile.mkdtemp(), elastic=False)
130        self.assertTrue(self.svc._vision_down())            # a non-elastic encoder that is down is started again
131
132    def test_an_unload_lets_go_of_the_share(self):
133        self.picture()
134        self.assertEqual(self.svc.unload(), "unloaded")
135        self.assertFalse(self.svc.vision_held)
136        self.assertFalse(self.vision.up)
137
138    def test_the_config_keys(self):
139        v = Vision({"exe": "e", "mmproj": "m", "model": "t", "elastic": True, "elastic_mib": 3000,
140                    "elastic_idle_s": 30}, lazy=False)          # elastic: nothing starts with the server
141        self.assertTrue(v.elastic and v.elastic_mib == 3000 and v.elastic_idle_s == 30 and not v.alive())
142        v = Vision({"exe": "e", "mmproj": "m", "model": "t"}, lazy=True)
143        self.assertFalse(v.elastic)
144        self.assertEqual((v.elastic_mib, v.elastic_idle_s), (2048, 120.0))
145
146    def test_the_ask_follows_the_image_limit(self):
147        """Without the person's own elastic_mib the cache keeps the reader's need at its image limit free, never less than 2,048 MiB."""
148        base = {"exe": "e", "mmproj": "m", "model": "t", "gpu": True, "elastic": True}
149        for limit, ask in ((None, 2048), (1024, 2048), (4096, 2048), (16384, 3674), (0, 3674)):
150            cfg = dict(base) if limit is None else {**base, "max_tokens": limit}
151            self.assertEqual(Vision(cfg, lazy=True).elastic_mib, ask, limit)
152        self.assertEqual(Vision({**base, "max_tokens": 16384, "elastic_mib": 2500}, lazy=True).elastic_mib, 2500)
153        self.assertEqual(Vision({**base, "max_tokens": 1024, "elastic_mib": 5000}, lazy=True).elastic_mib, 5000)
154
155
156class OnDemandReader(unittest.TestCase):
157    """The reader that starts with the first picture: no room on the card -> the CPU reader reads it, the cache grows back at once,
158    and the next start tries the card again; pictures already encoded start nothing."""
159
160    def vision(self, d):
161        v = Vision({"exe": "gpu-reader", "mmproj": "m", "model": "t", "gpu": True, "cpu_exe": "cpu-reader", "elastic": True}, lazy=True)
162        v.started = []
163
164        def start_reader():
165            exe = v.spawn[0][0]
166            v.started.append(exe)
167            if exe.endswith("gpu-reader") and v.gpu_fails:
168                raise RuntimeError("cudaMalloc failed: out of memory")
169            v.proc = mock.Mock()
170            v.proc.poll.return_value = None
171            v.stopped = False
172        v.gpu_fails = False
173        v._start_reader = start_reader
174        v.close = lambda: None
175        return v
176
177    def service(self, v, elastic_engine=True):
178        tok = ByteTokenizer()
179        engine = VramEngine(tok, elastic=elastic_engine)
180        engine.loaded = True
181        svc = Service(engine, tok, ChatTemplate(ROOT / "serve/chat_template.jinja"), vision=v)
182        return svc, engine
183
184    def test_a_gpu_reader_that_does_not_start_is_the_cpu_reader_for_this_start_only(self):
185        v = self.vision(tempfile.mkdtemp())
186        v.gpu_fails = True
187        svc, engine = self.service(v)
188        svc._vision_up()
189        self.assertEqual([x.split("-")[0] for x in v.started], ["gpu", "cpu"])
190        self.assertTrue(v.on_cpu)
191        self.assertEqual(engine.calls, [2048, 0])           # the cache made room, then took it back: the CPU reader needs none
192        self.assertFalse(svc.vision_held)
193        svc.last_image_at = 0
194        self.assertEqual(svc._vision_idle_down(), "down")   # the idle stop ends the CPU reader too ...
195        self.assertEqual(engine.calls, [2048, 0])           # ... and has no VRAM to give back
196        self.assertFalse(v.on_cpu)                          # the next start tries the card again
197        v.gpu_fails = False
198        svc._vision_up()                                    # the card is tried again, and works now
199        self.assertEqual(v.started[-1].split("-")[0], "gpu")
200        self.assertFalse(v.on_cpu)
201        self.assertTrue(svc.vision_held)
202
203    def test_no_room_and_a_cache_that_cannot_shrink_goes_straight_to_the_cpu_reader(self):
204        v = self.vision(tempfile.mkdtemp())
205        svc, engine = self.service(v, elastic_engine=False)
206        svc.free_vram_mib = lambda: 900
207        out = io.StringIO()
208        with contextlib.redirect_stdout(out):
209            svc._vision_up()
210        self.assertEqual([x.split("-")[0] for x in v.started], ["cpu"])   # the card was not tried
211        self.assertIn("this picture is read on the CPU", out.getvalue())
212        self.assertFalse(svc.vision_held)
213
214    def test_room_enough_and_a_cache_that_cannot_shrink_still_tries_the_card(self):
215        v = self.vision(tempfile.mkdtemp())
216        svc, engine = self.service(v, elastic_engine=False)
217        svc.free_vram_mib = lambda: 5000
218        svc._vision_up()
219        self.assertEqual([x.split("-")[0] for x in v.started], ["gpu"])
220        svc2, _ = self.service(self.vision(tempfile.mkdtemp()), elastic_engine=False)
221        svc2.free_vram_mib = lambda: None                   # unknown: the card is tried (and the CPU reader is there if it fails)
222        svc2._vision_up()
223        self.assertEqual([x.split("-")[0] for x in svc2.vision.started], ["gpu"])
224
225    def test_a_non_elastic_gpu_reader_keeps_the_cpu_reader_for_good(self):
226        v = Vision({"exe": "gpu-reader", "mmproj": "m", "model": "t", "gpu": True, "cpu_exe": "cpu-reader"}, lazy=True)
227        started = []
228
229        def start_reader():
230            started.append(v.spawn[0][0])
231            if started[-1].endswith("gpu-reader"):
232                raise RuntimeError("no kernel image")
233        v._start_reader = start_reader
234        v._start()
235        v.unload()
236        self.assertEqual([x.split("-")[0] for x in started], ["gpu", "cpu"])
237        self.assertTrue(v.on_cpu)                           # as before: the card is not tried again
238
239    def test_pictures_already_encoded_start_no_reader(self):
240        d = Path(tempfile.mkdtemp())
241        v = self.vision(d)
242        png = bytes([0x89]) + b"PNG" + bytes([13, 10, 26, 10]) + b"rest"
243        v.dir = d
244        v.cache["k"] = (d / "x.sve", 3)
245        import hashlib
246        v.cache[hashlib.sha256(png).hexdigest()[:32]] = (d / "x.sve", 3)
247        self.assertTrue(v.all_cached([png]))
248        self.assertFalse(v.all_cached([png + b"x"]))
249        self.assertFalse(v.all_cached(["/no/such/file.png"]))   # an error is encode()'s to report
250
251
252class OnDemandByDefault(unittest.TestCase):
253    """An NVIDIA GPU reader on one GPU starts on demand without the config saying so; everything else keeps its reader as it was."""
254    BASE = {"args": ["--max-context", "8192", "--vision"], "gpu": 0,
255            "vision": {"exe": "/e/strata-vision", "mmproj": "m", "model": "t", "gpu": True, "max_tokens": 1024}}
256
257    def setUp(self):
258        # these tests describe a PC (x86); the Spark class (Linux on Arm) has its own tests below, so a test run on a Spark does not change them
259        p = mock.patch("platform.machine", return_value="x86_64")
260        p.start()
261        self.addCleanup(p.stop)
262
263    def cfg(self, **over):
264        import copy
265        c = copy.deepcopy(self.BASE)
266        for k, v in over.items():
267            if k == "vision":
268                c["vision"].update(v)
269            else:
270                c[k] = v
271        return c
272
273    def test_the_spark_class_keeps_the_reader_loaded_by_default(self):
274        """Linux on Arm with an NVIDIA GPU reader on one GPU (a DGX Spark): resident, as the AMD reader and the Mac's are (owner 2026-11-11)."""
275        import sys
276        from serve.server import apply_vision_defaults, vision_on_demand_by_default as f
277        for machine in ("aarch64", "arm64", "AARCH64"):
278            with self.subTest(machine=machine), mock.patch("platform.machine", return_value=machine), mock.patch.object(sys, "platform", "linux"):
279                self.assertFalse(f(self.cfg()))
280                c = apply_vision_defaults(self.cfg(args=["--vision", "--vram-reserve-mib", "700"]))
281                self.assertNotIn("elastic", c["vision"])                                    # no key written: the reader starts with the server
282                self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "700")   # the resident path's reserve, not 2,048
283                self.assertFalse(f(self.cfg(vision={"exe": "component:engine/strata-vision"})))
284                self.assertFalse(f(self.cfg(backend="cuda")))
285
286    def test_the_spark_class_still_takes_an_explicit_elastic_key_either_way(self):
287        import sys
288        from serve.server import apply_vision_defaults
289        with mock.patch("platform.machine", return_value="aarch64"), mock.patch.object(sys, "platform", "linux"):
290            c = apply_vision_defaults(self.cfg(vision={"elastic": True}))
291            self.assertIs(c["vision"]["elastic"], True)                                     # the old behaviour is still reachable
292            self.assertEqual(c["args"], self.BASE["args"])
293            c = apply_vision_defaults(self.cfg(vision={"elastic": False}))
294            self.assertIs(c["vision"]["elastic"], False)
295
296    def test_other_hosts_keep_the_on_demand_default(self):
297        import sys
298        from serve.server import vision_on_demand_by_default as f
299        for system, machine in (("linux", "x86_64"), ("linux", "AMD64"), ("win32", "AMD64"), ("win32", "ARM64")):    # a PC, and Windows on Arm (not this rule)
300            with self.subTest(system=system, machine=machine), mock.patch("platform.machine", return_value=machine), mock.patch.object(sys, "platform", system):
301                self.assertTrue(f(self.cfg()))
302        with mock.patch("platform.machine", return_value="arm64"), mock.patch.object(sys, "platform", "darwin"):
303            self.assertFalse(f(self.cfg()))                                                # a Mac was never on demand
304
305    def test_the_spark_class_does_not_change_the_amd_rule(self):
306        import sys
307        import serve.server as S
308        with mock.patch("platform.machine", return_value="aarch64"), mock.patch.object(sys, "platform", "linux"), \
309                mock.patch.object(S, "VISION_ON_DEMAND_AMD_BY_DEFAULT", True):
310            self.assertTrue(S.vision_on_demand_by_default(self.cfg(vision={"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision"}, backend="hip")))
311
312    def test_the_plain_nvidia_config_is_on_demand(self):
313        from serve.server import apply_vision_defaults, vision_on_demand_by_default
314        c = apply_vision_defaults(self.cfg())
315        self.assertTrue(c["vision"]["elastic"])
316        self.assertIs(c["vram_elastic"], True)                                      # owner 11-11: the cache makes the room when a picture comes
317        self.assertEqual(c["args"], self.BASE["args"])                               # ... and nothing is held back before it
318        c = apply_vision_defaults(self.cfg(args=["--vision", "--vram-reserve-mib", "700"]))
319        self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "700")    # setup's reserve stays as written
320        c = apply_vision_defaults(self.cfg(args=["--vision", "--vram-reserve-mib", "1536"]))
321        self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "1536")   # a chosen reserve is kept
322        # a config that names the shrinking cache itself keeps the old rule: the reader's room in the reserve
323        c = apply_vision_defaults(self.cfg(vram_elastic=False, args=["--vision", "--vram-reserve-mib", "700"]))
324        self.assertIs(c["vram_elastic"], False)
325        self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "2048")
326        c = apply_vision_defaults(self.cfg(vram_elastic=False))
327        self.assertEqual(c["args"][-2:], ["--vram-reserve-mib", "2048"])
328        import serve.server as S
329        with mock.patch.object(S, "VISION_NO_RESERVE_BY_DEFAULT", False):              # the switch back: the old rule everywhere
330            c = apply_vision_defaults(self.cfg(args=["--vision", "--vram-reserve-mib", "700"]))
331            self.assertNotIn("vram_elastic", c)
332            self.assertEqual(c["args"][c["args"].index("--vram-reserve-mib") + 1], "2048")
333        self.assertTrue(vision_on_demand_by_default(self.cfg(vision={"exe": "component:engine/strata-vision.exe"})))
334        self.assertTrue(vision_on_demand_by_default(self.cfg(vision={"exe": "C:/e/strata-vision.exe"})))
335        bs = chr(92)
336        self.assertTrue(vision_on_demand_by_default(self.cfg(vision={"exe": "C:" + bs + "e" + bs + "strata-vision.exe"})))
337
338    def test_the_amd_reader_with_its_cpu_reader_is_on_demand_when_asked(self):
339        import serve.server as S
340        f = S.vision_on_demand_by_default
341        amd = self.cfg(vision={"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision"}, backend="hip")
342        self.assertFalse(f(amd))                                  # off by default on AMD (no slots gained: see the constant's note)
343        with mock.patch.object(S, "VISION_ON_DEMAND_AMD_BY_DEFAULT", True):
344            self.assertTrue(f(amd))
345            got = S.apply_vision_defaults(amd)
346            self.assertTrue(got["vision"]["elastic"])
347            self.assertNotIn("vram_elastic", got)                 # AMD: no shrinking cache, the room stays in the reserve
348            self.assertEqual(got["args"][-2:], ["--vram-reserve-mib", "2048"])
349        with mock.patch.object(__import__("serve.server").server, "VISION_ON_DEMAND_AMD_BY_DEFAULT", True):
350            self.assertFalse(f(self.cfg(vision={"exe": "/e/strata-vision-hip", "cpu_exe": "/e/strata-vision"}, backend="hip", gpu=[0, 1])))
351        self.assertFalse(f(self.cfg(vision={"exe": "/e/strata-vision-sycl", "cpu_exe": "/e/strata-vision"}, backend="sycl")))
352
353    def test_what_stays_as_it_was(self):
354        from serve.server import vision_on_demand_by_default as f
355        self.assertFalse(f(self.cfg(vision={"gpu": False})))                         # the CPU reader
356        self.assertFalse(f(self.cfg(vision={"elastic": False})))                     # the person said no
357        self.assertFalse(f(self.cfg(vision={"cuda_device": 1})))                     # a reader on its own card
358        self.assertFalse(f(self.cfg(vision={"exe": "/e/strata-vision-hip"}, backend="hip")))              # AMD without its CPU reader
359        self.assertFalse(f(self.cfg(vision={"exe": "/e/strata-vision"}, backend="hip")))
360        self.assertFalse(f(self.cfg(backend="sycl", vision={"exe": "/e/strata-vision-sycl"})))
361        self.assertFalse(f(self.cfg(gpu=[0, 1])))                                     # a layer split
362        self.assertFalse(f(self.cfg(args=["--vision", "--kv-grow"])))
363        self.assertTrue(f(self.cfg(args=["--vision", "--resident-budget-gib", "30"])))   # no cache to shrink is needed
364        self.assertFalse(f(self.cfg(parallel=4)))
365        self.assertFalse(f(self.cfg(arch="deepseek41")))
366        c = self.cfg()
367        c.pop("vision")
368        self.assertFalse(f(c))
369        c = self.cfg(vision={"elastic": True})                                        # already asked for: untouched
370        from serve.server import apply_vision_defaults
371        self.assertEqual(apply_vision_defaults(c)["args"], self.BASE["args"])   # already asked for: untouched
372
373
374if __name__ == "__main__":
375    unittest.main()