okami.mom/strata

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

waveringanaserve: restore the DeepSeek V4.1 server paths, tools and headers removed upstream, keeping the native picture tower firstba8745e13

main
9.8 KiB235 linesraw
1"""DeepSeek --parallel (Project Maya #332, mw00): several conversations in one engine, the server's side.
2
3A fake engine (a Python script speaking maya-ds4's multi protocol: READY ... multi=N, GEN ... rid=<id>, then
4`T <rid> <id>`, `PP <rid> ...`, `DONE <rid> ...`, STOP <rid>) runs behind the real StrataEngine and Service, so the
5server's half is tested without a GPU: requests up to N run at once on their own queues, a request that leaves
6is STOPped alone, one at a time (no multi=) is the old path, and "parallel": N in the config becomes --parallel N for
7DeepSeek only.
8
9    python -m unittest serve.test_ds_parallel -v
10"""
11import json
12import sys
13import tempfile
14import threading
15import time
16import unittest
17import urllib.request
18from pathlib import Path
19from unittest import mock
20
21from serve import server
22from serve.frontend import ChatTemplate
23from serve.server import ByteTokenizer, Service, StrataEngine, parallel_args, serve
24
25# One token every STEP seconds per active request (a multi step serves every active request at once).  A request's
26# reply is the byte of its first prompt id six times, then 257 (<|im_end|> in the ByteTokenizer), or "ok, done." then
27# 257 for a longer prompt (a chat's).
28FAKE_DS = r'''import os, queue, sys, threading, time
29args = sys.argv[1:]
30n = int(args[args.index("--parallel") + 1]) if "--parallel" in args else 1
31n = min(n, int(os.environ.get("FAKE_CAP", "99")))   # (the engine runs fewer when the cards hold fewer)
32log = open(args[args.index("--log") + 1], "a") if "--log" in args else None
33STEP = 0.03
34lines = queue.Queue()
35stopped, stop_all = set(), threading.Event()
36def reader():
37    for l in sys.stdin:
38        l = l.strip()
39        if log: log.write(l[:60] + "\n"); log.flush()
40        if l == "STOP":
41            stop_all.set()
42        elif l.startswith("STOP "):
43            stopped.add(int(l.split()[1]))
44        else:
45            lines.put(l)
46    lines.put(None)
47threading.Thread(target=reader, daemon=True).start()
48print("INFO engine=0.1.50", flush=True)
49print("READY 4096 stop" + (f" multi={n}" if n > 1 else ""), flush=True)
50active = {}    # rid -> [tokens left, produced, max_new, ids, t0]
51def admit(l):
52    f = l.split(" ")
53    rid = next(int(x[4:]) for x in f if x.startswith("rid="))
54    ids = [int(x) for x in f[-1].split(",")]
55    max_new = int(f[1])
56    rep = list(b"ok, done.") + [257] if len(ids) > 10 else [ids[0]] * 6 + [257]
57    print(f"PP {rid} {len(ids)} {len(ids)} 1.0 1000.0 0", flush=True)
58    active[rid] = [rep, 0, max_new, ids, time.time()]
59def step():
60    for rid in sorted(active):
61        left, produced, max_new, ids, t0 = active[rid]
62        if rid in stopped or stop_all.is_set():
63            print(f"DONE {rid} {produced} {len(ids)} 1.0 1.0 cancel 0 0 0 0 0", flush=True)
64            stopped.discard(rid)
65            del active[rid]
66            continue
67        t = left.pop(0)
68        produced += 1
69        print(f"T {rid} {t}", flush=True)
70        if t == 257 or produced >= max_new:
71            print(f"DONE {rid} {produced} {len(ids)} 1.0 1.0 {'stop' if t == 257 else 'length'} 0 0 0 0 0", flush=True)
72            del active[rid]
73        else:
74            active[rid][1] = produced
75    if len(active) > 0 and sum(1 for _ in active) >= 0:
76        print(f"STAT tok_s=1.00 ms_tok=1.00 active={len(active)}", flush=True)
77while True:
78    try:
79        l = lines.get(timeout=STEP if active else 0.5)
80    except queue.Empty:
81        l = ""
82    if l is None or l == "QUIT":
83        break
84    if l.startswith("GEN "):
85        admit(l)
86    if active:
87        time.sleep(STEP)
88        step()
89'''
90
91
92class Args(unittest.TestCase):
93    def test_parallel_key_is_deepseek_parallel(self):
94        ds = {"arch": "deepseek41"}
95        self.assertEqual(parallel_args({**ds, "parallel": 4}, []), ["--parallel", "4"])
96        self.assertEqual(parallel_args({**ds, "parallel": 1}, []), [])
97        self.assertEqual(parallel_args({**ds}, []), [])                                       # (absent: as before)
98        self.assertEqual(parallel_args({**ds, "parallel": 3}, ["--parallel", "2"]), [])       # the args' own value wins
99        self.assertEqual(parallel_args({**ds, "parallel": 3}, ["--batch", "2"]), [])
100        self.assertEqual(parallel_args({**ds, "parallel": "4"}, []), [])                      # said and ignored
101        import contextlib, io
102        with contextlib.redirect_stdout(io.StringIO()) as buf:
103            self.assertEqual(parallel_args({**ds, "parallel": 12}, []), ["--parallel", "8"])
104        self.assertIn("at most 8", buf.getvalue())
105
106    def test_qwen_keeps_batch(self):
107        self.assertEqual(parallel_args({"parallel": 4}, []), ["--batch", "4"])
108        self.assertEqual(parallel_args({"arch": "qwen38", "parallel": 4}, []), ["--batch", "4"])
109
110
111class Engine(unittest.TestCase):
112    def start(self, n):
113        self.tmp = tempfile.TemporaryDirectory()
114        script = Path(self.tmp.name) / "fake_ds.py"
115        script.write_text(FAKE_DS, encoding="utf-8")
116        self.log = Path(self.tmp.name) / "requests.log"
117        real = server.subprocess.Popen
118        extra = ["--parallel", str(n), "--log", str(self.log)]
119        with mock.patch.object(server.subprocess, "Popen",
120                               lambda cmd, **kw: real([sys.executable, str(script), *cmd[1:]], **kw)):
121            self.engine = StrataEngine("strata", extra)
122
123    def tearDown(self):
124        if getattr(self, "httpd", None):
125            self.httpd.shutdown()
126            self.httpd.server_close()
127        if getattr(self, "engine", None):
128            self.engine.unload()
129        if getattr(self, "tmp", None):
130            self.tmp.cleanup()
131
132    def run_one(self, ids, out, cancel=None, stop_after=None):
133        cancel = cancel or threading.Event()
134        got = []
135        g = self.engine.generate(ids, 64, {}, cancel)
136        for t in g:
137            if t is None:
138                continue
139            got.append(t)
140            if stop_after is not None and len(got) >= stop_after:
141                g.close()
142                break
143        out.append((got, dict(self.engine.last)))
144
145    def test_an_engine_that_runs_fewer_than_asked_is_said(self):
146        import contextlib, io
147        with mock.patch.dict("os.environ", {"FAKE_CAP": "2"}), contextlib.redirect_stdout(io.StringIO()) as out:
148            self.start(4)
149        self.assertEqual(self.engine.multi, 2)
150        self.assertEqual(self.engine.batch, 2)
151        self.assertIn("parallel requests: 4 asked, the engine runs 2", out.getvalue())
152
153    def test_ready_multi_makes_the_engine_parallel(self):
154        self.start(3)
155        self.assertEqual(self.engine.multi, 3)
156        self.assertEqual(self.engine.batch, 3)
157        self.engine.unload()
158        self.start(1)
159        self.assertEqual(self.engine.multi, 0)
160        self.assertEqual(self.engine.batch, 0)
161
162    def test_requests_at_once_each_their_own_tokens(self):
163        self.start(3)
164        outs = [[], [], []]
165        ths = [threading.Thread(target=self.run_one, args=([65 + i, 66, 67], outs[i])) for i in range(3)]
166        t0 = time.monotonic()
167        for t in ths:
168            t.start()
169        for t in ths:
170            t.join(30)
171        took = time.monotonic() - t0
172        for i in range(3):
173            got, last = outs[i][0]
174            self.assertEqual(got, [65 + i] * 6 + [257])
175            self.assertEqual(last["generated"], 7)         # (each its own DONE: thread-local figures)
176            self.assertEqual(last["finish"], "stop")
177        self.assertLess(took, 7 * 0.03 * 3 * 0.9 + 1.0)      # (together, not one after the other)
178        self.assertEqual(self.engine.rid_q, {})             # every request's queue taken down
179
180    def test_a_request_that_leaves_is_stopped_alone(self):
181        self.start(2)
182        outs = [[], []]
183        a = threading.Thread(target=self.run_one, args=([70, 1, 2], outs[0]), kwargs={"stop_after": 2})
184        b = threading.Thread(target=self.run_one, args=([71, 1, 2], outs[1]))
185        a.start()
186        b.start()
187        a.join(30)
188        b.join(30)
189        self.assertEqual(outs[1][0][0], [71] * 6 + [257])   # (the other one ran to its end)
190        self.assertEqual(outs[0][0][0], [70, 70])
191        text = self.log.read_text()
192        self.assertRegex(text, r"STOP \d+")
193        self.assertNotIn("\nSTOP\n", text)                  # (not a bare STOP: that ends every request)
194
195    def test_the_gen_line_carries_rid(self):
196        self.start(2)
197        out = []
198        self.run_one([80, 1], out)
199        first = self.log.read_text().splitlines()[0]
200        self.assertTrue(first.startswith("GEN 64 rid=1 80,1"), first)
201
202    def test_chat_requests_run_at_once(self):
203        self.start(2)
204        tok = ByteTokenizer()
205        svc = Service(self.engine, tok, ChatTemplate(Path(__file__).parent / "chat_template.jinja"))
206        self.httpd = serve(svc, port=0)
207        base = f"http://127.0.0.1:{self.httpd.server_address[1]}"
208
209        def chat(text, res, k):
210            body = {"messages": [{"role": "user", "content": text}], "max_tokens": 32, "reasoning_effort": "none"}
211            req = urllib.request.Request(base + "/v1/chat/completions", data=json.dumps(body).encode(),
212                                         headers={"Content-Type": "application/json"})
213            with urllib.request.urlopen(req, timeout=60) as r:
214                res[k] = json.loads(r.read().decode())
215
216        def timed(texts):
217            res = {}
218            ths = [threading.Thread(target=chat, args=(t, res, i)) for i, t in enumerate(texts)]
219            t0 = time.monotonic()
220            for t in ths:
221                t.start()
222            for t in ths:
223                t.join(60)
224            return time.monotonic() - t0, res
225
226        one, r1 = timed(["u1"])
227        two, r2 = timed(["u1", "u2"])
228        self.assertEqual(len(r2), 2)
229        for r in r2.values():
230            self.assertIn("ok, done.", r["choices"][0]["message"]["content"])
231        self.assertLess(two, one * 1.7 + 0.3)                  # two at once cost about one
232
233
234if __name__ == "__main__":
235    unittest.main()