okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e79156ae2
main
1"""vcmp.py - the picture gate: strata-q36 against llama.cpp (mtmd) on the same GGUF + mmproj, same pictures. 2 3For each (picture, question): llama.cpp HIP (q36_mtmd_dump, encoder on the CPU like strata-vision's) gives the prompt's 4chunks, its greedy answer and every step's full logits; the encoder file of strata-vision (venc.py) is laid over the same 5ids; strata-q36 (--tokens ids --emb file --force llama's greedy ids) gives its logits on the same sequence. Reported: 6the answer text agreement, the first token's logits (top-1/top-2 both, max |diff| over the top-5), the teacher-forced 7mean KL(P_llama || Q_strata) and top-1 agreement over the steps, and - the floor - the same numbers for llama.cpp's CPU 8backend against llama.cpp HIP. 9 10python q36_vision_cmp.py --dump BIN --q36 BIN --vision BIN --model GGUF --mmproj F --out DIR --pic shapes.png --pic code4217.png 11[--lock "flock ..."] [--n 24] [--q36-args "--vision --max-context 4096"] 12""" 13from pathlib import Path 14import argparse ,json ,os ,shlex ,struct ,subprocess ,sys 15import numpy as np 16 17V = 248320 18QUESTIONS = { 19"shapes.png" : ["What text is written in the image? Answer with the text only." , 20"List every shape in the image with its colour, from left to right. One short line each." ], 21"code4217.png" : ["What text is written in the image? Answer with the text only." , 22"Describe the shapes in the image with their colours and positions, one short line each." ], 23} 24TEMPLATE = "<|im_start|>user\n<__media__>{q}<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n" 25PAD = 248056 26TEMPLATE_PAIR = ("<|im_start|>user\nPicture 1: <__media__>\nPicture 2: <__media__>\n{q}<|im_end|>\n<|im_start|>assistant\n" 27"<think>\n\n</think>\n\n" ) 28PAIR_QUESTIONS = ["What text is written in each of the two pictures? One short line for each." ] 29 30 31def run (cmd ,lock ,log ,env = None ): 32full = (shlex .split (lock )if lock else [])+ cmd 33e = dict (os .environ ) 34e .update (env or {}) 35r = subprocess .run (full ,capture_output = True ,text = True ,timeout = 3600 ,env = e ) 36open (log ,"w" ).write (r .stdout + "\n--- stderr ---\n" + r .stderr ) 37if r .returncode != 0 : 38raise SystemExit ("%s failed (rc %d), see %s" % (cmd [0 ],r .returncode ,log )) 39return r .stdout 40 41 42def parse_dump (out ): 43chunks ,gen ,first = [], [],None 44for l in out .splitlines (): 45if l .startswith ("text:" ): 46chunks .append (("text" , [int (x )for x in l .split (":" ,1 )[1 ].split ()])) 47elif l .startswith ("image:" ): 48chunks .append (("image" ,int (l .split ()[1 ]))) 49elif l .startswith ("gen:" ): 50gen = [int (x )for x in l .split (":" ,1 )[1 ].split ()] 51elif l .startswith ("first:" ): 52first = l 53return chunks ,gen ,first 54 55 56def log_softmax (x ): 57x = x .astype (np .float64 ) 58m = x .max (axis = 1 ,keepdims = True ) 59return x - m - np .log (np .exp (x - m ).sum (axis = 1 ,keepdims = True )) 60 61 62def kl_stats (p_logits ,q_logits ): 63n = min (len (p_logits ),len (q_logits )) 64lp ,lq = log_softmax (p_logits [:n ]),log_softmax (q_logits [:n ]) 65kl = (np .exp (lp )* (lp - lq )).sum (axis = 1 ) 66top1 = (p_logits [:n ].argmax (axis = 1 )== q_logits [:n ].argmax (axis = 1 )) 67return kl ,top1 68 69 70def main (): 71ap = argparse .ArgumentParser () 72ap .add_argument ("--dump" ,required = True ) 73ap .add_argument ("--q36" ,required = True ) 74ap .add_argument ("--vision" ,required = True ) 75ap .add_argument ("--venc" ,default = str (Path (__file__ ).resolve ().parent / "q36_venc.py" )) 76ap .add_argument ("--model" ,required = True ) 77ap .add_argument ("--mmproj" ,required = True ) 78ap .add_argument ("--out" ,required = True ) 79ap .add_argument ("--pic" ,action = "append" ,required = True ,help = "a picture, or a+b for one request with two pictures" ) 80ap .add_argument ("--lock" ,default = "" ) 81ap .add_argument ("--n" ,type = int ,default = 24 ) 82ap .add_argument ("--q36-args" ,default = "--vision --max-context 4096" ) 83ap .add_argument ("--floor" ,action = "store_true" ,help = "also llama.cpp CPU (ngl 0) vs HIP" ) 84ap .add_argument ("--dump-ngl" ,type = int ,default = 99 ,help = "llama.cpp's offloaded layers (a quant larger than the card: fewer)" ) 85a = ap .parse_args () 86os .makedirs (a .out ,exist_ok = True ) 87rows = [] 88for pic_spec in a .pic : 89pics = pic_spec .split ("+" )# "a.png+b.png": one request with two pictures (one <__media__> each) 90name = "+" .join (os .path .basename (p )for p in pics ) 91# the encoder's file (strata-vision, CPU): one record per picture, in prompt order 92run ([sys .executable ,a .venc ,a .vision ,a .mmproj ,a .model ,* pics ],"" ,os .path .join (a .out ,name + ".venc.log" )) 93emb = os .path .join (a .out ,name + ".sve" ) 94with open (emb ,"wb" )as f : 95for p in pics : 96f .write (open (p + ".sve" ,"rb" ).read ()) 97questions = QUESTIONS .get (name , ["Describe this image." ]if len (pics )== 1 else PAIR_QUESTIONS ) 98for qi ,q in enumerate (questions ): 99tag = "%s.q%d" % (name ,qi ) 100prompt = TEMPLATE .format (q = q )if len (pics )== 1 else TEMPLATE_PAIR .format (q = q ) 101ref_log = os .path .join (a .out ,tag + ".llama.log" ) 102logit_f = os .path .join (a .out ,tag + ".llama.logits" ) 103out = run ([a .dump ,"--model" ,a .model ,"--mmproj" ,a .mmproj ,* sum ([["--image" ,p ]for p in pics ], []), 104"--prompt" ,prompt ,"--n" ,str (a .n ), 105"--dump-full-logits" ,logit_f ,"--mm-cpu" ,"1" ,"--max-tokens" ,"1024" ,"--ngl" ,str (a .dump_ngl )],a .lock ,ref_log ) 106chunks ,gen ,first = parse_dump (out ) 107ids = [] 108for kind ,v in chunks : 109ids += v if kind == "text" else [PAD ]* v 110tot_rows ,off ,data = 0 ,0 ,open (emb ,"rb" ).read () 111while off < len (data ):# the records' row counts 112h = struct .unpack ("<5i" ,data [off :off + 20 ]) 113tot_rows += h [1 ] 114off += 20 + 4 * h [1 ]* h [4 ] 115assert tot_rows == sum (v for k ,v in chunks if k == "image" ),"the encoders disagree on the token count %d vs %s" % (tot_rows ,chunks ) 116q_logit_f = os .path .join (a .out ,tag + ".q36.logits" ) 117qout = run ([a .q36 ,"--model" ,a .model ,"--tokens" ,"," .join (map (str ,ids )),"--emb" ,emb ,"--n" ,str (a .n ), 118"--force" ,"," .join (map (str ,gen [:- 1 ])),"--dump-full-logits" ,q_logit_f ,* shlex .split (a .q36_args )], 119a .lock ,os .path .join (a .out ,tag + ".q36.log" )) 120qgen = [int (x )for x in [l for l in qout .splitlines ()if l .startswith ("gen:" )][0 ].split (":" ,1 )[1 ].split ()] 121P = np .fromfile (logit_f ,dtype = np .float32 ).reshape (- 1 ,V ) 122Q = np .fromfile (q_logit_f ,dtype = np .float32 ).reshape (- 1 ,V ) 123kl ,top1 = kl_stats (P ,Q ) 124d5 = np .abs (np .sort (P [0 ])[- 5 :]- np .sort (Q [0 ])[- 5 :]).max () 125row = {"tag" :tag ,"prompt_tokens" :len (ids ),"llama_gen" :gen ,"strata_gen_forced" :qgen , 126"first_top1_same" :bool (P [0 ].argmax ()== Q [0 ].argmax ()),"first_max_top5_diff" :float (d5 ), 127"kl_mean" :float (kl .mean ()),"kl_first" :float (kl [0 ]),"top1" :float (top1 .mean ()),"steps" :int (len (kl ))} 128if a .floor : 129fl = os .path .join (a .out ,tag + ".cpu.logits" ) 130run ([a .dump ,"--model" ,a .model ,"--mmproj" ,a .mmproj ,* sum ([["--image" ,p ]for p in pics ], []), 131"--prompt" ,prompt ,"--n" ,str (a .n ), 132"--dump-full-logits" ,fl ,"--mm-cpu" ,"1" ,"--max-tokens" ,"1024" ,"--ngl" ,"0" ,"--force" , 133"," .join (map (str ,gen [:- 1 ]))],"" ,os .path .join (a .out ,tag + ".cpu.log" )) 134C = np .fromfile (fl ,dtype = np .float32 ).reshape (- 1 ,V ) 135klc ,t1c = kl_stats (P ,C ) 136row .update ({"floor_kl_mean" :float (klc .mean ()),"floor_kl_first" :float (klc [0 ]),"floor_top1" :float (t1c .mean ()), 137"floor_first_max_top5_diff" :float (np .abs (np .sort (P [0 ])[- 5 :]- np .sort (C [0 ])[- 5 :]).max ())}) 138rows .append (row ) 139json .dumps ({k :v for k ,v in row .items ()if k not in ("llama_gen" ,"strata_gen_forced" )}),flush = True ) 140" llama :" ,gen [:16 ],flush = True ) 141" strata :" ,qgen [:16 ],"(teacher-forced on llama's ids: its own greedy at each step)" ,flush = True ) 142json .dump (rows ,open (os .path .join (a .out ,"summary.json" ),"w" ),indent = 1 ) 143 144 145if __name__ == "__main__" : 146main ()