Module contents
Lesson 9 of 31Advanced 100 min

Self-training for reasoning: STaR, expert iteration and ReST-EM

Study STaR rationalization, expert iteration, rejection sampling, and ReST-EM on reasoning traces. Implement the LoRA loop, compare teacher trace distillation, and measure filtering bias, lucky answers, and diversity.

After this lesson you can

  • Implement the STaR loop: sample, filter for correctness, fine-tune, and repeat, including rationalization for unsolved problems.
  • Derive ReST-EM as EM maximization of a lower bound on log probability of success.
  • Measure filtering bias toward easy problems and the rate of accepted traces with incorrect reasoning.
  • Compare self-training with m20 trace distillation from a larger teacher at equal example counts.
  • Evaluate pass@1 and pass@k across iterations and detect stagnation or diversity loss.

Before you start

Learning from one’s own successes

A model produces eight solutions per problem. An answer verifier retains those ending in the expected value; those traces become supervised examples for the next policy. The process can expand reasoning data without hand-writing every trace, but it is not free: generation, verification, storage, and training all cost resources. A correct-answer label also does not certify every step as valid.

STaR (Self-Taught Reasoner) iterates rationale generation, answer filtering, supervised fine-tuning, and new generation. Zelikman and colleagues start with a few reasoning examples and also use a second chance conditioned on the correct answer. Their recipe fine-tunes again from the base model in each round on selected data, rather than accumulating the effects of successive fine-tunes without control. Restarting does not guarantee improvement or independence: generated data still depend on prior policies.

Rationalization asks for a rationale after revealing the known answer when the first attempt fails. It can introduce a problem the model did not solve on its own. It can also make it easier to invent an invalid rationale reaching the answer. During training remove the revealed answer from the prompt and evaluate new questions without giving it: otherwise leakage makes copying the answer look like reasoning.

The rationalized trace may retain the final answer as part of supervised output: that is the target being taught. What must be removed is the extra instruction revealing it to the generator. If an explanation makes a false claim and then writes the known answer, the outcome verifier will still accept it. A step audit can estimate this contamination in a sample; if an automated assistant performs review, describe it as such rather than attributing it to human annotators.

A rationalization and an autonomous solution answer different questions. The first estimates what explanation the model produces knowing the result; the second shows what it can find without that hint. Retain a provenance field and compare acceptance rates and lengths separately. If an answer cannot be automatically verified, filtering needs another source of labels; replacing verification with the generator’s own confidence changes the problem and can reinforce shared errors.

Consider one hundred problems and eight attempts per problem. With a constant 0.1 success rate and independent attempts, expected coverage is 100(1−0.98)≈56.95100(1-0.9^8)\approx56.95 problems. One rationalization attempt per unsolved problem would apply to about 43.05 problems in expectation; these additional attempts consume compute even when rejected. Real rates vary by question and samples may share errors, so this calculation plans an idealized case rather than predicting real coverage.

When saving each round, retain the question, seed, all eight original generations, extractor result, and rationalization provenance. Resumption must check that configuration and weights match the manifest. A round’s filtered set is not an unbiased sample of all attempts: measure how many problems contribute no trace and how many each contributes. These counts help interpret later improvement or degradation.

InteractiveFilter, fine-tune, and repeat
  • Easy
  • Medium
  • Hard

Expectation model, not real training: eight attempts per problem; hypothetical rescue adds a chain in 60% of unsolved cases.

4
Accuracy on easy problems80.6 %
Accuracy on hard problems13.9 %
Policy entropy0.826
This expectation model is hypothetical. Browse iterations and compare conditioned rescue with and without balancing across problem types.

The figure uses three strategies, three difficulty groups, and declared fixed probabilities. Eight attempts are expected per problem; hypothetical rescue adds a trace for 60% of problems with no successes. Balancing normalizes each group’s contribution and does not automatically correct wrong labels. These are toy equations, not a language-model training record.

Expert iteration and rejection learning

