DavidGadyan

Post-Training Mind Map: SFT, Reward Models, RLHF with PPO, RLVR, GRPO and DPO

How a pretrained LLM becomes a helpful, correct assistant: supervised fine-tuning, reward models, RLHF with PPO, verifiable rewards (RLVR), GRPO and DPO, with the formulas behind each step.

Section 2: Model training and alignment

  1. The post-training pipeline

    Base model to assistant

    What it is
    Pretraining gives a model knowledge; post-training turns it into an assistant. The usual order is supervised fine-tuning, then a preference or reward stage, then reinforcement learning with PPO or GRPO. Evaluation follows every stage.
    When to use it
    Placing any post-training method in the right step of the recipe.
    In code
    pretraining → SFT → reward model or preferences → RL (PPO / GRPO) → evaluation
    Key figures
    • InstructGPT's recipe has three steps: supervised fine-tuning on demonstrations, a reward model trained on rankings, and PPO against that reward model.Source: Ouyang et al., 2022
    1. Pretraining

      Next-token prediction

      What it is
      The model learns to predict the next token on a very large unlabelled text corpus. The result is a base model: it knows a lot and continues text well, but it does not reliably follow instructions.
      When to use it
      The starting point of every post-training method; usually you download it rather than train it.
    2. SFT stage

      Learn from demonstrations

      What it is
      The base model is trained on prompt–response demonstrations so it answers like an assistant. The SFT model is the starting point of the RL policy and, as a frozen copy, the reference model.
      When to use it
      Teaching format, tone and task behaviour before any reward signal is used.
    3. Preference or reward stage

      Which answer is better

      What it is
      People (or rules) judge model outputs. In RLHF their pairwise choices train a reward model. DPO skips the reward model and trains on the pairs directly; RLVR replaces this stage with a programmatic verifier.
      When to use it
      Capturing what "good" means when comparing answers is easier than writing the ideal one.
    4. RL stage

      PPO or GRPO updates

      What it is
      The policy generates answers, a reward model or a verifier scores them, and PPO or GRPO updates the policy to raise the score. A KL penalty to the reference model stops it drifting too far from the SFT model.
      When to use it
      Improving beyond the demonstrations: the model explores and keeps what scores well.
    5. Evaluation

      After every stage

      What it is
      Each checkpoint is compared with the previous one on held-out benchmarks, preference comparisons and safety tests. Evaluation also catches reward hacking and lost skills, which a rising reward curve hides.
      When to use it
      Deciding whether a new checkpoint ships or the run rolls back.
    6. TRL, OpenRLHF, veRL

      Training libraries

      What it is
      TRL is Hugging Face's library with trainers for SFT, reward models, DPO, PPO and GRPO. OpenRLHF is a Ray-based framework that uses vLLM for generation and DeepSpeed for training. veRL, open-sourced by ByteDance, runs PPO and GRPO with FSDP or Megatron-LM training and vLLM or SGLang rollouts.
      When to use it
      TRL for single-node experiments; OpenRLHF or veRL when RL training spans many GPUs.
      In code
      from trl import SFTTrainer, RewardTrainer, DPOTrainer, GRPOTrainer
  2. Supervised fine-tuning

    SFT on demonstrations

    What it is
    Training continues on curated prompt–response pairs with the same next-token loss as pretraining, but only on the response. It teaches the assistant format and the behaviour shown in the examples.
    When to use it
    The first post-training step, and often the only one for narrow tasks.
    1. Prompt–response pairs

      The training examples

      What it is
      Each example is a prompt and the answer you want, written by people or generated by a stronger model and filtered. Quality and coverage matter: the model copies whatever the examples show, mistakes included.
      When to use it
      Building the dataset for a domain assistant or a fixed output format.
      In code
      {"messages": [{"role": "user", "content": "…"}, {"role": "assistant", "content": "…"}]}
      Key figures
      • InstructGPT's SFT dataset had about 13k training prompts, taken from the API or written by labellers.Source: Ouyang et al., 2022
    2. Chat templates

      Roles as special tokens

      What it is
      A chat template turns system, user and assistant messages into one token sequence, with special tokens marking each turn. Training and inference must use the same template, or the model sees a format it never learned.
      When to use it
      Preparing SFT data for an open-weight model, and debugging odd answers after fine-tuning.
      In code
      text = tokenizer.apply_chat_template(messages, tokenize=False)
    3. Loss masking

      Train on answers only

      What it is
      Prompt tokens get the label -100, so the loss ignores them and only response tokens produce gradients. The model learns to answer, not to reproduce user prompts.
      When to use it
      Any SFT run on chat data; check it is switched on before training.
      In code
      labels = input_ids.clone()
      labels[:, :prompt_len] = -100   # ignore_index of CrossEntropyLoss
    4. Next-token loss

      Teacher-forced CE

      What it is
      Cross-entropy on each response token, given the prompt and the correct earlier tokens. This is teacher forcing: the model always sees the reference prefix, never its own samples, so all positions train in one parallel pass.
      When to use it
      Writing the SFT objective, and contrasting it with RL, where the model learns from its own samples.
      In code
      L_SFT = −Σ_t log π_θ(y_t | x, y_<t)
      t runs over response tokens only (prompt tokens masked)
      Teacher forcing: y_<t = reference tokens, not samples
    5. LoRA and QLoRA

      Train a low-rank update

      What it is
      LoRA freezes the weight matrix W and trains a low-rank update BA of rank r, so only a small share of parameters and optimiser states sits in memory. QLoRA also stores the frozen base model in 4-bit (NF4) and trains the adapters on top.
      When to use it
      Fine-tuning a large model on one or a few GPUs, or keeping one small adapter per customer or task.
      In code
      W' = W + (α / r) · B·A
      B ∈ ℝ^(d×r), A ∈ ℝ^(r×k), r ≪ min(d, k)
      B starts at 0, so W' = W at step 0
    6. Packing

      No padding waste

      What it is
      Short examples are joined into full-length sequences instead of padding each one, so fewer tokens are wasted. Without per-example attention masks, tokens can attend across example boundaries, so use masks or position resets when the library offers them.
      When to use it
      SFT datasets with many short chats, where padding would fill most of the batch.
      In code
      [ex1 <eos> ex2 <eos> ex3 <eos> …] → one max_len sequence
    7. Epochs and learning rate

      When to stop

      What it is
      SFT datasets are small, so the model memorises them quickly, and the learning rate is usually far below pretraining. Validation loss can start rising (overfitting) while answers still improve, so choose epochs with task evaluations and human preference, not loss alone.
      When to use it
      Setting the first hyperparameters of a fine-tuning run and deciding when to stop.
      Key figures
      • InstructGPT's SFT models overfit on validation loss after 1 epoch, yet training for 16 epochs still improved the reward-model score and human preference ratings.Source: Ouyang et al., 2022
    8. Catastrophic forgetting

      Lost general skills

      What it is
      Training hard on a narrow dataset can erase abilities the model had after pretraining, such as other languages, maths or general knowledge. Mixing in general data, a lower learning rate, fewer steps or LoRA reduce it; in RL the KL penalty plays a similar role.
      When to use it
      Explaining why a fine-tuned model got worse at things you never trained.
      Key figures
      • RLHF caused performance regressions on public NLP datasets (an "alignment tax"); InstructGPT reduced them by mixing pretraining updates into PPO (PPO-ptx).Source: Ouyang et al., 2022
    9. When SFT alone is enough

      Format, style, domain

      What it is
      If you can write good answers for the task, SFT is often enough: a fixed output format, a house style, domain vocabulary or a narrow extraction task. Add RL when you can rank or verify answers but cannot easily write the best one.
      When to use it
      Scoping a project: start with SFT and add RL only if evaluations show a gap.
  3. Reward model

    Learned human judgement

    What it is
    A model trained on human preference comparisons that gives any prompt–response pair a single score. During RLHF it stands in for the human labellers, so the policy can be scored at scale.
    When to use it
    RLHF for subjective goals such as helpfulness, tone and harmlessness.
    AI angle
    The reward model is a proxy for human judgement. The policy optimises the proxy, so the proxy's blind spots become the policy's habits.
    1. Pairwise preferences

      Chosen vs rejected

      What it is
      Each record is a prompt x with two answers: the chosen one y_w and the rejected one y_l. People compare answers rather than score them, because relative judgements are more consistent between labellers.
      When to use it
      Collecting data for a reward model or for DPO.
      In code
      {"prompt": x, "chosen": y_w, "rejected": y_l}
      Key figures
      • InstructGPT labellers ranked 4 to 9 answers per prompt, giving C(K,2) comparisons each time; the reward-model dataset had 33k training prompts.Source: Ouyang et al., 2022
    2. Bradley–Terry model

      Preference as a sigmoid

      What it is
      The probability that y_w beats y_l is the sigmoid of the reward difference. Training minimises −log σ(r_w − r_l), which pushes the chosen score above the rejected one. Only differences matter, so adding a constant to every reward changes nothing.
      When to use it
      Writing the reward-model loss, and explaining why reward scores need normalising.
      In code
      P(y_w ≻ y_l | x) = σ(r(x, y_w) − r(x, y_l))
      σ(z) = 1 / (1 + e^(−z))
      L_RM = −log σ(r_w − r_l)
      InstructGPT: L = −1/C(K,2) · E[log σ(r_θ(x, y_w) − r_θ(x, y_l))]
      Key figures
      • Bradley and Terry published the paired-comparison model in 1952, decades before LLMs.Source: Bradley & Terry, 1952
    3. Scalar reward head

      LLM + one number

      What it is
      The reward model is a transformer, usually started from the SFT model, with the vocabulary output replaced by a linear layer that returns one number. The score is read at the last token, after the model has seen the whole answer.
      When to use it
      Sizing GPU memory for RLHF and choosing which checkpoint the reward model starts from.
      AI angle
      It is a full LLM, so in RLHF each forward pass costs as much memory and compute as a policy of the same size.
      In code
      r_φ(x, y) = w · h_T + b   # h_T: hidden state at the last token
      Key figures
      • InstructGPT used a 6B reward model, started from the SFT model with the unembedding layer removed; 175B reward models could be unstable to train.Source: Ouyang et al., 2022
    4. Reward normalisation

      Fix the scale

      What it is
      A Bradley–Terry reward has no natural zero, so it is shifted (and often scaled) to a known reference before RL. Implementations also whiten rewards or advantages per batch, so the update size stays stable.
      When to use it
      Stopping a reward model's arbitrary scale from setting the PPO step size or the balance with the KL term.
      In code
      r ← r − b   # b chosen so reference answers average 0
      r̃ = (r − mean(r)) / std(r)   # per-batch whitening
      Key figures
      • InstructGPT normalised its reward model with a bias so that labeller demonstrations scored 0 on average before RL.Source: Ouyang et al., 2022
    5. Reward hacking

      Over-optimising the proxy

      What it is
      Pushed hard, the policy finds outputs the reward model scores highly but people do not prefer, such as longer, flattering or repetitive answers. The reward keeps rising while real quality falls. The KL penalty, early stopping and fresh labels on new outputs limit it.
      When to use it
      Reading an RLHF run where the reward climbs but evaluations get worse.
      Key figures
      • DeepSeek-R1-Zero used no neural reward model, because such models may suffer from reward hacking in large-scale RL.Source: DeepSeek-AI, 2025 (DeepSeek-R1)
    6. Labeller agreement

      The noise ceiling

      What it is
      People disagree on which answer is better, so preference labels are noisy. Agreement between labellers sets a rough ceiling on how accurate a reward model can look, and low agreement points to unclear guidelines.
      When to use it
      Judging reward-model accuracy and writing labelling guidelines.
      Key figures
      • InstructGPT's training labellers agreed with each other 72.6 ± 1.5% of the time; held-out labellers agreed 77.3 ± 1.3%.Source: Ouyang et al., 2022
  4. RLHF with PPO

    Optimise the reward

    What it is
    Reinforcement learning from human feedback: the policy writes answers, the reward model scores them, and PPO nudges the policy towards higher-scoring answers. A KL penalty keeps it close to the SFT model. Each answer is an episode and each token is an action.
    When to use it
    Aligning a chat model with human preferences on helpfulness and harmlessness.
    Key figures
    • PPO alternates between sampling data and optimising a clipped surrogate objective, which allows several epochs of minibatch updates on the same samples.Source: Schulman et al., 2017
    1. Four models in memory

      Policy, ref, RM, critic

      What it is
      PPO-based RLHF holds four LLM-sized models: the trainable policy and critic, with gradients and optimiser states, and the frozen reference and reward model. That is why RLHF needs far more GPU memory than SFT, and why GRPO drops the critic and DPO drops the reward model and the RL loop.
      When to use it
      Estimating GPUs for an RLHF run, and the opening line of any PPO versus GRPO comparison.
      1. Policy π_θ

        The model being trained

        What it is
        The LLM being trained, started from the SFT model. It generates the responses, one token (action) at a time, and it is the only one of the four models that gets deployed.
        When to use it
        The checkpoint you ship after RLHF.
        AI angle
        Trainable: it needs weights, gradients and optimiser states in memory, plus a fast generation engine for rollouts.
      2. Reference π_ref

        Frozen SFT copy

        What it is
        A frozen copy of the SFT model. Its token probabilities are compared with the policy's to compute the KL penalty, which measures how far training has moved the policy.
        When to use it
        Anchoring the policy so it stays fluent and does not drift into reward-model exploits.
        AI angle
        Frozen: forward passes only, so it costs weights and activations but no gradients or optimiser states.
      3. Reward model r_φ

        Scores the full answer

        What it is
        The frozen reward model trained on preferences. It scores each complete response once, at the last token, and that score becomes the reward of the final action.
        When to use it
        Turning human preferences into a reward the RL loop can query for every sample.
        AI angle
        Frozen during PPO, and it can be smaller than the policy to save memory: InstructGPT paired a 6B reward model with policies up to 175B.
      4. Critic V_ψ

        Predicts future reward

        What it is
        A value model that estimates, at every token, the reward still to come. PPO uses it as a baseline: the advantage is how much better an action turned out than the critic expected.
        When to use it
        Turning one end-of-answer score into credit for each token.
        AI angle
        Trainable and as large as an LLM, so it adds another set of weights, gradients and optimiser states; GRPO removes it.
        Key figures
        • InstructGPT initialised the value function from the reward model.Source: Ouyang et al., 2022
    2. Rollout

      Generate, then score

      What it is
      A batch of prompts is sampled and the policy generates responses. Every token is stored with its log-probability under the policy (π_old) and the reference, plus the critic's value. The reward model then scores each finished response.
      When to use it
      The data-collection half of every PPO iteration, run on a fast generation engine.
    3. Per-token KL penalty

      Stay near the SFT model

      What it is
      Each token's reward includes −β times the log ratio between policy and reference, and the reward-model score is added at the last token. A larger β keeps the policy closer to the SFT model; a smaller β lets it chase the reward harder.
      When to use it
      Tuning the trade-off between reward gain and drift; the first defence against reward hacking.
      In code
      r_t = r − β·log(π_θ / π_ref)
      r_t = r_φ(x, y)·[t = T] − β·log(π_θ(a_t|s_t) / π_ref(a_t|s_t))
      J = E[r_φ(x, y)] − β·KL(π_θ(·|x) ‖ π_ref(·|x))
    4. Returns and advantages

      Better than expected?

      What it is
      The return is the discounted sum of rewards from a token to the end of the answer. The advantage compares what happened with what the critic expected: positive means make this token more likely, negative means less likely.
      When to use it
      Explaining what signal actually reaches each token in PPO.
      In code
      R_t = Σ_{k≥0} γ^k · r_{t+k}
      A(s_t, a_t) = Q(s_t, a_t) − V(s_t)
      Â_t > 0 → raise π_θ(a_t|s_t);  Â_t < 0 → lower it
    5. TD error and GAE

      λ: bias vs variance

      What it is
      The TD error δ_t compares the critic's estimate with one real reward plus the next estimate. GAE adds up future TD errors with weights (γλ)^l. With λ = 0 it trusts the critic (low variance, more bias); with λ = 1 it uses the full return (no critic bias, high variance).
      When to use it
      Computing PPO advantages and the critic's training targets.
      In code
      δ_t = r_t + γ·V(s_{t+1}) − V(s_t)
      Â_t = Σ_l (γλ)^l · δ_{t+l}
      λ = 0 → Â_t = δ_t;  λ = 1 → Â_t = R_t − V(s_t)
      Value target: R̂_t = Â_t + V(s_t)
      Key figures
      • GAE was introduced as an exponentially weighted estimator of the advantage, with λ trading bias against variance.Source: Schulman et al., 2015
    6. Probability ratio

      New vs old policy

      What it is
      ρ_t divides the current policy's probability of a token by its probability under the policy that generated the rollout. It measures how far an update has moved, and it lets PPO reuse the same samples for several gradient steps.
      When to use it
      Computed from the log-probabilities stored during the rollout.
      In code
      ρ_t = π_θ(a_t|s_t) / π_old(a_t|s_t)
      ρ_t = exp(log π_θ(a_t|s_t) − log π_old(a_t|s_t))
    7. Clipped objective

      Small, safe steps

      What it is
      PPO multiplies the advantage by the ratio, clips the ratio to [1−ε, 1+ε] and keeps the smaller of the clipped and unclipped terms. Once a token's probability has moved far enough in the helpful direction, the gradient stops pushing, so one batch cannot wreck the policy.
      When to use it
      The core PPO line to write in an exam, and why PPO stays stable without a trust-region solver.
      In code
      L_CLIP = E_t[min(ρ_t·Â_t, clip(ρ_t, 1−ε, 1+ε)·Â_t)]
      Â_t > 0: no extra gain once ρ_t > 1+ε
      Â_t < 0: no extra gain once ρ_t < 1−ε
      Key figures
      • In the PPO paper's comparison of surrogate objectives, clipping with ε = 0.2 scored best.Source: Schulman et al., 2017
    8. Value loss and update

      Backprop policy + critic

      What it is
      The critic learns to predict the return with a squared error, and an entropy bonus keeps the policy exploring. Backpropagation sends the clipped-objective and entropy gradients into the policy and the value-loss gradient into the critic; the reference and reward model stay frozen. After a few epochs over the rollout, a new rollout starts.
      When to use it
      Closing the PPO loop: what is trained, what stays frozen, when new data is collected.
      In code
      L_VF = (V_ψ(s_t) − R̂_t)²
      S = entropy of π_θ(·|s_t)
      L = E_t[L_CLIP − c₁·L_VF + c₂·S]   # maximised
      loss = −L → loss.backward() → optimizer.step()
    9. InstructGPT

      The reference recipe

      What it is
      OpenAI's 2022 paper that made SFT, a reward model and PPO the standard recipe for instruction-following models. Its PPO-ptx variant also mixed pretraining gradients into PPO to limit regressions on public benchmarks.
      When to use it
      The paper to cite when explaining classic RLHF.
      Key figures
      • Outputs of the 1.3B InstructGPT model were preferred to those of the 175B GPT-3, despite 100× fewer parameters.Source: Ouyang et al., 2022
      • The PPO dataset had 31k training prompts, taken only from the API and used without human labels.Source: Ouyang et al., 2022
  5. RLVR: verifiable rewards

    Code checks the answer

    What it is
    Reinforcement Learning with Verifiable Rewards: a program checks each answer and returns the reward, so no learned reward model is needed. It suits tasks with an objective test of success, such as maths answers or code that must pass tests.
    When to use it
    Training reasoning, maths and coding skills where correctness can be checked automatically.
    1. Programmatic verifier

      Replaces the reward model

      What it is
      A function that receives the model's answer and returns a reward, usually 1 for correct and 0 for wrong. It is cheap, exact and consistent, but it only measures what it was written to check.
      When to use it
      Any task where you can write the check: tests, known answers, schemas or constraints.
      In code
      def verify(solution):
          tests = [(solution(2, 3), 5), (solution(10, 5), 15), (solution(-1, 1), 0)]
          return int(all(a == e for a, e in tests))
      1. Maths answers

        Compare the final answer

        What it is
        The verifier extracts the final answer (for example from a \boxed{} expression), normalises it and compares it with the known answer, or recomputes it. Reward 1 if equal, else 0.
        When to use it
        Maths word problems and competition questions with a single known answer.
        In code
        r = int(normalise(extract_answer(output)) == normalise(gold))
      2. Code with unit tests

        Run the tests

        What it is
        The generated function runs against unit tests in a sandbox. Reward 1 if every test passes, or the fraction of tests passed for a denser signal; crashes and timeouts score 0.
        When to use it
        Coding assistants and programming competition problems.
        In code
        r = passed / total   # or int(passed == total)
      3. SQL queries

        Compare result sets

        What it is
        The generated query runs on a test database and its result set is compared with the result of a reference query. Comparing results instead of SQL text accepts any correct way to write the query.
        When to use it
        Text-to-SQL assistants over a known schema.
        In code
        r = int(sorted(run(pred_sql)) == sorted(run(gold_sql)))
      4. Logic puzzles

        Check the known solution

        What it is
        The answer is compared with the known solution, or every rule of the puzzle is checked directly, as with a Sudoku grid. Reward 1 if solved, else 0.
        When to use it
        Training multi-step reasoning on puzzles whose solutions can be generated and checked.
      5. Structured output

        Validate the schema

        What it is
        The output is parsed and validated against a JSON Schema: required fields, types and allowed values. Reward 1 if valid, else 0, or partial credit per correct field.
        When to use it
        Extraction and tool-calling models that must return machine-readable JSON.
        In code
        jsonschema.validate(json.loads(output), schema)   # raises if invalid
      6. LLM-as-judge

        A softer verifier

        What it is
        Another model grades the answer against a rubric or a reference answer and returns pass/fail or a score. It covers tasks code cannot check, but it is noisier, costs inference and can be fooled like a reward model.
        When to use it
        Open-ended answers that have a reference but no exact match, such as summaries or explanations.
        AI angle
        A judge is a learned model again, so its biases and blind spots can be exploited; keep a deterministic check wherever one exists.
    2. Binary, partial, format

      Shaping the reward

      What it is
      Binary rewards (1/0) are clean but sparse: a hard prompt gives no signal until the model solves it. Partial rewards, such as the fraction of tests passed, are denser but easier to game. A format reward adds credit for the required structure, such as reasoning inside think tags.
      When to use it
      Choosing the reward for a new verifiable task.
      In code
      r = 1 if verify(answer) else 0
      r = tests_passed / tests_total
      r = r_accuracy + r_format
      Key figures
      • DeepSeek-R1-Zero used two rule-based rewards: accuracy (a correct final answer, or code that passes test cases) and format (thinking placed between <think> and </think> tags).Source: DeepSeek-AI, 2025 (DeepSeek-R1)
    3. Verifier hacking

      Passing weak tests

      What it is
      The policy optimises whatever the verifier rewards. It can hard-code the expected outputs of a few visible tests, special-case inputs, or print an answer in the right format without solving the task. Hidden and varied tests, sandboxing and spot checks by hand reduce it.
      When to use it
      Reviewing RLVR results where pass rates jump suspiciously fast.
    4. The rest of PPO stays

      Only the reward changes

      What it is
      Only the source of the reward changes: the verifier's score replaces r_φ at the last token. The rollout, KL penalty, returns, critic, GAE advantages, clipped loss and backpropagation work exactly as in RLHF, or GRPO replaces the critic with group baselines.
      When to use it
      Turning an RLHF training stack into an RLVR one by swapping the reward function.
      In code
      r_T = verify(x, y) − β·log(π_θ(a_T|s_T) / π_ref(a_T|s_T))
    5. Tülu 3

      Where the name comes from

      What it is
      Ai2's open post-training recipe, which introduced the term RLVR. Its pipeline is SFT, then DPO, then RLVR, and it ran RLVR with PPO, giving a reward only when the answer is verifiably correct.
      When to use it
      An open, reproducible reference when designing an RLVR stage.
      Key figures
      • Tülu 3 applied RLVR to maths (GSM8K, MATH) and to precise instruction following with verifiable constraints (IFEval).Source: Lambert et al., 2024
    6. DeepSeek-R1

      Rule rewards + GRPO

      What it is
      DeepSeek-R1-Zero was trained with GRPO and rule-based rewards directly on the base model, with no SFT first, and learned long step-by-step reasoning. DeepSeek-R1 then added cold-start SFT data; its final RL stage combined rule-based rewards for reasoning prompts with reward models for general prompts.
      When to use it
      The best-known evidence that verifiable rewards can teach reasoning at scale.
      Key figures
      • Through RL alone, DeepSeek-R1-Zero raised its AIME 2024 pass@1 from 15.6% to 71.0%.Source: DeepSeek-AI, 2025 (DeepSeek-R1)
  6. GRPO and DPO

    No critic, or no RL

    What it is
    Two lighter alternatives to PPO-based RLHF. GRPO keeps online RL but drops the critic by comparing answers within a group. DPO drops the reward model and the RL loop and learns offline from preference pairs.
    When to use it
    Cutting memory and complexity when four-model PPO is too heavy.
    1. GRPO

      Group-relative, no critic

      What it is
      Group Relative Policy Optimisation samples G answers per prompt, scores them all and uses the group's mean and spread as the baseline instead of a critic. It keeps PPO's clipped ratio and adds the KL to the reference directly to the loss.
      When to use it
      RL with verifiable rewards on reasoning tasks, where sampling several answers per prompt is natural.
      In code
      for each prompt q: sample o_1 … o_G ~ π_old(·|q)
      r_i = reward(q, o_i)   # no critic V_ψ
      Key figures
      • DeepSeekMath introduced GRPO: it forgoes the critic and estimates the baseline from group scores, cutting training resources compared with PPO.Source: Shao et al., 2024
      • DeepSeekMath 7B scored 51.7% on the competition-level MATH benchmark without external toolkits or voting.Source: Shao et al., 2024
    2. Group-relative advantage

      Score vs group mean

      What it is
      Each answer's advantage is its reward minus the group mean, divided by the group's standard deviation, and every token of that answer gets the same value. If all G answers get the same reward, every advantage is zero and the prompt teaches nothing.
      When to use it
      Explaining how GRPO gets a baseline without a value model, and why prompts that are too easy or too hard are wasted.
      In code
      Â_i = (r_i − mean(r_1, …, r_G)) / std(r_1, …, r_G)
      Â_{i,t} = Â_i   for every token t of answer o_i
    3. KL in the loss

      Not in the reward

      What it is
      PPO-based RLHF subtracts the KL penalty from each token's reward. GRPO instead adds a KL term to the loss, estimated per token with an unbiased estimator, so the advantage reflects only the task reward.
      When to use it
      Writing the GRPO objective and contrasting it with PPO's reward shaping.
      In code
      J_GRPO = E[(1/G) Σ_i (1/|o_i|) Σ_t (min(ρ_{i,t}·Â_{i,t}, clip(ρ_{i,t}, 1−ε, 1+ε)·Â_{i,t}) − β·D_KL[π_θ ‖ π_ref])]
      D_KL[π_θ ‖ π_ref] = π_ref/π_θ − log(π_ref/π_θ) − 1
    4. DPO

      RLHF without RL

      What it is
      Direct Preference Optimisation trains the policy straight on chosen and rejected pairs with a classification-style loss. There is no reward model, no sampling during training and no critic: only the policy and a frozen reference.
      When to use it
      Preference tuning with fixed pairwise data and modest compute.
      Key figures
      • The optimal policy of the KL-constrained RLHF objective can be written in closed form, so the reward can be expressed through the policy itself: "your language model is secretly a reward model".Source: Rafailov et al., 2023
      • In the paper's experiments, DPO beat PPO-based RLHF at controlling sentiment and matched or improved response quality in summarisation and single-turn dialogue.Source: Rafailov et al., 2023
    5. DPO loss

      Implicit reward margin

      What it is
      The loss raises the log-probability ratio (policy over reference) of the chosen answer relative to the rejected one. β·log(π_θ/π_ref) acts as an implicit reward, and β sets how far the policy may move from the reference.
      When to use it
      Writing the DPO objective and comparing it with the Bradley–Terry reward-model loss.
      In code
      L_DPO = −log σ(β·log(π_θ(y_w|x)/π_ref(y_w|x)) − β·log(π_θ(y_l|x)/π_ref(y_l|x)))
      Implicit reward: r̂(x, y) = β·log(π_θ(y|x) / π_ref(y|x))
    6. PPO, GRPO or DPO?

      Which one when

      What it is
      DPO when you have preference pairs and want simple, stable offline training. GRPO when rewards are verifiable and you can sample several answers per prompt, especially for reasoning. PPO when you need online RL with a learned reward model and per-token credit from a critic, and can afford four models.
      When to use it
      The design answer to "which alignment method would you use, and why?".
  7. RLHF vs RLVR

    Preferred vs verified

    What it is
    RLHF learns what humans prefer; RLVR learns what can be verified by a program. Both can run on the same PPO or GRPO machinery: the difference is where the reward comes from.
    When to use it
    Choosing the reward source for a new post-training project.
    1. What each one learns

      Preference vs correctness

      What it is
      RLHF optimises for answers people like: helpful, clear, polite and safe. RLVR optimises for answers that pass a check: the right number, passing tests, a valid schema.
      When to use it
      The one-sentence answer to "what is the difference between RLHF and RLVR?".
    2. Reward source

      8/10 vs 1/0

      What it is
      In RLHF a reward model trained on human preferences returns a graded score, for example 8/10. In RLVR a verifier returns pass or fail, 1 or 0, sometimes with partial credit.
      When to use it
      Explaining why RLVR rewards are harder to fool but carry less nuance.
    3. Subjective vs objective

      Taste vs facts

      What it is
      Tone, helpfulness, style and safety are matters of judgement, so they need human preferences. Whether a calculation, a program or a query is correct is objective, so a program can decide it.
      When to use it
      Sorting the goals of a project into "needs people" and "needs a test".
    4. Components each needs

      Labellers, RM, verifier

      What it is
      Both need a policy. RLHF needs human labellers and usually a reward model, but no verifier. RLVR needs a verifier, and usually no reward model and no labellers. Both usually keep a critic when they use PPO; GRPO drops it. See the table below the map.
      When to use it
      Planning the team, the data and the GPU budget for each approach.
    5. Tasks that suit RLVR

      Checkable success

      What it is
      Maths with known answers, code with unit tests, SQL with expected results, logic puzzles, structured extraction against a schema, and instructions with checkable constraints such as length or format.
      When to use it
      Spotting where a verifier can replace expensive human labelling.
    6. Not always an LLM

      Code, tests or a judge

      What it is
      The verifier does not have to be an LLM: it can be deterministic code, a test suite or an LLM judge. Deterministic checks are the cheapest, exact and hardest to fool; an LLM judge is the fallback when no exact check exists.
      When to use it
      Picking the simplest reliable checker for a task.
    7. Not only maths and code

      Any measurable success

      What it is
      RLVR works for any task with a reliable, measurable success criterion: format rules, constraint satisfaction, valid tool calls, games with a win condition or questions with known answers. Maths and code are just the easiest cases.
      When to use it
      Finding RLVR opportunities in business tasks such as extraction, forms or workflows.
  8. Key exam points

    Answers to memorise

    What it is
    The one-line answers that come up most about post-training. Open the other branches for the formulas behind each one.
    When to use it
    Last-hour revision before an exam or a technical interview.
    1. PPO needs four models

      GRPO drops the critic

      What it is
      PPO-based RLHF holds a policy, a reference, a reward model and a critic in memory. GRPO drops the critic by comparing answers within a group; DPO also drops the reward model.
      When to use it
      Memory and cost questions about RLHF.
    2. Why the KL penalty?

      Stay near the SFT model

      What it is
      It keeps the policy close to the SFT model, so it stays fluent, keeps its general skills and is slower to drift into text that fools the reward model.
      When to use it
      Standard question on the RLHF objective.
    3. DPO = RLHF without RL

      No RM, no sampling

      What it is
      DPO optimises the same KL-constrained preference objective in closed form, straight from chosen and rejected pairs: no reward model, no rollouts, no critic.
      When to use it
      Comparison question between DPO and PPO.
    4. Reward hacking

      Proxy, not the goal

      What it is
      The policy optimises the proxy, not the goal: it finds outputs that a learned reward model or a weak verifier scores highly but that are not actually better.
      When to use it
      Failure-mode questions on RLHF and RLVR.
    5. RLVR in one line

      Verifier replaces the RM

      What it is
      A programmatic verifier replaces the learned reward model; the rollout, KL penalty, advantages, clipped loss and backpropagation stay the same. The term comes from Tülu 3.
      When to use it
      Definition question on RLVR.
    6. What does clipping do?

      Caps each update

      What it is
      PPO clips the probability ratio to [1−ε, 1+ε] and takes the minimum, so a token gains nothing from moving further once it has moved enough. Updates stay small and training stays stable.
      When to use it
      The classic "explain the PPO objective" question.
    7. GAE in one line

      λ: bias vs variance

      What it is
      GAE sums future TD errors weighted by (γλ)^l. λ near 0 trusts the critic (low variance, more bias); λ near 1 trusts the real returns (less bias, more variance).
      When to use it
      Advantage-estimation questions.
    8. What a reward model learns

      Only differences count

      What it is
      Under Bradley–Terry the reward model learns score differences: P(chosen beats rejected) = σ(r_w − r_l). The absolute scale is arbitrary, which is why rewards are normalised before RL.
      When to use it
      Reward-model loss questions.

