okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/q8_dense_gguf.py - a copy of a model whose natively served dense projections and head are Q8_0, for the 2Pascal GP100 decode kernel (STRATA_Q8_SM60=1, docs/OLDER_GPUS.md). 3 4The GSQ-RCO packs keep those matrices in K- and i-quants (Q6_K, IQ4_XS, Q4_K, IQ3_S, Q5_K, Q2_0, IQ4_NL), whose 5decode is what a GP100 die is slowest at; STRATA_Q8_SM60 only runs Q8_0 matrices. Every shard of the model is 6handled, because a model may keep dense matrices in more than one (Swift 1.5 IQ3_XXS: 78 in shard 1, 223 in 7shard 2). A shard that holds any of them is written as: 8 9* the tensor-info block with the SAME byte length: names and dims are unchanged, only the u32 type and the u64 10offset of each converted tensor change, so the data section starts where it did and every other tensor - the 11routed experts above all - keeps its absolute offset. An existing native pack (its native_experts.txt) stays 12valid; nothing is repacked. 13* the original data section, then each converted tensor's Q8_0 blocks appended (the old bytes stay, unused). 14Qwen3.8-Flash-Next IQ3_XXS: 301 tensors, +3.5 GiB, the worst requantization error 0.41% of a tensor's |w|max 15(Q8_0 is finer than every source format). 16 17A shard that holds none is hard-linked into the output folder (--copy copies it): the engine finds the shards beside 18--native, so --native and --ple-gguf must both name files in the new folder (it refuses two shard 2s). 19 20python tools/q8_dense_gguf.py <folder>/<model>-00001-of-00002.gguf <new folder> [--copy] 21 22Any shard of the model may be named. Then point the config's --native and --ple-gguf at the new folder and run the 23engine with STRATA_Q8_SM60=1. 24""" 25from __future__import annotations 26 27import argparse 28import os 29import re 30import shutil 31import struct 32import sys 33import time 34from pathlib import Path 35 36import numpy as np 37 38sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 39import _paths # noqa: E402 40 41_gguf = _paths .gguf_lib () 42GGUFReader ,QT = _gguf .GGUFReader ,_gguf .GGMLQuantizationType 43dequantize ,quantize = _gguf .quants .dequantize ,_gguf .quants .quantize 44from gguf_writer import dequantize_q2_0 # noqa: E402 45 46# what src/core/native_dense.cpp serves natively (eligible()), and the head 47SUFFIXES = (".attn_qkv.weight" ,".attn_gate.weight" ,".ssm_out.weight" ,".attn_q.weight" ,".attn_k.weight" , 48".attn_v.weight" ,".attn_output.weight" ,".ffn_gate_shexp.weight" ,".ffn_up_shexp.weight" , 49".ffn_down_shexp.weight" ) 50Q2_0 = 42 # GSQ's 2-bit type (gguf-py's quants cannot dequantize it; tools/gguf_writer.py can) 51 52 53def is_target (name :str )-> bool : 54return name == "output.weight" or (name .startswith ("blk." )and name .endswith (SUFFIXES )) 55 56 57def to_f32 (t )-> np .ndarray : 58ne0 ,ne1 = int (t .shape [0 ]),int (t .shape [1 ]) 59raw = np .asarray (t .data ) 60if int (t .tensor_type )== Q2_0 : 61return np .asarray (dequantize_q2_0 (raw .tobytes ()),dtype = np .float32 ).reshape (ne1 ,ne0 ) 62return np .asarray (dequantize (raw ,t .tensor_type ),dtype = np .float32 ).reshape (ne1 ,ne0 ) 63 64 65def shards_of (path :Path )-> list [Path ]: 66"""Every shard of the model `path` belongs to (just `path` for an unsplit file).""" 67m = re .match (r"(.*-)(\d{5})-of-(\d{5})(\.gguf)$" ,path .name ) 68if not m : 69return [path ] 70return [path .parent / f" { m [ 1 ] } { k :05d } -of- { m [ 3 ] } { m [ 4 ] } " for k in range (1 ,int (m [3 ])+ 1 )] 71 72 73def jobs_of (r )-> list : 74"""The shard's convertible tensors and where each one's type/offset fields sit in its tensor-info block.""" 75data_start ,mm ,jobs = r .data_offset ,r .data , [] 76for t in r .tensors : 77if not is_target (t .name )or int (t .tensor_type )== int (QT .Q8_0 ): 78continue 79p = t .field .offset # the tensor-info entry: name, n_dims, dims, type, offset 80nlen = struct .unpack_from ("<Q" ,mm ,p )[0 ];p += 8 81assert bytes (mm [p :p + nlen ]).decode ()== t .name ;p += nlen 82ndim = struct .unpack_from ("<I" ,mm ,p )[0 ];p += 4 + 8 * ndim 83ttype ,toff = struct .unpack_from ("<IQ" ,mm ,p ) 84assert ttype == int (t .tensor_type )and data_start + toff == t .data_offset ,t .name 85if int (t .shape [0 ])% 32 : 86f" { t . name } : rows of { int ( t . shape [ 0 ]) } are not whole Q8_0 blocks, kept" ) 87continue 88jobs .append ((t ,p )) 89return jobs 90 91 92def convert (src :Path ,dst :Path ,r ,jobs )-> int : 93t0 = time .time () 94align ,data_start ,src_size = r .alignment ,r .data_offset ,os .path .getsize (src ) 95blobs ,worst = [],0.0 96for t ,p in jobs : 97f = to_f32 (t ) 98q = np .ascontiguousarray (quantize (f ,QT .Q8_0 )).view (np .uint8 ).reshape (- 1 ) 99assert q .nbytes == int (t .shape [0 ])// 32 * 34 * int (t .shape [1 ]),t .name 100back = dequantize (q ,QT .Q8_0 ).reshape (f .shape ) 101worst = max (worst ,float (np .abs (back - f ).max ()/ max (float (np .abs (f ).max ()),1e-30 ))) 102blobs .append ((t ,p ,q )) 103f" converted in { time . time () - t0 :.0f } s; worst requantization error { worst :.2e } of a tensor's |w|max; " 104f" { sum ( b [ 2 ]. nbytes for b in blobs ) / 2 ** 30 :.2f } GiB to append" ,flush = True ) 105 106tmp = dst .with_name (dst .name + ".part" ) 107shutil .copyfile (src ,tmp ) 108with open (tmp ,"r+b" )as fh : 109end = src_size 110for t ,p ,blob in blobs : 111at = (end + align - 1 )// align * align 112fh .seek (end );fh .write (b"\0" * (at - end )) 113fh .seek (at );fh .write (blob .tobytes ()) 114end = at + blob .nbytes 115fh .seek (p );fh .write (struct .pack ("<IQ" ,int (QT .Q8_0 ),at - data_start )) 116fh .flush ();os .fsync (fh .fileno ()) 117os .replace (tmp ,dst ) 118 119v = GGUFReader (dst )# every other tensor where it was, every new one as written 120conv = {t .name :blob for t ,_ ,blob in blobs } 121orig = {t .name :t for t in r .tensors } 122assert len (v .tensors )== len (r .tensors )and v .data_offset == data_start 123for t in v .tensors : 124if t .name in conv : 125assert t .tensor_type == QT .Q8_0 and np .array_equal (np .asarray (t .data ).view (np .uint8 ).reshape (- 1 ),conv [t .name ]),t .name 126else : 127assert t .tensor_type == orig [t .name ].tensor_type and t .data_offset == orig [t .name ].data_offset ,t .name 128f" wrote { dst } ( { os . path . getsize ( dst ) / 2 ** 30 :.2f } GiB): { len ( conv ) } converted, { len ( v . tensors ) - len ( conv ) } " 129"untouched, offsets checked" ,flush = True ) 130return len (conv ) 131 132 133def main ()-> int : 134ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 135ap .add_argument ("shard" ,type = Path ,help = "any GGUF shard of the model (or the model's only file)" ) 136ap .add_argument ("out_dir" ,type = Path ,help = "folder for the converted shards and the others' links" ) 137ap .add_argument ("--copy" ,action = "store_true" ,help = "copy the shards with nothing to convert instead of linking them" ) 138a = ap .parse_args () 139out = a .out_dir .resolve () 140shards = shards_of (a .shard .resolve ()) 141if out == shards [0 ].parent : 142sys .exit ("the output folder must not be the model's own folder" ) 143missing = [s for s in shards if not s .is_file ()] 144if missing : 145sys .exit (f"missing shard(s): { ', ' . join ( str ( s ) for s in missing ) } " ) 146out .mkdir (parents = True ,exist_ok = True ) 147total = 0 148for src in shards : 149dst = out / src .name 150r = GGUFReader (src ) 151jobs = jobs_of (r ) 152f" { src . name } : { len ( r . tensors ) } tensors, { len ( jobs ) } to convert to Q8_0" ,flush = True ) 153if jobs : 154total += convert (src ,dst ,r ,jobs ) 155continue 156if dst .exists (): 157dst .unlink ()# a link or copy from an earlier run 158if a .copy : 159shutil .copyfile (src ,dst ) 160else : 161os .link (src ,dst ) 162f" { 'copied' if a . copy else 'linked' } (nothing to convert)" ,flush = True ) 163f" { total } tensors converted over { len ( shards ) } shard(s) in { out } " ) 164return 0 165 166 167if __name__ == "__main__" : 168sys .exit (main ())