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
+
# Copyright 2024 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
import inspect
|
| 17 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import PIL.Image
|
| 21 |
+
import torch
|
| 22 |
+
import torch.nn.functional as F
|
| 23 |
+
from transformers import (
|
| 24 |
+
CLIPImageProcessor,
|
| 25 |
+
CLIPTextModel,
|
| 26 |
+
CLIPTextModelWithProjection,
|
| 27 |
+
CLIPTokenizer,
|
| 28 |
+
CLIPVisionModelWithProjection,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
from diffusers.utils.import_utils import is_invisible_watermark_available
|
| 32 |
+
|
| 33 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 34 |
+
from diffusers.image_processor import PipelineImageInput, VaeImageProcessor
|
| 35 |
+
from diffusers.loaders import (
|
| 36 |
+
FromSingleFileMixin,
|
| 37 |
+
IPAdapterMixin,
|
| 38 |
+
StableDiffusionXLLoraLoaderMixin,
|
| 39 |
+
TextualInversionLoaderMixin,
|
| 40 |
+
)
|
| 41 |
+
from diffusers.models import AutoencoderKL, ImageProjection, UNet2DConditionModel
|
| 42 |
+
from diffusers.models.attention_processor import (
|
| 43 |
+
AttnProcessor2_0,
|
| 44 |
+
XFormersAttnProcessor,
|
| 45 |
+
)
|
| 46 |
+
from diffusers.models.lora import adjust_lora_scale_text_encoder
|
| 47 |
+
from diffusers.schedulers import KarrasDiffusionSchedulers
|
| 48 |
+
from diffusers.utils import (
|
| 49 |
+
USE_PEFT_BACKEND,
|
| 50 |
+
deprecate,
|
| 51 |
+
logging,
|
| 52 |
+
replace_example_docstring,
|
| 53 |
+
scale_lora_layers,
|
| 54 |
+
unscale_lora_layers,
|
| 55 |
+
)
|
| 56 |
+
from diffusers.utils.torch_utils import is_compiled_module, randn_tensor
|
| 57 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline, StableDiffusionMixin
|
| 58 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
|
| 59 |
+
from diffusers.pipelines.controlnet import MultiControlNetModel
|
| 60 |
+
|
| 61 |
+
from ..models.controlnet import ControlNetModel
|
| 62 |
+
from kolors.models.ipa_faceid_plus.ipa_faceid_plus import ProjPlusModel
|
| 63 |
+
from kolors.models.ipa_faceid_plus.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
|
| 64 |
+
|
| 65 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.retrieve_latents
|
| 70 |
+
def retrieve_latents(
|
| 71 |
+
encoder_output: torch.Tensor, generator: Optional[torch.Generator] = None, sample_mode: str = "sample"
|
| 72 |
+
):
|
| 73 |
+
if hasattr(encoder_output, "latent_dist") and sample_mode == "sample":
|
| 74 |
+
return encoder_output.latent_dist.sample(generator)
|
| 75 |
+
elif hasattr(encoder_output, "latent_dist") and sample_mode == "argmax":
|
| 76 |
+
return encoder_output.latent_dist.mode()
|
| 77 |
+
elif hasattr(encoder_output, "latents"):
|
| 78 |
+
return encoder_output.latents
|
| 79 |
+
else:
|
| 80 |
+
raise AttributeError("Could not access latents of provided encoder_output")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class StableDiffusionXLControlNetImg2ImgPipeline(
|
| 84 |
+
DiffusionPipeline,
|
| 85 |
+
StableDiffusionMixin,
|
| 86 |
+
TextualInversionLoaderMixin,
|
| 87 |
+
StableDiffusionXLLoraLoaderMixin,
|
| 88 |
+
FromSingleFileMixin,
|
| 89 |
+
IPAdapterMixin,
|
| 90 |
+
):
|
| 91 |
+
r"""
|
| 92 |
+
Pipeline for image-to-image generation using Stable Diffusion XL with ControlNet guidance.
|
| 93 |
+
|
| 94 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
|
| 95 |
+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
|
| 96 |
+
|
| 97 |
+
The pipeline also inherits the following loading methods:
|
| 98 |
+
- [`~loaders.TextualInversionLoaderMixin.load_textual_inversion`] for loading textual inversion embeddings
|
| 99 |
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.load_lora_weights`] for loading LoRA weights
|
| 100 |
+
- [`~loaders.StableDiffusionXLLoraLoaderMixin.save_lora_weights`] for saving LoRA weights
|
| 101 |
+
- [`~loaders.IPAdapterMixin.load_ip_adapter`] for loading IP Adapters
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
vae ([`AutoencoderKL`]):
|
| 105 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
| 106 |
+
text_encoder ([`CLIPTextModel`]):
|
| 107 |
+
Frozen text-encoder. Stable Diffusion uses the text portion of
|
| 108 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
| 109 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
| 110 |
+
tokenizer (`CLIPTokenizer`):
|
| 111 |
+
Tokenizer of class
|
| 112 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
|
| 113 |
+
unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
|
| 114 |
+
controlnet ([`ControlNetModel`] or `List[ControlNetModel]`):
|
| 115 |
+
Provides additional conditioning to the unet during the denoising process. If you set multiple ControlNets
|
| 116 |
+
as a list, the outputs from each ControlNet are added together to create one combined additional
|
| 117 |
+
conditioning.
|
| 118 |
+
scheduler ([`SchedulerMixin`]):
|
| 119 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
|
| 120 |
+
[`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
|
| 121 |
+
requires_aesthetics_score (`bool`, *optional*, defaults to `"False"`):
|
| 122 |
+
Whether the `unet` requires an `aesthetic_score` condition to be passed during inference. Also see the
|
| 123 |
+
config of `stabilityai/stable-diffusion-xl-refiner-1-0`.
|
| 124 |
+
force_zeros_for_empty_prompt (`bool`, *optional*, defaults to `"True"`):
|
| 125 |
+
Whether the negative prompt embeddings shall be forced to always be set to 0. Also see the config of
|
| 126 |
+
`stabilityai/stable-diffusion-xl-base-1-0`.
|
| 127 |
+
add_watermarker (`bool`, *optional*):
|
| 128 |
+
Whether to use the [invisible_watermark library](https://github.com/ShieldMnt/invisible-watermark/) to
|
| 129 |
+
watermark output images. If not defined, it will default to True if the package is installed, otherwise no
|
| 130 |
+
watermarker will be used.
|
| 131 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 132 |
+
A `CLIPImageProcessor` to extract features from generated images; used as inputs to the `safety_checker`.
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
model_cpu_offload_seq = "text_encoder->image_encoder->unet->vae"
|
| 136 |
+
_optional_components = [
|
| 137 |
+
"tokenizer",
|
| 138 |
+
"text_encoder",
|
| 139 |
+
"feature_extractor",
|
| 140 |
+
"image_encoder",
|
| 141 |
+
]
|
| 142 |
+
_callback_tensor_inputs = [
|
| 143 |
+
"latents",
|
| 144 |
+
"prompt_embeds",
|
| 145 |
+
"negative_prompt_embeds",
|
| 146 |
+
"add_text_embeds",
|
| 147 |
+
"add_time_ids",
|
| 148 |
+
"negative_pooled_prompt_embeds",
|
| 149 |
+
"add_neg_time_ids",
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
def __init__(
|
| 153 |
+
self,
|
| 154 |
+
vae: AutoencoderKL,
|
| 155 |
+
text_encoder: CLIPTextModel,
|
| 156 |
+
tokenizer: CLIPTokenizer,
|
| 157 |
+
unet: UNet2DConditionModel,
|
| 158 |
+
controlnet: Union[ControlNetModel, List[ControlNetModel], Tuple[ControlNetModel], MultiControlNetModel],
|
| 159 |
+
scheduler: KarrasDiffusionSchedulers,
|
| 160 |
+
requires_aesthetics_score: bool = False,
|
| 161 |
+
force_zeros_for_empty_prompt: bool = True,
|
| 162 |
+
feature_extractor: CLIPImageProcessor = None,
|
| 163 |
+
image_encoder: CLIPVisionModelWithProjection = None,
|
| 164 |
+
face_clip_encoder: CLIPVisionModelWithProjection = None,
|
| 165 |
+
face_clip_processor: CLIPImageProcessor = None,
|
| 166 |
+
):
|
| 167 |
+
super().__init__()
|
| 168 |
+
|
| 169 |
+
if face_clip_encoder is not None:
|
| 170 |
+
self.image_proj_model = self.init_ip_adapter_proj_layer(
|
| 171 |
+
clip_embeddings_dim = face_clip_encoder.config.hidden_size,
|
| 172 |
+
num_tokens = 6
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
if isinstance(controlnet, (list, tuple)):
|
| 176 |
+
controlnet = MultiControlNetModel(controlnet)
|
| 177 |
+
|
| 178 |
+
self.register_modules(
|
| 179 |
+
vae=vae,
|
| 180 |
+
text_encoder=text_encoder,
|
| 181 |
+
tokenizer=tokenizer,
|
| 182 |
+
unet=unet,
|
| 183 |
+
controlnet=controlnet,
|
| 184 |
+
scheduler=scheduler,
|
| 185 |
+
feature_extractor=feature_extractor,
|
| 186 |
+
image_encoder=image_encoder,
|
| 187 |
+
face_clip_encoder=face_clip_encoder,
|
| 188 |
+
face_clip_processor=face_clip_processor,
|
| 189 |
+
)
|
| 190 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 191 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True)
|
| 192 |
+
self.control_image_processor = VaeImageProcessor(
|
| 193 |
+
vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True, do_normalize=False
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
self.watermark = None
|
| 197 |
+
|
| 198 |
+
self.register_to_config(force_zeros_for_empty_prompt=force_zeros_for_empty_prompt)
|
| 199 |
+
self.register_to_config(requires_aesthetics_score=requires_aesthetics_score)
|
| 200 |
+
|
| 201 |
+
#### set ip adapter module
|
| 202 |
+
def set_ip_adapter(self, device, num_tokens = 6):
|
| 203 |
+
unet = self.unet
|
| 204 |
+
attn_procs = {}
|
| 205 |
+
for name in unet.attn_processors.keys():
|
| 206 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 207 |
+
if name.startswith("mid_block"):
|
| 208 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 209 |
+
elif name.startswith("up_blocks"):
|
| 210 |
+
block_id = int(name[len("up_blocks.")])
|
| 211 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 212 |
+
elif name.startswith("down_blocks"):
|
| 213 |
+
block_id = int(name[len("down_blocks.")])
|
| 214 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 215 |
+
if cross_attention_dim is None:
|
| 216 |
+
attn_procs[name] = AttnProcessor()
|
| 217 |
+
else:
|
| 218 |
+
attn_procs[name] = IPAttnProcessor(
|
| 219 |
+
hidden_size = hidden_size,
|
| 220 |
+
cross_attention_dim = cross_attention_dim,
|
| 221 |
+
scale = 1.0,
|
| 222 |
+
num_tokens = num_tokens
|
| 223 |
+
).to(device, dtype = unet.dtype)
|
| 224 |
+
unet.set_attn_processor(attn_procs)
|
| 225 |
+
|
| 226 |
+
def init_ip_adapter_proj_layer(self, clip_embeddings_dim, num_tokens):
|
| 227 |
+
image_proj_model = ProjPlusModel(
|
| 228 |
+
cross_attention_dim = 4096,
|
| 229 |
+
id_embeddings_dim = 512,
|
| 230 |
+
clip_embeddings_dim = clip_embeddings_dim,
|
| 231 |
+
num_tokens = num_tokens
|
| 232 |
+
)
|
| 233 |
+
return image_proj_model
|
| 234 |
+
|
| 235 |
+
#### load ip adapter model weight
|
| 236 |
+
def load_ip_adapter_faceid_plus(self, ip_faceid_model_path, device):
|
| 237 |
+
params = torch.load(ip_faceid_model_path, 'cpu')
|
| 238 |
+
self.image_proj_model.load_state_dict(params["image_proj"])
|
| 239 |
+
self.image_proj_model.to(device, dtype = self.unet.dtype)
|
| 240 |
+
|
| 241 |
+
self.set_ip_adapter(num_tokens = 6, device = device)
|
| 242 |
+
ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
|
| 243 |
+
ip_layers.load_state_dict(params["adapter_modules"])
|
| 244 |
+
|
| 245 |
+
def set_face_fidelity_scale(self, scale):
|
| 246 |
+
for attn_processor in self.unet.attn_processors.values():
|
| 247 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
| 248 |
+
attn_processor.scale = scale
|
| 249 |
+
|
| 250 |
+
#### get image embeddings ####
|
| 251 |
+
def get_clip_feat(self, face_crop_image, device):
|
| 252 |
+
face_clip_images = self.face_clip_processor(images = face_crop_image, return_tensors = "pt").pixel_values
|
| 253 |
+
face_clip_images = face_clip_images.to(device, dtype = torch.float16)
|
| 254 |
+
|
| 255 |
+
with torch.no_grad():
|
| 256 |
+
face_clip_embeddings = self.face_clip_encoder(
|
| 257 |
+
face_clip_images,
|
| 258 |
+
output_hidden_states = True
|
| 259 |
+
).hidden_states[-2]
|
| 260 |
+
return face_clip_embeddings
|
| 261 |
+
def get_fused_face_embedds(self, face_insightface_embeds, face_crop_image, num_images_per_prompt, device):
|
| 262 |
+
with torch.inference_mode():
|
| 263 |
+
face_clip_embeds = self.get_clip_feat(face_crop_image, device)
|
| 264 |
+
face_clip_embeds = face_clip_embeds.to(device = device, dtype =face_insightface_embeds.dtype)
|
| 265 |
+
|
| 266 |
+
image_prompt_embeds = self.image_proj_model(face_insightface_embeds, face_clip_embeds)
|
| 267 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(face_insightface_embeds), torch.zeros_like(face_clip_embeds))
|
| 268 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
| 269 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 270 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 271 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 272 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 273 |
+
|
| 274 |
+
return (image_prompt_embeds, uncond_image_prompt_embeds)
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def encode_prompt(
|
| 278 |
+
self,
|
| 279 |
+
prompt,
|
| 280 |
+
device: Optional[torch.device] = None,
|
| 281 |
+
num_images_per_prompt: int = 1,
|
| 282 |
+
do_classifier_free_guidance: bool = True,
|
| 283 |
+
negative_prompt=None,
|
| 284 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 285 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 286 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 287 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 288 |
+
lora_scale: Optional[float] = None,
|
| 289 |
+
):
|
| 290 |
+
r"""
|
| 291 |
+
Encodes the prompt into text encoder hidden states.
|
| 292 |
+
|
| 293 |
+
Args:
|
| 294 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 295 |
+
prompt to be encoded
|
| 296 |
+
device: (`torch.device`):
|
| 297 |
+
torch device
|
| 298 |
+
num_images_per_prompt (`int`):
|
| 299 |
+
number of images that should be generated per prompt
|
| 300 |
+
do_classifier_free_guidance (`bool`):
|
| 301 |
+
whether to use classifier free guidance or not
|
| 302 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 303 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 304 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 305 |
+
less than `1`).
|
| 306 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 307 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 308 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 309 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 310 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 311 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 312 |
+
argument.
|
| 313 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 314 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 315 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 316 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 317 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 318 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 319 |
+
input argument.
|
| 320 |
+
lora_scale (`float`, *optional*):
|
| 321 |
+
A lora scale that will be applied to all LoRA layers of the text encoder if LoRA layers are loaded.
|
| 322 |
+
"""
|
| 323 |
+
# from IPython import embed; embed(); exit()
|
| 324 |
+
device = device or self._execution_device
|
| 325 |
+
|
| 326 |
+
# set lora scale so that monkey patched LoRA
|
| 327 |
+
# function of text encoder can correctly access it
|
| 328 |
+
if lora_scale is not None and isinstance(self, LoraLoaderMixin):
|
| 329 |
+
self._lora_scale = lora_scale
|
| 330 |
+
|
| 331 |
+
if prompt is not None and isinstance(prompt, str):
|
| 332 |
+
batch_size = 1
|
| 333 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 334 |
+
batch_size = len(prompt)
|
| 335 |
+
else:
|
| 336 |
+
batch_size = prompt_embeds.shape[0]
|
| 337 |
+
|
| 338 |
+
# Define tokenizers and text encoders
|
| 339 |
+
tokenizers = [self.tokenizer]
|
| 340 |
+
text_encoders = [self.text_encoder]
|
| 341 |
+
|
| 342 |
+
if prompt_embeds is None:
|
| 343 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 344 |
+
prompt_embeds_list = []
|
| 345 |
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
| 346 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 347 |
+
prompt = self.maybe_convert_prompt(prompt, tokenizer)
|
| 348 |
+
|
| 349 |
+
text_inputs = tokenizer(
|
| 350 |
+
prompt,
|
| 351 |
+
padding="max_length",
|
| 352 |
+
max_length=256,
|
| 353 |
+
truncation=True,
|
| 354 |
+
return_tensors="pt",
|
| 355 |
+
).to('cuda')
|
| 356 |
+
output = text_encoder(
|
| 357 |
+
input_ids=text_inputs['input_ids'] ,
|
| 358 |
+
attention_mask=text_inputs['attention_mask'],
|
| 359 |
+
position_ids=text_inputs['position_ids'],
|
| 360 |
+
output_hidden_states=True)
|
| 361 |
+
prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
| 362 |
+
pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone() # [batch_size, 4096]
|
| 363 |
+
bs_embed, seq_len, _ = prompt_embeds.shape
|
| 364 |
+
prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 365 |
+
prompt_embeds = prompt_embeds.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 366 |
+
|
| 367 |
+
prompt_embeds_list.append(prompt_embeds)
|
| 368 |
+
|
| 369 |
+
# prompt_embeds = torch.concat(prompt_embeds_list, dim=-1)
|
| 370 |
+
prompt_embeds = prompt_embeds_list[0]
|
| 371 |
+
|
| 372 |
+
# get unconditional embeddings for classifier free guidance
|
| 373 |
+
zero_out_negative_prompt = negative_prompt is None and self.config.force_zeros_for_empty_prompt
|
| 374 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None and zero_out_negative_prompt:
|
| 375 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 376 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
| 377 |
+
elif do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 378 |
+
# negative_prompt = negative_prompt or ""
|
| 379 |
+
uncond_tokens: List[str]
|
| 380 |
+
if negative_prompt is None:
|
| 381 |
+
uncond_tokens = [""] * batch_size
|
| 382 |
+
elif prompt is not None and type(prompt) is not type(negative_prompt):
|
| 383 |
+
raise TypeError(
|
| 384 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 385 |
+
f" {type(prompt)}."
|
| 386 |
+
)
|
| 387 |
+
elif isinstance(negative_prompt, str):
|
| 388 |
+
uncond_tokens = [negative_prompt]
|
| 389 |
+
elif batch_size != len(negative_prompt):
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 392 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 393 |
+
" the batch size of `prompt`."
|
| 394 |
+
)
|
| 395 |
+
else:
|
| 396 |
+
uncond_tokens = negative_prompt
|
| 397 |
+
|
| 398 |
+
negative_prompt_embeds_list = []
|
| 399 |
+
for tokenizer, text_encoder in zip(tokenizers, text_encoders):
|
| 400 |
+
# textual inversion: procecss multi-vector tokens if necessary
|
| 401 |
+
if isinstance(self, TextualInversionLoaderMixin):
|
| 402 |
+
uncond_tokens = self.maybe_convert_prompt(uncond_tokens, tokenizer)
|
| 403 |
+
|
| 404 |
+
max_length = prompt_embeds.shape[1]
|
| 405 |
+
uncond_input = tokenizer(
|
| 406 |
+
uncond_tokens,
|
| 407 |
+
padding="max_length",
|
| 408 |
+
max_length=max_length,
|
| 409 |
+
truncation=True,
|
| 410 |
+
return_tensors="pt",
|
| 411 |
+
).to('cuda')
|
| 412 |
+
output = text_encoder(
|
| 413 |
+
input_ids=uncond_input['input_ids'] ,
|
| 414 |
+
attention_mask=uncond_input['attention_mask'],
|
| 415 |
+
position_ids=uncond_input['position_ids'],
|
| 416 |
+
output_hidden_states=True)
|
| 417 |
+
negative_prompt_embeds = output.hidden_states[-2].permute(1, 0, 2).clone()
|
| 418 |
+
negative_pooled_prompt_embeds = output.hidden_states[-1][-1, :, :].clone() # [batch_size, 4096]
|
| 419 |
+
|
| 420 |
+
if do_classifier_free_guidance:
|
| 421 |
+
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
|
| 422 |
+
seq_len = negative_prompt_embeds.shape[1]
|
| 423 |
+
|
| 424 |
+
negative_prompt_embeds = negative_prompt_embeds.to(dtype=text_encoder.dtype, device=device)
|
| 425 |
+
|
| 426 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat(1, num_images_per_prompt, 1)
|
| 427 |
+
negative_prompt_embeds = negative_prompt_embeds.view(
|
| 428 |
+
batch_size * num_images_per_prompt, seq_len, -1
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 432 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 433 |
+
# to avoid doing two forward passes
|
| 434 |
+
|
| 435 |
+
negative_prompt_embeds_list.append(negative_prompt_embeds)
|
| 436 |
+
|
| 437 |
+
# negative_prompt_embeds = torch.concat(negative_prompt_embeds_list, dim=-1)
|
| 438 |
+
negative_prompt_embeds = negative_prompt_embeds_list[0]
|
| 439 |
+
|
| 440 |
+
bs_embed = pooled_prompt_embeds.shape[0]
|
| 441 |
+
pooled_prompt_embeds = pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 442 |
+
bs_embed * num_images_per_prompt, -1
|
| 443 |
+
)
|
| 444 |
+
if do_classifier_free_guidance:
|
| 445 |
+
negative_pooled_prompt_embeds = negative_pooled_prompt_embeds.repeat(1, num_images_per_prompt).view(
|
| 446 |
+
bs_embed * num_images_per_prompt, -1
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.encode_image
|
| 453 |
+
def encode_image(self, image, device, num_images_per_prompt, output_hidden_states=None):
|
| 454 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 455 |
+
|
| 456 |
+
if not isinstance(image, torch.Tensor):
|
| 457 |
+
image = self.feature_extractor(image, return_tensors="pt").pixel_values
|
| 458 |
+
|
| 459 |
+
image = image.to(device=device, dtype=dtype)
|
| 460 |
+
if output_hidden_states:
|
| 461 |
+
image_enc_hidden_states = self.image_encoder(image, output_hidden_states=True).hidden_states[-2]
|
| 462 |
+
image_enc_hidden_states = image_enc_hidden_states.repeat_interleave(num_images_per_prompt, dim=0)
|
| 463 |
+
uncond_image_enc_hidden_states = self.image_encoder(
|
| 464 |
+
torch.zeros_like(image), output_hidden_states=True
|
| 465 |
+
).hidden_states[-2]
|
| 466 |
+
uncond_image_enc_hidden_states = uncond_image_enc_hidden_states.repeat_interleave(
|
| 467 |
+
num_images_per_prompt, dim=0
|
| 468 |
+
)
|
| 469 |
+
return image_enc_hidden_states, uncond_image_enc_hidden_states
|
| 470 |
+
else:
|
| 471 |
+
image_embeds = self.image_encoder(image).image_embeds
|
| 472 |
+
image_embeds = image_embeds.repeat_interleave(num_images_per_prompt, dim=0)
|
| 473 |
+
uncond_image_embeds = torch.zeros_like(image_embeds)
|
| 474 |
+
|
| 475 |
+
return image_embeds, uncond_image_embeds
|
| 476 |
+
|
| 477 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_ip_adapter_image_embeds
|
| 478 |
+
def prepare_ip_adapter_image_embeds(
|
| 479 |
+
self, ip_adapter_image, ip_adapter_image_embeds, device, num_images_per_prompt, do_classifier_free_guidance
|
| 480 |
+
):
|
| 481 |
+
image_embeds = []
|
| 482 |
+
if do_classifier_free_guidance:
|
| 483 |
+
negative_image_embeds = []
|
| 484 |
+
if ip_adapter_image_embeds is None:
|
| 485 |
+
if not isinstance(ip_adapter_image, list):
|
| 486 |
+
ip_adapter_image = [ip_adapter_image]
|
| 487 |
+
|
| 488 |
+
if len(ip_adapter_image) != len(self.unet.encoder_hid_proj.image_projection_layers):
|
| 489 |
+
raise ValueError(
|
| 490 |
+
f"`ip_adapter_image` must have same length as the number of IP Adapters. Got {len(ip_adapter_image)} images and {len(self.unet.encoder_hid_proj.image_projection_layers)} IP Adapters."
|
| 491 |
+
)
|
| 492 |
+
|
| 493 |
+
for single_ip_adapter_image, image_proj_layer in zip(
|
| 494 |
+
ip_adapter_image, self.unet.encoder_hid_proj.image_projection_layers
|
| 495 |
+
):
|
| 496 |
+
output_hidden_state = not isinstance(image_proj_layer, ImageProjection)
|
| 497 |
+
single_image_embeds, single_negative_image_embeds = self.encode_image(
|
| 498 |
+
single_ip_adapter_image, device, 1, output_hidden_state
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
image_embeds.append(single_image_embeds[None, :])
|
| 502 |
+
if do_classifier_free_guidance:
|
| 503 |
+
negative_image_embeds.append(single_negative_image_embeds[None, :])
|
| 504 |
+
else:
|
| 505 |
+
for single_image_embeds in ip_adapter_image_embeds:
|
| 506 |
+
if do_classifier_free_guidance:
|
| 507 |
+
single_negative_image_embeds, single_image_embeds = single_image_embeds.chunk(2)
|
| 508 |
+
negative_image_embeds.append(single_negative_image_embeds)
|
| 509 |
+
image_embeds.append(single_image_embeds)
|
| 510 |
+
|
| 511 |
+
ip_adapter_image_embeds = []
|
| 512 |
+
for i, single_image_embeds in enumerate(image_embeds):
|
| 513 |
+
single_image_embeds = torch.cat([single_image_embeds] * num_images_per_prompt, dim=0)
|
| 514 |
+
if do_classifier_free_guidance:
|
| 515 |
+
single_negative_image_embeds = torch.cat([negative_image_embeds[i]] * num_images_per_prompt, dim=0)
|
| 516 |
+
single_image_embeds = torch.cat([single_negative_image_embeds, single_image_embeds], dim=0)
|
| 517 |
+
|
| 518 |
+
single_image_embeds = single_image_embeds.to(device=device)
|
| 519 |
+
ip_adapter_image_embeds.append(single_image_embeds)
|
| 520 |
+
|
| 521 |
+
return ip_adapter_image_embeds
|
| 522 |
+
|
| 523 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
|
| 524 |
+
def prepare_extra_step_kwargs(self, generator, eta):
|
| 525 |
+
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
|
| 526 |
+
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
|
| 527 |
+
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
|
| 528 |
+
# and should be between [0, 1]
|
| 529 |
+
|
| 530 |
+
accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 531 |
+
extra_step_kwargs = {}
|
| 532 |
+
if accepts_eta:
|
| 533 |
+
extra_step_kwargs["eta"] = eta
|
| 534 |
+
|
| 535 |
+
# check if the scheduler accepts generator
|
| 536 |
+
accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
|
| 537 |
+
if accepts_generator:
|
| 538 |
+
extra_step_kwargs["generator"] = generator
|
| 539 |
+
return extra_step_kwargs
|
| 540 |
+
|
| 541 |
+
def check_inputs(
|
| 542 |
+
self,
|
| 543 |
+
prompt,
|
| 544 |
+
image,
|
| 545 |
+
strength,
|
| 546 |
+
num_inference_steps,
|
| 547 |
+
callback_steps,
|
| 548 |
+
negative_prompt=None,
|
| 549 |
+
prompt_embeds=None,
|
| 550 |
+
negative_prompt_embeds=None,
|
| 551 |
+
pooled_prompt_embeds=None,
|
| 552 |
+
negative_pooled_prompt_embeds=None,
|
| 553 |
+
ip_adapter_image=None,
|
| 554 |
+
ip_adapter_image_embeds=None,
|
| 555 |
+
controlnet_conditioning_scale=1.0,
|
| 556 |
+
control_guidance_start=0.0,
|
| 557 |
+
control_guidance_end=1.0,
|
| 558 |
+
callback_on_step_end_tensor_inputs=None,
|
| 559 |
+
):
|
| 560 |
+
if strength < 0 or strength > 1:
|
| 561 |
+
raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
|
| 562 |
+
if num_inference_steps is None:
|
| 563 |
+
raise ValueError("`num_inference_steps` cannot be None.")
|
| 564 |
+
elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
|
| 565 |
+
raise ValueError(
|
| 566 |
+
f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
|
| 567 |
+
f" {type(num_inference_steps)}."
|
| 568 |
+
)
|
| 569 |
+
|
| 570 |
+
if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
|
| 571 |
+
raise ValueError(
|
| 572 |
+
f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
|
| 573 |
+
f" {type(callback_steps)}."
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 577 |
+
k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
|
| 578 |
+
):
|
| 579 |
+
raise ValueError(
|
| 580 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 581 |
+
)
|
| 582 |
+
|
| 583 |
+
if prompt is not None and prompt_embeds is not None:
|
| 584 |
+
raise ValueError(
|
| 585 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 586 |
+
" only forward one of the two."
|
| 587 |
+
)
|
| 588 |
+
elif prompt is None and prompt_embeds is None:
|
| 589 |
+
raise ValueError(
|
| 590 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 591 |
+
)
|
| 592 |
+
elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
|
| 593 |
+
raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
|
| 594 |
+
|
| 595 |
+
if negative_prompt is not None and negative_prompt_embeds is not None:
|
| 596 |
+
raise ValueError(
|
| 597 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
|
| 598 |
+
f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
if prompt_embeds is not None and negative_prompt_embeds is not None:
|
| 602 |
+
if prompt_embeds.shape != negative_prompt_embeds.shape:
|
| 603 |
+
raise ValueError(
|
| 604 |
+
"`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
|
| 605 |
+
f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
|
| 606 |
+
f" {negative_prompt_embeds.shape}."
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
if prompt_embeds is not None and pooled_prompt_embeds is None:
|
| 610 |
+
raise ValueError(
|
| 611 |
+
"If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
|
| 615 |
+
raise ValueError(
|
| 616 |
+
"If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
|
| 617 |
+
)
|
| 618 |
+
|
| 619 |
+
# `prompt` needs more sophisticated handling when there are multiple
|
| 620 |
+
# conditionings.
|
| 621 |
+
if isinstance(self.controlnet, MultiControlNetModel):
|
| 622 |
+
if isinstance(prompt, list):
|
| 623 |
+
logger.warning(
|
| 624 |
+
f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
|
| 625 |
+
" prompts. The conditionings will be fixed across the prompts."
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
# Check `image`
|
| 629 |
+
is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
|
| 630 |
+
self.controlnet, torch._dynamo.eval_frame.OptimizedModule
|
| 631 |
+
)
|
| 632 |
+
if (
|
| 633 |
+
isinstance(self.controlnet, ControlNetModel)
|
| 634 |
+
or is_compiled
|
| 635 |
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
| 636 |
+
):
|
| 637 |
+
self.check_image(image, prompt, prompt_embeds)
|
| 638 |
+
elif (
|
| 639 |
+
isinstance(self.controlnet, MultiControlNetModel)
|
| 640 |
+
or is_compiled
|
| 641 |
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
| 642 |
+
):
|
| 643 |
+
if not isinstance(image, list):
|
| 644 |
+
raise TypeError("For multiple controlnets: `image` must be type `list`")
|
| 645 |
+
|
| 646 |
+
# When `image` is a nested list:
|
| 647 |
+
# (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
|
| 648 |
+
elif any(isinstance(i, list) for i in image):
|
| 649 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
| 650 |
+
elif len(image) != len(self.controlnet.nets):
|
| 651 |
+
raise ValueError(
|
| 652 |
+
f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
for image_ in image:
|
| 656 |
+
self.check_image(image_, prompt, prompt_embeds)
|
| 657 |
+
else:
|
| 658 |
+
assert False
|
| 659 |
+
|
| 660 |
+
# Check `controlnet_conditioning_scale`
|
| 661 |
+
if (
|
| 662 |
+
isinstance(self.controlnet, ControlNetModel)
|
| 663 |
+
or is_compiled
|
| 664 |
+
and isinstance(self.controlnet._orig_mod, ControlNetModel)
|
| 665 |
+
):
|
| 666 |
+
if not isinstance(controlnet_conditioning_scale, float):
|
| 667 |
+
raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
|
| 668 |
+
elif (
|
| 669 |
+
isinstance(self.controlnet, MultiControlNetModel)
|
| 670 |
+
or is_compiled
|
| 671 |
+
and isinstance(self.controlnet._orig_mod, MultiControlNetModel)
|
| 672 |
+
):
|
| 673 |
+
if isinstance(controlnet_conditioning_scale, list):
|
| 674 |
+
if any(isinstance(i, list) for i in controlnet_conditioning_scale):
|
| 675 |
+
raise ValueError("A single batch of multiple conditionings are supported at the moment.")
|
| 676 |
+
elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
|
| 677 |
+
self.controlnet.nets
|
| 678 |
+
):
|
| 679 |
+
raise ValueError(
|
| 680 |
+
"For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
|
| 681 |
+
" the same length as the number of controlnets"
|
| 682 |
+
)
|
| 683 |
+
else:
|
| 684 |
+
assert False
|
| 685 |
+
|
| 686 |
+
if not isinstance(control_guidance_start, (tuple, list)):
|
| 687 |
+
control_guidance_start = [control_guidance_start]
|
| 688 |
+
|
| 689 |
+
if not isinstance(control_guidance_end, (tuple, list)):
|
| 690 |
+
control_guidance_end = [control_guidance_end]
|
| 691 |
+
|
| 692 |
+
if len(control_guidance_start) != len(control_guidance_end):
|
| 693 |
+
raise ValueError(
|
| 694 |
+
f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
if isinstance(self.controlnet, MultiControlNetModel):
|
| 698 |
+
if len(control_guidance_start) != len(self.controlnet.nets):
|
| 699 |
+
raise ValueError(
|
| 700 |
+
f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
|
| 701 |
+
)
|
| 702 |
+
|
| 703 |
+
for start, end in zip(control_guidance_start, control_guidance_end):
|
| 704 |
+
if start >= end:
|
| 705 |
+
raise ValueError(
|
| 706 |
+
f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
|
| 707 |
+
)
|
| 708 |
+
if start < 0.0:
|
| 709 |
+
raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
|
| 710 |
+
if end > 1.0:
|
| 711 |
+
raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
|
| 712 |
+
|
| 713 |
+
if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
|
| 714 |
+
raise ValueError(
|
| 715 |
+
"Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
if ip_adapter_image_embeds is not None:
|
| 719 |
+
if not isinstance(ip_adapter_image_embeds, list):
|
| 720 |
+
raise ValueError(
|
| 721 |
+
f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
|
| 722 |
+
)
|
| 723 |
+
elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
|
| 724 |
+
raise ValueError(
|
| 725 |
+
f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
|
| 726 |
+
)
|
| 727 |
+
|
| 728 |
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.check_image
|
| 729 |
+
def check_image(self, image, prompt, prompt_embeds):
|
| 730 |
+
image_is_pil = isinstance(image, PIL.Image.Image)
|
| 731 |
+
image_is_tensor = isinstance(image, torch.Tensor)
|
| 732 |
+
image_is_np = isinstance(image, np.ndarray)
|
| 733 |
+
image_is_pil_list = isinstance(image, list) and isinstance(image[0], PIL.Image.Image)
|
| 734 |
+
image_is_tensor_list = isinstance(image, list) and isinstance(image[0], torch.Tensor)
|
| 735 |
+
image_is_np_list = isinstance(image, list) and isinstance(image[0], np.ndarray)
|
| 736 |
+
|
| 737 |
+
if (
|
| 738 |
+
not image_is_pil
|
| 739 |
+
and not image_is_tensor
|
| 740 |
+
and not image_is_np
|
| 741 |
+
and not image_is_pil_list
|
| 742 |
+
and not image_is_tensor_list
|
| 743 |
+
and not image_is_np_list
|
| 744 |
+
):
|
| 745 |
+
raise TypeError(
|
| 746 |
+
f"image must be passed and be one of PIL image, numpy array, torch tensor, list of PIL images, list of numpy arrays or list of torch tensors, but is {type(image)}"
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
if image_is_pil:
|
| 750 |
+
image_batch_size = 1
|
| 751 |
+
else:
|
| 752 |
+
image_batch_size = len(image)
|
| 753 |
+
|
| 754 |
+
if prompt is not None and isinstance(prompt, str):
|
| 755 |
+
prompt_batch_size = 1
|
| 756 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 757 |
+
prompt_batch_size = len(prompt)
|
| 758 |
+
elif prompt_embeds is not None:
|
| 759 |
+
prompt_batch_size = prompt_embeds.shape[0]
|
| 760 |
+
|
| 761 |
+
if image_batch_size != 1 and image_batch_size != prompt_batch_size:
|
| 762 |
+
raise ValueError(
|
| 763 |
+
f"If image batch size is not 1, image batch size must be same as prompt batch size. image batch size: {image_batch_size}, prompt batch size: {prompt_batch_size}"
|
| 764 |
+
)
|
| 765 |
+
|
| 766 |
+
# Copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.StableDiffusionXLControlNetPipeline.prepare_image
|
| 767 |
+
def prepare_control_image(
|
| 768 |
+
self,
|
| 769 |
+
image,
|
| 770 |
+
width,
|
| 771 |
+
height,
|
| 772 |
+
batch_size,
|
| 773 |
+
num_images_per_prompt,
|
| 774 |
+
device,
|
| 775 |
+
dtype,
|
| 776 |
+
do_classifier_free_guidance=False,
|
| 777 |
+
guess_mode=False,
|
| 778 |
+
):
|
| 779 |
+
image = self.control_image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
| 780 |
+
image_batch_size = image.shape[0]
|
| 781 |
+
|
| 782 |
+
if image_batch_size == 1:
|
| 783 |
+
repeat_by = batch_size
|
| 784 |
+
else:
|
| 785 |
+
# image batch size is the same as prompt batch size
|
| 786 |
+
repeat_by = num_images_per_prompt
|
| 787 |
+
|
| 788 |
+
image = image.repeat_interleave(repeat_by, dim=0)
|
| 789 |
+
|
| 790 |
+
image = image.to(device=device, dtype=dtype)
|
| 791 |
+
|
| 792 |
+
if do_classifier_free_guidance and not guess_mode:
|
| 793 |
+
image = torch.cat([image] * 2)
|
| 794 |
+
|
| 795 |
+
return image
|
| 796 |
+
|
| 797 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
|
| 798 |
+
def get_timesteps(self, num_inference_steps, strength, device):
|
| 799 |
+
# get the original timestep using init_timestep
|
| 800 |
+
init_timestep = min(int(num_inference_steps * strength), num_inference_steps)
|
| 801 |
+
|
| 802 |
+
t_start = max(num_inference_steps - init_timestep, 0)
|
| 803 |
+
timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]
|
| 804 |
+
if hasattr(self.scheduler, "set_begin_index"):
|
| 805 |
+
self.scheduler.set_begin_index(t_start * self.scheduler.order)
|
| 806 |
+
|
| 807 |
+
return timesteps, num_inference_steps - t_start
|
| 808 |
+
|
| 809 |
+
# Copied from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl_img2img.StableDiffusionXLImg2ImgPipeline.prepare_latents
|
| 810 |
+
def prepare_latents(
|
| 811 |
+
self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None, add_noise=True
|
| 812 |
+
):
|
| 813 |
+
if not isinstance(image, (torch.Tensor, PIL.Image.Image, list)):
|
| 814 |
+
raise ValueError(
|
| 815 |
+
f"`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(image)}"
|
| 816 |
+
)
|
| 817 |
+
|
| 818 |
+
# Offload text encoder if `enable_model_cpu_offload` was enabled
|
| 819 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 820 |
+
torch.cuda.empty_cache()
|
| 821 |
+
|
| 822 |
+
image = image.to(device=device, dtype=dtype)
|
| 823 |
+
|
| 824 |
+
batch_size = batch_size * num_images_per_prompt
|
| 825 |
+
|
| 826 |
+
if image.shape[1] == 4:
|
| 827 |
+
init_latents = image
|
| 828 |
+
|
| 829 |
+
else:
|
| 830 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 831 |
+
if self.vae.config.force_upcast:
|
| 832 |
+
image = image.float()
|
| 833 |
+
self.vae.to(dtype=torch.float32)
|
| 834 |
+
|
| 835 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 836 |
+
raise ValueError(
|
| 837 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 838 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 839 |
+
)
|
| 840 |
+
|
| 841 |
+
elif isinstance(generator, list):
|
| 842 |
+
init_latents = [
|
| 843 |
+
retrieve_latents(self.vae.encode(image[i : i + 1]), generator=generator[i])
|
| 844 |
+
for i in range(batch_size)
|
| 845 |
+
]
|
| 846 |
+
init_latents = torch.cat(init_latents, dim=0)
|
| 847 |
+
else:
|
| 848 |
+
init_latents = retrieve_latents(self.vae.encode(image), generator=generator)
|
| 849 |
+
|
| 850 |
+
if self.vae.config.force_upcast:
|
| 851 |
+
self.vae.to(dtype)
|
| 852 |
+
|
| 853 |
+
init_latents = init_latents.to(dtype)
|
| 854 |
+
|
| 855 |
+
init_latents = self.vae.config.scaling_factor * init_latents
|
| 856 |
+
|
| 857 |
+
if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
|
| 858 |
+
# expand init_latents for batch_size
|
| 859 |
+
additional_image_per_prompt = batch_size // init_latents.shape[0]
|
| 860 |
+
init_latents = torch.cat([init_latents] * additional_image_per_prompt, dim=0)
|
| 861 |
+
elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
|
| 862 |
+
raise ValueError(
|
| 863 |
+
f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
|
| 864 |
+
)
|
| 865 |
+
else:
|
| 866 |
+
init_latents = torch.cat([init_latents], dim=0)
|
| 867 |
+
|
| 868 |
+
if add_noise:
|
| 869 |
+
shape = init_latents.shape
|
| 870 |
+
noise = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 871 |
+
# get latents
|
| 872 |
+
init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
|
| 873 |
+
|
| 874 |
+
latents = init_latents
|
| 875 |
+
|
| 876 |
+
return latents
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
|
| 880 |
+
def prepare_latents_t2i(self, batch_size, num_channels_latents, height, width, dtype, device, generator, latents=None):
|
| 881 |
+
shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
|
| 882 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 883 |
+
raise ValueError(
|
| 884 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 885 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
if latents is None:
|
| 889 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 890 |
+
else:
|
| 891 |
+
latents = latents.to(device)
|
| 892 |
+
|
| 893 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 894 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 895 |
+
return latents
|
| 896 |
+
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
def _get_add_time_ids(self, original_size, crops_coords_top_left, target_size, dtype):
|
| 900 |
+
add_time_ids = list(original_size + crops_coords_top_left + target_size)
|
| 901 |
+
|
| 902 |
+
passed_add_embed_dim = (
|
| 903 |
+
self.unet.config.addition_time_embed_dim * len(add_time_ids) + 4096
|
| 904 |
+
)
|
| 905 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 906 |
+
|
| 907 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
| 908 |
+
raise ValueError(
|
| 909 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 910 |
+
)
|
| 911 |
+
|
| 912 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 913 |
+
return add_time_ids
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_upscale.StableDiffusionUpscalePipeline.upcast_vae
|
| 917 |
+
def upcast_vae(self):
|
| 918 |
+
dtype = self.vae.dtype
|
| 919 |
+
self.vae.to(dtype=torch.float32)
|
| 920 |
+
use_torch_2_0_or_xformers = isinstance(
|
| 921 |
+
self.vae.decoder.mid_block.attentions[0].processor,
|
| 922 |
+
(
|
| 923 |
+
AttnProcessor2_0,
|
| 924 |
+
XFormersAttnProcessor,
|
| 925 |
+
),
|
| 926 |
+
)
|
| 927 |
+
# if xformers or torch_2_0 is used attention block does not need
|
| 928 |
+
# to be in float32 which can save lots of memory
|
| 929 |
+
if use_torch_2_0_or_xformers:
|
| 930 |
+
self.vae.post_quant_conv.to(dtype)
|
| 931 |
+
self.vae.decoder.conv_in.to(dtype)
|
| 932 |
+
self.vae.decoder.mid_block.to(dtype)
|
| 933 |
+
|
| 934 |
+
@property
|
| 935 |
+
def guidance_scale(self):
|
| 936 |
+
return self._guidance_scale
|
| 937 |
+
|
| 938 |
+
@property
|
| 939 |
+
def clip_skip(self):
|
| 940 |
+
return self._clip_skip
|
| 941 |
+
|
| 942 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 943 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 944 |
+
# corresponds to doing no classifier free guidance.
|
| 945 |
+
@property
|
| 946 |
+
def do_classifier_free_guidance(self):
|
| 947 |
+
return self._guidance_scale > 1
|
| 948 |
+
|
| 949 |
+
@property
|
| 950 |
+
def cross_attention_kwargs(self):
|
| 951 |
+
return self._cross_attention_kwargs
|
| 952 |
+
|
| 953 |
+
@property
|
| 954 |
+
def num_timesteps(self):
|
| 955 |
+
return self._num_timesteps
|
| 956 |
+
|
| 957 |
+
@torch.no_grad()
|
| 958 |
+
def __call__(
|
| 959 |
+
self,
|
| 960 |
+
prompt: Union[str, List[str]] = None,
|
| 961 |
+
image: PipelineImageInput = None,
|
| 962 |
+
control_image: PipelineImageInput = None,
|
| 963 |
+
# garment_image: PipelineImageInput = None,
|
| 964 |
+
height: Optional[int] = None,
|
| 965 |
+
width: Optional[int] = None,
|
| 966 |
+
strength: float = 0.8,
|
| 967 |
+
num_inference_steps: int = 50,
|
| 968 |
+
guidance_scale: float = 5.0,
|
| 969 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 970 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 971 |
+
eta: float = 0.0,
|
| 972 |
+
guess_mode: bool = False,
|
| 973 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 974 |
+
latents: Optional[torch.Tensor] = None,
|
| 975 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 976 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 977 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
| 978 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
| 979 |
+
ip_adapter_image: Optional[PipelineImageInput] = None,
|
| 980 |
+
ip_adapter_image_embeds: Optional[List[torch.Tensor]] = None,
|
| 981 |
+
face_crop_image: Optional[PipelineImageInput] = None,
|
| 982 |
+
face_insightface_embeds: Optional[torch.FloatTensor] = None,
|
| 983 |
+
output_type: Optional[str] = "pil",
|
| 984 |
+
return_dict: bool = True,
|
| 985 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 986 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
|
| 987 |
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
| 988 |
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
| 989 |
+
original_size: Tuple[int, int] = None,
|
| 990 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 991 |
+
target_size: Tuple[int, int] = None,
|
| 992 |
+
clip_skip: Optional[int] = None,
|
| 993 |
+
callback_on_step_end: Optional[
|
| 994 |
+
Union[Callable[[int, int, Dict], None], PipelineCallback, MultiPipelineCallbacks]
|
| 995 |
+
] = None,
|
| 996 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 997 |
+
**kwargs,
|
| 998 |
+
):
|
| 999 |
+
r"""
|
| 1000 |
+
Function invoked when calling the pipeline for generation.
|
| 1001 |
+
|
| 1002 |
+
Args:
|
| 1003 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 1004 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 1005 |
+
instead.
|
| 1006 |
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 1007 |
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 1008 |
+
The initial image will be used as the starting point for the image generation process. Can also accept
|
| 1009 |
+
image latents as `image`, if passing latents directly, it will not be encoded again.
|
| 1010 |
+
control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 1011 |
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 1012 |
+
The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
|
| 1013 |
+
the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also
|
| 1014 |
+
be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
|
| 1015 |
+
and/or width are passed, `image` is resized according to them. If multiple ControlNets are specified in
|
| 1016 |
+
init, images must be passed as a list such that each element of the list can be correctly batched for
|
| 1017 |
+
input to a single controlnet.
|
| 1018 |
+
height (`int`, *optional*, defaults to the size of control_image):
|
| 1019 |
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 1020 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 1021 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 1022 |
+
width (`int`, *optional*, defaults to the size of control_image):
|
| 1023 |
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 1024 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 1025 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 1026 |
+
strength (`float`, *optional*, defaults to 0.8):
|
| 1027 |
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
| 1028 |
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
| 1029 |
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
| 1030 |
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
| 1031 |
+
essentially ignores `image`.
|
| 1032 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 1033 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 1034 |
+
expense of slower inference.
|
| 1035 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 1036 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 1037 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 1038 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 1039 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 1040 |
+
usually at the expense of lower image quality.
|
| 1041 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1042 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 1043 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 1044 |
+
less than `1`).
|
| 1045 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 1046 |
+
The number of images to generate per prompt.
|
| 1047 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 1048 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 1049 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 1050 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 1051 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 1052 |
+
to make generation deterministic.
|
| 1053 |
+
latents (`torch.Tensor`, *optional*):
|
| 1054 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 1055 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 1056 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 1057 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 1058 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 1059 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 1060 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1061 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 1062 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 1063 |
+
argument.
|
| 1064 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1065 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 1066 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 1067 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1068 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 1069 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 1070 |
+
input argument.
|
| 1071 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
| 1072 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
| 1073 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
| 1074 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
| 1075 |
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
| 1076 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 1077 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 1078 |
+
The output format of the generate image. Choose between
|
| 1079 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 1080 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 1081 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 1082 |
+
plain tuple.
|
| 1083 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 1084 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 1085 |
+
`self.processor` in
|
| 1086 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1087 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 1088 |
+
The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
|
| 1089 |
+
to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
|
| 1090 |
+
corresponding scale as a list.
|
| 1091 |
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
| 1092 |
+
The percentage of total steps at which the controlnet starts applying.
|
| 1093 |
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 1094 |
+
The percentage of total steps at which the controlnet stops applying.
|
| 1095 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 1096 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
| 1097 |
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
| 1098 |
+
explained in section 2.2 of
|
| 1099 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1100 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 1101 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 1102 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 1103 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 1104 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1105 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 1106 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 1107 |
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
| 1108 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1109 |
+
clip_skip (`int`, *optional*):
|
| 1110 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 1111 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 1112 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 1113 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 1114 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 1115 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 1116 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 1117 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 1118 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 1119 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 1120 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 1121 |
+
|
| 1122 |
+
Examples:
|
| 1123 |
+
|
| 1124 |
+
Returns:
|
| 1125 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 1126 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
|
| 1127 |
+
containing the output images.
|
| 1128 |
+
"""
|
| 1129 |
+
|
| 1130 |
+
callback = kwargs.pop("callback", None)
|
| 1131 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 1132 |
+
|
| 1133 |
+
if callback is not None:
|
| 1134 |
+
deprecate(
|
| 1135 |
+
"callback",
|
| 1136 |
+
"1.0.0",
|
| 1137 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 1138 |
+
)
|
| 1139 |
+
if callback_steps is not None:
|
| 1140 |
+
deprecate(
|
| 1141 |
+
"callback_steps",
|
| 1142 |
+
"1.0.0",
|
| 1143 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 1144 |
+
)
|
| 1145 |
+
|
| 1146 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 1147 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 1148 |
+
|
| 1149 |
+
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
|
| 1150 |
+
|
| 1151 |
+
# align format for control guidance
|
| 1152 |
+
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
|
| 1153 |
+
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
|
| 1154 |
+
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
|
| 1155 |
+
control_guidance_end = len(control_guidance_start) * [control_guidance_end]
|
| 1156 |
+
elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
|
| 1157 |
+
mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
|
| 1158 |
+
control_guidance_start, control_guidance_end = (
|
| 1159 |
+
mult * [control_guidance_start],
|
| 1160 |
+
mult * [control_guidance_end],
|
| 1161 |
+
)
|
| 1162 |
+
|
| 1163 |
+
# from IPython import embed; embed()
|
| 1164 |
+
# 1. Check inputs. Raise error if not correct
|
| 1165 |
+
self.check_inputs(
|
| 1166 |
+
prompt,
|
| 1167 |
+
control_image,
|
| 1168 |
+
strength,
|
| 1169 |
+
num_inference_steps,
|
| 1170 |
+
callback_steps,
|
| 1171 |
+
negative_prompt,
|
| 1172 |
+
prompt_embeds,
|
| 1173 |
+
negative_prompt_embeds,
|
| 1174 |
+
pooled_prompt_embeds,
|
| 1175 |
+
negative_pooled_prompt_embeds,
|
| 1176 |
+
ip_adapter_image,
|
| 1177 |
+
ip_adapter_image_embeds,
|
| 1178 |
+
controlnet_conditioning_scale,
|
| 1179 |
+
control_guidance_start,
|
| 1180 |
+
control_guidance_end,
|
| 1181 |
+
callback_on_step_end_tensor_inputs,
|
| 1182 |
+
)
|
| 1183 |
+
|
| 1184 |
+
self._guidance_scale = guidance_scale
|
| 1185 |
+
self._clip_skip = clip_skip
|
| 1186 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 1187 |
+
|
| 1188 |
+
# 2. Define call parameters
|
| 1189 |
+
if prompt is not None and isinstance(prompt, str):
|
| 1190 |
+
batch_size = 1
|
| 1191 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1192 |
+
batch_size = len(prompt)
|
| 1193 |
+
else:
|
| 1194 |
+
batch_size = prompt_embeds.shape[0]
|
| 1195 |
+
|
| 1196 |
+
device = self._execution_device
|
| 1197 |
+
|
| 1198 |
+
if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
|
| 1199 |
+
controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
|
| 1200 |
+
|
| 1201 |
+
# 3.1. Encode input prompt
|
| 1202 |
+
text_encoder_lora_scale = (
|
| 1203 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 1204 |
+
)
|
| 1205 |
+
(
|
| 1206 |
+
prompt_embeds,
|
| 1207 |
+
negative_prompt_embeds,
|
| 1208 |
+
pooled_prompt_embeds,
|
| 1209 |
+
negative_pooled_prompt_embeds,
|
| 1210 |
+
) = self.encode_prompt(
|
| 1211 |
+
prompt,
|
| 1212 |
+
device,
|
| 1213 |
+
num_images_per_prompt,
|
| 1214 |
+
self.do_classifier_free_guidance,
|
| 1215 |
+
negative_prompt,
|
| 1216 |
+
prompt_embeds=prompt_embeds,
|
| 1217 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1218 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 1219 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 1220 |
+
lora_scale=text_encoder_lora_scale,
|
| 1221 |
+
)
|
| 1222 |
+
|
| 1223 |
+
# 3.2 Encode ip_adapter_image
|
| 1224 |
+
# if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
| 1225 |
+
# image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 1226 |
+
# ip_adapter_image,
|
| 1227 |
+
# ip_adapter_image_embeds,
|
| 1228 |
+
# device,
|
| 1229 |
+
# batch_size * num_images_per_prompt,
|
| 1230 |
+
# self.do_classifier_free_guidance,
|
| 1231 |
+
# )
|
| 1232 |
+
|
| 1233 |
+
if face_crop_image is not None and face_insightface_embeds is not None:
|
| 1234 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_fused_face_embedds(
|
| 1235 |
+
face_insightface_embeds = face_insightface_embeds,
|
| 1236 |
+
face_crop_image = face_crop_image,
|
| 1237 |
+
num_images_per_prompt = num_images_per_prompt,
|
| 1238 |
+
device = device
|
| 1239 |
+
)
|
| 1240 |
+
|
| 1241 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
| 1242 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
| 1243 |
+
|
| 1244 |
+
# 4. Prepare image and controlnet_conditioning_image
|
| 1245 |
+
# image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
| 1246 |
+
|
| 1247 |
+
# garment_image = self.image_processor.preprocess(garment_image, height=height, width=width).to(dtype=torch.float32)
|
| 1248 |
+
# garment_image = garment_image.to(device=device)
|
| 1249 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 1250 |
+
needs_upcasting = self.vae.dtype != torch.float32 and self.vae.config.force_upcast
|
| 1251 |
+
|
| 1252 |
+
if needs_upcasting:
|
| 1253 |
+
ori_dtype = self.vae.dtype
|
| 1254 |
+
self.upcast_vae()
|
| 1255 |
+
|
| 1256 |
+
|
| 1257 |
+
# garment_image = self.vae.encode(garment_image).latent_dist.sample()
|
| 1258 |
+
# garment_image = garment_image * self.vae.config.scaling_factor
|
| 1259 |
+
# garment_image = garment_image.to(dtype=prompt_embeds.dtype)
|
| 1260 |
+
|
| 1261 |
+
# cast back to fp16 if needed
|
| 1262 |
+
if needs_upcasting:
|
| 1263 |
+
self.vae.to(dtype=ori_dtype)
|
| 1264 |
+
|
| 1265 |
+
# if self.do_classifier_free_guidance:
|
| 1266 |
+
# garment_image = torch.cat([garment_image,torch.zeros_like(garment_image)])
|
| 1267 |
+
# garment_image = torch.cat([garment_image]*2)
|
| 1268 |
+
if isinstance(controlnet, ControlNetModel):
|
| 1269 |
+
control_image = self.prepare_control_image(
|
| 1270 |
+
image=control_image,
|
| 1271 |
+
width=width,
|
| 1272 |
+
height=height,
|
| 1273 |
+
batch_size=batch_size * num_images_per_prompt,
|
| 1274 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1275 |
+
device=device,
|
| 1276 |
+
dtype=controlnet.dtype,
|
| 1277 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1278 |
+
guess_mode=guess_mode,
|
| 1279 |
+
)
|
| 1280 |
+
height, width = control_image.shape[-2:]
|
| 1281 |
+
elif isinstance(controlnet, MultiControlNetModel):
|
| 1282 |
+
control_images = []
|
| 1283 |
+
|
| 1284 |
+
for control_image_ in control_image:
|
| 1285 |
+
control_image_ = self.prepare_control_image(
|
| 1286 |
+
image=control_image_,
|
| 1287 |
+
width=width,
|
| 1288 |
+
height=height,
|
| 1289 |
+
batch_size=batch_size * num_images_per_prompt,
|
| 1290 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1291 |
+
device=device,
|
| 1292 |
+
dtype=controlnet.dtype,
|
| 1293 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1294 |
+
guess_mode=guess_mode,
|
| 1295 |
+
)
|
| 1296 |
+
|
| 1297 |
+
control_images.append(control_image_)
|
| 1298 |
+
|
| 1299 |
+
control_image = control_images
|
| 1300 |
+
height, width = control_image[0].shape[-2:]
|
| 1301 |
+
else:
|
| 1302 |
+
assert False
|
| 1303 |
+
|
| 1304 |
+
# 5. Prepare timesteps
|
| 1305 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 1306 |
+
timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
|
| 1307 |
+
latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
|
| 1308 |
+
self._num_timesteps = len(timesteps)
|
| 1309 |
+
|
| 1310 |
+
# 6. Prepare latent variables
|
| 1311 |
+
|
| 1312 |
+
num_channels_latents = self.unet.config.in_channels
|
| 1313 |
+
if latents is None:
|
| 1314 |
+
# if strength >= 1.0:
|
| 1315 |
+
# latents = self.prepare_latents_t2i(
|
| 1316 |
+
# batch_size * num_images_per_prompt,
|
| 1317 |
+
# num_channels_latents,
|
| 1318 |
+
# height,
|
| 1319 |
+
# width,
|
| 1320 |
+
# prompt_embeds.dtype,
|
| 1321 |
+
# device,
|
| 1322 |
+
# generator,
|
| 1323 |
+
# latents,
|
| 1324 |
+
# )
|
| 1325 |
+
# else:
|
| 1326 |
+
# latents = self.prepare_latents(
|
| 1327 |
+
# image,
|
| 1328 |
+
# latent_timestep,
|
| 1329 |
+
# batch_size,
|
| 1330 |
+
# num_images_per_prompt,
|
| 1331 |
+
# prompt_embeds.dtype,
|
| 1332 |
+
# device,
|
| 1333 |
+
# generator,
|
| 1334 |
+
# True,
|
| 1335 |
+
# )
|
| 1336 |
+
latents = self.prepare_latents_t2i(
|
| 1337 |
+
batch_size * num_images_per_prompt,
|
| 1338 |
+
num_channels_latents,
|
| 1339 |
+
height,
|
| 1340 |
+
width,
|
| 1341 |
+
prompt_embeds.dtype,
|
| 1342 |
+
device,
|
| 1343 |
+
generator,
|
| 1344 |
+
latents,
|
| 1345 |
+
)
|
| 1346 |
+
|
| 1347 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 1348 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 1349 |
+
|
| 1350 |
+
# 7.1 Create tensor stating which controlnets to keep
|
| 1351 |
+
controlnet_keep = []
|
| 1352 |
+
for i in range(len(timesteps)):
|
| 1353 |
+
keeps = [
|
| 1354 |
+
1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
|
| 1355 |
+
for s, e in zip(control_guidance_start, control_guidance_end)
|
| 1356 |
+
]
|
| 1357 |
+
controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
|
| 1358 |
+
|
| 1359 |
+
# 7.2 Prepare added time ids & embeddings
|
| 1360 |
+
if isinstance(control_image, list):
|
| 1361 |
+
original_size = original_size or control_image[0].shape[-2:]
|
| 1362 |
+
else:
|
| 1363 |
+
original_size = original_size or control_image.shape[-2:]
|
| 1364 |
+
target_size = target_size or (height, width)
|
| 1365 |
+
|
| 1366 |
+
# 7. Prepare added time ids & embeddings
|
| 1367 |
+
add_text_embeds = pooled_prompt_embeds
|
| 1368 |
+
add_time_ids = self._get_add_time_ids(
|
| 1369 |
+
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 1370 |
+
)
|
| 1371 |
+
|
| 1372 |
+
if self.do_classifier_free_guidance:
|
| 1373 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 1374 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
| 1375 |
+
add_time_ids = torch.cat([add_time_ids, add_time_ids], dim=0)
|
| 1376 |
+
|
| 1377 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 1378 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 1379 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 1380 |
+
|
| 1381 |
+
# 8. Denoising loop
|
| 1382 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 1383 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1384 |
+
for i, t in enumerate(timesteps):
|
| 1385 |
+
# expand the latents if we are doing classifier free guidance
|
| 1386 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 1387 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 1388 |
+
|
| 1389 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 1390 |
+
|
| 1391 |
+
# controlnet(s) inference
|
| 1392 |
+
if guess_mode and self.do_classifier_free_guidance:
|
| 1393 |
+
# Infer ControlNet only for the conditional batch.
|
| 1394 |
+
control_model_input = latents
|
| 1395 |
+
control_model_input = self.scheduler.scale_model_input(control_model_input, t)
|
| 1396 |
+
controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
|
| 1397 |
+
controlnet_added_cond_kwargs = {
|
| 1398 |
+
"text_embeds": add_text_embeds.chunk(2)[1],
|
| 1399 |
+
"time_ids": add_time_ids.chunk(2)[1],
|
| 1400 |
+
}
|
| 1401 |
+
else:
|
| 1402 |
+
control_model_input = latent_model_input
|
| 1403 |
+
controlnet_prompt_embeds = prompt_embeds
|
| 1404 |
+
controlnet_added_cond_kwargs = added_cond_kwargs
|
| 1405 |
+
|
| 1406 |
+
if isinstance(controlnet_keep[i], list):
|
| 1407 |
+
cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
|
| 1408 |
+
else:
|
| 1409 |
+
controlnet_cond_scale = controlnet_conditioning_scale
|
| 1410 |
+
if isinstance(controlnet_cond_scale, list):
|
| 1411 |
+
controlnet_cond_scale = controlnet_cond_scale[0]
|
| 1412 |
+
cond_scale = controlnet_cond_scale * controlnet_keep[i]
|
| 1413 |
+
|
| 1414 |
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
| 1415 |
+
# torch.cat([control_model_input,garment_image],dim=1),
|
| 1416 |
+
control_model_input,
|
| 1417 |
+
t,
|
| 1418 |
+
encoder_hidden_states=controlnet_prompt_embeds,
|
| 1419 |
+
controlnet_cond=control_image,
|
| 1420 |
+
conditioning_scale=cond_scale,
|
| 1421 |
+
guess_mode=guess_mode,
|
| 1422 |
+
added_cond_kwargs=controlnet_added_cond_kwargs,
|
| 1423 |
+
return_dict=False,
|
| 1424 |
+
)
|
| 1425 |
+
|
| 1426 |
+
down_block_res_samples = [each.to(latent_model_input.dtype) for each in down_block_res_samples]
|
| 1427 |
+
mid_block_res_sample = mid_block_res_sample.to(latent_model_input.dtype)
|
| 1428 |
+
|
| 1429 |
+
if guess_mode and self.do_classifier_free_guidance:
|
| 1430 |
+
# Infered ControlNet only for the conditional batch.
|
| 1431 |
+
# To apply the output of ControlNet to both the unconditional and conditional batches,
|
| 1432 |
+
# add 0 to the unconditional batch to keep it unchanged.
|
| 1433 |
+
down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
|
| 1434 |
+
mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
|
| 1435 |
+
|
| 1436 |
+
# if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
| 1437 |
+
# added_cond_kwargs["image_embeds"] = image_embeds
|
| 1438 |
+
|
| 1439 |
+
# predict the noise residual
|
| 1440 |
+
noise_pred = self.unet(
|
| 1441 |
+
latent_model_input,
|
| 1442 |
+
t,
|
| 1443 |
+
encoder_hidden_states=prompt_embeds,
|
| 1444 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 1445 |
+
down_block_additional_residuals=down_block_res_samples,
|
| 1446 |
+
mid_block_additional_residual=mid_block_res_sample,
|
| 1447 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 1448 |
+
return_dict=False,
|
| 1449 |
+
)[0]
|
| 1450 |
+
|
| 1451 |
+
# perform guidance
|
| 1452 |
+
if self.do_classifier_free_guidance:
|
| 1453 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 1454 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 1455 |
+
|
| 1456 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 1457 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 1458 |
+
|
| 1459 |
+
# call the callback, if provided
|
| 1460 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 1461 |
+
progress_bar.update()
|
| 1462 |
+
if callback is not None and i % callback_steps == 0:
|
| 1463 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 1464 |
+
callback(step_idx, t, latents)
|
| 1465 |
+
|
| 1466 |
+
# If we do sequential model offloading, let's offload unet and controlnet
|
| 1467 |
+
# manually for max memory savings
|
| 1468 |
+
if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
|
| 1469 |
+
self.unet.to("cpu")
|
| 1470 |
+
self.controlnet.to("cpu")
|
| 1471 |
+
torch.cuda.empty_cache()
|
| 1472 |
+
|
| 1473 |
+
if not output_type == "latent":
|
| 1474 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 1475 |
+
needs_upcasting = self.vae.dtype != torch.float32 and self.vae.config.force_upcast
|
| 1476 |
+
|
| 1477 |
+
if needs_upcasting:
|
| 1478 |
+
ori_dtype = self.vae.dtype
|
| 1479 |
+
self.upcast_vae()
|
| 1480 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 1481 |
+
|
| 1482 |
+
latents = latents / self.vae.config.scaling_factor
|
| 1483 |
+
|
| 1484 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 1485 |
+
|
| 1486 |
+
# cast back to fp16 if needed
|
| 1487 |
+
if needs_upcasting:
|
| 1488 |
+
self.vae.to(dtype=ori_dtype)
|
| 1489 |
+
else:
|
| 1490 |
+
image = latents
|
| 1491 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
| 1492 |
+
|
| 1493 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 1494 |
+
|
| 1495 |
+
# Offload all models
|
| 1496 |
+
self.maybe_free_model_hooks()
|
| 1497 |
+
|
| 1498 |
+
if not return_dict:
|
| 1499 |
+
return (image,)
|
| 1500 |
+
|
| 1501 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
| 1502 |
+
|
| 1503 |
+
def train_step(
|
| 1504 |
+
self,
|
| 1505 |
+
accelerator,
|
| 1506 |
+
optimizer,
|
| 1507 |
+
lr_scheduler,
|
| 1508 |
+
prompt: Union[str, List[str]] = None,
|
| 1509 |
+
control_image: PipelineImageInput = None,
|
| 1510 |
+
ori_image: Optional[PipelineImageInput] = None,
|
| 1511 |
+
height: Optional[int] = None,
|
| 1512 |
+
width: Optional[int] = None,
|
| 1513 |
+
guidance_scale: float = 5.0,
|
| 1514 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 1515 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 1516 |
+
eta: float = 0.0,
|
| 1517 |
+
guess_mode: bool = False,
|
| 1518 |
+
latents: Optional[torch.Tensor] = None,
|
| 1519 |
+
prompt_embeds: Optional[torch.Tensor] = None,
|
| 1520 |
+
negative_prompt_embeds: Optional[torch.Tensor] = None,
|
| 1521 |
+
pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
| 1522 |
+
negative_pooled_prompt_embeds: Optional[torch.Tensor] = None,
|
| 1523 |
+
face_crop_image: Optional[PipelineImageInput] = None,
|
| 1524 |
+
face_insightface_embeds: Optional[torch.FloatTensor] = None,
|
| 1525 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 1526 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
|
| 1527 |
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
| 1528 |
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
| 1529 |
+
original_size: Tuple[int, int] = None,
|
| 1530 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 1531 |
+
target_size: Tuple[int, int] = None,
|
| 1532 |
+
clip_skip: Optional[int] = None,
|
| 1533 |
+
|
| 1534 |
+
):
|
| 1535 |
+
r"""
|
| 1536 |
+
Function invoked when calling the pipeline for generation.
|
| 1537 |
+
|
| 1538 |
+
Args:
|
| 1539 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 1540 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
| 1541 |
+
instead.
|
| 1542 |
+
image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 1543 |
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 1544 |
+
The initial image will be used as the starting point for the image generation process. Can also accept
|
| 1545 |
+
image latents as `image`, if passing latents directly, it will not be encoded again.
|
| 1546 |
+
control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 1547 |
+
`List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 1548 |
+
The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
|
| 1549 |
+
the type is specified as `torch.Tensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also
|
| 1550 |
+
be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
|
| 1551 |
+
and/or width are passed, `image` is resized according to them. If multiple ControlNets are specified in
|
| 1552 |
+
init, images must be passed as a list such that each element of the list can be correctly batched for
|
| 1553 |
+
input to a single controlnet.
|
| 1554 |
+
height (`int`, *optional*, defaults to the size of control_image):
|
| 1555 |
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 1556 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 1557 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 1558 |
+
width (`int`, *optional*, defaults to the size of control_image):
|
| 1559 |
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 1560 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 1561 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 1562 |
+
strength (`float`, *optional*, defaults to 0.8):
|
| 1563 |
+
Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
|
| 1564 |
+
starting point and more noise is added the higher the `strength`. The number of denoising steps depends
|
| 1565 |
+
on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
|
| 1566 |
+
process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
|
| 1567 |
+
essentially ignores `image`.
|
| 1568 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 1569 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 1570 |
+
expense of slower inference.
|
| 1571 |
+
guidance_scale (`float`, *optional*, defaults to 7.5):
|
| 1572 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
| 1573 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
| 1574 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
| 1575 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
| 1576 |
+
usually at the expense of lower image quality.
|
| 1577 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 1578 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 1579 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 1580 |
+
less than `1`).
|
| 1581 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 1582 |
+
The number of images to generate per prompt.
|
| 1583 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 1584 |
+
Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
| 1585 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
| 1586 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 1587 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
| 1588 |
+
to make generation deterministic.
|
| 1589 |
+
latents (`torch.Tensor`, *optional*):
|
| 1590 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
| 1591 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 1592 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
| 1593 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 1594 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 1595 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 1596 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1597 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 1598 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 1599 |
+
argument.
|
| 1600 |
+
pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1601 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
| 1602 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
| 1603 |
+
negative_pooled_prompt_embeds (`torch.Tensor`, *optional*):
|
| 1604 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 1605 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
| 1606 |
+
input argument.
|
| 1607 |
+
ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
|
| 1608 |
+
ip_adapter_image_embeds (`List[torch.Tensor]`, *optional*):
|
| 1609 |
+
Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of
|
| 1610 |
+
IP-adapters. Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should
|
| 1611 |
+
contain the negative image embedding if `do_classifier_free_guidance` is set to `True`. If not
|
| 1612 |
+
provided, embeddings are computed from the `ip_adapter_image` input argument.
|
| 1613 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 1614 |
+
The output format of the generate image. Choose between
|
| 1615 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
| 1616 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 1617 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 1618 |
+
plain tuple.
|
| 1619 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 1620 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 1621 |
+
`self.processor` in
|
| 1622 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 1623 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 1624 |
+
The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
|
| 1625 |
+
to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
|
| 1626 |
+
corresponding scale as a list.
|
| 1627 |
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
| 1628 |
+
The percentage of total steps at which the controlnet starts applying.
|
| 1629 |
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 1630 |
+
The percentage of total steps at which the controlnet stops applying.
|
| 1631 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 1632 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
| 1633 |
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
| 1634 |
+
explained in section 2.2 of
|
| 1635 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1636 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 1637 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 1638 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 1639 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 1640 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1641 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 1642 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 1643 |
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
| 1644 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 1645 |
+
clip_skip (`int`, *optional*):
|
| 1646 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 1647 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 1648 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 1649 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 1650 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 1651 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 1652 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 1653 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 1654 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 1655 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 1656 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 1657 |
+
|
| 1658 |
+
Examples:
|
| 1659 |
+
|
| 1660 |
+
Returns:
|
| 1661 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 1662 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
|
| 1663 |
+
containing the output images.
|
| 1664 |
+
"""
|
| 1665 |
+
|
| 1666 |
+
controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
|
| 1667 |
+
|
| 1668 |
+
# align format for control guidance
|
| 1669 |
+
if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
|
| 1670 |
+
control_guidance_start = len(control_guidance_end) * [control_guidance_start]
|
| 1671 |
+
elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
|
| 1672 |
+
control_guidance_end = len(control_guidance_start) * [control_guidance_end]
|
| 1673 |
+
elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
|
| 1674 |
+
mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
|
| 1675 |
+
control_guidance_start, control_guidance_end = (
|
| 1676 |
+
mult * [control_guidance_start],
|
| 1677 |
+
mult * [control_guidance_end],
|
| 1678 |
+
)
|
| 1679 |
+
|
| 1680 |
+
self._guidance_scale = guidance_scale
|
| 1681 |
+
self._clip_skip = clip_skip
|
| 1682 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 1683 |
+
|
| 1684 |
+
# 2. Define call parameters
|
| 1685 |
+
if prompt is not None and isinstance(prompt, str):
|
| 1686 |
+
batch_size = 1
|
| 1687 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 1688 |
+
batch_size = len(prompt)
|
| 1689 |
+
else:
|
| 1690 |
+
batch_size = prompt_embeds.shape[0]
|
| 1691 |
+
|
| 1692 |
+
device = self._execution_device
|
| 1693 |
+
|
| 1694 |
+
# 3.1. Encode input prompt
|
| 1695 |
+
text_encoder_lora_scale = (
|
| 1696 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 1697 |
+
)
|
| 1698 |
+
(
|
| 1699 |
+
prompt_embeds,
|
| 1700 |
+
_,
|
| 1701 |
+
pooled_prompt_embeds,
|
| 1702 |
+
_,
|
| 1703 |
+
) = self.encode_prompt(
|
| 1704 |
+
prompt,
|
| 1705 |
+
device,
|
| 1706 |
+
num_images_per_prompt,
|
| 1707 |
+
False,
|
| 1708 |
+
negative_prompt,
|
| 1709 |
+
prompt_embeds=prompt_embeds,
|
| 1710 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1711 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 1712 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 1713 |
+
lora_scale=text_encoder_lora_scale,
|
| 1714 |
+
)
|
| 1715 |
+
|
| 1716 |
+
# 3.2 Encode ip_adapter_image
|
| 1717 |
+
# if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
|
| 1718 |
+
# image_embeds = self.prepare_ip_adapter_image_embeds(
|
| 1719 |
+
# ip_adapter_image,
|
| 1720 |
+
# ip_adapter_image_embeds,
|
| 1721 |
+
# device,
|
| 1722 |
+
# batch_size * num_images_per_prompt,
|
| 1723 |
+
# self.do_classifier_free_guidance,
|
| 1724 |
+
# )
|
| 1725 |
+
|
| 1726 |
+
if face_crop_image is not None and face_insightface_embeds is not None:
|
| 1727 |
+
##### prepare fused face embeds
|
| 1728 |
+
image_prompt_embeds = []
|
| 1729 |
+
for crop_image,face_embed in zip(face_crop_image,face_insightface_embeds):
|
| 1730 |
+
image_prompt_embed, _ = self.get_fused_face_embedds(
|
| 1731 |
+
face_insightface_embeds = face_embed,
|
| 1732 |
+
face_crop_image = crop_image,
|
| 1733 |
+
num_images_per_prompt = num_images_per_prompt,
|
| 1734 |
+
device = device
|
| 1735 |
+
)
|
| 1736 |
+
image_prompt_embeds.append(image_prompt_embed)
|
| 1737 |
+
prompt_embeds = torch.cat([prompt_embeds, torch.cat(image_prompt_embeds)], dim=1)
|
| 1738 |
+
# negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
| 1739 |
+
|
| 1740 |
+
# 4. Prepare image and controlnet_conditioning_image
|
| 1741 |
+
# image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
|
| 1742 |
+
ori_image = self.image_processor.preprocess(ori_image, height=height, width=width).to(dtype=torch.float32)
|
| 1743 |
+
ori_image = ori_image.to(device=device)
|
| 1744 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 1745 |
+
|
| 1746 |
+
needs_upcasting = self.vae.dtype != torch.float32 and self.vae.config.force_upcast
|
| 1747 |
+
|
| 1748 |
+
if needs_upcasting:
|
| 1749 |
+
ori_dtype = self.vae.dtype
|
| 1750 |
+
self.upcast_vae()
|
| 1751 |
+
|
| 1752 |
+
ori_image = self.vae.encode(ori_image).latent_dist.sample()
|
| 1753 |
+
ori_image = ori_image * self.vae.config.scaling_factor
|
| 1754 |
+
ori_image = ori_image.to(dtype=prompt_embeds.dtype)
|
| 1755 |
+
|
| 1756 |
+
if needs_upcasting:
|
| 1757 |
+
self.vae.to(dtype=ori_dtype)
|
| 1758 |
+
|
| 1759 |
+
noise = torch.randn_like(ori_image)
|
| 1760 |
+
|
| 1761 |
+
timesteps = torch.randint(
|
| 1762 |
+
0, self.scheduler.config.num_train_timesteps, (batch_size,), device=device,dtype=torch.int64)
|
| 1763 |
+
|
| 1764 |
+
noisy_latents = self.scheduler.add_noise(ori_image, noise, timesteps)
|
| 1765 |
+
latent_model_input = noisy_latents
|
| 1766 |
+
|
| 1767 |
+
if isinstance(controlnet, ControlNetModel):
|
| 1768 |
+
control_image = self.prepare_control_image(
|
| 1769 |
+
image=control_image,
|
| 1770 |
+
width=width,
|
| 1771 |
+
height=height,
|
| 1772 |
+
batch_size=batch_size * num_images_per_prompt,
|
| 1773 |
+
num_images_per_prompt=num_images_per_prompt,
|
| 1774 |
+
device=device,
|
| 1775 |
+
dtype=controlnet.dtype,
|
| 1776 |
+
do_classifier_free_guidance=False,
|
| 1777 |
+
guess_mode=guess_mode,
|
| 1778 |
+
)
|
| 1779 |
+
height, width = control_image.shape[-2:]
|
| 1780 |
+
|
| 1781 |
+
|
| 1782 |
+
# 7.1 Create tensor stating which controlnets to keep
|
| 1783 |
+
# controlnet_keep = []
|
| 1784 |
+
# for i in range(len(timesteps)):
|
| 1785 |
+
# keeps = [
|
| 1786 |
+
# 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
|
| 1787 |
+
# for s, e in zip(control_guidance_start, control_guidance_end)
|
| 1788 |
+
# ]
|
| 1789 |
+
# controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
|
| 1790 |
+
|
| 1791 |
+
# 7.2 Prepare added time ids & embeddings
|
| 1792 |
+
if isinstance(control_image, list):
|
| 1793 |
+
original_size = original_size or control_image[0].shape[-2:]
|
| 1794 |
+
else:
|
| 1795 |
+
original_size = original_size or control_image.shape[-2:]
|
| 1796 |
+
target_size = target_size or (height, width)
|
| 1797 |
+
|
| 1798 |
+
# 7. Prepare added time ids & embeddings
|
| 1799 |
+
add_text_embeds = pooled_prompt_embeds
|
| 1800 |
+
add_time_ids = self._get_add_time_ids(
|
| 1801 |
+
original_size, crops_coords_top_left, target_size, dtype=prompt_embeds.dtype
|
| 1802 |
+
)
|
| 1803 |
+
|
| 1804 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 1805 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 1806 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 1807 |
+
|
| 1808 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 1809 |
+
|
| 1810 |
+
|
| 1811 |
+
control_model_input = latent_model_input
|
| 1812 |
+
controlnet_prompt_embeds = prompt_embeds
|
| 1813 |
+
controlnet_added_cond_kwargs = added_cond_kwargs
|
| 1814 |
+
|
| 1815 |
+
# if isinstance(controlnet_keep[i], list):
|
| 1816 |
+
# cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
|
| 1817 |
+
# else:
|
| 1818 |
+
# controlnet_cond_scale = controlnet_conditioning_scale
|
| 1819 |
+
# if isinstance(controlnet_cond_scale, list):
|
| 1820 |
+
# controlnet_cond_scale = controlnet_cond_scale[0]
|
| 1821 |
+
# cond_scale = controlnet_cond_scale * controlnet_keep[i]
|
| 1822 |
+
|
| 1823 |
+
with accelerator.accumulate(self.controlnet):
|
| 1824 |
+
down_block_res_samples, mid_block_res_sample = self.controlnet(
|
| 1825 |
+
control_model_input,
|
| 1826 |
+
timesteps,
|
| 1827 |
+
encoder_hidden_states=controlnet_prompt_embeds,
|
| 1828 |
+
controlnet_cond=control_image,
|
| 1829 |
+
conditioning_scale=1.0,
|
| 1830 |
+
guess_mode=guess_mode,
|
| 1831 |
+
added_cond_kwargs=controlnet_added_cond_kwargs,
|
| 1832 |
+
return_dict=False,
|
| 1833 |
+
)
|
| 1834 |
+
|
| 1835 |
+
down_block_res_samples = [each.to(latent_model_input.dtype) for each in down_block_res_samples]
|
| 1836 |
+
mid_block_res_sample = mid_block_res_sample.to(latent_model_input.dtype)
|
| 1837 |
+
|
| 1838 |
+
noise_pred = self.unet(
|
| 1839 |
+
latent_model_input,
|
| 1840 |
+
timesteps,
|
| 1841 |
+
encoder_hidden_states=prompt_embeds,
|
| 1842 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 1843 |
+
down_block_additional_residuals=down_block_res_samples,
|
| 1844 |
+
mid_block_additional_residual=mid_block_res_sample,
|
| 1845 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 1846 |
+
return_dict=False,
|
| 1847 |
+
)[0]
|
| 1848 |
+
loss = F.mse_loss(noise_pred.float(), noise.float(), reduction="mean")
|
| 1849 |
+
accelerator.backward(loss)
|
| 1850 |
+
accelerator.clip_grad_norm_(self.controlnet.parameters(), 1.0)
|
| 1851 |
+
optimizer.step()
|
| 1852 |
+
lr_scheduler.step()
|
| 1853 |
+
optimizer.zero_grad()
|
| 1854 |
+
|
| 1855 |
+
return loss
|
| 1856 |
+
|