"""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("") if marker < 0: return None final = response[marker + len("") :].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 ; 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()