okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
ba8745e13
main
1# Copyright (c) 2026 Peasant Smith and the Project Maya contributors (MIT; https://github.com/mw00/project-maya, v1.1.17). 2# Ported into Strata (third_party/project-maya/NOTICE.md, LICENSE); changes are in the git history of this file. 3"""tools/ds4/drafter_pack.py - DeepSeek-V4.1's DSpark drafter (the speculative decoder the GGUFs leave out) for a GGUF 4install: its three blocks from DeepSeek's own checkpoint (the shards that hold only them, model-00044..46-of-00048), 5in the formats the GGUF path runs, as one file beside them that pack_gguf.py adds to the pack. 6 7python tools/ds4/drafter_pack.py --dir <folder with the three shards> -> dspark.bin + dspark.json there 8 9Every value is kept exactly: the FP8 (E4M3) matrices with their E8M0 scale a 32 x 32 block become BF16 (an E4M3 value 10times a power of two has at most four significant bits); the routed experts (FP4 E2M1 codes two to a byte, the first in 11the low nibble, an E8M0 scale a 32) become ggml's MXFP4 blocks (the scale byte, then value j's code in byte j's low 12nibble and value j + 16's in its high one); BF16 and F32 tensors are copied. dspark.json lists every tensor (name, 13dtype, offset, bytes, shape) under the checkpoint's names, as tensors.txt does. 14""" 15from __future__import annotations 16 17import argparse 18import json 19import pathlib 20import re 21import struct 22import sys 23 24import numpy as np 25 26SHARDS = ("model-00044-of-00048.safetensors" ,"model-00045-of-00048.safetensors" ,"model-00046-of-00048.safetensors" ) 27ALIGN = 256 28 29 30def e4m3_table ()-> np .ndarray : 31t = np .zeros (256 ,np .float32 ) 32for c in range (256 ): 33s ,e ,m = c >> 7 , (c >> 3 )& 15 ,c & 7 34v = np .nan if (e == 15 and m == 7 )else (m / 8.0 )* 2.0 ** - 6 if e == 0 else (1 + m / 8.0 )* 2.0 ** (e - 7 ) 35t [c ]= - v if s else v 36return t 37 38 39E4M3 = e4m3_table () 40 41 42def shard (path :pathlib .Path ): 43raw = np .memmap (path ,np .uint8 ,mode = "r" ) 44n = struct .unpack ("<Q" ,bytes (raw [:8 ]))[0 ] 45head = json .loads (bytes (raw [8 :8 + n ])) 46head .pop ("__metadata__" ,None ) 47return raw ,head ,8 + n 48 49 50def data (raw ,base :int ,e :dict )-> np .ndarray : 51a ,b = e ["data_offsets" ] 52return raw [base + a :base + b ] 53 54 55def bf16 (x :np .ndarray )-> np .ndarray : 56"""float32 -> BF16 bits, rounded to nearest even (exact here).""" 57u = x .astype (np .float32 ).view (np .uint32 ) 58return ((u + 0x7FFF + ((u >> 16 )& 1 ))>> 16 ).astype (np .uint16 ) 59 60 61def fp8_to_bf16 (w :np .ndarray ,s :np .ndarray ,rows :int ,cols :int )-> np .ndarray : 62w = w .reshape (rows ,cols ) 63scale = np .exp2 (s .reshape ((rows + 31 )// 32 , (cols + 31 )// 32 ).astype (np .float32 )- 127.0 ) 64v = E4M3 [w ]* np .repeat (np .repeat (scale ,32 ,0 ),32 ,1 )[:rows , :cols ] 65return bf16 (v ) 66 67 68def fp4_to_mxfp4 (w :np .ndarray ,s :np .ndarray ,rows :int ,k :int )-> np .ndarray : 69nb = k // 32 70p = w .reshape (rows ,nb ,16 ) 71codes = np .empty ((rows ,nb ,32 ),np .uint8 ) 72codes [...,0 ::2 ]= p & 15 73codes [...,1 ::2 ]= p >> 4 74out = np .empty ((rows ,nb ,17 ),np .uint8 ) 75out [...,0 ]= s .reshape (rows ,nb ) 76out [...,1 :]= codes [..., :16 ]| (codes [...,16 :]<< 4 ) 77return out 78 79 80QTYPES = {"Q8_0" : (8 ,32 ,34 ),"Q2_K" : (10 ,256 ,84 ),"Q3_K" : (11 ,256 ,110 ),"Q4_K" : (12 ,256 ,144 ), 81"Q5_K" : (13 ,256 ,176 ),"Q6_K" : (14 ,256 ,210 ),"IQ2_XXS" : (16 ,256 ,66 ),"IQ3_XXS" : (18 ,256 ,98 ), 82"IQ3_S" : (21 ,256 ,110 ),"IQ2_S" : (22 ,256 ,82 ),"IQ4_XS" : (23 ,256 ,136 )} 83DENSE_KEEP = ("markov_head" ,"confidence_head" ,"norm" ,"hc_" ,"ffn.gate." ,"attn_sink" ) 84E2M1 = np .array ([0 ,1 ,2 ,3 ,4 ,6 ,8 ,12 ,0 ,- 1 ,- 2 ,- 3 ,- 4 ,- 6 ,- 8 ,- 12 ],dtype = np .float32 ) 85 86 87def requant (d :pathlib .Path ,name :str ,experts :str ,dense :str ,lib :str ,jobs :int ,out = None )-> int : 88"""dspark.bin's tensors again with the routed experts in `experts` and the dense matrices (the ones the engine reads 89as matrices) in `dense`, through ggml's quantizers (libggml-base): dspark-<name>.bin / .json beside it - a smaller 90drafter (pack_gguf.py --drafter dspark-<name>).""" 91import ctypes 92from concurrent .futures import ThreadPoolExecutor 93g = ctypes .CDLL (lib ) 94g .ggml_quantize_chunk .restype = ctypes .c_size_t 95g .ggml_quantize_chunk .argtypes = [ctypes .c_int ,ctypes .c_void_p ,ctypes .c_void_p ,ctypes .c_int64 ,ctypes .c_int64 , 96ctypes .c_int64 ,ctypes .c_void_p ] 97src = json .loads ((d / "dspark.json" ).read_text ()) 98raw = np .memmap (d / "dspark.bin" ,np .uint8 ,mode = "r" ) 99 100def f32 (dt ,b ): 101if dt == "BF16" : 102return (np .frombuffer (b ,np .uint16 ).astype (np .uint32 )<< 16 ).view (np .float32 ) 103if dt == "MXFP4" : 104blk = np .frombuffer (b ,np .uint8 ).reshape (- 1 ,17 ) 105v = np .empty ((blk .shape [0 ],32 ),np .float32 ) 106v [:, :16 ]= E2M1 [blk [:,1 :]& 15 ] 107v [:,16 :]= E2M1 [blk [:,1 :]>> 4 ] 108return (v * np .ldexp (np .float32 (1 ),blk [:, :1 ].astype (np .int32 )- 128 )).reshape (- 1 ) 109raise ValueError (dt ) 110 111def quant (t ,x ,rows ,ne0 ):# (one tensor on the calling thread; the pool runs tensors side by side) 112tid ,per ,bpb = QTYPES [t ] 113q = np .empty (rows * ne0 // per * bpb ,np .uint8 ) 114ones = np .ones (ne0 ,np .float32 ) 115g .ggml_quantize_chunk (tid ,x .ctypes .data ,q .ctypes .data ,0 ,rows ,ne0 ,ones .ctypes .data ) 116return q 117 118role_re = re .compile (r"(mtp\.\d+\.ffn\.experts\.)\d+\.(w[123])\.weight$" ) 119 120def prep (item ): 121t ,dt ,so ,nb ,shape = item 122b = raw [so :so + nb ] 123m = role_re .match (t ) 124role = (m .group (1 ),m .group (2 ))if m else None 125want = experts if role else dense 126if (not role and (dt != "BF16" or len (shape )!= 2 or shape [1 ]% 32 or any (k in t for k in DENSE_KEEP ))) \ 127or want in ("keep" ,dt ): 128return t ,dt ,np .asarray (b ),shape ,role 129if shape [1 ]% QTYPES [want ][1 ]: 130raise SystemExit ("%s: rows of %d are not whole %s blocks" % (t ,shape [1 ],want )) 131return t ,want ,quant (want ,np .ascontiguousarray (f32 (dt ,b )),shape [0 ],shape [1 ]),shape ,role 132 133for t in {experts ,dense }- {"keep" }: 134g .ggml_quantize_init (QTYPES [t ][0 ]) 135entries ,off ,prev = [],0 ,None 136o = pathlib .Path (out )if out else d 137o .mkdir (parents = True ,exist_ok = True ) 138items = list (src ["tensors" ]) 139with (o / ("dspark-%s.bin.part" % name )).open ("wb" )as f ,ThreadPoolExecutor (jobs )as ex : 140for i0 in range (0 ,len (items ),2 * jobs ): 141for t ,odt ,q ,shape ,role in ex .map (prep ,items [i0 :i0 + 2 * jobs ]): 142if role is None or role != prev :# (a role's experts back to back: expert e at the first's + e x size) 143pad = (- off )% ALIGN 144f .write (b"\0" * pad ) 145off += pad 146f .write (q .tobytes ()) 147entries .append ([t ,odt ,off ,q .nbytes ,shape ]) 148off += q .nbytes 149prev = role 150 (o / ("dspark-%s.bin.part" % name )).replace (o / ("dspark-%s.bin" % name )) 151 (o / ("dspark-%s.json" % name )).write_text (json .dumps ({"from" :"dspark.bin" ,"experts" :experts ,"dense" :dense , 152"tensors" :entries })) 153"dspark-%s.bin: %d tensors, %.2f GB (experts %s, dense %s)" % (name ,len (entries ),off / 1e9 ,experts ,dense )) 154return 0 155 156 157def main ()-> int : 158ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 159ap .add_argument ("--dir" ,required = True ,help = "the folder with the drafter's three shards" ) 160ap .add_argument ("--requant" ,metavar = "NAME" , 161help = "from dspark.bin there: dspark-NAME.bin with --experts / --dense types (ggml's quantizers)" ) 162ap .add_argument ("--experts" ,default = "IQ4_XS" ,help = "(--requant) the routed experts' type, or keep" ) 163ap .add_argument ("--dense" ,default = "Q8_0" ,help = "(--requant) the dense matrices' type, or keep" ) 164ap .add_argument ("--lib" ,default = str (pathlib .Path ("~/llama.cpp/build/bin/libggml-base.so" ).expanduser ()), 165help = "(--requant) libggml-base" ) 166ap .add_argument ("--jobs" ,type = int ,default = 8 ) 167ap .add_argument ("--out" ,help = "(--requant) the folder to write to (default: --dir)" ) 168a = ap .parse_args () 169d = pathlib .Path (a .dir ) 170if a .requant : 171return requant (d ,a .requant ,a .experts ,a .dense ,a .lib ,a .jobs ,a .out ) 172entries ,off = [],0 173exp = re .compile (r"(mtp\.\d+\.ffn\.experts\.)(\d+)\.(w[123])\.weight$" ) 174 175def order (head ): 176"""The block's tensors, then each role's experts (w1, w3, w2) back to back in expert order - the engine reads 177expert e of a role at the first one's offset + e x its size, as the GGUF stacks them.""" 178plain = sorted (t for t in head if t .startswith ("mtp." )and not t .endswith (".scale" )and not exp .match (t )) 179ex = [exp .match (t )for t in head if exp .match (t )] 180roles = sorted ({(m .group (1 ),m .group (3 ))for m in ex },key = lambda pr : (pr [0 ],"w1w3w2" .index (pr [1 ]))) 181n = {pr :1 + max (int (m .group (2 ))for m in ex if (m .group (1 ),m .group (3 ))== pr )for pr in roles } 182return [(t ,False )for t in plain ]+ [("%s%d.%s.weight" % (p ,i ,r ),i < n [(p ,r )]- 1 ) 183for p ,r in roles for i in range (n [(p ,r )])] 184 185with (d / "dspark.bin.part" ).open ("wb" )as f : 186for name in SHARDS : 187raw ,head ,base = shard (d / name ) 188for t ,packed in order (head ): 189e ,shape = head [t ],list (head [t ]["shape" ]) 190if e ["dtype" ]== "F8_E4M3" : 191s = head [t [:- len ("weight" )]+ "scale" ] 192out ,dt = fp8_to_bf16 (data (raw ,base ,e ),data (raw ,base ,s ),shape [0 ],shape [1 ]),"BF16" 193elif e ["dtype" ]== "I8" : 194s = head [t [:- len ("weight" )]+ "scale" ] 195shape = [shape [0 ],shape [1 ]* 2 ] 196out ,dt = fp4_to_mxfp4 (data (raw ,base ,e ),data (raw ,base ,s ),shape [0 ],shape [1 ]),"MXFP4" 197elif e ["dtype" ]in ("BF16" ,"F32" ): 198out ,dt = data (raw ,base ,e ),e ["dtype" ] 199else : 200raise SystemExit (f" { name } : { t } is { e [ 'dtype' ] } , not a type the drafter's pack covers" ) 201b = out .tobytes () 202f .write (b ) 203entries .append ([t ,dt ,off ,len (b ),shape ]) 204off += len (b ) 205if packed :# (the next expert of the role follows at once) 206continue 207pad = (- off )% ALIGN 208f .write (b"\0" * pad ) 209off += pad 210del raw 211 (d / "dspark.bin.part" ).replace (d / "dspark.bin" ) 212 (d / "dspark.json" ).write_text (json .dumps ({"from" :list (SHARDS ),"tensors" :entries })) 213f"dspark.bin: { len ( entries ) } tensors, { off / 1e9 :.2f } GB" ) 214return 0 215 216 217if __name__ == "__main__" : 218sys .exit (main ())