File size: 10,637 Bytes
fb4347b | 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 |
import argparse
import json
import os
from collections import defaultdict
from pathlib import Path
import pandas as pd
from datasets import load_dataset, load_from_disk
DEFAULT_JSON_COLUMNS = ["extra_metadata"]
DERIVED_CONFIGS = {"correctness_labels"}
PAIRWISE_CONFIG = "pairwise_judgments"
RAW_JUDGE_CONFIGS = {
"pairwise_raw",
"correctness_raw",
"diversity_baseline_raw",
"anti_prompt_raw",
"anti_prompt_pairwise_raw",
"single_prompt_raw",
"validation_raw",
}
CLUSTERING_RAW_CONFIG = "clustering_raw"
JSON_RECORD_CONFIGS = {
"diversity_samples": Path("data/postprocess/matharena_proofs/diversity_samples.json"),
"human_solutions": Path("data/postprocess/matharena_proofs/human_sols_ok.json"),
"all_solutions": Path("data/postprocess/matharena_proofs/all_sols_ok.json"),
"raw_problems": Path("data/raw/matharena_proofs/sample.json"),
"human_solutions_sample": Path("data/postprocess/matharena_proofs/human_sols_sample.json"),
"technique_verifier_samples": Path(
"data/postprocess/technique_adaptivity/verifier_agreement_samples.json"
),
}
OUTPUTS_DIR = Path("outputs")
# eval_package.py reads data/results/*.pkl, but the Sec. 4 and validation
# scripts (single_prompt_diversity_eval.py, technique_verifier_agreement.py,
# diversity_eval.py, ...) read the outputs/ trees directly. The caches carry
# every field those trees need, so rebuild the trees from them rather than
# shipping the same judgments twice.
JUDGE_ORG_DEFAULT = "openai"
# Settings that ship as complete raw trees. Their cache is `is_valid`-filtered,
# so rebuilding a tree from it would under-count solutions; never let the
# rebuild clobber the shipped tree.
TREE_SHIPPED_SETTINGS = {
"summary_diversity_clustering_main",
"answer_checker_diversity",
"completeness_checker_diversity",
}
def load_config(args, name: str):
if args.from_hub:
return load_dataset(args.repo_id, name, split="train", token=os.environ.get("HF_API_KEY"))
return load_from_disk(str(Path(args.source) / name))
def list_configs(args) -> list[str]:
if args.from_hub:
from datasets import get_dataset_config_names
return get_dataset_config_names(args.repo_id, token=os.environ.get("HF_API_KEY"))
return sorted(p.name for p in Path(args.source).iterdir() if (p / "dataset_info.json").exists())
def restore_setting(name: str, ds, results_dir: Path, json_columns: list[str], overwrite: bool,
rebuild_trees: bool = True) -> None:
out_path = results_dir / f"{name}.pkl"
if out_path.exists() and not overwrite:
print(f" [skip] {out_path} already exists (use --overwrite to replace)")
return
df = ds.to_pandas()
for col in json_columns:
if col in df.columns:
df[col] = df[col].apply(lambda v: json.loads(v) if isinstance(v, str) else v)
for col in ("outputs", "judgements"):
if col not in df.columns:
continue
flag_col = f"_{col}_was_scalar"
if flag_col in df.columns:
df[col] = [
(list(v)[0] if len(v) else None) if scalar else (list(v) if v is not None else [])
for v, scalar in zip(df[col], df[flag_col])
]
df = df.drop(columns=[flag_col])
else:
df[col] = df[col].apply(lambda v: list(v) if v is not None else [])
df.to_pickle(out_path)
print(f" restored {name}: {len(df)} rows -> {out_path}")
if rebuild_trees:
rebuild_tree_from_cache(name, df, overwrite)
def rebuild_tree_from_cache(name: str, df: pd.DataFrame, overwrite: bool) -> None:
"""Materialise outputs/<setting>/<judge>/<solver>/<problem>.json from a cache."""
if name in TREE_SHIPPED_SETTINGS:
print(f" [skip] {name} tree ships complete in diversity_baseline_raw")
return
required = {"judge", "solver_id", "problem_id", "outputs"}
if not required.issubset(df.columns):
return
written = skipped = 0
for _, row in df.iterrows():
judge = str(row["judge"])
if "/" not in judge:
judge = f"{JUDGE_ORG_DEFAULT}/{judge}"
out_path = (
OUTPUTS_DIR / name / judge / str(row["solver_id"])
/ f"{str(row['problem_id']).replace('/', '_')}.json"
)
if out_path.exists() and not overwrite:
skipped += 1
continue
outputs = row["outputs"]
if not isinstance(outputs, list):
outputs = [] if outputs is None else [outputs]
record = {
"model_id": row["solver_id"],
"problem_id": row["problem_id"],
"problem": row.get("problem"),
"solution": row.get("solution"),
"outputs": list(outputs),
# Per-sample verdicts are re-derived from `outputs` by the readers'
# documented fallback, so they are not duplicated here.
"judgements": None,
"majority_vote": row.get("true_grade"),
}
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
json.dump(record, f)
written += 1
print(f" rebuilt {name} tree: {written} files written, {skipped} already existed")
def restore_pairwise(ds, results_dir: Path, overwrite: bool) -> None:
groups: dict[tuple[str, str, str], list[dict]] = defaultdict(list)
for row in ds:
key = (row["metric"], row["setting"], row["judge"])
groups[key].append(
{"model_a": row["model_a"], "model_b": row["model_b"], "winner": row["winner"]}
)
for (metric, setting, judge), entries in sorted(groups.items()):
out_path = results_dir / f"pairwise_{metric}_{setting}_{judge.replace('/', '_')}.json"
if out_path.exists() and not overwrite:
print(f" [skip] {out_path.name} already exists (use --overwrite to replace)")
continue
with open(out_path, "w") as f:
json.dump(entries, f)
print(f" restored {out_path.name}: {len(entries)} judgments")
def restore_raw_judge(ds, overwrite: bool) -> None:
written = skipped = 0
for row in ds:
out_path = OUTPUTS_DIR / row["project"] / row["judge"] / row["relpath"]
if out_path.exists() and not overwrite:
skipped += 1
continue
out_path.parent.mkdir(parents=True, exist_ok=True)
record = {
"model_id": row["model_id"],
"problem_id": row["problem_id"],
"majority_vote": row["majority_vote"],
"judgements": json.loads(row["judgements"]) if row["judgements"] else None,
"outputs": json.loads(row["outputs"]) if row["outputs"] else None,
}
for field in ("problem", "solution"):
if field in row:
record[field] = json.loads(row[field]) if row[field] else None
with open(out_path, "w") as f:
json.dump(record, f)
written += 1
print(f" restored raw judge files: {written} written, {skipped} already existed")
def restore_clustering_raw(ds, overwrite: bool) -> None:
written = skipped = 0
for row in ds:
out_path = OUTPUTS_DIR / row["project"] / row["judge"] / row["relpath"]
if out_path.exists() and not overwrite:
skipped += 1
continue
out_path.parent.mkdir(parents=True, exist_ok=True)
record = {
"problem_id": row["problem_id"],
"model_id": row["model_id"],
"outputs": json.loads(row["outputs"]) if row["outputs"] else None,
}
with open(out_path, "w") as f:
json.dump(record, f)
written += 1
print(f" restored raw clustering files: {written} written, {skipped} already existed")
def restore_json_records(name: str, ds, overwrite: bool) -> None:
out_path = JSON_RECORD_CONFIGS[name]
if out_path.exists() and not overwrite:
print(f" [skip] {out_path} already exists (use --overwrite to replace)")
return
out_path.parent.mkdir(parents=True, exist_ok=True)
samples = [json.loads(row["record"]) for row in ds]
with open(out_path, "w", encoding="utf-8") as f:
json.dump(samples, f)
print(f" restored {out_path}: {len(samples)} entries")
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--source", default="data/hf_export", help="local export directory (default mode)")
ap.add_argument("--from-hub", action="store_true", help="download from the Hub instead of a local directory")
ap.add_argument("--repo-id", default=None, help="HF repo id, required with --from-hub")
ap.add_argument("--results-dir", default="data/results", help="destination directory")
ap.add_argument("--configs", nargs="*", default=None, help="subset of configs to restore (default: all)")
ap.add_argument("--json-columns", nargs="*", default=DEFAULT_JSON_COLUMNS,
help="string columns to decode back into objects")
ap.add_argument("--overwrite", action="store_true", help="replace existing files in --results-dir")
ap.add_argument("--no-rebuild-trees", action="store_true",
help="skip rebuilding the outputs/ judge trees from the restored caches "
"(they are what the Sec. 4 and validation scripts read)")
args = ap.parse_args()
if args.from_hub and not args.repo_id:
ap.error("--from-hub requires --repo-id")
results_dir = Path(args.results_dir)
results_dir.mkdir(parents=True, exist_ok=True)
configs = args.configs if args.configs else list_configs(args)
for name in configs:
if name in DERIVED_CONFIGS:
print(f"Skipping derived config {name} (re-derived by eval_package.py)")
continue
print(f"Loading {name}...")
ds = load_config(args, name)
if name == PAIRWISE_CONFIG:
restore_pairwise(ds, results_dir, args.overwrite)
elif name in RAW_JUDGE_CONFIGS:
restore_raw_judge(ds, args.overwrite)
elif name == CLUSTERING_RAW_CONFIG:
restore_clustering_raw(ds, args.overwrite)
elif name in JSON_RECORD_CONFIGS:
restore_json_records(name, ds, args.overwrite)
else:
restore_setting(name, ds, results_dir, args.json_columns, args.overwrite,
rebuild_trees=not args.no_rebuild_trees)
print("\nDone. eval_package.py will pick these up from --results-dir on its next run.")
if __name__ == "__main__":
main()
|