Submissions / #2 / scripts/para.py
scripts/para.py
Preview
"""Paraphrase-level GSM8K test overlap check.
A corpus text is a paraphrase candidate for test item t when
(a) the sorted multiset of numbers in the text equals t's (t has >= 3 numbers), and
(b) Jaccard similarity of content-word sets (stopwords and numbers removed) >= THRESH.
Usage: python para.py <name> <out.jsonl> <spec>... (spec as in contam.py)
"""
import json, os, re, sys
from collections import defaultdict
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from contam import norm, iter_texts
import pyarrow.parquet as pq
THRESH = float(os.environ.get("PARA_THRESH", "0.5"))
STOP = set("""a an the of to in on for and or is are was were be been it its he she they his her
their them this that these those with at by from as if then than so does do did how many much what
which who whom will would can could has have had per each every one if after before into out up""".split())
num = re.compile(r"^\d+$")
def feats(text):
toks = norm(text).split()
nums = tuple(sorted(t for t in toks if num.match(t)))
words = {t for t in toks if not num.match(t) and t not in STOP and len(t) > 1}
return nums, words
def main():
name, out, *specs = sys.argv[1:]
qs = pq.read_table(os.environ["GSM8K_TEST"]).column("question").to_pylist()
by_nums = defaultdict(list)
tf = []
for i, q in enumerate(qs):
n, w = feats(q)
tf.append((n, w))
if len(n) >= 3:
by_nums[n].append(i)
best = defaultdict(float); count = defaultdict(int); fields = defaultdict(set)
for spec in specs:
for field, text, _meta in iter_texts(spec):
if not text or len(text) > 4000:
continue
n, w = feats(text)
for i in by_nums.get(n, ()):
tw = tf[i][1]
j = len(w & tw) / max(1, len(w | tw))
if j >= THRESH:
count[i] += 1; fields[i].add(field)
best[i] = max(best[i], j)
eligible = sum(len(v) for v in by_nums.values())
with open(out, "w") as f:
for i in range(len(qs)):
f.write(json.dumps({"corpus": name, "idx": i, "eligible": len(tf[i][0]) >= 3,
"para_hit": count[i] > 0, "n_texts_hit": count[i],
"best_jaccard": round(best[i], 3), "fields": sorted(fields[i])}) + "\n")
print(json.dumps({"corpus": name, "eligible_items": eligible, "para_hit": sum(1 for v in count.values() if v > 0),
"thresh": THRESH}))
if __name__ == "__main__":
main()