Course contents 31 / 34

31 / 34 · Diffusion Models

Point-based image editing: DragGAN and DragDiffusion

Drag a point of an image to a target by optimizing the latent code of a generative model: GAN inversion, DragGAN's motion supervision and point tracking, and the same loop in a Stable Diffusion latent.

On this page 8

You have a photo of a cat and want its ear a little higher. A text prompt can describe the move, but does not reliably enforce an exact displacement such as “40 pixels up”. The editing tools of latent diffusion provide several kinds of control; here the input is explicitly geometric: a handle point pp on the object and a target point gg where it should end up.

Moving pixels alone leaves a hole at the old position and requires filling the newly exposed region. Point-based generative editing instead changes a model’s latent code. DragGAN (Pan et al., 2023) edits the code of StyleGAN2; DragDiffusion (Shi et al., 2024) edits a noisy Stable Diffusion latent. The latter covers a broader range of scenes, but reconstruction and precise control remain imperfect.

What a drag edit asks for#

The user gives handles p1,…,pnp_1, \dots, p_n, their targets g1,…,gng_1, \dots, g_n (we write gg for “goal” because tt will be a diffusion step), and optionally a binary mask MM, equal to 1 where the image may change. The result should be precise, with each handle ending at its target, and general, working for any object the model knows. A conditional GAN driven by face keypoints is specialized to that kind of input and does not by itself ensure arbitrary-object control.

The tool brings one more property. If every intermediate image is an output of a pretrained generator, the generator acts as a prior: when DragGAN opens a lion’s mouth, teeth appear inside. The prior is only a tendency. Being in the generator’s range is weaker than lying where its training data put mass, and an optimized code can drift into regions that produce artefacts or change a person’s identity.

Two things remain to be built. We need a differentiable way to say “this point should move one step that way”, and a way to know where the point is after each step.

The generator DragGAN edits#

DragGAN uses a StyleGAN2 trained on one category: faces, cats, cars. Two of its properties, derived in the StyleGAN note, matter here.

The first is the extended latent space W+\mathcal W^+. Each synthesis-layer style has its own code wj∈R512w_j \in \mathbb R^{512}. The style-mixing experiments show a tendency for early styles to affect coarse structure and later styles to affect texture. DragGAN optimizes only w1,…,w6w_1,\dots,w_6 to favor geometric changes; this does not guarantee unchanged color or identity.

The second is that generator features can distinguish positions. Let Fq(w)∈RCF_q(w) \in \mathbb R^C denote the feature at image position qq, obtained by resizing the sixth synthesis block’s 256×256256\times256 map. Bilinear interpolation provides values between grid points and piecewise derivatives with respect to coordinates. The block choice is an empirical result of the paper’s ablation, not a universal rule for other generators.

Editing a real photo: GAN inversion#

A generated image comes with its code. A photograph xx does not, so it is first inverted: we look for the code whose image reproduces it,

w∗=arg⁡min⁡w ℓ(G(w), x),w^* = \arg\min_{w}\ \ell\big(G(w),\ x\big),

where ℓ\ell is an image distance, often LPIPS plus squared error (Xia et al., 2023). Per-image optimization spends compute fitting the code; an encoder E:x↦wE:x\mapsto w amortizes this work into training and a forward pass. Their reconstruction and editing quality depend on the encoder, objective, latent space and compute budget.

The space matters. W+\mathcal W^+ has more degrees of freedom than W\mathcal W, which can improve reconstruction. Codes far from the mapping network’s usual outputs can be harder to edit: the desired transformation need not remain well behaved there. This is the distortion–editability trade-off discussed in the survey.

Pivotal tuning inversion (PTI, Roich et al., 2022) first finds a pivot wpw_p in W\mathcal W, then fixes it and fine-tunes generator weights to improve reconstruction. A locality penalty discourages changes at sampled codes around the pivot; it does not keep the generator exactly unchanged everywhere else. DragGAN’s real-photo pipeline uses this preparation before optimizing the drag code.

Inversion limits a category-specific editor. A solver can return a code for an out-of-domain photo, but a face generator cannot faithfully reproduce arbitrary full-body scenes or vehicles merely because an optimization ran.

DragGAN: motion supervision and point tracking#

DragGAN starts from w0w_0, features F0=F(w0)F^0=F(w_0) and initial handles pi0p_i^0. Motion supervision updates the code toward a local feature-matching target; point tracking then estimates the new handle positions. During this drag stage, the prepared generator weights remain fixed. The method exposition and schematic below adapt Pan et al.’s paper, v2, licensed CC BY 4.0; attribution and changes identify the scope. The numeric toy is a separate project fixture, not the paper’s experiment.

Figure

