okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4cfeaa0f4
main
1"""tools/qwen35/kl.py - teacher-forced KL for Qwen3.6-35B-A3B (NEW-MODELS-PLAN.md T1/T2): on one token sequence per 2prompt (the prompt + llama.cpp GPU's greedy answer, from a parity.py run), the next-token distributions of 3llama.cpp HIP (the reference P), llama.cpp CPU (the noise floor) and strata-q36ref. Reported: mean KL(P || Q) and 4the top-1 agreement over all steps, per engine; the plan's gate is Strata's KL within 1.5x of the floor. 5 6python tools/qwen35/kl.py --ref BIN --dump BIN --model GGUF --parity DIR --out DIR [--lock "..."] [--cpu-lock "..."] 7""" 8from __future__import annotations 9 10import argparse 11import shlex 12import subprocess 13import sys 14from pathlib import Path 15 16import numpy as np 17 18V = 248320 19EOS = 248046 # <|im_end|> 20 21 22def ids (path :Path ,key :str )-> list [int ]: 23for line in path .read_text (encoding = "utf-8" ).splitlines (): 24if line .startswith (key + ":" ): 25return [int (x )for x in line .split (":" ,1 )[1 ].split ()] 26raise SystemExit (f"no { key } : in { path } " ) 27 28 29def run (cmd :list [str ],lock :str ,log :Path )-> None : 30r = subprocess .run ((shlex .split (lock )if lock else [])+ cmd ,capture_output = True ,text = True ,timeout = 3600 ) 31log .write_text (r .stdout + "\n--- stderr ---\n" + r .stderr ,encoding = "utf-8" ) 32if r .returncode != 0 : 33raise SystemExit (f" { cmd [ 0 ] } failed (rc { r . returncode } ), see { log } " ) 34 35 36def log_softmax (x :np .ndarray )-> np .ndarray : 37x = x .astype (np .float64 ) 38m = x .max (axis = 1 ,keepdims = True ) 39return x - m - np .log (np .exp (x - m ).sum (axis = 1 ,keepdims = True )) 40 41 42def main ()-> int : 43ap = argparse .ArgumentParser () 44ap .add_argument ("--ref" ,required = True ) 45ap .add_argument ("--dump" ,required = True ) 46ap .add_argument ("--model" ,required = True ) 47ap .add_argument ("--parity" ,required = True ,help = "a parity.py output dir (its llama.cpp logs give the sequences)" ) 48ap .add_argument ("--out" ,required = True ) 49ap .add_argument ("--lock" ,default = "" ) 50ap .add_argument ("--cpu-lock" ,default = "" ) 51ap .add_argument ("--cache" ,default = "" ,help = "where llama.cpp's logits are kept between runs (default --out)" ) 52ap .add_argument ("--ref-args" ,default = "" ,help = "extra strata-q36ref arguments (e.g. '--act f32')" ) 53a = ap .parse_args () 54out ,par = Path (a .out ),Path (a .parity ) 55out .mkdir (parents = True ,exist_ok = True ) 56tags = sorted (p .name .split ("." )[0 ]for p in par .glob ("p*.llama.log" )) 57kl = {"cpu" : [],"strata" : []} 58top1 = {"cpu" : [],"strata" : []} 59kl_ans = {"cpu" : [],"strata" : []} 60top1_ans = {"cpu" : [],"strata" : []} 61for tag in tags : 62prompt ,gen = ids (par / f" { tag } .llama.log" ,"prompt" ),ids (par / f" { tag } .llama.log" ,"gen" ) 63force = "," .join (map (str ,gen )) 64toks = "," .join (map (str ,prompt )) 65cache = Path (a .cache )if a .cache else out 66f = {k : (out if k == "strata" else cache )/ f" { tag } . { k } .full" for k in ("gpu" ,"cpu" ,"strata" )} 67# llama.cpp's two runs depend only on the model and the sequence: kept in --out and reused (64 MB each) 68if not f ["gpu" ].exists (): 69run ([a .dump ,"--model" ,a .model ,"--tokens" ,toks ,"--force" ,force ,"--ngl" ,"99" ,"--dump-full-logits" , 70str (f ["gpu" ])],a .lock ,cache / f" { tag } .gpu.log" ) 71if not f ["cpu" ].exists (): 72run ([a .dump ,"--model" ,a .model ,"--tokens" ,toks ,"--force" ,force ,"--ngl" ,"0" ,"--dump-full-logits" , 73str (f ["cpu" ])],a .cpu_lock ,cache / f" { tag } .cpu.log" ) 74run ([a .ref ,"--model" ,a .model ,"--tokens" ,toks ,"--force" ,force ,"--dump-full-logits" ,str (f ["strata" ]), 75* shlex .split (a .ref_args )],a .lock ,out / f" { tag } .strata.log" ) 76P = log_softmax (np .fromfile (f ["gpu" ],dtype = np .float32 ).reshape (- 1 ,V )) 77# the answer: the steps up to and including the first <|im_end|> of the forced sequence (past it the context is 78# one no chat reaches, and its distributions are the noisiest); "all" keeps every step 79ans = gen .index (EOS )+ 1 if EOS in gen else len (P ) 80line = f" { tag } : { len ( P ) } steps ( { ans } answer)" 81per = {} 82for k in ("cpu" ,"strata" ): 83Q = log_softmax (np .fromfile (f [k ],dtype = np .float32 ).reshape (- 1 ,V )) 84n = min (len (P ),len (Q )) 85d = (np .exp (P [:n ])* (P [:n ]- Q [:n ])).sum (axis = 1 ) 86t1 = P [:n ].argmax (axis = 1 )== Q [:n ].argmax (axis = 1 ) 87kl [k ].extend (d .tolist ()) 88top1 [k ].extend (t1 .tolist ()) 89kl_ans [k ].extend (d [:ans ].tolist ()) 90top1_ans [k ].extend (t1 [:ans ].tolist ()) 91per [k ]= d 92line += f"; { k } : KL { d . mean ():.5f } (answer { d [: ans ]. mean ():.5f } ) top-1 { t1 . mean ():.3f } " 93np .savez (out / f" { tag } .kl.npz" ,answer = ans ,** per ) 94f ["strata" ].unlink (missing_ok = True ) 95line ,flush = True ) 96for name ,K ,T in (("all steps" ,kl ,top1 ), ("answers only" ,kl_ans ,top1_ans )): 97f"-- { name } " ) 98for k in ("cpu" ,"strata" ): 99f" { k :6s } vs llama.cpp HIP: mean KL { np . mean ( K [ k ]):.5f } (median { np . median ( K [ k ]):.6f } , p99 " 100f" { np . percentile ( K [ k ], 99 ):.4f } ), top-1 { np . mean ( T [ k ]):.4f } over { len ( K [ k ]) } steps" ) 101f"ratio strata / floor: { np . mean ( K [ 'strata' ]) / max ( np . mean ( K [ 'cpu' ]), 1e-12 ):.2f } " ) 102return 0 103 104 105if __name__ == "__main__" : 106sys .exit (main ())