In expert iteration, a policy proposes and an improvement procedure, such as search or filtering, produces data for fitting a new policy. In AlphaZero the expert includes tree search; here it can be an answer verifier and a set of samples. The policy distills selected behavior, but the filter is only as good as its specification. Yuan and colleagues describe fine-tuning with rejection sampling of mathematical traces. ReST generates an offline dataset and reuses it to improve the policy; its general formulation is not limited to binary reward.

A verifier can also use failures. V-STaR uses correct and incorrect solutions to train a preference selector and choose among inference candidates. The usefulness of a failure depends on how it was generated and labeled; an answer the extractor cannot recognize should not automatically become a negative example.

EM with binary reward

The EM interpretation treats trace yy as a latent variable. For fixed problem xx, let R(x,y)∈{0,1}R(x,y)\in\{0,1\} be a fixed verifier and define

Zθ(x)=∑yπθ(y∣x)R(x,y).Z_\theta(x)=\sum_y \pi_\theta(y\mid x)R(x,y).

If Zθold>0Z_{\theta_{\mathrm{old}}}>0, the posterior over successful traces is q(y)=πθold(y∣x)R(x,y)/Zθoldq(y)=\pi_{\theta_{\mathrm{old}}}(y\mid x)R(x,y)/Z_{\theta_{\mathrm{old}}}. For any qq supported on positive-reward traces, Jensen gives

log⁡Zθ≥∑yq(y)log⁡πθ(y∣x)R(x,y)q(y).\log Z_\theta \geq \sum_y q(y)\log\frac{\pi_\theta(y\mid x)R(x,y)}{q(y)}.

The bound touches the objective at θold\theta_{\mathrm{old}} when qq is that posterior. Since R=1R=1 on its support, the M step maximizes Eq[log⁡πθ(y∣x)]\E_q[\log \pi_\theta(y\mid x)]; if maximized exactly and the family includes the previous model, neither the new bound nor log⁡Zθ\log Z_\theta is lower. Singh and colleagues relate self-training to this procedure. In practice the posterior is approximated with finitely many samples, LoRA fitting is restricted, and the optimizer does not solve the M step exactly: monotonicity is not guaranteed. If no sample succeeds, there is no empirical posterior for that problem; rationalization changes the procedure and adds a conditioned source.

The proof applies to an objective and distribution defined before the M step. Limiting each problem to two traces or balancing groups changes relative observation weights compared with unmodified rejection sampling; answer-conditioned rationalization introduces another generating distribution. These choices may help coverage and cost, but the same EM guarantee no longer follows automatically for the modified set. Evaluating their effect requires an equal-budget ablation and held-out set.

The support condition avoids an undefined operation: qq assigns mass only where R=1R=1, so log⁡0\log 0 is not evaluated inside the expectation. If the verifier accepts a trace due to a lucky answer, that trace still belongs to the mathematical support of qq. When assumptions hold, the guarantee concerns the probability of satisfying that verifier; it does not guarantee the trace is a valid proof. Changing the success criterion also changes the objective ZθZ_\theta being improved.

With finite samples, a problem with no successes may be difficult or simply unlucky. Eight failures do not prove p=0p=0: even if p=0.1p=0.1, their probability is 0.98≈0.43050.9^8\approx0.4305. Always discarding such problems makes training data mostly represent questions the current policy can already solve. A second answer-conditioned chance or extra budget may improve coverage, but each changes the distribution and must be accounted for separately.

InteractiveFiltering changes the distribution
  • Initial
  • After

Hypothetical model: success rates A=(0.9, 0.5, 0.1), B=(0.1, 0.5, 0.9). The M-step represents the posterior exactly.

Self-training task
3
Entropy in nats0.314
Expected accuracy on current task0.862
Expected accuracy on the other task0.138
The strategy posterior is proportional to initial probability multiplied by success rate. Change the task and iteration count; effectiveness values are hypothetical.

In the example, optimizing for A can remove mass from strategies useful for B. This does not prove all self-training reduces diversity: measure it per problem and compare pass@1 with pass@k on a held-out set. If the policy converges on one answer, pass@1 may rise while multi-sample coverage falls.

The filter has its own bias