One DragGAN iteration: motion supervision and point tracking

A DragGAN iterationA latent w of l codes, of which the first six are trained, enters a frozen StyleGAN2, which outputs the image and the feature map F. On the map: the handle p, the goal g, the patch Ω₁ around p and the same patch moved one step d. The motion-supervision loss sends a gradient to w₁…w₆; after the Adam step the generator runs again, and nearest-neighbour search in the window Ω₂ finds the new handle position p′.w₁w₂w₃w₄w₅w₆w₇⋮wₗlatent w ∈ W+w₁…w₆ optimizedw₇…wₗ fixedGStyleGAN2frozengpfeatures F after block 6256 × 256, resized to the imageblock 6image512 × 512dΩ₁motion supervisionΣ over handles i, q ∈ Ω₁(pᵢ):‖F(q + dᵢ) − sg[F(q)]‖₁+ λ ‖(F − F₀)·(1 − M)‖₁user: pᵢ, gᵢ, mask M∂L/∂(w₁…w₆): one Adam stepw′ → F′Ω₂p′F′point trackingpᵢ ← argmin over q ∈ Ω₂(pᵢ):‖F′(q) − F₀(pᵢ⁰)‖₁repeatstop when every ‖pᵢ − gᵢ‖ ≤ 1 px12345inputstateweights, gatesoutputA DragGAN iterationA latent w of l codes, of which the first six are trained, enters a frozen StyleGAN2, which outputs the image and the feature map F. On the map: the handle p, the goal g, the patch Ω₁ around p and the same patch moved one step d. The motion-supervision loss sends a gradient to w₁…w₆; after the Adam step the generator runs again, and nearest-neighbour search in the window Ω₂ finds the new handle position p′.w₁w₂w₃w₄w₅w₆w₇⋮wₗlatent w ∈ W+optimizedfixedGStyleGAN2, frozengpfeatures Fafter block 6,256 × 256block 6image512 × 512dΩ₁motion supervisionΣ over handles i, q ∈ Ω₁(pᵢ):‖F(q + dᵢ) − sg[F(q)]‖₁+ λ ‖(F − F₀)·(1 − M)‖₁user: pᵢ, gᵢ, mask M→ ∂L/∂(w₁…w₆): one Adam stepw′ → F′Ω₂p′F′point trackingpᵢ ← argmin over q ∈ Ω₂(pᵢ):‖F′(q) − F₀(pᵢ⁰)‖₁repeatstop when every ‖pᵢ − gᵢ‖ ≤ 1 px12345inputstateweights, gatesoutput
Only w₁ … w₆ are optimized; tracking then searches for the original feature. Schematic 10 × 10 grid, 3 × 3 patch, 5 × 5 window. The illustrated p′ is not a neural-network result. Stopping threshold shown for up to five handles. Adapted from Pan et al.; attribution above.

In the figure, the gradient runs back from the loss to w1,…,w6w_1, \dots, w_6 only, and tracking searches the feature map F′F' computed after the step.

Motion supervision#

Let di=(gi−pi)/∥gi−pi∥2d_i = (g_i - p_i)/\lVert g_i - p_i \rVert_2 be the unit vector from a handle to its goal, Ω1(p,r1)\Omega_1(p, r_1) the disc of grid positions at distance strictly less than r1r_1 from pp, and sg[⋅]\mathrm{sg}[\cdot] the stop-gradient: its value passes forward, its gradient is zero. The loss of one iteration is

L(w)=∑i=1n∑q∈Ω1(pi,r1)∥Fq+di(w)−sg[Fq(w)]∥1+λ ∥(F(w)−F0)⊙(1−M)∥1,\begin{aligned} \mathcal L(w) = {}&\sum_{i=1}^{n} \sum_{q \in \Omega_1(p_i, r_1)} \big\lVert F_{q + d_i}(w) - \mathrm{sg}\big[F_q(w)\big] \big\rVert_1 \\ &+ \lambda\, \big\lVert \big(F(w) - F^0\big) \odot (1 - M) \big\rVert_1 , \end{aligned}

where ∥⋅∥1\lVert \cdot \rVert_1 is the sum of absolute values. The first term compares the patch of features around each handle with the same patch shifted by one pixel toward the goal. The second, used when a mask is drawn, penalizes changes to features outside the movable region. When a handle reaches its goal, did_i is set to 0 and its term vanishes.

Why the reference is frozen#

The stop-gradient decides the direction of the edit. Take one position qq and one channel, and write a=Fq+d(w)a = F_{q + d}(w) for the shifted feature and b=Fq(w)b = F_q(w) for the reference. With the reference frozen, the term is ∣a−sg[b]∣|a - \mathrm{sg}[b]|, and the chain rule through aa alone, with d∣y∣/dy=sign⁡(y)d|y|/dy = \operatorname{sign}(y), gives its gradient. One gradient step with learning rate η\eta then changes aa, to first order, by

