Upload eros_header_check.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Header audit for a 10Eros-Max checkpoint, without downloading the weights.
Reads only the safetensors header (a few MB, via HTTP range requests), collapses tensor names into patterns(block indices -> N) and reports what a diffusers `h3_eros.apply_eros` load would meet: dtypes, the AdaLN rank, tensorsno mapping rule knows, and — with --compare — every difference against a checkpoint that is known to load (default: thebeta5 hybrid you already ran).
Two ways to run it (torch is NOT needed, only `huggingface_hub`):
1. In a Space. Put this file next to app.py, add `import eros_header_check` near the top of app.py, and set the Space variable H3_EROS_AUDIT=1. The audit then runs once at startup and prints to the Space logs, every line prefixed `[eros-audit]`. It never raises and never blocks startup. Optional variables: H3_EROS_AUDIT_FILE file to audit (default: H3_EROS_FILE, else the v1.0 turbo hybrid) H3_EROS_AUDIT_COMPARE known-good file (default: the beta5 hybrid; empty = skip the comparison) Keep H3_EROS=off while auditing, so nothing 40 GB is downloaded. Remove H3_EROS_AUDIT afterwards.
2. From a shell: python eros_header_check.py python eros_header_check.py --file 10Eros_Max_raw_v1.0_ref2va.safetensors python eros_header_check.py --compare "" # skip the comparison
Read-only: nothing is written, and nothing beyond the header is downloaded. HF_TOKEN is used if set."""
import argparseimport contextlibimport ioimport osimport refrom collections import Counter, defaultdict
REPO = os.environ.get("H3_EROS_REPO", "TenStrip/10Eros-Max")DEFAULT_FILE = "10Eros_Max_8stepTurbo_v1.0_hybrid.safetensors"DEFAULT_COMPARE = "10Eros_Max_h3_hybrid_beta5.safetensors"
# Reference-tree names `h3_eros.map_tensor` knows how to place (block / refiner indices collapsed to N).KNOWN = [ r"blocks\.N\.attn\.qkv_proj\.weight", r"blocks\.N\.attn\.out_proj\.weight", r"blocks\.N\.attn\.q_norm\.weight", r"blocks\.N\.attn\.k_norm\.weight", r"blocks\.N\.mlp\.fc1\.weight", r"blocks\.N\.mlp\.fc2\.weight", r"blocks\.N\.norm[12]\.weight", r"blocks\.N\.adaln_proj\.linear\.(weight|bias)", r"final_layer\.adaln_proj\.linear\.(weight|bias)", r"final_layer\.(video_out|audio_out|norm)\.(weight|bias)", r"(video_patch_proj|audio_patch_proj|condition_proj)\.(weight|bias)", r"token_refiner\.blocks\.N\..+", r"token_refiner\.final_norm\.weight", r"adaln_(basis|mean|t_table)", r".*inv_freq",]KNOWN_RE = [re.compile(p + "$") for p in KNOWN]
def collapse(name: str) -> str: return re.sub(r"\.\d+(?=\.)", ".N", name)
def load(file: str): from huggingface_hub import parse_safetensors_file_metadata
meta = parse_safetensors_file_metadata(REPO, file) patterns: dict[str, dict] = defaultdict(lambda: {"count": 0, "dtypes": Counter(), "shapes": Counter()}) for name, info in meta.tensors.items(): entry = patterns[collapse(name)] entry["count"] += 1 entry["dtypes"][info.dtype] += 1 entry["shapes"][tuple(info.shape)] += 1 return meta, patterns
def report(file: str, meta, patterns) -> None: dtypes = Counter(info.dtype for info in meta.tensors.values()) total = len(meta.tensors) print(f"\n=== {REPO}/{file}") print(f"tensors: {total} dtypes: {dict(dtypes)}") if meta.metadata: print(f"header metadata: {dict(meta.metadata)}")
blocks = {int(m.group(1)) for n in meta.tensors if (m := re.match(r"blocks\.(\d+)\.", n))} print(f"transformer blocks: {len(blocks)} (indices {min(blocks)}..{max(blocks)})" if blocks else "no blocks.* tensors")
basis = meta.tensors.get("adaln_basis") if basis is not None: print(f"AdaLN: pruned form, adaln_basis {tuple(basis.shape)} -> rank {basis.shape[0]}") if "adaln_t_table" in meta.tensors: print(f" adaln_t_table {tuple(meta.tensors['adaln_t_table'].shape)}") else: sample = next((n for n in meta.tensors if n.endswith("adaln_proj.linear.weight")), None) print(f"AdaLN: no adaln_basis; full-rank form" + (f" ({sample}: {tuple(meta.tensors[sample].shape)})" if sample else ""))
bad_dtypes = [d for d in dtypes if d not in ("BF16", "F16", "F32", "F64")] if bad_dtypes: print(f"!! non-float dtypes present {bad_dtypes}: quantized — h3_eros refuses this file")
unknown = {p: v for p, v in patterns.items() if not any(r.match(p) for r in KNOWN_RE)} print("\ntensor patterns:") for pattern in sorted(patterns): v = patterns[pattern] flag = " " if pattern not in unknown else "??" shapes = ", ".join(f"{s}x{c}" if c > 1 else f"{s}" for s, c in list(v["shapes"].items())[:3]) print(f" {flag} {pattern:<58} n={v['count']:<4} {'/'.join(v['dtypes']):<5} {shapes}") if unknown: print(f"\n!! {len(unknown)} pattern(s) no mapping rule covers (strict mode would refuse the file):") for p in sorted(unknown): print(f" {p} n={unknown[p]['count']}") else: print("\nOK: every tensor name matches a known mapping rule.")
def compare(file_a: str, patterns_a, file_b: str, patterns_b) -> None: print(f"\n=== diff: {file_a} vs {file_b}") only_a = sorted(set(patterns_a) - set(patterns_b)) only_b = sorted(set(patterns_b) - set(patterns_a)) for p in only_a: print(f" only in {file_a}: {p} n={patterns_a[p]['count']} {dict(patterns_a[p]['shapes'])}") for p in only_b: print(f" only in {file_b}: {p} n={patterns_b[p]['count']}") changed = False for p in sorted(set(patterns_a) & set(patterns_b)): a, b = patterns_a[p], patterns_b[p] if a["count"] != b["count"] or dict(a["shapes"]) != dict(b["shapes"]) or dict(a["dtypes"]) != dict(b["dtypes"]): changed = True print(f" differs: {p}\n {file_a}: n={a['count']} {dict(a['dtypes'])} {dict(a['shapes'])}" f"\n {file_b}: n={b['count']} {dict(b['dtypes'])} {dict(b['shapes'])}") if not (only_a or only_b or changed): print(" identical structure (names, counts, shapes, dtypes).")
def run(file: str, compare_to: str) -> None: meta, patterns = load(file) report(file, meta, patterns) if compare_to and compare_to != file: meta_b, patterns_b = load(compare_to) report(compare_to, meta_b, patterns_b) compare(file, patterns, compare_to, patterns_b)
def run_in_space() -> None: """Startup hook: audit once, print every line to the Space logs with a greppable prefix, never raise.""" file = os.environ.get("H3_EROS_AUDIT_FILE") or os.environ.get("H3_EROS_FILE") or DEFAULT_FILE compare_to = os.environ.get("H3_EROS_AUDIT_COMPARE", DEFAULT_COMPARE) buffer = io.StringIO() try: with contextlib.redirect_stdout(buffer): run(file, compare_to) except BaseException as error: # noqa: BLE001 - an audit must never stop the Space from starting buffer.write(f"\nAUDIT FAILED: {type(error).__name__}: {error}\n") print(f"[eros-audit] ---- begin ({REPO}/{file}) ----", flush=True) for line in buffer.getvalue().splitlines(): print(f"[eros-audit] {line}", flush=True) print("[eros-audit] ---- end ----", flush=True)
def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--file", default=DEFAULT_FILE) parser.add_argument("--compare", default=DEFAULT_COMPARE, help='known-good file to diff against; "" to skip') args = parser.parse_args() run(args.file, args.compare)
if __name__ == "__main__": main()elif os.environ.get("H3_EROS_AUDIT", "").strip().lower() in ("1", "on", "true", "yes"): run_in_space()eros_header_check.pyAdded+168