okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/iq_pack.py - plan v0.3 P6: a native pack for any of the model files (Q2_0, IQ2_XS, IQ3_XXS). 2 3python tools/iq_pack.py --gguf <model>-00001-of-00002.gguf --out pack/iq3_xxs (standalone) 4python tools/iq_pack.py --gguf <model>-00001-of-00002.gguf --base pack/full --out ... (share dense.bin) 5 6The i-quant experts cannot be re-expressed in the Q2_0 pack form, so this pack keeps every quantized tensor in 7its GGUF form: 8 9experts.bin optional (--experts-bin): per layer, 512 blobs of [gate rows | up rows | down rows], the 10raw GGUF slices. Blob size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 / 11IQ4_NL down). experts.bin.src.json says which source it was cut from (the shards' names and 12sizes, the hash of native_experts.txt); an experts.bin is reused only when that matches. 13native_experts.txt one line per layer: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard]; 14written last, so a pack without it is not finished 15index.txt the table the engine loads. Quantized dense tensors, token_embd and output are served 16natively from the GGUF by the engine (--native): their rows carry shape only. 17dense.bin standalone: the BF16/F16/F32 tensors in the form the engine reads them (index kinds 4/5/2; 183 = F32 narrowed to F16 by the loader) - as the GGUF stores them, or converted (FORM below). 19conversions.json every tensor that was converted: shard, source/destination type, method, whether it was 20exact, the largest absolute error, the source bytes' sha256 (schema 1). 21With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are 22byte-identical in all three model files (checked) - plus extra.bin for tensors that are 23float here but quantized in the base pack (blk.1.ple_key). 24tokenizer/ exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template. 25 26Split files: every shard of the model is read (<name>-0000N-of-0000M.gguf beside --gguf; a missing shard is an 27error), so the layers may be split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in 28shard 1). A layer whose experts are not in shard 1 names its shard in native_experts.txt (v3). A shard boundary 29may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, its gate and up in shard 3): that 30layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file 31v4, so an older engine refuses it instead of misreading it. Every other pack stays v3, byte for byte. Router 32tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router 33takes (so are the other F32 tensors the engine reads as BF16, when exact); anything else is refused. 34 35For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using 36round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision 37weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE 38table stay unchanged. 39""" 40from __future__import annotations 41 42import argparse 43import hashlib 44import json 45import os 46import pathlib 47import re 48import shutil 49import subprocess 50import sys 51 52import numpy as np 53 54HERE = pathlib .Path (__file__ ).resolve ().parent 55sys .path .insert (0 ,str (HERE )) 56import gguf_reader as G # noqa: E402 57 58FLOAT = {"BF16" ,"F32" ,"F16" } 59ROUTERS = ("ffn_gate_inp.weight" ,"ffn_gate_inp_shexp.weight" ) 60NOT_IN_PACK = {"per_layer_token_embd.weight" }# the 28.8 GB PLE table: read from its GGUF by the engine 61 62# The float form the engine reads each pack tensor in (name without `blk.N.`; from eddoursul/Strata's FORM table). 63# The residual, router, GDN, QSA and PLE kernels read these small projections as BF16, the norms as F32 and the PLE 64# conv as F16. GSQ-RCO files already store them that way; other files do not (Unsloth's UD-Q4_K_XL: the routers, 65# SSM gates and injections F32, the hyper-connection projections and the PLE value Q8_0, the PLE conv F32), so a 66# tensor stored otherwise is converted, and every conversion is recorded in conversions.json: 67# F32 -> BF16 whose values are exactly BF16 (low 16 bits zero) exact, by default 68# F32 with other values, F16 or a quantized type -> BF16 rounds (nearest-even): only with --compat-bf16 69# F32 -> F16 (ple_conv1d) index kind 3, narrowed by the loader (#255), 70# by default - the kernel reads nothing else 71# F16 / BF16 -> F32 exact widening, by default 72# Tensors not named here are written as stored (floats) or served from the GGUF (quantized), as before. 73FORM = { 74"ffn_gate_inp.weight" :"BF16" ,"ffn_gate_inp_shexp.weight" :"BF16" , 75"hc_attn_down.weight" :"BF16" ,"hc_attn_up.weight" :"BF16" ,"hc_attn_inject.weight" :"BF16" , 76"hc_ffn_down.weight" :"BF16" ,"hc_ffn_up.weight" :"BF16" ,"hc_ffn_inject.weight" :"BF16" , 77"output_hc_down.weight" :"BF16" ,"output_hc_up.weight" :"BF16" , 78"indexer.k_proj.weight" :"BF16" ,"indexer.q_proj.weight" :"BF16" , 79"ssm_alpha.weight" :"BF16" ,"ssm_beta.weight" :"BF16" , 80"ple_key.weight" :"BF16" ,"ple_value.weight" :"BF16" ,"ple_conv1d.weight" :"F16" , 81"attn_q_norm.weight" :"F32" ,"attn_k_norm.weight" :"F32" ,"hc_attn_norm.weight" :"F32" , 82"hc_ffn_norm.weight" :"F32" ,"output_hc_norm.weight" :"F32" ,"indexer.q_norm.weight" :"F32" , 83"indexer.k_norm.weight" :"F32" ,"ple_norm_conv.weight" :"F32" ,"ple_norm_key.weight" :"F32" , 84"ple_norm_query.weight" :"F32" ,"ssm_a" :"F32" ,"ssm_conv1d.weight" :"F32" ,"ssm_dt.bias" :"F32" , 85"ssm_norm.weight" :"F32" , 86} 87# PLE key encodings left in the GGUF for the engine's native PLE key: the formats NativeDense serves (Q2_0; Q8_0 in 88# UD-Q4_K_XL; IQ3_XXS and IQ4_XS, #381). Other quantized keys take the BF16 path (--compat-bf16), as before. 89NATIVE_PLE_KEY = {"Q2_0" ,"Q8_0" ,"IQ3_XXS" ,"IQ4_XS" } 90KIND = {"BF16" :"4" ,"F16" :"5" ,"F32" :"2" } 91 92 93def form_of (name :str ): 94return FORM .get (re .sub (r"^blk\.\d+\." ,"" ,name )) 95 96 97def needs_bf16 (name :str ,type_name :str )-> bool : 98"""Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF).""" 99if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY : 100return False 101return form_of (name )== "BF16" 102 103 104def dequantize (raw :np .ndarray ,type_name :str )-> np .ndarray : 105"""The tensor's values as float32 (float types exactly, quantized ones through tools/strata_quants.py).""" 106if type_name == "F32" : 107return raw .view (np .float32 ) 108if type_name == "F16" : 109return raw .view (np .float16 ).astype (np .float32 ) 110if type_name == "BF16" : 111return (raw .view (np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ) 112from _paths import gguf_lib 113gguf = gguf_lib () 114return gguf .quants .dequantize (raw ,gguf .GGMLQuantizationType [type_name ]).astype (np .float32 ).reshape (- 1 ) 115 116 117def bf16_bytes (raw :np .ndarray ,type_name :str )-> bytes : 118from _paths import gguf_lib 119gguf = gguf_lib () 120Q ,quants = gguf .GGMLQuantizationType ,gguf .quants 121values = quants .dequantize (raw ,Q [type_name ]) 122if not np .isfinite (values ).all (): 123raise ValueError ("cannot convert non-finite weights to BF16" ) 124# ggml's round-to-nearest-even conversion, including correct halfway rounding. 125return quants .quantize (values ,Q .BF16 ).tobytes () 126 127 128def f16_values (values :np .ndarray ,name :str )-> np .ndarray : 129"""values -> F16, nearest-even (numpy's conversion, which is the engine loader's f16_from_f32); refuses a value 130that is not finite or overflows F16.""" 131if not np .isfinite (values ).all (): 132raise ValueError (f" { name } : cannot convert non-finite weights to F16" ) 133with np .errstate (over = "ignore" ): 134h = values .astype (np .float16 ) 135if not np .isfinite (h ).all (): 136raise ValueError (f" { name } : a value is beyond F16's range, which the engine reads it as" ) 137return h 138 139 140class Model : 141"""All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path).""" 142 143def __init__ (self ,first :pathlib .Path ): 144import re 145m = re .search (r"-(\d{5})-of-(\d{5})\.gguf$" ,first .name ) 146paths = [first ] 147if m : 148total = int (m .group (2 )) 149paths = [first .with_name (first .name [:m .start ()]+ "-%05d-of-%05d.gguf" % (i ,total )) 150for i in range (1 ,total + 1 )] 151missing = [str (p )for p in paths if not p .is_file ()] 152if missing : 153raise FileNotFoundError ("missing model shards (wait for the download): " + ", " .join (missing )) 154self .paths = paths 155self .files = [G .GGUFFile (p )for p in paths ] 156self .sizes = [p .stat ().st_size for p in paths ] 157check_split (self .files ) 158self .where = {} 159for p ,g in zip (paths ,self .files ): 160mm = np .memmap (p ,dtype = np .uint8 ,mode = "r" ) 161for t in g .tensors : 162size = t .expected_bytes () 163if size is None or g .data_start + t .offset + size > mm .size : 164raise ValueError (f" { p . name } : unsupported or truncated tensor { t . name } " ) 165if t .name in self .where : 166raise ValueError (f" { p . name } : duplicate tensor { t . name } " ) 167self .where [t .name ]= (g ,t ,mm ,p ) 168 169def bytes (self ,name )-> np .ndarray : 170g ,t ,mm ,_ = self .where [name ] 171return tensor_bytes (mm ,g ,t ) 172 173 174def check_split (files )-> None : 175"""The split keys, as the engine checks them (strata::GgufModel): shard 1 carries the metadata, and every shard 176declares split.count / split.no (and split.tensors.count) consistently - a shard of another model, or a shard 177renamed into the family, is refused rather than mixed in.""" 178n = len (files ) 179meta0 = files [0 ].metadata 180if n == 1 : 181if int (meta0 .get ("split.count" ,1 ))> 1 : 182raise ValueError (f" { files [ 0 ]. path . name } is shard 1 of { meta0 [ 'split.count' ] } , but its name has no " 183"-00001-of-0000N.gguf to find the others by" ) 184return 185if "general.architecture" not in meta0 : 186raise ValueError (f" { files [ 0 ]. path . name } has no general.architecture; the first shard of a split model " 187"carries the metadata" ) 188total = meta0 .get ("split.tensors.count" ) 189for i ,g in enumerate (files ): 190md = g .metadata 191if md .get ("split.count" )!= n or md .get ("split.no" )!= i or \ 192 (total is not None and md .get ("split.tensors.count" )!= total ): 193raise ValueError (f" { g . path . name } does not declare itself shard { i + 1 } of { n } of this model " 194"(split.count / split.no / split.tensors.count)" ) 195if total is not None and sum (len (g .tensors )for g in files )!= total : 196raise ValueError (f"the { n } shards hold { sum ( len ( g . tensors ) for g in files ) } tensors, but " 197f"split.tensors.count is { total } " ) 198 199 200ROLES = ("gate" ,"up" ,"down" ) 201N_EXPERT = 512 202ALIGN = 64 203NVFP4_TAIL = 16 # {s_gate, s_up, s_down, 0} after an NVFP4 expert blob 204 205 206def read_index (path :pathlib .Path ): 207rows ,header = {}, [] 208for line in path .read_text (encoding = "utf-8" ).splitlines (): 209if line .startswith ("#" ): 210header .append (line ) 211continue 212f = line .split () 213rows [f [0 ]]= f 214return header ,rows 215 216 217def tensor_bytes (mm ,g ,t )-> np .ndarray : 218n = t .expected_bytes () 219return mm [g .data_start + t .offset :g .data_start + t .offset + n ] 220 221 222def is_expert (name :str )-> bool : 223return name .startswith ("blk." )and name .endswith (("_exps.weight" ,)) 224 225 226def convert (name :str ,type_name :str ,raw :np .ndarray ,compat_bf16 :bool ): 227"""The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes, 228record or None), or an error string. `record` describes a conversion for conversions.json.""" 229form = form_of (name ) 230if form is None or form == type_name : 231return KIND [type_name ],raw .tobytes (),raw .nbytes ,None 232values = dequantize (raw ,type_name ) 233rec = {"src_type" :type_name ,"dst_type" :form } 234if form == "BF16" : 235u = values .view (np .uint32 )if type_name == "F32" else None 236if u is not None and not np .count_nonzero (u & 0xFFFF ): 237if not np .isfinite (values ).all (): 238return f" { name } is F32 with non-finite values; refused rather than converted" 239data = (u >> 16 ).astype ("<u2" ).tobytes ()# the exact BF16 values 240rec .update (method = "f32->bf16: the values are BF16's (low 16 bits zero)" ,exact = True ,max_abs_err = 0.0 ) 241return "4" ,data ,len (data ),rec 242if not compat_bf16 : 243what = "F32 with values that are not BF16" if type_name == "F32" else type_name 244return f" { name } is { what } , but the engine requires BF16; use --compat-bf16 (rounds to nearest-even)" 245data = bf16_bytes (raw ,type_name ) 246got = (np .frombuffer (data ,dtype = "<u2" ).astype (np .uint32 )<< 16 ).view (np .float32 ) 247rec .update (method = "dequantize->bf16 round-to-nearest-even (--compat-bf16)" if type_name not in FLOAT else 248"%s->bf16 round-to-nearest-even (--compat-bf16)" % type_name .lower ()) 249rec .update (exact = bool (np .array_equal (got ,values )), 250max_abs_err = float (np .max (np .abs (got .astype (np .float64 )- values )))if values .size else 0.0 ) 251return "4" ,data ,len (data ),rec 252if form == "F16" : 253if type_name != "F32" and not compat_bf16 : 254return f" { name } is { type_name } , but the engine reads F16; use --compat-bf16 (rounds to nearest-even)" 255h = f16_values (values ,name ) 256err = float (np .max (np .abs (h .astype (np .float64 )- values )))if values .size else 0.0 257rec .update (exact = bool (np .array_equal (h .astype (np .float32 ),values )),max_abs_err = err ) 258if type_name == "F32" : 259# The F32 bytes go into dense.bin as index kind 3 and the loader narrows them to F16 (nearest-even), the 260# form the PLE conv kernel reads (#255, gopinath87607): 4 B/elem in, 2 B/elem out. 261rec .update (method = "f32->f16 by the loader (index kind 3, round-to-nearest-even)" ) 262return "3" ,raw .tobytes (),raw .nbytes // 2 ,rec 263rec .update (method = "%s->f16 round-to-nearest-even (--compat-bf16)" % type_name .lower ()) 264data = h .astype ("<f2" ).tobytes () 265return "5" ,data ,len (data ),rec 266# form == "F32" 267if type_name not in ("F16" ,"BF16" )and not compat_bf16 : 268return f" { name } is { type_name } , but the engine reads F32; use --compat-bf16" 269data = values .astype ("<f4" ).tobytes () 270rec .update (method = "%s->f32 widening" % type_name .lower (),exact = True ,max_abs_err = 0.0 ) 271return "2" ,data ,len (data ),rec 272 273 274def index_standalone (src ,out ,model :Model ,compat_bf16 :bool = False )-> int : 275"""Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it 276reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF.""" 277todo ,problems = [], [] 278for name , (g ,t ,mm ,p )in model .where .items (): 279if is_expert (t .name )or t .name in NOT_IN_PACK : 280continue 281if len (t .shape )> 2 : 282"tensor %s has %d dimensions; the index holds two" % (t .name ,len (t .shape ))) 283return 1 284# quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes 285# --compat-bf16 to dequantize - except the native PLE key encodings 286form = form_of (name ) 287native = t .type_name not in FLOAT and (form is None or ( 288name == "blk.1.ple_key.weight" and t .type_name in NATIVE_PLE_KEY )) 289if t .type_name not in FLOAT and not native and not compat_bf16 : 290problems .append (f" { name } is { t . type_name } , but the engine requires { form } ; use --compat-bf16" ) 291todo .append ((name ,g ,t ,mm ,p ,native )) 292# refused before anything is written: the previous pack stays as it was 293if problems : 294for m in problems [:8 ]: 295m ) 296if len (problems )> 8 : 297"... and %d more" % (len (problems )- 8 )) 298return 1 299rows ,at = [],0 300served = 0 301converted ,records = [], [] 302with open (out / "dense.bin.tmp" ,"wb" )as fo : 303for name ,g ,t ,mm ,p ,native in todo : 304ne0 = int (t .shape [0 ]) 305ne1 = int (t .shape [1 ])if len (t .shape )> 1 else 0 306if native : 307served += 1 308rows .append ([t .name ,"0" ,"0" ,"0" ,"0" ,"0" ,"0" ,str (ne0 ),str (ne1 ),"8" ,"0" ,"32" ]+ ["0" ]* 7 ) 309continue 310raw = tensor_bytes (mm ,g ,t ) 311try : 312got = convert (name ,t .type_name ,raw ,compat_bf16 ) 313except ValueError as e : 314got = str (e ) 315if isinstance (got ,str ): 316got ) 317fo .close () 318 (out / "dense.bin.tmp" ).unlink (missing_ok = True ) 319return 1 320kind ,data ,dst_bytes ,rec = got 321if rec is not None : 322rec = {"name" :name ,"shard" :p .name ,** rec , 323"source_sha256" :hashlib .sha256 (raw .tobytes ()).hexdigest ()} 324records .append (rec ) 325if "--compat-bf16" in rec ["method" ]:# the rounding the flag allowed 326converted .append ({"name" :name ,"source_type" :t .type_name ,"bytes" :len (data )}) 327rows .append ([t .name ,"0" ,kind ,str (at ),str (len (data )),"0" ,str (dst_bytes ),str (ne0 ),str (ne1 ), 328"0" ,"0" ,"1" ]+ ["0" ]* 7 ) 329fo .write (data ) 330pad = (- len (data ))% ALIGN 331fo .write (b"\0" * pad ) 332at += len (data )+ pad 333write_index (out ,rows ,src ,served ,0 ,publish = False ) 334conv = out / "conversions.json.tmp" 335conv .write_text (json .dumps ({ 336"schema" :1 ,"tool" :"tools/iq_pack.py" ,"compat_bf16" :compat_bf16 , 337"source_shards" : [{"name" :q .name ,"size" :s }for q ,s in zip (model .paths ,model .sizes )], 338"tensors" :records , 339 },indent = 1 )+ "\n" ,encoding = "utf-8" ) 340# published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop 341# from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old 342# index or the reverse 343 (out / "native_experts.txt" ).unlink (missing_ok = True ) 344 (out / "dense.bin.tmp" ).replace (out / "dense.bin" ) 345 (out / "index.txt.tmp" ).replace (out / "index.txt" ) 346conv .replace (out / "conversions.json" ) 347if records : 348exact = sum (1 for r in records if r ["exact" ]) 349"conversions.json: %d tensors converted to the engine's form (%d exact, %d rounded; max |err| %.3g)" 350% (len (records ),exact ,len (records )- exact ,max (r ["max_abs_err" ]for r in records ))) 351for r in records : 352if r ["dst_type" ]== "F16" : 353"narrowed to F16 by the loader: %s (%s, index kind 3)" % (r ["name" ],r ["method" ])) 354if compat_bf16 : 355 (out / "compat-bf16.json" ).write_text (json .dumps ({ 356"source" :str (src ),"rounding" :"nearest-even" ,"tensors" :converted , 357 },indent = 2 )+ "\n" ,encoding = "utf-8" ) 358"compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged" 359% (len (converted ),sum (t ["bytes" ]for t in converted )/ 2 ** 30 )) 360return 0 361 362 363def write_index (out ,rows ,src ,served ,n_extra ,publish = True ): 364at = 0 365for r in rows : 366r [5 ]= str (at ) 367at += (int (r [6 ])+ ALIGN - 1 )// ALIGN * ALIGN 368with open (out / "index.txt.tmp" ,"w" ,encoding = "utf-8" ,newline = "\n" )as fo : 369fo .write ("# strata pack index v3 -- generated by tools/iq_pack.py (native experts) from %s\n" % src .name ) 370fo .write ("# align %d pool %d tensors %d\n" % (ALIGN ,at ,len (rows ))) 371for r in rows : 372fo .write (" " .join (r )+ "\n" ) 373if publish : 374 (out / "index.txt.tmp" ).replace (out / "index.txt" ) 375"index.txt: %d tensors, %d served natively, %d in extra.bin, arena %.2f GiB" 376% (len (rows ),served ,n_extra ,at / 2 ** 30 )) 377 378 379def index_from_base (a ,src ,base ,out ,g ,T ,mm )-> int : 380base_src = pathlib .Path (json .loads ((base / "manifest.json" ).read_text (encoding = "utf-8" ))["source" ]["shard1" ]) 381if not base_src .exists (): 382"cannot find the base pack's shard 1 from its manifest.json" ) 383return 1 384bg = G .GGUFFile (base_src ) 385BT = {t .name :t for t in bg .tensors } 386bmm = np .memmap (base_src ,dtype = np .uint8 ,mode = "r" ) 387header ,rows = read_index (base / "index.txt" ) 388new_rows ,extra = [], [] 389served = 0 390for name ,f in rows .items (): 391t ,bt = T .get (name ),BT .get (name ) 392if t is None or bt is None : 393"tensor %s missing from one of the models" % name ) 394return 1 395if t .type_name in FLOAT and bt .type_name in FLOAT : 396if t .type_name != bt .type_name or t .shape != bt .shape or \ 397not np .array_equal (tensor_bytes (mm ,g ,t ),tensor_bytes (bmm ,bg ,bt )): 398"float tensor %s differs from the base model; this pack cannot reuse its dense.bin" % name ) 399return 1 400new_rows .append (list (f )) 401elif t .type_name in FLOAT : 402if t .type_name != "BF16" : 403"unexpected float type %s for %s" % (t .type_name ,name )) 404return 1 405nbytes = t .expected_bytes () 406off = sum (len (b )+ (- len (b ))% ALIGN for b in extra ) 407extra .append (tensor_bytes (mm ,g ,t ).tobytes ()) 408# file 3 = extra.bin, raw BF16 (index kind 4) 409new_rows .append ([name ,"3" ,"4" ,str (off ),str (nbytes ),"0" ,str (nbytes ),f [7 ],f [8 ]]+ ["0" ]* 10 ) 410else : 411served += 1 412new_rows .append ([name ,f [1 ],"0" ,"0" ,"0" ,"0" ,"0" ,f [7 ],f [8 ],"8" ,"0" ,"32" ]+ ["0" ]* 7 ) 413write_index (out ,new_rows ,src ,served ,len (extra )) 414with open (out / "extra.bin" ,"wb" )as fo : 415for b in extra : 416fo .write (b ) 417fo .write (b"\0" * ((- len (b ))% ALIGN )) 418dense = out / "dense.bin" 419if not dense .exists (): 420try : 421os .link (base / "dense.bin" ,dense ) 422except OSError : 423shutil .copyfile (base / "dense.bin" ,dense ) 424if (base / "tokenizer" ).exists ()and not (out / "tokenizer" ).exists (): 425shutil .copytree (base / "tokenizer" ,out / "tokenizer" ) 426return 0 427 428 429def expert_layout (model :Model ,src :pathlib .Path ): 430"""The pack's expert table: (layout rows, native_experts.txt text, n_expert, total bytes), or an error string. 431Each role is resolved by name in whichever shard holds it, and its offset is absolute in THAT shard: two 432shards do not start their data section at the same byte, so one role's data_start must not be used for 433another's (per-role data_start as in #255, gopinath87607).""" 434T = {n :w [1 ]for n ,w in model .where .items ()} 435exps = [n for n in T if n .startswith ("blk." )and n .endswith ("_exps.weight" )] 436if not exps : 437return "the model has no expert tensors (blk.N.ffn_{gate,up,down}_exps.weight)" 438n_layers = 1 + max (int (n .split ("." )[1 ])for n in exps ) 439n_expert = int (T ["blk.0.ffn_gate_inp.weight" ].shape [1 ])# router rows = experts kept (pruned models ship < 512) 440if any (int (T ["blk.%d.ffn_gate_inp.weight" % l ].shape [1 ])!= n_expert for l in range (n_layers )): 441return "the routers disagree on the expert count; a per-layer pruned model cannot be packed" 442layout ,lines ,offset ,n_split = [], [],0 ,0 443for l in range (n_layers ): 444names = ["blk.%d.ffn_%s_exps.weight" % (l ,r )for r in ROLES ] 445if any (n not in T for n in names ): 446return "layer %d: missing %s" % (l ,", " .join (n for n in names if n not in T )) 447ts = [T [n ]for n in names ] 448if any (t .expected_bytes ()is None or len (t .shape )!= 3 or int (t .shape [2 ])!= n_expert for t in ts ): 449return "layer %d: an expert tensor is not [*, *, %d] of whole blocks" % (l ,n_expert ) 450per = [t .expected_bytes ()// n_expert for t in ts ] 451if per [0 ]!= per [1 ]or ts [0 ].type_name != ts [1 ].type_name : 452return "layer %d: gate and up differ in type" % l 453blob = per [0 ]+ per [1 ]+ per [2 ] 454nvfp4 = ts [0 ].type_name == "NVFP4" or ts [2 ].type_name == "NVFP4" 455if nvfp4 : 456# NVFP4 (ModelOpt) carries one F32 weight_scale_2 per expert and projection, which the block format has 457# no room for. Each blob gets a 16-byte tail {s_gate, s_up, s_down, 0} so every consumer that already 458# moves whole blobs (the arena, the device cache, the prefill staging, a second GPU) moves the scales 459# with the weights; the gate/up kernels read it. See tools/nvfp4_convert.py. 460# a mixed expert (e.g. NVFP4 gate/up + Q8_0 down) has the tail too, with 1.0 for the other projection 461if any (t .type_name == "NVFP4" and "blk.%d.ffn_%s_exps.scale" % (l ,r )not in T for t ,r in zip (ts ,ROLES )): 462return "layer %d: NVFP4 experts without their .scale tensors" % l 463blob += NVFP4_TAIL 464layout .append ((l ,ts [0 ].type_id ,ts [2 ].type_id ,offset ,blob ,ts )) 465ws = [model .where [n ]for n in names ] 466files = ["" if w [3 ]== src else w [3 ].name for w in ws ] 467column = files [0 ]if len (set (files ))== 1 else "," .join (files ) 468n_split += len (set (files ))!= 1 469if nvfp4 :# no GGUF offsets: experts.bin is the only source that carries the scale tails 470lines .append ("%d %d %d %d %d" % (l ,ts [0 ].type_id ,ts [2 ].type_id ,offset ,blob )) 471offset += blob * n_expert 472continue 473line = "%d %d %d %d %d %d %d %d" % (l ,ts [0 ].type_id ,ts [2 ].type_id ,offset ,blob , 474* [w [0 ].data_start + w [1 ].offset for w in ws ]) 475lines .append (line + ("" if not column else " " + column )) 476offset += blob * n_expert 477if n_split : 478head = ("# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off " 479"[shard | gate,up,down] (n_expert %d, total %d; absolute offsets in %s, or in the named shard " 480"beside it - per role where the column is gate,up,down)\n" % (n_expert ,offset ,src .name )) 481"%d layer(s) have their gate/up/down in different shards: native_experts.txt v4, per-role shard " 482"column for %s" % (n_split ,", " .join (str (l )for l ,* _ in layout if "," in lines [l ]))) 483else : 484head = ("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] " 485"(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n" 486% (n_expert ,offset ,src .name )) 487return layout ,head + "" .join (line + "\n" for line in lines ),n_expert ,offset 488 489 490NATIVE_HEAD = re .compile (r"^# strata native experts v(\d+):" ) 491 492 493def native_experts_v5 (text :str )-> str : 494"""native_experts.txt as expert_layout writes it (v3, or v4 with per-role shards) -> the same table marked v5 495(Hadamard-folded experts, hadamard.txt beside it), or an error string naming the version it cannot mark.""" 496head ,rest = text .split ("\n" ,1 )if "\n" in text else (text ,"" ) 497m = NATIVE_HEAD .match (head ) 498if not m or m .group (1 )not in ("3" ,"4" ): 499found = "v" + m .group (1 )if m else "without a version header (%r)" % head [:40 ] 500return ("cannot mark native_experts.txt %s as v5 for Hadamard-folded experts: only v3 and v4 tables are " 501"supported" % found ) 502return "# strata native experts v5:" + head [m .end ():]+ " - v5: Hadamard-folded experts, see hadamard.txt\n" + rest 503 504 505HADAMARD_ROLE = re .compile (r"^blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$" ) 506 507 508def hadamard_spec (meta :dict ,layout ,n_embd :int ,n_ff :int ): 509"""prism.hadamard.* (Agention's APR files: routed experts stored in a block-Hadamard-rotated basis; the runtime 510must rotate their input activations, see include/strata/kernels/cpu/hadamard.hpp) -> the text of hadamard.txt, 511None for a model without the metadata, or an error string. Anything this engine cannot apply is refused: a 512folded weight it would run unrotated computes plausible garbage.""" 513if "prism.hadamard.version" not in meta : 514return None 515if int (meta ["prism.hadamard.version" ])!= 1 : 516return "unsupported prism.hadamard.version %s" % meta ["prism.hadamard.version" ] 517block = int (meta .get ("prism.hadamard.block_size" ,0 )) 518if block <= 1 or block & (block - 1 ): 519return "invalid prism.hadamard.block_size %r" % block 520if meta .get ("prism.hadamard.transform" )!= "normalized-sylvester-walsh-hadamard" : 521return "unsupported prism.hadamard.transform %r" % meta .get ("prism.hadamard.transform" ) 522if meta .get ("prism.hadamard.axis" )!= "input-last-dimension" : 523return "unsupported prism.hadamard.axis %r" % meta .get ("prism.hadamard.axis" ) 524mode = meta .get ("prism.hadamard.sign_mode" ) 525if mode not in ("identity" ,"explicit" ): 526return "unsupported prism.hadamard.sign_mode %r" % mode 527if meta .get ("prism.hadamard.inverse_weight_names" ): 528return ("prism.hadamard.inverse_weight_names (a rotated token embedding) is not supported by this engine: " 529"%s" % ", " .join (meta ["prism.hadamard.inverse_weight_names" ][:4 ])) 530names = meta .get ("prism.hadamard.weight_names" )or [] 531if not names : 532return "prism.hadamard.weight_names is empty" 533n_layers = len (layout ) 534roles = [0 ]* n_layers 535for name in names : 536m = HADAMARD_ROLE .match (name ) 537if not m or int (m .group (1 ))>= n_layers : 538return ("prism.hadamard folds %s; this engine applies the activation rotation to the routed experts " 539"(blk.N.ffn_{gate,up,down}_exps) only" % name ) 540bit = {"gate" :1 ,"up" :2 ,"down" :4 }[m .group (2 )] 541if roles [int (m .group (1 ))]& bit : 542return "duplicate prism.hadamard weight %s" % name 543roles [int (m .group (1 ))]|= bit 544for l ,r in enumerate (roles ): 545if bool (r & 1 )!= bool (r & 2 ): 546return "layer %d: prism.hadamard folds only one of gate/up (they share one input)" % l 547if r and 42 in (layout [l ][1 ]if r & 3 else - 1 ,layout [l ][2 ]if r & 4 else - 1 ): 548return "layer %d: a Hadamard-folded Q2_0 expert (the engine's Q2_0 rows cannot rotate)" % l 549lines = ["# strata hadamard v1: prism.hadamard (normalized-sylvester-walsh-hadamard, input-last-dimension, " 550"sign_mode %s), written by tools/iq_pack.py" % mode ,"block %d" % block ] 551widths = {n_embd for r in roles if r & 3 }| {n_ff for r in roles if r & 4 } 552if any (w % block for w in widths ): 553return "prism.hadamard block %d does not divide the expert widths %s" % (block ,sorted (widths )) 554if mode == "explicit" : 555sw = [int (w )for w in meta .get ("prism.hadamard.sign_widths" )or []] 556sv = [int (v )for v in meta .get ("prism.hadamard.sign_values" )or []] 557if not sw or sum (sw )!= len (sv )or any (w <= 0 or w % block for w in sw )or len (set (sw ))!= len (sw ): 558return "prism.hadamard sign_widths / sign_values are inconsistent" 559if any (v not in (1 ,- 1 )for v in sv ): 560return "prism.hadamard sign values must be +1/-1" 561at ,table = 0 , {} 562for w in sw : 563table [w ]= sv [at :at + w ] 564at += w 565missing = sorted (widths - set (table )) 566if missing : 567return "prism.hadamard has no sign vector for width(s) %s" % missing 568for w in sorted (table ): 569lines .append ("signs %d %s" % (w ," " .join (str (v )for v in table [w ]))) 570for l ,r in enumerate (roles ): 571if r : 572lines .append ("layer %d %d %d %d" % (l ,r & 1 , (r >> 1 )& 1 , (r >> 2 )& 1 )) 573return "\n" .join (lines )+ "\n" 574 575 576def experts_source (model :Model ,text :str ,total :int )-> dict : 577"""What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every 578per-role file and offset, the formats and the blob sizes). A same-size experts.bin of another model or 579another packing is not this one.""" 580return {"schema" :1 , 581"shards" : [{"name" :p .name ,"size" :s }for p ,s in zip (model .paths ,model .sizes )], 582"native_experts_sha256" :hashlib .sha256 (text .encode ("utf-8" )).hexdigest (), 583"bytes" :total } 584 585 586def read_json (path :pathlib .Path ): 587try : 588return json .loads (path .read_text (encoding = "utf-8" )) 589except (OSError ,ValueError ): 590return None 591 592 593def main ()-> int : 594ap = argparse .ArgumentParser () 595ap .add_argument ("--gguf" ,required = True ,help = "the model's shard 1" ) 596ap .add_argument ("--base" ,help = "optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors" ) 597ap .add_argument ("--out" ,required = True ) 598ap .add_argument ("--skip-experts" ,action = "store_true" ,help = "rewrite the index only" ) 599ap .add_argument ("--compat-bf16" ,action = "store_true" , 600help = "dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs " 601"(rounds weights; leaves experts and the PLE table unchanged)" ) 602ap .add_argument ("--experts-bin" ,action = "store_true" , 603help = "also write experts.bin (the engine otherwise reads the experts from the GGUF itself)" ) 604a = ap .parse_args () 605if a .compat_bf16 and a .base : 606ap .error ("--compat-bf16 cannot reuse --base dense weights" ) 607# HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery: .absolute(), not 608# .resolve(), which would follow the link to the blob and lose the -0000N-of-0000M name. 609src = pathlib .Path (a .gguf ).absolute () 610base = pathlib .Path (a .base ).resolve ()if a .base else None 611out = pathlib .Path (a .out ) 612out .mkdir (parents = True ,exist_ok = True ) 613 614g = G .GGUFFile (src ) 615mm = np .memmap (src ,dtype = np .uint8 ,mode = "r" ) 616model = Model (src ) 617if len (model .paths )> 1 : 618"model shards: " + ", " .join (p .name for p in model .paths )) 619# ---- the expert table first: a model that cannot be packed is refused before any file of the pack changes 620got = expert_layout (model ,src ) 621if isinstance (got ,str ): 622got ) 623return 1 624layout ,text ,n_expert ,offset = got 625if any (t .type_name == "NVFP4" for * _ ,ts in layout for t in ts ): 626a .experts_bin = True # the GGUF holds the weights without the scale tails: the engine must read experts.bin 627# ---- prism.hadamard: rotated experts need hadamard.txt beside native_experts.txt, which becomes v5 so an engine 628# that cannot rotate refuses the pack (instead of running the folded experts on unrotated activations) 629t0 = layout [0 ][5 ] 630had = hadamard_spec (g .metadata ,layout ,int (t0 [0 ].shape [0 ]),int (t0 [2 ].shape [0 ])) 631if isinstance (had ,str )and not had .startswith ("# strata hadamard" ): 632"prism.hadamard: " + had ) 633return 1 634if had is not None : 635text = native_experts_v5 (text ) 636if not text .startswith ("# strata native experts v5:" ): 637"prism.hadamard: " + text ) 638return 1 639"prism.hadamard: %d layer(s) of Hadamard-folded experts (block %s, %s signs): hadamard.txt, " 640"native_experts.txt v5" % (sum (1 for ln in had .splitlines ()if ln .startswith ("layer " )), 641g .metadata ["prism.hadamard.block_size" ], 642g .metadata ["prism.hadamard.sign_mode" ])) 643path = out / "experts.bin" 644sidecar = out / "experts.bin.src.json" 645want = experts_source (model ,text ,offset ) 646reuse = path .exists ()and path .stat ().st_size == offset and read_json (sidecar )== want 647 648def nvfp4_tails (l ,ts ): 649"""(n_expert, NVFP4_TAIL) bytes {s_gate, s_up, s_down, 0} of a layer with an NVFP4 projection; a projection in 650another format gets exactly 1.0 (the engine multiplies by the tail unconditionally). None for a bad scale.""" 651s = [np .frombuffer (model .bytes ("blk.%d.ffn_%s_exps.scale" % (l ,r )).tobytes (),dtype = np .float32 ) 652if t .type_name == "NVFP4" else np .ones (n_expert ,dtype = np .float32 )for t ,r in zip (ts ,ROLES )] 653tail = np .zeros ((n_expert ,NVFP4_TAIL // 4 ),dtype = np .float32 ) 654tail [:,0 ],tail [:,1 ],tail [:,2 ]= s [0 ],s [1 ],s [2 ] 655if not np .isfinite (tail ).all ()or (tail [:, :3 ]<= 0 ).any (): 656"layer %d: a non-finite or non-positive NVFP4 scale" % l ) 657return None 658return tail .view (np .uint8 ) 659 660def layer_blobs (l ,blob ,ts ): 661"""(n_expert, blob): gate | up | down [| the NVFP4 scale tail] per expert; None for a bad NVFP4 scale.""" 662parts = [model .bytes (t .name ).reshape (n_expert ,- 1 )for t in ts ] 663if any (t .type_name == "NVFP4" for t in ts ): 664tail = nvfp4_tails (l ,ts ) 665if tail is None : 666return None 667parts .append (tail ) 668chunk = np .concatenate (parts ,axis = 1 ) 669assert chunk .shape == (n_expert ,blob ) 670return chunk 671 672if reuse : 673# the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same 674# geometry packed into the same folder can share: compare the first and last blobs of the first, middle and 675# last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once) 676with open (path ,"rb" )as f : 677for l ,gt ,dt ,off ,blob ,ts in (layout [0 ],layout [len (layout )// 2 ],layout [- 1 ]): 678for e in (0 ,n_expert - 1 ): 679f .seek (off + e * blob ) 680want_blob = b"" .join (model .bytes (t .name ).reshape (n_expert ,- 1 )[e ].tobytes ()for t in ts ) 681if any (t .type_name == "NVFP4" for t in ts ): 682tail = nvfp4_tails (l ,ts ) 683want_blob += tail [e ].tobytes ()if tail is not None else b"" 684if f .read (blob )!= want_blob : 685reuse = False 686if not reuse : 687"%s matches %s but not this GGUF's expert blobs" % (path ,sidecar .name )) 688if path .exists ()and not reuse and not a .experts_bin : 689if sidecar .exists (): 690"%s was cut from another source than this model (%s): the engine would read it instead of " 691"the GGUF. Delete it, or rerun with --experts-bin to rewrite it." % (path ,sidecar .name )) 692return 1 693"warning: %s has no %s, so nothing says it belongs to this model; the engine reads it instead of " 694"the GGUF (rerun with --experts-bin to rewrite it)" % (path ,sidecar .name )) 695if a .base : 696if any (w [3 ]!= src for w in model .where .values ()if not w [1 ].name in NOT_IN_PACK ): 697"--base needs a model whose tensors are all in shard 1" ) 698return 1 699 (out / "native_experts.txt" ).unlink (missing_ok = True ) 700rc = index_from_base (a ,src ,base ,out ,g , {t .name :t for t in g .tensors },mm ) 701else : 702rc = index_standalone (src ,out ,model ,a .compat_bf16 ) 703if rc : 704return rc 705if not (out / "tokenizer" / "vocab.json" ).exists ()or not (out / "tokenizer" / "chat_template.jinja" ).exists (): 706subprocess .run ([sys .executable ,str (HERE / "strata_tokenizer.py" ),"--gguf" ,str (src ),"--out" ,str (out )], 707check = True )# writes <out>/tokenizer/ 708 709# ---- the experts. native_experts.txt is written to a temporary name and renamed only when every layer is 710# in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup 711# run took as a finished pack (#172). It is the pack's completion marker, so it is published last. 712htmp = out / "hadamard.txt.tmp" 713if had is not None : 714htmp .write_text (had ,encoding = "utf-8" ,newline = "\n" ) 715htmp .replace (out / "hadamard.txt" ) 716else : 717 (out / "hadamard.txt" ).unlink (missing_ok = True )# a previous Hadamard model's, packed into this folder 718tmp = out / "native_experts.txt.tmp" 719with open (tmp ,"w" ,encoding = "utf-8" ,newline = "\n" )as fo : 720fo .write (text ) 721tmp .replace (out / "native_experts.txt" ) 722if a .skip_experts or not a .experts_bin : 723if path .exists ()and not a .experts_bin : 724"note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out ) 725return 0 726if reuse : 727"experts.bin was cut from this model's shards (%s); not rewritten" % sidecar .name ) 728return 0 729# written under a temporary name and renamed when complete, then the sidecar: an interrupted write leaves no 730# experts.bin, and an experts.bin without its sidecar is never reused 731sidecar .unlink (missing_ok = True ) 732part = out / "experts.bin.tmp" 733progress = out / "experts.bin.tmp.json" 734# A stop part-way (a kill, a power cut) used to cost the whole write again (40 GB, minutes). The finished layers are kept: 735# after every layer the file is flushed to disk and experts.bin.tmp.json says how many layers are in it and which source they were 736# cut from. The next run continues at that layer when the source is the same and the last kept layer still matches the GGUF. 737start = 0 738if part .exists (): 739done = read_json (progress ) 740k = done .get ("layers" )if isinstance (done ,dict )and done .get ("want" )== want else None 741if isinstance (k ,int )and 0 < k <= len (layout )and part .stat ().st_size >= (layout [k ][3 ]if k < len (layout )else offset ): 742l ,gt ,dt ,off ,blob ,ts = layout [k - 1 ] 743last = layer_blobs (l ,blob ,ts ) 744if last is not None : 745with open (part ,"rb" )as f : 746f .seek (off ) 747kept = f .read (n_expert * blob ) 748if kept == last .tobytes (): 749start = k 750if start : 751"the earlier packing was interrupted: keeping its first %d of %d layers and continuing with layer %d" 752% (start ,len (layout ),start ),flush = True ) 753else : 754"the earlier packing was interrupted and cannot be continued: starting it again" ,flush = True ) 755resume_at = layout [start ][3 ]if start < len (layout )else offset 756with open (part ,"r+b" if start else "wb" )as fo : 757if start : 758fo .truncate (resume_at )# whatever followed the last recorded layer is a partial write 759fo .seek (resume_at ) 760for l ,gt ,dt ,off ,blob ,ts in layout [start :]: 761chunk = layer_blobs (l ,blob ,ts ) 762if chunk is None : 763return 1 764fo .write (chunk .tobytes ()) 765fo .flush () 766os .fsync (fo .fileno ()) 767note = out / "experts.bin.tmp.json.new" 768note .write_text (json .dumps ({"want" :want ,"layers" :l + 1 }),encoding = "utf-8" ) 769note .replace (progress ) 770if l % 8 == 0 : 771" layer %2d %-8s/%-7s blob %8d at %.2f GiB" % (l ,ts [0 ].type_name ,ts [2 ].type_name ,blob , 772off / 2 ** 30 ),flush = True ) 773part .replace (path ) 774progress .unlink (missing_ok = True ) 775side_tmp = out / "experts.bin.src.json.tmp" 776side_tmp .write_text (json .dumps (want ,indent = 2 )+ "\n" ,encoding = "utf-8" ) 777side_tmp .replace (sidecar ) 778"experts.bin: %d layers, %.2f GiB" % (len (layout ),offset / 2 ** 30 )) 779return 0 780 781 782if __name__ == "__main__" : 783raise SystemExit (main ())