Filtering bias arises because an easy problem typically supplies more accepted traces than a hard one. If mm independent samples have success probability pip_i, the expected number accepted is mpimp_i and the probability that the problem appears at least once is 1−(1−pi)m1-(1-p_i)^m. Deduplicating traces and limiting examples per problem reduce concentration but change the training objective. Record distributions before and after filtering.

With eight attempts, problems with probabilities 0.9 and 0.1 would contribute expected 7.2 and 0.8 accepted traces respectively: a nine-to-one ratio. If at most two per problem are retained, for X∼Binomial(8,p)X\sim\mathrm{Binomial}(8,p) the expectation becomes E[min⁡(X,2)]=2−2P(X=0)−P(X=1)\E[\min(X,2)]=2-2\Pr(X=0)-\Pr(X=1). Values are approximately 2.000 and 0.756. The cap reduces the ratio to about 2.64 times but does not remove bias or ensure every problem is represented. Additional deduplication depends on trace content and is not included in this calculation.

For four-option multiple choice, suppose the model reasons correctly with probability pp and always succeeds in that case. Otherwise it guesses uniformly and succeeds with probability 1/41/4. The fraction of incorrect reasoning among accepted answers is

(1−p)/4p+(1−p)/4.\frac{(1-p)/4}{p+(1-p)/4}.

With p=0.3p=0.3 it is approximately 0.3684. The figure depends on assumptions: actual reasoning errors may correlate with answers and correct reasoning can still fail when transcribing the result.

InteractiveA lucky final answer
00.20.40.60.81Correct reasoning0.3Lucky guess0.175

Hypothetical model: correct reasoning always succeeds; incorrect reasoning guesses uniformly. This does not measure real chains.

0.30
Equally likely choices when guessing
Fraction accepted47.5 %
Incorrect reasoning among accepted36.8 %
Change the probability of correct reasoning and the number of choices. The figure computes Bayes’ rule under the uniform-guessing model described in the text.

Trace distillation replaces or supplements self-training with solutions from a teacher model. When comparing them, match example counts, separate test problems, and account for generation and training. Learning a template or delimiter before problem-solving ability is a hypothesis tested against formatting errors and verification, not an automatic conclusion. Gandhi and colleagues study habits such as checking and backtracking and show that the starting point influences self-learning in their setup; they do not prove every textual occurrence of “wait” is faithful reasoning.

Matching example counts does not necessarily match token counts or problem coverage. A collection of long traces may cost more to train on than one with the same number of rows; many solutions to one problem may cover fewer cases. Report both counts, traces discarded for length, and the cost of generating rejected answers too. If length is capped so both variants fit the same training, the filter may favor a teacher producing shorter explanations: that selection is part of the comparison.

To summarize multiple samples of one problem, with nn generations and cc observed successes, the usual coverage estimate for k≤nk\le n is 1−(n−ck)/(nk)1-\binom{n-c}{k}/\binom{n}{k}. It counts the proportion of size-kk subsets containing at least one success; under independent identically distributed samples it estimates policy pass@k. With n=8n=8, c=2c=2, and k=4k=4 it gives 1−15/70≈0.78571-15/70\approx0.7857. It does not claim a selector can recognize that success and does not make questions independent: intervals between methods must resample complete problems and preserve pairing.

A fair comparison can hold out exactly the same problems and evaluate each model with the same sample count, temperature, extraction rule, and generation limit. Calculate the difference between the two results per problem before resampling; a particularly hard question then affects both methods and that relationship is preserved. The interval describes uncertainty in the problem sample and procedure used, not every possible future change in model, seed, or distribution. Record extractor abstentions per method and avoid presenting unreadable answers as certainly mathematically incorrect.

Cost comparison also needs a clear time boundary. Counting only student fine-tuning omits failed teacher generations and search for acceptable traces; counting repeated evaluation for one variant but not the other also distorts comparison. Distinguish training-data generation, fine-tuning, and evaluation. If runs share a GPU, report observed wall time under that concurrency, not as exclusive GPU consumption.

Lab: a tabular policy

This simulation reproduces the first figure’s dynamics by expectation, without samples or neural training. Each row of rates gives success probabilities of three strategies for one problem type. After filtering, the M step replaces the distribution with the expected proportion of accepted strategies. Rescue uses a hypothetical strategy mix that differs by group; it does not imply a real rationalization is correct.

