Skip to content

Commit be0bfce

Browse files
authored
Diffedit Zero-Shot Inpainting Pipeline (#2837)
* Update Pix2PixZero Auto-correlation Loss * Add Stable Diffusion DiffEdit pipeline * Add draft documentation and import code * Bugfixes and refactoring * Add option to not decode latents in the inversion process * Harmonize preprocessing * Revert "Update Pix2PixZero Auto-correlation Loss" This reverts commit b218062. * Update annotations * rename `compute_mask` to `generate_mask` * Update documentation * Update docs * Update Docs * Fix copy * Change shape of output latents to batch first * Update docs * Add first draft for tests * Bugfix and update tests * Add `cross_attention_kwargs` support for all pipeline methods * Fix Copies * Add support for PIL image latents Add support for mask broadcasting Update docs and tests Align `mask` argument to `mask_image` Remove height and width arguments * Enable MPS Tests * Move example docstrings * Fix test * Fix test * fix pipeline inheritance * Harmonize `prepare_image_latents` with StableDiffusionPix2PixZeroPipeline * Register modules set to `None` in config for `test_save_load_optional_components` * Move fixed logic to specific test class * Clean changes to other pipelines * Update new tests to coordinate with #2953 * Update slow tests for better results * Safety to avoid potential problems with torch.inference_mode * Add reference in SD Pipeline Overview * Fix tests again * Enforce determinism in noise for generate_mask * Fix copies * Widen test tolerance for fp16 based on `test_stable_diffusion_upscale_pipeline_fp16` * Add LoraLoaderMixin and update `prepare_image_latents` * clean up repeat and reg * bugfix * Remove invalid args from docs Suppress spurious warning by repeating image before latent to mask gen
1 parent d464214 commit be0bfce

File tree

9 files changed

+2227
-0
lines changed

9 files changed

+2227
-0
lines changed

docs/source/en/_toctree.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,8 @@
203203
title: Text-to-Image Generation with ControlNet Conditioning
204204
- local: api/pipelines/stable_diffusion/model_editing
205205
title: Text-to-Image Model Editing
206+
- local: api/pipelines/stable_diffusion/diffedit
207+
title: DiffEdit
206208
title: Stable Diffusion
207209
- local: api/pipelines/stable_diffusion_2
208210
title: Stable Diffusion 2
Lines changed: 360 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,360 @@
1+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
2+
3+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
4+
the License. You may obtain a copy of the License at
5+
6+
http://www.apache.org/licenses/LICENSE-2.0
7+
8+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
9+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
10+
specific language governing permissions and limitations under the License.
11+
-->
12+
13+
# Zero-shot Diffusion-based Semantic Image Editing with Mask Guidance
14+
15+
## Overview
16+
17+
[DiffEdit: Diffusion-based semantic image editing with mask guidance](https://arxiv.org/abs/2210.11427) by Guillaume Couairon, Jakob Verbeek, Holger Schwenk, and Matthieu Cord.
18+
19+
The abstract of the paper is the following:
20+
21+
*Image generation has recently seen tremendous advances, with diffusion models allowing to synthesize convincing images for a large variety of text prompts. In this article, we propose DiffEdit, a method to take advantage of text-conditioned diffusion models for the task of semantic image editing, where the goal is to edit an image based on a text query. Semantic image editing is an extension of image generation, with the additional constraint that the generated image should be as similar as possible to a given input image. Current editing methods based on diffusion models usually require to provide a mask, making the task much easier by treating it as a conditional inpainting task. In contrast, our main contribution is able to automatically generate a mask highlighting regions of the input image that need to be edited, by contrasting predictions of a diffusion model conditioned on different text prompts. Moreover, we rely on latent inference to preserve content in those regions of interest and show excellent synergies with mask-based diffusion. DiffEdit achieves state-of-the-art editing performance on ImageNet. In addition, we evaluate semantic image editing in more challenging settings, using images from the COCO dataset as well as text-based generated images.*
22+
23+
Resources:
24+
25+
* [Paper](https://arxiv.org/abs/2210.11427).
26+
* [Blog Post with Demo](https://blog.problemsolversguild.com/technical/research/2022/11/02/DiffEdit-Implementation.html).
27+
* [Implementation on Github](https://github.com/Xiang-cd/DiffEdit-stable-diffusion/).
28+
29+
## Tips
30+
31+
* The pipeline can generate masks that can be fed into other inpainting pipelines. Check out the code examples below to know more.
32+
* In order to generate an image using this pipeline, both an image mask (manually specified or generated using `generate_mask`)
33+
and a set of partially inverted latents (generated using `invert`) _must_ be provided as arguments when calling the pipeline to generate the final edited image.
34+
Refer to the code examples below for more details.
35+
* The function `generate_mask` exposes two prompt arguments, `source_prompt` and `target_prompt`,
36+
that let you control the locations of the semantic edits in the final image to be generated. Let's say,
37+
you wanted to translate from "cat" to "dog". In this case, the edit direction will be "cat -> dog". To reflect
38+
this in the generated mask, you simply have to set the embeddings related to the phrases including "cat" to
39+
`source_prompt_embeds` and "dog" to `target_prompt_embeds`. Refer to the code example below for more details.
40+
* When generating partially inverted latents using `invert`, assign a caption or text embedding describing the
41+
overall image to the `prompt` argument to help guide the inverse latent sampling process. In most cases, the
42+
source concept is sufficently descriptive to yield good results, but feel free to explore alternatives.
43+
Please refer to [this code example](#generating-image-captions-for-inversion) for more details.
44+
* When calling the pipeline to generate the final edited image, assign the source concept to `negative_prompt`
45+
and the target concept to `prompt`. Taking the above example, you simply have to set the embeddings related to
46+
the phrases including "cat" to `negative_prompt_embeds` and "dog" to `prompt_embeds`. Refer to the code example
47+
below for more details.
48+
* If you wanted to reverse the direction in the example above, i.e., "dog -> cat", then it's recommended to:
49+
* Swap the `source_prompt` and `target_prompt` in the arguments to `generate_mask`.
50+
* Change the input prompt for `invert` to include "dog".
51+
* Swap the `prompt` and `negative_prompt` in the arguments to call the pipeline to generate the final edited image.
52+
* Note that the source and target prompts, or their corresponding embeddings, can also be automatically generated. Please, refer to [this discussion](#generating-source-and-target-embeddings) for more details.
53+
54+
## Available Pipelines:
55+
56+
| Pipeline | Tasks
57+
|---|---|
58+
| [StableDiffusionDiffEditPipeline](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_diffedit.py) | *Text-Based Image Editing*
59+
60+
<!-- TODO: add Colab -->
61+
62+
## Usage example
63+
64+
### Based on an input image with a caption
65+
66+
When the pipeline is conditioned on an input image, we first obtain partially inverted latents from the input image using a
67+
`DDIMInverseScheduler` with the help of a caption. Then we generate an editing mask to identify relevant regions in the image using the source and target prompts. Finally,
68+
the inverted noise and generated mask is used to start the generation process.
69+
70+
First, let's load our pipeline:
71+
72+
```py
73+
import torch
74+
from diffusers import DDIMScheduler, DDIMInverseScheduler, StableDiffusionPix2PixZeroPipeline
75+
76+
sd_model_ckpt = "stabilityai/stable-diffusion-2-1"
77+
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
78+
sd_model_ckpt,
79+
torch_dtype=torch.float16,
80+
safety_checker=None,
81+
)
82+
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
83+
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
84+
pipeline.enable_model_cpu_offload()
85+
pipeline.enable_vae_slicing()
86+
generator = torch.manual_seed(0)
87+
```
88+
89+
Then, we load an input image to edit using our method:
90+
91+
```py
92+
from diffusers.utils import load_image
93+
94+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
95+
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
96+
```
97+
98+
Then, we employ the source and target prompts to generate the editing mask:
99+
100+
```py
101+
# See the "Generating source and target embeddings" section below to
102+
# automate the generation of these captions with a pre-trained model like Flan-T5 as explained below.
103+
104+
source_prompt = "a bowl of fruits"
105+
target_prompt = "a basket of fruits"
106+
mask_image = pipeline.generate_mask(
107+
image=raw_image,
108+
source_prompt=source_prompt,
109+
target_prompt=target_prompt,
110+
generator=generator,
111+
)
112+
```
113+
114+
Then, we employ the caption and the input image to get the inverted latents:
115+
116+
```py
117+
inv_latents = pipeline.invert(prompt=source_prompt, image=raw_image, generator=generator).latents
118+
```
119+
120+
Now, generate the image with the inverted latents and semantically generated mask:
121+
122+
```py
123+
image = pipeline(
124+
prompt=target_prompt,
125+
mask_image=mask_image,
126+
image_latents=inv_latents,
127+
generator=generator,
128+
negative_prompt=source_prompt,
129+
).images[0]
130+
image.save("edited_image.png")
131+
```
132+
133+
## Generating image captions for inversion
134+
135+
The authors originally used the source concept prompt as the caption for generating the partially inverted latents. However, we can also leverage open source and public image captioning models for the same purpose.
136+
Below, we provide an end-to-end example with the [BLIP](https://huggingface.co/docs/transformers/model_doc/blip) model
137+
for generating captions.
138+
139+
First, let's load our automatic image captioning model:
140+
141+
```py
142+
import torch
143+
from transformers import BlipForConditionalGeneration, BlipProcessor
144+
145+
captioner_id = "Salesforce/blip-image-captioning-base"
146+
processor = BlipProcessor.from_pretrained(captioner_id)
147+
model = BlipForConditionalGeneration.from_pretrained(captioner_id, torch_dtype=torch.float16, low_cpu_mem_usage=True)
148+
```
149+
150+
Then, we define a utility to generate captions from an input image using the model:
151+
152+
```py
153+
@torch.no_grad()
154+
def generate_caption(images, caption_generator, caption_processor):
155+
text = "a photograph of"
156+
157+
inputs = caption_processor(images, text, return_tensors="pt").to(device="cuda", dtype=caption_generator.dtype)
158+
caption_generator.to("cuda")
159+
outputs = caption_generator.generate(**inputs, max_new_tokens=128)
160+
161+
# offload caption generator
162+
caption_generator.to("cpu")
163+
164+
caption = caption_processor.batch_decode(outputs, skip_special_tokens=True)[0]
165+
return caption
166+
```
167+
168+
Then, we load an input image for conditioning and obtain a suitable caption for it:
169+
170+
```py
171+
from diffusers.utils import load_image
172+
173+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
174+
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
175+
caption = generate_caption(raw_image, model, processor)
176+
```
177+
178+
Then, we employ the generated caption and the input image to get the inverted latents:
179+
180+
```py
181+
from diffusers import DDIMInverseScheduler, DDIMScheduler
182+
183+
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
184+
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
185+
)
186+
pipeline = pipeline.to("cuda")
187+
pipeline.enable_model_cpu_offload()
188+
pipeline.enable_vae_slicing()
189+
190+
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
191+
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
192+
193+
generator = torch.manual_seed(0)
194+
inv_latents = pipeline.invert(prompt=caption, image=raw_image, generator=generator).latents
195+
```
196+
197+
Now, generate the image with the inverted latents and semantically generated mask from our source and target prompts:
198+
199+
```py
200+
source_prompt = "a bowl of fruits"
201+
target_prompt = "a basket of fruits"
202+
203+
mask_image = pipeline.generate_mask(
204+
image=raw_image,
205+
source_prompt=source_prompt,
206+
target_prompt=target_prompt,
207+
generator=generator,
208+
)
209+
210+
image = pipeline(
211+
prompt=target_prompt,
212+
mask_image=mask_image,
213+
image_latents=inv_latents,
214+
generator=generator,
215+
negative_prompt=source_prompt,
216+
).images[0]
217+
image.save("edited_image.png")
218+
```
219+
220+
## Generating source and target embeddings
221+
222+
The authors originally required the user to manually provide the source and target prompts for discovering
223+
edit directions. However, we can also leverage open source and public models for the same purpose.
224+
Below, we provide an end-to-end example with the [Flan-T5](https://huggingface.co/docs/transformers/model_doc/flan-t5) model
225+
for generating source an target embeddings.
226+
227+
**1. Load the generation model**:
228+
229+
```py
230+
import torch
231+
from transformers import AutoTokenizer, T5ForConditionalGeneration
232+
233+
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-xl")
234+
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-xl", device_map="auto", torch_dtype=torch.float16)
235+
```
236+
237+
**2. Construct a starting prompt**:
238+
239+
```py
240+
source_concept = "bowl"
241+
target_concept = "basket"
242+
243+
source_text = f"Provide a caption for images containing a {source_concept}. "
244+
"The captions should be in English and should be no longer than 150 characters."
245+
246+
target_text = f"Provide a caption for images containing a {target_concept}. "
247+
"The captions should be in English and should be no longer than 150 characters."
248+
```
249+
250+
Here, we're interested in the "bowl -> basket" direction.
251+
252+
**3. Generate prompts**:
253+
254+
We can use a utility like so for this purpose.
255+
256+
```py
257+
@torch.no_grad
258+
def generate_prompts(input_prompt):
259+
input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids.to("cuda")
260+
261+
outputs = model.generate(
262+
input_ids, temperature=0.8, num_return_sequences=16, do_sample=True, max_new_tokens=128, top_k=10
263+
)
264+
return tokenizer.batch_decode(outputs, skip_special_tokens=True)
265+
```
266+
267+
And then we just call it to generate our prompts:
268+
269+
```py
270+
source_prompts = generate_prompts(source_text)
271+
target_prompts = generate_prompts(target_text)
272+
```
273+
274+
We encourage you to play around with the different parameters supported by the
275+
`generate()` method ([documentation](https://huggingface.co/docs/transformers/main/en/main_classes/text_generation#transformers.generation_tf_utils.TFGenerationMixin.generate)) for the generation quality you are looking for.
276+
277+
**4. Load the embedding model**:
278+
279+
Here, we need to use the same text encoder model used by the subsequent Stable Diffusion model.
280+
281+
```py
282+
from diffusers import StableDiffusionDiffEditPipeline
283+
284+
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
285+
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
286+
)
287+
pipeline = pipeline.to("cuda")
288+
pipeline.enable_model_cpu_offload()
289+
pipeline.enable_vae_slicing()
290+
291+
generator = torch.manual_seed(0)
292+
```
293+
294+
**5. Compute embeddings**:
295+
296+
```py
297+
import torch
298+
299+
@torch.no_grad()
300+
def embed_prompts(sentences, tokenizer, text_encoder, device="cuda"):
301+
embeddings = []
302+
for sent in sentences:
303+
text_inputs = tokenizer(
304+
sent,
305+
padding="max_length",
306+
max_length=tokenizer.model_max_length,
307+
truncation=True,
308+
return_tensors="pt",
309+
)
310+
text_input_ids = text_inputs.input_ids
311+
prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]
312+
embeddings.append(prompt_embeds)
313+
return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)
314+
315+
source_embeddings = embed_prompts(source_prompts, pipeline.tokenizer, pipeline.text_encoder)
316+
target_embeddings = embed_prompts(target_captions, pipeline.tokenizer, pipeline.text_encoder)
317+
```
318+
319+
And you're done! Now, you can use these embeddings directly while calling the pipeline:
320+
321+
```py
322+
from diffusers import DDIMInverseScheduler, DDIMScheduler
323+
from diffusers.utils import load_image
324+
325+
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
326+
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
327+
328+
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
329+
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
330+
331+
332+
mask_image = pipeline.generate_mask(
333+
image=raw_image,
334+
source_prompt_embeds=source_embeds,
335+
target_prompt_embeds=target_embeds,
336+
generator=generator,
337+
)
338+
339+
inv_latents = pipeline.invert(
340+
prompt_embeds=source_embeds,
341+
image=raw_image,
342+
generator=generator,
343+
).latents
344+
345+
images = pipeline(
346+
mask_image=mask_image,
347+
image_latents=inv_latents,
348+
prompt_embeds=target_embeddings,
349+
negative_prompt_embeds=source_embeddings,
350+
generator=generator,
351+
).images
352+
images[0].save("edited_image.png")
353+
```
354+
355+
## StableDiffusionDiffEditPipeline
356+
[[autodoc]] StableDiffusionDiffEditPipeline
357+
- all
358+
- generate_mask
359+
- invert
360+
- __call__

docs/source/en/api/pipelines/stable_diffusion/overview.mdx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ For more details about how Stable Diffusion works and how it differs from the ba
3636
| [StableDiffusionAttendAndExcitePipeline](./attend_and_excite) | **Experimental** *Text-to-Image Generation * | | [Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models](https://huggingface.co/spaces/AttendAndExcite/Attend-and-Excite)
3737
| [StableDiffusionPix2PixZeroPipeline](./pix2pix_zero) | **Experimental** *Text-Based Image Editing * | | [Zero-shot Image-to-Image Translation](https://arxiv.org/abs/2302.03027)
3838
| [StableDiffusionModelEditingPipeline](./model_editing) | **Experimental** *Text-to-Image Model Editing * | | [Editing Implicit Assumptions in Text-to-Image Diffusion Models](https://arxiv.org/abs/2303.08084)
39+
| [StableDiffusionDiffEditPipeline](./diffedit) | **Experimental** *Text-Based Image Editing * | | [DiffEdit: Diffusion-based semantic image editing with mask guidance](https://arxiv.org/abs/2210.11427)
3940

4041

4142

src/diffusers/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@
134134
StableDiffusionAttendAndExcitePipeline,
135135
StableDiffusionControlNetPipeline,
136136
StableDiffusionDepth2ImgPipeline,
137+
StableDiffusionDiffEditPipeline,
137138
StableDiffusionImageVariationPipeline,
138139
StableDiffusionImg2ImgPipeline,
139140
StableDiffusionInpaintPipeline,

src/diffusers/pipelines/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@
6060
StableDiffusionAttendAndExcitePipeline,
6161
StableDiffusionControlNetPipeline,
6262
StableDiffusionDepth2ImgPipeline,
63+
StableDiffusionDiffEditPipeline,
6364
StableDiffusionImageVariationPipeline,
6465
StableDiffusionImg2ImgPipeline,
6566
StableDiffusionInpaintPipeline,

0 commit comments

Comments
 (0)