Post-Training & Alignment

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 ▼

Preference Optimization

DiffusionART: Efficient, Stable and Scalable Reinforcement of Diffusion Models

Zhenglin Wan (105), Jiayu Chen (1), Zhengfeiyang Zhang (24), Pengfei Zhou (199), Wangbo Zhao (657), Fangyuan Kong (774), Pengfei Wan (8,434), Kun Gai (15,296), Yang You (4,926)

National University of Singapore · Kuaishou Technology · HKUST

arXiv, 2026

Oct 08, 2026      DiffusionART (0)      code (225)

imagevideoflowrlunread


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.

Figure 1. NFT's forces and a shared direction (Fig. 4). Left: NFT's positive branch pulls toward the positive endpoints' forward velocity. Its negative branch pushes from that of the negatives. Right: one covariance G of each prompt's endpoints and rewards moves all states.
  • NFT as one regression (§2, Eq. 1). NFT draws K endpoints x0 per prompt c from a frozen policy and maps rewards to r∈[0,1]. On xt=(1−t)x0+tϵ, it regresses vθ toward vtgt=aut+(1−a)vold, with ut=x0−ϵ and a=(2r−1)/β. An EMA moves the rollout policy.

  • The hidden consistency force (§3.1, Prop. 1, Eq. 3). Take q=𝔼[r∣st] and the shared guidance g=Cov(r,ut∣st) (Lemma 1, Eq. 2) at st=(xt,t,c). NFT's force is ℱNFT=2g+(2q−1)e, where e 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 d=vθ−vold and h=ut−vold, ℒNFT=𝔼[−2β(2r−1)⟨d,h⟩+β2‖d‖2]+const. The quadratic term pulls back to vold 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 pτ∝poldexp(τR), ∂τ𝔼pτ[x0∣c]|τ=0=Cov(R,x0∣c) =Cov(R,ut∣c) at every noise level.

  • Aggregation-first guidance (§4.1, Eq. 5). Cov―=(1/K)∑i(Ri−R¯c)(x0(i)−x¯0,c), G(c)=Cov―/RMS(Cov―). Each visited state has the target vtgtART(st)=vθ(0)(st)+G(c), with the cached rollout velocity vθ(0). The RMS removes the reward scale, so no strength needs tuning.

Figure 2. Guidance and restoration (Fig. 6b). OCR on SD3.5-M: one update (blue), two updates (red), NFT at β=0.1 (dashed).
  • Two updates per rollout (§4.2, Eq. 6). One step on each half of the rollout uses ℒ=wMSE(vθ,vtgtART), with MSE=D−1‖a−b‖2. The first step sees −∇vθℒ=(2w/D)G(c), and the second sees (2w/D)(G(c)−d(st)). Guidance dominates until the restoration −d 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 μ(st,v)=xt+h[(1+ν2/2)v−ν2xt/(2(1−t))] and σref2=ν2ht/(1−t), with ν=0.8 and the step h=t−tnext, gives the per-coordinate KL m(st)=‖μ(st,vθ)−μ(st,vθ(0))‖2/(2Dσref2(t)).

  • Trust-region mask (§4.3, Eq. 8). w(st)=t[1−1{m(st)≥δ}1{⟨d,G−d⟩>0}] with a fixed δ=10−5 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 K=2 give VQ 12.235 in 260.8 GPU hours. K=8 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), t

Finite Difference Flow Optimization for RL Post-Training of Text-to-Image Models

David McAllister (4,689), Miika Aittala (30,617), Tero Karras (53,938), Janne Hellsten (17,780), Angjoo Kanazawa (33,909), Timo Aila (78,397), Samuli Laine (72,836)

UC Berkeley · NVIDIA

European Conference on Computer Vision (ECCV), 2026

Mar 13, 2026      FDFO (8)      code (121)

imageflowrlunread


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.

