okami.mom/strata

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

Niko1221Merge f-mac-rel (Mac Metal support) into f-144-rel6a74320ca

main
4.2 KiB102 linesraw
1#!/usr/bin/env python3
2"""stream_experts.py: the routed experts of a GGUF re-laid for SSD streaming - every expert's gate, up and down rows
3next to each other, so the Metal engine reads a missed expert with one request instead of three (the M4 Mac mini's
4SSD: 2.97 GB/s for one 1.75 MB read per expert against 2.30 GB/s for three 0.58 MB reads, 6 threads, F_NOCACHE).
5
6    python3 metal/tools/stream_experts.py --gguf <model shard 1 or the repacked -metal.gguf> [--out <gguf>.experts] [--verify]
7
8The file: a 64-byte header ("STRX", version 1, 48 layers, 512 experts, the source GGUF's size), then per layer its
9offset in this file and the three slice sizes (4 x u64 each), then the experts, layer by layer, expert by expert:
10gate slice, up slice, down slice - each byte for byte the GGUF's.  --verify compares every expert with the GGUF.
11The engine (metal/src/engine/stream.cpp) uses it when it sits beside the GGUF as <gguf>.experts and its header
12matches; otherwise it reads the GGUF as before.
13"""
14from __future__ import annotations
15
16import argparse
17import hashlib
18import os
19import struct
20import sys
21from pathlib import Path
22
23sys.path.insert(0, str(Path(__file__).resolve().parent))
24import metal_repack as R  # noqa: E402
25
26NL, NE = 48, 512
27ALIGN = 16384
28
29
30def plan(gguf: Path):
31    """The reader, each layer's (gate, up, down, slice sizes), each layer's offset in the file, the file's size, the
32    first data offset."""
33    rd = R.Reader(gguf)
34    tab = {t["name"]: t for t in rd.tensors}
35    lay = []
36    for l in range(NL):
37        g, u, d = (tab[f"blk.{l}.ffn_{k}_exps.weight"] for k in ("gate", "up", "down"))
38        lay.append((g, u, d, g["bytes"] // NE, u["bytes"] // NE, d["bytes"] // NE))
39    head_len = 64 + NL * 32
40    data0 = (head_len + ALIGN - 1) // ALIGN * ALIGN
41    offs, at = [], data0
42    for g, u, d, gs, us, ds in lay:
43        offs.append(at)
44        at += NE * (gs + us + ds)
45        at = (at + ALIGN - 1) // ALIGN * ALIGN
46    return rd, lay, offs, at, data0
47
48
49def size_bytes(gguf: Path) -> int:
50    """The size the file for this GGUF will have (setup checks the free disk with it)."""
51    rd, _, _, at, _ = plan(gguf)
52    rd.f.close()
53    return at
54
55
56def main() -> int:
57    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
58    ap.add_argument("--gguf", required=True, type=Path)
59    ap.add_argument("--out", type=Path)
60    ap.add_argument("--verify", action="store_true")
61    a = ap.parse_args()
62    out = a.out or a.gguf.with_name(a.gguf.name + ".experts")
63    rd, lay, offs, at, data0 = plan(a.gguf)
64    head = struct.pack("<4sIIIQ", b"STRX", 1, NL, NE, os.path.getsize(a.gguf)).ljust(64, b"\0")
65    for (g, u, d, gs, us, ds), o in zip(lay, offs):
66        head += struct.pack("<QQQQ", o, gs, us, ds)
67    tmp = out.with_name(out.name + ".part")
68    src = rd.f
69    with open(tmp, "wb") as f:
70        f.write(head.ljust(data0, b"\0"))
71        for l, ((g, u, d, gs, us, ds), o) in enumerate(zip(lay, offs)):
72            src.seek(g["abs"]); G = src.read(g["bytes"])
73            src.seek(u["abs"]); U = src.read(u["bytes"])
74            src.seek(d["abs"]); D = src.read(d["bytes"])
75            f.seek(o)
76            f.write(b"".join(G[e * gs:(e + 1) * gs] + U[e * us:(e + 1) * us] + D[e * ds:(e + 1) * ds] for e in range(NE)))
77            print(f"\r  layer {l + 1} / {NL}", end="", flush=True)
78        f.truncate(at)
79    print()
80    if a.verify:
81        with open(tmp, "rb") as f:
82            for l, ((g, u, d, gs, us, ds), o) in enumerate(zip(lay, offs)):
83                h1, h2 = hashlib.sha256(), hashlib.sha256()
84                for t in (g, u, d):
85                    src.seek(t["abs"])
86                    h1.update(src.read(t["bytes"]))
87                f.seek(o)
88                blob = f.read(NE * (gs + us + ds))
89                step = gs + us + ds
90                for part, size, base in ((0, gs, 0), (1, us, gs), (2, ds, gs + us)):
91                    h2.update(b"".join(blob[e * step + base:e * step + base + size] for e in range(NE)))
92                if h1.digest() != h2.digest():
93                    tmp.unlink()
94                    sys.exit(f"verify FAILED at layer {l} (output removed)")
95        print(f"verify: {NL} layers x {NE} experts identical to the GGUF")
96    os.replace(tmp, out)
97    print(f"{out}: {at / 2**30:.2f} GiB")
98    return 0
99
100
101if __name__ == "__main__":
102    sys.exit(main())