Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

tools: whole-artifact digests in repack-manifest.json + verify-side check

monotophiccc4a589797cc
diff --git a/c/tests/test_rans_repack.py b/c/tests/test_rans_repack.py
index 544e79c5..d6f5875c 100644
--- a/c/tests/test_rans_repack.py
+++ b/c/tests/test_rans_repack.py
@@ -140,7 +140,13 @@ class TestRansRepack(unittest.TestCase):
self.assertIn("RESULT: TRUST", r.stdout)
def _reshard(self, shard, meta_mutator=None, tensor_mutator=None):
- """Read a shard fully, apply mutators, rewrite it deterministically."""
+ """Read a shard fully, apply mutators, rewrite it deterministically.
+ Drops the manifest sitting next to it: the battery tests the
+ PER-RECORD layer, which must hold even when an attacker removes the
+ whole-artifact manifest (digest tampering has its own test)."""
+ manifest = shard.parent / "repack-manifest.json"
+ if manifest.exists():
+ manifest.unlink()
header, data_start = rf.read_header(str(shard))
meta = dict(header["__metadata__"])
tensors = []
@@ -471,6 +477,138 @@ class TestRansRepack(unittest.TestCase):
fresh = self.repack(self.root / "partial_fresh")
self.assertEqual(shards[0].read_bytes(), fresh[0].read_bytes())
+ def test_manifest_digests(self):
+ """Whole-artifact digest layer: mint-time digests verify green; a
+ tampered record bites as E_DIGEST_MISMATCH; retro --manifest-only
+ reproduces the mint manifest byte-for-byte; a digest-less manifest
+ (older mint) means note-and-proceed, never an error."""
+ import hashlib
+ out = self.root / "digests"
+ shard = self.repack(out)[0]
+ manifest = out / "repack-manifest.json"
+ man = json.loads(manifest.read_text())
+
+ # every weight record has a digest, and it matches the bytes on disk;
+ # the whole-file sha256 matches the complete shard bytes
+ header, data_start = rf.read_header(str(shard))
+ recs = man["shards"][0]["records"]
+ self.assertEqual(sorted(recs), sorted(self.weights))
+ for name, want in recs.items():
+ blob, _ = rf.read_tensor_bytes(str(shard), header, data_start, name)
+ self.assertEqual(hashlib.sha256(blob).hexdigest(), want, name)
+ self.assertEqual(man["shards"][0]["sha256"],
+ hashlib.sha256(shard.read_bytes()).hexdigest())
+
+ # verify green, and it says both digest layers were actually checked
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+ self.assertIn("file digest checked", r.stdout)
+ self.assertIn("record digests checked", r.stdout)
+
+ # retro equivalence: --manifest-only over the minted dir must
+ # reproduce the manifest byte-for-byte (fields preserved, digests
+ # recomputed identical)
+ mint_bytes = manifest.read_bytes()
+ r = run_tool("repack_rans.py", "--manifest-only", str(out))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+ self.assertEqual(manifest.read_bytes(), mint_bytes)
+
+ # retro from scratch (manifest deleted): digests must equal the
+ # mint-time ones; provenance-only fields (source) are unknowable
+ manifest.unlink()
+ r = run_tool("repack_rans.py", "--manifest-only", str(out))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+ # provenance loss is visible in output, not just by field absence
+ self.assertIn("provenance is unknowable in retro mode", r.stderr)
+ man2 = json.loads(manifest.read_text())
+ self.assertEqual(man2["shards"][0]["records"], recs)
+ self.assertEqual(man2["shards"][0]["sha256"], man["shards"][0]["sha256"])
+ self.assertEqual(man2["table_crc32"], man["table_crc32"])
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+
+ # tamper bite A: flip one payload byte of a digested record IN THE
+ # SHARD FILE (manifest untouched) -> the whole-file gate fires AND
+ # the per-record layer localizes it to the tensor
+ target = sorted(recs)[0]
+ b, e = header[target]["data_offsets"]
+ raw = bytearray(shard.read_bytes())
+ raw[data_start + b + rf.record_header_bytes() + 3] ^= 0x40
+ shard.write_bytes(bytes(raw))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 1, msg=r.stdout)
+ self.assertIn("E_SHARD_DIGEST_MISMATCH", r.stdout)
+ self.assertIn("E_DIGEST_MISMATCH", r.stdout)
+
+ # tamper bite B β€” the exact gap the whole-file hash closes: flip a
+ # byte inside a .qs SIDECAR (raw passthrough; not covered by any
+ # record digest or record invariant). Only the file-level gate can
+ # see it: E_SHARD_DIGEST_MISMATCH fires, and NO record-level digest
+ # refusal appears (every record is intact)
+ raw[data_start + b + rf.record_header_bytes() + 3] ^= 0x40 # restore
+ qs_b, qs_e = header[target + ".qs"]["data_offsets"]
+ raw[data_start + qs_b + 1] ^= 0x01
+ shard.write_bytes(bytes(raw))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 1, msg=r.stdout)
+ self.assertIn("E_SHARD_DIGEST_MISMATCH", r.stdout)
+ self.assertNotIn("E_DIGEST_MISMATCH:", r.stdout.replace(
+ "E_SHARD_DIGEST_MISMATCH:", ""))
+ raw[data_start + qs_b + 1] ^= 0x01 # restore
+ shard.write_bytes(bytes(raw))
+
+ # backward compat: a manifest WITHOUT digest evidence (older mint)
+ # is note-and-proceed
+ for entry in man["shards"]:
+ del entry["records"]
+ del entry["sha256"]
+ manifest.write_text(json.dumps(man, indent=1, sort_keys=True))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+ self.assertIn("carries no digests", r.stdout)
+ self.assertIn("file digest unavailable", r.stdout)
+ self.assertIn("record digests unavailable", r.stdout)
+
+ # degraded mid-state: file sha present, records absent -> the file
+ # gate still runs (green here), record layer notes-and-skips
+ for entry, src in zip(man["shards"], man2["shards"]):
+ entry["sha256"] = src["sha256"]
+ manifest.write_text(json.dumps(man, indent=1, sort_keys=True))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 0, msg=r.stdout + r.stderr)
+ self.assertIn("file digest checked", r.stdout)
+ self.assertIn("no record digests", r.stdout)
+
+ # a corrupt manifest is refused by name, not skipped
+ manifest.write_text("{not json")
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 1, msg=r.stdout)
+ self.assertIn("E_MANIFEST_MALFORMED", r.stdout)
+ self.assertNotIn("Traceback", r.stderr)
+
+ # malformed-typed digest fields must be malformation even when the
+ # malformation removes ALL digest evidence β€” an entry whose only
+ # digest fields are wrong-typed must never be classed as a
+ # digest-less older mint (note + TRUST)
+ for corpse in (
+ {"shards": [{"file": shard.name, "sha256": 12345}]},
+ {"shards": [{"file": shard.name, "records": ["a"]}]},
+ ):
+ manifest.write_text(json.dumps(corpse, sort_keys=True))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 1, msg=f"{corpse}\n{r.stdout}")
+ self.assertIn("E_MANIFEST_MALFORMED", r.stdout, msg=str(corpse))
+ self.assertNotIn("RESULT: TRUST", r.stdout, msg=str(corpse))
+ self.assertNotIn("Traceback", r.stderr, msg=str(corpse))
+
+ # digests present but this shard missing from the set -> refusal
+ manifest.write_text(json.dumps(
+ {"shards": [{"file": "out-rans-99999.safetensors",
+ "records": {"x": "0" * 64}}]}, sort_keys=True))
+ r = run_tool("rans_verify.py", str(shard))
+ self.assertEqual(r.returncode, 1, msg=r.stdout)
+ self.assertIn("E_DIGEST_MISSING", r.stdout)
+
def test_quantize_freq_ties_and_termination(self):
"""Exact fractional-remainder ties must break identically everywhere
(stable argsort -> lowest symbol index wins), and an impossible table
diff --git a/c/tools/rans_format.py b/c/tools/rans_format.py
index 4c6e3614..29033025 100644
--- a/c/tools/rans_format.py
+++ b/c/tools/rans_format.py
@@ -29,6 +29,7 @@ the remainder by largest fractional part.
"""
import base64
import ctypes
+import hashlib
import json
import os
import struct
@@ -540,7 +541,10 @@ def read_tensor_bytes(path, header, data_start, name):
def write_shard(path, tensors, metadata):
"""tensors: list of (name, dtype, shape, bytes) β€” written in the given
order; metadata: {str: str}. Fully deterministic byte layout (sorted
- metadata keys, insertion-ordered tensors, no timestamps)."""
+ metadata keys, insertion-ordered tensors, no timestamps). Returns the
+ sha256 hex of the COMPLETE file bytes, computed while streaming the
+ write (before the atomic rename) β€” the whole-file digest the manifest
+ records."""
header = {"__metadata__": {k: metadata[k] for k in sorted(metadata)}}
offset = 0
for name, dtype, shape, raw in tensors:
@@ -548,10 +552,26 @@ def write_shard(path, tensors, metadata):
"data_offsets": [offset, offset + len(raw)]}
offset += len(raw)
hjson = json.dumps(header, separators=(",", ":"), sort_keys=False).encode()
+ h = hashlib.sha256()
tmp = path + ".tmp"
with open(tmp, "wb") as f:
- f.write(struct.pack("<Q", len(hjson)))
- f.write(hjson)
+ for chunk in (struct.pack("<Q", len(hjson)), hjson):
+ f.write(chunk)
+ h.update(chunk)
for _, _, _, raw in tensors:
f.write(raw)
+ h.update(raw)
os.replace(tmp, path)
+ return h.hexdigest()
+
+
+def sha256_file(path, bufsize=1 << 20):
+ """sha256 hex of a whole file, chunked (shards can be GB-scale)."""
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ while True:
+ chunk = f.read(bufsize)
+ if not chunk:
+ break
+ h.update(chunk)
+ return h.hexdigest()
diff --git a/c/tools/rans_verify.py b/c/tools/rans_verify.py
index efe692dd..81cc5fda 100644
--- a/c/tools/rans_verify.py
+++ b/c/tools/rans_verify.py
@@ -46,6 +46,31 @@ WHAT IS CHECKED, per shard:
shard's own table must reproduce the record byte-for-byte
(E_REENCODE_MISMATCH) β€” the writer is deterministic, so any surviving
divergence is corruption the invariants above happened to miss.
+ whole-artifact layer (repack-manifest.json next to the shards, written by
+ repack_rans.py; per-shard whole-file sha256 + per-record sha256 digests):
+ E_MANIFEST_MALFORMED a manifest file exists but cannot be parsed as
+ the expected JSON shape β€” refused rather than
+ treated as "no manifest", since a corrupted
+ manifest is itself evidence of tampering
+ E_SHARD_DIGEST_MISMATCH the complete shard file does not hash to the
+ digest the mint run recorded β€” checked FIRST;
+ covers .qs sidecars, headers and padding, which
+ the per-record map cannot see. On mismatch the
+ per-record layer still runs, to localize the
+ damage when it sits inside a record
+ E_DIGEST_MISSING the manifest carries digests but not for this
+ shard or this stamped tensor (a record the
+ mint run never produced)
+ E_DIGEST_MISMATCH a record's bytes do not hash to the digest the
+ mint run recorded β€” the wrong-checkpoint /
+ swapped-record case per-record checks alone
+ cannot see
+ No manifest, or a manifest without digest maps, means NO check is
+ possible (older mint runs): a note is printed and per-record
+ verification proceeds β€” never an error. This layer checks BUILD
+ integrity (these exact bytes came from that mint run); container
+ identity proper is the stamp/registry lineage, and the consumer-side
+ load check ships with the consumer PR.
Exit status: 0 = every named shard TRUSTED; 1 = at least one refusal
(each printed as `REFUSE <shard> <tensor|-> <CLASS>: detail`); 2 = usage.
@@ -58,6 +83,7 @@ Usage:
python3 tools/rans_verify.py --max-tensors 8 <shard> # sampled quick look
"""
import argparse
+import hashlib
import json
import os
import sys
@@ -71,6 +97,70 @@ def refuse(failures, shard, tensor, code, detail):
failures.append((shard, tensor, code))
+def load_manifest_digests(shard_path):
+ """Digest evidence for one shard from the repack-manifest.json next to
+ it. Returns (file_sha256-or-None, records-map-or-None, notes:list);
+ raises RansRefusal E_MANIFEST_MALFORMED when a manifest exists but is
+ not the expected shape (a corrupt manifest is evidence, not an excuse
+ to skip checks), and E_DIGEST_MISSING when the manifest carries digest
+ evidence but no entry for this shard."""
+ mpath = os.path.join(os.path.dirname(os.path.abspath(shard_path)),
+ "repack-manifest.json")
+ if not os.path.exists(mpath):
+ return None, None, ["no repack-manifest.json β€” whole-artifact digest "
+ "check skipped"]
+ try:
+ with open(mpath) as fh:
+ man = json.load(fh)
+ if not isinstance(man, dict) or not isinstance(man.get("shards"), list):
+ raise ValueError("not the expected {.., shards: [..]} object")
+ entries = man["shards"]
+ except (OSError, ValueError) as exc:
+ raise rf.RansRefusal("E_MANIFEST_MALFORMED",
+ f"repack-manifest.json unreadable: {exc}")
+ # type-validate EVERY entry's shape unconditionally, BEFORE the evidence
+ # scan: a wrong-typed sha256/records field is malformation regardless of
+ # whether any valid evidence remains elsewhere β€” otherwise an entry
+ # whose only digest fields are malformed-typed would zero the evidence
+ # scan and be silently classed as a digest-less older mint
+ for i, e in enumerate(entries):
+ if not isinstance(e, dict):
+ raise rf.RansRefusal("E_MANIFEST_MALFORMED",
+ f"shards[{i}] is not an object")
+ sha = e.get("sha256")
+ if sha is not None and not isinstance(sha, str):
+ raise rf.RansRefusal("E_MANIFEST_MALFORMED",
+ f"shards[{i}].sha256 is not a string")
+ rec = e.get("records")
+ if rec is not None and (not isinstance(rec, dict) or
+ not all(isinstance(k, str) and isinstance(v, str)
+ for k, v in rec.items())):
+ raise rf.RansRefusal("E_MANIFEST_MALFORMED",
+ f"shards[{i}].records is not a str->str map")
+ any_evidence = any(e.get("records") is not None or
+ e.get("sha256") is not None for e in entries)
+ if not any_evidence:
+ return None, None, ["repack-manifest.json carries no digests "
+ "(older mint) β€” whole-artifact digest check skipped"]
+ base = os.path.basename(shard_path)
+ for e in entries:
+ if e.get("file") != base:
+ continue
+ sha = e.get("sha256")
+ rec = e.get("records")
+ notes = []
+ if sha is None:
+ notes.append("manifest entry has no whole-file sha256 β€” "
+ "file-level check skipped")
+ if rec is None:
+ notes.append("manifest entry has no record digests β€” "
+ "record-level digest check skipped")
+ return sha, rec, notes
+ raise rf.RansRefusal("E_DIGEST_MISSING",
+ f"manifest carries digests but no entry for {base} β€” "
+ f"this shard is not part of the minted set")
+
+
def verify_shard(path, failures, max_tensors=None):
"""One shard. Wrapped by main()'s catch-all so no input can escape as a
traceback; rf.read_header pins the whole header shape by name first."""
@@ -116,6 +206,24 @@ def verify_shard(path, failures, max_tensors=None):
refuse(failures, path, None, exc.code, exc.detail)
return
+ try:
+ file_sha, digests, digest_notes = load_manifest_digests(path)
+ except rf.RansRefusal as exc:
+ refuse(failures, path, None, exc.code, exc.detail)
+ return
+ for note in digest_notes:
+ print(f"[note] {os.path.basename(path)}: {note}")
+ if file_sha is not None:
+ # whole-file gate FIRST (cheapest whole-artifact check; covers .qs
+ # sidecars, headers and padding the per-record map cannot see); on
+ # mismatch, continue into the per-record layer so the refusal gets
+ # localized to a tensor when the damage is inside a record
+ got = rf.sha256_file(path)
+ if got != file_sha:
+ refuse(failures, path, None, "E_SHARD_DIGEST_MISMATCH",
+ f"file hashes {got[:16]}…, manifest recorded "
+ f"{file_sha[:16]}… β€” shard bytes differ from the mint run")
+
checked = 0
trusted = 0
for name in ours:
@@ -133,6 +241,20 @@ def verify_shard(path, failures, max_tensors=None):
raise rf.RansRefusal("E_STAMP_DTYPE",
f"dtype {info['dtype']} != U8")
blob, _ = rf.read_tensor_bytes(path, header, data_start, name)
+ if digests is not None:
+ # whole-artifact check first: the swapped-valid-record case
+ # every per-record invariant below is structurally blind to
+ if name not in digests:
+ raise rf.RansRefusal(
+ "E_DIGEST_MISSING",
+ "manifest carries digests but none for this tensor β€” "
+ "a record the mint run never produced")
+ got = hashlib.sha256(blob).hexdigest()
+ if got != digests[name]:
+ raise rf.RansRefusal(
+ "E_DIGEST_MISMATCH",
+ f"record hashes {got[:16]}…, manifest recorded "
+ f"{digests[name][:16]}… β€” bytes differ from the mint run")
packed = rf.decode_record(blob, table)
# deterministic re-encode cross-check
re_rec = rf.build_record(rf.unpack_nibbles(packed), table["freq"],
@@ -153,7 +275,10 @@ def verify_shard(path, failures, max_tensors=None):
trusted += 1
print(f"[trust] {os.path.basename(path)}: {trusted}/{checked} verified "
f"tensor(s) byte-exact (table_id={table['table_id']}, "
- f"codec={'C' if rf.LIB else 'python'})")
+ f"codec={'C' if rf.LIB else 'python'}, file digest "
+ f"{'checked' if file_sha is not None else 'unavailable'}, "
+ f"record digests "
+ f"{'checked' if digests is not None else 'unavailable'})")
def main():
diff --git a/c/tools/repack_rans.py b/c/tools/repack_rans.py
index df87dd7d..4bb91a67 100644
--- a/c/tools/repack_rans.py
+++ b/c/tools/repack_rans.py
@@ -40,12 +40,32 @@ Build `make rans` first for the C codec (tools/librans_c.*); without it this
tool falls back to a pure-Python codec that emits the same bytes orders of
magnitude slower (fine for the test fixtures, not for a real container).
+WHOLE-ARTIFACT DIGESTS: repack-manifest.json carries, per output shard,
+BOTH a whole-file `sha256` (the complete .safetensors bytes, hashed while
+streaming the write before the atomic rename β€” subsumes .qs sidecars,
+headers, and padding) AND a `records` map β€” original tensor name -> sha256
+of the emitted RECORD bytes (the U8 blob exactly as written) for granular
+diagnosis. The record wire format is untouched (sidecar-file fields only).
+rans_verify.py checks the file hash first, then records, when the manifest
+sits next to the shards; a manifest without digests (or no manifest) means
+"no check possible", never an error.
+`--manifest-only <dir>` regenerates the manifest for an ALREADY-minted
+output directory by hashing the existing shards in place (no re-encoding);
+it preserves every field of an existing manifest and only recomputes the
+digest maps, so retro output is byte-identical to mint output for the same
+shards. This mode lives HERE and not in rans_verify.py deliberately: the
+manifest is the writer's completion/provenance artifact, and the verifier
+stays side-effect-free β€” a tool you point at a stranger's download must
+never write into it.
+
Usage:
python3 tools/repack_rans.py --indir <int4_dir> --outdir <out> --dry-run
python3 tools/repack_rans.py --indir <int4_dir> --outdir <out> [--layers 20,55]
+ python3 tools/repack_rans.py --manifest-only <outdir>
"""
import argparse
import glob
+import hashlib
import json
import os
import re
@@ -160,12 +180,114 @@ def select_targets(index, layers):
return selected
+def write_manifest(manifest_path, manifest):
+ """Deterministic manifest write (sorted keys, no timestamps), atomic."""
+ tmp = manifest_path + ".tmp"
+ with open(tmp, "w") as fh:
+ json.dump(manifest, fh, indent=1, sort_keys=True)
+ os.replace(tmp, manifest_path)
+
+
+def shard_record_digests(path):
+ """Hash every stamped record in one emitted shard: {name: sha256hex}.
+ Returns (digests, n_bytes). Read-only with respect to the shard."""
+ header, data_start = rf.read_header(path)
+ meta = header.get("__metadata__", {})
+ try:
+ fmt_map = json.loads(meta.get(rf.METADATA_KEY, "{}"))
+ except ValueError:
+ fmt_map = {}
+ digests = {}
+ for name in sorted(n for n, v in fmt_map.items()
+ if v == rf.FORMAT_NAME and n in header):
+ blob, _ = rf.read_tensor_bytes(path, header, data_start, name)
+ digests[name] = hashlib.sha256(blob).hexdigest()
+ return digests, os.path.getsize(path)
+
+
+def manifest_only(outdir):
+ """Retro-manifest: (re)generate repack-manifest.json for an already-
+ minted output directory by hashing the existing shards in place β€” no
+ re-encoding. Preserves every field of an existing manifest and only
+ recomputes the per-shard digest maps, so the result is byte-identical
+ to what a fresh mint of the same shards writes."""
+ shards = sorted(glob.glob(os.path.join(outdir, "out-rans-*.safetensors")))
+ if not shards:
+ print(f"ERROR: no out-rans-*.safetensors under {outdir} β€” nothing to "
+ f"manifest", file=sys.stderr)
+ sys.exit(1)
+ manifest_path = os.path.join(outdir, "repack-manifest.json")
+ existing = {}
+ if os.path.exists(manifest_path):
+ try:
+ with open(manifest_path) as fh:
+ existing = json.load(fh)
+ if not isinstance(existing, dict):
+ raise ValueError("manifest is not a JSON object")
+ except (OSError, ValueError) as exc:
+ print(f"ERROR: existing {manifest_path} is unreadable ({exc}) β€” "
+ f"remove it first if a rebuild from the shards is intended",
+ file=sys.stderr)
+ sys.exit(1)
+ by_file = {e.get("file"): e for e in existing.get("shards", [])
+ if isinstance(e, dict)}
+
+ entries = []
+ total_records = 0
+ fmt_seen = None
+ crc_seen = None
+ for p in shards:
+ base = os.path.basename(p)
+ digests, nbytes = shard_record_digests(p)
+ if not digests:
+ print(f"ERROR: {base} carries no {rf.FORMAT_NAME} stamps β€” not an "
+ f"entropy container this tool minted", file=sys.stderr)
+ sys.exit(1)
+ header, _ = rf.read_header(p)
+ meta = header.get("__metadata__", {})
+ try:
+ crc_seen = json.loads(meta[rf.TABLE_KEY]).get("table_crc32", crc_seen)
+ except (KeyError, ValueError):
+ pass
+ fmt_seen = rf.FORMAT_NAME
+ prior = by_file.get(base)
+ if prior is None or "source" not in prior:
+ # visible in output, not just by field absence: retro mode cannot
+ # reconstruct mint-time provenance
+ print(f"[manifest] warning: {base}: no prior manifest entry β€” "
+ f"`source` provenance is unknowable in retro mode and is "
+ f"omitted", file=sys.stderr)
+ entry = dict(prior or {})
+ entry.update({
+ "file": base,
+ "bytes": nbytes,
+ "weight_tensors": len(digests),
+ "sha256": rf.sha256_file(p), # whole-file: subsumes .qs/header/pad
+ "records": digests,
+ })
+ entries.append(entry)
+ total_records += len(digests)
+ print(f"[manifest] {base}: {len(digests)} record digest(s)")
+
+ manifest = dict(existing)
+ manifest.update({
+ "format": existing.get("format", fmt_seen),
+ "table_crc32": existing.get("table_crc32", crc_seen),
+ "n_shards": len(entries),
+ "n_weight_tensors": total_records,
+ "shards": entries,
+ })
+ write_manifest(manifest_path, manifest)
+ print(f"[manifest] wrote {manifest_path}: {len(entries)} shard(s), "
+ f"{total_records} record digest(s)")
+
+
def main():
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
- ap.add_argument("--indir", required=True,
+ ap.add_argument("--indir",
help="directory of per-row-int4 *.safetensors shards")
- ap.add_argument("--outdir", required=True,
+ ap.add_argument("--outdir",
help="destination for the entropy-coded container shards")
ap.add_argument("--layers",
help="comma-separated layer subset (default: every layer)")
@@ -175,8 +297,22 @@ def main():
help="overwrite an outdir that already contains repack output "
"(default: refuse β€” a pre-existing partial set from an "
"interrupted run must never be silently papered over)")
+ ap.add_argument("--manifest-only", metavar="DIR",
+ help="regenerate repack-manifest.json (incl. per-record "
+ "sha256 digests) for an already-minted output "
+ "directory, hashing shards in place β€” no re-encoding")
a = ap.parse_args()
+ if a.manifest_only:
+ if a.indir or a.outdir:
+ print("ERROR: --manifest-only takes no --indir/--outdir",
+ file=sys.stderr)
+ sys.exit(2)
+ manifest_only(a.manifest_only)
+ return
+ if not a.indir or not a.outdir:
+ ap.error("--indir and --outdir are required (unless --manifest-only)")
+
layers = None
if a.layers:
layers = {int(x) for x in a.layers.split(",")}
@@ -256,6 +392,7 @@ def main():
for p in sorted(by_shard):
tensors = []
fmt_map = {}
+ digests = {}
for name in by_shard[p]:
_, header, data_start = index[name]
raw, info = rf.read_tensor_bytes(p, header, data_start, name)
@@ -269,6 +406,8 @@ def main():
sys.exit(1)
tensors.append((name, "U8", [len(record)], record))
fmt_map[name] = rf.FORMAT_NAME
+ # whole-artifact digest: hash the record bytes already in hand
+ digests[name] = hashlib.sha256(record).hexdigest()
total_record += len(record)
qs = name + ".qs"
qp, qheader, qdata_start = index[qs]
@@ -279,12 +418,14 @@ def main():
rf.TABLE_KEY: table_json,
}
out_path = os.path.join(a.outdir, f"out-rans-{out_n:05d}.safetensors")
- rf.write_shard(out_path, tensors, metadata)
+ file_sha = rf.write_shard(out_path, tensors, metadata)
shard_manifest.append({
"file": os.path.basename(out_path),
"source": os.path.basename(p),
"bytes": os.path.getsize(out_path),
"weight_tensors": len(fmt_map),
+ "sha256": file_sha,
+ "records": digests,
})
print(f"[write] {out_path}: {len(tensors)} tensor(s) "
f"({os.path.getsize(out_path) / 1e9:.4f} GB) "
@@ -300,10 +441,7 @@ def main():
"n_weight_tensors": len(selected),
"shards": shard_manifest,
}
- tmp = manifest_path + ".tmp"
- with open(tmp, "w") as fh:
- json.dump(manifest, fh, indent=1, sort_keys=True)
- os.replace(tmp, manifest_path)
+ write_manifest(manifest_path, manifest)
ratio = total_record / total_w
print(f"[ratio] record/original: {ratio:.4f} ({(1 - ratio) * 100:.2f}% "
diff --git a/docs/int4-rans256-g0.md b/docs/int4-rans256-g0.md
index 96df21c9..2e437226 100644
--- a/docs/int4-rans256-g0.md
+++ b/docs/int4-rans256-g0.md
@@ -211,6 +211,30 @@ description above to read records: parse the shard header, find the stamp
and table in `__metadata__`, locate a tensor's record by name, and decode
its 256 streams with the table (in any order or in parallel).
+## Whole-artifact verification
+
+Per-record validation (framing, stream invariants, re-encode pin) proves a
+record is *a* well-formed artifact of this format β€” it cannot prove it is
+*the* record a given mint run produced: a well-formed record swapped in
+from another checkpoint passes every check above. For that, the writer's
+`repack-manifest.json` (the completion marker, written last, deterministic)
+carries per shard a whole-file `sha256` (the complete `.safetensors` bytes,
+hashed while streaming the write β€” it subsumes the `.qs` sidecars, the
+header, and the padding, none of which per-record digests can see) plus a
+`records` map β€” original tensor name β†’ sha256 of the emitted record bytes
+exactly as written β€” for granular diagnosis. `rans_verify.py` checks the
+file hash first, then every record against its digest, whenever the
+manifest sits next to the shards (named refusals:
+`E_SHARD_DIGEST_MISMATCH`, `E_DIGEST_MISMATCH`, `E_DIGEST_MISSING`,
+`E_MANIFEST_MALFORMED`); a manifest without digests, or no manifest, means
+no check is possible (a note, never an error), and
+`repack_rans.py --manifest-only <dir>` retro-generates digests for
+already-minted directories by hashing shards in place. This is **build
+integrity** β€” these exact bytes came from that mint run; container
+*identity* proper remains the stamp/registry lineage above, and the
+engine-side load check ships with the consumer PR. The record wire format
+is untouched by all of this: the manifest is a sidecar file.
+
## Proposed registry row
| ordinal | name | weight bytes | scale layout | status |