File size: 10,417 Bytes
a06d854 | 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 | #!/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()
|