#!/usr/bin/env python3 """Measure an explicitly limited real GGUF slice; keep all weights outside Git. The input may be a growing .part file. In that case --index-gguf is a sparse metadata-only copy with the GGUF's declared full length. The result is a provisional sample until the full source shard passes its manifest SHA-256. """ import argparse import hashlib import json import pathlib import re import struct import subprocess SAMPLES_SMALL = ( ("a-iq3-s.gguf", "blk.17.ffn_gate_exps.weight", 21, 110 * 262144), ("b-iq4-nl.gguf", "blk.0.ffn_down_shexp.weight", 20, 921600), ) SAMPLES_EXPERT = ( SAMPLES_SMALL[0], ("b-iq4-nl.gguf", "blk.0.ffn_down_exps.weight", 20, 18 * 1_600_000), ) SAMPLES_PER_LAYER = ( SAMPLES_SMALL[0], ("b-iq4-nl.gguf", "per_layer_token_embd.weight", 20, 18 * 1_600_000), ) BLOCK = {21: (256, 110), 20: (32, 18)} def digest(path: pathlib.Path) -> str: hasher = hashlib.sha256() with path.open("rb") as file: for chunk in iter(lambda: file.read(4 * 1024 * 1024), b""): hasher.update(chunk) return hasher.hexdigest() def gguf_shard(name: str, kind: int, payload: bytes) -> bytes: elements_per_block, block_bytes = BLOCK[kind] if len(payload) % block_bytes: raise ValueError("sample must end on a GGUF block boundary") header = bytearray(b"GGUF" + struct.pack(" None: encoded = value.encode() header.extend(struct.pack(" None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--binary", type=pathlib.Path, required=True) parser.add_argument("--source", type=pathlib.Path, required=True) parser.add_argument("--index-gguf", type=pathlib.Path) parser.add_argument("--second-source", type=pathlib.Path, help="second GGUF shard for the per-layer profile") parser.add_argument("--second-index-gguf", type=pathlib.Path, help="metadata-only copy while the second shard is partial") parser.add_argument("--second-source-sha256") parser.add_argument("--output-dir", type=pathlib.Path, required=True) parser.add_argument("--source-sha256", help="verify the complete source shard first") parser.add_argument("--profile", choices=("small", "expert", "per-layer"), default="small") parser.add_argument("--levels", type=int, default=2) args = parser.parse_args() binary = args.binary.resolve(strict=True) source = args.source.resolve(strict=True) index_gguf = (args.index_gguf or source).resolve(strict=True) if args.profile == "per-layer" and args.second_source is None: parser.error("--profile per-layer requires --second-source") second = args.second_source.resolve(strict=True) if args.second_source else None second_index = ((args.second_index_gguf or second).resolve(strict=True) if second else None) output = args.output_dir.resolve() repository = pathlib.Path(__file__).resolve().parent.parent if output == repository or repository in output.parents: parser.error("output must be outside the Git repository") if output.exists(): parser.error("output directory already exists") if args.source_sha256 and digest(source) != args.source_sha256.lower(): parser.error("source shard SHA-256 differs from expected") if second and args.second_source_sha256 and digest(second) != args.second_source_sha256.lower(): parser.error("second source shard SHA-256 differs from expected") for data_path, metadata_path in ((source, index_gguf), (second, second_index)): if data_path and metadata_path and data_path != metadata_path: with data_path.open("rb") as real, metadata_path.open("rb") as metadata: if real.read(1024 * 1024) != metadata.read(1024 * 1024): parser.error("metadata GGUF header differs from source") index = subprocess.run( [binary, "model", "index", index_gguf], capture_output=True, text=True, check=True, ) rows = {row["name"]: row for row in map(json.loads, index.stdout.splitlines())} second_rows = {} if second_index: second_listing = subprocess.run( [binary, "model", "index", second_index], capture_output=True, text=True, check=True, ) second_rows = {row["name"]: row for row in map(json.loads, second_listing.stdout.splitlines())} selected = [] samples = {"small": SAMPLES_SMALL, "expert": SAMPLES_EXPERT, "per-layer": SAMPLES_PER_LAYER}[args.profile] for number, (filename, name, kind, count) in enumerate(samples): data_path = second if args.profile == "per-layer" and number == 1 else source tensor = (second_rows if data_path == second and second else rows)[name] # `model index` prints an absolute GGUF file offset. offset = tensor["offset"] if tensor["type"] != kind or tensor["bytes"] < count or offset + count > data_path.stat().st_size: parser.error(f"{name}: kind, span, or downloaded extent differs") selected.append((filename, name, kind, count, offset, data_path)) output.mkdir(parents=True) files = [] sample_records = [] for filename, name, kind, count, offset, data_path in selected: with data_path.open("rb") as real: real.seek(offset) payload = real.read(count) if len(payload) != count: raise ValueError(f"{name}: truncated source slice") data = gguf_shard(name, kind, payload) path = output / filename path.write_bytes(data) sha256 = hashlib.sha256(data).hexdigest() files.append({"name": filename, "url": f"https://example.invalid/{filename}", "size": len(data), "sha256": sha256}) sample_records.append({"tensor": name, "source_shard": data_path.name, "kind": kind, "offset": offset, "payload_bytes": count, "slice_gguf_sha256": sha256}) manifest = output / "manifest.json" manifest.write_text(json.dumps({"schema_version": 1, "files": files}, indent=2) + "\n") archive = output / f"sample-l{args.levels}.kar" prepare = subprocess.run( [binary, "model", "prepare-sharded-streamed", manifest, "--source-dir", output, "--output", archive, "--levels", str(args.levels)], capture_output=True, text=True, check=True, ) subprocess.run( [binary, "model", "verify-sharded-streamed", archive, "--manifest", manifest, "--source-dir", output, "--levels", str(args.levels)], capture_output=True, text=True, check=True, ) source_bytes = sum(file["size"] for file in files) archive_bytes = archive.stat().st_size l2 = re.search(r"maximum tensor relative L2: ([0-9.]+)", prepare.stdout) print(json.dumps({ "source_verified": bool(args.source_sha256) and (args.profile != "per-layer" or bool(args.second_source_sha256)), "profile": args.profile, "samples": sample_records, "source_gguf_bytes": source_bytes, "archive_bytes": archive_bytes, "archive_to_source_ratio": archive_bytes / source_bytes, "archive_sha256": digest(archive), "maximum_tensor_relative_l2": float(l2.group(1)) if l2 else None, }, indent=2)) if __name__ == "__main__": main()