[ ]Self-training a discrete policyBrowser
from math import log
rates=[[.9,.7,.4],[.6,.5,.2],[.05,.25,.45]]
weights=[.5,.3,.2]
teacher=[[.6,.3,.1],[.3,.4,.3],[.1,.3,.6]]
def star_dynamics(rational=False,balanced=False,rounds=10):
    policy=[1/3]*3; history=[]
    for iteration in range(rounds+1):
        success=[sum(x*y for x,y in zip(row,policy)) for row in rates]
        entropy=-sum(x*log(x) for x in policy if x>0)
        history.append((iteration,policy[:],success,entropy))
        counts=[0.,0.,0.]
        for task in range(3):
            rescue=.6*(1-success[task])**8 if rational else 0.
            group=[8*policy[j]*rates[task][j]+rescue*teacher[task][j] for j in range(3)]
            total=sum(group)
            for j in range(3):
                counts[j]+=weights[task]*(group[j]/total if balanced and total else group[j])
        z=sum(counts); policy=[x/z for x in counts]
    return history
for rational in (False,True):
    for balanced in (False,True):
        _,policy,success,entropy=star_dynamics(rational,balanced)[-1]
        print('racionalización',rational,'equilibrio',balanced,
              'política',tuple(round(x,4) for x in policy),
              'éxito',tuple(round(x,4) for x in success),'entropía',round(entropy,4))

Balancing here equalizes contributions per difficulty group, not per individual problem. Results depend on selected rates: they reflect the explicit model, not the quality of real training. In a language lab save question, text, seed, extracted answer, abstention state, source, and round; deduplicate within each problem and separate validation and test before generation.

Local lab: three STaR rounds

star_local.py starts from Qwen2.5-0.5B-Instruct and takes the first 300 problems from GSM8K training and 200 held-out problems from lesson 3. It generates eight answers per problem and round, keeps up to two distinct verified answers, and asks for rationalization when none succeed. Each round’s fine-tune reloads the base; that round’s examples are kept with the adapter. It needs the extractor and its dependency in the same import directory.

python star_local.py --model-path "$SNAPSHOT_05" --train-records gsm8k_train_2000.json --test-samples muestras_200x64.jsonl.gz --output star_smoke --train-count 3 --test-count 2
python star_local.py --model-path "$SNAPSHOT_05" --train-records gsm8k_train_2000.json --test-samples muestras_200x64.jsonl.gz --output star_run --train-count 300 --test-count 200

Each fine-tune writes complete checkpoints every 25 batches and at round end. They save adapter, optimizer, random states, and position, with hashes and fingerprints of examples and prompts. After interruption rerun the same command and keep the output directory: the program checks the contract and resumes from the latest complete checkpoint. Batches after the last save are recomputed; do not confuse a temporary directory with a published checkpoint.

The reasoning teacher generator obtains DeepSeek-R1-Distill-Qwen-1.5B traces on the same 300 training problems. The distillation comparator selects from that corpus the same number of examples as the final STaR round, trains from the same base, and evaluates the same questions. Before selection it records and excludes examples exceeding 768 tokens with the student tokenizer, the same limit used in training; this can bias comparison toward short traces. If too few remain to match size, the program stops and reports the deficit. Matching examples does not automatically match production cost: retain teacher and student times and calls. pass@1 and pass@8 summaries do not certify valid steps; audit a sample of successful traces to study contamination by faulty reasoning.

A local run of the vLLM generator completed 300 groups of eight teacher answers. The extractor recognized 2331 of 2400 answers, 28 outputs hit the length limit, and 1896 numerically matched the training reference. Truncation and extraction categories can overlap. Group generation took about 4 wall-clock hours with other concurrent loads, not exclusive GPU hours. The audit checks hashes and identity, but a correct final answer does not certify intermediate steps.

The checkpoint and corpus package lets you rerun the auditor after extraction. Before the final STaR round size was known, the preparation script filtered the corpus by answer, deduplication, and length: it retained 529 candidates from 272 problems, with their manifest. This is a training set, not held-out evaluation. The comparator accepts that file via --teacher-pool and checks it matches reproduced filtering.

