"""Near-duplicate check between the generic benchmark and the images Sev models were trained on. Every training image of kev-vision-decisions-full (photo, document and chart sources) and of doc-index is hashed once (256-bit average hash, as in the dataset audit); a benchmark item is flagged when its image is within MAX_BITS of any training image. The same photo re-encoded or resized by another uploader lands within a few bits; different photos of a similar scene rarely do. Writes {bench: {n, flagged, by_source}} and the flagged item ids. uv run modal run modal_app.py::contamination # -> /vol/runs/eval/contamination.json """ import argparse, json from collections import Counter, defaultdict from pathlib import Path import numpy as np import pyarrow.parquet as pq from .sources import ahash MAX_BITS = 6 FULL = "Jacqkues/kev-vision-decisions-full" IMAGE_SOURCES = ["aokvqa", "vqav2", "scienceqa", "chartnet", "documents", "rvl_cdip", "ava", "pets", "eurosat", "fairface_age"] def _words(h): """256-bit int -> 4 uint64 words, for vectorised Hamming distances.""" return [(h >> (64 * k)) & (2**64 - 1) for k in range(4)] def _hash_file(path): hs = [] for b in pq.ParquetFile(path).iter_batches(batch_size=500, columns=["image"]): for r in b.to_pylist(): if r["image"] and r["image"].get("bytes"): hs.append(_words(ahash(r["image"]["bytes"]))) return np.array(hs, dtype=np.uint64).reshape(-1, 4) def main(): from huggingface_hub import hf_hub_download ap = argparse.ArgumentParser() ap.add_argument("--bench", default="/vol/data/generic.parquet") ap.add_argument("--docindex", default="/vol/data/docindex") ap.add_argument("--out", default="/vol/runs/eval/contamination.json") a = ap.parse_args() items = [r for b in pq.ParquetFile(a.bench).iter_batches(batch_size=500, columns=["id", "bench", "image"]) for r in b.to_pylist()] bench = np.array([_words(ahash(r["image"])) for r in items], dtype=np.uint64) print(f"{len(items)} benchmark images hashed", flush=True) train = {s: hf_hub_download(FULL, f"train/{s}.parquet", repo_type="dataset") for s in IMAGE_SOURCES} train.update({f"docindex/{p.stem}": str(p) for p in sorted(Path(a.docindex, "train").glob("*.parquet"))}) best = np.full(len(items), 257); best_src = [None] * len(items) for src, path in train.items(): th = _hash_file(path) for s in range(0, len(th), 4000): # [bench, chunk] Hamming distances d = sum(np.bitwise_count(bench[:, None, k] ^ th[None, s:s + 4000, k]).astype(np.int32) for k in range(4)).min(axis=1) better = d < best best = np.where(better, d, best) for i in np.nonzero(better)[0]: best_src[i] = src print(f"{src}: {len(th)} training images, {(best <= MAX_BITS).sum()} benchmark items flagged so far", flush=True) flagged = defaultdict(list); report = {} for it, d, s in zip(items, best, best_src): if d <= MAX_BITS: flagged[it["bench"]].append({"id": it["id"], "source": s, "bits": int(d)}) for b, n in Counter(it["bench"] for it in items).items(): report[b] = {"n": n, "flagged": len(flagged[b]), "share": round(len(flagged[b]) / n, 4), "by_source": dict(Counter(f["source"] for f in flagged[b]))} print(b, report[b], flush=True) Path(a.out).parent.mkdir(parents=True, exist_ok=True) Path(a.out).write_text(json.dumps({"max_bits": MAX_BITS, "benches": report, "flagged": flagged}, indent=1)) print(f"saved {a.out}", flush=True) if __name__ == "__main__": main()