okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""gyro_reencode.py - gate 2/3 quality check of the trellis encoder against agentionai's Gyro files. 2 3Decodes expert tensors of a Gyro GGUF (TQK6 gate/up, TQK7 down in Gyro-S; TQ2_T in Gyro-M) with the Strata decoder 4(libtqenc's decode, bit-identical to tq_states.hpp, see tqenc_test), re-encodes the decoded weights at the same type 5with tools/tqenc.py and reports the reconstruction error. The decoded weights are a feasible trellis point, so an 6ideal encoder recovers them exactly (error 0): the error measures the search, not the quantization. 7 8python3 tools/trellis/gyro_reencode.py --gguf /data/models/gyro/Qwen3.8-Flash-Next-Gyro-S-TQ1_0.gguf \ 9--layers 0,20,39 --experts 0,7 --rows 256 [--cfg default,rot3,scale3] 10""" 11from __future__import annotations 12 13import argparse 14import mmap 15import pathlib 16import sys 17import time 18 19import numpy as np 20 21HERE = pathlib .Path (__file__ ).resolve ().parent 22sys .path .insert (0 ,str (HERE .parent )) 23import gguf_reader # noqa: E402 24import tqenc # noqa: E402 25 26CFGS = { 27"fast" :dict (iters = 0 ,ncand = 1 ,scale_tries = 1 ), 28"default" :dict (iters = 1 ,ncand = 1 ,scale_tries = 1 ), 29"iters3" :dict (iters = 3 ,ncand = 1 ,scale_tries = 1 ), 30"rot3" :dict (iters = 3 ,ncand = 3 ,scale_tries = 1 ), 31"scale3" :dict (iters = 3 ,ncand = 3 ,scale_tries = 3 ), 32"scale5" :dict (iters = 3 ,ncand = 3 ,scale_tries = 5 ), 33} 34 35 36def main ()-> int : 37ap = argparse .ArgumentParser () 38ap .add_argument ("--gguf" ,required = True ) 39ap .add_argument ("--layers" ,default = "0,20,39" ) 40ap .add_argument ("--experts" ,default = "0" ) 41ap .add_argument ("--rows" ,type = int ,default = 256 ,help = "rows (output channels) of each expert slice to test" ) 42ap .add_argument ("--cfg" ,default = "fast,default,rot3" ) 43ap .add_argument ("--roles" ,default = "gate,up,down" ) 44ap .add_argument ("--threads" ,type = int ,default = 0 ) 45a = ap .parse_args () 46 47g = gguf_reader .GGUFFile (a .gguf ) 48fh = open (a .gguf ,"rb" ) 49mm = mmap .mmap (fh .fileno (),0 ,access = mmap .ACCESS_READ ) 50by_name = {t .name :t for t in g .tensors } 51"file" ,pathlib .Path (a .gguf ).name ,"tensors" ,len (g .tensors ),"types" ,g .by_type ()) 52hk = {k :v for k ,v in g .metadata .items ()if k .startswith ("prism." )and not isinstance (v ,list )} 53"prism metadata:" ,hk ) 54cfgs = a .cfg .split ("," ) 55rows_total = {c : [0.0 ,0.0 ,0 ,0 ,0.0 ]for c in cfgs }# err, energy, blocks, exact blocks, seconds 56for layer in [int (x )for x in a .layers .split ("," )]: 57for role in a .roles .split ("," ): 58name = "blk.%d.ffn_%s_exps.weight" % (layer ,role ) 59ti = by_name .get (name ) 60if ti is None : 61"no tensor" ,name ) 62continue 63t = tqenc .TYPE_BY_NAME .get (ti .type_name ) 64if t is None : 65name ,"type" ,ti .type_name ,"is not a trellis type: skipped" ) 66continue 67n_in ,n_out ,n_exp = ti .shape [0 ],ti .shape [1 ],ti .shape [2 ] 68bb = tqenc .block_bytes (t ) 69row_bytes = n_in // 128 * bb 70for e in [int (x )for x in a .experts .split ("," )]: 71nrows = min (a .rows ,n_out ) 72off = g .data_start + ti .offset + (e * n_out )* row_bytes 73raw = np .frombuffer (mm ,dtype = np .uint8 ,count = nrows * row_bytes ,offset = off ) 74wd = tqenc .decode (raw ,t ).reshape (nrows ,n_in ) 75en = float (np .sum (wd .astype (np .float64 )** 2 )) 76scales = raw .reshape (- 1 ,bb )[:, :2 ].copy ().view (np .float16 ).astype (np .float32 ).ravel () 77"%s expert %d: %d rows x %d, %s %.3f bpw, |w| rms %.4g, agentionai block scales: median %.4g, " 78"p1 %.4g, p99 %.4g, zero-scale blocks %d" % ( 79name ,e ,nrows ,n_in ,ti .type_name ,tqenc .bpw (t ),np .sqrt (en / wd .size ), 80np .median (scales ),np .percentile (scales ,1 ),np .percentile (scales ,99 ),int ((scales == 0 ).sum ()))) 81for c in cfgs : 82t0 = time .time () 83packed ,err ,tot ,st = tqenc .encode (wd ,t ,threads = a .threads ,** CFGS [c ]) 84sec = time .time ()- t0 85dec = tqenc .decode (packed ,t ) 86chk = float (np .sum ((wd .ravel ().astype (np .float64 )- dec )** 2 )) 87nexact = int ((err == 0 ).sum ()) 88same_bytes = int ((packed .reshape (- 1 )== raw ).sum ())/ raw .size 89" %-8s rel MSE %.3e SQNR %7.2f dB exact blocks %5d/%d (%.1f%%) scale==theirs %.1f%% " 90"%.0f weights/s (recheck %.3e)" % ( 91c ,tot / en ,tqenc .sqnr_db (wd ,dec ),nexact ,err .size ,100.0 * nexact / err .size , 92100.0 * float (np .mean (packed [:, :2 ].reshape (- 1 ,2 ).view (np .uint16 ).ravel () 93== raw .reshape (- 1 ,bb )[:, :2 ].copy ().view (np .uint16 ).ravel ())), 94wd .size / sec ,chk / en )) 95r = rows_total [c ] 96r [0 ]+= tot ;r [1 ]+= en ;r [2 ]+= err .size ;r [3 ]+= nexact ;r [4 ]+= sec 97"\nTOTAL over all tested slices" ) 98for c in cfgs : 99r = rows_total [c ] 100if r [1 ]> 0 : 101" %-8s rel MSE %.3e SQNR %.2f dB exact blocks %.1f%% %.0f weights/s" % ( 102c ,r [0 ]/ r [1 ],10 * np .log10 (r [1 ]/ max (r [0 ],1e-300 )),100.0 * r [3 ]/ r [2 ],r [2 ]* 128 / max (r [4 ],1e-9 ))) 103return 0 104 105 106if __name__ == "__main__" : 107sys .exit (main ())