Reasoning models: training recipe and reinforcement learning dynamics
Study reasoning-model training recipes and dynamics: cold starts, reinforcement learning, rejection sampling, distillation, difficulty-based problem selection, and switchable thinking modes. Reproduce a small R1-Zero-style Countdown training run and analyze its behavior.
After this lesson you can
- Describe the reasoning-model training recipe and the contribution of cold starts, RL, rejection sampling, and distillation.
- Explain why all-correct or all-incorrect groups provide no gradient and design difficulty filtering to preserve learning signal.
- Reproduce small-scale R1-Zero-style Countdown training using GRPO and LoRA while recording reward, length, entropy, and pass@k.
- Interpret training dynamics including length growth, entropy collapse, and self-verification, and critically assess the so-called aha moment.
- Use a hybrid model with switchable thinking and measure accuracy, token, and latency tradeoffs under different budgets.
Before you start
- 23The LLM as a stochastic text policyExact and executable verifiersSelf-Taught Reasoner (STaR)Expert iteration and rejection sampling fine-tuningCoverage under repeated samplingBest-of-N overoptimizationSuccess-rate estimation with repeated trialsBudget forcing
- 20Group Relative Policy OptimizationGRPO normalization biasesREINFORCE Leave-One-OutVerifiable rewardsReward hackingReasoning trace distillationpass@k and its unbiased estimatorLow-Rank Adaptation
- 22Policy gradient theoremPPO clipped objective
A recipe, not a magic length
A reasoning model is trained to produce intermediate steps that can consume additional compute before answering. A long chain alone is not proof of correct reasoning. To study whether compute helps, compare accuracy, length, cost, and traces using held-out problems and a verifier defined before seeing answers.
The DeepSeek-R1 recipe distinguishes two systems. R1-Zero starts from the base model and applies reinforcement with correctness and format rewards. The paper describes long chains and self-verification, but also language mixing and readability problems. R1 adds readable initial data and several later stages. Its results belong to that scale and evaluations; a local 0.5B experiment does not reproduce large-model training.
The R1 recipe first fine-tunes the base model on thousands of readable reasoning examples; applies reinforcement on verifiable tasks; generates and filters traces for another supervised fine-tuning stage with general-task data; and finishes with reinforcement for other scenarios. Distillation to smaller dense models is a later branch. Kimi k1.5 and Qwen3 describe different decisions, including long context and thinking modes. A stage’s isolated effect cannot be inferred without a comparable ablation.
GRPO refresher
In GRPO, answers with rewards are generated for the same problem. A common advantage centers by the mean and, if standard deviation is positive, divides by it. With equal rewards, all group advantages are zero and the policy-gradient term weighted by those advantages vanishes. An independent KL penalty can still contribute: “group without signal” here refers to relative reward, not necessarily the entire loss.
For example, in a group of four rewards , the mean is . Centered advantages are before dividing by a deviation. This compares each answer with others for the same problem without needing a separate value critic for that computation. The ratio between the current policy probability and that of the policy generating the sample constructs the clipped objective: if an update tries to change that ratio too far in the advantage direction, clipping limits the policy term’s contribution. By itself it does not force the whole policy within a maximum distance.
Two implementations can produce numerically different advantages from the same rewards: one may use population standard deviation and another sample standard deviation; a constant added to the denominator also changes the result. This difference matters in small groups. Match those conventions, per-answer or per-token reduction, padding mask, sampling policy, and KL term before comparing losses. The policy generating answers must be the same whose old log probability appears in the ratio; applying temperature or filters only when sampling and then using uncorrected logits breaks that correspondence.
In group , population standard deviation is and normalized advantages, without an added constant, are . With sample standard deviation, the divisor is 0.5 and advantages are . Both have zero mean but different magnitude. This example also shows why reporting only “normalization by standard deviation” is insufficient to reproduce an implementation.
For reference, RLOO subtracts from each reward the mean of the other answers: . It does not necessarily divide by group standard deviation. Constant rewards also make this advantage zero, but that property does not make RLOO and GRPO scales and full objectives identical.
A partial reward’s weight must be interpreted alongside that normalization. If only format varies within a group, multiplying all rewards by 0.1 multiplies both their differences from the mean and their standard deviation by 0.1. Without a denominator constant, resulting advantages do not change. Thus that weight limits format’s relative importance when it competes with correctness, but does not guarantee a tenfold smaller signal in a group where only format varies. With a positive constant, cancellation is no longer exact, especially for tiny variations.
To make the comparison concrete, let be the policy that generated an answer and the current policy. At position in that answer, the conditional probability ratio is
One clipped objective averages, over valid tokens, the minimum of and . If advantage is positive, pressure increases to make the answer more likely until the upper limit is reached; if negative, the minimum protects the opposite side of the update. An implementation minimizing a loss changes the objective’s sign and adds the chosen KL penalty. Clipping acts on individual samples and terms: it does not impose an exact global bound on every new-policy probability.
Per-answer averaging gives each answer equal weight after dividing by its valid tokens. Global per-token averaging gives longer answers greater weight. With answers of 10 and 100 tokens, the first scheme gives each half the weight; the second, if all tokens participate, assigns and . Both computations may be legitimate for different objectives, but comparing them without declaring reduction confuses a mathematical decision with algorithmic improvement. Padding tokens and those after end-of-sequence must be excluded from both denominators.
When a different engine generates answers, small numerical differences between its log probabilities and the trainer’s can accumulate over a long sequence. For example, a constant 0.02 log-probability difference per token over 200 tokens sums to 4; exponentiation gives a ratio of approximately 54.6. Sign and actual differences vary, so this figure is illustrative only. Importance correction can clip or mask extreme ratios, but each rule changes which samples contribute and must be logged with its statistics. It is not enough to check that both engines accept the same prompt.
If rewards are independent Bernoulli variables with success probability , a useful group contains at least one success and one failure. Its probability is
The two excluded events are all correct and all incorrect. For , and . Differentiating gives , positive before 0.5 and negative after, so the maximum for is at 0.5. If format reward accompanies correctness, or samples are dependent, the binary formula no longer describes all useful groups.
Problem selection for reinforcement seeks to maintain signal without hiding the cost of finding it. DAPO studies dynamic sampling among other training decisions. Filtering constant groups can save useless updates, but not their generations: count all discarded answers. If the model improves, the list of useful problems changes; a filter based on an old estimate may become stale.
With and , about one third of groups are mixed under the independent Bernoulli model. If ten useful groups are needed, budgeting their 80 answers is insufficient: discarded groups must also be generated, and actual cost fluctuates. Approximation gives about 29.7 generated groups in expectation if the rate stays fixed and groups are independent. In real training rates change with weights and a partial format reward introduces more than two values; this calculation is a reference, not an exact campaign prediction.
Dynamics and alternative explanations
Reasoning reinforcement dynamics are observed using semantic reward, format compliance, length, entropy, distance from a reference, and pass@k on problems distinct from training. Per-token entropy depends on where and how it is averaged; KL estimated on frozen samples is a proxy and does not automatically measure exact divergence of the whole policy. Inspect samples, not just means: format reward can grow while the answer remains wrong.
Normalization also matters. Liu and colleagues analyze biases that can favor longer incorrect answers and propose Dr. GRPO with another normalization. Their analyses find self-reflection examples in the base model and observe that those behaviors in their comparison do not positively correlate with greater accuracy. A “Wait” example after training does not prove reinforcement created the capability from scratch or reflection caused the correct answer. Cui and colleagues study entropy in reasoning training; a decline observed in one local run needs comparisons and controls before assigning a mechanism.
Hybrid thinking modes allow an answer with or without an explicit reasoning phase. In comparisons retain the same problems and verify which mode the model actually received. A token limit can truncate thought, prevent a final answer, or change the answer distribution; report those cases rather than silently counting them as incorrect. GPU time depends on concurrency, context length, and batch size.
In Cui and colleagues’ analysis, entropy change is related to covariance between action probability and logit change; in their runs covariance was mostly positive while entropy fell. They propose clipping or penalizing updates associated with high covariance. This is an explanation and intervention evaluated under their conditions, not a law diagnosing our run from one curve. Lower entropy can reduce diversity; its relationship to exploration and accuracy must be measured on the specific task.
A paired comparison takes each held-out question and generates one answer in each mode with the same verifier. Report both successes over all questions and successes among extracted answers: the second ratio can improve merely because one condition abstains more. Count input, thought, and answer tokens separately, plus elapsed time. If thought closure is forced, that is a third intervention condition, not a natural sample from short mode. Repeating seeds helps distinguish an effect from a lucky generation.
Length observations also need an explicit denominator. An answer truncated at the limit may not have reached its conclusion; excluding it from mean length or accuracy changes the compared population. Record natural ending, inserted closure, and budget exhaustion separately. An improvement seen only among extracted outputs could reflect that the shorter condition produced fewer recognizable answers. Read results across all problems together with abstention analysis.
Lab: signal and sampling cost
This toy model assigns rate to each problem. A group of eight answers is simulated with independent Bernoulli variables; if mixed, an artificial rule slightly increases the rate. This is not a neural network gradient. We compare immediate uniform updates, oracle filtering of extreme rates, and accumulation of eight useful groups. All spend 300 generated groups; accumulation updates only on completing a batch and loses the partial batch at the end. Discarded groups are also counted.
from random import Random
def simulacion(mode,seed=10,groups=300,G=8):
r=Random(seed); p=[.01+.98*i/99 for i in range(100)]
initial=sum(p)/len(p); useful=0; updates=0; pending=[]
for _ in range(groups):
eligible=[i for i,x in enumerate(p) if .05<=x<=.95] if mode=='filtrado' else list(range(len(p)))
if not eligible: break
i=r.choice(eligible)
successes=sum(r.random()<p[i] for _ in range(G))
mixed=0<successes<G
if mixed:
useful+=1
if mode=='dinamico':
pending.append(i)
if len(pending)==8:
for j in pending: p[j]+=.1*p[j]*(1-p[j])
updates+=len(pending); pending=[]
else:
p[i]+=.1*p[i]*(1-p[i]); updates+=1
return {'muestras':groups*G,'grupos_utiles':useful,'actualizaciones':updates,
'tasa_inicial':initial,'tasa_final':sum(p)/len(p),'pendientes':len(pending)}
for mode in ('uniforme','filtrado','dinamico'):
print(mode,simulacion(mode))The filter knows the true rate at every moment, which a practical system does not get for free. Mean rate in this simulation changes only due to the chosen artificial rule; it is not evidence of LLM improvement. Dynamic sampling can spend many answers gathering a useful batch when nearly all problems are too easy or too hard.
Local lab: GRPO and hybrid modes
grpo_countdown.py trains the 0.5B model on verifiable Countdown: it uses groups of eight, correctness reward plus up to 0.1 for format, and 900 steps. It requires reward_countdown.py. In this local variant, format progresses in quarters for ordered markers and receives full credit only for strict structure. Correctness is checked separately on a single expression delimited by <answer> using exact arithmetic; expressions appearing only in reasoning are not rewarded. Strict evaluation also retains the full-structure requirement. This reward choice is lab design, not a paper’s recipe.
Partial reward can provide signal before any well-formed answer appears, but the model might learn tags without solving the problem. Record partial format, strict format, and correctness separately, and compare on held-out problems. Training generation fixes temperature 1, top-p 1, and top-k 0 so behavior policy matches the distribution used for old probabilities. Retain manifest, generations, checkpoints, and history; inspect mixed-group and format proportions before interpreting mean reward.
Weight 0.1 controls format contribution relative to correctness when both vary. GRPO normalizes rewards within a group: if only format varies, multiplying all differences by 0.1 also reduces their deviation and does not necessarily make normalized advantage small. Do not interpret that weight as a guarantee that format barely affects the update. The log separately retains correctness of a delimited answer and correctness with the full strict structure.
The local campaign completed 900 steps, generating 7200 answers and 625 constant-reward groups. Under the training verifier eight answers had a correct expression inside one tag and 6270 had strict format; these are training counts, not a comparison with the initial policy. Checkpoints and the verified final adapter were saved. Four segment times total about 4.86 wall-clock training hours under concurrency, excluding some model loading and not measuring exclusive GPU use. Three pauses resumed from complete checkpoints; a same-backend resume pilot reproduced its texts, though not weights bit for bit.
Scale conditions interpretation: TinyZero reports that its run with base Qwen2.5 0.5B did not learn reasoning and shows more complex behaviors with 3B. This is not a universal capability threshold: model, data, and training change. Our exercise uses a 0.5B instruct model and local GPU; it measures one protocol, not the 3B result or R1 scale.
On 200 held-out problems, 256 answers were generated for both base and final adapter using vLLM, temperature 0.8, top-p 0.9, and the same strict verifier. The base had 2 correct answers of 51,200 and the adapter 18 of 51,200. For each problem with successes among 256 samples we calculated and averaged; the estimator is unbiased for pass@16 under independent sampling from the same distribution. Results were 0.0625% versus 0.5374%: paired difference 0.4749 percentage points, with a 95% bootstrap interval of 0.1232 to 0.9117 points resampling problems. The observed difference is positive here, but absolute rates remain low; the interval excludes uncertainty sources such as changing problem distribution, model, or configuration. The figure connects only evaluated initial and final checkpoints, without measuring intermediate ones.
In an installation test with two training groups and initially strict format, none of 16 outputs met full structure: two opened <think> and one included a <answer> block. An arithmetically valid expression appeared as an intermediate attempt, but text assigned it an incorrect result and did not present it as the answer; it was not counted correct. The gradual variant reran two groups from base: the second produced mean format progress 0.09375 and gradient norm 2.18, but no mathematical success. This test detects a training signal; two groups do not establish the model learned to solve Countdown.
Required format can also hide a correct expression when the model adds an equality, for example 2 * 4 + 3 - 4 = 7, although instructions requested only the expression. An exploratory training audit found five such cases among 1096 outputs reviewed. The reward was not changed: these remain failures under the strict contract. The additional audit, fixed before consulting test, separately evaluates the first side before = for base and adapter. Under that rule it recognizes 24 of 51,200 base answers and 635 of 51,200 adapter answers, versus 2 and 18 under the strict verifier. That rule does not certify later equalities or the validity of full reasoning; it does not make the measures equivalent.
star_countdown.py applies three rounds of self-training to the same problem split, and evaluate_countdown.py evaluates base and adapters on held-out problems using the same sampling protocol. Also download star_local.py and the previous lesson’s extractor. Compare generations used to construct data too: matching primary attempts does not automatically include rationalizations, evaluations, or training. A smoke test with few problems or steps detects installation errors but does not estimate the full campaign result.
To match training output count, a budgeted variant counted both primary outputs and rationalizations. Before generation it fixed three rounds, at most eight primary attempts per problem, and one rationalization when no primary succeeds and budget remains. Only during training generation it added an arithmetic-format example disjoint from training and test problems; verifier and evaluation prompt remained strict. The earlier trial, without an example, had already spent another 2400 primary attempts and 300 rationalizations without accepted examples; it is counted separately. Its restored package has SHA256 4537954a49ade9e1a7f15624338c36877fff797d81114e8cc3f0480dcfe0489e.
The final variant persisted 6400 primary outputs and 800 rationalizations, 7200 outputs total, matching GRPO. None passed the filter, so no supervised fine-tuning occurred in any round and the base remained. It also generated 6400 answers for internal evaluations, outside those 7200. The auditor checks policies, seeds, traces, and balances; generated tokens and time were not equal between methods. Calculations use persisted samples: interruption may have discarded in-flight work whose cost is unknown.
The final policy remained the base, and revision, tokenizer, template, verifier, and protocol were checked to match. The comparison therefore reuses the already recorded real base evaluation against the GRPO adapter without regenerating the same condition. With 256 samples for each of the same 200 problems, estimated pass@16 was 0.0625% for STaR/base and 0.5374% for GRPO; STaR minus GRPO was −0.4749 percentage points, with a 95% paired bootstrap interval of −0.9150 to −0.1232. The result shows a bootstrap failure of this local STaR variant, not an unperformed fine-tune or a general conclusion about both methods. Recipes differ and the interval resamples only these problems.
The verifiable comparator rechecks all 102,400 held-out answers and contracts. Comparison data retain group hashes, costs, and curves. The portable package includes budgeted traces and markers without weights; SHA256 is 1e5e92f3c3db946e9f9934dfdd1db78e37db188f947911c6bb1a605d8c8821cf. The packager restored files and reran the auditor with a separate snapshot. Both held-out evaluations and contracts are in a second package of 61 MB, SHA256 46ea7aa526a5778b8f4a71aa91be61502238bcdcb87270576076b889c20be1da; its packager restored logs and repeated the complete comparison.
python grpo_countdown.py --model-path "$SNAPSHOT_05" --output grpo_run --steps 900 --train-count 300
python star_countdown.py --model-path "$SNAPSHOT_05" --output star_countdown --train-count 300 --test-count 200
python evaluate_countdown.py --model-path "$SNAPSHOT_05" --adapter grpo_run/final --output grpo_test --count 200 --samples 16
The trainer saves the first ten steps and then every hundred. To request an orderly pause, create a file named PAUSE in the run folder: the program finishes the current step, saves adapter, optimizer, scheduler, state, and random generators, and publishes the complete checkpoint. To resume, remove PAUSE and rerun the same command and configuration. The program verifies hashes and separately retains generations written after the last confirmed checkpoint. Do not confuse forced interruption before saving with a complete pause.
On Windows, the script chooses TRL’s PyTorch path within its process and records the backend; it does not change the shared package. This avoids depending on a C compiler for Triton kernels in the tested installation. The pilot should also verify that a real pause and resume produce a coherent checkpoint before trusting it with a long campaign. Option --profile measures synchronized wall times for generation, log-probability computation, and full step; the step includes preparation and gradient, so these figures overlap and must not be summed. The no-gradient field may include both old policy and reference.
For the mode comparison, hybrid_modes.py uses Qwen3-1.7B with thinking disabled and enabled on the same 200 MATH-500 rows; it requires math_eval.py. It counts truncated thoughts and unextracted answers per condition. Limits of 256 and 1024 are different interventions, not interchangeable samples from the same policy. Record environment and TRL version with results to reconstruct advantage computation and loss reduction.
The retained run used the vLLM runner, one answer per condition and problem and a maximum of 256 final-answer tokens. The auditor reconstructed all 600 evaluations and paired contrasts. Counting answers unrecognized by the extractor as incorrect, rates were 24%, 19%, and 15.5% without thinking, with cap 256, and with cap 1024 respectively. Paired differences against the first mode were −5 percentage points (bootstrap interval −10 to −0.5) and −8.5 points (−14 to −3.5).
Extraction strongly limits this comparison: 150, 161, and 168 of 200 cases respectively lacked a recognized answer, and 154, 166, and 173 answers reached their own length limit. An additional inspection of logs showed that all abstentions coincided with an answer cut by the limit without \boxed; the breakdown script reproduces the count. This identifies a protocol abstention cause, not whether the solution would have been correct with more time. Thinking reached its limit and required forced closure in 200 of 200 cases at cap 256 and 181 of 200 at cap 1024. Among extracted answers denominators are only 50, 39, and 32; those conditional rates do not represent all problems. Figure times are from concurrent batches, not isolated latencies. These results describe the protocol and extractor, not a general Qwen3 capability or proof that more thought always hurts.
All 600 traces with tokens, protocol, and summary are in the portable package, without model weights; SHA256 is b7c1256c3029e4271980c95712fddcd781157a042505de21ce8620f785714c5c. The packager checked hashes, restored files, and reran the auditor using the snapshot and original data separately.
Exercises
Step 1 of 3. What values does centered advantage take if all rewards are equal?
def dynamic_sampling(prompts, sample_fn, reward_fn, G, batch_size):
pass