okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b82a36810
main
1#!/usr/bin/env python3 2"""Synthetic qwen4exp GGUF files with random weights, at any shape, in the per-tensor type mix of an Unsloth UD file. 3 4Why: the engine is compiled for one model shape (include/strata/core/geometry.hpp). To check that a build for another shape 5loads and runs, there has to be a file of that shape. The writer in gguf_writer.py holds every tensor in memory and knows 6only F32, F16 and Q2_0; this one streams, and writes the types the UD files use (Q8_0, Q4_K, Q5_K, Q6_K, Q5_0, Q5_1, IQ4_NL, 7IQ4_XS, IQ3_S, BF16, F32). The weights are random bytes with the scale fields of every block set to a fixed small number, so 8the dequantized values stay in a few hundredths and the activations stay finite; nothing here quantizes anything. 9 10python tools/q4geo_synth.py --shape q4_lite --layers 8 --vocab 8192 --recipe ud-q4k --out /data/synth/lite.gguf 11python tools/q4geo_synth.py --shape q4_lite --layers 8 --header out.hpp # the geometry header for that file 12python tools/q4geo_synth.py --from-gguf some.gguf --header out.hpp # day one: a geometry header from a real file 13python tools/q4geo_synth.py --list 14 15The layout (tensor names and shapes) is core/family_layout.hpp's for qwen4exp. The PLE / n-gram tables of Flash-Next are NOT 16written (their hash constants are compiled in and the table is 28 GB): run the engine with --no-ple on these files. 17 18The geometry header written by --header is what -DSTRATA_GEOMETRY_FILE=<path> takes. 19""" 20from __future__import annotations 21 22import argparse 23import pathlib 24import struct 25import sys 26 27import numpy as np 28 29sys .path .insert (0 ,str (pathlib .Path (__file__ ).resolve ().parent )) 30from gguf_writer import GGUFWriter ,GGUF_MAGIC ,DEFAULT_ALIGNMENT # noqa: E402 31 32# ggml type id, elements per block, bytes per block, fields to set: (byte offset, fp16 value) 33QTYPES = { 34"F32" : (0 ,1 ,4 , []), 35"F16" : (1 ,1 ,2 , []), 36"BF16" : (30 ,1 ,2 , []), 37"Q5_0" : (6 ,32 ,22 , [(0 ,0.0024 )]), 38"Q5_1" : (7 ,32 ,24 , [(0 ,0.0012 ), (2 ,- 0.018 )]), 39"Q8_0" : (8 ,32 ,34 , [(0 ,0.0003 )]), 40"Q4_K" : (12 ,256 ,144 , [(0 ,3e-5 ), (2 ,3e-5 )]), 41"Q5_K" : (13 ,256 ,176 , [(0 ,1.5e-5 ), (2 ,1.5e-5 )]), 42"Q6_K" : (14 ,256 ,210 , [(208 ,5e-6 )]), 43"IQ4_NL" : (20 ,32 ,18 , [(0 ,0.0003 )]), 44"IQ3_S" : (21 ,256 ,110 , [(0 ,1e-4 )]), 45"IQ4_XS" : (23 ,256 ,136 , [(0 ,1e-5 )]), 46} 47 48ROUTER_SCALE = 1.0 # --router-scale: the router's weights times this. Random weights give router logits packed so closely that two 49# implementations of one model (llama.cpp CPU and GPU among them) pick different experts at a few positions, and one 50# expert flip moves a position's KL by 100x; a larger scale spreads the logits like a trained router's 51EXACT_PARTS :set = set ()# --exact-parts router,f32,q8 (--exact-bf16 = all three): which tensors are written BF16-exact 52TOKENIZER_FROM = None # --tokenizer-from FILE: the tokenizer.* keys (vocabulary, merges, special tokens, chat template) and the PLE token ids of a real GGUF, so a Terminal/server can encode text for the synthetic model 53EXACT_BF16 = False # --exact-bf16: every F32 tensor holds BF16-representable values and the Q8_0 scale is a power of two, so the pack's 54# --compat-bf16 conversion (router, shared-expert gate, HC down/up, ...) is lossless and llama.cpp sees the engine's weights 55 56# Flash-Next's values for every field a shape does not name 57FLASH = dict (n_embd = 2560 ,n_layers = 48 ,n_head = 24 ,n_head_kv = 2 ,head_dim = 256 ,n_rot = 64 ,ssm_state = 128 ,ssm_k_heads = 16 , 58ssm_v_heads = 48 ,ssm_d_conv = 4 ,idx_q_heads = 4 ,idx_key_dim = 128 ,idx_top_k = 2048 ,idx_block = 4 ,hc = 4 ,hc_lr = 320 , 59n_expert = 512 ,n_expert_used = 10 ,n_ff = 640 ,qsa_interval = 4 ) 60SHAPES = { 61"flash_next" : {}, 62"q4_deep" :dict (n_layers = 64 ), 63"q4_lite" :dict (n_embd = 2048 ,n_layers = 40 ,n_head = 16 ,ssm_v_heads = 32 ,hc_lr = 256 ,n_expert = 256 ,n_expert_used = 8 ,n_ff = 512 ), 64"q4_mid" :dict (n_embd = 3072 ,n_layers = 48 ,n_head = 32 ,ssm_v_heads = 64 ,hc_lr = 384 ,n_expert = 256 ,n_expert_used = 8 ,n_ff = 1024 ), 65"q4_big" :dict (n_embd = 4096 ,n_layers = 60 ,n_head = 32 ,ssm_v_heads = 64 ,hc_lr = 512 ,n_expert = 512 ,n_expert_used = 10 ,n_ff = 1024 ), 66} 67 68 69def shape (name :str ,layers :int | None = None ,** over )-> dict : 70s = dict (FLASH ) 71s .update (SHAPES [name ]) 72if layers : 73s ["n_layers" ]= layers 74s .update (over ) 75s ["conv_ch" ]= 2 * s ["ssm_state" ]* s ["ssm_k_heads" ]+ s ["ssm_state" ]* s ["ssm_v_heads" ] 76s ["value_dim" ]= s ["ssm_state" ]* s ["ssm_v_heads" ] 77return s 78 79 80# ------------------------------------------------------------------ layout (core/family_layout.hpp) 81def layer_tensors (s :dict ,layer :int ): 82"""(name, shape, role) of one layer.""" 83N ,NE ,FF = s ["n_embd" ],s ["n_expert" ],s ["n_ff" ] 84H = s ["hc" ]* N 85t = [("ffn_gate_inp.weight" , [N ,NE ],"router" ), ("ffn_gate_inp_shexp.weight" , [N ],"small" ), 86 ("ffn_gate_shexp.weight" , [N ,FF ],"shexp" ), ("ffn_up_shexp.weight" , [N ,FF ],"shexp" ), 87 ("ffn_down_shexp.weight" , [FF ,N ],"shexp" ), 88 ("ffn_gate_exps.weight" , [N ,FF ,NE ],"gate" ), ("ffn_up_exps.weight" , [N ,FF ,NE ],"up" ), 89 ("ffn_down_exps.weight" , [FF ,N ,NE ],"down" )] 90for blk in ("attn" ,"ffn" ): 91t += [(f"hc_ { blk } _down.weight" , [H ,s ["hc_lr" ]],"hc" ), (f"hc_ { blk } _up.weight" , [s ["hc_lr" ],H ],"hc" ), 92 (f"hc_ { blk } _inject.weight" , [H ,s ["hc" ]],"inject" ), (f"hc_ { blk } _norm.weight" , [H ],"norm" )] 93if (layer % s ["qsa_interval" ])!= s ["qsa_interval" ]- 1 : 94t += [("attn_qkv.weight" , [N ,s ["conv_ch" ]],"dense" ), ("attn_gate.weight" , [N ,s ["value_dim" ]],"dense" ), 95 ("ssm_out.weight" , [s ["value_dim" ],N ],"dense" ), ("ssm_conv1d.weight" , [s ["ssm_d_conv" ],s ["conv_ch" ]],"conv" ), 96 ("ssm_alpha.weight" , [N ,s ["ssm_v_heads" ]],"small_mat" ), ("ssm_beta.weight" , [N ,s ["ssm_v_heads" ]],"small_mat" ), 97 ("ssm_a" , [s ["ssm_v_heads" ]],"ssm_a" ), ("ssm_dt.bias" , [s ["ssm_v_heads" ]],"bias" ), 98 ("ssm_norm.weight" , [s ["ssm_state" ]],"norm" )] 99else : 100hd ,nh ,nkv = s ["head_dim" ],s ["n_head" ],s ["n_head_kv" ] 101t += [("attn_q.weight" , [N ,2 * nh * hd ],"dense" ), ("attn_k.weight" , [N ,nkv * hd ],"dense" ), 102 ("attn_v.weight" , [N ,nkv * hd ],"dense" ), ("attn_output.weight" , [nh * hd ,N ],"dense" ), 103 ("attn_q_norm.weight" , [hd ],"norm" ), ("attn_k_norm.weight" , [hd ],"norm" ), 104 ("indexer.q_proj.weight" , [N ,s ["idx_q_heads" ]* s ["idx_key_dim" ]],"indexer" ), 105 ("indexer.k_proj.weight" , [N ,s ["idx_key_dim" ]],"indexer" ), 106 ("indexer.q_norm.weight" , [s ["idx_key_dim" ]],"norm" ), ("indexer.k_norm.weight" , [s ["idx_key_dim" ]],"norm" )] 107return t 108 109 110PLE_ROWS = 320001536 111PLE_VOCAB = [20000003 ,20000023 ,20000033 ,20000047 ,20000059 ,20000063 ,20000069 ,20000077 ,20000081 ,20000093 ,20000107 , 11220000147 ,20000153 ,20000159 ,20000161 ,20000171 ] 113PLE_MULT = [23703573157769 ,20109073645365 ,8052911324071 ] 114 115 116def all_tensors (s :dict ,vocab :int ,ple :bool = True ): 117N = s ["n_embd" ] 118H = s ["hc" ]* N 119out = [("token_embd.weight" , [N ,vocab ],"embd" ), ("output.weight" , [N ,vocab ],"output" ), 120 ("output_hc_down.weight" , [H ,s ["hc_lr" ]],"hc" ), ("output_hc_up.weight" , [s ["hc_lr" ],H ],"hc" ), 121 ("output_hc_norm.weight" , [H ],"norm" )] 122for l in range (s ["n_layers" ]): 123out += [(f"blk. { l } . { n } " ,sh ,r )for n ,sh ,r in layer_tensors (s ,l )] 124if ple : 125# the engine's native path always reads the PLE key; its hash constants are compiled in (kernels/ngram.cpp), so the table has 126# Flash-Next's 320001536 rows of n_embd/16; it is written SPARSE (zeros: IQ4_NL blocks with a zero scale are zero vectors) 127out += [("per_layer_token_embd.weight" , [N // 16 ,PLE_ROWS ],"ple_table" ), 128 ("blk.1.ple_conv1d.weight" , [4 ,H ],"conv" ), ("blk.1.ple_key.weight" , [N ,H ],"dense" ), 129 ("blk.1.ple_norm_conv.weight" , [H ],"norm" ), ("blk.1.ple_norm_key.weight" , [H ],"norm" ), 130 ("blk.1.ple_norm_query.weight" , [H ],"norm" ), ("blk.1.ple_value.weight" , [N ,N ],"dense" )] 131return out 132 133 134# ------------------------------------------------------------------ recipes (the type per role, as Unsloth's UD files) 135def recipe_type (recipe :str ,role :str ,layer :int ,s :dict )-> str : 136ff256 = s ["n_ff" ]% 256 == 0 137if role in ("router" ,"small" ,"norm" ,"inject" ,"small_mat" ,"conv" ,"ssm_a" ,"bias" ): 138return "F32" 139if role == "indexer" : 140return "BF16" 141if role in ("dense" ,"shexp" ,"hc" ): 142return "Q8_0" 143if role == "embd" : 144return "Q8_0" 145if role == "ple_table" : 146return "IQ4_NL" 147if role == "output" : 148return "Q6_K" if recipe == "ud-iq4xs" else "Q8_0" 149first = layer == 0 150if recipe == "ud-q4k" :# UD-Q4_K_XL: Q4_K gate/up; down Q5_K, or Q5_1 where llama.cpp falls back (n_ff % 256); Q8_0 in a few 151if role in ("gate" ,"up" ): 152return "Q5_K" if first else "Q4_K" 153return "Q8_0" if first else ("Q5_K" if ff256 else "Q5_1" ) 154if recipe == "ud-q4k-q6" :# as ud-q4k with Q6_K down on every 8th layer (Unsloth's Qwen3.6 mix: 38 x Q5_K, 3 x Q6_K) 155if role in ("gate" ,"up" ): 156return "Q5_K" if first else "Q4_K" 157if first : 158return "Q8_0" 159return ("Q6_K" if layer % 8 == 1 else "Q5_K" )if ff256 else "Q5_1" 160if recipe == "ud-iq4xs" :# UD-IQ4_XS: IQ3_S gate/up (IQ4_XS in one layer), IQ4_XS down or IQ4_NL by the fallback 161if role in ("gate" ,"up" ): 162return "IQ4_XS" if first else "IQ3_S" 163return "Q8_0" if first else ("IQ4_XS" if ff256 else "IQ4_NL" ) 164if recipe == "ud-q5_0down" :# the v31 mix: Q5_0 down layers (what llama.cpp makes of Q4_K down at a non-256 width) 165if role in ("gate" ,"up" ): 166return "Q4_K" 167return "Q5_0" 168if recipe == "fused-kq" :# Q4_K gate/up (Q5_K in layer 0) with Q5_1 / Q8_0 down at ANY expert width: the pairs the AMD fused / F16 prompt kernels take (Q4-HIPKQ) 169if role in ("gate" ,"up" ): 170return "Q5_K" if first else "Q4_K" 171return "Q8_0" if layer % 2 == 0 else "Q5_1" 172if recipe == "mix-kq" :# one file with every K-quant expert path of the AMD prompt kernels: Q5_K/Q8_0 (fused), Q4_K/Q5_K and Q4_K/Q6_K (MMQ), Q4_K/Q5_1 (fused F16), by layer % 4 (Q4-HIPKQ) 173if role in ("gate" ,"up" ): 174return "Q5_K" if layer % 4 == 0 else "Q4_K" 175return ("Q8_0" ,"Q5_K" ,"Q5_1" ,"Q6_K" )[layer % 4 ] 176if recipe == "fused-iq" :# IQ3_S gate/up (IQ4_XS in layer 0) with IQ4_NL down at any expert width: the native IQ pack's fused prompt kernels (Q4-HIPKQ) 177if role in ("gate" ,"up" ): 178return "IQ4_XS" if first else "IQ3_S" 179return "IQ4_NL" 180raise SystemExit (f"unknown recipe { recipe } " ) 181 182 183RECIPES = ["ud-q4k" ,"ud-q4k-q6" ,"ud-iq4xs" ,"ud-q5_0down" ,"fused-kq" ,"fused-iq" ,"mix-kq" ] 184 185 186def row_ok (ty :str ,ne0 :int )-> bool : 187return ne0 % QTYPES [ty ][1 ]== 0 188 189 190# ------------------------------------------------------------------ data 191def bf16_round (a :np .ndarray )-> np .ndarray : 192"""float32 rounded to the nearest BF16 (ties to even), returned as float32.""" 193u = a .astype ("<f4" ).view ("<u4" ).astype (np .uint64 ) 194u = (u + 0x7FFF + ((u >> 16 )& 1 ))& 0xFFFF0000 195return u .astype ("<u4" ).view ("<f4" ) 196 197 198def small_f32 (role :str ,shape :list [int ],rng :np .random .Generator )-> np .ndarray : 199a = _small_f32 (role ,shape ,rng ) 200if role == "router" : 201a = (a * np .float32 (ROUTER_SCALE )).astype ("<f4" ) 202if role == "router" : 203return bf16_round (a )if ("router" in EXACT_PARTS )else a 204return bf16_round (a )if ("f32" in EXACT_PARTS )else a 205 206 207def _small_f32 (role :str ,shape :list [int ],rng :np .random .Generator )-> np .ndarray : 208n = int (np .prod (shape )) 209if role == "norm" : 210return (1.0 + 0.05 * rng .standard_normal (n )).astype ("<f4" ) 211if role == "ssm_a" : 212return (- rng .uniform (0.1 ,1.5 ,n )).astype ("<f4" ) 213if role == "bias" : 214return (0.1 * rng .standard_normal (n )).astype ("<f4" ) 215if role == "conv" : 216return (0.1 * rng .standard_normal (n )).astype ("<f4" ) 217if role == "inject" : 218return (0.25 + 0.05 * rng .standard_normal (n )).astype ("<f4" ) 219return (0.02 * rng .standard_normal (n )).astype ("<f4" ) 220 221 222def tensor_bytes (ty :str ,shape :list [int ])-> int : 223_ ,blk ,tsz ,_ = QTYPES [ty ] 224n = int (np .prod (shape )) 225assert n % blk == 0 , (ty ,shape ) 226return n // blk * tsz 227 228 229def emit_data (fh ,ty :str ,role :str ,shape :list [int ],rng :np .random .Generator )-> int : 230tid ,blk ,tsz ,fields = QTYPES [ty ] 231total = tensor_bytes (ty ,shape ) 232if role == "ple_table" :# a hole: zeros, no disk 233fh .seek (total - 1 ,1 ) 234fh .write (bytes (1 )) 235return total 236if ty == "F32" : 237fh .write (small_f32 (role ,shape ,rng ).tobytes ()) 238return total 239if ty == "BF16" : 240a = (0.02 * rng .standard_normal (int (np .prod (shape )))).astype ("<f4" ) 241fh .write ((a .view ("<u4" )>> 16 ).astype ("<u2" ).tobytes ()) 242return total 243nblk = total // tsz 244step = max (1 , (64 << 20 )// tsz ) 245done = 0 246while done < nblk : 247m = min (step ,nblk - done ) 248b = rng .integers (0 ,256 ,size = (m ,tsz ),dtype = np .uint8 ) 249for off ,val in fields : 250if "q8" in EXACT_PARTS and ty == "Q8_0" : 251val = 2.0 ** - 12 252b [:,off :off + 2 ]= np .frombuffer (np .float16 (val ).tobytes (),dtype = np .uint8 ) 253fh .write (b .tobytes ()) 254done += m 255return total 256 257 258# ------------------------------------------------------------------ metadata 259def metadata (s :dict ,vocab :int ,name :str )-> GGUFWriter : 260w = GGUFWriter () 261p = "qwen4exp." 262w .add ("general.architecture" ,"qwen4exp" ) 263w .add ("general.type" ,"model" ) 264w .add ("general.name" ,name ) 265w .add ("general.description" ,"synthetic random weights (tools/q4geo_synth.py), not a model" ) 266w .add (p + "block_count" ,s ["n_layers" ],"u32" ) 267w .add (p + "context_length" ,262144 ,"u32" ) 268w .add (p + "embedding_length" ,s ["n_embd" ],"u32" ) 269w .add (p + "attention.head_count" ,s ["n_head" ],"u32" ) 270w .add (p + "attention.head_count_kv" ,s ["n_head_kv" ],"u32" ) 271w .add (p + "rope.dimension_sections" , [11 ,11 ,10 ,0 ],"array:i32" ) 272w .add (p + "rope.freq_base" ,10000000.0 ,"f32" ) 273w .add (p + "attention.layer_norm_rms_epsilon" ,1e-6 ,"f32" ) 274w .add (p + "expert_count" ,s ["n_expert" ],"u32" ) 275w .add (p + "expert_used_count" ,s ["n_expert_used" ],"u32" ) 276w .add (p + "attention.key_length" ,s ["head_dim" ],"u32" ) 277w .add (p + "attention.value_length" ,s ["head_dim" ],"u32" ) 278w .add (p + "expert_feed_forward_length" ,s ["n_ff" ],"u32" ) 279w .add (p + "expert_shared_feed_forward_length" ,s ["n_ff" ],"u32" ) 280w .add (p + "ssm.conv_kernel" ,s ["ssm_d_conv" ],"u32" ) 281w .add (p + "ssm.state_size" ,s ["ssm_state" ],"u32" ) 282w .add (p + "ssm.group_count" ,s ["ssm_k_heads" ],"u32" ) 283w .add (p + "ssm.time_step_rank" ,s ["ssm_v_heads" ],"u32" ) 284w .add (p + "ssm.inner_size" ,s ["value_dim" ],"u32" ) 285w .add (p + "full_attention_interval" ,s ["qsa_interval" ],"u32" ) 286w .add (p + "rope.dimension_count" ,s ["n_rot" ],"u32" ) 287w .add (p + "hyper_connection.count" ,s ["hc" ],"u32" ) 288w .add (p + "hyper_connection.low_rank" ,s ["hc_lr" ],"u32" ) 289w .add (p + "attention.indexer.head_count" ,s ["idx_q_heads" ],"u32" ) 290w .add (p + "attention.indexer.key_length" ,s ["idx_key_dim" ],"u32" ) 291w .add (p + "attention.indexer.top_k" ,s ["idx_top_k" ],"u32" ) 292w .add (p + "attention.compress_ratios" , 293 [s ["idx_block" ]if l % s ["qsa_interval" ]== s ["qsa_interval" ]- 1 else 0 for l in range (s ["n_layers" ])],"array:i32" ) 294offs = [sum (PLE_VOCAB [:i ])for i in range (16 )] 295w .add (p + "ple.layers" , [1 ],"array:i32" ) 296w .add (p + "ple.ngram_size" ,3 ,"u32" ) 297w .add (p + "ple.heads_per_ngram" ,8 ,"u32" ) 298w .add (p + "ple.conv_kernel" ,4 ,"u32" ) 299w .add (p + "ple.eos_token_id" ,vocab - 2 ,"u32" ) 300w .add (p + "embedding_length_per_layer_input" ,s ["n_embd" ]// 16 ,"u32" ) 301w .add (p + "ple.layer_multipliers" ,PLE_MULT ,"array:u64" ) 302w .add (p + "ple.head_offsets" ,offs ,"array:u64" ) 303w .add (p + "ple.head_vocab_sizes" ,PLE_VOCAB ,"array:u64" ) 304w .add (p + "ple.image_token_id" ,vocab - 3 ,"u32" ) 305w .add ("tokenizer.ggml.model" ,"gpt2" ) 306w .add ("tokenizer.ggml.pre" ,"qwen35" ) 307w .add ("tokenizer.ggml.tokens" , ["a" ,"b" ,"ab" ]+ [f"<t { i } >" for i in range (3 ,vocab )],"array:string" ) 308w .add ("tokenizer.ggml.token_type" , [1 ]* vocab ,"array:i32" ) 309w .add ("tokenizer.ggml.merges" , ["a b" ],"array:string" ) 310w .add ("tokenizer.ggml.eos_token_id" ,vocab - 2 ,"u32" ) 311w .add ("tokenizer.ggml.padding_token_id" ,vocab - 1 ,"u32" ) 312w .add ("tokenizer.ggml.bos_token_id" ,vocab - 1 ,"u32" ) 313w .add ("general.quantization_version" ,2 ,"u32" ) 314if TOKENIZER_FROM is not None : 315for k ,v in TOKENIZER_FROM .metadata .items (): 316if k .startswith ("tokenizer." ): 317if k .endswith ("_token_id" ): 318w .add (k ,int (v ),"u32" ) 319elif k == "tokenizer.ggml.tokens" or k == "tokenizer.ggml.merges" : 320w .add (k ,list (v ),"array:string" ) 321elif k == "tokenizer.ggml.token_type" : 322w .add (k , [int (x )for x in v ],"array:i32" ) 323elif isinstance (v ,bool ): 324w .add (k ,v ,"bool" ) 325elif isinstance (v ,str ): 326w .add (k ,v ,"string" ) 327elif k .endswith (".ple.eos_token_id" )or k .endswith (".ple.image_token_id" ): 328w .add (p + "ple." + k .rsplit (".ple." ,1 )[1 ],int (v ),"u32" ) 329return w 330 331 332def write_gguf (path :pathlib .Path ,s :dict ,vocab :int ,recipe :str ,seed :int ,name :str )-> dict : 333rng = np .random .default_rng (seed ) 334w = metadata (s ,vocab ,name ) 335tl = all_tensors (s ,vocab ) 336plan = [] 337for n ,sh ,role in tl : 338layer = int (n .split ("." )[1 ])if n .startswith ("blk." )else - 1 339ty = recipe_type (recipe ,role ,layer ,s ) 340if not row_ok (ty ,sh [0 ]): 341raise SystemExit (f" { n } { sh } : row length { sh [ 0 ] } is not a multiple of { QTYPES [ ty ][ 1 ] } ( { ty } )" ) 342plan .append ((n ,sh ,role ,ty )) 343# the expert pack (tools/iq_pack.py -> native_experts.txt) wants every layer's gate, up, down tensors back to back and the layers one after 344# the other, so the experts come first in the file (a stable sort keeps the layer order) 345plan .sort (key = lambda x :0 if "_exps.weight" in x [0 ]else 1 ) 346body = bytearray () 347body += struct .pack ("<I" ,GGUF_MAGIC )+ struct .pack ("<I" ,3 )+ struct .pack ("<Q" ,len (plan ))+ struct .pack ("<Q" ,len (w .metadata )) 348for k , (t ,v )in w .metadata .items (): 349body += w ._kv_bytes (k ,t ,v ) 350off = 0 351for n ,sh ,role ,ty in plan : 352body += struct .pack ("<Q" ,len (n ))+ n .encode ()+ struct .pack ("<I" ,len (sh ))+ struct .pack (f"< { len ( sh ) } Q" ,* sh ) 353body += struct .pack ("<I" ,QTYPES [ty ][0 ])+ struct .pack ("<Q" ,off ) 354off += tensor_bytes (ty ,sh ) 355off = (off + DEFAULT_ALIGNMENT - 1 )// DEFAULT_ALIGNMENT * DEFAULT_ALIGNMENT 356body += b"\0" * ((- len (body ))% DEFAULT_ALIGNMENT ) 357types :dict [str ,int ]= {} 358with open (path ,"wb" )as fh : 359fh .write (body ) 360for n ,sh ,role ,ty in plan : 361nb = emit_data (fh ,ty ,role ,sh ,rng ) 362fh .write (b"\0" * ((- nb )% DEFAULT_ALIGNMENT )) 363types [ty ]= types .get (ty ,0 )+ 1 364return {"tensors" :len (plan ),"bytes" :path .stat ().st_size ,"types" :types } 365 366 367# ------------------------------------------------------------------ geometry header 368def header_text (s :dict ,label :str ,source :str )-> str : 369f = FLASH 370lines = [f"// { label } : written by tools/q4geo_synth.py from { source } ." ,"// Take it with -DSTRATA_GEOMETRY_FILE=<this file>." , 371"#pragma once" ,"" ,"namespace strata::core {" ,"" , 372f'inline constexpr const char* kGeometryName = " { label } ";' , 373"inline constexpr ModelGeometry kCompiledGeometry = [] {" ," ModelGeometry g;" ] 374m = [("n_embd" ,"n_embd" ), ("n_layers" ,"n_layers" ), ("qsa_interval" ,"qsa_interval" ), ("n_head" ,"n_head" ), 375 ("n_head_kv" ,"n_head_kv" ), ("head_dim" ,"head_dim" ), ("n_rot" ,"n_rot" ), ("ssm_state" ,"ssm_state_size" ), 376 ("ssm_k_heads" ,"ssm_k_heads" ), ("ssm_v_heads" ,"ssm_v_heads" ), ("ssm_d_conv" ,"ssm_d_conv" ), 377 ("idx_q_heads" ,"idx_q_heads" ), ("idx_key_dim" ,"idx_key_dim" ), ("idx_block" ,"idx_block" ), ("idx_top_k" ,"idx_top_k" ), 378 ("hc" ,"hc" ), ("hc_lr" ,"hc_lr" ), ("n_expert" ,"n_expert" ), ("n_expert_used" ,"n_expert_used" ), ("n_ff" ,"n_ff" )] 379for k ,c in m : 380lines .append (f" g. { c } = { s [ k ] } ;" ) 381lines += [" g.n_ff_shexp = g.n_ff;" , 382" g.ssm_conv_channels = 2 * g.ssm_state_size * g.ssm_k_heads + g.ssm_state_size * g.ssm_v_heads;" , 383" g.ssm_value_dim = g.ssm_state_size * g.ssm_v_heads;" ," return g;" ,"}();" ,"" ,"} // namespace strata::core" ,"" ] 384return "\n" .join (lines ) 385 386 387def shape_from_gguf (path :str )-> dict : 388from gguf_reader import GGUFFile 389g = GGUFFile (pathlib .Path (path )) 390md = g .metadata 391p = "qwen4exp." 392gi = lambda k ,d = None :int (md [p + k ])if (p + k )in md else d 393s = dict (FLASH ) 394s .update (n_embd = gi ("embedding_length" ),n_layers = gi ("block_count" ),n_head = gi ("attention.head_count" ), 395n_head_kv = gi ("attention.head_count_kv" ),head_dim = gi ("attention.key_length" ,256 ),n_rot = gi ("rope.dimension_count" ,64 ), 396ssm_state = gi ("ssm.state_size" ,128 ),ssm_k_heads = gi ("ssm.group_count" ,16 ),ssm_v_heads = gi ("ssm.time_step_rank" ,48 ), 397ssm_d_conv = gi ("ssm.conv_kernel" ,4 ),idx_q_heads = gi ("attention.indexer.head_count" ,4 ), 398idx_key_dim = gi ("attention.indexer.key_length" ,128 ),idx_top_k = gi ("attention.indexer.top_k" ,2048 ), 399hc = gi ("hyper_connection.count" ,4 ),hc_lr = gi ("hyper_connection.low_rank" ,320 ),n_expert = gi ("expert_count" ), 400n_expert_used = gi ("expert_used_count" ),n_ff = gi ("expert_feed_forward_length" ), 401qsa_interval = gi ("full_attention_interval" ,4 )) 402cr = md .get (p + "attention.compress_ratios" ) 403if cr : 404nz = [int (x )for x in cr if int (x )] 405if nz : 406s ["idx_block" ]= nz [0 ] 407s ["conv_ch" ]= 2 * s ["ssm_state" ]* s ["ssm_k_heads" ]+ s ["ssm_state" ]* s ["ssm_v_heads" ] 408s ["value_dim" ]= s ["ssm_state" ]* s ["ssm_v_heads" ] 409return s 410 411 412def main ()-> int : 413ap = argparse .ArgumentParser (description = __doc__ ,formatter_class = argparse .RawDescriptionHelpFormatter ) 414ap .add_argument ("--shape" ,choices = sorted (SHAPES ),default = "flash_next" ) 415ap .add_argument ("--layers" ,type = int ,help = "block_count of the file (a build for it needs a header with the same count)" ) 416ap .add_argument ("--vocab" ,type = int ,default = 8192 ) 417ap .add_argument ("--recipe" ,choices = RECIPES ,default = "ud-q4k" ) 418ap .add_argument ("--seed" ,type = int ,default = 1 ) 419ap .add_argument ("--out" ,help = "the GGUF to write" ) 420ap .add_argument ("--header" ,help = "write the geometry header for the shape (or --from-gguf) here" ) 421ap .add_argument ("--label" ,help = "kGeometryName in the header (default: the shape, plus _<layers>l)" ) 422ap .add_argument ("--from-gguf" ,help = "read the shape from this file's metadata instead of --shape" ) 423ap .add_argument ("--exact-bf16" ,action = "store_true" ,help = "F32 tensors rounded to BF16 values and Q8_0 scale 2^-12: the pack's BF16 conversion is then lossless" ) 424ap .add_argument ("--router-scale" ,type = float ,default = 1.0 ,help = "multiply the router weights (default 1: the files of Q4-GEO2)" ) 425ap .add_argument ("--exact-parts" ,default = "" ,help = "router, f32 (the other F32 tensors) and/or q8 (Q8_0 scale 2^-12): the BF16-exact parts of --exact-bf16" ) 426ap .add_argument ("--tokenizer-from" ,help = "a real qwen4exp GGUF (any shard 1): its tokenizer.* keys and PLE token ids go into the file, and --vocab becomes its vocabulary size" ) 427ap .add_argument ("--list" ,action = "store_true" ) 428ap .add_argument ("--small-ple" ,action = "store_true" , 429help = "PLE head sizes of 16 small primes (a table of ~1.6M rows, ~50 MB) instead of Flash-Next's 320001536 rows (28 GB): the hash moduli are read from the file, so the engine runs it; " 430"for hosts where the sparse 28 GB table cannot be written (Windows)" ) 431ap .add_argument ("--set" ,default = "" ,help = "comma list of field=value overrides of the shape (a bisection of one field), e.g. n_ff=1024,hc_lr=384" ) 432a = ap .parse_args () 433global EXACT_BF16 434EXACT_BF16 = a .exact_bf16 435global EXACT_PARTS 436EXACT_PARTS = {"router" ,"f32" ,"q8" }if a .exact_bf16 else set (x for x in a .exact_parts .split ("," )if x ) 437global ROUTER_SCALE 438ROUTER_SCALE = a .router_scale 439if a .tokenizer_from : 440global TOKENIZER_FROM 441from gguf_reader import GGUFFile 442TOKENIZER_FROM = GGUFFile (pathlib .Path (a .tokenizer_from )) 443a .vocab = len (TOKENIZER_FROM .metadata ["tokenizer.ggml.tokens" ]) 444if a .list : 445for n in sorted (SHAPES ): 446s = shape (n ) 447n , {k :s [k ]for k in ("n_embd" ,"n_layers" ,"n_head" ,"n_head_kv" ,"ssm_v_heads" ,"hc_lr" ,"n_expert" ,"n_expert_used" ,"n_ff" )}) 448return 0 449if a .from_gguf : 450s = shape_from_gguf (a .from_gguf ) 451label = a .label or pathlib .Path (a .from_gguf ).stem .replace ("-" ,"_" ).lower () 452src = a .from_gguf 453else : 454s = shape (a .shape ,a .layers ,** {k :int (v )for k ,v in (kv .split ("=" )for kv in a .set .split ("," )if kv )}) 455label = a .label or (a .shape + (f"_ { a . layers } l" if a .layers else "" )) 456src = f"shape { a . shape } " + (f", { a . layers } layers" if a .layers else "" ) 457if a .small_ple : 458global PLE_ROWS 459primes ,n = [],100003 460while len (primes )< 16 : 461if all (n % d for d in range (2 ,int (n ** 0.5 )+ 1 )): 462primes .append (n ) 463n += 2 464PLE_VOCAB [:]= primes 465PLE_ROWS = sum (primes ) 466if a .header : 467pathlib .Path (a .header ).write_text (header_text (s ,label ,src ),encoding = "utf8" ,newline = "\n" ) 468f"wrote { a . header } ( { label } )" ) 469if a .out : 470if a .from_gguf : 471raise SystemExit ("--from-gguf is for --header" ) 472info = write_gguf (pathlib .Path (a .out ),s ,a .vocab ,a .recipe ,a .seed ,f"synthetic { label } ( { a . recipe } )" ) 473f"wrote { a . out } : { info [ 'tensors' ] } tensors, { info [ 'bytes' ] / 1e9 :.2f } GB, types { info [ 'types' ] } " ) 474return 0 475 476 477if __name__ == "__main__" : 478raise SystemExit (main ())