Training pipelines, step by step

Pick a method, then press Next or click a card to follow the calculation. The numbers are one worked example, not a benchmark.

Supervised fine-tuning: one training step

The model learns to copy good answers. Only the answer tokens count in the loss; the prompt is context.

Step 1 of 6

Take a demonstration

One training example: a prompt and the answer we want.

Calculation

x = "2 + 3 = ?"
y = "5"
All steps as text

Supervised fine-tuning: one training step

  1. Take a demonstration. One training example: a prompt and the answer we want. x = "2 + 3 = ?" · y = "5"
  2. Tokenise and mask the prompt. Only the answer is learned; the prompt tokens are context. tokens = ["2", "+", "3", "= ?", "5"] · mask = [ 0, 0, 0, 0, 1 ]
  3. Forward pass. The policy scores every vocabulary token for the next position. z = f_θ(x, y_<t) (one score per vocabulary token)
  4. Probability of the right token. Softmax turns scores into probabilities. p(y_t) = exp(z_y) / Σ_j exp(z_j) · p("5") = 0.70
  5. Cross-entropy loss. The loss is small when the model is confident and right. L_SFT = −(1/T) Σ_t mask_t · log p(y_t | x, y_<t) · L = −log 0.70 = 0.357
  6. Update the weights. After the update p("5") rises and the loss falls; repeat over the dataset for 1 to 3 epochs. θ ← θ − η · ∇_θ L · LoRA: W′ = W + B·A (only A and B train)

