Diffusion DPO & RLHF: Fine-Tuning Image Models on Preferences
After this lesson, you will be able to:
- Explain why a pretrained image model misses what people want (hands, layout, style, matching the prompt), and why more data of the same kind cannot fix it
- Describe drawing an image as a series of decisions with one score at the end (DDPO), and how a policy-gradient update uses that score
- Follow how Diffusion-DPO takes the language-model DPO loss and swaps in the diffusion training error as a stand-in for image likelihood, giving a loss built from four noise-guessing errors
- Say where preference pairs come from (human-rated sets, learned scorers, a language-model judge) and what gets tuned (the full network, a LoRA, the text encoder)
- Explain how online methods differ from Diffusion-DPO: group-relative policy gradients on flow models (with the ODE-to-SDE change that makes steps random) and reward gradients through the last sampling steps, and why both invite reward hacking
- Spot and reduce the standard failures: reward hacking, mode collapse, lost prompt match and bias amplification, using a large beta, mixed training data and several scorers
Before you start
Two images made from the same prompt, plus a note of which one a person preferred: the winner and the loser.
A single score for a finished image that says how good it is. Higher is better.
A frozen copy of the model from before tuning. The tuned model is kept close to it.
The model that is being tuned. In this lesson it is the image model.
A dial that sets how far the tuned model may move away from the reference. A large beta means a short leash.
The tuned model finds a trick that raises the score without making images people like.
A small set of extra trained numbers placed on top of a frozen model, so tuning is cheap.
How much better one output scored than its group's average, in units of the group's spread. Positive means better than its siblings.
Two ways to write the sampling path. An ODE has no randomness, so the same noise gives the same picture. An SDE adds a noise term at every step.
A number you can compute that bounds how unlikely an image is. For diffusion it is a sum of noise-guessing errors.
One safeguard matters. Keep a frozen copy of the model from before tuning, and do not let the tuned model wander far from it. Without that copy, the model can learn to please the judge in strange ways. The dial called beta sets how tight the leash is.
#The Motivation: Why Pretraining Isn't Enough
(caption, image) pairs scraped from the web. The objective is straightforward — predict the noise that was added to each image — and after enough data and compute, the model can produce plausible images for novel prompts.But "plausible" and "what the user wants" diverge on at least four axes:
- Anatomy. Hands with six fingers, eyes pointing in different directions, limbs growing from torsos. These artifacts are common in pretraining data (cropped, occluded, partially visible) so the model treats them as in-distribution.
- Composition. The prompt asks for "a dog on the left of a cat" and you get the cat on the left. The model has no special reward for prompt order; it minimizes a per-pixel noise-prediction loss.
- Aesthetic. A default SDXL output is technically a valid image but visually flat, brown-toned, generically lit. Human raters consistently prefer images with crisper contrast, more saturated color, sharper subject focus.
- Prompt adherence. Long, multi-constraint prompts ("a red cube on a blue sphere, in front of a brick wall, photorealistic, sunset lighting") get partially satisfied. The model picks the easiest 3 of 5 constraints and ignores the rest.
A base SDXL model is trained on ~5 billion image-caption pairs. Why can't you fix prompt-adherence problems just by scaling to 50 billion pairs?
#DDPO: Diffusion Sampling as an MDP
Training Diffusion Models with Reinforcement Learning
Kevin Black, Michael Janner, Yilun Du, Ilya Kostrikov, Sergey Levine (2023)
DDPO: frames diffusion sampling as a multi-step decision process and applies policy gradients (REINFORCE and a PPO-style clipped version) to optimize a reward on the final image.
#The Denoising Trajectory as an MDP
Given a noise vector z_T and a prompt c, a diffusion model samples by iteratively denoising:
z_T → z_{T-1} → z_{T-2} → ... → z_1 → z_0
Each step calls the noise-predictor ε_θ(z_t, t, c), uses the predicted noise to compute z_ (via DDPM, DDIM, or another sampler), and continues. DDPO reads this as a Markov Decision Process:
- State at step t: the current noisy latent z_t together with timestep t and prompt c. The MDP has T+1 states per sample, one per timestep from t=T down to t=0.
- Action at step t: the predicted noise ε_θ(z_t, t, c) — or, equivalently, the next state z_ produced by plugging that prediction into the sampler. The action space is high-dimensional and continuous.
- Trajectory: τ = (z_T, z_, ..., z_0). A single sample = one episode.
- Reward: applied only at the end, on the final image z_0. R(z_0, c) is computed by an aesthetic scorer, a CLIP-alignment model, a learned human-preference model — anything that scores a finished image given the prompt.
Picture first: the model draws a picture in about fifty small moves, and only at the end does a judge give it a score. Say one picture scores 0.8 and another 0.3. DDPO makes the fifty moves behind the 0.8 picture more likely, and the fifty behind the 0.3 picture less likely. The objective below says exactly that.
The credit-assignment problem is real: every action in the T-step trajectory contributed to the final reward, and we are spreading one scalar across T denoising steps. DDPO uses a terminal reward, normalizes rewards per prompt to form advantages, and uses clipped importance ratios (PPO-style) to keep updates stable. It has no value function and no GAE, and the KL penalty to a frozen reference policy belongs to DPOK (Fan et al.), not DDPO. Black et al. showed improvements on compressibility, aesthetic quality, and prompt-image alignment.
The policy gradient needs the log-probability of one sampled trajectory. The derivation builds it step by step and leaves the policy gradient theorem itself to Policy Gradient Methods.
#Why DDPO Is Painful in Practice
DDPO works, but it inherits every operational headache of language-model PPO:
- You need a reward model — either a learned classifier on human-labeled pairs (extra training stage, extra failure point) or a fixed scorer (aesthetic CNN, CLIP), which you then have to trust not to be gameable.
- Trajectory-level policy gradients are high-variance. Twenty to fifty denoising steps means twenty to fifty potential places for the gradient signal to attenuate or explode.
- A KL penalty to a reference policy is the usual guard against reward hacking (DPOK adds one; DDPO does not). Tune β too small and the model drifts toward whatever the reward model rewards; tune it too large and you get no learning.
- Policy-gradient bookkeeping: advantage normalization and ratio clipping, and in some methods value baselines, all have to be re-tuned per image-model architecture.
The natural next question, after seeing DPO replace PPO for language models, is: can we do the same for diffusion?
#Diffusion-DPO: DPO Without the Reward Model
Diffusion Model Alignment Using Direct Preference Optimization
Bram Wallace, Meihua Dang, Rafael Rafailov, Linqi Zhou, Aaron Lou, Senthil Purushwalkam, Stefano Ermon, Caiming Xiong, Shafiq Joty, Nikhil Naik (2023)
Diffusion-DPO — adapts DPO from language models to diffusion by substituting the intractable image likelihood with the diffusion ELBO bound. Reports results on SD 1.5 and SDXL.
#The Language-DPO Starting Point
For a language model, DPO replaces the reward-model + PPO pipeline with a single supervised loss on preference pairs (winner w, loser l) for the same prompt c:
Picture first, with small numbers. For one prompt, the frozen copy rates the winner and the loser as equally likely, say 0.10 each. After a tuning step, the model rates the winner at 0.12 and the loser at 0.08. Against the frozen copy, the winner went up by a factor of 1.2 and the loser down by a factor of 0.8. The loss rewards exactly that gap.
P(w preferred over l) = σ(r(w) - r(l)), and Rafailov et al. showed that the optimal reward in the KL-constrained RLHF problem has the closed form r(x) = β log(p_θ(x)/p_ref(x)) + const. Plug it in and you get the loss above — no separate reward training step.The Bradley-Terry model and this loss are derived in RLHF & DPO: Aligning LLMs with Human Preferences.
log p_θ(x | c) for an image x. That is exactly what diffusion models do not give you.#The Likelihood Substitution: ELBO Bound
p_θ(x_0 | c) only implicitly, as the marginal over a complicated forward/reverse process. The exact log-likelihood is intractable. But diffusion training already uses a tractable bound, the ELBO, which decomposes into per-timestep noise-prediction MSE terms:Picture first: nobody can count directly how likely a picture is. But training already measures how well the network guesses the noise that was added to a picture. A picture the network guesses well is one it finds likely. So the guessing error stands in for the likelihood. The bound below is that error, summed over the noise steps.
This bound is the diffusion training objective, derived in Diffusion Models (DDPM, DDIM, CFG).
log p_θ everywhere in the DPO loss. After algebra (and choosing a single timestep t per training step rather than summing all of them), the loss collapses to a tractable form that compares four noise-prediction errors — the policy and the reference model, each evaluated on a winner and a loser noisy latent.Picture first, with small numbers. On the winner, the frozen copy guesses the noise with error 0.50 and the tuned model with 0.40, so the tuned model is 0.10 better. On the loser, the frozen copy errs by 0.50 and the tuned model by 0.55, so it is 0.05 worse. That is what we want: better on the winner, worse on the loser. The total gap is 0.15, and the loss below shrinks as this gap grows.
Open the derivation to follow every step from the DPO loss to the four errors.
DDPO frames a diffusion sample as an MDP with one state per denoising timestep. For a sampler with T denoising steps, how many states does the MDP have per sample?
Wallace 2023 introduces Diffusion-DPO as an alternative to Diffusion-PPO (DDPO). What is the single biggest practical reason to prefer DPO over PPO for diffusion fine-tuning?
#A Toy Diffusion-DPO Run
The playground is a toy: a 2D shift added to a frozen reference predictor, one timestep, two Gaussians, and 10% of the labels swapped. It uses the real four-error loss. The gradient is multiplied by β, so the code divides the learning rate by β; otherwise a bigger β would simply move faster at a fixed learning rate and hide the effect you want to see.
Read the table it prints. A smaller β lets the policy move further, roughly 0.3 divided by β. At β = 0.05 it overshoots the preferred cluster at (+1.5, +1.5); at β = 5 it barely moves. The β values here are on the toy's scale. Real runs use β in the thousands because their error terms are scaled differently, so compare how β changes the behavior, not the number.
#Where Preference Data Comes From
(winner image, loser image, prompt). Four standard sources, in roughly descending order of quality and ascending order of practicality:- Human-rated datasets. Paid annotators see two model outputs for the same prompt and pick one. Pick-a-Pic (Kirstain et al. 2023) is a large open dataset of hundreds of thousands of preference pairs collected from users of text-to-image models. ImageReward (Xu et al. 2023) collected ~137k expert-rated pairs and trained a reward model on them. PickScore is a learned model trained on Pick-a-Pic that you can use as a fast pair-scorer.
- Aesthetic models. LAION-aesthetic v2 (a small CLIP-conditioned regressor) and HPSv2 (Human Preference Score v2, Wu et al. 2023) score individual images for general aesthetic appeal. Generate N candidates per prompt, score them, treat the top-1 as winner and bottom-1 as loser.
- CLIP-based prompt-adherence scoring. Compute the CLIP similarity between each candidate image and the prompt. Highest similarity = winner, lowest = loser. Cheap and effective for prompt-following objectives, prone to gaming if used alone.
- Multimodal-LLM-as-judge. Show GPT-4V or Claude 3 the two candidate images and the prompt, and ask which better satisfies the prompt. Slow and expensive per pair but eliminates the need for any pretrained reward model. Increasingly common for high-quality fine-tunes in 2024-2025.
Most production pipelines mix several of these — a base layer of CLIP/aesthetic-scored pairs (cheap, high volume) plus a top layer of LLM-judged or human-rated pairs (expensive, high quality).
Which preference-data source most directly tests prompt-adherence (does the image follow the text)?
#What Gets Fine-Tuned
| Target | Cost | Capacity | Used by |
|---|---|---|---|
| LoRA adapters on the UNet attention layers | Cheap (a single GPU) | Limited but surprisingly effective | Hobbyists, fast-iteration teams |
| Full UNet / DiT weights | Expensive (many GPUs) | Maximum | Well-funded labs (what each lab does is rarely published) |
| Just the text encoder | Very cheap | Limited (mostly prompt-adherence, no visual changes) | Specialized prompt-following fine-tunes |
A common community recipe is "full base model plus a DPO LoRA on top." Ship the base; let users mix in adapters at inference time with adjustable strength.
#Production Models That Use This
The labs behind most products do not publish how they tune them. What is public:
- Diffusion-DPO (Wallace et al. 2023). Reports gains on SD 1.5 and SDXL using human preference data (Pick-a-Pic).
- SDXL Turbo (Stability AI, 2023). Made with adversarial diffusion distillation (ADD) from the SDXL base. It is a distillation method, not a DPO-tuned model.
- FLUX.1 [pro] and [dev]. Black Forest Labs describes [dev] as distilled from [pro]. It does not publish a preference-tuning recipe for either, so this lesson makes no claim about one.
- DALL-E 3 (OpenAI, 2023). The technical report credits better prompt following to training on highly descriptive synthetic captions, not to preference training.
- Midjourney. No public technical details.
- Community adapters. People have trained Diffusion-DPO LoRAs for SDXL with the Wallace recipe; this lesson does not count or name them.
#Failure Modes and Mitigations
Preference-tuning is powerful and dangerous in equal measure. The standard failure modes:
- Reward hacking. The policy finds shortcut features that the reward model loves and that humans hate. Classic example: an aesthetic scorer trained on stock photos rewards warm color tones, so the DPO-tuned model starts adding brown haze to every image. The CLIP-score reward analogue: model learns to embed prompt-keywords as floating text overlays.
- Mode collapse. Preference fine-tuning narrows the output distribution. After enough DPO steps, the model produces a few "preferred" templates regardless of prompt — same composition, same color palette, same subject framing. Diversity drops; novel prompts get squeezed into known molds.
- Prompt-adherence loss. Aggressive aesthetic fine-tuning can hurt CLIP-score on prompt-following. The model gets prettier but stops listening to detailed prompts.
- Bias amplification. Reward models inherit human-rater biases — demographic, stylistic, cultural. Preference tuning amplifies these biases relative to the more diverse pretraining distribution.
The 2024-2025 mitigation playbook:
- Keep β large enough to anchor the policy to the reference. The KL term in DPO is your defense against drift.
- Mix preference data with non-preference SFT. Continue training on a plain pretraining-style noise-prediction loss for some fraction of every batch; this stops mode collapse by pinning the policy near the data distribution.
- Ensemble reward models. Use 3-5 different scoring models (PickScore + HPSv2 + CLIP + an LLM judge), take pairs only where multiple scorers agree on the winner. This filters reward-hacking shortcuts that game any single scorer.
- Out-of-distribution prompt evaluation. Hold out prompts that look unlike training-set prompts and measure CLIP, FID, and human ratings on them. Pure in-distribution metrics will hide drift.
- Iterate, do not finalize. Run DPO for one preference batch, evaluate, generate new preference data from the updated model, repeat. Single-shot DPO at scale tends to overshoot; iterative DPO with fresh preferences stays closer to the desired Pareto frontier.
In Diffusion-DPO, what is the primary role of the β coefficient (KL anchor strength)?
A team trains a Diffusion-DPO LoRA on SDXL with β set far too small (for example β=10 instead of a tuned value in the thousands). The aesthetic reward model strongly prefers images with warm tones. What is the most likely failure mode after a few thousand training steps?
#2024-2025 Advances
Four lines of work that push past basic Diffusion-DPO:
- D3PO (Yang et al. 2024) — applies the DPO idea to each denoising step, treating the chain as a decision process. No separate reward model is needed. Conceptually the same Bradley-Terry preference setup, applied step by step.
- Timestep weighting. An idea explored in follow-up work: instead of sampling a single t uniformly per training step, weight timesteps differently, for example emphasizing late-denoising steps (fine detail) over early steps (coarse structure). It changes the weighting, not the underlying loss.
- Reward-regression variants. Some 2024 methods skip pairwise preferences: train a regression reward model on absolute scores and plug the predicted reward into a DPO-style loss as a soft preference signal. Useful when you have scalar ratings rather than pairwise comparisons.
- SPIN-Diffusion (Yuan et al. 2024) — self-play preference optimization. The current model generates pairs of outputs, judges them against its previous checkpoint, and uses these self-generated preferences to fine-tune further. No new preference labels are needed. Echoes the SPIN paper for language models (Chen et al. 2024). Particularly attractive when human preference data is scarce or expensive.
Using Human Feedback to Fine-tune Diffusion Models without Any Reward Model (D3PO)
Kai Yang, Jian Tao, Jiafei Lyu et al. (2024)
Applies the DPO idea to each denoising step by treating the chain as a decision process, with no separate reward model.
Self-Play Fine-Tuning of Diffusion Models for Text-to-Image Generation (SPIN-Diffusion)
Huizhuo Yuan et al. (2024)
Self-play preference optimization. The model competes with its own prior checkpoint as judge — no external preference data needed.
#Online RL and Reward Gradients
#Group-relative policy gradient (Flow-GRPO style)
A_i = (r_i - mean(r)) / std(r)There is no separate value network to train. The group itself is the baseline: an image that beats its siblings gets a positive advantage, one that loses gets a negative one, and the advantages of a group always sum to zero. The update makes the winners' sampling moves more likely and the losers' less likely, with the clipped ratio and the KL anchor to a frozen reference that you met in the DDPO section.
Flow-GRPO: Training Flow Matching Models via Online RL
Jie Liu et al. (2025)
Applies group-relative policy gradients to flow-matching models by converting the sampling ODE into an SDE with the same marginals. Verify the paper for the exact SDE form (it depends on the time convention), the noise-level setting, the KL weight, any reduction in sampling steps during training, and every reported result.
The exact SDE drift, the noise schedule, how many steps are used in training versus at test time, and the benchmark numbers are details to verify in the paper. This lesson does not quote them.
#Reward gradients: backprop through sampling
If the scorer is a neural network, you can skip reinforcement learning. Sample a picture, score it, and send the score's gradient back through the sampling steps into the model's weights, the way you would train any network. This is usually far less noisy than a policy gradient because it uses the scorer's slope, not just the number it returns. The cost is memory: the gradient has to travel through every sampling step, so the methods cut the path short.
- ReFL (Reward Feedback Learning, from the ImageReward paper, Xu et al. 2023): pick one late step at random, jump from there to a predicted clean picture in one move, score that, and backpropagate from that single step.
- DRaFT (Clark et al. 2023): backpropagate through only the last K sampling steps (DRaFT-K). The paper also describes a lower-variance variant; verify the paper for how it works.
- AlignProp (Prabhudesai et al. 2023): backpropagate through the whole chain, made affordable with small adapters and checkpointing. Verify the paper for the memory tricks.
| Method | Needs a differentiable scorer | Learns from | Main risk |
|---|---|---|---|
| Diffusion-DPO | No | Fixed winner and loser pairs | Limited by the pairs you have |
| DDPO | No | Fresh samples, one reward per picture | Noisy gradient, tuning effort |
| Flow-GRPO style | No | Fresh groups, relative scores | Needs the ODE-to-SDE change, noisy gradient |
| ReFL, DRaFT | Yes | The scorer's gradient | Fast reward hacking, memory |
#A toy of both ideas, and of reward hacking
The lab below is deliberately tiny. A "picture" is a single number x drawn from a bell curve with mean mu. The scorer likes bigger x. What people truly want peaks at x = 3. The first part shows group-relative advantages for one made-up group of eight scores. The second part trains mu with group-relative advantages against the scorer and prints the scorer's number next to the true quality.
Tests: Check that the eight advantages sum to 0, that the proxy score rises at every printed step, and that true quality is highest at step 30 and lower at step 60.
The same idea with real weights needs a GPU and a differentiable scorer, so it does not run on this page. The sketch below shows a DRaFT-K style update. Copy it to Google Colab and fill in the placeholders for your model.
# Copy to Colab: needs torch, a diffusion model and a differentiable reward model.
# It is a sketch, not a runnable script: decode, reward_model and prompt are placeholders.
import torch
def draft_k_step(unet, scheduler, prompt_emb, prompt, optimizer, steps=30, K=3):
"""Backpropagate the reward through only the last K sampling steps."""
z = torch.randn(1, 4, 64, 64, device="cuda") # start from noise
scheduler.set_timesteps(steps)
for i, t in enumerate(scheduler.timesteps):
track = i >= steps - K # gradients only for the last K steps
with torch.set_grad_enabled(track):
eps = unet(z, t, encoder_hidden_states=prompt_emb).sample
z = scheduler.step(eps, t, z).prev_sample
if not track:
z = z.detach()
loss = -reward_model(decode(z), prompt).mean() # higher reward means lower loss
optimizer.zero_grad()
loss.backward()
optimizer.step()
return loss.item()Two honest limits. First, pick the method by the scorer you have: a differentiable scorer allows reward gradients, while a rule-based or black-box check needs the RL route. Second, whichever you pick, track a scorer the training never saw. If the training scorer keeps rising while the held-out one and human ratings stall or fall, you are watching the same split the toy printed: the scorer's number keeps rising while true quality falls.