okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-p8merge (b5f5e38a4): the Qwen4 rehearsal's fixes - F1-F5 (make_model_release schema, mmproj KeyError, drafter: none honoured, neutral expert profile for another shape with the owner's line, budget for feed qwen4exp sizes), STRATA_CMAKE_EXTRA in the Linux packaging scripts, G14 plan line, G12 release plan, G10/G3 docs, and G2: a real-file feed-model install gate in tools/check (tools/feed_model_install_gate.py; fails if any of F2-F5 is reverted); version bump left for the release candidateb82a36810

main
25.9 KiB478 linesraw
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
10    python tools/q4geo_synth.py --shape q4_lite --layers 8 --vocab 8192 --recipe ud-q4k --out /data/synth/lite.gguf
11    python tools/q4geo_synth.py --shape q4_lite --layers 8 --header out.hpp          # the geometry header for that file
12    python tools/q4geo_synth.py --from-gguf some.gguf --header out.hpp              # day one: a geometry header from a real file
13    python 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,
58             ssm_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,
59             n_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:
70    s = dict(FLASH)
71    s.update(SHAPES[name])
72    if layers:
73        s["n_layers"] = layers
74    s.update(over)
75    s["conv_ch"] = 2 * s["ssm_state"] * s["ssm_k_heads"] + s["ssm_state"] * s["ssm_v_heads"]
76    s["value_dim"] = s["ssm_state"] * s["ssm_v_heads"]
77    return s
78
79
80# ------------------------------------------------------------------ layout (core/family_layout.hpp)
81def layer_tensors(s: dict, layer: int):
82    """(name, shape, role) of one layer."""
83    N, NE, FF = s["n_embd"], s["n_expert"], s["n_ff"]
84    H = s["hc"] * N
85    t = [("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")]
90    for blk in ("attn", "ffn"):
91        t += [(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")]
93    if (layer % s["qsa_interval"]) != s["qsa_interval"] - 1:
94        t += [("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")]
99    else:
100        hd, nh, nkv = s["head_dim"], s["n_head"], s["n_head_kv"]
101        t += [("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")]
107    return t
108
109
110PLE_ROWS = 320001536
111PLE_VOCAB = [20000003, 20000023, 20000033, 20000047, 20000059, 20000063, 20000069, 20000077, 20000081, 20000093, 20000107,
112             20000147, 20000153, 20000159, 20000161, 20000171]
113PLE_MULT = [23703573157769, 20109073645365, 8052911324071]
114
115
116def all_tensors(s: dict, vocab: int, ple: bool = True):
117    N = s["n_embd"]
118    H = s["hc"] * N
119    out = [("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")]
122    for l in range(s["n_layers"]):
123        out += [(f"blk.{l}.{n}", sh, r) for n, sh, r in layer_tensors(s, l)]
124    if 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)
127        out += [("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")]
131    return 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:
136    ff256 = s["n_ff"] % 256 == 0
137    if role in ("router", "small", "norm", "inject", "small_mat", "conv", "ssm_a", "bias"):
138        return "F32"
139    if role == "indexer":
140        return "BF16"
141    if role in ("dense", "shexp", "hc"):
142        return "Q8_0"
143    if role == "embd":
144        return "Q8_0"
145    if role == "ple_table":
146        return "IQ4_NL"
147    if role == "output":
148        return "Q6_K" if recipe == "ud-iq4xs" else "Q8_0"
149    first = layer == 0
150    if 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
151        if role in ("gate", "up"):
152            return "Q5_K" if first else "Q4_K"
153        return "Q8_0" if first else ("Q5_K" if ff256 else "Q5_1")
154    if 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)
155        if role in ("gate", "up"):
156            return "Q5_K" if first else "Q4_K"
157        if first:
158            return "Q8_0"
159        return ("Q6_K" if layer % 8 == 1 else "Q5_K") if ff256 else "Q5_1"
160    if recipe == "ud-iq4xs":         # UD-IQ4_XS: IQ3_S gate/up (IQ4_XS in one layer), IQ4_XS down or IQ4_NL by the fallback
161        if role in ("gate", "up"):
162            return "IQ4_XS" if first else "IQ3_S"
163        return "Q8_0" if first else ("IQ4_XS" if ff256 else "IQ4_NL")
164    if recipe == "ud-q5_0down":      # the v31 mix: Q5_0 down layers (what llama.cpp makes of Q4_K down at a non-256 width)
165        if role in ("gate", "up"):
166            return "Q4_K"
167        return "Q5_0"
168    if 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)
169        if role in ("gate", "up"):
170            return "Q5_K" if first else "Q4_K"
171        return "Q8_0" if layer % 2 == 0 else "Q5_1"
172    if 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)
173        if role in ("gate", "up"):
174            return "Q5_K" if layer % 4 == 0 else "Q4_K"
175        return ("Q8_0", "Q5_K", "Q5_1", "Q6_K")[layer % 4]
176    if 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)
177        if role in ("gate", "up"):
178            return "IQ4_XS" if first else "IQ3_S"
179        return "IQ4_NL"
180    raise 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:
187    return 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."""
193    u = a.astype("<f4").view("<u4").astype(np.uint64)
194    u = (u + 0x7FFF + ((u >> 16) & 1)) & 0xFFFF0000
195    return u.astype("<u4").view("<f4")
196
197
198def small_f32(role: str, shape: list[int], rng: np.random.Generator) -> np.ndarray:
199    a = _small_f32(role, shape, rng)
200    if role == "router":
201        a = (a * np.float32(ROUTER_SCALE)).astype("<f4")
202    if role == "router":
203        return bf16_round(a) if ("router" in EXACT_PARTS) else a
204    return 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:
208    n = int(np.prod(shape))
209    if role == "norm":
210        return (1.0 + 0.05 * rng.standard_normal(n)).astype("<f4")
211    if role == "ssm_a":
212        return (-rng.uniform(0.1, 1.5, n)).astype("<f4")
213    if role == "bias":
214        return (0.1 * rng.standard_normal(n)).astype("<f4")
215    if role == "conv":
216        return (0.1 * rng.standard_normal(n)).astype("<f4")
217    if role == "inject":
218        return (0.25 + 0.05 * rng.standard_normal(n)).astype("<f4")
219    return (0.02 * rng.standard_normal(n)).astype("<f4")
220
221
222def tensor_bytes(ty: str, shape: list[int]) -> int:
223    _, blk, tsz, _ = QTYPES[ty]
224    n = int(np.prod(shape))
225    assert n % blk == 0, (ty, shape)
226    return n // blk * tsz
227
228
229def emit_data(fh, ty: str, role: str, shape: list[int], rng: np.random.Generator) -> int:
230    tid, blk, tsz, fields = QTYPES[ty]
231    total = tensor_bytes(ty, shape)
232    if role == "ple_table":              # a hole: zeros, no disk
233        fh.seek(total - 1, 1)
234        fh.write(bytes(1))
235        return total
236    if ty == "F32":
237        fh.write(small_f32(role, shape, rng).tobytes())
238        return total
239    if ty == "BF16":
240        a = (0.02 * rng.standard_normal(int(np.prod(shape)))).astype("<f4")
241        fh.write((a.view("<u4") >> 16).astype("<u2").tobytes())
242        return total
243    nblk = total // tsz
244    step = max(1, (64 << 20) // tsz)
245    done = 0
246    while done < nblk:
247        m = min(step, nblk - done)
248        b = rng.integers(0, 256, size=(m, tsz), dtype=np.uint8)
249        for off, val in fields:
250            if "q8" in EXACT_PARTS and ty == "Q8_0":
251                val = 2.0 ** -12
252            b[:, off:off + 2] = np.frombuffer(np.float16(val).tobytes(), dtype=np.uint8)
253        fh.write(b.tobytes())
254        done += m
255    return total
256
257
258# ------------------------------------------------------------------ metadata
259def metadata(s: dict, vocab: int, name: str) -> GGUFWriter:
260    w = GGUFWriter()
261    p = "qwen4exp."
262    w.add("general.architecture", "qwen4exp")
263    w.add("general.type", "model")
264    w.add("general.name", name)
265    w.add("general.description", "synthetic random weights (tools/q4geo_synth.py), not a model")
266    w.add(p + "block_count", s["n_layers"], "u32")
267    w.add(p + "context_length", 262144, "u32")
268    w.add(p + "embedding_length", s["n_embd"], "u32")
269    w.add(p + "attention.head_count", s["n_head"], "u32")
270    w.add(p + "attention.head_count_kv", s["n_head_kv"], "u32")
271    w.add(p + "rope.dimension_sections", [11, 11, 10, 0], "array:i32")
272    w.add(p + "rope.freq_base", 10000000.0, "f32")
273    w.add(p + "attention.layer_norm_rms_epsilon", 1e-6, "f32")
274    w.add(p + "expert_count", s["n_expert"], "u32")
275    w.add(p + "expert_used_count", s["n_expert_used"], "u32")
276    w.add(p + "attention.key_length", s["head_dim"], "u32")
277    w.add(p + "attention.value_length", s["head_dim"], "u32")
278    w.add(p + "expert_feed_forward_length", s["n_ff"], "u32")
279    w.add(p + "expert_shared_feed_forward_length", s["n_ff"], "u32")
280    w.add(p + "ssm.conv_kernel", s["ssm_d_conv"], "u32")
281    w.add(p + "ssm.state_size", s["ssm_state"], "u32")
282    w.add(p + "ssm.group_count", s["ssm_k_heads"], "u32")
283    w.add(p + "ssm.time_step_rank", s["ssm_v_heads"], "u32")
284    w.add(p + "ssm.inner_size", s["value_dim"], "u32")
285    w.add(p + "full_attention_interval", s["qsa_interval"], "u32")
286    w.add(p + "rope.dimension_count", s["n_rot"], "u32")
287    w.add(p + "hyper_connection.count", s["hc"], "u32")
288    w.add(p + "hyper_connection.low_rank", s["hc_lr"], "u32")
289    w.add(p + "attention.indexer.head_count", s["idx_q_heads"], "u32")
290    w.add(p + "attention.indexer.key_length", s["idx_key_dim"], "u32")
291    w.add(p + "attention.indexer.top_k", s["idx_top_k"], "u32")
292    w.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")
294    offs = [sum(PLE_VOCAB[:i]) for i in range(16)]
295    w.add(p + "ple.layers", [1], "array:i32")
296    w.add(p + "ple.ngram_size", 3, "u32")
297    w.add(p + "ple.heads_per_ngram", 8, "u32")
298    w.add(p + "ple.conv_kernel", 4, "u32")
299    w.add(p + "ple.eos_token_id", vocab - 2, "u32")
300    w.add(p + "embedding_length_per_layer_input", s["n_embd"] // 16, "u32")
301    w.add(p + "ple.layer_multipliers", PLE_MULT, "array:u64")
302    w.add(p + "ple.head_offsets", offs, "array:u64")
303    w.add(p + "ple.head_vocab_sizes", PLE_VOCAB, "array:u64")
304    w.add(p + "ple.image_token_id", vocab - 3, "u32")
305    w.add("tokenizer.ggml.model", "gpt2")
306    w.add("tokenizer.ggml.pre", "qwen35")
307    w.add("tokenizer.ggml.tokens", ["a", "b", "ab"] + [f"<t{i}>" for i in range(3, vocab)], "array:string")
308    w.add("tokenizer.ggml.token_type", [1] * vocab, "array:i32")
309    w.add("tokenizer.ggml.merges", ["a b"], "array:string")
310    w.add("tokenizer.ggml.eos_token_id", vocab - 2, "u32")
311    w.add("tokenizer.ggml.padding_token_id", vocab - 1, "u32")
312    w.add("tokenizer.ggml.bos_token_id", vocab - 1, "u32")
313    w.add("general.quantization_version", 2, "u32")
314    if TOKENIZER_FROM is not None:
315        for k, v in TOKENIZER_FROM.metadata.items():
316            if k.startswith("tokenizer."):
317                if k.endswith("_token_id"):
318                    w.add(k, int(v), "u32")
319                elif k == "tokenizer.ggml.tokens" or k == "tokenizer.ggml.merges":
320                    w.add(k, list(v), "array:string")
321                elif k == "tokenizer.ggml.token_type":
322                    w.add(k, [int(x) for x in v], "array:i32")
323                elif isinstance(v, bool):
324                    w.add(k, v, "bool")
325                elif isinstance(v, str):
326                    w.add(k, v, "string")
327            elif k.endswith(".ple.eos_token_id") or k.endswith(".ple.image_token_id"):
328                w.add(p + "ple." + k.rsplit(".ple.", 1)[1], int(v), "u32")
329    return w
330
331
332def write_gguf(path: pathlib.Path, s: dict, vocab: int, recipe: str, seed: int, name: str) -> dict:
333    rng = np.random.default_rng(seed)
334    w = metadata(s, vocab, name)
335    tl = all_tensors(s, vocab)
336    plan = []
337    for n, sh, role in tl:
338        layer = int(n.split(".")[1]) if n.startswith("blk.") else -1
339        ty = recipe_type(recipe, role, layer, s)
340        if not row_ok(ty, sh[0]):
341            raise SystemExit(f"{n} {sh}: row length {sh[0]} is not a multiple of {QTYPES[ty][1]} ({ty})")
342        plan.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)
345    plan.sort(key=lambda x: 0 if "_exps.weight" in x[0] else 1)
346    body = bytearray()
347    body += struct.pack("<I", GGUF_MAGIC) + struct.pack("<I", 3) + struct.pack("<Q", len(plan)) + struct.pack("<Q", len(w.metadata))
348    for k, (t, v) in w.metadata.items():
349        body += w._kv_bytes(k, t, v)
350    off = 0
351    for n, sh, role, ty in plan:
352        body += struct.pack("<Q", len(n)) + n.encode() + struct.pack("<I", len(sh)) + struct.pack(f"<{len(sh)}Q", *sh)
353        body += struct.pack("<I", QTYPES[ty][0]) + struct.pack("<Q", off)
354        off += tensor_bytes(ty, sh)
355        off = (off + DEFAULT_ALIGNMENT - 1) // DEFAULT_ALIGNMENT * DEFAULT_ALIGNMENT
356    body += b"\0" * ((-len(body)) % DEFAULT_ALIGNMENT)
357    types: dict[str, int] = {}
358    with open(path, "wb") as fh:
359        fh.write(body)
360        for n, sh, role, ty in plan:
361            nb = emit_data(fh, ty, role, sh, rng)
362            fh.write(b"\0" * ((-nb) % DEFAULT_ALIGNMENT))
363            types[ty] = types.get(ty, 0) + 1
364    return {"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:
369    f = FLASH
370    lines = [f"// {label}: written by tools/q4geo_synth.py from {source}.", "// Take it with -DSTRATA_GEOMETRY_FILE=<this file>.",
371             "#pragma once", "", "namespace strata::core {", "",
372             f'inline constexpr const char* kGeometryName = "{label}";',
373             "inline constexpr ModelGeometry kCompiledGeometry = [] {", "    ModelGeometry g;"]
374    m = [("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")]
379    for k, c in m:
380        lines.append(f"    g.{c} = {s[k]};")
381    lines += ["    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", ""]
384    return "\n".join(lines)
385
386
387def shape_from_gguf(path: str) -> dict:
388    from gguf_reader import GGUFFile
389    g = GGUFFile(pathlib.Path(path))
390    md = g.metadata
391    p = "qwen4exp."
392    gi = lambda k, d=None: int(md[p + k]) if (p + k) in md else d
393    s = dict(FLASH)
394    s.update(n_embd=gi("embedding_length"), n_layers=gi("block_count"), n_head=gi("attention.head_count"),
395             n_head_kv=gi("attention.head_count_kv"), head_dim=gi("attention.key_length", 256), n_rot=gi("rope.dimension_count", 64),
396             ssm_state=gi("ssm.state_size", 128), ssm_k_heads=gi("ssm.group_count", 16), ssm_v_heads=gi("ssm.time_step_rank", 48),
397             ssm_d_conv=gi("ssm.conv_kernel", 4), idx_q_heads=gi("attention.indexer.head_count", 4),
398             idx_key_dim=gi("attention.indexer.key_length", 128), idx_top_k=gi("attention.indexer.top_k", 2048),
399             hc=gi("hyper_connection.count", 4), hc_lr=gi("hyper_connection.low_rank", 320), n_expert=gi("expert_count"),
400             n_expert_used=gi("expert_used_count"), n_ff=gi("expert_feed_forward_length"),
401             qsa_interval=gi("full_attention_interval", 4))
402    cr = md.get(p + "attention.compress_ratios")
403    if cr:
404        nz = [int(x) for x in cr if int(x)]
405        if nz:
406            s["idx_block"] = nz[0]
407    s["conv_ch"] = 2 * s["ssm_state"] * s["ssm_k_heads"] + s["ssm_state"] * s["ssm_v_heads"]
408    s["value_dim"] = s["ssm_state"] * s["ssm_v_heads"]
409    return s
410
411
412def main() -> int:
413    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
414    ap.add_argument("--shape", choices=sorted(SHAPES), default="flash_next")
415    ap.add_argument("--layers", type=int, help="block_count of the file (a build for it needs a header with the same count)")
416    ap.add_argument("--vocab", type=int, default=8192)
417    ap.add_argument("--recipe", choices=RECIPES, default="ud-q4k")
418    ap.add_argument("--seed", type=int, default=1)
419    ap.add_argument("--out", help="the GGUF to write")
420    ap.add_argument("--header", help="write the geometry header for the shape (or --from-gguf) here")
421    ap.add_argument("--label", help="kGeometryName in the header (default: the shape, plus _<layers>l)")
422    ap.add_argument("--from-gguf", help="read the shape from this file's metadata instead of --shape")
423    ap.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")
424    ap.add_argument("--router-scale", type=float, default=1.0, help="multiply the router weights (default 1: the files of Q4-GEO2)")
425    ap.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")
426    ap.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")
427    ap.add_argument("--list", action="store_true")
428    ap.add_argument("--small-ple", action="store_true",
429                    help="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)")
431    ap.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")
432    a = ap.parse_args()
433    global EXACT_BF16
434    EXACT_BF16 = a.exact_bf16
435    global EXACT_PARTS
436    EXACT_PARTS = {"router", "f32", "q8"} if a.exact_bf16 else set(x for x in a.exact_parts.split(",") if x)
437    global ROUTER_SCALE
438    ROUTER_SCALE = a.router_scale
439    if a.tokenizer_from:
440        global TOKENIZER_FROM
441        from gguf_reader import GGUFFile
442        TOKENIZER_FROM = GGUFFile(pathlib.Path(a.tokenizer_from))
443        a.vocab = len(TOKENIZER_FROM.metadata["tokenizer.ggml.tokens"])
444    if a.list:
445        for n in sorted(SHAPES):
446            s = shape(n)
447            print(n, {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")})
448        return 0
449    if a.from_gguf:
450        s = shape_from_gguf(a.from_gguf)
451        label = a.label or pathlib.Path(a.from_gguf).stem.replace("-", "_").lower()
452        src = a.from_gguf
453    else:
454        s = shape(a.shape, a.layers, **{k: int(v) for k, v in (kv.split("=") for kv in a.set.split(",") if kv)})
455        label = a.label or (a.shape + (f"_{a.layers}l" if a.layers else ""))
456        src = f"shape {a.shape}" + (f", {a.layers} layers" if a.layers else "")
457    if a.small_ple:
458        global PLE_ROWS
459        primes, n = [], 100003
460        while len(primes) < 16:
461            if all(n % d for d in range(2, int(n ** 0.5) + 1)):
462                primes.append(n)
463            n += 2
464        PLE_VOCAB[:] = primes
465        PLE_ROWS = sum(primes)
466    if a.header:
467        pathlib.Path(a.header).write_text(header_text(s, label, src), encoding="utf8", newline="\n")
468        print(f"wrote {a.header} ({label})")
469    if a.out:
470        if a.from_gguf:
471            raise SystemExit("--from-gguf is for --header")
472        info = write_gguf(pathlib.Path(a.out), s, a.vocab, a.recipe, a.seed, f"synthetic {label} ({a.recipe})")
473        print(f"wrote {a.out}: {info['tensors']} tensors, {info['bytes'] / 1e9:.2f} GB, types {info['types']}")
474    return 0
475
476
477if __name__ == "__main__":
478    raise SystemExit(main())