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.
StyleGAN: a style-based generator · Latent diffusion and Stable Diffusion · LPIPS · LoRA
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 on the object and a target point 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 , their targets (we write for “goal” because will be a diffusion step), and optionally a binary mask , 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 . Each synthesis-layer style has its own code . The style-mixing experiments show a tendency for early styles to affect coarse structure and later styles to affect texture. DragGAN optimizes only to favor geometric changes; this does not guarantee unchanged color or identity.
The second is that generator features can distinguish positions. Let denote the feature at image position , obtained by resizing the sixth synthesis block’s 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 does not, so it is first inverted: we look for the code whose image reproduces it,
where is an image distance, often LPIPS plus squared error (Xia et al., 2023). Per-image optimization spends compute fitting the code; an encoder 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. has more degrees of freedom than , 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 in , 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 , features and initial handles . 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.
One DragGAN iteration: motion supervision and point tracking
In the figure, the gradient runs back from the loss to only, and tracking searches the feature map computed after the step.
Motion supervision#
Let be the unit vector from a handle to its goal, the disc of grid positions at distance strictly less than from , and the stop-gradient: its value passes forward, its gradient is zero. The loss of one iteration is
where 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, 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 and one channel, and write for the shifted feature and for the reference. With the reference frozen, the term is , and the chain rule through alone, with , gives its gradient. One gradient step with learning rate then changes , to first order, by
The third line is a first-order Taylor expansion. For a nonzero residual and a sufficiently small step, it moves toward the current frozen value of . At zero residual we use the zero subgradient of the absolute value. After updating , 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: for a bump centred at a position , the latent. Write . The reference is , and the frozen-reference loss is zero when , which holds at : 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 , and for a sufficiently small nonzero , the gradient at the current has a fixed sign on either flank:
The first line is a Taylor expansion in . The second takes its sign with : the size of drops out, and only its direction and the sign of the slope remain. The third line is the chain rule with . The fifth substitutes the second and the third, and in the last the sign of the slope meets the slope itself: cancels it. Gradient descent changes by : 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 . 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 read in two channels,
where the second channel tells the left flank from the right one. Let , the handle , the goal , so , and a patch of one position, (toy numbers):
| Quantity | Value |
|---|---|
| reference | |
| shifted feature | |
| loss | |
| with the stop-gradient | |
| without it, first channel only | |
| without it, both channels |
With the stop-gradient, descent increases and the bump moves toward the goal. The frozen-reference loss is a sum of absolute values, so it is never negative. At it is zero, because the generator only translates: reads the bump at , as does. Zero is the smallest possible value, so the shift by is a minimum. It is the only one: the first channel matches only at , that is or , and at the second channel has the wrong sign. The Code section gives at and at . 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,
where is the updated code, the feature of the handle in the original image, and the square of grid positions at distance strictly less than from 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 , the candidates have distances to , and the handle is found at . 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 image the paper uses , and , 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.
A toy DragGAN: one handle, the position of a blob as the latent
The toy stops after 13 steps at , exactly one pixel from its goal . 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 , 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 : 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 , , and the text encoder are those of the latent diffusion note.
- Identity-preserving fine-tuning trains LoRA weights of the U-Net on the input image alone.
- DDIM inversion turns the image latent into the noisy latent , 35 steps of a 50-step schedule away from the image.
- Latent optimization moves the handles by motion supervision and point tracking on U-Net features; only changes.
- 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 of rank 16 in the attention projections. The loss is the usual noise-prediction objective restricted to the single latent of the photo,
with , frozen weights and a short prompt 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 (). Here indices count positions of the chosen sampling schedule, so is the cumulative noise coefficient at that selected level, not necessarily training timestep . One step predicts the clean latent and re-noises it to the next level along the predicted noise:
DDIM inversion runs the same update upward, from to , with the noise predicted at standing in for the noise at the unknown . 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 ; classifier-free guidance is switched off for real photos, because it amplifies the inversion error.
A scalar round trip. Choose two levels with , , start at , and define the toy predictor . These are independently specified scalar inputs, not a trained diffusion model. The upward step gives
The downward step recomputes the prediction as . Consequently , and . Reusing the old prediction 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 and the features of the U-Net’s third upsampling block in place of the generator’s. Here is a square of grid positions with each coordinate difference at most , unlike DragGAN’s strict disc. With the latent after updates and ,
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: is one DDIM step of denoising from the current latent and 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 as the reference. Its tracking square also uses inclusive coordinate bounds. Adam runs for at most 80 steps with , and .
Reference-latent-control#
After optimization, is denoised for the remaining steps and decoded. Reference-latent-control runs the denoising of the original 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:
Here and are matrices whose rows are token features of the edited and reference branches; 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 , , , and . For query the scaled logits are , so the weights are and the output is . Swapping the query coordinates gives weights and output . Nothing in the reference changed; only its mixture did. This separately specified arithmetic fixture illustrates attention, not image quality.
Shared values, different mixtures
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, , 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#
| DragGAN | DragDiffusion | |
|---|---|---|
| Model | StyleGAN2 of one category | Stable Diffusion 1.5 |
| Variable | of : numbers | : numbers |
| Features | generator, after block 6 | U-Net, third upsampling block |
| Keeping the rest | on features outside the mask | on the next latent, LoRA, reference-latent-control |
| Real photos | through PTI | through 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 , the candidates have distances to the handle’s original value : the mirror position , on the far flank of the bump, ties with the right answer . The search returns the first minimum, , 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: 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 in ; real photos enter through PTI.
- DragDiffusion: LoRA on the photo, DDIM inversion to 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 are , and . 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#
- X. Pan, A. Tewari, T. Leimkühler, L. Liu, A. Meka, C. Theobalt. Drag Your GAN: Interactive Point-based Manipulation on the Generative Image Manifold. SIGGRAPH 2023 Conference Proceedings. Section 3 (motion supervision, tracking, settings), Section 4.1 (PTI for real images), Table 1 (face landmark manipulation), Section 4.3 (limitations).
- Y. Shi, C. Xue, J. H. Liew, J. Pan, H. Yan, W. Zhang, V. Y. F. Tan, S. Bai. DragDiffusion: Harnessing Diffusion Models for Interactive Point-based Image Editing. CVPR, 2024. Sections 3.2–3.4 (method), 4.1 (settings), 4.2 (DragBench), 4.4–4.7 (ablations), Appendix I, Tables 1–2.
- W. Xia, Y. Zhang, Y. Yang, J.-H. Xue, B. Zhou, M.-H. Yang. GAN Inversion: A Survey. IEEE Transactions on Pattern Analysis and Machine Intelligence, 45, 3121–3138, 2023. Sections II and IV.
- D. Roich, R. Mokady, A. H. Bermano, D. Cohen-Or. Pivotal Tuning for Latent-based Editing of Real Images. ACM Transactions on Graphics, 2022.
- J. Song, C. Meng, S. Ermon. Denoising Diffusion Implicit Models. ICLR, 2021. Eq. 12 (the update) and Section 4.3 (the ODE view and encoding).
- M. Cao, X. Wang, Z. Qi, Y. Shan, X. Qie, Y. Zheng. MasaCtrl: Tuning-Free Mutual Self-Attention Control for Consistent Image Synthesis and Editing. ICCV, 2023.
- L. Tang, M. Jia, Q. Wang, C. P. Phoo, B. Hariharan. Emergent Correspondence from Image Diffusion. NeurIPS, 2023. DIFT.