okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
049ae1c67
main
1"""serve/server.py for an Intel Arc: the same server, with the Intel pieces added from outside. 2 3python sycl/serve/server_intel.py --engine strata --config strata-<model>.json --port 8080 [...] 4 5Every argument is serve/server.py's. Nothing in serve/ is edited (the SYCL port keeps out of the shared files so 6upstream merges stay clean); this wrapper adds, at run time: 7 8- the Monitor tab's GPU readings on an Intel Arc (sycl/serve/xe_telemetry.py) (also on a PC with an NVIDIA card: the engine runs on the Intel one); 9- a model menu in the web app's header, for a host that swaps models on one GPU: the config names the RPC that 10does the swap as "model_switcher" (it takes {"mode": m} and answers {"mode", "up", "starting", "choices", 11"urls"}); the menu offers the models served on this server's port. Without that key nothing changes; 12- OpenAI `logprobs` / `top_logprobs` on /v1/chat/completions (streamed or not): the engine (the SYCL port, 13`logprobs=K` on its GEN line) writes an `LP` line after each `T` line, which upstream's server would ignore. 14The values are the model's log-probabilities from the verify window's logits, before sampling, temperature and 15penalties; with thinking on, the thinking tokens are listed too (in order, under `reasoning_content`). 16""" 17from __future__import annotations 18 19import collections 20import json 21import sys 22import time 23import urllib .parse 24import urllib .request 25from pathlib import Path 26 27HERE = Path (__file__ ).resolve ().parent 28ROOT = HERE .parent .parent 29sys .path .insert (0 ,str (ROOT )) 30sys .path .insert (0 ,str (HERE )) 31 32import serve .server as S # noqa: E402 33import serve .telemetry as T # noqa: E402 34from xe_telemetry import _XeGpu # noqa: E402 35 36 37def install_xe_reader (): 38"""telemetry.gpu_reader -> the xe reader whenever an Intel Arc is there. #2001: this server runs the SYCL engine, 39so the cards it reports are the Intel ones; before, an NVIDIA card in the same PC answered first and the Monitor 40(and the benchmark report, which takes the card's name from it) showed the GeForce the engine never used.""" 41orig = T .gpu_reader 42 43def gpu_reader (index = 0 ,amd = False ): 44xe = _XeGpu (index ) 45return xe if xe .ok ()else orig (index ,amd ) 46 47T .gpu_reader = gpu_reader 48 49 50def install_shared_embeddings (): 51"""Pictures: the engine runs in a container, and a request's image embeddings reach it as a file named on its GENI line. 52serve/server.py writes that file to /dev/shm when that has room, and strata-sycl.sh shares the host's /dev/shm with the 53container, so the path means the same on both sides. Anywhere else (a full /dev/shm) the container cannot see the file: 54said once, in the log, in plain words.""" 55orig = S .combined_embeddings_path 56said = [] 57 58def path (vision_dir ,nbytes ): 59p = orig (vision_dir ,nbytes ) 60if not str (p ).startswith ("/dev/shm/" )and not said : 61said .append (1 ) 62"[strata] /dev/shm has no room for this picture: the engine runs in a container that sees only the host's /dev/shm, so it " 63"cannot read the picture. Free /dev/shm (or enlarge it: mount -o remount,size=4G /dev/shm) and send it again." ,flush = True ) 64return p 65S .combined_embeddings_path = path 66 67 68def model_switcher (url :str ,port ,model ,mode :str = "" )-> dict : 69"""The host's model swapper: the models it serves on THIS port, which one holds the card, whether one is loading. 70With `mode`, asks for that one first; this server is then usually the one stopped, so the web app waits for 71/health to name the new model.""" 72try : 73body = json .dumps ({"mode" :mode }if mode else {}).encode () 74req = urllib .request .Request (url ,body , {"Content-Type" :"application/json" }) 75with urllib .request .urlopen (req ,timeout = 10 )as r : 76res = json .load (r ) 77st = res .get ("result" ,res ) 78except (OSError ,ValueError )as e : 79return {"enabled" :True ,"error" :f"the model switcher did not answer ( { e } )" } 80urls = st .get ("urls" )or {} 81mine = {k :v for k ,v in (st .get ("choices" )or {}).items () 82if not urls or str (urllib .parse .urlsplit (str (urls .get (k ,"" ))).port )== str (port )} 83return {"enabled" :True ,"mode" :st .get ("mode" ),"up" :st .get ("up" ),"starting" :st .get ("starting" ), 84"choices" :mine ,"model" :model } 85 86 87def install_switcher (argv ): 88"""Wraps make_handler: GET/POST /switcher, the menu's script and style, and the index page that loads them.""" 89def arg (name ,default = None ): 90return argv [argv .index (name )+ 1 ]if name in argv and argv .index (name )+ 1 < len (argv )else default 91 92try : 93cfg = json .loads (Path (arg ("--config" )).read_text (encoding = "utf-8-sig" ))if arg ("--config" )else {} 94except (OSError ,ValueError ): 95cfg = {} 96url = cfg .get ("model_switcher" ) 97if not url : 98return 99port = arg ("--port" ,"8080" ) 100web = HERE / "web" 101types = {".js" :"text/javascript; charset=utf-8" ,".css" :"text/css; charset=utf-8" } 102make_handler = S .make_handler 103 104def make (svc ): 105base = make_handler (svc ) 106 107class Handler (base ): 108def _send (self ,body :bytes ,ctype :str ): 109self .send_response (200 ) 110self .send_header ("Content-Type" ,ctype ) 111self .send_header ("Cache-Control" ,"no-cache" ) 112self .send_header ("Content-Length" ,str (len (body ))) 113self .end_headers () 114self .wfile .write (body ) 115 116def do_GET (self ): 117path = self .path .split ("?" )[0 ].rstrip ("/" ) 118if path == "/switcher" : 119if self ._authorized (): 120self ._json (200 ,model_switcher (url ,port ,svc .model )) 121return 122if path .startswith ("/sycl-web/" ): 123f = web / path [len ("/sycl-web/" ):] 124if f .parent != web or f .suffix not in types or not f .is_file (): 125self ._json (404 , {"error" : {"message" :"not found" }}) 126return 127self ._send (f .read_bytes (),types [f .suffix ]) 128return 129if path == "" : 130page = (ROOT / "serve" / "web" / "index.html" ).read_text (encoding = "utf-8" ) 131page = page .replace ("</head>" ,'<link rel="stylesheet" href="sycl-web/switcher.css">\n</head>' ,1 ) 132page = page .replace ("</body>" ,'<script src="sycl-web/switcher.js"></script>\n</body>' ,1 ) 133self ._send (page .encode ("utf-8" ),"text/html; charset=utf-8" ) 134return 135super ().do_GET () 136 137def do_POST (self ): 138path = self .path .split ("?" )[0 ].rstrip ("/" ) 139if path == "/switcher" : 140if not self ._authorized (): 141return 142req = json .loads (self .rfile .read (int (self .headers .get ("Content-Length" ,0 )))or b"{}" ) 143self ._json (200 ,model_switcher (url ,port ,svc .model ,str (req .get ("mode" )or "" ))) 144return 145super ().do_POST () 146 147return Handler 148 149S .make_handler = make 150 151 152def install_logprobs (): 153"""`LP` lines next to their tokens, the request's `logprobs` to the engine, OpenAI's `logprobs` in the reply.""" 154Eng = S .StrataEngine 155 156def _pump (self ):# serve/server.py's StrataEngine._pump, plus: an LP line goes beside its token, not in the queue 157proc ,lines = self .proc ,self .lines 158slot_q = self .slot_q 159lp = self .__dict__ .setdefault ("lp_lines" ,collections .deque ()) 160last_t = None 161line = None 162for line in proc .stdout : 163if line .startswith (S .FATAL_PREFIXES ):# as serve/server.py: never a slot's own line 164if self .proc is proc : 165self .silent_note = "Unrecoverable native verification failure: " + line [4 :].strip () 166self .ended = True 167try : 168proc .terminate () 169except OSError : 170pass 171break 172if line .startswith (("BT " ,"BDONE " ))and slot_q :# --batch ("parallel"): a batch slot's own lines 173try : 174slot_q [int (line .split ()[1 ])].put (line ) 175continue 176except (IndexError ,ValueError ): 177pass 178if line .startswith ("LP " ): 179lp .append ((last_t ,line )) 180continue 181if line .startswith ("T " ): 182try : 183last_t = int (line [2 :]) 184except ValueError : 185last_t = None 186lines .put (line ) 187if self .proc is proc : 188self .ended = True 189if line and line .startswith ("ERR" ): 190self .last_err = line [4 :].strip () 191lines .put (None ) 192for q in slot_q : 193q .put (None ) 194Eng ._pump = _pump 195 196keys = Eng .sampling_keys 197 198def sampling_keys (sampling ): 199k = top_logprobs (sampling or {}) 200return keys (sampling )+ (f" logprobs= { k } " if k is not None else "" ) 201Eng .sampling_keys = staticmethod (sampling_keys ) 202 203generate = Eng .generate 204 205def gen (self ,* a ,** kw ): 206self .__dict__ .setdefault ("lp_lines" ,collections .deque ()).clear ()# this request's lines only 207return generate (self ,* a ,** kw ) 208Eng .generate = gen 209 210def entry (tok ,t ,line ): 211f = line .split () 212if len (f )< 2 or f [1 ]== "nan" : 213return None 214 215def item (i ,lp ): 216b = tok .token_bytes (i )if hasattr (tok ,"token_bytes" )else tok .decode ([i ]).encode () 217return {"token" :b .decode ("utf-8" ,"replace" ),"logprob" :lp ,"bytes" :list (b )} 218e = item (t ,float (f [1 ]))if t is not None else {"token" :"" ,"logprob" :float (f [1 ]),"bytes" : []} 219e ["top_logprobs" ]= [item (int (i ),float (v ))for i ,_ ,v in (x .partition (":" )for x in f [2 :])] 220return e 221 222chunks = S .openai_chunks 223 224def openai_chunks (svc ,req ,* a ,** kw ): 225if top_logprobs (req )is None : 226yield from chunks (svc ,req ,* a ,** kw ) 227return 228eng = svc .engine 229for c in chunks (svc ,req ,* a ,** kw ): 230lp = getattr (eng ,"lp_lines" ,None ) 231if c and c .get ("choices" )and lp : 232got = [] 233while lp : 234t ,line = lp .popleft () 235if t in svc .stop_ids :# the stop token ends the reply; OpenAI does not list it 236continue 237e = entry (svc .tok ,t ,line ) 238if e is not None : 239got .append (e ) 240if got : 241d = c ["choices" ][0 ].get ("delta" )or {} 242key = "reasoning_content" if d .get ("reasoning_content" )and not d .get ("content" )else "content" 243c ["choices" ][0 ]["logprobs" ]= {key :got } 244yield c 245S .openai_chunks = openai_chunks 246 247collect = S .openai_collect 248 249def openai_collect (cs ): 250merged = {"content" : [],"reasoning_content" : []} 251 252def tap (): 253for c in cs : 254if c and c .get ("choices" )and c ["choices" ][0 ].get ("logprobs" ): 255for k ,v in c ["choices" ][0 ]["logprobs" ].items (): 256merged [k ].extend (v ) 257yield c 258out = collect (tap ()) 259if merged ["content" ]or merged ["reasoning_content" ]: 260out ["choices" ][0 ]["logprobs" ]= {k :v for k ,v in merged .items ()if v }| {"content" :merged ["content" ]} 261return out 262S .openai_collect = openai_collect 263 264 265def install_narrator (): 266"""The start narrator of serve/server.py says the CUDA engine's thing - tens of GB read into RAM, "YOUR PC CAN BE 267SLOW OR STOP RESPONDING" - at the experts' step. With --stream-experts the SYCL port reads them from the GGUF 268into VRAM (and a pinned mirror), which does not do that: say that instead. Without it (an i915 card) the experts 269do go into a RAM arena and the original text stands.""" 270orig = S .narrate_start 271 272def narrate_start (log_path ,offset ,args ,done ,heartbeat = 20.0 ): 273if "--stream-experts" not in args : 274return orig (log_path ,offset ,args ,done ,heartbeat ) 275t0 = last = time .time () 276said = set () 277 278def say (key ,text ): 279nonlocal last 280if key not in said : 281said .add (key ) 282last = time .time () 283text ,flush = True ) 284 285say ("weights" ,"[strata] starting the engine: reading the model's weights ..." ) 286pos = offset 287while not done .wait (0.5 ): 288try : 289with open (log_path ,"rb" )as f : 290f .seek (pos ) 291chunk = f .read () 292except OSError : 293chunk = b"" 294if chunk .count (b"\n" ): 295cut = chunk .rfind (b"\n" )+ 1 296pos += cut 297for line in chunk [:cut ].decode ("utf-8" ,"replace" ).splitlines (): 298if "PLE on" in line or "expert arena:" in line : 299say ("arena" ,"[strata] streaming the experts from the model files into the GPU's memory " 300"(and a pinned RAM mirror for what does not fit); the first start takes a few minutes ..." ) 301elif " loaded " in line and "GiB at" in line : 302say ("loaded" ,"[strata] experts loaded: " + line .split (" loaded " ,1 )[1 ].strip ()+ 303f" ( { time . time () - t0 :.0f } s so far)" ) 304elif "expert cache " in line and " slots, " in line and "auto" not in line : 305n = line .split ("expert cache " ,1 )[1 ].split (";" )[0 ].replace (" slots," ," experts," ).strip () 306say ("cache" ,f"[strata] filling the GPU's expert cache ( { n } ) ..." ) 307elif "session is up" in line : 308say ("up" ,"[strata] almost ready ..." ) 309if time .time ()- last > heartbeat : 310last = time .time () 311f"[strata] still starting ( { time . time () - t0 :.0f } s) - please wait ..." ,flush = True ) 312S .narrate_start = narrate_start 313 314 315def top_logprobs (req :dict ): 316"""The K for the engine's logprobs=K, or None when the request did not ask (OpenAI: logprobs=true, top_logprobs 3170..20; the legacy completions form, logprobs=N, is taken as N).""" 318lp = req .get ("logprobs" ) 319if lp is True : 320k = req .get ("top_logprobs" ) 321return max (0 ,min (20 ,int (k )))if isinstance (k ,int )and not isinstance (k ,bool )else 0 322if isinstance (lp ,int )and not isinstance (lp ,bool )and lp >= 0 : 323return min (20 ,lp ) 324return None 325 326 327def install_two_card_spec (): 328"""engine_args -> the config's --spec 2 on exactly two Arc B-series cards (strata_control/intel_spec.py), at every start: a 329config written before (by an older setup, or by the launcher) gets what a new setup run would write. The person's own 330--spec ("user_args", or a value other than setup's 4) is never touched; one plain line says what changed.""" 331from strata_control import intel_spec 332original = S .engine_args 333 334def engine_args (cfg ,exe = None ,* ,announce = True ):# the base signature (serve/server.py engine_args): start calls it with exe, the budget check with announce=False 335args = original (cfg ,exe ,announce = announce ) 336try : 337if cfg .get ("backend" )== "sycl" and S .layer_split_of (cfg ): 338sysfs = intel_spec .sysfs_cards () 339cards = [sysfs [i ]for i in S .gpu_list (cfg )if isinstance (i ,int )and 0 <= i < len (sysfs )] 340new ,note = intel_spec .plan (args ,cfg .get ("user_args" ),cards ,mtp_off = cfg .get ("mtp" )is False ) 341if note : 342if announce :# (announce=False builds the arguments without any line) 343"[strata] " + note ,flush = True ) 344return new 345except Exception as exc :# noqa: BLE001 - a rule that cannot be read leaves the config's own args 346f"[strata] two-card --spec rule skipped: { exc } " ,flush = True ) 347return args 348S .engine_args = engine_args 349 350 351if __name__ == "__main__" : 352install_two_card_spec () 353install_xe_reader () 354install_shared_embeddings () 355install_narrator () 356install_switcher (sys .argv [1 :]) 357install_logprobs () 358sys .exit (S .main ())