#!/usr/bin/env python3 """Repair math benchmark cache predictions/correct flags in place using current answer parsing.""" from __future__ import annotations import argparse import json import sys from collections import Counter, defaultdict from pathlib import Path from tempfile import NamedTemporaryFile from typing import Any, Dict, Iterable, Iterator, List, Tuple PROJECT_ROOT = Path(__file__).resolve().parents[1] if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from answer_utils import ( check_answer, extract_answer, extract_confidence_reason, repair_confidence_reason_record_fields, ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--root", default="cache/benchmarks/math", help="Math benchmark cache root to repair. Default: cache/benchmarks/math", ) parser.add_argument( "--dry-run", action="store_true", help="Report intended changes without rewriting files.", ) parser.add_argument( "--verbose", action="store_true", help="Print per-file change counts.", ) return parser.parse_args() def _safe_str(value: Any) -> str: if value is None: return "" return str(value).strip() def _iter_stage_files(root: Path) -> Iterator[Path]: for path in sorted(root.rglob("*.stage*.cached.jsonl")): if path.is_file(): yield path def _iter_only_files(root: Path) -> Iterator[Path]: for path in sorted(root.rglob("only/*/*.jsonl")): if path.is_file(): yield path def _write_lines_atomic(path: Path, lines: List[str]) -> None: with NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as tmp: tmp.writelines(lines) tmp_path = Path(tmp.name) tmp_path.replace(path) def _repair_stage_record(record: Dict[str, Any], counts: Counter) -> Dict[str, Any]: updated = repair_confidence_reason_record_fields(record) task = _safe_str(updated.get("task")).lower() if task != "math": return updated gold = updated.get("label") for stage_idx in (1, 2, 3): raw_key = f"stage{stage_idx}_raw" pred_key = f"stage{stage_idx}_pred" correct_key = f"stage{stage_idx}_correct" raw_text = _safe_str(updated.get(raw_key)) if raw_text: new_pred = _safe_str(extract_answer(task, raw_text)) if new_pred != _safe_str(updated.get(pred_key)): updated[pred_key] = new_pred counts[f"stage{stage_idx}_pred_changed"] += 1 new_correct = bool(check_answer(task, new_pred, gold)) if bool(updated.get(correct_key, False)) != new_correct: updated[correct_key] = new_correct counts[f"stage{stage_idx}_correct_changed"] += 1 if stage_idx >= 3: continue retry_raw_key = f"stage{stage_idx}_retry_raw" retry_pred_key = f"stage{stage_idx}_retry_pred" retry_correct_key = f"stage{stage_idx}_retry_correct" retry_raw = _safe_str(updated.get(retry_raw_key)) if retry_raw: new_retry_pred = _safe_str(extract_answer(task, retry_raw)) if new_retry_pred != _safe_str(updated.get(retry_pred_key)): updated[retry_pred_key] = new_retry_pred counts[f"stage{stage_idx}_retry_pred_changed"] += 1 new_retry_correct = bool(check_answer(task, new_retry_pred, gold)) if bool(updated.get(retry_correct_key, False)) != new_retry_correct: updated[retry_correct_key] = new_retry_correct counts[f"stage{stage_idx}_retry_correct_changed"] += 1 return updated def repair_stage_file(path: Path, dry_run: bool = False) -> Counter: counts: Counter = Counter() out_lines: List[str] = [] changed = False with path.open("r", encoding="utf-8") as handle: for raw_line in handle: stripped = raw_line.strip() if not stripped: out_lines.append(raw_line) continue record = json.loads(stripped) updated = _repair_stage_record(record, counts) if updated != record: changed = True counts["records_changed"] += 1 out_lines.append(json.dumps(updated, ensure_ascii=False) + "\n") if changed and not dry_run: _write_lines_atomic(path, out_lines) if changed: counts["files_changed"] += 1 counts["files_scanned"] += 1 return counts def _only_report_for_rows(path: Path, rows: List[Dict[str, Any]]) -> Dict[str, Any]: total = len(rows) correct = sum(int(bool(row.get("correct", False))) for row in rows) report_path = path.with_suffix(".report.json") existing = json.loads(report_path.read_text(encoding="utf-8")) if report_path.exists() else {} report = dict(existing) report.update( { "path": str(path), "split": path.stem, "total": total, "correct": correct, "accuracy": (correct / total) if total else 0.0, } ) by_task = defaultdict(lambda: {"total": 0, "correct": 0}) for row in rows: task = _safe_str(row.get("task")) by_task[task]["total"] += 1 by_task[task]["correct"] += int(bool(row.get("correct", False))) if existing.get("by_task"): merged = {} for task_name, stats in dict(existing["by_task"]).items(): merged[task_name] = dict(stats) for task_name, stats in by_task.items(): merged.setdefault(task_name, {}) merged[task_name]["total"] = stats["total"] merged[task_name]["correct"] = stats["correct"] report["by_task"] = merged else: report["by_task"] = dict(by_task) return report def _repair_only_record(record: Dict[str, Any], counts: Counter) -> Dict[str, Any]: updated = repair_confidence_reason_record_fields(record) task = _safe_str(updated.get("task")).lower() if task != "math": return updated raw_text = _safe_str(updated.get("raw")) if raw_text: new_pred = _safe_str(extract_answer(task, raw_text)) if new_pred != _safe_str(updated.get("pred")): updated["pred"] = new_pred counts["pred_changed"] += 1 conf, reason = extract_confidence_reason(raw_text) if float(updated.get("conf", 0.0) or 0.0) != float(conf): updated["conf"] = float(conf) counts["conf_changed"] += 1 if _safe_str(updated.get("reason")) != _safe_str(reason): updated["reason"] = _safe_str(reason) counts["reason_changed"] += 1 new_correct = bool(check_answer(task, new_pred, updated.get("label"))) if bool(updated.get("correct", False)) != new_correct: updated["correct"] = new_correct counts["correct_changed"] += 1 return updated def repair_only_file(path: Path, dry_run: bool = False) -> Counter: counts: Counter = Counter() out_lines: List[str] = [] changed = False rows: List[Dict[str, Any]] = [] with path.open("r", encoding="utf-8") as handle: for raw_line in handle: stripped = raw_line.strip() if not stripped: out_lines.append(raw_line) continue record = json.loads(stripped) updated = _repair_only_record(record, counts) rows.append(updated) if updated != record: changed = True counts["records_changed"] += 1 out_lines.append(json.dumps(updated, ensure_ascii=False) + "\n") report = _only_report_for_rows(path, rows) report_path = path.with_suffix(".report.json") old_report = json.loads(report_path.read_text(encoding="utf-8")) if report_path.exists() else None report_changed = old_report != report if (changed or report_changed) and not dry_run: if changed: _write_lines_atomic(path, out_lines) report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8") if changed: counts["files_changed"] += 1 if report_changed: counts["reports_changed"] += 1 counts["files_scanned"] += 1 return counts def main() -> int: args = parse_args() root = Path(args.root) if not root.exists(): raise FileNotFoundError(f"Root does not exist: {root}") totals: Counter = Counter() for path in _iter_stage_files(root): file_counts = repair_stage_file(path, dry_run=args.dry_run) totals.update(file_counts) if args.verbose and (file_counts["records_changed"] or file_counts["files_changed"]): print(f"{path}: stage_records_changed={file_counts['records_changed']}") for path in _iter_only_files(root): file_counts = repair_only_file(path, dry_run=args.dry_run) totals.update(file_counts) if args.verbose and (file_counts["records_changed"] or file_counts["reports_changed"]): print( f"{path}: only_records_changed={file_counts['records_changed']} " f"reports_changed={file_counts['reports_changed']}" ) mode = "dry-run" if args.dry_run else "rewritten" print( f"[{mode}] files_scanned={totals['files_scanned']} files_changed={totals['files_changed']} " f"reports_changed={totals['reports_changed']} records_changed={totals['records_changed']}" ) for key in sorted(k for k in totals if k not in {"files_scanned", "files_changed", "reports_changed", "records_changed"}): print(f"{key}={totals[key]}") return 0 if __name__ == "__main__": raise SystemExit(main())