#!/usr/bin/env python3 """Audit whether candidate image/audio filename matches are better than random in ImageBind.""" from __future__ import annotations import sys as _sys from pathlib import Path as _Path _SCRIPTS = next(_p for _p in _Path(__file__).resolve().parents if _p.name == "scripts") _sys.path[:0] = [str(_SCRIPTS.parent), str(_SCRIPTS.parent / "models")] + [str(_d) for _d in sorted(_SCRIPTS.rglob("*")) if _d.is_dir() and _d.name != "__pycache__"] import argparse import json from pathlib import Path import numpy as np import pandas as pd def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--manifest", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--permutations", type=int, default=10_000) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--group-column", help="average repeated rows per location before auditing") return parser.parse_args() def unit(x: np.ndarray) -> np.ndarray: return x / np.linalg.norm(x, axis=1, keepdims=True).clip(1e-9) def load(frame: pd.DataFrame, column: str) -> np.ndarray: return np.stack([np.load(path)["embedding"].astype(np.float32) for path in frame[column]]) def main() -> None: args = parse_args() frame = pd.read_csv(args.manifest) if args.group_column: vision_rows, audio_rows, labels = [], [], [] for label, group in frame.groupby(args.group_column, sort=False): vision_rows.append(load(group.head(1), "imagebind_vision_path")[0]) audio_rows.append(load(group, "imagebind_audio_path").mean(0)) labels.append(str(label)) vision, audio = unit(np.stack(vision_rows)), unit(np.stack(audio_rows)) else: vision = unit(load(frame, "imagebind_vision_path")) audio = unit(load(frame, "imagebind_audio_path")) labels = frame.get("photo_id", pd.Series(range(len(frame)))).astype(str).tolist() similarity = vision @ audio.T n = len(vision) own = np.diag(similarity) other_mean = (similarity.sum(1) - own) / max(n - 1, 1) advantage = own - other_mean order = np.argsort(-similarity, axis=1) ranks = np.argmax(order == np.arange(n)[:, None], axis=1) + 1 rng = np.random.default_rng(args.seed) permutation_means = np.empty(args.permutations, dtype=np.float64) for index in range(args.permutations): permutation_means[index] = similarity[np.arange(n), rng.permutation(n)].mean() boot = rng.integers(0, n, size=(args.permutations, n)) advantage_boot = advantage[boot].mean(1) pairing_status = frame.get("pairing_status", pd.Series(["unspecified"])).iloc[0] reliable = advantage.mean() > 0 and np.percentile(advantage_boot, 2.5) > 0 if reliable: interpretation = ( "Candidate filename matches show cross-modal evidence above random. This is evidence " "for pairing quality, not proof of synchronized or co-located collection." ) elif str(pairing_status).startswith("accepted_"): interpretation = ( "No reliable cross-modal evidence above random. Pairs remain accepted by the explicit " "dataset ID rule; report this result as a pairing-quality warning." ) else: interpretation = ( "Candidate filename matches do not show reliable cross-modal evidence above random; " "do not train on them without a separate acceptance rule." ) result = { "pairs": n, "unit": "group" if args.group_column else "row", "group_column": args.group_column, "pairing_status": pairing_status, "own_pair_cosine_mean": float(own.mean()), "random_pair_cosine_mean": float(permutation_means.mean()), "own_minus_other_cosine": float(advantage.mean()), "own_minus_other_ci95": [float(x) for x in np.percentile(advantage_boot, [2.5, 97.5])], "permutation_p_one_sided": float((1 + (permutation_means >= own.mean()).sum()) / (args.permutations + 1)), "retrieval_recall_at_1": float((ranks <= 1).mean()), "retrieval_recall_at_5": float((ranks <= 5).mean()), "retrieval_recall_at_10": float((ranks <= 10).mean()), "median_retrieval_rank": float(np.median(ranks)), "mean_reciprocal_rank": float((1.0 / ranks).mean()), "own_pair_cosine_p10_p50_p90": [float(x) for x in np.percentile(own, [10, 50, 90])], "interpretation": interpretation, } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(result, indent=2), encoding="utf-8") print(json.dumps(result, indent=2)) if __name__ == "__main__": main()