NOEON / scripts /audit_sources.py
Frankenstein-Labs's picture
NOEON: capability-slot rename (vision/computer_use/generation) + provenance; migrate weights
b871251 verified
Raw History Blame Contribute Delete
5.2 kB
#!/usr/bin/env python3
"""Verify the source models directly from Hugging Face.
Reads safetensors *headers only* via HTTP range requests, so it uses a few
kilobytes per shard instead of downloading gigabytes. Prints the real tensor
counts, parameter counts, dtypes, and the shape-compatibility verdict between
Mage-VL and Mage-VL-Cowork. Writes ``audit/source_audit.json``.
Usage:
python scripts/audit_sources.py
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from noeon.core import hub
from noeon.core.compat import compare, header_to_tensors, total_params
from noeon.core.registry import SOURCE_MODELS
def audit_multimodal(repo: str, revision: str, token=None) -> dict:
"""Audit a sharded transformers model (Mage-VL / Mage-VL-Cowork)."""
idx = hub.get_json(repo, "model.safetensors.index.json", revision, token)
shards = sorted(set(idx["weight_map"].values()))
tensors = {}
for sh in shards:
tensors.update(header_to_tensors(hub.read_safetensors_header(repo, sh, revision, token)))
ts = list(tensors.values())
dtypes = {}
for t in ts:
dtypes[t.dtype] = dtypes.get(t.dtype, 0) + t.numel
return {
"repo": repo,
"revision": revision,
"shards": shards,
"n_tensors": len(ts),
"params": total_params(ts),
"dtypes": dtypes,
"_tensors": tensors,
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--token", default=None, help="HF token (else $HF_TOKEN)")
ap.add_argument("--out", default="audit/source_audit.json")
args = ap.parse_args()
token = args.token
print("=" * 72)
print("NOEON source-model audit (headers only, no weight download)")
print("=" * 72)
result: dict = {"sources": {}}
for key in ("vision", "computer_use"):
src = SOURCE_MODELS[key]
print(f"\n[{key}] {src.repo}@{src.revision}")
try:
info = audit_multimodal(src.repo, src.revision, token)
except Exception as e: # noqa: BLE001
print(f" FAILED: {type(e).__name__}: {e}")
result["sources"][key] = {"repo": src.repo, "error": str(e)}
continue
tensors = info.pop("_tensors")
result["sources"][key] = info
print(f" tensors : {info['n_tensors']}")
print(f" params : {info['params']} ({info['params']/1e9:.4f} B)")
print(f" dtypes : {info['dtypes']}")
print(f" shards : {info['shards']}")
result.setdefault("_tensors", {})[key] = tensors
# Shape compatibility between the two VL models.
tensors = result.pop("_tensors", {})
if "vision" in tensors and "computer_use" in tensors:
rep = compare(tensors["vision"], tensors["computer_use"],
"vision", "computer_use")
print("\n" + rep.summary())
result["vl_compat"] = {
"compatible": rep.compatible,
"identical_shape": len(rep.identical_shape),
"shape_mismatch": len(rep.shape_mismatch),
"only_a": rep.only_a,
"only_b": rep.only_b,
}
# Mage-Flow: audit the three sub-modules of the public mirror.
flow = SOURCE_MODELS["generation"]
print(f"\n[generation] {flow.repo}@{flow.revision}")
flow_out = {"repo": flow.repo, "revision": flow.revision, "modules": {}}
for mod, path in (
("transformer", "transformer/diffusion_pytorch_model.safetensors"),
("vae", "vae/diffusion_pytorch_model.safetensors"),
):
try:
h = hub.read_safetensors_header(flow.repo, path, flow.revision, token)
ts = list(header_to_tensors(h).values())
flow_out["modules"][mod] = {
"n_tensors": len(ts), "params": total_params(ts), "file": path,
}
print(f" {mod:12s}: {len(ts)} tensors, {total_params(ts)/1e9:.4f} B")
except Exception as e: # noqa: BLE001
print(f" {mod:12s}: FAILED {e}")
flow_out["modules"][mod] = {"error": str(e)}
try:
idx = hub.get_json(flow.repo, "text_encoder/model.safetensors.index.json",
flow.revision, token)
tot = 0
n = 0
for sh in sorted(set(idx["weight_map"].values())):
h = hub.read_safetensors_header(flow.repo, f"text_encoder/{sh}",
flow.revision, token)
ts = list(header_to_tensors(h).values())
tot += total_params(ts)
n += len(ts)
flow_out["modules"]["text_encoder"] = {"n_tensors": n, "params": tot}
print(f" text_encoder: {n} tensors, {tot/1e9:.4f} B")
except Exception as e: # noqa: BLE001
print(f" text_encoder: FAILED {e}")
flow_out["modules"]["text_encoder"] = {"error": str(e)}
result["sources"]["generation"] = flow_out
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, indent=2))
print(f"\nwrote {out}")
return 0
if __name__ == "__main__":
raise SystemExit(main())