AI Wiki中文/EN

Generative image editing: preservation, noise and instruction strength

生成式图像编辑

Compute an exact editing kernel, finite-step error, editable masks and two-condition guidance.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Change something while keeping something else

Drawing a new red car is different from changing one particular car from blue to red. In the second task, the viewpoint, wheels, background and identity may need to remain stable. “More change” and “better editing” are not the same objective.

SDEdit perturbs a supplied guide with noise and denoises it using a learned image prior. InstructPix2Pix trains an editor conditioned on both an input image and an editing instruction, using generated training pairs. One changes the starting state of a generative process; the other learns an explicit instruction-conditioned mapping. Neither description implies exact preservation outside the intended edit. Start with text-to-image generation, score SDEs and classifier-free guidance.

Exact Gaussian moments separate guide preservation, prior matching and finite-step variance error.
Exact Gaussian moments separate guide preservation, prior matching and finite-step variance error.

Noise strength determines how much of the guide survives

For a variance-exploding construction, write a noisy guide as:

y=g+sϵ,ϵ∼N(0,I),s≥0.y=g+\sqrt{s}\epsilon,\qquad \epsilon\sim\mathcal N(0,I),\qquad s\geq0.

Here s is noise variance, not a universally standardized interface slider. Relating a time or “strength” setting to s requires the actual noise schedule. At s=0 there is no perturbation; large s obscures more information about the guide.

SDEdit’s algorithm denoises from an intermediate noise level rather than requiring the guide to be a sample from the image prior. To see precisely what this can do, replace the image prior with a one-dimensional Gaussian X∼N(μ,v). Bayes’ rule for a noisy observation yields:

X∣Y=y∼N(λy+(1−λ)μ,vsv+s),λ=vv+s.X\mid Y=y\sim\mathcal N\left(\lambda y+(1-\lambda)\mu,\frac{vs}{v+s}\right),\qquad \lambda=\frac{v}{v+s}.

The posterior formula follows by adding precisions 1/v and 1/s and completing the square. At s=0 use the continuous limit: the output equals the observation. Our editing guide g is fixed, so the perturbed Y has variance s rather than v+s. Averaging the posterior kernel over that perturbed guide gives:

E[Xedit]=λg+(1−λ)μ,Vedit=λ2s+vsv+s=v(1−λ2).\mathbb E[X_{\mathrm{edit}}]=\lambda g+(1-\lambda)\mu,\qquad V_{\mathrm{edit}}=\lambda^2s+\frac{vs}{v+s}=v(1-\lambda^2).

The first variance term comes from randomizing the guide; the second comes from sampling the posterior. Using only a posterior mean drops the second term and produces a different distribution. At finite s the edited distribution need not equal the prior. As s grows without bound, its mean tends to μ and its variance to v, while dependence on g disappears.

An exact preservation cost in this example is:

E[(Xedit−g)2]=(E[Xedit]−g)2+Vedit.\mathbb E[(X_{\mathrm{edit}}-g)^2]=(\mathbb E[X_{\mathrm{edit}}]-g)^2+V_{\mathrm{edit}}.

A separate distribution discrepancy is KL(N(mean,V)||N(μ,v)). Neither this KL nor squared change is a human image-quality metric. At zero noise the output is a point mass; its KL to a continuous Gaussian is infinite, not zero. The program serializes that case as null with an explicit infinite flag.

For numerical reverse VE steps, let u be the current noise variance and Δ>0 the decrease to the next variance. The Gaussian score is −(x−μ)/(v+u), giving:

xnext=x−Δ(x−μ)v+u+Δ ξ,ξ∼N(0,1).x_{\mathrm{next}}=x-\frac{\Delta(x-\mu)}{v+u}+\sqrt{\Delta}\,\xi,\qquad \xi\sim\mathcal N(0,1).

The drift moves toward the prior mean; random increments scale with the square root of the variance decrease. Finite steps introduce their own error even with an exact score. Keeping a clear decreasing-time convention prevents a negative noise variance or a drift pointing the wrong way.

Compare an exact editing kernel with a finite solver

Save as image_editing_models.py; use Python 3.12 and NumPy 1.26.4. The prior has μ=.5 and v=.25; the fixed guide is 1.5. The program computes exact posterior and output moments, samples the two noise sources, propagates Euler moments, and demonstrates masks and two-condition guidance. There is no trained neural denoiser or natural-image editor.

The exact scalar kernel costs O(B) for B samples. S Euler steps would cost O(BS) for sampled paths; propagating only scalar mean and variance costs O(S). For an image model, each denoiser evaluation adds substantial network cost. Our final mask operation is O(P) for P entries and is only an explicit compositing operation, not the entire SDEdit masked trajectory algorithm.

"""Original exact Gaussian editing kernel and finite-step VE comparison."""
import json
import numpy as np
MU=.5
VAR=.25
GUIDE=1.5

