okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
60d431e2a
main
1#!/usr/bin/env python3 2"""The GPU gate of the own vision tower (rule 6 of RESULTS-OWN-3V.md): our GPU tower against the float32 reference, and no noisier than mtmd's GPU path. 3 4python3 gate_gpu.py --helper <strata-vision> --compare <strata-vision-own-compare> --mmproj <mmproj.gguf> --model <text model .gguf> --out <dir> 5[--max-tokens 1024] [--repeat 4] [--ref-dir <dir of our float32 reference's <picture>.sve>] [--cpu-dir <dir of stored mtmd-CPU <picture>.sve>] 6<image> [<image> ...] 7 8The reference is our float32 tower (VitRef: the own tower on the CPU with STRATA_VIT_CPU=ref), from --ref-dir where it holds the picture's file, else made 9here. Until 11-14 the reference was mtmd's CPU path; mtmd itself sits up to 0.0168 below float32 (16 pictures: global cosine min 0.983 on its GPU, 0.998 10on its CPU), so it stays only as an information column. One strata-vision per reader (VitRef on the CPU, mtmd on the CPU unless --cpu-dir gives its 11files, mtmd on the GPU, own on the GPU), every picture through each. Per picture: 12main cosine(own GPU, float32) must be >= --min-cos (0.999) 13floor cosine(mtmd GPU, float32) what llama.cpp's reader gives 14no-worse main >= floor - 1e-4 or main >= 0.9999 our GPU tower is at least as close to float32 as mtmd-GPU is (the coordinator's tolerance, 11-09) 15info cosine(own GPU, mtmd CPU), cosine(own GPU, mtmd GPU) (printed, no pass / fail) 16and the times of the two GPU readers (median of --repeat further encodes, after the first); the GPU memory (nvidia-smi, rocm-smi or Linux DRM fdinfo); whether 17our GPU tower gives byte-identical output on every encode (REPEATABLE line; information, the exit code does not depend on it). Exit 0 when every picture passes main and no-worse. Standard library only. 18""" 19import argparse 20import hashlib 21import os 22import statistics 23import subprocess 24import sys 25 26 27def fdinfo_mib (pid ): 28"""Device-local memory of a process from Linux's DRM fdinfo (/proc/<pid>/fdinfo; i915 / xe drm-total-local0 or drm-resident-local0, amdgpu 29drm-memory-vram), the largest over its DRM files, MiB; 0 where it cannot be read (no such files, another OS).""" 30best = 0 31d = "/proc/%d/fdinfo" % pid 32try : 33fds = os .listdir (d ) 34except OSError : 35return 0 36for fd in fds : 37try : 38with open (os .path .join (d ,fd ))as f : 39txt = f .read () 40except OSError : 41continue 42if "drm-driver" not in txt : 43continue 44for line in txt .splitlines (): 45k ,_ ,v = line .partition (":" ) 46if k .strip ()not in ("drm-total-local0" ,"drm-resident-local0" ,"drm-memory-vram" ,"drm-total-vram0" ,"drm-resident-vram0" ): 47continue 48parts = v .split () 49if not parts : 50continue 51n = float (parts [0 ]) 52unit = parts [1 ]if len (parts )> 1 else "" 53mib = {"KiB" :n / 1024.0 ,"MiB" :n ,"GiB" :n * 1024.0 }.get (unit ,n / 1048576.0 ) 54best = max (best ,int (mib )) 55return best 56 57 58def mac_footprint_mib (pid ): 59"""macOS: the process's physical footprint (what Activity Monitor calls Memory; on unified memory it includes the GPU buffers), MiB, from the 60`footprint` tool (no root needed for our own process); 0 elsewhere or when it cannot be read.""" 61if sys .platform != "darwin" : 62return 0 63try : 64out = subprocess .run (["footprint" ,"-p" ,str (pid )],capture_output = True ,text = True ,timeout = 60 ).stdout 65except Exception :# noqa: BLE001 66return 0 67for line in out .splitlines (): 68low = line .lower () 69if "phys_footprint:" in low or low .strip ().startswith ("footprint:" ): 70t = line .split (":" ,1 )[1 ].split () 71if len (t )>= 2 : 72try : 73n = float (t [0 ]) 74except ValueError : 75continue 76return int ({"KB" :n / 1024.0 ,"MB" :n ,"GB" :n * 1024.0 }.get (t [1 ].upper (),0 )) 77return 0 78 79 80class Reader : 81def __init__ (self ,exe ,tower ,mmproj ,model ,gpu ,max_tokens ,threads ,out ,label ,env = None ): 82args = [exe ,"--mmproj" ,mmproj ,"--model" ,model ,"--tower" ,tower ] 83if gpu : 84args .append ("--gpu" ) 85if max_tokens : 86args += ["--max-tokens" ,str (max_tokens )] 87if threads and not gpu : 88args += ["--threads" ,str (threads )] 89self .label = label 90self .p = subprocess .Popen (args ,stdin = subprocess .PIPE ,stdout = subprocess .PIPE ,stderr = open (os .path .join (out ,label + ".stderr" ),"w" ),text = True , 91env = dict (os .environ ,** env )if env else None ) 92line = self .p .stdout .readline ().strip () 93if not line .startswith ("READY" ): 94raise SystemExit ("%s reader did not start: %r" % (label ,line )) 95 96peak_mib = 0 97 98def vram (self ): 99"""This reader's GPU memory now (nvidia-smi's compute-apps list, by pid); remembers the peak. 0 when it cannot be read.""" 100try : 101out = subprocess .run (["nvidia-smi" ,"--query-compute-apps=pid,used_memory" ,"--format=csv,noheader,nounits" ],capture_output = True ,text = True , 102timeout = 30 ).stdout 103for line in out .splitlines (): 104pid ,_ ,mem = line .partition ("," ) 105if pid .strip ()== str (self .p .pid )and mem .strip ().isdigit (): 106self .peak_mib = max (self .peak_mib ,int (mem .strip ())) 107except Exception :# noqa: BLE001 108pass 109try :# AMD: rocm-smi's KFD process list: PID NAME #GPUs VRAM USED(B) SDMA USED CU OCCUPANCY 110out = subprocess .run (["rocm-smi" ,"--showpids" ],capture_output = True ,text = True ,timeout = 30 ).stdout 111for line in out .splitlines (): 112t = line .split () 113if len (t )>= 6 and t [0 ]== str (self .p .pid )and t [- 3 ].isdigit (): 114self .peak_mib = max (self .peak_mib ,int (t [- 3 ])// (1 << 20 )) 115except Exception :# noqa: BLE001 116pass 117self .peak_mib = max (self .peak_mib ,fdinfo_mib (self .p .pid ))# Linux DRM: Intel (i915 / xe) and AMD report device memory per process here 118self .peak_mib = max (self .peak_mib ,mac_footprint_mib (self .p .pid ))# a Mac: the whole footprint (unified memory) 119return self .peak_mib 120 121def enc (self ,img ,out ): 122self .p .stdin .write ("ENC %s %s\n" % (img ,out )) 123self .p .stdin .flush () 124res = self .p .stdout .readline ().strip () 125if self .label .endswith ("-gpu" ): 126self .vram () 127return res 128 129def close (self ): 130try : 131self .p .stdin .write ("QUIT\n" ) 132self .p .stdin .flush () 133self .p .wait (timeout = 30 ) 134except Exception : 135self .p .kill () 136 137 138def cmp (compare ,a ,b ): 139r = subprocess .run ([compare ,a ,b ],capture_output = True ,text = True ).stdout .strip () 140if not r .startswith ("n=" ): 141return None 142return dict (p .split ("=" )for p in r .split ()) 143 144 145def gate_pass (main ,floor ,min_cos = 0.999 ,skip_cpu = False ): 146"""main = cosine(own GPU, float32), floor = cosine(mtmd GPU, float32). Rule 1: main >= min_cos; rule 2: main >= floor - 1e-4, or main >= 0.9999. 147With --skip-cpu (no float32 reference: pictures at the largest token limit) main compares the two GPU readers and only has to reach 0.99.""" 148if skip_cpu : 149return main >= 0.99 150return main >= min_cos and (main >= floor - 1e-4 or main >= 0.9999 ) 151 152 153def main (): 154ap = argparse .ArgumentParser () 155ap .add_argument ("--helper" ,required = True ) 156ap .add_argument ("--compare" ,required = True ) 157ap .add_argument ("--mmproj" ,required = True ) 158ap .add_argument ("--model" ,required = True ) 159ap .add_argument ("--out" ,required = True ) 160ap .add_argument ("--max-tokens" ,type = int ,default = 1024 ) 161ap .add_argument ("--threads" ,type = int ,default = 12 ) 162ap .add_argument ("--repeat" ,type = int ,default = 4 ) 163ap .add_argument ("--min-cos" ,type = float ,default = 0.999 ) 164ap .add_argument ("--ref-dir" ,default = "" ) 165ap .add_argument ("--cpu-dir" ,default = "" ) 166ap .add_argument ("--skip-cpu" ,action = "store_true" ,help = "no mtmd-CPU run: for pictures at the largest token limit (the columns then compare the two GPU readers)" ) 167ap .add_argument ("images" ,nargs = "+" ) 168a = ap .parse_args () 169for d in ("ref-cpu" ,"mtmd-cpu" ,"mtmd-gpu" ,"own-gpu" ): 170os .makedirs (os .path .join (a .out ,d ),exist_ok = True ) 171mk = lambda tower ,gpu ,label ,env = None :Reader (a .helper ,tower ,a .mmproj ,a .model ,gpu ,a .max_tokens ,a .threads ,a .out ,label ,env )# noqa: E731 172ref_of = lambda name :os .path .join (a .ref_dir ,name + ".sve" )if a .ref_dir and os .path .isfile (os .path .join (a .ref_dir ,name + ".sve" ))else None # noqa: E731 173need_ref = not a .skip_cpu and any (ref_of (os .path .basename (i ))is None for i in a .images ) 174r_ref = mk ("own" ,False ,"ref-cpu" , {"STRATA_VIT_CPU" :"ref" })if need_ref else None # the float32 reference, made here where --ref-dir lacks it 175r_cpu = None if (a .cpu_dir or a .skip_cpu )else mk ("mtmd" ,False ,"mtmd-cpu" ) 176r_mg = mk ("mtmd" ,True ,"mtmd-gpu" ) 177r_og = mk ("own" ,True ,"own-gpu" ) 178 179unrepeatable = []# own-gpu pictures whose output bytes changed between encodes in one process 180 181def digest (path ): 182with open (path ,"rb" )as f : 183return hashlib .sha256 (f .read ()).hexdigest () 184 185def run (r ,img ,name ,repeat = None ): 186out = os .path .join (a .out ,r .label ,name + ".sve" ) 187res = r .enc (os .path .abspath (img ),out ) 188if not res .startswith ("OK" ): 189return out ,None ,res 190ms = [] 191seen = {digest (out )}if r is r_og else set () 192for _ in range (a .repeat if repeat is None else repeat ): 193again = r .enc (os .path .abspath (img ),out ) 194if again .startswith ("OK" ): 195ms .append (float (again .split ()[4 ])) 196if r is r_og : 197seen .add (digest (out )) 198if len (seen )> 1 : 199unrepeatable .append ("%s (%d different outputs in %d encodes)" % (name ,len (seen ),a .repeat + 1 )) 200return out ,statistics .median (ms )if ms else float (res .split ()[4 ]),res 201 202hdr = "%-22s %6s | %9s %9s %9s | %9s %9s | %8s %8s %6s | %s" 203hdr % ("picture" ,"tokens" ,"own/ref" ,"mtmdG/ref" ,"own/mtmdG" ,"own/mtmdC" ,"tokmin" ,"mtmdG ms" ,"own ms" ,"ratio" ,"gate" ),flush = True ) 204ok_all ,main_c ,floor_c = True , [], [] 205for img in a .images : 206name = os .path .basename (img ) 207res_r ,res_c ,cpu_f = "OK" ,"OK" ,None 208if a .skip_cpu : 209ref_f = None # a picture at the largest token limit: the CPU readers would take many minutes; the GPU reader of mtmd is the yardstick 210else : 211ref_f = ref_of (name ) 212if ref_f is None : 213ref_f ,_ ,res_r = run (r_ref ,img ,name ,0 ) 214if a .cpu_dir : 215cpu_f = os .path .join (a .cpu_dir ,name + ".sve" ) 216elif r_cpu : 217cpu_f ,_ ,res_c = run (r_cpu ,img ,name ,0 ) 218mg_f ,mg_ms ,res_m = run (r_mg ,img ,name ) 219og_f ,og_ms ,res_o = run (r_og ,img ,name ) 220if ref_f is None : 221ref_f = mg_f 222if not (str (res_r ).startswith ("OK" )and str (res_c ).startswith ("OK" )and res_m .startswith ("OK" )and res_o .startswith ("OK" ))or mg_ms is None or og_ms is None : 223"%-22s FAILED: ref=%s mtmd-cpu=%s mtmd-gpu=%s own-gpu=%s" % (name ,res_r ,res_c ,res_m ,res_o ),flush = True ) 224ok_all = False 225continue 226main = cmp (a .compare ,og_f ,ref_f ) 227floor = cmp (a .compare ,mg_f ,ref_f ) 228info = cmp (a .compare ,og_f ,mg_f ) 229info_c = cmp (a .compare ,og_f ,cpu_f )if cpu_f and os .path .isfile (cpu_f )else None 230if not (main and floor and info ): 231"%-22s shapes differ between readers" % name ,flush = True ) 232ok_all = False 233continue 234m ,f = float (main ["global" ]),float (floor ["global" ]) 235passed = gate_pass (m ,f ,a .min_cos ,a .skip_cpu ) 236ok_all &= passed 237main_c .append (m ) 238floor_c .append (f ) 239hdr % (name ,main ["n" ],main ["global" ],floor ["global" ],info ["global" ],info_c ["global" ]if info_c else "-" ,main ["tokmin" ],"%.0f" % mg_ms ,"%.0f" % og_ms , 240"%.2f" % (og_ms / mg_ms ),"ok" if passed else "FAIL (%s)" % ("main < %.4f" % a .min_cos if m < a .min_cos else "noisier than mtmd-GPU" )),flush = True ) 241vram = "GPU memory of the reader (nvidia-smi / rocm-smi / DRM fdinfo / macOS footprint, peak after the pictures): mtmd-gpu %d MiB, own-gpu %d MiB%s" % ( 242r_mg .peak_mib ,r_og .peak_mib ,"" if r_og .peak_mib <= r_mg .peak_mib else " (own is larger)" ) 243"REPEATABLE own-gpu: %s" % ("yes, every picture byte-identical over %d encodes" % (a .repeat + 1 )if not unrepeatable else "NO: " + "; " .join (unrepeatable )), 244flush = True ) 245for r in (r_ref ,r_cpu ,r_mg ,r_og ): 246if r : 247r .close () 248vram ,flush = True ) 249if main_c : 250"SUMMARY own GPU vs float32: %d pictures, min %.6f mean %.6f; mtmd GPU vs float32 (the floor): min %.6f mean %.6f" % 251 (len (main_c ),min (main_c ),sum (main_c )/ len (main_c ),min (floor_c ),sum (floor_c )/ len (floor_c )),flush = True ) 252"RESULT %s" % ("PASS" if ok_all and main_c else "FAIL" ),flush = True ) 253return 0 if ok_all and main_c else 1 254 255 256if __name__ == "__main__" : 257sys .exit (main ())