okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1#!/usr/bin/env python3 2"""dense_requant.py - the dense matrices of a DeepSeek-V4.1 pack (attention, compressor, indexer, shared experts; BF16 in the 3unsloth GGUF) in a ggml K-quant, through ggml's own quantizer (libggml-base, ctypes), written beside the model as a small file the 4pack reads instead of the originals - the experts, the Engram and the embedding/head are not touched, nothing big is copied: 5 6python tools/dsv41/dense_requant.py --pack PACK --out DIR --type Q5_K [--lib libggml-base.so] [--jobs 8] 7python tools/dsv41/pack_gguf.py --model GGUF_DIR --out PACK2 --dense-override DIR 8 9DIR/dense.bin holds the quantized tensors (4096-aligned), DIR/dense.json {tensor name: [type, file, offset, bytes, shape]}. 10Types: Q4_K (4.5 bpw), Q5_K (5.5), Q6_K (6.56), Q8_0 (8.5). --include / --exclude are regexes on the checkpoint name 11(default: layers.N.attn.* and layers.N.ffn.shared_experts.*, the main layers only, matrices whose rows are whole 256 blocks). 12""" 13import argparse 14import ctypes 15import json 16import multiprocessing as mp 17import os 18import pathlib 19import re 20import sys 21import time 22 23import numpy as np 24 25GT = {"Q8_0" : (8 ,32 ,34 ),"Q4_K" : (12 ,256 ,144 ),"Q5_K" : (13 ,256 ,176 ),"Q6_K" : (14 ,256 ,210 )} 26_lib = None 27 28 29def _init (libpath ): 30global _lib 31try : 32os .nice (10 ) 33except OSError : 34pass 35_lib = ctypes .CDLL (libpath ) 36_lib .ggml_quantize_chunk .restype = ctypes .c_size_t 37_lib .ggml_quantize_chunk .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_int64 , 38ctypes .c_int64 ,ctypes .c_void_p ] 39 40 41def _job (j ): 42name ,path ,off ,nbytes ,rows ,cols ,tid ,qrb ,out_path ,out_off = j 43raw = np .memmap (path ,dtype = np .uint16 ,mode = "r" ,offset = off ,shape = (rows * cols ,)) 44x = (raw .astype (np .uint32 )<< 16 ).view (np .float32 ).reshape (rows ,cols ) 45x = np .ascontiguousarray (x ) 46dst = np .empty (rows * qrb ,dtype = np .uint8 ) 47got = _lib .ggml_quantize_chunk (tid ,x .ctypes .data ,dst .ctypes .data ,0 ,rows ,cols ,None ) 48if got != rows * qrb : 49raise RuntimeError ("%s: ggml_quantize_chunk wrote %d of %d bytes" % (name ,got ,rows * qrb )) 50# relative error of the result against the source (dequantize by the type's own reference is not exposed here: 51# the engine's tests compare the kernels; this tool only checks the size) 52fd = os .open (out_path ,os .O_WRONLY ) 53os .pwrite (fd ,dst .tobytes (),out_off ) 54os .close (fd ) 55return name ,rows * qrb 56 57 58def main (): 59ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 60ap .add_argument ("--pack" ,required = True ) 61ap .add_argument ("--out" ,required = True ) 62ap .add_argument ("--type" ,required = True ,choices = sorted (GT )) 63ap .add_argument ("--lib" ,default = "/data/dsv41/build-hip/bin/libggml-base.so" ) 64ap .add_argument ("--jobs" ,type = int ,default = 8 ) 65ap .add_argument ("--include" ,default = r"^layers\.\d+\.(attn\.|ffn\.shared_experts\.)" ) 66ap .add_argument ("--exclude" ,default = r"(norm|sink|gate\.bias|\.gate\.weight$|hc_|weights_proj)" ) 67a = ap .parse_args () 68tid ,per ,bpb = GT [a .type ] 69files ,tensors ,cfg = {}, [], {} 70for line in open (os .path .join (a .pack ,"tensors.txt" ),encoding = "utf-8" ): 71f = line .split () 72if f and f [0 ]== "file" : 73files [int (f [1 ])]= line .split (None ,2 )[2 ].strip () 74elif f and f [0 ]== "t" : 75tensors .append ((f [1 ],f [2 ],int (f [3 ]),int (f [4 ]),int (f [5 ]), [int (x )for x in f [6 :]])) 76for line in open (os .path .join (a .pack ,"ds4.txt" ),encoding = "utf-8" ): 77k ,_ ,v = line .strip ().partition (" " ) 78cfg [k ]= v 79model_dir = cfg ["model_dir" ] 80inc ,exc = re .compile (a .include ),re .compile (a .exclude ) 81sel = [t for t in tensors if t [1 ]== "BF16" and len (t [5 ])== 2 and t [5 ][1 ]% per == 0 and inc .search (t [0 ])and not exc .search (t [0 ])] 82os .makedirs (a .out ,exist_ok = True ) 83out_path = os .path .join (a .out ,"dense.bin" ) 84jobs ,idx ,off = [], {},0 85for name ,dt ,fi ,o ,nb ,shape in sel : 86rows ,cols = shape 87qrb = cols // per * bpb 88jobs .append ((name ,os .path .join (model_dir ,files [fi ]),o ,nb ,rows ,cols ,tid ,qrb ,out_path ,off )) 89idx [name ]= [a .type ,"dense.bin" ,off ,rows * qrb ,shape ] 90off += (rows * qrb + 4095 )// 4096 * 4096 91with open (out_path ,"wb" )as f : 92f .truncate (off ) 93src_b = sum (t [4 ]for t in sel ) 94t0 = time .time () 95with mp .get_context ("fork" ).Pool (a .jobs ,initializer = _init ,initargs = (a .lib ,))as pool : 96for i , (name ,n )in enumerate (pool .imap_unordered (_job ,jobs )): 97if i % 40 == 0 : 98"%d/%d %s %.0f s" % (i ,len (jobs ),name ,time .time ()- t0 ),flush = True ) 99json .dump (idx ,open (os .path .join (a .out ,"dense.json" ),"w" )) 100"dense %s: %d tensors, %.2f GB BF16 -> %.2f GB, %.0f s" % (a .type ,len (sel ),src_b / 1e9 ,sum (v [3 ]for v in idx .values ())/ 1e9 ,time .time ()- t0 )) 101 102 103if __name__ == "__main__" : 104main ()