Figure 1. A group and a pair (Fig. 1). Left: Flow-GRPO reinforces the perturbation (red) of each step, weighted by the group-relative advantage A. Right: two trajectories start from one seed. Every step moves toward the image difference Δx, scaled by the reward difference ΔR.
  • Paired rollouts (§4). Two rollouts x0:T and x^0:T start from one noise ϵ. Their final images xT, x^T and the reward R give Δx=x^T−xT, ΔR=R(x^T)−R(xT). Training moves the velocities at all steps of both rollouts toward the reward-weighted image difference ΔRΔx.

  • Stochastic sampler (Alg. 1, App. B.1). Each step overshoots to t~i+1=ti+1/(1−γiti+1+γi) Eq. (4), with the noise fraction γi=0.0025. An Euler step gives x~i+1=xi+(t~i+1−ti)vi, and new noise ϵi returns it to ti+1: xi+1=(x~i+1+t~i+1γi2+2γiϵi)/(γit~i+1+1) Eq. (5).

  • Normalized difference (§4.3). To first order ΔR∝‖Δx‖, so ΔRΔx counts the distance twice. The signal is Δx―=Δx/(‖Δx‖RMS2+10−6).

  • Clipped objective (Alg. 2). PPO's ratio needs a likelihood. So the stored velocity vref gets the target vtarget=vref−Δx―. The current one vcur gives the proxy ratio ρ=exp(‖vtarget−vref‖2−‖vtarget−vcur‖2) in SPO's loss L=−ΔRρ−(|ΔR|/2ε)(ρ−1)2 with the clip range ε=0.03.

Figure 2. Alg. 2. SampleRollouts runs two samplers from one ϵ and gives ΔR and Δx― for each pair. TrainEpoch regresses onto vref−Δx― in SPO's ratio.
Figure 3. Each part, one at a time (Fig. 8). OneIG alignment. Top rows add one change each, and bottom rows change one part.
  • 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, dx

Advantage Weighted Matching: Aligning RL with Pretraining in Diffusion Models

Shuchen Xue (1,126), Chongjian Ge (5,761), Shilong Zhang (6,373), Yichen Li (642), Zhi-Ming Ma (3,261)

UCAS · Adobe Research · HKU · MIT

International Conference on Machine Learning (ICML), 2026

Sep 29, 2025      AWM (77)      code (100)

imagediffusionflowrl


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.

Figure 1. The loop (Fig. 4). Any sampler's images get a reward and noise once, and the advantage weights their score-matching loss.
  • DDPO as score matching (Thm 1, Eq. 6). A DDPO step with its Gaussian likelihood Eq. (4) targets 𝔼‖sθ(xt,t)−∇logp(xt∣xt−Δt)‖2. This is score matching on a noisy xt−Δt, not on the clean x0. 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 c, and the action is the clean image x0. The flow-matching surrogate −𝔼t[w(t)‖vθ(xt,t,c)−(ϵ−x0)‖2] gives logπθ(x0|c), with the uniform w(t)=1. It works better than the ELBO weight (1−t)/t Eq. (2).

  • GRPO on the surrogate (Eq. 9, 11–12). In GRPO's (πθ/πθold)Ai−βDKL Eq. (9), the ratio is exp(−𝔼t[w(t)(‖vθ−v‖2−‖vθold−v‖2)]) Eq. (11), with v=ϵ−x0. Both policies share t and ϵ to cut variance, with one ratio per image. The velocity-space KL is w(t)‖vθ−vθref‖2 Eq. (12).

  • The gradient (§4). On-policy, the update is −Ai∇θ𝔼t[w(t)‖vθ−(ϵ−x0)‖2], a scaled pretraining gradient. So any sampler can roll out.

Figure 2. Noisy targets slow pretraining (Fig. 3). EDM with the noisy target (blue) or the clean target (orange) in one architecture.
  • 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 t 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, t

DiffusionNFT: Online Diffusion Reinforcement with Forward Process

Kaiwen Zheng (2,050), Huayu Chen (4,104), Haotian Ye (4,731), Haoxiang Wang (3,550), Qinsheng Zhang (5,383), Kai Jiang (590), Hang Su (27,847), Stefano Ermon (154,775), Jun Zhu (75,882), Ming-Yu Liu (56,881)

Tsinghua University · NVIDIA · Stanford University

International Conference on Learning Representations (ICLR), 2026

Sep 19, 2025      DiffusionNFT (268)      code (1.1K)

✓ reviewedimagediffusionflowrl


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.