Training the reward model from human preferences

  1. Sample two answers. The SFT model answers the same prompt twice. y_A, y_B ~ π_SFT(· | x)
  2. A person compares them. The labeler marks which answer is better. y_w = y_A (chosen) · y_l = y_B (rejected)
  3. Score both answers. The reward model gives each answer one number. r_w = r_φ(x, y_w) = 1.2 · r_l = r_φ(x, y_l) = 0.4
  4. Take the difference. The model should score the chosen answer higher. Δ = r_w − r_l = 1.2 − 0.4 = 0.8
  5. Probability the human agrees (Bradley–Terry). A sigmoid of the gap. P(y_w ≻ y_l) = σ(Δ) = 1 / (1 + e^−0.8) = 0.69
  6. Pairwise loss. Low when the reward model already prefers y_w. L_RM = −log σ(r_w − r_l) · L = −log 0.69 = 0.371
  7. Update the reward model. Over many pairs the reward model learns what people prefer; it is then frozen and used by PPO. φ ← φ − η · ∇_φ L_RM

RLHF with PPO: one update, four models

  1. Roll out an answer. The current policy answers the prompt; its log-probabilities are stored as π_old. y ~ π_θ(· | x) · log π_old(y | x) = −12.1
  2. Reward model scores it. One scalar for the whole answer, given at the last token. r = r_φ(x, y) = 0.80
  3. Reference model: how far did we drift?. The frozen SFT model scores the same tokens. log π_ref(y | x) = −12.6 · KL ≈ log π_θ − log π_ref = −12.1 − (−12.6) = 0.5
  4. Reward with KL penalty. Drifting away costs reward, so the policy cannot exploit the reward model with strange text. r_total = r − β · KL · = 0.80 − 0.1 × 0.5 = 0.75
  5. Critic predicts the baseline. What reward does the policy usually get here? V_ψ(x) = 0.60
  6. Advantage. Better than expected, so this answer should become more likely. Per token, GAE spreads this over the sequence. Â = R − V = 0.75 − 0.60 = +0.15 · per token: δ_t = r_t + γ·V(s_t+1) − V(s_t) · Â_t = Σ_l (γλ)^l · δ_t+l
  7. Probability ratio. PPO reuses the batch for several gradient steps; after a few, the policy has moved. ρ = exp(log π_θ − log π_old) = exp(0.262) = 1.30
  8. Clip the update. With ε = 0.2 the ratio counts at most 1.2, so the gain from this answer is capped. clip(1.30, 1 − 0.2, 1 + 0.2) = 1.20 · L_CLIP = min(ρ·Â, clip(ρ)·Â) · = min(1.30 × 0.15, 1.20 × 0.15) = min(0.195, 0.180) = 0.180
  9. Losses. Minimise minus the objective; the critic learns the real return. L_policy = −0.180 · L_value = (R − V)² = (0.75 − 0.60)² = 0.0225 · L = L_policy + c₁·L_value − c₂·entropy
  10. Backpropagate. Policy and critic are updated; reward model and reference stay frozen. Four models sit in memory. θ ← θ − η · ∇_θ L_policy · ψ ← ψ − η · ∇_ψ L_value

