okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""proxy_diag_error.py - the diagonal-Hessian output error of the swapped layers, no engine needed. 2 3For some experts of the chosen layers: W' = the ORIGINAL weights in the file's rotated basis; shipped = agentionai's decoded 4blocks; ours = plain-MSE encode, and activation-weighted encodes (h = E[x^2]^p from a STRATA_ACT_DUMP directory). 5Reported: the unweighted relative error ||W' - Q||^2 / ||W'||^2 and the diagonal-Hessian error 6sum_i h_i ||W'_:,i - Q_:,i||^2 / sum_i h_i ||W'_:,i||^2 (the expected squared output error under independent channels), 7per layer and role, the mean over experts, in dB. 8""" 9from __future__import annotations 10 11import argparse 12import mmap 13import pathlib 14import sys 15 16import numpy as np 17 18HERE = pathlib .Path (__file__ ).resolve ().parent 19sys .path .insert (0 ,str (HERE .parent )) 20sys .path .insert (0 ,str (HERE )) 21import gguf_reader # noqa: E402 22import tqenc # noqa: E402 23from build_swap import bf16 ,load_h # noqa: E402 24 25 26def main ()-> int : 27ap = argparse .ArgumentParser () 28ap .add_argument ("--gguf" ,required = True ) 29ap .add_argument ("--orig" ,required = True ) 30ap .add_argument ("--dump-dir" ,required = True ) 31ap .add_argument ("--layers" ,default = "4,16,28,40" ) 32ap .add_argument ("--experts" ,default = "0,37,111,200,301,420" ) 33ap .add_argument ("--powers" ,default = "1.0,0.5" ) 34ap .add_argument ("--threads" ,type = int ,default = 16 ) 35ap .add_argument ("--gpu" ,action = "store_true" ) 36a = ap .parse_args () 37g = gguf_reader .GGUFFile (a .gguf ) 38fh = open (a .gguf ,"rb" ) 39mm = mmap .mmap (fh .fileno (),0 ,access = mmap .ACCESS_READ ) 40by = {t .name :t for t in g .tensors } 41sw = [int (x )for x in g .metadata ["prism.hadamard.sign_widths" ]] 42sv = np .array (g .metadata ["prism.hadamard.sign_values" ],dtype = np .float32 ) 43signs ,at = {},0 44for w in sw : 45signs [w ]= sv [at :at + w ] 46at += w 47powers = [float (x )for x in a .powers .split ("," )] 48experts = [int (x )for x in a .experts .split ("," )] 49res = {} 50for l in [int (x )for x in a .layers .split ("," )]: 51gu_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_gate_up.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (512 ,1280 ,2560 ) 52dn_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_down.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (512 ,2560 ,640 ) 53hs = {"gu" :load_h (a .dump_dir ,l ,"gu" ,1.0 )[0 ],"dn" :load_h (a .dump_dir ,l ,"dn" ,1.0 )[0 ]} 54for e in experts : 55gu = bf16 (np .asarray (gu_raw [e ])) 56dn = bf16 (np .asarray (dn_raw [e ])) 57for role ,W ,kind in (("gate" ,gu [:640 ],"gu" ), ("up" ,gu [640 :],"gu" ), ("down" ,dn ,"dn" )): 58ti = by ["blk.%d.ffn_%s_exps.weight" % (l ,role )] 59t = tqenc .TYPE_BY_NAME [ti .type_name ] 60n_in ,n_out = ti .shape [0 ],ti .shape [1 ] 61rb = n_in // 128 * tqenc .block_bytes (t ) 62raw = np .frombuffer (mm ,dtype = np .uint8 ,count = n_out * rb ,offset = g .data_start + ti .offset + e * n_out * rb ) 63ship = tqenc .decode (raw ,t ).reshape (n_out ,n_in ) 64Wr = tqenc .rotate (W ,signs [n_in ]) 65h = hs [kind ] 66cands = {"shipped" :ship } 67kw = dict (iters = 1 ,ncand = 1 ) 68if a .gpu : 69kw ["gpu" ]= True 70else : 71kw ["threads" ]= a .threads 72pk ,_ ,_ ,_ = tqenc .encode (Wr ,t ,** kw ) 73cands ["plain" ]= tqenc .decode (pk ,t ).reshape (n_out ,n_in ) 74for p in powers : 75hp = (h ** p / (h ** p ).mean ()).astype (np .float32 ) 76pk ,_ ,_ ,_ = tqenc .encode (Wr ,t ,h = np .broadcast_to (hp ,Wr .shape ).copy (),** kw ) 77cands ["diag p=%g" % p ]= tqenc .decode (pk ,t ).reshape (n_out ,n_in ) 78en = float (np .sum (Wr .astype (np .float64 )** 2 )) 79enh = float (np .sum ((Wr .astype (np .float64 )** 2 )* h )) 80for name ,Q in cands .items (): 81d = Wr .astype (np .float64 )- Q 82res .setdefault ((l ,role ,name ), []).append ((float (np .sum (d * d )/ en ),float (np .sum (d * d * h )/ enh ))) 83"layer %d expert %d done" % (l ,e ),flush = True ) 84"\nrelative error in dB (higher = better), mean over experts: unweighted | diagonal-Hessian" ) 85names = ["shipped" ,"plain" ]+ ["diag p=%g" % p for p in powers ] 86tot = {n : [[], []]for n in names } 87for l in [int (x )for x in a .layers .split ("," )]: 88for role in ("gate" ,"up" ,"down" ): 89line = "L%-2d %-5s" % (l ,role ) 90for n in names : 91v = np .array (res [(l ,role ,n )]) 92line += " %-11s %5.2f | %5.2f" % (n ,- 10 * np .log10 (v [:,0 ].mean ()),- 10 * np .log10 (v [:,1 ].mean ())) 93tot [n ][0 ].append (v [:,0 ].mean ()) 94tot [n ][1 ].append (v [:,1 ].mean ()) 95line ) 96"ALL " + " " .join ("%-11s %5.2f | %5.2f" % (n ,- 10 * np .log10 (np .mean (tot [n ][0 ])),- 10 * np .log10 (np .mean (tot [n ][1 ])))for n in names )) 97return 0 98 99 100if __name__ == "__main__" : 101sys .exit (main ())