Figure 1. Forward and reverse RL (Fig. 2). Reverse RL keeps the full SDE path. Forward RL keeps only a clean image and its reward.
  • Positive and negative policies (§3.1). The reward r∈[0,1] is p(o=1∣x0,c), the probability that the image x0 for the prompt c is good. Bayes' rule on the old policy πold gives π+(x0∣c)=p(x0∣o=1,c)=p(o=1∣x0,c)πold(x0∣c)/p(o=1∣c)=rπold/𝔼πoldr and π−∝(1−r)πold.

  • Implicit policies (§3.2). The trained network vθ and the frozen old-policy network vold give vθ+=(1−β)vold+βvθ=vold+βd, vθ−=(1+β)vold−βvθ=vold−βd, where d=vθ−vold. So the two implicit policies are symmetric about vold, with the step β=1 along d.

  • Reinforcement guidance (Eq. 3–4). As in CFG, the target is v*=vold+(1/β)Δ Eq. (3), where Δ is the improvement direction and 1/β is its strength. v± are the velocities of π±, and Δ=α(v+−vold)=(1−α)(vold−v−) Eq. (4), with α=p(o=1∣xt) for the noised image xt.

  • One loss (Eq. 5–6). Flow matching on π+ weights the rollouts by r: 𝔼x0~π+‖vθ+−v‖2=𝔼x0~πold[r‖vθ+−v‖2]/𝔼r, where v=ϵ−x0 is the target velocity and ϵ is the noise. The same step on π− gives the loss ℒ=𝔼[r‖vθ+−v‖2+(1−r)‖vθ−−v‖2], with the optimum vold+(2/β)Δ Eq. (6).

  • Reward to probability (Alg. 1). The raw reward rraw becomes r=1/2+1/2clip[(rraw−𝔼πoldrraw)/Zc,−1,1], where the mean is over the group of the prompt and Zc is 5 times the global standard deviation of the reward. Thus r is group-relative and stays a probability.

  • Intuition. With e=v−vold, the error of the old policy on a sample, each term of Eq. (5) is r‖βd−e‖2+(1−r)‖βd+e‖2 =β2‖d‖2−2β(2r−1)d·e+‖e‖2 =‖βd−(2r−1)e‖2+const. So ℒ=β2𝔼‖vθ−target‖2+const, with target=vold+A(v−vold)/β and A=2r−1. By Alg. 1, A=clip[(rraw−𝔼πoldrraw)/Zc,−1,1] is the clipped group advantage. Thus the method starts from the old policy. It moves the velocity target of each sample toward v when A>0, or reflects it about vold when A<0, and then does a plain regression of vθ.

  • Soft update of the old policy (§3.3). The old policy is an EMA copy of the model, θold←ηiθold+(1−ηi)θ, with ηi=min(0.001i,0.5) at iteration i. A small ηi learns fast but can be unstable, and a large ηi is stable but slow. The training loss needs no importance ratio.

  • Loss weighting (§3.3). A self-normalized x0 regression replaces the time weight w(t) of the flow-matching loss, so no time weight needs manual tuning: ‖xθ−x0‖2/sg(mean|xθ−x0|), where xθ=xt−tvθ is the predicted clean image and sg 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 v−, 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 step

DanceGRPO: Unleashing GRPO on Visual Generation

Zeyue Xue (1,308), Jie Wu (4,562), Yu Gao (3,957), Fangyuan Kong (774), Lingting Zhu (1,346), Mengzhao Chen (2,135), Zhiheng Liu (698), Wei Liu (690), Qiushan Guo (3,368), Weilin Huang (18,528), Ping Luo (123,306)

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.

