okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/mtp_pack.py - plan v0.3 P6 prep: the MTP draft block as a Strata GGUF, from the BF16 tensors. 2 3llama.cpp's qwen4exp converter drops the MTP head (`supports_mtp_export = False`), and the flyweight MTP GGUF is 4no longer on this PC, so Strata packs its own from the 31 `mtp.*` tensors fetched by tools/mtp_fetch.py: 5 6python tools/mtp_pack.py --src Desktop/Strata/mtp-bf16 --experts q2_0 --out mtp-q2_0.gguf 7python tools/mtp_pack.py --src ... --experts q4_0 --out mtp-q4_0.gguf (acceptance comparison arm) 8 9Layout: dense tensors (attention, indexer, hyper-connections, shared expert, router, fc/norms) stay BF16 (F32 for 101-D norms), ~0.18 GB. The routed experts keep the checkpoint's fused layout - `gate_up_proj` [512, 1280, 2560] and 11`down_proj` [512, 2560, 640], quantized along the last (input) axis - in one of: 12 13q2_0 64-element blocks, grid {-1, 0, 1, 2} x d. The scale is chosen per block to MINIMIZE squared error over 14that grid (the ggml reference sets d = max|w| and never uses the +2 level). Same format as the main 15model's experts, so Strata's CPU VNNI kernel and GPU hit kernel serve it unchanged. ~0.71 GB. 16q4_0 ggml reference rounding. ~1.42 GB. q8_0 ggml reference. ~2.67 GB. 17 18This is round-to-nearest, not GSQ: the plan picks the expert format by MEASURED draft acceptance (P0.3/P6), not 19by this file's reconstruction error, which is reported per tensor only as a sanity check. No model runs here. 20""" 21from __future__import annotations 22 23import argparse 24import hashlib 25import json 26import sys 27import time 28from pathlib import Path 29 30import numpy as np 31 32HERE = Path (__file__ ).resolve ().parent 33sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 34from _paths import gguf_lib # noqa: E402 35gguf = gguf_lib ()# noqa: E402 (tools/strata_gguf.py; STRATA_GGUF_PY selects llama.cpp's gguf-py instead) 36 37EXPERT_TENSORS = ("mtp.layers.0.mlp.experts.gate_up_proj" ,"mtp.layers.0.mlp.experts.down_proj" ) 38 39 40class _Experts : 41"""Index an expert out of a BF16 memmap as float32 on demand.""" 42def __init__ (self ,raw ): 43self .raw = raw 44 45def __getitem__ (self ,e ): 46return (np .asarray (self .raw [e ]).astype (np .uint32 )<< 16 ).view (np .float32 ) 47 48 49def load_bf16 (path :Path ,shape :list [int ])-> np .ndarray : 50raw = np .fromfile (path ,dtype = "<u2" ) 51if raw .size != int (np .prod (shape )): 52raise ValueError (f" { path } : { raw . size } values, expected shape { shape } " ) 53return (raw .astype (np .uint32 )<< 16 ).view (np .float32 ).reshape (shape ) 54 55 56# ------------------------------------------------------------------------------------------------ quantizers 57def q2_0 (w :np .ndarray )-> np .ndarray : 58"""[..., n] float32 -> bytes of Q2_0 blocks (fp16 d, 16 bytes of 2-bit codes, code = q + 1, 4 per byte).""" 59x = w .reshape (- 1 ,64 ).astype (np .float32 ) 60amax = np .abs (x ).max (axis = 1 ,keepdims = True ) 61best_err = np .full ((x .shape [0 ],1 ),np .inf ,dtype = np .float32 ) 62best_d = np .zeros_like (amax ) 63# Candidate scales span amax/2 (the +2 level reaches the max) to amax (the ggml reference); 17 steps. 64for f in np .linspace (0.5 ,1.0 ,17 ,dtype = np .float32 ): 65d = amax * f 66inv = np .where (d > 0 ,1.0 / np .where (d > 0 ,d ,1.0 ),0.0 ) 67q = np .clip (np .rint (x * inv ),- 1 ,2 ) 68err = ((q * d - x )** 2 ).sum (axis = 1 ,keepdims = True ) 69better = err < best_err 70best_err = np .where (better ,err ,best_err ) 71best_d = np .where (better ,d ,best_d ) 72d16 = best_d .astype (np .float16 ) 73d = d16 .astype (np .float32 )# quantize against the STORED scale 74inv = np .where (d > 0 ,1.0 / np .where (d > 0 ,d ,1.0 ),0.0 ) 75codes = (np .clip (np .rint (x * inv ),- 1 ,2 )+ 1 ).astype (np .uint8 )# 0..3 76c = codes .reshape (- 1 ,16 ,4 ) 77packed = (c [:, :,0 ]| (c [:, :,1 ]<< 2 )| (c [:, :,2 ]<< 4 )| (c [:, :,3 ]<< 6 )).astype (np .uint8 ) 78out = np .empty ((x .shape [0 ],18 ),dtype = np .uint8 ) 79out [:, :2 ]= d16 .view (np .uint8 ).reshape (- 1 ,2 ) 80out [:,2 :]= packed 81return out .reshape (- 1 ) 82 83 84def q4_0 (w :np .ndarray )-> np .ndarray : 85"""ggml quantize_row_q4_0_ref: d = max / -8 (signed max), code = clamp(round(x/d + 8.5) truncated, 0, 15).""" 86x = w .reshape (- 1 ,32 ).astype (np .float32 ) 87idx = np .abs (x ).argmax (axis = 1 ) 88mx = x [np .arange (x .shape [0 ]),idx ][:,None ] 89d = mx / - 8.0 90inv = np .where (d != 0 ,1.0 / np .where (d != 0 ,d ,1.0 ),0.0 ) 91q = np .minimum (15 ,np .trunc (x * inv + 8.5 )).astype (np .uint8 ) 92packed = (q [:, :16 ]| (q [:,16 :]<< 4 )).astype (np .uint8 ) 93out = np .empty ((x .shape [0 ],18 ),dtype = np .uint8 ) 94out [:, :2 ]= d .astype (np .float16 ).view (np .uint8 ).reshape (- 1 ,2 ) 95out [:,2 :]= packed 96return out .reshape (- 1 ) 97 98 99def q8_0 (w :np .ndarray )-> np .ndarray : 100x = w .reshape (- 1 ,32 ).astype (np .float32 ) 101d = np .abs (x ).max (axis = 1 ,keepdims = True )/ 127.0 102inv = np .where (d > 0 ,1.0 / np .where (d > 0 ,d ,1.0 ),0.0 ) 103q = np .rint (x * inv ).astype (np .int8 ) 104out = np .empty ((x .shape [0 ],34 ),dtype = np .uint8 ) 105out [:, :2 ]= d .astype (np .float16 ).view (np .uint8 ).reshape (- 1 ,2 ) 106out [:,2 :]= q .view (np .uint8 ) 107return out .reshape (- 1 ) 108 109 110def dequant (kind :str ,blob :np .ndarray ,n :int )-> np .ndarray : 111if kind == "q2_0" : 112b = blob .reshape (- 1 ,18 ) 113d = b [:, :2 ].copy ().view (np .float16 ).astype (np .float32 ) 114qs = b [:,2 :] 115codes = np .stack ([(qs >> s )& 3 for s in (0 ,2 ,4 ,6 )],axis = 2 ).reshape (- 1 ,64 ).astype (np .float32 ) 116return ((codes - 1.0 )* d ).reshape (- 1 )[:n ] 117if kind == "q4_0" : 118b = blob .reshape (- 1 ,18 ) 119d = b [:, :2 ].copy ().view (np .float16 ).astype (np .float32 ) 120qs = b [:,2 :] 121q = np .concatenate ([qs & 15 ,qs >> 4 ],axis = 1 ).astype (np .float32 ) 122return ((q - 8.0 )* d ).reshape (- 1 )[:n ] 123b = blob .reshape (- 1 ,34 ) 124d = b [:, :2 ].copy ().view (np .float16 ).astype (np .float32 ) 125return (b [:,2 :].view (np .int8 ).astype (np .float32 )* d ).reshape (- 1 )[:n ] 126 127 128QUANT = {"q2_0" : (q2_0 ,gguf .GGMLQuantizationType .Q2_0 ,64 ,18 ), 129"q4_0" : (q4_0 ,gguf .GGMLQuantizationType .Q4_0 ,32 ,18 ), 130"q8_0" : (q8_0 ,gguf .GGMLQuantizationType .Q8_0 ,32 ,34 )} 131 132 133def main ()-> int : 134ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 135ap .add_argument ("--src" ,required = True ,help = "directory written by tools/mtp_fetch.py fetch" ) 136ap .add_argument ("--experts" ,choices = sorted (QUANT ),default = "q2_0" ) 137ap .add_argument ("--out" ,required = True ) 138ap .add_argument ("--check-experts" ,type = int ,default = 8 ,help = "experts per tensor used for the error report" ) 139a = ap .parse_args () 140src = Path (a .src ) 141manifest = json .loads ((src / "mtp-manifest.json" ).read_text ()) 142fn ,qtype ,block ,block_bytes = QUANT [a .experts ] 143w = gguf .GGUFWriter (a .out ,"qwen4exp-mtp" ) 144w .add_string ("strata.mtp.source" ,"Qwen/Qwen3.8-Flash-Next BF16 checkpoint, mtp.* tensors" ) 145w .add_string ("strata.mtp.source_sha256" ,hashlib .sha256 ( 146json .dumps ({t ["name" ]:t ["sha256" ]for t in manifest },sort_keys = True ).encode ()).hexdigest ()) 147w .add_string ("strata.mtp.expert_format" ,a .experts ) 148w .add_string ("strata.mtp.expert_quantizer" ,"per-block MSE scale search" if a .experts == "q2_0" else "ggml reference" ) 149report = [] 150for t in sorted (manifest ,key = lambda t :t ["name" ]): 151name ,shape = t ["name" ],t ["shape" ] 152t0 = time .time () 153if name in EXPERT_TENSORS : 154# Streamed one expert at a time from a read-only view: the fused gate_up tensor alone is 6.7 GB as 155# float32, so it is never materialized whole. 156raw = np .memmap (src / t ["file" ],dtype = "<u2" ,mode = "r" ,shape = tuple (shape )) 157x = _Experts (raw ) 158if shape [- 1 ]% block : 159raise ValueError (f" { name } : inner dim { shape [ - 1 ] } not a multiple of { block } " ) 160parts = [fn (x [e ])for e in range (shape [0 ])]# one expert at a time bounds memory 161blob = np .concatenate (parts ) 162errs = [] 163for e in range (min (a .check_experts ,shape [0 ])): 164ref = x [e ].reshape (- 1 ) 165got = dequant (a .experts ,parts [e ],ref .size ) 166errs .append (float (np .sqrt (((got - ref )** 2 ).mean ())/ (np .sqrt ((ref ** 2 ).mean ())+ 1e-12 ))) 167# the writer takes the quantized bytes with the ELEMENT shape; ggml order is innermost-first. 168w .add_tensor (name ,blob ,raw_shape = list (shape [:- 1 ])+ [shape [- 1 ]// block * block_bytes ],raw_dtype = qtype ) 169report .append ({"tensor" :name ,"format" :a .experts ,"bytes" :int (blob .size ), 170"relative_rms_error_first_experts" :round (float (np .mean (errs )),5 ), 171"seconds" :round (time .time ()- t0 ,1 )}) 172elif len (shape )== 1 : 173x = load_bf16 (src / t ["file" ],shape ) 174w .add_tensor (name ,x .astype (np .float32 )) 175report .append ({"tensor" :name ,"format" :"F32" ,"bytes" :x .size * 4 }) 176else : 177bf = np .fromfile (src / t ["file" ],dtype = "<u2" ).reshape (shape ) 178w .add_tensor (name ,bf ,raw_dtype = gguf .GGMLQuantizationType .BF16 ) 179report .append ({"tensor" :name ,"format" :"BF16" ,"bytes" :bf .size * 2 }) 180f" { name } : { report [ - 1 ][ 'format' ] } { report [ - 1 ][ 'bytes' ] / 1e6 :.1f } MB" ,flush = True ) 181w .write_header_to_file () 182w .write_kv_data_to_file () 183w .write_tensors_to_file () 184w .close () 185total = sum (r ["bytes" ]for r in report ) 186Path (a .out + ".report.json" ).write_text (json .dumps ({"total_bytes" :total ,"tensors" :report },indent = 1 )) 187f"wrote { a . out } : { total / 1e9 :.3f } GB of tensor data" ) 188return 0 189 190 191if __name__ == "__main__" : 192sys .exit (main ())