Download evaluation/src/helixbench/report.py from NoizAI/Helixbench: direct link, hf CLI and curl.
- Browser
- Download file 9.39 kB
-
https://huggingface.co/datasets/NoizAI/Helixbench/resolve/main/evaluation/src/helixbench/report.py
- Command line
-
hf download hf://datasets/NoizAI/Helixbench/evaluation/src/helixbench/report.py
-
curl -L -o report.py https://huggingface.co/datasets/NoizAI/Helixbench/resolve/main/evaluation/src/helixbench/report.py
9.39 kB
| """Strictly aggregate only the six Helixbench main metrics.""" | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import statistics | |
| from pathlib import Path | |
| import numpy as np | |
| from scipy.linalg import svdvals | |
| from scipy.special import logsumexp | |
| from .inputs import ROOT, atomic_json, read_jsonl, sha256, validate_prepared, verify_media_manifest, verify_packaged_gt_features | |
| NAMES = ("KL", "FAD", "DeSync", "IB", "CLAP", "Spatial") | |
| SCOPES = {"KL": 1015, "FAD": 1015, "DeSync": 165, "IB": 1015, "CLAP": 1015, "Spatial": 150} | |
| def _check_ids(rows: list[dict], ids: set[str], label: str, key: str = "sample_id") -> None: | |
| actual = [row[key] for row in rows] | |
| if len(actual) != len(ids) or len(set(actual)) != len(actual) or set(actual) != ids: | |
| raise ValueError(f"{label}: expected exact {len(ids)} unique IDs") | |
| def paired_kl(gt_logits: np.ndarray, generated_logits: np.ndarray) -> np.ndarray: | |
| if gt_logits.shape != generated_logits.shape or gt_logits.ndim != 2 or gt_logits.shape[1] != 527: | |
| raise ValueError("KL requires matched [N, 527] logits") | |
| if not (np.isfinite(gt_logits).all() and np.isfinite(generated_logits).all()): | |
| raise ValueError("Nonfinite PaSST logits") | |
| gt = np.asarray(gt_logits, dtype=np.float64) | |
| generated = np.asarray(generated_logits, dtype=np.float64) | |
| log_p = gt - logsumexp(gt, axis=1, keepdims=True) | |
| log_q = generated - logsumexp(generated, axis=1, keepdims=True) | |
| values = np.sum(np.exp(log_p) * (log_p - log_q), axis=1) | |
| if values.min() < -1e-10: | |
| raise ValueError("KL unexpectedly negative") | |
| return values | |
| def frechet(a: np.ndarray, b: np.ndarray) -> float: | |
| """The historical float64 unbiased-covariance/SVD FAD calculation.""" | |
| a = np.asarray(a, dtype=np.float64) | |
| b = np.asarray(b, dtype=np.float64) | |
| if a.ndim != 2 or b.ndim != 2 or a.shape[1] != b.shape[1] or min(len(a), len(b)) < 2: | |
| raise ValueError("FAD requires two nonempty 2D feature sets") | |
| if not (np.isfinite(a).all() and np.isfinite(b).all()): | |
| raise ValueError("Nonfinite VGGish feature") | |
| mu = a.mean(0) - b.mean(0) | |
| x = (a - a.mean(0)) / np.sqrt(len(a) - 1) | |
| y = (b - b.mean(0)) / np.sqrt(len(b) - 1) | |
| trace = float(np.square(x).sum() + np.square(y).sum()) | |
| if max(len(a), len(b)) <= a.shape[1]: | |
| cross = float(svdvals(x @ y.T).sum()) | |
| else: | |
| def root(z: np.ndarray) -> np.ndarray: | |
| values, vectors = np.linalg.eigh(z.T @ z) | |
| if values.min() < -1e-9 * max(values.max(), 1): | |
| raise ValueError("Covariance not positive semidefinite") | |
| return (vectors * np.sqrt(np.maximum(values, 0))) @ vectors.T | |
| cross = float(svdvals(root(x) @ root(y)).sum()) | |
| result = float(mu @ mu + trace - 2 * cross) | |
| if result < -1e-7 * max(trace, 1): | |
| raise ValueError("FAD unexpectedly negative") | |
| return max(0.0, result) | |
| def _features(run_dir: Path, metric: str, group: str, ids: list[str], media: dict[str, str], key: str) -> list[np.ndarray]: | |
| arrays = [] | |
| for sample_id in ids: | |
| path = run_dir / "results" / metric / group / f"{sample_id}.npz" | |
| with np.load(path) as item: | |
| if str(item["sample_id"]) != sample_id or str(item["media_sha256"]) != media[sample_id]: | |
| raise ValueError(f"{metric} feature/media mismatch: {sample_id}") | |
| value = item[key] | |
| if not np.isfinite(value).all(): | |
| raise ValueError(f"{metric} nonfinite feature: {sample_id}") | |
| arrays.append(value) | |
| return arrays | |
| def calculate(run_dir: Path) -> dict: | |
| prepared = validate_prepared(run_dir) | |
| verify_media_manifest(run_dir) | |
| if prepared["gt_input_sha256"] == "packaged_reference_features": | |
| verify_packaged_gt_features(run_dir) | |
| manifest_dir = run_dir / "manifests" | |
| all_rows = read_jsonl(manifest_dir / "all1015.jsonl") | |
| gt_rows = read_jsonl(manifest_dir / "gt1015.jsonl") | |
| event_rows = read_jsonl(manifest_dir / "event165.jsonl") | |
| perspective_rows = read_jsonl(manifest_dir / "perspective150.jsonl") | |
| all_ids = [row["sample_id"] for row in all_rows] | |
| event_ids = {row["sample_id"] for row in event_rows} | |
| perspective_ids = {row["sample_id"] for row in perspective_rows} | |
| if len(all_ids) != 1015 or len(set(all_ids)) != 1015 or len(event_ids) != 165 or len(perspective_ids) != 150: | |
| raise ValueError("Prepared manifests have invalid scopes") | |
| _check_ids(gt_rows, set(all_ids), "GT") | |
| generated_media = {row["sample_id"]: row["media_sha256"] for row in all_rows} | |
| gt_media = {row["sample_id"]: row["media_sha256"] for row in gt_rows} | |
| gt_logits = np.stack(_features(run_dir, "passt", "gt", all_ids, gt_media, "logits")) | |
| generated_logits = np.stack(_features(run_dir, "passt", "generated", all_ids, generated_media, "logits")) | |
| kl_values = paired_kl(gt_logits, generated_logits) | |
| gt_vggish = np.concatenate(_features(run_dir, "vggish", "gt", all_ids, gt_media, "vggish")) | |
| generated_vggish = np.concatenate(_features(run_dir, "vggish", "generated", all_ids, generated_media, "vggish")) | |
| fad_self = frechet(gt_vggish, gt_vggish) | |
| if fad_self >= 1e-5: | |
| raise ValueError(f"FAD GT self-check failed: {fad_self}") | |
| clap_rows = read_jsonl(run_dir / "results/clap/scores_0.jsonl") | |
| _check_ids(clap_rows, set(all_ids), "CLAP") | |
| if any(row.get("status") != "ok" for row in clap_rows): | |
| raise ValueError("CLAP contains failures") | |
| clap = statistics.fmean(float(row["clap_cosine"]) for row in clap_rows) | |
| desync_rows = read_jsonl(run_dir / "results/desync/results.jsonl") | |
| _check_ids(desync_rows, {row["clip_id"] for row in event_rows}, "DeSync", "clip_id") | |
| if any(row.get("status") != "ok" for row in desync_rows): | |
| raise ValueError("DeSync contains failures") | |
| desync = statistics.fmean(float(row["desync_sec"]) for row in desync_rows) | |
| video_embeddings, audio_embeddings = [], [] | |
| for row in all_rows: | |
| path = run_dir / "results/imagebind/features" / f"{row['imagebind_id']}.npz" | |
| with np.load(path) as item: | |
| video_embeddings.append(item["video"].astype(np.float32)) | |
| audio_embeddings.append(item["audio"].astype(np.float32)) | |
| matrix = np.stack(video_embeddings) @ np.stack(audio_embeddings).T | |
| if matrix.shape != (1015, 1015) or not np.isfinite(matrix).all(): | |
| raise ValueError("Invalid ImageBind embedding matrix") | |
| ib = float(np.diag(matrix).mean()) | |
| spatial = json.loads((run_dir / "results/spatial/scores/summary.json").read_text()) | |
| spatial_rows = spatial["results"] | |
| if spatial.get("schema") != "spatial_three_region_all_candidates_v3" or spatial.get("clips_failed") != 0: | |
| raise ValueError("Spatial v3 summary invalid") | |
| _check_ids(spatial_rows, perspective_ids, "Spatial") | |
| spatial_mean = statistics.fmean(float(row["score"]) for row in spatial_rows) | |
| if not math.isclose(spatial_mean, spatial["score"], abs_tol=1e-10): | |
| raise ValueError("Spatial summary mean mismatch") | |
| values = {"KL": float(kl_values.mean()), "FAD": frechet(gt_vggish, generated_vggish), | |
| "DeSync": desync, "IB": ib, "CLAP": clap, "Spatial": spatial_mean} | |
| if set(values) != set(NAMES) or not all(math.isfinite(value) for value in values.values()): | |
| raise ValueError("Main report must contain exactly six finite scores") | |
| return { | |
| "schema": "Helixbench.six_metrics.v1", | |
| "model_id": prepared["model_id"], | |
| "metrics": {name: {"value": values[name], "n": SCOPES[name]} for name in NAMES}, | |
| "spatial_counts": spatial["counts"], | |
| "inputs": {"cohort_sha256": prepared["cohort_sha256"], "manifest_sha256": prepared["manifests"]}, | |
| "provenance": { | |
| "sources_sha256": sha256(ROOT / "resources/SOURCES.json"), | |
| "report_code_sha256": sha256(Path(__file__)), | |
| "stage_receipts_sha256": { | |
| path.stem: sha256(path) for path in sorted((run_dir / "stages").glob("*.json")) | |
| } if (run_dir / "stages").exists() else {}, | |
| }, | |
| "protocol": { | |
| "KL": "PaSST527 softmax KL(GT||generated), matched ID, natural logarithm", | |
| "FAD": "VGGish128, first five seconds, distribution Frechet distance", | |
| "DeSync": "Synchformer mean absolute offset, event165", | |
| "IB": "ImageBind matched audio/video cosine, all1015", | |
| "CLAP": "LAION-CLAP audio/caption_av cosine, all1015", | |
| "Spatial": "v3 all150: invalid=-100, eligible center=0, signed side frames", | |
| }, | |
| } | |
| def aggregate(run_dir: Path) -> dict: | |
| report = calculate(run_dir) | |
| atomic_json(run_dir / "REPORT.json", report) | |
| lines = [f"# Helixbench — {report['model_id']}", "", | |
| "| KL ↓ | FAD ↓ | DeSync (s) ↓ | IB ↑ | CLAP ↑ | Spatial ↑ |", | |
| "|---:|---:|---:|---:|---:|---:|", | |
| "| " + " | ".join(f"{report['metrics'][name]['value']:.4f}" for name in NAMES) + " |", | |
| "", "Spatial counts: " + json.dumps(report["spatial_counts"], ensure_ascii=False, sort_keys=True)] | |
| (run_dir / "REPORT.md").write_text("\n".join(lines) + "\n", encoding="utf-8") | |
| atomic_json(run_dir / "COMPLETE.json", { | |
| "report_sha256": sha256(run_dir / "REPORT.json"), | |
| "metrics": list(NAMES), | |
| "n": SCOPES, | |
| }) | |
| return report | |