research-logs / scripts /aime_ensemble_selector.py
oof-baroomf's picture
Add AIME20 ensemble selector result
f0e27bf verified
Raw
History Blame Contribute Delete
6.29 kB
from __future__ import annotations
import argparse
import json
import re
from collections import Counter
from pathlib import Path
from eval_answer_utils import extract_final_answer
RUNS = {
"qwen_full": "runs/20260408T070936Z_aime20_qwen4b_instruct_english/results.jsonl",
"qwen_repair": "runs/20260408T070936Z_aime20_qwen4b_instruct_english_repair/results.jsonl",
"qwen_cont": (
"runs/20260408T070936Z_aime20_qwen4b_instruct_english_continuation_repaired/results.jsonl"
),
"alt": "runs/20260408T070936Z_aime20_qwen4b_instruct_lfm25_alternating_repaired/results.jsonl",
"gemma": "runs/20260408T103238Z_aime20_gemma4e4b_thinking/results.jsonl",
"gemma_sr": "runs/20260409T125112Z_aime20_gemma4e4b_thinking_self_repair/results.jsonl",
}
PRIORITY = ["qwen_cont", "alt", "gemma", "gemma_sr", "qwen_full"]
REPAIR_BAD_MARKERS = (
"known solution",
"known problem",
"known similar",
"given the time",
"not sure",
"guess",
"i think i will go",
"in the absence",
"typo",
)
INTEGER_ANSWER_RE = re.compile(r"^0*\d{1,3}$")
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--out-dir", required=True)
return parser.parse_args()
def load_records(path: Path) -> list[dict[str, object]]:
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
def answer_source(record: dict[str, object]) -> str:
return str(
record.get("raw_output") or record.get("final") or record.get("predicted_answer") or ""
)
def integer_answer(record: dict[str, object]) -> str | None:
answer = extract_final_answer(answer_source(record)).strip().strip(" .")
if INTEGER_ANSWER_RE.fullmatch(answer) is None:
return None
return str(int(answer))
def clean_repair(record: dict[str, object]) -> bool:
source = answer_source(record).lower()
return (
integer_answer(record) is not None
and record.get("finish_reason") == "stop"
and not any(marker in source for marker in REPAIR_BAD_MARKERS)
)
def majority_vote(votes: list[tuple[str, str]]) -> tuple[str | None, list[str]]:
if not votes:
return None, []
counts = Counter(answer for answer, _ in votes)
answer = sorted(
counts,
key=lambda value: (
-counts[value],
min(PRIORITY.index(name) for candidate, name in votes if candidate == value),
),
)[0]
return answer, [name for candidate, name in votes if candidate == answer]
def select_answer(records: dict[str, dict[str, object]]) -> tuple[str | None, list[str], str]:
votes = []
for name in PRIORITY:
if name in records:
answer = integer_answer(records[name])
if answer is not None:
votes.append((answer, name))
answer, sources = majority_vote(votes)
rationale = f"majority_{len(sources)}" if sources else "no_integer_vote"
repair = records.get("qwen_repair")
if repair is not None and clean_repair(repair) and len(sources) <= 2:
repair_answer = integer_answer(repair)
if repair_answer is None:
raise ValueError(f"clean repair without integer answer for {repair['id']}")
return repair_answer, ["qwen_repair"], "clean_qwen_repair_override"
return answer, sources, rationale
def evaluate(records_by_id: dict[str, dict[str, dict[str, object]]]) -> list[dict[str, object]]:
rows = []
for problem_id in sorted(records_by_id):
records = records_by_id[problem_id]
gold = str(int(str(next(iter(records.values()))["gold_answer"])))
answer, sources, rationale = select_answer(records)
votes = {}
for name, record in sorted(records.items()):
vote = integer_answer(record)
if vote is not None:
votes[name] = vote
rows.append(
{
"id": problem_id,
"gold_answer": gold,
"selected_answer": answer,
"correct": answer == gold,
"selected_sources": sources,
"rationale": rationale,
"integer_votes": votes,
"oracle_correct_in_selected_runs": any(
bool(record.get("correct")) for record in records.values()
),
}
)
return rows
def load_runs() -> dict[str, dict[str, dict[str, object]]]:
records_by_id: dict[str, dict[str, dict[str, object]]] = {}
for name, path_text in RUNS.items():
path = Path(path_text)
if not path.exists():
raise FileNotFoundError(path)
for record in load_records(path):
problem_id = str(record["id"])
if problem_id.startswith("aime24_"):
records_by_id.setdefault(problem_id, {})[name] = record
return records_by_id
def summarize(
rows: list[dict[str, object]],
records_by_id: dict[str, dict[str, dict[str, object]]],
) -> dict[str, object]:
total = len(rows)
correct = sum(bool(row["correct"]) for row in rows)
oracle_correct = sum(bool(row["oracle_correct_in_selected_runs"]) for row in rows)
single_run_scores = {
name: sum(
bool(records.get(name, {}).get("correct")) for records in records_by_id.values()
)
for name in RUNS
}
return {
"correct": correct,
"total": total,
"accuracy": correct / total,
"oracle_correct_in_selected_runs": oracle_correct,
"best_single_run_correct": max(single_run_scores.values()),
"single_run_scores": single_run_scores,
"runs": RUNS,
}
def main() -> None:
args = parse_args()
records_by_id = load_runs()
rows = evaluate(records_by_id)
summary = summarize(rows, records_by_id)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
with (out_dir / "results.jsonl").open("w") as handle:
for row in rows:
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
(out_dir / "summary.json").write_text(
json.dumps(summary, indent=2, ensure_ascii=False) + "\n"
)
print(json.dumps(summary, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()