okami.mom/strata

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

Niko1221Merge f-own-2b (cc8c29f31) into f-own-int: our own GGUF reader/writer and quantizers (gguf-py out of the pack tools)0f1e5e4cb

main
42.9 KiB783 linesraw
1"""tools/iq_pack.py - plan v0.3 P6: a native pack for any of the model files (Q2_0, IQ2_XS, IQ3_XXS).
2
3    python tools/iq_pack.py --gguf <model>-00001-of-00002.gguf --out pack/iq3_xxs            (standalone)
4    python tools/iq_pack.py --gguf <model>-00001-of-00002.gguf --base pack/full --out ...    (share dense.bin)
5
6The i-quant experts cannot be re-expressed in the Q2_0 pack form, so this pack keeps every quantized tensor in
7its GGUF form:
8
9  experts.bin          optional (--experts-bin): per layer, 512 blobs of [gate rows | up rows | down rows], the
10                       raw GGUF slices.  Blob size is per layer (the files mix IQ1_M ... IQ3_S gate/up and Q2_0 /
11                       IQ4_NL down).  experts.bin.src.json says which source it was cut from (the shards' names and
12                       sizes, the hash of native_experts.txt); an experts.bin is reused only when that matches.
13  native_experts.txt   one line per layer: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard];
14                       written last, so a pack without it is not finished
15  index.txt            the table the engine loads.  Quantized dense tensors, token_embd and output are served
16                       natively from the GGUF by the engine (--native): their rows carry shape only.
17  dense.bin            standalone: the BF16/F16/F32 tensors in the form the engine reads them (index kinds 4/5/2;
18                       3 = F32 narrowed to F16 by the loader) - as the GGUF stores them, or converted (FORM below).
19  conversions.json     every tensor that was converted: shard, source/destination type, method, whether it was
20                       exact, the largest absolute error, the source bytes' sha256 (schema 1).
21                       With --base: the base (Q2_0) pack's dense.bin, hard-linked - the float tensors are
22                       byte-identical in all three model files (checked) - plus extra.bin for tensors that are
23                       float here but quantized in the base pack (blk.1.ple_key).
24  tokenizer/           exported from the GGUF (tools/strata_tokenizer.py), with the model's chat template.
25
26Split files: every shard of the model is read (<name>-0000N-of-0000M.gguf beside --gguf; a missing shard is an
27error), so the layers may be split anyhow (Swift 1.5's GGUFs put layers 13-47 in shard 2 and the PLE table in
28shard 1).  A layer whose experts are not in shard 1 names its shard in native_experts.txt (v3).  A shard boundary
29may even fall inside a layer (Unsloth's UD-Q4_K_XL: layer 11's down in shard 2, its gate and up in shard 3): that
30layer's shard column is per role, `gate,up,down` (an empty field = the --gguf shard), and only then is the file
31v4, so an older engine refuses it instead of misreading it.  Every other pack stays v3, byte for byte.  Router
32tensors stored as F32 whose values are exactly BF16 (Swift 1.5) are written as BF16, the form the engine's router
33takes (so are the other F32 tensors the engine reads as BF16, when exact); anything else is refused.
34
35For ordinary quants, --compat-bf16 dequantizes the small projections that the engine reads as BF16, using
36round-to-nearest-even. This introduces BF16 rounding; it does not reconstruct the original full-precision
37weights. Experts, native attention projections, token embeddings, a Q2_0/Q8_0 PLE key and the disk-backed PLE
38table stay unchanged.
39"""
40from __future__ import annotations
41
42import argparse
43import hashlib
44import json
45import os
46import pathlib
47import re
48import shutil
49import subprocess
50import sys
51
52import numpy as np
53
54HERE = pathlib.Path(__file__).resolve().parent
55sys.path.insert(0, str(HERE))
56import gguf_reader as G  # noqa: E402
57
58FLOAT = {"BF16", "F32", "F16"}
59ROUTERS = ("ffn_gate_inp.weight", "ffn_gate_inp_shexp.weight")
60NOT_IN_PACK = {"per_layer_token_embd.weight"}      # the 28.8 GB PLE table: read from its GGUF by the engine
61
62# The float form the engine reads each pack tensor in (name without `blk.N.`; from eddoursul/Strata's FORM table).
63# The residual, router, GDN, QSA and PLE kernels read these small projections as BF16, the norms as F32 and the PLE
64# conv as F16.  GSQ-RCO files already store them that way; other files do not (Unsloth's UD-Q4_K_XL: the routers,
65# SSM gates and injections F32, the hyper-connection projections and the PLE value Q8_0, the PLE conv F32), so a
66# tensor stored otherwise is converted, and every conversion is recorded in conversions.json:
67#   F32 -> BF16 whose values are exactly BF16 (low 16 bits zero)    exact, by default
68#   F32 with other values, F16 or a quantized type -> BF16          rounds (nearest-even): only with --compat-bf16
69#   F32 -> F16 (ple_conv1d)                                         index kind 3, narrowed by the loader (#255),
70#                                                                   by default - the kernel reads nothing else
71#   F16 / BF16 -> F32                                               exact widening, by default
72# Tensors not named here are written as stored (floats) or served from the GGUF (quantized), as before.
73FORM = {
74    "ffn_gate_inp.weight": "BF16", "ffn_gate_inp_shexp.weight": "BF16",
75    "hc_attn_down.weight": "BF16", "hc_attn_up.weight": "BF16", "hc_attn_inject.weight": "BF16",
76    "hc_ffn_down.weight": "BF16", "hc_ffn_up.weight": "BF16", "hc_ffn_inject.weight": "BF16",
77    "output_hc_down.weight": "BF16", "output_hc_up.weight": "BF16",
78    "indexer.k_proj.weight": "BF16", "indexer.q_proj.weight": "BF16",
79    "ssm_alpha.weight": "BF16", "ssm_beta.weight": "BF16",
80    "ple_key.weight": "BF16", "ple_value.weight": "BF16", "ple_conv1d.weight": "F16",
81    "attn_q_norm.weight": "F32", "attn_k_norm.weight": "F32", "hc_attn_norm.weight": "F32",
82    "hc_ffn_norm.weight": "F32", "output_hc_norm.weight": "F32", "indexer.q_norm.weight": "F32",
83    "indexer.k_norm.weight": "F32", "ple_norm_conv.weight": "F32", "ple_norm_key.weight": "F32",
84    "ple_norm_query.weight": "F32", "ssm_a": "F32", "ssm_conv1d.weight": "F32", "ssm_dt.bias": "F32",
85    "ssm_norm.weight": "F32",
86}
87# PLE key encodings left in the GGUF for the engine's native PLE key: the formats NativeDense serves (Q2_0; Q8_0 in
88# UD-Q4_K_XL; IQ3_XXS and IQ4_XS, #381).  Other quantized keys take the BF16 path (--compat-bf16), as before.
89NATIVE_PLE_KEY = {"Q2_0", "Q8_0", "IQ3_XXS", "IQ4_XS"}
90KIND = {"BF16": "4", "F16": "5", "F32": "2"}
91
92
93def form_of(name: str):
94    return FORM.get(re.sub(r"^blk\.\d+\.", "", name))
95
96
97def needs_bf16(name: str, type_name: str) -> bool:
98    """Whether the engine reads `name` as BF16 from the pack (not natively from the GGUF)."""
99    if name == "blk.1.ple_key.weight" and type_name in NATIVE_PLE_KEY:
100        return False
101    return form_of(name) == "BF16"
102
103
104def dequantize(raw: np.ndarray, type_name: str) -> np.ndarray:
105    """The tensor's values as float32 (float types exactly, quantized ones through tools/strata_quants.py)."""
106    if type_name == "F32":
107        return raw.view(np.float32)
108    if type_name == "F16":
109        return raw.view(np.float16).astype(np.float32)
110    if type_name == "BF16":
111        return (raw.view(np.uint16).astype(np.uint32) << 16).view(np.float32)
112    from _paths import gguf_lib
113    gguf = gguf_lib()
114    return gguf.quants.dequantize(raw, gguf.GGMLQuantizationType[type_name]).astype(np.float32).reshape(-1)
115
116
117def bf16_bytes(raw: np.ndarray, type_name: str) -> bytes:
118    from _paths import gguf_lib
119    gguf = gguf_lib()
120    Q, quants = gguf.GGMLQuantizationType, gguf.quants
121    values = quants.dequantize(raw, Q[type_name])
122    if not np.isfinite(values).all():
123        raise ValueError("cannot convert non-finite weights to BF16")
124    # ggml's round-to-nearest-even conversion, including correct halfway rounding.
125    return quants.quantize(values, Q.BF16).tobytes()
126
127
128def f16_values(values: np.ndarray, name: str) -> np.ndarray:
129    """values -> F16, nearest-even (numpy's conversion, which is the engine loader's f16_from_f32); refuses a value
130    that is not finite or overflows F16."""
131    if not np.isfinite(values).all():
132        raise ValueError(f"{name}: cannot convert non-finite weights to F16")
133    with np.errstate(over="ignore"):
134        h = values.astype(np.float16)
135    if not np.isfinite(h).all():
136        raise ValueError(f"{name}: a value is beyond F16's range, which the engine reads it as")
137    return h
138
139
140class Model:
141    """All shards of one model: name -> (GGUFFile, TensorInfo, memmap, shard path)."""
142
143    def __init__(self, first: pathlib.Path):
144        import re
145        m = re.search(r"-(\d{5})-of-(\d{5})\.gguf$", first.name)
146        paths = [first]
147        if m:
148            total = int(m.group(2))
149            paths = [first.with_name(first.name[:m.start()] + "-%05d-of-%05d.gguf" % (i, total))
150                     for i in range(1, total + 1)]
151        missing = [str(p) for p in paths if not p.is_file()]
152        if missing:
153            raise FileNotFoundError("missing model shards (wait for the download): " + ", ".join(missing))
154        self.paths = paths
155        self.files = [G.GGUFFile(p) for p in paths]
156        self.sizes = [p.stat().st_size for p in paths]
157        check_split(self.files)
158        self.where = {}
159        for p, g in zip(paths, self.files):
160            mm = np.memmap(p, dtype=np.uint8, mode="r")
161            for t in g.tensors:
162                size = t.expected_bytes()
163                if size is None or g.data_start + t.offset + size > mm.size:
164                    raise ValueError(f"{p.name}: unsupported or truncated tensor {t.name}")
165                if t.name in self.where:
166                    raise ValueError(f"{p.name}: duplicate tensor {t.name}")
167                self.where[t.name] = (g, t, mm, p)
168
169    def bytes(self, name) -> np.ndarray:
170        g, t, mm, _ = self.where[name]
171        return tensor_bytes(mm, g, t)
172
173
174def check_split(files) -> None:
175    """The split keys, as the engine checks them (strata::GgufModel): shard 1 carries the metadata, and every shard
176    declares split.count / split.no (and split.tensors.count) consistently - a shard of another model, or a shard
177    renamed into the family, is refused rather than mixed in."""
178    n = len(files)
179    meta0 = files[0].metadata
180    if n == 1:
181        if int(meta0.get("split.count", 1)) > 1:
182            raise ValueError(f"{files[0].path.name} is shard 1 of {meta0['split.count']}, but its name has no "
183                             "-00001-of-0000N.gguf to find the others by")
184        return
185    if "general.architecture" not in meta0:
186        raise ValueError(f"{files[0].path.name} has no general.architecture; the first shard of a split model "
187                         "carries the metadata")
188    total = meta0.get("split.tensors.count")
189    for i, g in enumerate(files):
190        md = g.metadata
191        if md.get("split.count") != n or md.get("split.no") != i or \
192                (total is not None and md.get("split.tensors.count") != total):
193            raise ValueError(f"{g.path.name} does not declare itself shard {i + 1} of {n} of this model "
194                             "(split.count / split.no / split.tensors.count)")
195    if total is not None and sum(len(g.tensors) for g in files) != total:
196        raise ValueError(f"the {n} shards hold {sum(len(g.tensors) for g in files)} tensors, but "
197                         f"split.tensors.count is {total}")
198
199
200ROLES = ("gate", "up", "down")
201N_EXPERT = 512
202ALIGN = 64
203NVFP4_TAIL = 16          # {s_gate, s_up, s_down, 0} after an NVFP4 expert blob
204
205
206def read_index(path: pathlib.Path):
207    rows, header = {}, []
208    for line in path.read_text(encoding="utf-8").splitlines():
209        if line.startswith("#"):
210            header.append(line)
211            continue
212        f = line.split()
213        rows[f[0]] = f
214    return header, rows
215
216
217def tensor_bytes(mm, g, t) -> np.ndarray:
218    n = t.expected_bytes()
219    return mm[g.data_start + t.offset: g.data_start + t.offset + n]
220
221
222def is_expert(name: str) -> bool:
223    return name.startswith("blk.") and name.endswith(("_exps.weight",))
224
225
226def convert(name: str, type_name: str, raw: np.ndarray, compat_bf16: bool):
227    """The pack form of one tensor the engine reads from dense.bin: (kind, stored bytes, destination bytes,
228    record or None), or an error string.  `record` describes a conversion for conversions.json."""
229    form = form_of(name)
230    if form is None or form == type_name:
231        return KIND[type_name], raw.tobytes(), raw.nbytes, None
232    values = dequantize(raw, type_name)
233    rec = {"src_type": type_name, "dst_type": form}
234    if form == "BF16":
235        u = values.view(np.uint32) if type_name == "F32" else None
236        if u is not None and not np.count_nonzero(u & 0xFFFF):
237            if not np.isfinite(values).all():
238                return f"{name} is F32 with non-finite values; refused rather than converted"
239            data = (u >> 16).astype("<u2").tobytes()       # the exact BF16 values
240            rec.update(method="f32->bf16: the values are BF16's (low 16 bits zero)", exact=True, max_abs_err=0.0)
241            return "4", data, len(data), rec
242        if not compat_bf16:
243            what = "F32 with values that are not BF16" if type_name == "F32" else type_name
244            return f"{name} is {what}, but the engine requires BF16; use --compat-bf16 (rounds to nearest-even)"
245        data = bf16_bytes(raw, type_name)
246        got = (np.frombuffer(data, dtype="<u2").astype(np.uint32) << 16).view(np.float32)
247        rec.update(method="dequantize->bf16 round-to-nearest-even (--compat-bf16)" if type_name not in FLOAT else
248                   "%s->bf16 round-to-nearest-even (--compat-bf16)" % type_name.lower())
249        rec.update(exact=bool(np.array_equal(got, values)),
250                   max_abs_err=float(np.max(np.abs(got.astype(np.float64) - values))) if values.size else 0.0)
251        return "4", data, len(data), rec
252    if form == "F16":
253        if type_name != "F32" and not compat_bf16:
254            return f"{name} is {type_name}, but the engine reads F16; use --compat-bf16 (rounds to nearest-even)"
255        h = f16_values(values, name)
256        err = float(np.max(np.abs(h.astype(np.float64) - values))) if values.size else 0.0
257        rec.update(exact=bool(np.array_equal(h.astype(np.float32), values)), max_abs_err=err)
258        if type_name == "F32":
259            # The F32 bytes go into dense.bin as index kind 3 and the loader narrows them to F16 (nearest-even), the
260            # form the PLE conv kernel reads (#255, gopinath87607): 4 B/elem in, 2 B/elem out.
261            rec.update(method="f32->f16 by the loader (index kind 3, round-to-nearest-even)")
262            return "3", raw.tobytes(), raw.nbytes // 2, rec
263        rec.update(method="%s->f16 round-to-nearest-even (--compat-bf16)" % type_name.lower())
264        data = h.astype("<f2").tobytes()
265        return "5", data, len(data), rec
266    # form == "F32"
267    if type_name not in ("F16", "BF16") and not compat_bf16:
268        return f"{name} is {type_name}, but the engine reads F32; use --compat-bf16"
269    data = values.astype("<f4").tobytes()
270    rec.update(method="%s->f32 widening" % type_name.lower(), exact=True, max_abs_err=0.0)
271    return "2", data, len(data), rec
272
273
274def index_standalone(src, out, model: Model, compat_bf16: bool = False) -> int:
275    """Every non-expert tensor of the model: the floats the engine reads from the pack into dense.bin in the form it
276    reads them (FORM; converted when stored otherwise, see above), quantized ones served natively from the GGUF."""
277    todo, problems = [], []
278    for name, (g, t, mm, p) in model.where.items():
279        if is_expert(t.name) or t.name in NOT_IN_PACK:
280            continue
281        if len(t.shape) > 2:
282            print("tensor %s has %d dimensions; the index holds two" % (t.name, len(t.shape)))
283            return 1
284        # quantized: served from the GGUF unless the engine reads it from the pack (FORM), which takes
285        # --compat-bf16 to dequantize - except the native PLE key encodings
286        form = form_of(name)
287        native = t.type_name not in FLOAT and (form is None or (
288            name == "blk.1.ple_key.weight" and t.type_name in NATIVE_PLE_KEY))
289        if t.type_name not in FLOAT and not native and not compat_bf16:
290            problems.append(f"{name} is {t.type_name}, but the engine requires {form}; use --compat-bf16")
291        todo.append((name, g, t, mm, p, native))
292    # refused before anything is written: the previous pack stays as it was
293    if problems:
294        for m in problems[:8]:
295            print(m)
296        if len(problems) > 8:
297            print("... and %d more" % (len(problems) - 8))
298        return 1
299    rows, at = [], 0
300    served = 0
301    converted, records = [], []
302    with open(out / "dense.bin.tmp", "wb") as fo:
303        for name, g, t, mm, p, native in todo:
304            ne0 = int(t.shape[0])
305            ne1 = int(t.shape[1]) if len(t.shape) > 1 else 0
306            if native:
307                served += 1
308                rows.append([t.name, "0", "0", "0", "0", "0", "0", str(ne0), str(ne1), "8", "0", "32"] + ["0"] * 7)
309                continue
310            raw = tensor_bytes(mm, g, t)
311            try:
312                got = convert(name, t.type_name, raw, compat_bf16)
313            except ValueError as e:
314                got = str(e)
315            if isinstance(got, str):
316                print(got)
317                fo.close()
318                (out / "dense.bin.tmp").unlink(missing_ok=True)
319                return 1
320            kind, data, dst_bytes, rec = got
321            if rec is not None:
322                rec = {"name": name, "shard": p.name, **rec,
323                       "source_sha256": hashlib.sha256(raw.tobytes()).hexdigest()}
324                records.append(rec)
325                if "--compat-bf16" in rec["method"]:          # the rounding the flag allowed
326                    converted.append({"name": name, "source_type": t.type_name, "bytes": len(data)})
327            rows.append([t.name, "0", kind, str(at), str(len(data)), "0", str(dst_bytes), str(ne0), str(ne1),
328                         "0", "0", "1"] + ["0"] * 7)
329            fo.write(data)
330            pad = (-len(data)) % ALIGN
331            fo.write(b"\0" * pad)
332            at += len(data) + pad
333    write_index(out, rows, src, served, 0, publish=False)
334    conv = out / "conversions.json.tmp"
335    conv.write_text(json.dumps({
336        "schema": 1, "tool": "tools/iq_pack.py", "compat_bf16": compat_bf16,
337        "source_shards": [{"name": q.name, "size": s} for q, s in zip(model.paths, model.sizes)],
338        "tensors": records,
339    }, indent=1) + "\n", encoding="utf-8")
340    # published together, and the completion marker (native_experts.txt, written last by main) goes first: a stop
341    # from here on leaves a pack that setup and the engine see as unfinished, never a new dense.bin under an old
342    # index or the reverse
343    (out / "native_experts.txt").unlink(missing_ok=True)
344    (out / "dense.bin.tmp").replace(out / "dense.bin")
345    (out / "index.txt.tmp").replace(out / "index.txt")
346    conv.replace(out / "conversions.json")
347    if records:
348        exact = sum(1 for r in records if r["exact"])
349        print("conversions.json: %d tensors converted to the engine's form (%d exact, %d rounded; max |err| %.3g)"
350              % (len(records), exact, len(records) - exact, max(r["max_abs_err"] for r in records)))
351        for r in records:
352            if r["dst_type"] == "F16":
353                print("narrowed to F16 by the loader: %s (%s, index kind 3)" % (r["name"], r["method"]))
354    if compat_bf16:
355        (out / "compat-bf16.json").write_text(json.dumps({
356            "source": str(src), "rounding": "nearest-even", "tensors": converted,
357        }, indent=2) + "\n", encoding="utf-8")
358        print("compat-bf16: %d tensors, %.2f GiB; expert and PLE table bytes unchanged"
359              % (len(converted), sum(t["bytes"] for t in converted) / 2**30))
360    return 0
361
362
363def write_index(out, rows, src, served, n_extra, publish=True):
364    at = 0
365    for r in rows:
366        r[5] = str(at)
367        at += (int(r[6]) + ALIGN - 1) // ALIGN * ALIGN
368    with open(out / "index.txt.tmp", "w", encoding="utf-8", newline="\n") as fo:
369        fo.write("# strata pack index v3 -- generated by tools/iq_pack.py (native experts) from %s\n" % src.name)
370        fo.write("# align %d pool %d tensors %d\n" % (ALIGN, at, len(rows)))
371        for r in rows:
372            fo.write(" ".join(r) + "\n")
373    if publish:
374        (out / "index.txt.tmp").replace(out / "index.txt")
375    print("index.txt: %d tensors, %d served natively, %d in extra.bin, arena %.2f GiB"
376          % (len(rows), served, n_extra, at / 2**30))
377
378
379def index_from_base(a, src, base, out, g, T, mm) -> int:
380    base_src = pathlib.Path(json.loads((base / "manifest.json").read_text(encoding="utf-8"))["source"]["shard1"])
381    if not base_src.exists():
382        print("cannot find the base pack's shard 1 from its manifest.json")
383        return 1
384    bg = G.GGUFFile(base_src)
385    BT = {t.name: t for t in bg.tensors}
386    bmm = np.memmap(base_src, dtype=np.uint8, mode="r")
387    header, rows = read_index(base / "index.txt")
388    new_rows, extra = [], []
389    served = 0
390    for name, f in rows.items():
391        t, bt = T.get(name), BT.get(name)
392        if t is None or bt is None:
393            print("tensor %s missing from one of the models" % name)
394            return 1
395        if t.type_name in FLOAT and bt.type_name in FLOAT:
396            if t.type_name != bt.type_name or t.shape != bt.shape or \
397                    not np.array_equal(tensor_bytes(mm, g, t), tensor_bytes(bmm, bg, bt)):
398                print("float tensor %s differs from the base model; this pack cannot reuse its dense.bin" % name)
399                return 1
400            new_rows.append(list(f))
401        elif t.type_name in FLOAT:
402            if t.type_name != "BF16":
403                print("unexpected float type %s for %s" % (t.type_name, name))
404                return 1
405            nbytes = t.expected_bytes()
406            off = sum(len(b) + (-len(b)) % ALIGN for b in extra)
407            extra.append(tensor_bytes(mm, g, t).tobytes())
408            # file 3 = extra.bin, raw BF16 (index kind 4)
409            new_rows.append([name, "3", "4", str(off), str(nbytes), "0", str(nbytes), f[7], f[8]] + ["0"] * 10)
410        else:
411            served += 1
412            new_rows.append([name, f[1], "0", "0", "0", "0", "0", f[7], f[8], "8", "0", "32"] + ["0"] * 7)
413    write_index(out, new_rows, src, served, len(extra))
414    with open(out / "extra.bin", "wb") as fo:
415        for b in extra:
416            fo.write(b)
417            fo.write(b"\0" * ((-len(b)) % ALIGN))
418    dense = out / "dense.bin"
419    if not dense.exists():
420        try:
421            os.link(base / "dense.bin", dense)
422        except OSError:
423            shutil.copyfile(base / "dense.bin", dense)
424    if (base / "tokenizer").exists() and not (out / "tokenizer").exists():
425        shutil.copytree(base / "tokenizer", out / "tokenizer")
426    return 0
427
428
429def expert_layout(model: Model, src: pathlib.Path):
430    """The pack's expert table: (layout rows, native_experts.txt text, n_expert, total bytes), or an error string.
431    Each role is resolved by name in whichever shard holds it, and its offset is absolute in THAT shard: two
432    shards do not start their data section at the same byte, so one role's data_start must not be used for
433    another's (per-role data_start as in #255, gopinath87607)."""
434    T = {n: w[1] for n, w in model.where.items()}
435    exps = [n for n in T if n.startswith("blk.") and n.endswith("_exps.weight")]
436    if not exps:
437        return "the model has no expert tensors (blk.N.ffn_{gate,up,down}_exps.weight)"
438    n_layers = 1 + max(int(n.split(".")[1]) for n in exps)
439    n_expert = int(T["blk.0.ffn_gate_inp.weight"].shape[1])   # router rows = experts kept (pruned models ship < 512)
440    if any(int(T["blk.%d.ffn_gate_inp.weight" % l].shape[1]) != n_expert for l in range(n_layers)):
441        return "the routers disagree on the expert count; a per-layer pruned model cannot be packed"
442    layout, lines, offset, n_split = [], [], 0, 0
443    for l in range(n_layers):
444        names = ["blk.%d.ffn_%s_exps.weight" % (l, r) for r in ROLES]
445        if any(n not in T for n in names):
446            return "layer %d: missing %s" % (l, ", ".join(n for n in names if n not in T))
447        ts = [T[n] for n in names]
448        if any(t.expected_bytes() is None or len(t.shape) != 3 or int(t.shape[2]) != n_expert for t in ts):
449            return "layer %d: an expert tensor is not [*, *, %d] of whole blocks" % (l, n_expert)
450        per = [t.expected_bytes() // n_expert for t in ts]
451        if per[0] != per[1] or ts[0].type_name != ts[1].type_name:
452            return "layer %d: gate and up differ in type" % l
453        blob = per[0] + per[1] + per[2]
454        nvfp4 = ts[0].type_name == "NVFP4" or ts[2].type_name == "NVFP4"
455        if nvfp4:
456            # NVFP4 (ModelOpt) carries one F32 weight_scale_2 per expert and projection, which the block format has
457            # no room for. Each blob gets a 16-byte tail {s_gate, s_up, s_down, 0} so every consumer that already
458            # moves whole blobs (the arena, the device cache, the prefill staging, a second GPU) moves the scales
459            # with the weights; the gate/up kernels read it. See tools/nvfp4_convert.py.
460            # a mixed expert (e.g. NVFP4 gate/up + Q8_0 down) has the tail too, with 1.0 for the other projection
461            if any(t.type_name == "NVFP4" and "blk.%d.ffn_%s_exps.scale" % (l, r) not in T for t, r in zip(ts, ROLES)):
462                return "layer %d: NVFP4 experts without their .scale tensors" % l
463            blob += NVFP4_TAIL
464        layout.append((l, ts[0].type_id, ts[2].type_id, offset, blob, ts))
465        ws = [model.where[n] for n in names]
466        files = ["" if w[3] == src else w[3].name for w in ws]
467        column = files[0] if len(set(files)) == 1 else ",".join(files)
468        n_split += len(set(files)) != 1
469        if nvfp4:   # no GGUF offsets: experts.bin is the only source that carries the scale tails
470            lines.append("%d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob))
471            offset += blob * n_expert
472            continue
473        line = "%d %d %d %d %d %d %d %d" % (l, ts[0].type_id, ts[2].type_id, offset, blob,
474                                            *[w[0].data_start + w[1].offset for w in ws])
475        lines.append(line + ("" if not column else " " + column))
476        offset += blob * n_expert
477    if n_split:
478        head = ("# strata native experts v4: layer gu_type d_type offset blob_bytes gate_off up_off down_off "
479                "[shard | gate,up,down] (n_expert %d, total %d; absolute offsets in %s, or in the named shard "
480                "beside it - per role where the column is gate,up,down)\n" % (n_expert, offset, src.name))
481        print("%d layer(s) have their gate/up/down in different shards: native_experts.txt v4, per-role shard "
482              "column for %s" % (n_split, ", ".join(str(l) for l, *_ in layout if "," in lines[l])))
483    else:
484        head = ("# strata native experts v3: layer gu_type d_type offset blob_bytes gate_off up_off down_off [shard] "
485                "(n_expert %d, total %d; absolute offsets in %s, or in the named shard beside it)\n"
486                % (n_expert, offset, src.name))
487    return layout, head + "".join(line + "\n" for line in lines), n_expert, offset
488
489
490NATIVE_HEAD = re.compile(r"^# strata native experts v(\d+):")
491
492
493def native_experts_v5(text: str) -> str:
494    """native_experts.txt as expert_layout writes it (v3, or v4 with per-role shards) -> the same table marked v5
495    (Hadamard-folded experts, hadamard.txt beside it), or an error string naming the version it cannot mark."""
496    head, rest = text.split("\n", 1) if "\n" in text else (text, "")
497    m = NATIVE_HEAD.match(head)
498    if not m or m.group(1) not in ("3", "4"):
499        found = "v" + m.group(1) if m else "without a version header (%r)" % head[:40]
500        return ("cannot mark native_experts.txt %s as v5 for Hadamard-folded experts: only v3 and v4 tables are "
501                "supported" % found)
502    return "# strata native experts v5:" + head[m.end():] + " - v5: Hadamard-folded experts, see hadamard.txt\n" + rest
503
504
505HADAMARD_ROLE = re.compile(r"^blk\.(\d+)\.ffn_(gate|up|down)_exps\.weight$")
506
507
508def hadamard_spec(meta: dict, layout, n_embd: int, n_ff: int):
509    """prism.hadamard.* (Agention's APR files: routed experts stored in a block-Hadamard-rotated basis; the runtime
510    must rotate their input activations, see include/strata/kernels/cpu/hadamard.hpp) -> the text of hadamard.txt,
511    None for a model without the metadata, or an error string.  Anything this engine cannot apply is refused: a
512    folded weight it would run unrotated computes plausible garbage."""
513    if "prism.hadamard.version" not in meta:
514        return None
515    if int(meta["prism.hadamard.version"]) != 1:
516        return "unsupported prism.hadamard.version %s" % meta["prism.hadamard.version"]
517    block = int(meta.get("prism.hadamard.block_size", 0))
518    if block <= 1 or block & (block - 1):
519        return "invalid prism.hadamard.block_size %r" % block
520    if meta.get("prism.hadamard.transform") != "normalized-sylvester-walsh-hadamard":
521        return "unsupported prism.hadamard.transform %r" % meta.get("prism.hadamard.transform")
522    if meta.get("prism.hadamard.axis") != "input-last-dimension":
523        return "unsupported prism.hadamard.axis %r" % meta.get("prism.hadamard.axis")
524    mode = meta.get("prism.hadamard.sign_mode")
525    if mode not in ("identity", "explicit"):
526        return "unsupported prism.hadamard.sign_mode %r" % mode
527    if meta.get("prism.hadamard.inverse_weight_names"):
528        return ("prism.hadamard.inverse_weight_names (a rotated token embedding) is not supported by this engine: "
529                "%s" % ", ".join(meta["prism.hadamard.inverse_weight_names"][:4]))
530    names = meta.get("prism.hadamard.weight_names") or []
531    if not names:
532        return "prism.hadamard.weight_names is empty"
533    n_layers = len(layout)
534    roles = [0] * n_layers
535    for name in names:
536        m = HADAMARD_ROLE.match(name)
537        if not m or int(m.group(1)) >= n_layers:
538            return ("prism.hadamard folds %s; this engine applies the activation rotation to the routed experts "
539                    "(blk.N.ffn_{gate,up,down}_exps) only" % name)
540        bit = {"gate": 1, "up": 2, "down": 4}[m.group(2)]
541        if roles[int(m.group(1))] & bit:
542            return "duplicate prism.hadamard weight %s" % name
543        roles[int(m.group(1))] |= bit
544    for l, r in enumerate(roles):
545        if bool(r & 1) != bool(r & 2):
546            return "layer %d: prism.hadamard folds only one of gate/up (they share one input)" % l
547        if r and 42 in (layout[l][1] if r & 3 else -1, layout[l][2] if r & 4 else -1):
548            return "layer %d: a Hadamard-folded Q2_0 expert (the engine's Q2_0 rows cannot rotate)" % l
549    lines = ["# strata hadamard v1: prism.hadamard (normalized-sylvester-walsh-hadamard, input-last-dimension, "
550             "sign_mode %s), written by tools/iq_pack.py" % mode, "block %d" % block]
551    widths = {n_embd for r in roles if r & 3} | {n_ff for r in roles if r & 4}
552    if any(w % block for w in widths):
553        return "prism.hadamard block %d does not divide the expert widths %s" % (block, sorted(widths))
554    if mode == "explicit":
555        sw = [int(w) for w in meta.get("prism.hadamard.sign_widths") or []]
556        sv = [int(v) for v in meta.get("prism.hadamard.sign_values") or []]
557        if not sw or sum(sw) != len(sv) or any(w <= 0 or w % block for w in sw) or len(set(sw)) != len(sw):
558            return "prism.hadamard sign_widths / sign_values are inconsistent"
559        if any(v not in (1, -1) for v in sv):
560            return "prism.hadamard sign values must be +1/-1"
561        at, table = 0, {}
562        for w in sw:
563            table[w] = sv[at:at + w]
564            at += w
565        missing = sorted(widths - set(table))
566        if missing:
567            return "prism.hadamard has no sign vector for width(s) %s" % missing
568        for w in sorted(table):
569            lines.append("signs %d %s" % (w, " ".join(str(v) for v in table[w])))
570    for l, r in enumerate(roles):
571        if r:
572            lines.append("layer %d %d %d %d" % (l, r & 1, (r >> 1) & 1, (r >> 2) & 1))
573    return "\n".join(lines) + "\n"
574
575
576def experts_source(model: Model, text: str, total: int) -> dict:
577    """What experts.bin is cut from: the shards (names and sizes) and the hash of native_experts.txt (every
578    per-role file and offset, the formats and the blob sizes).  A same-size experts.bin of another model or
579    another packing is not this one."""
580    return {"schema": 1,
581            "shards": [{"name": p.name, "size": s} for p, s in zip(model.paths, model.sizes)],
582            "native_experts_sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
583            "bytes": total}
584
585
586def read_json(path: pathlib.Path):
587    try:
588        return json.loads(path.read_text(encoding="utf-8"))
589    except (OSError, ValueError):
590        return None
591
592
593def main() -> int:
594    ap = argparse.ArgumentParser()
595    ap.add_argument("--gguf", required=True, help="the model's shard 1")
596    ap.add_argument("--base", help="optional: a Q2_0 canonical pack whose dense.bin holds the shared float tensors")
597    ap.add_argument("--out", required=True)
598    ap.add_argument("--skip-experts", action="store_true", help="rewrite the index only")
599    ap.add_argument("--compat-bf16", action="store_true",
600                    help="dequantize small non-native projections to BF16 for ordinary Qwen4Exp GGUFs "
601                         "(rounds weights; leaves experts and the PLE table unchanged)")
602    ap.add_argument("--experts-bin", action="store_true",
603                    help="also write experts.bin (the engine otherwise reads the experts from the GGUF itself)")
604    a = ap.parse_args()
605    if a.compat_bf16 and a.base:
606        ap.error("--compat-bf16 cannot reuse --base dense weights")
607    # HF snapshot files are symlinks to hash-named blobs. Keep the shard filename for discovery: .absolute(), not
608    # .resolve(), which would follow the link to the blob and lose the -0000N-of-0000M name.
609    src = pathlib.Path(a.gguf).absolute()
610    base = pathlib.Path(a.base).resolve() if a.base else None
611    out = pathlib.Path(a.out)
612    out.mkdir(parents=True, exist_ok=True)
613
614    g = G.GGUFFile(src)
615    mm = np.memmap(src, dtype=np.uint8, mode="r")
616    model = Model(src)
617    if len(model.paths) > 1:
618        print("model shards: " + ", ".join(p.name for p in model.paths))
619    # ---- the expert table first: a model that cannot be packed is refused before any file of the pack changes
620    got = expert_layout(model, src)
621    if isinstance(got, str):
622        print(got)
623        return 1
624    layout, text, n_expert, offset = got
625    if any(t.type_name == "NVFP4" for *_, ts in layout for t in ts):
626        a.experts_bin = True   # the GGUF holds the weights without the scale tails: the engine must read experts.bin
627    # ---- prism.hadamard: rotated experts need hadamard.txt beside native_experts.txt, which becomes v5 so an engine
628    # that cannot rotate refuses the pack (instead of running the folded experts on unrotated activations)
629    t0 = layout[0][5]
630    had = hadamard_spec(g.metadata, layout, int(t0[0].shape[0]), int(t0[2].shape[0]))
631    if isinstance(had, str) and not had.startswith("# strata hadamard"):
632        print("prism.hadamard: " + had)
633        return 1
634    if had is not None:
635        text = native_experts_v5(text)
636        if not text.startswith("# strata native experts v5:"):
637            print("prism.hadamard: " + text)
638            return 1
639        print("prism.hadamard: %d layer(s) of Hadamard-folded experts (block %s, %s signs): hadamard.txt, "
640              "native_experts.txt v5" % (sum(1 for ln in had.splitlines() if ln.startswith("layer ")),
641                                         g.metadata["prism.hadamard.block_size"],
642                                         g.metadata["prism.hadamard.sign_mode"]))
643    path = out / "experts.bin"
644    sidecar = out / "experts.bin.src.json"
645    want = experts_source(model, text, offset)
646    reuse = path.exists() and path.stat().st_size == offset and read_json(sidecar) == want
647
648    def nvfp4_tails(l, ts):
649        """(n_expert, NVFP4_TAIL) bytes {s_gate, s_up, s_down, 0} of a layer with an NVFP4 projection; a projection in
650        another format gets exactly 1.0 (the engine multiplies by the tail unconditionally). None for a bad scale."""
651        s = [np.frombuffer(model.bytes("blk.%d.ffn_%s_exps.scale" % (l, r)).tobytes(), dtype=np.float32)
652             if t.type_name == "NVFP4" else np.ones(n_expert, dtype=np.float32) for t, r in zip(ts, ROLES)]
653        tail = np.zeros((n_expert, NVFP4_TAIL // 4), dtype=np.float32)
654        tail[:, 0], tail[:, 1], tail[:, 2] = s[0], s[1], s[2]
655        if not np.isfinite(tail).all() or (tail[:, :3] <= 0).any():
656            print("layer %d: a non-finite or non-positive NVFP4 scale" % l)
657            return None
658        return tail.view(np.uint8)
659
660    def layer_blobs(l, blob, ts):
661        """(n_expert, blob): gate | up | down [| the NVFP4 scale tail] per expert; None for a bad NVFP4 scale."""
662        parts = [model.bytes(t.name).reshape(n_expert, -1) for t in ts]
663        if any(t.type_name == "NVFP4" for t in ts):
664            tail = nvfp4_tails(l, ts)
665            if tail is None:
666                return None
667            parts.append(tail)
668        chunk = np.concatenate(parts, axis=1)
669        assert chunk.shape == (n_expert, blob)
670        return chunk
671
672    if reuse:
673        # the sidecar names the shards by name and size, which a re-quantized or fine-tuned checkpoint of the same
674        # geometry packed into the same folder can share: compare the first and last blobs of the first, middle and
675        # last layers with the GGUF too (six blobs, so an unchanged pack is still reused at once)
676        with open(path, "rb") as f:
677            for l, gt, dt, off, blob, ts in (layout[0], layout[len(layout) // 2], layout[-1]):
678                for e in (0, n_expert - 1):
679                    f.seek(off + e * blob)
680                    want_blob = b"".join(model.bytes(t.name).reshape(n_expert, -1)[e].tobytes() for t in ts)
681                    if any(t.type_name == "NVFP4" for t in ts):
682                        tail = nvfp4_tails(l, ts)
683                        want_blob += tail[e].tobytes() if tail is not None else b""
684                    if f.read(blob) != want_blob:
685                        reuse = False
686        if not reuse:
687            print("%s matches %s but not this GGUF's expert blobs" % (path, sidecar.name))
688    if path.exists() and not reuse and not a.experts_bin:
689        if sidecar.exists():
690            print("%s was cut from another source than this model (%s): the engine would read it instead of "
691                  "the GGUF.  Delete it, or rerun with --experts-bin to rewrite it." % (path, sidecar.name))
692            return 1
693        print("warning: %s has no %s, so nothing says it belongs to this model; the engine reads it instead of "
694              "the GGUF (rerun with --experts-bin to rewrite it)" % (path, sidecar.name))
695    if a.base:
696        if any(w[3] != src for w in model.where.values() if not w[1].name in NOT_IN_PACK):
697            print("--base needs a model whose tensors are all in shard 1")
698            return 1
699        (out / "native_experts.txt").unlink(missing_ok=True)
700        rc = index_from_base(a, src, base, out, g, {t.name: t for t in g.tensors}, mm)
701    else:
702        rc = index_standalone(src, out, model, a.compat_bf16)
703    if rc:
704        return rc
705    if not (out / "tokenizer" / "vocab.json").exists() or not (out / "tokenizer" / "chat_template.jinja").exists():
706        subprocess.run([sys.executable, str(HERE / "strata_tokenizer.py"), "--gguf", str(src), "--out", str(out)],
707                       check=True)   # writes <out>/tokenizer/
708
709    # ---- the experts.  native_experts.txt is written to a temporary name and renamed only when every layer is
710    # in: a stop part-way (a layer split across shards, #171) left a partial native_experts.txt that the next setup
711    # run took as a finished pack (#172).  It is the pack's completion marker, so it is published last.
712    htmp = out / "hadamard.txt.tmp"
713    if had is not None:
714        htmp.write_text(had, encoding="utf-8", newline="\n")
715        htmp.replace(out / "hadamard.txt")
716    else:
717        (out / "hadamard.txt").unlink(missing_ok=True)      # a previous Hadamard model's, packed into this folder
718    tmp = out / "native_experts.txt.tmp"
719    with open(tmp, "w", encoding="utf-8", newline="\n") as fo:
720        fo.write(text)
721    tmp.replace(out / "native_experts.txt")
722    if a.skip_experts or not a.experts_bin:
723        if path.exists() and not a.experts_bin:
724            print("note: %s/experts.bin exists; the engine reads it instead of the GGUF" % out)
725        return 0
726    if reuse:
727        print("experts.bin was cut from this model's shards (%s); not rewritten" % sidecar.name)
728        return 0
729    # written under a temporary name and renamed when complete, then the sidecar: an interrupted write leaves no
730    # experts.bin, and an experts.bin without its sidecar is never reused
731    sidecar.unlink(missing_ok=True)
732    part = out / "experts.bin.tmp"
733    progress = out / "experts.bin.tmp.json"
734    # A stop part-way (a kill, a power cut) used to cost the whole write again (40 GB, minutes).  The finished layers are kept:
735    # after every layer the file is flushed to disk and experts.bin.tmp.json says how many layers are in it and which source they were
736    # cut from.  The next run continues at that layer when the source is the same and the last kept layer still matches the GGUF.
737    start = 0
738    if part.exists():
739        done = read_json(progress)
740        k = done.get("layers") if isinstance(done, dict) and done.get("want") == want else None
741        if isinstance(k, int) and 0 < k <= len(layout) and part.stat().st_size >= (layout[k][3] if k < len(layout) else offset):
742            l, gt, dt, off, blob, ts = layout[k - 1]
743            last = layer_blobs(l, blob, ts)
744            if last is not None:
745                with open(part, "rb") as f:
746                    f.seek(off)
747                    kept = f.read(n_expert * blob)
748                if kept == last.tobytes():
749                    start = k
750        if start:
751            print("the earlier packing was interrupted: keeping its first %d of %d layers and continuing with layer %d"
752                  % (start, len(layout), start), flush=True)
753        else:
754            print("the earlier packing was interrupted and cannot be continued: starting it again", flush=True)
755    resume_at = layout[start][3] if start < len(layout) else offset
756    with open(part, "r+b" if start else "wb") as fo:
757        if start:
758            fo.truncate(resume_at)       # whatever followed the last recorded layer is a partial write
759            fo.seek(resume_at)
760        for l, gt, dt, off, blob, ts in layout[start:]:
761            chunk = layer_blobs(l, blob, ts)
762            if chunk is None:
763                return 1
764            fo.write(chunk.tobytes())
765            fo.flush()
766            os.fsync(fo.fileno())
767            note = out / "experts.bin.tmp.json.new"
768            note.write_text(json.dumps({"want": want, "layers": l + 1}), encoding="utf-8")
769            note.replace(progress)
770            if l % 8 == 0:
771                print("  layer %2d  %-8s/%-7s blob %8d  at %.2f GiB" % (l, ts[0].type_name, ts[2].type_name, blob,
772                                                                        off / 2**30), flush=True)
773    part.replace(path)
774    progress.unlink(missing_ok=True)
775    side_tmp = out / "experts.bin.src.json.tmp"
776    side_tmp.write_text(json.dumps(want, indent=2) + "\n", encoding="utf-8")
777    side_tmp.replace(sidecar)
778    print("experts.bin: %d layers, %.2f GiB" % (len(layout), offset / 2**30))
779    return 0
780
781
782if __name__ == "__main__":
783    raise SystemExit(main())