okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
f93c5019f
main
1#!/usr/bin/env python3 2"""Pack the incoai DFlash2 drafter for Qwen3.8-Flash-Next (safetensors) into the engine's runtime file. 3 4python tools/dflash2_pack.py model.safetensors config.json out.pack [--q4_0] [--q4_0-selector] 5python tools/dflash2_pack.py --convert-selector in.pack out.pack (a finished Q4_0 pack: its bf16 selector codebooks become Q4_0, nothing else changes) 6 7Format (little endian): "DF2P", u32 version (1), u32 index_len, a text index (padded with spaces so the data starts on a 4096 multiple), then 8the tensors, each 256-byte aligned at its offset (from the end of the index). Index lines: "cfg <key> <value>", "t <name> <dtype> <rows> 9<cols> <offset> <bytes>" (a matrix [out][in] is rows x cols; a vector or codebook row set is the leading dims folded into rows), "end". 10dtypes: "q8_0" (ggml Q8_0 blocks, 34 bytes per 32 values, rows of the weight matrix [out][in] one after the other: what the engine's 11multi-column MMVQ reads), "f32" (norms, the two conv base kernels), "q4_0" (--q4_0: ggml Q4_0 blocks, 18 bytes per 32 values, the matrices only; the engine tiles them like Q8_0, see gemm4_kernel in 12src/kernels/cuda/dflash2.cu), "bf16" (the selector's two codebooks: only gathered rows are read; with --q4_0-selector they are "q4_0" rows in block order, not tiled). 13The matrices' quantization matches ggml's quantize_row_q8_0 (d = amax / 127, q = round(x / d), d stored as fp16); the research harness 14(tools/dflash2/q8test.py) measured no acceptance loss from it. 15""" 16import json 17import struct 18import sys 19 20import numpy as np 21 22 23class SafeTensors : 24"""A .safetensors file read with numpy alone (no torch, no safetensors package: this runs on the person's PC, where neither is 25installed). The format is a little-endian u64 header length, a JSON header {name: {dtype, shape, data_offsets}}, then the raw data.""" 26 27def __init__ (self ,path ): 28self .path = path 29with open (path ,"rb" )as fh : 30 (n ,)= struct .unpack ("<Q" ,fh .read (8 )) 31if n > (64 << 20 ): 32raise ValueError ("not a safetensors file (header too large)" ) 33self .header = json .loads (fh .read (n )) 34self .base = 8 + n 35self .header .pop ("__metadata__" ,None ) 36 37def raw (self ,name ): 38"""-> (dtype string, shape, uint8 memmap of the tensor's bytes)""" 39info = self .header [name ] 40lo ,hi = info ["data_offsets" ] 41return info ["dtype" ],info ["shape" ],np .memmap (self .path ,dtype = np .uint8 ,mode = "r" ,offset = self .base + lo ,shape = (hi - lo ,)) 42 43def get_float32 (self ,name ): 44"""-> float32 ndarray (bf16 and f16 tensors are widened exactly)""" 45dtype ,shape ,data = self .raw (name ) 46if dtype == "BF16" : 47return (np .frombuffer (data ,dtype = np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ).reshape (shape ) 48if dtype == "F16" : 49return np .frombuffer (data ,dtype = np .float16 ).astype (np .float32 ).reshape (shape ) 50if dtype == "F32" : 51return np .frombuffer (data ,dtype = np .float32 ).reshape (shape ).copy () 52raise ValueError ("%s: unsupported dtype %s" % (name ,dtype )) 53 54def get_bf16_bits (self ,name ): 55dtype ,shape ,data = self .raw (name ) 56if dtype != "BF16" : 57raise ValueError ("%s: expected BF16, found %s" % (name ,dtype )) 58return np .frombuffer (data ,dtype = np .uint16 ).reshape (shape ).copy () 59 60 61def load_tensor (f ,name ): 62"""-> float32 ndarray (bf16 tensors are widened exactly)""" 63return f .get_float32 (name ) 64 65 66def raw_bf16 (f ,name ): 67return np .ascontiguousarray (f .get_bf16_bits (name )) 68 69 70def quant_q8_0 (w ): 71"""w: float32 [rows, cols], cols % 32 == 0 -> bytes of rows * cols/32 blocks (fp16 d, 32 int8)""" 72rows ,cols = w .shape 73assert cols % 32 == 0 74b = w .reshape (rows ,cols // 32 ,32 ) 75amax = np .abs (b ).max (axis =- 1 ) 76d = amax / 127.0 77inv = np .where (d != 0 ,1.0 / np .where (d == 0 ,1 ,d ),0.0 ) 78q = np .rint (b * inv [...,None ]).astype (np .int8 )# round half to even; ggml uses roundf (ties are measure-zero for these weights) 79out = np .empty ((rows ,cols // 32 ,34 ),np .uint8 ) 80out [..., :2 ]= d .astype (np .float16 ).view (np .uint8 ).reshape (rows ,cols // 32 ,2 ) 81out [...,2 :]= q .view (np .uint8 ) 82return out .tobytes () 83 84 85def quant_q4_0 (w ): 86"""w: float32 [rows, cols], cols % 32 == 0 -> bytes of rows * cols/32 ggml Q4_0 blocks (fp16 d, 16 bytes: value i in the low nibble of byte i, value i + 16 in the high 87nibble). ggml's quantize_row_q4_0_ref: d = (the value of largest magnitude) / -8, q = min(15, int(x / d + 8.5)); the scale is stored as fp16, q uses the float d.""" 88rows ,cols = w .shape 89assert cols % 32 == 0 90b = w .reshape (rows ,cols // 32 ,32 ).astype (np .float32 ) 91idx = np .abs (b ).argmax (axis =- 1 ) 92mx = np .take_along_axis (b ,idx [...,None ],axis =- 1 )[...,0 ] 93d = mx / np .float32 (- 8.0 ) 94inv = np .where (d != 0 ,1.0 / np .where (d == 0 ,1 ,d ),0.0 ).astype (np .float32 ) 95q = np .minimum (15 , (b * inv [...,None ]+ np .float32 (8.5 )).astype (np .int32 )).astype (np .uint8 ) 96out = np .empty ((rows ,cols // 32 ,18 ),np .uint8 ) 97out [..., :2 ]= d .astype (np .float16 ).view (np .uint8 ).reshape (rows ,cols // 32 ,2 ) 98out [...,2 :]= q [..., :16 ]| (q [...,16 :]<< 4 ) 99return out .tobytes () 100 101 102def pack (st_path ,cfg_path ,out_path ,say = q4 = False ,q4_selector = False ): 103"""Write the engine's runtime file for the drafter in `st_path` (+ its config.json). Returns the number of bytes written.""" 104with open (cfg_path ,encoding = "utf-8" )as fh : 105cfg = json .load (fh ) 106dc = cfg ["dflash_config" ] 107f = SafeTensors (st_path ) 108tensors = [] 109blobs = [] 110 111def add (name ,dtype ,shape ,data ): 112tensors .append ({"name" :name ,"dtype" :dtype ,"shape" :list (shape ),"bytes" :len (data )}) 113blobs .append (data ) 114 115def mat (name ,new = None ): 116w = load_tensor (f ,name ) 117assert w .ndim == 2 118if q4 : 119add (new or name ,"q4_0" ,w .shape ,quant_q4_0 (w )) 120else : 121add (new or name ,"q8_0" ,w .shape ,quant_q8_0 (w )) 122 123def vec (name ,new = None ): 124w = load_tensor (f ,name ) 125add (new or name ,"f32" ,w .shape ,np .ascontiguousarray (w ,np .float32 ).tobytes ()) 126 127L = cfg ["num_hidden_layers" ] 128mat ("fc.weight" ) 129vec ("hidden_norm.weight" ) 130vec ("norm.weight" ) 131for l in range (L ): 132p = "layers.%d." % l 133for n in ("self_attn.q_proj" ,"self_attn.k_proj" ,"self_attn.v_proj" ,"self_attn.o_proj" ,"mlp.gate_proj" ,"mlp.up_proj" , 134"mlp.down_proj" ,"attention_conv.kernel_projection" ,"mlp_conv.kernel_projection" ): 135mat (p + n + ".weight" ) 136for n in ("input_layernorm" ,"post_attention_layernorm" ,"self_attn.q_norm" ,"self_attn.k_norm" ): 137vec (p + n + ".weight" ) 138vec (p + "attention_conv.base_kernel" ) 139vec (p + "mlp_conv.base_kernel" ) 140mat ("candidate_selector.hidden_projection.weight" ) 141for n in ("predecessor_codebook" ,"successor_codebook" ): 142if q4_selector :# --q4_0-selector: ggml Q4_0 rows in block order (NOT tiled): 8 blocks of 18 bytes a row of 256, the community GGUF's selector_* bytes 143w = load_tensor (f ,"candidate_selector." + n ) 144add ("candidate_selector." + n ,"q4_0" ,w .shape ,quant_q4_0 (w )) 145continue 146a = raw_bf16 (f ,"candidate_selector." + n ) 147add ("candidate_selector." + n ,"bf16" ,a .shape ,a .tobytes ()) 148 149meta = { 150"hidden" :cfg ["hidden_size" ],"layers" :L ,"heads" :cfg ["num_attention_heads" ],"kv_heads" :cfg ["num_key_value_heads" ], 151"head_dim" :cfg ["head_dim" ],"inter" :cfg ["intermediate_size" ],"window" :cfg ["sliding_window" ],"rope_theta" :cfg ["rope_parameters" ]["rope_theta" ], 152"eps" :cfg ["rms_norm_eps" ],"block" :dc ["block_size" ],"conv_group" :dc ["conv_group_size" ],"conv_kernel" :dc ["conv_kernel_size" ], 153"mask_token" :dc ["mask_token_id" ],"rank" :dc ["selector_rank" ],"top_k" :dc ["selector_top_k" ],"taps" :dc ["target_layer_ids" ], 154"vocab" :cfg ["vocab_size" ],"source" :"incoai/Qwen3.8-Flash-Next-DFlash2 a22a1744" , 155 } 156# offsets: relative to the end of the (padded) index; 256-byte aligned 157off = 0 158for t in tensors : 159off = (off + 255 )& ~ 255 160t ["offset" ]= off 161off += t ["bytes" ] 162lines = [] 163for k ,v in meta .items (): 164if k == "taps" : 165v = "," .join (str (x )for x in v ) 166lines .append ("cfg %s %s" % (k ,str (v ).replace (" " ,"_" ))) 167for t in tensors : 168sh = t ["shape" ]+ [1 ]* (2 - len (t ["shape" ]))if len (t ["shape" ])< 2 else t ["shape" ] 169lines .append ("t %s %s %d %d %d %d" % (t ["name" ],t ["dtype" ],int (np .prod (sh [:- 1 ])),sh [- 1 ],t ["offset" ],t ["bytes" ])) 170lines .append ("end" ) 171js = ("\n" .join (lines )+ "\n" ).encode () 172js += b" " * ((- (len (js )+ 12 ))% 4096 ) 173with open (out_path ,"wb" )as o : 174o .write (b"DF2P" + struct .pack ("<II" ,1 ,len (js ))+ js ) 175base = o .tell () 176for t ,b in zip (tensors ,blobs ): 177o .seek (base + t ["offset" ]) 178o .write (b ) 179say ("wrote %s: %d tensors, %.1f MB" % (out_path ,len (tensors ), (base + off )/ 1e6 )) 180return base + off 181 182 183def convert_selector_q4 (src_path ,dst_path ,say = rows_per_step = 16384 ): 184"""Rewrite a finished DF2P pack with the selector's two codebooks as Q4_0 rows: every other tensor's bytes are carried over unchanged, the two bf16 codebooks 185(tensors `candidate_selector.predecessor_codebook` / `successor_codebook`, [vocab x 256]) are widened exactly to float32 and quantized by quant_q4_0, which is 186ggml's quantize_row_q4_0_ref. The result is byte-identical to `pack(..., q4=True, q4_selector=True)` from the same safetensors file (and the codebooks are the 187bytes of the community GGUF nazeshinjite/Qwen3.8-Flash-Next-DFlash2-GGUF, selector_predecessor / selector_successor). Memory stays under ~300 MB: the codebooks go 188through `rows_per_step` rows at a time. Returns the size written. Needs only numpy, no network.""" 189with open (src_path ,"rb" )as fh : 190if fh .read (4 )!= b"DF2P" : 191raise ValueError ("not a DF2P pack" ) 192version ,index_len = struct .unpack ("<II" ,fh .read (8 )) 193if version != 1 : 194raise ValueError ("unknown DF2P version %d" % version ) 195index = fh .read (index_len ).decode () 196base = 12 + index_len 197cfg_lines ,tensors = [], [] 198for line in index .split ("\n" ): 199w = line .split () 200if not w or w [0 ]== "end" : 201continue 202if w [0 ]== "cfg" : 203cfg_lines .append (line ) 204elif w [0 ]== "t" : 205tensors .append ({"name" :w [1 ],"dtype" :w [2 ],"rows" :int (w [3 ]),"cols" :int (w [4 ]),"offset" :int (w [5 ]),"bytes" :int (w [6 ])}) 206books = ("candidate_selector.predecessor_codebook" ,"candidate_selector.successor_codebook" ) 207for t in tensors : 208if t ["name" ]in books : 209if t ["dtype" ]!= "bf16" : 210raise ValueError ("%s is already %s" % (t ["name" ],t ["dtype" ])) 211if t ["cols" ]% 32 : 212raise ValueError ("%s: %d columns" % (t ["name" ],t ["cols" ])) 213off = 0 214for t in tensors : 215if t ["name" ]in books : 216t ["new_bytes" ]= t ["rows" ]* (t ["cols" ]// 32 )* 18 217t ["new_dtype" ]= "q4_0" 218else : 219t ["new_bytes" ],t ["new_dtype" ]= t ["bytes" ],t ["dtype" ] 220off = (off + 255 )& ~ 255 221t ["new_offset" ]= off 222off += t ["new_bytes" ] 223lines = list (cfg_lines ) 224for t in tensors : 225lines .append ("t %s %s %d %d %d %d" % (t ["name" ],t ["new_dtype" ],t ["rows" ],t ["cols" ],t ["new_offset" ],t ["new_bytes" ])) 226lines .append ("end" ) 227js = ("\n" .join (lines )+ "\n" ).encode () 228js += b" " * ((- (len (js )+ 12 ))% 4096 ) 229with open (dst_path ,"wb" )as out : 230out .write (b"DF2P" + struct .pack ("<II" ,1 ,len (js ))+ js ) 231new_base = out .tell () 232for t in tensors : 233out .seek (new_base + t ["new_offset" ]) 234fh .seek (base + t ["offset" ]) 235if t ["name" ]not in books : 236left = t ["bytes" ] 237while left : 238block = fh .read (min (left ,1 << 24 )) 239if not block : 240raise ValueError ("%s: the pack is shorter than its index" % t ["name" ]) 241out .write (block ) 242left -= len (block ) 243continue 244for r0 in range (0 ,t ["rows" ],rows_per_step ): 245n = min (rows_per_step ,t ["rows" ]- r0 ) 246raw = np .frombuffer (fh .read (n * t ["cols" ]* 2 ),dtype = np .uint16 ) 247if raw .size != n * t ["cols" ]: 248raise ValueError ("%s: the pack is shorter than its index" % t ["name" ]) 249w = (raw .astype (np .uint32 )<< 16 ).view (np .float32 ).reshape (n ,t ["cols" ]) 250out .write (quant_q4_0 (w )) 251out .seek (new_base + off )# the last tensor ends the file (the pack writer's size is base + off too) 252out .truncate (new_base + off ) 253say ("wrote %s: %d tensors, %.1f MB" % (dst_path ,len (tensors ), (new_base + off )/ 1e6 )) 254return new_base + off 255 256 257def main (): 258if len (sys .argv )== 4 and sys .argv [1 ]== "--convert-selector" : 259convert_selector_q4 (sys .argv [2 ],sys .argv [3 ]) 260return 261flags = ("--q4_0" ,"--q4_0-selector" ) 262args = [a for a in sys .argv [1 :]if a not in flags ] 263if len (args )< 3 : 264sys .exit (__doc__ ) 265pack (* args [:3 ],q4 = "--q4_0" in sys .argv [1 :]or "--q4_0-selector" in sys .argv [1 :],q4_selector = "--q4_0-selector" in sys .argv [1 :]) 266 267 268if __name__ == "__main__" : 269main ()