okami.mom/strata

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

Niko1221Merge commit 'b8d604d28' into f-clean-1ab0fc432ed

main
21.3 KiB451 linesraw
1"""Strata P1.S6/S7 - the pack builder and verifier.
2
3This is `strata-pack build` / `strata-pack verify` / `strata-pack info`.  It is the Python implementation of
4`docs/pack-format.md`; the C++ `tools/strata-pack` is a port of it, and if the two disagree the C++ is wrong.
5
6WHY PYTHON FIRST.  The canonicalisation in `tools/canonical_xcheck.py` is measured bit-exact over every block
7of every tensor (757,139,840 blocks across 1021 tensors, plus Q2_0), against gguf-py and, for Q2_0, backed by
8`dequant_xcheck` against ggml itself.  That makes the Python mapping table the specification of record.  The
9pack is Phase 2's prerequisite and can be produced from it today; the port then has a golden artifact to be
10tested against instead of being the thing everything else waits on.
11
12THE ONE RULE.  A pack is only valid if, for every tensor, `decode(pack) == dequant_ggml(source)` BIT FOR BIT.
13`verify` is that test and it is not optional - it re-reads the written pack from disk and compares it against
14the source shard.  A pack that has not passed `verify` does not exist.
15
16SCALE PRECISION.  A canonical scale is an FP32 product (`fl(d*sc)`), which is generally NOT representable in
17FP16.  The packer therefore stores scales as FP16 only when the round-trip is exact and as FP32 otherwise, and
18records which per tensor.  It never has to decide correctly: `verify` re-checks bit-exactness, so a wrong
19choice is a failed build rather than a silently lossy pack.  The expert arena is the exception and is FP16 by
20construction - architecture §3.2 fixes the blob at exactly 1,382,400 bytes and pack_layer.py asserts it.
21"""
22from __future__ import annotations
23
24import argparse
25import hashlib
26import json
27import pathlib
28import sys
29
30import numpy as np
31
32HERE = pathlib.Path(__file__).resolve().parent
33sys.path.insert(0, str(HERE))
34sys.path.insert(0, str(HERE.parent / "ref"))
35
36import gguf_reader as G                                                    # noqa: E402
37import pack_layer as PL                                                    # noqa: E402
38from canonical_xcheck import (MAPPINGS, KV_IQ4NL, open_shard,             # noqa: E402
39                              data_section_offset, reference_values)
40
41FORMAT_VERSION = 1
42ALIGN = 64                       # every plane starts on a 64-byte boundary (P1.S7)
43_HERE = pathlib.Path(__file__).resolve()
44STRATA = _HERE.parents[min(3, len(_HERE.parents) - 1)]   # the development layout; build takes the shard from --gguf
45SHARD2 = STRATA / "Q2_0" / "Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf"
46
47EXPERT_RE = ("ffn_gate_exps.weight", "ffn_up_exps.weight", "ffn_down_exps.weight")
48EMBD_NAME = "token_embd.weight"
49
50
51def is_expert(name: str) -> bool:
52    return name.startswith("blk.") and name.endswith(EXPERT_RE)
53
54
55def code_bits(form: str) -> int:
56    return {"S2": 2, "S4": 4, "S8": 8}[form]
57
58
59def pack_codes(codes: np.ndarray, bits: int) -> bytes:
60    """Pack one code per element into bytes, LSB-first, `8//bits` codes per byte.
61
62    This is Q2_0's own convention (4 codes per byte, byte j/4, bits (j%4)*2), kept for every form so the
63    kernel has one unpacking loop rather than one per source type.
64    """
65    flat = codes.reshape(-1).astype(np.uint8)
66    if bits == 8:
67        return flat.tobytes()
68    per = 8 // bits
69    if flat.size % per:
70        raise ValueError("code count %d is not a multiple of %d per byte" % (flat.size, per))
71    g = flat.reshape(-1, per).astype(np.uint16)
72    out = np.zeros(g.shape[0], dtype=np.uint16)
73    for k in range(per):
74        out |= (g[:, k] & ((1 << bits) - 1)) << (k * bits)
75    return out.astype(np.uint8).tobytes()
76
77
78def unpack_codes(buf: bytes, bits: int, n: int) -> np.ndarray:
79    if bits == 8:
80        return np.frombuffer(buf, dtype=np.uint8)[:n].copy()
81    per = 8 // bits
82    b = np.frombuffer(buf, dtype=np.uint8)
83    out = np.empty((b.size, per), dtype=np.uint8)
84    for k in range(per):
85        out[:, k] = (b >> (k * bits)) & ((1 << bits) - 1)
86    return out.reshape(-1)[:n].copy()
87
88
89def choose_scale_dtype(scales: np.ndarray) -> tuple[np.ndarray, bool]:
90    """FP16 when the round-trip is exact, else FP32.  Returns (bytes, is_fp16)."""
91    as16 = scales.astype(np.float16)
92    if np.array_equal(as16.astype(np.float32), scales):
93        return as16.tobytes(), True
94    return scales.astype("<f4").tobytes(), False
95
96
97def canonicalise(name: str, tname: str, raw: bytes):
98    """Source bytes -> the canonical planes, as (codes, scales, offsets_or_None, mapping)."""
99    m = MAPPINGS[tname]
100    parts = m.enc(raw)
101    if len(parts) == 3:
102        return parts[0], parts[1], parts[2], m
103    return parts[0], parts[1], None, m
104
105
106def tensor_entry(name, meta, tname, raw, seg_offset):
107    """Encode one tensor and return (blob_bytes, manifest_entry)."""
108    m = MAPPINGS[tname]
109
110    body = bytearray()
111    base = seg_offset
112
113    def put(b: bytes) -> dict:
114        nonlocal body
115        pad = (-len(body)) % ALIGN
116        body += b"\0" * pad
117        off = base + len(body)
118        body += b
119        return {"offset": off, "bytes": len(b)}
120
121    common = {
122        "name": name, "source_type": tname, "form": m.form, "codebook": m.codebook,
123        "code_bias": m.code_bias, "has_offset": m.has_offset,
124        "block_elems": m.block_elems, "block_bytes": m.block_bytes, "group_elems": m.group_elems,
125        "shape": list(meta.shape), "source_offset": meta.offset,
126    }
127
128    # ---- P16/P32 are pass-through: one value plane, no codes, no scale, no offset
129    if m.form in ("P16", "P32"):
130        vals = np.ascontiguousarray(m.dec(m.enc(raw)), dtype=np.float32).reshape(-1)
131        if m.form == "P32":
132            vb, v16 = vals.astype("<f4").tobytes(), False
133        else:
134            a16 = vals.astype(np.float16)
135            if not np.array_equal(a16.astype(np.float32), vals):
136                raise ValueError("%s: P16 would lose precision, so this tensor needs P32" % name)
137            vb, v16 = a16.tobytes(), True
138        ent = dict(common, elements=int(vals.size), values_fp16=v16)
139        ent["values"] = put(vb)
140        return bytes(body), ent
141
142    codes, scales, offsets, m = canonicalise(name, tname, raw)
143    codes = np.ascontiguousarray(codes)
144    scales = np.ascontiguousarray(scales.reshape(-1), dtype=np.float32)
145    n_el = int(codes.size)
146    bits = code_bits(m.form)
147    codes_b = pack_codes(codes, bits)
148    scales_b, sc16 = choose_scale_dtype(scales)
149
150    ent = dict(common, elements=n_el, code_bits=bits)
151    ent["codes"] = put(codes_b)
152    ent["scales"] = put(scales_b)
153    ent["scales_fp16"] = sc16
154    if offsets is not None:
155        ob, o16 = choose_scale_dtype(np.ascontiguousarray(offsets.reshape(-1), dtype=np.float32))
156        ent["offsets"] = put(ob)
157        ent["offsets_fp16"] = o16
158    return bytes(body), ent
159
160
161def decode_entry(head: bytes, ent: dict) -> np.ndarray:
162    """Decode a tensor from the pack, using ONLY what the manifest says.
163
164    Deliberately manifest-driven: if the manifest does not carry enough to decode the tensor, this cannot
165    silently fall back on knowledge of the source type, and the omission becomes a failure here.
166    """
167    if ent["form"] in ("P16", "P32"):
168        vb = head[ent["values"]["offset"]: ent["values"]["offset"] + ent["values"]["bytes"]]
169        return np.frombuffer(vb, dtype="<f2" if ent["values_fp16"] else "<f4").astype(np.float32)
170
171    n = ent["elements"]
172    codes = unpack_codes(head[ent["codes"]["offset"]: ent["codes"]["offset"] + ent["codes"]["bytes"]],
173                         ent["code_bits"], n)
174    sc = head[ent["scales"]["offset"]: ent["scales"]["offset"] + ent["scales"]["bytes"]]
175    sc = np.frombuffer(sc, dtype="<f2" if ent["scales_fp16"] else "<f4").astype(np.float32)
176    if "offsets" in ent:
177        ob = head[ent["offsets"]["offset"]: ent["offsets"]["offset"] + ent["offsets"]["bytes"]]
178        off = np.frombuffer(ob, dtype="<f2" if ent.get("offsets_fp16") else "<f4").astype(np.float32)
179    else:
180        off = None
181    if ent["codebook"] == "IQ4NL":
182        v = KV_IQ4NL[codes]
183    else:
184        v = (codes.astype(np.int32) + ent["code_bias"]).astype(np.float32)
185    g = ent["group_elems"]
186    if g == 1:                       # one scale for the whole tensor
187        return (v * sc[0]).reshape(-1) if off is None else (v * sc[0] + off[0]).reshape(-1)
188    out = v.reshape(-1, g) * sc[:, None]
189    if off is not None:
190        out = out + off[:, None]
191    return out.reshape(-1)
192
193
194def sha256(path: pathlib.Path, chunk: int = 1 << 24) -> str:
195    h = hashlib.sha256()
196    with open(path, "rb") as f:
197        while True:
198            b = f.read(chunk)
199            if not b:
200                break
201            h.update(b)
202    return h.hexdigest()
203
204
205# The files the engine reads a pack's identity from (src/core/expert_source.cpp, the fingerprint): one of them in
206# --out means the directory already holds a pack, this tool's or iq_pack.py's.  experts.bin on its own does not:
207# build writes manifest.json last, so experts.bin without it is a build that did not finish, and is rebuilt.
208PACK_MARKERS = ("manifest.json", "index.txt", "native_experts.txt")
209
210
211def occupied(out_dir: pathlib.Path) -> pathlib.Path | None:
212    """The pack marker already in `out_dir`, or None when the directory is empty, absent or holds no pack."""
213    for name in PACK_MARKERS:
214        if (out_dir / name).exists():
215            return out_dir / name
216    return None
217
218
219def build(gguf: pathlib.Path, out_dir: pathlib.Path, n_layers: int | None, skip_hash: bool, force: bool = False) -> int:
220    # refused before anything is opened or written: build used to mkdir(exist_ok=True) and overwrite experts.bin,
221    # dense.bin, embd.bin and manifest.json of whatever pack was there, with nothing said
222    marker = None if force else occupied(out_dir)   # --force: setup rebuilding a pack that lost index.txt or experts.bin
223    if marker is not None:
224        print("%s already holds a pack (%s is there) - refusing to build; delete the directory, pass another "
225              "--out, or --force to rebuild it" % (out_dir, marker.name))
226        return 1
227    out_dir.mkdir(parents=True, exist_ok=True)
228    if force:
229        # the old pack's markers go before a byte is written, so a forced build that stops part-way leaves an
230        # unfinished build (experts.bin without a manifest.json), which the next build or setup makes again - not
231        # the old manifest.json and index.txt over partly new experts, which setup's "index.txt and experts.bin are
232        # there" check would hand to the engine.  The data files need no removing: the build rewrites each one.
233        for name in PACK_MARKERS:
234            (out_dir / name).unlink(missing_ok=True)
235    g = G.GGUFFile(gguf)
236    head, flen = open_shard(gguf)
237    data_off = data_section_offset(g, flen)
238    print("source %s: %d tensors, data at %d" % (gguf.name, len(g.tensors), data_off))
239
240    n_layers = 48 if n_layers is None else n_layers
241    man = {
242        "format": "strata-pack", "format_version": FORMAT_VERSION,
243        "source": {"shard1": str(gguf), "shard2": str(SHARD2)},
244        "n_layers": n_layers, "align": ALIGN,
245        "codebooks": {"IQ4NL": [float(x) for x in KV_IQ4NL]},
246        "tensors": {}, "experts": {}, "n_experts_per_layer": PL.NE,
247    }
248
249    # ---- experts.bin: delegated to pack_layer so the blob layout has exactly ONE implementation
250    # pack_layer reads its own hardcoded SHARD1, so a different --gguf would silently take the expert arena
251    # from a different file than the dense tensors.  Refuse rather than produce a mixed-source pack.
252    # the expert arena and the dense tensors come from the same file: point pack_layer at it
253    PL.SHARD1 = pathlib.Path(gguf).resolve()
254    shard2 = pathlib.Path(str(PL.SHARD1).replace("00001-of-00002", "00002-of-00002"))
255    man["source"]["shard2"] = str(shard2)
256    exp_path = out_dir / "experts.bin"
257    print("experts.bin: %d layers, %.2f GiB" % (n_layers, n_layers * PL.NE * PL.BLOB_BYTES / 2**30))
258    em = PL.build(n_layers, exp_path)
259    man["experts"] = {"blob_bytes": em["blob_bytes"], "offsets": em["offsets"],
260                      "layers": em["layers"], "total_bytes": em["total_bytes"],
261                      "scales_fp16": True, "source_type": "Q2_0", "form": "S2"}
262
263    # ---- dense.bin and embd.bin
264    dense = []
265    embd = []
266    for t in g.tensors:
267        if is_expert(t.name):
268            continue
269        (embd if t.name == EMBD_NAME else dense).append(t)
270
271    for fname, group in (("dense.bin", dense), ("embd.bin", embd)):
272        path = out_dir / fname
273        seg_base = 0
274        with open(path, "wb") as fh:
275            for t in group:
276                if t.type_name not in MAPPINGS:
277                    print("  %s: NO MAPPING for %s - refusing to build" % (t.name, t.type_name))
278                    return 1
279                raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)]
280                if len(raw) != (t.expected_bytes() or 0):
281                    print("  %s: SHORT READ - refusing to build" % t.name)
282                    return 1
283                blob, ent = tensor_entry(t.name, t, t.type_name, raw, seg_base)
284                ent["file"] = fname
285                fh.write(blob)
286                seg_base += len(blob)
287                man["tensors"][t.name] = ent
288        print("%s: %d tensors, %.2f GiB" % (fname, len(group), path.stat().st_size / 2**30))
289
290    man["files"] = {"experts.bin": exp_path.stat().st_size,
291                    "dense.bin": (out_dir / "dense.bin").stat().st_size,
292                    "embd.bin": (out_dir / "embd.bin").stat().st_size}
293    if not skip_hash:
294        print("hashing shards (this is the slow part)...")
295        man["source"]["shard1_sha256"] = sha256(gguf)
296        man["source"]["shard2_sha256"] = sha256(shard2) if shard2.exists() else None
297    # shard 2 is NOT copied: the PLE table stays where it is and the manifest records how to find it
298    if shard2.exists():
299        g2 = G.GGUFFile(shard2)
300        t2 = [t for t in g2.tensors if t.name == "per_layer_token_embd.weight"][0]
301        man["shard2_tensor"] = {"name": t2.name, "type": t2.type_name, "shape": list(t2.shape),
302                                "offset": t2.offset, "elements": t2.elements,
303                                "path": str(shard2)}
304    (out_dir / "manifest.json").write_text(json.dumps(man, indent=1), encoding="utf-8")
305    print("manifest.json: %d tensor entries" % len(man["tensors"]))
306    return 0
307
308
309def rebuild_role(blob: bytes, role: str) -> bytes:
310    """Rebuild one role's raw Q2_0 bytes from an expert blob - the exact inverse of pack_layer's layout.
311
312    The arena stores codes and scales in SEPARATE PLANES and interleaves gate/up ROWS (g0,u0,g1,u1,...), so
313    a verifier that cannot invert that cannot check the arena.  Written as the inverse on purpose: this is
314    the only independent statement about the blob layout in the tree, and if it and `pack_layer` were the
315    same code the arena would be unverified by construction.
316    """
317    O, out = PL.OFF, bytearray()
318    n_blk = PL.H * PL.FF // PL.QK
319    for blk in range(n_blk):
320        if role == "down":
321            row, b_in = blk // PL.SCALES_D, blk % PL.SCALES_D
322            co = O["down_codes"] + row * PL.ROW_BYTES_D + b_in * 16
323            so = O["down_scales"] + (row * PL.SCALES_D + b_in) * 2
324        else:
325            row, b_in = blk // PL.SCALES_GU, blk % PL.SCALES_GU
326            slot = 2 * row + (0 if role == "gate" else 1)
327            co = O["gate_up_codes"] + slot * PL.ROW_BYTES_GU + b_in * 16
328            so = O["gate_up_scales"] + (slot * PL.SCALES_GU + b_in) * 2
329        out += blob[so:so + 2]          # fp16 d first, as block_q2_0 has it
330        out += blob[co:co + 16]         # then the 16 packed code bytes
331    return bytes(out)
332
333
334def verify_experts(gguf: pathlib.Path, out_dir: pathlib.Path, man: dict, every: int) -> int:
335    """Verify the expert arena: 85% of the pack by bytes and the part Phase 2 reads 480x per token."""
336    g = G.GGUFFile(gguf)
337    head, flen = open_shard(gguf)
338    data_off = data_section_offset(g, flen)
339    by_name = {t.name: t for t in g.tensors}
340    exp_mm, _ = open_shard(out_dir / "experts.bin")
341    blob = man["experts"]["blob_bytes"]
342    n_layers = man["n_layers"]
343    checked = bad = 0
344    for layer in range(n_layers):
345        for e in range(0, PL.NE, every):
346            base = (layer * PL.NE + e) * blob
347            b = exp_mm[base:base + blob]
348            for role in ("gate", "up", "down"):
349                t = by_name["blk.%d.ffn_%s_exps.weight" % (layer, role)]
350                per_expert = t.elements // PL.NE
351                nbytes = per_expert * PL.BLOCK_BYTES // PL.QK
352                src = head[data_off + t.offset + e * nbytes: data_off + t.offset + (e + 1) * nbytes]
353                ref = reference_values("Q2_0", src)
354                got = MAPPINGS["Q2_0"].dec(canonicalise(t.name, "Q2_0", rebuild_role(b, role))[:2])
355                checked += 1
356                if not np.array_equal(ref, got):
357                    print("  layer %d expert %d %-4s *** MISMATCH *** max|d| %.3e"
358                          % (layer, e, role, np.abs(ref.astype(np.float64) - got.astype(np.float64)).max()))
359                    bad += 1
360    print("experts: %d layer/expert/role checks (%d layers, every %dth expert), %d bad"
361          % (checked, n_layers, every, bad))
362    return bad
363
364
365def verify(gguf: pathlib.Path, out_dir: pathlib.Path, limit: int | None, expert_every: int) -> int:
366    """P1.T3 over the pack: decode it from disk and compare with the source, bit for bit."""
367    man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8"))
368    # A full verify also reads back the source hash build recorded (absent after --skip-hash, which is how setup
369    # builds): a pack compared against a different shard than it was built from is a mismatch, not a decode bug.
370    want = (man.get("source") or {}).get("shard1_sha256")
371    if want and limit is None:
372        got = sha256(gguf)
373        if got != want:
374            print("%s: sha256 %s, but the pack was built from %s" % (gguf.name, got, want))
375            print("tools/strata_pack.py verify FAIL")
376            return 1
377    g = G.GGUFFile(gguf)
378    head, flen = open_shard(gguf)
379    data_off = data_section_offset(g, flen)
380    by_name = {t.name: t for t in g.tensors}
381    files = {}
382    bad = 0
383    n_t = n_el = 0
384    for i, (name, ent) in enumerate(sorted(man["tensors"].items())):
385        if limit is not None and i >= limit:
386            break
387        if ent["file"] not in files:
388            files[ent["file"]] = open_shard(out_dir / ent["file"])[0]
389        t = by_name[name]
390        raw = head[data_off + t.offset: data_off + t.offset + (t.expected_bytes() or 0)]
391        ref = reference_values(t.type_name, raw)
392        got = decode_entry(files[ent["file"]], ent)
393        n_t += 1
394        n_el += ref.size
395        if ref.shape != got.shape or not np.array_equal(ref, got):
396            d = np.abs(ref.astype(np.float64) - got.astype(np.float64)) if ref.shape == got.shape else None
397            print("  %-40s *** MISMATCH *** %s" % (name, ("max|d| %.3e" % d.max()) if d is not None else
398                                                   "shape %s vs %s" % (ref.shape, got.shape)))
399            bad += 1
400        elif i < 3 or i % 200 == 0:
401            print("  %-40s bit-exact  (%d elements, %s)" % (name, ref.size, ent["form"]))
402    print()
403    print("verify: %d tensors, %d elements, %d bad" % (n_t, n_el, bad))
404    if expert_every > 0:
405        bad += verify_experts(gguf, out_dir, man, expert_every)
406    print("tools/strata_pack.py verify " + ("PASS" if bad == 0 else "FAIL"))
407    return 0 if bad == 0 else 1
408
409
410def info(out_dir: pathlib.Path) -> int:
411    man = json.loads((out_dir / "manifest.json").read_text(encoding="utf-8"))
412    print("strata-pack v%d  layers=%d" % (man["format_version"], man["n_layers"]))
413    for f, n in man.get("files", {}).items():
414        print("  %-12s %12.3f GiB" % (f, n / 2**30))
415    forms = {}
416    for e in man["tensors"].values():
417        forms[e["form"]] = forms.get(e["form"], 0) + 1
418    print("  dense/embd by form: %s" % ", ".join("%s=%d" % kv for kv in sorted(forms.items())))
419    print("  experts: %d blobs x %d B, %s" % (man["experts"]["layers"].__len__() * man["n_experts_per_layer"],
420                                              man["experts"]["blob_bytes"], man["experts"]["source_type"]))
421    return 0
422
423
424def main() -> int:
425    ap = argparse.ArgumentParser()
426    sub = ap.add_subparsers(dest="cmd", required=True)
427    b = sub.add_parser("build")
428    b.add_argument("--gguf", required=True)
429    b.add_argument("--out", required=True)
430    b.add_argument("--layers", type=int, default=None, help="expert layers to emit (default 48)")
431    b.add_argument("--skip-hash", action="store_true")
432    b.add_argument("--force", action="store_true", help="build into a directory that already holds a pack, unmaking that pack first (#634)")
433    v = sub.add_parser("verify")
434    v.add_argument("--gguf", required=True)
435    v.add_argument("--out", required=True)
436    v.add_argument("--limit", type=int, default=None)
437    v.add_argument("--expert-every", type=int, default=32,
438                   help="verify every Nth expert per layer in the arena (0 disables; the arena is 85%% of "
439                        "the pack and verifying NONE of it is how a pack passes while being wrong)")
440    n = sub.add_parser("info")
441    n.add_argument("--out", required=True)
442    args = ap.parse_args()
443    if args.cmd == "build":
444        return build(pathlib.Path(args.gguf), pathlib.Path(args.out), args.layers, args.skip_hash, args.force)
445    if args.cmd == "verify":
446        return verify(pathlib.Path(args.gguf), pathlib.Path(args.out), args.limit, args.expert_every)
447    return info(pathlib.Path(args.out))
448
449
450if __name__ == "__main__":
451    raise SystemExit(main())