RLVR: the same PPO loop, a verifier instead of a reward model

  1. Roll out an answer. Prompts come with a way to check the answer (a known result or tests). y ~ π_θ(· | x) → "5"
  2. Verifier checks it. Deterministic code returns 1 for correct, 0 for wrong (or a partial score if designed that way). def verify(solution): · tests = [(solution(2, 3), 5), (solution(10, 5), 15), (solution(-1, 1), 0)] · return int(all(a == e for a, e in tests)) · r = int("5" == "5") = 1
  3. Reference model. Same KL as RLHF; many RLVR recipes keep a small β or none. KL ≈ log π_θ − log π_ref = 0.3
  4. Reward with KL penalty. r_total = 1 − 0.1 × 0.3 = 0.97
  5. Critic baseline. The critic predicts the chance the policy solves this prompt. V_ψ(x) = 0.70
  6. Advantage. A correct answer on a prompt the model often fails gets a big positive advantage. Â = 0.97 − 0.70 = +0.27
  7. Probability ratio. Inside the clip range this time. ρ = 0.90 (inside 0.8 … 1.2)
  8. Clip (no effect here). The ratio is within 1 ± 0.2, so the clip changes nothing. min(0.90 × 0.27, clip(0.90) × 0.27) = 0.243
  9. Losses. L_policy = −0.243 · L_value = (0.97 − 0.70)² = 0.0729
  10. Backpropagate. Three models in memory instead of four: policy, reference and critic. The verifier is just code. θ ← θ − η · ∇_θ L_policy · ψ ← ψ − η · ∇_ψ L_value

