25 Fine-Tuning and Alignment
Large language models, trained on trillions of tokens of internet text, acquire extraordinary breadth: they can summarize articles, write code, translate between languages, and answer factual questions. Yet this raw capability is, by itself, insufficient. A pretrained model is a stochastic parrot [14] in the most literal sense: it has learned to predict the next token in web text, including toxic rants, conspiracy theories, and confidently stated falsehoods. Asking such a model a question may yield a helpful answer, a harmful one, or a continuation of the prompt as if it were a web page, all with roughly equal probability.
The problem, then, is not one of capability but of control. We need the model to follow instructions, refuse harmful requests, acknowledge uncertainty, and produce outputs that humans judge as helpful, honest, and harmless. This is the alignment problem: the challenge of ensuring that a model's behaviour reflects human intent and human values, not merely the statistical patterns of its training data.
This chapter develops the mathematical foundations of alignment. We will see that alignment is, at its core, an optimization problem, but one with a subtle twist. The objective is not a fixed loss function given to us by nature (as in next-token prediction) but a moving target defined by human preferences, which are noisy, inconsistent, and expensive to collect. The central mathematical challenge is to extract a useful training signal from sparse preference data and use it to steer the model without destroying the capabilities acquired during pretraining.
Key Idea.
Alignment as constrained optimization. The alignment objective can be stated as: maximize a reward function reflecting human preferences while remaining close to the pretrained model. Formally, (Central Objective) where is the policy (the language model viewed as a distribution over responses given prompts), is a reward model trained on human preferences, is the pretrained reference policy, and controls the strength of the KL constraint. The KL term is not a nuisance; it is the primary defense against reward hacking, preventing the model from degenerating into a narrow distribution that exploits artifacts of the learned reward.
Historical Note.
The idea of learning from human preferences has a rich history. Christiano et al. (2017) [1] proposed learning reward functions from pairwise human comparisons in Atari games and simulated robotics tasks, demonstrating that a few thousand preference labels could guide an RL agent more effectively than hand-crafted reward functions. Ziegler et al. (2019) [2] brought this idea to natural language, fine-tuning GPT-2 on human preferences for continuation quality. Stiennon et al. (2020) [3] showed that RLHF substantially outperforms supervised learning for text summarization, a result that surprised many, since summarization had been considered a “solved” supervised-learning task. Ouyang et al. (2022) [4] synthesized these ideas into the three-stage InstructGPT pipeline (supervised fine-tuning (SFT), reward model (RM) training, and Proximal Policy Optimization (PPO)), creating the first widely deployed aligned language model. Rafailov et al. (2023) [5] made a striking observation: the reward model and RL loop can be eliminated entirely, yielding Direct Preference Optimization (DPO), which reduces alignment to a single supervised-learning step on preference data.
The chapter is organized as follows. Supervised Fine-Tuning covers supervised fine-tuning, the first stage of the alignment pipeline, including parameter-efficient methods such as LoRA. Reward Modelling develops the mathematics of reward modelling, showing how pairwise human preferences give rise to a reward function via the Bradley–Terry model. Proximal Policy Optimization for Alignment studies Proximal Policy Optimization as applied to language model alignment, deriving the KL-constrained objective and its optimal solution. Direct Preference Optimization presents Direct Preference Optimization, the key theoretical contribution of the chapter, building the derivation step by step from the reparameterization trick to the partition-function cancellation that eliminates the need for a reward model. Group Relative Policy Optimization introduces Group Relative Policy Optimization (GRPO), which eliminates the critic network, and DAPO: Alignment at Scale extends this to DAPO with four innovations for scaling. Alignment for Diffusion Models shows how these ideas transfer to diffusion model alignment. Connections and Synthesis synthesizes the landscape, and Exercises provides exercises.
The three-stage pipeline that underlies most alignment work is illustrated in fig:alignment:pipeline. Each stage uses a different kind of data: pretraining consumes raw text at scale, SFT requires curated demonstrations, and alignment relies on pairwise preference judgments. The cost per datum increases at each stage, but the total data volume decreases by orders of magnitude.
Supervised Fine-Tuning
The first stage of alignment is deceptively simple: take the pretrained language model and continue training it on a curated dataset of high-quality demonstrations. Each demonstration consists of a prompt (an instruction, question, or conversational context) paired with a desired response written by a human expert. This stage, known as supervised fine-tuning (SFT), transforms a base model that continues web text into a model that follows instructions.
Despite its simplicity, SFT has an outsized impact. Empirically, the jump in perceived quality from a base model to an SFT model is often larger than the subsequent jump from SFT to the aligned model. The reason is straightforward: SFT changes the format of the model's outputs, teaching it to respond to questions rather than complete documents, while alignment refines the quality within that format.
The SFT Objective
Definition 1 (Supervised Fine-Tuning Objective).
Given a dataset of demonstrations where is a prompt and is a response tokenized into tokens, the SFT loss is the negative log-likelihood of the response tokens conditioned on the prompt: (SFT LOSS) where is the model's predicted probability of token given the prompt and all preceding response tokens .
Remark 1 (SFT Is Next-Token Prediction).
The SFT objective is identical in form to the pretraining objective; both are next-token prediction via cross-entropy. The only difference is the data: pretraining uses raw web text, while SFT uses curated prompt–response pairs. In practice, the loss is typically computed only over the response tokens , not the prompt tokens , since we want the model to learn to generate responses, not to predict prompts. This is sometimes called prompt masking or completion-only training.
The SFT dataset is typically small by pretraining standards; InstructGPT used approximately 13,000 demonstrations [4], while Alpaca [15] used 52,000 instruction–response pairs generated by GPT-4. The key is not quantity but quality and diversity: the demonstrations must cover the range of tasks and response styles that we want the model to exhibit.
Training is straightforward: initialize from the pretrained checkpoint, set a small learning rate (typically to ), and train for 1–3 epochs. Overfitting is the primary concern: with only tens of thousands of examples, the model can memorize the training set within a single epoch.
Parameter-Efficient Fine-Tuning: LoRA
Full fine-tuning updates every parameter of the model, which poses two problems. First, it requires storing a full copy of the model gradients and optimizer states, which for a 70B-parameter model demands hundreds of gigabytes of GPU memory. Second, deploying multiple fine-tuned variants (one per task or customer) requires storing a separate copy of the full model for each variant.
Low-Rank Adaptation (LoRA), introduced by Hu et al. [16], addresses both problems by freezing the pretrained weights and injecting small trainable low-rank matrices into each layer.
Definition 2 (Low-Rank Adaptation (LoRA)).
For a pretrained weight matrix , LoRA reparameterizes the effective weight as (LORA Reparam) where and with . The forward pass computes (LORA Forward) where is a scaling hyperparameter. The matrices are initialized as and , so that at initialization and the model begins from the pretrained weights. Only and are trained; is frozen.
The key insight is that the weight update has rank at most , so LoRA restricts the fine-tuning update to a low-rank subspace. This dramatically reduces the number of trainable parameters.
Proposition 1 (LoRA Parameter Reduction).
For a single weight matrix , LoRA reduces the number of trainable parameters from to . The compression ratio is (LORA Compression) For typical values and : full fine-tuning requires parameters, while LoRA requires parameters, a reduction.
Proof.
The matrix has parameters and has parameters, giving total. The ratio follows immediately. Substituting and yields .
Definition 3 (QLoRA).
QLoRA [6] combines LoRA with aggressive quantization of the frozen weights. The pretrained matrix is stored in 4-bit NormalFloat (NF4) format, a data type whose quantization levels are optimally spaced for normally distributed weights. QLoRA introduces two additional techniques: double quantization, which quantizes the quantization constants themselves to further reduce memory, and paged optimizers, which offload optimizer states to CPU memory when GPU memory is exhausted. The LoRA adapters and remain in 16-bit precision, so the gradient computation is unchanged. The result is that a 65B-parameter model can be fine-tuned on a single 48,GB GPU.
Example 1 (Fine-Tuning LLaMA-7B with LoRA).
Consider fine-tuning a LLaMA-7B model.
Full fine-tuning: 7 billion parameters 2 bytes (FP16) ,GB of trainable parameters, plus optimizer states (Adam requires the parameter memory), totaling 42,GB.
LoRA (rank 8): Apply LoRA to the query and value projection matrices in all 32 Transformer layers. Each layer has 2 matrices of size , yielding bytes ,MB of trainable parameters.
Compression ratio: .
The LoRA-adapted model achieves comparable performance to full fine-tuning on instruction-following benchmarks while using approximately of the trainable parameter budget.
Insight.
LoRA exploits the hypothesis that weight updates during fine-tuning have low intrinsic dimensionality [7]: the effective number of parameters needed to capture task-specific knowledge is far smaller than the full parameter count. Aghajanyan et al. showed that pretrained models can be fine-tuned in a randomly projected subspace of dimension as low as a few hundred, with minimal loss in performance. LoRA provides a structured, hardware-efficient way to exploit this low-rank structure, replacing random projections with learned low-rank factors.
Remark 2 (Inference-Time Merging).
At inference time, the LoRA adapters can be merged into the base weights: . After merging, the forward pass is identical to that of a standard model with no additional latency or memory overhead. Moreover, multiple LoRA adapters (one per task) can be stored separately and swapped dynamically, enabling efficient multi-task serving from a single base model. This is sometimes called LoRA task routing and is the basis of systems like S-LoRA [8] that serve hundreds of LoRA adapters from a single GPU.
Reward Modelling
The SFT model follows instructions, but not all instructions are followed equally well. Given a prompt, the model might produce several plausible responses that differ in helpfulness, accuracy, tone, and safety. How do we teach the model which responses are better?
The answer is to learn a reward model from human preference data. Instead of asking humans to write perfect demonstrations (which is expensive and difficult to scale), we ask them a simpler question: given two responses, which one is better? This pairwise comparison format is cognitively easier for annotators, produces more consistent labels, and can be used to construct a scalar reward function that captures the aggregate structure of human preferences.
Preference Data
Definition 4 (Preference Dataset).
A preference dataset is a collection (Preference DATA) where for each prompt , the response is preferred (“winning”) and is dispreferred (“losing”), as judged by a human annotator. We write to denote the preference relation.
In practice, collecting preference data proceeds as follows: (1) sample a batch of prompts from a distribution of interest; (2) for each prompt, generate candidate responses from the current policy; (3) present pairs (or -tuples) of responses to human annotators and ask them to rank the responses; (4) convert the rankings into pairwise preferences.
The Bradley–Terry Model
To convert pairwise preferences into a trainable objective, we need a preference model: a probabilistic model of the annotator's choice. The most widely used model is the Bradley–Terry model, which dates to 1952 [17] and is also the foundation of the Elo rating system in chess.
Definition 5 (Bradley–Terry Preference Model).
Given a latent reward function parameterized by , the Bradley–Terry model defines the probability that response is preferred over given prompt as (BT Model) where is the logistic sigmoid function.
The Bradley–Terry model has a clean interpretation: the probability that is preferred depends only on the difference in rewards. If , then and preference for is near-certain. If the rewards are equal, the preference probability is exactly (a coin flip), as one would expect.
Reward Model Training
The reward model is trained by maximum likelihood under the Bradley–Terry model.
Definition 6 (Reward Model Loss).
The reward model training loss is the negative log-likelihood of the observed preferences under the Bradley–Terry model: (RM LOSS) This is a binary cross-entropy loss where the “label” is always (since is always the preferred response by construction) and the “logit” is the reward difference .
Remark 3 (-way Rankings).
In practice, annotators often rank responses rather than comparing just two. Given responses ranked , we form pairwise comparisons. This is more data-efficient: responses yield training pairs. InstructGPT uses to rankings per prompt, generating between 6 and 36 pairwise comparisons from each annotation [4]. To avoid correlated training examples, InstructGPT ensures that all pairs from a single ranking appear in the same training batch.
Proposition 2 (Reward Identifiability).
Under the Bradley–Terry model, the reward function is identifiable only up to an input-dependent constant. That is, and induce the same preference distribution for any function .
Proof.
Substitute into the Bradley–Terry model: (Reward Identifiability) The terms cancel because the Bradley–Terry probability depends only on the reward difference, which is invariant to any additive function of the input alone. Therefore, without additional constraints (such as normalizing the reward to have zero mean per prompt), the reward is determined only up to this additive ambiguity.
Caution.
Goodhart's Law and Reward Hacking. “When a measure becomes a target, it ceases to be a good measure.” When the learned reward model is optimized too aggressively, the policy may discover adversarial inputs to the reward model, outputs that score high on but are low quality according to true human preferences. This phenomenon, known as reward hacking or reward overoptimization, is the alignment analogue of Goodhart's law. Empirically, Gao et al. [9] showed that reward model score initially tracks true preference quality as optimization proceeds, but eventually diverges: the policy finds reward-model-specific artifacts that inflate the score without improving actual quality. The KL penalty in the RLHF objective is the primary defense, limiting how far the policy can deviate from the reference and thereby bounding the extent of reward exploitation.
Example 2 (InstructGPT Reward Model).
InstructGPT [4] trains a 6B-parameter reward model, not the full 175B model. The RM is initialized from the SFT model checkpoint: the language model head (the unembedding matrix that projects hidden states to vocabulary logits) is removed and replaced with a linear projection to a scalar: (RM Architecture) where is the hidden state at the last token position of the concatenated input , and , are learned parameters. Using a smaller model (6B rather than 175B) for the reward model improves training stability and reduces the risk of overfitting to the relatively small preference dataset (33K comparisons).
Remark 4 (Reward Model Architecture).
The standard recipe for building a reward model is:
Initialize from the SFT model checkpoint (which has already learned useful representations of language quality).
Replace the language model head with a scalar projection .
The reward for a prompt–response pair is the scalar output at the last token position.
This architecture has the advantage that the reward model “understands” language at a level comparable to the policy, since it shares the same pretrained backbone. However, it also means that the reward model has the same failure modes as the language model (hallucination, sensitivity to phrasing), which contributes to the reward hacking problem.
Proximal Policy Optimization for Alignment
With a reward model in hand, we can now formulate alignment as a reinforcement learning problem. The language model is the policy , the prompt is the state, the generated response is the action, and the reward model provides the reward signal. The goal is to update the policy to maximize the expected reward while staying close to the pretrained reference policy.
The KL-Constrained Objective
Definition 7 (KL-Constrained Reward Maximization).
The alignment objective is (RLHF Objective) where is the SFT policy (frozen after Stage 1), is the reward model (frozen after Stage 2), and controls the strength of the KL constraint. The KL divergence is (KL DIV)
The KL term serves two purposes. First, it prevents reward hacking: by limiting how far the policy can deviate from the reference, it bounds the extent to which the policy can exploit artifacts of the learned reward model (see warn:goodhart). Second, it preserves the general capabilities acquired during pretraining: without the KL constraint, aggressive reward maximization can cause the model to forget how to perform tasks that are not directly rewarded, a phenomenon known as catastrophic forgetting.
The Optimal Policy
The KL-constrained objective has a remarkably clean closed-form solution, which will play a central role in the DPO derivation (Direct Preference Optimization).
Theorem 1 (Optimal Policy under KL Constraint).
Proof.
We seek to maximize the functional (J Functional) subject to the constraint . Introducing a Lagrange multiplier for the normalization constraint, we form the Lagrangian (Lagrangian) Taking the functional derivative with respect to for a fixed and setting it to zero: (Lagrangian Deriv) Solving for : (LOG Ratio) and exponentiating: (Unnormalized) The factor is independent of and serves as the normalization constant. Defining and enforcing recovers (Partition Function).
To verify this is a maximum, note that is strictly concave in (as the sum of a linear term and a negative KL divergence, which is strictly concave), so the unique stationary point is the global maximum.
The optimal policy has an intuitive interpretation: it is the reference policy reweighted by the exponentiated reward. Responses with high reward are upweighted, responses with low reward are downweighted, and the temperature controls the sharpness of this reweighting. As , the policy concentrates on the reward-maximizing response; as , the policy converges to .
Per-Token Reward and the PPO Objective
In practice, the reward model assigns a single scalar to the entire response. To apply token-level policy gradient methods, we distribute this reward across tokens. The standard approach combines the KL penalty at each step with the final reward at the last token.
The per-token reward is defined as (PER Token Reward) At each intermediate step, the reward is the negative KL penalty: the cost of deviating from the reference policy. At the final step, the reward model score is added. The total reward equals the sequence-level objective , so optimizing the per-token formulation is equivalent to optimizing the original objective.
The policy is then updated using the PPO clipped objective: (PPO CLIP) where (PPO Ratio) is the importance sampling ratio between the current and old policies, is the generalized advantage estimate (GAE), and (typically ) is the clipping range. The and operations ensure that the policy does not change too much in a single update, stabilizing training.
Definition 8 (PPO-ptx: Pretraining Loss Mixing).
To prevent catastrophic forgetting of general capabilities, InstructGPT augments the PPO objective with a pretraining loss: (PPO PTX) where balances alignment with capability preservation and is a sample of pretraining data. InstructGPT uses , indicating that preserving general capabilities is weighted heavily relative to the PPO signal.
The InstructGPT Pipeline
Algorithm 1 (InstructGPT RLHF Pipeline).
The full InstructGPT training pipeline consists of three stages:
Stage 1 - Supervised Fine-Tuning (SFT):
Collect a dataset of 13K prompt–demonstration pairs from human labelers.
Fine-tune the pretrained GPT-3 model on this dataset using the SFT loss for 16 epochs.
Select the checkpoint with highest validation reward model score (not lowest validation loss).
Stage 2 - Reward Model (RM) Training:
For each of 33K prompts, generate responses from the SFT model.
Have human labelers rank the responses.
Decompose rankings into pairwise preferences.
Initialize a 6B model from the SFT checkpoint, replace the LM head with a scalar projection, and train using the Bradley–Terry loss .
Stage 3 - PPO:
Initialize the policy from the SFT model.
Initialize the value function (critic) from the RM weights.
For each PPO iteration: enumerate[label=()]
Sample a batch of prompts .
Generate responses .
Compute advantages using GAE.
Update the value function to minimize the value loss. enumerate
Example 3 (Reward Hacking Without KL Penalty).
Consider what happens when in (RLHF Objective), pure reward maximization with no KL constraint. The policy is free to deviate arbitrarily from . In practice, this leads to degenerate behaviour. For instance, a helpfulness reward model might assign high scores to effusively positive responses (“I'm so happy to help you with this wonderful question!”) regardless of content. Without the KL penalty, the policy quickly converges to producing such responses for every prompt, achieving high reward-model scores while being completely useless. With , the KL penalty charges a cost for this deviation: the model cannot stray far from the reference policy's distribution, which includes diverse and substantive responses. The result is a model that is somewhat more helpful (high reward) while remaining broadly capable (low KL from reference).
Remark 5 (Critic Initialization).
The value function (critic) in PPO estimates the expected future reward . In InstructGPT, the critic is initialized from the reward model weights. This gives the critic a significant head start: the RM has already learned to evaluate response quality, so the initial value estimates are meaningful rather than random. This initialization is crucial for stable training, as random critic values lead to high variance in the advantage estimates and erratic policy updates.
Remark 6 (InstructGPT Results).
The InstructGPT paper [4] reported a striking result: a 1.3B-parameter InstructGPT model was preferred over the 175B-parameter GPT-3 base model by human evaluators 85% of the time. This demonstrated that alignment can compensate for orders-of-magnitude differences in model size: a well-aligned small model can be more useful than a poorly aligned large one. The result catalyzed the field, demonstrating that the bottleneck for useful AI systems was not just scale but alignment.
Direct Preference Optimization
The RLHF pipeline described in Proximal Policy Optimization for Alignment works, but it is complex. It requires training three separate models (the SFT policy, the reward model, and the PPO critic), managing an online RL loop with all its instabilities (reward hacking, value function divergence, hyperparameter sensitivity), and running four neural networks simultaneously during training (the policy, the reference policy, the reward model, and the critic). Each of these components introduces potential points of failure, and the overall system is notoriously difficult to tune.
Direct Preference Optimization (DPO), introduced by Rafailov et al. (2023) [5], makes a beautiful observation: the reward model and the RL loop are unnecessary. By exploiting the closed-form solution for the optimal policy (Theorem 1), DPO reparameterizes the reward in terms of the policy and eliminates the reward model entirely. The result is a simple, stable, supervised-learning objective that directly optimizes the policy on preference data.
Recap: From Bradley–Terry to the KL-Constrained Objective
Let us briefly review the key results from Reward Modelling and Proximal Policy Optimization for Alignment that DPO builds upon.
The Bradley–Terry model (Definition 5) gives the probability of preference in terms of a latent reward: (DPO BT Recap)
The KL-constrained alignment objective (Definition 7) is (DPO KL Recap) and its optimal solution (Theorem 1) is (DPO Optimal Recap)
The standard RLHF pipeline uses (DPO BT Recap) to train a reward model, then uses the reward model in (DPO KL Recap) to train the policy with PPO. DPO takes a different path.
The Reparameterization Trick
The key insight begins with a simple algebraic manipulation. Starting from the optimal policy , take the logarithm of both sides: (DPO LOG Optimal) Now solve for the reward: (DPO Reward Reparam)
This is the reparameterization: the reward is expressed purely in terms of the optimal policy , the reference policy , and the partition function . The reward model has been eliminated, replaced by the log-ratio of the optimal and reference policies, plus a prompt-dependent constant.
Remark 7.
Equation should be compared with the reward identifiability result (Proposition 2): the reward is only identifiable up to an input-dependent constant, and here that constant is . This ambiguity is harmless for pairwise preferences, as we will see in the next subsection.
Partition Function Cancellation
Now substitute the reparameterized reward into the Bradley–Terry model : (DPO Cancel) The terms cancel. This cancellation is the mathematical heart of DPO: the intractable partition function, which would require summing over all possible responses, simply disappears in the pairwise preference setting. No approximation is needed; the cancellation is exact.
The DPO Loss
With the partition function gone, we can replace the true optimal policy with our parameterized policy (since we are optimizing to approach ) and write down a loss function directly.
Definition 9 (DPO Loss).
The Direct Preference Optimization loss is (DPO LOSS)
Let us unpack this expression. Define the implicit reward of a response under the current policy: (Implicit Reward) Then the DPO loss simplifies to (DPO LOSS Simple) which is precisely the Bradley–Terry loss with the explicit reward replaced by the implicit reward . The DPO loss is a binary cross-entropy loss that encourages the policy to assign higher implicit reward to the preferred response than to the dispreferred response.
Theorem 2 (DPO–RLHF Equivalence).
Proof sketch.
The DPO loss is derived by substituting the closed-form optimal policy into the Bradley–Terry likelihood. The derivation is exact; no approximations are made. Therefore, the population-level DPO loss is minimized when , the same policy that simultaneously (a) satisfies the Bradley–Terry model under the true reward and (b) solves the KL-constrained optimization. In the finite-sample or finite-capacity regime, DPO and RLHF may converge to different solutions due to different optimization landscapes and regularization properties, but the population-level optima coincide.
Gradient Analysis
Understanding the gradient of the DPO loss reveals an elegant self-weighting mechanism.
Proposition 3 (DPO Gradient).
The gradient of the DPO loss with respect to is (DPO Gradient) where is the implicit reward.
Proof.
Starting from the DPO loss , let . Then . Using , we have (DPO GRAD Step1) Now compute : (DPO GRAD Step2) since does not depend on . Substituting into yields .
The gradient has a beautiful interpretation. The update increases the log-probability of the preferred response and decreases the log-probability of the dispreferred response . But the magnitude of the update is controlled by the sigmoid weighting factor , which is large when the model currently assigns higher implicit reward to the wrong response () and small when the model already gets it right (). This is automatic hard-example mining: the gradient focuses on the pairs that the model currently ranks incorrectly, and ignores the easy pairs that are already correct.
Proposition 4 (Implicit Reward Model).
After DPO training, the policy itself encodes a reward model: (Implicit RM) where is an input-dependent constant. Since preferences depend only on reward differences (Proposition 2), the term is irrelevant for ranking responses, and the log-ratio serves as a fully functional reward model.
Insight.
DPO converts an RL problem into a classification problem. Instead of training three models (policy, reward model, critic) and running an online RL loop with all its instabilities, DPO trains a single model with a binary cross-entropy-style loss on static preference data. The reward model is not eliminated; it is absorbed into the policy. Every DPO-trained policy is a reward model (up to an irrelevant constant), accessible via the log-ratio in (Implicit RM). This duality between policies and reward models is the fundamental insight underlying DPO.
The DPO Algorithm
Algorithm 2 (DPO Training).
Input: Reference policy (the SFT model), preference dataset , temperature , learning rate .
Procedure:
Initialize .
Freeze (no gradient updates).
For each mini-batch : enumerate[label=()]
Compute log-probabilities under : and .
Compute log-probabilities under (forward pass, no gradient): and .
Compute implicit rewards: , .
Compute loss: .
Update: . enumerate
Output: Aligned policy .
The simplicity of Algorithm 2 is remarkable compared to the InstructGPT pipeline (Algorithm 1). There is no reward model to train, no critic to initialize, no online generation loop, and no GAE computation. The entire alignment procedure reduces to computing log-probabilities under two models (the policy and the frozen reference) and backpropagating through a binary cross-entropy loss.
Example 4 (DPO vs. PPO on Summarization).
On the TL;DR summarization task [3], Rafailov et al. reported the following results:
DPO achieves a win rate of 61% against the SFT baseline (as judged by GPT-4).
PPO (best of sweep) achieves a win rate of 57% against the same baseline.
DPO uses approximately less compute than PPO, since it avoids online generation and reward model inference during training.
The fact that DPO matches or exceeds PPO while being dramatically simpler was a key factor in its rapid adoption.
Remark 8 (Choice of ).
The temperature parameter controls how far the aligned policy can deviate from the reference. The effects are as follows:
Small (e.g., ): aggressive optimization. The implicit reward is amplified, so the policy can move far from to maximize preference alignment. Risk: overfitting to preference data, reduced diversity, potential reward hacking.
Large (e.g., ): conservative optimization. The policy stays close to , making small adjustments. Risk: underfitting, failing to fully capture human preferences.
Typical range: . Rafailov et al. use for summarization and for dialogue.
Remark 9 (DPO Limitations).
Despite its elegance, DPO has known limitations:
Distribution shift: DPO trains on offline preference data (generated by the SFT policy or a previous checkpoint), but the policy evolves during training. As diverges from the data-generating policy, the preference pairs become less informative, and the model may learn to distinguish responses that it would never generate. Online variants such as online DPO and iterative DPO address this by periodically regenerating preference data from the current policy.
Reference policy dependence: The DPO loss depends on through the log-ratio. If assigns near-zero probability to a response in the preference data, the log-ratio becomes very large, leading to numerical instability. In practice, this requires careful filtering of preference data to ensure both responses are plausible under .
No exploration: Unlike PPO, which generates new responses during training and can discover novel high-reward strategies, DPO is limited to the behaviors represented in the static preference dataset. This can be a significant disadvantage for tasks where the optimal strategy is not well represented in the training data.
We summarize the comparison between RLHF (PPO) and DPO in Table 1.
| Aspect | RLHF (PPO) | DPO |
| Models required | Policy + Reward Model + Critic (3) | Policy only (1) |
| Training data | Online (generated during training) | Offline (static preference dataset) |
| Reward model | Explicit, separately trained | Implicit in the policy |
| Optimization | Reinforcement learning (policy gradient) | Supervised learning (cross-entropy) |
| Partition function | Approximated (not needed explicitly) | Cancels exactly in pairwise comparisons |
| Hyperparameters | Many (PPO clip, GAE , critic lr, ) | Few (, learning rate) |
| Compute cost | High (4 forward passes per step) | Low (2 forward passes per step) |
| Exploration | Yes (online generation) | No (offline data) |
| Reward hacking | Controlled by KL penalty | Implicitly controlled by |
| Distribution shift | Mitigated by online sampling | Can be problematic |
Group Relative Policy Optimization
The PPO algorithm described in Proximal Policy Optimization for Alignment requires maintaining four neural networks simultaneously during training: the policy , the reference policy , the reward model , and a critic (value function) . The critic alone can be as large as the policy itself, doubling the GPU memory required. For models at the 70B–671B parameter scale, this cost is prohibitive: a 671B policy would require two copies of itself (policy + critic) plus a reward model, easily exceeding the memory of an entire compute cluster.
Group Relative Policy Optimization (GRPO), introduced by Shao et al. (2024) [18] in the context of DeepSeekMath, eliminates the critic entirely by computing advantages relative to a group of sampled outputs. The key insight is disarmingly simple: instead of learning a value function to estimate the advantage, just sample multiple outputs for the same prompt and normalize their rewards.
Key Idea.
Group-based advantage estimation. Given a prompt , sample a group of candidate outputs from the current policy . Score each output with the reward model to obtain . The advantage of output is simply its z-scored reward within the group: No learned value function is needed; the group is the baseline.
From PPO to GRPO
Recall the PPO objective from (PPO CLIP). In standard PPO, the advantage at each token is estimated using Generalized Advantage Estimation (GAE), which requires the value function . GRPO replaces this with a constant advantage across all tokens in a given output: every token in output receives the same advantage .
Definition 10 (GRPO Objective).
Given a prompt , group of outputs sampled from the old policy , and group-normalized advantages , the GRPO objective is: (GRPO Objective) where the importance ratio is , is the clipping threshold (typically ), and the per-token KL divergence uses the unbiased estimator (GRPO KL)
Remark 10 (Unbiased KL Estimator).
The estimator in (GRPO KL) is derived from the identity . Let where . Then , since and . The estimator for all (with equality at ), so each sample provides a non-negative, unbiased estimate of the KL divergence. This avoids the variance issues of the naive estimator when and are close.
Outcome Supervision vs. Process Supervision
GRPO is particularly effective for tasks with verifiable rewards (mathematics, coding, formal logic) where the correctness of the final answer can be checked automatically. In this setting, two supervision strategies are natural:
Outcome supervision: The reward depends only on the final answer: . This is cheap to implement but provides a sparse signal.
Process supervision: The reward incorporates intermediate reasoning steps, e.g., checking each line of a mathematical derivation. This provides a denser signal but requires a process reward model (PRM) or step-level verification.
DeepSeekMath [18] demonstrates that GRPO with outcome supervision alone achieves 51.7% accuracy on the MATH benchmark, competitive with GPT-4 on mathematical reasoning, using a 7B parameter model. The group-based normalization ensures that even with binary (correct/incorrect) rewards, the advantage signal is informative: within any group, correct solutions receive positive advantage and incorrect ones receive negative advantage.
Proposition 5 (GRPO Advantage with Binary Rewards).
If the reward is binary, , and out of outputs in the group are correct (), then: The advantage magnitude is larger for the minority class: if few outputs are correct (), correct outputs receive large positive advantage; if few are incorrect (), incorrect outputs receive large negative advantage.
Proof.
The group mean is and the variance is . For a correct output, . For an incorrect output, .
Example 5 (GRPO in Action: Mathematical Reasoning).
Consider the prompt: “Solve .” We sample candidate outputs from the policy. Suppose 3 outputs arrive at the correct answer and 5 produce incorrect results. The rewards are with , . The advantages are: The correct (minority) outputs receive a larger magnitude advantage, ensuring the policy updates focus on amplifying rare successful strategies. No value function was needed; the group provided its own baseline.
PPO vs. GRPO: A Comparison
| Aspect | PPO | GRPO |
| Advantage estimation | Learned critic (GAE) | Group z-score normalization |
| Models in memory | Policy + Critic + Reward + Reference (4) | Policy + Reward + Reference (3) |
| Memory saving | Baseline | 50% (no critic) |
| Token-level advantage | Yes (different per token) | No (same for all tokens) |
| KL regularization | Reward penalty or PPO constraint | Explicit KL term per token |
| Best suited for | General RLHF, creative tasks | Verifiable tasks (math, code) |
Algorithm 3 (GRPO Training).
- Input: Prompt dataset , initial policy , reference policy , reward model , group size , clip threshold , KL coefficient
- for iteration
- Sample a batch of prompts
- for each prompt
- Sample outputs:
- Compute rewards: for
- Normalize:
- Compute via (GRPO Objective)
- Update
- Update old policy:
Remark 11 (Connection to DeepSeek-R1).
GRPO is the foundational RL algorithm behind DeepSeek-R1 [10], the reasoning-focused language model discussed in DeepSeek-R1: A Case Study. DeepSeek-R1 applies GRPO at massive scale (671B MoE parameters), using rule-based reward functions for mathematical reasoning and coding tasks. The critic-free design is essential at this scale: maintaining a separate 671B critic would roughly double the already enormous memory footprint. The success of DeepSeek-R1 demonstrated that GRPO scales reliably to frontier-class models.
DAPO: Alignment at Scale
GRPO provides a solid foundation, but scaling RL-based alignment to very large models and datasets reveals several failure modes. Yu et al. (2025) [11] identify four specific pathologies in standard GRPO training and propose targeted fixes, each with a clear mathematical motivation. Together, these fixes constitute Dynamic-sampling Aligned Policy Optimization (DAPO).
The four innovations are:
Clip-Higher: asymmetric clipping to prevent entropy collapse;
Dynamic Sampling: filtering degenerate groups to improve signal quality;
Token-Level Loss: global token normalization to prevent length bias;
Overlong Reward Shaping: soft penalty for exceeding length limits.
We now develop each innovation in detail.
Clip-Higher: Asymmetric Clipping
In standard PPO/GRPO, the importance ratio is clipped symmetrically to . This prevents excessively large policy updates. However, Yu et al. observe that symmetric clipping causes entropy collapse: the policy's entropy decreases monotonically during training, and the model converges to a narrow distribution that generates only a few stereotyped responses.
The root cause is an asymmetry in the update dynamics. When a token already has high probability under the current policy:
A positive advantage pushes above , and the clip prevents further increase: the gradient is zeroed out.
A negative advantage pushes below , and the clip activates only when the ratio is very small.
The net effect is that high-probability tokens can be suppressed but not amplified, while low-probability tokens (which contribute most to entropy) are clipped on the upside. Over many iterations, the distribution narrows.
Definition 11 (Clip-Higher).
Replace the symmetric clip with an asymmetric clip where : (CLIP Higher) In DAPO, and .
Proposition 6 (Clip-Higher Prevents Entropy Collapse).
Consider a token with positive advantage (). Under symmetric clipping, the gradient is zeroed when . Under Clip-Higher with , the gradient remains active for , allowing low-probability tokens (which produce large when their probability increases) to continue increasing. Since entropy increases when probability mass is transferred from high-probability tokens to low-probability tokens, Clip-Higher permits entropy-increasing updates that symmetric clipping blocks.
Dynamic Sampling
When all outputs in a group are correct (or all incorrect), the z-scored advantages are zero (the numerator vanishes for all ), providing no learning signal. Worse, these degenerate batches still consume compute for sampling and reward evaluation.
Definition 12 (Dynamic Sampling).
After sampling a group of outputs for prompt , compute the number of correct outputs . Discard and resample the group if or . Only groups satisfying are used for the policy update. Formally, the effective dataset is:
Remark 12 (Dynamic Sampling and Difficulty Curriculum).
Dynamic Sampling implicitly creates a difficulty curriculum. Early in training, easy prompts (where ) are filtered out because the model already solves them perfectly. As training progresses and the model improves, harder prompts that previously had begin producing some correct outputs and enter the training set. This natural curriculum concentrates training signal on prompts at the frontier of the model's capability, neither too easy nor too hard.
Token-Level Loss
Standard GRPO normalizes the loss per sequence: the inner sum over tokens is divided by , then averaged over the group. This means each sequence contributes equally, regardless of length. Consequently, short sequences have higher per-token gradient magnitude, biasing the policy toward generating shorter outputs.
Definition 13 (Token-Level Loss).
Replace the sequence-level normalization with a global token normalization: (Token Level LOSS) Each token contributes equally to the gradient, regardless of the length of the sequence it belongs to.
Overlong Reward Shaping
In practice, generated outputs that exceed the maximum context length are truncated and typically receive zero reward (the truncated output is rarely correct). This creates a sharp cliff in the reward landscape at , which is difficult for the policy to learn from, as the model receives no information about how close it was to producing a valid answer within the length limit.
Definition 14 (Overlong Reward Shaping).
For an output that exceeds the length limit , replace the hard zero reward with a soft penalty that increases linearly with the excess length: (Overlong Reward) where is a buffer length (typically tokens). This provides a smooth gradient from (at ) to (at ).
Remark 13 (Gradient of Overlong Reward).
The overlong reward provides a gradient signal proportional to for outputs in the range . This encourages the model to “tighten” its reasoning, finding more concise solution strategies, rather than simply truncating. Without this shaping, the model has no incentive to reduce length until it is already below .
The Full DAPO Algorithm
Combining all four innovations yields the complete DAPO algorithm.
Algorithm 4 (DAPO Training).
- Input: Prompt dataset , policy , reference , reward , group size , clips , KL coefficient , max length , cache
- for iteration
- Sample batch of prompts
- for each prompt
- repeat
- Sample outputs:
- Compute rewards: ; if , add
- Dynamic Sampling check
- until
- Normalize:
- Compute via (Token Level LOSS) with Clip-Higher
- Update
Example 6 (DAPO Ablation on AIME 2024).
Yu et al. (2025) [11] report a progressive ablation study on the AIME 2024 competition math benchmark, starting from a vanilla GRPO baseline and adding each DAPO innovation:
| Configuration | AIME 2024 Score |
| GRPO baseline | 30.0 |
| Clip-Higher | 36.7 |
| Dynamic Sampling | 40.0 |
| Token-Level Loss | 43.3 |
| Overlong Reward (full DAPO) | 50.0 |
Each innovation provides a meaningful improvement, with the full DAPO system achieving 50.0 on AIME 2024, a 67% relative improvement over the GRPO baseline. Notably, Clip-Higher provides one of the two largest single improvements (6.7 points, matched by Overlong Reward Shaping), confirming that entropy collapse is among the most critical failure modes.
Alignment for Diffusion Models
The alignment techniques developed in sec:alignment:ppo,sec:alignment:dpo,sec:alignment:grpo were designed for autoregressive language models, where the policy is a tractable distribution factorized token by token. But the alignment problem is equally pressing for generative image models. A text-to-image diffusion model may produce photorealistic images, but they may be aesthetically unpleasing, contain artifacts, fail to match the text prompt, or generate unsafe content. Human (or automated) feedback can improve these aspects, if we can formalize the diffusion process as a decision-making problem amenable to RL.
This section shows that the -step denoising process of a diffusion model can be cast as a Markov Decision Process (MDP), enabling direct application of policy gradient methods. We then survey four complementary alignment approaches: DDPO (RL-based), DRaFT (direct gradient), Diffusion-DPO (preference-based), and ReFL (reward feedback).
Denoising as a Markov Decision Process
Definition 15 (Denoising MDP).
The -step denoising process of a diffusion model defines an MDP with:
States: where is the noisy image at step , is the timestep, and is the text conditioning;
Actions: , the denoised image at the next step;
Transition: deterministic given the action (the action is the next state's image component);
Policy: , the learned denoising distribution;
Reward: , a scalar reward given only at the final step , evaluating the quality of the generated image with respect to the prompt .
Proposition 7 (Exact Log-Probabilities in Gaussian Denoising).
When the denoising policy is Gaussian, , the log-probability of each transition is: (Diffusion Logprob) where is the dimensionality of . This is exact and differentiable; no approximation is needed, unlike the intractable of the full generative model.
Proof.
This follows directly from the density of a multivariate Gaussian with diagonal covariance .
DDPO: Denoising Diffusion Policy Optimization
Black et al. (2024) [19] propose DDPO, applying policy gradient methods directly to the denoising MDP.
The policy gradient for the denoising MDP is: (DDPO Gradient) This is a standard REINFORCE gradient applied to the -step trajectory. Black et al. propose two variants:
DDPO-SF (score function): Directly applies (DDPO Gradient) with a learned baseline to reduce variance: .
DDPO-IS (importance sampling): Uses a PPO-style clipped objective with importance ratios: (DDPO IS) where and .
Remark 14 (Variance Scales with ).
The REINFORCE gradient in (DDPO Gradient) has variance that scales linearly with the number of denoising steps , since the trajectory length is . With typical values of –, this can be substantial. DDPO-IS mitigates this through the clipping mechanism, and practical implementations often use (DDIM sampling) rather than (DDPM).
DRaFT: Direct Reward Fine-Tuning
When the reward function is differentiable with respect to the generated image (e.g., a neural network aesthetic scorer or CLIP similarity), we can bypass the high-variance REINFORCE estimator entirely and backpropagate the reward gradient directly through the denoising chain.
Definition 16 (DRaFT Objective).
Given a differentiable reward , the DRaFT objective [12] is simply: (Draft) where denotes the full -step deterministic (DDIM) denoising chain from to .
The gradient is computed by backpropagating through all denoising steps. For a typical diffusion model with steps and hundreds of millions of parameters, this requires enormous memory. DRaFT addresses this in two ways:
DRaFT-: Backpropagate through only the last denoising steps (typically or ), treating the first steps as frozen. This reduces memory by a factor of at the cost of a biased gradient.
LoRA: Apply LoRA (Parameter-Efficient Fine-Tuning: LoRA) to the diffusion model's U-Net, reducing the number of trainable parameters and the memory footprint of gradient computation.
Remark 15 (DRaFT-1 Approximation Quality).
Clark et al. (2024) show empirically that DRaFT-1 (backprop through only the final denoising step) achieves 80–90% of the reward improvement of full-chain DRaFT, while using less memory. This is because the final denoising step has the most direct influence on the pixel-level content of ; earlier steps primarily determine the coarse structure, which is less sensitive to small parameter changes.
Diffusion-DPO: Preference Learning for Diffusion
Wallace et al. (2024) [13] adapt DPO (Direct Preference Optimization) to diffusion models. The key challenge is that DPO requires log-likelihoods , but for diffusion models the marginal likelihood is intractable.
The solution uses the evidence lower bound (ELBO) as a proxy. Recall that for a diffusion model, the ELBO decomposes into a sum of per-step terms: (Diffusion ELBO) where is a constant independent of .
Definition 17 (Diffusion-DPO Loss).
Given preference pairs where is preferred over , the Diffusion-DPO loss [13] is: (Diffusion DPO) where is the difference in per-step denoising losses: (Diffusion DPO Delta) with sampled uniformly from , , and obtained by adding noise to according to the forward diffusion schedule.
Insight.
Diffusion-DPO is a single-step loss. Despite the diffusion model having denoising steps, the Diffusion-DPO loss evaluates at a single randomly sampled timestep , just like standard diffusion training. This makes it as computationally efficient as regular fine-tuning; no multi-step sampling or trajectory rollout is needed. The factor of in (Diffusion DPO) compensates for the single-step approximation to the full ELBO.
Example 7 (Aligning Stable Diffusion with Aesthetics).
Wallace et al. (2024) [13] align Stable Diffusion XL using Diffusion-DPO with the Pick-a-Pic dataset of human preference pairs. The aligned model achieves a 69% win rate against the base model in human evaluations of visual quality, while maintaining text-image alignment. DDPO achieves similar win rates but requires online sampling during training, making it approximately more expensive.
ReFL: Reward Feedback Learning
Xu et al. (2023) [20] propose a simpler approach when a differentiable reward model (ImageReward) is available: simply backpropagate the reward signal into the later denoising steps.
Definition 18 (ReFL Objective).
The ReFL loss fine-tunes only the last denoising steps: (REFL) where is the predicted clean image from step using a one-step approximation, and is the ImageReward model.
Remark 16 (ReFL vs. DRaFT).
ReFL is essentially a special case of DRaFT- using ImageReward as the reward function. The key contribution is the ImageReward model itself: a BLIP-based model fine-tuned on 137K human preference annotations that correlates well with human judgments of text-image alignment and aesthetic quality.
Diffusion Alignment Taxonomy
| Method | Approach | Reward Type | Online Sampling | Multi-Step Backprop | Data |
| DDPO | Policy gradient | Any (black-box) | Yes | No | None (online) |
| DRaFT | Direct gradient | Differentiable | No | Yes ( steps) | None |
| Diffusion-DPO | Preference | None needed | No | No | Preference pairs |
| ReFL | Direct gradient | Differentiable | No | Yes ( steps) | None |
Connections and Synthesis
Having developed the mathematical foundations of six alignment methods (PPO, DPO, GRPO, DAPO, DDPO, Diffusion-DPO) and two direct-gradient methods (DRaFT, ReFL), we now step back and identify the unifying themes.
A Unified Framework
Definition 19 (Unified Alignment Objective).
Every alignment method discussed in this chapter can be viewed as an instance of the constrained optimization problem: (Unified) where is a reward functional measuring alignment quality and is a constraint functional measuring deviation from the reference policy.
The methods differ in how they instantiate , how they handle the constraint , and whether optimization is performed online (with sampling) or offline (on a fixed dataset):
| Method | Models | Online? | Gradient | Memory | Best For |
| PPO (RLHF) | 4 | Yes | Policy gradient | Very high | General alignment |
| DPO | 2 | No | Supervised | Low | Preference-rich data |
| GRPO | 3 | Yes | Policy gradient | High | Verifiable tasks |
| DAPO | 3 | Yes | Policy gradient | High | Large-scale math/code |
| DDPO | 2 | Yes | Policy gradient | Moderate | Image alignment (any reward) |
| Diff-DPO | 2 | No | Supervised | Low | Image alignment (preference data) |
| DRaFT | 1 | No | Direct (backprop) | Moderate | Image alignment (differentiable reward) |
| ReFL | 1 | No | Direct (backprop) | Low | Image alignment (ImageReward) |
The Alignment Spectrum
The methods in this chapter can be arranged along a spectrum from fully online RL to fully offline supervised learning:
Key Idea.
No single method dominates. The choice of alignment method depends on three factors:
Reward verifiability: For tasks with automatic verifiers (math, code), GRPO/DAPO excel because they can leverage binary correctness signals. For tasks requiring human judgment (creative writing, helpfulness), PPO or DPO with preference data is more appropriate.
Data availability: DPO requires a static dataset of preference pairs; PPO/GRPO generate their own data online. If collecting preference data is cheap, DPO is simpler; if expensive, online methods amortize the cost.
Compute budget: PPO requires 4 models in memory; GRPO eliminates the critic; DPO requires only 2. At frontier scale (100B+ parameters), memory constraints often dictate the method.
Historical Timeline
Historical Note.
The alignment research timeline reveals a clear trend toward simplification. The original RLHF pipeline (Christiano et al., 2017) required a separate reward model and a full RL training loop. InstructGPT (2022) made this practical at scale but still needed four neural networks. DPO (2023) eliminated the reward model and RL loop entirely. GRPO (2024) kept the RL formulation but eliminated the critic. DAPO (2025) refined GRPO with engineering innovations for scale. Meanwhile, diffusion alignment followed a parallel trajectory: from DDPO (RL-based) to Diffusion-DPO (direct preference) and DRaFT/ReFL (direct gradient). The field is converging toward methods that are simpler, more memory-efficient, and require less infrastructure, while maintaining or improving alignment quality.
Exercises
Exercise 1 (SFT Loss Derivation).
Show that the SFT objective is equivalent to minimizing the KL divergence where is the empirical distribution of demonstration sequences, up to a constant independent of .
Exercise 2 (LoRA Parameter Count).
Consider LLaMA-7B, which has 32 transformer layers, each containing attention projections and MLP projections and .
How many total parameters does the model have in these weight matrices alone?
If LoRA with rank is applied to and only, how many trainable parameters are added? What fraction of the full parameter count is this?
Repeat (b) for rank applied to all seven weight matrices. At what rank does LoRA training cost exceed 1% of full fine-tuning?
Exercise 3 (Bradley–Terry MLE).
Derive the Bradley–Terry MLE explicitly. Given preference pairs for a fixed prompt , and a parametric reward function , show that the negative log-likelihood is convex in the reward differences .
Exercise 4 (Reward Identifiability).
Prove that the reward function under the Bradley–Terry model is identifiable only up to a prompt-dependent constant. Specifically, show that if satisfies for all pairs, then for any function satisfies the same equations. Conversely, show that any two solutions must differ by such an additive function.
Exercise 5 (DPO Reparameterization from Scratch).
Starting from the KL-constrained objective :
Derive the optimal policy .
Invert this to express the reward as .
Substitute into the Bradley–Terry model and show that cancels.
Write the resulting DPO loss explicitly.
Verify that when .
Exercise 6 (DPO Gradient Analysis).
Compute the gradient of the DPO loss with respect to : where .
Show that the sigmoid weight is large when the model assigns higher implicit reward to the losing response, interpreting this as “hard example mining.”
What happens to the gradient magnitude as training progresses and the model correctly ranks most preference pairs?
Compare this to the PPO gradient, which weights updates by the advantage . Under what conditions are the two gradients similar?
Exercise 7 (DPO–RLHF Equivalence).
Prove that in the infinite-data, infinite-capacity regime, the DPO and RLHF solutions coincide. Specifically:
Show that if is the global minimizer of the DPO loss (over all policies), then is the optimal policy of the KL-constrained RLHF objective.
Show that if the preference data is generated according to the Bradley–Terry model with a ground-truth reward , then the implicit DPO reward recovers up to a prompt-dependent constant.
Exercise 8 (GRPO Advantage Variance).
Analyze the variance of the GRPO advantage estimator.
For a fixed prompt, let be i.i.d. rewards. Compute in terms of the moments of and the group size .
Show that as (since the z-score has unit variance in the limit).
For binary rewards with success probability , find the group size that minimizes the coefficient of variation of the advantage. How does depend on ?
Exercise 9 (PPO vs. GRPO Memory).
Consider a transformer with layers, hidden dimension , and total parameters. Assume Adam optimization (2 states per parameter) and 16-bit mixed precision.
Compute the GPU memory required for PPO training: policy ( params + Adam states), critic ( params + Adam states), reward model ( params, frozen), reference ( params, frozen).
Compute the memory for GRPO (no critic).
For , compute the memory savings in gigabytes. At what model size does the saving exceed the capacity of a single A100 (80,GB)?
Exercise 10 (Clip-Higher Entropy Analysis).
Consider a vocabulary of size and a policy over this vocabulary. Suppose token has and positive advantage .
Show that after one gradient step with symmetric clipping , the importance ratio for token is clipped at when is small enough.
With Clip-Higher (), compute the additional probability mass that can be transferred to token per update step.
Argue that the entropy is increasing in the probability of low-probability tokens. Conclude that Clip-Higher permits entropy-increasing updates.
Exercise 11 (Dynamic Sampling Probability).
Suppose the policy produces correct outputs with probability for a given prompt, independently across the group.
Compute the probability that a group of size passes the Dynamic Sampling filter (i.e., ).
For , plot this probability as a function of . At what values of is filtering most likely to reject?
Compute the expected number of sampling attempts before passing the filter.
How does Dynamic Sampling affect the effective training distribution? Show that prompts with or are underrepresented relative to prompts with .
Exercise 12 (Overlong Reward Gradient).
Consider the overlong reward shaping from Definition 14.
Compute for outputs in the three regimes: , , and .
Show that the gradient magnitude in the middle regime is . What is the effect of increasing ?
Compare this to a hard threshold reward (0 for , full reward otherwise) in terms of the gradient signal available at length .
Exercise 13 (Diffusion MDP Formalization).
Formalize the denoising MDP of Definition 15 rigorously.
Define the state space , action space , and transition kernel precisely.
Show that the trajectory probability is .
Derive the policy gradient from the standard REINFORCE theorem.
Compute the variance of this estimator as a function of and the reward variance.
Exercise 14 (DDPO Variance vs. Denoising Steps).
The REINFORCE gradient for the denoising MDP has the form .
Assuming the per-step score functions are independent with variance (a simplifying assumption), show that (approximately).
Using DDIM with steps, how does the variance change? Argue that reducing by a factor of reduces variance by approximately the same factor.
Why does DDPO-IS (PPO-style clipping) further reduce variance compared to DDPO-SF (REINFORCE)?
Exercise 15 (DRaFT- Gradient Approximation).
In DRaFT-, we backpropagate through only the last steps.
Write the DRaFT- gradient as (chain rule through steps).
Show that DRaFT- (full chain) gives the exact gradient, while DRaFT-1 is a biased approximation.
Assuming the Jacobians (a contraction), bound the approximation error in terms of and .
For Stable Diffusion with and a typical contraction factor , at what is the approximation error below 10% of the full gradient norm?
Exercise 16 (Diffusion-DPO ELBO Derivation).
Derive the Diffusion-DPO loss from first principles.
Starting from the standard DPO loss , substitute the ELBO approximation for .
Show that the ELBO difference simplifies to a sum of per-step denoising loss differences.
Argue that sampling a single timestep and multiplying by gives an unbiased estimator of the full ELBO difference.
Write out the final single-step loss and verify it matches (Diffusion DPO).
Exercise 17 (LoRA Rank vs. Accuracy).
The LoRA update is where and .
Show that .
If the true optimal update has rank , bound the approximation error in terms of the singular values of (hint: Eckart–Young theorem).
Discuss the trade-off: increasing reduces approximation error but increases memory and risks overfitting. When is likely sufficient vs. when is needed?
Exercise 18 (KL Penalty Sensitivity).
Consider the KL-constrained objective .
Show that where is the optimal value and the optimal policy (envelope theorem).
Conclude that increasing always decreases the optimal reward.
For the DPO loss, show that the implicit KL constraint is controlled by . What happens as and ?
Design an experiment to select optimally for a specific task. What metric would you use?
Exercise 19 (Designing an Alignment Pipeline).
You are tasked with aligning a 13B-parameter language model for code generation. The model should produce correct, efficient, and well-documented Python code. You have access to:
A training dataset of 50K coding problems with reference solutions;
An automated test suite that can verify correctness;
8 NVIDIA A100 GPUs (80,GB each);
A budget of 500 GPU-hours.
Which alignment method(s) would you choose? Justify based on the properties of the task and available resources.
Design the reward function. Would you use binary (pass/fail) rewards or a more nuanced scoring?
Estimate the memory requirements for your chosen method. Does it fit in 8 80,GB with appropriate parallelism?
Describe how you would monitor for reward hacking.
Exercise 20 (Open Problem: Optimal Schedule).
In all alignment methods, is typically fixed throughout training. Investigate whether a schedule could improve results.
Argue intuitively why starting with small (aggressive optimization) and increasing it (conservative fine-tuning) might be beneficial.
Conversely, argue why starting with large (exploration near ) and decreasing it (exploitation) could also work.
Design a simple schedule (e.g., linear, cosine, step) and describe how you would evaluate it experimentally.
This is an open research problem. What theoretical tools (e.g., regret bounds, convergence rates) might help determine the optimal schedule?
References
-
Deep Reinforcement Learning from Human Preferences
BibTeX
@article{christiano2017deep, title={Deep Reinforcement Learning from Human Preferences}, author={Christiano, Paul F and Leike, Jan and Brown, Tom and Martic, Miljan and Legg, Shane and Amodei, Dario}, journal={Advances in Neural Information Processing Systems}, volume={30}, year={2017} }Journal article
-
Fine-Tuning Language Models from Human Preferences
BibTeX
@article{ziegler2019fine, title={Fine-Tuning Language Models from Human Preferences}, author={Ziegler, Daniel M and Stiennon, Nisan and Wu, Jeffrey and Brown, Tom B and Radford, Alec and Amodei, Dario and Christiano, Paul and Irving, Geoffrey}, journal={arXiv preprint arXiv:1909.08593}, year={2019} }Journal article
-
Learning to Summarize with Human Feedback
BibTeX
@article{stiennon2020learning, title={Learning to Summarize with Human Feedback}, author={Stiennon, Nisan and Ouyang, Long and Wu, Jeffrey and Ziegler, Daniel and Lowe, Ryan and Voss, Chelsea and Radford, Alec and Amodei, Dario and Christiano, Paul F}, journal={Advances in Neural Information Processing Systems}, volume={33}, pages={3008--3021}, year={2020} }Journal article
-
Training Language Models to Follow Instructions with Human Feedback
BibTeX
@article{ouyang2022training, title={Training Language Models to Follow Instructions with Human Feedback}, author={Ouyang, Long and Wu, Jeffrey and Jiang, Xu and Almeida, Diogo and Wainwright, Carroll and Mishkin, Pamela and Zhang, Chong and Agarwal, Sandhini and Slama, Katarina and Ray, Alex and others}, journal={Advances in Neural Information Processing Systems}, volume={35}, pages={27730--27744}, year={2022} }Journal article
-
Direct Preference Optimization: Your Language Model is Secretly a Reward Model
BibTeX
@article{rafailov2023direct, title={Direct Preference Optimization: Your Language Model is Secretly a Reward Model}, author={Rafailov, Rafael and Sharma, Archit and Mitchell, Eric and Ermon, Stefano and Manning, Christopher D and Finn, Chelsea}, journal={Advances in Neural Information Processing Systems}, volume={36}, year={2023} }Journal article
-
QLoRA: Efficient Finetuning of Quantized Language Models
BibTeX
@article{dettmers2023qlora, title={{QLoRA}: Efficient Finetuning of Quantized Language Models}, author={Dettmers, Tim and Pagnoni, Artidoro and Holtzman, Ari and Zettlemoyer, Luke}, journal={Advances in Neural Information Processing Systems}, volume={36}, year={2023} }Journal article
-
Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning
BibTeX
@article{aghajanyan2021intrinsic, title={Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning}, author={Aghajanyan, Armen and Gupta, Sonal and Zettlemoyer, Luke}, journal={arXiv preprint arXiv:2012.13255}, year={2021} }Journal article
-
S-LoRA: Serving Thousands of Concurrent LoRA Adapters
BibTeX
@article{sheng2024slora, title={{S-LoRA}: Serving Thousands of Concurrent {LoRA} Adapters}, author={Sheng, Ying and Cao, Shiyi and Li, Dacheng and Hooper, Coleman and Lee, Nicholas and Yang, Shuo and Chou, Christopher and Zhu, Banghua and Zheng, Lianmin and Keutzer, Kurt and Gonzalez, Joseph E and Stoica, Ion}, journal={arXiv preprint arXiv:2311.03285}, year={2024} }Journal article
-
Scaling Laws for Reward Model Overoptimization
BibTeX
@article{gao2023scaling, title={Scaling Laws for Reward Model Overoptimization}, author={Gao, Leo and Schulman, John and Hilton, Jacob}, journal={arXiv preprint arXiv:2210.10760}, year={2023} }Journal article
-
DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning
BibTeX
@article{deepseekr1, title={{DeepSeek-R1}: Incentivizing Reasoning Capability in {LLMs} via Reinforcement Learning}, author={{DeepSeek-AI}}, journal={arXiv preprint arXiv:2501.12948}, year={2025} }Journal article
-
DAPO: An Open-Source LLM Reinforcement Learning System at Scale
BibTeX
@article{yu2025dapo, title={{DAPO}: An Open-Source {LLM} Reinforcement Learning System at Scale}, author={Yu, Qiying and others}, journal={arXiv preprint arXiv:2503.14476}, year={2025} }Journal article
-
Directly Fine-Tuning Diffusion Models on Differentiable Rewards
BibTeX
@article{clark2024directly, title={Directly Fine-Tuning Diffusion Models on Differentiable Rewards}, author={Clark, Kevin and Vicol, Paul and Swersky, Kevin and Fleet, David J}, journal={International Conference on Learning Representations}, year={2024} }Journal article
-
Diffusion Model Alignment Using Direct Preference Optimization
BibTeX
@article{wallace2024diffusion, title={Diffusion Model Alignment Using Direct Preference Optimization}, author={Wallace, Bram and Dang, Meihua and Rafailov, Rafael and Zhou, Linqi and Lou, Aaron and Purber, Senthil and Ermon, Stefano and Xiong, Caiming and Joty, Shafiq and Naik, Nikhil}, journal={Conference on Computer Vision and Pattern Recognition}, year={2024} }Journal article
-
On the Dangers of Stochastic Parrots: Can Language Models Be Too Big?
BibTeX
@inproceedings{bender2021dangers, title={On the Dangers of Stochastic Parrots: Can Language Models Be Too Big?}, author={Bender, Emily M and Gebru, Timnit and McMillan-Major, Angelina and Shmitchell, Shmargaret}, booktitle={Proceedings of the ACM Conference on Fairness, Accountability, and Transparency (FAccT)}, year={2021} }Conference paper
-
Stanford Alpaca: An Instruction-Following LLaMA Model
BibTeX
@article{taori2023stanford, title={Stanford {Alpaca}: An Instruction-Following {LLaMA} Model}, author={Taori, Rohan and Gulrajani, Ishaan and Zhang, Tianyi and Dubois, Yann and Li, Xuechen and Guestrin, Carlos and Liang, Percy and Hashimoto, Tatsunori B}, journal={GitHub repository}, year={2023} }Journal article
-
LoRA: Low-Rank Adaptation of Large Language Models
BibTeX
@article{hu2022lora, title={{LoRA}: Low-Rank Adaptation of Large Language Models}, author={Hu, Edward J and Shen, Yelong and Wallis, Phillip and Allen-Zhu, Zeyuan and Li, Yuanzhi and Wang, Shean and Wang, Lu and Chen, Weizhu}, journal={International Conference on Learning Representations}, year={2022} }Journal article
-
Rank Analysis of Incomplete Block Designs: I. The Method of Paired Comparisons
BibTeX
@article{bradley1952rank, title={Rank Analysis of Incomplete Block Designs: {I}. The Method of Paired Comparisons}, author={Bradley, Ralph Allan and Terry, Milton E}, journal={Biometrika}, volume={39}, number={3/4}, pages={324--345}, year={1952} }Journal article
-
DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models
BibTeX
@article{shao2024deepseekmath, title={{DeepSeekMath}: Pushing the Limits of Mathematical Reasoning in Open Language Models}, author={Shao, Zhihong and Wang, Peiyi and Zhu, Qihao and Xu, Runxin and Song, Junxiao and Zhang, Mingchuan and Li, Y.K. and Wu, Y. and Guo, Daya}, journal={arXiv preprint arXiv:2402.03300}, year={2024} }Journal article
-
Training Diffusion Models with Reinforcement Learning
BibTeX
@article{black2024training, title={Training Diffusion Models with Reinforcement Learning}, author={Black, Kevin and Janner, Michael and Du, Yilun and Kostrikov, Ilya and Levine, Sergey}, journal={International Conference on Learning Representations}, year={2024} }Journal article
-
ImageReward: Learning and Evaluating Human Preferences for Text-to-Image Generation
BibTeX
@article{xu2023imagereward, title={{ImageReward}: Learning and Evaluating Human Preferences for Text-to-Image Generation}, author={Xu, Jiazheng and Liu, Xiao and Wu, Yuchen and Tong, Yuxuan and Li, Qinkai and Ding, Ming and Tang, Jie and Dong, Yuxiao}, journal={Advances in Neural Information Processing Systems}, volume={36}, year={2023} }Journal article