okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b0fc432ed
main
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 39data_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 : 52return name .startswith ("blk." )and name .endswith (EXPERT_RE ) 53 54 55def code_bits (form :str )-> int : 56return {"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 62This is Q2_0's own convention (4 codes per byte, byte j/4, bits (j%4)*2), kept for every form so the 63kernel has one unpacking loop rather than one per source type. 64""" 65flat = codes .reshape (- 1 ).astype (np .uint8 ) 66if bits == 8 : 67return flat .tobytes () 68per = 8 // bits 69if flat .size % per : 70raise ValueError ("code count %d is not a multiple of %d per byte" % (flat .size ,per )) 71g = flat .reshape (- 1 ,per ).astype (np .uint16 ) 72out = np .zeros (g .shape [0 ],dtype = np .uint16 ) 73for k in range (per ): 74out |= (g [:,k ]& ((1 << bits )- 1 ))<< (k * bits ) 75return out .astype (np .uint8 ).tobytes () 76 77 78def unpack_codes (buf :bytes ,bits :int ,n :int )-> np .ndarray : 79if bits == 8 : 80return np .frombuffer (buf ,dtype = np .uint8 )[:n ].copy () 81per = 8 // bits 82b = np .frombuffer (buf ,dtype = np .uint8 ) 83out = np .empty ((b .size ,per ),dtype = np .uint8 ) 84for k in range (per ): 85out [:,k ]= (b >> (k * bits ))& ((1 << bits )- 1 ) 86return 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).""" 91as16 = scales .astype (np .float16 ) 92if np .array_equal (as16 .astype (np .float32 ),scales ): 93return as16 .tobytes (),True 94return 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).""" 99m = MAPPINGS [tname ] 100parts = m .enc (raw ) 101if len (parts )== 3 : 102return parts [0 ],parts [1 ],parts [2 ],m 103return 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).""" 108m = MAPPINGS [tname ] 109 110body = bytearray () 111base = seg_offset 112 113def put (b :bytes )-> dict : 114nonlocal body 115pad = (- len (body ))% ALIGN 116body += b"\0" * pad 117off = base + len (body ) 118body += b 119return {"offset" :off ,"bytes" :len (b )} 120 121common = { 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 129if m .form in ("P16" ,"P32" ): 130vals = np .ascontiguousarray (m .dec (m .enc (raw )),dtype = np .float32 ).reshape (- 1 ) 131if m .form == "P32" : 132vb ,v16 = vals .astype ("<f4" ).tobytes (),False 133else : 134a16 = vals .astype (np .float16 ) 135if not np .array_equal (a16 .astype (np .float32 ),vals ): 136raise ValueError ("%s: P16 would lose precision, so this tensor needs P32" % name ) 137vb ,v16 = a16 .tobytes (),True 138ent = dict (common ,elements = int (vals .size ),values_fp16 = v16 ) 139ent ["values" ]= put (vb ) 140return bytes (body ),ent 141 142codes ,scales ,offsets ,m = canonicalise (name ,tname ,raw ) 143codes = np .ascontiguousarray (codes ) 144scales = np .ascontiguousarray (scales .reshape (- 1 ),dtype = np .float32 ) 145n_el = int (codes .size ) 146bits = code_bits (m .form ) 147codes_b = pack_codes (codes ,bits ) 148scales_b ,sc16 = choose_scale_dtype (scales ) 149 150ent = dict (common ,elements = n_el ,code_bits = bits ) 151ent ["codes" ]= put (codes_b ) 152ent ["scales" ]= put (scales_b ) 153ent ["scales_fp16" ]= sc16 154if offsets is not None : 155ob ,o16 = choose_scale_dtype (np .ascontiguousarray (offsets .reshape (- 1 ),dtype = np .float32 )) 156ent ["offsets" ]= put (ob ) 157ent ["offsets_fp16" ]= o16 158return 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 164Deliberately manifest-driven: if the manifest does not carry enough to decode the tensor, this cannot 165silently fall back on knowledge of the source type, and the omission becomes a failure here. 166""" 167if ent ["form" ]in ("P16" ,"P32" ): 168vb = head [ent ["values" ]["offset" ]:ent ["values" ]["offset" ]+ ent ["values" ]["bytes" ]] 169return np .frombuffer (vb ,dtype = "<f2" if ent ["values_fp16" ]else "<f4" ).astype (np .float32 ) 170 171n = ent ["elements" ] 172codes = unpack_codes (head [ent ["codes" ]["offset" ]:ent ["codes" ]["offset" ]+ ent ["codes" ]["bytes" ]], 173ent ["code_bits" ],n ) 174sc = head [ent ["scales" ]["offset" ]:ent ["scales" ]["offset" ]+ ent ["scales" ]["bytes" ]] 175sc = np .frombuffer (sc ,dtype = "<f2" if ent ["scales_fp16" ]else "<f4" ).astype (np .float32 ) 176if "offsets" in ent : 177ob = head [ent ["offsets" ]["offset" ]:ent ["offsets" ]["offset" ]+ ent ["offsets" ]["bytes" ]] 178off = np .frombuffer (ob ,dtype = "<f2" if ent .get ("offsets_fp16" )else "<f4" ).astype (np .float32 ) 179else : 180off = None 181if ent ["codebook" ]== "IQ4NL" : 182v = KV_IQ4NL [codes ] 183else : 184v = (codes .astype (np .int32 )+ ent ["code_bias" ]).astype (np .float32 ) 185g = ent ["group_elems" ] 186if g == 1 :# one scale for the whole tensor 187return (v * sc [0 ]).reshape (- 1 )if off is None else (v * sc [0 ]+ off [0 ]).reshape (- 1 ) 188out = v .reshape (- 1 ,g )* sc [:,None ] 189if off is not None : 190out = out + off [:,None ] 191return out .reshape (- 1 ) 192 193 194def sha256 (path :pathlib .Path ,chunk :int = 1 << 24 )-> str : 195h = hashlib .sha256 () 196with open (path ,"rb" )as f : 197while True : 198b = f .read (chunk ) 199if not b : 200break 201h .update (b ) 202return 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.""" 213for name in PACK_MARKERS : 214if (out_dir / name ).exists (): 215return out_dir / name 216return 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 222marker = None if force else occupied (out_dir )# --force: setup rebuilding a pack that lost index.txt or experts.bin 223if marker is not None : 224"%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 )) 226return 1 227out_dir .mkdir (parents = True ,exist_ok = True ) 228if 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. 233for name in PACK_MARKERS : 234 (out_dir / name ).unlink (missing_ok = True ) 235g = G .GGUFFile (gguf ) 236head ,flen = open_shard (gguf ) 237data_off = data_section_offset (g ,flen ) 238"source %s: %d tensors, data at %d" % (gguf .name ,len (g .tensors ),data_off )) 239 240n_layers = 48 if n_layers is None else n_layers 241man = { 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 253PL .SHARD1 = pathlib .Path (gguf ).resolve () 254shard2 = pathlib .Path (str (PL .SHARD1 ).replace ("00001-of-00002" ,"00002-of-00002" )) 255man ["source" ]["shard2" ]= str (shard2 ) 256exp_path = out_dir / "experts.bin" 257"experts.bin: %d layers, %.2f GiB" % (n_layers ,n_layers * PL .NE * PL .BLOB_BYTES / 2 ** 30 )) 258em = PL .build (n_layers ,exp_path ) 259man ["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 264dense = [] 265embd = [] 266for t in g .tensors : 267if is_expert (t .name ): 268continue 269 (embd if t .name == EMBD_NAME else dense ).append (t ) 270 271for fname ,group in (("dense.bin" ,dense ), ("embd.bin" ,embd )): 272path = out_dir / fname 273seg_base = 0 274with open (path ,"wb" )as fh : 275for t in group : 276if t .type_name not in MAPPINGS : 277" %s: NO MAPPING for %s - refusing to build" % (t .name ,t .type_name )) 278return 1 279raw = head [data_off + t .offset :data_off + t .offset + (t .expected_bytes ()or 0 )] 280if len (raw )!= (t .expected_bytes ()or 0 ): 281" %s: SHORT READ - refusing to build" % t .name ) 282return 1 283blob ,ent = tensor_entry (t .name ,t ,t .type_name ,raw ,seg_base ) 284ent ["file" ]= fname 285fh .write (blob ) 286seg_base += len (blob ) 287man ["tensors" ][t .name ]= ent 288"%s: %d tensors, %.2f GiB" % (fname ,len (group ),path .stat ().st_size / 2 ** 30 )) 289 290man ["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 } 293if not skip_hash : 294"hashing shards (this is the slow part)..." ) 295man ["source" ]["shard1_sha256" ]= sha256 (gguf ) 296man ["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 298if shard2 .exists (): 299g2 = G .GGUFFile (shard2 ) 300t2 = [t for t in g2 .tensors if t .name == "per_layer_token_embd.weight" ][0 ] 301man ["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"manifest.json: %d tensor entries" % len (man ["tensors" ])) 306return 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 312The arena stores codes and scales in SEPARATE PLANES and interleaves gate/up ROWS (g0,u0,g1,u1,...), so 313a verifier that cannot invert that cannot check the arena. Written as the inverse on purpose: this is 314the only independent statement about the blob layout in the tree, and if it and `pack_layer` were the 315same code the arena would be unverified by construction. 316""" 317O ,out = PL .OFF ,bytearray () 318n_blk = PL .H * PL .FF // PL .QK 319for blk in range (n_blk ): 320if role == "down" : 321row ,b_in = blk // PL .SCALES_D ,blk % PL .SCALES_D 322co = O ["down_codes" ]+ row * PL .ROW_BYTES_D + b_in * 16 323so = O ["down_scales" ]+ (row * PL .SCALES_D + b_in )* 2 324else : 325row ,b_in = blk // PL .SCALES_GU ,blk % PL .SCALES_GU 326slot = 2 * row + (0 if role == "gate" else 1 ) 327co = O ["gate_up_codes" ]+ slot * PL .ROW_BYTES_GU + b_in * 16 328so = O ["gate_up_scales" ]+ (slot * PL .SCALES_GU + b_in )* 2 329out += blob [so :so + 2 ]# fp16 d first, as block_q2_0 has it 330out += blob [co :co + 16 ]# then the 16 packed code bytes 331return 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.""" 336g = G .GGUFFile (gguf ) 337head ,flen = open_shard (gguf ) 338data_off = data_section_offset (g ,flen ) 339by_name = {t .name :t for t in g .tensors } 340exp_mm ,_ = open_shard (out_dir / "experts.bin" ) 341blob = man ["experts" ]["blob_bytes" ] 342n_layers = man ["n_layers" ] 343checked = bad = 0 344for layer in range (n_layers ): 345for e in range (0 ,PL .NE ,every ): 346base = (layer * PL .NE + e )* blob 347b = exp_mm [base :base + blob ] 348for role in ("gate" ,"up" ,"down" ): 349t = by_name ["blk.%d.ffn_%s_exps.weight" % (layer ,role )] 350per_expert = t .elements // PL .NE 351nbytes = per_expert * PL .BLOCK_BYTES // PL .QK 352src = head [data_off + t .offset + e * nbytes :data_off + t .offset + (e + 1 )* nbytes ] 353ref = reference_values ("Q2_0" ,src ) 354got = MAPPINGS ["Q2_0" ].dec (canonicalise (t .name ,"Q2_0" ,rebuild_role (b ,role ))[:2 ]) 355checked += 1 356if not np .array_equal (ref ,got ): 357" layer %d expert %d %-4s *** MISMATCH *** max|d| %.3e" 358% (layer ,e ,role ,np .abs (ref .astype (np .float64 )- got .astype (np .float64 )).max ())) 359bad += 1 360"experts: %d layer/expert/role checks (%d layers, every %dth expert), %d bad" 361% (checked ,n_layers ,every ,bad )) 362return 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.""" 367man = 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. 370want = (man .get ("source" )or {}).get ("shard1_sha256" ) 371if want and limit is None : 372got = sha256 (gguf ) 373if got != want : 374"%s: sha256 %s, but the pack was built from %s" % (gguf .name ,got ,want )) 375"tools/strata_pack.py verify FAIL" ) 376return 1 377g = G .GGUFFile (gguf ) 378head ,flen = open_shard (gguf ) 379data_off = data_section_offset (g ,flen ) 380by_name = {t .name :t for t in g .tensors } 381files = {} 382bad = 0 383n_t = n_el = 0 384for i , (name ,ent )in enumerate (sorted (man ["tensors" ].items ())): 385if limit is not None and i >= limit : 386break 387if ent ["file" ]not in files : 388files [ent ["file" ]]= open_shard (out_dir / ent ["file" ])[0 ] 389t = by_name [name ] 390raw = head [data_off + t .offset :data_off + t .offset + (t .expected_bytes ()or 0 )] 391ref = reference_values (t .type_name ,raw ) 392got = decode_entry (files [ent ["file" ]],ent ) 393n_t += 1 394n_el += ref .size 395if ref .shape != got .shape or not np .array_equal (ref ,got ): 396d = np .abs (ref .astype (np .float64 )- got .astype (np .float64 ))if ref .shape == got .shape else None 397" %-40s *** MISMATCH *** %s" % (name , ("max|d| %.3e" % d .max ())if d is not None else 398"shape %s vs %s" % (ref .shape ,got .shape ))) 399bad += 1 400elif i < 3 or i % 200 == 0 : 401" %-40s bit-exact (%d elements, %s)" % (name ,ref .size ,ent ["form" ])) 402"verify: %d tensors, %d elements, %d bad" % (n_t ,n_el ,bad )) 404if expert_every > 0 : 405bad += verify_experts (gguf ,out_dir ,man ,expert_every ) 406"tools/strata_pack.py verify " + ("PASS" if bad == 0 else "FAIL" )) 407return 0 if bad == 0 else 1 408 409 410def info (out_dir :pathlib .Path )-> int : 411man = json .loads ((out_dir / "manifest.json" ).read_text (encoding = "utf-8" )) 412"strata-pack v%d layers=%d" % (man ["format_version" ],man ["n_layers" ])) 413for f ,n in man .get ("files" , {}).items (): 414" %-12s %12.3f GiB" % (f ,n / 2 ** 30 )) 415forms = {} 416for e in man ["tensors" ].values (): 417forms [e ["form" ]]= forms .get (e ["form" ],0 )+ 1 418" dense/embd by form: %s" % ", " .join ("%s=%d" % kv for kv in sorted (forms .items ()))) 419" experts: %d blobs x %d B, %s" % (man ["experts" ]["layers" ].__len__ ()* man ["n_experts_per_layer" ], 420man ["experts" ]["blob_bytes" ],man ["experts" ]["source_type" ])) 421return 0 422 423 424def main ()-> int : 425ap = argparse .ArgumentParser () 426sub = ap .add_subparsers (dest = "cmd" ,required = True ) 427b = sub .add_parser ("build" ) 428b .add_argument ("--gguf" ,required = True ) 429b .add_argument ("--out" ,required = True ) 430b .add_argument ("--layers" ,type = int ,default = None ,help = "expert layers to emit (default 48)" ) 431b .add_argument ("--skip-hash" ,action = "store_true" ) 432b .add_argument ("--force" ,action = "store_true" ,help = "build into a directory that already holds a pack, unmaking that pack first (#634)" ) 433v = sub .add_parser ("verify" ) 434v .add_argument ("--gguf" ,required = True ) 435v .add_argument ("--out" ,required = True ) 436v .add_argument ("--limit" ,type = int ,default = None ) 437v .add_argument ("--expert-every" ,type = int ,default = 32 , 438help = "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)" ) 440n = sub .add_parser ("info" ) 441n .add_argument ("--out" ,required = True ) 442args = ap .parse_args () 443if args .cmd == "build" : 444return build (pathlib .Path (args .gguf ),pathlib .Path (args .out ),args .layers ,args .skip_hash ,args .force ) 445if args .cmd == "verify" : 446return verify (pathlib .Path (args .gguf ),pathlib .Path (args .out ),args .limit ,args .expert_every ) 447return info (pathlib .Path (args .out )) 448 449 450if __name__ == "__main__" : 451raise SystemExit (main ())