Turning a pre-trained model into one that does what we want.
12 papers · 513 avg citations
Written by Junkun Yuan.
Click here to go back to main contents.
Table of contents ▼
UnifiedReward(arXiv 2025) VideoReward(NeurIPS 2025) ImageReward(NeurIPS 2023)
DiffusionART: Efficient, Stable and Scalable Reinforcement of Diffusion Models
National University of Singapore · Kuaishou Technology · HKUST
arXiv, 2026
Oct 08, 2026 DiffusionART (0) code (225)
Online RL pools each prompt's rewards into one reward–endpoint covariance and regresses it at ODE states in two updates per rollout.
Insight. Examine an RL objective by the forces it applies at each state, not by its loss. Hidden terms explained a collapse and its cure.
NFT as one regression (§2, Eq. 1). NFT draws endpoints per prompt from a frozen policy and maps rewards to . On , it regresses toward , with and . An EMA moves the rollout policy.
The hidden consistency force (§3.1, Prop. 1, Eq. 3). Take and the shared guidance (Lemma 1, Eq. 2) at . NFT's force is , where is the gap between the endpoints' forward velocity and the sampler's field.
EMA works by restoration (§3.2, Prop. 2, Eq. 4). With the drift and , . The quadratic term pulls back to and is zero on-policy. So the EMA lag gives stability, but the decay schedule needs tuning per task.
Tilting as a covariance (§4.1, Lemma 2). For , at every noise level.
Aggregation-first guidance (§4.1, Eq. 5). , . Each visited state has the target , with the cached rollout velocity . The RMS removes the reward scale, so no strength needs tuning.
Two updates per rollout (§4.2, Eq. 6). One step on each half of the rollout uses , with . The first step sees , and the second sees . Guidance dominates until the restoration grows with the drift.
KL proxy for an ODE (§4.3, Eq. 7, App. C.2). For ODE rollouts, a reference SDE step of mean and , with and the step , gives the per-coordinate KL .
Trust-region mask (§4.3, Eq. 8). with a fixed drops far states that move outward.
Experiments (§5). On SD3.5-M, FLUX.1-dev, HunyuanVideo and Wan2.1-I2V, FLUX gets GenEval 0.9684 (Flow-DPPO: 0.9183).
One pair per prompt is enough (Tab. 1). Winner/loser labels at give VQ 12.235 in 260.8 GPU hours. gives 12.092 in 883.3.
Reverse RL lowers VQ (Tab. 3). Flow-GRPO-Fast and DanceGRPO get VQ 3.149 and 3.922, below the base model's 5.195.
The training and sampling code. Follow Algorithm 1 of the paper.
def shift_time(t, shift=3.0):
return shift * t / (1 + (shift - 1) * t)
def guidance_direction(R, x0, eps=1e-5):
x = x0.flatten(2) # [prompts, K, D]
cov = ((R - R.mean(1, keepdim=True))[..., None] * (x - x.mean(1, keepdim=True))).mean(1) # Eq. 5
G = cov / cov.square().mean(1, keepdim=True).sqrt().clamp(min=eps) # Eq. 5. Equal rewards give G = 0.
return G.view(x0.shape[0], *x0.shape[2:])
def reference_kl(d, t, t_next, nu=0.8):
h = t - t_next
var = nu ** 2 * h * t / (1 - t) if t < 1 else nu ** 2 # sigma_ref^2. The release takes nu^2 at t = 1.
coef = h * (1 + nu ** 2 / 2) if t < 1 else h
return coef ** 2 * d.square().flatten(1).mean(1) / (2 * var) # Eq. 7
def train(
model, prompts, reward_fn, optimizer,
samples_per_prompt=24, num_steps=10, delta=1e-5, updates_per_rollout=2
):
# 1. Roll out the endpoints of each prompt with the plain ODE sampler. Cache every state and velocity.
P, K = len(prompts), samples_per_prompt
c = prompts.repeat_interleave(K, 0)
with no_grad():
x0, states, v_old, t = sample(model, c, num_steps)
R = reward_fn(x0, c).view(P, K) # black-box scalar, no reward gradient
# 2. Pool the rewards and endpoints of each prompt into one direction, and freeze the targets.
G = guidance_direction(R, x0.view(P, K, *x0.shape[1:])).repeat_interleave(K, 0)
v_tgt = v_old + G[:, None] # Alg. 1 line 3, at every visited state
# 3. Take one optimizer step on each disjoint part of the trajectories.
for rows in torch.randperm(P * K).chunk(updates_per_rollout):
for i in range(num_steps):
v = model(states[rows, i], t[i], c[rows])
d = v - v_old[rows, i] # zero in the first update
outward = (d * (G[rows] - d)).flatten(1).mean(1) > 0
w = t[i] * (1 - ((reference_kl(d, t[i], t[i + 1]) >= delta) & outward).float()) # Eq. 8
loss = (w * (v - v_tgt[rows, i]).square().flatten(1).mean(1)).mean() # Eq. 6
(loss / num_steps).backward()
optimizer.step()
optimizer.zero_grad()
def sample(model, c, num_steps=40):
t = shift_time(linspace(1, 0, num_steps + 1))
x = torch.randn(len(c), 16, 64, 64)
states, vs = [], []
for i in range(num_steps):
v = model(x, t[i], c)
states.append(x)
vs.append(v)
x = x + (t[i] - t[i + 1]) * v # v points to data, as in the paper
return x, torch.stack(states, 1), torch.stack(vs, 1), tFinite Difference Flow Optimization for RL Post-Training of Text-to-Image Models
UC Berkeley · NVIDIA
European Conference on Computer Vision (ECCV), 2026
Mar 13, 2026 FDFO (8) code (121)
Each step of a pair of trajectories from one noise moves toward their reward-weighted image difference. The whole run is one action.
Insight. Diffusion RL may not need credit for each step. The difference of two paired runs gives a reward gradient cheap enough for raters.
Paired rollouts (§4). Two rollouts and start from one noise . Their final images , and the reward give , . Training moves the velocities at all steps of both rollouts toward the reward-weighted image difference .
Stochastic sampler (Alg. 1, App. B.1). Each step overshoots to Eq. (4), with the noise fraction . An Euler step gives , and new noise returns it to : Eq. (5).
Normalized difference (§4.3). To first order , so counts the distance twice. The signal is .
Clipped objective (Alg. 2). PPO's ratio needs a likelihood. So the stored velocity gets the target . The current one gives the proxy ratio in SPO's loss with the clip range .
Experiments (§5). SD3.5-M with the reward PickScore + VLM alignment/10 gets OneIG 82.13, against 71.06 for Flow-GRPO.
The exact gradient does not help (Fig. 8 I–J). The true reward gradient gives 81.47. The gradient through the SDE gives 66.69.
The training and sampling code. Follow Algorithm 1 and 2 of the paper.
def churn_step(x, v, t, s, gamma=0.0025):
t_over = s / (1 - gamma * s + gamma) # Eq. 4
x_over = x + (t_over - t) * v # Euler step beyond s
noise = torch.randn_like(x)
return (x_over + t_over * (gamma ** 2 + 2 * gamma) ** 0.5 * noise) / (gamma * t_over + 1) # Eq. 5
def partner(a):
return a.view(-1, 2, *a.shape[1:]).flip(1).reshape(a.shape) # rows 2i and 2i + 1 swap
def reward(image, c, vlm_weight=0.1):
r_vlm = 100 * torch.sigmoid(vlm_logit(image, c, "Yes") - vlm_logit(image, c, "No")) # Qwen2.5-VL-7B
return pickscore(image, c) + vlm_weight * r_vlm
def spo_loss(v_cur, v_ref, dR, dx, clip_range=0.03):
v_target = (v_ref - dx).detach() # t falls, so -dx moves x by +dx
ps = -(v_target - v_cur).square().mean(dim=(1, 2, 3)) # means over pixels, not sums
ps_ref = -(v_target - v_ref).square().mean(dim=(1, 2, 3))
ratio = torch.exp(ps - ps_ref)
return -dR * ratio - dR.abs() / (2 * clip_range) * (ratio - 1) ** 2 # release: + (ratio - 1) ** 2
def train(model, x_t, t, c, v_ref, dR, dx):
# 1. Predict the current velocity at a stored state of either branch.
v_cur = model(x_t, t, c)
# 2. Calculate the SPO loss toward the reference velocity shifted by the pair's difference.
loss = spo_loss(v_cur, v_ref, dR, dx).mean()
def sample(model, c, num_steps=40, gamma=0.0025):
# 1. Draw one seed per pair, and churn it once per branch.
eps = torch.randn(bs, 16, 64, 64).repeat_interleave(2, dim=0)
x = (eps + (gamma ** 2 + 2 * gamma) ** 0.5 * torch.randn_like(eps)) / (gamma + 1)
c = c.repeat_interleave(2, dim=0)
# 2. Run both branches with the churned Euler sampler. The last step is deterministic.
ts = sd3_timesteps(num_steps) # 1 -> 0, shift 3
xs, vs = [], []
with no_grad():
for i in range(num_steps):
v = model(x, ts[i], c)
xs.append(x)
vs.append(v)
x = churn_step(x, v, ts[i], ts[i + 1], gamma if i < num_steps - 1 else 0.0)
# 3. Score the pair. The difference of each branch points from its partner to that branch.
r = reward(vae_decode(x), c)
dR = (r - partner(r)) / 2
dx = (x - partner(x)) / 2
dx = dx / (dx.square().mean(dim=(1, 2, 3), keepdim=True) + 1e-6) # normalized by ||dx||^2_RMS
return stack(xs, 1), stack(vs, 1), ts[:-1], c, dR, dxAdvantage Weighted Matching: Aligning RL with Pretraining in Diffusion Models
UCAS · Adobe Research · HKU · MIT
International Conference on Machine Learning (ICML), 2026
Sep 29, 2025 AWM (77) code (100)
DDPO is denoising score matching with noisy targets. AWM keeps the pretraining loss and weights each sample by its advantage.
Insight. Policy-gradient RL is pretraining with noisier targets. An advantage-weighted pretraining loss lets RL reuse the pretraining recipe.
DDPO as score matching (Thm 1, Eq. 6). A DDPO step with its Gaussian likelihood Eq. (4) targets . This is score matching on a noisy , not on the clean . It has the same minimizer but a target of higher variance (Lemma 1, Thm 2).
One-step MDP and its likelihood (§4, Eq. 10). The state is the prompt , and the action is the clean image . The flow-matching surrogate gives , with the uniform . It works better than the ELBO weight Eq. (2).
GRPO on the surrogate (Eq. 9, 11–12). In GRPO's Eq. (9), the ratio is Eq. (11), with . Both policies share and to cut variance, with one ratio per image. The velocity-space KL is Eq. (12).
The gradient (§4). On-policy, the update is , a scaled pretraining gradient. So any sampler can roll out.
Experiments (§5). On SD3.5-M, AWM reaches GenEval 0.95 with 8× less compute than Flow-GRPO, and OCR 0.89 with 23.6× less.
The prior matters (§5.2). Uniform and the sampler's grid score equally. Logit-normal, pretraining's default, lags and then degrades.
The training and sampling code. Follow Algorithm 1 of the paper.
def shift_time(t, shift=3.0):
return shift * t / (1 + (shift - 1) * t)
def awm_log_prob(v, x0, noise, t, ghuber_power=0.5):
mse = (v - (noise - x0)).square().flatten(1).mean(1) # Eq. 10, the flow-matching loss
return -((mse + 1e-10) ** ghuber_power - 1e-10 ** ghuber_power) * t / ghuber_power # generalized Huber, times t
def sample_train_steps(num_steps=14, train_timesteps=6, timestep_fraction=0.9):
edges = linspace(1, int(num_steps * timestep_fraction), train_timesteps).long()
idx = edges[:-1] + (torch.rand(train_timesteps - 1) * (edges[1:] - edges[:-1])).long() # one per bin
return cat([torch.zeros(1).long(), idx]) # the sampler's first step always trains
def group_advantage(rewards, num_image_per_prompt=24, adv_clip_max=5.0, advantage_max=1.0):
r = rewards.view(-1, num_image_per_prompt)
adv = (r - r.mean(1, keepdim=True)) / (rewards.std(unbiased=False) + 1e-4) # per-prompt mean, global std
return adv.flatten().clamp(-adv_clip_max, adv_clip_max) / adv_clip_max * advantage_max
def train(
model, ref_model, ema_model, prompts, reward_fn, optimizer, step,
num_image_per_prompt=24, beta=0.003, ema_beta=1.0, base_kl_cfg_scale=4.5, clip_range=1.0,
kl_ema_decay=0.3, kl_ema_decay_rate=0.001
):
# 1. Roll out images with any sampler and score them.
c = prompts.repeat_interleave(num_image_per_prompt, 0)
with no_grad():
x0, t_grid = sample(model, c)
adv = group_advantage(reward_fn(x0, c), num_image_per_prompt)
# 2. Add noise to each image once per training timestep.
for t in t_grid[sample_train_steps()]:
noise = torch.randn_like(x0) # shared by all images of a prompt
x_t = (1 - t) * x0 + t * noise
# 3. Calculate the ratio of the matching-loss likelihoods, one ratio per image.
v = model(x_t, t, c)
log_p = awm_log_prob(v, x0, noise, t)
ratio = torch.exp(log_p - log_p.detach()) # Eq. 11. On-policy, the old policy is the current one.
policy_loss = torch.maximum(-adv * ratio, -adv * ratio.clamp(1 - clip_range, 1 + clip_range)).mean()
# 4. Add the velocity-space KL to the guided base model and to the EMA copy.
with no_grad():
v_ref_u, v_ref_c = ref_model(x_t, t, null), ref_model(x_t, t, c)
v_ref = v_ref_u + base_kl_cfg_scale * (v_ref_c - v_ref_u)
v_ema = ema_model(x_t, t, c)
kl = (v - v_ref).square().flatten(1).mean(1).mean() # Eq. 12, w(t) = 1
ema_kl = (v - v_ema).square().flatten(1).mean(1).mean()
(policy_loss + beta * kl + ema_beta * ema_kl).backward()
optimizer.step()
# 5. Move the EMA copy toward the policy. Its decay increases linearly.
decay = min(kl_ema_decay, kl_ema_decay_rate * step)
for p_ema, p in zip(ema_model.parameters(), model.parameters()):
p_ema.data = decay * p_ema.data + (1 - decay) * p.data
def sample(model, c, num_steps=14, noise_level=0.4):
t = shift_time(linspace(1, 0, num_steps + 1))
t[0], t[-2] = 1 - 1e-3, t[-3] / 2
x = torch.randn(len(c), 16, 64, 64)
tau = lambda s: noise_level if 0.3 <= s <= 0.9 else 0.0 # noise only in the middle of the trajectory
x = sa_solver(model, x, t, c, tau, predictor_order=2, corrector_order=2) # no CFG
return x, tDiffusionNFT: Online Diffusion Reinforcement with Forward Process
Tsinghua University · NVIDIA · Stanford University
International Conference on Learning Representations (ICLR), 2026
Sep 19, 2025 DiffusionNFT (268) code (1.1K)
Online RL on the forward process: one flow-matching loss learns the positive and negative policies that the reward defines on the rollouts.
Insight. RL on the forward process needs no likelihoods or SDE samplers. Unlike in language models, negative samples are necessary.
Positive and negative policies (§3.1). The reward is , the probability that the image for the prompt is good. Bayes' rule on the old policy gives and .
Implicit policies (§3.2). The trained network and the frozen old-policy network give , , where . So the two implicit policies are symmetric about , with the step along .
Reinforcement guidance (Eq. 3–4). As in CFG, the target is Eq. (3), where is the improvement direction and is its strength. are the velocities of , and Eq. (4), with for the noised image .
One loss (Eq. 5–6). Flow matching on weights the rollouts by : , where is the target velocity and is the noise. The same step on gives the loss , with the optimum Eq. (6).
Reward to probability (Alg. 1). The raw reward becomes , where the mean is over the group of the prompt and is 5 times the global standard deviation of the reward. Thus is group-relative and stays a probability.
Intuition. With , the error of the old policy on a sample, each term of Eq. (5) is . So , with and . By Alg. 1, is the clipped group advantage. Thus the method starts from the old policy. It moves the velocity target of each sample toward when , or reflects it about when , and then does a plain regression of .
Soft update of the old policy (§3.3). The old policy is an EMA copy of the model, , with at iteration . A small learns fast but can be unstable, and a large is stable but slow. The training loss needs no importance ratio.
Loss weighting (§3.3). A self-normalized regression replaces the time weight of the flow-matching loss, so no time weight needs manual tuning: , where is the predicted clean image and is the stop-gradient operator.
Any solver, no CFG (§3.2). Training needs only clean images, so any solver can make the rollouts. The policy starts without CFG.
Experiments (§4). SD3.5-M without CFG reaches GenEval 0.94, above SD3.5-L with CFG, and is 3–25× faster than Flow-GRPO.
Positive samples alone collapse (§4.4). Without , the reward collapses. But language models train well on positive samples alone.
The training and sampling code. Follow Algorithm 1 of paper.
1. Prepare the group data for one epoch of training.
def prepare_data(dataset, epoch, seed=42, num_batches=16, num_groups=3, group_size=24):
prompts = []
for i in range(num_batches):
# Make sure the sample order is the same across ranks.
g = torch.Generator()
g.manual_seed(seed + epoch * num_batches + i)
# Pick the first num_groups samples, for example ["dog", "sun", "car"].
indices = torch.randperm(len(dataset), generator=g)[:num_groups]
# Repeat each sample to make the groups, for example ["dog", "dog", "sun", "sun", "car", "car"].
repeated = [idx for idx in indices.tolist() for _ in range(group_size)]
# Shuffle the samples, so that each batch contains samples from different groups.
order = torch.randperm(len(repeated), generator=g).tolist()
prompts += [dataset[repeated[k]] for k in order] # one global batch of num_groups whole groups
return prompts
2. Calculate the group advantages.
def group_advantages(prompts, rewards):
prompts = np.array(prompts)
adv = np.zeros_like(rewards)
std = rewards.std() + 1e-4 # one std over all groups
for p in np.unique(prompts):
group = rewards[prompts == p]
adv[prompts == p] = (group - group.mean()) / std # Alg. 1 line 4
return adv
3. Roll out the prompts.
def sample(model, c, num_steps=10, solver="dpm2", resolution=512):
x = torch.randn(len(c), 16, resolution // 8, resolution // 8)
sigmas = sd3_sigmas(num_steps) # 1 -> 0, shift 3
x0_preds = []
for i in range(num_steps):
v = model(x, (sigmas[i] * 1000).expand(len(c)), c) # no CFG
if solver == "flow":
x = x + (sigmas[i + 1] - sigmas[i]) * v # Euler
else:
x0_preds.append(x - sigmas[i] * v)
x = dpm2_step(x0_preds, x, sigmas, i) # 2nd-order multistep DPM-Solver
return x, sigmas[:-1] * 1000
def rollout(old_model, prompts, reward_fn, batch_size=9, num_steps=10):
# Sample each batch of prompts with the old policy. Keep only the clean latents and calculate their rewards.
batches = []
for k in range(0, len(prompts), batch_size):
p = prompts[k:k + batch_size]
c = encode_prompt(p)
with no_grad():
x0, timesteps = sample(old_model, c, num_steps)
order = torch.stack([torch.randperm(num_steps) for _ in p]) # each image's own timestep order
batches.append({
"prompt_embeds": c,
"latents": x0,
"timesteps": timesteps.repeat(len(p), 1).gather(1, order),
"rewards": reward_fn(vae_decode(x0), p),
})
samples = {k: torch.cat([b[k] for b in batches]) for k in batches[0]}
# Calculate the group-relative advantages over all samples of the epoch.
samples["advantages"] = torch.as_tensor(group_advantages(prompts, samples.pop("rewards").numpy()))
return samples
4. Train one step.
def adaptive_x0_loss(x0_pred, x0, eps=1e-5):
weight = (x0_pred - x0).abs().flatten(1).mean(1).clip(min=eps).detach() # each sample's mean error
return (x0_pred - x0).square().flatten(1).mean(1) / weight
def train(model, old_model, batch, j, beta=1.0, kl_beta=1e-4, adv_clip_max=5.0):
# 1. Add noise to the clean latents at the j-th timestep of each image.
x0, c, timesteps = batch["latents"], batch["prompt_embeds"], batch["timesteps"][:, j]
t = (timesteps / 1000).view(-1, 1, 1, 1)
noise = torch.randn_like(x0)
x_t = (1 - t) * x0 + t * noise # Alg. 1 line 9
# 2. Predict the velocities of the old, trained, and reference policies.
with no_grad():
v_old = old_model(x_t, timesteps, c)
with model.disable_adapter():
v_ref = model(x_t, timesteps, c) # the base model with LoRA off
v = model(x_t, timesteps, c)
# 3. Map the advantages to optimality probabilities.
adv = torch.clamp(batch["advantages"], -adv_clip_max, adv_clip_max)
r = adv / adv_clip_max / 2 + 0.5 # Alg. 1 line 5
# 4. Calculate the loss of the implicit positive and negative policies.
v_pos = beta * v + (1 - beta) * v_old # see paper Eq. 5; Alg. 1 line 10
v_neg = (1 + beta) * v_old - beta * v # see paper Eq. 5; Alg. 1 line 11
loss_pos = adaptive_x0_loss(x_t - t * v_pos, x0)
loss_neg = adaptive_x0_loss(x_t - t * v_neg, x0)
policy_loss = ((r * loss_pos + (1 - r) * loss_neg) / beta * adv_clip_max).mean() # Eq. 5
# 5. Add the KL to the reference policy as the squared velocity difference.
kl = (v - v_ref).square().flatten(1).mean(1)
return policy_loss + kl_beta * kl.mean()
5. Train for one epoch.
def soft_update(old_model, model, step, eta_rate=0.001, eta_max=0.5, eta_delay=0):
eta = 0.0 if step < eta_delay else min((step - eta_delay) * eta_rate, eta_max)
for p_old, p in zip(old_model.parameters(), model.parameters()):
p_old.data = eta * p_old.data + (1 - eta) * p.data # Alg. 1 line 14
def train_epoch(
model, old_model, optimizer, dataset, reward_fn, epoch, step,
batch_size=9, updates_per_epoch=1, max_grad_norm=1.0, num_steps=10, timestep_fraction=0.99
):
# Roll out the prompts of one epoch with the old policy, the EMA of the model.
prompts = prepare_data(dataset, epoch)
samples = rollout(old_model, prompts, reward_fn, batch_size, num_steps)
# Keep all samples, because a zero advantage also trains (r = 0.5). Shuffle them and divide them into batches.
num_batches = len(prompts) // batch_size
perm = torch.randperm(len(samples["advantages"]))
batches = [
{k: v[perm[b * batch_size:(b + 1) * batch_size]] for k, v in samples.items()} for b in range(num_batches)
]
# Accumulate the loss of each trained timestep, and update the model updates_per_epoch times.
accu, T = num_batches // updates_per_epoch, int(num_steps * timestep_fraction)
for b, batch in enumerate(batches):
for j in range(T):
(train(model, old_model, batch, j) / (accu * T)).backward()
if (b + 1) % accu == 0:
clip_grad_norm_(model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
step += 1
# Soft-update the old policy toward the trained model, with eta from the optimizer step count.
soft_update(old_model, model, step)
return stepDanceGRPO: Unleashing GRPO on Visual Generation
ByteDance Seed · HKU
arXiv, 2025
May 12, 2025 DanceGRPO (433) code (1.7K)
Concurrent with Flow-GRPO, it took GRPO to production scale for image and video. Its shared-noise groups and timestep dropout are standard parts of video RL.
One GRPO recipe covers diffusion and rectified flow and image, video and image-to-video, with the changes that each scale needs.
Insight. In visual GRPO, the recipe matters more than the algorithm. Shared group noise and timestep subsampling let it span modalities.
One update rule (§2.1, Eq. 5). Diffusion and rectified flow both step , with , for -prediction and , for flow. So one MDP Eq. (6) with the state , the action and a reward at covers both paradigms.
Flow SDE (Eq. 8). The ODE cannot explore, so sample with the noise level , as Eq. (7) does for diffusion. The closed-form score of gives a per-step Gaussian policy .
The objective (Eq. 9–10). For samples of a prompt, all steps share Eq. (10), because the rewards are sparse. It enters Eq. (9), with and . The KL has little effect, so DanceGRPO omits it.
Shared noise (§2.2). All samples of a prompt start from the same . Different noise per sample causes reward hacking in video.
Timestep selection (Alg. 1). Each iteration trains random steps out of , with , because the others are not necessary.
Multiple rewards (Alg. 1). Rewards differ in scale, so normalize the advantages per model and sum them: .
Experiments (§3). On SD1.4, FLUX, HunyuanVideo and SkyReels-I2V, SD1.4 HPS goes 0.239 → 0.365, against 0.297 for DDPO.
Rewards trade off (§3.2–3.3). With HPS, FLUX falls 0.659 → 0.561 on GenEval. HunyuanVideo's text alignment falls 1.75 → 1.59.
The training and sampling code. Follow Algorithm 1 of the paper.
def shift_time(t, shift=3.0):
return shift * t / (1 + (shift - 1) * t)
def sde_step(v, z, sigma, sigma_next, z_next=None, eta=0.3):
x0 = z - sigma * v # the step's clean prediction
score = -(z - (1 - sigma) * x0) / sigma ** 2 # closed-form Gaussian score
mean = z + (sigma_next - sigma) * (v - 0.5 * eta ** 2 * score) # Eq. 8
std = eta * math.sqrt(sigma - sigma_next)
if z_next is None:
z_next = mean + std * torch.randn_like(z)
log_prob = -(z_next.detach() - mean) ** 2 / (2 * std ** 2) - math.log(std) - math.log(math.sqrt(2 * math.pi))
return z_next, x0, log_prob.flatten(1).mean(1)
def group_advantage(rewards, num_generations=12):
r = rewards.view(-1, num_generations)
return ((r - r.mean(1, keepdim=True)) / (r.std(1, keepdim=True) + 1e-8)).flatten() # Eq. 10
def train(
model, prompts, reward_fns, optimizer,
num_generations=12, sampling_steps=16, timestep_fraction=0.6, clip_range=1e-4, adv_clip_max=5.0
):
# 1. Roll out a group per prompt from one shared noise.
c = prompts.repeat_interleave(num_generations, 0)
noise = torch.randn(len(prompts), 16, 90, 90).repeat_interleave(num_generations, 0) # one noise per group
with no_grad():
x0, zs, old_log_probs, sigmas = sample(model, c, noise, sampling_steps)
# 2. Sum the group advantages of every reward model.
adv = sum(group_advantage(reward_fn(x0, c), num_generations) for reward_fn in reward_fns) # Alg. 1 line 8
adv = adv.clamp(-adv_clip_max, adv_clip_max)
# 3. Keep a random subset of the steps. The last step is never trained.
steps = torch.randperm(sampling_steps - 1)[:int((sampling_steps - 1) * timestep_fraction)]
# 4. Calculate the log-prob of each kept step again and take the clipped-ratio loss.
for i in steps:
v = model(zs[:, i], sigmas[i], c)
_, _, log_prob = sde_step(v, zs[:, i], sigmas[i], sigmas[i + 1], z_next=zs[:, i + 1])
ratio = torch.exp(log_prob - old_log_probs[:, i])
loss = torch.maximum(-adv * ratio, -adv * ratio.clamp(1 - clip_range, 1 + clip_range)).mean() # Eq. 9
(loss / len(steps)).backward()
optimizer.step()
def sample(model, c, z, sampling_steps=16):
sigmas = shift_time(linspace(1, 0, sampling_steps + 1))
zs, log_probs = [z], []
for i in range(sampling_steps):
z, x0, log_prob = sde_step(model(z, sigmas[i], c), z, sigmas[i], sigmas[i + 1])
zs.append(z)
log_probs.append(log_prob)
return x0, torch.stack(zs, 1), torch.stack(log_probs, 1), sigmasFlow-GRPO: Training Flow Matching Models via Online RL
CUHK · Tsinghua University · Kuaishou Technology · Nanjing University · Shanghai AI Laboratory
Advances in Neural Information Processing Systems (NeurIPS), 2025
May 08, 2025 Flow-GRPO (733) code (2.6K)
It brought online RL to flow models with an ODE-to-SDE conversion. This conversion gave a flow a policy, and every later flow RL method starts from it.
A flow model has no randomness to explore. Flow-GRPO converts its ODE into an equivalent SDE, so GRPO applies almost unchanged.
Insight. Noise that keeps the marginals lets policy gradients train deterministic flows. Later flow RL methods use it as the baseline to beat.
The MDP (§3). DDPO uses , and a reward at . But a flow's deterministic ODE cannot explore.
ODE to SDE (§4, Eq. 7). A same-marginal reverse SDE is , with its score from in Eq. (8).
The sampler (Eq. 9). Euler–Maruyama on Eq. 8 gives , with and because goes 1 → 0. The noise level in controls exploration. At , it is the deterministic ODE.
Gaussian policy and KL (§4). , with from Eq. 9. The KL is closed-form.
The objective (Eq. 4–5). For images of one prompt , all steps share the advantage in , averaged over and , with . There is no value network.
Denoising reduction (§4). Roll out at and evaluate at . It is over 4× faster, because coarse trajectories rank the same.
Experiments (§5). On SD3.5-M, Flow-GRPO raises GenEval from 0.63 to 0.95, above GPT-4o's 0.84, and OCR from 0.59 to 0.92.
KL is not early stopping (§5.3). Without the KL, GenEval is 0.95, but DrawBench aesthetics fall 5.39 → 4.93 and diversity collapses.
Templates transfer (§5.3). Trained on 60 GenEval classes, it goes 0.64 → 0.90 on 20 unseen ones. It learns relations, not prompts.
The training and sampling code. Follow §4 of the paper.
1. Prepare the group data for one epoch of training.
def prepare_data(dataset, epoch, seed=42, num_batches=4, num_groups=12, group_size=24):
prompts = []
for i in range(num_batches):
# Make sure the sample order is the same across ranks.
g = torch.Generator()
g.manual_seed(seed + epoch * num_batches + i)
# Pick the first num_groups samples, for example ["dog", "sun", "car"].
indices = torch.randperm(len(dataset), generator=g)[:num_groups]
# Repeat each sample to make the groups, for example ["dog", "dog", "sun", "sun", "car", "car"].
repeated = [idx for idx in indices.tolist() for _ in range(group_size)]
# Shuffle the samples, so that each batch contains samples from different groups.
order = torch.randperm(len(repeated), generator=g).tolist()
prompts += [dataset[repeated[k]] for k in order] # one global batch of num_groups whole groups
return prompts
2. Calculate the group advantages.
def group_advantages(prompts, rewards):
prompts = np.array(prompts)
adv = np.zeros_like(rewards)
std = rewards.std() + 1e-4 # one std over all groups
for p in np.unique(prompts):
group = rewards[prompts == p]
adv[prompts == p] = (group - group.mean()) / std # Eq. 4
return adv
3. Roll out the prompts.
def sde_step(v, x, sigma, sigma_prev, sigma_max, noise_level=0.7, x_prev=None):
dt = sigma_prev - sigma # dt < 0: sigma runs 1 -> 0
std_t = noise_level * torch.sqrt(sigma / (1 - torch.where(sigma == 1, sigma_max, sigma))) # a sqrt(t / (1 - t))
mean = x + (v + std_t ** 2 / (2 * sigma) * (x + (1 - sigma) * v)) * dt # Eq. 9
std = std_t * torch.sqrt(-dt)
if x_prev is None:
x_prev = mean + std * torch.randn_like(x)
log_prob = -(x_prev.detach() - mean) ** 2 / (2 * std ** 2) - torch.log(std) - math.log(math.sqrt(2 * math.pi))
return x_prev, log_prob.mean(dim=(1, 2, 3)), mean, std_t
def guided_v(model, x, t, c, guidance_scale=4.5):
v_u, v_c = model(cat([x, x]), cat([t, t]), cat([null, c])).chunk(2)
return v_u + guidance_scale * (v_c - v_u)
def sample(model, c, num_steps=10, guidance_scale=4.5, noise_level=0.7, resolution=512):
x = torch.randn(len(c), 16, resolution // 8, resolution // 8)
sigmas = sd3_sigmas(num_steps) # 1 -> 0, shift 3
latents, log_probs = [x], []
for i in range(num_steps):
v = guided_v(model, x, (sigmas[i] * 1000).expand(len(c)), c, guidance_scale)
x, log_prob, _, _ = sde_step(v, x, sigmas[i], sigmas[i + 1], sigmas[1], noise_level)
latents.append(x)
log_probs.append(log_prob)
return torch.stack(latents, dim=1), torch.stack(log_probs, dim=1), sigmas # noise_level=0: the ODE sampler
def rollout(model, prompts, reward_fn, batch_size=9, num_steps=10, timestep_fraction=0.99):
# Sample each batch of prompts with the SDE, and calculate the rewards of its images.
T = int(num_steps * timestep_fraction) # the last step is never trained
batches = []
for k in range(0, len(prompts), batch_size):
p = prompts[k:k + batch_size]
c = encode_prompt(p)
with no_grad():
latents, log_probs, sigmas = sample(model, c, num_steps)
batches.append({
"prompt_embeds": c,
"log_probs": log_probs[:, :T],
"latents": latents[:, :T],
"next_latents": latents[:, 1:T + 1],
"steps": torch.arange(T).repeat(len(p), 1),
"timesteps": (sigmas[:T] * 1000).repeat(len(p), 1),
"rewards": reward_fn(vae_decode(latents[:, -1]), p),
})
samples = {k: torch.cat([b[k] for b in batches]) for k in batches[0]}
# Calculate the group-relative advantages over all samples of the epoch.
samples["advantages"] = torch.as_tensor(group_advantages(prompts, samples.pop("rewards").numpy()))
return samples, sigmas
4. Train one step.
def train(model, batch, j, sigmas, noise_level=0.7, clip_range=1e-4, adv_clip_max=5.0, beta=0.04):
# 1. Get the stored step j of each sample.
x, x_prev = batch["latents"][:, j], batch["next_latents"][:, j]
c, t = batch["prompt_embeds"], batch["timesteps"][:, j]
i = batch["steps"][:, j].view(-1, 1, 1, 1)
sigma, sigma_prev = sigmas[i], sigmas[i + 1]
# 2. Calculate the log prob of the stored next latent again under the current policy.
v = guided_v(model, x, t, c)
_, log_prob, mean, std_t = sde_step(v, x, sigma, sigma_prev, sigmas[1], noise_level, x_prev=x_prev)
# 3. Calculate the clipped policy loss.
adv = torch.clamp(batch["advantages"], -adv_clip_max, adv_clip_max)
ratio = torch.exp(log_prob - batch["log_probs"][:, j])
clipped = torch.clamp(ratio, 1 - clip_range, 1 + clip_range)
policy_loss = torch.maximum(-adv * ratio, -adv * clipped).mean() # Eq. 5
# 4. Add the closed-form KL to the reference policy, the base model with LoRA off.
with no_grad(), model.disable_adapter():
v_ref = guided_v(model, x, t, c)
_, _, mean_ref, _ = sde_step(v_ref, x, sigma, sigma_prev, sigmas[1], noise_level, x_prev=x_prev)
kl = ((mean - mean_ref) ** 2).mean(dim=(1, 2, 3)) / (2 * std_t.flatten() ** 2)
return policy_loss + beta * kl.mean() # Eq. 5
5. Train for one epoch.
def filter_samples(samples, num_batches):
mask = samples["advantages"] != 0 # drop the groups whose rewards are all equal
true_count = mask.sum()
if true_count % num_batches != 0 or true_count == 0: # pad back to a multiple of num_batches
false_indices = torch.where(~mask)[0]
num_to_change = num_batches - true_count % num_batches
if len(false_indices) >= num_to_change:
mask[false_indices[torch.randperm(len(false_indices))[:num_to_change]]] = True
return {k: v[mask] for k, v in samples.items()}
def train_epoch(model, optimizer, dataset, reward_fn, epoch, batch_size=9, updates_per_epoch=2, max_grad_norm=1.0):
# Roll out the prompts of one epoch.
prompts = prepare_data(dataset, epoch)
samples, sigmas = rollout(model, prompts, reward_fn, batch_size)
# Filter the samples, shuffle them, and divide them into the fixed number of batches.
num_batches = len(prompts) // batch_size
samples = filter_samples(samples, num_batches)
perm = torch.randperm(len(samples["advantages"]))
size = len(perm) // num_batches # the actual batch size
batches = [{k: v[perm[b * size:(b + 1) * size]] for k, v in samples.items()} for b in range(num_batches)]
# Accumulate the loss of each trained step, and update the model updates_per_epoch times.
accu, num_steps = num_batches // updates_per_epoch, samples["steps"].shape[1]
for b, batch in enumerate(batches):
for j in range(num_steps):
(train(model, batch, j, sigmas) / (accu * num_steps)).backward()
if (b + 1) % accu == 0:
clip_grad_norm_(model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()Diffusion Model Alignment Using Direct Preference Optimization
Salesforce AI · Stanford University
Conference on Computer Vision and Pattern Recognition (CVPR), 2024
Nov 21, 2023 Diffusion-DPO (977) code (715)
It made preference alignment of image models a fine-tuning task on a static dataset, and it became the default first method to try.
DPO for diffusion: a pairwise preference loss only asks the model to improve on the winner more than it does on the loser of the pair.
Insight. Offline preference pairs align a diffusion model with no reward model or sampling. Online methods must beat this cheap baseline.
Reward from the policy (Eq. 3–7). For a prompt , a winner and a loser , Bradley–Terry is Eq. (3). The optimum of the reward minus times the KL to a reference Eq. (5) is Eq. (7).
DPO (Eq. 8). In Eq. 3 the partition function cancels, so .
Path DPO (§4, Eq. 9–11). marginalizes all paths . So a chain reward with Eq. (9) and the path KL Eq. (10) turn Eq. 8 into whole-path ratios Eq. (11) under the reverse process . It is intractable to sample over all steps.
Forward process and Jensen (Eq. 12–13). Replace the reverse process with the forward , so training needs only the fixed dataset. Sample one step and scale the loss by . Jensen on the convex makes each log-ratio a difference of two Gaussian KLs.
The objective (Eq. 14). : denoise the winner better than the reference does, and the loser worse. absorbs the constant , as in Eq. (46): for SDXL and for SD1.5.
Experiments (§5). Tuned on Pick-a-Pic v2, DPO-SDXL wins 70.0% / 64.7% of votes against SDXL-base on PartiPrompts / HPSv2.
Implicit reward model (§5.5). As a classifier, Eq. 14's inner term gets 72.0% on Pick-a-Pic for DPO-SDXL, and PickScore gets 64.2.
Pseudo-labels are better than labels (§5.4). When PickScore ranks the pairs, the PartiPrompts win rate goes from 59.8% to 63.3%.
The training code. Follow Eq. 14 of the paper. Sampling is the same as for the base model.
def denoising_error(unet, x_t, t, c, noise):
return (unet(x_t, t, c) - noise).square().mean(dim=(1, 2, 3)) # means over latent dims
def train(unet, unet_ref, x_w, x_l, c, beta_dpo=5000.0, caption_dropout=0.2):
# 1. Drop the caption. Then draw one timestep and one noise for both the winner and the loser.
c = where(rand(len(c)) < caption_dropout, null, c)
t = torch.randint(0, 1000, (x_w.shape[0],))
noise = torch.randn_like(x_w)
# 2. Add the same noise to both images at the same t.
x_w_t = alphas_cumprod[t].sqrt() * x_w + (1 - alphas_cumprod[t]).sqrt() * noise
x_l_t = alphas_cumprod[t].sqrt() * x_l + (1 - alphas_cumprod[t]).sqrt() * noise
# 3. Calculate the margin by which the model denoises the winner better than the loser.
model_diff = denoising_error(unet, x_w_t, t, c, noise) - denoising_error(unet, x_l_t, t, c, noise)
# 4. Calculate the same margin for the frozen reference model.
with no_grad():
ref_diff = denoising_error(unet_ref, x_w_t, t, c, noise) - denoising_error(unet_ref, x_l_t, t, c, noise)
# 5. Calculate the DPO loss on the difference between the two margins.
inside_term = -0.5 * beta_dpo * (model_diff - ref_diff) # Eq. 14, 46, with omega(lambda_t) = 1
loss = -torch.nn.functional.logsigmoid(inside_term).mean()DPOK: Reinforcement Learning for Fine-tuning Text-to-Image Diffusion Models
Google Research · University of Wisconsin-Madison · UC Berkeley · Amazon · KAIST
Advances in Neural Information Processing Systems (NeurIPS), 2023
May 25, 2023 DPOK (559) code
Concurrent with DDPO, it added the second half of diffusion RL: a KL to the pretrained model in the objective. Later methods keep it, tune it or argue against it.
DPOK finds the same multi-step MDP as DDPO independently and adds a KL to the pretrained model at each step as an implicit reward.
Insight. Online reward fine-tuning needs a KL to the pretrained model. The gradient path of the KL, not its weight, decides whether it helps.
The MDP (Eq. 4). For a prompt , , , , and the reward is only at .
REINFORCE (Eq. 5–6). The gradient of Eq. (5) is Eq. (6) for a fixed DDPM covariance.
KL-regularized objective (Lemma 4.2, Eq. 8). DPOK minimizes , with the pretrained model and . The per-step KL sum bounds the image KL Eq. (7). One shared variance makes each KL a squared gap of noise predictions.
Gradient used (Eq. 9, App. A.3). It is the REINFORCE term plus a direct , without the KL term through the states, Eq. (16).
Value baseline (App. A.5, Eq. 24). A baseline Eq. (23) keeps the gradient unbiased. minimizes .
Sample reuse (App. A.6, Eq. 26). An importance ratio against the sampling policy Eq. (25) lets five gradient steps share one sampling step. A PPO-style clip bounds the drift of the policy: , with the clip hyperparameter .
Experiments (§5). On SD v1.5, RL is better than supervised fine-tuning on all four tasks: COCO ImageReward goes 0.22 → 0.55.
Whiskey to flowers (§5.4). The base model draws whiskey for "Four roses", and RL draws flowers (ImageReward −0.52 → 1.12).
The training and sampling code. Follow Algorithm 1 of the paper, with the clipped ratio of App. A.6.
def guided_eps(unet, x_t, t, c, guidance_scale=7.5):
eps_u, eps_c = unet(cat([x_t, x_t]), cat([t, t]), cat([null, c])).chunk(2)
return eps_u + guidance_scale * (eps_c - eps_u)
def ddim_step(eps, x_t, t, t_prev, eta=1.0, x_prev=None):
a_t, a_prev = alphas_cumprod[t], alphas_cumprod[t_prev]
x_0 = (x_t - (1 - a_t).sqrt() * eps) / a_t.sqrt()
std = eta * ((1 - a_prev) / (1 - a_t) * (1 - a_t / a_prev)).sqrt() # eta = 1: the DDPM variance, kept fixed
mean = a_prev.sqrt() * x_0 + (1 - a_prev - std ** 2).sqrt() * eps
if x_prev is None:
x_prev = mean + std * torch.randn_like(x_t)
log_prob = -(x_prev.detach() - mean) ** 2 / (2 * std ** 2) - std.log() - math.log(math.sqrt(2 * math.pi))
return x_prev, log_prob.mean(dim=(1, 2, 3)) # mean over latent dims, not a sum
def train(
unet, unet_pre, value_fn, buffer,
reward_weight=100.0, kl_weight=0.01, ratio_clip=1e-4, p_batch_size=2, v_batch_size=256
):
# 1. Fit the value baseline to the final reward on a large buffer batch.
x_v, _, t_v, _, c_v, r_v, _ = buffer.sample(v_batch_size)
value_loss = (value_fn(x_v, c_v, t_v) - r_v).square().mean() # Eq. 24
# 2. Draw stored transitions and calculate their log-probability again under the current policy.
x_t, x_prev, t, t_prev, c, r, log_prob_old = buffer.sample(p_batch_size)
eps = guided_eps(unet, x_t, t, c)
_, log_prob = ddim_step(eps, x_t, t, t_prev, x_prev=x_prev)
# 3. Weight the clamped ratio by the advantage.
adv = (r - value_fn(x_t, c, t)).detach()
ratio = torch.clamp(torch.exp(log_prob - log_prob_old), 1 - ratio_clip, 1 + ratio_clip) # Eq. 26
policy_loss = (-reward_weight * adv * ratio).mean()
# 4. Add the KL to the pretrained model as the squared difference of the two noise predictions.
with no_grad():
eps_pre = guided_eps(unet_pre, x_t, t, c)
loss = policy_loss + kl_weight * (eps - eps_pre).square().mean() # Eq. 8
def sample(unet, c, prompts, num_steps=50):
x = torch.randn(bs, 4, 64, 64)
ts = ddim_timesteps(num_steps) # 981, 961, ..., 1, then the final alpha
traj = []
with no_grad():
for i in range(num_steps):
x_prev, log_prob = ddim_step(guided_eps(unet, x, ts[i], c), x, ts[i], ts[i + 1])
traj.append((x, x_prev, ts[i], ts[i + 1], log_prob))
x = x_prev
reward = image_reward(vae_decode(x), prompts) # ImageReward
return traj, rewardTraining Diffusion Models with Reinforcement Learning
UC Berkeley · MIT
International Conference on Learning Representations (ICLR), 2024
May 22, 2023 DDPO (1,188) code (775)
The multi-step MDP that it defines is the formulation that every later diffusion RL method builds on or argues against.
DDPO reads denoising as a multi-step decision process. Each sampler step is a Gaussian, and a policy gradient uses its exact likelihood.
Insight. One action per denoising step made online RL possible for diffusion. Later methods keep this per-step view or try to remove it.
The objective (§4.1). Maximize for a black-box reward and a prompt . is intractable.
Reward-weighted regression, RWR (§4.2). A one-step MDP scales the diffusion loss by . It only bounds .
Multi-step MDP (§4.3). Each step is an action, and is a Dirac mass at . Only the last step gets a reward, so :
| RWR, one step (§4.2) | DDPO, multi-step (§4.3) | |
|---|---|---|
| State | ||
| Action | ||
| Policy | ||
| Transition | straight to an absorbing state | |
| Initial state | ||
| Reward | at , else |
Exact likelihoods (Eq. 2). Under a standard sampler the policy is , so its log-likelihoods are exact.
CFG training (App. E.1, Eq. 3). Training uses the guided with , as in the sampler.
Importance-sampled estimator (§4.3). REINFORCE, , allows one gradient step per round. reuses 's trajectories for four updates per round: . It is accurate while stays close to .
Clipped objective (App. D.1, D.3). PPO's clipped surrogate on the ratio of each step is , with , far below the usual RL clip ranges. The advantage is the reward normalized by a running mean and std per prompt, like a value baseline.
Experiments (§6). On SD v1.4 with three rewards, DDPO is better than RWR per reward query, and is better than .
Style changes (§6). Aesthetics turns photos into drawings, compressibility removes backgrounds, and alignment gives cartoons.
The training and sampling code. Follow §4.3 of the paper, the importance-sampled estimator.
def guided_eps(unet, x_t, t, c, guidance_scale=5.0):
eps_u, eps_c = unet(cat([x_t, x_t]), cat([t, t]), cat([null, c])).chunk(2)
return eps_u + guidance_scale * (eps_c - eps_u) # Eq. 3
def ddim_step(eps, x_t, t, t_prev, eta=1.0, x_prev=None):
a_t, a_prev = alphas_cumprod[t], alphas_cumprod[t_prev]
x_0 = (x_t - (1 - a_t).sqrt() * eps) / a_t.sqrt()
std = eta * ((1 - a_prev) / (1 - a_t) * (1 - a_t / a_prev)).sqrt() # eta = 1: a stochastic policy
mean = a_prev.sqrt() * x_0 + (1 - a_prev - std ** 2).sqrt() * eps
if x_prev is None:
x_prev = mean + std * torch.randn_like(x_t)
log_prob = (-(x_prev.detach() - mean) ** 2 / (2 * std ** 2)
- std.log() - math.log(math.sqrt(2 * math.pi))) # Eq. 2
return x_prev, log_prob.mean(dim=(1, 2, 3)) # mean over latent dims, not a sum
def advantages(prompts, rewards, history, buffer_size=16, min_count=16):
adv = torch.empty_like(rewards)
for p in set(prompts):
idx = [i for i, q in enumerate(prompts) if q == p]
history[p] = (history.get(p, []) + rewards[idx].tolist())[-buffer_size:]
ref = torch.tensor(history[p]) if len(history[p]) >= min_count else rewards
adv[idx] = (rewards[idx] - ref.mean()) / (ref.std(unbiased=False) + 1e-6) # per-prompt running stats
return adv
def train(unet, x_t, x_prev, t, t_prev, c, log_prob_old, adv, adv_clip_max=5.0, clip_range=1e-4):
# 1. Calculate the log-probability of a stored step again under the current policy.
_, log_prob = ddim_step(guided_eps(unet, x_t, t, c), x_t, t, t_prev, x_prev=x_prev)
# 2. Calculate the clipped importance-sampled loss with one ratio per denoising step.
adv = torch.clamp(adv, -adv_clip_max, adv_clip_max)
ratio = torch.exp(log_prob - log_prob_old)
loss = torch.maximum(-adv * ratio, -adv * torch.clamp(ratio, 1 - clip_range, 1 + clip_range)).mean()
def sample(unet, c, prompts, history, num_steps=50):
x = torch.randn(bs, 4, 64, 64)
ts = ddim_timesteps(num_steps) # 981, 961, ..., 1, then the final alpha
traj = []
with no_grad():
for i in range(num_steps):
x_prev, log_prob = ddim_step(guided_eps(unet, x, ts[i], c), x, ts[i], ts[i + 1])
traj.append((x, x_prev, ts[i], ts[i + 1], log_prob))
x = x_prev
rewards = reward_fn(vae_decode(x), prompts) # for example JPEG compressibility or LAION aesthetics
return traj, advantages(prompts, rewards, history)ImageReward: Learning and Evaluating Human Preferences for Text-to-Image Generation
Tsinghua University · Zhipu AI · Beijing University of Posts and Telecommunications
Advances in Neural Information Processing Systems (NeurIPS), 2023
Apr 12, 2023 ReFL (1,397) code (1.7K)
Text-to-image RL papers use it first as their reward and their metric. ReFL opened the route of backpropagation from a reward model straight into the generator.
A text-to-image reward model learns from 137k expert comparisons, and ReFL tunes diffusion models by backpropagation of that reward.
Insight. A differentiable reward needs no likelihood. Score the model's one-step prediction late in sampling, and backpropagate through it.
Annotation (§2.1). 8,878 DiffusionDB prompts have 4–9 images, rated on alignment, fidelity and overall, then ranked: 136,892 pairs.
Reward model (§2.2, Eq. 1). BLIP's ViT-L image encoder feeds its text encoder through cross-attention. An MLP maps the [CLS] feature to a scalar . Every ranked pair of a prompt trains it by , with preferred over for the prompt .
ReFL step (Alg. 1). Denoise without gradient to a random late step, and take one step with gradient to the clean prediction . The paper uses 30–39 of 40 DDPM steps. On a flow model, the code uses [7, 10) of 10 and , where is the velocity at the noise level .
ReFL loss (Eq. 2). , , where is the reward standardized with the base model's mean and standard deviation on 512 prompts. So the push stops two standard deviations above the base model. The code drops the pre-training loss Eq. (3).
Experiments (§4). The pairwise accuracy is 65.14 against 57.76 for BLIP. ReFL wins 58.79% of human votes against SD v1.4.
FID disagrees with humans (Tab. 1). On six models, its Spearman is 0.09, against 0.60 for CLIP and 1.00 for ImageReward.
The training and sampling code. Follow §2.2 and Algorithm 1 of the paper.
1. Train the reward model.
def score(blip, mlp, prompt_ids, image):
image_embeds = blip.visual_encoder(image) # ViT-L, 224 px
text = blip.text_encoder(prompt_ids, encoder_hidden_states=image_embeds) # the prompt attends to the image
return mlp(text.last_hidden_state[:, 0]) # [CLS] -> 1024 -> 128 -> 64 -> 16 -> 1, no activations
def freeze_layers(blip, fix_rate=0.7):
blip.text_encoder.embeddings.requires_grad_(False)
blip.visual_encoder.patch_embed.requires_grad_(False)
for layer in blip.text_encoder.encoder.layer[:int(12 * fix_rate)]:
layer.requires_grad_(False)
for block in blip.visual_encoder.blocks[:int(24 * fix_rate)]:
block.requires_grad_(False)
def train_reward_model(blip, mlp, prompt_ids, better, worse):
# 1. Score the preferred and the other image of each ranked pair.
r_better = score(blip, mlp, prompt_ids, better)
r_worse = score(blip, mlp, prompt_ids, worse)
# 2. Calculate the pairwise ranking loss.
loss = -F.logsigmoid(r_better - r_worse).mean() # Eq. 1
2. Prepare the group data for one epoch of training.
def prepare_data(dataset, epoch, seed=42, num_batches=16, num_groups=3, group_size=24):
prompts = []
for i in range(num_batches):
# Make sure the sample order is the same across ranks.
g = torch.Generator()
g.manual_seed(seed + epoch * num_batches + i)
# Pick the first num_groups samples, for example ["dog", "sun", "car"].
indices = torch.randperm(len(dataset), generator=g)[:num_groups]
# Repeat each sample to make the groups, for example ["dog", "dog", "sun", "sun", "car", "car"].
repeated = [idx for idx in indices.tolist() for _ in range(group_size)]
# Shuffle the samples, so that each batch contains samples from different groups.
order = torch.randperm(len(repeated), generator=g).tolist()
prompts += [dataset[repeated[k]] for k in order] # one global batch of num_groups whole groups
return prompts
3. Roll out the prompts.
def sample(model, c, num_steps=10, solver="dpm2", resolution=512):
x = torch.randn(len(c), 16, resolution // 8, resolution // 8)
sigmas = sd3_sigmas(num_steps) # 1 -> 0, shift 3
latents, x0_preds = [x], []
for i in range(num_steps):
v = model(x, (sigmas[i] * 1000).long().expand(len(c)), c) # no CFG
if solver == "flow":
x = x + (sigmas[i + 1] - sigmas[i]) * v # Euler
else:
x0_preds.append(x - sigmas[i] * v)
x = dpm2_step(x0_preds, x, sigmas, i) # 2nd-order multistep DPM-Solver
latents.append(x)
return torch.stack(latents, dim=1), sigmas
def rollout(model, prompts, reward_model, batch_size=9, num_steps=10, train_step_range=(7, 10)):
# Sample each batch of prompts, and keep one random late state of each image to train on.
batches = []
for k in range(0, len(prompts), batch_size):
p = prompts[k:k + batch_size]
c = encode_prompt(p)
with no_grad():
latents, sigmas = sample(model, c, num_steps)
steps = torch.randint(*train_step_range, (len(p),)) # Alg. 1 line 8
batches.append({
"prompt_embeds": c,
"reward_prompt_embeds": reward_model.embed_prompts(p),
"latents": latents[torch.arange(len(p)), steps], # the states to denoise with gradients
"sigmas": sigmas[steps], # their noise levels
})
return {k: torch.cat([b[k] for b in batches]) for k in batches[0]}
4. Calibrate the reward with the base model.
def predict_reward(model, reward_model, batch):
# Predict the clean latents in one step, and reward their images. The gradients flow back through the VAE.
x, sigma = batch["latents"], batch["sigmas"]
v = model(x, (sigma * 1000).long(), batch["prompt_embeds"]) # the integer timesteps of the sampler
x0_pred = x - sigma.view(-1, 1, 1, 1) * v # Alg. 1 line 14
return reward_model.score_grad(vae_decode(x0_pred), batch["reward_prompt_embeds"])
def calibrate(model, reward_model, prompts, batch_size=9):
# Roll out each prompt once, and reward one random late state of each image.
with no_grad():
rewards = [
predict_reward(model, reward_model, rollout(model, prompts[k:k + batch_size], reward_model, batch_size))
for k in range(0, len(prompts), batch_size)
]
rewards = torch.cat(rewards)
return rewards.mean(), rewards.std()
5. Train one step.
def train(model, reward_model, batch, reward_mean, reward_std, margin=2.0, reward_weight=1e-3):
# 1. Reward the one-step predictions of the late states, with gradients.
rewards = predict_reward(model, reward_model, batch)
# 2. Standardize the rewards with the base model, and push them up to the margin.
z = (rewards - reward_mean) / reward_std
return reward_weight * torch.relu(margin - z).mean() # Eq. 2
6. Train for one epoch.
def train_epoch(
model, reward_model, optimizer, dataset, epoch, calibration=None,
batch_size=9, updates_per_epoch=1, max_grad_norm=1.0, calibration_prompts=512
):
# Calibrate the reward on the first training prompts before the first rollout, while the model is the base model.
if calibration is None:
calibration = calibrate(model, reward_model, dataset[:calibration_prompts], batch_size)
# Roll out the prompts of one epoch. Keep all samples, shuffle them, and divide them into batches.
prompts = prepare_data(dataset, epoch)
samples = rollout(model, prompts, reward_model, batch_size)
num_batches = len(prompts) // batch_size
perm = torch.randperm(len(prompts))
batches = [
{k: v[perm[b * batch_size:(b + 1) * batch_size]] for k, v in samples.items()} for b in range(num_batches)
]
# Backpropagate the reward of each batch, and update the model updates_per_epoch times.
accu = num_batches // updates_per_epoch
for b, batch in enumerate(batches):
(train(model, reward_model, batch, *calibration) / accu).backward()
if (b + 1) % accu == 0:
clip_grad_norm_(model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
return calibrationUnified Reward Model for Multimodal Understanding and Generation
Fudan University · Shanghai Innovation Institute · Shanghai AI Laboratory · Shanghai Academy of Artificial Intelligence for Science
arXiv, 2025
Mar 07, 2025 UnifiedReward (211) code (825)
One VLM, UnifiedReward, learns pair ranks and point scores for image and video generation and understanding, then sifts DPO pairs.
Insight. Judging skills transfer across tasks and modalities, so a task with few labels, such as video generation, learns from the other tasks.
Unified data (§3.2.1, Tab. 2). About 236K samples from existing sets, such as EvalMuse, HPD and OIP, cover four tasks: image generation, image understanding, video generation and video understanding. Video generation pairs are the scarcest, 10K from VideoDPO.
Answer formats (§3.2.1). A pair answer reads "X is better than Y" or names a tie, such as "Both images are equally good", with any human reasons that the source set gives. A point answer keeps the score scale of its source set, and the instruction prompt states that scale.
Reward model training (§3.2.2, §4.1.1). LLaVA-OneVision 7B fine-tunes on all four tasks at once, with cross-entropy on the answer tokens only, at a learning rate of for 3 epochs, with a batch size of 2, 16 gradient accumulation steps and a warm-up ratio of 0.3.
Data generation (§3.3). For each prompt, the VLM or the diffusion model to align makes outputs . The release samples SDXL-Turbo in one step with no guidance, and the video model is T2V-Turbo. Video DPO uses 10K pairs, and the other tasks use 14K.
Pair ranking (§3.3). The outputs form disjoint pairs, and UnifiedReward ranks each pair. The winners form the chosen list and the losers form the rejected list . The release ranks two 512×512 images by greedy decoding and looks for "Image 2 is better than Image 1".
Point sifting (§3.3). , give the final pair, where is the point score that UnifiedReward assigns to an output. The release drops a pair with , and it asks for a score from 1 to 10, where the template of the paper says 1 to 5.
DPO for generation (§3.4.1). with is the Diffusion-DPO loss on the pairs that UnifiedReward sifts. SDXL-Turbo trains only at its four timesteps 249, 499, 749 and 999 of 1000.
DPO for understanding (§3.4.2). with , where and are the chosen and rejected responses. LLaVA-OneVision 7B for images and LLaVA-Video for videos train at a learning rate of .
Experiments (Tab. 5). On GenAI-Bench video generation, accuracy with / without ties is 60.7 / 77.2 (VideoReward: 50.2 / 73.3).
One task alone makes a weak judge (Tab. 3). On VLRewardBench, it gets 47.4% from image-understanding data, 66.1% from all tasks.
Sifted pairs beat human pairs (Tab. 9). DPO on sifted pairs gets PickScore 63.32, and DPO on human Pick-a-Pic pairs gets 54.32.
The training and data code. Follow §3 of the paper and the released DiffusionDPO scripts.
def answer_loss(vlm, input_ids, images, answer_mask):
# Train on the answer tokens only: the score or the ranking, and any reasons.
logits = vlm(input_ids, images=images).logits[:, :-1]
targets, mask = input_ids[:, 1:], answer_mask[:, 1:]
return F.cross_entropy(logits[mask], targets[mask])
def train_reward_model(
vlm, optimizer_cls, dataset,
learning_rate=2.5e-6, num_epochs=3, batch_size=2, grad_accum=16
):
optimizer = optimizer_cls(vlm.parameters(), lr=learning_rate)
for epoch in range(num_epochs):
for step, batch in enumerate(dataset.batches(batch_size)):
loss = answer_loss(vlm, batch.input_ids, batch.images, batch.answer_mask) / grad_accum
loss.backward()
if (step + 1) % grad_accum == 0:
optimizer.step()
optimizer.zero_grad()
def pair_rank(reward_model, caption, a, b):
answer = reward_model.generate(pair_prompt(caption), images=[a, b]) # greedy decoding
return (b, a) if "Image 2 is better than Image 1" in answer else (a, b) # (chosen, rejected)
def point_score(reward_model, caption, image):
answer = reward_model.generate(point_prompt(caption), images=[image])
digits = re.findall(r"\d+", answer.split("Final Score:")[-1])
return int(digits[0]) if digits else 0
def build_pair(generator, reward_model, caption, num_outputs=10):
# 1. Generate N outputs for the caption.
outputs = [generator(caption, num_inference_steps=1, guidance_scale=0.0, seed=k) for k in range(num_outputs)]
# 2. Rank N/2 pairs into a chosen list and a rejected list.
pairs = [pair_rank(reward_model, caption, outputs[2 * k], outputs[2 * k + 1]) for k in range(num_outputs // 2)]
chosen, rejected = [p[0] for p in pairs], [p[1] for p in pairs]
# 3. Keep the best chosen and the worst rejected output by point score.
s_c = [point_score(reward_model, caption, o) for o in chosen]
s_r = [point_score(reward_model, caption, o) for o in rejected]
if max(s_c) <= min(s_r):
return None # the release drops the pair
return chosen[s_c.index(max(s_c))], rejected[s_r.index(min(s_r))]
def diffusion_dpo(unet, ref_unet, x_w, x_l, c, beta=5000.0, num_train_timesteps=1000):
# 1. Add one noise at one timestep to both latents. SDXL-Turbo trains at its four timesteps only.
t = torch.randint(0, num_train_timesteps, (len(x_w),))
t = 250 * (t % 4) + 249
noise = torch.randn_like(x_w)
xw_t, xl_t = add_noise(x_w, noise, t), add_noise(x_l, noise, t)
# 2. Compare the noise errors of the policy and the reference on the pair.
err = lambda m, x_t: (m(x_t, t, c) - noise).pow(2).mean(dim=(1, 2, 3))
with no_grad():
ref_diff = err(ref_unet, xw_t) - err(ref_unet, xl_t)
model_diff = err(unet, xw_t) - err(unet, xl_t)
return -F.logsigmoid(-0.5 * beta * (model_diff - ref_diff)).mean() # DPO for generation
def vlm_dpo(logp_w, logp_l, ref_logp_w, ref_logp_l, beta=0.1):
# Log-probabilities of the chosen and rejected responses under the policy and the reference.
return -F.logsigmoid(beta * ((logp_w - ref_logp_w) - (logp_l - ref_logp_l))).mean() # DPO for understandingImproving Video Generation with Human Feedback
CUHK · Tsinghua University · Kuaishou Technology · SJTU · Shanghai AI Laboratory
Advances in Neural Information Processing Systems (NeurIPS), 2025
Jan 23, 2025 VideoReward (310) code (522)
The paper builds a 182k pairwise video preference set and a reward model, and adapts DPO, RWR and reward guidance to flow models.
Insight. In video RL, the reward model is the bottleneck. Reward guidance works at inference with no training, so it is a cheap first try.
The dataset (§3.1). 182k triplets from 12 generators have labels for visual quality (VQ), motion quality (MQ) and text alignment (TA).
Bradley–Terry with ties (§3.2, Eq. 3–6). For a prompt , two videos , and their rewards , , Eq. (4) and Eq. (3). Their NLL Eq. (6), with the tie parameter , also trains on ties.
The reward model (§3.2). Qwen2-VL-2B has LoRA on the LLM, a fully tuned vision encoder and one token per axis.
Flow-DPO (Eq. 8–10). Because Eq. (9), Diffusion-DPO becomes . A fixed replaces its .
Reward guidance (§4.3, Eq. 15). With inside , the target is Eq. (14). Inference reaches it by with the guidance weight and no training. The axis weights for VQ, MQ and TA are runtime settings.
Noisy reward (§4.3, Eq. 16–17). Guidance needs on the noisy . If one noise on both videos keeps the preference Eq. (16), Eq. (17) fits it. The model is three fully connected heads on the generator's first 20 transformer blocks.
Experiments (§5). On VideoGen-RewardBench, accuracy with / without ties is 61.26 / 73.59, against VisionReward's 56.77 / 67.59.
LoRA is necessary (§5.2). Full-parameter fine-tuning degrades or collapses the generator, so all alignment runs tune only LoRA.
The training and sampling code. Follow §3.2, §4 and Appendix E of the paper.
def score(vlm, rm_head, inputs, special_ids):
logits = rm_head(vlm(inputs).last_hidden_state) # one linear head, three outputs, no bias
at_tokens = torch.isin(inputs.input_ids, special_ids) # the [VQ], [MQ], [TA] positions
return logits[at_tokens].view(-1, 3, 3).diagonal(dim1=1, dim2=2) # axis k read at its own token
def btt_loss(r_a, r_b, label, theta=5.0):
# label per axis: 1 if A wins, -1 if B wins, 0 for a tie
r_w, r_l = where(label == 1, r_a, r_b), where(label == 1, r_b, r_a)
log_theta = math.log(theta)
win = -F.logsigmoid(r_w - r_l - log_theta) # Eq. 4
tie = (-F.logsigmoid(r_a - r_b - log_theta) - F.logsigmoid(r_b - r_a - log_theta)
- math.log(theta ** 2 - 1)) # Eq. 3
return where(label == 0, tie, win).mean() # Eq. 6
def train(vlm, rm_head, inputs_a, inputs_b, label, special_ids):
# 1. Score both videos on the three axes.
r_a = score(vlm, rm_head, inputs_a, special_ids)
r_b = score(vlm, rm_head, inputs_b, special_ids)
# 2. Calculate the Bradley-Terry-with-ties loss on each axis.
loss = btt_loss(r_a, r_b, label)
def flow_dpo(model, ref_model, x_w, x_l, c, beta=500.0):
# 1. Add one noise to both videos at one timestep.
t = torch.rand(len(x_w))
noise = torch.randn_like(x_w)
xw_t, xl_t = (1 - t) * x_w + t * noise, (1 - t) * x_l + t * noise
# 2. Compare the velocity errors of the policy and the reference on the pair.
err = lambda m, x_t, x0: (m(x_t, c, t) - (noise - x0)).pow(2).sum()
with no_grad():
ref_w, ref_l = err(ref_model, xw_t, x_w), err(ref_model, xl_t, x_l)
inside = -0.5 * beta * (
(err(model, xw_t, x_w) - ref_w) - (err(model, xl_t, x_l) - ref_l)) # Eq. 10, constant beta
loss = -F.logsigmoid(inside)
def noisy_reward_loss(noisy_reward, x_w, x_l, c):
t = torch.rand(len(x_w))
noise = torch.randn_like(x_w) # one noise for both videos keeps the preference
r_w = noisy_reward((1 - t) * x_w + t * noise, c, t) # Eq. 16
r_l = noisy_reward((1 - t) * x_l + t * noise, c, t)
return -F.logsigmoid(r_w - r_l).mean() # Eq. 17
def sample(model, noisy_reward, z, c, timesteps, w, reward_weight):
for i in range(len(timesteps) - 1):
t = timesteps[i]
v = model(z, c, t)
z = z.detach().requires_grad_(True)
r = (noisy_reward(z, c, t) * reward_weight).sum() # weights over VQ, MQ, TA
v = v - w * t / (1 - t) * torch.autograd.grad(r, z)[0] # Eq. 15
z = z - (t - timesteps[i + 1]) * v
return zImageReward: Learning and Evaluating Human Preferences for Text-to-Image Generation
Tsinghua University · Zhipu AI · Beijing University of Posts and Telecommunications
Advances in Neural Information Processing Systems (NeurIPS), 2023
Apr 12, 2023 ImageReward (1,397) code (1.7K)
Text-to-image RL papers use it first as their reward and their metric. ReFL opened the route of backpropagation from a reward model straight into the generator.
A text-to-image reward model learns from 137k expert comparisons, and ReFL tunes diffusion models by backpropagation of that reward.
Insight. A differentiable reward needs no likelihood. Score the model's one-step prediction late in sampling, and backpropagate through it.
Annotation (§2.1). 8,878 DiffusionDB prompts have 4–9 images, rated on alignment, fidelity and overall, then ranked: 136,892 pairs.
Reward model (§2.2, Eq. 1). BLIP's ViT-L image encoder feeds its text encoder through cross-attention. An MLP maps the [CLS] feature to a scalar . Every ranked pair of a prompt trains it by , with preferred over for the prompt .
ReFL step (Alg. 1). Denoise without gradient to a random late step, and take one step with gradient to the clean prediction . The paper uses 30–39 of 40 DDPM steps. On a flow model, the code uses [7, 10) of 10 and , where is the velocity at the noise level .
ReFL loss (Eq. 2). , , where is the reward standardized with the base model's mean and standard deviation on 512 prompts. So the push stops two standard deviations above the base model. The code drops the pre-training loss Eq. (3).
Experiments (§4). The pairwise accuracy is 65.14 against 57.76 for BLIP. ReFL wins 58.79% of human votes against SD v1.4.
FID disagrees with humans (Tab. 1). On six models, its Spearman is 0.09, against 0.60 for CLIP and 1.00 for ImageReward.
The training and sampling code. Follow §2.2 and Algorithm 1 of the paper.
1. Train the reward model.
def score(blip, mlp, prompt_ids, image):
image_embeds = blip.visual_encoder(image) # ViT-L, 224 px
text = blip.text_encoder(prompt_ids, encoder_hidden_states=image_embeds) # the prompt attends to the image
return mlp(text.last_hidden_state[:, 0]) # [CLS] -> 1024 -> 128 -> 64 -> 16 -> 1, no activations
def freeze_layers(blip, fix_rate=0.7):
blip.text_encoder.embeddings.requires_grad_(False)
blip.visual_encoder.patch_embed.requires_grad_(False)
for layer in blip.text_encoder.encoder.layer[:int(12 * fix_rate)]:
layer.requires_grad_(False)
for block in blip.visual_encoder.blocks[:int(24 * fix_rate)]:
block.requires_grad_(False)
def train_reward_model(blip, mlp, prompt_ids, better, worse):
# 1. Score the preferred and the other image of each ranked pair.
r_better = score(blip, mlp, prompt_ids, better)
r_worse = score(blip, mlp, prompt_ids, worse)
# 2. Calculate the pairwise ranking loss.
loss = -F.logsigmoid(r_better - r_worse).mean() # Eq. 1
2. Prepare the group data for one epoch of training.
def prepare_data(dataset, epoch, seed=42, num_batches=16, num_groups=3, group_size=24):
prompts = []
for i in range(num_batches):
# Make sure the sample order is the same across ranks.
g = torch.Generator()
g.manual_seed(seed + epoch * num_batches + i)
# Pick the first num_groups samples, for example ["dog", "sun", "car"].
indices = torch.randperm(len(dataset), generator=g)[:num_groups]
# Repeat each sample to make the groups, for example ["dog", "dog", "sun", "sun", "car", "car"].
repeated = [idx for idx in indices.tolist() for _ in range(group_size)]
# Shuffle the samples, so that each batch contains samples from different groups.
order = torch.randperm(len(repeated), generator=g).tolist()
prompts += [dataset[repeated[k]] for k in order] # one global batch of num_groups whole groups
return prompts
3. Roll out the prompts.
def sample(model, c, num_steps=10, solver="dpm2", resolution=512):
x = torch.randn(len(c), 16, resolution // 8, resolution // 8)
sigmas = sd3_sigmas(num_steps) # 1 -> 0, shift 3
latents, x0_preds = [x], []
for i in range(num_steps):
v = model(x, (sigmas[i] * 1000).long().expand(len(c)), c) # no CFG
if solver == "flow":
x = x + (sigmas[i + 1] - sigmas[i]) * v # Euler
else:
x0_preds.append(x - sigmas[i] * v)
x = dpm2_step(x0_preds, x, sigmas, i) # 2nd-order multistep DPM-Solver
latents.append(x)
return torch.stack(latents, dim=1), sigmas
def rollout(model, prompts, reward_model, batch_size=9, num_steps=10, train_step_range=(7, 10)):
# Sample each batch of prompts, and keep one random late state of each image to train on.
batches = []
for k in range(0, len(prompts), batch_size):
p = prompts[k:k + batch_size]
c = encode_prompt(p)
with no_grad():
latents, sigmas = sample(model, c, num_steps)
steps = torch.randint(*train_step_range, (len(p),)) # Alg. 1 line 8
batches.append({
"prompt_embeds": c,
"reward_prompt_embeds": reward_model.embed_prompts(p),
"latents": latents[torch.arange(len(p)), steps], # the states to denoise with gradients
"sigmas": sigmas[steps], # their noise levels
})
return {k: torch.cat([b[k] for b in batches]) for k in batches[0]}
4. Calibrate the reward with the base model.
def predict_reward(model, reward_model, batch):
# Predict the clean latents in one step, and reward their images. The gradients flow back through the VAE.
x, sigma = batch["latents"], batch["sigmas"]
v = model(x, (sigma * 1000).long(), batch["prompt_embeds"]) # the integer timesteps of the sampler
x0_pred = x - sigma.view(-1, 1, 1, 1) * v # Alg. 1 line 14
return reward_model.score_grad(vae_decode(x0_pred), batch["reward_prompt_embeds"])
def calibrate(model, reward_model, prompts, batch_size=9):
# Roll out each prompt once, and reward one random late state of each image.
with no_grad():
rewards = [
predict_reward(model, reward_model, rollout(model, prompts[k:k + batch_size], reward_model, batch_size))
for k in range(0, len(prompts), batch_size)
]
rewards = torch.cat(rewards)
return rewards.mean(), rewards.std()
5. Train one step.
def train(model, reward_model, batch, reward_mean, reward_std, margin=2.0, reward_weight=1e-3):
# 1. Reward the one-step predictions of the late states, with gradients.
rewards = predict_reward(model, reward_model, batch)
# 2. Standardize the rewards with the base model, and push them up to the margin.
z = (rewards - reward_mean) / reward_std
return reward_weight * torch.relu(margin - z).mean() # Eq. 2
6. Train for one epoch.
def train_epoch(
model, reward_model, optimizer, dataset, epoch, calibration=None,
batch_size=9, updates_per_epoch=1, max_grad_norm=1.0, calibration_prompts=512
):
# Calibrate the reward on the first training prompts before the first rollout, while the model is the base model.
if calibration is None:
calibration = calibrate(model, reward_model, dataset[:calibration_prompts], batch_size)
# Roll out the prompts of one epoch. Keep all samples, shuffle them, and divide them into batches.
prompts = prepare_data(dataset, epoch)
samples = rollout(model, prompts, reward_model, batch_size)
num_batches = len(prompts) // batch_size
perm = torch.randperm(len(prompts))
batches = [
{k: v[perm[b * batch_size:(b + 1) * batch_size]] for k, v in samples.items()} for b in range(num_batches)
]
# Backpropagate the reward of each batch, and update the model updates_per_epoch times.
accu = num_batches // updates_per_epoch
for b, batch in enumerate(batches):
(train(model, reward_model, batch, *calibration) / accu).backward()
if (b + 1) % accu == 0:
clip_grad_norm_(model.parameters(), max_grad_norm)
optimizer.step()
optimizer.zero_grad()
return calibrationLast updated on November 04, 2026 · Citations from Semantic Scholar & Google Scholar; stars from GitHub, November 2026