okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
0f1e5e4cb
main
1"""tools/mtp_rt.py - plan v0.3 P6: the MTP draft layer's runtime files, from the packed MTP GGUF. 2 3python tools/mtp_rt.py --gguf <Strata>/mtp-bf16/mtp-q2_0.gguf --out <Strata>/mtp-bf16/rt 4 5Writes 6experts.bin 512 routed experts in the engine's blob layout (`include/strata/kernels/cpu/expert.hpp`): gate/up 7rows interleaved (2r = gate r, 2r+1 = up r), then down rows; the Q2_0 codes in one plane and the fp16 8scales in another. A lossless relayout of the GGUF's Q2_0 blocks (same bytes, `cpu_expert_fixture.py`). 9dense.bin every other tensor: the large projections quantized to Q8_0 (ggml's reference rounding) so the 10engine's multi-column MMVQ can run them; the hyper-connection and router weights kept BF16; the 11RMSNorm weights as F32 with the Gemma "+1" applied (vLLM GemmaRMSNorm scales by 1 + w). 12dense.txt one line per tensor: name kind rows cols offset bytes (kind = q8_0 | bf16 | f32) 13""" 14from __future__import annotations 15 16import argparse 17import sys 18from pathlib import Path 19 20import numpy as np 21 22sys .path .insert (0 ,str (Path (__file__ ).resolve ().parent )) 23from _paths import gguf_lib # noqa: E402 24gguf = gguf_lib () 25 26H ,FF ,NE = 2560 ,640 ,512 27BLOB = 3 * (H * FF * 18 // 64 ) 28Q8 = {"fc_embedding.weight" ,"fc_hidden.weight" ,"self_attn.q_proj.weight" ,"self_attn.k_proj.weight" , 29"self_attn.v_proj.weight" ,"self_attn.o_proj.weight" ,"self_attn.indexer.index_qk_proj.weight" , 30"mlp.shared_expert.gate_proj.weight" ,"mlp.shared_expert.up_proj.weight" ,"mlp.shared_expert.down_proj.weight" } 31 32 33def q8_0 (x :np .ndarray )-> bytes : 34"""ggml quantize_row_q8_0_ref over rows of a 2-D float32 array: 32-value blocks, fp16 d = amax / 127.""" 35b = x .reshape (- 1 ,32 ).astype (np .float32 ) 36amax = np .abs (b ).max (axis = 1 ) 37d = amax / 127.0 38inv = np .where (d > 0 ,1.0 / np .where (d > 0 ,d ,1.0 ),0.0 ).astype (np .float32 ) 39v = b * inv [:,None ] 40q = (np .sign (v )* np .floor (np .abs (v )+ 0.5 )).astype (np .int8 ) 41out = np .empty ((b .shape [0 ],34 ),dtype = np .uint8 ) 42out [:, :2 ]= d .astype (np .float16 ).view (np .uint8 ).reshape (- 1 ,2 ) 43out [:,2 :]= q .view (np .uint8 ) 44return out .tobytes () 45 46 47def blob_of (gu :np .ndarray ,dn :np .ndarray )-> bytes : 48"""gu: (1280, 720) Q2_0 rows (gate rows 0..639, up rows 640..1279); dn: (2560, 180).""" 49gub = gu .reshape (2 * FF ,H // 64 ,18 ) 50inter = np .empty_like (gub ) 51inter [0 ::2 ]= gub [:FF ] 52inter [1 ::2 ]= gub [FF :] 53dnb = dn .reshape (H ,FF // 64 ,18 ) 54parts = [inter [:, :,2 :].tobytes (),dnb [:, :,2 :].tobytes (),inter [:, :, :2 ].tobytes (),dnb [:, :, :2 ].tobytes ()] 55out = b"" .join (parts ) 56assert len (out )== BLOB ,len (out ) 57return out 58 59 60def main ()-> int : 61ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 62ap .add_argument ("--gguf" ,required = True ) 63ap .add_argument ("--out" ,required = True ) 64a = ap .parse_args () 65out = Path (a .out ) 66out .mkdir (parents = True ,exist_ok = True ) 67r = gguf .GGUFReader (a .gguf ) 68tens = {t .name :t for t in r .tensors } 69gu = np .asarray (tens ["mtp.layers.0.mlp.experts.gate_up_proj" ].data ) 70dn = np .asarray (tens ["mtp.layers.0.mlp.experts.down_proj" ].data ) 71assert gu .shape == (NE ,2 * FF ,720 )and dn .shape == (NE ,H ,180 ), (gu .shape ,dn .shape ) 72with open (out / "experts.bin" ,"wb" )as f : 73for e in range (NE ): 74f .write (blob_of (gu [e ],dn [e ])) 75lines = [] 76off = 0 77with open (out / "dense.bin" ,"wb" )as f : 78for name ,t in tens .items (): 79if "experts." in name : 80continue 81short = name [len ("mtp." ):] 82short = short [len ("layers.0." ):]if short .startswith ("layers.0." )else short 83data = np .asarray (t .data ) 84if int (t .tensor_type )== 0 :# F32 norm weights: raw GemmaRMSNorm w -> 1 + w 85arr = (data .astype (np .float32 )+ 1.0 ) 86raw ,kind ,rows ,cols = arr .tobytes (),"f32" ,1 ,arr .size 87else :# BF16 88u16 = data .view (np .uint16 )if data .dtype != np .uint16 else data 89u16 = u16 .reshape (data .shape [0 ],- 1 ) 90rows ,cols = u16 .shape 91if short in Q8 : 92f32 = (u16 .astype (np .uint32 )<< 16 ).view (np .float32 ) 93raw ,kind = q8_0 (f32 ),"q8_0" 94else : 95raw ,kind = u16 .tobytes (),"bf16" 96pad = (- off )% 256 97f .write (b"\0" * pad ) 98off += pad 99f .write (raw ) 100lines .append (f" { short } { kind } { rows } { cols } { off } { len ( raw ) } " ) 101off += len (raw ) 102 (out / "dense.txt" ).write_text ("\n" .join (lines )+ "\n" ,encoding = "utf-8" ) 103f"experts.bin { NE * BLOB } B, dense.bin { off } B, { len ( lines ) } tensors -> { out } " ) 104for l in lines : 105" " + l ) 106return 0 107 108 109if __name__ == "__main__" : 110sys .exit (main ())