imagevideodiffusionflowrl


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 z~s=z~t+(network output)(ηs−ηt), with z~=z/α, η=σ/α for ϵ-prediction and z~=z, η=t for flow. So one MDP Eq. (6) with the state (c,t,zt), the action zt−1 and a reward at t=0 covers both paradigms.

  • Flow SDE (Eq. 8). The ODE dzt=utdt cannot explore, so sample dzt=(ut−12εt2∇logpt(zt))dt+εtdw with the noise level εt=0.3, as Eq. (7) does for diffusion. The closed-form score ∇logpt=−(zt−αtx)/σt2 of pt=𝒩(αtx,σt2I) gives a per-step Gaussian policy π(at∣st).

  • The objective (Eq. 9–10). For G samples of a prompt, all steps share Ai=(ri−mean{r})/std{r} Eq. (10), because the rewards are sparse. It enters min(ρt,iAi,clip(ρt,i,1−ϵ,1+ϵ)Ai) Eq. (9), with ρt,i=πθ/πθold and ϵ=10−4. The KL has little effect, so DanceGRPO omits it.

  • Shared noise (§2.2). All G samples of a prompt start from the same zT. Different noise per sample causes reward hacking in video.

  • Timestep selection (Alg. 1). Each iteration trains ⌈τT⌉ random steps out of T, with τ=0.6, because the others are not necessary.

  • Multiple rewards (Alg. 1). Rewards differ in scale, so normalize the advantages per model k and sum them: Ai=∑k(rik−μk)/σk.

Figure 1. Three settings (Fig. 4). Reward over iterations for pools of 16, 64, 256 (left), step subsets (middle) and noise levels (right).
  • 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), sigmas

Flow-GRPO: Training Flow Matching Models via Online RL

Jie Liu (1,638), Gongye Liu (1,989), Jiajun Liang (7,343), Yangguang Li (5,110), Jiaheng Liu (1,068), Xintao Wang (41,695), Pengfei Wan (8,434), Di Zhang (2,605), Wanli Ouyang (80,960)

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.

✓ reviewedimageflowrl


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 st=(c,t,xt), at=xt−1 and a reward at t=0. But a flow's deterministic ODE dxt=vtdt cannot explore.

  • ODE to SDE (§4, Eq. 7). A same-marginal reverse SDE is dxt=[vt(xt)−(σt2/2)∇logpt(xt)]dt+σtdw, with its score from vt in Eq. (8).

  • The sampler (Eq. 9). Euler–Maruyama on Eq. 8 gives xt+Δt=xt+[vθ(xt,t)+(σt2/2t)(xt+(1−t)vθ(xt,t))]Δt+σtΔtϵ, with ϵ~𝒩(0,I) and Δt<0 because t goes 1 → 0. The noise level a=0.7 in σt=at/(1−t) controls exploration. At a=0, it is the deterministic ODE.

  • Gaussian policy and KL (§4). πθ(xt−1|xt,c)=𝒩(μθ,σt2|Δt|I), with μθ from Eq. 9. The KL ‖μθ−μref‖2/(2σt2|Δt|) is closed-form.

  • The objective (Eq. 4–5). For G images of one prompt c, all steps share the advantage Ai=(Ri−meanR)/stdR in min(rtiAi,clip(rti,1−ε,1+ε)Ai)−βDKL, averaged over i and t, with rti=pθ(xt−1i|xti,c)/pθold(xt−1i|xti,c). There is no value network.

  • Denoising reduction (§4). Roll out at T=10 and evaluate at T=40. It is over 4× faster, because coarse trajectories rank the same.

Figure 1. The two strategies (Fig. 7). Left: reward over GPU hours for 5, 10 and 40 steps. Right: OCR accuracy at four noise levels.
  • 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

Bram Wallace (1,731), Meihua Dang (1,510), Rafael Rafailov (22,180), Linqi Zhou (3,437), Aaron Lou (3,944), Senthil Purushwalkam (3,621), Stefano Ermon (154,775), Caiming Xiong (38,931), Shafiq Joty (30,227), Nikhil Naik (15,469)

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.

imagediffusionrl


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.

