Post-Training Primer
Introduction
How do we turn a language model that *just* predicts text into one that produces useful answers? Post-training offers a solution that addresses this question by learning from various types of data: ground truth demonstrations [1], preferences [1, 2], rollout rewards [3], and etc. Different post-training methods might look quite different on a surface, but nevertheless many (if not all of them) share a simple idea: change the probability of a response according to how good it is [8, 10].
Think of training a model as teaching someone to cook. Pretraining is like reading an enormous library of cookbooks: the learner absorbs ingredients, techniques, and patterns, but also encounters bad recipes and contradictory or unclear advice. Supervised fine-tuning is like following a chef’s worked examples, learning what a well-prepared dish should look like and how to make it. Reward-based training is like cooking your own dishes and having them judged: instead of being given the recipe to imitate, you use feedback on the result to adjust what you try next. On-policy distillation (OPD) is like having the chef beside you as you try your own recipe: the learner generates the steps, while the chef provides guidance at each step. Likewise, the student model generates its own responses and learns to match a teacher’s next-token distribution along those responses [9].
Training pipelines typically separate pretraining and post-training, with the former preceding the latter—and for good reason. Pretraining builds a broad foundation from large amounts of text, while post-training uses more targeted supervision to shape how the model applies that foundation. Returning to the cooking analogy, it is easier to refine someone’s dishes once they already know what ingredients and techniques are available.
In this post, we move from that intuition to the mechanics of post-training. We first connect learning from demonstrations and rewards through a shared view of probability updates, then derive policy gradients [4, 5] and build toward PPO [3] and GRPO [8]. Along the way, we will explain what baselines, advantages [7], and probability ratios contribute, and how they fit together in practical language-model training [1].
Mechanics of Post-Training
The cooking analogy gives us several ways to teach a model. To compare them mathematically, we need to keep four choices separate: 1) which responses and prefixes we train on, 2) what feedback we receive, 3) how that feedback weights an update, and 4) what limits the update. A loss function alone does not fully describe a training method: the responses and prefixes used to compute it matter too. Meanwhile, many different objectives reuse the same building block—the gradient of a token’s log probability. We will derive this building block first, then show how demonstrations, preferences, rewards, and teacher predictions use it differently [8, 10].
For an autoregressive model, a recurring building block is
\[g_\theta(q,o_{<t},a)=\nabla_\theta\log\pi_\theta(a\mid q,o_{<t}).\]One gradient update often combines many such vectors, with weights supplied by demonstrations, preferences, rewards, or a teacher. This does not necessarily make all methods policy-gradient algorithms, though it gives us a common language for deriving their differences.
For orientation, the method sections follow this route: demonstrations, preferences, PPO, GRPO and reasoning, interactive agents, and distillation.
State, Action, and Reward
To connect post-training with reinforcement learning, we need to describe three things: what the model sees, what it chooses, and what feedback it receives. We start with an episodic Markov decision process, where an agent interacts with an environment until the episode ends. The state contains the information needed to determine the distribution of the next state and reward, given an action.
At step \(t\), the agent is in state \(s_t\), chooses an action \(a_t\), and transitions to \(s_{t+1}\). We write \(r_t\) for the reward received after that action. An episode with \(T\) actions produces the trajectory
\[\tau=(s_0,a_0,r_0,s_1,a_1,r_1,\ldots,s_T).\]The agent’s choices are governed by its policy: a distribution over actions conditioned on the current state,
\[\pi_{\theta}(a_t\mid s_t),\]where \(\theta\) denotes the trainable parameters. Changing these parameters changes which actions the agent is likely to take.
Sparse rewards, dense supervision
In outcome-supervised GRPO, the task reward arrives only after the complete rollout; the intermediate rewards are zero. That response-level score is then normalized within the group and used to weight updates across its tokens [8].
SFT, OPD, and OPSD provide a learning signal at each token. SFT supplies the target token at each demonstration prefix. OPD supplies a teacher's next-token distribution at student-generated prefixes; OPSD obtains that distribution from the model itself conditioned on privileged information, such as a verified solution [9, 11]. These are token-level supervision signals, rather than necessarily environment rewards. GRPO still updates individual tokens, and process-supervised GRPO variants can also use intermediate rewards.
A reward scores one step; the return scores the whole trajectory. For now, we use a finite, undiscounted return, so rewards at different steps enter with equal weight:
\[R(\tau)=\sum_{t=0}^{T-1}r_t.\]Because the policy samples actions, repeated episodes can produce different trajectories and returns. Training aims to maximize the return averaged over those trajectories, including the randomness in initial states and environment transitions:
\[J(\theta)=\mathbb{E}_{\tau\sim\pi_{\theta}}[R(\tau)].\]For an autoregressive language model, this setup has a concrete interpretation. We identify
\[s_t=(q,o_{<t}),\qquad a_t=o_t.\]The model sees the prompt and the response generated so far, chooses the next token, and moves to a state by appending that token. In this text-only setting, the transition is deterministic; the policy supplies the randomness. A reward might score the answer, such as whether it passes tests, or provide feedback at intermediate steps.
The probability of a complete response is the product of its token probabilities:
\[\pi_{\theta}(o\mid q) = \prod_{t=1}^{|o|}\pi_{\theta}(o_t\mid q,o_{<t}).\]For variable-length responses, the sequence includes the end-of-sequence token when stopping is sampled from the policy.
Log-Probability Gradient
Taking the logarithm of the sequence factorization gives
\[\log\pi_\theta(o\mid q) =\sum_{t=1}^{|o|}\log\pi_\theta(o_t\mid q,o_{<t}).\]Therefore,
\[\nabla_\theta\log\pi_\theta(o\mid q) =\sum_{t=1}^{|o|}g_\theta(q,o_{<t},o_t).\]At a fixed prefix, let the next-token probabilities be a softmax over logits. For a target or sampled token \(a\), we have:
\[\pi_j=\frac{\exp z_j}{\sum_k\exp z_k}, \qquad \log\pi_a=z_a-\log\sum_k\exp z_k, \qquad \frac{\partial\log\pi_a}{\partial z_j} =\mathbf 1[j=a]-\pi_j.\]This is the local mechanism we will reuse. Maximizing a positively weighted log probability raises the selected token’s logit relative to the alternatives at that prefix; a negative weight reverses the direction. An actual parameter update also affects other prefixes, so this local calculation is not a guarantee about every output probability after a finite optimizer step.
One more identity follows from normalization. At a fixed state \(s\), the probabilities of all possible next tokens sum to one. Expanding the expectation of the log-probability gradient gives:
\(\nabla_\theta\log\pi_\theta(a\mid s)=\frac{\nabla_\theta\pi_\theta(a\mid s)}{\pi_\theta(a\mid s)}\)?
The derivative of the natural logarithm is
$$ \frac{d}{dx}\log x=\frac{1}{x},\qquad x>0. $$For a positive function \(f(\theta)\), the chain rule therefore gives
$$ \nabla_\theta\log f(\theta) =\frac{1}{f(\theta)}\nabla_\theta f(\theta). $$Taking \(f(\theta)=\pi_\theta(a\mid s)\), with the state and token held fixed, yields
$$ \nabla_\theta\log\pi_\theta(a\mid s) =\frac{\nabla_\theta\pi_\theta(a\mid s)}{\pi_\theta(a\mid s)}. $$Multiplying by \(\pi_\theta(a\mid s)\) cancels the denominator in the next step of the derivation.
\[\begin{aligned} \mathbb E_{a\sim\pi_\theta(\cdot\mid s)} [\nabla_\theta\log\pi_\theta(a\mid s)] &=\sum_a\pi_\theta(a\mid s)\nabla_\theta\log\pi_\theta(a\mid s)\\ &=\sum_a\pi_\theta(a\mid s) \frac{\nabla_\theta\pi_\theta(a\mid s)}{\pi_\theta(a\mid s)}\\ &=\sum_a\nabla_\theta\pi_\theta(a\mid s)\\ &=\nabla_\theta\sum_a\pi_\theta(a\mid s)\\ &=\nabla_\theta 1=0. \end{aligned}\]
This zero-score identity will remove past rewards, justify baselines, and simplify the reverse-KL gradient later.
Policy Gradient
So far, we have derived how token probabilities change with the model parameters. To learn from demonstrations, we can directly increase the probability of the supplied tokens. But suppose the model generates a program and receives a reward of one if it passes the tests, or zero otherwise. This feedback evaluates the result without supplying the tokens the model should have generated.
Ordinary backpropagation cannot pass through discrete token sampling and test execution to tell us how to change the model’s parameters. Yet those parameters determine which programs are likely to be sampled, so they still affect the expected reward. We need a way to differentiate that expectation without differentiating through the sampled program or its evaluation.
The policy gradient provides this connection: it expresses the gradient of expected return as an average of log-probability gradients weighted by returns. The model supplies the differentiable log probabilities, while the evaluator only needs to supply a score for each sampled attempt.
REINFORCE
The probability of a trajectory is
\[p_{\theta}(\tau) = p(s_0) \prod_{t=0}^{T-1} \pi_{\theta}(a_t\mid s_t) P(s_{t+1}\mid s_t,a_t).\]The initial-state distribution and environment dynamics do not depend on the policy parameters. Starting from the objective,
\[J(\theta)=\sum_{\tau}p_{\theta}(\tau)R(\tau),\]we differentiate:
\[\nabla_{\theta}J(\theta) = \sum_{\tau}\nabla_{\theta}p_{\theta}(\tau)R(\tau).\]Use the log-derivative identity
\[\nabla_{\theta}p_{\theta}(\tau) = p_{\theta}(\tau)\nabla_{\theta}\log p_{\theta}(\tau).\]Then
\[\nabla_{\theta}J(\theta) = \mathbb{E}_{\tau\sim\pi_{\theta}} \left[ R(\tau)\nabla_{\theta}\log p_{\theta}(\tau) \right].\]One gradient, many algorithms
The blue term is the log-probability gradient introduced earlier: a shared building block of these optimization algorithms. It points in the direction that locally increases the log probability of the selected action. Here, REINFORCE weights it by the return; later, advantages and probability ratios will shape how this same building block contributes to an update.
Because only the policy factors depend on \(\theta\),
\[\nabla_{\theta}\log p_{\theta}(\tau) = \sum_{t=0}^{T-1} \color{#2563eb}{\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t)}.\]Therefore,
\[\nabla_{\theta}J(\theta) = \mathbb{E} \left[ R(\tau) \sum_{t=0}^{T-1} \color{#2563eb}{\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t)} \right].\]This is the score-function or REINFORCE estimator [4]. It is the central mechanism behind the methods discussed below. We do not differentiate through the sampled discrete action. Instead, we differentiate the log-probability of having sampled it.
To see how this gradient estimator translates into learning, let’s work through a simple example. In the notebook below, we apply REINFORCE to a six-armed bandit, where each action produces a noisy reward with a different mean. A softmax policy starts with equal probabilities, samples an arm, and minimizes \(-r\log\pi_\theta(a)\) after observing its reward. There is only one action per episode, so the return is simply that reward.
Reward-to-Go and Discounting
The previous formula multiplies every policy-score term by the entire trajectory return. At first this seems to imply that an action at time \(t\) should be credited for a reward received at time \(k\) for \(k < t\). Causally, that cannot be right: the later action cannot change an event that has already happened.
The mathematical statement is exactly
\[\mathbb{E} \left[ r_0\nabla_{\theta}\log\pi_{\theta}(a_{10}\mid s_{10}) \right] =0.\]More generally, for every \(k\lt t\),
\[\mathbb{E} \left[ r_k\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right] =0.\]To show why these terms vanish, let \(H_t\) denote everything known immediately before sampling \(a_t\):
\[H_t=(s_0,a_0,r_0,\ldots,s_t).\]For \(k\lt t\), the reward \(r_k\) is already contained in \(H_t\). It is therefore fixed after conditioning on \(H_t\). By the law of total expectation,
\[\begin{aligned} &\mathbb{E} \left[ r_k\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right] \\ &=\mathbb{E} \left[ \mathbb{E} \left[ r_k\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \mid H_t \right] \right] \\ &=\mathbb{E} \left[ r_k \mathbb{E} \left[ \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \mid H_t \right] \right]. \end{aligned}\]Conditional on the history, the only remaining randomness in this expression is the newly sampled action
\[a_t\sim\pi_{\theta}(\cdot\mid s_t).\]Conditioning on the history fixes \(s_t\). By the zero-score identity derived earlier,
\[\mathbb{E} \left[ \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \mid H_t \right] =0.\]Substituting this into the conditional expectation proves the claim.
We can now remove the past-reward terms from the policy gradient. Write
\[g_t=\color{#2563eb}{\nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t)}.\]Then
\[\begin{aligned} \nabla_{\theta}J &= \sum_t \mathbb{E} \left[ \left(\sum_k r_k\right)g_t \right] \\ &= \sum_t\sum_k\mathbb{E}[r_k g_t]. \end{aligned}\]Every term with \(k\lt t\) is zero. Consequently,
\[\begin{aligned} \nabla_{\theta}J &= \sum_t \mathbb{E} \left[ \left(\sum_{k=t}^{T-1}r_k\right)g_t \right] \\ &= \mathbb{E} \left[ \sum_t G_t \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right], \qquad \text{where} \quad G_t=\sum_{k=t}^{T-1}r_k. \end{aligned}\]Here, \(G_t\) is the reward-to-go for the undiscounted objective. If the objective is
\[J_{\gamma}(\theta) = \mathbb{E} \left[ \sum_{k=0}^{T-1}\gamma^k r_k \right],\]define the locally discounted reward-to-go
Why introduce discounting?
Discounting makes future rewards count less than immediate rewards. It can express a preference for near-term outcomes or a chance that the interaction terminates before a later reward arrives, and it limits the effective planning horizon. See Sutton and Barto, Sections 3.3–3.4 [76].Discounting can also reduce the variance of policy-gradient estimates by downweighting distant rewards, at the cost of bias relative to the undiscounted gradient; Schulman et al. discuss this tradeoff in Section 2 [7]. Here, we explicitly define a discounted objective: it is a different optimization problem from the undiscounted one.
The exact episodic gradient then contains the discount accumulated before time \(t\):
\[\nabla_{\theta}J_{\gamma} = \mathbb{E} \left[ \sum_t \gamma^t G_t^{(\gamma)} \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right].\]Discounting favors earlier rewards: with \(\gamma=0.9\), a reward of \(+1\) contributes \(1\) now but only \(0.9^{10}\approx0.35\) ten steps later. Downweighting distant rewards can also reduce gradient noise [7], but gives less credit to valuable delayed outcomes.
We can now extend the bandit example to a sequence of decisions. In the notebook below, an agent learns to balance a pole in CartPole using REINFORCE with discounted reward-to-go.
Baselines and Advantages
A high return can reflect a good action, an easy starting state, or luck. Even an action with no effect can receive a large update: its gradient contributions cancel in expectation, but imperfectly across finite batches. Subtracting a baseline, such as the expected return from the current state, measures how much better or worse the outcome was than expected. This can reduce fluctuations between updates without changing the expected policy gradient.
We write \(V^{\pi,\gamma}(s)\) for the expected discounted return from a state, and \(Q^{\pi,\gamma}(s,a)\) for the expected return after choosing a particular action there, following policy \(\pi\) afterward in both cases.
\[V^{\pi,\gamma}(s)=\mathbb{E}_{\pi}\!\left[G_t^{(\gamma)}\mid s_t=s\right], \qquad Q^{\pi,\gamma}(s,a)=\mathbb{E}_{\pi}\!\left[G_t^{(\gamma)}\mid s_t=s,\ a_t=a\right].\]Their difference is the advantage: how much better or worse that action is than the policy’s usual choice.
Subtracting a baseline preserves the expected policy gradient for the same reason we could remove past rewards. The zero-score identity says that, before sampling an action, its log-probability gradient has expectation zero. Multiplying by a baseline already determined at that point preserves this zero expectation. Let \(b(H_t)\) be any quantity known before sampling \(a_t\). Then
\[\underset{ \substack{ a_t\sim\pi_\theta(\cdot\mid s_t) } }{ \mathbb{E} } \left[ b(H_t) \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right] =0.\]Thus,
\[\nabla_{\theta}J = \mathbb{E}_{\tau\sim p_\theta} \left[ \sum_t \left(G_t-b(H_t)\right) \nabla_{\theta}\log\pi_{\theta}(a_t\mid s_t) \right].\]The baseline does not need to be constant. It can depend on the state or the full pre-action history. It must not depend on the current sampled action in a way that invalidates the zero-score argument.
Learning the baseline
If a learned baseline shares parameters with the policy, its value is normally detached in the actor loss. Otherwise, automatic differentiation adds a gradient through the baseline itself, which is not part of the policy-gradient identity above.
A natural baseline is the state-value function \(V^{\pi,\gamma}(s_t)\) introduced above: the discounted return we expect before choosing the next action. Subtracting it from the action value gives the advantage:
\[A^{\pi,\gamma}(s,a) = Q^{\pi,\gamma}(s,a)-V^{\pi,\gamma}(s).\]A positive advantage weights the update toward increasing the action’s probability; a negative advantage weights it toward decreasing that probability. A zero advantage contributes no policy-gradient update.
We now express the policy gradient in terms of the advantage of each action. We keep the discounted objective \(J_\gamma\), so each step retains its outer weight \(\gamma^t\). For a finite horizon, we include the time step in the state so that the value functions account for the remaining time.
Starting from the trajectory-level expression, we first isolate the contribution of each decision step:
\[\nabla_{\theta}J_{\gamma} = \sum_{t=0}^{T-1}\gamma^t \mathbb{E}_{\tau\sim p_\theta(\tau)} \left[ G_t^{(\gamma)} \nabla_{\theta} \log\pi_{\theta}(a_t\mid s_t) \right].\]The discounted return \(G_t^{(\gamma)}\) depends on the future trajectory after the action at step \(t\). We can therefore condition on the current state and action and take the expectation over the possible future trajectories:
\[\begin{aligned} \nabla_{\theta}J_{\gamma} &= \sum_{t=0}^{T-1}\gamma^t \mathbb{E}_{\tau\sim p_\theta(\tau)} \left[ \mathbb{E} \left[ G_t^{(\gamma)} \mid s_t,a_t \right] \nabla_{\theta} \log\pi_{\theta}(a_t\mid s_t) \right]. \end{aligned}\]By definition, the conditional expectation of the return is the action-value function:
\[Q^{\pi,\gamma}(s_t,a_t) = \mathbb{E} \left[ G_t^{(\gamma)} \mid s_t,a_t \right].\]Thus,
\[\nabla_{\theta}J_{\gamma} = \sum_{t=0}^{T-1}\gamma^t \mathbb{E}_{\tau\sim p_\theta(\tau)} \left[ Q^{\pi,\gamma}(s_t,a_t) \nabla_{\theta} \log\pi_{\theta}(a_t\mid s_t) \right].\]We can now subtract the state-value function without changing the expectation. For any state \(s_t\),
\[\underset{ a_t\sim\pi_\theta(\cdot\mid s_t) }{ \mathbb{E} } \left[ V^{\pi,\gamma}(s_t) \nabla_{\theta} \log\pi_{\theta}(a_t\mid s_t) \right] = 0.\]Subtracting this baseline gives the advantage function:
\[A^{\pi,\gamma}(s_t,a_t) = Q^{\pi,\gamma}(s_t,a_t)-V^{\pi,\gamma}(s_t).\]The discounted episodic policy gradient can therefore be written in advantage form [5]:
\[\nabla_{\theta}J_{\gamma} = \sum_{t=0}^{T-1}\gamma^t \mathbb{E}_{\tau\sim p_\theta(\tau)} \left[ A^{\pi,\gamma}(s_t,a_t) \nabla_{\theta} \log\pi_{\theta}(a_t\mid s_t) \right].\]In practice, the exact advantage is unknown because \(V^{\pi,\gamma}\) and \(Q^{\pi,\gamma}\) average over possible future trajectories. We therefore replace it with an estimate. We discuss how to train the value estimator and compute advantages in the PPO section below.
Importance Weighting
So far, our gradient estimates assume that trajectories come from the policy we are updating. But collecting new trajectories can be expensive: a language model must generate responses, and those responses may need to be scored or executed in an environment. We would therefore like to take several optimization steps using the same batch. After the first step, however, the policy has changed, while the batch still reflects its earlier behavior / policy.
Importance weighting accounts for this mismatch. Let \(\pi_{\mathrm{old}}\) be the policy that collected the batch and \(\pi_\theta\) the policy we are optimizing. On this fixed batch, the policy-gradient update can be implemented by minimizing the actor loss
\[\mathcal L_{\mathrm{actor}}(\theta) = -\mathbb E_{\tau\sim p_{\mathrm{old}}(\tau)} \left[ \sum_{t=0}^{T-1}\gamma^t A^{\pi_{\mathrm{old}},\gamma}(s_t,a_t) \log\pi_\theta(a_t\mid s_t) \right].\]We use the exact advantage here and hold it fixed during differentiation. Later, we will replace it with estimates constructed from sampled rewards and learned value functions, as discussed in the PPO section. The negative gradient of this loss matches the policy gradient at \(\theta=\theta_{\mathrm{old}}\).
When reusing a batch, we treat the old policy’s advantages as a useful guide for several updates. These advantages evaluate an action assuming that subsequent actions follow the old policy. They therefore become less reliable as the updated policy moves further away. Importance ratios adjust how we weight actions under the new policy; the advantages remain those computed for the old policy.
Likelihood Ratios
To see where the importance ratio enters, start with the gradient of the actor loss. At a fixed state \(s\), its contribution is
\[-\mathbb E_{a\sim\pi_{\mathrm{old}}(\cdot\mid s)} \left[ A^{\pi_{\mathrm{old}},\gamma}(s,a) \nabla_\theta\log\pi_\theta(a\mid s) \right].\]As the policy changes, we would like to weight actions according to their current probabilities. Keeping the old advantage fixed, the corresponding gradient contribution is
\[-\mathbb E_{a\sim\pi_\theta(\cdot\mid s)} \left[ A^{\pi_{\mathrm{old}},\gamma}(s,a) \nabla_\theta\log\pi_\theta(a\mid s) \right].\]This changes the action distribution in the update; it is not an equality with the original actor-loss gradient away from the old policy. To compute this contribution using old-policy samples, multiply and divide by their sampling probabilities:
\[\begin{aligned} &-\sum_a\pi_\theta(a\mid s) A^{\pi_{\mathrm{old}},\gamma}(s,a) \nabla_\theta\log\pi_\theta(a\mid s)\\ &=-\sum_a\pi_{\mathrm{old}}(a\mid s) \frac{\pi_\theta(a\mid s)}{\pi_{\mathrm{old}}(a\mid s)} A^{\pi_{\mathrm{old}},\gamma}(s,a) \nabla_\theta\log\pi_\theta(a\mid s). \end{aligned}\]Define the importance ratio
\[\color{#2563eb}{\rho_t(\theta)} = \frac{\pi_\theta(a_t\mid s_t)}{\pi_{\mathrm{old}}(a_t\mid s_t)}.\]Averaging over states visited by the old policy and restoring the discount weights gives the corrected gradient expression
\[-\mathbb E_{\tau\sim p_{\mathrm{old}}(\tau)} \left[ \sum_{t=0}^{T-1}\gamma^t \color{#2563eb}{\rho_t(\theta)} A^{\pi_{\mathrm{old}},\gamma}(s_t,a_t) \nabla_\theta\log\pi_\theta(a_t\mid s_t) \right].\]To implement this expression with backpropagation, observe that
\[\nabla_\theta\rho_t(\theta) = \rho_t(\theta)\nabla_\theta\log\pi_\theta(a_t\mid s_t).\]Differentiating the importance ratio
For a fixed sampled pair \((s_t,a_t)\), the old probability does not depend on \(\theta\). Using \(\nabla_\theta\pi_\theta=\pi_\theta\nabla_\theta\log\pi_\theta\),
\[\begin{aligned} \nabla_\theta\rho_t(\theta) &=\frac{\nabla_\theta\pi_\theta(a_t\mid s_t)} {\pi_{\mathrm{old}}(a_t\mid s_t)}\\ &=\frac{\pi_\theta(a_t\mid s_t)} {\pi_{\mathrm{old}}(a_t\mid s_t)} \nabla_\theta\log\pi_\theta(a_t\mid s_t)\\ &=\rho_t(\theta)\nabla_\theta\log\pi_\theta(a_t\mid s_t). \end{aligned}\]It is therefore the gradient of the importance-weighted surrogate loss
\[\mathcal L_{\mathrm{IS}}(\theta) = -\mathbb E_{\tau\sim p_{\mathrm{old}}(\tau)} \left[ \sum_{t=0}^{T-1}\gamma^t \color{#2563eb}{\rho_t(\theta)} A^{\pi_{\mathrm{old}},\gamma}(s_t,a_t) \right].\]At \(\theta=\theta_{\mathrm{old}}\), all ratios equal one, so the negative gradient of this surrogate matches the discounted policy gradient:
\[-\left.\nabla_\theta\mathcal L_{\mathrm{IS}}(\theta)\right|_{\theta=\theta_{\mathrm{old}}} = \left.\nabla_\theta J_\gamma(\theta)\right|_{\theta=\theta_{\mathrm{old}}}.\]The ratio corrects the action distribution at states sampled by the old policy. It does not fully correct the state-visitation distribution, which also changes when the policy changes. Methods such as TRPO [6] and PPO [3] address this issue by limiting policy changes.
Reference Policy
Keeping each policy update small helps us reuse a batch, but many small updates can still move the model far from its starting behavior. We may also want to preserve that behavior while improving reward. To express this preference, we introduce a fixed reference policy \(\pi_{\mathrm{ref}}\) and penalize deviations from it.
KL regularization limits drift from the reference policy, helping preserve useful behavior that the reward may not capture—even when correctness is verifiable. With learned rewards, it can also curb reward-model overoptimization, where higher predicted scores no longer reflect better responses [20, 21, 1].
What does KL regularization help with?
Ziegler et al. show a concrete failure: optimizing a sentiment score without KL regularization produces repetitive gibberish despite a high score (Appendix C, Table 10) [20]. InstructGPT reports worse human ratings with either zero or an excessively strong KL penalty than with a moderate penalty (Appendix E.7) [1].
The benefit depends on the setup. Gao et al. find that KL mainly limits optimization similarly to early stopping, without improving gold reward at a given policy distance (Section 3.6) [51]. Coste et al. find that a small KL penalty combined with conservative reward-model ensembles prevents overoptimization in their experiments; KL alone requires a stronger penalty and sacrifices performance (Section 5.2) [77].
The reference has a different role from \(\pi_{\mathrm{old}}\): the old policy generated the current batch and is refreshed when we collect new rollouts; the reference stays fixed across updates. In RLHF, it is commonly the model obtained after supervised fine-tuning [1].
We can introduce this penalty directly into our discounted setting. At a state \(s\), the KL divergence compares the current and reference action distributions:
\[D_{\mathrm{KL}}\!\left(\pi_\theta(\cdot\mid s)\|\pi_{\mathrm{ref}}(\cdot\mid s)\right) = \mathbb E_{a\sim\pi_\theta(\cdot\mid s)} \left[ \log\frac{\pi_\theta(a\mid s)}{\pi_{\mathrm{ref}}(a\mid s)} \right].\]We subtract the sampled log-ratio from each reward:
\[\tilde r_t = r_t-\beta\log\frac{\pi_\theta(a_t\mid s_t)}{\pi_{\mathrm{ref}}(a_t\mid s_t)}, \qquad \beta>0.\]A larger \(\beta\) puts more weight on staying close to the reference. An individual log-ratio can be negative, but its expectation over actions at a fixed state—the KL divergence—is nonnegative.
The objective and reward-to-go keep the same discounted form:
\[J_{\gamma,\beta}(\theta) = \mathbb E_{\tau\sim p_\theta(\tau)} \left[\sum_{t=0}^{T-1}\gamma^t\tilde r_t\right], \qquad \tilde G_t^{(\gamma)} = \sum_{k=t}^{T-1}\gamma^{k-t}\tilde r_k.\]We now define the value functions using these adjusted returns and subtract them to obtain the regularized advantage:
\[\tilde A^{\pi,\gamma}(s,a) = \tilde Q^{\pi,\gamma}(s,a)-\tilde V^{\pi,\gamma}(s).\]The policy gradient therefore has the same form as before, with the adjusted advantage supplying the weight:
\[\nabla_\theta J_{\gamma,\beta}(\theta) = \mathbb E_{\tau\sim p_\theta(\tau)} \left[ \sum_{t=0}^{T-1}\gamma^t \tilde A^{\pi,\gamma}(s_t,a_t) \nabla_\theta\log\pi_\theta(a_t\mid s_t) \right].\]Why can the log-ratio act as a reward?
The adjusted reward depends on \(\theta\). For parameter-independent environment rewards and a fixed reference, differentiating it adds the term
\[\mathbb E_{\tau\sim p_\theta} \left[\sum_t\gamma^t\nabla_\theta\tilde r_t\right] = -\beta\sum_t\gamma^t \mathbb E_{\tau\sim p_\theta} \left[\nabla_\theta\log\pi_\theta(a_t\mid s_t)\right] =0.\]Each expected score is zero conditional on its state, by the zero-score identity. The remaining terms give the usual reward-to-go and advantage derivation. In the sampled actor loss, we hold the adjusted rewards and advantages fixed during backpropagation. This identity assumes trajectories are sampled from the current policy.
When collecting a batch with \(\pi_{\mathrm{old}}\), we compute the reward penalty using \(\pi_{\mathrm{old}}/\pi_{\mathrm{ref}}\) and keep the resulting advantages fixed during its updates. We then use the same importance-weighted surrogate:
\[\mathcal L_{\mathrm{IS},\beta}(\theta) = -\mathbb E_{\tau\sim p_{\mathrm{old}}(\tau)} \left[ \sum_{t=0}^{T-1}\gamma^t \rho_t(\theta) \tilde A^{\pi_{\mathrm{old}},\gamma}(s_t,a_t) \right].\]Supervised Fine-Tuning
A reward tells the model how well an attempt went. A demonstration goes further: it supplies a sequence of actions worth taking. This is especially useful when the current policy rarely produces a good solution on its own. Supervised fine-tuning (SFT) [1, 17] increases the probability of demonstrated responses, giving the model useful behavior to build on. InstructGPT [1], Llama 2 [90], and Tulu 3 [49] all use SFT before further preference-based training.
From the policy perspective, a demonstration tells us which action to encourage at each step. For a language model, this means increasing the probability of each target token given the demonstration’s preceding tokens—a procedure called teacher forcing. In RL terms, the training states are supplied by the demonstration rather than reached through the policy’s own sampled actions. The update uses the same log-probability gradient we derived earlier, but the demonstration supplies the direction of learning directly: we reinforce its tokens without estimating returns or advantages.
Log-Probability Gradient
Let \((q,o^*)\sim\mathcal D_{\mathrm{SFT}}\) be a prompt and its demonstrated response. Each target token \(a_t^*=o_t^*\) is an action, and \(s_t^*=(q,o_{<t}^*)\) is the state formed by the prompt and preceding demonstration tokens. We minimize the negative log-probability of the response:
\[\mathcal L_{\mathrm{SFT}}(\theta) = -\mathbb E_{(q,o^*)\sim\mathcal D_{\mathrm{SFT}}} \left[ \sum_{t=1}^{|o^*|}\log\pi_\theta(a_t^*\mid s_t^*) \right].\]Its negative gradient gives the direction of the update:
\[-\nabla_\theta\mathcal L_{\mathrm{SFT}} = \mathbb E_{(q,o^*)\sim\mathcal D_{\mathrm{SFT}}} \left[ \sum_{t=1}^{|o^*|} \nabla_\theta\log\pi_\theta(a_t^*\mid s_t^*) \right].\]Compare this with the discounted policy gradient we derived earlier:
\[\nabla_\theta J_\gamma = \mathbb E_{\tau\sim p_\theta} \left[ \sum_{t=0}^{T-1}\gamma^t A^{\pi,\gamma}(s_t,a_t) \nabla_\theta\log\pi_\theta(a_t\mid s_t) \right].\]Both updates use the same score vector \(\nabla_\theta\log\pi_\theta(a\mid s)\). SFT assigns each demonstrated token a positive coefficient of one; RL uses the advantage to decide whether to reinforce or discourage an action sampled from the policy. This also gives SFT a distribution-matching interpretation. At a demonstration state \(s\), let \(p_{\mathrm{data}}(a\mid s)\) describe the target-token distribution. Its cross-entropy with the policy satisfies
\[-\sum_a p_{\mathrm{data}}(a\mid s)\log\pi_\theta(a\mid s) = H(p_{\mathrm{data}}(\cdot\mid s)) + D_{\mathrm{KL}}\!\left(p_{\mathrm{data}}(\cdot\mid s)\|\pi_\theta(\cdot\mid s)\right).\]Entropy is constant with respect to \(\theta\), so SFT minimizes forward KL.
Eliciting Capabilities
Supervised Fine-Tuning can make pretrained capabilities easier to use and transfer additional skills through demonstrations [17, 64]. LIMA [17] illustrates how much can already be present before SFT. Fine-tuning a strong pretrained model on just 1,000 carefully curated examples produced useful instruction-following behavior and generalization to unseen tasks. This supports the authors’ hypothesis that much of the knowledge comes from pretraining, while alignment teaches how to present it. It does not establish that every SFT dataset merely changes style, or that a weaker model would learn equally much from those examples.
The demonstrations also determine which tasks and procedures receive practice. FLAN [13] and T0 [14] show that instruction tuning across task mixtures improves performance on unseen tasks. Scaling Instruction-Finetuned Language Models [15] extends this picture through larger task mixtures and chain-of-thought supervision. These results show that supervised training can improve generalization, although a benchmark gain alone does not tell us whether a skill was newly acquired or became easier to elicit.
Synthetic Supervision
Models can supply demonstrations as well as humans. Self-Instruct [16] generates and filters instruction examples, while Orca [18] and Distilling Step-by-Step [45] use teacher explanations to supervise smaller models. Such demonstrations can transfer methods the student rarely produces unaided: Yue et al. [64] find that distillation introduces reasonings beyond those observed in the student base model.
SFT can also establish useful behavior for later training. DeepSeek-R1 [38] uses cold-start supervision before RL and distills reasoning into smaller models. SFT Memorizes, RL Generalizes [93] finds that SFT establishes a usable output format, but its supervised models struggle with unseen rule and visual variants. Demonstrations can therefore provide a useful starting point without guaranteeing generalization.
The notebook below fine-tunes a small model on a handful of request-to-JSON examples, then compares held-out performance before and after SFT against a few-shot baseline.
Learning from Preferences
SFT tells the model what to imitate, but producing high-quality demonstrations can be expensive. An annotator must write a complete response: solve the task, choose the wording, organize the explanation, and check its accuracy. Long answers and specialist tasks make this especially time-consuming, and many prompts have several acceptable answers rather than a single ground-truth response.
Preference feedback can reduce this burden. The model generates candidate answers, and an evaluator compares them instead of composing an ideal answer from scratch. Choosing which response is clearer, more accurate, or more useful can be easier and faster than writing every sentence, although difficult comparisons still require expertise and verification. InstructGPT [1], for example, follows supervised fine-tuning with rankings of model-generated responses.
To turn these judgments into training data, we record each comparison as a pair of responses to the same prompt \(q\): the preferred response \(o^+\) and the less-preferred response \(o^-\). This gives us a dataset of triples:
\[(q,o^+,o^-)\sim\mathcal D_{\mathrm{pref}}.\]The label is relative: \(o^+\) need not be perfect, and \(o^-\) need not be entirely wrong. Training only on \(o^+\) with SFT would discard the comparison. Preference methods instead use both responses to learn which differences matter, although the label alone does not identify the responsible tokens.
There are two routes. We can train a reward model to score responses, then use those scores in the policy-gradient machinery developed earlier. Or we can train the policy directly with a loss built from the two response probabilities. Both start from the same comparisons; they differ in how those comparisons become policy updates.
Preference Modeling
A reward model \(r_\phi(q,o)\) reads a prompt and a complete response and returns a scalar score. Its parameters \(\phi\) are separate from the policy parameters \(\theta\). We train the scores so that preferred responses rank above their alternatives, using the Bradley–Terry model of pairwise preferences:
\[P_\phi(o^+\succ o^-\mid q) =\frac{\exp r_\phi(q,o^+)} {\exp r_\phi(q,o^+)+\exp r_\phi(q,o^-)} =\sigma(\Delta r_\phi(q,o^+,o^-)),\]where \(\Delta r_\phi(q,o^+,o^-)=r_\phi(q,o^+)-r_\phi(q,o^-)\) and \(\sigma\) is the sigmoid function. Equal scores predict a preference probability of \(1/2\); a larger positive gap makes the observed preference more likely. We therefore minimize its negative log-likelihood:
\[\mathcal L_{\mathrm{RM}}(\phi) =-\mathbb E_{(q,o^+,o^-)\sim\mathcal D_{\mathrm{pref}}} \log\sigma(\Delta r_\phi(q,o^+,o^-)).\]For one observed comparison,
\[\frac{\partial\ell_{\mathrm{RM}}}{\partial\Delta r_\phi(q,o^+,o^-)} =\sigma(\Delta r_\phi(q,o^+,o^-))-1,\]so
\[\nabla_\phi\ell_{\mathrm{RM}} =(\sigma(\Delta r_\phi(q,o^+,o^-)) - 1) \left[\nabla_\phi r_\phi(q,o^+)-\nabla_\phi r_\phi(q,o^-)\right].\]From comparisons to RLHF
Learning from Human Preferences [19] established this reward-learning-plus-RL approach outside language modeling. Fine-Tuning Language Models from Human Preferences [20] and Learning to Summarize from Human Feedback [21] applied it to text. A General Language Assistant as a Laboratory for Alignment [86] compares imitation and preference modeling, while Training a Helpful and Harmless Assistant [22] explores iterative feedback collection and competing goals. Kaufmann et al.’s Survey of RLHF [87] reviews the wider framework.
The update increases the chosen-minus-rejected score difference, most strongly when the model currently predicts the wrong ordering.
Reward Model Training
The reward model is usually a language-model backbone with a scalar scoring head in place of its next-token prediction head. It reads the prompt and response, then produces a score from their representation. It can start from a pretrained or supervised-fine-tuned checkpoint, but need not match the policy’s size. InstructGPT [1] uses a 6B reward model to supervise policies of several sizes, including 175B. In this setup, the policy and reward model have separate parameters, even if they share an architecture or initialization.
Training proceeds in stages: collect comparisons, fit \(r_\phi\) with the preference loss, then freeze it while updating \(\pi_\theta\) on newly sampled responses. They do not optimize a shared loss: the reward model learns to predict judgments, while the policy learns to obtain higher scores.
Freezing the reward model for a policy-training phase does not require keeping it fixed forever. As the policy changes, we can collect judgments on its new responses, retrain the reward model, and begin another phase. Training a Helpful and Harmless Assistant [22] explores this iterative setup with fresh feedback.
The judgments used to train the reward model can also come from another model, much like synthetic SFT demonstrations. Constitutional AI [23] uses written principles to guide revisions and comparisons: revised responses support SFT, while preference judgments train a reward model for RL. RLAIF vs. RLHF [30] compares AI and human feedback and also studies direct AI-generated rewards.
Optimal Policy
Given a fixed reward function, what policy maximizes reward while staying close to the reference policy? We can solve this objective directly to see how the reward determines the optimal policy.
Here we specialize the earlier objective to complete responses: \(\gamma=1\), with a reward \(r(q,o)\) at the end of the response. The sum of token log-ratios becomes the response log-ratio. This is the undiscounted special case of the earlier setup.
At a fixed prompt \(q\), suppress the prompt in the notation and hold the reward function fixed:
\[\max_\pi\;\sum_o\pi(o)r(o) -\beta\sum_o\pi(o)\log\frac{\pi(o)}{\pi_{\mathrm{ref}}(o)}, \qquad\sum_o\pi(o)=1.\]Introduce a multiplier \(\lambda\):
\[\mathcal F(\pi,\lambda) =\sum_o\pi(o)r(o) -\beta\sum_o\pi(o)\log\frac{\pi(o)}{\pi_{\mathrm{ref}}(o)} +\lambda\left(\sum_o\pi(o)-1\right).\]Setting its derivative with respect to each \(\pi(o)\) to zero gives
\[r(o)-\beta\left(\log\frac{\pi(o)}{\pi_{\mathrm{ref}}(o)}+1\right)+\lambda=0.\]Where do λ and Z come from?
Rearranging the stationary condition gives
\[\log\frac{\pi(o)}{\pi_{\mathrm{ref}}(o)} =\frac{r(o)}{\beta}+\frac{\lambda}{\beta}-1.\]Exponentiating turns the additive term containing \(\lambda\) into a multiplicative factor:
\[\pi(o)=\pi_{\mathrm{ref}}(o)e^{r(o)/\beta} \underbrace{e^{\lambda/\beta-1}}_{C}.\]At a fixed prompt, the same \(\lambda\) applies to every response, so \(C\) is shared across them. Requiring probabilities to sum to one determines it:
\[1=\sum_o\pi(o) =C\underbrace{\sum_o\pi_{\mathrm{ref}}(o)e^{r(o)/\beta}}_{Z}.\]Therefore \(C=1/Z\), or equivalently \(\lambda=\beta(1-\log Z)\). The multiplier has not disappeared: it supplies exactly the normalization factor. Restoring the prompt notation gives \(Z(q)\), since the sum depends on the prompt.
Thus the optimum is an exponential reweighting of the reference:
\[\pi^*(o\mid q) =\frac{\pi_{\mathrm{ref}}(o\mid q)\exp(r(q,o)/\beta)}{Z(q)}, \quad Z(q)=\sum_o\pi_{\mathrm{ref}}(o\mid q)\exp(r(q,o)/\beta).\]Equivalently,
\[r(q,o) =\beta\log\frac{\pi^*(o\mid q)}{\pi_{\mathrm{ref}}(o\mid q)} +\beta\log Z(q).\]This gives us another way to express a reward: how much its optimal policy increases a response’s probability relative to the reference, plus a prompt-dependent constant.
Direct Preference Optimization (DPO)
Can we use this reward–policy relationship to learn directly from comparisons? Direct Preference Optimization (DPO) [2] substitutes it into the preference likelihood, avoiding a trained reward model.
For two responses to the same prompt, the unknown \(\beta\log Z(q)\) cancels:
\[r(q,o^+)-r(q,o^-) =\beta\left[ \log\frac{\pi^*(o^+\mid q)}{\pi_{\mathrm{ref}}(o^+\mid q)} -\log\frac{\pi^*(o^-\mid q)}{\pi_{\mathrm{ref}}(o^-\mid q)} \right].\]We now parameterize this relation with the trainable policy \(\pi_\theta\) and insert the resulting reward difference into the same preference likelihood used above. The reference remains fixed. Define
\[h_\theta =\log\frac{\pi_\theta(o^+\mid q)}{\pi_{\mathrm{ref}}(o^+\mid q)} -\log\frac{\pi_\theta(o^-\mid q)}{\pi_{\mathrm{ref}}(o^-\mid q)}, \qquad m_\theta=\beta h_\theta.\]The DPO loss is
\[\mathcal L_{\mathrm{DPO}}(\theta) =-\mathbb E_{\mathcal D_{\mathrm{pref}}}\log\sigma(m_\theta).\]Its gradient follows from the same logistic derivative used for reward modeling:
\[\nabla_\theta\ell_{\mathrm{DPO}} =-\beta\sigma(-m_\theta) \left[ \nabla_\theta\log\pi_\theta(o^+\mid q) -\nabla_\theta\log\pi_\theta(o^-\mid q) \right].\]This returns us to the score vector from SFT and policy gradients. Under gradient descent, DPO combines a direction that raises the chosen response’s log probability with one that lowers the rejected response’s log probability. Both are weighted by \(\beta\sigma(-m_\theta)\): a pair receives more weight when the model fits its preference poorly.
The notebook below applies DPO to the request-to-JSON task using 256 synthetic preference pairs. We compare held-out generations before and after training, tracking content accuracy and format compliance alongside the preference loss.
Alternative Objectives
The common gradient language makes several alternatives easier to place. Each changes a concrete part of the preference problem.
IPO [24] fits a finite target for the log-ratio difference rather than using DPO’s logistic likelihood. With \(\tau\) denoting its regularization parameter, its sampled squared loss has the form
\[\ell_{\mathrm{IPO}}=\left(h_\theta-\frac{1}{2\tau}\right)^2, \qquad \nabla_\theta\ell_{\mathrm{IPO}} =2\left(h_\theta-\frac{1}{2\tau}\right)\nabla_\theta h_\theta.\]The update can reverse after exceeding the target, illustrating a different relationship between preference fitting and regularization.
SimPO [27] removes the reference model and uses average sequence log probability with a target margin \(\delta\) (renamed here to distinguish it from the discount factor):
\[\ell_{\mathrm{SimPO}} =-\log\sigma\left( \frac{\beta}{T_+}\log\pi_\theta(o^+\mid q) -\frac{\beta}{T_-}\log\pi_\theta(o^-\mid q)-\delta \right).\]Its derivative again uses the logistic factor, but the sequence gradients have different length weights and no reference subtraction.
ORPO [26] combines a chosen-response SFT loss with an odds-ratio preference penalty in one reference-free stage. KTO [25] changes the data requirement: desirable/undesirable labels replace paired comparisons, with an objective motivated by prospect theory. These are different supervision and objective choices, rather than interchangeable names for DPO.
RRHF [28] learns likelihood rankings among candidate responses from different sources. SLiC-HF [29] calibrates sequence likelihoods from human comparisons. They provide useful alternatives when the central task is to make model likelihoods respect a ranking, and historical context for direct preference training.
Learning from Rewards
We now have the ingredients for a reward-based update: advantages tell us how to weight sampled actions, importance ratios let us reuse a rollout batch, and the reference penalty controls drift across training. Two practical questions remain: how do we estimate the advantages, and how do we keep repeated updates on one batch from becoming too large?
A common Proximal Policy Optimization (PPO) recipe combines a learned critic and Generalized Advantage Estimation (GAE) for the first question with a clipped policy objective for the second [3, 7]. We can build both directly on the machinery above.
Estimating Advantages
In the advantage derivation, we assumed access to \(V^{\pi,\gamma}\) and \(Q^{\pi,\gamma}\). In practice, we fit a critic, \(V_\psi\), to approximate the rollout policy’s value function. We train it alongside the policy: the policy learns from estimated advantages, while the critic learns to predict returns from the collected trajectories. As the policy changes, the critic must keep adapting to the outcomes that policy produces.
Write \(V_{\mathrm{old}}(s_t)\) for the critic’s predictions saved during rollout collection. These saved values remain fixed when computing advantages for the current batch, even as we update the critic’s parameters \(\psi\).
To compute the return, we first need to place the rewards along the completion. Suppose the reward model assigns one score \(r_\phi(q,o)\) to the whole answer. Its contribution is zero at every intermediate token, and the full score is assigned to the final token. The reference penalty, however, contributes at every token. Using indices \(t=0,\ldots,T-1\), define the log-ratio and combined immediate reward:
\[k_t=\log\frac{\pi_{\mathrm{old}}(o_t\mid q,o_{<t})} {\pi_{\mathrm{ref}}(o_t\mid q,o_{<t})}, \qquad r_t= \begin{cases} -\beta k_t, & t<T-1,\\ r_\phi(q,o)-\beta k_t, & t=T-1. \end{cases}\]We compute these rewards at rollout time and keep them fixed for the batch [1, 66]. Taking \(\gamma=1\), a common choice in LLM post-training, gives:
What if the critic is inaccurate at the start?
At the beginning of training, the critic may predict poorly. If its predictions start near zero, this estimate is initially close to the observed return itself. The policy can still learn: as we showed for baselines, subtracting a state-dependent prediction does not change the expected on-policy gradient, even when that prediction is inaccurate. It may, however, fail to reduce variance or even increase it. Training the critic on collected returns makes the baseline more useful over time.
We can train the critic by treating each collected prefix and its observed return as a supervised example. The simplest value loss is
\[\mathcal L_{\mathrm{value}}^{\mathrm{MC}}(\psi) =\frac12\mathbb E_t\left[(V_\psi(s_t)-G_t)^2\right].\]We hold the observed returns fixed and backpropagate through \(V_\psi\). Across sampled continuations, this regression teaches the critic to predict the expected return from a prefix. Meanwhile, the policy learns from the advantages computed using the saved predictions \(V_{\mathrm{old}}\).
Generalized Advantage Estimation (GAE)
How can we refine this estimate? Start by splitting the return into the immediate reward and everything that follows:
\[G_t^{(\gamma)}=r_t+\gamma G_{t+1}^{(\gamma)}, \qquad \hat G_t^{(1)}=r_t+\gamma V_{\mathrm{old}}(s_{t+1}).\]The future return \(G_{t+1}^{(\gamma)}\) comes from one sampled continuation, which may turn out unusually well or badly. The critic’s prediction \(V_{\mathrm{old}}(s_{t+1})\) estimates the average return over possible continuations from that next prefix. The second equation keeps the observed immediate reward and replaces the sampled future with this prediction.
Subtracting the current-state baseline, just as before, gives the one-step advantage estimate, also called the temporal-difference residual:
\[\delta_t= \underbrace{r_t+\gamma V_{\mathrm{old}}(s_{t+1})}_{\text{reward after taking the token}} -\underbrace{V_{\mathrm{old}}(s_t)}_{\text{reward before taking it}}.\]This asks: after seeing which token was chosen, did our expectation improve or worsen? Using the critic can reduce noise from the sampled continuation, but makes the estimate depend on the critic’s accuracy.
To connect \(\delta_t\) to the advantage, recall that \(Q(s_t,a_t)\) is the expected return after choosing action \(a_t\). With an exact critic, the immediate reward plus the predicted remaining return, \(r_t+\gamma V(s_{t+1})\), equals \(Q(s_t,a_t)\) on average. The TD residual subtracts \(V(s_t)\) from that quantity, so
\[\mathbb E[\delta_t\mid s_t,a_t]=Q(s_t,a_t)-V(s_t)=A(s_t,a_t).\]How do the intermediate value predictions cancel?
For two steps, expand \(\delta_t+\gamma\delta_{t+1}\):
\[\begin{aligned} \delta_t+\gamma\delta_{t+1} &=r_t+\gamma V_{\mathrm{old}}(s_{t+1})-V_{\mathrm{old}}(s_t)\\ &\quad+\gamma r_{t+1}+\gamma^2V_{\mathrm{old}}(s_{t+2})-\gamma V_{\mathrm{old}}(s_{t+1})\\ &=r_t+\gamma r_{t+1}+\gamma^2V_{\mathrm{old}}(s_{t+2})-V_{\mathrm{old}}(s_t). \end{aligned}\]The \(+\gamma V_{\mathrm{old}}(s_{t+1})\) from the first residual cancels the \(-\gamma V_{\mathrm{old}}(s_{t+1})\) from the second. What remains is two computed rewards, the predicted return after them, and the starting baseline. The same cancellation occurs at every intermediate state when we sum \(k\) discounted residuals.
An inaccurate critic can bias the estimate, so we can use the next \(k\) computed token rewards before asking it to predict the remaining return, then subtract the same baseline \(V_{\mathrm{old}}(s_t)\). This gives \(\hat A_t^{(k)}=\sum_{\ell=0}^{k-1}\gamma^\ell\delta_{t+\ell}\): adding consecutive TD residuals cancels the intermediate value predictions. With \(k=1\), we recover the one-step estimate; using the full remaining completion gives \(G_t^{(\gamma)}-V_{\mathrm{old}}(s_t)\), with no prediction of future rewards. Shorter estimates rely more on the critic, while longer ones rely more on the sampled continuation.
GAE takes a weighted average of these advantage estimates, from one token through the full remaining completion. It can be computed as the following weighted sum of TD residuals, with \(\lambda\) controlling the weighting:
\[\hat A_t =\sum_{\ell=0}^{T-t-1}(\gamma\lambda)^\ell\delta_{t+\ell}.\]With \(\lambda=0\), only the first residual contributes. With \(\lambda=1\), the sum telescopes to the Monte Carlo estimate for a completed episode. Intermediate values trade reliance on the critic against noise from the sampled continuation. Smaller values generally reduce variance but can introduce more bias from inaccurate value predictions [7].
There is no need to compute a separate sum for every token. Starting from \(\hat A_T=0\), work backward:
\[\hat A_t=\delta_t+\gamma\lambda\hat A_{t+1}.\]What happens at the end of a completion?
At the end of the completion, we set \(V_{\mathrm{old}}(s_T)=0\) because there are no future rewards left to predict. The final reward is already included in \(r_{T-1}\), so the last residual is simply \(\delta_{T-1}=r_{T-1}-V_{\mathrm{old}}(s_{T-1})\).
With GAE, a common choice is to replace the Monte Carlo target in the value loss with a target formed from the estimated advantage:
\[\hat R_t=\hat A_t+V_{\mathrm{old}}(s_t), \qquad \mathcal L_{\mathrm{value}}(\psi) =\frac12\mathbb E_t\left[(V_\psi(s_t)-\hat R_t)^2\right].\]Clipped Objective
We now have an advantage estimate \(\hat A_t\) for each sampled token and a target for training the critic. The next step is to update the policy.
The importance-weighted surrogate already gives us an objective for this update, \(\mathbb E_t[\rho_t(\theta)\hat A_t]\), where \(\rho_t\) compares the token’s current probability with its probability under the rollout policy. At the start of optimization, the ratio is \(1\). As we take several steps on the same batch, it changes, but the advantages still describe outcomes under the old policy. Continuing to optimize those fixed estimates can therefore push the policy beyond what the batch reliably supports.
PPO stops rewarding further increases in a token’s probability once it has increased enough for a positive advantage, and further decreases once it has decreased enough for a negative advantage. It does this by clipping the probability ratio in the objective:
\[L^{\mathrm{CLIP}}(\theta) =\mathbb E_t\left[ \min\left( \rho_t\hat A_t, \operatorname{clip}(\rho_t,1-\epsilon,1+\epsilon)\hat A_t \right) \right].\]These thresholds limit a sample’s contribution to the objective, rather than imposing hard bounds on its probability. Updates from other samples can still move that probability because they share model parameters. PPO therefore does not guarantee a bound on the policy’s KL divergence [3]. To see exactly which contributions remain active, we can differentiate the clipped objective.
An optimizer minimizes \(\mathcal L_{\mathrm{policy}}=-L^{\mathrm{CLIP}}\). Away from the clipping boundaries, define an indicator for whether a sample still contributes a gradient:
\[m_t =\mathbf 1[\hat A_t>0,\rho_t<1+\epsilon] +\mathbf 1[\hat A_t<0,\rho_t>1-\epsilon].\]Since the old probability and advantage are fixed, differentiation gives
\[\nabla_\theta\mathcal L_{\mathrm{policy}} =-\mathbb E_t\left[ m_t\rho_t\hat A_t\nabla_\theta\log\pi_\theta(a_t\mid s_t) \right].\]Relative to the importance-weighted gradient derived earlier, the new factor is \(m_t\): samples that have saturated contribute no further policy gradient. The log-probability derivative itself is unchanged.
Complete Training Loop
We can now put the two updates together: the policy learns from the fixed GAE advantages through the clipped objective, while the critic learns to predict the corresponding return targets. In the setup described here, the reward model has already been trained on preferences and stays frozen throughout PPO, as does the reference policy. Only the policy and critic are trained.
Each round starts by sampling completions from the current policy, which becomes \(\pi_{\mathrm{old}}\) for this batch. We save the generated tokens’ log-probabilities and the critic’s predictions \(V_{\mathrm{old}}(s_t)\). The frozen reward model scores each completed answer; we assign that score to its final token and subtract the token-level reference penalties. These rewards and saved value predictions give us the GAE advantages \(\hat A_t\) and critic targets \(\hat R_t=\hat A_t+V_{\mathrm{old}}(s_t)\), both detached from the computation graph.
We then take minibatch updates on the same completions, recomputing the current token log-probabilities and value predictions at each step. The policy minimizes \(-L^{\mathrm{CLIP}}\) using ratios against the saved log-probabilities, while the critic minimizes its squared error against \(\hat R_t\). The saved log-probabilities, rewards, advantages, and critic targets stay fixed throughout these updates.
After the chosen number of optimization passes, we generate a fresh batch with the updated policy and repeat, using the updated critic to compute new value predictions. The optional entropy term encourages a broader token distribution. The reference penalty already enters through the rewards used to compute the advantages. The losses can be written together as
\[\mathcal L_{\mathrm{PPO}} =-L^{\mathrm{CLIP}}+c_V\mathcal L_{\mathrm{value}}-c_H\mathcal H, \qquad \mathcal H=\mathbb E_t\left[-\sum_a\pi_\theta(a\mid s_t)\log\pi_\theta(a\mid s_t)\right].\]Verifiable Reasoning
In the PPO setup above, a frozen reward model scores each completed answer. For some tasks, we can obtain that score directly: run generated code against tests, compare a numerical answer with the expected result, or ask a proof assistant to check a proof. These checks give us verifiable rewards. The policy still generates its own attempts and learns from their outcomes; we have changed how those outcomes are evaluated.
This is often called reinforcement learning with verifiable rewards, or RLVR. It does not require a particular optimizer. We could keep the PPO loop we just derived, including its critic and GAE, and replace the learned reward score with the verifier’s result. A correct final answer also does not necessarily establish that every reasoning step was correct: the feedback is only as informative as the check we perform.
There is another useful change we can make when we can score several attempts at the same prompt. Instead of training a critic to predict the expected return, we can compare each attempt with the other attempts. This is the starting point for Group Relative Policy Optimization (GRPO), introduced in DeepSeekMath [8] and used in the reasoning-training pipeline of DeepSeek-R1 [38].
Group Relative Policy Optimization (GRPO)
Recall what the critic supplied in PPO: a baseline against which to compare a sampled return. GRPO replaces that learned baseline with the mean reward of several responses to the same prompt. Comparing responses within a prompt helps account for its difficulty: success on a prompt where every attempt succeeds gives a different signal from success on one where most attempts fail.
For each prompt \(q\), generate \(G>1\) independent responses from \(\pi_{\mathrm{old}}\) and score each completed response:
\[o_1,\ldots,o_G\sim\pi_{\mathrm{old}}(\cdot\mid q), \qquad R_i=R(q,o_i).\]Here \(G\) is the group size, while \(R_i\) is the task score for one whole response, such as \(1\) for a correct answer and \(0\) for an incorrect one. Compute the mean and standard deviation within this group, then normalize each response’s score:
\[\mu_q=\frac1G\sum_{i=1}^G R_i, \qquad \sigma_q=\sqrt{\frac1G\sum_{i=1}^G(R_i-\mu_q)^2+\varepsilon_{\mathrm{std}}}, \qquad \hat A_i=\frac{R_i-\mu_q}{\sigma_q}.\]This normalized score, \(\hat A_i\), is our advantage estimate for the GRPO policy update. It plays the same role as the advantage in PPO, but we compute it from the response’s reward relative to its group instead of using a critic and GAE. Subtracting \(\mu_q\) tells us whether the response did better or worse than its peers. Dividing by \(\sigma_q\) scales that difference relative to the spread of scores in the group. The small positive \(\varepsilon_{\mathrm{std}}\) prevents division by zero.
Responses with rewards above the group mean receive positive advantages; those below it receive negative advantages. Under this outcome-based formulation, every token in a response receives the same advantage, \(\hat A_{i,t}=\hat A_i\). This saves the critic’s training cost, but also gives us coarser feedback: GRPO does not identify which particular step made the response succeed or fail.
GRPO Policy Update
Once we have \(\hat A_i\), the policy update follows the same clipping rule as before. Let \(\rho_{i,t}\) be the current-to-old probability ratio for token \(t\) in response \(i\), and write its clipped contribution as \(\ell_{i,t}\):
\[\rho_{i,t}=\frac{\pi_\theta(o_{i,t}\mid q,o_{i,<t})}{\pi_{\mathrm{old}}(o_{i,t}\mid q,o_{i,<t})}, \qquad \ell_{i,t}=\min\!\left(\rho_{i,t}\hat A_i, \operatorname{clip}(\rho_{i,t},1-\epsilon,1+\epsilon)\hat A_i\right).\]The original response-normalized GRPO objective averages over tokens within each response and then over responses:
\[J_{\mathrm{GRPO}}(\theta) =\mathbb E\left[ \frac1G\sum_{i=1}^G\frac1{T_i}\sum_{t=0}^{T_i-1} \left(\ell_{i,t}-\beta\hat D_{\mathrm{KL},i,t}(\pi_\theta\|\pi_{\mathrm{ref}})\right) \right].\]Here \(\hat D_{\mathrm{KL},i,t}(\pi_\theta\|\pi_{\mathrm{ref}})\) estimates the reverse KL between the current policy’s and frozen reference policy’s next-token distributions, both conditioned on the same prefix \(s_{i,t}=(q,o_{i,<t})\). We use the following KL-divergence estimator from GRPO, evaluated at the generated token \(o_{i,t}\):
\[u_{i,t}=\log\frac{\pi_\theta(o_{i,t}\mid s_{i,t})}{\pi_{\mathrm{ref}}(o_{i,t}\mid s_{i,t})}, \qquad \hat D_{\mathrm{KL},i,t}(\pi_\theta\|\pi_{\mathrm{ref}})=e^{-u_{i,t}}+u_{i,t}-1.\]In our PPO recipe, the reference penalty was included in the token rewards before computing advantages. Here the group advantages use task rewards alone, so the reference penalty enters the objective separately and is recomputed and differentiated through the current policy at each update [8]. The training loop is therefore familiar: generate groups of completions, score them, compute group advantages, and take minibatch policy updates before collecting fresh groups.
Alternative Policy Updates
Once we separate the baseline, normalization, and clipping choices, related methods become easier to compare. They change particular parts of this update rather than requiring a new policy-gradient derivation.
RLOO [37] replaces the group mean with the mean of the other responses:
\[\hat A_i^{\mathrm{LOO}}=R_i-\frac1{G-1}\sum_{j\ne i}R_j.\]For a fixed prompt and independently sampled attempts, the baseline uses only the other responses’ rewards; response \(i\) and its own reward do not enter that average. This makes the baseline independent of the response being updated. As we showed in the baseline derivation, subtracting such a baseline preserves the expected reward gradient.
Dr. GRPO [40] examines the weighting introduced by dividing by response length and group standard deviation. In the original objective, a token’s advantage coefficient is proportional to \((R_i-\mu_q)/(T_i\sigma_q)\). Dr. GRPO removes the group standard-deviation normalization and uses a fixed length scale \(L\) instead of each response’s length:
\[J_{\mathrm{Dr}}=\mathbb E\left[\frac1{GL}\sum_{i,t} \min\left(\rho_{i,t}(R_i-\mu_q), \operatorname{clip}(\rho_{i,t},1-\epsilon,1+\epsilon)(R_i-\mu_q)\right)\right].\]Dropping \(\sigma_q\) avoids giving extra weight to prompt groups with less reward variation, leaving the centered reward \(R_i-\mu_q\). Replacing each response’s length \(T_i\) with a shared constant \(L\) removes the weaker per-token penalties on longer unsuccessful responses.
DAPO [39] changes both optimization and sampling. It allows different clipping thresholds for probability increases and decreases, and averages over all response tokens in the batch:
\[\operatorname{clip}(\rho,1-\epsilon_{\mathrm{low}},1+\epsilon_{\mathrm{high}}), \qquad J_{\mathrm{token}}=\mathbb E\left[\frac{\sum_{i,t}\ell_{i,t}}{\sum_iT_i}\right].\]A longer response now contributes more tokens to the pooled average, rather than receiving the same total weight as a shorter response. DAPO also keeps sampling to collect groups whose responses receive different rewards. To discourage excessive length, it subtracts a length penalty from the correctness reward: the penalty is zero below a chosen threshold, then increases as the response gets longer.
GSPO [41] moves the clipping decision from individual tokens to the whole response. It uses the geometric mean of token probability ratios:
\[s_i(\theta)=\exp\left(\frac1{T_i}\sum_t\log\rho_{i,t}\right), \qquad J_{\mathrm{GSPO}}=\mathbb E\left[\frac1G\sum_i \min\left(s_i\hat A_i,\operatorname{clip}(s_i,1-\epsilon,1+\epsilon)\hat A_i\right)\right].\]All tokens in a response therefore share the same clipping decision. Differentiating gives \(\nabla_\theta s_i=(s_i/T_i)\sum_t\nabla_\theta\log\pi_\theta(o_{i,t}\mid q,o_{i,<t})\). Here we use the fact that a response’s log-probability is the sum of its token log-probabilities, so its gradient is the sum of their gradients; the old policy stays fixed.
Rewards and Sampling
So far, the task reward has arrived only after the complete answer. A verifier or learned judge can also evaluate intermediate reasoning steps. We can assign each step’s score to its ending token and use the reward-to-go machinery already introduced. This provides more local feedback, although deciding how to combine step scores is complicated.
Let’s Verify Step by Step [33] studies human supervision of intermediate steps, while Math-Shepherd [34] constructs step-level supervision automatically and uses it for verification and reinforcement learning. These learned process scores differ from direct correctness checks, even when verified outcomes help generate their training labels.
The reward model also need not remain frozen in every training recipe. PRIME [65] updates an implicit process reward model using policy rollouts and outcome labels. This changes the source of feedback as training proceeds.
Whether feedback evaluates complete answers or intermediate steps, a verifier can only score the attempts the policy generates. With binary outcome rewards, if every answer in a group fails, GRPO receives no relative reward signal. Concentrating probability on successful attempts can therefore improve current performance while reducing the diversity needed to discover better ones. The Entropy Mechanism [62] studies this behavior and proposes interventions to preserve useful exploration.
We can also use scored samples without a policy-gradient update. A verifier can select the best candidate at inference time, as in Training Verifiers to Solve Math Word Problems [31]. Or we can keep successful responses and train on them with the SFT loss. STaR [32], ReST [35], and ReST-EM [36] explore forms of this generate–select–train loop.
Agentic Post-Training
In a single-response task, appending a generated token determines the next text prefix. An interactive agent also changes an external environment: a search query returns documents, a shell command changes files, or a test run reveals an error. Later decisions depend on those observations. Agentic post-training learns the policy that chooses these actions and interprets their consequences.
There are several ways to supply the learning signal. WebGPT studies browser-assisted answering with demonstrations and human feedback, including RL and reward-model-based selection; its best reported configuration uses behavior cloning followed by rejection sampling [68]. Toolformer constructs and filters API-augmented text for self-supervised training, teaching tool calls through language-model updates [69]. Tool use therefore does not require a new optimizer: demonstrations, selected synthetic data, preferences, and online rewards can all train an interactive policy.
From Responses to Interactive Trajectories
Use \(k\) for an interaction turn and \(\ell\) for a token within the agent’s turn. Let \(h_k\) contain the task and the interaction history available to the agent. It generates a message or action
\[a_k=(a_{k,1},\ldots,a_{k,L_k}), \qquad \pi_\theta(a_k\mid h_k) =\prod_{\ell=1}^{L_k} \pi_\theta(a_{k,\ell}\mid h_k,a_{k,<\ell}).\]The message can include reasoning followed by a tool call, or terminate the task with an answer. Its stopping or control tokens are part of the sampled action when the policy generates them. The environment responds with observation \(e_{k+1}\) and reward \(r_k\), after which the next history is constructed.
The agent need not observe the environment’s full state. Let \(x_k\) denote that underlying state, such as the complete repository or a browser session, and let \(P\) describe its transition and observation law. For a trajectory with \(K\) agent turns, including termination, a factorization is
\[\begin{aligned} p_\theta(\tau\mid q) &=p(x_0,e_0\mid q)\\ &\quad\times\prod_{k=0}^{K-1} \pi_\theta(a_k\mid h_k) P(x_{k+1},e_{k+1},r_k\mid x_k,a_k). \end{aligned}\]Histories are constructed from the observations and previous actions using a fixed runtime. This is a partially observed setting: conditioning the policy on \(h_k\) does not assert that its current text context reveals all of \(x_k\). Context truncation or memory management can further limit what it sees.
RAGEN develops a trajectory-level framework, StarPO, for this multi-turn setting and studies training behavior in stylized interactive environments [71]. The broader trajectory makes the existing RL formulation useful beyond completing a single answer.
Deriving the Agent Policy Gradient
Assume the environment law and runtime are fixed with respect to the policy parameters. Their probabilities influence which trajectories occur, but their log derivatives contribute no policy-score term. Reusing the shared log-derivative and sequence-factorization identities gives
\[\nabla_\theta\log p_\theta(\tau\mid q) =\sum_{k=0}^{K-1}\nabla_\theta\log\pi_\theta(a_k\mid h_k) =\sum_{k=0}^{K-1}\sum_{\ell=1}^{L_k} \nabla_\theta\log\pi_\theta(a_{k,\ell}\mid h_k,a_{k,<\ell}).\]For an undiscounted return \(R(\tau)=\sum_k r_k\) and parameter-independent rewards, the same reward-to-go proof removes rewards preceding action \(a_k\). Define the turn’s return and score vector:
\[\begin{aligned} G_k&=\sum_{j=k}^{K-1}r_j,\\ g_k^{\mathrm{turn}}&=\nabla_\theta\log\pi_\theta(a_k\mid h_k). \end{aligned}\]With an action-independent baseline \(b(h_k)\), the gradient is
\[\boxed{ \nabla_\theta J =\mathbb E_{q\sim\mathcal D,\,\tau\sim p_\theta(\cdot\mid q)} \left[\sum_{k=0}^{K-1}(G_k-b(h_k))\,g_k^{\mathrm{turn}}\right]. }\]This is the earlier policy gradient applied to interactive actions. Each turn’s token scores share its return-to-go in this estimator because the environment supplies feedback after the whole message. Finer token-conditioned baselines or advantage estimates can be used without redefining the trajectory.
In a flattened transcript, let \(m_i=1\) for a model-generated token and \(m_i=0\) for a prompt, tool observation, or other externally supplied token. If \(c_i\) is the actual context used to generate token \(y_i\), the trajectory score becomes
\[\nabla_\theta\log p_\theta(\tau\mid q) =\sum_{i:m_i=1}\nabla_\theta\log\pi_\theta(y_i\mid c_i).\]The observation remains in the context for later decisions, but is not treated as an action sampled from the policy. Its mask removes a likelihood target; gradients still pass through the model’s computation on that context. Search-R1 makes this distinction concrete by masking retrieved passage tokens in its policy loss while optimizing reasoning and search interactions [70].
For example, a coding transcript might contain an agent’s test command, the tool’s failure report, and the agent’s subsequent patch. The command and patch contribute policy-score terms. The failure report conditions the patch without becoming another policy-generated target. Training the model to predict that report would be a separate supervised objective.
Credit Assignment across Tokens, Turns, and Tasks
With only a terminal success reward, early exploratory calls and the final answer all receive feedback from the completed attempt. Subtracting a baseline reduces variance; it does not reveal which particular call caused success. More informative feedback may evaluate intermediate progress, correct tool selection, or valid arguments. ToolRL studies the scale, granularity, and temporal design of such rewards while training with GRPO [72].
PPO can reuse a critic and advantage estimation across the interactive rollout. GRPO can compare several complete attempts at the same task under a specified reset distribution. Environment randomness then contributes to reward differences alongside differences in policy decisions. RAGEN analyzes reward-variability collapse and unstable gradients, illustrating why longer interaction introduces practical problems beyond substituting a new reward into the loss [71].
At each generated token, the old-to-current ratio still has the familiar form
\[\rho_i(\theta) =\frac{\pi_\theta(y_i\mid c_i)}{\pi_{\mathrm{old}}(y_i\mid c_i)}, \qquad m_i=1.\]Clipping can be applied to these sampled decisions, but this local ratio does not fully correct the changed distribution of later interaction histories. The runtime must also preserve the contexts and log probabilities actually used for sampling. Replaying a transcript under a different tool template or truncated context changes the likelihood being compared.
The reduction rule matters here too. Equal trajectory weights, equal turn weights, and equal generated-token weights give different influence to long attempts. Including tool-output tokens in a policy-loss denominator would additionally weight attempts according to text the environment returned. Our derivation uses undiscounted rewards; discounting per tool turn and discounting per generated token impose different effective horizons.
Training Long-Context, Multi-Turn Software Engineering Agents applies rejection fine-tuning followed by a DAPO-based RL pipeline to repository interactions and execution feedback [73]. It grounds these choices in tasks requiring multiple commands, observations, and edits before a final test result.
GLM-5 connects long-horizon agent training with asynchronous RL: its report describes separating generation from training and developing asynchronous agent RL algorithms for complex interactions, including software-engineering tasks [92]. We discuss the resulting policy-lag problem in the asynchronous RL section.
Training Environments and Evaluating Agents
Collecting agent experience requires reproducible task initialization, environment resets, action execution, observation capture, and terminal feedback. Agent Lightning separates agent execution from training through a standardized transition interface and proposes hierarchical credit assignment with LightningRL [74]. Its contribution concerns how an agent’s workflow becomes training experience, complementing the policy-loss derivation.
The environment distribution is also part of the curriculum. ScaleEnv constructs interactive tool-use environments and verifiable tasks, using procedural checks and executable action verification, and studies transfer as environmental diversity changes [75]. These recent results concern the evaluated environments and do not establish that synthetic tasks guarantee general agent capability.
Evaluate success together with tool-call count, generated tokens, elapsed execution time, and recovery from errors. Keep tools, context limits, reset rules, and action budgets comparable across policies, and test on held-out task instances and environments. A change in scaffolding or access to a stronger tool can improve the complete agent even when the learned policy has not improved.
Agentic training therefore extends the source of trajectories and the credit-assignment horizon while reusing the shared gradient machinery. We next turn to a complementary source of supervision: a teacher can guide the model at the prefixes it visits, including prefixes containing tool feedback.
Learning from Teachers
An outcome reward tells us whether a completed attempt was useful. A teacher distribution can say how the next-token probabilities should differ at each prefix. Knowledge distillation introduces this richer form of supervision; Sequence-Level Knowledge Distillation instead trains on complete teacher-generated targets [42, 43]. These choices affect both the feedback and the training-prefix distribution.
Let \(p_T(\cdot\mid s)\) be a fixed teacher distribution at prefix \(s=(q,o_{<t})\) and \(\pi_\theta(\cdot\mid s)\) the student. We assume aligned token vocabularies and positive probabilities where the KL ratios require them. A teacher accessible only through generated text can still supply sequence targets, but does not provide the full probabilities these equations require.
Forward KL and Soft Targets
At a fixed prefix, the teacher-to-student KL is
\[\ell_{\mathrm{FKL}}(s) =D_{\mathrm{KL}}(p_T\|\pi_\theta) =\sum_a p_T(a\mid s)\log\frac{p_T(a\mid s)}{\pi_\theta(a\mid s)}.\]Because the teacher is fixed, its entropy is constant with respect to the student. Minimizing this KL is equivalent to minimizing soft-target cross-entropy:
\[\ell_{\mathrm{CE}}(s)=-\sum_a p_T(a\mid s)\log\pi_\theta(a\mid s),\]with gradients
\[\nabla_\theta\ell_{\mathrm{CE}} =-\sum_a p_T(a\mid s)g_\theta(s,a), \qquad \frac{\partial\ell_{\mathrm{CE}}}{\partial z_j} =\pi_j-p_{T,j}.\]This reuses the SFT derivative, replacing a one-hot target with a probability distribution. In the toy final-answer example, if
\[\pi=(0.2,0.3,0.5),\qquad p_T=(0.8,0.1,0.1),\]then \(\nabla_z\ell=(-0.6,0.2,0.4)\). The teacher still favors 4, but communicates relative preferences among all three tokens. A standard temperature variant softens teacher and student distributions and scales the loss by the squared temperature [42].
For a fixed teacher-generated response, ordinary sequence distillation applies SFT to its written tokens. Even when both methods use the same teacher, matching its distribution and imitating one of its complete responses supply different information [43].
Reverse KL and the Score-Function Connection
Now reverse the KL direction at the same fixed prefix:
\[\ell_{\mathrm{RKL}}(s) =D_{\mathrm{KL}}(\pi_\theta\|p_T) =\sum_a\pi_\theta(a\mid s) \log\frac{\pi_\theta(a\mid s)}{p_T(a\mid s)}.\]Write \(u_\theta(s,a)=\log\pi_\theta(a\mid s)-\log p_T(a\mid s)\). Differentiating both occurrences of the student distribution gives
\[\begin{aligned} \nabla_\theta\ell_{\mathrm{RKL}}(s) &=\sum_a\pi_\theta(a\mid s) \bigl(u_\theta(s,a)+1\bigr)g_\theta(s,a)\\ &=\mathbb E_{a\sim\pi_\theta(\cdot\mid s)} [u_\theta(s,a)g_\theta(s,a)]. \end{aligned}\]The \(+1\) term disappears by the zero-score identity. Equivalently, to maximize negative reverse KL, the sampled token has a teacher-derived weight
\[r_T(s,a)=\log p_T(a\mid s)-\log\pi_\theta(a\mid s).\]A token more likely under the teacher than under the student receives a positive weight; the opposite discrepancy receives a negative weight. This is a precise connection between distribution matching and reward-weighted log-probability updates. Forward and reverse KL generally make different compromises when the student cannot represent the teacher exactly; neither direction is universally preferable [44, 9].
Whose Prefixes Receive the Teacher’s Feedback?
We have derived the local loss, but have not specified the distribution of \(s\). Let \(\mu_k\) denote the prefix distribution collected for update \(k\). A distribution-matching training loss can be written as
\[\mathcal L_k(\theta) =\mathbb E_{s\sim\mu_k} [D(p_T(\cdot\mid s),\pi_\theta(\cdot\mid s))],\]where \(\mu_k\) is held fixed during differentiation. It may contain demonstration prefixes, teacher-generated prefixes, or prefixes generated by the student snapshot \(\pi_k\).
Generalized Knowledge Distillation, or GKD, trains on student-generated sequences and permits different divergences and mixtures of training data [9]. The teacher is queried at the student’s actual prefixes, applying the learner-state supervision principle discussed earlier with DAgger [12]. This is why “on-policy” describes the source of the prefixes rather than requiring one particular KL direction.
Collecting fresh student rollouts moves training toward the prefixes encountered at inference. Holding those sampled prefixes fixed during backpropagation is still a choice: the resulting update differentiates the local distribution-matching loss, not every effect of changing the student’s future state distribution.
A Full Sequence Objective Includes Future Feedback
To see the distinction, consider the full reverse KL between sequence distributions:
\[\mathcal L_{\mathrm{seq}}(\theta) =\mathbb E_{o\sim\pi_\theta(\cdot\mid q)} \log\frac{\pi_\theta(o\mid q)}{p_T(o\mid q)}.\]The shared KL derivation and sequence-score identity give
\[-\nabla_\theta\mathcal L_{\mathrm{seq}} =\mathbb E_{o\sim\pi_\theta} \left[\left(\sum_k r_T(s_k,o_k)\right) \sum_tg_\theta(s_t,o_t)\right].\]Remove past terms using the same causal argument as reward-to-go:
\[\boxed{ -\nabla_\theta\mathcal L_{\mathrm{seq}} =\mathbb E_{o\sim\pi_\theta} \left[\sum_t \left(\sum_{k=t}^{T}r_T(s_k,o_k)\right) g_\theta(s_t,o_t)\right]. }\]The explicit derivative of the log student probability inside the log-ratio has zero expectation, as in the shared KL calculation. The remaining score-function term includes how an earlier token changes later prefixes and teacher feedback.
MiniLLM develops on-policy reverse-KL distillation with a decomposition into immediate and future contributions, along with practical sampling and normalization choices [44]. The immediate weight \(r_T(s_t,o_t)\) alone is the fixed-prefix local gradient above; it is not the full sequence gradient in this box. Distinguishing the two avoids silently discarding a credit-assignment term.
Sampled OPD and Variance Reduction
For the fixed-prefix reverse-KL update, we can sum over the vocabulary or sample an action. At an on-policy snapshot,
\[\widehat g_T =\bigl(r_T(s,a)-b(s)\bigr)g_\theta(s,a), \qquad a\sim\pi_\theta(\cdot\mid s),\]has the same expectation as the local negative-KL gradient for any action-independent baseline. This is exactly the earlier baseline identity. A corresponding maximized surrogate is
\[\widehat J_T =\operatorname{sg}[r_T(s,a)-b(s)]\log\pi_\theta(a\mid s),\]where \(\operatorname{sg}\) stops gradients through the sampled weight. The identity concerns its expected gradient at the sampling policy, not the numerical value of this surrogate loss.
The local mean reward has a closed form:
\[b_T(s)=\mathbb E_{a\sim\pi_\theta}[r_T(s,a)] =-D_{\mathrm{KL}}(\pi_\theta(\cdot\mid s)\|p_T(\cdot\mid s)).\]vOPD uses a detached KL-derived control-variate baseline to stabilize sampled OPD [60]. This reconnects dense teacher feedback to the variance-reduction machinery developed at the start of the post. The local mean is not, in general, the full sequence value function or the variance-minimizing baseline for every parameterization.
Approximating an action-independent baseline can preserve the baseline identity; restricting and renormalizing the action distribution in the actual KL loss changes the objective. These are distinct uses of top-token approximations. If a rollout batch is reused after the student changes, sampling corrections or a clearly defined frozen-batch surrogate are also needed.
A Teacher Can Be the Model with More Information
In self-distillation, the same model can play two roles with different contexts. Let \(f\) be privileged training information, such as a verified solution or execution feedback. A stopped-gradient teacher can be formed as
\[p_T(\cdot\mid s,f) =\operatorname{sg}[\pi_{\bar\theta}(\cdot\mid s,f)],\]while the student conditions only on \(s\). The information is available to construct training targets; it need not be available to the deployed student.
OPSD, introduced in Self-Distilled Reasoner, uses privileged information such as verified reasoning traces [11]. SDPO, from Reinforcement Learning via Self-Distillation, converts rich feedback, including explanations of failure, into feedback-conditioned self-teacher predictions [46]. The names are similar, but the algorithms and feedback construction should be distinguished.
Distilling LLM Feedback for Lean Theorem Proving studies feedback-conditioned self-distillation in Lean4 and its combination with subsequent GRPO [59]. These approaches show how a textual explanation of an error can provide more training information than a single final correctness bit.
Which Teacher Signals Should Be Followed?
Uniform teacher matching assumes every supervised token deserves the selected weighting. Dr. OPD instead learns token weights through a bilevel objective aimed at improving the student’s reward [55]. A schematic inner loss is
\[\mathcal L_{\mathrm{weighted}} =\mathbb E_{s\sim\mu_k}[w(s)\,D(p_T(\cdot\mid s),\pi_\theta(\cdot\mid s))],\]with weights fixed for the student step and adjusted through an outer performance objective. The important change is not the existence of a scalar weight, but how the method determines which teacher advice improves the student.
Teacher quality also depends on compatibility. Rethinking On-Policy Distillation studies thinking-pattern alignment and proposes off-policy cold starts and teacher-aligned prompt selection in its experiments [61]. Scaling Properties of Same-Family OPD examines teacher–student scale relationships and reports that teacher benchmark accuracy alone does not predict teaching value in the studied settings [56].
MOPD extends the teacher source to several domain-specialized RL teachers, distilling their capabilities into one student on its own rollouts [58]. This makes distillation a way to integrate capabilities, rather than only compress a larger model. The MiMo-V2-Flash Technical Report describes this approach in a model-training pipeline: domain-specialized teachers provide dense token-level feedback on student-generated responses [91].
Combining Teacher Guidance with Exploration
A weak student may rarely produce a successful trajectory. LUFFY combines off-policy reasoning demonstrations with on-policy rollouts and uses mixed-policy optimization and importance weighting [63]. It changes the sources of candidate behavior as well as the weights applied to that behavior.
Distilled RL integrates selective teacher supervision into RL through clipped reverse importance weighting, negative-sample reset, and sequence-level geometric normalization [57]. Its aim differs from unconditional teacher matching: preserve task-driven optimization while using teacher feedback to guide transfer.
When all outcome rewards in a GRPO group are equal, that group provides no centered correctness signal. Projected Distillation constructs nearby correct targets by editing failed student attempts, then learns contrastively from corrections and failures [53]. It explores how to supply successful behavior while keeping targets close to the student’s attempted trajectories.
The 2026 methods discussed here include recent preprints. Their findings are evidence from particular teachers, students, tasks, and training recipes. They motivate useful design questions—whose prefixes, which teacher, what feedback, and what weighting—without establishing a universal best distillation method.
Implementation and Optimization Pitfalls
Minimal PyTorch-Style Implementation
The following code contains the mathematical core. Production implementations additionally need distributed rollout collection, padding masks, mixed precision, optimizer state management, and careful metric logging.
from __future__ import annotations
import torch
from torch import Tensor
def ppo_policy_loss(
log_probs: Tensor,
old_log_probs: Tensor,
advantages: Tensor,
mask: Tensor,
*,
clip_epsilon: float = 0.2,
) -> Tensor:
"""Clipped PPO policy loss over valid tokens."""
old_log_probs = old_log_probs.detach()
advantages = advantages.detach()
mask = mask.to(log_probs.dtype)
ratio = torch.exp(log_probs - old_log_probs)
unclipped = ratio * advantages
clipped = ratio.clamp(
1.0 - clip_epsilon,
1.0 + clip_epsilon,
) * advantages
token_objective = torch.minimum(unclipped, clipped)
valid_tokens = mask.sum().clamp_min(1.0)
return -(token_objective * mask).sum() / valid_tokens
def grpo_loss(
log_probs: Tensor, # [batch, group, time]
old_log_probs: Tensor, # [batch, group, time]
ref_log_probs: Tensor, # [batch, group, time]
rewards: Tensor, # [batch, group]
mask: Tensor, # [batch, group, time]
*,
clip_epsilon: float = 0.2,
kl_coefficient: float = 0.01,
std_epsilon: float = 1e-6,
) -> Tensor:
"""Outcome-supervised, response-normalized GRPO loss."""
old_log_probs = old_log_probs.detach()
ref_log_probs = ref_log_probs.detach()
rewards = rewards.detach()
mask = mask.to(log_probs.dtype)
group_mean = rewards.mean(dim=1, keepdim=True)
group_variance = (rewards - group_mean).square().mean(
dim=1,
keepdim=True,
)
group_std = torch.sqrt(group_variance + std_epsilon)
response_advantage = (
(rewards - group_mean) / group_std
).detach()
token_advantage = response_advantage.unsqueeze(-1)
ratio = torch.exp(log_probs - old_log_probs)
unclipped = ratio * token_advantage
clipped = ratio.clamp(
1.0 - clip_epsilon,
1.0 + clip_epsilon,
) * token_advantage
policy_token_loss = -torch.minimum(unclipped, clipped)
log_ref_over_policy = ref_log_probs - log_probs
kl_token_loss = (
torch.exp(log_ref_over_policy)
- log_ref_over_policy
- 1.0
)
token_loss = policy_token_loss + kl_coefficient * kl_token_loss
token_count = mask.sum(dim=-1).clamp_min(1.0)
response_loss = (token_loss * mask).sum(dim=-1) / token_count
return response_loss.mean()
The essential implementation rules are visible in the code:
-
Compute probability ratios as exponentiated log-probability differences.
-
Detach old log-probabilities and advantages.
-
Normalize GRPO rewards independently within each prompt group.
-
Apply the response mask before averaging.
-
Decide deliberately whether to weight responses equally or tokens equally.
Common Failure Modes
Confusing objective and loss signs
Papers usually write an objective to maximize. Deep-learning libraries usually minimize. The implementation therefore needs a leading minus sign on the clipped policy objective.
Dividing log-probabilities
The correct ratio is
\[\rho=\exp(\log\pi_{\theta}-\log\pi_{\mathrm{old}}),\]not \(\log\pi_{\theta}/\log\pi_{\mathrm{old}}\).
Backpropagating through rollout quantities
Old log-probabilities, sampled rewards, returns, and advantages are fixed data during the actor update. They should not retain a gradient path to trainable rollout models.
Confusing the old and reference policies
The old policy is the denominator of the PPO ratio. The reference policy is the target of KL regularization. Replacing one role with the other changes the algorithm.
Refreshing the old policy inside the optimization epoch
The old policy should remain fixed while the rollout batch is reused for several minibatch updates. Otherwise the denominator changes and the clipping interpretation no longer matches the collected data.
Treating clipping as a global KL guarantee
PPO clipping limits the incentive contributed by individual sampled actions. It does not mathematically guarantee that the complete policy remains inside a fixed KL ball. Learning rate, number of epochs, and correlated parameter changes still matter.
Normalizing GRPO rewards across unrelated prompts
The defining comparison is within the group generated for one prompt. Batch-wide normalization mixes prompt difficulty and changes the meaning of the advantage.
Ignoring zero-variance groups
When every response in a group receives the same reward, the normalized advantages vanish. Monitoring the fraction of zero-variance groups is therefore an important GRPO diagnostic.
Specify the Estimator before Comparing Implementations
The GRPO function implements response-normalized, outcome-supervised clipping plus the fixed-sample KL surrogate derived above. It leaves the old policy, reference, and reward values detached. It does not implement process supervision, a full-vocabulary KL, or the alternative reductions used by Dr. GRPO and DAPO.
The PPO function contains only the policy loss. A full PPO pipeline also trains the critic, constructs returns and advantages, and chooses entropy and reference regularization. The N+ Implementation Details of RLHF with PPO is a useful reproduction study because preprocessing, reward handling, generation, and optimizer choices all influence the resulting experiment [66].
For any implementation, log the reduction rule, rollout freshness, reward-group variance, response lengths, entropy, and both old-policy and reference-policy divergence diagnostics. Those quantities describe the actual training procedure more precisely than the optimizer’s name alone.
Asynchronous RL
The training loops described above collect a batch and then update the policy. In a synchronous training loop, these stages take turns: generation waits for training, and training waits for the next batch. For language models, responses can have very different lengths, so a few long generations can hold up an entire batch. Asynchronous RL overlaps the two stages: rollout workers keep generating responses while training workers update the policy using completed samples [80–82].
The tradeoff is policy lag. A response might begin under policy version 10 and reach the learner after it has already advanced to version 12. Even a newly completed response can therefore be off-policy. A training batch may also contain responses from several policy versions, rather than a single \(\pi_{\mathrm{old}}\) [81].
This gives us another use for importance weighting. Let \(\mu_{i,t}\) denote the behavior policy that actually sampled action \(a_{i,t}\) in trajectory \(i\). Its action-probability ratio is
\[\rho_{i,t}(\theta) = \frac{\pi_\theta(a_{i,t}\mid s_{i,t})} {\mu_{i,t}(a_{i,t}\mid s_{i,t})}.\]We store the sampling log-probability alongside each action so that the denominator describes how that action was generated. If a worker keeps its weights fixed for a whole response, all its tokens share the same behavior-policy version. Systems that refresh weights during a response must instead track the probabilities used for its individual tokens [81].
As before, this ratio corrects action weighting at sampled states; it does not make old trajectories and advantages fully equivalent to fresh ones. Large policy differences can also produce extreme weights. Practical systems therefore combine corrections with control over how far generation can lag behind training. AReaL, for example, bounds data staleness and modifies the PPO objective; its experiments show that allowing unbounded staleness hurts performance even with that correction [81].
From asynchronous actors to LLM training
A3C established an influential approach in which parallel workers collect experience and asynchronously apply gradients to shared parameters [78]. IMPALA separates actors that collect trajectories from learners that compute updates, introducing V-trace to correct value targets for the resulting policy mismatch [79].
For language models, Asynchronous RLHF studies how much off-policy data different algorithms can tolerate while retaining final performance [80]. AReaL combines continuous generation with staleness-aware learning [81]. StreamRL focuses on streaming generation, overlapping pipeline stages, and scheduling responses with uneven lengths across separate generation and training resources [82].
The goal is to reach a useful policy sooner in wall-clock time. Higher rollout throughput helps only if the learner can still make effective use of those samples; the acceptable amount of lag depends on the algorithm and task [80, 81].
Evaluation: What Did the Update Improve?
Every derivation optimizes a stated mathematical objective. Whether that objective captures the behavior we want is an empirical question. Training reward, preference likelihood, teacher agreement, and held-out task success are different measurements.
Reward Quality before Reward Optimization
RewardBench evaluates reward models on chosen/rejected pairs spanning chat, safety, and reasoning, including challenging and out-of-distribution comparisons [67]. Such checks ask whether the learning signal distinguishes desirable behavior before using it to drive policy updates. Pairwise benchmark accuracy is useful evidence, but does not guarantee reliability on the evolving policy’s outputs.
Suppose a learned proxy score is \(r_{\mathrm{proxy}}\) and independent evaluation measures \(r_{\mathrm{eval}}\). Improving
\[\mathbb E_{o\sim\pi_\theta}[r_{\mathrm{proxy}}(q,o)]\]does not imply improvement in
\[\mathbb E_{o\sim\pi_\theta}[r_{\mathrm{eval}}(q,o)].\]Scaling Laws for Reward Model Overoptimization studies this divergence using proxy and gold reward models in a controlled setup [51]. The failure can arise even when the optimizer follows its objective correctly. Stronger optimization may discover responses that exploit a proxy’s errors.
Response length is one concrete source of misleading gains. A Long Way to Go finds that much of the reward improvement in its RLHF experiments comes from longer responses, with reward models amplifying length biases in preference data [83]. Disentangling Length from Quality in Direct Preference Optimization shows that DPO can also exploit length and proposes regularization to reduce this effect while retaining quality improvements [84]. These results motivate reporting response lengths and checking whether preference gains persist when controlling for length.
Towards Understanding Sycophancy examines assistants agreeing with user beliefs rather than being truthful and the role of preference judgments [52]. A response can be persuasive or agreeable enough to win a comparison while being factually worse. Independent behavioral tests must therefore accompany reward and preference metrics.
Red Teaming Language Models to Reduce Harms complements preference evaluation with adversarial testing: human participants actively try to elicit harmful responses. Ganguli et al. compare model sizes and training methods, including RLHF, and document both discovered failures and limitations of the evaluation process [88]. This tests how behavior holds up under deliberate probing, beyond ordinary task performance.
Accuracy, Coverage, and Sampling Budgets
Single-sample success and the chance of finding a correct answer among many attempts measure different aspects of a distribution. For independent samples on one prompt with per-attempt success probability \(p\),
\[P(\text{at least one success in }k\text{ attempts})=1-(1-p)^k.\]Across a heterogeneous benchmark, averaging this quantity depends on the distribution of per-prompt success rates, not just their mean. A policy may improve on frequently solved prompts while losing coverage of harder ones.
Does RL Really Incentivize Reasoning Capacity Beyond the Base Model? compares RLVR and base models using large-\(k\) pass@\(k\), coverage, and likelihood analyses [64]. Its findings show that better small-\(k\) performance can coexist with reduced coverage in the tested regimes. They do not prove that RL cannot acquire new reasoning behavior under other data, exploration, or interaction setups.
Use matched decoding settings and sampling budgets when comparing checkpoints. Also report response length and total generated tokens: a higher success rate bought with much longer attempts has a different practical cost. Entropy diagnostics and the interventions studied in the entropy-mechanism paper help examine whether the training process is exhausting exploration [62].
Learning and Forgetting Together
Target-task gains do not describe what happens to previously useful behavior. OPDArena compares SFT, RLVR, and OPD while measuring both mathematical learning and general capability retention [54]. It reports strong teacher-dependent differences in forgetting and an association between out-of-domain distribution changes and retention.
This connects back to the four design choices. Student-generated prefixes can reduce one form of training–inference mismatch, but the teacher’s distribution may still push the student away from useful behavior elsewhere. Neither on-policy sampling nor dense supervision alone guarantees retention.
A practical evaluation records target-task performance, independent preference or correctness judgments, general capability retention, and training/inference cost. Keep evaluation prompts and answers separate from instruction generation, teacher feedback, preference collection, and model selection. Otherwise an apparent improvement may measure leakage or adaptation to the evaluator rather than transferable behavior.
Putting the Methods Together
The preceding sections isolate objectives so their gradients can be understood. Training a useful model also requires deciding how to parameterize those updates and how to compose the stages.
LoRA and QLoRA: Change the Trainable Parameters
LoRA freezes a pretrained weight matrix and learns a low-rank update [47]:
\[W=W_0+\frac{\alpha}{r}BA, \qquad B\in\mathbb R^{d_{\mathrm{out}}\times r}, \quad A\in\mathbb R^{r\times d_{\mathrm{in}}}.\]For an upstream weight gradient \(G_W=\partial\mathcal L/\partial W\), the chain rule gives
\[\frac{\partial\mathcal L}{\partial A} =\frac{\alpha}{r}B^\top G_W, \qquad \frac{\partial\mathcal L}{\partial B} =\frac{\alpha}{r}G_WA^\top.\]The learning signal may come from SFT, preferences, or RL. LoRA changes the parameterization through which that signal reaches the weights; it does not supply a new reward or supervision source.
QLoRA combines a frozen quantized base with low-rank adaptation, using NF4, double quantization, and paged optimizers to reduce memory requirements [48]. Memory-efficient adaptation makes training more accessible, but data quality, reward validity, and evaluation remain necessary regardless of how many parameters are trainable.
Full Recipes Show Why Stages Interact
Tulu 3 provides an open recipe spanning data curation, SFT, DPO, and reinforcement learning with verifiable rewards, together with evaluation and decontamination procedures [49]. It illustrates several distinct roles: demonstrations establish useful behavior, preferences reshape choices, and verified outcomes improve selected measurable skills.
OLMoE provides an open example of instruction and preference tuning applied to a sparse mixture-of-experts model. Its release includes model weights, training data, code, and logs, making it a useful resource for studying how these stages work with a different model architecture [85].
Llama 2 documents the fine-tuning and safety evaluation of dialogue models, providing an earlier example of building an assistant from a pretrained foundation model [90]. Command A describes a decentralized training pipeline with self-refinement and model merging, targeting multilingual assistance, retrieval-grounded generation, and tool use [89].
The Llama 3 Herd of Models supplies an industrial-scale account of post-training, including iterative data construction and preference-based training across instruction following, reasoning, coding, and tool use [50]. Such reports show how data mixtures, candidate generation, filtering, and repeated training stages interact with the loss.
These are concrete recipes, not a mandatory universal ordering. DeepSeek-R1 also studies RL directly from a base model in R1-Zero, alongside its multi-stage R1 pipeline and distillation experiments [38]. A stage is useful when it addresses a bottleneck in the starting policy and the available supervision.
For example, when successful solutions are extremely rare, demonstrations or teacher-guided corrections may first make useful behavior reachable. Once the policy can explore promising attempts, verifiable rewards can improve their frequency. Distillation can transfer the resulting behavior to another model, and broad evaluation checks whether specialization damaged other capabilities.
The unified post-training survey describes related roles as support expansion, policy reshaping, and behavioral consolidation [10]. These are useful questions for designing a pipeline, while the derivations tell us precisely what each chosen stage optimizes.
A Unifying View of Post-Training
We can now return to the shared log-probability gradient with the full set of methods in view. For a maximized policy objective or a specified update surrogate, many actor updates admit the schematic form
\[g_{\mathrm{update}} =\mathbb E_{s\sim\mu} \left[\sum_a w(s,a)\nabla_\theta\log\pi_\theta(a\mid s)\right].\]The sum may be evaluated over the vocabulary or estimated from sampled tokens. The weights may include target probabilities, returns, preference margins, importance ratios, and clipping masks. Some depend on the current parameters; a surrogate must specify which quantities are differentiated and which are held fixed.
The equation is a way to compare updates, not a claim that one scalar coefficient completely defines a training method [8, 10]. We also need the prefix distribution, the action distribution or summation rule, the supervision source, the reduction across tokens and responses, and additional losses or constraints.
| Method | Prefixes and responses | Feedback or target | Main update structure |
|---|---|---|---|
| SFT | Demonstrations | Target token | Increase demonstrated-token log probability |
| Offline DPO | Chosen/rejected dataset pairs | Pairwise preference | Margin-weighted difference of two sequence scores |
| REINFORCE | Current-policy rollouts | Sampled reward-to-go | Return times token score |
| PPO | Old-policy rollout batch | Critic-based advantages | Ratio- and clipping-weighted token scores |
| GRPO | Same-prompt rollout groups | Relative response rewards | Group advantages with ratios and clipping |
| Interactive agent RL | Agent actions interleaved with external observations | Task outcomes and intermediate feedback | Return- or advantage-weighted scores of agent-generated tokens |
| Sequence distillation | Teacher-written responses | Hard target tokens | SFT on teacher samples |
| Local distribution distillation | Demonstration, teacher, or student prefixes | Teacher probabilities | Vocabulary sum or sampled KL-gradient estimator |
| Full sequence reverse-KL distillation | Student trajectories | Teacher/student log ratios | Score-function update with future teacher feedback |
The shared derivations explain the links. Sequence factorization turns response scores into token gradients. The zero-score identity removes past rewards and permits baselines. Importance weighting handles a specified sampling mismatch. KL regularization connects reward optimization, implicit preference rewards, and teacher matching. Each later method reuses those tools while making different choices about data and feedback.
Conclusion
Post-training changes a model through demonstrations, comparisons, rewards, and teacher predictions. These sources of supervision contain different information and cover different parts of the model’s behavior.
The mathematical foundations are reusable. SFT supplies target tokens. Reward modeling learns scores from comparisons, and DPO turns a KL-regularized preference problem into direct policy fitting. PPO uses a critic and clipping to make reward-weighted updates practical; GRPO replaces the critic with same-prompt comparisons. Interactive agents extend those updates across actions and external observations. Distillation supplies teacher targets, with on-policy variants moving that supervision to prefixes the student actually visits.
Once those connections are clear, the important differences become easier to identify: where useful trajectories come from, how feedback assigns credit, how updates are controlled, and what evaluation says about learning and forgetting. Those choices determine whether a training objective produces a more useful model.
References
[1] Long Ouyang et al. Training language models to follow instructions with human feedback. 2022.
[2] Rafael Rafailov et al. Direct Preference Optimization: Your Language Model is Secretly a Reward Model. 2023.
[3] John Schulman et al. Proximal Policy Optimization Algorithms. 2017.
[4] Ronald J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. 1992.
[5] R. S. Sutton, D. McAllester, S. Singh, and Y. Mansour. Policy Gradient Methods for Reinforcement Learning with Function Approximation. NeurIPS, 1999.
[6] John Schulman et al. Trust Region Policy Optimization. 2015.
[7] John Schulman et al. High-Dimensional Continuous Control Using Generalized Advantage Estimation. 2015.
[8] Zhihong Shao et al. DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models. 2024.
[9] Rishabh Agarwal et al. On-Policy Distillation of Language Models: Learning from Self-Generated Mistakes. 2023.
[10] Shiwan Zhao et al. Large Language Model Post-Training: A Unified View of Off-Policy and On-Policy Learning. 2026.
[11] Siyan Zhao et al. Self-Distilled Reasoner: On-Policy Self-Distillation for Large Language Models. 2026. Recent preprint.
[12] Stéphane Ross, Geoffrey Gordon, and J. Andrew Bagnell. A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning. 2010.
[13] Jason Wei et al. Finetuned Language Models Are Zero-Shot Learners. 2021.
[14] Victor Sanh et al. Multitask Prompted Training Enables Zero-Shot Task Generalization. 2021.
[15] Hyung Won Chung et al. Scaling Instruction-Finetuned Language Models. 2022.
[16] Yizhong Wang et al. Self-Instruct: Aligning Language Models with Self-Generated Instructions. 2022.
[17] Chunting Zhou et al. LIMA: Less Is More for Alignment. Advances in Neural Information Processing Systems, vol. 36, pp. 55006–55021, 2023.
[18] Subhabrata Mukherjee et al. Orca: Progressive Learning from Complex Explanation Traces of GPT-4. 2023.
[19] Paul Christiano et al. Deep reinforcement learning from human preferences. 2017.
[20] Daniel M. Ziegler et al. Fine-Tuning Language Models from Human Preferences. 2019.
[21] Nisan Stiennon et al. Learning to summarize from human feedback. 2020.
[22] Yuntao Bai et al. Training a Helpful and Harmless Assistant with Reinforcement Learning from Human Feedback. 2022.
[23] Yuntao Bai et al. Constitutional AI: Harmlessness from AI Feedback. 2022.
[24] Mohammad Gheshlaghi Azar et al. A General Theoretical Paradigm to Understand Learning from Human Preferences. 2023.
[25] Kawin Ethayarajh et al. KTO: Model Alignment as Prospect Theoretic Optimization. 2024.
[26] Jiwoo Hong, Noah Lee, and James Thorne. ORPO: Monolithic Preference Optimization without Reference Model. 2024.
[27] Yu Meng, Mengzhou Xia, and Danqi Chen. SimPO: Simple Preference Optimization with a Reference-Free Reward. 2024.
[28] Zheng Yuan et al. RRHF: Rank Responses to Align Language Models with Human Feedback without tears. 2023.
[29] Yao Zhao et al. SLiC-HF: Sequence Likelihood Calibration with Human Feedback. 2023.
[30] Harrison Lee et al. RLAIF vs. RLHF: Scaling Reinforcement Learning from Human Feedback with AI Feedback. 2023.
[31] Karl Cobbe et al. Training Verifiers to Solve Math Word Problems. 2021.
[32] Eric Zelikman et al. STaR: Bootstrapping Reasoning With Reasoning. 2022.
[33] Hunter Lightman et al. Let's Verify Step by Step. International Conference on Learning Representations (ICLR), 2024.
[34] Peiyi Wang et al. Math-Shepherd: Verify and Reinforce LLMs Step-by-step without Human Annotations. 2023.
[35] Caglar Gulcehre et al. Reinforced Self-Training (ReST) for Language Modeling. 2023.
[36] Avi Singh et al. Beyond Human Data: Scaling Self-Training for Problem-Solving with Language Models. 2023.
[37] Arash Ahmadian et al. Back to Basics: Revisiting REINFORCE Style Optimization for Learning from Human Feedback in LLMs. 2024.
[38] DeepSeek-AI et al. DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning. 2025.
[39] Qiying Yu et al. DAPO: An Open-Source LLM Reinforcement Learning System at Scale. 2025.
[40] Zichen Liu et al. Understanding R1-Zero-Like Training: A Critical Perspective. 2025.
[41] Chujie Zheng et al. Group Sequence Policy Optimization. 2025.
[42] Geoffrey Hinton, Oriol Vinyals, and Jeff Dean. Distilling the Knowledge in a Neural Network. 2015.
[43] Yoon Kim and Alexander M. Rush. Sequence-Level Knowledge Distillation. 2016.
[44] Yuxian Gu et al. MiniLLM: On-Policy Distillation of Large Language Models. 2023.
[45] Cheng-Yu Hsieh et al. Distilling Step-by-Step! Outperforming Larger Language Models with Less Training Data and Smaller Model Sizes. 2023.
[46] Jonas Hübotter et al. Reinforcement Learning via Self-Distillation. 2026.
[47] Edward J. Hu et al. LoRA: Low-Rank Adaptation of Large Language Models. 2021.
[48] Tim Dettmers et al. QLoRA: Efficient Finetuning of Quantized LLMs. 2023.
[49] Nathan Lambert et al. Tulu 3: Pushing Frontiers in Open Language Model Post-Training. 2024.
[50] Meta / Aaron Grattafiori et al. The Llama 3 Herd of Models. 2024.
[51] Leo Gao, John Schulman, and Jacob Hilton. Scaling Laws for Reward Model Overoptimization. International Conference on Machine Learning (ICML), PMLR, pp. 10835–10866, 2023.
[52] Mrinank Sharma et al. Towards Understanding Sycophancy in Language Models. 2023.
[53] Shripad V. Deshmukh et al. Projected Distillation: On Learning to Solve Hard Problems from Close, Correct Targets. 2026. Recent preprint.
[54] Yuanze Xu et al. OPDArena: Understanding Learning and Forgetting in On-Policy Distillation. 2026. Recent preprint.
[55] Zhenyu Wang et al. Dr. OPD: Learning What to Follow for Optimal On-Policy Distillation of Large Language Models. 2026. Recent preprint.
[56] Yuntai Bao et al. Scaling Properties of Same-Family On-Policy Distillation. 2026. Recent preprint.
[57] Chen Wang et al. Distilled Reinforcement Learning for LLM Post-training. 2026. Recent preprint.
[58] Wenhan Ma et al. MOPD: Multi-Teacher On-Policy Distillation for Capability Integration in LLM Post-Training. 2026. Recent preprint.
[59] Gaetan Narozniak et al. Distilling LLM Feedback for Lean Theorem Proving. 2026. Recent preprint.
[60] Minjae Oh et al. KL for a KL: On-Policy Distillation with Control Variate Baseline. 2026. Recent preprint.
[61] Yaxuan Li et al. Rethinking On-Policy Distillation of Large Language Models: Phenomenology, Mechanism, and Recipe. 2026. Recent preprint.
[62] Ganqu Cui et al. The Entropy Mechanism of Reinforcement Learning for Reasoning Language Models. 2025.
[63] Jianhao Yan et al. Learning to Reason under Off-Policy Guidance. 2025.
[64] Yang Yue et al. Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model?. 2025.
[65] Ganqu Cui et al. Process Reinforcement through Implicit Rewards. 2025.
[66] Shengyi Huang et al. The N+ Implementation Details of RLHF with PPO: A Case Study on TL;DR Summarization. 2024.
[67] Nathan Lambert et al. RewardBench: Evaluating Reward Models for Language Modeling. 2024.
[68] Reiichiro Nakano et al. WebGPT: Browser-assisted question-answering with human feedback. 2021.
[69] Timo Schick et al. Toolformer: Language Models Can Teach Themselves to Use Tools. 2023.
[70] Bowen Jin et al. Search-R1: Training LLMs to Reason and Leverage Search Engines with Reinforcement Learning. 2025.
[71] Zihan Wang et al. RAGEN: Understanding Self-Evolution in LLM Agents via Multi-Turn Reinforcement Learning. 2025.
[72] Cheng Qian et al. ToolRL: Reward is All Tool Learning Needs. 2025.
[73] Alexander Golubev et al. Training Long-Context, Multi-Turn Software Engineering Agents with Reinforcement Learning. 2025.
[74] Xufang Luo et al. Agent Lightning: Train ANY AI Agents with Reinforcement Learning. 2025.
[75] Dunwei Tu et al. ScaleEnv: Scaling Environment Synthesis from Scratch for Generalist Interactive Tool-Use Agent Training. 2026. Recent research.
[76] Richard S. Sutton and Andrew G. Barto. Reinforcement Learning: An Introduction. 2nd edition, MIT Press, 2018. Sections 3.3–3.4.
[77] Thomas Coste, Usman Anwar, Robert Kirk, and David Krueger. Reward Model Ensembles Help Mitigate Overoptimization. ICLR, 2024.
[78] Volodymyr Mnih et al. Asynchronous Methods for Deep Reinforcement Learning. ICML, 2016.
[79] Lasse Espeholt et al. IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures. ICML, 2018.
[80] Michael Noukhovitch et al. Asynchronous RLHF: Faster and More Efficient Off-Policy RL for Language Models. ICLR, 2025.
[81] Wei Fu et al. AReaL: A Large-Scale Asynchronous Reinforcement Learning System for Language Reasoning. 2025.
[82] Yinmin Zhong et al. StreamRL: Scalable, Heterogeneous, and Elastic RL for LLMs with Disaggregated Stream Generation. 2025.
[83] Prasann Singhal, Tanya Goyal, Jiacheng Xu, and Greg Durrett. A Long Way to Go: Investigating Length Correlations in RLHF. arXiv:2310.03716, 2023.
[84] Ryan Park, Rafael Rafailov, Stefano Ermon, and Chelsea Finn. Disentangling Length from Quality in Direct Preference Optimization. Findings of the Association for Computational Linguistics: ACL 2024, pp. 4998–5017, 2024.
[85] Niklas Muennighoff et al. OLMoE: Open Mixture-of-Experts Language Models. International Conference on Learning Representations (ICLR), 2025.
[86] Amanda Askell et al. A General Language Assistant as a Laboratory for Alignment. arXiv:2112.00861, 2021.
[87] Timo Kaufmann, Paul Weng, Viktor Bengs, and Eyke Hüllermeier. A Survey of Reinforcement Learning from Human Feedback. Transactions on Machine Learning Research (TMLR), 2025.
[88] Deep Ganguli et al. Red Teaming Language Models to Reduce Harms: Methods, Scaling Behaviors, and Lessons Learned. arXiv:2209.07858, 2022.
[89] Team Cohere et al. Command A: An Enterprise-Ready Large Language Model. arXiv:2504.00698, 2025.
[90] Hugo Touvron et al. Llama 2: Open Foundation and Fine-Tuned Chat Models. arXiv:2307.09288, 2023.
[91] Xiaomi LLM-Core Team et al. MiMo-V2-Flash Technical Report. January 2026. doi:10.48550/arXiv.2601.02780.
[92] GLM-5 Team et al. GLM-5: From Vibe Coding to Agentic Engineering. February 2026. doi:10.48550/arXiv.2602.15763.
[93] Tianzhe Chu et al. SFT Memorizes, RL Generalizes: A Comparative Study of Foundation Model Post-training. arXiv:2501.17161, 2025.