Submissions / #2 / scripts/contam.py
scripts/contam.py
Preview
"""GSM8K test-set contamination scan: exact-match + 13-gram overlap.
Usage: python contam.py <corpus_name> <out.jsonl> <spec>...
spec = kind:path:field[,field...] kind in {parquet, json}
Each listed field of each record is scanned as a separate text unit.
Normalisation: NFKC, lowercase, curly quotes -> ascii, every non [a-z0-9] char -> space,
whitespace collapsed. Tokens = whitespace-split words.
An n-gram hit = any 13-token window of a GSM8K test question that appears in a corpus text
(questions shorter than 13 tokens use the whole question as their single gram).
Per test item we record: which corpus fields hit, the max fraction of the item's 13-grams found
in any single corpus text, and whether the full normalised question appears as an exact match /
substring.
Optional env: META_COLS=id,url,dump (parquet columns to attach) and HITS_OUT=<path> write one
JSON line per (corpus text, test item) hit.
"""
import json, os, re, sys, unicodedata, hashlib
from collections import defaultdict
import pyarrow.parquet as pq
N = 13
_trans = str.maketrans({"’": "'", "‘": "'", "“": '"', "”": '"'})
_nonalnum = re.compile(r"[^a-z0-9]+")
def norm(s):
s = unicodedata.normalize("NFKC", s or "").translate(_trans).lower()
return _nonalnum.sub(" ", s).strip()
def load_test(path):
qs = pq.read_table(path).column("question").to_pylist()
items = []
for i, q in enumerate(qs):
n = norm(q)
toks = n.split()
grams = [tuple(toks[j:j + N]) for j in range(max(1, len(toks) - N + 1))]
items.append({"idx": i, "sha256": hashlib.sha256(q.encode()).hexdigest(),
"norm": n, "ntok": len(toks), "grams": set(grams)})
return items
def iter_texts(spec):
kind, path, fields = spec.split(":", 2)
fields = fields.split(",")
if kind == "parquet":
meta = [c for c in os.environ.get("META_COLS", "").split(",") if c]
pf = pq.ParquetFile(path)
for b in pf.iter_batches(batch_size=4096, columns=fields + meta):
cols = {f: b.column(f).to_pylist() for f in fields + meta}
for f in fields:
for r, t in enumerate(cols[f]):
yield f, t, {m: cols[m][r] for m in meta}
else:
for r in json.load(open(path)):
for f in fields:
yield f, r.get(f), {}
def main():
name, out, *specs = sys.argv[1:]
items = load_test(os.environ["GSM8K_TEST"])
gram2items = defaultdict(list)
for it in items:
for g in it["grams"]:
gram2items[g].append(it["idx"])
short = {it["norm"]: it["idx"] for it in items if it["ntok"] < N}
pairs = {g[:2] for g in gram2items}
exact = {it["norm"]: it["idx"] for it in items}
res = {it["idx"]: {"fields": set(), "max_cov": 0.0, "exact": False, "substring": False,
"n_texts_hit": 0} for it in items}
n_texts = n_tok = 0
hits_out = open(os.environ["HITS_OUT"], "w") if os.environ.get("HITS_OUT") else None
for field, text, meta in iter_texts_all(specs):
n_texts += 1
t = norm(text)
toks = t.split()
n_tok += len(toks)
if t in exact:
r = res[exact[t]]; r["exact"] = True; r["fields"].add(field)
found = defaultdict(set)
for j in range(len(toks) - N + 1):
if (toks[j], toks[j + 1]) in pairs:
g = tuple(toks[j:j + N])
for k in gram2items.get(g, ()):
found[k].add(g)
for k, gs in found.items():
r = res[k]
r["fields"].add(field); r["n_texts_hit"] += 1
r["max_cov"] = max(r["max_cov"], len(gs) / len(items[k]["grams"]))
if not r["substring"] and r["max_cov"] >= 0.999 and items[k]["norm"] in t:
r["substring"] = True
if hits_out:
hits_out.write(json.dumps({"idx": k, "cov": round(len(gs) / len(items[k]["grams"]), 4),
"n_grams": len(gs), **meta}) + "\n")
if short and len(toks) < 40 * N:
for s, k in short.items():
if s in t:
res[k]["fields"].add(field); res[k]["n_texts_hit"] += 1
if n_texts % 500000 == 0:
print(f"{name}: {n_texts} texts {n_tok} tokens", file=sys.stderr, flush=True)
with open(out, "w") as f:
for it in items:
r = res[it["idx"]]
f.write(json.dumps({"corpus": name, "idx": it["idx"], "sha256": it["sha256"],
"ntok": it["ntok"], "ngram_hit": bool(r["fields"]),
"max_cov": round(r["max_cov"], 4), "exact": r["exact"],
"substring": r["substring"], "n_texts_hit": r["n_texts_hit"],
"fields": sorted(r["fields"])}) + "\n")
hit = sum(bool(res[i]["fields"]) for i in res)
print(json.dumps({"corpus": name, "texts": n_texts, "tokens": n_tok, "items": len(items),
"ngram_hit": hit,
"cov50": sum(res[i]["max_cov"] >= 0.5 for i in res),
"cov90": sum(res[i]["max_cov"] >= 0.9 for i in res),
"exact": sum(res[i]["exact"] for i in res),
"substring": sum(res[i]["substring"] for i in res)}))
def iter_texts_all(specs):
for s in specs:
yield from iter_texts(s)
if __name__ == "__main__":
main()