diff --git a/metal/tools/metal_repack.py b/metal/tools/metal_repack.py new file mode 100644 index 00000000..b6064077 --- /dev/null +++ b/metal/tools/metal_repack.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""metal_repack.py: a multi-shard GGUF (Unsloth's UD-*_K_XL: 4-6 shards, shards cutting through layers) as ONE GGUF +for the Metal engine, which maps a single file into one GPU buffer (or streams its experts from it). + + python3 metal/tools/metal_repack.py --shard1 <...-00001-of-0000N.gguf> --out -metal.gguf [--verify] + +--verify: after writing, every tensor of the output is hashed (SHA-256) against its bytes in the source shard; any +difference stops with an error and removes the output. + +The output holds shard 1's metadata (without the split.* keys) and every tensor of every shard except the n-gram +table (per_layer_token_embd: it stays in its shard, read from the SSD by the host through --ple-gguf), byte for +byte. The dense tensors come first; then each layer's routed experts (gate, up, down) together. Every tensor starts +on a 16 KiB boundary (general.alignment = 16384: Apple Silicon's page). Prints the shard holding the n-gram table. +""" +from __future__ import annotations + +import argparse +import hashlib +import os +import re +import struct +import sys +from pathlib import Path + +ALIGN = 16384 +# GGML type -> (bytes per block, values per block) +TYPE_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), + 10: (84, 256), 11: (110, 256), 12: (144, 256), 13: (176, 256), 14: (210, 256), 16: (66, 256), + 17: (74, 256), 18: (98, 256), 19: (50, 256), 20: (18, 32), 21: (110, 256), 22: (82, 256), 23: (136, 256), + 42: (18, 64)} +PLE = "per_layer_token_embd.weight" + + +class Reader: + def __init__(self, path: Path): + self.path = path + self.f = open(path, "rb") + magic, self.version, nt, nkv = struct.unpack("<4sIQQ", self.f.read(24)) + if magic != b"GGUF": + sys.exit(f"{path}: not a GGUF file") + self.kv = [] # (key, raw bytes of the whole entry) + self.align = 32 + for _ in range(nkv): + start = self.f.tell() + key = self._str() + t = struct.unpack(" str: + n = struct.unpack(" list[Path]: + m = re.match(r"(.*)-00001-of-(\d{5})\.gguf$", shard1.name) + if not m: + return [shard1] + n = int(m.group(2)) + return [shard1.with_name(f"{m.group(1)}-{i:05d}-of-{n:05d}.gguf") for i in range(1, n + 1)] + + +def tensor_hash(f, pos: int, n: int) -> str: + h = hashlib.sha256() + f.seek(pos) + while n: + buf = f.read(min(n, 64 << 20)) + if not buf: + break + h.update(buf) + n -= len(buf) + return h.hexdigest() + + +def verify(out: Path, data0: int, order: list) -> list[str]: + """The names of the tensors whose bytes in `out` differ from their source shard's (SHA-256 each).""" + bad = [] + with open(out, "rb") as o: + r = Reader(out) # the output's own table, as a reader sees it + table = {t["name"]: t for t in r.tensors} + for i, t in enumerate(order): + mine = table.get(t["name"]) + if mine is None or mine["abs"] != data0 + t["new"] or mine["bytes"] != t["bytes"] or \ + tensor_hash(o, mine["abs"], t["bytes"]) != tensor_hash(t["src"].f, t["abs"], t["bytes"]): + bad.append(t["name"]) + if i % 50 == 0: + print(f"\r verify {i + 1} / {len(order)}", end="", flush=True) + r.f.close() + print() + return bad + + +def gguf_str(s: str) -> bytes: + b = s.encode("utf-8") + return struct.pack(" int: + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--shard1", required=True, type=Path) + ap.add_argument("--out", required=True, type=Path) + ap.add_argument("--verify", action="store_true", help="hash every tensor of the output against the source") + a = ap.parse_args() + shards = [Reader(p) for p in shard_paths(a.shard1)] + every = [t for s in shards for t in s.tensors] + ple = [t for t in every if t["name"] == PLE] + keep = [t for t in every if t["name"] != PLE] + + def layer_of(t): + m = re.match(r"blk\.(\d+)\.", t["name"]) + return int(m.group(1)) if m else -1 + dense = [t for t in keep if "_exps." not in t["name"]] + role = {"ffn_gate_exps": 0, "ffn_up_exps": 1, "ffn_down_exps": 2} + exps = sorted((t for t in keep if "_exps." in t["name"]), + key=lambda t: (layer_of(t), role.get(t["name"].split(".")[2], 9))) + order = dense + exps + kv = [raw for key, raw in shards[0].kv if not key.startswith("split.") and key != "general.alignment"] + kv.append(gguf_str("general.alignment") + struct.pack("