okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d19c07650
main
1"""A scripted research run against a running Strata server: one long document, then many different questions. 2 3Reads the document once, then asks each question and reports, per question, the time to the first streamed token and 4the whole request, and the run's total. Greedy (temperature 0), so two runs of the same file give the same answers and 5a change in how the server keeps the document (the shared prefix below) can be compared answer by answer. 6 7python tools/research_run.py --url http://127.0.0.1:8080 --doc paper.txt --questions questions.txt 8python tools/research_run.py --doc paper.txt --questions q.txt --prefix off --json base.json 9python tools/research_run.py --doc paper.txt --questions q.txt --prefix on --json fork.json 10python tools/research_run.py --compare base.json fork.json 11 12--layout split (the default): the document is the first message, the question the second. 13--layout joined: one message, "document + question" (a client that cannot split them). 14--prefix on: the request carries "strata_prefix" naming the document as the shared prefix (docs/DETAILS.md): the 15server reads it once and every question starts from it. off: the field is left out. 16--parallel N: N questions at a time (the server needs "parallel": N for them to run together). 17""" 18from __future__import annotations 19 20import argparse 21import json 22import statistics 23import sys 24import threading 25import time 26import urllib .request 27from pathlib import Path 28 29 30def request_body (doc :str ,question :str ,layout :str ,prefix :bool ,max_tokens :int ,model :str | None )-> dict : 31if layout == "joined" : 32body = {"messages" : [{"role" :"user" ,"content" :doc + "\n\nQuestion: " + question + "\nAnswer:" }]} 33if prefix : 34body ["strata_prefix" ]= {"message" :0 ,"chars" :len (doc )+ 2 } 35else : 36body = {"messages" : [{"role" :"user" ,"content" :doc }, {"role" :"user" ,"content" :question }]} 37if prefix : 38body ["strata_prefix" ]= {"messages" :1 } 39body .update (temperature = 0 ,max_tokens = max_tokens ,stream = True ) 40if model : 41body ["model" ]= model 42return body 43 44 45def ask (url :str ,body :dict ,headers :dict ,timeout :float )-> dict : 46t0 = time .time () 47req = urllib .request .Request (url + "/v1/chat/completions" ,data = json .dumps (body ).encode (),headers = headers ) 48first ,parts = None , [] 49with urllib .request .urlopen (req ,timeout = timeout )as r : 50for raw in r : 51line = raw .decode ("utf-8" ,"replace" ).strip () 52if not line .startswith ("data:" )or line .endswith ("[DONE]" ): 53continue 54event = json .loads (line [5 :]) 55for choice in event .get ("choices" , []): 56delta = choice .get ("delta" , {}) 57piece = (delta .get ("reasoning_content" )or "" )+ (delta .get ("content" )or "" ) 58if piece and first is None : 59first = time .time ()- t0 60parts .append (piece ) 61return {"ttft_s" :round (first or 0.0 ,3 ),"wall_s" :round (time .time ()- t0 ,2 ),"text" :"" .join (parts )} 62 63 64def run (args )-> dict : 65doc = Path (args .doc ).read_text (encoding = "utf-8" ,errors = "replace" ) 66if args .limit_chars : 67doc = doc [:args .limit_chars ] 68questions = [x .strip ()for x in Path (args .questions ).read_text (encoding = "utf-8" ).splitlines ()if x .strip ()] 69questions = questions [:args .n ]if args .n else questions 70headers = {"Content-Type" :"application/json" } 71if args .api_key : 72headers ["Authorization" ]= "Bearer " + args .api_key 73rows :list [dict | None ]= [None ]* len (questions ) 74started = time .time () 75for k in range (0 ,len (questions ),max (1 ,args .parallel )): 76group = list (range (k ,min (k + max (1 ,args .parallel ),len (questions )))) 77 78def one (i ): 79try : 80rows [i ]= {"q" :i ,** ask (args .url ,request_body (doc ,questions [i ],args .layout ,args .prefix == "on" , 81args .max_tokens ,args .model ),headers ,args .timeout )} 82except Exception as e :# noqa: BLE001 - a failed question is reported, the run goes on 83rows [i ]= {"q" :i ,"error" :repr (e )} 84threads = [threading .Thread (target = one ,args = (i ,))for i in group ] 85 [t .start ()for t in threads ] 86 [t .join ()for t in threads ] 87for i in group : 88r = rows [i ] 89f"q { i :02d } first token { r . get ( 'ttft_s' , '-' ) } s total { r . get ( 'wall_s' , '-' ) } s " 90f" { r . get ( 'error' ) or repr ( r [ 'text' ][: 60 ]) } " ,flush = True ) 91out = {"url" :args .url ,"layout" :args .layout ,"prefix" :args .prefix ,"doc_chars" :len (doc ),"questions" :rows , 92"total_s" :round (time .time ()- started ,1 )} 93later = [r ["ttft_s" ]for r in rows [1 :]if r and "ttft_s" in r ] 94if later : 95out ["first_token_median_after_first_s" ]= round (statistics .median (later ),3 ) 96f"total { out [ 'total_s' ] } s" + (f", median first token after the first question { out [ 'first_token_median_after_first_s' ] } s" 97if later else "" ),flush = True ) 98return out 99 100 101def compare (a_path :str ,b_path :str )-> int : 102a ,b = (json .loads (Path (p ).read_text (encoding = "utf-8" ))for p in (a_path ,b_path )) 103same = diff = 0 104for x ,y in zip (a ["questions" ],b ["questions" ]): 105if "text" in x and "text" in y : 106if x ["text" ]== y ["text" ]: 107same += 1 108else : 109diff += 1 110f"q { x [ 'q' ]:02d } : the answers differ" ) 111f" { same } answers identical, { diff } differ; total { a [ 'total_s' ] } s -> { b [ 'total_s' ] } s; median first token " 112f" { a . get ( 'first_token_median_after_first_s' ) } s -> { b . get ( 'first_token_median_after_first_s' ) } s" ) 113return 1 if diff else 0 114 115 116def main (argv = None )-> int : 117ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 118ap .add_argument ("--url" ,default = "http://127.0.0.1:8080" ) 119ap .add_argument ("--api-key" ,default = "" ) 120ap .add_argument ("--model" ,default = None ) 121ap .add_argument ("--doc" ) 122ap .add_argument ("--questions" ,help = "a text file, one question per line" ) 123ap .add_argument ("--n" ,type = int ,default = 0 ,help = "only the first N questions" ) 124ap .add_argument ("--layout" ,choices = ("split" ,"joined" ),default = "split" ) 125ap .add_argument ("--prefix" ,choices = ("on" ,"off" ),default = "on" ) 126ap .add_argument ("--parallel" ,type = int ,default = 1 ) 127ap .add_argument ("--max-tokens" ,type = int ,default = 128 ) 128ap .add_argument ("--limit-chars" ,type = int ,default = 0 ,help = "use only the first N characters of the document" ) 129ap .add_argument ("--timeout" ,type = float ,default = 7200.0 ) 130ap .add_argument ("--json" ,help = "write the per-question results here" ) 131ap .add_argument ("--compare" ,nargs = 2 ,metavar = ("A.json" ,"B.json" ),help = "compare two saved runs' answers and times" ) 132args = ap .parse_args (argv ) 133if args .compare : 134return compare (* args .compare ) 135if not args .doc or not args .questions : 136ap .error ("--doc and --questions are needed" ) 137out = run (args ) 138if args .json : 139Path (args .json ).write_text (json .dumps (out ,indent = 1 ),encoding = "utf-8" ) 140return 1 if any ("error" in r for r in out ["questions" ])else 0 141 142 143if __name__ == "__main__" : 144sys .exit (main ())