How to Evaluate LLM Math Reasoning: A Reproducible Evaluation Methodology

    This article provides developers and technical leads with a reproducible methodology for evaluating the mathematical reasoning capabilities of Large Language Models (LLMs). Rather than offering model rankings, it focuses on test design, script implementation, and metric definitions, enabling readers to apply this framework directly to their own business scenarios.

    Targeted at developers and technical leads selecting LLMs for their projects, this article explains how to evaluate a model’s mathematical reasoning capabilities using a reproducible methodology. We will not provide model rankings; instead, the focus is placed on test design, script implementation, and metric definitions, allowing you to directly apply these practices to your own business scenarios.

    1. Why Version Numbers and General Benchmarks Are Not Enough

    Public leaderboards typically use fixed question banks, and these questions and answers may have already appeared in the models’ training data. A version number only indicates the iteration order of the model, not how it performs on your specific tasks. Mathematical reasoning capabilities affect the reliability of scenarios such as code generation, algorithm design, and data analysis. Therefore, it is highly recommended to conduct a test using your own questions before making a selection.

    During evaluation, you need to pay attention to two things simultaneously. First, is the final answer correct? Second, is the reasoning process clear and is the length reasonable? Both factors affect cost and usability. A model that produces correct answers but has verbose, trial-and-error reasoning may be harder to use in high-concurrency scenarios than a model with slightly lower accuracy but faster response times.

    2. Three-Tier Test Set Design

    It is recommended to divide the test set into three tiers. For each tier, clearly specify the sample size, source, difficulty annotation, and scoring rules.

    1. Basic Calculation Questions: Validate the model’s ability to handle basic formulas and numbers. It is recommended to have at least 50 questions per category. Sources can include textbook exercises or self-generated arithmetic problems. Use exact matching for scoring.
    2. Competition-Level Closed-Ended Questions: These have unique answers and can be automatically scored. It is recommended to source these from public competition past papers, annotating the difficulty as easy, medium, or hard, with at least 30 questions per tier. When scoring, perform equivalent simplification on values and expressions before comparing them to avoid misjudgments caused by different notations.
    3. Open-Ended Math Logic Questions: These have no fixed solution method and require the model to propose a method or proof outline. Such questions cannot be automatically scored and require manual or judge-model scoring based on a rubric. For each question, clearly state the scoring criteria, such as whether the key lemmas are correct, whether the conclusion is complete, and whether circular reasoning exists.

    A portion of the test set should be retained as a final validation set and not used for any prompt tuning. Otherwise, it is difficult to determine whether an improved score stems from the model’s capability or from tuning specifically for known questions.

    3. Evaluation Script

    The following script demonstrates how to call an OpenAI-compatible API, record latency and token usage, and extract the final answer. The API key is read from an environment variable and is not hardcoded.

    1. import json
    2. import os
    3. import time
    4. import requests
    5. from requests.adapters import HTTPAdapter
    6. from urllib3.util.retry import Retry
    7. API_URL = os.environ.get("LLM_API_URL", "https://your-api-endpoint.com/v1/chat/completions")
    8. API_KEY = os.environ["LLM_API_KEY"]
    9. session = requests.Session()
    10. retry = Retry(
    11. total=3,
    12. backoff_factor=1.5,
    13. status_forcelist=[429, 500, 502, 503, 504],
    14. allowed_methods=["POST"],
    15. )
    16. session.mount("https://", HTTPAdapter(max_retries=retry))
    17. def evaluate_math_reasoning(question, model="target-model-v1", seed=None):
    18. headers = {
    19. "Content-Type": "application/json",
    20. "Authorization": f"Bearer {API_KEY}",
    21. }
    22. payload = {
    23. "model": model,
    24. "messages": [
    25. {"role": "system", "content": "You are a math expert. Please provide detailed problem-solving steps, and output 'Final Answer: [Answer]' on a separate line at the end."},
    26. {"role": "user", "content": question},
    27. ],
    28. "temperature": 0.0,
    29. }
    30. if seed is not None:
    31. payload["seed"] = seed
    32. start = time.perf_counter()
    33. try:
    34. resp = session.post(API_URL, headers=headers, json=payload, timeout=(5, 180))
    35. except requests.RequestException as exc:
    36. return {"question": question, "error": f"request_failed: {exc}"}
    37. latency = time.perf_counter() - start
    38. if resp.status_code != 200:
    39. return {"question": question, "error": f"http_{resp.status_code}", "detail": resp.text[:500]}
    40. data = resp.json()
    41. try:
    42. content = data["choices"][0]["message"]["content"]
    43. except (KeyError, IndexError, TypeError):
    44. return {"question": question, "error": "unexpected_response_schema"}
    45. usage = data.get("usage", {})
    46. final_answer = None
    47. if "Final Answer:" in content:
    48. final_answer = content.rsplit("Final Answer:", 1)[-1].strip()
    49. return {
    50. "question": question,
    51. "latency_s": round(latency, 3),
    52. "prompt_tokens": usage.get("prompt_tokens"),
    53. "completion_tokens": usage.get("completion_tokens"),
    54. "reasoning_chain": content,
    55. "final_answer": final_answer,
    56. }
    57. if __name__ == "__main__":
    58. test_questions = ["Prove that there are infinitely many primes."]
    59. for q in test_questions:
    60. print(json.dumps(evaluate_math_reasoning(q), ensure_ascii=False, indent=2))

    Note the following points in the script:

    Token counts should use the usage field returned by the API. Different models use different tokenizers, and the token count for the same Chinese text can vary significantly between models. Estimating via space splitting or character count is unreliable. If the API does not return usage, you can calculate it locally using the corresponding model’s tokenizer and note the tool used in your report.

    Setting temperature to 0 only reduces output randomness; it does not guarantee identical outputs every time. The same question should be sampled 3 to 5 times, recording the mean and variance of the accuracy. Whether the seed parameter takes effect depends on server-side support, which should be confirmed before use.

    Requests must have a timeout set and perform a limited number of retries for 429 and 5xx status codes. Otherwise, a single network glitch during batch testing can distort the entire batch of results. Failed requests should be logged separately; they should neither be counted directly as incorrect answers nor discarded.

    4. How to Calculate Composite Metrics

    It is recommended to split the composite score into three parts:

    Accuracy accounts for 50%. Statistics are kept separately by question type. The score for open-ended questions is converted by a judge to a fraction between 0 and 1 based on the rubric.

    Efficiency accounts for 30%. The metrics for efficiency must be clearly defined; otherwise, data from different environments cannot be compared. It is recommended to record the P50 and P95 of end-to-end latency, the average number of output tokens consumed per correct answer, and the cost per correct response. Region, concurrency, and request parameters should be fixed during testing.

    Logical Coherence accounts for 20%. This item is scored by a judge model, which should be different from the model being tested. The scoring prompt must specify the criteria, such as whether each derivation step has a basis, whether there are logical jumps, and whether it contains irrelevant repetitive content. Score each item from 1 to 5 and provide the reasoning.

    The weights of 50%, 30%, and 20% can serve as a starting point and be adjusted later according to business needs. It is recommended to perform a sensitivity analysis to see if the model ranking changes when weights are adjusted. If the ranking is highly sensitive to the weights, it indicates that the gap between models is small, and more samples are needed to draw a conclusion.

    5. How to Validate the Judge Model

    The judge model’s scoring may have biases and must be calibrated before formal use.

    First, manually annotate 50 to 100 reasoning chains as a calibration set. Then, calculate the consistency between the judge model and manual scores, for example, using Cohen’s kappa or correlation coefficient. If consistency is low, you should first revise the scoring rubric before re-scoring.

    Second, during formal testing, spot-check no less than 10% of the judge’s results every week. If the judge is found to systematically favor a certain writing style (for example, preferring longer answers), you need to add constraints in the prompt or switch to another judge model for cross-scoring.

    6. Model Selection Checklist

    When comparing candidate models, you can fill out a checklist item by item based on the metrics defined above. By systematically comparing accuracy, efficiency, and logical coherence across your specific three-tier test sets, you can make a more informed and reproducible decision tailored to your project’s exact requirements.