(see notes in jupyter)

  • Reward from the policy (Eq. 3–7). For a prompt c, a winner x0w and a loser x0l, Bradley–Terry is p(x0w≻x0l|c)=σ(r(c,x0w)−r(c,x0l)) Eq. (3). The optimum of the reward minus β times the KL to a reference pref Eq. (5) is r(c,x0)=βlog(pθ*(x0|c)/pref(x0|c))+βlogZ(c) Eq. (7).

  • DPO (Eq. 8). In Eq. 3 the partition function Z(c) cancels, so LDPO=−𝔼logσ(βlog(pθ(x0w|c)/pref(x0w|c))−βlog(pθ(x0l|c)/pref(x0l|c))).

  • Path DPO (§4, Eq. 9–11). pθ(x0|c) marginalizes all paths x1:T. So a chain reward with r(c,x0)=𝔼[R(c,x0:T)] Eq. (9) and the path KL Eq. (10) turn Eq. 8 into whole-path ratios Eq. (11) under the reverse process pθ(x1:T|x0). It is intractable to sample over all T=1000 steps.

  • Forward process and Jensen (Eq. 12–13). Replace the reverse process with the forward q(x1:T|x0), so training needs only the fixed dataset. Sample one step t and scale the loss by T. Jensen on the convex −logσ makes each log-ratio a difference of two Gaussian KLs.

  • The objective (Eq. 14). L(θ)=−𝔼logσ(−βTω(λt)[(‖ϵw−ϵθ‖2−‖ϵw−ϵref‖2)−(‖ϵl−ϵθ‖2−‖ϵl−ϵref‖2)]): denoise the winner better than the reference ϵref does, and the loser worse. β absorbs the constant Tω(λt), as β/2 in Eq. (46): β=5000 for SDXL and β=2000 for SD1.5.

Figure 1. The loss surface (Fig. 2). The loss over the two error changes is lowest where the winner's error falls and the loser's error rises. A larger β curves it more.
  • 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%.

Figure 2. Win rates against the base model (Fig. 3). Labelers' majority on PartiPrompts (left) and HPSv2 (right). Dashed: chance.

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

Ying Fan (1,657), Olivia Watkins (15,383), Yuqing Du (8,316), Hao Liu (11,758), Moonkyung Ryu (2,158), Craig Boutilier (32,174), Pieter Abbeel (291,303), Mohammad Ghavamzadeh (21,921), Kangwook Lee (3,638), Kimin Lee (14,663)

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.

imagediffusionrl


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 z, st=(z,xT−t), at=xT−t−1, πθ(at|st)=pθ(xT−t−1|xT−t,z), and the reward is only at t=T−1.

  • REINFORCE (Eq. 5–6). The gradient of 𝔼[−r(x0,z)] Eq. (5) is 𝔼[−r(x0,z)∑t∇θlogpθ(xt−1|xt,z)] Eq. (6) for a fixed DDPM covariance.

  • KL-regularized objective (Lemma 4.2, Eq. 8). DPOK minimizes 𝔼z[α𝔼[−r(x0,z)]+β∑t𝔼KL(pθ‖ppre)], with the pretrained model ppre and β=0.01. 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 β∑t∇θKL, without the KL term through the states, Eq. (16).

  • Value baseline (App. A.5, Eq. 24). A baseline V=𝔼[r|xt] Eq. (23) keeps the gradient unbiased. V^ minimizes 𝔼[(r(x0,z)−V^(xt,z))2].

  • Sample reuse (App. A.6, Eq. 26). An importance ratio against the sampling policy pold Eq. (25) lets five gradient steps share one sampling step. A PPO-style clip bounds the drift of the policy: 𝔼[−∑t(r−V)∇θclip(pθ/pold,1−ϵ,1+ϵ)], with the clip hyperparameter ϵ=10−4.

  • 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).

Figure 1. Reward, quality, and people (Fig. 3). Scores of RL, supervised fine-tuning and the base model per task. Right: votes.

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, reward

Training Diffusion Models with Reinforcement Learning

Kevin Black (2,636), Michael Janner (15,279), Yilun Du (36,812), Ilya Kostrikov (22,324), Sergey Levine (296,999)

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.

imagediffusionrl


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 JDDRL(θ)=𝔼c,x0~pθ(x0|c)[r(x0,c)] for a black-box reward r and a prompt c. pθ(x0|c) is intractable.

  • Reward-weighted regression, RWR (§4.2). A one-step MDP scales the diffusion loss by w=exp(βr)/Z. It only bounds logpθ(x0|c).

  • Multi-step MDP (§4.3). Each step is an action, and δy is a Dirac mass at y. Only the last step gets a reward, so JRL(π)=JDDRL(θ):

