okami.mom/strata

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

Niko1221Merge f-mac-rel ccfe67aa (Mac memory-safety fix for big Macs) into f-144-reld6bd7c1d6

main
10.2 KiB243 linesraw
1#!/usr/bin/env python3
2"""metal_repack.py: a multi-shard GGUF (Unsloth's UD-*_K_XL: 4-6 shards, shards cutting through layers) as ONE GGUF
3for the Metal engine, which maps a single file into one GPU buffer (or streams its experts from it).
4
5    python3 metal/tools/metal_repack.py --shard1 <...-00001-of-0000N.gguf> --out <model>-metal.gguf [--verify]
6
7--verify: after writing, every tensor of the output is hashed (SHA-256) against its bytes in the source shard; any
8difference stops with an error and removes the output.
9
10The output holds shard 1's metadata (without the split.* keys) and every tensor of every shard except the n-gram
11table (per_layer_token_embd: it stays in its shard, read from the SSD by the host through --ple-gguf), byte for
12byte. The dense tensors come first; then each layer's routed experts (gate, up, down) together. Every tensor starts
13on a 16 KiB boundary (general.alignment = 16384: Apple Silicon's page). Prints the shard holding the n-gram table.
14"""
15from __future__ import annotations
16
17import argparse
18import atexit
19import hashlib
20import os
21import re
22import struct
23import sys
24from pathlib import Path
25
26ALIGN = 16384
27SYNC_EVERY = 1 << 30      # the output is flushed to the disk every GiB: at most this much (plus a chunk) is ever dirty
28CHUNK = 64 << 20
29LOCK_SUFFIX = ".repack.lock"   # <out>.repack.lock holds the repack's pid while it runs (setup_mac.py and the engine look)
30# GGML type -> (bytes per block, values per block)
31TYPE_SIZE = {0: (4, 1), 1: (2, 1), 30: (2, 1), 2: (18, 32), 3: (20, 32), 6: (22, 32), 7: (24, 32), 8: (34, 32),
32             10: (84, 256), 11: (110, 256), 12: (144, 256), 13: (176, 256), 14: (210, 256), 16: (66, 256),
33             17: (74, 256), 18: (98, 256), 19: (50, 256), 20: (18, 32), 21: (110, 256), 22: (82, 256), 23: (136, 256),
34             42: (18, 64)}
35PLE = "per_layer_token_embd.weight"
36
37
38def nocache(f) -> None:
39    """Writes through this file skip the page cache (macOS F_NOCACHE; measured with mincore on a 4 GB write: 100% of the file cached
40    without it, 0% with it).  A repack writes 100+ GB: through the cache that is 100+ GB of dirty pages competing with everything
41    else for memory (the 128 GB M5 Max keeps a 37 GB file-cache floor and compresses other programs' memory beyond it).  READS are
42    not helped on this macOS (a cold 4 GB read was 98% cached afterwards with F_NOCACHE set); those pages are clean and evictable,
43    the harm of the old tool was the unbounded dirty output."""
44    try:
45        import fcntl
46        fcntl.fcntl(f.fileno(), getattr(fcntl, "F_NOCACHE", 48), 1)
47    except (ImportError, OSError, ValueError):
48        pass
49
50
51def drop_cache(f) -> None:
52    """Where F_NOCACHE does not exist (Linux, the BSDs): ask the kernel to drop this file's cached pages."""
53    if hasattr(os, "posix_fadvise"):
54        try:
55            os.posix_fadvise(f.fileno(), 0, 0, os.POSIX_FADV_DONTNEED)
56        except OSError:
57            pass
58
59
60def write_all(o, buf) -> None:
61    mv = memoryview(buf)
62    while len(mv):
63        mv = mv[o.write(mv):]
64
65
66class Reader:
67    def __init__(self, path: Path):
68        self.path = path
69        self.f = open(path, "rb")
70        magic, self.version, nt, nkv = struct.unpack("<4sIQQ", self.f.read(24))
71        if magic != b"GGUF":
72            sys.exit(f"{path}: not a GGUF file")
73        self.kv = []                                    # (key, raw bytes of the whole entry)
74        self.align = 32
75        for _ in range(nkv):
76            start = self.f.tell()
77            key = self._str()
78            t = struct.unpack("<I", self.f.read(4))[0]
79            val = self._val(t)
80            raw_end = self.f.tell()
81            self.f.seek(start)
82            raw = self.f.read(raw_end - start)
83            self.kv.append((key, raw))
84            if key == "general.alignment":
85                self.align = int(val)
86        self.tensors = []
87        for _ in range(nt):
88            name = self._str()
89            nd = struct.unpack("<I", self.f.read(4))[0]
90            dims = struct.unpack(f"<{nd}Q", self.f.read(8 * nd))
91            ty, off = struct.unpack("<IQ", self.f.read(12))
92            self.tensors.append({"name": name, "dims": dims, "type": ty, "off": off})
93        pos = self.f.tell()
94        self.data = (pos + self.align - 1) // self.align * self.align
95        for t in self.tensors:
96            ne = 1
97            for d in t["dims"]:
98                ne *= d
99            b, q = TYPE_SIZE[t["type"]]
100            t["bytes"] = ne // q * b
101            t["src"] = self
102            t["abs"] = self.data + t["off"]
103        nocache(self.f)                                 # the header is read; the tensors' bytes are read once, uncached
104
105    def _str(self) -> str:
106        n = struct.unpack("<Q", self.f.read(8))[0]
107        return self.f.read(n).decode("utf-8", "replace")
108
109    def _val(self, t):
110        sz = {0: "B", 1: "b", 2: "H", 3: "h", 4: "I", 5: "i", 6: "f", 7: "?", 10: "Q", 11: "q", 12: "d"}
111        if t == 8:
112            return self._str()
113        if t == 9:
114            at, n = struct.unpack("<IQ", self.f.read(12))
115            return [self._val(at) for _ in range(n)]
116        return struct.unpack("<" + sz[t], self.f.read(struct.calcsize(sz[t])))[0]
117
118
119def shard_paths(shard1: Path) -> list[Path]:
120    m = re.match(r"(.*)-00001-of-(\d{5})\.gguf$", shard1.name)
121    if not m:
122        return [shard1]
123    n = int(m.group(2))
124    return [shard1.with_name(f"{m.group(1)}-{i:05d}-of-{n:05d}.gguf") for i in range(1, n + 1)]
125
126
127def tensor_hash(f, pos: int, n: int) -> str:
128    h = hashlib.sha256()
129    f.seek(pos)
130    while n:
131        buf = f.read(min(n, CHUNK))
132        if not buf:
133            break
134        h.update(buf)
135        n -= len(buf)
136    return h.hexdigest()
137
138
139def verify(out: Path, data0: int, order: list) -> list[str]:
140    """The names of the tensors whose bytes in `out` differ from their source shard's (SHA-256 each)."""
141    bad = []
142    with open(out, "rb") as o:
143        nocache(o)
144        r = Reader(out)                                # the output's own table, as a reader sees it
145        table = {t["name"]: t for t in r.tensors}
146        for i, t in enumerate(order):
147            mine = table.get(t["name"])
148            if mine is None or mine["abs"] != data0 + t["new"] or mine["bytes"] != t["bytes"] or \
149                    tensor_hash(o, mine["abs"], t["bytes"]) != tensor_hash(t["src"].f, t["abs"], t["bytes"]):
150                bad.append(t["name"])
151            if i % 50 == 0:
152                print(f"\r  verify {i + 1} / {len(order)}", end="", flush=True)
153        r.f.close()
154    print()
155    return bad
156
157
158def gguf_str(s: str) -> bytes:
159    b = s.encode("utf-8")
160    return struct.pack("<Q", len(b)) + b
161
162
163def main() -> int:
164    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
165    ap.add_argument("--shard1", required=True, type=Path)
166    ap.add_argument("--out", required=True, type=Path)
167    ap.add_argument("--verify", action="store_true", help="hash every tensor of the output against the source")
168    a = ap.parse_args()
169    shards = [Reader(p) for p in shard_paths(a.shard1)]
170    every = [t for s in shards for t in s.tensors]
171    ple = [t for t in every if t["name"] == PLE]
172    keep = [t for t in every if t["name"] != PLE]
173
174    def layer_of(t):
175        m = re.match(r"blk\.(\d+)\.", t["name"])
176        return int(m.group(1)) if m else -1
177    dense = [t for t in keep if "_exps." not in t["name"]]
178    role = {"ffn_gate_exps": 0, "ffn_up_exps": 1, "ffn_down_exps": 2}
179    exps = sorted((t for t in keep if "_exps." in t["name"]),
180                  key=lambda t: (layer_of(t), role.get(t["name"].split(".")[2], 9)))
181    order = dense + exps
182    kv = [raw for key, raw in shards[0].kv if not key.startswith("split.") and key != "general.alignment"]
183    kv.append(gguf_str("general.alignment") + struct.pack("<II", 4, ALIGN))
184    off = 0
185    infos = []
186    for t in order:
187        t["new"] = off
188        infos.append(gguf_str(t["name"]) + struct.pack("<I", len(t["dims"])) +
189                     struct.pack(f"<{len(t['dims'])}Q", *t["dims"]) + struct.pack("<IQ", t["type"], off))
190        off = (off + t["bytes"] + ALIGN - 1) // ALIGN * ALIGN
191    head = struct.pack("<4sIQQ", b"GGUF", 3, len(order), len(kv)) + b"".join(kv) + b"".join(infos)
192    data0 = (len(head) + ALIGN - 1) // ALIGN * ALIGN
193    total = data0 + off
194    tmp = a.out.with_name(a.out.name + ".part")
195    lock = a.out.with_name(a.out.name + LOCK_SUFFIX)
196    lock.write_text(str(os.getpid()))
197    atexit.register(lambda: lock.unlink() if lock.exists() else None)
198    # unbuffered writes (a write() is a write), uncached, flushed every SYNC_EVERY bytes: the dirty pages stay a chunk or two,
199    # wherever the other programs' memory stands (the old buffered, cached write left 2+ GB dirty and filled the RAM)
200    with open(tmp, "wb", buffering=0) as o:
201        nocache(o)
202        write_all(o, head)
203        write_all(o, b"\0" * (data0 - len(head)))
204        done = 0
205        since = 0
206        for t in order:
207            o.seek(data0 + t["new"])
208            src = t["src"].f
209            src.seek(t["abs"])
210            left = t["bytes"]
211            while left:
212                buf = src.read(min(left, CHUNK))
213                if not buf:
214                    sys.exit(f"{t['src'].path}: short read in {t['name']}")
215                write_all(o, buf)
216                left -= len(buf)
217                since += len(buf)
218                if since >= SYNC_EVERY:
219                    os.fsync(o.fileno())
220                    drop_cache(o)
221                    drop_cache(src)
222                    since = 0
223            done += t["bytes"]
224            if t is order[-1] or t["name"].endswith("ffn_down_exps.weight"):
225                print(f"\r  {done / 2**30:6.1f} / {sum(x['bytes'] for x in order) / 2**30:.1f} GiB", end="", flush=True)
226        o.truncate(total)
227        os.fsync(o.fileno())
228    print()
229    if a.verify:
230        bad = verify(tmp, data0, order)
231        if bad:
232            tmp.unlink()
233            sys.exit(f"verify FAILED: {len(bad)} tensors differ from the source, first {bad[0]} (output removed)")
234        print(f"verify: {len(order)} tensors, SHA-256 identical to the source shards")
235    os.replace(tmp, a.out)
236    print(f"{a.out}: {len(order)} tensors ({len(dense)} dense, {len(exps)} expert), {total / 2**30:.2f} GiB")
237    if ple:
238        print(f"n-gram table: {ple[0]['src'].path}")
239    return 0
240
241
242if __name__ == "__main__":
243    sys.exit(main())