python generate_reasoning_teacher.py --model-path "$REASONER" --train-records gsm8k_train_2000.json --output teacher --count 300 --samples 8
python distill_compare.py --model-path "$SNAPSHOT_05" --teacher-samples teacher/teacher.jsonl.gz --star-output star_run --test-samples muestras_200x64.jsonl.gz --output teacher_comparison

The retained run used vLLM to generate rounds and returned to the base for each fine-tune. It generated 7200 primary training answers and 404 additional rationalizations; 279, 296, and 294 examples were selected across the three rounds. Internal evaluation of four policies produced another 6400 answers. The auditor verified groups, seeds, extractors, and adapters; seeds identify requests but do not guarantee identical tokens when changing backend or batch sizes.

The portable campaign package collects 1700 groups, three adapters, and phase times without base weights; its SHA256 is c6eb7a81b82b6d9df7b71a3df456101bec833c4ea5f6066a5d98f3014c20c492. The packager replaced each configuration’s local path with the public model identifier, recorded original fingerprints, and reran the auditor on an independent restoration. Input samples from earlier lessons and the base snapshot are downloaded separately.

InteractiveSelection and evaluation across STaR

Loading data.

Measure
0
pass@1no data
95% bootstrap intervalno data
Not extractedno data
Examples for next fine-tuning round—
Change the round and measure. Diversity counts distinct texts and does not prove reasoning diversity.

On 200 held-out problems, mean per-answer rate was 20.5% for the base and 20.19% after round three; pass@8 was 50% and 46%, respectively. These are not evidence of improvement in this sample. The extractor did not recognize 1038 of 1600 base answers and 890 of 1600 final-round answers; abstentions remain in the denominator. Figure intervals resample problems, not individual traces.

For comparison with distillation, 294 teacher-corpus examples were selected, matching the final STaR round, and another student was fine-tuned from the same base. On the same 200 questions with eight samples per policy, the teacher-trained student achieved 4.44% per answer and 20.5% pass@8, versus 20.19% and 46% for STaR. Paired teacher-minus-STaR differences were −15.75 percentage points (bootstrap interval −19.19 to −12.44) and −25.5 points (−32 to −19), respectively. The extractor did not recognize 1466 of 1600 teacher-trained answers versus 890 for STaR, strongly limiting the comparison. The reproducible comparison retains its sources and costs; the teacher generated 2400 traces and STaR generated 7200 primary traces plus rationalizations, so matching fine-tuning examples does not match compute or prove causality.

A preselected sample of 50 accepted training occurrences was manually reviewed by an assistant, not human annotators. The judgment record and its summary distinguish 32 valid traces, 9 with reasoning or unit inconsistencies, and 9 uncertain. If all uncertain traces were reclassified, the inconsistent fraction would be between 18% and 36% in this sample; it is not a population rate. A rationalization knows the answer during generation and should not be interpreted as independent discovery.

Exercises

ProofEM bound
Prove: Prove that an exact M step does not reduce log Z for binary reward.
0
Z_old > 0; q is the posterior over reward-1 traces under the previous policy.

Step 1 of 3. What bound does Jensen give?

Numeric
With probability 0.3 of correct reasoning and uniform random guessing among four options when reasoning is incorrect, what fraction of accepted traces have incorrect reasoning?
Code
Implement build_star_dataset(samples, verifier, max_per_problem). Each sample is a (problem, trace) pair. Keep those accepted by verifier(problem, trace), deduplicate per problem using normalized whitespace and lowercase, preserve arrival order, and limit each problem to max_per_problem. Return original pairs. Reject max_per_problem below one.
def build_star_dataset(samples, verifier, max_per_problem):
  pass
Shift+Enter to run
Quiz
What role does restarting fine-tuning from the base play in each iteration of this recipe?
Quiz
Which comparison can reveal lost coverage as pass@1 improves?
Key idea
Answer filtering creates useful data and biases. The EM guarantee is idealized, and a correct result does not certify reasoning.