∇wL=sign⁡(a−b) ∇waw′−w=−η sign⁡(a−b) ∇waa′−a≈(∇wa)⊤(w′−w)=−η sign⁡(a−b) ∥∇wa∥2.\begin{aligned} \nabla_w \mathcal L &= \operatorname{sign}(a - b)\, \nabla_w a \\ w' - w &= -\eta\, \operatorname{sign}(a - b)\, \nabla_w a \\ a' - a &\approx (\nabla_w a)^\top (w' - w) \\ &= -\eta\, \operatorname{sign}(a - b)\, \lVert \nabla_w a \rVert^2 . \end{aligned}

The third line is a first-order Taylor expansion. For a nonzero residual and a sufficiently small step, it moves aa toward the current frozen value of bb. At zero residual we use the zero subgradient of the absolute value. After updating ww, both features are recomputed; neither an exact one-pixel displacement nor monotonic decrease of the recomputed loss follows from this local calculation.

To see that this is a forward motion, take a generator that only translates its content: Fx(s)=ϕ(x−s)F_x(s) = \phi(x - s) for a bump ϕ\phi centred at a position ss, the latent. Write u=q−su = q - s. The reference is b=ϕ(u)b = \phi(u), and the frozen-reference loss is zero when ϕ(q+d−s′)=ϕ(u)\phi(q + d - s') = \phi(u), which holds at s′=s+ds' = s + d: the bump shifted by one step toward the goal. (A symmetric bump also matches at a mirrored position; a second, odd channel such as the one in the example below rules it out.) Away from a stationary point, with ϕ′(u)≠0\phi'(u)\ne0, and for a sufficiently small nonzero dd, the gradient at the current ss has a fixed sign on either flank:

a−b=ϕ(u+d)−ϕ(u)≈d ϕ′(u)sign⁡(a−b)=sign⁡(d) sign⁡(ϕ′(u))∂a∂s=−ϕ′(u+d)≈−ϕ′(u)∂L∂s=sign⁡(a−b) ∂a∂s≈−sign⁡(d) sign⁡(ϕ′(u)) ϕ′(u)=−sign⁡(d) ∣ϕ′(u)∣.\begin{aligned} a - b &= \phi(u + d) - \phi(u) \approx d\, \phi'(u) \\ \operatorname{sign}(a - b) &= \operatorname{sign}(d)\, \operatorname{sign}\big(\phi'(u)\big) \\ \frac{\partial a}{\partial s} &= -\phi'(u + d) \approx -\phi'(u) \\ \frac{\partial \mathcal L}{\partial s} &= \operatorname{sign}(a - b)\, \frac{\partial a}{\partial s} \\ &\approx -\operatorname{sign}(d)\, \operatorname{sign}\big(\phi'(u)\big)\, \phi'(u) \\ &= -\operatorname{sign}(d)\, \lvert \phi'(u) \rvert . \end{aligned}

The first line is a Taylor expansion in dd. The second takes its sign with sign⁡(xy)=sign⁡(x) sign⁡(y)\operatorname{sign}(xy) = \operatorname{sign}(x)\, \operatorname{sign}(y): the size of dd drops out, and only its direction and the sign of the slope remain. The third line is the chain rule with ∂(x−s)/∂s=−1\partial(x - s)/\partial s = -1. The fifth substitutes the second and the third, and in the last the sign of the slope meets the slope itself: sign⁡(y) y=∣y∣\operatorname{sign}(y)\, y = |y| cancels it. Gradient descent changes ss by +η sign⁡(d) ∣ϕ′(u)∣+\eta\, \operatorname{sign}(d)\, |\phi'(u)|: toward the goal in this local approximation on either flank. At stationary points the first-order sign argument does not apply, and finite updates can overshoot.

Without stop-gradient the derivative is sign⁡(a−b)(∇wa−∇wb)\operatorname{sign}(a-b)(\nabla_w a-\nabla_w b). In a smooth translation field, nearby positions can have similar Jacobians, so this subtraction can cancel much of the update or reverse its direction. This is a mechanism illustrated by the following fixture, not a claim that every learned feature map has nearly identical neighboring derivatives.

Worked example. Take a bump of width σ=2\sigma = 2 read in two channels,

Fx(s)=(ϕ(x−s), x−sσ ϕ(x−s)),ϕ(u)=e−u2/(2σ2),\begin{aligned} F_x(s) &= \Big(\phi(x - s),\ \tfrac{x - s}{\sigma}\, \phi(x - s)\Big), \\ \phi(u) &= e^{-u^2 / (2\sigma^2)} , \end{aligned}

where the second channel tells the left flank from the right one. Let s=0s = 0, the handle p=1p = 1, the goal g=4g = 4, so d=1d = 1, and a patch of one position, Ω1={1}\Omega_1 = \{1\} (toy numbers):

QuantityValue
reference F1(0)F_1(0)(0.8825, 0.4412)(0.8825,\ 0.4412)
shifted feature F2(0)F_2(0)(0.6065, 0.6065)(0.6065,\ 0.6065)
loss0.276+0.165=0.4410.276 + 0.165 = 0.441
∂L/∂s\partial \mathcal L / \partial s with the stop-gradient−0.3033-0.3033
∂L/∂s\partial \mathcal L / \partial s without it, first channel only−0.0826-0.0826
∂L/∂s\partial \mathcal L / \partial s without it, both channels+0.2483+0.2483

With the stop-gradient, descent increases ss and the bump moves toward the goal. The frozen-reference loss is a sum of absolute values, so it is never negative. At s=1s = 1 it is zero, because the generator only translates: F2(1)F_2(1) reads the bump at u=1u = 1, as F1(0)=bF_1(0) = b does. Zero is the smallest possible value, so the shift by dd is a minimum. It is the only one: the first channel matches only at u=±1u = \pm 1, that is s=1s = 1 or s=3s = 3, and at s=3s = 3 the second channel has the wrong sign. The Code section gives 0.2530.253 at s=0.5s = 0.5 and 0.2860.286 at s=1.5s = 1.5. Without it, the first channel alone still pushes forward, 3.7 times more weakly, and the second channel flips the sign: descent moves the bump away from the goal.

Point tracking#

After the step the content has moved, by an amount the loss does not fix: one gradient step can move it by less than a pixel or by more. If the next step supervised the old position, it would push the wrong content. DragGAN therefore re-locates each handle by nearest-neighbour search in feature space,

pi←arg⁡min⁡q∈Ω2(pi,r2)∥Fq(w′)−fi∥1,p_i \leftarrow \arg\min_{q \in \Omega_2(p_i, r_2)} \big\lVert F_q(w') - f_i \big\rVert_1 ,

where w′w' is the updated code, fi=Fpi0(w0)f_i = F_{p_i^0}(w_0) the feature of the handle in the original image, and Ω2(p,r2)\Omega_2(p, r_2) the square of grid positions at distance strictly less than r2r_2 from pp along each axis. Keeping the original feature avoids replacing it by a drifting sequence of references; it does not prevent a wrong match or a drifting search window.

In the worked example, after the bump has moved to s=1s = 1, the candidates x=−1,0,1,2,3x = -1, 0, 1, 2, 3 have distances 1.324,0.882,0.559,0,0.4411.324, 0.882, 0.559, 0, 0.441 to f=(0.8825,0.4412)f = (0.8825, 0.4412), and the handle is found at x=2=p+dx = 2 = p + d. On the paper’s face test, which moves the landmarks of one generated face onto those of another, a single handle ends 2.44 pixels from its goal on average, against 12.93 before editing; with an optical-flow network (RAFT) as the tracker it ends 13.43 pixels away (Pan et al., 2023, Table 1).

The loop#

The optimizer is Adam on the six codes. For a 512×512512 \times 512 image the paper uses r1=3r_1 = 3, r2=12r_2 = 12 and λ=20\lambda = 20, and stops when every handle is within 1 pixel of its goal, or 2 pixels when there are more than five handles. The authors report roughly 30 to 200 iterations and a few seconds in their hardware configuration; this is not a runtime guarantee. The toy below runs the whole loop in two dimensions, with the position of a blob as the latent.

Figure

A toy DragGAN: one handle, the position of a blob as the latent

Dragging a handle in a toy modelLeft: the 32 by 20 map with the blob after 13 steps, the path of the tracked handle from (11, 9) to (20, 13) next to the goal (21, 13), and the windows Ω₁ and Ω₂ at the start. Right: the distance to the goal per iteration; with the stop-gradient it falls from 10.77 to 1, without it grows to 11.40.feature map (channel 1) after 13 stepsp₀p₁₃goal gno sgtracked handle pgoal gΩ₁, r₁ = 3Ω₂, r₂ = 5blob at the startdistance ‖p − g‖ to the goal, pixels05101304812iteration kstop at 1 px11.40with stop-gradientwithoutDragging a handle in a toy modelLeft: the 32 by 20 map with the blob after 13 steps, the path of the tracked handle from (11, 9) to (20, 13) next to the goal (21, 13), and the windows Ω₁ and Ω₂ at the start. Right: the distance to the goal per iteration; with the stop-gradient it falls from 10.77 to 1, without it grows to 11.40.feature map (channel 1) after 13 stepsp₀p₁₃goal gno sgtracked handle pgoal gΩ₁, r₁ = 3Ω₂, r₂ = 5blob at the startdistance ‖p − g‖ to the goal, pixels05101304812iteration kstop at 1 px11.40with stop-gradientwithout
Three-channel analytic field: σ = 3, p₀ = (11, 9), g = (21, 13), r₁ = 3, r₂ = 5, step 0.1. With stop-gradient, 13 iterations reach the 1-pixel stopping threshold; without it, the distance is 11.40. This computes a blob translation, not a trained GAN.

The toy stops after 13 steps at (20,13)(20,13), exactly one pixel from its goal (21,13)(21,13). Its loss is not monotonic: it ranges from 7.4 to 8.5 as the tracked point and supervised patch change. The content translation is (9.11,4.01)(9.11,4.01), while tracking returns grid coordinates, leaving a 0.11-pixel tracking error. These measured properties describe this analytic field and optimizer, not a convergence guarantee for DragGAN.

DragDiffusion: the same loop in a diffusion latent#

DragGAN edits only what a category-specific GAN can draw. A text-to-image diffusion model covers far more images, but it has no single code like ww: an image is the end of a chain of denoising steps. DragDiffusion keeps DragGAN’s two sub-steps and changes the variable: one noisy latent of Stable Diffusion 1.5 at one intermediate step (Shi et al., 2024). The diffusion symbols ztz_t, αˉt\bar\alpha_t, εθ\varepsilon_\theta and the text encoder τ\tau are those of the latent diffusion note.

  1. Identity-preserving fine-tuning trains LoRA weights of the U-Net on the input image alone.
  2. DDIM inversion turns the image latent z0z_0 into the noisy latent z35z_{35}, 35 steps of a 50-step schedule away from the image.
  3. Latent optimization moves the handles by motion supervision and point tracking on U-Net features; only z35z_{35} changes.
  4. Denoising with reference-latent-control takes the edited latent back to an image, borrowing keys and values from the denoising of the original latent.

Identity-preserving fine-tuning#

Inverting a photo and denoising it again does not return exactly the photo, and after an edit the gap grows. Before editing, DragDiffusion fine-tunes the U-Net on the one image with LoRA updates Δθ\Delta\theta of rank 16 in the attention projections. The loss is the usual noise-prediction objective restricted to the single latent z0z_0 of the photo,

Lft(Δθ)=Eε,t[∥ε−εθ+Δθ(zt, t, τ(y))∥22],\mathcal L_{\text{ft}}(\Delta\theta) = \mathbb E_{\varepsilon, t}\Big[\big\lVert \varepsilon - \varepsilon_{\theta + \Delta\theta}(z_t,\ t,\ \tau(y))\big\rVert_2^2\Big] ,

with zt=αˉt z0+1−αˉt εz_t = \sqrt{\bar\alpha_t}\, z_0 + \sqrt{1 - \bar\alpha_t}\, \varepsilon, frozen weights θ\theta and a short prompt yy that describes the image. The authors use 80 updates and report about 25 seconds on an A100. Their ablation supports better reconstruction and identity preservation; fine-tuning does not guarantee either.

DDIM inversion to a single step#

Sampling with DDIM is deterministic when its added-noise parameter is zero (η=0\eta=0). Here indices count positions of the chosen sampling schedule, so αˉt\bar\alpha_t is the cumulative noise coefficient at that selected level, not necessarily training timestep tt. One step predicts the clean latent and re-noises it to the next level along the predicted noise:

z^0(zt)=zt−1−αˉt  εθ(zt,t)αˉt,zt−1=αˉt−1  z^0(zt)+1−αˉt−1  εθ(zt,t).\begin{aligned} \hat z_0(z_t) &= \frac{z_t - \sqrt{1 - \bar\alpha_t}\; \varepsilon_\theta(z_t, t)}{\sqrt{\bar\alpha_t}} , \\ z_{t-1} &= \sqrt{\bar\alpha_{t-1}}\; \hat z_0(z_t) + \sqrt{1 - \bar\alpha_{t-1}}\; \varepsilon_\theta(z_t, t) . \end{aligned}

DDIM inversion runs the same update upward, from ztz_t to zt+1z_{t+1}, with the noise predicted at ztz_t standing in for the noise at the unknown zt+1z_{t+1}. The substitution is an approximation: it is accurate only to the extent that the prediction changes little across the adjacent states and levels. Smaller steps can help but do not ensure exact recovery (Song, Meng and Ermon, 2021, Section 4.3). DragDiffusion inverts for 35 of 50 steps and edits z35z_{35}; classifier-free guidance is switched off for real photos, because it amplifies the inversion error.

A scalar round trip. Choose two levels with αˉA=0.64\bar\alpha_A=0.64, αˉB=0.36\bar\alpha_B=0.36, start at zA=1z_A=1, and define the toy predictor εθ(z,t)=z/2\varepsilon_\theta(z,t)=z/2. These are independently specified scalar inputs, not a trained diffusion model. The upward step gives

z^0A=1−0.6(0.5)0.8=0.875,zB=0.6(0.875)+0.8(0.5)=0.925.\begin{aligned} \hat z_0^A &= \frac{1-0.6(0.5)}{0.8}=0.875, \\ z_B &= 0.6(0.875)+0.8(0.5)=0.925. \end{aligned}

The downward step recomputes the prediction as 0.925/2=0.46250.925/2=0.4625. Consequently z^0B=(0.925−0.8(0.4625))/0.6=0.925\hat z_0^B=(0.925-0.8(0.4625))/0.6=0.925, and zA′=0.8(0.925)+0.6(0.4625)=1.0175z_A'=0.8(0.925)+0.6(0.4625)=1.0175. Reusing the old prediction 0.50.5 would return exactly 1, but evaluating the predictor at the new state does not. Determinism alone is not invertibility of these discrete updates.

The paper motivates a single editable latent by the tendency of coarse structure to form early in denoising. It avoids differentiating through the whole sampling chain. Its timestep ablation finds a trade-off between movement and identity preservation; neither the preferred step nor this behavior is guaranteed for other models and images.

Latent optimization on U-Net features#

Motion supervision carries over with the latent in place of ww and the features of the U-Net’s third upsampling block in place of the generator’s. Here Ω(p,r)\Omega(p,r) is a square of grid positions with each coordinate difference at most rr, unlike DragGAN’s strict disc. With z^tk\hat z_t^k the latent after kk updates and z^t0=zt\hat z_t^0 = z_t,

Lms(z^tk)=∑i=1n∑q∈Ω(pik,r1)∥Fq+di(z^tk)−sg[Fq(z^tk)]∥1+λ ∥(z^t−1k−sg[z^t−10])⊙(1−M)∥1.\begin{aligned} \mathcal L_{\text{ms}}(\hat z_t^k) = {}&\sum_{i=1}^{n} \sum_{q \in \Omega(p_i^k, r_1)} \big\lVert F_{q + d_i}(\hat z_t^k) - \mathrm{sg}\big[F_q(\hat z_t^k)\big] \big\rVert_1 \\ &+ \lambda\, \big\lVert \big(\hat z_{t-1}^k - \mathrm{sg}[\hat z_{t-1}^0]\big) \odot (1 - M) \big\rVert_1 . \end{aligned}

The stop-gradient plays the role derived above. The mask term acts on latents rather than features, with the mask resized to the latent grid: z^t−1k\hat z_{t-1}^k is one DDIM step of denoising from the current latent and z^t−10\hat z_{t-1}^0 the same step from the unedited one, so outside the mask changes to the next, slightly cleaner latent are penalized. Tracking is DragGAN’s nearest-neighbour search, with U-Net features and the original feature Fpi0(zt)F_{p_i^0}(z_t) as the reference. Its tracking square also uses inclusive coordinate bounds. Adam runs for at most 80 steps with r1=1r_1 = 1, r2=3r_2 = 3 and λ=0.1\lambda = 0.1.

Reference-latent-control#

After optimization, z^t\hat z_t is denoised for the remaining tt steps and decoded. Reference-latent-control runs the denoising of the original ztz_t alongside and, in the self-attention layers of the U-Net’s upsampling blocks, replaces the keys and values of the edited branch by those of the original:

Q^=φ^WQ,K=φWK,V=φWV,Attention(Q^,K,V)=softmax⁡(Q^K⊤dk)V,\begin{aligned} \hat Q &= \hat\varphi W_Q, \\ K &= \varphi W_K, \\ V &= \varphi W_V, \\ \mathrm{Attention}(\hat Q, K, V) &= \operatorname{softmax}\Big(\frac{\hat Q K^\top}{\sqrt{d_k}}\Big) V , \end{aligned}

Here φ^\hat\varphi and φ\varphi are matrices whose rows are token features of the edited and reference branches; dkd_k is the key dimension. The output is a weighted mixture of reference values. Queries decide the mixture, so sharing values does not force the same spatial layout or guarantee identity preservation. The mechanism is credited to MasaCtrl (Cao et al., 2023).

Two reference tokens. Fix K1=(1,0)K_1=(1,0), K2=(0,1)K_2=(0,1), V1=(2,−1)V_1=(2,-1), V2=(−2,3)V_2=(-2,3) and dk=2d_k=2. For query Q^A=(2log⁡3,0)\hat Q_A=(\sqrt2\log3,0) the scaled logits are (log⁡3,0)(\log3,0), so the weights are (3/4,1/4)(3/4,1/4) and the output is (1,0)(1,0). Swapping the query coordinates gives weights (1/4,3/4)(1/4,3/4) and output (−1,2)(-1,2). Nothing in the reference changed; only its mixture did. This separately specified arithmetic fixture illustrates attention, not image quality.

Figure

Shared values, different mixtures

Two mixtures of the same reference valuesK1=(1,0), K2=(0,1), V1=(2,-1), V2=(-2,3). Query A gives weights 0.75 and 0.25, output (1,0). Query B swaps the weights, output (-1,2).Reference tokens: fixedK1 = (1, 0)V1 = (2, -1)K2 = (0, 1)V2 = (-2, 3)Query A: QKᵀ/√2 = (log 3, 0)softmax → (0.75, 0.25)0.75 V₁ + 0.25 V₂ = (1, 0)Query B: QKᵀ/√2 = (0, log 3)softmax → (0.25, 0.75)0.25 V₁ + 0.75 V₂ = (-1, 2)
Keys and values stay fixed. Swapping query coordinates changes weights from (¾, ¼) to (¼, ¾) and output from (1, 0) to (−1, 2). The reference contributes to both outputs but does not fix the result. Numbers are specified for this example.

Evaluation on DragBench#

DragBench has 205 images with 349 handle–target pairs in ten categories (Shi et al., 2024, Section 4.2 and Appendix A). Two measures pull in opposite directions. Image fidelity, IF=1−LPIPS(x,xedit)\mathrm{IF} = 1 - \mathrm{LPIPS}(x, x_{\text{edit}}), is 1 for an unchanged image. Mean distance (MD) locates the handle’s content in the edited image with diffusion-feature correspondence (Tang et al., 2023) and averages its distance to the goal. Doing nothing scores perfect fidelity. IF is an index derived from LPIPS, not a percentage of preserved pixels or a guaranteed [0,1] probability.

In the authors’ reported category tables, DragDiffusion has lower MD in all ten categories and higher IF in nine. Their DragGAN baseline selects the generator category using CLIP similarity; upper-body and full-body IF values are 0.33 and 0.31 (Shi et al., 2024, Appendix I, Tables 1–2). These scores are not percentages of image content preserved, and we have not rerun this benchmark.

What changed#

DragGANDragDiffusion
ModelStyleGAN2 of one categoryStable Diffusion 1.5
Variablew1,…,w6w_1, \dots, w_6 of W+\mathcal W^+: 6⋅512=30726 \cdot 512 = 3072 numbersz35z_{35}: 4⋅64⋅64=16,3844 \cdot 64 \cdot 64 = 16{,}384 numbers
Featuresgenerator, after block 6U-Net, third upsampling block
Keeping the restλ\lambda on features outside the maskλ\lambda on the next latent, LoRA, reference-latent-control
Real photosthrough PTIthrough LoRA and DDIM inversion

Where it breaks#

Tracking can slip where many positions look alike. In the worked example, keep only the first channel, the bump itself, which is symmetric. After the move to s=1s = 1, the candidates x=−1,0,1,2,3x = -1, 0, 1, 2, 3 have distances 0.276,0,0.118,0,0.2760.276, 0, 0.118, 0, 0.276 to the handle’s original value 0.88250.8825: the mirror position x=0x = 0, on the far flank of the bump, ties with the right answer x=2x = 2. The search returns the first minimum, x=0x = 0, and the next motion-supervision step pushes the wrong content. Texture-less regions cause the same failure, which is why DragGAN recommends handles on textured parts.

Other failures come from the setup. A few points do not determine a unique edit, and a soft mask penalty does not strictly freeze protected pixels. Optimizing a code can leave the useful part of a generator’s range; both methods may miss targets or alter identity. The described real-photo pipelines add per-image PTI or LoRA preparation, while generated inputs already have model latents. An edited photograph is synthetic content, not evidence that the depicted pose or event occurred.

What you should remember#

  • A drag edit optimizes a generator’s latent; the generator invents the uncovered content.
  • Motion supervision: ∥Fq+d(w)−sg[Fq(w)]∥1\lVert F_{q+d}(w) - \mathrm{sg}[F_q(w)] \rVert_1 sets a local feature target one step toward the goal; the actual movement is determined by optimization and tracking.
  • Without stop-gradient, subtraction of neighboring feature Jacobians can weaken or reverse the update.
  • Tracking: nearest neighbour of the handle’s original feature after every step.
  • DragGAN moves w1,…,w6w_1, \dots, w_6 in W+\mathcal W^+; real photos enter through PTI.
  • DragDiffusion: LoRA on the photo, DDIM inversion to t=35t = 35 of 50, one latent optimized, keys and values borrowed when denoising.

Notebook#

Run python3 scripts/notes/generative-practice.py drag-editing. The new analytic experiment defines a two-dimensional feature field whose only editable parameter is a translation. The three features at translated coordinates (u,v)(u,v) are sin⁡(0.7u)\sin(0.7u), cos⁡(0.4v)\cos(0.4v) and u+2vu+2v. There is no photograph, pretrained generator or inversion step.

  • Start with handle (−1, 2) and translate the field by (2, −1). Search a 7-by-7 integer grid for the original feature vector. The saved result recovers the expected handle (1, 1). Keeping only the first feature produces a tie across rows; the first minimum is (1, −3). Feature ambiguity can make tracking select the wrong point.
  • Optimize the translation against the desired handle position with 20 gradient steps of size 0.3. The remaining handle error is 0.001784. Every point shares the same translation, so a supposedly protected point also moves by 2.234284: this parameterization cannot isolate a local edit.
  • This checks feature matching and a restricted editing parameterization. Its known coordinate Jacobian differs from DragGAN’s learned-feature motion loss; there is no claim of running DragGAN, DragDiffusion or image-quality evaluation. The separate Code section retains its earlier derivation example.

The example, script and observations were newly authored for this course with Codex assistance; the numerical results are from the linked run.

Code#

The worked example in NumPy, with the gradients written out: the stop-gradient keeps the reference’s derivative out of the sum. A finite-difference check confirms both gradients.

import numpy as np

sigma = 2.0

def feat(x, s):
    """Toy generator: a bump at position s, read at positions x; two channels."""
    u = x - s
    phi = np.exp(-u**2 / (2 * sigma**2))
    return np.array([phi, u / sigma * phi])

def dfeat_ds(x, s):
    """Derivative of both channels with respect to the latent s (d/ds = -d/du)."""
    u = x - s
    phi = np.exp(-u**2 / (2 * sigma**2))
    dphi = -u / sigma**2 * phi
    return -np.array([dphi, (phi + u * dphi) / sigma])

p, g, s = 1.0, 4.0, 0.0
d = np.sign(g - p)                              # unit step from the handle toward the goal
a, b = feat(p + d, s), feat(p, s)               # shifted feature and reference
sign = np.sign(a - b)
grad_sg = sign @ dfeat_ds(p + d, s)             # sg[F_p]: only the shifted feature moves
grad_no = sign @ (dfeat_ds(p + d, s) - dfeat_ds(p, s))
print(np.round(b, 4), np.round(a, 4), round(np.abs(a - b).sum(), 4))
print(round(grad_sg, 4), round(grad_no, 4), round(sign[0] * (dfeat_ds(p + d, s) - dfeat_ds(p, s))[0], 4))
# [0.8825 0.4412] [0.6065 0.6065] 0.4412
# -0.3033 0.2483 -0.0826

h = 1e-6                                        # finite-difference check of both gradients
L_sg = lambda t: np.abs(feat(p + d, t) - b).sum()
L_no = lambda t: np.abs(feat(p + d, t) - feat(p, t)).sum()
print(round((L_sg(h) - L_sg(-h)) / (2 * h), 4), round((L_no(h) - L_no(-h)) / (2 * h), 4))
# -0.3033 0.2483
print([round(float(L_sg(t)), 3) for t in (0.5, 1.0, 1.5)])   # zero at s = d
# [0.253, 0.0, 0.286]

# Point tracking once the content has moved by d (s = 1), with both channels and with the first only
xs = np.arange(-1.0, 4.0)                       # strict Omega_2 around p = 1 with r2 = 3
dist2 = np.abs(feat(xs, 1.0) - b[:, None]).sum(0)
dist1 = np.abs(feat(xs, 1.0)[0] - b[0])
print(xs[dist2.argmin()], np.round(dist2, 3))
print(xs[dist1.argmin()], np.round(dist1, 3))
# 2.0 [1.324 0.882 0.559 0.    0.441]
# 0.0 [0.276 0.    0.118 0.    0.276]

Next#

These editing procedures return a modified image without evaluating its likelihood. That is a property of the editing procedure, not a claim that diffusion models have no probabilistic objective. The autoregressive-model note studies a different interface: a joint distribution built from normalized conditionals, with explicit log-likelihood evaluation.

References#