Spaces:
Running
on
Zero
Running
on
Zero
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel | |
import torch | |
import numpy as np | |
from typing import Any, Callable, Dict, List, Optional, Union | |
import sys | |
import PIL | |
import os | |
import inspect | |
import diffusers | |
path = inspect.getfile(diffusers) | |
sys.path.append(os.path.join(path, "pipelines/controlnet")) | |
sys.path.append(path) | |
from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel | |
from diffusers.utils import replace_example_docstring | |
from diffusers.image_processor import PipelineImageInput | |
from diffusers.utils.torch_utils import is_compiled_module | |
from diffusers.loaders import TextualInversionLoaderMixin, LoraLoaderMixin | |
from diffusers.utils.peft_utils import unscale_lora_layers | |
from diffusers.utils.import_utils import is_torch_version | |
from diffusers.pipelines.stable_diffusion.pipeline_output import StableDiffusionPipelineOutput | |
from diffusers.utils import PIL_INTERPOLATION | |
EXAMPLE_DOC_STRING = "" | |
USE_PEFT_BACKEND = False | |
class CustomStableDiffusionControlNetPipeline(StableDiffusionControlNetPipeline): | |
def encode_prompt( | |
self, | |
prompt, | |
device, | |
num_images_per_prompt, | |
do_classifier_free_guidance, | |
negative_prompt=None, | |
prompt_embeds: Optional[torch.FloatTensor] = None, | |
negative_prompt_embeds: Optional[torch.FloatTensor] = None, | |
lora_scale: Optional[float] = None, | |
clip_skip: Optional[int] = None, | |
): | |
r""" | |
Encodes the prompt into text encoder hidden states. | |
Args: | |
prompt (`str` or `List[str]`, *optional*): | |
prompt to be encoded | |
device: (`torch.device`): | |
torch device | |
num_images_per_prompt (`int`): | |
number of images that should be generated per prompt | |
do_classifier_free_guidance (`bool`): | |
whether to use classifier free guidance or not | |
negative_prompt (`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`). | |
prompt_embeds (`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. | |
negative_prompt_embeds (`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. | |
lora_scale (`float`, *optional*): | |
A LoRA scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded. | |
clip_skip (`int`, *optional*): | |
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that | |
the output of the pre-final layer will be used for computing the prompt embeddings. | |
""" | |
# set lora scale so that monkey patched LoRA | |
# function of text encoder can correctly access it | |
if lora_scale is not None and isinstance(self, LoraLoaderMixin): | |
self._lora_scale = lora_scale | |
# dynamically adjust the LoRA scale | |
if not USE_PEFT_BACKEND: | |
adjust_lora_scale_text_encoder(self.text_encoder, lora_scale) | |
else: | |
scale_lora_layers(self.text_encoder, lora_scale) | |
if prompt is not None and isinstance(prompt, str): | |
batch_size = 1 | |
elif prompt is not None and isinstance(prompt, list): | |
batch_size = len(prompt) | |
else: | |
batch_size = prompt_embeds.shape[0] | |
if prompt_embeds is None: | |
# textual inversion: procecss multi-vector tokens if necessary | |
if isinstance(self, TextualInversionLoaderMixin): | |
prompt = self.maybe_convert_prompt(prompt, self.tokenizer) | |
text_inputs = self.tokenizer( | |
prompt, | |
padding="max_length", | |
max_length=self.tokenizer.model_max_length, | |
truncation=True, | |
return_tensors="pt", | |
) | |
text_input_ids = text_inputs.input_ids | |
untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids | |
if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal( | |
text_input_ids, untruncated_ids | |
): | |
removed_text = self.tokenizer.batch_decode( | |
untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] | |
) | |
logger.warning( | |
"The following part of your input was truncated because CLIP can only handle sequences up to" | |
f" {self.tokenizer.model_max_length} tokens: {removed_text}" | |
) | |
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: | |
attention_mask = text_inputs.attention_mask.to(device) | |
else: | |
attention_mask = None | |
if clip_skip is None: | |
prompt_embeds = self.text_encoder(text_input_ids.to(device), attention_mask=attention_mask) | |
prompt_embeds = prompt_embeds[0] | |
else: | |
prompt_embeds = self.text_encoder( | |
text_input_ids.to(device), attention_mask=attention_mask, output_hidden_states=True | |
) | |
# Access the `hidden_states` first, that contains a tuple of | |
# all the hidden states from the encoder layers. Then index into | |
# the tuple to access the hidden states from the desired layer. | |
prompt_embeds = prompt_embeds[-1][-(clip_skip + 1)] | |
# We also need to apply the final LayerNorm here to not mess with the | |
# representations. The `last_hidden_states` that we typically use for | |
# obtaining the final prompt representations passes through the LayerNorm | |
# layer. | |
prompt_embeds = self.text_encoder.text_model.final_layer_norm(prompt_embeds) | |
if self.text_encoder is not None: | |
prompt_embeds_dtype = self.text_encoder.dtype | |
elif self.unet is not None: | |
prompt_embeds_dtype = self.unet.dtype | |
else: | |
prompt_embeds_dtype = prompt_embeds.dtype | |
prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) | |
bs_embed, seq_len, _ = prompt_embeds.shape | |
# duplicate text embeddings for each generation per prompt, using mps friendly method | |
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1) | |
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1) | |
# get unconditional embeddings for classifier free guidance | |
if do_classifier_free_guidance and negative_prompt_embeds is None: | |
uncond_tokens: List[str] | |
if negative_prompt is None: | |
uncond_tokens = [""] * batch_size | |
elif prompt is not None and type(prompt) is not type(negative_prompt): | |
raise TypeError( | |
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !=" | |
f" {type(prompt)}." | |
) | |
elif isinstance(negative_prompt, str): | |
uncond_tokens = [negative_prompt] | |
elif batch_size != len(negative_prompt): | |
raise ValueError( | |
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:" | |
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches" | |
" the batch size of `prompt`." | |
) | |
else: | |
uncond_tokens = negative_prompt | |
# textual inversion: procecss multi-vector tokens if necessary | |
if isinstance(self, TextualInversionLoaderMixin): | |
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, self.tokenizer) | |
max_length = prompt_embeds.shape[1] | |
uncond_input = self.tokenizer( | |
uncond_tokens, | |
padding="max_length", | |
max_length=max_length, | |
truncation=True, | |
return_tensors="pt", | |
) | |
if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask: | |
attention_mask = uncond_input.attention_mask.to(device) | |
else: | |
attention_mask = None | |
negative_prompt_embeds = self.text_encoder( | |
uncond_input.input_ids.to(device), | |
attention_mask=attention_mask, | |
) | |
negative_prompt_embeds = negative_prompt_embeds[0] | |
if do_classifier_free_guidance: | |
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method | |
seq_len = negative_prompt_embeds.shape[1] | |
negative_prompt_embeds = negative_prompt_embeds.to(dtype=prompt_embeds_dtype, device=device) | |
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1) | |
negative_prompt_embeds = negative_prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1) | |
if isinstance(self, LoraLoaderMixin) and USE_PEFT_BACKEND: | |
# Retrieve the original scale by scaling back the LoRA layers | |
unscale_lora_layers(self.text_encoder, lora_scale) | |
# print(prompt_embeds.shape, negative_prompt_embeds.shape) | |
return prompt_embeds, negative_prompt_embeds | |
def prepare_latents_legacy( | |
self, | |
image, | |
timestep, | |
batch_size, | |
num_images_per_prompt, | |
dtype, | |
device, | |
generator, | |
): | |
image = image.to(device=self.device, dtype=dtype) | |
init_latent_dist = self.vae.encode(image).latent_dist | |
init_latents = init_latent_dist.sample(generator=generator) | |
init_latents = 0.18215 * init_latents | |
# Expand init_latents for batch_size and num_images_per_prompt | |
init_latents = torch.cat( | |
[init_latents] * batch_size * num_images_per_prompt, dim=0 | |
) | |
init_latents_orig = init_latents | |
# add noise to latents using the timesteps | |
noise = torch.randn( | |
init_latents.shape, generator=generator, device=self.device, dtype=dtype | |
) | |
print(init_latents.shape, noise.shape) | |
init_latents = self.scheduler.add_noise(init_latents, noise, timestep) | |
latents = init_latents | |
return latents, init_latents_orig, noise | |
def preprocess_mask(self, mask, scale_factor=8): | |
mask = mask.convert("L") | |
w, h = mask.size | |
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 | |
mask = mask.resize( | |
(w // scale_factor, h // scale_factor), resample=PIL_INTERPOLATION["nearest"] | |
) | |
# print("in preprocess mask 0", np.unique(mask)) | |
mask = np.array(mask).astype(np.float32) / 255.0 | |
mask = np.tile(mask, (4, 1, 1)) | |
# print("in preprocess mask 1", np.unique(mask)) | |
mask = mask[None].transpose(0, 1, 2, 3) | |
mask = 1 - mask # repaint white, keep black | |
# print("in preprocess mask 2", np.unique(mask)) | |
mask = torch.from_numpy(mask) | |
return mask | |
def preprocess_image(self, image): | |
w, h = image.size | |
w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32 | |
image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"]) | |
image = np.array(image).astype(np.float32) / 255.0 | |
image = image[None].transpose(0, 3, 1, 2) | |
image = torch.from_numpy(image) | |
return 2.0 * image - 1.0 | |
def get_timesteps(self, num_inference_steps, strength, device): | |
# get the original timestep using init_timestep | |
offset = self.scheduler.config.get("steps_offset", 0) | |
init_timestep = int(num_inference_steps * strength) + offset | |
init_timestep = min(init_timestep, num_inference_steps) | |
t_start = max(num_inference_steps - init_timestep + offset, 0) | |
timesteps = self.scheduler.timesteps[t_start:] | |
return timesteps, num_inference_steps - t_start | |
def collage( | |
self, | |
prompt: Union[str, List[str]], | |
image: Union[torch.FloatTensor, PIL.Image.Image], | |
mask_image: Union[torch.FloatTensor, PIL.Image.Image], | |
strength: float = 0.8, | |
num_inference_steps: Optional[int] = 50, | |
guidance_scale: Optional[float] = 7.5, | |
negative_prompt: Optional[Union[str, List[str]]] = None, | |
num_images_per_prompt: Optional[int] = 1, | |
eta: Optional[float] = 0.0, | |
generator: Optional[torch.Generator] = None, | |
output_type: Optional[str] = "pil", | |
return_dict: bool = True, | |
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, | |
callback_steps: Optional[int] = 1, | |
attention_mod: Optional[Callable] = None, | |
**kwargs, | |
): | |
r""" | |
Function invoked when calling the pipeline for generation. | |
Hello | |
Args: | |
prompt (`str` or `List[str]`): | |
The prompt or prompts to guide the image generation. | |
image (`torch.FloatTensor` or `PIL.Image.Image`): | |
`Image`, or tensor representing an image batch, that will be used as the starting point for the | |
process. This is the image whose masked region will be inpainted. | |
mask_image (`torch.FloatTensor` or `PIL.Image.Image`): | |
`Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be | |
replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a | |
PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should | |
contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`. | |
strength (`float`, *optional*, defaults to 0.8): | |
Conceptually, indicates how much to inpaint the masked area. Must be between 0 and 1. When `strength` | |
is 1, the denoising process will be run on the masked area for the full number of iterations specified | |
in `num_inference_steps`. `image` will be used as a reference for the masked area, adding more noise to | |
that region the larger the `strength`. If `strength` is 0, no inpainting will occur. | |
num_inference_steps (`int`, *optional*, defaults to 50): | |
The reference number of denoising steps. More denoising steps usually lead to a higher quality image at | |
the expense of slower inference. This parameter will be modulated by `strength`, as explained above. | |
guidance_scale (`float`, *optional*, defaults to 7.5): | |
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598). | |
`guidance_scale` is defined as `w` of equation 2. of [Imagen | |
Paper](https://arxiv.org/pdf/2205.11487.pdf). 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. | |
negative_prompt (`str` or `List[str]`, *optional*): | |
The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored | |
if `guidance_scale` is less than `1`). | |
num_images_per_prompt (`int`, *optional*, defaults to 1): | |
The number of images to generate per prompt. | |
eta (`float`, *optional*, defaults to 0.0): | |
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to | |
[`schedulers.DDIMScheduler`], will be ignored for others. | |
generator (`torch.Generator`, *optional*): | |
A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation | |
deterministic. | |
output_type (`str`, *optional*, defaults to `"pil"`): | |
The output format of the generate image. Choose between | |
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`. | |
return_dict (`bool`, *optional*, defaults to `True`): | |
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a | |
plain tuple. | |
callback (`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)`. | |
callback_steps (`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. | |
Returns: | |
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: | |
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple. | |
When returning a tuple, the first element is a list with the generated images, and the second element is a | |
list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work" | |
(nsfw) content, according to the `safety_checker`. | |
""" | |
# message = "Please use `image` instead of `init_image`." | |
# init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs) | |
# image = init_image or image | |
# 1. Check inputs | |
# self.check_inputs(prompt, strength, callback_steps) | |
# 2. Define call parameters | |
batch_size = 1 | |
device = self._execution_device | |
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) | |
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` | |
# corresponds to doing no classifier free guidance. | |
do_classifier_free_guidance = guidance_scale > 1.0 | |
# 3. Encode input prompt | |
text_embeddings = self._encode_prompt( | |
prompt, | |
device, | |
num_images_per_prompt, | |
do_classifier_free_guidance, | |
negative_prompt, | |
) | |
# 4. Preprocess image and mask | |
if not isinstance(image[0], torch.FloatTensor): | |
image = torch.cat([self.preprocess_image(image[i]) for i in range(len(image))], dim=0) | |
if not isinstance(mask_image, torch.FloatTensor): | |
mask_image = torch.cat([self.preprocess_mask(mask_image[i], self.vae_scale_factor) for i in range(len(mask_image))], dim=0) | |
# 5. set timesteps | |
self.scheduler.set_timesteps(num_inference_steps, device=device) | |
timesteps, num_inference_steps = self.get_timesteps( | |
num_inference_steps, strength, device | |
) | |
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt) | |
# 6. Prepare latent variables | |
# encode the init image into latents and scale the latents | |
latents, init_latents_orig, noise = self.prepare_latents_legacy( | |
image, | |
latent_timestep, | |
batch_size, | |
num_images_per_prompt, | |
text_embeddings.dtype, | |
device, | |
generator, | |
) | |
# 7. Prepare mask latent | |
mask = mask_image.to(device=self.device, dtype=latents.dtype) | |
mask = torch.cat([mask] * batch_size * num_images_per_prompt) | |
# 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline | |
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) | |
# 9. Denoising loop | |
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order | |
with self.progress_bar(total=num_inference_steps) as progress_bar: | |
for i, t in enumerate(timesteps): | |
# expand the latents if we are doing classifier free guidance | |
latent_model_input = ( | |
torch.cat([latents] * 2) if do_classifier_free_guidance else latents | |
) | |
latent_model_input = self.scheduler.scale_model_input( | |
latent_model_input, t | |
) | |
if attention_mod is not None: | |
sigma = self.scheduler.sigmas[i] | |
attention_mod(self.unet, sigma) | |
# predict the noise residual | |
noise_pred = self.unet( | |
latent_model_input, t, encoder_hidden_states=text_embeddings | |
).sample | |
# perform guidance | |
if do_classifier_free_guidance: | |
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) | |
noise_pred = noise_pred_uncond + guidance_scale * ( | |
noise_pred_text - noise_pred_uncond | |
) | |
# compute the previous noisy sample x_t -> x_t-1 | |
latents = self.scheduler.step( | |
noise_pred, t, latents, **extra_step_kwargs | |
).prev_sample | |
# masking | |
noise = torch.randn( | |
latents.shape, | |
generator=generator, | |
device=self.device, | |
dtype=text_embeddings.dtype, | |
) | |
init_latents_proper = self.scheduler.add_noise( | |
init_latents_orig, noise, torch.tensor([t]) | |
) | |
mask_t = (mask > (1 - t/1000)).type(mask.dtype) # So when t is high, most of the mask is 1 (fixed), but when t is low, most of the mask is 0 (variable) | |
dilate_size = (int)(4*t/1000) | |
mask_t_dilated = torch.nn.functional.max_pool2d(mask_t, dilate_size*2 + 1, stride=1, padding=dilate_size) | |
latents = (init_latents_proper * mask_t_dilated) + (latents * (1 - mask_t_dilated)) | |
# call the callback, if provided | |
if i == len(timesteps) - 1 or ( | |
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0 | |
): | |
progress_bar.update() | |
if callback is not None and i % callback_steps == 0: | |
callback(i, t, latents) | |
# 10. Post-processing | |
image = self.decode_latents(latents) | |
# 11. Run safety checker | |
image, has_nsfw_concept = self.run_safety_checker( | |
image, device, text_embeddings.dtype | |
) | |
# print(image.shape) | |
# 12. Convert to PIL | |
if output_type == "pil": | |
image = self.numpy_to_pil(image) | |
if not return_dict: | |
return (image, has_nsfw_concept) | |
return StableDiffusionPipelineOutput( | |
images=image, nsfw_content_detected=has_nsfw_concept | |
) | |
def __call__( | |
self, | |
prompt: Union[str, List[str]] = None, | |
image: PipelineImageInput = None, | |
height: Optional[int] = None, | |
width: Optional[int] = None, | |
num_inference_steps: int = 50, | |
guidance_scale: float = 7.5, | |
negative_prompt: Optional[Union[str, List[str]]] = None, | |
num_images_per_prompt: Optional[int] = 1, | |
eta: float = 0.0, | |
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, | |
latents: Optional[torch.FloatTensor] = None, | |
prompt_embeds: Optional[torch.FloatTensor] = None, | |
negative_prompt_embeds: Optional[torch.FloatTensor] = None, | |
output_type: Optional[str] = "pil", | |
return_dict: bool = True, | |
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, | |
callback_steps: int = 1, | |
cross_attention_kwargs: Optional[Dict[str, Any]] = None, | |
controlnet_conditioning_scale: Union[float, List[float]] = 1.0, | |
guess_mode: bool = False, | |
control_guidance_start: Union[float, List[float]] = 0.0, | |
control_guidance_end: Union[float, List[float]] = 1.0, | |
clip_skip: Optional[int] = None, | |
key_image = None, | |
key_scale = 0.5, | |
neg_mask = None, | |
neg_prompt = None, | |
): | |
r""" | |
The call function to the pipeline for generation. | |
Args: | |
prompt (`str` or `List[str]`, *optional*): | |
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`. | |
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,: | |
`List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`): | |
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is | |
specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be | |
accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height | |
and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in | |
`init`, images must be passed as a list such that each element of the list can be correctly batched for | |
input to a single ControlNet. | |
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): | |
The height in pixels of the generated image. | |
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`): | |
The width in pixels of the generated image. | |
num_inference_steps (`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. | |
guidance_scale (`float`, *optional*, defaults to 7.5): | |
A higher guidance scale value encourages the model to generate images closely linked to the text | |
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`. | |
negative_prompt (`str` or `List[str]`, *optional*): | |
The prompt or prompts to guide what to not include in image generation. If not defined, you need to | |
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`). | |
num_images_per_prompt (`int`, *optional*, defaults to 1): | |
The number of images to generate per prompt. | |
eta (`float`, *optional*, defaults to 0.0): | |
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies | |
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers. | |
generator (`torch.Generator` or `List[torch.Generator]`, *optional*): | |
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make | |
generation deterministic. | |
latents (`torch.FloatTensor`, *optional*): | |
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image | |
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents | |
tensor is generated by sampling using the supplied random `generator`. | |
prompt_embeds (`torch.FloatTensor`, *optional*): | |
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not | |
provided, text embeddings are generated from the `prompt` input argument. | |
negative_prompt_embeds (`torch.FloatTensor`, *optional*): | |
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If | |
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument. | |
output_type (`str`, *optional*, defaults to `"pil"`): | |
The output format of the generated image. Choose between `PIL.Image` or `np.array`. | |
return_dict (`bool`, *optional*, defaults to `True`): | |
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a | |
plain tuple. | |
callback (`Callable`, *optional*): | |
A function that calls every `callback_steps` steps during inference. The function is called with the | |
following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`. | |
callback_steps (`int`, *optional*, defaults to 1): | |
The frequency at which the `callback` function is called. If not specified, the callback is called at | |
every step. | |
cross_attention_kwargs (`dict`, *optional*): | |
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in | |
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py). | |
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0): | |
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added | |
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set | |
the corresponding scale as a list. | |
guess_mode (`bool`, *optional*, defaults to `False`): | |
The ControlNet encoder tries to recognize the content of the input image even if you remove all | |
prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended. | |
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0): | |
The percentage of total steps at which the ControlNet starts applying. | |
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0): | |
The percentage of total steps at which the ControlNet stops applying. | |
clip_skip (`int`, *optional*): | |
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that | |
the output of the pre-final layer will be used for computing the prompt embeddings. | |
Examples: | |
Returns: | |
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`: | |
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned, | |
otherwise a `tuple` is returned where the first element is a list with the generated images and the | |
second element is a list of `bool`s indicating whether the corresponding generated image contains | |
"not-safe-for-work" (nsfw) content. | |
""" | |
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet | |
# align format for control guidance | |
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list): | |
control_guidance_start = len(control_guidance_end) * [control_guidance_start] | |
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list): | |
control_guidance_end = len(control_guidance_start) * [control_guidance_end] | |
elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list): | |
mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1 | |
control_guidance_start, control_guidance_end = mult * [control_guidance_start], mult * [ | |
control_guidance_end | |
] | |
# 1. Check inputs. Raise error if not correct | |
self.check_inputs( | |
prompt, | |
image, | |
callback_steps, | |
negative_prompt, | |
prompt_embeds, | |
negative_prompt_embeds, | |
controlnet_conditioning_scale, | |
control_guidance_start, | |
control_guidance_end, | |
) | |
# 2. Define call parameters | |
if prompt is not None and isinstance(prompt, str): | |
batch_size = 1 | |
elif prompt is not None and isinstance(prompt, list): | |
batch_size = len(prompt) | |
else: | |
batch_size = prompt_embeds.shape[0] | |
device = self._execution_device | |
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) | |
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` | |
# corresponds to doing no classifier free guidance. | |
do_classifier_free_guidance = guidance_scale > 1.0 | |
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float): | |
controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets) | |
global_pool_conditions = ( | |
controlnet.config.global_pool_conditions | |
if isinstance(controlnet, ControlNetModel) | |
else controlnet.nets[0].config.global_pool_conditions | |
) | |
guess_mode = guess_mode or global_pool_conditions | |
# 3. Encode input prompt | |
text_encoder_lora_scale = ( | |
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None | |
) | |
prompt_embeds, negative_prompt_embeds = self.encode_prompt( | |
prompt, | |
device, | |
num_images_per_prompt, | |
do_classifier_free_guidance, | |
negative_prompt, | |
lora_scale=text_encoder_lora_scale, | |
clip_skip=clip_skip, | |
) | |
# For classifier free guidance, we need to do two forward passes. | |
# Here we concatenate the unconditional and text embeddings into a single batch | |
# to avoid doing two forward passes | |
if do_classifier_free_guidance: | |
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds]) | |
if neg_mask is not None: | |
empty_prompt_embeds = torch.cat([empty_negative_prompt_embeds, empty_prompt_embeds]) | |
# 4. Prepare image | |
if isinstance(controlnet, ControlNetModel): | |
# breakpoint() | |
image = self.prepare_image( | |
image=image, | |
width=width, | |
height=height, | |
batch_size=batch_size * num_images_per_prompt, | |
num_images_per_prompt=num_images_per_prompt, | |
device=device, | |
dtype=controlnet.dtype, | |
do_classifier_free_guidance=do_classifier_free_guidance, | |
guess_mode=guess_mode, | |
) | |
height, width = image.shape[-2:] | |
if key_image is not None: | |
key_image = self.prepare_image( | |
image=key_image, | |
width=width, | |
height=height, | |
batch_size=batch_size * num_images_per_prompt, | |
num_images_per_prompt=num_images_per_prompt, | |
device=device, | |
dtype=controlnet.dtype, | |
do_classifier_free_guidance=do_classifier_free_guidance, | |
guess_mode=guess_mode, | |
) | |
elif isinstance(controlnet, MultiControlNetModel): | |
images = [] | |
key_images = [] | |
for image_ in image: | |
image_ = self.prepare_image( | |
image=image_, | |
width=width, | |
height=height, | |
batch_size=batch_size * num_images_per_prompt, | |
num_images_per_prompt=num_images_per_prompt, | |
device=device, | |
dtype=controlnet.dtype, | |
do_classifier_free_guidance=do_classifier_free_guidance, | |
guess_mode=guess_mode, | |
) | |
images.append(image_) | |
image = images | |
height, width = image[0].shape[-2:] | |
else: | |
assert False | |
# 5. Prepare timesteps | |
self.scheduler.set_timesteps(num_inference_steps, device=device) | |
timesteps = self.scheduler.timesteps | |
# 6. Prepare latent variables | |
num_channels_latents = self.unet.config.in_channels | |
latents = self.prepare_latents( | |
batch_size * num_images_per_prompt, | |
num_channels_latents, | |
height, | |
width, | |
prompt_embeds.dtype, | |
device, | |
generator, | |
latents, | |
) | |
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline | |
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta) | |
# 7.1 Create tensor stating which controlnets to keep | |
controlnet_keep = [] | |
for i in range(len(timesteps)): | |
keeps = [ | |
1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e) | |
for s, e in zip(control_guidance_start, control_guidance_end) | |
] | |
controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps) | |
# 8. Denoising loop | |
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order | |
is_unet_compiled = is_compiled_module(self.unet) | |
is_controlnet_compiled = is_compiled_module(self.controlnet) | |
is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1") | |
with self.progress_bar(total=num_inference_steps) as progress_bar: | |
for i, t in enumerate(timesteps): | |
# Relevant thread: | |
# https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428 | |
if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1: | |
torch._inductor.cudagraph_mark_step_begin() | |
# expand the latents if we are doing classifier free guidance | |
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents | |
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) | |
# controlnet(s) inference | |
if guess_mode and do_classifier_free_guidance: | |
# Infer ControlNet only for the conditional batch. | |
control_model_input = latents | |
control_model_input = self.scheduler.scale_model_input(control_model_input, t) | |
controlnet_prompt_embeds = prompt_embeds.chunk(2)[1] | |
else: | |
control_model_input = latent_model_input | |
controlnet_prompt_embeds = prompt_embeds | |
if isinstance(controlnet_keep[i], list): | |
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])] | |
else: | |
controlnet_cond_scale = controlnet_conditioning_scale | |
if isinstance(controlnet_cond_scale, list): | |
controlnet_cond_scale = controlnet_cond_scale[0] | |
cond_scale = controlnet_cond_scale * controlnet_keep[i] | |
down_block_res_samples, mid_block_res_sample = self.controlnet( | |
control_model_input, | |
t, | |
encoder_hidden_states=controlnet_prompt_embeds, | |
controlnet_cond=image, | |
conditioning_scale=cond_scale, | |
guess_mode=guess_mode, | |
return_dict=False, | |
) | |
if guess_mode and do_classifier_free_guidance: | |
# Infered ControlNet only for the conditional batch. | |
# To apply the output of ControlNet to both the unconditional and conditional batches, | |
# add 0 to the unconditional batch to keep it unchanged. | |
down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples] | |
mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample]) | |
# predict the noise residual | |
noise_pred = self.unet( | |
latent_model_input, | |
t, | |
encoder_hidden_states=prompt_embeds, | |
cross_attention_kwargs=cross_attention_kwargs, | |
down_block_additional_residuals=down_block_res_samples, | |
mid_block_additional_residual=mid_block_res_sample, | |
return_dict=False, | |
)[0] | |
# perform guidance | |
if do_classifier_free_guidance: | |
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) | |
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) | |
# compute the previous noisy sample x_t -> x_t-1 | |
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0] | |
# call the callback, if provided | |
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0): | |
progress_bar.update() | |
if callback is not None and i % callback_steps == 0: | |
step_idx = i // getattr(self.scheduler, "order", 1) | |
callback(step_idx, t, latents) | |
# If we do sequential model offloading, let's offload unet and controlnet | |
# manually for max memory savings | |
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None: | |
self.unet.to("cpu") | |
self.controlnet.to("cpu") | |
torch.cuda.empty_cache() | |
if not output_type == "latent": | |
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0] | |
image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype) | |
else: | |
image = latents | |
has_nsfw_concept = None | |
if has_nsfw_concept is None: | |
do_denormalize = [True] * image.shape[0] | |
else: | |
do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept] | |
image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize) | |
# Offload all models | |
self.maybe_free_model_hooks() | |
if not return_dict: | |
return (image, has_nsfw_concept) | |
return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept) |