okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1#!/usr/bin/env python3 2"""Split serving (serve/split.py): the exactness check and the speed comparison, run on a test box with the real engine. 3 4python3 tools/split_serve_check.py exact CONFIG.json OUT.json [--tokens N] 5python3 tools/split_serve_check.py bench CONFIG.json OUT.json --arm layer|single|split [--reps 3] 6 7Run it from the repository root (it imports serve.server and serve.split). CONFIG.json: 8 9{"exe": "/path/strata", "cwd": "/path/repo", "args": ["--serve", "--pack", ..., "--max-context", "40960", ...], 10"env": {...}, "prompts": "/path/prompts", "dir": "/path/work", 11"prefill_gpu": 0, "decode_gpu": 1, "arena": "/path/arena.bin" (optional), "min_prompt_tokens": 2048} 12 13`args` holds no --layer-split, --shared-expert-arena or card choice: the tool adds them for each arm. 14The prompts folder has pp_<N>.txt files of comma-separated token ids (the bench harness's). 15 16exact: a fresh engine reads a prompt and answers (the reference, twice, to show the engine's own run-to-run noise); 17then the prefill engine reads the same prompt, saves the session, a fresh decode engine restores it and answers. Compared: 18the state fingerprint (STRATA_STATE_HASH) of the prefill engine and of the decode engine right after the restore, then the 19answer's token ids and the fingerprint after the answer. 20 21bench: one arm per call (run it in its own job so the engines start fresh): 22layer one engine over both cards (--layer-split auto), the normal two-card setup 23single one engine on the decode card 24split prefill engine on one card, decode engine on the other, through SplitEngine (the production path) 25Workloads: 8K and 32K prompt + 256 tokens, a 3-turn chat with short follow-ups, a 3-turn chat with long follow-ups. 26""" 27import argparse 28import copy 29import json 30import os 31import re 32import sys 33import threading 34import time 35 36sys .path .insert (0 ,os .path .dirname (os .path .dirname (os .path .abspath (__file__ )))) 37from serve import server as srv # noqa: E402 38from serve import split as split_mod # noqa: E402 39 40 41def read_ids (path ): 42return [int (x )for x in open (path ).read ().replace ("\n" ,"," ).split ("," )if x .strip ()] 43 44 45def session_dir (cfg ): 46"""Where the session files go: cfg["session_dir"], else /dev/shm when it has room (as the server chooses), else cfg["dir"].""" 47d = cfg .get ("session_dir" ) 48if not d and os .path .isdir ("/dev/shm" ): 49import shutil 50if shutil .disk_usage ("/dev/shm" ).free > (6 << 30 ): 51d = "/dev/shm/strata-split-check" 52d = d or cfg ["dir" ] 53os .makedirs (d ,exist_ok = True ) 54return d 55 56 57def mem_available_gib (): 58for line in open ("/proc/meminfo" ): 59if line .startswith ("MemAvailable" ): 60return int (line .split ()[1 ])/ 1048576.0 61return 0.0 62 63 64def make_engine (cfg ,gpus ,tag ,extra_args = (),arena = None ,min_free_gib = 8.0 ,state_hash = False ): 65free = mem_available_gib () 66if free < min_free_gib : 67raise SystemExit (f"only { free :.1f } GiB of RAM available (< { min_free_gib } ): not starting an engine" ) 68c = copy .deepcopy (cfg ) 69c ["gpu" ]= gpus 70c ["args" ]= list (c ["args" ])+ list (extra_args )+ (["--shared-expert-arena" ,arena ]if arena else []) 71c ["log" ]= os .path .join (cfg ["dir" ],f"engine- { tag } .log" ) 72open (c ["log" ],"w" ).close () 73env = srv .child_env (c ) 74if state_hash :# the fingerprint after every request costs time proportional to the prompt: exact mode only 75env ["STRATA_STATE_HASH" ]= "1" 76for k ,v in (cfg .get ("env" )or {}).items (): 77env [str (k )]= str (v ) 78t0 = time .time () 79e = srv .StrataEngine (c ["exe" ],srv .engine_args (c ),cwd = c .get ("cwd" ),log = c ["log" ],env = env ) 80e .silence_s = 0 81e .tag ,e .load_s = tag ,time .time ()- t0 82return e 83 84 85def log_tail (e ,start ): 86try : 87with open (e .log_path ,"rb" )as f : 88f .seek (start ) 89return f .read ().decode ("utf-8" ,"replace" ) 90except OSError : 91return "" 92 93 94def log_size (e ): 95try : 96return os .path .getsize (e .log_path ) 97except OSError : 98return 0 99 100 101def state_hashes (text ): 102"""The STATE_HASH lines of an engine log excerpt, as dicts.""" 103out = [] 104for m in re .finditer (r"STATE_HASH L=(\d+) (.*)" ,text ): 105d = {"L" :int (m .group (1 ))} 106d .update (dict (kv .split ("=" ,1 )for kv in m .group (2 ).split ()if "=" in kv )) 107out .append (d ) 108return out 109 110 111def run_gen (engine ,ids ,max_new ): 112"""One request through engine.generate (a StrataEngine or a SplitEngine). -> dict of tokens and times.""" 113cancel = threading .Event () 114toks ,t_first = [],None 115t0 = time .perf_counter () 116for t in engine .generate (ids ,max_new , {},cancel ): 117if t is None : 118continue 119if t_first is None : 120t_first = time .perf_counter () 121toks .append (t ) 122t_end = time .perf_counter () 123last = dict (engine .last or {}) 124dec = (len (toks )- 1 )/ (t_end - t_first )if t_first and len (toks )> 1 and t_end > t_first else None 125return {"tokens" :toks ,"ttft_s" : (t_first - t0 )if t_first else None ,"wall_s" :t_end - t0 , 126"dec_tok_s" :dec ,"last" :last } 127 128 129def close_all (* engines ): 130for e in engines : 131try : 132e .close () 133except Exception as x :# noqa: BLE001 134"close:" ,x ,flush = True ) 135 136 137def cmd_exact (a ,cfg ): 138ids = read_ids (os .path .join (cfg ["prompts" ],f"pp_ { a . prompt } .txt" ))[:a .prompt ] 139arena = cfg .get ("arena" ) 140P ,Dg = cfg ["prefill_gpu" ],cfg ["decode_gpu" ] 141res = {"prompt_tokens" :len (ids ),"new_tokens" :a .tokens ,"runs" : {}} 142# 1. the reference twice: a fresh engine on the decode card each time 143for k in (1 ,2 ): 144e = make_engine (cfg ,Dg ,f"ref { k } " ,arena = arena ,state_hash = True ) 145pos = log_size (e ) 146r = run_gen (e ,ids ,a .tokens ) 147h = state_hashes (log_tail (e ,pos )) 148res ["runs" ][f"ref { k } " ]= {"tokens" :r ["tokens" ],"hash_end" :h [- 1 ]if h else None ,"last" :r ["last" ], 149"wall_s" :r ["wall_s" ]} 150f"ref { k } : { len ( r [ 'tokens' ]) } tokens, wall { r [ 'wall_s' ]:.1f } s" ,flush = True ) 151close_all (e ) 152# 2. the split: prefill engine, save, fresh decode engine, restore, answer 153pe = make_engine (cfg ,P ,"prefill" ,arena = arena ,state_hash = True ) 154pos = log_size (pe ) 155cancel = threading .Event () 156for _ in pe .generate (ids ,0 , {},cancel ,prefill_only = True ): 157pass 158hp = state_hashes (log_tail (pe ,pos )) 159path = os .path .join (session_dir (cfg ),"exact.session" ) 160saved = pe .session_file ("save" ,path ) 161f"prefill engine: held { saved [ 'tokens' ] } tokens, saved { saved [ 'bytes' ] / 2 ** 20 :.0f } MiB in { saved [ 'ms' ]:.0f } ms" , 162flush = True ) 163de = make_engine (cfg ,Dg ,"decode" ,arena = arena ,state_hash = True ) 164restored = de .session_file ("restore" ,path ) 165f"decode engine: restored { restored [ 'tokens' ] } tokens in { restored [ 'ms' ]:.0f } ms" ,flush = True ) 166pos = log_size (de ) 167for _ in de .generate (ids ,0 , {},cancel ,prefill_only = True ):# nothing to read: only the state fingerprint 168pass 169hd = state_hashes (log_tail (de ,pos )) 170pos = log_size (de ) 171r = run_gen (de ,ids ,a .tokens ) 172h = state_hashes (log_tail (de ,pos )) 173res ["runs" ]["split" ]= {"tokens" :r ["tokens" ],"hash_end" :h [- 1 ]if h else None ,"last" :r ["last" ], 174"wall_s" :r ["wall_s" ],"hash_prefill_engine" :hp [- 1 ]if hp else None , 175"hash_decode_after_restore" :hd [- 1 ]if hd else None ,"saved" :saved ,"restored" :restored } 176f"split: { len ( r [ 'tokens' ]) } tokens, wall { r [ 'wall_s' ]:.1f } s" ,flush = True ) 177close_all (pe ,de ) 178try : 179os .unlink (path ) 180except OSError : 181pass 182# verdicts 183ref1 ,ref2 ,sp = (res ["runs" ][k ]for k in ("ref1" ,"ref2" ,"split" )) 184 185def first_diff (x ,y ): 186for i , (p ,q )in enumerate (zip (x ,y )): 187if p != q : 188return i 189return None if len (x )== len (y )else min (len (x ),len (y )) 190v = { 191"restore_round_trip_state_equal" :sp ["hash_prefill_engine" ]== sp ["hash_decode_after_restore" ]and 192sp ["hash_prefill_engine" ]is not None , 193"ref1_vs_ref2_first_diff" :first_diff (ref1 ["tokens" ],ref2 ["tokens" ]), 194"ref1_vs_split_first_diff" :first_diff (ref1 ["tokens" ],sp ["tokens" ]), 195"ref2_vs_split_first_diff" :first_diff (ref2 ["tokens" ],sp ["tokens" ]), 196"end_state_ref1_eq_ref2" :ref1 ["hash_end" ]== ref2 ["hash_end" ], 197"end_state_ref1_eq_split" :ref1 ["hash_end" ]== sp ["hash_end" ], 198 } 199res ["verdict" ]= v 200json .dump (res ,open (a .out ,"w" ),indent = 1 ) 201json .dumps (v ,indent = 1 ),flush = True ) 202# the check passes when the split run equals the reference wherever the reference equals itself 203same_ref = v ["ref1_vs_ref2_first_diff" ]is None 204ok = v ["restore_round_trip_state_equal" ]and ( 205 (v ["ref1_vs_split_first_diff" ]is None and v ["end_state_ref1_eq_split" ])if same_ref 206else v ["ref1_vs_split_first_diff" ]is None or v ["ref2_vs_split_first_diff" ]is None ) 207"EXACT: PASS" if ok else "EXACT: FAIL" ,flush = True ) 208return 0 if ok else 1 209 210 211WORKLOADS = [ 212 ("p8k" , {"prompt" :8192 ,"gen" :256 }), 213 ("p32k" , {"prompt" :32768 ,"gen" :256 }), 214 ("chat_short" , {"prompt" :4096 ,"gen" :128 ,"turns" :3 ,"follow" :200 }), 215 ("chat_long" , {"prompt" :8192 ,"gen" :128 ,"turns" :3 ,"follow" :6000 }), 216] 217 218 219def follow_ids (cfg ,n ,turn ): 220"""n token ids for a follow-up message: a slice of the 16K prompt (different for each turn).""" 221pool = read_ids (os .path .join (cfg ["prompts" ],"pp_16384.txt" )) 222start = 1000 + turn * 7000 223return pool [start :start + n ] 224 225 226def cmd_bench (a ,cfg ): 227arm = a .arm 228P ,Dg = cfg ["prefill_gpu" ],cfg ["decode_gpu" ] 229arena = cfg .get ("arena" ) 230t_load = time .time () 231if arm == "layer" : 232eng = make_engine (cfg , [min (P ,Dg ),max (P ,Dg )],"layer" ) 233closers = [eng ] 234elif arm == "single" : 235eng = make_engine (cfg ,Dg ,"single" ) 236closers = [eng ] 237elif arm == "single_shared" :# one card, the arena in the shared file: what the split's engines read from 238eng = make_engine (cfg ,Dg ,"single_shared" ,arena = arena ) 239closers = [eng ] 240elif arm == "split" : 241spec = split_mod .split_spec ({"split_serve" : {"prefill_gpu" :P ,"decode_gpu" :Dg , 242"min_prompt_tokens" :cfg .get ("min_prompt_tokens" ,2048 )}}) 243pe = make_engine (cfg ,P ,"prefill" ,extra_args = cfg .get ("prefill_args" , []),arena = arena ) 244de = make_engine (cfg ,Dg ,"decode" ,extra_args = cfg .get ("decode_args" , []),arena = arena ) 245eng = split_mod .SplitEngine (pe ,de ,min_tokens = spec ["min_prompt_tokens" ],work_dir = session_dir (cfg ),say = closers = [pe ,de ] 247else : 248raise SystemExit ("--arm layer|single|split" ) 249load_s = time .time ()- t_load 250f"[ { arm } ] loaded in { load_s :.0f } s" ,flush = True ) 251rows = [] 252try : 253warm = read_ids (os .path .join (cfg ["prompts" ],"dec_story.txt" )) 254for _ in range (3 ):# warm-up: graphs, the adaptive tier (discarded) 255run_gen (eng ,warm ,100 ) 256if arm == "split" : 257wp = read_ids (os .path .join (cfg ["prompts" ],"pp_4096.txt" )) 258wp [0 ]= 2999 # its own prompt: no workload below finds it in a cache 259run_gen (eng ,wp ,16 )# one hand-over: warms the file path 260for rep in range (a .reps ): 261for widx , (name ,w )in enumerate (WORKLOADS ): 262if a .only and name not in a .only : 263continue 264ids = read_ids (os .path .join (cfg ["prompts" ],f"pp_ { w [ 'prompt' ] } .txt" ))[:w ["prompt" ]] 265ids [0 ]= 3000 + rep * 16 + widx # a prompt of its own: a cold start in every arm, every rep 266if "turns" not in w : 267# a fresh conversation each time: a tiny unrelated request first, so no session is continued 268run_gen (eng ,warm [:40 ],1 ) 269r = run_gen (eng ,ids ,w ["gen" ]) 270turns = [r ] 271else : 272run_gen (eng ,warm [:40 ],1 ) 273turns ,conv = [],list (ids ) 274for t in range (w ["turns" ]): 275r = run_gen (eng ,conv ,w ["gen" ]) 276turns .append (r ) 277conv = conv + r ["tokens" ]+ follow_ids (cfg ,w ["follow" ],t ) 278row = {"arm" :arm ,"rep" :rep ,"workload" :name ,"load_s" :round (load_s ,1 ),"turns" : []} 279for r in turns : 280last = r ["last" ] 281row ["turns" ].append ({ 282"prompt" :last .get ("prompt_tokens" ),"generated" :len (r ["tokens" ]), 283"ttft_s" :round (r ["ttft_s" ],3 )if r ["ttft_s" ]else None ,"wall_s" :round (r ["wall_s" ],3 ), 284"dec_tok_s" :round (r ["dec_tok_s" ],2 )if r ["dec_tok_s" ]else None , 285"reused" :last .get ("reused" ),"prompt_ms" :last .get ("prompt_ms" ), 286"split" : {k :last [k ]for k in last if k .startswith ("split_" )}or None , 287"finish" :last .get ("finish" ),"tokens" :r ["tokens" ][:8 ]}) 288row ["total_wall_s" ]= round (sum (r ["wall_s" ]for r in turns ),3 ) 289rows .append (row ) 290json .dumps ({k :row [k ]for k in ("arm" ,"rep" ,"workload" ,"total_wall_s" )}),flush = True ) 291for t in row ["turns" ]: 292" " ,json .dumps ({k :t [k ]for k in ("prompt" ,"generated" ,"ttft_s" ,"wall_s" ,"dec_tok_s" , 293"reused" ,"split" )}),flush = True ) 294finally : 295out = {"arm" :arm ,"rows" :rows ,"cfg" : {k :v for k ,v in cfg .items ()if k != "env" }, 296"split_view" :eng .split_view ()if hasattr (eng ,"split_view" )else None } 297json .dump (out ,open (a .out ,"w" ),indent = 1 ) 298close_all (* closers ) 299return 0 300 301 302def main (): 303ap = argparse .ArgumentParser () 304ap .add_argument ("mode" ,choices = ["exact" ,"bench" ]) 305ap .add_argument ("config" ) 306ap .add_argument ("out" ) 307ap .add_argument ("--tokens" ,type = int ,default = 64 ) 308ap .add_argument ("--prompt" ,type = int ,default = 4096 ) 309ap .add_argument ("--arm" ,default = "split" ,choices = ["layer" ,"single" ,"single_shared" ,"split" ]) 310ap .add_argument ("--reps" ,type = int ,default = 2 ) 311ap .add_argument ("--only" ,nargs = "*" ,default = None ) 312a = ap .parse_args () 313cfg = json .load (open (a .config )) 314os .makedirs (cfg ["dir" ],exist_ok = True ) 315return cmd_exact (a ,cfg )if a .mode == "exact" else cmd_bench (a ,cfg ) 316 317 318if __name__ == "__main__" : 319sys .exit (main ())