okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0479b72e9
main
1#!/usr/bin/env python3 2"""Runs strata-vision twice (--tower A and --tower B, default mtmd and own) over the same pictures and compares the embeddings. 3 4python compare_towers.py --helper <strata-vision> --compare <strata-vision-own-compare> --mmproj <mmproj.gguf> --model <text model .gguf> 5--out <dir> [--a mtmd] [--b own] [--gpu] [--threads N] [--max-tokens N] [--min-tokens N] 6[--repeat K] [--env NAME=VALUE ...] <image> [<image> ...] 7 8Per picture: the tokens, the time of each tower (the first encode, then --repeat K further encodes of the same picture, median reported), and the 9cosine of the two embedding files (global = both files as one vector; tokmin / tokmean = per-token cosines), max |difference|. 10The last lines are the summary the gate asks for: minimum and mean cosine over the pictures. Exit 0 when every picture was read by both and 11the minimum global cosine is at least --min-cos (default 0.999); 1 otherwise. Standard library only. 12""" 13import argparse 14import os 15import statistics 16import subprocess 17import sys 18import time 19 20 21class Reader : 22def __init__ (self ,exe ,tower ,a ,gpu ,label ): 23args = [exe ,"--mmproj" ,a .mmproj ,"--model" ,a .model ,"--tower" ,tower ] 24if gpu : 25args .append ("--gpu" ) 26if a .threads : 27args += ["--threads" ,str (a .threads )] 28if a .max_tokens : 29args += ["--max-tokens" ,str (a .max_tokens )] 30if a .min_tokens : 31args += ["--min-tokens" ,str (a .min_tokens )] 32env = dict (os .environ ) 33for kv in a .env : 34k ,_ ,v = kv .partition ("=" ) 35env [k ]= v 36self .tower = tower 37self .t0 = time .time () 38self .p = subprocess .Popen (args ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = open (os .path .join (a .out ,label + ".stderr" ),"w" ), 39text = True ,env = env ) 40line = self .p .stdout .readline ().strip () 41self .ready = line .startswith ("READY" ) 42self .start_s = time .time ()- self .t0 43if not self .ready : 44raise SystemExit ("%s reader did not start: %r" % (tower ,line )) 45 46def enc (self ,img ,out ): 47self .p .stdin .write ("ENC %s %s\n" % (img ,out )) 48self .p .stdin .flush () 49return self .p .stdout .readline ().strip () 50 51def close (self ): 52try : 53self .p .stdin .write ("QUIT\n" ) 54self .p .stdin .flush () 55self .p .wait (timeout = 30 ) 56except Exception : 57self .p .kill () 58 59 60def main (): 61ap = argparse .ArgumentParser () 62ap .add_argument ("--helper" ,required = True ) 63ap .add_argument ("--compare" ,required = True ) 64ap .add_argument ("--mmproj" ,required = True ) 65ap .add_argument ("--model" ,required = True ) 66ap .add_argument ("--out" ,required = True ) 67ap .add_argument ("--a" ,default = "mtmd" ) 68ap .add_argument ("--b" ,default = "own" ) 69ap .add_argument ("--a-dir" ,default = "" ,help = "A's embeddings from an earlier run: <dir>/<picture name>.sve (no reader is started for A)" ) 70ap .add_argument ("--helper-b" ,default = "" ,help = "another program for B (e.g. strata-vision-own); default: --helper" ) 71ap .add_argument ("--gpu" ,action = "store_true" ,help = "both readers on the GPU" ) 72ap .add_argument ("--gpu-a" ,action = "store_true" ) 73ap .add_argument ("--gpu-b" ,action = "store_true" ) 74ap .add_argument ("--threads" ,type = int ,default = 0 ) 75ap .add_argument ("--max-tokens" ,type = int ,default = 0 ) 76ap .add_argument ("--min-tokens" ,type = int ,default = 0 ) 77ap .add_argument ("--repeat" ,type = int ,default = 0 ) 78ap .add_argument ("--min-cos" ,type = float ,default = 0.999 ) 79ap .add_argument ("--env" ,action = "append" ,default = []) 80ap .add_argument ("images" ,nargs = "+" ) 81a = ap .parse_args () 82os .makedirs (a .out ,exist_ok = True ) 83la = a .a + ("-gpu" if a .gpu or a .gpu_a else "" ) 84lb = a .b + ("-gpu" if a .gpu or a .gpu_b else "" ) 85if la == lb : 86lb += "-2" 87for t in (la ,lb ): 88os .makedirs (os .path .join (a .out ,t ),exist_ok = True ) 89 90# --a-dir: A's embeddings were made earlier (<dir>/<picture name>.sve, from a run of the same limits); no reader is started for A 91ra = None if a .a_dir else Reader (a .helper ,a .a ,a ,a .gpu or a .gpu_a ,la ) 92rb = Reader (a .helper_b or a .helper ,a .b ,a ,a .gpu or a .gpu_b ,lb ) 93if ra : 94ra .label = la 95rb .label = lb 96"start: %s %.1f s, %s %.1f s" % (la ,ra .start_s if ra else 0.0 ,lb ,rb .start_s ),flush = True ) 97"%-24s %11s %6s %9s %9s %9s %9s %9s %10s" % ("picture" ,"size" ,"tokens" ,la + " ms" ,lb + " ms" ,"global" ,"tokmin" ,"tokmean" ,"maxabs" ),flush = True ) 98glob ,tmin ,ok_all = [], [],True 99for img in a .images : 100name = os .path .basename (img ) 101outs ,res ,times = {}, {}, {} 102for r in (ra ,rb ): 103if r is None : 104outs [la ]= os .path .join (a .a_dir ,name + ".sve" ) 105res [la ]= "OK" if os .path .isfile (outs [la ])else "ERR no file " + outs [la ] 106times [la ]= float ("nan" ) 107continue 108outs [r .label ]= os .path .join (a .out ,r .label ,name + ".sve" ) 109res [r .label ]= r .enc (os .path .abspath (img ),outs [r .label ]) 110ms = [float (res [r .label ].split ()[4 ])]if res [r .label ].startswith ("OK" )else [] 111for _ in range (a .repeat if ms else 0 ): 112again = r .enc (os .path .abspath (img ),outs [r .label ]) 113if again .startswith ("OK" ): 114ms .append (float (again .split ()[4 ])) 115times [r .label ]= statistics .median (ms [1 :]if len (ms )> 1 else ms )if ms else float ("nan" ) 116if not (res [la ].startswith ("OK" )and res [lb ].startswith ("OK" )): 117"%-24s FAILED: %s: %s | %s: %s" % (name ,la ,res [la ],lb ,res [lb ]),flush = True ) 118ok_all = False 119continue 120c = subprocess .run ([a .compare ,outs [la ],outs [lb ]],capture_output = True ,text = True ).stdout .strip () 121if not c .startswith ("n=" ): 122"%-24s %s" % (name ,c ),flush = True ) 123ok_all = False 124continue 125kv = dict (p .split ("=" )for p in c .split ()) 126size = "%sx%s" % (kv ["nx" ],kv ["ny" ]) 127glob .append (float (kv ["global" ])) 128tmin .append (float (kv ["tokmin" ])) 129"%-24s %11s %6s %9.0f %9.0f %9s %9s %9s %10s" % (name ,size ,kv ["n" ],times [la ],times [lb ],kv ["global" ],kv ["tokmin" ],kv ["tokmean" ],kv ["maxabs" ]),flush = True ) 130if ra : 131ra .close () 132rb .close () 133if glob : 134"SUMMARY %s vs %s: %d pictures, global cosine min %.6f mean %.6f, smallest per-token cosine %.6f" % (lb ,la ,len (glob ),min (glob ),sum (glob )/ len (glob ),min (tmin ))) 135good = ok_all and glob and min (glob )>= a .min_cos 136"RESULT %s (minimum cosine %s %.4f)" % ("PASS" if good else "FAIL" ,">=" if good else "below or errors," ,a .min_cos ),flush = True ) 137return 0 if good else 1 138 139 140if __name__ == "__main__" : 141sys .exit (main ())