How to Build and Run a Math Reasoning Evaluation for Large Language Models

    Math reasoning evaluation is an engineering project, not a single benchmark score. This article walks through a practical approach: layering math tasks into measurable difficulty tiers (L1–L4), constructing an evaluation set that resists data contamination and stays judgeable and maintainable, scoring with pass@1, PASS@k, and all-pass rates instead of single-run accuracy, and quantifying cost, latency, and process quality per item. It includes a runnable evaluation skeleton, auto-grading logic based on symbolic comparison with regex fallback, guidance on expert review for proof tasks, cost and quota control strategies, and how to carry evaluation results into tiered routing, fallback paths, and ongoing regression monitoring.

    1. Why Treat Math Reasoning Evaluation as an Engineering Problem

    A familiar pattern shows up when developers compare model services. Benchmark scores on vendor pages often look nearly identical, but in real workloads the differences are obvious: some models get multi-step calculations right while contradicting themselves along the way, some write complete proofs that are almost unreadable, and some slow down badly at peak hours, forcing a fallback to a weaker option.

    General-purpose leaderboards cover many task types, so they rarely isolate math reasoning. Public test sets also leak into training corpora, which inflates scores. Getting a reliable basis for selection means building your own evaluation system focused on math reasoning. Three properties make math a good fit:

    1. Answers are relatively objective. Computational problems have unique solutions, and proofs can be judged rigorously on logical grounds, which reduces subjective bias.
    2. Processes are auditable. Conclusions, lemmas, case analysis, and boundary cases can all be checked item by item. This exposes “answer-fitting” hallucination: the final number happens to be right, but the reasoning does not hold up.
    3. The capability transfers. Symbolic reasoning underpins code generation, data analysis, and formal verification. Models that are consistently strong at math tend to be more reliable in those settings too.

    So instead of asking “is model X good,” ask three actionable questions: Which classes of math tasks does it handle well? How stable is it across repeated sampling? How much compute does it take to reach the same accuracy?

    2. Task Layering: Breaking “Math Ability” Into Measurable Dimensions

    Different math tasks place very different demands on a model. Using one ruler for everything wastes compute and hides real differences. The suggested split is four tiers:

    Tier Typical tasks Judging method What it measures
    L1 Basic computation Algebraic simplification, equation solving, elementary probability Automatic comparison against a standard answer Fundamentals and format compliance
    L2 Intermediate application Multi-step computation, combinations of classic problem types, ODE solving Automatic comparison plus light human review Stability of multi-step reasoning
    L3 Open-ended proofs Constructive proofs, counterexample construction, combinatorics and number theory proofs Line-by-line expert review Rigor of argumentation and mathematical writing
    L4 Exploratory tasks Unpublished or still-open problems Expert review for genuinely new ideas Upper bound of capability and generalization

    L3 and L4 usually offer the highest discrimination. They rarely appear verbatim in public corpora, so the model has to reason its way through. In one example, a model was asked to prove a proposition from a combinatorics source for which no proof had been published, and to produce the result as an English lecture note. There was no room to “look up the answer,” which makes such tasks a fairly direct signal of real reasoning ability.

    3. Constructing the Evaluation Set: Contamination-Resistant, Judgeable, Maintainable

    3.1 Resisting data contamination

    • Original or rewritten items: Write your own problems, or modify public ones by substituting values, adjusting conditions, and rewriting the narrative, then re-derive the reference answer.
    • Temporal isolation: Prefer material published after the corpus cutoff. New problems that human experts cannot solve quickly tend to discriminate better.
    • Deduplication screening: Before release, run text-similarity checks against known problem banks and drop items that are too close to something the model may have memorized.
    • Premise validation: Every record carries fields such as question, reference_answer, proof_outline, and judge_type. Self-written items must be checked for sufficient conditions. Anything uncertain should be routed to expert review rather than forced into a standard answer.
    1. # Illustrative structure of a single evaluation record (JSON)
    2. {
    3. "id": "L3-017",
    4. "level": "L3",
    5. "subject": "combinatorics",
    6. "question": "Original problem statement...",
    7. "reference_answer": "Reference answer or final result",
    8. "proof_outline": ["Key construction", "Induction step", "Handling of boundary cases"],
    9. "judge_type": "expert", # auto = automatic grading / expert = expert review
    10. "source": "in_house",
    11. "created_at": "2026-03-12"
    12. }

    3.2 Judgeable

    For computational items, standardize how the reference answer is written: fractions as a/b, radicals as sqrt(n), constants as pi or e. Numeric items should state a precision requirement and be compared within a tolerance.

    Proofs cannot be matched as raw strings. Reviewers need to prepare a checklist in advance: the correct key lemmas, complete case analysis, no missing boundary cases, rigorous limit arguments, and so on. The checklist serves as the prompt for automated review and as the scoring rubric for experts.

    3.3 Maintainable

    • Version the evaluation set, the scoring rules, and the prompt templates.
    • Record the model version, sampling parameters, and rule version for every run.
    • Write results to object storage and keep them long-term, so you can later answer “did the model change, or did the items change?”

    4. Running the Evaluation and Scoring: From Single-Run Accuracy to a Stability Profile

    4.1 Fix the sampling strategy

    Pin down temperature, max output length, and number of samples for every run. Use at least 3–5 samples so single-run variance does not drive the conclusion.

    • pass@1: Reporting only “the fraction answered correctly on the first try” is not enough. Also report the mean score across repeated samples, which reflects expected performance.
    • PASS@k: Use the unbiased estimator

      [
      \mathrm{PASS}@k = 1 - \frac{\binom{n-c}{k}}{\binom{n}{k}}
      ]

      where (n) is the total number of samples and (c) is the number of correct ones. It gives the probability of at least one correct answer in another (k) draws, which measures whether the model is capable of solving the item.

      If accuracy is fairly stable across samples, a temperature around 0.6 balances diversity and convergence. If the model tends to oscillate between multiple solution paths, lower the temperature. The important part is to fix the choice so results stay comparable.

    • All-pass rate: Measures stability in the sense of “correct every single time.” It describes capability from a different angle than PASS@k, and both matter.

    4.2 Automatic grading must be trustworthy

    Check answer format first, then verify equivalence with symbolic computation, and only then fall back to numeric comparison. The code below shows the core idea:

    1. import re
    2. import sympy as sp
    3. NUMERIC_TOL = 1e-6 # Relative tolerance for numeric items; tune per use case
    4. def extract_boxed(text: str):
    5. """Extract the content of the last \boxed{...}, supporting one level of nested braces."""
    6. start = text.rfind(r"\boxed{")
    7. if start < 0:
    8. return None
    9. i = start + len(r"\boxed{")
    10. depth, end = 1, i
    11. while end < len(text) and depth > 0:
    12. if text[end] == "{":
    13. depth += 1
    14. elif text[end] == "}":
    15. depth -= 1
    16. end += 1
    17. return text[i:end - 1] if depth == 0 else None
    18. def to_symbolic(answer: str):
    19. """Convert common math notation into a SymPy-parsable expression; return None on failure."""
    20. if answer is None:
    21. return None
    22. normalized = (
    23. answer.strip()
    24. .replace("\\left", "").replace("\\right", "")
    25. .replace("\\dfrac", "\\frac").replace("\\tfrac", "\\frac")
    26. .replace("\\cdot", "*").replace("\\times", "*")
    27. .replace("\\ln", "log").replace("\\log", "log")
    28. .replace("\\pi", "pi")
    29. )
    30. try:
    31. return sp.sympify(normalized)
    32. except (sp.SympifyError, SyntaxError, TypeError):
    33. return None
    34. def judge_auto(item: dict, completion: str) -> int:
    35. """Auto-grade objective items: numeric items use a tolerance, others use symbolic equivalence."""
    36. pred = to_symbolic(extract_boxed(completion))
    37. gold = to_symbolic(item["reference_answer"])
    38. if pred is None or gold is None:
    39. return 0
    40. if item.get("numeric"):
    41. try:
    42. return int(abs(float(sp.N(pred)) - float(sp.N(gold)))
    43. <= NUMERIC_TOL * max(1.0, abs(float(sp.N(gold)))))
    44. except (TypeError, ValueError):
    45. return 0
    46. try:
    47. return int(sp.simplify(pred - gold) == 0) # Subtract first, then simplify: faster than simplifying each side
    48. except (TypeError, ValueError, RecursionError, TimeoutError):
    49. return 0
    50. def fallback_regex_judge(gold: str, pred: str) -> int:
    51. """Fallback: exact match, or match after stripping whitespace and common LaTeX commands."""
    52. def canonical(s: str) -> str:
    53. s = re.sub(r"\\[a-zA-Z]+", "", s) # Drop command names like \frac, \sqrt
    54. return re.sub(r"[\s{}]", "", s)
    55. return int(canonical(gold) == canonical(pred))

    Symbolic grading is inherently approximate. Overly complex expressions can make simplification time out, so set a timeout and keep the regex fallback in place.

    For proof tasks, combine automated screening with expert review:

    • Automated screening: In the judging prompt, have the model walk the checklist and emit a structured verdict, for example whether all cases are covered and whether any unproven proposition was used.
    • Expert review: Two independent blind reviews. If they disagree on whether the argument holds, a third reviewer arbitrates.
    • Human calibration: Automated review will misjudge some items. Periodically sample expert-graded items and compute the agreement rate between the automated judge and the experts. That agreement rate is how you decide whether the judge itself can be trusted.

    4.3 Quantify process quality too

    • Tokens to first correct result: Record how many tokens are consumed before the first correct answer (or key lemma) appears. A longer chain of thought does not imply greater capability.
    • Cost per item: Estimated as (C{\text{item}}=(T{in}+T{out})\times P\times n), where (T{in}) and (T_{out}) are average input and output tokens, (P) is the price per token, and (n) is the number of samples. Use cost per item divided by accuracy as the value metric.
    • Mathematical writing quality: Score on whether theorem statements are precise, whether notation stays consistent, and whether the LaTeX compiles and renders.

    4.4 A runnable evaluation skeleton

    The script below is a working skeleton. The model-calling layer is a placeholder interface; swap in the implementation for whichever service you use.

    1. import json
    2. import math
    3. import random
    4. import time
    5. from concurrent.futures import ThreadPoolExecutor, as_completed
    6. from pathlib import Path
    7. TEMPLATE_VERSION = "v1.0" # Prompt template version
    8. RUN_ID = "eval_20260312_01"
    9. def load_dataset(path: str) -> list:
    10. with open(path, encoding="utf-8") as f:
    11. return [json.loads(line) for line in f if line.strip()]
    12. def build_messages(item: dict) -> list:
    13. return [
    14. {"role": "system", "content": "You are a rigorous math assistant. Analyze first, then answer. Wrap the final answer in \\boxed{}."},
    15. {"role": "user", "content": f"Problem: {item['question']}\nAnswer requirement: {item['judge_type']}"},
    16. ]
    17. # ---- Placeholder interface; replace with your model service call ----
    18. def chat_once(messages, temperature, max_tokens, timeout=120):
    19. raise NotImplementedError("Replace with the call implementation for your model service")
    20. def usage_of(resp):
    21. return {"prompt_tokens": 0, "completion_tokens": 0}
    22. # -------------------------------------------------------------------
    23. def judge_item(item: dict, completion: str) -> int:
    24. return 0 # Replace with a real judge: judge_auto or the expert review result
    25. def pass_at_k(c: int, n: int, k: int) -> float:
    26. """Unbiased PASS@k estimate: 1 - C(n-c, k) / C(n, k)."""
    27. if n - c < k:
    28. return 1.0
    29. return 1.0 - math.comb(n - c, k) / math.comb(n, k)
    30. def evaluate(client, n: int = 4, temperature: float = 0.6, workers: int = 4) -> dict:
    31. dataset = load_dataset("math_eval.jsonl")
    32. groups = {}
    33. for idx, item in enumerate(dataset):
    34. group = str(item.get("id", "G0"))
    35. groups.setdefault(group, []).append((idx, item))
    36. rows, stats = [], {"prompt_tokens": 0, "completion_tokens": 0, "calls": 0}
    37. def run_one(task):
    38. idx, item, seed = task
    39. random.seed(f"{RUN_ID}:{TEMPLATE_VERSION}:{idx}:{seed}")
    40. t0 = time.perf_counter()
    41. resp = chat_once(build_messages(item), temperature, max_tokens=16384)
    42. usage = usage_of(resp)
    43. correct = judge_item(item, resp.text) if resp.ok else 0
    44. return idx, {
    45. "correct": correct, "usage": usage,
    46. "latency_s": round(time.perf_counter() - t0, 3),
    47. "error": None if resp.ok else resp.error,
    48. }
    49. # Queue by item group; members of a group run sequentially in a fixed order,
    50. # and the random seed keeps runs reproducible
    51. tasks = []
    52. for group, members in groups.items():
    53. for s in range(n):
    54. for idx, item in members:
    55. tasks.append((idx, item, s))
    56. with ThreadPoolExecutor(max_workers=workers) as pool:
    57. futures = {pool.submit(run_one, t): t[0] for t in tasks}
    58. for fut in as_completed(futures):
    59. idx, res = fut.result()
    60. rows.append((idx, res))
    61. stats["prompt_tokens"] += res["usage"]["prompt_tokens"]
    62. stats["completion_tokens"] += res["usage"]["completion_tokens"]
    63. stats["calls"] += 1
    64. rows.sort(key=lambda r: r[0])
    65. record = {
    66. "run_id": RUN_ID, "template_version": TEMPLATE_VERSION, "n": n,
    67. "items": [{
    68. "id": dataset[i].get("id", str(i)),
    69. "level": dataset[i].get("level", "L1"),
    70. "passes": sum(r["correct"] for j, r in rows if j == i),
    71. "latency_s": sum(r["latency_s"] for j, r in rows if j == i),
    72. "errors": [r["error"] for j, r in rows if j == i and r["error"]],
    73. } for i in range(len(dataset))],
    74. "usage": stats,
    75. }
    76. # Aggregate pass@1 / pass@k / all-pass rate by difficulty level
    77. report = {}
    78. for level in sorted({it.get("level", "L1") for it in dataset}):
    79. subset = [x for x in record["items"] if x["level"] == level]
    80. m = len(subset)
    81. if m == 0:
    82. continue
    83. report[level] = {
    84. "count": m,
    85. "pass@1": round(sum(x["passes"] for x in subset) / (m * n), 4),
    86. "pass@k": round(sum(pass_at_k(x["passes"], n, n) for x in subset) / m, 4),
    87. "all_pass": round(sum(x["passes"] == n for x in subset) / m, 4),
    88. "avg_latency_s": round(sum(x["latency_s"] for x in subset) / (m * n), 3),
    89. }
    90. record["report"] = report
    91. out = Path(f"eval_results/{RUN_ID}.json")
    92. out.parent.mkdir(exist_ok=True)
    93. out.write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
    94. return record
    95. if __name__ == "__main__":
    96. print(json.dumps(evaluate(client=object()), ensure_ascii=False, indent=2))

    The skeleton reflects three design choices:

    • Reproducible: every run gets a unique RUN_ID, and combined with a pinned prompt version and fixed random seed, the same configuration can reproduce the same results.
    • Decomposable: pass counts, latency, and token usage are recorded per item, which makes stratified analysis by difficulty straightforward.
    • Auditable: all results land on disk in a consistent format, making version-to-version comparison easy.

    5. Cost, Throughput, and Quota Governance: Accuracy Is Not the Whole Story

    5.1 Usage estimation

    Total evaluation cost is (C = n \times m \times (T{in}+T{out}) \times P), where (m) is the number of items. Output tokens are usually billed at a higher rate, and long-chain reasoning spends most of its budget on output. Cost grows linearly with the number of samples and quickly with output length, so estimate before you run.

    5.2 Capacity and queuing

    Two problems show up in practice:

    • Some models queue at peak hours, and the wait is unpredictable.
    • Some credit- or quota-based plans still have credits left, yet queuing makes them impractical to use.

    Queuing can be approximated with queueing theory: service intensity (\rho=\lambda/\mu), where (\lambda) is the request arrival rate and (\mu) is the service rate. As (\rho) approaches 1, queueing time rises sharply. In other words, high throughput with low latency requires enough service capacity behind it; rate limiting alone will not fix it.

    5.3 Five cost-control strategies

    1. Stratified sampling: Basic items need only a few samples to classify; reserve larger sample counts for hard items.
    2. Cache reuse: Cache results for calls with identical prompt templates, temperature, and sample counts. Change the template and the cache is invalidated.
    3. Budget circuit breaker: Set a total token budget per run, stop gracefully at the threshold, and record whatever has completed.
    4. Batching and off-peak scheduling: Run offline batch evaluation during business troughs rather than online peaks.
    5. Unified observability: On a cloud platform such as Baidu AI Cloud, you can store evaluation results in object storage, run evaluation jobs on a container platform, retain call records through a logging service, and track cost and failure rates with monitoring and alerting. Aggregate token usage and spend per project so abnormal growth triggers an alert.

    For plans billed by credits or quota, “assess first, invest later” matters even more: use a small sample to estimate pass rates and per-item consumption on hard problems before deciding whether to scale up.

    6. From Evaluation to Production: Routing, Fallback, and Regression Monitoring

    6.1 Tiered routing

    Route requests to different model tiers and sizes based on problem difficulty and business latency requirements:

    • Simple computation and formatting tasks go to lightweight, low-cost models.
    • Open-ended proofs and complex modeling go to models with stronger reasoning.

    The per-difficulty accuracy and cost-per-item figures in the evaluation report are exactly what you need to set routing thresholds.

    6.2 Cross-checking

    For critical tasks, have two models built on different technical approaches solve the problem independently. If the results agree, take the answer; if they disagree, bring in an arbitration step. The “two-model agreement rate” measured during evaluation tells you how many potential errors such a mechanism would catch.

    6.3 Rate limiting and fallback

    When a model is slow or unavailable, set timeouts and retry caps, and keep a fallback path ready so evaluation jobs cannot crowd out production traffic.

    6.4 Regression monitoring

    Model services keep changing, so evaluation has to become routine:

    • Version upgrades: Re-run the pinned baseline evaluation set after every upgrade.
    • Regression alerts: Trigger an alert automatically when a core metric at any level drops past a set threshold (for example, 3 percentage points).
    • Item rotation: Add new items regularly and retire old ones that may have been memorized, so the evaluation set does not go stale.

    7. Common Pitfalls

    1. Judging by a single run. One correct answer may be a lucky guess. Track PASS@k and the all-pass rate alongside it.
    2. Using public problem sets for everything. If the model has likely seen the items, results are inflated. The core evaluation set should be original.
    3. Treating thinking length as skill. Long reasoning sometimes just means repeated trial and error. Look at tokens-to-correctness, in other words, cost-effectiveness.
    4. Ignoring mathematical writing. Proofs are ultimately read by people, so rigorous argumentation and clear exposition both matter.
    5. Evaluation that does not match production. If production uses tools, appends retrieved content, or applies a different system prompt, offline results do not transfer. Evaluation configuration should stay close to the real call path.

    8. Conclusion

    Deciding whether a model fits a math reasoning workload cannot rest on a single score. What works is a layered, reproducible, cost-aware evaluation system:

    • Layer math tasks by difficulty.
    • Use original items to counter memorization.
    • Measure the capability ceiling with PASS@k and stability with the all-pass rate.
    • Measure real cost with token usage.

    Combined with tiered routing and routine regression checks, this setup supports model selection today and keeps protecting the quality of production math reasoning services as models keep iterating.