GRPO: no critic, the group is the baseline

  1. Sample a group. Several answers to the same prompt. y_1 … y_G ~ π_θ(· | x), G = 4 · answers = ["5", "6", "5", "5"]
  2. Score every answer. The verifier returns 1 for correct answers. r = [1, 0, 1, 1]
  3. Group statistics. The mean is the baseline the critic used to provide. μ = (1 + 0 + 1 + 1) / 4 = 0.75 · σ = √(((0.25)² × 3 + (0.75)²) / 4) = 0.433
  4. Group-relative advantage. The wrong answer gets a strong negative signal; the right ones a small positive one. Â_i = (r_i − μ) / σ · Â = [(1 − 0.75)/0.433, (0 − 0.75)/0.433, …] = [+0.58, −1.73, +0.58, +0.58]
  5. Clipped objective. On the first gradient step ρ = 1, so the objective is just Â. J_i = min(ρ·Â_i, clip(ρ, 1 − ε, 1 + ε)·Â_i) · ρ = 1 → J = Â = [+0.58, −1.73, +0.58, +0.58]
  6. KL to the reference. Subtracted inside the objective rather than from the reward. J_GRPO = (1/G) Σ_i (1/|y_i|) Σ_t [ J_i,t − β · D_KL(π_θ ‖ π_ref) ] · β = 0.04 (DeepSeekMath)
  7. Loss. Mean of the four objectives with ρ = 1 and KL ≈ 0 at the start. mean(J) = (0.58 − 1.73 + 0.58 + 0.58) / 4 ≈ 0.00 · L = −J_GRPO (gradients still flow: each answer is pushed by its own Â_i)
  8. Update only the policy. No critic to train: about half the memory of PPO, which is why DeepSeek-R1 used it for reasoning RL. θ ← θ − η · ∇_θ L

