okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
28ce98bf1
main
1"""pilot.py - gate-3 block-quality pilot: a few experts from several layers of a source checkpoint, encoded at TQK4X / TQK5X / 2TQK6 / TQK7 with and without the input-only block-128 Hadamard, and measured. 3 4Sources: --gguf <shard1 or shard dir files...> (UD-Q8_K_XL: MXFP4 / Q8_0 / BF16 / F16 tensors, decoded exactly: the decoded 5source is the teacher, as the plan says) or --hf Qwen/... (range requests; test of the pipeline) 6 7Metrics per (layer, role, expert, rate, transform), over a random row subset of the projection (--rows): 8mse relative weight MSE ||W - W^||^2 / ||W||^2 in the original basis (the Hadamard is orthonormal: the same in either basis) 9act_iso ||(W - W^) X||^2 / ||W X||^2 with X i.i.d. N(0,1) columns - PLACEHOLDER; in expectation equal to mse 10act_syn ||(W - W^) X||^2 / ||W X||^2 with X whose input channels have heavy-tailed scales (a few outlier channels, 11log-normal rest) - SYNTHETIC PLACEHOLDER for real calibration activations, labelled as such in every output 12Real activation-weighted numbers need calibration activations from the reference runtime (not done here). 13""" 14from __future__import annotations 15 16import argparse 17import json 18import mmap 19import pathlib 20import sys 21import time 22 23import numpy as np 24 25HERE = pathlib .Path (__file__ ).resolve ().parent 26sys .path .insert (0 ,str (HERE .parent )) 27sys .path .insert (0 ,str (HERE )) 28import gguf_reader # noqa: E402 29import tqenc # noqa: E402 30 31MXFP4_LUT = np .array ([0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,- 1 ,- 2 ,- 3 ,- 4 ,- 6 ,- 8 ,- 12 ],dtype = np .float32 ) 32RATES = {"K4" :tqenc .TQK4X ,"K5" :tqenc .TQK5X ,"K6" :tqenc .TQK6 ,"K7" :tqenc .TQK7 ,"K4t" :tqenc .TQK4T ,"K5t" :tqenc .TQK5T }# K4 / K5: computed codebook (v2); K4t / K5t: point table (v1) 33CFGS = { 34"fast" :dict (iters = 0 ,ncand = 1 ,scale_tries = 1 ), 35"default" :dict (iters = 1 ,ncand = 1 ,scale_tries = 1 ), 36"rot3" :dict (iters = 3 ,ncand = 3 ,scale_tries = 1 ), 37} 38 39 40def decode_mxfp4 (raw :np .ndarray ,n_in :int )-> np .ndarray : 41"""raw: [rows * n_in/32 * 17] bytes -> float32 [rows, n_in]. ggml block_mxfp4: e8m0 scale, 16 bytes, low nibble = 42element j, high nibble = element j + 16, value = kvalues[nibble] * 2^(e - 128) (the e8m0 half scale).""" 43b = raw .reshape (- 1 ,17 ) 44e = b [:,0 ].astype (np .int32 ) 45d = np .where (e == 0 ,np .float32 (2.0 ** - 127 ),np .ldexp (np .float32 (1.0 ),e - 128 )).astype (np .float32 ) 46q = b [:,1 :] 47vals = np .concatenate ([MXFP4_LUT [q & 15 ],MXFP4_LUT [q >> 4 ]],axis = 1 )* d [:,None ] 48return vals .reshape (- 1 ,n_in ) 49 50 51def decode_q8_0 (raw :np .ndarray ,n_in :int )-> np .ndarray : 52b = raw .reshape (- 1 ,34 ) 53d = b [:, :2 ].copy ().view (np .float16 ).astype (np .float32 ) 54q = b [:,2 :].copy ().view (np .int8 ).astype (np .float32 ) 55return (q * d ).reshape (- 1 ,n_in ) 56 57 58class Source : 59"""Yields float32 [rows, n_in] row subsets of one expert's projection. Local GGUF files (mmap) or, with 60remote=(repo, rev, [shard paths]), the same files read by HTTP range requests (headers and the few experts needed).""" 61 62def __init__ (self ,gguf_paths = None ,remote = None ,tmpdir = "/tmp" ): 63self .tensors = {} 64if gguf_paths : 65for p in gguf_paths : 66g = gguf_reader .GGUFFile (p ) 67fh = open (p ,"rb" ) 68mm = mmap .mmap (fh .fileno (),0 ,access = mmap .ACCESS_READ ) 69for t in g .tensors : 70self .tensors [t .name ]= (g , (lambda off ,n ,mm = mm :np .frombuffer (mm ,dtype = np .uint8 ,count = n ,offset = off )),t ) 71if remote : 72import urllib .request 73repo ,rev ,shards = remote 74for sh in shards : 75url = "https://huggingface.co/%s/resolve/%s/%s" % (repo ,rev ,sh ) 76 77def rd (off ,n ,url = url ): 78req = urllib .request .Request (url ,headers = {"Range" :"bytes=%d-%d" % (off ,off + n - 1 )}) 79with urllib .request .urlopen (req ,timeout = 300 )as r : 80return np .frombuffer (r .read (),dtype = np .uint8 ) 81hdr = rd (0 ,6 << 20 ) 82tp = pathlib .Path (tmpdir )/ ("hdr_%s" % pathlib .Path (sh ).name ) 83tp .write_bytes (hdr .tobytes ()) 84g = gguf_reader .GGUFFile (tp ) 85for t in g .tensors : 86self .tensors [t .name ]= (g ,rd ,t ) 87 88def names (self ,needle ): 89return sorted (n for n in self .tensors if needle in n ) 90 91def expert_rows (self ,name :str ,expert :int ,rows :np .ndarray )-> np .ndarray : 92g ,rd ,ti = self .tensors [name ] 93n_in ,n_out = ti .shape [0 ],ti .shape [1 ] 94if ti .type_name == "MXFP4" : 95rb = n_in // 32 * 17 96elif ti .type_name == "Q8_0" : 97rb = n_in // 32 * 34 98elif ti .type_name in ("BF16" ,"F16" ): 99rb = n_in * 2 100elif ti .type_name == "F32" : 101rb = n_in * 4 102else : 103raise ValueError ("%s: tensor type %s is not readable by this pilot" % (name ,ti .type_name )) 104base = g .data_start + ti .offset + expert * n_out * rb 105whole = rd (base ,n_out * rb )# one expert's projection (6.3 MB for MXFP4 2304 x 5120), then the row subset 106out = np .empty ((len (rows ),n_in ),dtype = np .float32 ) 107for k ,r in enumerate (rows ): 108raw = whole [int (r )* rb :(int (r )+ 1 )* rb ] 109if ti .type_name == "MXFP4" : 110out [k ]= decode_mxfp4 (raw ,n_in )[0 ] 111elif ti .type_name == "Q8_0" : 112out [k ]= decode_q8_0 (raw ,n_in )[0 ] 113elif ti .type_name == "BF16" : 114out [k ]= (raw .view (np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ) 115elif ti .type_name == "F16" : 116out [k ]= raw .view (np .float16 ).astype (np .float32 ) 117else : 118out [k ]= raw .view (np .float32 ) 119return out 120 121 122def synth_x (n_in :int ,T :int ,seed :int )-> np .ndarray : 123"""SYNTHETIC activations: channel scale exp(N(0, 0.5)), 1% of the channels x (10..40).""" 124r = np .random .default_rng (seed ) 125s = np .exp (0.5 * r .standard_normal (n_in )).astype (np .float32 ) 126out = r .choice (n_in ,size = max (1 ,n_in // 100 ),replace = False ) 127s [out ]*= r .uniform (10 ,40 ,size = out .size ).astype (np .float32 ) 128return (r .standard_normal ((n_in ,T )).astype (np .float32 )* s [:,None ]) 129 130 131def act_err (W ,What ,X ): 132D = (W - What ).astype (np .float32 ) @X 133Y = W .astype (np .float32 ) @X 134return float (np .sum (D .astype (np .float64 )** 2 )/ max (np .sum (Y .astype (np .float64 )** 2 ),1e-300 )) 135 136 137def main ()-> int : 138ap = argparse .ArgumentParser () 139ap .add_argument ("--gguf" ,nargs = "+" ,default = None ) 140ap .add_argument ("--remote" ,default = None ,help = "REPO@REV: read the shards named in --shards by HTTP range requests" ) 141ap .add_argument ("--shards" ,nargs = "+" ,default = []) 142ap .add_argument ("--layers" ,default = "1,7,14,21,30,38" ) 143ap .add_argument ("--experts" ,default = "0,97,200,383" ) 144ap .add_argument ("--roles" ,default = "gate,up,down" ) 145ap .add_argument ("--rates" ,default = "K4,K5,K6,K7" ) 146ap .add_argument ("--rows" ,type = int ,default = 256 ) 147ap .add_argument ("--tokens" ,type = int ,default = 256 ,help = "columns of the placeholder X" ) 148ap .add_argument ("--cfg" ,default = "default" ) 149ap .add_argument ("--threads" ,type = int ,default = 0 ) 150ap .add_argument ("--out" ,required = True ,help = "jsonl results" ) 151ap .add_argument ("--seed" ,type = int ,default = 1 ) 152ap .add_argument ("--pattern" ,default = "blk.{L}.ffn_{R}_exps.weight" ) 153ap .add_argument ("--gpu" ,action = "store_true" ,help = "encode on the GPU (run under the box locks, HIP_VISIBLE_DEVICES)" ) 154ap .add_argument ("--act-diag-dir" ,default = None , 155help = "directory with L<layer>_<role>.npy = E[x^2] per input channel of that projection (calibration " 156"second moments, diagonal). Adds act_diag (the exact diagonal-Hessian error) and an importance-weighted " 157"encode (h = E[x^2]; in the Hadamard basis h = the block average of it)" ) 158a = ap .parse_args () 159 160if a .remote : 161repo ,rev = a .remote .split ("@" ) 162src = Source (remote = (repo ,rev ,a .shards )) 163else : 164src = Source (a .gguf ) 165rng = np .random .default_rng (a .seed ) 166cfg = CFGS [a .cfg ] 167sign_cache ,x_cache = {}, {} 168out = open (a .out ,"a" ) 169for layer in [int (x )for x in a .layers .split ("," )]: 170for role in a .roles .split ("," ): 171name = a .pattern .format (L = layer ,R = role ) 172if name not in src .tensors : 173"no tensor" ,name ,"(have e.g. %s)" % src .names ("exps" )[:3 ]) 174continue 175g ,rd ,ti = src .tensors [name ] 176n_in ,n_out ,n_exp = ti .shape [0 ],ti .shape [1 ],ti .shape [2 ] 177for e in [int (x )for x in a .experts .split ("," )]: 178if e >= n_exp : 179continue 180rows = np .sort (rng .choice (n_out ,size = min (a .rows ,n_out ),replace = False )) 181W = src .expert_rows (name ,e ,rows ) 182en = float (np .sum (W .astype (np .float64 )** 2 )) 183if n_in not in sign_cache : 184sign_cache [n_in ]= tqenc .make_signs (n_in ,1000 + n_in ) 185x_cache [n_in ]= (np .random .default_rng (7 ).standard_normal ((n_in ,a .tokens )).astype (np .float32 ), 186synth_x (n_in ,a .tokens ,9 )) 187Xi ,Xs = x_cache [n_in ] 188diag = None 189if a .act_diag_dir : 190dp = pathlib .Path (a .act_diag_dir )/ ("L%d_%s.npy" % (layer ,role )) 191if dp .exists (): 192diag = np .load (dp ).astype (np .float64 ) 193assert diag .shape == (n_in ,), (dp ,diag .shape ) 194for had in (False ,True ): 195sg = sign_cache [n_in ]if had else None 196Wr = tqenc .rotate (W ,sg )if had else W 197for rname in a .rates .split ("," ): 198t = RATES [rname ] 199t0 = time .time () 200packed ,err ,tot ,st = tqenc .encode (Wr ,t ,threads = a .threads ,gpu = a .gpu ,** cfg ) 201sec = time .time ()- t0 202dec = tqenc .decode (packed ,t ).reshape (Wr .shape ) 203What = tqenc .unrotate (dec ,sg )if had else dec 204rec = dict (layer = layer ,role = role ,expert = e ,rate = rname ,had = had ,n_in = n_in ,rows = len (rows ), 205mse = float (np .sum ((W .astype (np .float64 )- What )** 2 )/ en ), 206act_iso = act_err (W ,What ,Xi ),act_syn = act_err (W ,What ,Xs ), 207bpw = tqenc .bpw (t ),seconds = sec ,zero_blocks = st ["zero_blocks" ],cfg = a .cfg , 208x_kind = "placeholder: iso gaussian / synthetic outlier channels" ) 209if diag is not None : 210hv = np .maximum (diag ,1e-30 ).astype (np .float32 ) 211rec ["act_diag" ]= float (np .sum (((W - What ).astype (np .float64 )** 2 )* hv )/ np .sum ((W .astype (np .float64 )** 2 )* hv )) 212hb = hv if not had else np .repeat (hv .reshape (- 1 ,128 ).mean (axis = 1 ),128 ) 213hw = np .broadcast_to (hb ,Wr .shape ).astype (np .float32 ) 214packed2 ,_ ,_ ,_ = tqenc .encode (Wr ,t ,h = hw ,threads = a .threads ,gpu = a .gpu ,** cfg ) 215dec2 = tqenc .decode (packed2 ,t ).reshape (Wr .shape ) 216What2 = tqenc .unrotate (dec2 ,sg )if had else dec2 217rec ["act_diag_weighted_encode" ]= float (np .sum (((W - What2 ).astype (np .float64 )** 2 )* hv )/ np .sum ((W .astype (np .float64 )** 2 )* hv )) 218rec ["mse_weighted_encode" ]= float (np .sum ((W .astype (np .float64 )- What2 )** 2 )/ en ) 219out .write (json .dumps (rec )+ "\n" ) 220out .flush () 221"L%-3d %-4s e%-3d %s %-5s mse %.4f (%.2f dB) act_iso %.4f act_syn %.4f %.1fs" % ( 222layer ,role ,e ,rname ,"had" if had else "plain" ,rec ["mse" ],- 10 * np .log10 (rec ["mse" ]), 223rec ["act_iso" ],rec ["act_syn" ],sec ),flush = True ) 224return 0 225 226 227if __name__ == "__main__" : 228sys .exit (main ())