How LLMs learn to reason and do mathematics
From predicting tokens to solving problems: examples, feedback, verification and computation at inference time.
Learning goals: distinguish training from inference; explain demonstrations and rewards; assess a mathematical answer and its verification.
What does “learning to reason” mean?
Several ingredients, with different roles
A language model can learn useful mathematical procedures because its training data contain relationships, worked examples, algorithms and proofs. Later training can make successful problem-solving behaviour more likely. At answer time, it can also spend computation on intermediate steps, alternative attempts and tools.
These are different operations: training changes the model’s parameters; ordinary inference uses fixed parameters. Writing a longer answer does not by itself train the model. Here, reasoning means the observable ability to combine steps to solve new problems; this definition makes no claim about consciousness or human-like understanding.
A practical map
- Pretraining: predict tokens in large collections of text, code and mathematical material.
- Supervised fine-tuning (SFT): imitate selected problem–solution demonstrations.
- Reinforcement learning (RL): generate attempts, score them and update the model toward better outcomes.
- Inference: use the trained model, possibly with multiple attempts, a verifier or external tools.
This is a useful teaching map, not a mandatory recipe shared by every model. Stages can be repeated, mixed or omitted. More mathematical data and more inference computation are also separate choices.
The question to keep asking
For every method below, ask: What is the training signal? Do the parameters change? Who checks correctness? Prerequisites: conditional probability, cross-entropy and the gradient update from Neural networks with Keras. The reward discussion connects to Reinforcement learning I.
First, learn to predict mathematical text
Tokens, context and a loss
A tokenizer turns text into tokens: words, word pieces, symbols or digit groups. The number 2026 need not be a single token. A causal language model with parameters $\theta$ predicts a distribution over the next token given the previous ones:
\[p_\theta(x_1,\ldots,x_T)=\prod_{t=1}^{T}p_\theta(x_t\mid x_{<t}).\]For a training collection $\mathcal D$, a standard objective is the negative log-likelihood:
\[\mathcal L_{\rm pre}(\theta)=-\sum_{x\in\mathcal D}\sum_t\log p_\theta(x_t\mid x_{<t}),\qquad \theta\leftarrow\theta-\eta\nabla_\theta\mathcal L_{\rm pre}.\]The target token comes from the text itself: this is self-supervision. Backpropagation adjusts the parameters. Predicting a derivation can reward representations of dependencies such as which variable is being isolated. The objective still measures prediction error, not the truth of a theorem.
What the Transformer contributes
Attention lets a token representation combine information from earlier positions; feed-forward layers transform those representations. Repeated layers provide a flexible computation over the context. A causal mask prevents access to future tokens during next-token prediction. The architecture supplies capacity, while data and optimization shape what is learned. Attention weights are not a proof of logical validity. See Vaswani et al., Attention Is All You Need (2017).
Why mathematical data matter
Training on technical material exposes models to notation, worked derivations and code more often than a purely conversational corpus would. Minerva is a documented example of further training a general language model on technical content. This improves mathematical performance in the reported experiments; it does not turn every generated derivation into a correct one. See Lewkowycz et al., Minerva (2022).
Predicting a useful continuation
Consider the prefix “$3x+5=20$. Subtract 5 from both sides: $3x=$”. A training example continues with 15. Learning this pattern can support generalization to other coefficients, but memorizing familiar examples can also improve a training score. To distinguish them, test unseen problems and changed numerical values.
A small token loss does not certify arithmetic: a plausible continuation can be wrong, and a confidently written sentence can contain an invalid operation.
Show solutions, then learn from them
Supervised fine-tuning on worked examples
A demonstration pairs a question $q$ with a selected answer $y=(y_1,\ldots,y_T)$, possibly including a derivation. A common SFT objective applies the loss to answer tokens:
\[\mathcal L_{\rm SFT}(\theta)=-\sum_{(q,y)\in\mathcal D_{\rm SFT}}\sum_t\log p_\theta(y_t\mid q,y_{<t}).\]The model is trained to reproduce useful explanations and solution patterns. Demonstrations can be human-written or generated and filtered. Their quality matters: imitation also learns mistakes that survive filtering. Instruction tuning and human preference feedback are described in Ouyang et al. (2022); helpfulness preferences are not the same as a mathematical correctness checker.
A complete demonstration
Question: solve $3x+5=20$ over the real numbers.
- Subtract 5 from both sides: $3x=15$.
- Divide by the nonzero number 3: $x=5$.
- Substitute into the original equation: $3\cdot5+5=20$.
This example teaches a decomposition and a check. A varied dataset must also include negative coefficients, fractions, no-solution cases and infinitely many solutions. Repeating one template is insufficient evidence of general reasoning.
Distillation: learn from a stronger model
A stronger model can generate candidate solutions; selected outputs become supervised examples for a smaller model. This is one form of distillation. The student learns from produced text, without copying the teacher’s full architecture. Filtering only the final answer can leave incorrect intermediate steps in the data.
The original DeepSeek-R1 report (2025) includes smaller models fine-tuned on generated examples. Such an experiment does not imply that a smaller model inherits every capability of its teacher.
Use intermediate steps at answer time
Chain-of-thought prompting is not a parameter update
A prompt can include examples with intermediate steps, encouraging the model to generate a similar decomposition for a new question. Wei et al. reported improvements on arithmetic, symbolic and commonsense tasks with this method. In this setting, parameters stay fixed: the prompt changes the context, not the weights. See Chain-of-Thought Prompting (2022).
Intermediate tokens give subsequent predictions additional context and computation. They may preserve a subresult that a direct answer would have to produce in one go. They can also introduce errors. A visible explanation is something to check, not a guaranteed account of all the internal computation.
An original arithmetic example
Compute $17\times24$. One decomposition is
\[17\times24=17\times(20+4)=340+68=408.\]An independent decomposition gives $24\times(10+7)=240+168=408$. Both are valid because multiplication distributes over addition. The intermediate expressions make an arithmetic mistake easier to locate. Merely saying “I have checked” supplies no evidence unless the check itself is valid.
More attempts and self-consistency
Self-consistency samples several solution paths and selects the most frequent final answer after suitable answer normalization. This is an inference strategy; it does not update parameters. See Wang et al. (2022).
If independent attempts each succeed with probability $p$, the probability of at least one success in $k$ attempts is
\[1-(1-p)^k.\]For $p=0.4$ and $k=5$, it is $0.92224$. This is not the probability that majority voting returns the right answer. An oracle could recognize the successful attempt, but a real selector can fail. Common systematic errors and repeated deterministic outputs also invalidate the independence assumption. Extra computation can help; a longer response alone is no guarantee.
Reward successful mathematical attempts
From a score to a parameter update
Let $q$ be a problem and $y$ a sampled full answer. An idealized objective is
\[J(\theta)=\mathbb E_{q}\mathbb E_{y\sim p_\theta(\cdot\mid q)}[r(q,y)].\]When the verifier’s reward $r$ has no direct dependence on $\theta$, the score-function identity gives
\[\nabla_\theta J=\mathbb E[(r(q,y)-b(q))\nabla_\theta\log p_\theta(y\mid q)].\]The baseline $b(q)$ can reduce variance without changing this expectation. A sample with reward above the baseline pushes toward increasing its log-probability. The gradient passes through the log-probability, not through the correctness checker. Practical training adds stabilization, constraints and other details; this equation is not a complete production RL algorithm.
Which score should the model optimize?
Outcome supervision scores the final result, for example by comparing a normalized answer with a reference. Process supervision evaluates intermediate steps. A correct final result can accompany invalid reasoning, so these signals are not interchangeable. Lightman et al. studied step-level supervision and found gains over outcome supervision in their MATH experiments; this is not a universal theorem about all models. See Let’s Verify Step by Step (2023).
A human preference model estimates what assessors prefer; a rule-based reward can check a numeric answer, unit test or formal proof. Each rewards what it actually measures. If a checker accepts a misleading format or an incomplete answer, optimizing its score can reinforce that failure.
Laboratory: the reward changes what is learned
Solve $x^2=4$ over the real numbers. This small model chooses among three fixed candidate responses. It is an exact categorical-policy demonstration, not a running LLM.
- A: “$x=2$.” This gives a root but omits $-2$.
- B: “$x\in\{-2,2\}$ because $(x-2)(x+2)=0$.” This is complete.
- C: “$x\in\{-4,4\}$.” This is wrong.
A weak checker accepts any listed numbers that satisfy the equation and forgets to check completeness. Its rewards are $(1,1,0)$. A complete-answer checker uses $(0,1,0)$.
| Response | Probability | Reward |
|---|---|---|
| A · incomplete | 33.33% | 0 |
| B · complete | 33.33% | 1 |
| C · wrong | 33.33% | 0 |
Step 0. Expected reward: 0.3333. Probability of a complete correct answer: 33.33%.
For logits $z_i$, use $p_i=e^{z_i}/\sum_j e^{z_j}$ and $J=\sum_i p_i r_i$. The exact gradient is $\partial J/\partial z_i=p_i(r_i-J)$. Each click applies $z_i\leftarrow z_i+0.5p_i(r_i-J)$ simultaneously. Changing the checker resets the experiment. A real LLM samples token sequences and shares parameters across many questions; it does not store just three response probabilities.
A documented case, not a universal recipe
DeepSeek-R1-Zero applied reinforcement learning directly to an already pretrained base model, without preliminary supervised fine-tuning. “Zero” does not mean learning from no data. The report describes increased reasoning behaviour alongside readability and language-mixing problems. DeepSeek-R1 instead used a multistage pipeline including cold-start examples and RL. See the original DeepSeek-R1 report (2025).
Separate proposing a solution from checking it
Code and symbolic computation
A model can translate a problem into a program and delegate arithmetic to an interpreter. PAL demonstrates this division between language-based decomposition and program execution. See Gao et al., Program-aided Language Models (2022).
A correct computation is only as useful as its model of the problem. If the generated program uses the wrong equation, the interpreter will faithfully solve the wrong task. Units, domains, assumptions and the correspondence to the original statement still require checking.
A numerical check is not a proof
Suppose an answer claims $\sqrt{x^2}=x$ for all real $x$. Testing $x=2$ passes. Testing $x=-2$ refutes it: the left side is 2 and the right side is $-2$. The correct identity is $\sqrt{x^2}=|x|$.
A numerical test can reveal a counterexample; finitely many successful tests do not prove a universal statement over the real numbers. A symbolic derivation must preserve the domain. A formal proof assistant can check a proof against an explicitly encoded statement and axioms, but a mistranslated statement may certify a different problem.
Why checking only the answer is weaker
For $x^2=4$, substituting $x=2$ verifies a candidate solution. It does not show that there are no other solutions. Factorization gives the completeness argument:
\[x^2-4=(x-2)(x+2)=0\iff x=2\ \text{or}\ x=-2.\]Distinguish a valid candidate, a complete solution set and a proof of completeness. The verifier in the previous laboratory intentionally separates the first two.
Measure what the model has really learned
A useful evaluation protocol
- Hold out problems: remove exact and near duplicates across training and test sets; include newly written variants and different problem families.
- Fix the resources: state the prompt, sampling settings, token budget, number of attempts and allowed tools.
- State the metric: one-attempt accuracy, success among several attempts, or correctness after selection measure different things.
- Audit reasoning: check assumptions and intermediate arguments on a sample, in addition to final answers.
- Inspect failures: change numbers, domains and wording; look for omitted cases and unsupported claims.
The MATH dataset (Hendrycks et al., 2021) provides competition problems with worked solutions. A high score on one dataset does not establish reliable general theorem proving. Benchmark contamination can make apparent generalization difficult to interpret.
A score must include the selection rule
Imagine a model produces five attempts per question. Reporting “one attempt was right” assumes access to the correct answer to judge success. An end user who receives one selected answer needs the accuracy of the actual selection procedure. Compare methods at the same computation budget and distinguish these outcomes explicitly.
For a scientific or engineering calculation, ask for the assumptions, derivation, units and a reproducible check. A fluent style, an emphatic confidence claim or agreement among correlated attempts does not replace those checks.
Check your understanding and follow the evidence
5 · Programming: learn a reusable algebraic procedure
Implement a tiny solver for $ax+b=c$. It chooses among three procedures: $(c-b)/a$, $(c+b)/a$, and $c-b/a$. Only the first is valid in general. Starting with equal probabilities, sample a procedure, substitute its answer into the original equation, and reward a correct result.
The trainable parameters are three logits. With sampled method $k$ and reward $r$, apply $z_i\leftarrow z_i+0.05r(\mathbf{1}_{i=k}-p_i)$. This is a sampled REINFORCE update. The procedures are supplied by us: the model learns to select a useful procedure across problems. It does not invent algebra or train a Transformer. This restriction makes the learning signal visible.
- Copy the program into a Python file; it needs only the standard library.
- Complete the reward by substituting the proposed answer into the original equation.
- Complete the simultaneous logit update, using the probabilities before the update.
- Compare zero training steps with 3000 steps. Try seeds 7, 8 and 9.
- Evaluate the new equation with coefficients outside the training ranges. Explain why selecting a general procedure can transfer.
- Replace the reward with a constant 1. Does training reliably identify the correct procedure? Explain the missing feedback.
"""Tiny trainable solver: learn which algebraic procedure earns a reward."""import mathimport randomdef probabilities(logits): m = max(logits) weights = [math.exp(x - m) for x in logits] return [x / sum(weights) for x in weights]def solve(a, b, c, method): # Three competing procedures for a*x + b = c (a is nonzero). return [(c - b) / a, (c + b) / a, c - b / a][method]def train(steps=3000, seed=7): rng = random.Random(seed) logits = [0.0, 0.0, 0.0] for _ in range(steps): a = rng.choice([2, 3, 4, 5]) b = rng.choice([1, 2, 3, 4]) target = rng.randint(-5, 5) c = a * target + b p = probabilities(logits) method = rng.choices(range(3), weights=p)[0] answer = solve(a, b, c, method) reward = ... # Check the original equation # REINFORCE: gradient of log p(method) is one_hot(method) - p. logits = [... # Update logit i using the policy gradient for i, z in enumerate(logits)] return probabilities(logits)if __name__ == '__main__': p = train() print('Probabilities after training:', [round(x, 4) for x in p]) method = max(range(3), key=lambda i: p[i]) # New coefficients outside the training ranges. print('Held-out equation: 7*x + 9 = 58') print('Selected procedure gives x =', solve(7, 9, 58, method)) print('Check:', 7 * solve(7, 9, 58, method) + 9)
Show the explanation
"""Tiny trainable solver: learn which algebraic procedure earns a reward."""import mathimport randomdef probabilities(logits): m = max(logits) weights = [math.exp(x - m) for x in logits] return [x / sum(weights) for x in weights]def solve(a, b, c, method): # Three competing procedures for a*x + b = c (a is nonzero). return [(c - b) / a, (c + b) / a, c - b / a][method]def train(steps=3000, seed=7): rng = random.Random(seed) logits = [0.0, 0.0, 0.0] for _ in range(steps): a = rng.choice([2, 3, 4, 5]) b = rng.choice([1, 2, 3, 4]) target = rng.randint(-5, 5) c = a * target + b p = probabilities(logits) method = rng.choices(range(3), weights=p)[0] answer = solve(a, b, c, method) reward = float(abs(a * answer + b - c) < 1e-9) # REINFORCE: gradient of log p(method) is one_hot(method) - p. logits = [z + 0.05 * reward * (float(i == method) - p[i]) for i, z in enumerate(logits)] return probabilities(logits)if __name__ == '__main__': p = train() print('Probabilities after training:', [round(x, 4) for x in p]) method = max(range(3), key=lambda i: p[i]) # New coefficients outside the training ranges. print('Held-out equation: 7*x + 9 = 58') print('Selected procedure gives x =', solve(7, 9, 58, method)) print('Check:', 7 * solve(7, 9, 58, method) + 9)
With seed 7 and 3000 steps, the probabilities rounded to four decimals are [0.9953, 0.0023, 0.0024]. The selected procedure gives x = 7 for 7*x + 9 = 58; substitution gives 58. Learning changes the logits during training. Solving the held-out equation uses fixed logits. High selection probability is not a guarantee of correctness, and one held-out problem is not a general evaluation.
1 · Training or inference?
Classify these operations: (a) put two worked examples in a prompt; (b) backpropagate a loss on worked solutions; (c) sample ten answers and take a majority vote; (d) update parameters after scoring generated answers.
Show the explanation
(a) Inference: context changes. (b) Supervised training: parameters change. (c) Inference: more sampling and selection. (d) Reinforcement learning: the reward influences parameter updates.
2 · Compute one policy update
Use the complete checker from the laboratory. Start with $z=(0,0,0)$, $p=(1/3,1/3,1/3)$ and $r=(0,1,0)$. Compute $J$, its gradient and the next logits for step size $0.5$.
Show the explanation
$J=1/3$, so $\nabla_z J=(-1/9,2/9,-1/9)$. The next logits are $(-1/18,1/9,-1/18)$. After softmax, B has probability $e^{1/6}/(2+e^{1/6})\approx0.3713$; A and C each have probability about $0.3143$. These are probabilities, not a guarantee that the next sample is correct.
3 · Detect a lost solution
A model solves $x^2=x$ by dividing by $x$ and concludes $x=1$. Identify the invalid step and give a complete solution.
Show the explanation
Division by $x$ assumes $x\ne0$ and loses the solution $x=0$. Instead, $x^2-x=x(x-1)=0$, so $x\in\{0,1\}$. Substitute both values. A final-answer checker must account for the full solution set.
4 · Explain the weak verifier
In the laboratory, train 20 steps with each checker from the same initial state. Why can expected reward improve while incomplete answers remain probable?
Show the explanation
The weak checker gives the same reward to A and B. Symmetry keeps their probabilities equal; training suppresses C but has no signal to prefer B over A. The complete checker distinguishes them. Optimizing a reward only encourages the properties that reward detects.
Historical landmarks and primary sources
These references document different ingredients, rather than a single linear invention or the undisclosed recipe of every commercial model.
- 2017 · Vaswani et al. — Attention Is All You Need: Transformer architecture.
- 2021 · Hendrycks et al. — MATH: evaluation problems and worked solutions.
- 2022 · Ouyang et al. — Instruction following with human feedback: demonstrations and preferences.
- 2022 · Wei et al. — Chain-of-Thought Prompting: intermediate steps in prompts.
- 2022 · Lewkowycz et al. — Minerva: training on technical material.
- 2022 · Wang et al. — Self-Consistency: sampling and answer aggregation.
- 2022 · Gao et al. — PAL: execution of generated programs.
- 2023 · Lightman et al. — Let’s Verify Step by Step: process supervision.
- 2025 · DeepSeek-AI — DeepSeek-R1, original report: reinforcement learning and distillation.