RLHF vs RLVR: which components each needs

From the author's study notes. Both approaches usually also keep a frozen reference model for the KL penalty.

ComponentRLHFRLVR
PolicyYesYes
Human labellersYesNot required
Reward modelUsually yesUsually no
VerifierNot requiredYes
Critic (value model)Usually yes (PPO)Usually yes with PPO; none with GRPO

RLVR verifiers by task

Every verifier is plain code except the last one; the reward is what the RL loop receives at the end of the answer.

TaskHow the verifier checksReward
MathsExtracts the final answer, normalises it and compares it with the known answer (or recomputes it)1 if equal, else 0
Python codeRuns the unit tests in a sandbox1 if all pass, else 0; or the fraction passed
SQLExecutes the query on a test database and compares the result set with the reference query's1 if the results match, else 0
Logic puzzlesCompares with the known solution or checks every rule of the puzzle1 if solved, else 0
Structured outputParses the output and validates it against a JSON Schema1 if valid, else 0; or partial credit per field
Open-ended answers (LLM-as-judge)Another model grades against a rubric or a reference answerPass/fail or a score; softer, noisier and easier to game

Sources, checked 2026-11-27: the papers on InstructGPT (Ouyang et al., 2022), PPO (Schulman et al., 2017), generalised advantage estimation (Schulman et al., 2015), paired comparisons (Bradley & Terry, 1952), DPO (Rafailov et al., 2023), DeepSeekMath and GRPO (Shao et al., 2024), DeepSeek-R1 (DeepSeek-AI, 2025), Tülu 3 (Lambert et al., 2024), LoRA (Hu et al., 2021) and QLoRA (Dettmers et al., 2023); the TRL, OpenRLHF and veRL repositories for the library card; the author's own study notes comparing RLHF and RLVR. Figures are the ones the papers report on their own setups, not a promise for yours. Library APIs change between releases: check the current docs.