okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
1"""build_swap.py - Gyro-S with a few layers' experts swapped, without copying the 58 GB file. 2 3Writes <var>/swap.bin (the new gate / up / down tensors of the chosen layers) and a pack <var>/pack whose native_experts.txt 4points those layers at swap.bin (the shard column), everything else being the shipped Gyro-S pack and file: <var>/ holds a 5symlink to the shipped GGUF, so `--native <var>/<gguf name>` finds swap.bin beside it. 6 7Modes (all from the ORIGINAL Qwen weights, rotated into the file's basis with the file's own sign vectors): 8q8 Q8_0 (types 8/8): the near-lossless reference for the swapped layers 9plain TQK6 gate/up + TQK7 down, plain-MSE trellis encode (tools/tqenc.py) 10diag the same with per-input-column importance weights h = E[x^2]^power from the calibration dump (STRATA_ACT_DUMP) 11ldl the same with block feedback from the full second-moment matrix of the dump (STRATA_ACT_DUMP_COV=1), blockldl.py 12 13python3 tools/trellis/build_swap.py --gguf SHIPPED --pack PACK --orig DIR --layers 4,16,28,40 --mode plain --var DIR [--gpu] 14""" 15from __future__import annotations 16 17import argparse 18import pathlib 19import sys 20import time 21 22import numpy as np 23 24HERE = pathlib .Path (__file__ ).resolve ().parent 25sys .path .insert (0 ,str (HERE .parent )) 26sys .path .insert (0 ,str (HERE )) 27import gguf_reader # noqa: E402 28import blockldl # noqa: E402 29import tqenc # noqa: E402 30 31N_EXP ,N_EMBD ,N_FF = 512 ,2560 ,640 32ALIGN = 4096 33 34 35def q8_0_quantize (w :np .ndarray )-> np .ndarray : 36"""float32 [..., n] (n % 32 == 0) -> uint8 [..., n/32 * 34] block_q8_0 (fp16 scale, 32 int8).""" 37shp = w .shape 38b = w .reshape (- 1 ,32 ).astype (np .float32 ) 39amax = np .abs (b ).max (axis = 1 ) 40d = amax / 127.0 41d16 = d .astype (np .float16 ) 42dq = d16 .astype (np .float32 ) 43with np .errstate (divide = "ignore" ,invalid = "ignore" ): 44q = np .where (dq [:,None ]> 0 ,b / dq [:,None ],0.0 ) 45q = np .clip (np .sign (q )* np .floor (np .abs (q )+ 0.5 ),- 127 ,127 ).astype (np .int8 ) 46out = np .empty ((b .shape [0 ],34 ),dtype = np .uint8 ) 47out [:, :2 ]= d16 .view (np .uint8 ).reshape (- 1 ,2 ) 48out [:,2 :]= q .view (np .uint8 ) 49return out .reshape (* shp [:- 1 ],shp [- 1 ]// 32 * 34 ) 50 51 52def bf16 (raw :np .ndarray )-> np .ndarray : 53return (raw .astype (np .uint32 )<< 16 ).view (np .float32 ) 54 55 56def load_h (dump_dir ,layer ,kind ,power ): 57p = pathlib .Path (dump_dir )/ ("act_L%d_%s.bin" % (layer ,kind )) 58raw = p .read_bytes () 59n ,count = np .frombuffer (raw [:16 ],dtype = np .int64 ) 60sq = np .frombuffer (raw [16 :16 + 8 * n ],dtype = np .float64 ) 61h = (sq / max (count ,1 ))** power 62h = np .maximum (h ,h .mean ()* 1e-4 )# no weight below 1e-4 of the mean 63return (h / h .mean ()).astype (np .float32 ),int (count ) 64 65 66def load_hessian (dump_dir ,layer ,kind ): 67p = pathlib .Path (dump_dir )/ ("act_L%d_%s.bin" % (layer ,kind )) 68raw = p .read_bytes () 69n ,count = np .frombuffer (raw [:16 ],dtype = np .int64 ) 70n = int (n ) 71if len (raw )< 16 + 8 * n + 8 * n * n : 72raise SystemExit ("%s has no covariance (run the calibration with STRATA_ACT_DUMP_COV=1)" % p ) 73cov = np .frombuffer (raw [16 + 8 * n :16 + 8 * n + 8 * n * n ],dtype = np .float64 ).reshape (n ,n ) 74return cov / max (int (count ),1 ) 75 76 77def main ()-> int : 78ap = argparse .ArgumentParser () 79ap .add_argument ("--gguf" ,required = True ) 80ap .add_argument ("--pack" ,required = True ) 81ap .add_argument ("--orig" ,required = True ) 82ap .add_argument ("--layers" ,required = True ) 83ap .add_argument ("--mode" ,required = True ,choices = ["q8" ,"plain" ,"diag" ,"ldl" ]) 84ap .add_argument ("--var" ,required = True ) 85ap .add_argument ("--dump-dir" ,default = None ) 86ap .add_argument ("--power" ,type = float ,default = 1.0 ) 87ap .add_argument ("--gpu" ,action = "store_true" ) 88ap .add_argument ("--threads" ,type = int ,default = 16 ) 89ap .add_argument ("--iters" ,type = int ,default = 2 ) 90ap .add_argument ("--ncand" ,type = int ,default = 2 ) 91ap .add_argument ("--chunk" ,type = int ,default = 16 ) 92ap .add_argument ("--damp" ,type = float ,default = 0.3 ,help = "ldl: damping, a fraction of the mean diagonal of H" ) 93a = ap .parse_args () 94layers = [int (x )for x in a .layers .split ("," )] 95var = pathlib .Path (a .var ) 96var .mkdir (parents = True ,exist_ok = True ) 97gg = pathlib .Path (a .gguf ) 98link = var / gg .name 99if not link .exists (): 100link .symlink_to (gg ) 101g = gguf_reader .GGUFFile (a .gguf ) 102sw = [int (x )for x in g .metadata ["prism.hadamard.sign_widths" ]] 103sv = np .array (g .metadata ["prism.hadamard.sign_values" ],dtype = np .float32 ) 104signs ,at = {},0 105for w in sw : 106signs [w ]= sv [at :at + w ] 107at += w 108if a .mode == "q8" : 109gu_t = d_t = 8 110row_gu ,row_d = N_EMBD // 32 * 34 ,N_FF // 32 * 34 111else : 112gu_t ,d_t = tqenc .TQK6 ,tqenc .TQK7 113row_gu ,row_d = N_EMBD // 128 * tqenc .block_bytes (gu_t ),N_FF // 128 * tqenc .block_bytes (d_t ) 114t_gate = N_EXP * N_FF * row_gu # bytes of the gate (and up) tensor of a layer 115t_down = N_EXP * N_EMBD * row_d 116swap = open (var / "swap.bin" ,"wb" ) 117offs = {} 118pos = 0 119for l in layers : 120offs [l ]= {} 121for role ,nbytes in (("gate" ,t_gate ), ("up" ,t_gate ), ("down" ,t_down )): 122offs [l ][role ]= pos 123pos += (nbytes + ALIGN - 1 )// ALIGN * ALIGN 124swap .truncate (pos ) 125 126def enc (w2d ,t ,h ): 127kw = dict (iters = a .iters ,ncand = a .ncand ,gpu = a .gpu ) 128if not a .gpu : 129kw ["threads" ]= a .threads 130hh = None 131if h is not None : 132hh = np .broadcast_to (h ,w2d .shape ).astype (np .float32 ) 133packed ,err ,tot ,st = tqenc .encode (w2d ,t ,h = hh ,** kw ) 134return packed ,tot 135 136stats = {} 137t_start = time .time () 138for l in layers : 139gu_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_gate_up.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (N_EXP ,2 * N_FF ,N_EMBD ) 140dn_raw = np .memmap (pathlib .Path (a .orig )/ ("L%d_down.bf16" % l ),dtype = np .uint16 ,mode = "r" ).reshape (N_EXP ,N_EMBD ,N_FF ) 141h_gu = h_dn = None 142fb_gu = fb_dn = None 143if a .mode == "ldl" : 144fb_gu = blockldl .feedback_matrices (blockldl .hessian_factor (load_hessian (a .dump_dir ,l ,"gu" ),a .damp )) 145fb_dn = blockldl .feedback_matrices (blockldl .hessian_factor (load_hessian (a .dump_dir ,l ,"dn" ),a .damp )) 146if a .mode == "diag" : 147h_gu ,c1 = load_h (a .dump_dir ,l ,"gu" ,a .power ) 148h_dn ,c2 = load_h (a .dump_dir ,l ,"dn" ,a .power ) 149"layer %d: calibration counts gu %d dn %d; h cv gu %.2f dn %.2f" % (l ,c1 ,c2 ,h_gu .std ()/ h_gu .mean (),h_dn .std ()/ h_dn .mean ())) 150err_sum = {"gate" :0.0 ,"up" :0.0 ,"down" :0.0 } 151en_sum = {"gate" :0.0 ,"up" :0.0 ,"down" :0.0 } 152for e0 in range (0 ,N_EXP ,a .chunk ): 153e1 = min (N_EXP ,e0 + a .chunk ) 154gu = bf16 (np .asarray (gu_raw [e0 :e1 ])) 155dn = bf16 (np .asarray (dn_raw [e0 :e1 ])) 156mats = {"gate" : (gu [:, :N_FF ],signs [N_EMBD ],h_gu ,row_gu ,N_FF ,t_gate ,gu_t ), 157"up" : (gu [:,N_FF :],signs [N_EMBD ],h_gu ,row_gu ,N_FF ,t_gate ,gu_t ), 158"down" : (dn ,signs [N_FF ],h_dn ,row_d ,N_EMBD ,t_down ,d_t )} 159ldl_done = {} 160if a .mode == "ldl" : 161# gate and up share H: one batch of rows 162both = np .concatenate ([tqenc .rotate (np .ascontiguousarray (gu [:, :N_FF ]),signs [N_EMBD ]).reshape (- 1 ,N_EMBD ), 163tqenc .rotate (np .ascontiguousarray (gu [:,N_FF :]),signs [N_EMBD ]).reshape (- 1 ,N_EMBD )]) 164pk ,dec = blockldl .encode_ldl (both ,gu_t ,fb_gu ,gpu = a .gpu ,iters = a .iters ,ncand = a .ncand ,threads = a .threads ) 165half = pk .shape [0 ]// 2 166ldl_done ["gate" ]= (pk [:half ].reshape (half ,- 1 ),dec [:half ]) 167ldl_done ["up" ]= (pk [half :].reshape (half ,- 1 ),dec [half :]) 168wrd = tqenc .rotate (np .ascontiguousarray (dn ),signs [N_FF ]).reshape (- 1 ,N_FF ) 169pk ,dec = blockldl .encode_ldl (wrd ,d_t ,fb_dn ,gpu = a .gpu ,iters = a .iters ,ncand = a .ncand ,threads = a .threads ) 170ldl_done ["down" ]= (pk .reshape (pk .shape [0 ],- 1 ),dec ) 171for role , (w ,sg ,h ,row ,n_out ,tb ,ty )in mats .items (): 172wr = tqenc .rotate (np .ascontiguousarray (w ),sg )# [chunk, n_out, n_in] 173n_in = wr .shape [- 1 ] 174if a .mode == "q8" : 175data = q8_0_quantize (wr ) 176dec = None 177elif a .mode == "ldl" : 178data ,dec = ldl_done [role ] 179err_sum [role ]+= float (np .sum ((wr .reshape (- 1 ,n_in ).astype (np .float64 )- dec )** 2 )) 180else : 181packed ,tot = enc (wr .reshape (- 1 ,n_in ),ty ,h if a .mode == "diag" else None ) 182data = packed 183err_sum [role ]+= tot 184en_sum [role ]+= float (np .sum (wr .astype (np .float64 )** 2 )) 185swap .seek (offs [l ][role ]+ e0 * n_out * row ) 186swap .write (np .ascontiguousarray (data ).tobytes ()) 187if e0 % 128 == 0 : 188"layer %d experts %d-%d done (%.0f s)" % (l ,e0 ,e1 ,time .time ()- t_start ),flush = True ) 189stats [l ]= {r : (10 * np .log10 (en_sum [r ]/ err_sum [r ])if err_sum [r ]> 0 else None )for r in err_sum } 190"layer %d weight SQNR (dB, unweighted): %s" % (l , {k : (round (v ,3 )if v else v )for k ,v in stats [l ].items ()}),flush = True ) 191swap .close () 192# the pack: symlinks to the shipped pack's files, a new native_experts.txt 193pk = var / "pack" 194pk .mkdir (exist_ok = True ) 195src = pathlib .Path (a .pack ) 196for f in src .iterdir (): 197if f .name == "native_experts.txt" : 198continue 199d = pk / f .name 200if not d .exists (): 201d .symlink_to (f .resolve ()) 202lines = (src / "native_experts.txt" ).read_text ().splitlines () 203head ,body = lines [0 ],lines [1 :] 204out_lines ,arena = [],0 205for ln in body : 206f = ln .split () 207l = int (f [0 ]) 208if l in offs : 209blob = row_gu * N_FF * 2 + row_d * N_EMBD 210f = [str (l ),str (gu_t ),str (d_t ),str (arena ),str (blob ),str (offs [l ]["gate" ]),str (offs [l ]["up" ]),str (offs [l ]["down" ]),"swap.bin" ] 211else : 212f [3 ]= str (arena ) 213out_lines .append (" " .join (f )) 214arena += N_EXP * int (f [4 ]) 215import re 216head = re .sub (r"total \d+" ,"total %d" % arena ,head ) 217 (pk / "native_experts.txt" ).write_text (head + "\n" + "\n" .join (out_lines )+ "\n" ) 218"wrote" ,var ,"swap.bin %.2f GB, pack %s" % (pos / 1e9 ,pk )) 219return 0 220 221 222if __name__ == "__main__" : 223sys .exit (main ())