okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1#!/usr/bin/env python3 2"""make_imatrix.py CAL_DIR OUT.dat : llama.cpp's legacy imatrix (.dat) for requant_gguf.py from the per-expert calibration sums the 3gate-3 run dumped (CAL_DIR/L<l>_gu.f64 [384][5120] sums of x^2 of the gate/up input, L<l>_dn.f64 [384][2304] of the down input, 4L<l>_cnt.u64 [384] picks). One entry per expert tensor: blk.<l>.ffn_{gate,up,down}_exps.weight with 384 x ne0 values (E[x^2] per 5expert and input channel; an expert with few picks is shrunk toward the layer mean with a prior of 64 picks, as gate 3 did).""" 6import struct 7import sys 8 9import numpy as np 10 11cal ,out = sys .argv [1 ],sys .argv [2 ] 12PRIOR = 64.0 13ents = [] 14for l in range (40 ): 15gu = np .fromfile ("%s/L%d_gu.f64" % (cal ,l ),dtype = np .float64 ).reshape (384 ,5120 ) 16dn = np .fromfile ("%s/L%d_dn.f64" % (cal ,l ),dtype = np .float64 ).reshape (384 ,2304 ) 17cnt = np .fromfile ("%s/L%d_cnt.u64" % (cal ,l ),dtype = np .uint64 ).astype (np .float64 ) 18tot = max (cnt .sum (),1.0 ) 19for names ,s in ((("gate" ,"up" ),gu ), (("down" ,),dn )): 20mean = s .sum (0 )/ tot 21h = (s + PRIOR * mean )/ (cnt [:,None ]+ PRIOR ) 22h = np .maximum (h ,1e-8 ).astype (np .float32 ) 23for nm in names : 24ents .append (("blk.%d.ffn_%s_exps.weight" % (l ,nm ),h .reshape (- 1 ))) 25with open (out ,"wb" )as f : 26f .write (struct .pack ("<i" ,len (ents ))) 27for name ,v in ents : 28b = name .encode () 29f .write (struct .pack ("<i" ,len (b ))+ b + struct .pack ("<ii" ,1 ,v .size )+ v .tobytes ()) 30"wrote" ,out ,len (ents ),"entries" )