okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/embd_bf16_pack.py - the token embedding exactly as the checkpoint ships it (BF16), as a GGUF the engine reads. 2 3python tools/embd_bf16_pack.py --model <checkpoint dir> --out <token-embd-bf16.gguf> 4 5nvfp4_convert.py stores token_embd as Q8_0 (0.56% off per value). The engine keeps the table in mapped host memory 6and reads one row per token, so BF16 costs 0.6 GB of RAM more and no VRAM; `--embd-gguf` takes it from this file. 7 8The output is a one-tensor GGUF: `token_embd.weight`, ne = [n_embd, n_vocab], type BF16, the bytes copied straight 9out of the safetensors file - nothing decoded or rounded. 10 11python tools/embd_bf16_pack.py --gguf <model.gguf> --out <token-embd-bf16.gguf> 12 13instead dequantizes a GGUF's own token_embd.weight to BF16 (round-to-nearest-even, tools/strata_quants.py), for a file whose 14embedding type has no GPU dequantizer in the engine (Agention's Gyro-S stores it as Q6_K). That is the GGUF's values 15rounded to BF16, not the checkpoint's. 16""" 17import argparse 18import json 19import pathlib 20import struct 21import sys 22 23GGUF_TYPE_STRING = 8 24GGML_TYPE_BF16 = 30 25ALIGN = 32 26CHUNK = 64 << 20 27 28 29def safetensors_header (path ): 30with open (path ,"rb" )as f : 31n = struct .unpack ("<Q" ,f .read (8 ))[0 ] 32return json .loads (f .read (n )),8 + n 33 34 35def gguf_string (s ): 36b = s .encode ("utf-8" ) 37return struct .pack ("<Q" ,len (b ))+ b 38 39 40def kv_string (key ,val ): 41return gguf_string (key )+ struct .pack ("<I" ,GGUF_TYPE_STRING )+ gguf_string (val ) 42 43 44def write_header (dim ,vocab ,source ,what ): 45kvs = [kv_string ("general.architecture" ,"strata-embd" ), 46kv_string ("general.name" ,what ), 47kv_string ("strata.embd.source" ,source )] 48head = b"GGUF" + struct .pack ("<IQQ" ,3 ,1 ,len (kvs ))+ b"" .join (kvs ) 49head += gguf_string ("token_embd.weight" )+ struct .pack ("<I" ,2 )+ struct .pack ("<QQ" ,dim ,vocab ) 50head += struct .pack ("<I" ,GGML_TYPE_BF16 )+ struct .pack ("<Q" ,0 ) 51head += b"\0" * ((- len (head ))% ALIGN ) 52return head 53 54 55def from_gguf (src ,out ): 56"""token_embd.weight of a GGUF, dequantized and rounded to BF16 (nearest-even), in row chunks.""" 57import numpy as np 58sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 59import gguf_reader as G 60from _paths import gguf_lib 61gguf = gguf_lib () 62Q ,quants = gguf .GGMLQuantizationType ,gguf .quants 63g = G .GGUFFile (src ) 64t = next ((t for t in g .tensors if t .name == "token_embd.weight" ),None ) 65if t is None or len (t .shape )!= 2 or t .expected_bytes ()is None : 66sys .exit ("%s: no 2-D token_embd.weight of a known type" % src ) 67dim ,vocab = int (t .shape [0 ]),int (t .shape [1 ]) 68row = t .expected_bytes ()// vocab 69mm = np .memmap (src ,dtype = np .uint8 ,mode = "r" ) 70base = g .data_start + t .offset 71"token_embd.weight: %d x %d %s -> BF16, %.2f GB" % (vocab ,dim ,t .type_name ,vocab * dim * 2 / 1e9 ),flush = True ) 72head = write_header (dim ,vocab ,src .name ,"token embedding, %s dequantized to BF16" % t .type_name ) 73out .parent .mkdir (parents = True ,exist_ok = True ) 74tmp = out .with_suffix (out .suffix + ".part" ) 75rows = 8192 76with open (tmp ,"wb" )as w : 77w .write (head ) 78for r0 in range (0 ,vocab ,rows ): 79r1 = min (vocab ,r0 + rows ) 80raw = np .asarray (mm [base + r0 * row :base + r1 * row ]).reshape (r1 - r0 ,row ) 81vals = quants .dequantize (raw ,Q [t .type_name ]).astype (np .float32 ) 82if not np .isfinite (vals ).all (): 83sys .exit ("token_embd.weight has non-finite values" ) 84w .write (quants .quantize (vals ,Q .BF16 ).tobytes ()) 85if tmp .stat ().st_size != len (head )+ vocab * dim * 2 : 86sys .exit ("size check failed" ) 87tmp .replace (out ) 88"wrote %s (header %d B)" % (out ,len (head ))) 89 90 91def main (): 92ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 93src = ap .add_mutually_exclusive_group (required = True ) 94src .add_argument ("--model" ,help = "the checkpoint directory (model.safetensors.index.json)" ) 95src .add_argument ("--gguf" ,help = "a model GGUF whose token_embd.weight is dequantized to BF16" ) 96ap .add_argument ("--out" ,required = True ) 97a = ap .parse_args () 98if a .gguf : 99from_gguf (pathlib .Path (a .gguf ).absolute (),pathlib .Path (a .out )) 100return 101model ,out = pathlib .Path (a .model ),pathlib .Path (a .out ) 102wmap = json .loads ((model / "model.safetensors.index.json" ).read_text (encoding = "utf-8" ))["weight_map" ] 103 104names = [n for n in wmap if n .endswith ("embed_tokens.weight" )and "visual" not in n and "mtp" not in n ] 105if len (names )!= 1 : 106sys .exit ("expected one text embed_tokens.weight in %s, found %s" % (model ,names )) 107name = names [0 ] 108hdr ,base = safetensors_header (model / wmap [name ]) 109t = hdr [name ] 110if t ["dtype" ]!= "BF16" or len (t ["shape" ])!= 2 : 111sys .exit ("%s is %s %s, not a 2-D BF16 tensor" % (name ,t ["dtype" ],t ["shape" ])) 112vocab ,dim = t ["shape" ] 113n = vocab * dim * 2 114if t ["data_offsets" ][1 ]- t ["data_offsets" ][0 ]!= n : 115sys .exit ("%s: data size does not match its shape" % name ) 116"%s: %d x %d BF16, %.2f GB" % (name ,vocab ,dim ,n / 1e9 ),flush = True ) 117 118head = write_header (dim ,vocab ,model .name ,"token embedding, BF16 as shipped" ) 119 120out .parent .mkdir (parents = True ,exist_ok = True ) 121tmp = out .with_suffix (out .suffix + ".part" ) 122with open (tmp ,"wb" )as w ,open (model / wmap [name ],"rb" )as f : 123w .write (head ) 124f .seek (base + t ["data_offsets" ][0 ]) 125left = n 126while left : 127b = f .read (min (CHUNK ,left )) 128if not b : 129sys .exit ("short read in " + str (model / wmap [name ])) 130w .write (b ) 131left -= len (b ) 132if tmp .stat ().st_size != len (head )+ n : 133sys .exit ("size check failed: %d != %d" % (tmp .stat ().st_size ,len (head )+ n )) 134tmp .replace (out ) 135"wrote %s (header %d B)" % (out ,len (head ))) 136 137 138if __name__ == "__main__" : 139main ()