Evaluating Long-Context Math Reasoning: A Reproducible Practical Guide

    Evaluating long-context mathematical reasoning models requires a structured and reproducible approach to avoid hidden errors like "lost in the middle." This guide provides developers with a practical framework for conducting internal evaluations. It covers designing anti-contamination evaluation sets, context governance with rollback mechanisms, statistical metrics and tiering using confidence intervals, deployment cost measurement, and a step-by-step action template. By following this guide, developers can make reliable model selection decisions.

    Introduction: Why Long-Context Math Reasoning Requires Reproducible Evaluation

    Many developers have encountered the “lost in the middle” phenomenon when processing long materials. For instance, if a model is given a document containing over thirty definitions and lemmas and asked to prove a specific corollary, it might reference a non-existent lemma in an intermediate step or reverse a condition’s direction, while the final conclusion still appears reasonable. Such errors are hard to spot with the naked eye and difficult to judge through a one-off subjective trial.

    This article targets developers who need to conduct their own model selection or internal evaluations. Following the sequence of “Problems, Context, Metrics, Cost, Actions,” it provides a reproducible evaluation methodology along with runnable code and recording table templates.

    1. Why Design the Evaluation Set First

    Evaluation results depend primarily on the problems themselves. If a proposition already has a public proof, the model might rely on its training data to recite the answer, testing its memorization rather than reasoning ability. Therefore, the evaluation set should prioritize propositions meeting two conditions: they have no publicly available complete proof, and their conclusions can be independently verified.

    1.1 Problem Selection and Verification Methods

    Each problem should have a registered verification method. Common approaches include:

    • Formal verification: Using proof assistants like Lean to check the model’s proof. The result can be automatically determined.
    • Symbolic or numerical verification: Substituting specific parameters for calculation to check if the conclusion holds.
    • Expert review: Judged by personnel with the relevant background, suitable for problems that cannot be formalized.

    The verification method determines the credibility ceiling of the evaluation. If only expert review is possible, the report should specify the number of reviewers and the inter-rater agreement rate.

    1.2 Anti-Contamination Measures

    Once an evaluation set is made public, it may enter future training data. Therefore, regular checks are required:

    1. Record the source and first public date of each problem, and compare them with the training cutoff date of the models being tested.
    2. Perform equivalent rewrites on the problems, such as replacing variable names or changing specific numerical values, while preserving the reasoning structure.
    3. Maintain an undisclosed holdout set, used only for official comparisons.
    4. Replace a portion of the samples each quarter, with a replacement ratio set around 20%.

    1.3 Sample Size and Output Format

    It is recommended to have no fewer than 50 problems per task type. If comparing the accuracy differences between two models, it is best to have at least 100 problems per group. The output should uniformly be a LaTeX-formatted derivation process, with the conclusion provided on a separate final line, making it easy for a program to extract the conclusion and submit it for manual review.

    The evaluation set registration table template is as follows:

    Field Description Example
    Problem ID Unique identifier LC-017
    Source & First Public Date Origin and time of the proposition An open-source repo, 2024-03
    Verification Method Formal, symbolic/numerical, or expert review Formal verification
    Context Length Input token count ~16k
    Is Rewritten Yes or No Yes
    Reviewer Personnel responsible for judgment Jane Doe
    Remarks Other notes None

    2. Context Governance: Cleaning Must Be Rollback-able

    The goal of context cleaning is to reduce noise without deleting the information necessary for reasoning. A robust process includes five steps: deduplication, contradiction annotation, sorting by logical dependency, fidelity verification, and rollback when limits are exceeded or fidelity is lost.

    For contradiction detection, automatically modifying the original text is not recommended. Automatically resolving contradictions might alter the original intent of the material. Instead, log the contradiction locations and confirm them manually or via explicit rules.

    The following code relies only on the Python standard library. Paragraph deduplication uses character similarity with a threshold of 0.92. Fidelity verification checks whether theorem numbers, variable names, and numbers still appear in the cleaned text; a retention rate below 0.90 triggers a rollback to the original text.

    1. import re
    2. from dataclasses import dataclass
    3. from difflib import SequenceMatcher
    4. from typing import Callable, List
    5. @dataclass
    6. class CleanConfig:
    7. max_tokens: int = 16000 # Max tokens allowed after cleaning
    8. dedup_threshold: float = 0.92 # Paragraph similarity at this value is considered duplicate
    9. min_keep_ratio: float = 0.90 # Lower limit for key item retention rate
    10. def dedup_paragraphs(paragraphs: List[str], threshold: float) -> List[str]:
    11. kept: List[str] = []
    12. for p in paragraphs:
    13. if not any(SequenceMatcher(None, p, q).ratio() >= threshold for q in kept):
    14. kept.append(p)
    15. return kept
    16. def key_tokens(text: str) -> set:
    17. return set(re.findall(r"[A-Za-z]+\d*|\d+(?:\.\d+)?", text))
    18. def fidelity_ratio(original: str, cleaned: str) -> float:
    19. src = key_tokens(original)
    20. if not src:
    21. return 1.0
    22. return len(src & key_tokens(cleaned)) / len(src)
    23. def clean_context(raw_text: str, cfg: CleanConfig,
    24. count_tokens: Callable[[str], int]):
    25. paragraphs = [p.strip() for p in raw_text.split("\n\n") if p.strip()]
    26. cleaned = "\n\n".join(dedup_paragraphs(paragraphs, cfg.dedup_threshold))
    27. if fidelity_ratio(raw_text, cleaned) < cfg.min_keep_ratio:
    28. return raw_text, "rollback_fidelity"
    29. if count_tokens(cleaned) > cfg.max_tokens:
    30. return raw_text, "rollback_over_limit"
    31. return cleaned, "ok"

    Usage instructions: count_tokens should be provided by the tokenizer of the model used; do not use character count as a substitute for token count to judge limits. When there are many paragraphs, pairwise comparison is expensive. You can first use exact hash deduplication, followed by similarity comparison for small batches. This code has not been validated on your data; before formal use, inspect the output with about 20 samples.

    Each cleaning run should save the original text hash, cleaned text hash, status code, and contradiction log. When encountering rollback_over_limit, do not forcefully truncate the material. Instead, switch to a model with a longer context window, or split the task into multiple segments.

    3. Metrics and Tiering: Use Thresholds Instead of Impressions

    Evaluation results should be expressed with metrics. The table below lists the recommended core metrics.

    Metric Calculation Type Pass Condition (Example, to be set by business)
    Accuracy Number of problems with correct conclusions and no fatal derivation errors divided by total problems Quality >= 0.80
    Stability Proportion of problems with consistent conclusions when sampled 5 times Quality >= 0.90
    Derivation Completeness Proportion of manually annotated key steps covered Quality >= 0.85
    Cost per Problem Input and output token count multiplied by unit price Constraint Within budget
    P95 Latency Completion time for 95% of requests Constraint Within product requirements

    Cost and latency are constraints and do not participate in the weighted average of quality metrics. A model exceeding the budget or latency limit fails directly.

    Sample size affects the reliability of conclusions. The 95% confidence interval for accuracy can be estimated using normal approximation, with a half-width of approximately 1.96 * sqrt(p(1-p)/n). When n is 100 and the accuracy is 80%, the half-width is about 8 percentage points. If two models differ in accuracy by only 5 percentage points, a meaningful difference generally cannot be determined with a sample of 100 problems.

    Tiering should not predefine “tiers” but should be determined based on results under the same evaluation conditions:

    1. Compare all models under the same evaluation set, output format, and context window tier.
    2. A difference in accuracy between two models is only considered significant if it exceeds the combined width of their confidence intervals.
    3. Record results by context window tier, such as 4k, 16k, and 64k token levels. A model is marked as available only on tiers where it passes the threshold.
    4. If a model’s accuracy drops significantly at longer tiers, record the context length at which the drop begins as the capability degradation point.

    The result summary table template is as follows:

    Model Version Context Tier Num Problems Accuracy 95% CI Stability P95 Latency Cost per Problem Conclusion
    Model A Example v1.0 16k 100 0.82 ±0.08 0.91 4.2s $0.005 Available

    The table should also record the sampling temperature, max output tokens, and evaluation date. Without these parameters, the results cannot be reproduced.

    4. Deployment Cost and Selection Checklist

    Cost descriptions must specify the measurement criteria. Statements like “a certain task consumes a certain percentage of a platform’s quota” are irreproducible and incomparable with other solutions if the platform, quota, task scale, and billing method are missing. It is recommended to record the following table for each evaluation:

    Field Description
    Platform & Billing Method Pay-as-you-go or monthly, unit price, and currency
    Task Description Lecture length, number of problems, average tokens per problem
    Call Count Including retries and multiple samplings
    Total Consumption Input tokens, output tokens, and total cost
    Cost per Output Total cost divided by the number of outputs passing review

    The denominator for cost per output only counts outputs that pass review, while the numerator includes costs for all calls. The resulting figure reflects the true cost.

    Throughput and latency also require unified criteria. Measurements should specify hardware model, batch size, input and output sequence lengths, concurrency, tokens/s, and P95 latency. The results of the same model can vary greatly under different batch sizes; figures under different conditions cannot be compared directly.

    Deployment options can be judged in the following order:

    1. Data Sensitivity: When materials involve internal or restricted data, prioritize self-deployment or privatized services.
    2. Concurrency Peaks: When traffic fluctuates greatly, cloud elastic scaling is usually easier for cost control.
    3. Operations Staffing: Self-deployment requires handling environment configuration, model updates, and fault resolution. If the team lacks manpower, this cost should be factored into the total cost.

    Selection checklist:

    • Does the evaluation set have verifiable conclusions and has it been processed for anti-contamination?
    • Are candidate models compared under the same context window tier and output format?
    • Are confidence intervals provided for accuracy?
    • Are cost and latency measured under the same criteria?
    • Are model versions and sampling parameters recorded?
    • Does context cleaning have fidelity verification and a rollback mechanism?

    5. Action Template

    5.1 Three-Week Execution Plan

    1. Week 1: Establish the evaluation set registration table and annotate verification methods for at least 50 problems.
    2. Week 2: Implement context cleaning, perform fidelity verification with about 20 problems, and record the rollback rate.
    3. Week 3 onwards: Run full evaluations for each candidate model, saving raw outputs and extracted conclusions.

    5.2 Review Steps

    1. Fully manually review all error samples to determine whether it is a model error or an incorrect verification standard.
    2. Spot-check 20% of correct samples to check for skipped steps or references to non-existent theorems.
    3. Categorize deviations into symbolic errors, omitted conditions, skipped steps, citation errors, or conclusion errors.
    4. Write the categorized results into a report and update the prompt or context cleaning rules accordingly.

    5.3 Call Layer Interface Contract

    The call layer is only responsible for returning raw results; scoring and calling are separated. This way, when switching models, the evaluation script requires no changes.

    1. from dataclasses import dataclass
    2. from typing import Protocol
    3. @dataclass
    4. class ModelResult:
    5. text: str
    6. input_tokens: int
    7. output_tokens: int
    8. latency_ms: float
    9. model_version: str
    10. class ModelAdapter(Protocol):
    11. def generate(self, context: str, prompt: str,
    12. max_output_tokens: int, temperature: float) -> ModelResult:
    13. """Calls the model and returns the raw result, without judging the conclusion."""
    14. ...
    15. def extract_conclusion(self, result: ModelResult) -> str:
    16. """Extracts the conclusion from the last line of the output, returns empty string if format is invalid."""
    17. ...

    Each model only needs to implement this interface, and the evaluation script will not depend on a specific vendor’s SDK. The token counts and latency returned by the interface will go directly into the cost and latency recording table.

    6. Conclusion

    Evaluating long-context math reasoning requires a reproducible process. Problems must be verifiable, cleaning must be rollback-able, and metrics must have confidence intervals. Without any of these three, the conclusions will be difficult to use for model selection.