Skip to content

Commit ee71d9d

Browse files
Add support for different model prediction types in DDIMInverseScheduler (#2619)
* Add support for different model prediction types in DDIMInverseScheduler Resolve alpha_prod_t_prev index issue for final step of inversion * Fix old bug introduced when prediction type is "sample" * Add support for sample clipping for numerical stability and deprecate old kwarg * Detach sample, alphas, betas Derive predicted noise from model output before dist. regularization Style cleanup * Log loss for debugging * Revert "Log loss for debugging" This reverts commit 76ea9c8. * Add comments * Add inversion equivalence test * Add expected data for Pix2PixZero pipeline tests with SD 2 * Update tests/pipelines/stable_diffusion/test_stable_diffusion_pix2pix_zero.py * Remove cruft and add more explanatory comments --------- Co-authored-by: Patrick von Platen <[email protected]>
1 parent 268ebcb commit ee71d9d

File tree

3 files changed

+157
-29
lines changed

3 files changed

+157
-29
lines changed

src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_pix2pix_zero.py

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,8 @@ class Pix2PixInversionPipelineOutput(BaseOutput):
153153
>>> source_embeds = pipeline.get_embeds(source_prompts)
154154
>>> target_embeds = pipeline.get_embeds(target_prompts)
155155
>>> # the latents can then be used to edit a real image
156+
>>> # when using Stable Diffusion 2 or other models that use v-prediction
157+
>>> # set `cross_attention_guidance_amount` to 0.01 or less to avoid input latent gradient explosion
156158
157159
>>> image = pipeline(
158160
... caption,
@@ -730,6 +732,23 @@ def prepare_image_latents(self, image, batch_size, dtype, device, generator=None
730732

731733
return latents
732734

735+
def get_epsilon(self, model_output: torch.Tensor, sample: torch.Tensor, timestep: int):
736+
pred_type = self.inverse_scheduler.config.prediction_type
737+
alpha_prod_t = self.inverse_scheduler.alphas_cumprod[timestep]
738+
739+
beta_prod_t = 1 - alpha_prod_t
740+
741+
if pred_type == "epsilon":
742+
return model_output
743+
elif pred_type == "sample":
744+
return (sample - alpha_prod_t ** (0.5) * model_output) / beta_prod_t ** (0.5)
745+
elif pred_type == "v_prediction":
746+
return (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
747+
else:
748+
raise ValueError(
749+
f"prediction_type given as {pred_type} must be one of `epsilon`, `sample`, or `v_prediction`"
750+
)
751+
733752
def auto_corr_loss(self, hidden_states, generator=None):
734753
batch_size, channel, height, width = hidden_states.shape
735754
if batch_size > 1:
@@ -1156,8 +1175,8 @@ def invert(
11561175

11571176
# 7. Denoising loop where we obtain the cross-attention maps.
11581177
num_warmup_steps = len(timesteps) - num_inference_steps * self.inverse_scheduler.order
1159-
with self.progress_bar(total=num_inference_steps - 2) as progress_bar:
1160-
for i, t in enumerate(timesteps[1:-1]):
1178+
with self.progress_bar(total=num_inference_steps - 1) as progress_bar:
1179+
for i, t in enumerate(timesteps[:-1]):
11611180
# expand the latents if we are doing classifier free guidance
11621181
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
11631182
latent_model_input = self.inverse_scheduler.scale_model_input(latent_model_input, t)
@@ -1181,7 +1200,11 @@ def invert(
11811200
if lambda_auto_corr > 0:
11821201
for _ in range(num_auto_corr_rolls):
11831202
var = torch.autograd.Variable(noise_pred.detach().clone(), requires_grad=True)
1184-
l_ac = self.auto_corr_loss(var, generator=generator)
1203+
1204+
# Derive epsilon from model output before regularizing to IID standard normal
1205+
var_epsilon = self.get_epsilon(var, latent_model_input.detach(), t)
1206+
1207+
l_ac = self.auto_corr_loss(var_epsilon, generator=generator)
11851208
l_ac.backward()
11861209

11871210
grad = var.grad.detach() / num_auto_corr_rolls
@@ -1190,7 +1213,10 @@ def invert(
11901213
if lambda_kl > 0:
11911214
var = torch.autograd.Variable(noise_pred.detach().clone(), requires_grad=True)
11921215

1193-
l_kld = self.kl_divergence(var)
1216+
# Derive epsilon from model output before regularizing to IID standard normal
1217+
var_epsilon = self.get_epsilon(var, latent_model_input.detach(), t)
1218+
1219+
l_kld = self.kl_divergence(var_epsilon)
11941220
l_kld.backward()
11951221

11961222
grad = var.grad.detach()

src/diffusers/schedulers/scheduling_ddim_inverse.py

Lines changed: 64 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323

2424
from diffusers.configuration_utils import ConfigMixin, register_to_config
2525
from diffusers.schedulers.scheduling_utils import SchedulerMixin
26-
from diffusers.utils import BaseOutput
26+
from diffusers.utils import BaseOutput, deprecate
2727

2828

2929
@dataclass
@@ -96,15 +96,17 @@ class DDIMInverseScheduler(SchedulerMixin, ConfigMixin):
9696
trained_betas (`np.ndarray`, optional):
9797
option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
9898
clip_sample (`bool`, default `True`):
99-
option to clip predicted sample between -1 and 1 for numerical stability.
100-
set_alpha_to_one (`bool`, default `True`):
99+
option to clip predicted sample for numerical stability.
100+
clip_sample_range (`float`, default `1.0`):
101+
the maximum magnitude for sample clipping. Valid only when `clip_sample=True`.
102+
set_alpha_to_zero (`bool`, default `True`):
101103
each diffusion step uses the value of alphas product at that step and at the previous one. For the final
102-
step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
103-
otherwise it uses the value of alpha at step 0.
104+
step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `0`,
105+
otherwise it uses the value of alpha at step `num_train_timesteps - 1`.
104106
steps_offset (`int`, default `0`):
105107
an offset added to the inference steps. You can use a combination of `offset=1` and
106-
`set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
107-
stable diffusion.
108+
`set_alpha_to_zero=False`, to make the last step use step `num_train_timesteps - 1` for the previous alpha
109+
product.
108110
prediction_type (`str`, default `epsilon`, optional):
109111
prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion
110112
process), `sample` (directly predicting the noisy sample`) or `v_prediction` (see section 2.4
@@ -122,10 +124,18 @@ def __init__(
122124
beta_schedule: str = "linear",
123125
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
124126
clip_sample: bool = True,
125-
set_alpha_to_one: bool = True,
127+
set_alpha_to_zero: bool = True,
126128
steps_offset: int = 0,
127129
prediction_type: str = "epsilon",
130+
clip_sample_range: float = 1.0,
131+
**kwargs,
128132
):
133+
if kwargs.get("set_alpha_to_one", None) is not None:
134+
deprecation_message = (
135+
"The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
136+
)
137+
deprecate("set_alpha_to_one", "1.0.0", deprecation_message, standard_warn=False)
138+
set_alpha_to_zero = kwargs["set_alpha_to_one"]
129139
if trained_betas is not None:
130140
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
131141
elif beta_schedule == "linear":
@@ -144,11 +154,12 @@ def __init__(
144154
self.alphas = 1.0 - self.betas
145155
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
146156

147-
# At every step in ddim, we are looking into the previous alphas_cumprod
148-
# For the final step, there is no previous alphas_cumprod because we are already at 0
149-
# `set_alpha_to_one` decides whether we set this parameter simply to one or
150-
# whether we use the final alpha of the "non-previous" one.
151-
self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
157+
# At every step in inverted ddim, we are looking into the next alphas_cumprod
158+
# For the final step, there is no next alphas_cumprod, and the index is out of bounds
159+
# `set_alpha_to_zero` decides whether we set this parameter simply to zero
160+
# in this case, self.step() just output the predicted noise
161+
# or whether we use the final alpha of the "non-previous" one.
162+
self.final_alpha_cumprod = torch.tensor(0.0) if set_alpha_to_zero else self.alphas_cumprod[-1]
152163

153164
# standard deviation of the initial noise distribution
154165
self.init_noise_sigma = 1.0
@@ -157,6 +168,7 @@ def __init__(
157168
self.num_inference_steps = None
158169
self.timesteps = torch.from_numpy(np.arange(0, num_train_timesteps).copy().astype(np.int64))
159170

171+
# Copied from diffusers.schedulers.scheduling_ddim.DDIMScheduler.scale_model_input
160172
def scale_model_input(self, sample: torch.FloatTensor, timestep: Optional[int] = None) -> torch.FloatTensor:
161173
"""
162174
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
@@ -205,23 +217,52 @@ def step(
205217
variance_noise: Optional[torch.FloatTensor] = None,
206218
return_dict: bool = True,
207219
) -> Union[DDIMSchedulerOutput, Tuple]:
208-
e_t = model_output
209-
210-
x = sample
220+
# 1. get previous step value (=t+1)
211221
prev_timestep = timestep + self.config.num_train_timesteps // self.num_inference_steps
212222

213-
a_t = self.alphas_cumprod[timestep - 1]
214-
a_prev = self.alphas_cumprod[prev_timestep - 1] if prev_timestep >= 0 else self.final_alpha_cumprod
223+
# 2. compute alphas, betas
224+
# change original implementation to exactly match noise levels for analogous forward process
225+
alpha_prod_t = self.alphas_cumprod[timestep]
226+
alpha_prod_t_prev = (
227+
self.alphas_cumprod[prev_timestep]
228+
if prev_timestep < self.config.num_train_timesteps
229+
else self.final_alpha_cumprod
230+
)
231+
232+
beta_prod_t = 1 - alpha_prod_t
233+
234+
# 3. compute predicted original sample from predicted noise also called
235+
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
236+
if self.config.prediction_type == "epsilon":
237+
pred_original_sample = (sample - beta_prod_t ** (0.5) * model_output) / alpha_prod_t ** (0.5)
238+
pred_epsilon = model_output
239+
elif self.config.prediction_type == "sample":
240+
pred_original_sample = model_output
241+
pred_epsilon = (sample - alpha_prod_t ** (0.5) * pred_original_sample) / beta_prod_t ** (0.5)
242+
elif self.config.prediction_type == "v_prediction":
243+
pred_original_sample = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
244+
pred_epsilon = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
245+
else:
246+
raise ValueError(
247+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"
248+
" `v_prediction`"
249+
)
215250

216-
pred_x0 = (x - (1 - a_t) ** 0.5 * e_t) / a_t.sqrt()
251+
# 4. Clip or threshold "predicted x_0"
252+
if self.config.clip_sample:
253+
pred_original_sample = pred_original_sample.clamp(
254+
-self.config.clip_sample_range, self.config.clip_sample_range
255+
)
217256

218-
dir_xt = (1.0 - a_prev).sqrt() * e_t
257+
# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
258+
pred_sample_direction = (1 - alpha_prod_t_prev) ** (0.5) * pred_epsilon
219259

220-
prev_sample = a_prev.sqrt() * pred_x0 + dir_xt
260+
# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
261+
prev_sample = alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction
221262

222263
if not return_dict:
223-
return (prev_sample, pred_x0)
224-
return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_x0)
264+
return (prev_sample, pred_original_sample)
265+
return DDIMSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
225266

226267
def __len__(self):
227268
return self.config.num_train_timesteps

tests/pipelines/stable_diffusion/test_stable_diffusion_pix2pix_zero.py

Lines changed: 63 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,6 @@ def test_stable_diffusion_pix2pix_inversion(self):
347347
pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(
348348
"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16
349349
)
350-
pipe.inverse_scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
351350
pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
352351

353352
caption = "a photography of a cat with flowers"
@@ -366,6 +365,28 @@ def test_stable_diffusion_pix2pix_inversion(self):
366365

367366
assert np.abs(expected_slice - image_slice.cpu().numpy()).max() < 5e-2
368367

368+
def test_stable_diffusion_2_pix2pix_inversion(self):
369+
pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(
370+
"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16
371+
)
372+
pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
373+
374+
caption = "a photography of a cat with flowers"
375+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
376+
pipe.enable_model_cpu_offload()
377+
pipe.set_progress_bar_config(disable=None)
378+
379+
generator = torch.manual_seed(0)
380+
output = pipe.invert(caption, image=self.raw_image, generator=generator, num_inference_steps=10)
381+
inv_latents = output[0]
382+
383+
image_slice = inv_latents[0, -3:, -3:, -1].flatten()
384+
385+
assert inv_latents.shape == (1, 4, 64, 64)
386+
expected_slice = np.array([0.7515, -0.2397, 0.4922, -0.9736, -0.7031, 0.4846, -1.0781, 1.1309, -0.6973])
387+
388+
assert np.abs(expected_slice - image_slice.cpu().numpy()).max() < 5e-2
389+
369390
def test_stable_diffusion_pix2pix_full(self):
370391
# numpy array of https://huggingface.co/datasets/hf-internal-testing/diffusers-images/blob/main/pix2pix/dog.png
371392
expected_image = load_numpy(
@@ -375,7 +396,6 @@ def test_stable_diffusion_pix2pix_full(self):
375396
pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(
376397
"CompVis/stable-diffusion-v1-4", safety_checker=None, torch_dtype=torch.float16
377398
)
378-
pipe.inverse_scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
379399
pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
380400

381401
caption = "a photography of a cat with flowers"
@@ -407,3 +427,44 @@ def test_stable_diffusion_pix2pix_full(self):
407427

408428
max_diff = np.abs(expected_image - image).mean()
409429
assert max_diff < 0.05
430+
431+
def test_stable_diffusion_2_pix2pix_full(self):
432+
# numpy array of https://huggingface.co/datasets/hf-internal-testing/diffusers-images/blob/main/pix2pix/dog_2.png
433+
expected_image = load_numpy(
434+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/pix2pix/dog_2.npy"
435+
)
436+
437+
pipe = StableDiffusionPix2PixZeroPipeline.from_pretrained(
438+
"stabilityai/stable-diffusion-2-1", safety_checker=None, torch_dtype=torch.float16
439+
)
440+
pipe.inverse_scheduler = DDIMInverseScheduler.from_config(pipe.scheduler.config)
441+
442+
caption = "a photography of a cat with flowers"
443+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
444+
pipe.enable_model_cpu_offload()
445+
pipe.set_progress_bar_config(disable=None)
446+
447+
generator = torch.manual_seed(0)
448+
output = pipe.invert(caption, image=self.raw_image, generator=generator)
449+
inv_latents = output[0]
450+
451+
source_prompts = 4 * ["a cat sitting on the street", "a cat playing in the field", "a face of a cat"]
452+
target_prompts = 4 * ["a dog sitting on the street", "a dog playing in the field", "a face of a dog"]
453+
454+
source_embeds = pipe.get_embeds(source_prompts)
455+
target_embeds = pipe.get_embeds(target_prompts)
456+
457+
image = pipe(
458+
caption,
459+
source_embeds=source_embeds,
460+
target_embeds=target_embeds,
461+
num_inference_steps=125,
462+
cross_attention_guidance_amount=0.015,
463+
generator=generator,
464+
latents=inv_latents,
465+
negative_prompt=caption,
466+
output_type="np",
467+
).images
468+
469+
max_diff = np.abs(expected_image - image).mean()
470+
assert max_diff < 0.05

0 commit comments

Comments
 (0)