okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
c27998f5a
main
1"""A/B two engine builds or environments on one config: restart the server per arm, alternate arms over rounds. 2 3python tools/ab_engine.py strata-q2_0.json A:exe=/path/a B:exe=/path/b,STRATA_EXP_MODE=0 [--rounds 3] 4 5An arm is NAME:key=value,...; `exe` replaces the config's engine, `xargs` appends ';'-separated engine arguments, 6every other key is set in the engine's environment. Each round starts the server once per arm (the arms' order alternates), warms it up with one short 7answer, then sends the same requests: greedy, fixed prompts, a short chat set and one long prompt. Prints the 8server's own timings (llama.cpp's `timings`: decode and prompt tokens per second) per request and the per-arm 9medians. Decode numbers move run to run (the adaptive expert tier, the OS), so compare medians over rounds. 10""" 11from __future__import annotations 12 13import argparse 14import json 15import os 16import random 17import statistics 18import subprocess 19import sys 20import tempfile 21import time 22import urllib .request 23from pathlib import Path 24 25ROOT = Path (__file__ ).resolve ().parents [1 ] 26PROMPTS = ( 27"Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests." , 28"Explain in two paragraphs how a refrigerator moves heat from inside to outside." , 29"List ten practical tips for learning a new language as an adult, one sentence each." , 30) 31 32 33def long_prompt (words :int )-> str : 34rng = random .Random (7 ) 35vocab = ("river stone market lantern copper winter garden signal harbor needle orbit velvet canyon ember " 36"ledger quartz meadow anchor violet thunder" ).split () 37body = " " .join (rng .choice (vocab )for _ in range (words )) 38return f"Here is a list of words:\n { body } \n\nSummarize what kinds of words appear in the list, in five sentences." 39 40 41def post (port :int ,prompt :str ,max_tokens :int )-> dict : 42req = urllib .request .Request ( 43f"http://127.0.0.1: { port } /v1/chat/completions" , 44data = json .dumps ({"messages" : [{"role" :"user" ,"content" :prompt }],"max_tokens" :max_tokens , 45"temperature" :0 ,"chat_template_kwargs" : {"enable_thinking" :False }}).encode (), 46headers = {"Content-Type" :"application/json" }) 47with urllib .request .urlopen (req ,timeout = 1800 )as r : 48return json .loads (r .read ()) 49 50 51def wait_ready (port :int ,proc :subprocess .Popen ,timeout :float = 1800 )-> None : 52t0 = time .time () 53while time .time ()- t0 < timeout : 54if proc .poll ()is not None : 55raise RuntimeError (f"server exited with { proc . returncode } " ) 56try : 57with urllib .request .urlopen (f"http://127.0.0.1: { port } /v1/models" ,timeout = 5 )as r : 58if r .status == 200 : 59post (port ,"Say hi." ,8 ) 60return 61except Exception : 62pass 63time .sleep (3 ) 64raise TimeoutError ("server not ready" ) 65 66 67def main ()-> int : 68ap = argparse .ArgumentParser () 69ap .add_argument ("config" ) 70ap .add_argument ("arms" ,nargs = "+" ) 71ap .add_argument ("--rounds" ,type = int ,default = 3 ) 72ap .add_argument ("--port" ,type = int ,default = 8090 ) 73ap .add_argument ("--max-new" ,type = int ,default = 256 ) 74ap .add_argument ("--long-words" ,type = int ,default = 6000 ) 75ap .add_argument ("--log" ,default = "ab_engine.jsonl" ) 76a = ap .parse_args () 77base = json .loads (Path (a .config ).read_text ()) 78arms = [] 79for s in a .arms : 80name ,_ ,kv = s .partition (":" ) 81env = dict (x .split ("=" ,1 )for x in kv .split ("," )if x ) 82arms .append ((name ,env )) 83reqs = [(f"chat { i } " ,p )for i ,p in enumerate (PROMPTS )]+ [("long" ,long_prompt (a .long_words ))] 84out = open (a .log ,"a" ) 85res :dict = {n : {}for n ,_ in arms } 86for rnd in range (a .rounds ): 87order = arms if rnd % 2 == 0 else arms [::- 1 ] 88for name ,env in order : 89cfg = dict (base ) 90e = dict (env ) 91if "exe" in e : 92cfg ["exe" ]= e .pop ("exe" ) 93if "xargs" in e :# extra engine arguments, ';'-separated 94cfg ["args" ]= list (base ["args" ])+ e .pop ("xargs" ).split (";" ) 95cfg ["port" ]= a .port 96cfg ["log" ]= str (Path (tempfile .gettempdir ())/ f"ab_ { name } _r { rnd } .log" ) 97cpath = Path (tempfile .gettempdir ())/ f"ab_ { name } .json" 98cpath .write_text (json .dumps (cfg ,indent = 1 )) 99penv = dict (os .environ ,** e ) 100proc = subprocess .Popen ([sys .executable ,str (ROOT / "serve" / "server.py" ),"--engine" ,"strata" ,"--config" , 101str (cpath ),"--port" ,str (a .port )],cwd = str (ROOT ),env = penv , 102stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL ) 103try : 104t0 = time .time () 105wait_ready (a .port ,proc ) 106f"round { rnd } { name } : ready in { time . time () - t0 :.0f } s" ,flush = True ) 107for tag ,p in reqs : 108r = post (a .port ,p ,a .max_new ) 109t = r .get ("timings" , {}) 110row = {"round" :rnd ,"arm" :name ,"req" :tag ,"decode" :t .get ("predicted_per_second" ), 111"prompt" :t .get ("prompt_per_second" ),"prompt_n" :t .get ("prompt_n" ), 112"n" :r .get ("usage" , {}).get ("completion_tokens" ), 113"text" :r ["choices" ][0 ]["message" ].get ("content" ,"" )[:80 ]} 114out .write (json .dumps (row )+ "\n" ) 115out .flush () 116res [name ].setdefault (tag , []).append (row ) 117f" { tag :6s } decode { row [ 'decode' ] } tok/s prompt { row [ 'prompt' ] } tok/s ( { row [ 'prompt_n' ] } ) " 118f"n { row [ 'n' ] } " ,flush = True ) 119finally : 120proc .terminate () 121try : 122proc .wait (60 ) 123except subprocess .TimeoutExpired : 124proc .kill () 125time .sleep (5 ) 126"\nmedians over rounds:" ) 127for tag ,_ in reqs : 128cells = [] 129for name ,_ in arms : 130rows = res [name ].get (tag , []) 131d = statistics .median ([x ["decode" ]for x in rows if x ["decode" ]])if rows else float ("nan" ) 132pr = statistics .median ([x ["prompt" ]for x in rows if x ["prompt" ]])if rows else float ("nan" ) 133cells .append (f" { name } : decode { d :6.1f } prompt { pr :7.1f } " ) 134f" { tag :6s } | " + " | " .join (cells )) 135return 0 136 137 138if __name__ == "__main__" : 139sys .exit (main ())