Data and Training Practices for Math-Specialized Language Models
Building language models for competition math and engineering computation is less about recognizing formulas and more about sustaining multi-step derivations, keeping symbols consistent, and turning problems into executable programs when needed. This article walks through a complete pipeline—continual pretraining, iterative data curation, a three-stage capability build, rigorous evaluation, and production deployment—for teams designing math-specialized models on top of an existing base model.
Building language models for competition math and engineering computation is hard not because the model needs to “recognize formulas,” but because it must reliably complete multi-step derivations, maintain symbol consistency, and, when necessary, convert a problem into an executable program. If you take a general-purpose base model and apply it directly to math, the common failure modes are familiar: steps look complete but intermediate quantities silently go wrong, or the natural language flows nicely while the final answer violates the problem’s constraints. The value of a math-specialized model lies precisely in using domain corpora, reasoning formats, and verifiable rewards to suppress this instability. This article is organized into four sections—data, training, evaluation, and deployment—and is not tied to any specific model, so you can map it onto your own base model.
Why Start from a Base Model with Strong Coding Ability
Math and code share the same class of constraints: variables must remain consistent throughout, branches must be executable, and errors tend to appear in intermediate steps rather than the final sentence. If a base model has already learned lexicon, control flow, and library usage conventions from large-scale code, continued training on math makes it easier for the model to write “setting up an equation” as a “runnable solving process.” This path is usually called continual pretraining: keep the original vocabulary and architecture (frozen or otherwise) and run long-horizon next-token prediction on the new distribution, rather than retraining from random initialization.
Continual pretraining should feed three types of text simultaneously, not just pages of formulas. First, math web pages and textbook-style exposition, providing definitions, theorems, and worked examples. Second, word problems and proof walkthroughs in natural language, so the model learns to read problems rather than only manipulate symbols. Third, code related to numerical computation and symbolic manipulation, so that “writing a program to verify” becomes an in-distribution behavior. There is no universal constant for the data mixture ratio. The principle is: the core math distribution must not be diluted by generic chit-chat, and there must be enough code that the model does not forget its tool-use habits. If the training context window is still around 4K tokens, control the length of individual samples during preprocessing—split overly long proofs into coherent, titled segments—so that truncation does not cut right through the middle of a derivation.
Compute budget should prioritize “data quality × effective tokens” rather than blindly adding epochs. Loss going down during continual pretraining does not mean problem-solving is improving; periodically run few-shot inference spot checks on a fixed problem set and look at answer accuracy, not just perplexity.
Four Iterations: How to Fish Math Pages out of the Noise
The fraction of genuinely learnable math content on the public web is very low; training on everything directly drowns the model in ads, navigation, and irrelevant encyclopedia pages. A more robust approach is a small seed and fast iterations, rather than crawling the entire web in one shot.
Round one: use a batch of manually confirmed math documents as seeds and train a lightweight text classifier. Features can be character n-grams or a bag of words; the only objective is to distinguish “looks like math” from “doesn’t look like math,” not to understand proofs. Round two: score the deduplicated public web corpus, take the top-scoring pages, and compute statistics by domain, path, and template—whichever sites and sections repeatedly produce high scores become candidate domains. Round three: have annotators verify URLs and sections rather than reading every page in detail; once confirmed, add same-structure pages from those sites that are not yet in the seed set. Round four and beyond: repeat the loop of “train classifier → recall → aggregate domains → human verification → expand seeds.” In every round, hold out a set of validation pages that never participate in classifier training, so the classifier does not simply memorize site skins.
Deduplication cannot be URL-only. Textbook reprints and mirrored problem banks cause the same proof to appear in many different HTML forms; apply paragraph hashing or similarity-based deduplication, or the model will memorize rather than generalize. During filtering, keep derivations but remove pure answer lists, unreadable formula-image alt text, and large blocks of navigation links. Final corpus acceptance is judged on three things: topic purity (the share of non-math pages found in spot checks), coverage (whether algebra, geometry, probability, and number theory are all represented), and parseability (whether formulas are still garbled).
In terms of scale, the effective token count of math web pages is usually far smaller than the raw HTML. Teams should track “page count, tokens after cleaning, deduplication rate, classifier precision/recall”—these process metrics are more useful than a headline total. Do not put unverified absolute performance numbers into internal conclusions; only compare before-and-after results using the same problem set and the same decoding method.
Three Capability Stages: Base, Instruction, Verifiable Reinforcement
Specialization generally happens in three layers with different objectives—they cannot be collapsed into a single training run.
Base continual pretraining optimizes only next-token prediction, making the model fluent in mathematical prose and code-based solving. At this stage, evaluate with few-shot chain-of-thought prompting: include a few complete derivations in the prompt, then let the model solve new problems. Few-shot examples align the output format; they do not mean the model has “learned” those example problems. When comparing runs, fix the problem set split, temperature, maximum generation length, and whether retries are allowed—otherwise absolute scores are meaningless. Public competition-style multiple-choice and numeric-answer problems are suitable for automatic grading; open-ended proofs can only be spot-checked or verified with formal checkers—exact string matching must not be passed off as correctness.
Instruction tuning turns the “solving process” into a stable format: read the problem, define unknowns, derive step by step, state the final answer, and explicitly call out assumptions when uncertain. The data should come from verifiable solutions, not from model-generated outputs recycled back without filtering—recycling tends to amplify early errors. Instruction data should ideally include both pure reasoning problems and “write a program to verify” problems, so both strategies receive supervision.
The reinforcement learning stage requires rewards that can be automatically adjudicated—and math suits this better than open-ended dialogue: whether the final number or choice is correct, whether a program run produces the expected output, whether a formal proof passes the checker. One practical relative-optimization approach is to sample a group of different solutions for the same problem and use within-group relative quality to estimate advantage, rather than relying on a huge separately trained reward model. This way the reward mostly comes from verifiers, reducing cases of “eloquent but arithmetically wrong yet still high-scoring.” Constrain how far the policy can drift during updates, and keep a share of correct trajectories for supervised replay, so the model does not learn to exploit grading loopholes for reward hacking—for example, outputting a literal match to the reference answer with empty reasoning.
Tool use is not a bolt-on slogan. When a problem involves large integers, systems of equations, or numerical integration, having the model generate a short program, running it in a sandboxed execution environment, and writing the result back into the solution is usually more stable than pure mental arithmetic. The execution environment must enforce time limits, memory limits, and no network access, exposing only a whitelist of computational capabilities. Report evaluation numbers separately: accuracy without tools, accuracy with tools allowed, and tool-call success rate. Blending these into a single composite score makes it impossible to tell whether reasoning improved or the executor is doing the heavy lifting.
How to Evaluate Without Fooling Yourself
Use at least four rulers. First, competition-style closed-form problems, automatically graded on the final answer, reported both with and without tools. Second, step-by-step reasoning quality, checked manually or with rules for skipped steps and silently swapped symbols. Third, code-solving problems: does the program run and produce a consistent answer? Fourth, general-capability regression: reading comprehension, general reasoning, and basic coding must not collapse noticeably after math continual pretraining, or the specialized model cannot be dropped into a real assistant.
When comparing against “a bigger general model,” compare only under the same prompting protocol, and state parameter scale, whether voting was used, and whether multiple samples were taken for self-consistency. Voting and self-consistency inflate scores but do not count as single-pass reasoning ability. Formal theorem proving needs its own benchmark set—high scores on natural-language proofs do not extrapolate to machine-checkable proofs.
Common biases include: test problems leaking into the pretraining web corpus, using only problem types the model is good at, running greedy decoding while claiming sampling, and counting formatting credit for computation errors. Spot checks should preserve raw generations for later review.
Production Deployment and Usage Boundaries
On the serving side, inference is most stable when sequence length matches training; if you need longer proofs, confirm that positional-encoding extrapolation has actually been validated—do not assume a longer window preserves accuracy. Decode at low temperature, and, when necessary, sample a few candidates per problem and filter them with a verifier, rather than hand-picking the “best-looking” one and writing it into a report.
Store data and checkpoints in object storage, schedule training jobs on a container platform, pipe logs and metrics into monitoring and alerting, and make failed steps, data shards, and validation curves traceable. If you use such general-purpose capabilities on Baidu AI Cloud, treat them only as compute and storage infrastructure—model quality is still defined by the corpus, objectives, and evaluation, not guaranteed by the cloud platform’s name.
On permissions: math problem banks may contain copyrighted material, so confirm the permitted scope of use before continual pretraining. When offering solving capabilities externally, state that results require review—especially in engineering computation and exam scenarios. Do not treat unreproduced third-party scores as your own acceptance bar.
An illustrative interface keeps only the task structure, without binding to any library’s proprietary API:
Input: problem text + output format convention (steps and final answer listed separately)Optional: allow generating a restricted program; after execution, only stdout is returnedOutput: step-by-step derivation + final answer + whether tools were usedScoring: answer match / program exit code / formal check pass or fail
The deployment checklist can be condensed into five items: hold out a validation set for seeds and classifiers every round; record deduplication rate and spot-check purity after cleaning; monitor a small fixed evaluation set during continual pretraining by answer accuracy, not just loss; make instruction data verifiable and take RL rewards from verifiers; after launch, monitor tool-free accuracy, tool success rate, and general-capability regression together. Following this order is how a specialized math model goes from “having seen more formulas” to “making fewer arithmetic mistakes.”
