Datasets:
File size: 12,983 Bytes
77e9b16 | 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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 | """Extract unique OpenThoughts3 questions and remove benchmark overlaps."""
from __future__ import annotations
import csv
import hashlib
import json
import re
import unicodedata
from collections import Counter, defaultdict
from pathlib import Path
import ahocorasick
import pyarrow as pa
import pyarrow.parquet as pq
from rapidfuzz import fuzz
ROOT = Path(__file__).parent
BENCH = ROOT / "work" / "benchmarks"
SOURCE = ROOT / "work" / "source" / "data"
OUT = ROOT / "work" / "publish"
def normalized(text: str) -> str:
text = unicodedata.normalize("NFKC", text).casefold()
text = re.sub(r"[^\w]+", " ", text, flags=re.UNICODE)
return " ".join(text.split())
def benchmark_questions() -> tuple[list[dict], dict]:
specs = [
("MATH500", "HuggingFaceH4__MATH-500/test.jsonl", "problem"),
("AIME25", "MathArena__aime_2025/data/train-00000-of-00001.parquet", "problem"),
("AIME26", "MathArena__aime_2026/data/train-00000-of-00001.parquet", "problem"),
("HMMT_Feb_2025", "MathArena__hmmt_feb_2025/data/train-00000-of-00001.parquet", "problem"),
("HMMT_Feb_2026", "MathArena__hmmt_feb_2026/data/train-00000-of-00001.parquet", "problem"),
("IMOAnswerBench_v2", "imo_answerbench_v2.csv", "Problem"),
("OJBench", "He-Ren__OJBench_testdata/prompts/full.jsonl", "prompt"),
]
for i in range(1, 7):
specs.append(("LiveCodeBench_v6", f"livecodebench__code_generation_lite/test{'' if i == 1 else i}.jsonl", "question_content"))
questions = []
counts = Counter()
for name, rel, field in specs:
path = BENCH / rel
if path.suffix == ".parquet":
rows = pq.read_table(path, columns=[field]).to_pylist()
elif path.suffix == ".csv":
with path.open(newline="", encoding="utf-8-sig") as f:
rows = list(csv.DictReader(f))
else:
with path.open(encoding="utf-8") as f:
rows = [json.loads(line) for line in f]
for row in rows:
value = row.get(field)
if isinstance(value, str) and value.strip():
norm = normalized(value)
questions.append({"name": name, "norm": norm, "words": set(norm.split())})
counts[name] += 1
return questions, dict(counts)
def build_index(bench: list[dict]):
exact = defaultdict(set)
anchors = defaultdict(set)
for idx, item in enumerate(bench):
norm = item["norm"]
exact[norm].add(idx)
words = norm.split()
width = min(10, max(4, len(words) // 2))
if len(words) < width:
continue
positions = list(range(0, len(words) - width + 1, max(1, width // 2)))
if len(positions) > 40:
positions = [positions[round(i * (len(positions) - 1) / 39)] for i in range(40)]
for pos in positions:
window = words[pos : pos + width]
if len(set(window)) < min(5, width) or not any(len(w) >= 6 for w in window):
continue
anchors[" " + " ".join(window) + " "].add(idx)
machine = ahocorasick.Automaton()
for pattern, ids in anchors.items():
machine.add_word(pattern, tuple(ids))
machine.make_automaton()
return exact, machine, len(anchors)
def matches(question: str, bench: list[dict], exact, machine):
norm = normalized(question)
if not norm:
return []
hit = set(exact.get(norm, ()))
candidates = set()
for _, ids in machine.iter(" " + norm + " "):
candidates.update(ids)
source_words = set(norm.split())
for idx in candidates - hit:
target = bench[idx]["norm"]
if not target:
continue
if (len(target) >= 50 and target in norm) or (len(norm) >= 100 and len(norm) >= 0.65 * len(target) and norm in target):
hit.add(idx)
continue
target_words = bench[idx]["words"]
coverage = len(target_words.intersection(source_words)) / max(1, len(target_words))
if coverage < 0.55:
continue
ratio = fuzz.ratio(norm, target, score_cutoff=82)
partial = 0
if not ratio and coverage >= 0.70 and len(target) <= 800 and len(norm) <= 3000:
partial = fuzz.partial_ratio(norm, target, score_cutoff=88)
if ratio or partial:
hit.add(idx)
return sorted(hit)
BOX = re.compile(r"\\+boxed\s*\{")
FENCE = re.compile(r"```([^\n`]*)\n(.*?)\n```", re.DOTALL)
ANSWER_LABEL = re.compile(r"(?im)(?:^|\n)\s*(?:\*\*)?(?:final answer|answer)(?:\*\*)?\s*[::]\s*(.+)")
def last_box(text: str) -> str | None:
found = None
for match in BOX.finditer(text):
depth = 1
i = match.end()
start = i
while i < len(text) and depth:
if text[i] == "{":
depth += 1
elif text[i] == "}":
depth -= 1
i += 1
if depth == 0:
found = text[start : i - 1].strip()
return found
def extract_answer(response: str, domain: str) -> tuple[str, str] | None:
if not isinstance(response, str):
return None
marker = response.rfind("</think>")
if marker < 0:
return None
final = response[marker + len("</think>") :].strip()
if not final:
return None
if domain == "math":
box = last_box(final)
if box:
return box, "final_boxed"
labels = ANSWER_LABEL.findall(final)
if labels:
answer = labels[-1].strip().strip("*$ ")
if answer and len(answer) <= 300:
return answer, "final_answer_label"
return None
if domain == "code":
blocks = FENCE.findall(final)
if blocks:
language, code = blocks[-1]
if code.strip():
return code.strip(), "final_code_block"
return None
if domain == "science":
if final.rstrip("* ").endswith((".", "!", "?", "}", "]", ")")):
return final, "completed_final_text"
return None
def main():
OUT.mkdir(parents=True, exist_ok=True)
bench, benchmark_counts = benchmark_questions()
exact, machine, anchor_count = build_index(bench)
print(f"Benchmarks: {benchmark_counts}; anchors: {anchor_count}", flush=True)
files = sorted(SOURCE.glob("train-*-of-00120.parquet"))
if len(files) != 120:
raise RuntimeError(f"Expected 120 source shards, found {len(files)}")
records = {}
counts = Counter()
removed_by_benchmark = Counter()
audit = []
rejected = set()
for n, path in enumerate(files, 1):
parquet = pq.ParquetFile(path)
for batch in parquet.iter_batches(batch_size=512, columns=["difficulty", "source", "domain", "conversations"]):
for row in batch.to_pylist():
counts["source_rows"] += 1
turns = row["conversations"]
if not turns or not isinstance(turns[0], dict) or not isinstance(turns[0].get("value"), str) or not turns[0]["value"].strip():
counts["invalid_question"] += 1
continue
question = turns[0]["value"]
if question in rejected:
counts["duplicate_question"] += 1
continue
record = records.get(question)
if record is None:
hit = matches(question, bench, exact, machine)
if hit:
rejected.add(question)
counts["benchmark_overlap"] += 1
names = sorted({bench[i]["name"] for i in hit})
for name in names:
removed_by_benchmark[name] += 1
audit.append({"question_sha256": hashlib.sha256(question.encode()).hexdigest(), "benchmarks": names, "benchmark_indices": hit})
continue
record = {"difficulty": row["difficulty"], "source": row["source"], "domain": row["domain"], "conversations": [turns[0]], "answer_candidates": Counter(), "best_answer": None, "answer_method": None, "responses": 0}
records[question] = record
counts["published"] += 1
else:
counts["duplicate_question"] += 1
for turn in turns[1:]:
if turn.get("from") not in ("gpt", "assistant"):
continue
record["responses"] += 1
candidate = extract_answer(turn.get("value"), record["domain"])
if candidate is None:
continue
answer, method = candidate
if record["domain"] == "math":
record["answer_candidates"][answer] += 1
elif record["best_answer"] is None or (record["domain"] == "science" and len(answer) < len(record["best_answer"])):
record["best_answer"] = answer
record["answer_method"] = method
print(f"{n}/120: {dict(counts)}", flush=True)
question_schema = pa.schema([("difficulty", pa.int64()), ("source", pa.string()), ("domain", pa.string()), ("conversations", pa.list_(pa.struct([("from", pa.string()), ("value", pa.string())])))])
answer_schema = question_schema.append(pa.field("answer", pa.string())).append(pa.field("answer_method", pa.string())).append(pa.field("answer_confidence", pa.string())).append(pa.field("response_count", pa.int64())).append(pa.field("answer_support", pa.int64()))
question_dir = OUT / "data" / "questions"
answer_dir = OUT / "data" / "with_answers"
question_dir.mkdir(parents=True, exist_ok=True)
answer_dir.mkdir(parents=True, exist_ok=True)
qwriter = pq.ParquetWriter(question_dir / "train.parquet", question_schema, compression="zstd")
awriter = pq.ParquetWriter(answer_dir / "train.parquet", answer_schema, compression="zstd")
qbatch, abatch = [], []
domain_counts = Counter()
answer_counts = Counter()
try:
for record in records.values():
basic = {key: record[key] for key in ("difficulty", "source", "domain", "conversations")}
domain_counts[record["domain"]] += 1
answer = record["best_answer"]
method = record["answer_method"]
support = 1 if answer is not None else 0
confidence = "medium" if answer is not None else "none"
if record["domain"] == "math":
votes = record["answer_candidates"].most_common()
if votes and (len(votes) == 1 or votes[0][1] > votes[1][1]):
answer, support = votes[0]
method = "final_boxed_or_labeled"
confidence = "high" if support >= 2 else "medium"
elif votes:
answer, method, support, confidence = None, "conflicting_answers", 0, "none"
if answer is None and method is None:
method = "no_explicit_final_answer"
answer_counts[record["domain"] + ":" + ("answered" if answer is not None else "null")] += 1
qbatch.append(basic)
abatch.append({**basic, "answer": answer, "answer_method": method, "answer_confidence": confidence, "response_count": record["responses"], "answer_support": support})
if len(qbatch) >= 2000:
qwriter.write_table(pa.Table.from_pylist(qbatch, schema=question_schema))
awriter.write_table(pa.Table.from_pylist(abatch, schema=answer_schema))
qbatch.clear(); abatch.clear()
if qbatch:
qwriter.write_table(pa.Table.from_pylist(qbatch, schema=question_schema))
awriter.write_table(pa.Table.from_pylist(abatch, schema=answer_schema))
finally:
qwriter.close(); awriter.close()
report = {"source_repo": "open-thoughts/OpenThoughts3-1.2M", "source_revision": "61bcf9d4eb38b30295efc2021227a63cc5bb34c8", "benchmark_counts": benchmark_counts, "anchor_count": anchor_count, "counts": dict(counts), "domain_counts": dict(domain_counts), "answer_counts": dict(answer_counts), "removed_by_benchmark": dict(removed_by_benchmark), "method": "Exact question deduplication; casefolded NFKC alphanumeric exact matching; 4-10 word anchor candidate retrieval followed by normalized containment or RapidFuzz ratio >=82 (benchmark token coverage >=0.55), or partial ratio >=88 (coverage >=0.70, benchmark <=800 characters, source <=3000 characters). Answers are extracted only from completed final response sections after </think>; no correctness guarantee."}
(OUT / "processing_report.json").write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n")
(ROOT / "work" / "removed_audit.jsonl").write_text("".join(json.dumps(x, ensure_ascii=False) + "\n" for x in audit))
print(json.dumps(report, indent=2), flush=True)
if __name__ == "__main__":
main()
|