rileyherchert commited on
Commit ·
ca8650e
1
Parent(s): 9ef0b4d
Added arithmetic and number analysis
Browse files- analyze_prompt_number_coverage.py +287 -0
- analyze_reasoning_arithmetic.py +683 -0
analyze_prompt_number_coverage.py
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# dependencies = ["inspect-ai"]
|
| 3 |
+
# ///
|
| 4 |
+
"""Measure whether every number in each prompt appears in the model response.
|
| 5 |
+
|
| 6 |
+
Numbers are matched as complete numeric tokens and normalized by value, so
|
| 7 |
+
10, 10.0, and 10,000-style formatting compare consistently. Repeated prompt
|
| 8 |
+
values are treated as one distinct number.
|
| 9 |
+
|
| 10 |
+
Example:
|
| 11 |
+
uv run hf_dataset/analyze_prompt_number_coverage.py hf_dataset/logs/example.eval
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import csv
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 22 |
+
from decimal import Decimal, InvalidOperation
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Any
|
| 25 |
+
|
| 26 |
+
from inspect_ai.log import read_eval_log
|
| 27 |
+
|
| 28 |
+
NUMBER_RE = re.compile(
|
| 29 |
+
r"(?<![\w.])[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?(?!\w|\.\d)"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def normalize_number(token: str) -> Decimal | None:
|
| 34 |
+
"""Return a canonical numeric value for a matched token."""
|
| 35 |
+
try:
|
| 36 |
+
value = Decimal(token.replace(",", ""))
|
| 37 |
+
except InvalidOperation:
|
| 38 |
+
return None
|
| 39 |
+
return value.normalize() if value else Decimal(0)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def extract_numbers(text: str) -> set[Decimal]:
|
| 43 |
+
"""Extract distinct, normalized numeric tokens from text."""
|
| 44 |
+
numbers = {normalize_number(match.group(0)) for match in NUMBER_RE.finditer(text)}
|
| 45 |
+
numbers.discard(None)
|
| 46 |
+
return numbers
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def display_number(value: Decimal) -> str:
|
| 50 |
+
"""Format a normalized Decimal without scientific notation."""
|
| 51 |
+
rendered = format(value, "f")
|
| 52 |
+
if "." in rendered:
|
| 53 |
+
rendered = rendered.rstrip("0").rstrip(".")
|
| 54 |
+
return rendered or "0"
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def score_to_bool(sample: Any) -> bool | None:
|
| 58 |
+
"""Read the preferred final-answer score from an Inspect sample."""
|
| 59 |
+
scores = sample.scores or {}
|
| 60 |
+
for preferred in ("math", "pattern"):
|
| 61 |
+
if preferred not in scores:
|
| 62 |
+
continue
|
| 63 |
+
value = getattr(scores[preferred], "value", scores[preferred])
|
| 64 |
+
if isinstance(value, bool):
|
| 65 |
+
return value
|
| 66 |
+
if isinstance(value, (int, float)):
|
| 67 |
+
return bool(value)
|
| 68 |
+
if isinstance(value, str):
|
| 69 |
+
normalized = value.strip().upper()
|
| 70 |
+
if normalized in {"C", "CORRECT", "TRUE", "1"}:
|
| 71 |
+
return True
|
| 72 |
+
if normalized in {"I", "INCORRECT", "FALSE", "0"}:
|
| 73 |
+
return False
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def safe_rate(numerator: int, denominator: int) -> float | None:
|
| 78 |
+
return numerator / denominator if denominator else None
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def summarize_group(rows: list[dict[str, Any]]) -> dict[str, Any]:
|
| 82 |
+
covered = sum(row["all_prompt_numbers_present"] for row in rows)
|
| 83 |
+
return {
|
| 84 |
+
"samples": len(rows),
|
| 85 |
+
"samples_with_all_prompt_numbers_present": covered,
|
| 86 |
+
"samples_missing_prompt_numbers": len(rows) - covered,
|
| 87 |
+
"all_prompt_numbers_present_rate": safe_rate(covered, len(rows)),
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def analyze_log(path: Path, max_samples: int | None = None) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
| 92 |
+
log = read_eval_log(str(path))
|
| 93 |
+
samples = (log.samples or [])[:max_samples]
|
| 94 |
+
sample_rows: list[dict[str, Any]] = []
|
| 95 |
+
|
| 96 |
+
for sample in samples:
|
| 97 |
+
prompt = sample.input if isinstance(sample.input, str) else str(sample.input)
|
| 98 |
+
response = sample.output.completion
|
| 99 |
+
prompt_numbers = extract_numbers(prompt)
|
| 100 |
+
response_numbers = extract_numbers(response)
|
| 101 |
+
missing_numbers = prompt_numbers - response_numbers
|
| 102 |
+
|
| 103 |
+
sample_rows.append(
|
| 104 |
+
{
|
| 105 |
+
"log": path.name,
|
| 106 |
+
"model": log.eval.model,
|
| 107 |
+
"task": log.eval.task,
|
| 108 |
+
"sample_id": sample.id,
|
| 109 |
+
"epoch": sample.epoch,
|
| 110 |
+
"source_id": (sample.metadata or {}).get("source_id"),
|
| 111 |
+
"language": (sample.metadata or {}).get("language"),
|
| 112 |
+
"final_correct": score_to_bool(sample),
|
| 113 |
+
"prompt_number_count": len(prompt_numbers),
|
| 114 |
+
"prompt_numbers": " | ".join(display_number(value) for value in sorted(prompt_numbers)),
|
| 115 |
+
"missing_prompt_number_count": len(missing_numbers),
|
| 116 |
+
"missing_prompt_numbers": " | ".join(display_number(value) for value in sorted(missing_numbers)),
|
| 117 |
+
"all_prompt_numbers_present": not missing_numbers,
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
final_scored = [row for row in sample_rows if row["final_correct"] is not None]
|
| 122 |
+
final_correct_rows = [row for row in final_scored if row["final_correct"]]
|
| 123 |
+
final_incorrect_rows = [row for row in final_scored if not row["final_correct"]]
|
| 124 |
+
correct_summary = summarize_group(final_correct_rows)
|
| 125 |
+
incorrect_summary = summarize_group(final_incorrect_rows)
|
| 126 |
+
correct_rate = correct_summary["all_prompt_numbers_present_rate"]
|
| 127 |
+
incorrect_rate = incorrect_summary["all_prompt_numbers_present_rate"]
|
| 128 |
+
|
| 129 |
+
summary = {
|
| 130 |
+
"log": path.name,
|
| 131 |
+
"status": str(log.status),
|
| 132 |
+
"model": log.eval.model,
|
| 133 |
+
"task": log.eval.task,
|
| 134 |
+
"samples": len(samples),
|
| 135 |
+
"final_scored_samples": len(final_scored),
|
| 136 |
+
"final_accuracy": safe_rate(
|
| 137 |
+
sum(row["final_correct"] for row in final_scored),
|
| 138 |
+
len(final_scored),
|
| 139 |
+
),
|
| 140 |
+
"samples_with_all_prompt_numbers_present": sum(
|
| 141 |
+
row["all_prompt_numbers_present"] for row in sample_rows
|
| 142 |
+
),
|
| 143 |
+
"all_prompt_numbers_present_rate": safe_rate(
|
| 144 |
+
sum(row["all_prompt_numbers_present"] for row in sample_rows),
|
| 145 |
+
len(sample_rows),
|
| 146 |
+
),
|
| 147 |
+
"number_coverage_breakdown": {
|
| 148 |
+
"final_correct": correct_summary,
|
| 149 |
+
"final_incorrect": incorrect_summary,
|
| 150 |
+
},
|
| 151 |
+
"correct_minus_incorrect_percentage_points": (
|
| 152 |
+
(correct_rate - incorrect_rate) * 100
|
| 153 |
+
if correct_rate is not None and incorrect_rate is not None
|
| 154 |
+
else None
|
| 155 |
+
),
|
| 156 |
+
"matcher": "distinct normalized complete numeric tokens",
|
| 157 |
+
"note": (
|
| 158 |
+
"A sample is covered when every distinct numeric value in the original prompt "
|
| 159 |
+
"appears somewhere in the full model completion."
|
| 160 |
+
),
|
| 161 |
+
}
|
| 162 |
+
return summary, sample_rows
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def discover_logs(inputs: list[Path]) -> list[Path]:
|
| 166 |
+
logs: set[Path] = set()
|
| 167 |
+
for path in inputs:
|
| 168 |
+
if path.is_dir():
|
| 169 |
+
logs.update(candidate for candidate in path.rglob("*.eval") if candidate.stat().st_size >= 1_000)
|
| 170 |
+
elif path.suffix == ".eval" and path.stat().st_size >= 1_000:
|
| 171 |
+
logs.add(path)
|
| 172 |
+
return sorted(logs)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def resolve_worker_count(requested: int | None, log_count: int) -> int:
|
| 176 |
+
if requested is not None and requested < 1:
|
| 177 |
+
raise ValueError("--workers must be at least 1.")
|
| 178 |
+
default = min(4, os.cpu_count() or 1)
|
| 179 |
+
return min(requested or default, log_count)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def analyze_logs(
|
| 183 |
+
logs: list[Path],
|
| 184 |
+
max_samples: int | None,
|
| 185 |
+
workers: int,
|
| 186 |
+
) -> list[tuple[dict[str, Any], list[dict[str, Any]]]]:
|
| 187 |
+
if workers == 1:
|
| 188 |
+
results = []
|
| 189 |
+
for path in logs:
|
| 190 |
+
print(f"Analyzing {path}")
|
| 191 |
+
results.append(analyze_log(path, max_samples))
|
| 192 |
+
return results
|
| 193 |
+
|
| 194 |
+
ordered_results: list[tuple[dict[str, Any], list[dict[str, Any]]] | None] = [None] * len(logs)
|
| 195 |
+
with ProcessPoolExecutor(max_workers=workers) as executor:
|
| 196 |
+
futures = {
|
| 197 |
+
executor.submit(analyze_log, path, max_samples): (index, path)
|
| 198 |
+
for index, path in enumerate(logs)
|
| 199 |
+
}
|
| 200 |
+
for future in as_completed(futures):
|
| 201 |
+
index, path = futures[future]
|
| 202 |
+
ordered_results[index] = future.result()
|
| 203 |
+
print(f"Analyzed {path}")
|
| 204 |
+
|
| 205 |
+
return [result for result in ordered_results if result is not None]
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def write_csv(path: Path, rows: list[dict[str, Any]]) -> None:
|
| 209 |
+
if not rows:
|
| 210 |
+
return
|
| 211 |
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
| 212 |
+
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
| 213 |
+
writer.writeheader()
|
| 214 |
+
writer.writerows(rows)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def run_self_test() -> None:
|
| 218 |
+
cases = [
|
| 219 |
+
("Use 10, 10.0, and 1,000.", "10 and 1000", True),
|
| 220 |
+
("Use 10 and 2.", "The result is 210.", False),
|
| 221 |
+
("Temperatures are -5 and +3.", "-5 + 3 = -2", True),
|
| 222 |
+
("There are 4 groups of 4.", "4 groups", True),
|
| 223 |
+
("A value is 1.5.", "15", False),
|
| 224 |
+
]
|
| 225 |
+
for prompt, response, expected in cases:
|
| 226 |
+
actual = extract_numbers(prompt) <= extract_numbers(response)
|
| 227 |
+
if actual != expected:
|
| 228 |
+
raise AssertionError(
|
| 229 |
+
f"Failed: prompt={prompt!r}, response={response!r}, expected={expected}, got={actual}"
|
| 230 |
+
)
|
| 231 |
+
print(f"Self-test passed ({len(cases)} cases).")
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def main() -> None:
|
| 235 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 236 |
+
parser.add_argument("inputs", nargs="*", type=Path, help="Inspect .eval logs or directories containing logs.")
|
| 237 |
+
parser.add_argument("--out-dir", type=Path, default=Path("prompt_number_coverage"))
|
| 238 |
+
parser.add_argument("--max-samples", type=int)
|
| 239 |
+
parser.add_argument(
|
| 240 |
+
"--workers",
|
| 241 |
+
type=int,
|
| 242 |
+
help="Parallel log processes. Defaults to min(4, CPU count); use 1 for serial execution.",
|
| 243 |
+
)
|
| 244 |
+
parser.add_argument("--self-test", action="store_true")
|
| 245 |
+
args = parser.parse_args()
|
| 246 |
+
|
| 247 |
+
if args.self_test:
|
| 248 |
+
run_self_test()
|
| 249 |
+
if not args.inputs:
|
| 250 |
+
return
|
| 251 |
+
|
| 252 |
+
logs = discover_logs(args.inputs)
|
| 253 |
+
if not logs:
|
| 254 |
+
raise SystemExit("No non-empty .eval logs found.")
|
| 255 |
+
|
| 256 |
+
try:
|
| 257 |
+
workers = resolve_worker_count(args.workers, len(logs))
|
| 258 |
+
except ValueError as error:
|
| 259 |
+
parser.error(str(error))
|
| 260 |
+
print(f"Analyzing {len(logs)} log(s) with {workers} worker(s).")
|
| 261 |
+
|
| 262 |
+
summaries: list[dict[str, Any]] = []
|
| 263 |
+
sample_rows: list[dict[str, Any]] = []
|
| 264 |
+
for summary, samples in analyze_logs(logs, args.max_samples, workers):
|
| 265 |
+
summaries.append(summary)
|
| 266 |
+
sample_rows.extend(samples)
|
| 267 |
+
|
| 268 |
+
args.out_dir.mkdir(parents=True, exist_ok=True)
|
| 269 |
+
(args.out_dir / "summary.json").write_text(
|
| 270 |
+
json.dumps(summaries, ensure_ascii=False, indent=2),
|
| 271 |
+
encoding="utf-8",
|
| 272 |
+
)
|
| 273 |
+
write_csv(args.out_dir / "samples.csv", sample_rows)
|
| 274 |
+
|
| 275 |
+
for summary in summaries:
|
| 276 |
+
breakdown = summary["number_coverage_breakdown"]
|
| 277 |
+
print(
|
| 278 |
+
f"{summary['model']} | {summary['task']}: "
|
| 279 |
+
f"all={summary['all_prompt_numbers_present_rate']!s}, "
|
| 280 |
+
f"right={breakdown['final_correct']['all_prompt_numbers_present_rate']!s}, "
|
| 281 |
+
f"wrong={breakdown['final_incorrect']['all_prompt_numbers_present_rate']!s}"
|
| 282 |
+
)
|
| 283 |
+
print(f"Wrote {args.out_dir}")
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
if __name__ == "__main__":
|
| 287 |
+
main()
|
analyze_reasoning_arithmetic.py
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# dependencies = ["inspect-ai", "math-verify[antlr4_13_2]>=0.9,<0.10"]
|
| 3 |
+
# ///
|
| 4 |
+
"""Check intermediate equations in Inspect logs with Hugging Face Math-Verify.
|
| 5 |
+
|
| 6 |
+
The script segments explicit equality chains, then delegates LaTeX parsing,
|
| 7 |
+
normalization, symbolic execution, and equivalence checking to Math-Verify.
|
| 8 |
+
It measures local mathematical consistency, not whether a step is relevant to
|
| 9 |
+
the word problem.
|
| 10 |
+
|
| 11 |
+
Example:
|
| 12 |
+
uv run hf_dataset/analyze_reasoning_arithmetic.py hf_dataset/logs/example.eval
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import csv
|
| 19 |
+
import json
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
from collections.abc import Iterable
|
| 25 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 26 |
+
from dataclasses import asdict, dataclass
|
| 27 |
+
from functools import lru_cache
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
from inspect_ai.log import read_eval_log
|
| 32 |
+
from math_verify import ExprExtractionConfig, LatexExtractionConfig, parse, verify
|
| 33 |
+
|
| 34 |
+
MATH_SPAN_RE = re.compile(
|
| 35 |
+
r"\\\[(.*?)\\\]|\\\((.*?)\\\)|(?<!\\)\$(?![\d,])(.+?)(?<!\\)\$",
|
| 36 |
+
re.DOTALL,
|
| 37 |
+
)
|
| 38 |
+
APPROX_RE = re.compile(r"\\approx|\\simeq|≈|~=")
|
| 39 |
+
TRANSITION_RE = re.compile(r"\\implies|\\Rightarrow|⇒|→")
|
| 40 |
+
TEXT_CONTENT_RE = re.compile(r"\\(?:text|mathrm)\s*\{([^{}]*)\}")
|
| 41 |
+
TEXT_COMMAND_RE = re.compile(r"\\(?:text|mathrm)\s*\{[^{}]*\}")
|
| 42 |
+
PERCENT_SCALE_RE = re.compile(r"(?:\\times|\\cdot|\*|×|·)\s*100\b")
|
| 43 |
+
PLAIN_WORD_RE = re.compile(r"(?<!\\)\b[^\W\d_]{2,}\b", re.UNICODE)
|
| 44 |
+
FUNCTION_CALL_RE = re.compile(r"(?<!\\)\b[^\W\d_]\s*\(", re.UNICODE)
|
| 45 |
+
ELLIPSIS_RE = re.compile(r"(?:\\ldots|\\dots|\.\.\.)")
|
| 46 |
+
CURRENCY_RE = re.compile(r"\\?[$€£¥₹₽₪₩₫฿₺₿]")
|
| 47 |
+
THOUSANDS_SEPARATOR_RE = re.compile(r"(?<=\d),(?=\d{3}(?:\D|$))")
|
| 48 |
+
LATEX_LINEBREAK_RE = re.compile(r"\\\\(?=\s|$)")
|
| 49 |
+
MARKDOWN_BULLET_RE = re.compile(r"^\s*[-*+]\s+")
|
| 50 |
+
ASSIGNMENT_LABEL_RE = re.compile(r"^\s*[^\W\d_][^\d=+*/×÷<>]{1,80}\s*$", re.UNICODE)
|
| 51 |
+
|
| 52 |
+
LATEX_CONFIG = [LatexExtractionConfig(boxed_match_priority=-1)]
|
| 53 |
+
EXPR_CONFIG = [ExprExtractionConfig()]
|
| 54 |
+
|
| 55 |
+
logging.getLogger("math_verify").setLevel(logging.ERROR)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=True)
|
| 59 |
+
class EquationCheck:
|
| 60 |
+
expression: str
|
| 61 |
+
lhs: str
|
| 62 |
+
rhs: str
|
| 63 |
+
lhs_parsed: str
|
| 64 |
+
rhs_parsed: str
|
| 65 |
+
correct: bool
|
| 66 |
+
approximate: bool
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@lru_cache(maxsize=20_000)
|
| 70 |
+
def parse_side(text: str) -> Any | None:
|
| 71 |
+
"""Parse one side of an equality, preferring LaTeX to preserve variables."""
|
| 72 |
+
text = MARKDOWN_BULLET_RE.sub("", text.strip())
|
| 73 |
+
text = CURRENCY_RE.sub("", text)
|
| 74 |
+
text = THOUSANDS_SEPARATOR_RE.sub("", text)
|
| 75 |
+
text = text.replace(r"\left", "").replace(r"\right", "")
|
| 76 |
+
text = _strip_trailing_prose_parenthetical(text)
|
| 77 |
+
|
| 78 |
+
# Math-Verify strips units, but semantic text placeholders must remain
|
| 79 |
+
# unscored. Unit annotations follow a numeric quantity; labels do not.
|
| 80 |
+
for match in TEXT_COMMAND_RE.finditer(text):
|
| 81 |
+
prefix = text[: match.start()].rstrip()
|
| 82 |
+
if not prefix or not (prefix[-1].isdigit() or prefix[-1] in ")}]%"):
|
| 83 |
+
return None
|
| 84 |
+
text = TEXT_COMMAND_RE.sub("", text)
|
| 85 |
+
text = ELLIPSIS_RE.sub("", text)
|
| 86 |
+
text = text.replace("×", "*").replace("÷", "/").replace("·", "*")
|
| 87 |
+
text = re.sub(r"(\d+(?:\.\d+)?)\s*\\%", r"(\1/100)", text)
|
| 88 |
+
text = re.sub(r"(?<=\d)\s*\(", "*(", text)
|
| 89 |
+
if PLAIN_WORD_RE.search(text) or FUNCTION_CALL_RE.search(text) or re.search(r"\\(?:cap|cup|Pr)\b", text):
|
| 90 |
+
return None
|
| 91 |
+
symbol_text = re.sub(r"\\[A-Za-z]+", "", text)
|
| 92 |
+
if re.search(r"[A-Z]", symbol_text):
|
| 93 |
+
# Math-Verify/SymPy interpret I and E as mathematical constants. More
|
| 94 |
+
# generally, assignments involving named quantities require context.
|
| 95 |
+
return None
|
| 96 |
+
if not text:
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
if not re.search(r"\\[A-Za-z]+|(?<!\\)[A-Za-z]", text):
|
| 100 |
+
text = re.sub(r"(\d+(?:\.\d+)?)\s*%", r"(\1/100)", text)
|
| 101 |
+
parsed = parse(
|
| 102 |
+
text,
|
| 103 |
+
extraction_config=EXPR_CONFIG,
|
| 104 |
+
fallback_mode="no_fallback",
|
| 105 |
+
parsing_timeout=None,
|
| 106 |
+
)
|
| 107 |
+
if parsed:
|
| 108 |
+
return parsed[0]
|
| 109 |
+
|
| 110 |
+
parsed = parse(
|
| 111 |
+
rf"\({text}\)",
|
| 112 |
+
extraction_config=LATEX_CONFIG,
|
| 113 |
+
fallback_mode="no_fallback",
|
| 114 |
+
parsing_timeout=None,
|
| 115 |
+
)
|
| 116 |
+
return parsed[0] if parsed else None
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _free_symbols(value: Any) -> set[Any]:
|
| 120 |
+
return set(getattr(value, "free_symbols", set()))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _strip_trailing_prose_parenthetical(text: str) -> str:
|
| 124 |
+
match = re.search(r"\s*\(([^()]*)\)\s*$", text)
|
| 125 |
+
if not match:
|
| 126 |
+
return text
|
| 127 |
+
content = TEXT_COMMAND_RE.sub("", match.group(1))
|
| 128 |
+
content = re.sub(r"\\[A-Za-z]+", "", content)
|
| 129 |
+
if PLAIN_WORD_RE.search(content):
|
| 130 |
+
return text[: match.start()]
|
| 131 |
+
return text
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _strip_percent(text: str) -> str:
|
| 135 |
+
return text.replace(r"\%", "").replace("%", "")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _display_precision(text: str) -> int:
|
| 139 |
+
numbers = re.findall(r"-?\d+(?:\.(\d+))?", _strip_percent(text))
|
| 140 |
+
if not numbers:
|
| 141 |
+
return 6
|
| 142 |
+
decimals = numbers[-1]
|
| 143 |
+
return len(decimals) if decimals else 0
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _is_display_decimal(text: str) -> bool:
|
| 147 |
+
cleaned = TEXT_COMMAND_RE.sub("", text)
|
| 148 |
+
cleaned = CURRENCY_RE.sub("", cleaned)
|
| 149 |
+
cleaned = cleaned.strip().strip(".:;")
|
| 150 |
+
return bool(re.fullmatch(r"-?\d+\.\d+", cleaned))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _equivalent(lhs: Any, rhs: Any, approximate: bool, precision: int) -> bool:
|
| 154 |
+
if verify(lhs, rhs, float_rounding=precision, timeout_seconds=None):
|
| 155 |
+
return True
|
| 156 |
+
if not _free_symbols(lhs) and not _free_symbols(rhs):
|
| 157 |
+
try:
|
| 158 |
+
lhs_value = float(lhs.doit().evalf())
|
| 159 |
+
rhs_value = float(rhs.doit().evalf())
|
| 160 |
+
tolerance = (0.5 * 10**-precision) if approximate else 1e-9
|
| 161 |
+
if math.isclose(lhs_value, rhs_value, rel_tol=1e-12, abs_tol=tolerance):
|
| 162 |
+
return True
|
| 163 |
+
except (AttributeError, TypeError, ValueError):
|
| 164 |
+
pass
|
| 165 |
+
if not approximate:
|
| 166 |
+
return False
|
| 167 |
+
try:
|
| 168 |
+
lhs_rounded = lhs.doit().evalf().round(precision)
|
| 169 |
+
rhs_rounded = rhs.doit().evalf().round(precision)
|
| 170 |
+
return verify(lhs_rounded, rhs_rounded, timeout_seconds=None)
|
| 171 |
+
except (AttributeError, TypeError, ValueError):
|
| 172 |
+
return False
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _verify_pair(lhs: str, rhs: str, approximate: bool) -> tuple[Any, Any, bool] | None:
|
| 176 |
+
if ELLIPSIS_RE.search(lhs) or ELLIPSIS_RE.search(rhs):
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
lhs_parsed = parse_side(lhs)
|
| 180 |
+
rhs_parsed = parse_side(rhs)
|
| 181 |
+
if lhs_parsed is None or rhs_parsed is None:
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
lhs_symbols = _free_symbols(lhs_parsed)
|
| 185 |
+
rhs_symbols = _free_symbols(rhs_parsed)
|
| 186 |
+
if (lhs_symbols or rhs_symbols) and lhs_symbols != rhs_symbols:
|
| 187 |
+
# An equation such as 100 = 2n constrains n; it is not independently
|
| 188 |
+
# true or false without the surrounding reasoning state.
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
displayed_decimal = _is_display_decimal(rhs)
|
| 192 |
+
effective_approximate = approximate or displayed_decimal
|
| 193 |
+
float_rounding = _display_precision(rhs) if effective_approximate else 6
|
| 194 |
+
correct = _equivalent(lhs_parsed, rhs_parsed, effective_approximate, float_rounding)
|
| 195 |
+
if (lhs_symbols or rhs_symbols) and not correct:
|
| 196 |
+
return None
|
| 197 |
+
|
| 198 |
+
# Worked solutions commonly write ratio * 100 = 5%, using the percent
|
| 199 |
+
# suffix as display notation. Math-Verify correctly treats 5% as 0.05, so
|
| 200 |
+
# retry without the suffix only for this explicit percentage-scale idiom.
|
| 201 |
+
lhs_has_percent = "%" in lhs
|
| 202 |
+
rhs_has_percent = "%" in rhs
|
| 203 |
+
if not correct and lhs_has_percent and rhs_has_percent:
|
| 204 |
+
lhs_display = parse_side(_strip_percent(lhs))
|
| 205 |
+
rhs_display = parse_side(_strip_percent(rhs))
|
| 206 |
+
if lhs_display is not None and rhs_display is not None:
|
| 207 |
+
correct = _equivalent(lhs_display, rhs_display, effective_approximate, float_rounding)
|
| 208 |
+
if not correct and lhs_has_percent != rhs_has_percent:
|
| 209 |
+
non_percent_side = rhs if lhs_has_percent else lhs
|
| 210 |
+
if PERCENT_SCALE_RE.search(non_percent_side) or approximate:
|
| 211 |
+
percent_side = lhs if lhs_has_percent else rhs
|
| 212 |
+
percent_display = parse_side(_strip_percent(percent_side))
|
| 213 |
+
if percent_display is not None:
|
| 214 |
+
if lhs_has_percent:
|
| 215 |
+
comparison = rhs_parsed * 100 if approximate and not PERCENT_SCALE_RE.search(rhs) else rhs_parsed
|
| 216 |
+
correct = _equivalent(percent_display, comparison, effective_approximate, float_rounding)
|
| 217 |
+
else:
|
| 218 |
+
comparison = lhs_parsed * 100 if approximate and not PERCENT_SCALE_RE.search(lhs) else lhs_parsed
|
| 219 |
+
correct = _equivalent(comparison, percent_display, effective_approximate, float_rounding)
|
| 220 |
+
|
| 221 |
+
return lhs_parsed, rhs_parsed, correct
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _unit_annotations(text: str) -> set[str]:
|
| 225 |
+
return {
|
| 226 |
+
re.sub(r"[^\w/]+", " ", content, flags=re.UNICODE).strip().lower()
|
| 227 |
+
for content in TEXT_CONTENT_RE.findall(text)
|
| 228 |
+
if content.strip()
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _is_dimension_conversion(lhs: str, rhs: str, correct: bool) -> bool:
|
| 233 |
+
"""Exclude conversions Math-Verify cannot dimensionally validate."""
|
| 234 |
+
if correct:
|
| 235 |
+
return False
|
| 236 |
+
lhs_units = _unit_annotations(lhs)
|
| 237 |
+
rhs_units = _unit_annotations(rhs)
|
| 238 |
+
if lhs_units and rhs_units and lhs_units != rhs_units:
|
| 239 |
+
return True
|
| 240 |
+
|
| 241 |
+
lhs_is_unit_quantity = bool(lhs_units) and not re.search(r"[+*/]|\\(?:times|div|frac)", lhs)
|
| 242 |
+
rhs_has_operation = bool(re.search(r"[+*/]|\\(?:times|div|frac)", rhs))
|
| 243 |
+
if lhs_is_unit_quantity and rhs_has_operation:
|
| 244 |
+
return True
|
| 245 |
+
rhs_is_unit_quantity = bool(rhs_units) and not re.search(r"[+*/]|\\(?:times|div|frac)", rhs)
|
| 246 |
+
if lhs_is_unit_quantity and CURRENCY_RE.search(rhs):
|
| 247 |
+
return True
|
| 248 |
+
if rhs_is_unit_quantity and CURRENCY_RE.search(lhs):
|
| 249 |
+
return True
|
| 250 |
+
|
| 251 |
+
if bool(lhs_units) != bool(rhs_units):
|
| 252 |
+
unitless_side = rhs if lhs_units else lhs
|
| 253 |
+
if re.search(r"(?:[*×÷/]|\b)\s*(?:12|60|1000)\b", unitless_side):
|
| 254 |
+
return True
|
| 255 |
+
return False
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _math_fragments(completion: str) -> Iterable[str]:
|
| 259 |
+
covered: list[tuple[int, int]] = []
|
| 260 |
+
for match in MATH_SPAN_RE.finditer(completion):
|
| 261 |
+
covered.append(match.span())
|
| 262 |
+
fragment = next(group for group in match.groups() if group is not None)
|
| 263 |
+
yield from (part for part in LATEX_LINEBREAK_RE.split(fragment) if part.strip())
|
| 264 |
+
|
| 265 |
+
uncovered = list(completion)
|
| 266 |
+
for start, end in covered:
|
| 267 |
+
uncovered[start:end] = " " * (end - start)
|
| 268 |
+
for line in "".join(uncovered).splitlines():
|
| 269 |
+
if "=" in line or APPROX_RE.search(line):
|
| 270 |
+
yield line
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _assignment_label(text: str) -> str | None:
|
| 274 |
+
text = MARKDOWN_BULLET_RE.sub("", text.strip())
|
| 275 |
+
text = TEXT_CONTENT_RE.sub(lambda match: match.group(1), text)
|
| 276 |
+
text = text.replace(r"\left", "").replace(r"\right", "").strip()
|
| 277 |
+
if not ASSIGNMENT_LABEL_RE.fullmatch(text):
|
| 278 |
+
return None
|
| 279 |
+
return re.sub(r"\s+", " ", text).casefold()
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _is_assignment_separator(line: str) -> bool:
|
| 283 |
+
"""Allow one assignment chain to span adjacent display-math blocks."""
|
| 284 |
+
return line.strip() in {"", r"\[", r"\]", r"\(", r"\)"}
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _assignment_checks(completion: str) -> list[EquationCheck]:
|
| 288 |
+
checks: list[EquationCheck] = []
|
| 289 |
+
previous: tuple[str, str] | None = None
|
| 290 |
+
|
| 291 |
+
for line in completion.splitlines():
|
| 292 |
+
if _is_assignment_separator(line):
|
| 293 |
+
continue
|
| 294 |
+
|
| 295 |
+
equality = TRANSITION_RE.sub("=", APPROX_RE.sub("=", line))
|
| 296 |
+
if equality.count("=") != 1:
|
| 297 |
+
previous = None
|
| 298 |
+
continue
|
| 299 |
+
|
| 300 |
+
lhs, rhs = equality.split("=")
|
| 301 |
+
label = _assignment_label(lhs)
|
| 302 |
+
if label is None or parse_side(rhs) is None:
|
| 303 |
+
previous = None
|
| 304 |
+
continue
|
| 305 |
+
|
| 306 |
+
approximate = bool(APPROX_RE.search(line) or TRANSITION_RE.search(line) or ELLIPSIS_RE.search(line))
|
| 307 |
+
if previous is not None and previous[0] == label:
|
| 308 |
+
previous_text = previous[1]
|
| 309 |
+
result = _verify_pair(previous_text, rhs, approximate)
|
| 310 |
+
if result is not None:
|
| 311 |
+
previous_parsed, current_parsed, correct = result
|
| 312 |
+
checks.append(
|
| 313 |
+
EquationCheck(
|
| 314 |
+
expression=f"{previous_text} = {rhs.strip()}",
|
| 315 |
+
lhs=previous_text,
|
| 316 |
+
rhs=rhs.strip(),
|
| 317 |
+
lhs_parsed=str(previous_parsed),
|
| 318 |
+
rhs_parsed=str(current_parsed),
|
| 319 |
+
correct=correct,
|
| 320 |
+
approximate=approximate,
|
| 321 |
+
)
|
| 322 |
+
)
|
| 323 |
+
previous = (label, rhs.strip())
|
| 324 |
+
|
| 325 |
+
return checks
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def check_completion(completion: str) -> tuple[list[EquationCheck], int]:
|
| 329 |
+
"""Check every independently verifiable adjacent equality."""
|
| 330 |
+
checks: list[EquationCheck] = []
|
| 331 |
+
claims = 0
|
| 332 |
+
|
| 333 |
+
for fragment in _math_fragments(completion):
|
| 334 |
+
approximate = bool(APPROX_RE.search(fragment) or TRANSITION_RE.search(fragment) or ELLIPSIS_RE.search(fragment))
|
| 335 |
+
equality = TRANSITION_RE.sub("=", APPROX_RE.sub("=", fragment))
|
| 336 |
+
if "=" not in equality:
|
| 337 |
+
continue
|
| 338 |
+
|
| 339 |
+
parts = equality.split("=")
|
| 340 |
+
claims += max(0, len(parts) - 1)
|
| 341 |
+
|
| 342 |
+
for lhs, rhs in zip(parts, parts[1:], strict=False):
|
| 343 |
+
result = _verify_pair(lhs, rhs, approximate)
|
| 344 |
+
if result is None:
|
| 345 |
+
continue
|
| 346 |
+
lhs_parsed, rhs_parsed, correct = result
|
| 347 |
+
if _is_dimension_conversion(lhs, rhs, correct):
|
| 348 |
+
continue
|
| 349 |
+
checks.append(
|
| 350 |
+
EquationCheck(
|
| 351 |
+
expression=fragment.strip(),
|
| 352 |
+
lhs=lhs.strip(),
|
| 353 |
+
rhs=rhs.strip(),
|
| 354 |
+
lhs_parsed=str(lhs_parsed),
|
| 355 |
+
rhs_parsed=str(rhs_parsed),
|
| 356 |
+
correct=correct,
|
| 357 |
+
approximate=approximate,
|
| 358 |
+
)
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
checks.extend(_assignment_checks(completion))
|
| 362 |
+
return checks, claims
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def score_to_bool(sample: Any) -> bool | None:
|
| 366 |
+
scores = sample.scores or {}
|
| 367 |
+
for preferred in ("math", "pattern"):
|
| 368 |
+
if preferred not in scores:
|
| 369 |
+
continue
|
| 370 |
+
value = getattr(scores[preferred], "value", scores[preferred])
|
| 371 |
+
if isinstance(value, bool):
|
| 372 |
+
return value
|
| 373 |
+
if isinstance(value, (int, float)):
|
| 374 |
+
return bool(value)
|
| 375 |
+
if isinstance(value, str):
|
| 376 |
+
normalized = value.strip().upper()
|
| 377 |
+
if normalized in {"C", "CORRECT", "TRUE", "1"}:
|
| 378 |
+
return True
|
| 379 |
+
if normalized in {"I", "INCORRECT", "FALSE", "0"}:
|
| 380 |
+
return False
|
| 381 |
+
return None
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def _safe_rate(numerator: int, denominator: int) -> float | None:
|
| 385 |
+
return numerator / denominator if denominator else None
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def summarize_final_answer_group(rows: list[dict]) -> dict[str, Any]:
|
| 389 |
+
with_checks = [row for row in rows if row["checked_expressions"]]
|
| 390 |
+
with_wrong = [row for row in with_checks if row["any_checked_wrong"]]
|
| 391 |
+
checked_expressions = sum(row["checked_expressions"] for row in rows)
|
| 392 |
+
correct_expressions = sum(row["correct_expressions"] for row in rows)
|
| 393 |
+
wrong_expressions = checked_expressions - correct_expressions
|
| 394 |
+
|
| 395 |
+
return {
|
| 396 |
+
"samples": len(rows),
|
| 397 |
+
"samples_with_checked_expressions": len(with_checks),
|
| 398 |
+
"samples_with_wrong_expression": len(with_wrong),
|
| 399 |
+
"sample_wrong_expression_rate_all": _safe_rate(len(with_wrong), len(rows)),
|
| 400 |
+
"sample_wrong_expression_rate_checked": _safe_rate(len(with_wrong), len(with_checks)),
|
| 401 |
+
"checked_expressions": checked_expressions,
|
| 402 |
+
"wrong_expressions": wrong_expressions,
|
| 403 |
+
"expression_wrong_rate": _safe_rate(wrong_expressions, checked_expressions),
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
def analyze_log(path: Path, max_samples: int | None = None) -> tuple[dict[str, Any], list[dict], list[dict]]:
|
| 408 |
+
log = read_eval_log(str(path))
|
| 409 |
+
samples = (log.samples or [])[:max_samples]
|
| 410 |
+
expression_rows: list[dict] = []
|
| 411 |
+
sample_rows: list[dict] = []
|
| 412 |
+
|
| 413 |
+
for sample in samples:
|
| 414 |
+
checks, claims = check_completion(sample.output.completion)
|
| 415 |
+
checked = len(checks)
|
| 416 |
+
correct = sum(check.correct for check in checks)
|
| 417 |
+
final_correct = score_to_bool(sample)
|
| 418 |
+
all_checked_correct = checked > 0 and correct == checked
|
| 419 |
+
any_checked_wrong = checked > 0 and correct < checked
|
| 420 |
+
|
| 421 |
+
sample_rows.append(
|
| 422 |
+
{
|
| 423 |
+
"log": path.name,
|
| 424 |
+
"model": log.eval.model,
|
| 425 |
+
"task": log.eval.task,
|
| 426 |
+
"sample_id": sample.id,
|
| 427 |
+
"epoch": sample.epoch,
|
| 428 |
+
"source_id": (sample.metadata or {}).get("source_id"),
|
| 429 |
+
"language": (sample.metadata or {}).get("language"),
|
| 430 |
+
"final_correct": final_correct,
|
| 431 |
+
"equality_claims": claims,
|
| 432 |
+
"checked_expressions": checked,
|
| 433 |
+
"correct_expressions": correct,
|
| 434 |
+
"expression_accuracy": _safe_rate(correct, checked),
|
| 435 |
+
"parse_coverage": _safe_rate(checked, claims),
|
| 436 |
+
"all_checked_correct": all_checked_correct,
|
| 437 |
+
"any_checked_wrong": any_checked_wrong,
|
| 438 |
+
}
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
for check in checks:
|
| 442 |
+
expression_rows.append(
|
| 443 |
+
{
|
| 444 |
+
"log": path.name,
|
| 445 |
+
"model": log.eval.model,
|
| 446 |
+
"task": log.eval.task,
|
| 447 |
+
"sample_id": sample.id,
|
| 448 |
+
"epoch": sample.epoch,
|
| 449 |
+
"source_id": (sample.metadata or {}).get("source_id"),
|
| 450 |
+
"final_correct": final_correct,
|
| 451 |
+
**asdict(check),
|
| 452 |
+
}
|
| 453 |
+
)
|
| 454 |
+
|
| 455 |
+
total_claims = sum(row["equality_claims"] for row in sample_rows)
|
| 456 |
+
total_checked = sum(row["checked_expressions"] for row in sample_rows)
|
| 457 |
+
total_correct = sum(row["correct_expressions"] for row in sample_rows)
|
| 458 |
+
with_checks = [row for row in sample_rows if row["checked_expressions"]]
|
| 459 |
+
final_scored = [row for row in sample_rows if row["final_correct"] is not None]
|
| 460 |
+
final_correct_rows = [row for row in final_scored if row["final_correct"]]
|
| 461 |
+
final_incorrect_rows = [row for row in final_scored if not row["final_correct"]]
|
| 462 |
+
suspicious = [row for row in final_correct_rows if row["any_checked_wrong"]]
|
| 463 |
+
|
| 464 |
+
summary = {
|
| 465 |
+
"log": path.name,
|
| 466 |
+
"status": str(log.status),
|
| 467 |
+
"model": log.eval.model,
|
| 468 |
+
"task": log.eval.task,
|
| 469 |
+
"samples": len(samples),
|
| 470 |
+
"final_accuracy": _safe_rate(sum(row["final_correct"] for row in final_scored), len(final_scored)),
|
| 471 |
+
"equality_claims": total_claims,
|
| 472 |
+
"checked_expressions": total_checked,
|
| 473 |
+
"parse_coverage": _safe_rate(total_checked, total_claims),
|
| 474 |
+
"expression_accuracy": _safe_rate(total_correct, total_checked),
|
| 475 |
+
"samples_with_checked_expressions": len(with_checks),
|
| 476 |
+
"all_checked_expressions_correct_rate": _safe_rate(
|
| 477 |
+
sum(row["all_checked_correct"] for row in with_checks), len(with_checks)
|
| 478 |
+
),
|
| 479 |
+
"final_correct_with_wrong_expression_rate": _safe_rate(len(suspicious), len(final_correct_rows)),
|
| 480 |
+
"final_correct_with_wrong_expression_count": len(suspicious),
|
| 481 |
+
"wrong_expression_breakdown": {
|
| 482 |
+
"final_correct": summarize_final_answer_group(final_correct_rows),
|
| 483 |
+
"final_incorrect": summarize_final_answer_group(final_incorrect_rows),
|
| 484 |
+
},
|
| 485 |
+
"verifier": "math-verify",
|
| 486 |
+
"note": (
|
| 487 |
+
"Expression accuracy measures local mathematical consistency. "
|
| 488 |
+
"The final-correct/wrong-expression rate is a lucky-answer proxy, not proof of memorization."
|
| 489 |
+
),
|
| 490 |
+
}
|
| 491 |
+
return summary, sample_rows, expression_rows
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def discover_logs(inputs: list[Path]) -> list[Path]:
|
| 495 |
+
logs: set[Path] = set()
|
| 496 |
+
for path in inputs:
|
| 497 |
+
if path.is_dir():
|
| 498 |
+
logs.update(candidate for candidate in path.rglob("*.eval") if candidate.stat().st_size >= 1_000)
|
| 499 |
+
elif path.suffix == ".eval" and path.stat().st_size >= 1_000:
|
| 500 |
+
logs.add(path)
|
| 501 |
+
return sorted(logs)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def resolve_worker_count(requested: int | None, log_count: int) -> int:
|
| 505 |
+
if requested is not None and requested < 1:
|
| 506 |
+
raise ValueError("--workers must be at least 1.")
|
| 507 |
+
default = min(4, os.cpu_count() or 1)
|
| 508 |
+
return min(requested or default, log_count)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def analyze_logs(
|
| 512 |
+
logs: list[Path],
|
| 513 |
+
max_samples: int | None,
|
| 514 |
+
workers: int,
|
| 515 |
+
) -> list[tuple[dict[str, Any], list[dict], list[dict]]]:
|
| 516 |
+
if workers == 1:
|
| 517 |
+
results = []
|
| 518 |
+
for path in logs:
|
| 519 |
+
print(f"Analyzing {path}")
|
| 520 |
+
results.append(analyze_log(path, max_samples))
|
| 521 |
+
return results
|
| 522 |
+
|
| 523 |
+
ordered_results: list[tuple[dict[str, Any], list[dict], list[dict]] | None] = [None] * len(logs)
|
| 524 |
+
with ProcessPoolExecutor(max_workers=workers) as executor:
|
| 525 |
+
futures = {
|
| 526 |
+
executor.submit(analyze_log, path, max_samples): (index, path)
|
| 527 |
+
for index, path in enumerate(logs)
|
| 528 |
+
}
|
| 529 |
+
for future in as_completed(futures):
|
| 530 |
+
index, path = futures[future]
|
| 531 |
+
ordered_results[index] = future.result()
|
| 532 |
+
print(f"Analyzed {path}")
|
| 533 |
+
|
| 534 |
+
return [result for result in ordered_results if result is not None]
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def write_csv(path: Path, rows: list[dict]) -> None:
|
| 538 |
+
if not rows:
|
| 539 |
+
return
|
| 540 |
+
with path.open("w", newline="", encoding="utf-8") as handle:
|
| 541 |
+
writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
|
| 542 |
+
writer.writeheader()
|
| 543 |
+
writer.writerows(rows)
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def run_self_test() -> None:
|
| 547 |
+
cases = [
|
| 548 |
+
(r"45 \times 4 = 180", [True]),
|
| 549 |
+
(r"180 \text{ inches} + 180 \text{ inches} = 360 \text{ inches}", [True]),
|
| 550 |
+
(r"40 * €0.75 = €30", [True]),
|
| 551 |
+
(r"5 × €8 = €40", [True]),
|
| 552 |
+
(r"\$390,000 + \$15,600 + \$42,900 = \$448,500", [True]),
|
| 553 |
+
(r"\$650,000 \times 5\% = \$32,500", [True]),
|
| 554 |
+
(r"- 14 \div 28 = 0.5", [True]),
|
| 555 |
+
(r"44 \times 0.88 = 44 \times \left(1 - 0.12\right)", [True]),
|
| 556 |
+
(r"101.16 - 17.16 = 84", [True]),
|
| 557 |
+
(r"3(11) + 1 = 33 + 1", [True]),
|
| 558 |
+
(r"2(9 \text{ feet} + 55 \text{ feet}) = 2 \times 64 \text{ feet}", [True]),
|
| 559 |
+
(r"20 + (0.10 \times 20) = 20 + 2", [True]),
|
| 560 |
+
(r"\frac{20}{9} \approx 2.22", [True]),
|
| 561 |
+
(r"\frac{3400}{150} = 22.67", [True]),
|
| 562 |
+
(r"94 - 31.333\ldots = 62.666\ldots", []),
|
| 563 |
+
(r"15 / 150 * 100 = 10\%", [True]),
|
| 564 |
+
(r"0.2 \times 100\% = 20\%", [True]),
|
| 565 |
+
(r"\frac{51}{196} \times 100 \approx 26.09\%", [False]),
|
| 566 |
+
(r"\frac{8}{15} \implies 0.5333 \implies 53.33\%", [True, True]),
|
| 567 |
+
(r"180 + 180 = 350", [False]),
|
| 568 |
+
(r"1 + 2n - 2 = 2n - 1", [True]),
|
| 569 |
+
(r"100 = 2n", []),
|
| 570 |
+
(r"164 = 2I", []),
|
| 571 |
+
(r"2 \times 5 \text{ hours} = 2 \times 60", []),
|
| 572 |
+
]
|
| 573 |
+
for expression, expected in cases:
|
| 574 |
+
checks, _ = check_completion(rf"\[{expression}\]")
|
| 575 |
+
actual = [check.correct for check in checks]
|
| 576 |
+
if actual != expected:
|
| 577 |
+
raise AssertionError(f"Failed: {expression!r}: expected {expected}, got {checks}")
|
| 578 |
+
|
| 579 |
+
multiline = check_completion(
|
| 580 |
+
"\\[\n15 - 12.5 = 2.5 \\\\\n\\frac{2.5}{0.5} = 5\n\\]"
|
| 581 |
+
)[0]
|
| 582 |
+
if [check.correct for check in multiline] != [True, True]:
|
| 583 |
+
raise AssertionError(f"Failed multiline equations: {multiline}")
|
| 584 |
+
|
| 585 |
+
assignments = check_completion(
|
| 586 |
+
"Total costs = $26,800 + $40,200 + $500,000\n"
|
| 587 |
+
"Total costs = $587,000\n"
|
| 588 |
+
)[0]
|
| 589 |
+
if [check.correct for check in assignments] != [False]:
|
| 590 |
+
raise AssertionError(f"Failed repeated assignments: {assignments}")
|
| 591 |
+
|
| 592 |
+
display_assignments = check_completion(
|
| 593 |
+
"\\[\n"
|
| 594 |
+
r"\text{Number of bags of popcorn} = \frac{19.70}{0.55}"
|
| 595 |
+
"\n\\]\n\n\\[\n"
|
| 596 |
+
r"\text{Number of bags of popcorn} = 36"
|
| 597 |
+
"\n\\]\n"
|
| 598 |
+
)[0]
|
| 599 |
+
if [check.correct for check in display_assignments] != [False]:
|
| 600 |
+
raise AssertionError(f"Failed display-block assignments: {display_assignments}")
|
| 601 |
+
|
| 602 |
+
reused_label = check_completion(
|
| 603 |
+
"Total puppies = 14\n"
|
| 604 |
+
"Puppies with spots = 3\n"
|
| 605 |
+
"Total puppies = 11\n"
|
| 606 |
+
"Puppies with spots = 2\n"
|
| 607 |
+
)[0]
|
| 608 |
+
if reused_label:
|
| 609 |
+
raise AssertionError(f"Compared non-consecutive reused labels: {reused_label}")
|
| 610 |
+
|
| 611 |
+
prose_separated = check_completion(
|
| 612 |
+
"\\[\nTotal puppies = 14\n\\]\n"
|
| 613 |
+
"The next calculation changes topic.\n"
|
| 614 |
+
"\\[\nTotal puppies = 11\n\\]\n"
|
| 615 |
+
)[0]
|
| 616 |
+
if prose_separated:
|
| 617 |
+
raise AssertionError(f"Compared prose-separated labels: {prose_separated}")
|
| 618 |
+
print(f"Self-test passed ({len(cases)} cases).")
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def main() -> None:
|
| 622 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 623 |
+
parser.add_argument("inputs", nargs="*", type=Path, help="Inspect .eval logs or directories containing logs.")
|
| 624 |
+
parser.add_argument("--out-dir", type=Path, default=Path("reasoning_arithmetic"))
|
| 625 |
+
parser.add_argument("--max-samples", type=int)
|
| 626 |
+
parser.add_argument(
|
| 627 |
+
"--workers",
|
| 628 |
+
type=int,
|
| 629 |
+
help="Parallel log processes. Defaults to min(4, CPU count); use 1 for serial execution.",
|
| 630 |
+
)
|
| 631 |
+
parser.add_argument("--self-test", action="store_true")
|
| 632 |
+
args = parser.parse_args()
|
| 633 |
+
|
| 634 |
+
if args.self_test:
|
| 635 |
+
run_self_test()
|
| 636 |
+
if not args.inputs:
|
| 637 |
+
return
|
| 638 |
+
|
| 639 |
+
logs = discover_logs(args.inputs)
|
| 640 |
+
if not logs:
|
| 641 |
+
raise SystemExit("No non-empty .eval logs found.")
|
| 642 |
+
|
| 643 |
+
try:
|
| 644 |
+
workers = resolve_worker_count(args.workers, len(logs))
|
| 645 |
+
except ValueError as error:
|
| 646 |
+
parser.error(str(error))
|
| 647 |
+
print(f"Analyzing {len(logs)} log(s) with {workers} worker(s).")
|
| 648 |
+
|
| 649 |
+
summaries: list[dict] = []
|
| 650 |
+
sample_rows: list[dict] = []
|
| 651 |
+
expression_rows: list[dict] = []
|
| 652 |
+
for summary, samples, expressions in analyze_logs(logs, args.max_samples, workers):
|
| 653 |
+
summaries.append(summary)
|
| 654 |
+
sample_rows.extend(samples)
|
| 655 |
+
expression_rows.extend(expressions)
|
| 656 |
+
|
| 657 |
+
args.out_dir.mkdir(parents=True, exist_ok=True)
|
| 658 |
+
(args.out_dir / "summary.json").write_text(
|
| 659 |
+
json.dumps(summaries, ensure_ascii=False, indent=2),
|
| 660 |
+
encoding="utf-8",
|
| 661 |
+
)
|
| 662 |
+
write_csv(args.out_dir / "samples.csv", sample_rows)
|
| 663 |
+
write_csv(args.out_dir / "expressions.csv", expression_rows)
|
| 664 |
+
|
| 665 |
+
for summary in summaries:
|
| 666 |
+
breakdown = summary["wrong_expression_breakdown"]
|
| 667 |
+
print(
|
| 668 |
+
f"{summary['model']} | {summary['task']}: "
|
| 669 |
+
f"final={summary['final_accuracy']!s}, "
|
| 670 |
+
f"expressions={summary['expression_accuracy']!s}, "
|
| 671 |
+
f"coverage={summary['parse_coverage']!s}, "
|
| 672 |
+
f"wrong-step samples (right/wrong final)="
|
| 673 |
+
f"{breakdown['final_correct']['sample_wrong_expression_rate_checked']!s}/"
|
| 674 |
+
f"{breakdown['final_incorrect']['sample_wrong_expression_rate_checked']!s}, "
|
| 675 |
+
f"wrong expressions (right/wrong final)="
|
| 676 |
+
f"{breakdown['final_correct']['expression_wrong_rate']!s}/"
|
| 677 |
+
f"{breakdown['final_incorrect']['expression_wrong_rate']!s}"
|
| 678 |
+
)
|
| 679 |
+
print(f"Wrote {args.out_dir}")
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
if __name__ == "__main__":
|
| 683 |
+
main()
|