Jacqkues commited on
Commit
7b93f5d
·
verified ·
1 Parent(s): 3ae01c3

Upload contamination.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. contamination.py +74 -0
contamination.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Near-duplicate check between the generic benchmark and the images Sev models were trained on.
2
+
3
+ Every training image of kev-vision-decisions-full (photo, document and chart sources) and of doc-index is hashed once
4
+ (256-bit average hash, as in the dataset audit); a benchmark item is flagged when its image is within MAX_BITS of any
5
+ training image. The same photo re-encoded or resized by another uploader lands within a few bits; different photos of a
6
+ similar scene rarely do. Writes {bench: {n, flagged, by_source}} and the flagged item ids.
7
+
8
+ uv run modal run modal_app.py::contamination # -> /vol/runs/eval/contamination.json
9
+ """
10
+ import argparse, json
11
+ from collections import Counter, defaultdict
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pyarrow.parquet as pq
16
+
17
+ from .sources import ahash
18
+
19
+ MAX_BITS = 6
20
+ FULL = "Jacqkues/kev-vision-decisions-full"
21
+ IMAGE_SOURCES = ["aokvqa", "vqav2", "scienceqa", "chartnet", "documents", "rvl_cdip", "ava", "pets", "eurosat", "fairface_age"]
22
+
23
+
24
+ def _words(h):
25
+ """256-bit int -> 4 uint64 words, for vectorised Hamming distances."""
26
+ return [(h >> (64 * k)) & (2**64 - 1) for k in range(4)]
27
+
28
+
29
+ def _hash_file(path):
30
+ hs = []
31
+ for b in pq.ParquetFile(path).iter_batches(batch_size=500, columns=["image"]):
32
+ for r in b.to_pylist():
33
+ if r["image"] and r["image"].get("bytes"): hs.append(_words(ahash(r["image"]["bytes"])))
34
+ return np.array(hs, dtype=np.uint64).reshape(-1, 4)
35
+
36
+
37
+ def main():
38
+ from huggingface_hub import hf_hub_download
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--bench", default="/vol/data/generic.parquet")
41
+ ap.add_argument("--docindex", default="/vol/data/docindex")
42
+ ap.add_argument("--out", default="/vol/runs/eval/contamination.json")
43
+ a = ap.parse_args()
44
+
45
+ items = [r for b in pq.ParquetFile(a.bench).iter_batches(batch_size=500, columns=["id", "bench", "image"]) for r in b.to_pylist()]
46
+ bench = np.array([_words(ahash(r["image"])) for r in items], dtype=np.uint64)
47
+ print(f"{len(items)} benchmark images hashed", flush=True)
48
+
49
+ train = {s: hf_hub_download(FULL, f"train/{s}.parquet", repo_type="dataset") for s in IMAGE_SOURCES}
50
+ train.update({f"docindex/{p.stem}": str(p) for p in sorted(Path(a.docindex, "train").glob("*.parquet"))})
51
+ best = np.full(len(items), 257); best_src = [None] * len(items)
52
+ for src, path in train.items():
53
+ th = _hash_file(path)
54
+ for s in range(0, len(th), 4000): # [bench, chunk] Hamming distances
55
+ 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)
56
+ better = d < best
57
+ best = np.where(better, d, best)
58
+ for i in np.nonzero(better)[0]: best_src[i] = src
59
+ print(f"{src}: {len(th)} training images, {(best <= MAX_BITS).sum()} benchmark items flagged so far", flush=True)
60
+
61
+ flagged = defaultdict(list); report = {}
62
+ for it, d, s in zip(items, best, best_src):
63
+ if d <= MAX_BITS: flagged[it["bench"]].append({"id": it["id"], "source": s, "bits": int(d)})
64
+ for b, n in Counter(it["bench"] for it in items).items():
65
+ report[b] = {"n": n, "flagged": len(flagged[b]), "share": round(len(flagged[b]) / n, 4),
66
+ "by_source": dict(Counter(f["source"] for f in flagged[b]))}
67
+ print(b, report[b], flush=True)
68
+ Path(a.out).parent.mkdir(parents=True, exist_ok=True)
69
+ Path(a.out).write_text(json.dumps({"max_bits": MAX_BITS, "benches": report, "flagged": flagged}, indent=1))
70
+ print(f"saved {a.out}", flush=True)
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()