GRPO with verifiable rewards
Implement GRPO to improve a 0.5B to 1.5B model's mathematical reasoning on GSM8K-style problems using verifiable correctness and format rewards. Build the complete loop with group sampling, normalized group advantages, clipped probability ratios, and KL, monitor entropy, length, and groups without signal, and actively test reward shortcuts.
After this lesson you can
- Implement group sampling, group advantages, and clipped loss with KL.
- Design verifiable rewards robust to ambiguous extraction and format shortcuts.
- Monitor reward, KL, entropy, length, and the fraction of degenerate groups.
- Measure improvement on the GSM8K test set with an interval relative to the initial model.
Before you start
- P08DPO diagnosticsReference log-prob cachingQLoRA training setup
- 22Policy gradient theoremAdvantage functionPPO clipped objective
- 20Group Relative Policy OptimizationREINFORCE Leave-One-OutGRPO normalization biasesReward hackingReward model overoptimization
- 21Temperature samplingCost per token model
- 18Autoregressive generation loop
Reward must measure the task
An answer containing the correct number somewhere is not necessarily a correct solution: it could enumerate every option. Mathematical reasoning needs a verifier with a clear output contract and independent evaluation that does not reward a weakness in the verifier itself. Verifiable reward design starts by specifying that contract before training.
In this project the final answer is written once as <respuesta>número</respuesta> at the end of the text. The verifier requires exactly one opening and closing tag, a finite integer or decimal inside, and no subsequent text. It compares the value with the reference answer extracted from the dataset. A pattern accepting the first number anywhere can reward a contradictory answer; one allowing several tags can be exploited by listing many candidates. This contract is deliberately narrow: a mathematically equivalent answer using a fraction or units may be rejected. Declare and measure that limitation.
The proposed experiment uses a pinned revision of GSM8K, with 7473 training and 1319 test problems; reserve the first 500 test problems for paired comparison. The dataset card declares an MIT license. The initial policy is the reconstructed SFT adapter on Qwen2.5-0.5B-Instruct, whose card declares Apache 2.0. Public questions allow the examination to be repeated but do not establish that they were unseen during pretraining. Fix the 500-problem cutoff before comparing variants and do not change it after observing results.
Before training, test a specific shortcut. The first verifier in this cell accepts the first integer it finds and therefore passes output that also asserts another number. The second enforces the final-answer contract. These are test strings designed to check the code, not outputs attributed to the model.
The lab protocol combines two indicators: reward one for verifiable correctness and 0.1 for valid format. The result can be 1.1 for a correct formatted answer, 0.1 for an incorrect numeric answer in the right format, or zero for invalid format. This auxiliary incentive may help obtain evaluable answers, but can also increase mean reward without increasing accuracy. Therefore record both indicators and report accuracy over all problems, not only those already meeting the format.
import re
from decimal import Decimal
NUMBER = re.compile(r'[+-]?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?')
FINAL = re.compile(r'<respuesta>\s*([^<>]+?)\s*</respuesta>\s*\Z')
def number(text):
text = text.strip()
return Decimal(text.replace(',', '')) if NUMBER.fullmatch(text) else None
def strict(text, gold):
if text.count('<respuesta>') != 1 or text.count('</respuesta>') != 1:
return False
match = FINAL.search(text)
parsed = number(match.group(1)) if match else None
return parsed is not None and parsed == Decimal(gold)
def naive(text, gold):
match = re.search(r'\d+', text)
return bool(match and int(match.group()) == gold)
trap = 'Podría ser 42 o 7.'
assert naive(trap, 42) and not strict(trap, 42)
assert strict('Cálculo. <respuesta>1,200.0</respuesta>', 1200)
assert not strict('<respuesta>42</respuesta> <respuesta>7</respuesta>', 42)
assert not strict('<respuesta>42</respuesta> texto posterior', 42)
assert not strict('<respuesta>NaN</respuesta>', 42)
print('La extracción ingenua acepta la trampa:', naive(trap, 42))
print('El contrato estricto la rechaza:', not strict(trap, 42))Advantages relative to the same problem
GRPO generates a group of answers for the same prompt and compares their rewards. For rewards , one explicit convention is
Here is the population standard deviation and protects the denominator. If every answer receives the same reward, advantages are zero and the group contributes no reward gradient. A group without signal does not mean the model is correct: it may have failed every time. Measure all-correct and all-incorrect groups separately. With binary reward and successes out of , without and with , advantages are for a success and for a failure. Normalization changes the weight of the same success according to group difficulty.
Compare this choice with RLOO, which uses as the baseline for answer the mean of the other rewards. If , then
Without dividing by standard deviation, this advantage is a fixed multiple of the group-centered reward. With samples independent conditional on the prompt, the baseline excluding does not depend on the action of , and its expected gradient term cancels under standard policy-gradient assumptions. Dividing by the group’s own standard deviation introduces a random factor depending on all rewards. This changes weighting and can introduce normalization bias relative to the expected reward gradient. It does not make either variant universally superior: specify the estimator and objective before comparing curves.
If each answer is independent with success probability , all succeed with probability and all fail with probability . Their sum is the probability of a group without relative signal. Real language-model answers may be correlated and difficulty varies across prompts, so this formula is a reference, not an empirical training estimate.
The old policy generated the group; freeze its log-probabilities before updating. For each answer token, . As in the PPO clipped objective, the term uses the minimum of and . The minimum also matters for negative advantages: it prevents an overly large update from appearing to improve without limit. The mask excludes prompt and padding but retains the end-of-answer token actually generated.
A common penalty uses . It is pointwise nonnegative because . If actions are sampled from and both distributions are positive on the same finite support, its expectation is : the exponential term averages one. If samples come from another policy, the identity does not hold without correcting the distribution. Recording the estimator does not automatically make it an exact KL.
To check the identity, write . Under an action distributed according to , the mean of is the sum of reference probabilities on the same support and equals one. The mean of is the forward KL. The constant term completes the cancellation. If an action has positive reference probability but zero policy probability, the sum over policy support no longer covers the whole reference; if the policy assigns mass where the reference is zero, forward KL can be infinite. These assumptions are essential to the proof.
Clipping is clearer when signs are separated. With positive advantage, increasing the ratio far above stops increasing the clipped term; with negative advantage, reducing it below stops improving that term. The minimum is taken after multiplying by advantage. Clipping the ratio and always choosing the smaller ratio reverses behavior for negative advantages. Also, a gradient with zero advantage does not come from relative reward, but the reference penalty can still have a gradient if the policy has already moved away from it.
Numerical stability requires care at invalid positions. A padded sequence may contain arbitrary log-probabilities where no average is taken. Computing a huge exponential there and then multiplying by zero can produce infinity times zero and end in NaN. First replace differences at masked positions by zero, compute ratio and penalty on those safe values, and apply the mask when summing. Near zero, an implementation can use expm1(u) - u to reduce cancellation; this form is algebraically equal to .
Averaging per answer and per token gives different weights. If one answer has two valid tokens and another eight, averaging their two mean losses gives each answer half the weight; summing all ten terms and dividing by ten gives the long answer four times as much weight. This difference remains even with exactly the same mask. To test equivalence with a library, fix the reduction as well as input values; agreement on an equal-length batch can hide disagreement.
import numpy as np
losses = np.array([[1., 1., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])
mask = np.array([[1., 1., 0., 0., 0., 0., 0., 0.],
[1., 1., 1., 1., 1., 1., 1., 1.]])
by_sequence = ((losses * mask).sum(axis=1) / mask.sum(axis=1)).mean()
by_token = (losses * mask).sum() / mask.sum()
print('por respuesta:', by_sequence, '· por token:', by_token)
assert np.isclose(by_sequence, 0.5) and np.isclose(by_token, 0.2)The first answer has mean loss one and the second zero. The per-answer mean is 0.5; the per-token mean is 0.2 because two of the ten tokens contribute loss one. In real fitting, each token’s loss can have either sign due to the policy term, but the weighting difference remains.
How loss is reduced over tokens matters. Averaging per sequence first gives short and long answers equal weight; normalizing by a fixed length or total token count gives other weights. Do not call these variants equivalent. To compare with TRL, fix version, reduction, mask, , clipping, and reference; compare the same batch before comparing training runs.
In TRL 1.19.0, group normalization uses sample standard deviation with Bessel’s correction and adds to the denominator. This section uses population standard deviation. Thus advantages differ even for the same rewards: in a group of eight with three successes, population deviation is 0.484123 and sample deviation 0.517549. Without , positive population advantage is 1.290994; under TRL’s convention it is approximately 1.207381. To compare only loss, explicitly give both implementations the same advantages; to compare the full algorithm, reproduce normalization too and declare the version.
This check compares a fixed batch with GRPOTrainer from TRL 1.19.0 in the previous lessons’ local environment. bnpo is chosen because it averages per valid token, like the function below. In that version grpo averages each answer before averaging the batch and need not match for unequal lengths. The test model returns fixed log-probabilities; this is not a training run.
import importlib.metadata
from collections import defaultdict
from types import MethodType, SimpleNamespace
import torch
from trl import GRPOTrainer
if importlib.metadata.version('trl') != '1.19.0':
raise RuntimeError('Esta comprobación usa TRL 1.19.0')
class IdentityAccelerator:
num_processes = 1
def gather(self, value): return value
def reduce(self, value, reduction='sum'): return value
class Fixed(torch.nn.Module):
pass
model = Fixed().eval()
trainer = GRPOTrainer.__new__(GRPOTrainer)
trainer.model = model
trainer.accelerator = IdentityAccelerator()
trainer.aux_loss_enabled = False
trainer.top_entropy_quantile = 1.0
trainer.off_policy_mask_threshold = None
trainer.importance_sampling_level = 'token'
trainer.beta = 0.02
trainer.args = SimpleNamespace(use_bias_correction_kl=False, delta=None)
trainer.loss_type = 'bnpo'
trainer.epsilon_low = trainer.epsilon_high = 0.2
trainer.use_vllm = False
trainer._entropy_bonus_enabled = False
trainer._metrics = {'train': defaultdict(list), 'eval': defaultdict(list)}
logp = torch.tensor([[-1., -2., -3.], [-2., -3., -4.]], dtype=torch.float64)
trainer._get_per_token_logps_and_entropies = MethodType(
lambda self, *args, **kwargs: (logp, torch.ones_like(logp), None), trainer)
old = logp + torch.tensor([[0., 0.5, -0.5], [0.2, -0.1, 0.]], dtype=torch.float64)
ref = logp + 0.4
mask = torch.tensor([[1, 1, 1], [1, 1, 0]])
adv = torch.tensor([1., -1.], dtype=torch.float64)
inputs = {'prompt_ids': torch.zeros(2, 1, dtype=torch.long), 'prompt_mask': torch.ones(2, 1),
'completion_ids': torch.zeros(2, 3, dtype=torch.long), 'completion_mask': mask,
'advantages': adv, 'old_per_token_logps': old, 'ref_per_token_logps': ref}
actual = trainer._compute_loss(model, inputs)
ratio = torch.exp(logp - old)
objective = torch.minimum(ratio * adv[:, None], ratio.clamp(0.8, 1.2) * adv[:, None])
delta = ref - logp
kl = torch.exp(delta) - delta - 1
own = ((-objective + 0.02 * kl) * mask).sum() / mask.sum()
print('TRL:', actual.item(), '· propia:', own.item(), '· diferencia:', abs(actual.item() - own.item()))
assert torch.allclose(actual, own, atol=1e-12, rtol=0)npm run lab and open the connection link.The resulting loss is approximately in both calculations. The negative sign is not an error: the minimized function includes the negative policy objective, not a distance required to be positive. Agreement checks only this batch; complete generation, verification, and training remain.
Sampling and updating use the same policy
The ratio represents the stated relationship only if its denominator matches the distribution that actually generated the token. A generation configuration may carry default temperature, top-p, top-k, or repetition penalty even when absent from the call. If sampling transforms logits but stored log-probabilities come from the original distribution, the denominator is no longer the behavior policy. In particular, top-p and top-k remove part of the support: recording temperature alone cannot recover the sampling probability.
One initial implementation samples with temperature one, top-p one, top-k disabled, and repetition penalty one. Save that policy’s log-probabilities and do not recalculate them after changing its weights. If updating more than once with the same group, compare each new policy with those frozen old probabilities; clipping limits the objective’s incentive but imposes no strict distance bound between policies. Any other sampling distribution requires computing and recording its actual probabilities and checking support conditions.
The mask also defines the distribution being optimized. The prompt is context, not an action generated by the policy in that episode. Padding must not enter the denominator either. The first generated end-of-answer token is part of the trajectory: excluding it prevents the loss from directly learning its probability. Distinguish that end from maximum-length truncation. Counting both cases helps detect an apparent format improvement caused by cut-off answers and shows whether the generation limit permits difficult reasoning to finish.
Advantage magnitude is not absolute reward magnitude. For example, with one correct solution in a group of eight and without , that solution receives advantage , but if seven are correct its advantage is . Both assign reward one to a success. Centering emphasizes rare within-group contrasts; prompts whose candidates are all equal provide no relative signal. Changing changes the probability of contrast, generation cost, and advantage distribution. State prompt and generated-answer counts explicitly when comparing group sizes.
In an independent evaluation, separate three indicators: format compliance, correctness among valid-format answers, and correctness over all problems. The second is conditional and can rise while the first falls. Retain the counts behind each ratio and the raw outputs. Inspect correct-format examples with wrong values, invalid-format examples containing the result, and attempts to list answers. If the verifier changes after seeing those examples, evaluate the new version as a protocol change rather than the same previous measurement.
Training-loop budget
The cost of a step includes more than backpropagation. For each problem, generate variable-length answers, then reevaluate their tokens under the old policy, reference, and updated policy. Autoregressive sampling proceeds token by token; raising the maximum limit multiplies potential work even when many answers finish earlier. Count generated tokens, truncations, and time per stage as well as problems per second. Comparing and on the same number of problems does not give the same generation budget.
With LoRA, base weights remain frozen and small matrices are trained, but activations needed for their gradients still occupy memory. Keeping a second full base for the reference adds to this cost. An alternative shares the frozen base and maintains two separate adapters: a frozen reference and a trainable policy. Switching the active adapter must restore the correct one before each update; check that the reference gives the same log-probabilities before and after training and only policy parameters receive gradients. Sharing a base is an implementation choice, not proof that the policies are identical.
Record batch size and maximum length with the actual hardware. If a configuration does not fit, process microbatches and accumulate gradients to reproduce a well-defined average, taking care with masks and relative sequence weights. Averaging each microbatch separately gives a different result from averaging all tokens when they contain different numbers of valid tokens. Do not extrapolate memory measurements from another GPU or confuse allocator-reserved memory with memory occupied by tensors; report the measured metric and device.
Saving requires more than weights: for faithful resumption retain optimizer state, position in data order, random generators, and the version, tokenizer, and parameter manifest. Changing code or data order may still permit a useful continuation, but it is no longer the same reproducible trajectory. Label intermediate results with completed problem and update counts. A short test can detect integration errors; it is not evidence that a full GSM8K epoch succeeded.
To reproduce the workflow, download grpo.py, gsm_verifier.py, and panel.py into the same folder. You need the p08-l04 SFT, p08-l05 CUDA environment, and datasets. The script pins revision 740312add88f781978c0658806c59bc2815b9866 of openai/gsm8k; first access requires cached data or a connection. By default it processes 7473 training problems with group size 4, , and up to 128 tokens per answer. In PowerShell:
$env:P08_L04_DIR = 'C:\ruta\a\salida-p08-l04'
$env:P08_GRPO_DIR = 'C:\ruta\a\grpo'
python grpo.py
python panel.py C:\ruta\a\grpo\g4-beta0.02\completo
The run compares 500 held-out questions before and after, retains outputs and checkpoints, and panel.py prepares JSON for the figure. To study another group size or coefficient, use P08_GRPO_GROUP and P08_GRPO_BETA and keep each manifest. P08_GSM_TRAIN_LIMIT permits a short run, but the same script also evaluates the 500 held-out questions: do not use those results to tune hyperparameters. Its output is labeled short and does not represent a full epoch.
During training, the history retains correctness and format indicators for each answer and the text of only one answer per group; it does not save the other strings. Before-and-after evaluations retain every examined answer. This limits later auditing of training examples: counts can be reviewed, but unsaved texts cannot be verified again.
To compare configurations without consulting the test set, also save diagnostico.py and its protocol alongside grpo.py and the verifier. The diagnostic uses eight fixed training-split problems, two updates per group, and each combination of and . For example, python diagnostico.py --group 4 --beta 0.02 saves its own panel.json and checkpoints; repeat other combinations to compare them. Each variant starts from the same SFT. With eight problems, generates 32 answers and generates 64: equal problem counts do not mean equal answer or token cost. The diagnostic is too short to establish general improvement and does not change the main campaign.
The short TRL trial uses those eight problems, group size 4, and 16 updates; save it with the same files and run python trl-corto.py in the pinned environment. The recorded result processed all eight indices once in another order, with 32 answers and two updates per group: none was correct, two had valid format, and six groups had uniform reward. The custom loop with and had zero correct, one valid format, and seven uniform groups among 32 answers. These are not equivalent trajectories: besides order and samples, TRL 1.19 uses sample deviation and , whereas the custom loop uses population deviation and . During updates the trainer enters train mode, and its default option does not disable LoRA dropout of 0.05; the custom loop retains eval. These differences prevent attribution to one cause. The TRL trial took 27.83 seconds of measured training under that workload; it does not use the 500 held-out questions.
Health signals
RL fine-tuning diagnostics include reward, estimated KL, entropy, length, and fraction of groups without variance. Add held-out problem accuracy with the same template, temperature, and generation limit before and after. Rising reward can indicate that the model learned the format, found a correct answer, or exploited the verifier: inspect individual answers and check all three cases.
The fraction of tokens where clipping is active helps interpret update magnitude. A high value means many terms reached the objective’s flat region, though it does not itself measure exact policy distance. Mean entropy may fall because the policy concentrates on correct solutions or repeats a wrong answer; inspect per-prompt diversity alongside accuracy. Also record the percentage of truncated generations: if it rises with length, low format reward may be due to the output limit rather than forgetting the final tag.
In the recorded diagnostics, both variants obtained 0/32 correct, 1/32 formatted answers, and seven zero-variance groups; both variants obtained 0/64, 7/64, and three zero-variance groups. On these eight questions, increasing group size produced more formatted answers and groups with contrast, but doubled the answer count. One seed and so few problems cannot reliably separate effects of and or estimate general improvement. Some reward curves overlap because values coincide; switch to the KL estimator to inspect other recorded differences. The diagnostic reward axis ends at 0.1 to show small values, while theoretical reward can reach 1.1. Selecting the full epoch extends the axis to 1.1.
The recorded run completed all 7473 proposed groups with , , two updates per group, and seed zero. Of 29,892 training answers, 918 were correct (3.07%) and 28,721 met the format (96.08%); 5813 groups (77.79%) had uniform reward. These are training counts, not exam results. Median group KL estimator was 0.236 and its maximum 102.530: a smoothed mean can hide extreme values. Per-token log-probabilities were not retained to explain that maximum, and with old-policy samples this estimator is not the current policy’s exact KL.
The run used an NVIDIA GeForce RTX 3060 with 12 GiB and BF16. Between checkpoints 50 and 7473, 16,110.7 seconds elapsed for 7423 groups, including checkpoint writes and concurrent workloads: an average of 2.17 seconds per group over that interval. Generation for the initial and final 500 questions took 360.81 and 505.36 synchronized seconds respectively; these are observed times, not performance promises for another machine. Evaluation and training have different costs and output lengths.
On 500 held-out questions, with deterministic generation and the same template and limit before and after, the initial SFT got 0/500 correct and the fitted policy 16/500. The paired difference was +3.2 percentage points, with 95% bootstrap interval [+1.8, +4.8] points resampling questions. The 16 improvements had no offsetting losses; the other 484 questions retained their correctness indicators. Valid format rose from 83/500 to 499/500, but only 16 of the 499 formatted final answers were correct. The result shows measured improvement on this slice alongside low absolute accuracy: format reward does not replace solving the problem. Review the initial answers, final answers, and paired result.
The interval describes variation across questions within this comparison, not variation across seeds, tasks, or models. This is one seed and one revision of a public dataset that may have appeared during pretraining; the narrow numeric verifier can also reject equivalent answers expressed as fractions or with units. Do not extrapolate the interval to a general reasoning result.
The first-integer shortcut also appears when reviewing actual outputs, without subsequently modifying the verifier: for question 357 of the slice, labeled 2, the later answer first wrote 2 and then <respuesta>4</respuesta>. The naive rule accepts the first 2 even though the declared final answer is 4; the strict verifier rejects it. Across the full slice, there were 12 initial cases and one later case that the naive rule would accept and the strict rule rejected. The audit log retains counts and examples. This evidences a naive-rule false positive, not intent or exploitation of that flaw by the policy during training.
To investigate possible repetition of one answer, valid numeric values were normalized: the 499 later formatted answers contain 171 distinct values; the most frequent are 30 and 12, each appearing 22 times. The count rules out all answers being the same number in this deterministic exam, but diversity does not establish correct reasoning.
The 500-question GSM8K evaluation is paired: save correctness before and after for each question and resample questions, not tokens, to compute a difference interval. A short training run or noisy estimate does not establish definitive improvement. DeepSeekMath introduced GRPO at a different model and scale; do not transfer its results to this small model.
import numpy as np
r = np.array([1, 0, 0, 1, 1, 0, 0, 0], dtype=float)
a = (r - r.mean()) / r.std()
print('media:', r.mean(), 'desviación poblacional:', r.std())
print('ventajas:', np.round(a, 6))Exercises
import numpy as np
def group_advantages(rewards, group_size, eps):
...
def grpo_loss(logp, old_logp, ref_logp, adv, mask, clip, beta):
...