Math-Specialized LLMs: Continued Pretraining and Data Engineering in Practice

    Building a math-specialized large language model requires more than increasing parameter count. This article examines continued pretraining on a code-capable base model, iterative mathematical corpus construction, consistent evaluation, and the roles of Base, Instruct, and RL variants. It also covers inference requirements, tool isolation, cloud infrastructure, and a practical deployment checklist.

    1. Why General-Purpose Models Can Explain Math but Struggle to Calculate

    Weak mathematical performance in general-purpose large language models is not simply a matter of insufficient parameters. A major issue is a mismatch in training data. Mathematical content accounts for only a small fraction of web text, and much of it consists of fragmented exercises and answers without a complete chain of assumptions, derivation, and conclusions.

    As a result, models may reproduce formulas while struggling with multistep reasoning. This weakness becomes particularly pronounced on competition-level problems.

    A common approach is therefore not to train a model from scratch, but to apply continued pretraining to a base model that already has coding and logical reasoning capabilities. Mathematical data is introduced at a high proportion while general language capabilities are retained.

    Public technical reports describe an effective route: initialize from a code-capable model with approximately 7 billion parameters and continue training on roughly 500 billion tokens of mixed data. Mathematical tokens are retrieved selectively from public web corpora and mixed with natural language and code. The resulting model achieves approximately 51.7% accuracy on a competition-level mathematics benchmark without external tools or voting across multiple sampled answers.

    The engineering takeaway is clear: data engineering can be the main source of gains in mathematical capability, rather than changes to model architecture.

    2. Key Decisions in Continued Pretraining

    2.1 Choosing the Base Model

    A code-capable base model provides a useful starting point for formal symbolic manipulation. Models trained on code tend to be more sensitive to variables, scope, and loop invariants. These structural capabilities can help maintain consistency across mathematical derivations.

    Tokenizer suitability also matters. The tokenizer should provide reasonable coverage of mathematical notation, including subscripts, superscripts, Greek letters, and operators. Poor coverage increases token consumption and effectively reduces the amount of useful information that fits within the context window.

    2.2 Corpus Size, Mixture, and Context Length

    • Scale: The reported approach uses approximately 500B training tokens. The aim is to provide sufficient coverage of competition-level problem types without overemphasizing specialized data at the expense of general capabilities.
    • Mixture: Mathematical, natural-language, and code data serve different purposes. Natural language helps preserve general comprehension and expression, while code reinforces executable reasoning.
    • Context length: A 4,096-token context is a practical choice for many extended competition-level derivations while keeping GPU memory requirements and throughput costs manageable.

    These choices should be validated together. Training scale alone does not establish whether a model has sufficient mathematical coverage or whether its general capabilities have been preserved.

    2.3 Checking for Catastrophic Forgetting

    Continued pretraining requires dual-track evaluation:

    1. Measure improvements on mathematical benchmarks.
    2. Check for regressions in general comprehension, reasoning, and coding.

    Public reports indicate that the described approach retains general capabilities broadly comparable to those of the coding base model, suggesting that its data mixture is effective.

    For an engineering implementation, a useful practice is to create a dual-track evaluation snapshot every 50B tokens. If general capabilities decline substantially, revert the mixture adjustment rather than continuing unchanged.

    3. Data Engineering: Four Rounds of Bootstrapped Corpus Construction

    The most reusable part of the pipeline is its iterative data construction process. The core idea is to feed retrieved mathematical content back into the seed corpus, creating a bootstrapping loop.

    The reported final corpus contains approximately 35.5 million mathematical web pages, totaling around 120 billion tokens.

    The four-round process works as follows:

    1. Prepare a seed set. Start with a public corpus of mathematical web pages.
    2. Train a lightweight retrieval model. Use the seed set to train a linear text classifier or ranker. Bag-of-words n-gram features and a linear classifier provide a low-cost starting point.
    3. Retrieve at scale. Score a deduplicated public web corpus and retrieve high-confidence mathematical pages.
    4. Expand domain coverage. Analyze retrieved content to identify underrepresented related areas, such as applied physics problems or competition-focused sections.
    5. Add human labels and expand through links. Manually label a set of relevant URLs, then add previously uncrawled linked pages to the seed collection.
    6. Repeat steps 2–5 for four rounds. Improve coverage and corpus purity with each iteration.

    Illustrative pseudocode:

    1. seed = load_public_math_corpus()
    2. for round_idx in range(4):
    3. ranker = train_linear_ranker(seed) # Lightweight; supports incremental training
    4. candidates = dedup(public_web_corpus) # Deduplicate and filter for quality first
    5. recalled = ranker.recall(candidates, topk=35_000_000)
    6. new_domains = analyze_domain_shift(recalled) # Identify potentially relevant domains
    7. labeled = human_label(recalled.sample(5_000)) # Estimate precision through manual review
    8. seed = seed + recalled.filter(labeled.precision > 0.9)
    9. seed = seed + frontier_links(labeled) # Expand links to address coverage gaps

    This is a schematic workflow, not an executable implementation. Its main engineering principles are:

    • Prioritize precision over recall. Noise introduced into the seed set can be amplified by subsequent rounds. Use manual sampling and acceptance thresholds in every iteration.
    • Deduplicate before retrieval. Otherwise, high-scoring template pages can consume the retrieval budget.
    • Keep snapshots of every round. They make it possible to trace when a particular problem category entered the corpus.

    4. Evaluation: Making Mathematical Capability Comparable

    Benchmark results are meaningful only when evaluation conditions are consistent. Fix and report the following variables:

    • Benchmark: Use a competition-level mathematics dataset with English-language problem statements and answers that can be checked unambiguously.
    • Prompting: Use few-shot chain-of-thought prompting with a fixed number and ordering of examples.
    • Decoding: Fix temperature and sample count, and state whether the result is pass@1 or majority voting.
    • Tool access: Distinguish text-only reasoning from runs that can execute code or use formal proof tools.

    Public reports describe a base model that outperforms comparable open-source base models by more than 10 percentage points under few-shot chain-of-thought evaluation. It also exceeds the performance of general-purpose models with tens of billions of parameters. The instruction-tuned variant provides consistent step-by-step reasoning, while the reinforcement-learning variant approaches 60% accuracy when tool assistance is permitted.

    These results should not be collapsed into a single comparison. The approximately 51.7% result described earlier excludes external tools and multiple-sample voting; tool-assisted results belong to a separate evaluation setting.

    Explicit disclosure of tool use and voting is essential. Otherwise, apparently higher scores may reflect differences in the evaluation setup rather than improvements in the model itself.

    5. Three Model Variants: Base, Instruct, and RL

    Variant Training approach Typical use cases
    Base Continued pretraining Further model development, domain fine-tuning, and evaluation baselines
    Instruct Instruction fine-tuning Direct conversation, problem-solving assistance, and step-by-step explanations
    RL Reinforcement learning using approaches such as Group Relative Policy Optimization (GRPO) Maximizing accuracy, potentially combined with tool execution

    Group Relative Policy Optimization uses a group of sampled answers to the same problem and estimates advantages from their relative scores. A key advantage of the described approach is that it does not require a separate reward model, reducing the cost of optimization.

    In practice, sampling-group size and temperature directly affect training stability and require careful tuning.

    Tool integration provides another route to improvement. A model can express complex calculations as programs and delegate execution to an interpreter, reducing arithmetic and symbolic manipulation errors.

    Formal theorem proving takes a different approach: it turns natural-language reasoning into a search over machine-checkable proof states. This requires an additional proof environment.

    6. Deployment and Operational Engineering

    For a 7B-parameter model in bf16, the weights alone require approximately 14 GB of GPU memory. After accounting for the KV cache and activations, a single 24 GB GPU can support small-batch inference with a 4,096-token context, depending on runtime overhead.

    For higher throughput, consider multi-GPU tensor parallelism or int8/int4 quantization, with an allowance for possible accuracy loss.

    The following inference example is pseudocode; actual interfaces depend on the framework:

    1. # Pseudocode: load a base model for text completion
    2. model = load_causal_lm("your-org/math-model-7b-base", dtype="bfloat16", device_map="auto")
    3. tok = load_tokenizer("your-org/math-model-7b-base")
    4. prompt = "Given f(x)=x^2, find its definite integral over [0,2]. Solution:"
    5. inputs = tok(prompt, return_tensors="pt").to(model.device)
    6. out = model.generate(**inputs, max_new_tokens=512, do_sample=False)
    7. print(tok.decode(out[0], skip_special_tokens=True))

    Production requirements include:

    • Constrained decoding: Mathematical answers should be parseable. Regular-expression or grammar constraints can enforce an output format suitable for automated grading.
    • Tool sandboxing: Execute generated code in isolated containers with limits on CPU usage, memory, execution time, and outbound network access.
    • Caching and batching: Use prefix caching for repeated problems and dynamic batching to improve GPU utilization.
    • Observability: Record prompt length, generated length, tool-call success rate, and answer acceptance rate in logging and monitoring systems.

    7. A Vendor-Neutral Cloud Architecture

    A cloud-hosted implementation can be assembled from standard service categories:

    • Object storage for model checkpoints and corpus snapshots.
    • Container platforms for inference services and elastic scaling.
    • Message queues to decouple offline batch evaluation jobs.
    • Logging, monitoring, and alerting for quality dashboards and operational visibility.
    • Data lake storage to support iterative corpus development.

    Cloud providers, including Baidu AI Cloud, offer services in these general categories. Teams should choose according to their existing technology stack and applicable service availability, rather than tightly coupling the system to vendor-specific interfaces.

    8. Implementation Checklist

    Before moving into production, verify that:

    1. The base tokenizer adequately covers mathematical symbols.
    2. The corpus has been deduplicated before retrieval, with manual quality checks in every iteration.
    3. General-capability regression tests are retained to detect catastrophic forgetting.
    4. Evaluation reports disclose tool use, voting, and other sources of external assistance.
    5. Inference supports structured output constraints and sandboxed tool execution.
    6. Continuous monitoring tracks problem-solving success and tool-call success rates.

    Conclusion

    The strongest engineering differentiators for math-specialized models are a reliable corpus bootstrapping loop and rigorous evaluation—not model size alone.

    Four-round corpus construction, dual-track evaluation, and properly sandboxed tools provide a practical foundation for building mathematical capability on an existing base model. Executed carefully, this approach can bring competition-level performance closer to that of much larger general-purpose models while preserving a manageable deployment footprint.