def noise_value(s):
    if isinstance(s,bool) or not np.isscalar(s) or not np.isfinite(s) or not 0<=s<=100:raise ValueError('Noise variance must be in[0,100]')
    return float(s)

def exact_moments(s,guide=GUIDE):
    s=noise_value(s)
    if not np.isfinite(guide):raise ValueError('Finite guide required')
    keep=VAR/(VAR+s);mean=keep*guide+(1-keep)*MU;variance=keep**2*s+VAR*s/(VAR+s)
    return float(mean),float(variance)

def posterior(y,s):
    s=noise_value(s);y=np.asarray(y,float)
    if not np.isfinite(y).all():raise ValueError('Finite observations required')
    keep=VAR/(VAR+s)
    return keep*y+(1-keep)*MU,VAR*s/(VAR+s)

def exact_sample(s,count=32768,seed=22):
    s=noise_value(s)
    if not isinstance(count,int) or isinstance(count,bool) or not 1<=count<=100000:raise ValueError('Invalid sample count')
    rng=np.random.default_rng(seed);noisy=GUIDE+np.sqrt(s)*rng.normal(size=count);mean,var=posterior(noisy,s)
    return mean+np.sqrt(var)*rng.normal(size=count)

def em_moments(s,steps):
    s=noise_value(s)
    if not isinstance(steps,int) or isinstance(steps,bool) or not 1<=steps<=8192:raise ValueError('Positive step count required')
    mean,var=GUIDE,s;delta=s/steps
    for i in range(steps,0,-1):
        current=i*delta;shrink=1-delta/(VAR+current);mean=MU+shrink*(mean-MU);var=shrink**2*var+delta
    return float(mean),float(var)

def preserve_unedited(generated,guide,editable):
    generated=np.asarray(generated,float);guide=np.asarray(guide,float);mask=np.asarray(editable)
    if generated.shape!=guide.shape or mask.shape!=guide.shape or mask.dtype!=bool or not np.isfinite(generated).all() or not np.isfinite(guide).all():raise ValueError('Matched arrays and boolean editable mask required')
    return np.where(mask,generated,guide)

def dual_guidance(unconditional,image_only,both,image_scale,text_scale):
    u,i,b=[np.asarray(x,float) for x in [unconditional,image_only,both]]
    if u.shape!=i.shape or i.shape!=b.shape or not all(np.isfinite(x).all() for x in [u,i,b]) or not all(np.isfinite(x) and 0<=x<=20 for x in [image_scale,text_scale]):raise ValueError('Invalid guidance inputs')
    return u+image_scale*(i-u)+text_scale*(b-i)

