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
21.0 KiB438 linesraw
1"""Data-parallel replicas (serve/replicas.py): the config, the router, and the real Service over HTTP with two fake
2engines (the fake of test_parallel.py) behind a ReplicaEngine."""
3import json
4import sys
5import tempfile
6import threading
7import time
8import unittest
9import urllib.request
10from pathlib import Path
11from unittest import mock
12
13from serve.frontend import ChatTemplate
14from serve.replicas import (BLOCK, ReplicaConfigError, ReplicaEngine, Router, cpu_sets, gpu_groups, remove_arena,
15                            replica_cfg, shared_arena_plan, sweep_stale_arenas)
16from serve.server import ByteTokenizer, Service, StrataEngine, serve
17from serve.test_parallel import FAKE_BATCH
18
19
20class Config(unittest.TestCase):
21    def test_a_number_cuts_the_gpu_list(self):
22        self.assertEqual(gpu_groups({"gpu": [0, 1, 2, 3], "replicas": 2}), [[0, 1], [2, 3]])
23        self.assertEqual(gpu_groups({"gpu": "0,1,2,3", "replicas": 4}), [[0], [1], [2], [3]])
24        self.assertEqual(gpu_groups({"gpu": [0, 1], "replicas": 1}), [])
25        self.assertEqual(gpu_groups({"gpu": [0, 1]}), [])
26
27    def test_named_groups(self):
28        self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}, {"gpus": [2]}]}), [[0, 1], [2]])
29        self.assertEqual(gpu_groups({"replicas": [{"gpus": [0, 1]}]}), [])
30
31    def test_mistakes_are_said(self):
32        for cfg in ({"gpu": [0, 1, 2], "replicas": 2}, {"replicas": 2}, {"replicas": "2"},
33                    {"replicas": [{"gpus": [0, 1]}, {"gpus": [1, 2]}]}, {"replicas": [{"gpus": []}, {"gpus": [1]}]}):
34            with self.assertRaises(ReplicaConfigError, msg=cfg):
35                gpu_groups(cfg)
36
37    def test_replica_cfg(self):
38        cfg = {"gpu": [0, 1, 2, 3], "args": ["--x"], "log": "/l/strata.log", "hip_ordinal": 1, "env": {"A": "1"},
39               "expert_profile_save": "/p/prof.bin",
40               "replicas": [{"gpus": [0, 1], "env": {"B": 2}}, {"gpus": [2, 3], "args": ["--y"]}]}
41        a, b = replica_cfg(cfg, 0, [0, 1]), replica_cfg(cfg, 1, [2, 3])
42        self.assertEqual((a["gpu"], b["gpu"]), ([0, 1], [2, 3]))
43        self.assertEqual((a["log"], b["log"]), ("/l/strata.r0.log", "/l/strata.r1.log"))
44        self.assertEqual(a["env"], {"A": "1", "B": "2"})
45        self.assertEqual(b["args"], ["--x", "--y"])
46        self.assertNotIn("replicas", a)
47        self.assertNotIn("hip_ordinal", a)
48        self.assertEqual(a["expert_profile_save"], "/p/prof.r0.bin")
49        self.assertEqual(cfg["args"], ["--x"])                       # the original is untouched
50        self.assertEqual(replica_cfg({"gpu": [0, 1], "args": []}, 0, [3])["gpu"], 3)
51
52    def test_cpu_sets_off(self):
53        self.assertIsNone(cpu_sets(2, enabled=False))
54        self.assertIsNone(cpu_sets(1))
55
56
57class Routing(unittest.TestCase):
58    def test_matched_prefix_per_replica(self):
59        r = Router(3)
60        a = list(range(BLOCK * 4))
61        r.note(0, a)
62        r.note(1, a[:BLOCK * 2])
63        self.assertEqual(r.matched(a + [9] * 70), [BLOCK * 4, BLOCK * 2, 0])
64        self.assertEqual(r.matched([7] * 200), [0, 0, 0])
65        r.forget(0)
66        self.assertEqual(r.matched(a), [0, BLOCK * 2, 0])
67
68    def test_the_index_is_bounded(self):
69        r = Router(2, cap=10)
70        for i in range(50):
71            r.note(i % 2, [i] * (BLOCK * 2))
72        self.assertLessEqual(len(r.blocks), 10)
73
74
75class FakeEngine:
76    def __init__(self, n=4):
77        self.batch, self.up = n, True
78        self.max_context = 4096
79        self.info = {}
80        self.last = {}
81
82    def alive(self):
83        return self.up
84
85    def generate(self, ids, max_new, sampling, cancel, embeddings=None):
86        yield 7
87
88
89class RouteChoice(unittest.TestCase):
90    def test_least_loaded_then_affinity(self):
91        e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
92        picks = [e.route([i] * 100) for i in range(4)]             # nothing cached: spread
93        self.assertEqual(sorted(picks), [0, 0, 1, 1])
94        ids = list(range(BLOCK * 8))
95        e.inflight = [0, 0]
96        k = e.route(ids)
97        e.router.note(k, ids)
98        e.inflight = [0, 0]
99        self.assertEqual(e.route(ids + [5] * 10), k)                # the conversation goes back
100        e.inflight = [0, 0]
101        e.inflight[k] = 1                                           # 512 tokens held < 3000 per running request
102        self.assertNotEqual(e.route(ids + [5] * 10), k)
103
104    def test_a_long_prefix_outweighs_load(self):
105        e = ReplicaEngine([FakeEngine(), FakeEngine()], load_tokens=3000)
106        ids = list(range(BLOCK * 200))                              # 12,800 tokens held on replica 0
107        e.router.note(0, ids)
108        e.inflight = [2, 0]
109        self.assertEqual(e.route(ids + [1]), 0)
110        e.inflight = [5, 0]
111        self.assertEqual(e.route(ids + [1]), 1)
112
113    def test_a_dead_replica_is_skipped(self):
114        a, b = FakeEngine(), FakeEngine()
115        e = ReplicaEngine([a, b])
116        e.heal = lambda: None
117        ids = list(range(BLOCK * 3))
118        e.router.note(0, ids)
119        a.up = False
120        self.assertEqual(e.route(ids), 1)
121        b.up = False
122        self.assertEqual(e.route(ids), -1)
123
124    def test_nonfinite_forgets_the_replica(self):
125        """#879: after DONE ... nonfinite the engine holds no conversation: the router forgets that replica."""
126        from serve.server import EngineNonFinite
127
128        class NonFinite(FakeEngine):
129            def generate(self, ids, max_new, sampling, cancel):
130                yield 7
131                raise EngineNonFinite("the engine's logits became non-finite (#879)")
132
133        e = ReplicaEngine([NonFinite(), NonFinite()])
134        other, ids = [9] * (BLOCK * 4), list(range(BLOCK * 3))
135        e.router.note(0, other)
136        e.router.note(1, other)
137        k = 0
138        e.inflight[k] += 1                                          # as route() counts it
139        with mock.patch.object(e, "route", return_value=k):
140            with self.assertRaises(EngineNonFinite):
141                list(e.generate(ids, 10, {}, threading.Event()))
142        self.assertEqual(e.router.matched(ids)[k], 0)
143        self.assertEqual(e.router.matched(other)[k], 0)             # its older conversations too
144        self.assertEqual(e.router.matched(other)[1 - k], len(other))
145        self.assertEqual(e.inflight[k], 0)
146
147    def test_batch_is_the_sum(self):
148        self.assertEqual(ReplicaEngine([FakeEngine(4), FakeEngine(4)]).batch, 8)
149        self.assertEqual(ReplicaEngine([FakeEngine(0), FakeEngine(0)]).batch, 2)
150
151    def test_selected_replica_is_reported_for_solo_requests_too(self):
152        engine = ReplicaEngine([FakeEngine(), FakeEngine()])
153        engine.inflight[0] = 1
154        cancel = threading.Event()
155        selected = []
156        cancel._strata_replica_selected = selected.append
157        self.assertEqual(list(engine.generate([1, 2], 1, {}, cancel)), [7])
158        self.assertEqual(selected, [1])
159
160
161class ReplicaService(unittest.TestCase):
162    def start(self, slots=4, n=2):
163        import serve.server as server
164        self.tmp = tempfile.TemporaryDirectory()
165        script = Path(self.tmp.name) / "fake_strata.py"
166        script.write_text(FAKE_BATCH, encoding="utf-8")
167        real = server.subprocess.Popen
168        self.logs = [Path(self.tmp.name) / f"r{i}.log" for i in range(n)]
169        engines = []
170        for i in range(n):
171            extra = (["--batch", str(slots)] if slots else []) + ["--log", str(self.logs[i])]
172            with mock.patch.object(server.subprocess, "Popen",
173                                   lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
174                engines.append(StrataEngine("strata", extra))
175        self.engine = ReplicaEngine(engines)
176        self.svc = Service(self.engine, ByteTokenizer(), ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
177        self.httpd = serve(self.svc, port=0)
178        self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
179
180    def tearDown(self):
181        if getattr(self, "httpd", None):
182            self.httpd.shutdown()
183            self.httpd.server_close()
184        if getattr(self, "engine", None):
185            self.engine.unload()
186        if getattr(self, "tmp", None):
187            self.tmp.cleanup()
188
189    def post(self, messages, max_tokens=64):
190        body = {"messages": messages, "max_tokens": max_tokens, "reasoning_effort": "none"}
191        req = urllib.request.Request(self.base + "/v1/chat/completions", data=json.dumps(body).encode(),
192                                     headers={"Content-Type": "application/json"})
193        with urllib.request.urlopen(req, timeout=60) as r:
194            return json.loads(r.read().decode())["choices"][0]["message"]["content"]
195
196    def chat(self, text, max_tokens=64):
197        return self.post([{"role": "user", "content": text}], max_tokens)
198
199    def served(self):
200        return [sum(1 for l in p.read_text().splitlines() if l.split()[0] in ("GEN", "BGEN")) if p.exists() else 0
201                for p in self.logs]
202
203    def burst(self, prompts):
204        out = [None] * len(prompts)
205
206        def one(i):
207            out[i] = self.chat(prompts[i])
208        ts = [threading.Thread(target=one, args=(i,)) for i in range(len(prompts))]
209        for t in ts:
210            t.start()
211        for t in ts:
212            t.join()
213        return out
214
215    def test_requests_spread_over_both_and_answers_are_the_solo_answer(self):
216        self.start()
217        solo = self.chat("hello there")
218        before = self.served()
219        out = self.burst([f"request number {i} " + "x" * 300 for i in range(6)])
220        got = [b - a for a, b in zip(before, self.served())]
221        self.assertTrue(all(g >= 2 for g in got), got)
222        self.assertEqual(set(out), {solo})
223
224    def test_metrics_and_status_see_all_slots(self):
225        self.start()
226        self.assertEqual(self.svc.v1_status()["concurrency"]["serving"], 8)
227        m = self.svc.metrics()
228        self.assertEqual(len(m["live"]["slots"]), 8)
229        self.assertEqual([r["replica"] for r in m["live"]["replicas"]], [0, 1])
230        self.assertEqual(m["engine"]["replicas"], 2)
231
232    def test_terminal_telemetry_correlates_second_replica_without_global_sample_claim(self):
233        self.start()
234        self.svc.replica_gpu_groups = [[0, 1], [2, 3]]
235        second = self.engine.engines[1]
236        request_id = "abcdef012345"
237        second.slot_live[1] = {"request_id": request_id, "state": "reading", "prompt_tokens": 100,
238                               "prompt_read": 12, "generated": 0, "started": time.time(), "first_token": None}
239        first = self.engine.engines[0]
240        first.terminal_batch_sample = {"windows": 2, "processed_rows": 8, "active_rows": 4,
241                                       "elapsed_ms": 1000, "observed_monotonic": time.monotonic()}
242        second.terminal_batch_sample = {"windows": 2, "processed_rows": 6, "active_rows": 4,
243                                        "elapsed_ms": 1000, "observed_monotonic": time.monotonic()}
244        first.terminal_stage_sample = {"elapsed_us": 1_000_000, "in_flight_us": [800_000, 600_000],
245                                       "observed_monotonic": time.monotonic()}
246        second.terminal_stage_sample = {"elapsed_us": 1_000_000, "in_flight_us": [700_000, 500_000],
247                                        "observed_monotonic": time.monotonic()}
248        self.svc.backend = "cuda"
249        for child, cards in ((first, [0, 1]), (second, [2, 3])):
250            child.spawn = (*child.spawn[:4], {"CUDA_DEVICE_ORDER": "PCI_BUS_ID",
251                                              "CUDA_VISIBLE_DEVICES": ",".join(map(str, cards))},
252                           *child.spawn[5:])
253            child.terminal_stages = [
254                {"stage": 0, "layer_start": 0, "layer_end": 19, "engine_ordinal": 0},
255                {"stage": 1, "layer_start": 20, "layer_end": 39, "engine_ordinal": 1}]
256        with self.svc.status_lock:
257            self.svc.terminal_requests[request_id] = {"id": request_id, "state": "waiting",
258                                                       "queued_at": time.time(), "admitted_at": time.time(),
259                                                       "prompt_tokens": 100}
260        with urllib.request.urlopen(self.base + "/v1/telemetry", timeout=10) as response:
261            snapshot = json.load(response)
262        slot = snapshot["work"]["slots"][5]
263        self.assertEqual((slot["slot"], slot["replica"], slot["group"], slot["request_id"]),
264                         (5, 1, 1, request_id))
265        request = snapshot["work"]["requests"][0]
266        self.assertEqual((request["slot"], request["replica"], request["group"], request["state"]),
267                         (5, 1, 1, "reading"))
268        self.assertEqual(snapshot["work"]["groups"], 2)
269        self.assertIsNone(snapshot["work"]["effective_rows_window"])
270        self.assertEqual([(row["replica"], row["batch_sample_rows"], row["batch_sample_active_rows"])
271                          for row in snapshot["work"]["replica_batches"]], [(0, 8, 4), (1, 6, 4)])
272        self.assertEqual([(row["replica"], row["stage_in_flight_us"])
273                          for row in snapshot["work"]["replica_stage_samples"]],
274                         [(0, [800_000, 600_000]), (1, [700_000, 500_000])])
275        self.assertNotIn("stage_in_flight_us", snapshot["work"])
276        self.assertEqual(snapshot["topology"]["stages"], [])
277        self.assertEqual(snapshot["topology"]["replica_stages"][1]["stages"][1]["device_index"], 3)
278        self.assertEqual(snapshot["topology"]["replica_devices"],
279                         [{"replica": 0, "devices": [0, 1]}, {"replica": 1, "devices": [2, 3]}])
280        second.spawn = (*second.spawn[:4], {"CUDA_DEVICE_ORDER": "PCI_BUS_ID",
281                                            "CUDA_VISIBLE_DEVICES": "9,3"}, *second.spawn[5:])
282        with urllib.request.urlopen(self.base + "/v1/telemetry", timeout=10) as response:
283            mismatch = json.load(response)
284        self.assertIsNone(mismatch["topology"]["replica_stages"][1]["stages"][0]["device_index"])
285        self.assertEqual(mismatch["topology"]["replica_stages"][1]["stages"][1]["device_index"], 3)
286
287    def test_engines_without_slots_run_one_each_at_once(self):
288        self.start(slots=0)
289        out = self.burst(["a" * 40, "b" * 40])
290        self.assertEqual(self.served(), [1, 1])
291        self.assertEqual(len(set(out)), 1)
292
293    def test_a_conversation_goes_back_to_its_replica(self):
294        self.start()
295        first = "begin " + "lorem ipsum " * 40
296        reply = self.chat(first)
297        k = self.served().index(1)
298        self.post([{"role": "user", "content": first}, {"role": "assistant", "content": reply},
299                   {"role": "user", "content": "and then?"}], 16)
300        self.assertEqual(self.served()[k], 2)
301
302    def test_a_replica_that_died_is_skipped(self):
303        self.start()
304        self.engine.heal = lambda: None
305        self.engine.engines[0].proc.kill()
306        self.engine.engines[0].proc.wait()
307        self.assertTrue(self.engine.alive())
308        for i in range(3):
309            self.assertIn("ok, done.", self.chat(f"after the loss {i}"))
310        self.assertEqual(self.served()[1], 3)
311
312
313class SharedArena(unittest.TestCase):
314    """The opt-in shared expert arena of the replicas (shared_arena_plan): when it is used, when it is not, what a stale
315    file means."""
316    CFG = {"replica_shared_arena": True, "args": ["--pack", "/p"], "gpu": [0, 1]}
317
318    def plan(self, cfg=None, n=2, tmp=None, **kw):
319        return shared_arena_plan(cfg or self.CFG, n, shm=tmp, platform=kw.pop("platform", "linux"),
320                                 environ=kw.pop("environ", {}), free_bytes=kw.pop("free_bytes", 100 << 30),
321                                 use_memfd=kw.pop("use_memfd", False), **kw)
322
323    def test_off_by_default_and_for_one_engine(self):
324        with tempfile.TemporaryDirectory() as d:
325            self.assertEqual(self.plan({"args": []}, tmp=d), (None, ""))
326            self.assertEqual(self.plan(n=1, tmp=d), (None, ""))
327            self.assertEqual(self.plan({"args": []}, tmp=d, environ={"STRATA_REPLICA_SHARED_ARENA": "0"}), (None, ""))
328
329    def test_on_by_config_or_environment(self):
330        with tempfile.TemporaryDirectory() as d:
331            path, note = self.plan(tmp=d)
332            self.assertTrue(path and path.startswith(d) and path.endswith(".bin"), path)
333            self.assertIn("once", note)
334            path2, _ = self.plan({"args": []}, tmp=d, environ={"STRATA_REPLICA_SHARED_ARENA": "1"})
335            self.assertTrue(path2)
336            self.assertEqual(path, path2)      # (one server: one file)
337
338    def test_windows_gets_a_named_section(self):
339        with tempfile.TemporaryDirectory() as d:
340            path, note = self.plan(tmp=d, platform="win32")
341            self.assertTrue(path and path.startswith("win:Local") and "strata-replicas-" in path, path)
342            self.assertIn("Windows section", note)
343            remove_arena(path)                 # (nothing to remove: harmless)
344
345    def test_only_where_there_is_an_arena_to_share(self):
346        with tempfile.TemporaryDirectory() as d:
347            self.assertIsNone(self.plan(tmp=d, platform="darwin")[0])
348            for flag in ("--mmap-experts", "--resident-experts", "--resident-budget-gib", "--shared-expert-arena"):
349                self.assertIsNone(self.plan({**self.CFG, "args": ["--pack", "/p", flag]}, tmp=d)[0], flag)
350            self.assertIsNone(self.plan({**self.CFG, "replicas": [{"gpus": [0], "args": ["--mmap-experts"]}, {"gpus": [1]}]}, tmp=d)[0])
351            self.assertIsNone(self.plan({**self.CFG, "arch": "deepseek41"}, tmp=d)[0])
352
353    def test_no_room_or_no_shm_says_so_and_falls_back(self):
354        with tempfile.TemporaryDirectory() as d:
355            path, note = self.plan(tmp=d, free_bytes=2 << 30)
356            self.assertIsNone(path)
357            self.assertIn("2.0 GiB free", note)
358            path, note = self.plan(tmp=d + "/nope")
359            self.assertIsNone(path)
360            self.assertIn("not usable", note)
361
362    def test_a_stale_file_goes_a_live_one_stays(self):
363        with tempfile.TemporaryDirectory() as d:
364            uid = __import__("os").getuid() if hasattr(__import__("os"), "getuid") else 0
365            dead = Path(d) / f"strata-replicas-{uid}-2999999.bin"
366            live = Path(d) / f"strata-replicas-{uid}-{__import__('os').getpid()}.bin"
367            other = Path(d) / f"strata-replicas-{uid + 1}-2999999.bin"
368            junk = Path(d) / "strata-replicas-x.bin"
369            for f in (dead, live, other, junk):
370                f.write_bytes(b"x")
371            with mock.patch("serve.replicas._pid_alive", side_effect=lambda pid: pid != 2999999):
372                gone = sweep_stale_arenas(d, uid)
373            self.assertEqual(gone, [dead.name])
374            self.assertFalse(dead.exists())
375            self.assertTrue(live.exists() and other.exists() and junk.exists())
376
377    @unittest.skipUnless(hasattr(__import__("os"), "memfd_create") and sys.platform.startswith("linux"), "Linux memfd")
378    def test_a_memfd_is_not_limited_by_dev_shm_and_is_closed_at_the_end(self):
379        import os
380        path, note = shared_arena_plan(self.CFG, 2, platform="linux", environ={}, free_bytes=100 << 30, use_memfd=True)
381        self.assertTrue(path and path.startswith(f"/proc/{os.getpid()}/fd/"), path)
382        fd = int(path.rsplit("/", 1)[1])
383        os.ftruncate(fd, 1 << 20)
384        self.assertEqual(os.fstat(fd).st_size, 1 << 20)
385        with open(path, "r+b") as other:          # (how an engine opens it)
386            other.seek(100)
387            other.write(b"x")
388        remove_arena(path)
389        with self.assertRaises(OSError):
390            os.fstat(fd)
391        remove_arena(path)                         # (twice: harmless)
392
393    @unittest.skipUnless(hasattr(__import__("os"), "memfd_create") and sys.platform.startswith("linux"), "Linux memfd")
394    def test_a_memfd_arena_warns_when_the_engines_will_not_all_fit(self):
395        cfg = {**self.CFG, "model_name": "qwen3.8-flash-next-iq3_s"}
396        path, note = shared_arena_plan(cfg, 2, platform="linux", environ={}, free_bytes=57 << 30, use_memfd=True)
397        try:
398            self.assertTrue(path)
399            self.assertIn("WARNING", note)
400            self.assertIn("may not fit", note)
401        finally:
402            remove_arena(path)
403        path, note = shared_arena_plan(cfg, 2, platform="linux", environ={}, free_bytes=120 << 30, use_memfd=True)
404        try:
405            self.assertNotIn("WARNING", note)
406        finally:
407            remove_arena(path)
408
409    def test_a_memfd_needs_free_ram(self):
410        path, note = shared_arena_plan(self.CFG, 2, platform="linux", environ={}, free_bytes=2 << 30, use_memfd=True)
411        self.assertIsNone(path)
412        self.assertIn("2.0 GiB of RAM", note)
413
414    def test_removing_twice_or_nothing_is_harmless(self):
415        with tempfile.TemporaryDirectory() as d:
416            f = Path(d) / "a.bin"
417            f.write_bytes(b"x")
418            remove_arena(str(f))
419            remove_arena(str(f))
420            remove_arena(None)
421            self.assertFalse(f.exists())
422
423    def test_the_replica_engine_unlinks_the_file_at_close(self):
424        with tempfile.TemporaryDirectory() as d:
425            f = Path(d) / "a.bin"
426            f.write_bytes(b"x")
427
428            class E:
429                def close(self):
430                    pass
431            r = ReplicaEngine([E(), E()])
432            r.__dict__["arena_file"] = str(f)
433            r.close()
434            self.assertFalse(f.exists())
435
436
437if __name__ == "__main__":
438    unittest.main()