RWR, one step (§4.2)DDPO, multi-step (§4.3)
States≜cst≜(c,t,xt)
Actiona≜x0at≜xt−1
Policyπ(a∣s)≜pθ(x0∣c)π(at∣st)≜pθ(xt−1∣xt,c)
Transitionstraight to an absorbing stateP(st+1∣st,at)≜(δc,δt−1,δxt−1)
Initial stateρ0(s)≜p(c)ρ0(s0)≜(p(c),δT,𝒩(0,I))
RewardR(s,a)≜r(x0,c)R(st,at)≜r(x0,c) at t=0, else 0
  • Exact likelihoods (Eq. 2). Under a standard sampler the policy is pθ(xt−1|xt,c)=𝒩(μθ(xt,c,t),σt2I), so its log-likelihoods are exact.

  • CFG training (App. E.1, Eq. 3). Training uses the guided ϵ~θ(xt,t,c)=wϵθ(xt,t,c)+(1−w)ϵθ(xt,t) with w=5, as in the sampler.

  • Importance-sampled estimator (§4.3). REINFORCE, DDPOSF, allows one gradient step per round. DDPOIS reuses θold's trajectories for four updates per round: 𝔼[∑t(pθ(xt−1|xt,c)/pθold(xt−1|xt,c))∇θlogpθ(xt−1|xt,c)r(x0,c)]. It is accurate while pθ stays close to pθold.

  • Clipped objective (App. D.1, D.3). PPO's clipped surrogate on the ratio ρt of each step is min(ρtA,clip(ρt,1−ϵ,1+ϵ)A), with ϵ=10−4, far below the usual RL clip ranges. The advantage A is the reward normalized by a running mean and std per prompt, like a value baseline.

Figure 1. A reward with no annotator (Fig. 2). The reward is the BERTScore recall of a LLaVA image description against the prompt.
  • Experiments (§6). On SD v1.4 with three rewards, DDPO is better than RWR per reward query, and DDPOIS is better than DDPOSF.

  • Style changes (§6). Aesthetics turns photos into drawings, compressibility removes backgrounds, and alignment gives cartoons.

Figure 2. Policy gradient and reweighted likelihood (Fig. 4). Reward against reward queries, for DDPO and RWR on three tasks.

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

Jiazheng Xu (7,087), Xiao Liu (22,059), Yuchen Wu (1,518), Yuxuan Tong (1,509), Qinkai Li (1,391), Ming Ding (13,619), Jie Tang (86,764), Yuxiao Dong (27,924)

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.

✓ reviewedimagediffusionrl


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 fθ(T,x). Every ranked pair of a prompt trains it by −𝔼logσ(fθ(T,xi)−fθ(T,xj)), with xi preferred over xj for the prompt T.

  • ReFL step (Alg. 1). Denoise without gradient to a random late step, and take one step with gradient to the clean prediction x0′. The paper uses 30–39 of 40 DDPM steps. On a flow model, the code uses [7, 10) of 10 and x0′=xt−σtvθ, where vθ is the velocity at the noise level σt.

  • ReFL loss (Eq. 2). ℒreward=λReLU(2−r(y,x0′)), λ=10−3, where r 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 calibration

Reward Modeling

Unified Reward Model for Multimodal Understanding and Generation

Yibin Wang (556), Yuhang Zang (10,458), Hao Li (442), Cheng Jin (679), Jiaqi Wang (17,415)

Fudan University · Shanghai Innovation Institute · Shanghai AI Laboratory · Shanghai Academy of Artificial Intelligence for Science

arXiv, 2025

Mar 07, 2025      UnifiedReward (211)      code (825)

imagevideorlunread


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 2.5×10−6 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 N=10 outputs O1,…,ON. 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 N outputs form N/2 disjoint pairs, and UnifiedReward ranks each pair. The winners form the chosen list C and the losers form the rejected list R. The release ranks two 512×512 images by greedy decoding and looks for "Image 2 is better than Image 1".

  • Point sifting (§3.3). Oc*=argmaxO∈CS(O), Or*=argminO∈RS(O) give the final pair, where S is the point score that UnifiedReward assigns to an output. The release drops a pair with S(Oc*)≤S(Or*), 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). −logσ(−(βg/2)[(‖ϵw−ϵθ(xtw)‖2−‖ϵw−ϵref(xtw)‖2)−(‖ϵl−ϵθ(xtl)‖2−‖ϵl−ϵref(xtl)‖2)]) with βg=5000 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). −logσ(βu[log(πθ(yw∣x)/πref(yw∣x))−log(πθ(yl∣x)/πref(yl∣x))]) with βu=0.1, where yw and yl are the chosen and rejected responses. LLaVA-OneVision 7B for images and LLaVA-Video for videos train at a learning rate of 5×10−7.

  • 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 understanding

