okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b3e73dbfb
main
1#!/usr/bin/env python3 2"""The quant quality yardstick (MODEL-UPDATE.md, Phase 0): teacher-forced top-1 agreement and KL of a quant against 3Q8_0, on one fixed text set (data/quant_quality/v1: code, docs, English, other languages, an agent transcript). 4 5python tools/quant_quality.py ids --tokenizer DIR [--set data/quant_quality/v1] [--out set.ids.json] 6tokenizes the set (each segment cut to --seg-tokens, default 1000) - the ids file is committed with the set 7(data/quant_quality/v1/set.ids.json), so a box without the tokenizer scores the same positions 8python tools/quant_quality.py run --config CFG.json --out RUN.tsv [--ids set.ids.json] [--env K=V ...] [--gpu-experts] 9one `strata --serve` engine (the config's exe and args), every segment one request whose tokens are all read 10through the decode windows (--short-read), where STRATA_LOGPOS / STRATA_LOGPOS_TOPK=64 write, per position, 11the log-probability of the text's next token and the 64 most likely tokens. Fixed: the experts on the CPU 12(one VRAM slot, --expert-cache 1: the verify windows need a profile-filled tier, so the config must have 13--expert-profile; --gpu-experts: 1500 slots), no expert adaptation, no PCIe share, no suffix drafts, no prompt 14cache, FP16 K/V, STRATA_ROUTE_TAIL_SKIP=0, STRATA_PREFILL_CPU_SHARE=0. RUN.tsv + RUN.tsv.seg.json (line ranges). 15python tools/quant_quality.py compare REF.tsv RUN.tsv [...] (REF = the Q8_0 run) 16per segment and overall: top-1 agreement (same argmax), mean / p99 KL(REF || RUN) over REF's 64 most likely 17tokens (both renormalized to that set; a token RUN does not list gets RUN's 64th log-probability), and the 18perplexity of the text under each. 19 20The RUN.tsv rows are the engine's STRATA_LOGPOS format: pos, target id, logp(target), argmax id, logp(argmax), 21argmax==target, logp(<|im_end|>), logp(target without <|im_end|>), then 64 `id:logp` fields (natural log). 22""" 23from __future__import annotations 24 25import argparse 26import json 27import math 28import os 29import pathlib 30import subprocess 31import sys 32import time 33 34HERE = pathlib .Path (__file__ ).resolve ().parent 35SET_DIR = HERE .parent / "data" / "quant_quality" / "v1" 36SEGMENTS = ["code" ,"docs" ,"english" ,"multilingual" ,"agent" ] 37TOPK = 64 38FIXED = ["--expert-cache" ,"1" ,"--adapt-every" ,"100000" ,"--pcie-frac" ,"0" ,"--suffix-draft" ,"0" , 39"--prompt-cache" ,"0" ,"--kv" ,"fp16" ] 40FIXED_ENV = {"STRATA_ROUTE_TAIL_SKIP" :"0" ,"STRATA_PREFILL_CPU_SHARE" :"0" ,"STRATA_PCIE_FRAC_DEFAULT" :"old" } 41# config args the yardstick replaces (value-taking) or drops (flags) 42DROP_VALUE = {"--expert-cache" ,"--adapt-every" ,"--pcie-frac" ,"--suffix-draft" ,"--prompt-cache" ,"--max-context" , 43"--prefill" ,"--prompt-cache-every" ,"--short-read" ,"--conversation-cache-mib" ,"--eos-ids" , 44"--kv" ,"--kv-resident" }# (--resident-budget-gib stays: a PC whose RAM does not hold the experts) 45DROP_FLAG = {"--serve" ,"--vision" ,"--resident-experts" ,"--resident-cpu-experts" } 46 47 48# ------------------------------------------------------------------------------------------------ ids 49def cmd_ids (a )-> int : 50sys .path .insert (0 ,str (HERE )) 51import strata_tokenizer as ST # noqa: E402 52tp = pathlib .Path (a .tokenizer ) 53vocab = json .loads ((tp / "vocab.json" ).read_text (encoding = "utf-8" )) 54toks = [None ]* len (vocab ) 55for t ,i in vocab .items (): 56toks [i ]= t 57tok = ST .Tokenizer (toks , (tp / "merges.txt" ).read_text (encoding = "utf-8" ).split ("\n" ), 58json .loads ((tp / "token_type.json" ).read_text ())) 59segs = [] 60for name in SEGMENTS : 61text = (pathlib .Path (a .set )/ f" { name } .txt" ).read_text (encoding = "utf-8" ) 62ids = tok .encode (text ,parse_special = (name == "agent" )) 63if len (ids )< a .seg_tokens : 64raise SystemExit (f" { name } : only { len ( ids ) } tokens (< { a . seg_tokens } )" ) 65segs .append ({"name" :name ,"ids" :ids [:a .seg_tokens ]}) 66f" { name } : { len ( ids ) } tokens, kept { a . seg_tokens } " ) 67out = pathlib .Path (a .out or (pathlib .Path (a .set )/ "set.ids.json" )) 68out .write_text (json .dumps ({"version" :pathlib .Path (a .set ).name ,"seg_tokens" :a .seg_tokens ,"vocab_size" :len (toks ),"segments" :segs })) 69f"wrote { out } " ) 70return 0 71 72 73# ------------------------------------------------------------------------------------------------ run 74def mem_available_gb ()-> float : 75try : 76for line in open ("/proc/meminfo" ): 77if line .startswith ("MemAvailable:" ): 78return int (line .split ()[1 ])/ 1048576 79except OSError : 80pass 81return float ("inf" ) 82 83 84def engine_args (cfg :dict ,gpu_experts ,seg_tokens :int )-> list [str ]: 85base ,out ,i = list (cfg ["args" ]), [],0 86while i < len (base ): 87x = base [i ] 88if x in DROP_FLAG : 89i += 1 90continue 91if x in DROP_VALUE : 92i += 2 93continue 94out .append (x ) 95i += 1 96fixed = list (FIXED ) 97if gpu_experts : 98fixed [1 ]= gpu_experts if isinstance (gpu_experts ,str )else "1500" 99return [cfg ["exe" ],"--serve" ,* out ,* fixed ,"--max-context" ,str (seg_tokens + 512 ), 100"--short-read" ,str (seg_tokens + 64 ),"--prefill" ,"512" ] 101 102 103def check_ids_vocab (st :dict ,cfg :dict ,ids_path :str )-> None : 104"""A wrong ids file fails here, loudly: every id must be inside the model's vocabulary (the vocabulary of the config's tokenizer 105folder when it names one, else the size the ids file recorded when `ids` made it), or the run reads nonsense - the committed 106data/quant_quality/v1/set.ids.json is tokenized for Qwen (ids up to 248,069), not for DeepSeek's 129,280.""" 107vocab = None 108tdir = cfg .get ("tokenizer" ) 109if tdir and (pathlib .Path (tdir )/ "vocab.json" ).is_file (): 110vocab = len (json .loads ((pathlib .Path (tdir )/ "vocab.json" ).read_text (encoding = "utf-8" ))) 111elif st .get ("vocab_size" ): 112vocab = int (st ["vocab_size" ]) 113if not vocab : 114return 115for s in st ["segments" ]: 116mx = max (s ["ids" ])if s ["ids" ]else - 1 117if mx >= vocab : 118raise SystemExit (f" { ids_path } : segment ' { s [ 'name' ] } ' has token id { mx } >= the model's vocabulary ( { vocab } ): this ids file was " 119f"made with another tokenizer; make one with `quant_quality.py ids --tokenizer <the model's tokenizer folder>`" ) 120 121 122def cmd_run (a )-> int : 123cfg = json .load (open (a .config ,encoding = "utf-8-sig" )) 124st = json .load (open (a .ids )) 125check_ids_vocab (st ,cfg ,a .ids ) 126out = pathlib .Path (a .out ).resolve () 127out .parent .mkdir (parents = True ,exist_ok = True ) 128if out .exists (): 129out .unlink () 130env = dict (os .environ ) 131env .update (cfg .get ("env" , {})) 132if cfg .get ("lib_dirs" ): 133env ["LD_LIBRARY_PATH" ]= ":" .join (cfg ["lib_dirs" ]+ [env .get ("LD_LIBRARY_PATH" ,"" )]) 134env .update (FIXED_ENV ) 135for kv in a .env or []: 136k ,_ ,v = kv .partition ("=" ) 137env [k ]= v 138env ["STRATA_LOGPOS" ]= str (out ) 139env ["STRATA_LOGPOS_TOPK" ]= str (TOPK ) 140if mem_available_gb ()< a .min_free_gb : 141raise SystemExit (f"only { mem_available_gb ():.0f } GB available (< { a . min_free_gb } ): not starting an engine" ) 142args = engine_args (cfg ,a .gpu_experts ,st ["seg_tokens" ]) 143if a .wrap : 144args = a .wrap .split ()+ args 145errf = open (str (out )+ ".stderr.txt" ,"w" ) 146"engine:" ," " .join (args ),flush = True ) 147p = subprocess .Popen (args ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = errf ,text = True , 148cwd = cfg .get ("cwd" ),env = env ,bufsize = 1 ) 149for line in p .stdout : 150if line .startswith ("READY" ): 151break 152else : 153raise SystemExit (f"the engine ended before READY (exit { p . wait () } ); see { out } .stderr.txt" ) 154segs ,info = [], [] 155 156def lines ()-> int : 157return sum (1 for _ in open (out ))if out .exists ()else 0 158 159for s in st ["segments" ]: 160n0 ,t0 = lines (),time .time () 161p .stdin .write ("GEN 1 " + "," .join (map (str ,s ["ids" ]))+ "\n" ) 162p .stdin .flush () 163done = None 164for line in p .stdout : 165if line .startswith (("DONE" ,"ERR" )): 166done = line .strip () 167break 168if done is None or not done .startswith ("DONE" )or "nonfinite" in done : 169p .kill () 170raise SystemExit (f" { s [ 'name' ] } : the engine answered { done !r } ; see { out } .stderr.txt" ) 171n1 = lines () 172segs .append ({"name" :s ["name" ],"first_line" :n0 ,"end_line" :n1 }) 173info .append (f" { s [ 'name' ] } : { n1 - n0 } positions, { time . time () - t0 :.1f } s" ) 174info [- 1 ],flush = True ) 175if n1 - n0 < len (s ["ids" ])// 2 : 176p .kill () 177raise SystemExit (f" { s [ 'name' ] } : only { n1 - n0 } positions were scored (the prompt took the batched path?)" ) 178p .stdin .write ("QUIT\n" ) 179p .stdin .flush () 180try : 181p .wait (timeout = 600 ) 182except subprocess .TimeoutExpired : 183p .kill () 184errf .close () 185err = pathlib .Path (str (out )+ ".stderr.txt" ).read_text (errors = "replace" ) 186cache = [l for l in err .splitlines ()if "expert cache" in l ][:3 ] 187pathlib .Path (str (out )+ ".seg.json" ).write_text (json .dumps ({"segments" :segs ,"config" :a .config , 188"args" :args ,"env" :a .env or [], 189"expert_cache_lines" :cache },indent = 1 )) 190return 0 191 192 193# ------------------------------------------------------------------------------------------------ prompt path 194PROMPT_LENS = (256 ,512 ,768 ,1000 ) 195 196 197def cmd_prompt (a )-> int : 198"""The batched prompt path's answer: every segment's first 256 / 512 / 768 / 1000 tokens as a prompt (one request 199each, no prompt cache), and the logits after it (STRATA_DUMP_FIRST_LOGITS: float32, the whole vocabulary).""" 200cfg = json .load (open (a .config ,encoding = "utf-8-sig" )) 201st = json .load (open (a .ids )) 202out = pathlib .Path (a .out ).resolve () 203out .mkdir (parents = True ,exist_ok = True ) 204for f in out .glob ("first.*" ): 205f .unlink () 206env = dict (os .environ ) 207env .update (cfg .get ("env" , {})) 208if cfg .get ("lib_dirs" ): 209env ["LD_LIBRARY_PATH" ]= ":" .join (cfg ["lib_dirs" ]+ [env .get ("LD_LIBRARY_PATH" ,"" )]) 210env .update (FIXED_ENV ) 211for kv in a .env or []: 212k ,_ ,v = kv .partition ("=" ) 213env [k ]= v 214env ["STRATA_DUMP_FIRST_LOGITS" ]= str (out / "first" ) 215if mem_available_gb ()< a .min_free_gb : 216raise SystemExit (f"only { mem_available_gb ():.0f } GB available (< { a . min_free_gb } ): not starting an engine" ) 217args = engine_args (cfg ,a .gpu_experts ,max (PROMPT_LENS )) 218k = args .index ("--short-read" ) 219del args [k :k + 2 ]# the default (64): these prompts take the batched prompt path 220k = args .index ("--prefill" ) 221args [k + 1 ]= "auto" 222if a .wrap : 223args = a .wrap .split ()+ args 224errf = open (out / "stderr.txt" ,"w" ) 225"engine:" ," " .join (args ),flush = True ) 226p = subprocess .Popen (args ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = errf ,text = True , 227cwd = cfg .get ("cwd" ),env = env ,bufsize = 1 ) 228for line in p .stdout : 229if line .startswith ("READY" ): 230break 231else : 232raise SystemExit (f"the engine ended before READY (exit { p . wait () } ); see { out } /stderr.txt" ) 233index = [] 234for s in st ["segments" ]: 235for n in PROMPT_LENS : 236p .stdin .write ("GEN 1 " + "," .join (map (str ,s ["ids" ][:n ]))+ "\n" ) 237p .stdin .flush () 238done = None 239for line in p .stdout : 240if line .startswith (("DONE" ,"ERR" )): 241done = line .strip () 242break 243if done is None or not done .startswith ("DONE" )or "nonfinite" in done : 244p .kill () 245raise SystemExit (f" { s [ 'name' ] } { n } : the engine answered { done !r } " ) 246index .append ({"segment" :s ["name" ],"tokens" :n }) 247p .stdin .write ("QUIT\n" ) 248p .stdin .flush () 249try : 250p .wait (timeout = 600 ) 251except subprocess .TimeoutExpired : 252p .kill () 253errf .close () 254 (out / "index.json" ).write_text (json .dumps ({"requests" :index ,"args" :args ,"env" :a .env or []},indent = 1 )) 255f" { len ( index ) } prompts" ) 256return 0 257 258 259def cmd_pcompare (a )-> int : 260import numpy as np 261ref = pathlib .Path (a .ref ) 262idx = json .loads ((ref / "index.json" ).read_text ())["requests" ] 263 264def logp (d ,i ): 265x = np .fromfile (d / f"first. { i } " ,dtype = np .float32 ).astype (np .float64 ) 266x -= x .max () 267return x - np .log (np .exp (x ).sum ()) 268 269f"reference: { ref } " ) 270for run in a .runs : 271r = pathlib .Path (run ) 272kls ,agree = [],0 273for i in range (len (idx )): 274if not (r / f"first. { i } " ).exists (): 275continue 276lr ,la = logp (ref ,i ),logp (r ,i ) 277pr = np .exp (lr ) 278kls .append (float ((pr * (lr - la )).sum ())) 279agree += int (lr .argmax ()== la .argmax ()) 280kls .sort () 281n = len (kls ) 282f" { r . name :40s } prompts { n :3d } top-1 { 100 * agree / max ( n , 1 ):6.2f } % KL mean { sum ( kls ) / max ( n , 1 ):.5f } " 283f"median { kls [ n // 2 ] if n else float ( 'nan' ):.5f } max { kls [ - 1 ] if n else float ( 'nan' ):.5f } " ) 284return 0 285 286 287# ------------------------------------------------------------------------------------------------ compare 288def read_run (path :str )-> dict : 289rows = open (path ).read ().splitlines () 290segs = json .load (open (path + ".seg.json" ))["segments" ] 291out = {} 292for s in segs : 293d = {} 294for line in rows [s ["first_line" ]:s ["end_line" ]]: 295f = line .split ("\t" ) 296if len (f )< 8 + TOPK : 297continue 298d [int (f [0 ])]= (int (f [1 ]),float (f [2 ]),int (f [3 ]), [(int (x ),float (y ))for x ,y in 299 (z .split (":" )for z in f [8 :8 + TOPK ])]) 300out [s ["name" ]]= d 301return out 302 303 304def compare (ref :dict ,run :dict )-> dict : 305res ,allk ,tot = {}, [], {"n" :0 ,"agree" :0 ,"nll_r" :0.0 ,"nll_a" :0.0 ,"kl" :0.0 } 306for name ,rr in ref .items (): 307ra = run .get (name , {}) 308pos = sorted (set (rr )& set (ra )) 309n = agree = 0 310kls ,nll_r ,nll_a = [],0.0 ,0.0 311for q in pos : 312tr ,lr ,topr ,kr = rr [q ] 313ta ,la ,topa ,ka = ra [q ] 314if tr != ta : 315raise SystemExit (f" { name } pos { q } : target { tr } != { ta } (not the same text)" ) 316n += 1 317agree += topr == topa 318nll_r -= lr 319nll_a -= la 320da = dict (ka ) 321floor = min (b for _ ,b in ka ) 322pr = [math .exp (b )for _ ,b in kr ] 323pa = [math .exp (da .get (i ,floor ))for i ,_ in kr ] 324sr ,sa = sum (pr ),sum (pa ) 325kls .append (sum ((x / sr )* math .log ((x / sr )/ (y / sa ))for x ,y in zip (pr ,pa )if x > 0 )) 326allk += kls 327if n : 328res [name ]= {"positions" :n ,"top1" :agree / n ,"kl" :sum (kls )/ n , 329"ppl_ref" :math .exp (nll_r / n ),"ppl" :math .exp (nll_a / n )} 330tot ["n" ]+= n 331tot ["agree" ]+= agree 332tot ["nll_r" ]+= nll_r 333tot ["nll_a" ]+= nll_a 334tot ["kl" ]+= sum (kls ) 335n = max (tot ["n" ],1 ) 336allk .sort () 337res ["all" ]= {"positions" :tot ["n" ],"top1" :tot ["agree" ]/ n ,"kl" :tot ["kl" ]/ n , 338"kl_p99" :allk [int (0.99 * (len (allk )- 1 ))]if allk else float ("nan" ), 339"ppl_ref" :math .exp (tot ["nll_r" ]/ n ),"ppl" :math .exp (tot ["nll_a" ]/ n )} 340return res 341 342 343def cmd_compare (a )-> int : 344ref = read_run (a .ref ) 345f"reference: { a . ref } " ) 346f" { 'run' :40s } { 'segment' :13s } { 'pos' :>5s } { 'top1' :>7s } { 'KL' :>8s } { 'KL p99' :>8s } { 'PPL' :>7s } { 'PPL ref' :>7s } " ) 347allres = {} 348for path in a .runs : 349r = compare (ref ,read_run (path )) 350allres [path ]= r 351for seg ,v in r .items (): 352if seg != "all" and not a .segments : 353continue 354f" { pathlib . Path ( path ). name [: 40 ]:40s } { seg :13s } { v [ 'positions' ]:5d } { 100 * v [ 'top1' ]:6.2f } % " 355f" { v [ 'kl' ]:8.5f } { v . get ( 'kl_p99' , float ( 'nan' )):8.4f } { v [ 'ppl' ]:7.3f } { v [ 'ppl_ref' ]:7.3f } " ) 356if a .json : 357pathlib .Path (a .json ).write_text (json .dumps (allres ,indent = 1 )) 358return 0 359 360 361def main ()-> int : 362ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 363sub = ap .add_subparsers (dest = "cmd" ,required = True ) 364p = sub .add_parser ("ids" ) 365p .add_argument ("--tokenizer" ,required = True ) 366p .add_argument ("--set" ,default = str (SET_DIR )) 367p .add_argument ("--seg-tokens" ,type = int ,default = 1000 ) 368p .add_argument ("--out" ) 369p = sub .add_parser ("run" ) 370p .add_argument ("--config" ,required = True ) 371p .add_argument ("--out" ,required = True ) 372p .add_argument ("--ids" ,default = str (SET_DIR / "set.ids.json" )) 373p .add_argument ("--env" ,action = "append" ) 374p .add_argument ("--gpu-experts" ,nargs = "?" ,const = True ,default = False , 375help = "--expert-cache 1500 (or the N given, e.g. auto) instead of one slot (the experts on the GPU kernels)" ) 376p .add_argument ("--min-free-gb" ,type = float ,default = 16 ) 377p .add_argument ("--wrap" ,help = "a command prefix for the engine, e.g. 'systemd-run --user --scope -p MemoryMax=200G'" ) 378p = sub .add_parser ("prompt" ,help = "the batched prompt path's next-token logits after 20 prompts (a directory)" ) 379p .add_argument ("--config" ,required = True ) 380p .add_argument ("--out" ,required = True ) 381p .add_argument ("--ids" ,default = str (SET_DIR / "set.ids.json" )) 382p .add_argument ("--env" ,action = "append" ) 383p .add_argument ("--gpu-experts" ,action = "store_true" ) 384p .add_argument ("--min-free-gb" ,type = float ,default = 16 ) 385p .add_argument ("--wrap" ) 386p = sub .add_parser ("compare" ) 387p .add_argument ("ref" ) 388p .add_argument ("runs" ,nargs = "+" ) 389p .add_argument ("--segments" ,action = "store_true" ) 390p .add_argument ("--json" ) 391p = sub .add_parser ("pcompare" ,help = "full-vocabulary KL and top-1 of `prompt` directories against a reference one" ) 392p .add_argument ("ref" ) 393p .add_argument ("runs" ,nargs = "+" ) 394a = ap .parse_args () 395return {"ids" :cmd_ids ,"run" :cmd_run ,"prompt" :cmd_prompt ,"compare" :cmd_compare , 396"pcompare" :cmd_pcompare }[a .cmd ](a ) 397 398 399if __name__ == "__main__" : 400raise SystemExit (main ())