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