Building and Evaluating Math-Specialized LLMs: A Practical Guide

    General-purpose LLMs often struggle with multi-step mathematical reasoning, symbolic formatting, and verifiable intermediate steps. This practical guide examines why those failures occur and outlines a pipeline for building and evaluating math-specialized models, covering domain continued pre-training, iterative corpus mining, Base/Instruct/RL model stages, evaluation design that separates tool-free and tool-assisted results, and engineering deployment considerations.

    1. Background: Why General-Purpose LLMs Can Calculate but Cannot Prove

    General-purpose large language models perform well in open-domain dialogue and text generation, but they commonly exhibit three weaknesses in mathematical tasks. First, long-chain reasoning decay: in multi-step derivations, earlier conclusions are easily overwritten by later generation. Second, symbolic and formatting fragility: formulas, superscripts, subscripts, fractions, and other structures are easily damaged during tokenization and generation. Third, unverifiable processes: the model provides an answer but lacks inspectable intermediate steps.

    As a result, the industry has gradually reached a consensus: mathematical capability is not obtained simply by scaling parameters. It depends more on the coordination of three elements: domain data quality + training-stage design + a verifiable evaluation loop. The value of math-specialized models lies in turning these three elements into an engineering pipeline.

    2. Build Path: From General Base to Domain Continued Pre-training

    The mainstream approach is not to train from scratch. Instead, teams select an open-source base model with strong code and text capabilities and perform domain continued pre-training. Publicly available practice shows that a math-specialized open-source model family initialized from a 7B-parameter-class code-capable base completed about 500 billion tokens of continued pre-training on math-related tokens filtered from web corpora, mixed with natural language and code data.

    There are two key engineering judgments here:

    • Why introduce code data: mathematical proofs and program-based solving are highly isomorphic in structure—both follow “definition—transformation—verification.” Code corpora can strengthen the model’s awareness of step-by-step execution, making it more inclined to write executable solution processes.
    • Token scale and mix: domain continued pre-training does not mean feeding the model only mathematics. A purely domain-specific corpus causes catastrophic forgetting of general capabilities. In practice, a substantial proportion of natural language and code tokens is usually retained to maintain general understanding and instruction-following ability.

    3. Data Engineering: A Four-Round Iterative Corpus Mining Loop

    High-quality mathematical corpora are scarce, and single-round filtering makes it difficult to balance coverage and purity. A reusable four-round iterative paradigm is as follows:

    1. Seed construction: use an existing open-source mathematical web corpus as the initial seed.
    2. Lightweight classifier training: train a linear text classification model, such as a fast classifier based on bag-of-words and hashing techniques, to learn “mathematicalness” discrimination.
    3. Large-scale retrieval: perform full scoring and threshold filtering on a deduplicated general web corpus.
    4. Domain discovery and human backfill: perform statistical analysis on high-scoring samples to identify uncovered mathematical subdomains; manually annotate a batch of relevant links and add the uncollected pages they point to into the seed library.
    5. Repeat iteration: cycle through the above process four times, ultimately obtaining approximately 35.5 million mathematical web pages and about 120 billion tokens of training corpus.

    The essence of this loop is: the classifier handles scale, while human annotation handles boundaries. Fully automatic filtering systematically misses pages with obscure wording or messy layout but correct content, and human backfill precisely fills the recall gap.

    4. Three-Stage Model Evolution: Base, Instruct, and RL

    • Base model: carries domain knowledge and, during evaluation, elicits reasoning through few-shot chain-of-thought prompting.
    • Instruction-tuned model: aligns with the output habit of “step-by-step reasoning,” making the solution process structured and readable.
    • Reinforcement learning model: uses algorithms such as Group Relative Policy Optimization (GRPO) to sample multiple solutions for the same problem and construct relative advantage signals based on answer correctness, thereby improving accuracy without relying on external tools. If the model is allowed to call computational tools, competition-level benchmark results can be further improved to a level close to 60%.

    It is worth noting that public results show that this type of 7B-parameter-class model can achieve approximately 51.7% accuracy on competition-level mathematical benchmarks without using external toolkits or multiple-sample voting, approaching the level of contemporaneous flagship closed-source models. This indicates that the marginal returns from data and training strategy can exceed pure parameter expansion in a specific vertical domain.

    5. Evaluation Design: Avoiding High-Score Illusions

    Evaluating mathematical capability should cover at least four dimensions:

    Dimension Focus Common pitfall
    Competition-level QA Multi-step reasoning accuracy Reporting only the best value under a single prompt setting
    Tool collaboration Whether the model can write a correct solving program Not distinguishing “the model computed correctly” from “the tool computed correctly”
    Formal proof Verifiable derivation within a symbolic system Passing natural-language proofs off as formal proofs
    General capability regression Whether understanding, reasoning, and coding degrade Looking only at math scores and ignoring catastrophic forgetting

    Be sure to fix the prompt template, temperature, and sampling count, and report both tool-free and tool-assisted results. Otherwise, the numbers are not comparable.

    6. Engineering Deployment and Example Code

    Open-source checkpoints usually provide a context length of 4096, which is sufficient to hold the problem statement and complete derivation for a competition-style problem. On the deployment side, it is recommended to store model weights in object storage, run inference services on a container platform, and observe the call chain through centralized logging and monitoring/alerting.

    1. # Illustrative pseudocode: load a local checkpoint and perform math text completion
    2. model = load_causal_lm(checkpoint_path, dtype="bfloat16", device_map="auto")
    3. tokenizer = load_tokenizer(checkpoint_path)
    4. prompt = "Calculate the definite integral ∫₀² x² dx and provide the complete derivation steps:"
    5. inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    6. outputs = model.generate(**inputs, max_new_tokens=1024,
    7. do_sample=False, temperature=None)
    8. print(tokenizer.decode(outputs[0], skip_special_tokens=True))

    Engineering recommendations: prefer greedy or low-temperature decoding to ensure stable derivations; for scenarios requiring numerical precision, add a tool loop of “generate code—execute—backfill results”; for batch scenarios, use continuous batching and quantization to reduce unit inference cost.

    7. Deployment Checklist

    1. Does the base model have code capability? Avoid using a pure-text base for mathematical continued pre-training.
    2. Has the corpus undergone triple checks for quality, deduplication, and contamination (evaluation-set leakage)?
    3. Has a general-corpus ratio been retained to suppress capability forgetting?
    4. Does evaluation use a fixed configuration and distinguish between tool on and tool off?
    5. Before launch, have stability stress testing and cost evaluation for long-chain reasoning been completed?

    In summary, the core competitiveness of math-specialized models comes from “an iterable data loop + staged training strategy + a verifiable evaluation system,” rather than a single parameter metric. Teams following this path can achieve significant vertical-domain gains under limited compute.