Problem

Libraries like TRL hide what RLHF actually does. I wanted to build the whole post-training pipeline by hand on a model small enough to run in minutes: supervised fine-tuning, then reinforcement learning with a KL penalty, then tool use.

Approach

  • Data: 1,200 seeded, validated multi-step arithmetic problems from 4 templates, split 800 / 200 / 100 / 100. Every answer has to follow a strict two-line format: Reasoning: then Answer:.
  • SFT: distilgpt2 (82M parameters), with prompt tokens masked so the loss only covers the response.
  • RL loop, written directly in PyTorch: sampled rollouts, log-probabilities over generated tokens only, a rule-based reward (1.0 correct, 0.2 well-formed but wrong, 0 malformed) and a KL penalty (β = 0.1) against a frozen copy of the SFT model.
  • Tool use: 20 hand-written word problems, answered directly by the model or routed to a sandboxed calculator.

Result

On 100 held-out problems with greedy decoding:

Checkpoint Exact accuracy Format adherence Avg reward
Base distilgpt2 0% 0% 0.00
After SFT 0% 100% 0.20
After RL 5% 100% 0.24
Bar chart of accuracy, format adherence and reward for base, SFT and RL checkpoints. Format jumps to 100% after SFT; accuracy rises to 5% after RL.
fig_01 — eval_metrics.pngBase vs SFT vs RL on the held-out set (n = 100).

SFT did the heavy lifting: the base model just echoes the prompt, and after one epoch it follows the format every time. But the SFT model collapsed to predicting 0 for every step. RL kept the format at 100% and pushed it to produce real, varied numbers, occasionally correct.

The calculator tool returned the right answer for 20 of 20 word problems when given the expression.

RL training log: batch reward settles near 0.2 while the KL estimate grows.
fig_02 — rl_training_log.pngRL training log, one point every 20 steps (batches of 4, so noisy).

What I’d do next

  • Add a reward baseline or GRPO-style group normalization, and PPO’s clipped objective.
  • Use a per-token KL or a larger β to stop the drift.
  • Train the model to emit the calculator call itself, instead of handing it the expression.