okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""proxy_ldl.py - the Hessian-weighted output error of plain, block-feedback (LDL) and agentionai's encodes, no engine needed. 2 3For some experts of the chosen layers: W' = ORIGINAL weights in the file's rotated basis, shipped = agentionai's decoded blocks, 4plain = our plain-MSE encode, ldl = block feedback with the second-moment matrix H of --dump-dir. Errors are measured with 5H_test (--test-dump-dir, a different part of the calibration set; default = H itself) as 6tr(E H E^T) / tr(W H W^T) (the expected squared output error for inputs with that second moment) 7and unweighted ||E||^2 / ||W||^2, in dB, mean over experts. 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 blockldl # noqa: E402 22import gguf_reader # noqa: E402 23import tqenc # noqa: E402 24from build_swap import bf16 ,load_hessian # noqa: E402 25 26 27def main ()-> int : 28ap = argparse .ArgumentParser () 29ap .add_argument ("--gguf" ,required = True ) 30ap .add_argument ("--orig" ,required = True ) 31ap .add_argument ("--dump-dir" ,required = True ) 32ap .add_argument ("--test-dump-dir" ,default = None ) 33ap .add_argument ("--layers" ,default = "4,16,28,40" ) 34ap .add_argument ("--experts" ,default = "0,111,301" ) 35ap .add_argument ("--roles" ,default = "gate,down" ) 36ap .add_argument ("--damps" ,default = "0.01" ) 37ap .add_argument ("--threads" ,type = int ,default = 4 ) 38ap .add_argument ("--gpu" ,action = "store_true" ) 39a = ap .parse_args () 40g = gguf_reader .GGUFFile (a .gguf ) 41fh = open (a .gguf ,"rb" ) 42mm = mmap .mmap (fh .fileno (),0 ,access = mmap .ACCESS_READ ) 43by = {t .name :t for t in g .tensors } 44sw = [int (x )for x in g .metadata ["prism.hadamard.sign_widths" ]] 45sv = np .array (g .metadata ["prism.hadamard.sign_values" ],dtype = np .float32 ) 46signs ,at = {},0 47for w in sw : 48signs [w ]= sv [at :at + w ] 49at += w 50damps = [float (x )for x in a .damps .split ("," )] 51res = {} 52for l in [int (x )for x in a .layers .split ("," )]: 53gu_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_gate_up.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (512 ,1280 ,2560 ) 54dn_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_down.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (512 ,2560 ,640 ) 55for role in a .roles .split ("," ): 56kind = "dn" if role == "down" else "gu" 57H = load_hessian (a .dump_dir ,l ,kind ) 58Ht = load_hessian (a .test_dump_dir ,l ,kind )if a .test_dump_dir else H 59fbs = {d :blockldl .feedback_matrices (blockldl .hessian_factor (H ,d ))for d in damps } 60for e in [int (x )for x in a .experts .split ("," )]: 61W = bf16 (np .asarray (gu_raw [e ][:640 ]if role == "gate" else gu_raw [e ][640 :]if role == "up" else dn_raw [e ])) 62ti = by ["blk.%d.ffn_%s_exps.weight" % (l ,role )] 63t = tqenc .TYPE_BY_NAME [ti .type_name ] 64n_in ,n_out = ti .shape [0 ],ti .shape [1 ] 65rb = n_in // 128 * tqenc .block_bytes (t ) 66raw = np .frombuffer (mm ,dtype = np .uint8 ,count = n_out * rb ,offset = g .data_start + ti .offset + e * n_out * rb ) 67Wr = tqenc .rotate (W ,signs [n_in ]).astype (np .float64 ) 68cands = {"shipped" :tqenc .decode (raw ,t ).reshape (n_out ,n_in ).astype (np .float64 )} 69kw = dict (threads = a .threads )if not a .gpu else dict (gpu = True ) 70pk ,_ ,_ ,_ = tqenc .encode (Wr .astype (np .float32 ),t ,iters = 1 ,** kw ) 71cands ["plain" ]= tqenc .decode (pk ,t ).reshape (n_out ,n_in ).astype (np .float64 ) 72for d in damps : 73_ ,dec = blockldl .encode_ldl (Wr .astype (np .float32 ),t ,fbs [d ],gpu = a .gpu ,threads = a .threads ) 74cands ["ldl damp=%g" % d ]= dec .astype (np .float64 ) 75den_u = float (np .sum (Wr ** 2 )) 76den_h = float (np .trace (Wr @Ht @Wr .T )) 77for name ,Q in cands .items (): 78E = Wr - Q 79res .setdefault ((l ,role ,name ), []).append ((float (np .sum (E ** 2 )/ den_u ),float (np .trace (E @Ht @E .T )/ den_h ))) 80"layer %d %s expert %d done" % (l ,role ,e ),flush = True ) 81names = ["shipped" ,"plain" ]+ ["ldl damp=%g" % d for d in damps ] 82"\nrelative error in dB (higher is better): unweighted | H-weighted (%s)" % ("held-out H" if a .test_dump_dir else "same H" )) 83tot = {n : [[], []]for n in names } 84for l in [int (x )for x in a .layers .split ("," )]: 85for role in a .roles .split ("," ): 86line = "L%-2d %-5s" % (l ,role ) 87for n in names : 88v = np .array (res [(l ,role ,n )]) 89line += " %-13s %5.2f | %5.2f" % (n ,- 10 * np .log10 (v [:,0 ].mean ()),- 10 * np .log10 (v [:,1 ].mean ())) 90tot [n ][0 ].append (v [:,0 ].mean ()) 91tot [n ][1 ].append (v [:,1 ].mean ()) 92line ) 93"ALL " + " " .join ("%-13s %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 )) 94return 0 95 96 97if __name__ == "__main__" : 98sys .exit (main ())