Download tools/prepare_data.py from Shangy/DR-256: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/Shangy/DR-256/resolve/main/tools/prepare_data.py
- Command line
-
hf download hf://datasets/Shangy/DR-256/tools/prepare_data.py
-
curl -L -o prepare_data.py https://huggingface.co/datasets/Shangy/DR-256/resolve/main/tools/prepare_data.py
10.4 kB
| #!/usr/bin/env python3 | |
| """Prepare leak-free Miles RL/eval JSONL from the public DeepResearch-9K files. | |
| DeepResearch-9K contains all 9,000 generated rows. DeepResearch-Hard is an | |
| exact row-level subset containing the 3,974 trajectories the teacher failed. | |
| The default split deduplicates the four repeated questions and keeps a | |
| question entirely on one side of the split. Use ``--split-unit row`` only when | |
| the paper's 7,226/1,774 row counts are more important than question leakage. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import random | |
| from collections import Counter, defaultdict | |
| from pathlib import Path | |
| from typing import Any | |
| try: | |
| from .common import normalize_question, question_key, stable_qid, to_plain, trajectory_fingerprint, write_jsonl | |
| except ImportError: # direct script execution | |
| from common import normalize_question, question_key, stable_qid, to_plain, trajectory_fingerprint, write_jsonl | |
| SYSTEM_PROMPT = """You are an expert deep-research agent. Answer the user's question precisely using the local search snapshot. Search broadly enough to identify the relevant entities, open promising sources, cross-check the evidence, and then submit a concise answer. | |
| You have access to these functions: | |
| <function=search> | |
| <parameter=query>search query</parameter> | |
| <parameter=topk>optional result count</parameter> | |
| </function> | |
| <function=open_page> | |
| <parameter=docid>document id from search results</parameter> | |
| </function> | |
| <function=finish> | |
| <parameter=answer>final answer only</parameter> | |
| <parameter=explanation>brief evidence-grounded explanation with docids</parameter> | |
| <parameter=confidence>optional confidence from 0% to 100%</parameter> | |
| </function> | |
| Every reply must end with exactly one valid function call. Do not claim access to the live web: this is a fixed local corpus, so try alternate queries when a page is unavailable.""" | |
| def load_parquet_rows(path: Path) -> list[dict[str, Any]]: | |
| import pandas as pd | |
| frame = pd.read_parquet(path) | |
| required = {"question", "difficulty", "search trajectory", "final answer"} | |
| missing = required - set(frame.columns) | |
| if missing: | |
| raise ValueError(f"{path} is missing columns: {sorted(missing)}") | |
| return [to_plain(row) for row in frame.to_dict(orient="records")] | |
| def classify_teacher_results(main_rows: list[dict[str, Any]], hard_rows: list[dict[str, Any]]) -> list[dict[str, Any]]: | |
| """Mark rows using exact trajectory fingerprints, including duplicates.""" | |
| remaining_hard = Counter(trajectory_fingerprint(row) for row in hard_rows) | |
| classified: list[dict[str, Any]] = [] | |
| for dataset_row, source in enumerate(main_rows): | |
| row = dict(source) | |
| fingerprint = trajectory_fingerprint(row) | |
| is_hard = remaining_hard[fingerprint] > 0 | |
| if is_hard: | |
| remaining_hard[fingerprint] -= 1 | |
| row["_dataset_row"] = dataset_row | |
| row["_fingerprint"] = fingerprint | |
| row["_teacher_correct"] = not is_hard | |
| classified.append(row) | |
| unmatched = sum(remaining_hard.values()) | |
| if unmatched: | |
| raise ValueError(f"DeepResearch-Hard contains {unmatched} rows not found exactly in the main parquet") | |
| return classified | |
| def collapse_questions(rows: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: | |
| """Deduplicate questions, preferring a correct teacher trajectory when one exists.""" | |
| grouped: dict[str, list[dict[str, Any]]] = defaultdict(list) | |
| for row in rows: | |
| grouped[question_key(row["question"])].append(row) | |
| collapsed: list[dict[str, Any]] = [] | |
| duplicate_report: list[dict[str, Any]] = [] | |
| for group in grouped.values(): | |
| ordered = sorted(group, key=lambda row: (not row["_teacher_correct"], row["_fingerprint"])) | |
| representative = dict(ordered[0]) | |
| representative["_teacher_correct"] = any(row["_teacher_correct"] for row in group) | |
| representative["_dataset_rows"] = sorted(row["_dataset_row"] for row in group) | |
| representative["_fingerprints"] = sorted(row["_fingerprint"] for row in group) | |
| collapsed.append(representative) | |
| if len(group) > 1: | |
| duplicate_report.append( | |
| { | |
| "qid": stable_qid(representative["question"]), | |
| "question": normalize_question(representative["question"]), | |
| "dataset_rows": representative["_dataset_rows"], | |
| "teacher_correct_by_row": [ | |
| bool(row["_teacher_correct"]) for row in sorted(group, key=lambda row: row["_dataset_row"]) | |
| ], | |
| } | |
| ) | |
| return sorted(collapsed, key=lambda row: row["_dataset_row"]), duplicate_report | |
| def assign_qids(rows: list[dict[str, Any]], split_unit: str) -> None: | |
| used: Counter[str] = Counter() | |
| for row in rows: | |
| base = stable_qid(row["question"]) | |
| if split_unit == "question": | |
| row["_qid"] = base | |
| continue | |
| candidate = f"{base}-{row['_fingerprint'][:10]}" | |
| used[candidate] += 1 | |
| row["_qid"] = candidate if used[candidate] == 1 else f"{candidate}-{used[candidate]}" | |
| def split_rows( | |
| rows: list[dict[str, Any]], *, hard_train_count: int, seed: int | |
| ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: | |
| correct = [row for row in rows if row["_teacher_correct"]] | |
| hard = [row for row in rows if not row["_teacher_correct"]] | |
| if hard_train_count < 0 or hard_train_count > len(hard): | |
| raise ValueError(f"hard_train_count must be between 0 and {len(hard)}, got {hard_train_count}") | |
| shuffled = sorted(hard, key=lambda row: row["_qid"]) | |
| random.Random(seed).shuffle(shuffled) | |
| train = correct + shuffled[:hard_train_count] | |
| test = shuffled[hard_train_count:] | |
| return sorted(train, key=lambda row: row["_qid"]), sorted(test, key=lambda row: row["_qid"]) | |
| def build_record(row: dict[str, Any], split: str, split_unit: str) -> dict[str, Any]: | |
| question = normalize_question(str(row["question"])) | |
| answer = str(row["final answer"]).strip() | |
| if not question or not answer: | |
| raise ValueError(f"row {row['_dataset_row']} has an empty question or answer") | |
| return { | |
| "prompt": [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| { | |
| "role": "user", | |
| "content": ( | |
| "Research this question using search and open_page. Use finish only after checking the evidence.\n\n" | |
| f"Question: {question}" | |
| ), | |
| }, | |
| ], | |
| "label": answer, | |
| "metadata": { | |
| "qid": row["_qid"], | |
| "manifest_qid": stable_qid(question), | |
| "question": question, | |
| "answer": answer, | |
| "difficulty": int(row["difficulty"]), | |
| "teacher_correct": bool(row["_teacher_correct"]), | |
| "data_source": f"deepresearch9k_{split}", | |
| "split_unit": split_unit, | |
| "dataset_rows": row.get("_dataset_rows", [row["_dataset_row"]]), | |
| "row_fingerprints": row.get("_fingerprints", [row["_fingerprint"]]), | |
| }, | |
| } | |
| def prepare( | |
| main_path: Path, | |
| hard_path: Path, | |
| output_dir: Path, | |
| *, | |
| split_unit: str = "question", | |
| hard_train_count: int = 2200, | |
| seed: int = 42, | |
| ) -> dict[str, Any]: | |
| main_rows = load_parquet_rows(main_path) | |
| hard_rows = load_parquet_rows(hard_path) | |
| classified = classify_teacher_results(main_rows, hard_rows) | |
| row_correct = sum(row["_teacher_correct"] for row in classified) | |
| collapsed, duplicate_report = collapse_questions(classified) | |
| selected = collapsed if split_unit == "question" else classified | |
| assign_qids(selected, split_unit) | |
| train, test = split_rows(selected, hard_train_count=hard_train_count, seed=seed) | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| write_jsonl(output_dir / "train.jsonl", (build_record(row, "train", split_unit) for row in train)) | |
| write_jsonl(output_dir / "test.jsonl", (build_record(row, "test", split_unit) for row in test)) | |
| write_jsonl(output_dir / "duplicate_questions.jsonl", duplicate_report) | |
| train_questions = {question_key(row["question"]) for row in train} | |
| test_questions = {question_key(row["question"]) for row in test} | |
| summary = { | |
| "main_rows": len(main_rows), | |
| "hard_rows": len(hard_rows), | |
| "row_teacher_correct": row_correct, | |
| "row_teacher_failed": len(classified) - row_correct, | |
| "unique_questions": len(collapsed), | |
| "duplicate_question_groups": len(duplicate_report), | |
| "split_unit": split_unit, | |
| "seed": seed, | |
| "hard_train_count": hard_train_count, | |
| "train_records": len(train), | |
| "test_records": len(test), | |
| "train_teacher_correct": sum(row["_teacher_correct"] for row in train), | |
| "train_teacher_failed": sum(not row["_teacher_correct"] for row in train), | |
| "test_teacher_failed": sum(not row["_teacher_correct"] for row in test), | |
| "question_overlap": len(train_questions & test_questions), | |
| "warning": ( | |
| "The public trajectories omit tool observations and are not standalone SFT conversations. " | |
| "Reconstruct evidence before using them for SFT." | |
| ), | |
| } | |
| (output_dir / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8") | |
| return summary | |
| def main() -> None: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--main", type=Path, required=True, help="DeepResearch-9K parquet") | |
| parser.add_argument("--hard", type=Path, required=True, help="DeepResearch-Hard parquet") | |
| parser.add_argument("--output-dir", type=Path, required=True) | |
| parser.add_argument( | |
| "--split-unit", | |
| choices=("question", "row"), | |
| default="question", | |
| help="question prevents leakage; row reproduces the paper's row counts", | |
| ) | |
| parser.add_argument("--hard-train-count", type=int, default=2200) | |
| parser.add_argument("--seed", type=int, default=42) | |
| args = parser.parse_args() | |
| summary = prepare( | |
| args.main, | |
| args.hard, | |
| args.output_dir, | |
| split_unit=args.split_unit, | |
| hard_train_count=args.hard_train_count, | |
| seed=args.seed, | |
| ) | |
| print(json.dumps(summary, indent=2, sort_keys=True)) | |
| if __name__ == "__main__": | |
| main() | |