okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
d6bd7c1d6
main
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 5python3 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 ), 3210 : (84 ,256 ),11 : (110 ,256 ),12 : (144 ,256 ),13 : (176 ,256 ),14 : (210 ,256 ),16 : (66 ,256 ), 3317 : (74 ,256 ),18 : (98 ,256 ),19 : (50 ,256 ),20 : (18 ,32 ),21 : (110 ,256 ),22 : (82 ,256 ),23 : (136 ,256 ), 3442 : (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 40without it, 0% with it). A repack writes 100+ GB: through the cache that is 100+ GB of dirty pages competing with everything 41else for memory (the 128 GB M5 Max keeps a 37 GB file-cache floor and compresses other programs' memory beyond it). READS are 42not helped on this macOS (a cold 4 GB read was 98% cached afterwards with F_NOCACHE set); those pages are clean and evictable, 43the harm of the old tool was the unbounded dirty output.""" 44try : 45import fcntl 46fcntl .fcntl (f .fileno (),getattr (fcntl ,"F_NOCACHE" ,48 ),1 ) 47except (ImportError ,OSError ,ValueError ): 48pass 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.""" 53if hasattr (os ,"posix_fadvise" ): 54try : 55os .posix_fadvise (f .fileno (),0 ,0 ,os .POSIX_FADV_DONTNEED ) 56except OSError : 57pass 58 59 60def write_all (o ,buf )-> None : 61mv = memoryview (buf ) 62while len (mv ): 63mv = mv [o .write (mv ):] 64 65 66class Reader : 67def __init__ (self ,path :Path ): 68self .path = path 69self .f = open (path ,"rb" ) 70magic ,self .version ,nt ,nkv = struct .unpack ("<4sIQQ" ,self .f .read (24 )) 71if magic != b"GGUF" : 72sys .exit (f" { path } : not a GGUF file" ) 73self .kv = []# (key, raw bytes of the whole entry) 74self .align = 32 75for _ in range (nkv ): 76start = self .f .tell () 77key = self ._str () 78t = struct .unpack ("<I" ,self .f .read (4 ))[0 ] 79val = self ._val (t ) 80raw_end = self .f .tell () 81self .f .seek (start ) 82raw = self .f .read (raw_end - start ) 83self .kv .append ((key ,raw )) 84if key == "general.alignment" : 85self .align = int (val ) 86self .tensors = [] 87for _ in range (nt ): 88name = self ._str () 89nd = struct .unpack ("<I" ,self .f .read (4 ))[0 ] 90dims = struct .unpack (f"< { nd } Q" ,self .f .read (8 * nd )) 91ty ,off = struct .unpack ("<IQ" ,self .f .read (12 )) 92self .tensors .append ({"name" :name ,"dims" :dims ,"type" :ty ,"off" :off }) 93pos = self .f .tell () 94self .data = (pos + self .align - 1 )// self .align * self .align 95for t in self .tensors : 96ne = 1 97for d in t ["dims" ]: 98ne *= d 99b ,q = TYPE_SIZE [t ["type" ]] 100t ["bytes" ]= ne // q * b 101t ["src" ]= self 102t ["abs" ]= self .data + t ["off" ] 103nocache (self .f )# the header is read; the tensors' bytes are read once, uncached 104 105def _str (self )-> str : 106n = struct .unpack ("<Q" ,self .f .read (8 ))[0 ] 107return self .f .read (n ).decode ("utf-8" ,"replace" ) 108 109def _val (self ,t ): 110sz = {0 :"B" ,1 :"b" ,2 :"H" ,3 :"h" ,4 :"I" ,5 :"i" ,6 :"f" ,7 :"?" ,10 :"Q" ,11 :"q" ,12 :"d" } 111if t == 8 : 112return self ._str () 113if t == 9 : 114at ,n = struct .unpack ("<IQ" ,self .f .read (12 )) 115return [self ._val (at )for _ in range (n )] 116return struct .unpack ("<" + sz [t ],self .f .read (struct .calcsize (sz [t ])))[0 ] 117 118 119def shard_paths (shard1 :Path )-> list [Path ]: 120m = re .match (r"(.*)-00001-of-(\d{5})\.gguf$" ,shard1 .name ) 121if not m : 122return [shard1 ] 123n = int (m .group (2 )) 124return [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 : 128h = hashlib .sha256 () 129f .seek (pos ) 130while n : 131buf = f .read (min (n ,CHUNK )) 132if not buf : 133break 134h .update (buf ) 135n -= len (buf ) 136return 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).""" 141bad = [] 142with open (out ,"rb" )as o : 143nocache (o ) 144r = Reader (out )# the output's own table, as a reader sees it 145table = {t ["name" ]:t for t in r .tensors } 146for i ,t in enumerate (order ): 147mine = table .get (t ["name" ]) 148if mine is None or mine ["abs" ]!= data0 + t ["new" ]or mine ["bytes" ]!= t ["bytes" ]or \ 149tensor_hash (o ,mine ["abs" ],t ["bytes" ])!= tensor_hash (t ["src" ].f ,t ["abs" ],t ["bytes" ]): 150bad .append (t ["name" ]) 151if i % 50 == 0 : 152f"\r verify { i + 1 } / { len ( order ) } " ,end = "" ,flush = True ) 153r .f .close () 154return bad 156 157 158def gguf_str (s :str )-> bytes : 159b = s .encode ("utf-8" ) 160return struct .pack ("<Q" ,len (b ))+ b 161 162 163def main ()-> int : 164ap = argparse .ArgumentParser (description = __doc__ .split ("\n\n" )[0 ]) 165ap .add_argument ("--shard1" ,required = True ,type = Path ) 166ap .add_argument ("--out" ,required = True ,type = Path ) 167ap .add_argument ("--verify" ,action = "store_true" ,help = "hash every tensor of the output against the source" ) 168a = ap .parse_args () 169shards = [Reader (p )for p in shard_paths (a .shard1 )] 170every = [t for s in shards for t in s .tensors ] 171ple = [t for t in every if t ["name" ]== PLE ] 172keep = [t for t in every if t ["name" ]!= PLE ] 173 174def layer_of (t ): 175m = re .match (r"blk\.(\d+)\." ,t ["name" ]) 176return int (m .group (1 ))if m else - 1 177dense = [t for t in keep if "_exps." not in t ["name" ]] 178role = {"ffn_gate_exps" :0 ,"ffn_up_exps" :1 ,"ffn_down_exps" :2 } 179exps = sorted ((t for t in keep if "_exps." in t ["name" ]), 180key = lambda t : (layer_of (t ),role .get (t ["name" ].split ("." )[2 ],9 ))) 181order = dense + exps 182kv = [raw for key ,raw in shards [0 ].kv if not key .startswith ("split." )and key != "general.alignment" ] 183kv .append (gguf_str ("general.alignment" )+ struct .pack ("<II" ,4 ,ALIGN )) 184off = 0 185infos = [] 186for t in order : 187t ["new" ]= off 188infos .append (gguf_str (t ["name" ])+ struct .pack ("<I" ,len (t ["dims" ]))+ 189struct .pack (f"< { len ( t [ 'dims' ]) } Q" ,* t ["dims" ])+ struct .pack ("<IQ" ,t ["type" ],off )) 190off = (off + t ["bytes" ]+ ALIGN - 1 )// ALIGN * ALIGN 191head = struct .pack ("<4sIQQ" ,b"GGUF" ,3 ,len (order ),len (kv ))+ b"" .join (kv )+ b"" .join (infos ) 192data0 = (len (head )+ ALIGN - 1 )// ALIGN * ALIGN 193total = data0 + off 194tmp = a .out .with_name (a .out .name + ".part" ) 195lock = a .out .with_name (a .out .name + LOCK_SUFFIX ) 196lock .write_text (str (os .getpid ())) 197atexit .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) 200with open (tmp ,"wb" ,buffering = 0 )as o : 201nocache (o ) 202write_all (o ,head ) 203write_all (o ,b"\0" * (data0 - len (head ))) 204done = 0 205since = 0 206for t in order : 207o .seek (data0 + t ["new" ]) 208src = t ["src" ].f 209src .seek (t ["abs" ]) 210left = t ["bytes" ] 211while left : 212buf = src .read (min (left ,CHUNK )) 213if not buf : 214sys .exit (f" { t [ 'src' ]. path } : short read in { t [ 'name' ] } " ) 215write_all (o ,buf ) 216left -= len (buf ) 217since += len (buf ) 218if since >= SYNC_EVERY : 219os .fsync (o .fileno ()) 220drop_cache (o ) 221drop_cache (src ) 222since = 0 223done += t ["bytes" ] 224if t is order [- 1 ]or t ["name" ].endswith ("ffn_down_exps.weight" ): 225f"\r { done / 2 ** 30 :6.1f } / { sum ( x [ 'bytes' ] for x in order ) / 2 ** 30 :.1f } GiB" ,end = "" ,flush = True ) 226o .truncate (total ) 227os .fsync (o .fileno ()) 228if a .verify : 230bad = verify (tmp ,data0 ,order ) 231if bad : 232tmp .unlink () 233sys .exit (f"verify FAILED: { len ( bad ) } tensors differ from the source, first { bad [ 0 ] } (output removed)" ) 234f"verify: { len ( order ) } tensors, SHA-256 identical to the source shards" ) 235os .replace (tmp ,a .out ) 236f" { a . out } : { len ( order ) } tensors ( { len ( dense ) } dense, { len ( exps ) } expert), { total / 2 ** 30 :.2f } GiB" ) 237if ple : 238f"n-gram table: { ple [ 0 ][ 'src' ]. path } " ) 239return 0 240 241 242if __name__ == "__main__" : 243sys .exit (main ())