Datasets:
File size: 9,111 Bytes
b8ea052 | 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 | """Build a leakage-separated Common-264 experiment bundle."""
from __future__ import annotations
import json
import shutil
from collections import defaultdict
from pathlib import Path
from typing import Any
from .schema import validate_planner_input
def read_jsonl(path: Path) -> list[dict[str, Any]]:
return [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
def load(path: Path) -> dict[str, Any]:
return json.loads(path.read_text(encoding="utf-8"))
def _dependency_index(path: Path) -> dict[str, dict[str, Any]]:
grouped: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in read_jsonl(path):
grouped[str(row["case_id"])].append(row)
return {case_id: rows[0] for case_id, rows in grouped.items() if len(rows) == 1}
def _balanced_sample(rows: list[dict[str, Any]], per_level: int) -> list[dict[str, Any]]:
result: list[dict[str, Any]] = []
for level in ("L1", "L2", "L3"):
families: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in rows:
if row.get("dependency_prelabel") == level:
families[str(row["case_family"])].append(row)
for values in families.values():
values.sort(key=lambda item: (int(item["position"]), str(item["uid"])))
names = sorted(families)
selected: list[dict[str, Any]] = []
cursor = 0
while len(selected) < per_level and names:
name = names[cursor % len(names)]
if families[name]:
selected.append(families[name].pop(0))
names = [item for item in names if families[item]]
cursor += 1
if len(selected) != per_level:
raise ValueError(f"insufficient {level} cases: wanted {per_level}, found {len(selected)}")
result.extend(selected)
return sorted(result, key=lambda item: int(item["position"]))
def build_bundle(
*,
common_cases_path: Path,
portable_dir: Path,
dependency_path: Path,
output_dir: Path,
) -> dict[str, Any]:
common = read_jsonl(common_cases_path)
source_generation = read_jsonl(portable_dir / "generation_manifest.jsonl")
generation_by_uid = {str(row["uid"]): row for row in source_generation}
source_batch = load(portable_dir / "batch_manifest.json")
batch_by_uid = {str(row["uid"]): row for row in source_batch["cases"]}
source_contract_manifest = load(portable_dir / "contract_manifest.json")
contract_by_uid = {str(row["uid"]): row for row in source_contract_manifest["cases"]}
dependency = _dependency_index(dependency_path)
frozen = output_dir / "frozen"
assets = frozen / "assets"
contracts = frozen / "contracts"
assets.mkdir(parents=True, exist_ok=True)
contracts.mkdir(parents=True, exist_ok=True)
generation_rows: list[dict[str, Any]] = []
batch_rows: list[dict[str, Any]] = []
contract_rows: list[dict[str, Any]] = []
planner_rows: list[dict[str, Any]] = []
selection_rows: list[dict[str, Any]] = []
for index, common_row in enumerate(common, 1):
uid = str(common_row["uid"])
source_gen = generation_by_uid[uid]
source_asset = (portable_dir / source_gen["input_image"]).resolve()
suffix = source_asset.suffix.lower() or ".jpg"
asset_name = f"{index:03d}{suffix}"
destination = assets / asset_name
shutil.copy2(source_asset, destination)
contract_item = contract_by_uid[uid]
source_contract = (portable_dir / contract_item["contract_path"]).resolve()
contract_name = f"{index:03d}.json"
shutil.copy2(source_contract, contracts / contract_name)
relative_image = f"assets/{asset_name}"
instruction = str(source_gen["instruction"])
base_meta = {
key: source_gen.get(key)
for key in (
"position", "uid", "source_uid", "case_id", "case_family", "source", "top_level",
"approval_batch", "reasoning_depth", "primary_operator", "analysis_weight",
)
}
generation_rows.append({**base_meta, "input_image": relative_image, "instruction": instruction})
source_batch_item = batch_by_uid[uid]
batch_rows.append({**source_batch_item, "input_image": relative_image, "gt_image": None})
contract_rows.append({**contract_item, "contract_path": f"contracts/{contract_name}"})
planner_row = {
**base_meta,
"input_image": f"frozen/assets/{asset_name}",
"instruction": instruction,
}
issues = validate_planner_input(planner_row)
if issues:
raise ValueError(f"planner input leakage/schema failure for {uid}: {issues}")
planner_rows.append(planner_row)
prelabel = dependency.get(str(source_gen["case_id"]))
selection_rows.append(
{
**base_meta,
"dependency_prelabel": prelabel.get("level") if prelabel else None,
"dependency_prelabel_confidence": prelabel.get("confidence") if prelabel else None,
"dependency_prelabel_status": "single_model_sampling_only" if prelabel else "unavailable",
}
)
if len(generation_rows) != 264 or len({row["uid"] for row in generation_rows}) != 264:
raise ValueError("Common bundle must contain exactly 264 unique UIDs")
write_jsonl(frozen / "generation_manifest.jsonl", generation_rows)
write_jsonl(output_dir / "planner_inputs.jsonl", planner_rows)
write_jsonl(output_dir / "selection_manifest.jsonl", selection_rows)
(frozen / "batch_manifest.json").write_text(
json.dumps({"schema_version": "solveedit.common264_batch.v1", "case_count": 264, "cases": batch_rows}, ensure_ascii=False, indent=2) + "\n"
)
(frozen / "contract_manifest.json").write_text(
json.dumps({"schema_version": "solveedit.common264_contracts.v1", "case_count": 264, "cases": contract_rows}, ensure_ascii=False, indent=2) + "\n"
)
eligible = [row for row in selection_rows if row.get("dependency_prelabel") in {"L1", "L2", "L3"}]
pilot = _balanced_sample(eligible, 16)
pilot_uids = {row["uid"] for row in pilot}
pilot_planner = [row for row in planner_rows if row["uid"] in pilot_uids]
by_level: dict[str, list[dict[str, Any]]] = defaultdict(list)
for row in pilot:
by_level[str(row["dependency_prelabel"])].append(row)
smoke_selection = []
for level in ("L1", "L2", "L3"):
smoke_selection.extend(by_level[level][:4])
smoke_uids = {row["uid"] for row in smoke_selection}
smoke_planner = [row for row in planner_rows if row["uid"] in smoke_uids]
write_jsonl(output_dir / "pilot48_selection.jsonl", pilot)
write_jsonl(output_dir / "pilot48_planner_inputs.jsonl", pilot_planner)
write_jsonl(output_dir / "smoke12_selection.jsonl", smoke_selection)
write_jsonl(output_dir / "smoke12_planner_inputs.jsonl", smoke_planner)
def write_subset(prefix: str, wanted: set[str]) -> None:
subset_generation = [row for row in generation_rows if row["uid"] in wanted]
subset_batch = [row for row in batch_rows if row["uid"] in wanted]
subset_contracts = [row for row in contract_rows if row["uid"] in wanted]
if not (len(subset_generation) == len(subset_batch) == len(subset_contracts) == len(wanted)):
raise ValueError(f"incomplete {prefix} frozen subset")
write_jsonl(frozen / f"{prefix}_direct_manifest.jsonl", subset_generation)
(frozen / f"{prefix}_batch_manifest.json").write_text(
json.dumps(
{"schema_version": f"solveedit.{prefix}_batch.v1", "case_count": len(wanted), "cases": subset_batch},
ensure_ascii=False,
indent=2,
)
+ "\n"
)
(frozen / f"{prefix}_contract_manifest.json").write_text(
json.dumps(
{
"schema_version": f"solveedit.{prefix}_contracts.v1",
"case_count": len(wanted),
"cases": subset_contracts,
},
ensure_ascii=False,
indent=2,
)
+ "\n"
)
write_subset("smoke12", smoke_uids)
write_subset("pilot48", pilot_uids)
summary = {
"schema_version": "solveedit.harness_common264_bundle.v1",
"common_cases": 264,
"prelabel_matched": len(eligible),
"prelabel_note": "single-model metadata used only for stratified sampling; not human gold",
"pilot48": len(pilot),
"smoke12": len(smoke_selection),
"output_dir": str(output_dir.resolve()),
}
(output_dir / "bundle_summary.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n")
return summary
|