Improving Video Generation with Human Feedback

Jie Liu (1,638), Gongye Liu (1,989), Jiajun Liang (7,343), Ziyang Yuan (1,975), Xiaokun Liu (348), Mingwu Zheng (2,745), Xiele Wu (418), Qiulin Wang (729), Wenyu Qin (409), Menghan Xia (6,489), Xintao Wang (41,695), Xiaohong Liu (9,388), Fei Yang (522), Pengfei Wan (8,434), Di Zhang (2,605), Kun Gai (15,296), Yujiu Yang (9,265), Wanli Ouyang (80,960)

CUHK · Tsinghua University · Kuaishou Technology · SJTU · Shanghai AI Laboratory

Advances in Neural Information Processing Systems (NeurIPS), 2025

Jan 23, 2025      VideoReward (310)      code (522)

videoflowrlunread


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.

Figure 1. The pipeline (Fig. 1). Three-axis labels train a reward model with one token per axis, for DPO, regression and guidance.
  • 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 y, two videos A, B and their rewards rA, rB, P(A≻B|y)=erA/(erA+θerB) Eq. (4) and P(A=B|y)=(θ2−1)erAerB/((erA+θerB)(θerA+erB)) Eq. (3). Their NLL Eq. (6), with the tie parameter θ=5.0, also trains on ties.

  • The reward model (§3.2). Qwen2-VL-2B has LoRA on the LLM, a fully tuned vision encoder and one [VQ][MQ][TA] token per axis.

Figure 2. Pairs and scores (Fig. 3). Accuracy of pairwise and pointwise training against the fraction of the training set, on a log scale.
  • Flow-DPO (Eq. 8–10). Because ‖ϵ*−ϵpred‖2=(1−t)2‖v*−vpred‖2 Eq. (9), Diffusion-DPO becomes −𝔼logσ(−(βt/2)[(‖vw−vθ(xtw)‖2−‖vw−vref(xtw)‖2)−(‖vl−vθ(xtl)‖2−‖vl−vref(xtl)‖2)]). A fixed β=500 replaces its βt=β(1−t)2.

  • Reward guidance (§4.3, Eq. 15). With β inside r, the target is pref(x0|y)exp(r(x0,y))w Eq. (14). Inference reaches it by v~t=vt−w(t/(1−t))∇r(xt,y) with the guidance weight w and no training. The axis weights for VQ, MQ and TA are runtime settings.

  • Noisy reward (§4.3, Eq. 16–17). Guidance needs r on the noisy xt. If one noise on both videos keeps the preference Eq. (16), −𝔼logσ(rθ(xtw,t)−rθ(xtl,t)) 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 z

ImageReward: Learning and Evaluating Human Preferences for Text-to-Image Generation

Jiazheng Xu (7,087), Xiao Liu (22,059), Yuchen Wu (1,518), Yuxuan Tong (1,509), Qinkai Li (1,391), Ming Ding (13,619), Jie Tang (86,764), Yuxiao Dong (27,924)

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.

✓ reviewedimagediffusionrl


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 fθ(T,x). Every ranked pair of a prompt trains it by −𝔼logσ(fθ(T,xi)−fθ(T,xj)), with xi preferred over xj for the prompt T.

  • ReFL step (Alg. 1). Denoise without gradient to a random late step, and take one step with gradient to the clean prediction x0′. The paper uses 30–39 of 40 DDPM steps. On a flow model, the code uses [7, 10) of 10 and x0′=xt−σtvθ, where vθ is the velocity at the noise level σt.

  • ReFL loss (Eq. 2). ℒreward=λReLU(2−r(y,x0′)), λ=10−3, where r 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 calibration

Last updated on November 04, 2026  ·  Citations from Semantic Scholar & Google Scholar; stars from GitHub, November 2026