DiffEdit: Diffusion-based semantic image editing with mask guidance by Guillaume Couairon, Jakob Verbeek, Holger Schwenk, and Matthieu Cord.
The abstract of the paper is the following:
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.
Resources:
generate_mask
)
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.
Refer to the code examples below for more details.generate_mask
exposes two prompt arguments, source_prompt
and target_prompt
,
that let you control the locations of the semantic edits in the final image to be generated. Let’s say,
you wanted to translate from “cat” to “dog”. In this case, the edit direction will be “cat -> dog”. To reflect
this in the generated mask, you simply have to set the embeddings related to the phrases including “cat” to
source_prompt_embeds
and “dog” to target_prompt_embeds
. Refer to the code example below for more details.invert
, assign a caption or text embedding describing the
overall image to the prompt
argument to help guide the inverse latent sampling process. In most cases, the
source concept is sufficently descriptive to yield good results, but feel free to explore alternatives.
Please refer to this code example for more details.negative_prompt
and the target concept to prompt
. Taking the above example, you simply have to set the embeddings related to
the phrases including “cat” to negative_prompt_embeds
and “dog” to prompt_embeds
. Refer to the code example
below for more details.source_prompt
and target_prompt
in the arguments to generate_mask
.invert
to include “dog”.prompt
and negative_prompt
in the arguments to call the pipeline to generate the final edited image.Pipeline | Tasks |
---|---|
StableDiffusionDiffEditPipeline | Text-Based Image Editing |
When the pipeline is conditioned on an input image, we first obtain partially inverted latents from the input image using a
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,
the inverted noise and generated mask is used to start the generation process.
First, let’s load our pipeline:
import torch
from diffusers import DDIMScheduler, DDIMInverseScheduler, StableDiffusionPix2PixZeroPipeline
sd_model_ckpt = "stabilityai/stable-diffusion-2-1"
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
sd_model_ckpt,
torch_dtype=torch.float16,
safety_checker=None,
)
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
pipeline.enable_model_cpu_offload()
pipeline.enable_vae_slicing()
generator = torch.manual_seed(0)
Then, we load an input image to edit using our method:
from diffusers.utils import load_image
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
Then, we employ the source and target prompts to generate the editing mask:
# See the "Generating source and target embeddings" section below to
# automate the generation of these captions with a pre-trained model like Flan-T5 as explained below.
source_prompt = "a bowl of fruits"
target_prompt = "a basket of fruits"
mask_image = pipeline.generate_mask(
image=raw_image,
source_prompt=source_prompt,
target_prompt=target_prompt,
generator=generator,
)
Then, we employ the caption and the input image to get the inverted latents:
inv_latents = pipeline.invert(prompt=source_prompt, image=raw_image, generator=generator).latents
Now, generate the image with the inverted latents and semantically generated mask:
image = pipeline(
prompt=target_prompt,
mask_image=mask_image,
image_latents=inv_latents,
generator=generator,
negative_prompt=source_prompt,
).images[0]
image.save("edited_image.png")
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. Below, we provide an end-to-end example with the BLIP model for generating captions.
First, let’s load our automatic image captioning model:
import torch
from transformers import BlipForConditionalGeneration, BlipProcessor
captioner_id = "Salesforce/blip-image-captioning-base"
processor = BlipProcessor.from_pretrained(captioner_id)
model = BlipForConditionalGeneration.from_pretrained(captioner_id, torch_dtype=torch.float16, low_cpu_mem_usage=True)
Then, we define a utility to generate captions from an input image using the model:
@torch.no_grad()
def generate_caption(images, caption_generator, caption_processor):
text = "a photograph of"
inputs = caption_processor(images, text, return_tensors="pt").to(device="cuda", dtype=caption_generator.dtype)
caption_generator.to("cuda")
outputs = caption_generator.generate(**inputs, max_new_tokens=128)
# offload caption generator
caption_generator.to("cpu")
caption = caption_processor.batch_decode(outputs, skip_special_tokens=True)[0]
return caption
Then, we load an input image for conditioning and obtain a suitable caption for it:
from diffusers.utils import load_image
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
caption = generate_caption(raw_image, model, processor)
Then, we employ the generated caption and the input image to get the inverted latents:
from diffusers import DDIMInverseScheduler, DDIMScheduler
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
)
pipeline = pipeline.to("cuda")
pipeline.enable_model_cpu_offload()
pipeline.enable_vae_slicing()
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
generator = torch.manual_seed(0)
inv_latents = pipeline.invert(prompt=caption, image=raw_image, generator=generator).latents
Now, generate the image with the inverted latents and semantically generated mask from our source and target prompts:
source_prompt = "a bowl of fruits"
target_prompt = "a basket of fruits"
mask_image = pipeline.generate_mask(
image=raw_image,
source_prompt=source_prompt,
target_prompt=target_prompt,
generator=generator,
)
image = pipeline(
prompt=target_prompt,
mask_image=mask_image,
image_latents=inv_latents,
generator=generator,
negative_prompt=source_prompt,
).images[0]
image.save("edited_image.png")
The authors originally required the user to manually provide the source and target prompts for discovering edit directions. However, we can also leverage open source and public models for the same purpose. Below, we provide an end-to-end example with the Flan-T5 model for generating source an target embeddings.
1. Load the generation model:
import torch
from transformers import AutoTokenizer, T5ForConditionalGeneration
tokenizer = AutoTokenizer.from_pretrained("google/flan-t5-xl")
model = T5ForConditionalGeneration.from_pretrained("google/flan-t5-xl", device_map="auto", torch_dtype=torch.float16)
2. Construct a starting prompt:
source_concept = "bowl"
target_concept = "basket"
source_text = f"Provide a caption for images containing a {source_concept}. "
"The captions should be in English and should be no longer than 150 characters."
target_text = f"Provide a caption for images containing a {target_concept}. "
"The captions should be in English and should be no longer than 150 characters."
Here, we’re interested in the “bowl -> basket” direction.
3. Generate prompts:
We can use a utility like so for this purpose.
@torch.no_grad
def generate_prompts(input_prompt):
input_ids = tokenizer(input_prompt, return_tensors="pt").input_ids.to("cuda")
outputs = model.generate(
input_ids, temperature=0.8, num_return_sequences=16, do_sample=True, max_new_tokens=128, top_k=10
)
return tokenizer.batch_decode(outputs, skip_special_tokens=True)
And then we just call it to generate our prompts:
source_prompts = generate_prompts(source_text) target_prompts = generate_prompts(target_text)
We encourage you to play around with the different parameters supported by the
generate()
method (documentation) for the generation quality you are looking for.
4. Load the embedding model:
Here, we need to use the same text encoder model used by the subsequent Stable Diffusion model.
from diffusers import StableDiffusionDiffEditPipeline
pipeline = StableDiffusionDiffEditPipeline.from_pretrained(
"stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
)
pipeline = pipeline.to("cuda")
pipeline.enable_model_cpu_offload()
pipeline.enable_vae_slicing()
generator = torch.manual_seed(0)
5. Compute embeddings:
import torch
@torch.no_grad()
def embed_prompts(sentences, tokenizer, text_encoder, device="cuda"):
embeddings = []
for sent in sentences:
text_inputs = tokenizer(
sent,
padding="max_length",
max_length=tokenizer.model_max_length,
truncation=True,
return_tensors="pt",
)
text_input_ids = text_inputs.input_ids
prompt_embeds = text_encoder(text_input_ids.to(device), attention_mask=None)[0]
embeddings.append(prompt_embeds)
return torch.concatenate(embeddings, dim=0).mean(dim=0).unsqueeze(0)
source_embeddings = embed_prompts(source_prompts, pipeline.tokenizer, pipeline.text_encoder)
target_embeddings = embed_prompts(target_captions, pipeline.tokenizer, pipeline.text_encoder)
And you’re done! Now, you can use these embeddings directly while calling the pipeline:
from diffusers import DDIMInverseScheduler, DDIMScheduler
from diffusers.utils import load_image
pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
raw_image = load_image(img_url).convert("RGB").resize((768, 768))
mask_image = pipeline.generate_mask(
image=raw_image,
source_prompt_embeds=source_embeds,
target_prompt_embeds=target_embeds,
generator=generator,
)
inv_latents = pipeline.invert(
prompt_embeds=source_embeds,
image=raw_image,
generator=generator,
).latents
images = pipeline(
mask_image=mask_image,
image_latents=inv_latents,
prompt_embeds=target_embeddings,
negative_prompt_embeds=source_embeddings,
generator=generator,
).images
images[0].save("edited_image.png")
( vae: AutoencoderKL text_encoder: CLIPTextModel tokenizer: CLIPTokenizer unet: UNet2DConditionModel scheduler: KarrasDiffusionSchedulers safety_checker: StableDiffusionSafetyChecker feature_extractor: CLIPImageProcessor inverse_scheduler: DDIMInverseScheduler requires_safety_checker: bool = True )
Parameters
CLIPTextModel
) —
Frozen text-encoder. Stable Diffusion uses the text portion of
CLIP, specifically
the clip-vit-large-patch14 variant.
CLIPTokenizer
) —
Tokenizer of class
CLIPTokenizer.
unet
to denoise the encoded image latents.
[DDIMInverseScheduler]
) —
A scheduler to be used in combination with unet
to fill in the unmasked part of the input latents
StableDiffusionSafetyChecker
) —
Classification module that estimates whether generated images could be considered offensive or harmful.
Please, refer to the model card for details.
CLIPImageProcessor
) —
Model that extracts features from generated images to be used as inputs for the safety_checker
.
Pipeline for text-guided image inpainting using Stable Diffusion using DiffEdit. This is an experimental feature.
This model inherits from DiffusionPipeline. Check the superclass documentation for the generic methods the library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
In addition the pipeline inherits the following loading methods:
as well as the following saving methods:
(
image: typing.Union[torch.FloatTensor, PIL.Image.Image] = None
target_prompt: typing.Union[str, typing.List[str], NoneType] = None
target_negative_prompt: typing.Union[str, typing.List[str], NoneType] = None
target_prompt_embeds: typing.Optional[torch.FloatTensor] = None
target_negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None
source_prompt: typing.Union[str, typing.List[str], NoneType] = None
source_negative_prompt: typing.Union[str, typing.List[str], NoneType] = None
source_prompt_embeds: typing.Optional[torch.FloatTensor] = None
source_negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None
num_maps_per_mask: typing.Optional[int] = 10
mask_encode_strength: typing.Optional[float] = 0.5
mask_thresholding_ratio: typing.Optional[float] = 3.0
num_inference_steps: int = 50
guidance_scale: float = 7.5
generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None
output_type: typing.Optional[str] = 'np'
cross_attention_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None
)
→
List[PIL.Image.Image]
or np.array
Parameters
PIL.Image.Image
) —
Image
, or tensor representing an image batch which will be used for computing the mask.
str
or List[str]
, optional) —
The prompt or prompts to guide the semantic mask generation. If not defined, one has to pass
prompt_embeds
. instead.
str
or List[str]
, optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds
. instead. Ignored when not using guidance (i.e., ignored if guidance_scale
is less than 1
).
torch.FloatTensor
, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt
input argument.
torch.FloatTensor
, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt
input
argument.
str
or List[str]
, optional) —
The prompt or prompts to guide the semantic mask generation using the method in DiffEdit:
Diffusion-Based Semantic Image Editing with Mask Guidance. If
not defined, one has to pass source_prompt_embeds
or source_image
instead.
str
or List[str]
, optional) —
The prompt or prompts to guide the semantic mask generation away from using the method in DiffEdit:
Diffusion-Based Semantic Image Editing with Mask Guidance. If
not defined, one has to pass source_negative_prompt_embeds
or source_image
instead.
torch.FloatTensor
, optional) —
Pre-generated text embeddings to guide the semantic mask generation. Can be used to easily tweak text
inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from
source_prompt
input argument.
torch.FloatTensor
, optional) —
Pre-generated text embeddings to negatively guide the semantic mask generation. Can be used to easily
tweak text inputs, e.g. prompt weighting. If not provided, text embeddings will be generated from
source_negative_prompt
input argument.
int
, optional, defaults to 10) —
The number of noise maps sampled to generate the semantic mask using the method in DiffEdit:
Diffusion-Based Semantic Image Editing with Mask Guidance.
float
, optional, defaults to 0.5) —
Conceptually, the strength of the noise maps sampled to generate the semantic mask using the method in
DiffEdit: Diffusion-Based Semantic Image Editing with Mask Guidance. Must be between 0 and 1.
float
, optional, defaults to 3.0) —
The maximum multiple of the mean absolute difference used to clamp the semantic guidance map before
mask binarization.
int
, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional, defaults to 7.5) —
Guidance scale as defined in Classifier-Free Diffusion Guidance.
guidance_scale
is defined as w
of equation 2. of Imagen
Paper. Guidance scale is enabled by setting guidance_scale > 1
. Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
torch.Generator
or List[torch.Generator]
, optional) —
One or a list of torch generator(s)
to make generation deterministic.
str
, optional, defaults to "pil"
) —
The output format of the generate image. Choose between
PIL: PIL.Image.Image
or np.array
.
dict
, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor
as defined under
self.processor
in
diffusers.cross_attention.
Returns
List[PIL.Image.Image]
or np.array
List[PIL.Image.Image]
if output_type
is "pil"
, otherwise a
np.array
. When returning a List[PIL.Image.Image]
, the list will consist of a batch of single-channel
binary image with dimensions (height // self.vae_scale_factor, width // self.vae_scale_factor)
, otherwise
the np.array
will have shape (batch_size, height // self.vae_scale_factor, width // self.vae_scale_factor)
.
Function used to generate a latent mask given a mask prompt, a target prompt, and an image.
Examples:
( prompt: typing.Union[str, typing.List[str], NoneType] = None image: typing.Union[torch.FloatTensor, PIL.Image.Image] = None num_inference_steps: int = 50 inpaint_strength: float = 0.8 guidance_scale: float = 7.5 negative_prompt: typing.Union[str, typing.List[str], NoneType] = None generator: typing.Union[torch._C.Generator, typing.List[torch._C.Generator], NoneType] = None prompt_embeds: typing.Optional[torch.FloatTensor] = None negative_prompt_embeds: typing.Optional[torch.FloatTensor] = None decode_latents: bool = False output_type: typing.Optional[str] = 'pil' return_dict: bool = True callback: typing.Union[typing.Callable[[int, int, torch.FloatTensor], NoneType], NoneType] = None callback_steps: typing.Optional[int] = 1 cross_attention_kwargs: typing.Union[typing.Dict[str, typing.Any], NoneType] = None lambda_auto_corr: float = 20.0 lambda_kl: float = 20.0 num_reg_steps: int = 0 num_auto_corr_rolls: int = 5 )
Parameters
str
or List[str]
, optional) —
The prompt or prompts to guide the image generation. If not defined, one has to pass prompt_embeds
.
instead.
PIL.Image.Image
) —
Image
, or tensor representing an image batch to produce the inverted latents, guided by prompt
.
float
, optional, defaults to 0.8) —
Conceptually, indicates how far into the noising process to run latent inversion. Must be between 0 andstrength
is 1, the inversion process will be run for the full number of iterations specified
in num_inference_steps
. image
will be used as a reference for the inversion process, adding more
noise the larger the strength
. If strength
is 0, no inpainting will occur.int
, optional, defaults to 50) —
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
expense of slower inference.
float
, optional, defaults to 7.5) —
Guidance scale as defined in Classifier-Free Diffusion Guidance.
guidance_scale
is defined as w
of equation 2. of Imagen
Paper. Guidance scale is enabled by setting guidance_scale > 1
. Higher guidance scale encourages to generate images that are closely linked to the text prompt
,
usually at the expense of lower image quality.
str
or List[str]
, optional) —
The prompt or prompts not to guide the image generation. If not defined, one has to pass
negative_prompt_embeds
. instead. Ignored when not using guidance (i.e., ignored if guidance_scale
is less than 1
).
torch.Generator
, optional) —
One or a list of torch generator(s)
to make generation deterministic.
torch.FloatTensor
, optional) —
Pre-generated text embeddings. Can be used to easily tweak text inputs, e.g. prompt weighting. If not
provided, text embeddings will be generated from prompt
input argument.
torch.FloatTensor
, optional) —
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, e.g. prompt
weighting. If not provided, negative_prompt_embeds will be generated from negative_prompt
input
argument.
bool
, optional, defaults to False
) —
Whether or not to decode the inverted latents into a generated image. Setting this argument to True
will decode all inverted latents for each timestep into a list of generated images.
str
, optional, defaults to "pil"
) —
The output format of the generate image. Choose between
PIL: PIL.Image.Image
or np.array
.
bool
, optional, defaults to True
) —
Whether or not to return a ~pipelines.stable_diffusion.DiffEditInversionPipelineOutput
instead of a
plain tuple.
Callable
, optional) —
A function that will be called every callback_steps
steps during inference. The function will be
called with the following arguments: callback(step: int, timestep: int, latents: torch.FloatTensor)
.
int
, optional, defaults to 1) —
The frequency at which the callback
function will be called. If not specified, the callback will be
called at every step.
dict
, optional) —
A kwargs dictionary that if specified is passed along to the AttentionProcessor
as defined under
self.processor
in
diffusers.cross_attention.
float
, optional, defaults to 20.0) —
Lambda parameter to control auto correction
float
, optional, defaults to 20.0) —
Lambda parameter to control Kullback–Leibler divergence output
int
, optional, defaults to 0) —
Number of regularization loss steps
int
, optional, defaults to 5) —
Number of auto correction roll steps
Function used to generate inverted latents given a prompt and image.
>>> import PIL
>>> import requests
>>> import torch
>>> from io import BytesIO
>>> from diffusers import StableDiffusionDiffEditPipeline
>>> def download_image(url):
... response = requests.get(url)
... return PIL.Image.open(BytesIO(response.content)).convert("RGB")
>>> img_url = "https://github.com/Xiang-cd/DiffEdit-stable-diffusion/raw/main/assets/origin.png"
>>> init_image = download_image(img_url).resize((768, 768))
>>> pipe = StableDiffusionDiffEditPipeline.from_pretrained(
... "stabilityai/stable-diffusion-2-1", torch_dtype=torch.float16
... )
>>> pipe = pipe.to("cuda")
>>> pipeline.scheduler = DDIMScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.inverse_scheduler = DDIMInverseScheduler.from_config(pipeline.scheduler.config)
>>> pipeline.enable_model_cpu_offload()
>>> prompt = "A bowl of fruits"
>>> inverted_latents = pipe.invert(image=init_image, prompt=prompt).latents
Disable sliced VAE decoding. If enable_vae_slicing
was previously invoked, this method will go back to
computing decoding in one step.
Disable tiled VAE decoding. If enable_vae_tiling
was previously invoked, this method will go back to
computing decoding in one step.
Offloads all models to CPU using accelerate, reducing memory usage with a low impact on performance. Compared
to enable_sequential_cpu_offload
, this method moves one whole model at a time to the GPU when its forward
method is called, and the model remains in GPU until the next model runs. Memory savings are lower than with
enable_sequential_cpu_offload
, but performance is much better due to the iterative execution of the unet
.
Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
torch.device('meta') and loaded to GPU only when their specific submodule has its
forwardmethod called. Note that offloading happens on a submodule basis. Memory savings are higher than with
enable_model_cpu_offload`, but performance is lower.
Enable sliced VAE decoding.
When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.
Enable tiled VAE decoding.
When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in several steps. This is useful to save a large amount of memory and to allow the processing of larger images.