File size: 7,707 Bytes
b16b327
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""Finding training problems that overlap eval problems.



Word n-grams catch copies and are removed outright. Embedding neighbours catch paraphrases

but also near-misses, so they are only marked for an LLM judge (judge_prompt) to rule on.

"""

from __future__ import annotations

import re
import warnings
from collections import Counter, defaultdict
from dataclasses import replace

from pocket_math.types import Problem

DEFAULT_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
COPY_SCORE = 0.5
COMMON_IN_TRAIN = 10


_MATH = re.compile(r"\$\$.*?\$\$|\$.*?\$|\\\(.*?\\\)|\\\[.*?\\\]", re.S)
_COMMAND = re.compile(r"\\[a-zA-Z]+")


def words(text: str) -> list[str]:
    """Lowercase word and number tokens. Inside math, letters are single tokens and LaTeX commands

    are dropped, so "$A B C$", "\\(ABC\\)" and "$\\overline{AB}C$" tokenize alike."""
    tokens: list[str] = []
    pos = 0
    for m in _MATH.finditer(text):
        tokens += re.findall(r"[a-z]+|\d+", _COMMAND.sub(" ", text[pos : m.start()]).lower())
        tokens += re.findall(r"[a-z]|\d+", _COMMAND.sub(" ", m.group(0)).lower())
        pos = m.end()
    return tokens + re.findall(r"[a-z]+|\d+", _COMMAND.sub(" ", text[pos:]).lower())


def _grams(ws: list[str], n: int) -> set[tuple[str, ...]]:
    return {tuple(ws[i : i + n]) for i in range(len(ws) - n + 1)}


def ngram_candidates(train: list[Problem], evals: list[Problem], n: int = 13) -> list[dict]:
    """Rows for train problems that copy an eval problem, judged by shared word n-grams.



    score is the share of the eval problem's n-grams found in the train problem. A pair counts

    when score >= COPY_SCORE, or when it shares an n-gram that is specific to that eval problem:

    found in no other eval problem and in at most COMMON_IN_TRAIN train problems. An eval

    problem shorter than n words counts when its whole text appears in the train problem.

    """
    owners: dict[tuple[str, ...], list[str]] = defaultdict(list)
    sizes: dict[str, int] = {}
    short: dict[str, str] = {}
    for e in evals:
        ws = words(e.problem)
        if len(ws) < n:
            short[e.uid] = " " + " ".join(ws) + " "
            continue
        grams = _grams(ws, n)
        sizes[e.uid] = len(grams)
        for g in grams:
            owners[g].append(e.uid)
    shared = [_grams(words(p.problem), n) & owners.keys() for p in train]
    # Stock wording ("... relatively prime positive integers. Find m+n") recurs across problems; a copy does not.
    train_count = Counter(g for gs in shared for g in gs)

    rows = []
    for p, gs in zip(train, shared, strict=True):
        by_eval: dict[str, list[tuple[str, ...]]] = defaultdict(list)
        for g in gs:
            for uid in owners[g]:
                by_eval[uid].append(g)
        scores = {uid: len(common) / sizes[uid] for uid, common in by_eval.items()
                  if len(common) / sizes[uid] >= COPY_SCORE
                  or any(len(owners[g]) == 1 and train_count[g] <= COMMON_IN_TRAIN for g in common)}
        joined = " " + " ".join(words(p.problem)) + " "
        scores.update({uid: 1.0 for uid, text in short.items() if text.strip() and text in joined})
        rows += [{"pool_uid": p.uid, "eval_uid": uid, "method": "ngram", "score": round(s, 4)}
                 for uid, s in sorted(scores.items())]
    return rows


def lexical_overlap(train: list[Problem], evals: list[Problem]) -> list[float]:
    """Per train problem, the largest share of any eval problem's distinct uncommon words it contains."""
    eval_words = [set(words(e.problem)) for e in evals]
    df = Counter(w for ws in eval_words for w in ws)
    common = {w for w, c in df.items() if c > max(1, len(evals) // 10)}
    index: dict[str, list[int]] = defaultdict(list)
    for j, ws in enumerate(eval_words):
        for w in ws - common:
            index[w].append(j)
    # Floor the denominator: an eval problem with two uncommon words would give thousands of problems a perfect score.
    sizes = [max(8, len(ws - common)) for ws in eval_words]
    scores = []
    for p in train:
        hits = Counter(j for w in set(words(p.problem)) for j in index.get(w, ()))
        scores.append(max((c / sizes[j] for j, c in hits.items()), default=0.0))
    return scores


def embedding_candidates(train: list[Problem], evals: list[Problem], model: str = DEFAULT_MODEL,

                         threshold: float = 0.85, batch_size: int = 64) -> list[dict]:
    """Rows for train problems whose cosine similarity to an eval problem is at least `threshold`."""
    try:
        from sentence_transformers import SentenceTransformer
    except ImportError:
        warnings.warn("sentence-transformers is not installed; skipping embedding decontamination", stacklevel=2)
        return []
    if not train or not evals:
        return []
    encoder = SentenceTransformer(model)

    def encode(problems: list[Problem]):
        return encoder.encode([p.problem for p in problems], batch_size=batch_size,
                              normalize_embeddings=True, convert_to_numpy=True)

    eval_vectors = encode(evals)
    rows = []
    chunk = 4096
    for start in range(0, len(train), chunk):
        part = train[start : start + chunk]
        sims = encode(part) @ eval_vectors.T
        for i, j in zip(*(sims >= threshold).nonzero(), strict=True):
            rows.append({"pool_uid": part[i].uid, "eval_uid": evals[j].uid, "method": "embedding",
                         "score": round(float(sims[i, j]), 4)})
    return rows


def judge_prompt(train_problem: str, eval_problem: str) -> str:
    return (
        "You are checking a training set for leaked test problems.\n\n"
        f"Problem A (training set):\n<<<\n{train_problem.strip()}\n>>>\n\n"
        f"Problem B (test set):\n<<<\n{eval_problem.strip()}\n>>>\n\n"
        "Answer YES if A and B are the same problem: a copy, a rewording, renamed variables, changed "
        "formatting, or the same question asking for the answer in another form (for example m+n "
        "instead of m/n). Answer NO if they are different problems, even if they share a topic, a "
        "setup or a technique.\n"
        "Reply with one word: YES or NO."
    )


def decontaminate(pool: list[Problem], evals: list[Problem], n: int = 13, model: str = DEFAULT_MODEL,

                  threshold: float = 0.85, embed_limit: int | None = None) -> tuple[list[Problem], list[dict]]:
    """Drop pool problems with an n-gram hit; mark embedding-only hits with meta["judge"] = [eval uids].



    embed_limit caps the embedding pass to the pool problems with the most word overlap with

    any eval problem, for machines where embedding the whole pool is too slow.

    Returns the kept problems and report rows {pool_uid, eval_uid, method, score}.

    """
    ngram_rows = ngram_candidates(pool, evals, n)
    flagged = {r["pool_uid"] for r in ngram_rows}
    kept = [p for p in pool if p.uid not in flagged]

    targets = kept
    if embed_limit is not None and embed_limit < len(kept):
        scores = lexical_overlap(kept, evals)
        top = sorted(range(len(kept)), key=lambda i: (-scores[i], i))[:embed_limit]
        targets = [kept[i] for i in sorted(top)]
    embed_rows = embedding_candidates(targets, evals, model, threshold)

    judge: dict[str, list[str]] = defaultdict(list)
    for r in embed_rows:
        judge[r["pool_uid"]].append(r["eval_uid"])
    kept = [replace(p, meta={**p.meta, "judge": judge[p.uid]}) if p.uid in judge else p for p in kept]
    return kept, ngram_rows + embed_rows