Math-Specialized LLMs: Data Engineering and Reasoning Enhancement

    This article outlines a practical engineering path for building math-specialized large language models, covering the rationale for domain-specific math models, a closed-loop pipeline from base initialization to tool augmentation, four-round data engineering for high-quality math corpora, continued pretraining with code-capable bases, instruction tuning for verifiable step-by-step reasoning, reinforcement learning with relative policy optimization and reward design, tool integration for programmatic solving and formal proof, layered evaluation, and production deployment practices. Readers will learn how data quality, reasoning alignment, tool use, and regression testing fit together, along with key risks such as evaluation leakage, data contamination, reward hacking, and overfitting to public benchmarks.

    1. Background: Why Math Reasoning Needs Specialized Models

    Math reasoning differs significantly from general natural language tasks. It typically requires a model to combine symbolic understanding, multi-step derivation, constraint satisfaction, result verification, and normalized expression. A math problem often has only one final answer, but it can have many intermediate steps. The model must not only “calculate correctly” but also “explain clearly,” while maintaining consistency across steps in complex problems. General language models perform well in open-domain question answering, but when faced with competition-level math problems, programmatic solving, and formal proofs, they are prone to losing conditions midway, misusing symbols, skipping steps, and producing unstable answer formats.

    Therefore, the technical path for math-specialized models is usually not simply adding math data to general corpora. Instead, it forms a complete closed loop around “math corpus construction—continued pretraining—instruction tuning—reinforcement learning—tool integration—evaluation regression.” In publicly described technical practice, a class of billion-parameter-scale math-specialized models can approach leading closed-source general models on competition-level math reasoning benchmarks through large-scale continued pretraining and subsequent alignment. After introducing tool calls and reinforcement learning, capability can be further improved. The key value is not only a single benchmark score, but also the validation of a reproducible, scalable engineering path with open model checkpoints.

    2. Overall Technical Path: From Base Initialization to Tool Augmentation

    A complete training pipeline for a math-specialized model can be summarized in the following stages:

    1. Base initialization: Select a pretrained base with code and natural language capabilities to provide initialization parameters for subsequent math continued pretraining. Code capability is especially important because math problems can be solved with the help of programmatic enumeration, symbolic computation, and numerical verification.
    2. Math continued pretraining: Conduct large-scale continued pretraining on a mixture of math-related tokens, natural language, and code so that the model adapts to mathematical expression, proof structure, and programmatic solving patterns.
    3. Instruction tuning: Construct instruction data for step-by-step reasoning, answer extraction, format normalization, and error correction, so the model learns to output verifiable solution processes.
    4. Reinforcement learning alignment: Use methods such as relative policy optimization to further optimize model behavior with reward signals such as answer correctness, step consistency, and tool-call effectiveness.
    5. Tool integration and formal proof: Enable the model to generate programs, call symbolic computation or proof-checking tools, and explain and backfill tool results.
    6. Layered evaluation and regression: Systematically evaluate under settings such as no tools, tool augmentation, few-shot chain-of-thought, voting, and non-voting to prevent evaluation leakage and overfitting.

    The core idea of this path is: first feed mathematical knowledge into the model, then align its problem-solving behavior, and finally connect external tools. All three are indispensable.

    3. Data Engineering: Four Iterations to Build High-Quality Math Corpora

    The upper bound of a math-specialized model is largely determined by data quality. Public practice usually adopts an iterative approach of “seed corpus—classifier retrieval—statistical analysis—human annotation—seed expansion,” cycling through multiple rounds to improve coverage and purity. A reusable four-round iterative process is as follows:

    • Round 1: Seed training. Train a lightweight text classifier on an initial set of math web page seeds so that it can distinguish math-related pages from general pages.
    • Round 2: Large-scale retrieval. Score and filter a deduplicated large-scale public web corpus to recall potential math pages.
    • Round 3: Domain statistics. Perform statistical analysis on recalled results to identify high-frequency math subdomains, page structures, and link patterns, and to discover missed domains.
    • Round 4: Human annotation and seed expansion. Manually annotate high-value links, add linked but uncollected pages to the seed library, retrain the classifier, and repeat retrieval.

    After multiple iterations, it is possible to obtain a candidate corpus at the scale of millions of math web pages and hundreds of billions of tokens. However, “more” does not equal “better,” so quality governance is also required:

    • Deduplication: Document-level, paragraph-level, and near-duplicate deduplication to prevent the model from memorizing repeated expressions.
    • Quality filtering: Filter low-quality pages such as advertisements, navigation, garbled text, missing formulas, and answer piles.
    • Formula normalization: Unify mathematical symbols, formula delimiters, and layout structures to reduce training noise.
    • Domain ratios: Balance subdomains such as algebra, geometry, number theory, combinatorics, calculus, and probability and statistics to avoid skewed coverage.
    • Contamination control: Perform near matching and decontamination against evaluation sets to prevent training corpora from leaking answers.
    • Licensing and compliance: Record data sources and license information, and establish traceable data versions.

    An illustrative pseudocode for data construction is as follows:

    1. def build_math_corpus(seed_links, web_snapshot, rounds=4):
    2. seeds = seed_links
    3. corpus = []
    4. for r in range(rounds):
    5. classifier = train_lightweight_classifier(seeds)
    6. candidates = deduplicate(web_snapshot)
    7. math_pages = classifier.filter(candidates, threshold=0.8)
    8. stats = statistical_profile(math_pages)
    9. new_seeds = human_annotate_high_value_links(stats)
    10. corpus.extend(quality_filter(math_pages))
    11. seeds = merge(seeds, new_seeds)
    12. return normalize_formula(corpus)

    4. Continued Pretraining: Mixed Training on Code-Capable Bases and Math Corpora

    Math-specialized models usually choose a code-capable base for initialization. The reason is that code data contains many patterns of structured reasoning, variable binding, conditional branching, and function calling, which share commonalities with mathematical derivation. Through continued pretraining, the model can gain benefits in three areas at the same time:

    • Mathematical expression adaptation: Familiarity with formulas, proofs, symbols, and mixed expressions of mathematical natural language.
    • Programmatic solving capability: Learning to transform math problems into programs, pseudocode, or executable steps.
    • General capability retention: Avoiding obvious degradation in natural language understanding, reasoning, and coding skills.

    During training, attention should be paid to data ratios and curriculum learning. In the early stage, basic math and code corpora can be increased; in the middle stage, competition problems and multi-step reasoning corpora can be added; in the later stage, high-quality proofs and tool-call traces can be added. The loss function usually remains an autoregressive language modeling objective, but special handling is needed for formulas, answers, and step boundaries. An illustrative training configuration is as follows:

    1. config = {
    2. "init_from": "code_capable_base",
    3. "corpus_mix": {"math": 0.6, "code": 0.25, "natural_language": 0.15},
    4. "sequence_length": "long_context",
    5. "dedup": true,
    6. "decontaminate_eval": true,
    7. "curriculum": ["basic_math", "competition_math", "proof_and_tool_trace"]
    8. }

    5. Instruction Tuning: Teaching the Model to Reason Step by Step

    Continued pretraining addresses “what the model knows,” while instruction tuning addresses “how the model answers.” Math instruction data should cover the following types:

    • Step-by-step solving: Output condition organization, planning, derivation, conclusion, and answer.
    • Answer extraction: Stably extract the final result from a lengthy derivation.
    • Error correction: Given incorrect steps, require the model to locate and correct them.
    • Multi-solution comparison: Compare different paths such as algebraic methods, geometric methods, and programmatic methods.
    • Tool-call explanation: Generate programs or express tool-call intent when needed.
    • Format constraints: Normalize the final answer format to reduce evaluation parsing failures.

    Few-shot chain-of-thought prompting can further elicit the reasoning ability of base models, but during instruction tuning, the emphasis should be on “verifiable steps.” High-quality instruction data is not simply a pile of long answers; instead, each step should be verifiable by subsequent steps or tools. For enterprise deployment, it is recommended to establish a quadruple data specification of “problem—steps—answer—verifier” to facilitate subsequent reinforcement learning reward calculation and evaluation regression.

    6. Reinforcement Learning: Relative Policy Optimization and Reward Design

    After instruction tuning, reinforcement learning is used to further optimize the model’s problem-solving strategy. Group relative policy optimization is a commonly used relative policy optimization method: for the same problem, a group of candidate solutions is sampled, and advantages are calculated based on relative performance within the group. This reduces dependence on an independent value network and improves training stability. The key is not the algorithm name, but the reward design.

    Rewards for math tasks usually consist of multiple parts:

    • Answer correctness: The final answer exactly matches or is equivalent to the gold answer.
    • Step consistency: Intermediate steps do not contradict the final answer, and the derivation chain is complete.
    • Tool effectiveness: Tool calls succeed, parameters are reasonable, and returned results are used correctly.
    • Format compliance: The answer can be stably parsed by the evaluator.
    • Length and cost penalty: Avoid meaningless lengthy reasoning and excessive tool calls.

    An illustrative reward function is as follows:

    1. def math_reward(response, gold, tool_trace):
    2. r_answer = equivalent_match(response.final_answer, gold)
    3. r_steps = step_consistency(response.steps)
    4. r_tool = tool_success_and_used(tool_trace)
    5. r_format = format_compliance(response)
    6. r_len = length_penalty(response)
    7. return 2.0*r_answer + 1.0*r_steps + 0.5*r_tool + 0.3*r_format - 0.1*r_len

    The reinforcement learning stage must prevent “reward hacking”: the model may obtain high scores by guessing answer formats, stuffing keywords, or abusing tools. It is recommended to introduce adversarial evaluation, manual spot checks, tool log audits, and multi-reward weighting, while retaining two evaluation lines: no-tool and tool-augmented.

    7. Tool Integration: Programmatic Solving and Formal Proof

    An important advantage of math-specialized models is tool integration. The model can generate programs for enumeration, numerical verification, and symbolic simplification, and can also translate natural language theorems into formal proof targets and then call proof checkers for verification. From an engineering perspective, a clear call flow should be designed:

    1. Parse the problem and determine whether tools are needed.
    2. Generate a solving plan and tool-call parameters.
    3. Execute programs or proof checks in a secure sandbox.
    4. Read tool return results and determine whether they succeeded.
    5. Backfill results into natural language reasoning to form an explainable answer.
    6. Record tool traces for evaluation, auditing, and reinforcement learning rewards.

    Tool calls require resource quotas, timeout control, sandbox isolation, and log tracing. For enterprise-level systems, corpora and model checkpoints can be placed in object storage, container platforms can be used to orchestrate training and evaluation tasks, and logging services and monitoring alerts can track task status and anomalies. These general cloud capabilities help improve experiment reproducibility and engineering efficiency.

    8. Evaluation System: Look Beyond Final Accuracy

    Math model evaluation should be designed in layers:

    • Competition-level math reasoning benchmarks: Measure complex multi-step reasoning capability.
    • Textbook and basic problem benchmarks: Check coverage of foundational knowledge.
    • Formal proof benchmarks: Check theorem proving and proof-check pass rates.
    • Tool-augmented evaluation: Compare settings such as no tools, tools available, and tools forced.
    • Few-shot chain-of-thought evaluation: Observe prompt sensitivity.
    • Voting and non-voting evaluation: Distinguish single-pass reasoning from multi-candidate aggregation.
    • Step-level evaluation: Check correctness, readability, and consistency of intermediate steps.
    • Robustness evaluation: Perturb conditions, change numbers, and add distracting information.
    • Efficiency evaluation: Measure inference latency, number of tool calls, and cost.

    An illustrative evaluation loop is as follows:

    1. for suite in evaluation_suites:
    2. for task in suite.tasks:
    3. pred_no_tool = model.solve(task.prompt, tools=False)
    4. pred_with_tool = model.solve(task.prompt, tools=True)
    5. metrics.update(check(pred_no_tool, task.gold), setting="no_tool")
    6. metrics.update(check(pred_with_tool, task.gold), setting="with_tool")
    7. report(metrics, by_domain=True, by_difficulty=True)

    9. Engineering Deployment Recommendations and Risk Control

    When deploying math-specialized models, the following best practices are recommended:

    • Data versioning: Record corpus sources, filtering rules, deduplication strategies, and decontamination results.
    • Reproducible training: Fix random seeds, save configurations, and record checkpoints and evaluation results.
    • Evaluation regression: Automatically run layered evaluation after each training run to prevent capability regression.
    • Secure sandbox: Tool execution must be isolated, with limits on network, files, and compute resources.
    • Cost control: Set budgets for tool calls and prioritize lightweight verifiers.
    • Compliance review: Pay attention to data copyright, privacy, licensing, and commercial use terms.
    • Manual spot checks: Retain expert review for high-value scenarios to avoid blindly trusting automatic scoring.

    At the same time, be alert to evaluation leakage, data contamination, and overfitting to public benchmarks. A truly usable math reasoning system should iterate continuously on open problems, step explanations, tool integration, and failure recovery, rather than pursuing a single leaderboard number. Through the combination of data engineering, continued pretraining, instruction tuning, relative policy reinforcement learning, and tool integration, developers can build more robust, more interpretable, and more scalable math-specialized large model systems.