Code Pretraining for Stronger Mathematical Reasoning
Math-specialized models are not produced by simply memorizing more problems. This article explains why a code foundation followed by continued pretraining on mathematical text is often more stable than textbook text alone, then covers data mix, chain-of-thought with program assistance, instruction tuning and verifiable rewards, evaluation splits, and deployment constraints.
Math-specialized models are not created by making a general-purpose large model “memorize a few more problems.” Competition-level questions require the model to keep symbols consistent across a long chain, choose the right transformations, and finish with an answer that can be checked. A pattern that shows up repeatedly in practice is that building a solid foundation on code, then continuing pretraining on mathematical text, is often more stable than simply stacking natural-language textbooks. Code writes “steps must be executable and results must be verifiable” into the training distribution, and that inductive bias transfers to algebra, number theory, and combinatorial reasoning.
Why code becomes mathematical ability
Programs and proofs are structurally similar. Both are made of a finite set of symbols, explicit scope, and composable transformations; one wrong step sends the later state off course. Code corpora contain many loop invariants, boundary conditions, and function decompositions. From these, a model learns to break a large problem into named subprocesses instead of producing an explanation that reads smoothly but skips steps.
This transfer usually appears in three behaviors. First, symbol hygiene improves: parentheses, variable bindings, and subscripts are less likely to be renamed halfway through. Second, search is more directed: the model tends to state what is known and what is sought before choosing a transformation, rather than guessing the final number. Third, tool interfaces feel more natural: when the model is allowed to write a short computation program, it already has habits for function calls, list processing, and numeric checks, so it does not have to learn from scratch how to turn a problem into a runnable process.
Two points should be kept separate. Code ability is not mathematical ability. A model that only completes boilerplate still fails on inequality problems that require constructing auxiliary quantities. Code supplies a starting point for operational discipline and tool coordination; continued training on the math distribution is still necessary.
Continued pretraining: where the data comes from and how to mix it
Continued pretraining on a general or code base aims to shift the token distribution toward “mathematical narration + formal derivation + executable fragments,” while preserving existing language understanding and coding ability as much as possible. Data usually comes from textbook excerpts, solution discussions, and formula-dense pages on the public web, mixed with natural-language explanation and programs. Filtering should focus on form rather than brand of source: whether the content has a clear problem statement, derivation, or executable check, rather than ads, navigation, and repeated templates.
The mix should keep three strands present at the same time.
- Math-dense text covers concepts, theorem statements, and the style of worked solutions.
- Natural language translates symbolic steps into readable reasoning, so the model does not emit only formula fragments.
- Code covers process decomposition and tool-call format. If the code share is too low, later “solve it with a program” degrades into pseudocode. If it is too high, the model may use a programming voice to avoid conceptual judgments inside a proof.
The training objective remains next-token prediction. There is no need to introduce an external solver at this stage. In scale, continued pretraining needs enough token exposure to change intermediate-layer statistics over symbolic patterns, not merely to memorize surface templates. Token volume and learning rate should be judged together against validation loss and accuracy on downstream short problems. A single drop in loss is not evidence that “math has been learned.”
A practical check is capability conservation: hold out a small regression set for code completion and ordinary reading comprehension. If math metrics rise while those tasks collapse, the data mix or learning rate is too aggressive and the base has been washed out. The value of a balanced model is that the same weights can both read the problem and write a checking program.
How to use it at inference: chain-of-thought and programs together
Few-shot chain-of-thought makes hidden steps explicit. The prompt gives several complete derivations, and the model imitates the rhythm of “transform, then classify, then compute” on a new problem. For a base model, this is closer to the pretraining distribution than asking only for the final answer, so it is usually more effective on competition-style questions. Chain-of-thought quality depends on whether the prompt covers the problem types, not on how ornate the sentences are. Prompts that are too long, or examples that contradict each other, waste the decode budget on imitating format.
Program assistance is a complementary path. Numeric calculation, enumeration, modular arithmetic, and some geometric coordinate checks are often more stable in a short program than in pure text mental arithmetic. The model’s job becomes: model the problem, choose an algorithm, write a runnable fragment, read the output, and decide whether to retry. The runtime must be controlled: timeouts, memory limits, no network, and read-only dependencies, so that “can run code” does not become an unrestricted execution channel.
Do not bind the two paradigms into the same decode. For proof-style problems, derive in text first and then check key equations with a program; that is usually more interpretable than using code the whole way to “force an answer.” For counting and simulation problems, enter the program earlier. Evaluation must report separately: text-only accuracy, accuracy with tools allowed, and the number of tool calls. Otherwise it is impossible to tell whether the gain comes from reasoning or from external computation covering up a faulty argument.
A short sketch is enough. The point is the boundary, not framework decoration:
Read the problem -> decide whether exact calculation or enumeration is requiredIf yes: generate a restricted program -> run it in a sandbox -> check the output against the problem statementIf the program fails: shrink the search space or return to symbolic derivation, rather than retrying without limitOutput: final answer + key steps (steps must be auditable)
Instruction tuning and verifiable rewards
A base model is good at continuing a distribution. It is not necessarily good at obeying “answer only / step by step / use this format.” Instruction tuning uses problem–solution pairs to align outputs with instructional, stepwise reasoning. The data should cover common failure points: missed conditions, inequality direction, integer versus real ranges, and discussion of multiple solutions. Quality matters more than quantity; wrong solutions write bad steps into the preference.
Supervised learning alone can still produce wrong solutions that look complete. Math problems have an advantage: the answer can often be judged automatically—a number, a choice, or a final form a machine can check. Reinforcement learning or preference optimization can then turn verifiable correctness into a reward, instead of only imitating the wording of one reference solution.
Within-group comparison is a steady approach: sample several solutions for the same problem, score them with rules or a checker, estimate advantage from relative quality inside the group, and update the policy. Relative scores reduce reward-scale drift caused by different problem difficulties. The reward should land only on verifiable results and hard constraints (format, and whether a forbidden step was called). Do not give high weight to “the style resembles a sample essay,” or the model will trade correctness for style.
Guard against reward hacking during training: the model may emit vague answers that cannot be judged, or exploit checker holes (for example, omitting a unit and still being marked correct). Use the checker together with human spot checks. Keep policy update steps small, and retain an instruction-tuned model as a reference, so that chasing the auto-gradable subset does not damage open-ended proof problems.
Evaluation that holds up
A single total score is not enough. At least split these dimensions.
- Final-answer accuracy: under a fixed decode setting, whether the answer matches the standard answer.
- Step fidelity: spot-check whether intermediate expressions actually lead to the final answer, rather than guessing the answer and backfilling.
- Tool gain: the same model and the same sampling budget, with tools on versus off.
- Robustness: variation after changing numbers, wording, or language. A high score only on the original wording is often memorization.
- General regression: whether reading, code, and instruction following hold up.
Few-shot prompts, temperature, number of samples, and whether voting is used must all be written into the experiment record. Voting and multiple samples raise accuracy, but they must not be mixed with single-decode results in the same comparison table. The same applies to external solver packages. When stating capability externally, keep two scopes explicit: “no tools” and “with tools.” Do not present a system score as the model’s own score.
Public contest benchmarks are useful for side-by-side observation, but they cannot replace in-domain problems. If the model will be used for homework grading, item-bank generation, or internal knowledge checks, build a private set that matches the target level, allowed tools, and answer format, and rotate items regularly to reduce memorization risk.
Constraints when putting it into production
Training and inference can run on GPU clusters in a general cloud: object storage for corpora and checkpoints, a job queue for continued pretraining and alignment jobs, and logs and monitoring for loss, reward, and sandbox failure rate. If cloud resources such as Baidu AI Cloud are used, plan around general compute, storage, and observability. Do not tie results to one proprietary interface. For access control, keep training data and user problems in separate storage. Run code execution in an isolated sandbox, and do not mount production secrets.
Before launch, define refusal and fallback: when the problem is ambiguous, the checker disagrees, or the program fails repeatedly, return “cannot solve reliably” together with the parts that were verified, rather than inventing steps. In math, confident error is worse than refusal.
Keep a person in the loop. The model is suited to generating candidate solutions, locating calculation errors, and formalizing natural-language conditions. When the output is used for teaching or decisions, a teacher or reviewer should still spot-check high-risk samples. Verifiable rewards can raise final-answer hit rate; they do not automatically guarantee that every step is pedagogically correct.
Boundaries
Code strengthens process discipline and tool coordination. It is not a universal theorem machine. Formal proofs, open research, and problems that need new definitions still depend on dedicated proof environments and human insight. Wrong solutions in the data, holes in the checker, and overly strong format rewards will all pull the model off course. Design the data mix, tool-free versus tool-assisted evaluation, and verifiable rewards separately. Only then can you tell where the ability actually comes from, and make mathematical reasoning stable without sacrificing the language and coding base.
