okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
9a11b3eb7
main
1"""tools/needle_bench.py - needle-in-a-haystack recall through a running Strata server. 2 3A long text is built from files in this repository (its docs and source code, and the llama.cpp docs setup downloads 4into third_party/), a code word is hidden in it at a chosen depth, and the model is asked for it through the normal 5API (thinking off, greedy). One line per test: length, depth, found or not, prompt tokens, time. 6 7python tools/needle_bench.py # 32K at depths 10/50/90, http://127.0.0.1:8080 8python tools/needle_bench.py --lengths 32k,128k,262k --depths 10,50,90 --url http://127.0.0.1:8081 9python tools/needle_bench.py --out needles.json --api-key KEY 10 11The lengths are targets, 2% under so that "128k" fits a 128K context: the text is cut by characters (about 3.2 per 12token), and the line reports the prompt's real token count from the server. A length the server's context cannot hold is skipped. 13""" 14from __future__import annotations 15 16import argparse 17import json 18import random 19import sys 20import time 21import urllib .error 22import urllib .request 23from pathlib import Path 24 25ROOT = Path (__file__ ).resolve ().parent .parent 26SOURCES = [("docs" ,"*.md" ), ("src" ,"*.cpp" ), ("src" ,"*.cu" ), ("include" ,"*.hpp" ), ("serve" ,"*.py" ), ("tools" ,"*.py" ), 27 ("third_party/llama.cpp/docs" ,"*.md" )] 28WORDS = ["amber" ,"falcon" ,"quartz" ,"willow" ,"copper" ,"harbor" ,"saffron" ,"glacier" ,"orchid" ,"lantern" , 29"meadow" ,"cobalt" ,"juniper" ,"tundra" ,"velvet" ,"ember" ] 30CHARS_PER_TOKEN = 3.2 31 32 33def haystack (n_chars :int )-> str : 34"""Deterministic filler: the repository's text files in a fixed order, repeated if needed.""" 35files = [] 36for d ,pat in SOURCES : 37files += sorted ((ROOT / d ).rglob (pat )) 38parts ,total = [],0 39while total < n_chars : 40for f in files : 41try : 42t = f .read_text (encoding = "utf-8" ,errors = "replace" ) 43except OSError : 44continue 45parts .append (f"\n\n=== { f . relative_to ( ROOT ). as_posix () } ===\n { t } " ) 46total += len (parts [- 1 ]) 47if total >= n_chars : 48break 49if not files : 50raise SystemExit ("no text files found to build the haystack from" ) 51return "" .join (parts )[:n_chars ] 52 53 54def ask (url :str ,key :str ,prompt :str ,timeout :float )-> tuple [str ,int ,float ]: 55body = {"model" :"strata" ,"max_tokens" :40 ,"temperature" :0 , 56"chat_template_kwargs" : {"enable_thinking" :False }, 57"messages" : [{"role" :"user" ,"content" :prompt }]} 58headers = {"Content-Type" :"application/json" } 59if key : 60headers ["Authorization" ]= "Bearer " + key 61t0 = time .time () 62req = urllib .request .Request (url .rstrip ("/" )+ "/v1/chat/completions" ,data = json .dumps (body ).encode (),headers = headers ) 63with urllib .request .urlopen (req ,timeout = timeout )as r : 64out = json .loads (r .read ()) 65return (out ["choices" ][0 ]["message" ].get ("content" )or "" ),out ["usage" ]["prompt_tokens" ],time .time ()- t0 66 67 68def main ()-> int : 69ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 70ap .add_argument ("--url" ,default = "http://127.0.0.1:8080" ) 71ap .add_argument ("--api-key" ,default = "" ) 72ap .add_argument ("--lengths" ,default = "32k" ,help = "comma-separated, e.g. 1k,32k,128k,262k" ) 73ap .add_argument ("--depths" ,default = "10,50,90" ,help = "where the code word sits, percent of the text" ) 74ap .add_argument ("--timeout" ,type = float ,default = 1800 ) 75ap .add_argument ("--out" ,help = "also write the results as JSON" ) 76a = ap .parse_args () 77try : 78with urllib .request .urlopen (a .url .rstrip ("/" )+ "/metrics" ,timeout = 10 )as r : 79ctx = int ((json .loads (r .read ()).get ("engine" )or {}).get ("max_context" )or 0 ) 80except (OSError ,ValueError ): 81ctx = 0 82rnd = random .Random (7 ) 83rows ,found = [],0 84for L in a .lengths .split ("," ): 85tokens = int (float (L .lower ().rstrip ("k" ))* 1024 )if L .lower ().endswith ("k" )else int (L ) 86tokens = int (tokens * 0.98 )# "128k" fits a 128K context with room to answer 87if ctx and tokens + 200 > ctx : 88f" { L :>5 } : skipped (the server's context is { ctx } )" ) 89continue 90text = haystack (int (tokens * CHARS_PER_TOKEN )) 91for d in (int (x )for x in a .depths .split ("," )): 92word = f" { rnd . choice ( WORDS ) } - { rnd . choice ( WORDS ) } - { rnd . randint ( 100 , 999 ) } " 93cut = int (len (text )* d / 100 ) 94cut = text .rfind ("\n" ,0 ,cut )+ 1 or cut # at a line start 95needle = f"\nThe secret code word for this text is: { word } . Remember it.\n" 96prompt = (text [:cut ]+ needle + text [cut :]+ 97"\n\nWhat is the secret code word mentioned in the text above? Reply with the code word only." ) 98try : 99answer ,n ,secs = ask (a .url ,a .api_key ,prompt ,a .timeout ) 100except (OSError ,urllib .error .HTTPError )as e : 101f" { L :>5 } depth { d :>3 } %: request failed ( { e } )" ) 102rows .append ({"length" :L ,"depth" :d ,"error" :str (e )}) 103continue 104ok = word in answer 105found += ok 106f" { L :>5 } depth { d :>3 } %: { 'FOUND' if ok else 'missed' } ( { n :, } prompt tokens, { secs :.0f } s)" 107+ ("" if ok else f" answer: { answer . strip ()[: 80 ]!r } " ),flush = True ) 108rows .append ({"length" :L ,"depth" :d ,"prompt_tokens" :n ,"seconds" :round (secs ,1 ),"found" :ok , 109"word" :word ,"answer" :answer .strip ()[:200 ]}) 110done = [r for r in rows if "found" in r ] 111f" { found } of { len ( done ) } found" ) 112if a .out : 113Path (a .out ).write_text (json .dumps (rows ,indent = 1 ),encoding = "utf-8" ) 114return 0 if done and found == len (done )else 1 115 116 117if __name__ == "__main__" : 118sys .exit (main ())