okami.mom/strata

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

Niko1221Merge f-027-split: split serving (#4000), opt-in, first versionccf18ea14

main
12.5 KiB271 linesraw
1"""Split serving (serve/split.py): the config, the decision, the hand-over with two fake engines, and every fallback.
2The engine-side proof (the continuation after a hand-over equals a single engine's) is tests/split_serve_exact.py."""
3import os
4import tempfile
5import threading
6import unittest
7
8from serve import split as sp
9from serve.server import EngineDied, SessionRefused
10from serve.split import SplitConfigError, SplitEngine, check_cfg, common_prefix, role_cfg, split_spec
11
12
13class Config(unittest.TestCase):
14    def test_off_without_the_key(self):
15        self.assertIsNone(split_spec({}))
16        self.assertIsNone(split_spec({"split_serve": False}))
17        self.assertIsNone(split_spec({"split_serve": None}))
18
19    def test_cards_and_defaults(self):
20        s = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": "1"}})
21        self.assertEqual((s["prefill_gpu"], s["decode_gpu"]), (0, 1))
22        self.assertEqual(s["min_prompt_tokens"], sp.MIN_TOKENS)
23        self.assertIs(s["shared_arena"], True)
24        self.assertEqual((s["prefill_args"], s["decode_args"]), ([], []))
25
26    def test_mistakes_are_said(self):
27        bad = [{"split_serve": 1}, {"split_serve": {"prefill_gpu": 0}}, {"split_serve": {"prefill_gpu": 1, "decode_gpu": 1}},
28               {"split_serve": {"prefill_gpu": 0, "decode_gpu": -1}}, {"split_serve": {"prefill_gpu": True, "decode_gpu": 1}},
29               {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "x": 1}},
30               {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "min_prompt_tokens": "9"}},
31               {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "prefill_args": "--x"}},
32               {"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": 3}}]
33        for cfg in bad:
34            with self.assertRaises(SplitConfigError, msg=cfg):
35                split_spec(cfg)
36
37    def test_check_cfg_refuses_what_cannot_run(self):
38        spec = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1}})
39        check_cfg({"args": ["--serve", "--prompt-cache", "3"]}, spec)
40        for cfg in ({"args": ["--layer-split", "24"]}, {"args": ["--batch", "2"]}, {"args": ["--prompt-cache", "0"]},
41                    {"args": [], "replicas": 2}, {"args": [], "parallel": 2}, {"args": ["--peer-device", "1"]}):
42            with self.assertRaises(SplitConfigError, msg=cfg):
43                check_cfg(cfg, spec)
44        spec2 = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "decode_args": ["--batch", "2"]}})
45        with self.assertRaises(SplitConfigError):
46            check_cfg({"args": []}, spec2)
47
48    def test_role_cfg(self):
49        cfg = {"gpu": [0, 1], "args": ["--x"], "log": "/l/strata.log", "hip_ordinal": 1, "gpu_roles": {"0": "main"},
50               "expert_profile_save": "/p/prof.bin",
51               "split_serve": {"prefill_gpu": 2, "decode_gpu": 3, "decode_args": ["--expert-cache", "auto"]}}
52        spec = split_spec(cfg)
53        p, d = role_cfg(cfg, spec, "prefill"), role_cfg(cfg, spec, "decode")
54        self.assertEqual((p["gpu"], d["gpu"]), (2, 3))
55        self.assertEqual((p["log"], d["log"]), ("/l/strata.prefill.log", "/l/strata.decode.log"))
56        self.assertEqual(p["args"], ["--x"])
57        self.assertEqual(d["args"], ["--x", "--expert-cache", "auto"])
58        self.assertEqual(d["expert_profile_save"], "/p/prof.decode.bin")
59        for c in (p, d):
60            self.assertNotIn("split_serve", c)
61            self.assertNotIn("hip_ordinal", c)
62            self.assertNotIn("gpu_roles", c)
63        self.assertEqual(cfg["args"], ["--x"])                       # the original is untouched
64
65    def test_arena_choice(self):
66        spec = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1}})
67        off = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": False}})
68        named = split_spec({"split_serve": {"prefill_gpu": 0, "decode_gpu": 1, "shared_arena": "/data/a.bin"}})
69        self.assertIsNone(sp.arena_path({"args": ["--shared-expert-arena", "/x"]}, spec)[0])
70        self.assertIsNone(sp.arena_path({"args": []}, off)[0])
71        if os.name != "nt":
72            self.assertEqual(sp.arena_path({"args": []}, named)[0], os.path.abspath("/data/a.bin"))
73            path, note = sp.arena_path({"args": ["--pack", "/no/such/pack"]}, spec)      # nothing to size it from
74            self.assertIsNone(path)
75            self.assertIn("experts.bin", note)
76
77    def test_common_prefix(self):
78        self.assertEqual(common_prefix([1, 2, 3], [1, 2, 9, 4]), 2)
79        self.assertEqual(common_prefix([], [1]), 0)
80        self.assertEqual(common_prefix([1, 2], [1, 2]), 2)
81
82
83class FakeEngine:
84    """The part of StrataEngine the SplitEngine uses.  `session` is the token list its session holds (a file is a json-free
85    list in a dict keyed by path, shared between the two fakes)."""
86    files = {}
87
88    def __init__(self, name, tokens_per_answer=3):
89        self.name, self.up, self.max_context, self.info, self.last = name, True, 4096, {}, {}
90        self.session, self.log, self.progress, self.prefill_tok_s_mean = [], [], None, None
91        self.answer = tokens_per_answer
92        self.fail_save = self.fail_restore = self.fail_prefill = None
93        self.unloaded = False
94
95    def alive(self):
96        return self.up
97
98    def restart(self, tries=3):
99        self.up = True
100
101    def exit_code(self):
102        return None
103
104    def death_note(self):
105        return ""
106
107    def unload(self):
108        self.up = False
109
110    def close(self):
111        self.up = False
112
113    def generate(self, ids, max_new, sampling, cancel, embeddings=None, prefill_only=False):
114        if not self.up:
115            raise EngineDied("down")
116        if prefill_only:
117            if self.fail_prefill:
118                raise self.fail_prefill
119            have = common_prefix(self.session, ids[:-1])
120            self.log.append(("prefill", len(ids)))
121            self.session = list(ids[:-1])
122            self.last = {"generated": 0, "prompt_tokens": len(ids), "prompt_ms": 1000.0, "decode_ms": 0.0,
123                         "finish": "length", "reused": have, "prompt_read": len(ids) - have}
124            yield None
125            return
126        have = common_prefix(self.session, ids[:-1])
127        out = [100 + i for i in range(min(max_new, self.answer))]
128        self.log.append(("generate", len(ids), have))
129        self.session = list(ids) + out[:-1]
130        self.last = {"generated": len(out), "prompt_tokens": len(ids), "prompt_ms": 50.0, "decode_ms": 200.0,
131                     "finish": "length", "reused": have, "prompt_read": len(ids) - have}
132        for t in out:
133            yield t
134
135    def session_file(self, action, path):
136        if action == "save":
137            if self.fail_save:
138                raise self.fail_save
139            FakeEngine.files[path] = list(self.session)
140            with open(path, "wb") as f:
141                f.write(b"x" * 1000)
142            return {"tokens": len(self.session), "bytes": 1000, "ms": 12.0}
143        if self.fail_restore:
144            raise self.fail_restore
145        self.session = list(FakeEngine.files[path])
146        return {"tokens": len(self.session), "bytes": 1000, "ms": 7.0}
147
148
149class Handover(unittest.TestCase):
150    def setUp(self):
151        FakeEngine.files = {}
152        self.dir = tempfile.mkdtemp(prefix="split-test-")
153        self.p, self.d = FakeEngine("p"), FakeEngine("d")
154        self.said = []
155        self.e = SplitEngine(self.p, self.d, min_tokens=100, work_dir=self.dir, say=self.said.append)
156        self.cancel = threading.Event()
157
158    def run_one(self, ids, max_new=5):
159        return [t for t in self.e.generate(ids, max_new, {}, self.cancel) if t is not None]
160
161    def test_a_long_prompt_is_handed_over(self):
162        ids = list(range(500))
163        out = self.run_one(ids)
164        self.assertEqual(out, [100, 101, 102])
165        self.assertEqual(self.p.log, [("prefill", 500)])
166        self.assertEqual(self.d.log, [("generate", 500, 499)])         # the decode engine read one token itself
167        self.assertEqual(self.e.stats["handed_over"], 1)
168        self.assertEqual(os.listdir(self.dir), [])                      # the session file is gone
169        last = self.e.last
170        self.assertEqual(last["reused"], 0)
171        self.assertEqual(last["prompt_read"], 500)                     # 499 read by the prefill engine, 1 by the decode one... 500
172        self.assertGreaterEqual(last["prompt_ms"], 12.0 + 7.0 + 50.0)                  # the file steps and the decode engine's start
173        self.assertLess(last["prompt_ms"], 12.0 + 7.0 + 50.0 + 1000.0)
174        self.assertEqual(last["split_bytes"], 1000)
175
176    def test_a_short_prompt_stays_on_the_decode_engine(self):
177        self.run_one(list(range(50)))
178        self.assertEqual(self.p.log, [])
179        self.assertEqual(self.e.stats["short"], 1)
180
181    def test_the_next_turn_is_not_handed_over_when_the_decode_engine_holds_it(self):
182        ids = list(range(500))
183        out = self.run_one(ids)
184        turn2 = ids + out + list(range(7000, 7040))                      # the answer and a short question
185        self.run_one(turn2)
186        self.assertEqual(len(self.p.log), 1)                            # only the first turn went through the prefill engine
187        self.assertEqual(self.d.log[-1][0], "generate")
188        self.assertGreater(self.d.log[-1][2], 490)                      # and the decode engine continued its own session
189
190    def test_a_big_new_part_is_handed_over_again(self):
191        ids = list(range(500))
192        out = self.run_one(ids)
193        self.run_one(ids + out + list(range(9000, 9400)))
194        self.assertEqual(len(self.p.log), 2)
195
196    def test_pictures_go_to_the_decode_engine(self):
197        list(self.e.generate(list(range(500)), 3, {}, self.cancel, embeddings="/tmp/x"))
198        self.assertEqual(self.p.log, [])
199
200    def test_a_dead_prefill_engine_is_not_an_error(self):
201        self.p.up = False
202        self.e.heal = lambda: None
203        out = self.run_one(list(range(500)))
204        self.assertEqual(out, [100, 101, 102])
205        self.assertEqual(self.d.log, [("generate", 500, 0)])            # the decode engine read all of it
206
207    def test_a_prefill_engine_that_dies_midway_falls_back(self):
208        self.p.fail_prefill = EngineDied("gone")
209        self.e.heal = lambda: None
210        out = self.run_one(list(range(500)))
211        self.assertEqual(out, [100, 101, 102])
212        self.assertEqual(self.d.log, [("generate", 500, 0)])
213        self.assertTrue(any("failed" in s for s in self.said))
214
215    def test_a_refused_file_falls_back(self):
216        for which in ("fail_save", "fail_restore"):
217            FakeEngine.files = {}
218            self.p.session, self.d.session = [], []
219            setattr(self.p if which == "fail_save" else self.d, which, SessionRefused("invalid", "other model", False))
220            self.d.log.clear()
221            ids = list(range(500)) if which == "fail_save" else list(range(1000, 1500))
222            out = self.run_one(ids)
223            self.assertEqual(out, [100, 101, 102])
224            self.assertEqual(self.d.log, [("generate", 500, 0)], which)
225            setattr(self.p if which == "fail_save" else self.d, which, None)
226        self.assertEqual(self.e.stats["fallbacks"], 2)
227        self.assertEqual(os.listdir(self.dir), [])
228
229    def test_a_decode_engine_that_dies_in_the_restore_is_an_error(self):
230        def boom(*a):
231            self.d.up = False
232            raise EngineDied("transfer failed")
233        self.d.fail_restore = None
234        orig = self.d.session_file
235        self.d.session_file = lambda action, path: boom() if action == "restore" else orig(action, path)
236        with self.assertRaises(EngineDied):
237            self.run_one(list(range(500)))
238        self.assertEqual(os.listdir(self.dir), [])
239
240    def test_cancel_during_the_prefill_ends_quietly(self):
241        self.cancel.set()
242        orig = self.p.generate
243
244        def gen(*a, **k):
245            for t in orig(*a, **k):
246                yield t
247        self.p.generate = gen
248        out = self.run_one(list(range(500)))
249        self.assertEqual(out, [])
250        self.assertEqual(self.d.log, [])
251        self.assertEqual(self.e.held, [])
252
253    def test_attributes_come_from_the_decode_engine(self):
254        self.assertEqual(self.e.max_context, 4096)
255        self.assertEqual(self.e.batch, 0)
256        self.assertFalse(hasattr(self.e, "session_file"))
257        self.assertTrue(self.e.alive())
258        self.d.up = False
259        self.assertFalse(self.e.alive())
260        self.assertTrue(self.e.info["split_serve"])
261        self.e.silence_s = 5
262        self.assertEqual((self.p.silence_s, self.d.silence_s), (5, 5))
263
264    def test_close_removes_the_work_dir(self):
265        self.e.close()
266        self.assertFalse(os.path.exists(self.dir))
267        self.assertFalse(self.p.up or self.d.up)
268
269
270if __name__ == "__main__":
271    unittest.main()