okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1#!/usr/bin/env python3 2"""tq_convert.py - re-encode the routed experts of some layers of a DeepSeek-V4.1 pack with the trellis encoder 3(tools/tqenc.py, HIP) and write them in the format the engine reads (strata-dsv41: ds4_tq.cu / ds4_tq_cpu.cpp): 4 5HIP_VISIBLE_DEVICES=2 TQENC_GPU_LOCK=2 python tools/dsv41/tq_convert.py --pack PACK --out DIR --layers 1,7 --type K5 6 7PACK is the pack pack_gguf.py wrote (its tensors.txt names the source MXFP4 experts in the GGUF shards). Per layer one file 8DIR/tq-L<layer>.bin holds the three roles one after another (gate = w1, up = w3, down = w2), each stacked [n_exp][rows][row 9bytes] in the trellis types' file layout (a row = k / 128 blocks of {fp16 d; 4 K stream bytes}, tools/trellis/tqenc.hpp), 4096-aligned; 10DIR/tq.json lists them as {"layers.N.ffn.experts.w1": [type name, file, offset, bytes, [n_exp, rows, cols]], ...}. Then 11 12python tools/dsv41/pack_gguf.py --model <gguf dir> --out PACK2 --tq-experts DIR 13 14writes a pack whose layers listed there read these experts (the other layers keep their MXFP4). The weights are encoded as they 15are (plain error, no rotation, no activation weights): what the dense override experiments of gate 3 measure. Types: 16K4 = TQK4X, K5 = TQK5X (computed codebook, version 2), K4T / K5T (the table, version 1), K6 = TQK6, K7 = TQK7. 17""" 18import argparse 19import concurrent .futures as cf 20import json 21import os 22import pathlib 23import sys 24import threading 25import time 26 27import numpy as np 28 29sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent .parent )) 30import tqenc # noqa: E402 31 32TYPES = {"K4" :tqenc .TQK4X ,"K5" :tqenc .TQK5X ,"K4T" :tqenc .TQK4T ,"K5T" :tqenc .TQK5T ,"K6" :tqenc .TQK6 ,"K7" :tqenc .TQK7 } 33CFGS = {"fast" :dict (iters = 0 ,ncand = 1 ,scale_tries = 1 ),"default" :dict (iters = 1 ,ncand = 1 ,scale_tries = 1 )} 34MXFP4_LUT = np .array ([0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,- 1 ,- 2 ,- 3 ,- 4 ,- 6 ,- 8 ,- 12 ],dtype = np .float32 ) 35ROLES = (("w1" ,"gate" ), ("w3" ,"up" ), ("w2" ,"down" )) 36 37 38def decode_mxfp4 (raw ,n_in ): 39"""ggml MXFP4 blocks (32 values in 17 bytes: E8M0 scale, 16 code bytes) -> float32 [rows, n_in]""" 40b = raw .reshape (- 1 ,17 ) 41e = b [:,0 ].astype (np .int32 ) 42d = np .where (e == 0 ,np .float32 (2.0 ** - 127 ),np .ldexp (np .float32 (1.0 ),e - 128 )).astype (np .float32 ) 43q = b [:,1 :] 44return (np .concatenate ([MXFP4_LUT [q & 15 ],MXFP4_LUT [q >> 4 ]],axis = 1 )* d [:,None ]).reshape (- 1 ,n_in ) 45 46 47def read_pack (path ): 48files ,tensors ,cfg = {}, {}, {} 49for line in open (os .path .join (path ,"tensors.txt" ),encoding = "utf-8" ): 50f = line .split () 51if f and f [0 ]== "file" : 52files [int (f [1 ])]= line .split (None ,2 )[2 ].strip () 53elif f and f [0 ]== "t" : 54tensors [f [1 ]]= (f [2 ],int (f [3 ]),int (f [4 ]),int (f [5 ]), [int (x )for x in f [6 :]]) 55for line in open (os .path .join (path ,"ds4.txt" ),encoding = "utf-8" ): 56k ,_ ,v = line .strip ().partition (" " ) 57cfg [k ]= v 58return files ,tensors ,cfg 59 60 61def align (n ,a = 4096 ): 62return (n + a - 1 )// a * a 63 64 65def main (): 66ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 67ap .add_argument ("--pack" ,required = True ) 68ap .add_argument ("--out" ,required = True ) 69ap .add_argument ("--layers" ,required = True ,help = "comma list" ) 70ap .add_argument ("--type" ,required = True ,choices = sorted (TYPES )) 71ap .add_argument ("--cfg" ,default = "fast" ,choices = sorted (CFGS )) 72ap .add_argument ("--experts" ,type = int ,default = 0 ,help = "only the first N experts (tests; the others stay zero streams)" ) 73ap .add_argument ("--act" ,default = "" ,help = "calibration dir with L<l>_gu.f64 [n_exp][dim], L<l>_dn.f64 [n_exp][ff] (sums of x^2 of the " 74"gate/up and down inputs per expert) and L<l>_cnt.u64 [n_exp]: an input-column weighted encode (error = sum h (w - dec)^2)" ) 75ap .add_argument ("--prior" ,type = float ,default = 64.0 ,help = "pseudo-count of the layer-mean prior for rarely used experts" ) 76ap .add_argument ("--threads" ,type = int ,default = 4 ) 77ap .add_argument ("--cpu" ,action = "store_true" ,help = "the CPU encoder instead of the card" ) 78a = ap .parse_args () 79t = TYPES [a .type ] 80cfg = CFGS [a .cfg ] 81files ,tensors ,pcfg = read_pack (a .pack ) 82model_dir = pcfg ["model_dir" ] 83n_exp = int (pcfg ["n_routed_experts" ]) 84ff ,dim = int (pcfg ["moe_intermediate_size" ]),int (pcfg ["hidden_size" ]) 85n_do = a .experts or n_exp 86os .makedirs (a .out ,exist_ok = True ) 87idx_path = os .path .join (a .out ,"tq.json" ) 88idx = json .load (open (idx_path ))if os .path .exists (idx_path )else {} 89bb = tqenc .block_bytes (t ) 90mm = {} 91gpu_lock = threading .Lock () 92for L in [int (x )for x in a .layers .split ("," )]: 93path = os .path .join (a .out ,"tq-L%d.bin" % L ) 94if all ("layers.%d.ffn.experts.%s" % (L ,r )in idx for r ,_ in ROLES )and os .path .exists (path ): 95"layer %d: already in %s, skipped" % (L ,idx_path ),flush = True ) 96continue 97sizes = {} 98offs = {} 99off = 0 100for role ,_ in ROLES : 101rows ,cols = (ff ,dim )if role != "w2" else (dim ,ff ) 102sizes [role ]= (rows ,cols ,n_exp * rows * (cols // 128 )* bb ) 103offs [role ]= off 104off += align (sizes [role ][2 ]) 105with open (path ,"wb" )as f : 106f .truncate (off ) 107fd = os .open (path ,os .O_RDWR ) 108act = None 109if a .act : 110gu = np .fromfile ("%s/L%d_gu.f64" % (a .act ,L ),dtype = np .float64 ).reshape (n_exp ,dim ) 111dn = np .fromfile ("%s/L%d_dn.f64" % (a .act ,L ),dtype = np .float64 ).reshape (n_exp ,ff ) 112cnt = np .fromfile ("%s/L%d_cnt.u64" % (a .act ,L ),dtype = np .uint64 ).astype (np .float64 ) 113tot = max (cnt .sum (),1.0 ) 114act = (gu ,dn ,cnt ,gu .sum (0 )/ tot ,dn .sum (0 )/ tot ) 115for role ,rname in ROLES : 116rows ,cols ,total = sizes [role ] 117t0 = time .time () 118per_out = rows * (cols // 128 )* bb 119names = ["layers.%d.ffn.experts.%d.%s.weight" % (L ,e ,role )for e in range (n_do )] 120err2 = np .zeros (n_do ) 121ref2 = np .zeros (n_do ) 122 123def one (e ): 124dt ,fi ,off_ ,nb ,shape = tensors [names [e ]] 125if dt != "MXFP4" : 126raise SystemExit ("%s is %s, not MXFP4: only MXFP4 sources are re-encoded" % (names [e ],dt )) 127key = files [fi ] 128if key not in mm : 129mm [key ]= np .memmap (os .path .join (model_dir ,key ),dtype = np .uint8 ,mode = "r" ) 130w = decode_mxfp4 (np .asarray (mm [key ][off_ :off_ + nb ]),cols ) 131h = None 132if act is not None :# the input columns' mean x^2 of this expert, shrunk toward the layer's mean by the prior 133gu_ ,dn_ ,cnt_ ,mg ,md = act 134sq ,m = (dn_ [e ],md )if role == "w2" else (gu_ [e ],mg ) 135hc = (sq + a .prior * m )/ (cnt_ [e ]+ a .prior ) 136hc = np .maximum (hc / hc .mean (),1e-3 ).astype (np .float32 ) 137h = np .ascontiguousarray (np .broadcast_to (hc , (rows ,cols ))) 138with gpu_lock : 139packed ,err ,tot ,st = tqenc .encode (w ,t ,h = h ,gpu =not a .cpu ,** cfg ) 140dec = tqenc .decode (packed ,t ).reshape (rows ,cols ) 141err2 [e ]= ((w .astype (np .float64 )- dec )** 2 ).sum () 142ref2 [e ]= (w .astype (np .float64 )** 2 ).sum () 143os .pwrite (fd ,packed .tobytes (),offs [role ]+ e * per_out ) 144return st ["nonfinite_blocks" ] 145 146with cf .ThreadPoolExecutor (a .threads )as ex : 147nonfin = sum (ex .map (one ,range (n_do ))) 148"layer %d %s: %d experts %s %.0f s, rel mse %.4f (sqnr %.2f dB), nonfinite blocks %d" % 149 (L ,rname ,n_do ,a .type ,time .time ()- t0 ,err2 .sum ()/ ref2 .sum (),10 * np .log10 (ref2 .sum ()/ err2 .sum ()),nonfin ),flush = True ) 150idx ["layers.%d.ffn.experts.%s" % (L ,role )]= [tqenc .TYPE_NAMES [t ],os .path .basename (path ),offs [role ],total , [n_exp ,rows ,cols ]] 151os .fsync (fd ) 152os .close (fd ) 153json .dump (idx ,open (idx_path ,"w" ),indent = 1 ) 154 155 156if __name__ == "__main__" : 157main ()