def demo():
    rows={}
    for s in [0,.01,.1,1,10]:
        mean,var=exact_moments(s);kl=None if var==0 else .5*(var/VAR+(mean-MU)**2/VAR-1+np.log(VAR/var))
        rows[str(s)]=dict(mean=mean,variance=var,expected_squared_change=(mean-GUIDE)**2+var,kl_to_prior=kl,kl_infinite=var==0)
    draw=exact_sample(1);truth=exact_moments(1)
    return dict(noise_variances=rows,em_errors={str(n):abs(em_moments(1,n)[1]-truth[1]) for n in [1,8,64,512]},sample_mean=float(draw.mean()),sample_variance=float(draw.var()),guided_prediction=dual_guidance([.1,.2],[.3,.1],[.5,-.4],1.2,2.).tolist(),mask_example=preserve_unedited([9.,8.,7.],[1.,2.,3.],[False,True,False]).tolist(),scope='One-dimensional Gaussian prior; KL is an analytic distribution discrepancy, not human image realism. No neural score or instruction editor training.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))

At noise variances 0,.1,1,10, output means are approximately 1.5,1.214286,.7,.524390; output variances are 0,.122449,.24,.249851. Increasing noise makes the synthetic distribution closer to its prior while increasing expected squared change from the guide. At s=1 the exact change is .88 and KL is .080411.

At s=1, Euler variance errors for 1,8,64,512 steps are .8,.069884,.007661,.000940. The mean is exact at these uniform steps because the linear shrinkage factors telescope; the variance is not. Seeded exact sampling with 32,768 draws gives mean about .704498 and variance .243041, checked against the analytic moments with sampling tolerances.

For explicit unedited-region preservation, define an editable mask M:

xout=M⊙xgenerated+(1−M)⊙g.x_{\mathrm{out}}=M\odot x_{\mathrm{generated}}+(1-M)\odot g.

This guarantees entrywise preservation where M=0. It does not guarantee natural boundaries, consistent lighting or correct semantics. The paper and the fixed SDEdit runner use different mask conventions; our function names the convention explicitly rather than copying an ambiguous binary mask.

Instruction following adds a second condition

InstructPix2Pix’s method uses a language model to propose instructions and edited captions, then an image generator and correspondence/filtering procedures to produce training pairs. Its editor receives the original image through additional channels and the instruction through text conditioning. Synthetic pair quality is part of the learning problem, not ground truth guaranteed by the generator.

The model supports unconditional, image-only and joint image/text predictions. With those predictions denoted εu, εI and εIT, its two-scale guidance rule is:

ϵ~=ϵu+sI(ϵI−ϵu)+sT(ϵIT−ϵI).\tilde\epsilon=\epsilon_u+s_I(\epsilon_I-\epsilon_u)+s_T(\epsilon_{IT}-\epsilon_I).

The second difference adds text relative to the image-conditioned branch. Setting sI=0 does not turn the joint branch into a text-only model. With both scales one the expression equals εIT. The training implementation drops only text, only image or both in separate 5% intervals, retaining both for the remaining 85%.

A real editing evaluation should separately measure requested change, unintended change, identity/layout preservation and diverse valid outcomes. Inversion-based methods, masks, learned instruction editors and spatial controls solve related but different constraints. No fixed guidance setting optimizes all of them. See ControlNet for an additional learned spatial-conditioning branch.

Separate preservation, randomness and solver error

  1. Calculation. With μ=.5, v=.25, g=1.5 and s=1, what are the exact output mean and variance? Answer: λ=.2, so mean=.2×1.5+.8×.5=.7. Variance=.2²×1+.25/1.25=.24. The first .04 and second .20 come from different noise sources.
  2. Prediction. Does denoising without perturbing the fixed guide necessarily draw a fresh prior sample in this Gaussian example? Answer: No. At s=0 the exact kernel is the identity, giving a point mass at g. Noise strength changes the distribution of possible edits.
  3. Boundary. Why does an explicit final mask preserve a background entry exactly but not guarantee a seamless boundary? Answer: Where M=0 the formula returns the original entry by definition. It imposes no constraint that generated neighboring entries share compatible texture or lighting.
  4. Transfer. Set sI=0 and sT=1 in the two-condition guidance rule. Is the result a text-only prediction? Answer: It is εu+εIT−εI. The joint prediction still used the input image, so it is not generally equal to a separately trained text-only branch.

Check the time convention instead of copying a printed sign

We read SDEdit v2’s selected method, Algorithm 1 and Appendix C.2 after comparing the first preprint. The v2 PDF’s printed Equation 4 reverses the variance difference relative to its increasing noise schedule; Algorithm 1 uses the positive current-minus-next difference. Our update follows that positive difference and independently recovers Gaussian moments. PDF pages 3 and 6 were inspected; no claim is made that the authors’ VP runner executes the printed negative variance.

For instruction editing, read InstructPix2Pix v1 §3.1–3.2, its three-branch inference rule and condition-dropout code; PDF page 5 was viewed. These are bounded source checks, not reproductions of their image or human-preference results.

Make a prediction, then check

Does zeroing image guidance create a text-only editing predictor?

Choose one answer

Learning objectives

  • Derive Gaussian editing moments and preservation cost.
  • Use a consistent reverse-time sign convention.
  • Explain hard masks and their limits.
  • Derive two-condition instruction guidance.

Prerequisites & connections

Explore related knowledge →

References

  1. SDEdit: Guided Image Synthesis and Editing with Stochastic Differential Equations (v2)
    Chenlin Meng; Yutong He; Yang Song; Jiaming Song; Jiajun Wu; Jun-Yan Zhu; Stefano Ermon · 2022
  2. InstructPix2Pix: Learning to Follow Image Editing Instructions (v1)
    Tim Brooks; Aleksander Holynski; Alexei A. Efros · 2022
  3. sdedit-runner reference at 66a5e44
    ermongroup/SDEdit contributors · 2023
  4. ip2p-guidance reference at 0dffd1e
    timothybrooks/instruct-pix2pix contributors · 2023
  5. ip2p-loss reference at 0dffd1e
    timothybrooks/instruct-pix2pix contributors · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-20 · Single AI author checked SDEdit v1/v2 selected method and v2 Algorithm1, IP2P v1 section3 and fixed author guidance/mask code. Seven paired equations and four explained exercises; original Gaussian posterior moments, positive variance steps, Euler variance convergence, zero-noise infinite KL, post-compositing mask and two-scale guidance. Printed SDEdit variance-order inconsistency explicitly distinguished from the algorithm; no perceptual realism benchmark.

  • Single AI author checked SDEdit v1/v2 selected method and v2 Algorithm1, IP2P v1 section3 and fixed author guidance/mask code. Seven paired equations and four explained exercises; original Gaussian posterior moments, positive variance steps, Euler variance convergence, zero-noise infinite KL, post-compositing mask and two-scale guidance. Printed SDEdit variance-order inconsistency explicitly distinguished from the algorithm; no perceptual realism benchmark.
  • Four computed SVG variants per topic. Thirteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. English spacing correction and initial test-mixin discovery error preserved. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.