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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 The InstantX 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 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
import cv2
|
| 19 |
+
import math
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import PIL.Image
|
| 23 |
+
from PIL import Image
|
| 24 |
+
import torch, traceback, pdb
|
| 25 |
+
import torch.nn.functional as F
|
| 26 |
+
|
| 27 |
+
from diffusers.image_processor import PipelineImageInput
|
| 28 |
+
|
| 29 |
+
from diffusers.models import ControlNetModel
|
| 30 |
+
|
| 31 |
+
from diffusers.utils import (
|
| 32 |
+
deprecate,
|
| 33 |
+
logging,
|
| 34 |
+
replace_example_docstring,
|
| 35 |
+
)
|
| 36 |
+
from diffusers.utils.torch_utils import is_compiled_module, is_torch_version
|
| 37 |
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
| 38 |
+
|
| 39 |
+
from diffusers import StableDiffusionXLPipeline
|
| 40 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 41 |
+
|
| 42 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
| 43 |
+
from insightface.utils import face_align
|
| 44 |
+
|
| 45 |
+
from ip_adapter.resampler import Resampler
|
| 46 |
+
from ip_adapter.utils import is_torch2_available
|
| 47 |
+
from ip_adapter.ip_adapter_faceid import faceid_plus
|
| 48 |
+
|
| 49 |
+
from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
|
| 50 |
+
from ip_adapter.attention_processor_faceid import LoRAIPAttnProcessor2_0 as LoRAIPAttnProcessor, LoRAAttnProcessor2_0 as LoRAAttnProcessor
|
| 51 |
+
|
| 52 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
EXAMPLE_DOC_STRING = """
|
| 56 |
+
Examples:
|
| 57 |
+
```py
|
| 58 |
+
>>> # !pip install opencv-python transformers accelerate insightface
|
| 59 |
+
>>> import diffusers
|
| 60 |
+
>>> from diffusers.utils import load_image
|
| 61 |
+
>>> import cv2
|
| 62 |
+
>>> import torch
|
| 63 |
+
>>> import numpy as np
|
| 64 |
+
>>> from PIL import Image
|
| 65 |
+
|
| 66 |
+
>>> from insightface.app import FaceAnalysis
|
| 67 |
+
>>> from pipeline_sdxl_storymaker import StableDiffusionXLStoryMakerPipeline
|
| 68 |
+
|
| 69 |
+
>>> # download 'buffalo_l' under ./models
|
| 70 |
+
>>> app = FaceAnalysis(name='buffalo_l', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
| 71 |
+
>>> app.prepare(ctx_id=0, det_size=(640, 640))
|
| 72 |
+
|
| 73 |
+
>>> # download models under ./checkpoints
|
| 74 |
+
>>> storymaker_adapter = f'./checkpoints/ip-adapter.bin'
|
| 75 |
+
|
| 76 |
+
>>> pipe = StableDiffusionXLStoryMakerPipeline.from_pretrained(
|
| 77 |
+
... "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16
|
| 78 |
+
... )
|
| 79 |
+
>>> pipe.cuda()
|
| 80 |
+
|
| 81 |
+
>>> # load adapter
|
| 82 |
+
>>> pipe.load_storymaker_adapter(storymaker_adapter)
|
| 83 |
+
|
| 84 |
+
>>> prompt = "a person is taking a selfie, the person is wearing a red hat, and a volcano is in the distance"
|
| 85 |
+
>>> negative_prompt = "bad quality, NSFW, low quality, ugly, disfigured, deformed"
|
| 86 |
+
|
| 87 |
+
>>> # load an image
|
| 88 |
+
>>> image = load_image("your-example.jpg")
|
| 89 |
+
>>> # load the mask image of portrait
|
| 90 |
+
>>> mask_image = load_image("your-mask.jpg")
|
| 91 |
+
|
| 92 |
+
>>> face_info = app.get(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR))[-1]
|
| 93 |
+
|
| 94 |
+
>>> # generate image
|
| 95 |
+
>>> image = pipe(
|
| 96 |
+
... prompt, image=image, mask_image=mask_image,face_info=face_info, controlnet_conditioning_scale=0.8
|
| 97 |
+
... ).images[0]
|
| 98 |
+
```
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def bounding_rectangle(ori_img, mask):
|
| 102 |
+
"""
|
| 103 |
+
Calculate the bounding rectangle of multiple rectangles.
|
| 104 |
+
Args:
|
| 105 |
+
rectangles (list of tuples): List of rectangles, where each rectangle is represented as (x, y, w, h)
|
| 106 |
+
Returns:
|
| 107 |
+
tuple: The bounding rectangle (x, y, w, h)
|
| 108 |
+
"""
|
| 109 |
+
contours, _ = cv2.findContours(mask[:,:,0], cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
|
| 110 |
+
rectangles = [cv2.boundingRect(contour) for contour in contours]
|
| 111 |
+
|
| 112 |
+
min_x = float('inf')
|
| 113 |
+
min_y = float('inf')
|
| 114 |
+
max_x = float('-inf')
|
| 115 |
+
max_y = float('-inf')
|
| 116 |
+
for x, y, w, h in rectangles:
|
| 117 |
+
min_x = min(min_x, x)
|
| 118 |
+
min_y = min(min_y, y)
|
| 119 |
+
max_x = max(max_x, x + w)
|
| 120 |
+
max_y = max(max_y, y + h)
|
| 121 |
+
try:
|
| 122 |
+
crop = ori_img[min_y:max_y, min_x:max_x]
|
| 123 |
+
mask = mask[min_y:max_y, min_x:max_x]
|
| 124 |
+
except:
|
| 125 |
+
traceback.print_exc()
|
| 126 |
+
return crop, mask
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class StableDiffusionXLStoryMakerPipeline(StableDiffusionXLPipeline):
|
| 131 |
+
|
| 132 |
+
def cuda(self, dtype=torch.float16, use_xformers=False):
|
| 133 |
+
self.to('cuda', dtype)
|
| 134 |
+
if hasattr(self, 'image_proj_model'):
|
| 135 |
+
self.image_proj_model.to(self.unet.device).to(self.unet.dtype)
|
| 136 |
+
|
| 137 |
+
def load_storymaker_adapter(self, image_encoder_path, model_ckpt, image_emb_dim=512, num_tokens=20, scale=0.8, lora_scale=0.8):
|
| 138 |
+
self.clip_image_processor = CLIPImageProcessor()
|
| 139 |
+
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(image_encoder_path).to(self.device, dtype=self.dtype)
|
| 140 |
+
self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens)
|
| 141 |
+
self.set_ip_adapter(model_ckpt, num_tokens)
|
| 142 |
+
self.set_ip_adapter_scale(scale, lora_scale)
|
| 143 |
+
print(f'successful load adapter.')
|
| 144 |
+
|
| 145 |
+
def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16):
|
| 146 |
+
|
| 147 |
+
image_proj_model = faceid_plus(
|
| 148 |
+
cross_attention_dim=self.unet.config.cross_attention_dim,
|
| 149 |
+
id_embeddings_dim=512,
|
| 150 |
+
clip_embeddings_dim=1280,
|
| 151 |
+
)
|
| 152 |
+
image_proj_model.eval()
|
| 153 |
+
|
| 154 |
+
self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype)
|
| 155 |
+
state_dict = torch.load(model_ckpt, map_location="cpu")
|
| 156 |
+
if 'image_proj_model' in state_dict:
|
| 157 |
+
state_dict = state_dict["image_proj_model"]
|
| 158 |
+
self.image_proj_model.load_state_dict(state_dict)
|
| 159 |
+
|
| 160 |
+
def set_ip_adapter(self, model_ckpt, num_tokens, lora_rank=128):
|
| 161 |
+
|
| 162 |
+
unet = self.unet
|
| 163 |
+
attn_procs = {}
|
| 164 |
+
for name in unet.attn_processors.keys():
|
| 165 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
| 166 |
+
if name.startswith("mid_block"):
|
| 167 |
+
hidden_size = unet.config.block_out_channels[-1]
|
| 168 |
+
elif name.startswith("up_blocks"):
|
| 169 |
+
block_id = int(name[len("up_blocks.")])
|
| 170 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
| 171 |
+
elif name.startswith("down_blocks"):
|
| 172 |
+
block_id = int(name[len("down_blocks.")])
|
| 173 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
| 174 |
+
if cross_attention_dim is None:
|
| 175 |
+
attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank).to(unet.device, dtype=unet.dtype)
|
| 176 |
+
else:
|
| 177 |
+
attn_procs[name] = LoRAIPAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=lora_rank).to(unet.device, dtype=unet.dtype)
|
| 178 |
+
unet.set_attn_processor(attn_procs)
|
| 179 |
+
|
| 180 |
+
state_dict = torch.load(model_ckpt, map_location="cpu")
|
| 181 |
+
ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
|
| 182 |
+
if 'ip_adapter' in state_dict:
|
| 183 |
+
state_dict = state_dict['ip_adapter']
|
| 184 |
+
ip_layers.load_state_dict(state_dict)
|
| 185 |
+
|
| 186 |
+
def set_ip_adapter_scale(self, scale, lora_scale=0.8):
|
| 187 |
+
unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
|
| 188 |
+
for attn_processor in unet.attn_processors.values():
|
| 189 |
+
if isinstance(attn_processor, LoRAIPAttnProcessor) or isinstance(attn_processor, LoRAAttnProcessor):
|
| 190 |
+
attn_processor.scale = scale
|
| 191 |
+
attn_processor.lora_scale = lora_scale
|
| 192 |
+
|
| 193 |
+
def crop_image(self, ori_img, ori_mask, face_info):
|
| 194 |
+
ori_img = np.array(ori_img)
|
| 195 |
+
ori_mask = np.array(ori_mask)
|
| 196 |
+
crop, mask = bounding_rectangle(ori_img, ori_mask)
|
| 197 |
+
mask = cv2.GaussianBlur(mask, (5, 5), 0)/255.
|
| 198 |
+
crop = (255*np.ones_like(mask)*(1-mask)+mask*crop).astype(np.uint8)
|
| 199 |
+
# cv2.imwrite('examples/results/0crop.jpg', crop[:,:,::-1])
|
| 200 |
+
# cv2.imwrite('examples/results/0mask.jpg', (mask*255).astype(np.uint8))
|
| 201 |
+
|
| 202 |
+
face_kps = face_info['kps']
|
| 203 |
+
# face_image = face_align.norm_crop(crop, landmark=face_kps.numpy(), image_size=224) # 224
|
| 204 |
+
face_image = face_align.norm_crop(ori_img, landmark=face_kps, image_size=224) # 224
|
| 205 |
+
clip_face = self.clip_image_processor(images=face_image, return_tensors="pt").pixel_values
|
| 206 |
+
|
| 207 |
+
ref_img = Image.fromarray(crop)
|
| 208 |
+
ref_img = ref_img.resize((224, 224))
|
| 209 |
+
clip_img = self.clip_image_processor(images=ref_img, return_tensors="pt").pixel_values
|
| 210 |
+
return clip_img, clip_face, torch.from_numpy(face_info.normed_embedding).unsqueeze(0)
|
| 211 |
+
|
| 212 |
+
def _encode_prompt_image_emb(self, image, image_2, mask_image, mask_image_2, face_info, face_info_2, cloth, cloth_2, \
|
| 213 |
+
device, num_images_per_prompt, dtype, do_classifier_free_guidance):
|
| 214 |
+
crop_list = []; face_list = []; id_list = []
|
| 215 |
+
if image is not None:
|
| 216 |
+
clip_img, clip_face, face_emb = self.crop_image(image, mask_image, face_info)
|
| 217 |
+
crop_list.append(clip_img)
|
| 218 |
+
face_list.append(clip_face)
|
| 219 |
+
id_list.append(face_emb)
|
| 220 |
+
if image_2 is not None:
|
| 221 |
+
clip_img, clip_face, face_emb = self.crop_image(image_2, mask_image_2, face_info_2)
|
| 222 |
+
crop_list.append(clip_img)
|
| 223 |
+
face_list.append(clip_face)
|
| 224 |
+
id_list.append(face_emb)
|
| 225 |
+
if cloth is not None:
|
| 226 |
+
crop_list = []
|
| 227 |
+
clip_img = self.clip_image_processor(images=cloth.resize((224, 224)), return_tensors="pt").pixel_values
|
| 228 |
+
crop_list.append(clip_img)
|
| 229 |
+
if cloth_2 is not None:
|
| 230 |
+
clip_img = self.clip_image_processor(images=cloth_2.resize((224, 224)), return_tensors="pt").pixel_values
|
| 231 |
+
crop_list.append(clip_img)
|
| 232 |
+
assert len(crop_list)>0, f"input error, images is None"
|
| 233 |
+
clip_image = torch.cat(crop_list, dim=0).to(device, dtype=dtype)
|
| 234 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
| 235 |
+
clip_face = torch.cat(face_list, dim=0).to(device, dtype=dtype)
|
| 236 |
+
clip_face_embeds = self.image_encoder(clip_face, output_hidden_states=True).hidden_states[-2]
|
| 237 |
+
id_embeds = torch.cat(id_list, dim=0).to(device, dtype=dtype)
|
| 238 |
+
# print(f'clip_image_embeds: {clip_image_embeds.shape}, clip_face_embeds:{clip_face_embeds.shape}, id_embeds:{id_embeds.shape}')
|
| 239 |
+
if do_classifier_free_guidance:
|
| 240 |
+
prompt_image_emb = self.image_proj_model(id_embeds, clip_image_embeds, clip_face_embeds)
|
| 241 |
+
B, C, D = prompt_image_emb.shape
|
| 242 |
+
prompt_image_emb = prompt_image_emb.view(1, B*C, D)
|
| 243 |
+
neg_emb = self.image_proj_model(torch.zeros_like(id_embeds), torch.zeros_like(clip_image_embeds), torch.zeros_like(clip_face_embeds))
|
| 244 |
+
neg_emb = neg_emb.view(1, B*C, D)
|
| 245 |
+
prompt_image_emb = torch.cat([neg_emb, prompt_image_emb], dim=0)
|
| 246 |
+
else:
|
| 247 |
+
prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
|
| 248 |
+
B, C, D = prompt_image_emb.shape
|
| 249 |
+
prompt_image_emb = prompt_image_emb.view(1, B*C, D)
|
| 250 |
+
|
| 251 |
+
# print(f'prompt_image_emb: {prompt_image_emb.shape}')
|
| 252 |
+
bs_embed, seq_len, _ = prompt_image_emb.shape
|
| 253 |
+
prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
|
| 254 |
+
prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
|
| 255 |
+
|
| 256 |
+
return prompt_image_emb.to(device=device, dtype=dtype)
|
| 257 |
+
|
| 258 |
+
@torch.no_grad()
|
| 259 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 260 |
+
def __call__(
|
| 261 |
+
self,
|
| 262 |
+
prompt: Union[str, List[str]] = None,
|
| 263 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
| 264 |
+
image: PipelineImageInput = None,
|
| 265 |
+
mask_image: Union[torch.Tensor, PIL.Image.Image] = None,
|
| 266 |
+
image_2: PipelineImageInput = None,
|
| 267 |
+
mask_image_2: Union[torch.Tensor, PIL.Image.Image] = None,
|
| 268 |
+
height: Optional[int] = None,
|
| 269 |
+
width: Optional[int] = None,
|
| 270 |
+
num_inference_steps: int = 50,
|
| 271 |
+
guidance_scale: float = 5.0,
|
| 272 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
| 273 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
| 274 |
+
num_images_per_prompt: Optional[int] = 1,
|
| 275 |
+
eta: float = 0.0,
|
| 276 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 277 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 278 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 279 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 280 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 281 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
| 282 |
+
output_type: Optional[str] = "pil",
|
| 283 |
+
return_dict: bool = True,
|
| 284 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
| 285 |
+
controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
|
| 286 |
+
guess_mode: bool = False,
|
| 287 |
+
control_guidance_start: Union[float, List[float]] = 0.0,
|
| 288 |
+
control_guidance_end: Union[float, List[float]] = 1.0,
|
| 289 |
+
original_size: Tuple[int, int] = None,
|
| 290 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 291 |
+
target_size: Tuple[int, int] = None,
|
| 292 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
| 293 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
| 294 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
| 295 |
+
clip_skip: Optional[int] = None,
|
| 296 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 297 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 298 |
+
|
| 299 |
+
# IP adapter
|
| 300 |
+
ip_adapter_scale=None,
|
| 301 |
+
lora_scale=None,
|
| 302 |
+
face_info = None,
|
| 303 |
+
face_info_2 = None,
|
| 304 |
+
cloth = None,
|
| 305 |
+
cloth_2 = None,
|
| 306 |
+
|
| 307 |
+
**kwargs,
|
| 308 |
+
):
|
| 309 |
+
r"""
|
| 310 |
+
The call function to the pipeline for generation.
|
| 311 |
+
|
| 312 |
+
Args:
|
| 313 |
+
prompt (`str` or `List[str]`, *optional*):
|
| 314 |
+
The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
|
| 315 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
| 316 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
| 317 |
+
used in both text-encoders.
|
| 318 |
+
image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
|
| 319 |
+
`List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
|
| 320 |
+
The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
|
| 321 |
+
specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
|
| 322 |
+
accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
|
| 323 |
+
and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
|
| 324 |
+
`init`, images must be passed as a list such that each element of the list can be correctly batched for
|
| 325 |
+
input to a single ControlNet.
|
| 326 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 327 |
+
The height in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 328 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 329 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 330 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 331 |
+
The width in pixels of the generated image. Anything below 512 pixels won't work well for
|
| 332 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
| 333 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
| 334 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
| 335 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 336 |
+
expense of slower inference.
|
| 337 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
| 338 |
+
A higher guidance scale value encourages the model to generate images closely linked to the text
|
| 339 |
+
`prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
|
| 340 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
| 341 |
+
The prompt or prompts to guide what to not include in image generation. If not defined, you need to
|
| 342 |
+
pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
|
| 343 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
| 344 |
+
The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
|
| 345 |
+
and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
|
| 346 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
| 347 |
+
The number of images to generate per prompt.
|
| 348 |
+
eta (`float`, *optional*, defaults to 0.0):
|
| 349 |
+
Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
|
| 350 |
+
to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
|
| 351 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 352 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 353 |
+
generation deterministic.
|
| 354 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 355 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 356 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 357 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 358 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 359 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 360 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 361 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 362 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 363 |
+
not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
|
| 364 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 365 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
|
| 366 |
+
not provided, pooled text embeddings are generated from `prompt` input argument.
|
| 367 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
| 368 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
|
| 369 |
+
weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
|
| 370 |
+
argument.
|
| 371 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 372 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 373 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 374 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 375 |
+
plain tuple.
|
| 376 |
+
cross_attention_kwargs (`dict`, *optional*):
|
| 377 |
+
A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
|
| 378 |
+
[`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 379 |
+
controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 380 |
+
The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
|
| 381 |
+
to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
|
| 382 |
+
the corresponding scale as a list.
|
| 383 |
+
guess_mode (`bool`, *optional*, defaults to `False`):
|
| 384 |
+
The ControlNet encoder tries to recognize the content of the input image even if you remove all
|
| 385 |
+
prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
|
| 386 |
+
control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
|
| 387 |
+
The percentage of total steps at which the ControlNet starts applying.
|
| 388 |
+
control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
|
| 389 |
+
The percentage of total steps at which the ControlNet stops applying.
|
| 390 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 391 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
| 392 |
+
`original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
|
| 393 |
+
explained in section 2.2 of
|
| 394 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 395 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 396 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
| 397 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
| 398 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 399 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 400 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 401 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
| 402 |
+
not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
|
| 403 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
| 404 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 405 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
| 406 |
+
micro-conditioning as explained in section 2.2 of
|
| 407 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 408 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 409 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
| 410 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
| 411 |
+
micro-conditioning as explained in section 2.2 of
|
| 412 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 413 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 414 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
| 415 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
| 416 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
| 417 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
| 418 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
| 419 |
+
clip_skip (`int`, *optional*):
|
| 420 |
+
Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
|
| 421 |
+
the output of the pre-final layer will be used for computing the prompt embeddings.
|
| 422 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 423 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 424 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 425 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 426 |
+
`callback_on_step_end_tensor_inputs`.
|
| 427 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 428 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 429 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 430 |
+
`._callback_tensor_inputs` attribute of your pipeine class.
|
| 431 |
+
|
| 432 |
+
Examples:
|
| 433 |
+
|
| 434 |
+
Returns:
|
| 435 |
+
[`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
|
| 436 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
|
| 437 |
+
otherwise a `tuple` is returned containing the output images.
|
| 438 |
+
"""
|
| 439 |
+
|
| 440 |
+
callback = kwargs.pop("callback", None)
|
| 441 |
+
callback_steps = kwargs.pop("callback_steps", None)
|
| 442 |
+
|
| 443 |
+
if callback is not None:
|
| 444 |
+
deprecate(
|
| 445 |
+
"callback",
|
| 446 |
+
"1.0.0",
|
| 447 |
+
"Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 448 |
+
)
|
| 449 |
+
if callback_steps is not None:
|
| 450 |
+
deprecate(
|
| 451 |
+
"callback_steps",
|
| 452 |
+
"1.0.0",
|
| 453 |
+
"Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
# 0. set ip_adapter_scale
|
| 457 |
+
if ip_adapter_scale is not None and lora_scale is not None:
|
| 458 |
+
self.set_ip_adapter_scale(ip_adapter_scale, lora_scale)
|
| 459 |
+
|
| 460 |
+
# 1. Check inputs. Raise error if not correct
|
| 461 |
+
# self.check_inputs(
|
| 462 |
+
# prompt=prompt,
|
| 463 |
+
# prompt_2=prompt_2,
|
| 464 |
+
# height=height, width=width,
|
| 465 |
+
# callback_steps=callback_steps,
|
| 466 |
+
# negative_prompt=negative_prompt,
|
| 467 |
+
# negative_prompt_2=negative_prompt_2,
|
| 468 |
+
# prompt_embeds=prompt_embeds,
|
| 469 |
+
# negative_prompt_embeds=negative_prompt_embeds,
|
| 470 |
+
# pooled_prompt_embeds=pooled_prompt_embeds,
|
| 471 |
+
# negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 472 |
+
# callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 473 |
+
# )
|
| 474 |
+
|
| 475 |
+
self._guidance_scale = guidance_scale
|
| 476 |
+
self._clip_skip = clip_skip
|
| 477 |
+
self._cross_attention_kwargs = cross_attention_kwargs
|
| 478 |
+
|
| 479 |
+
# 2. Define call parameters
|
| 480 |
+
if prompt is not None and isinstance(prompt, str):
|
| 481 |
+
batch_size = 1
|
| 482 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 483 |
+
batch_size = len(prompt)
|
| 484 |
+
else:
|
| 485 |
+
batch_size = prompt_embeds.shape[0]
|
| 486 |
+
|
| 487 |
+
device = self.unet.device
|
| 488 |
+
# pdb.set_trace()
|
| 489 |
+
# 3.1 Encode input prompt
|
| 490 |
+
text_encoder_lora_scale = (
|
| 491 |
+
self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
|
| 492 |
+
)
|
| 493 |
+
(
|
| 494 |
+
prompt_embeds,
|
| 495 |
+
negative_prompt_embeds,
|
| 496 |
+
pooled_prompt_embeds,
|
| 497 |
+
negative_pooled_prompt_embeds,
|
| 498 |
+
) = self.encode_prompt(
|
| 499 |
+
prompt,
|
| 500 |
+
prompt_2,
|
| 501 |
+
device,
|
| 502 |
+
num_images_per_prompt,
|
| 503 |
+
self.do_classifier_free_guidance,
|
| 504 |
+
negative_prompt,
|
| 505 |
+
negative_prompt_2,
|
| 506 |
+
prompt_embeds=prompt_embeds,
|
| 507 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 508 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 509 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 510 |
+
lora_scale=text_encoder_lora_scale,
|
| 511 |
+
clip_skip=self.clip_skip,
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
# 3.2 Encode image prompt
|
| 515 |
+
prompt_image_emb = self._encode_prompt_image_emb(image, image_2, mask_image, mask_image_2, face_info, face_info_2, cloth,cloth_2,
|
| 516 |
+
device, num_images_per_prompt,
|
| 517 |
+
self.unet.dtype, self.do_classifier_free_guidance)
|
| 518 |
+
|
| 519 |
+
# 5. Prepare timesteps
|
| 520 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 521 |
+
timesteps = self.scheduler.timesteps
|
| 522 |
+
self._num_timesteps = len(timesteps)
|
| 523 |
+
|
| 524 |
+
# 6. Prepare latent variables
|
| 525 |
+
num_channels_latents = self.unet.config.in_channels
|
| 526 |
+
latents = self.prepare_latents(
|
| 527 |
+
batch_size * num_images_per_prompt,
|
| 528 |
+
num_channels_latents,
|
| 529 |
+
height,
|
| 530 |
+
width,
|
| 531 |
+
prompt_embeds.dtype,
|
| 532 |
+
device,
|
| 533 |
+
generator,
|
| 534 |
+
latents,
|
| 535 |
+
)
|
| 536 |
+
|
| 537 |
+
# 6.5 Optionally get Guidance Scale Embedding
|
| 538 |
+
timestep_cond = None
|
| 539 |
+
if self.unet.config.time_cond_proj_dim is not None:
|
| 540 |
+
guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
|
| 541 |
+
timestep_cond = self.get_guidance_scale_embedding(
|
| 542 |
+
guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
|
| 543 |
+
).to(device=device, dtype=latents.dtype)
|
| 544 |
+
|
| 545 |
+
# 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
| 546 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
| 547 |
+
|
| 548 |
+
# 7.2 Prepare added time ids & embeddings
|
| 549 |
+
original_size = original_size or (height, width)
|
| 550 |
+
target_size = target_size or (height, width)
|
| 551 |
+
|
| 552 |
+
add_text_embeds = pooled_prompt_embeds
|
| 553 |
+
if self.text_encoder_2 is None:
|
| 554 |
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
| 555 |
+
else:
|
| 556 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
| 557 |
+
|
| 558 |
+
add_time_ids = self._get_add_time_ids(
|
| 559 |
+
original_size,
|
| 560 |
+
crops_coords_top_left,
|
| 561 |
+
target_size,
|
| 562 |
+
dtype=prompt_embeds.dtype,
|
| 563 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
| 564 |
+
)
|
| 565 |
+
|
| 566 |
+
if negative_original_size is not None and negative_target_size is not None:
|
| 567 |
+
negative_add_time_ids = self._get_add_time_ids(
|
| 568 |
+
negative_original_size,
|
| 569 |
+
negative_crops_coords_top_left,
|
| 570 |
+
negative_target_size,
|
| 571 |
+
dtype=prompt_embeds.dtype,
|
| 572 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
| 573 |
+
)
|
| 574 |
+
else:
|
| 575 |
+
negative_add_time_ids = add_time_ids
|
| 576 |
+
|
| 577 |
+
if self.do_classifier_free_guidance:
|
| 578 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
| 579 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
| 580 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
| 581 |
+
|
| 582 |
+
prompt_embeds = prompt_embeds.to(device)
|
| 583 |
+
add_text_embeds = add_text_embeds.to(device)
|
| 584 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
| 585 |
+
encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
|
| 586 |
+
|
| 587 |
+
# 8. Denoising loop
|
| 588 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 589 |
+
is_unet_compiled = is_compiled_module(self.unet)
|
| 590 |
+
|
| 591 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 592 |
+
for i, t in enumerate(timesteps):
|
| 593 |
+
|
| 594 |
+
# expand the latents if we are doing classifier free guidance
|
| 595 |
+
latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
|
| 596 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 597 |
+
|
| 598 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
| 599 |
+
|
| 600 |
+
# predict the noise residual
|
| 601 |
+
noise_pred = self.unet(
|
| 602 |
+
latent_model_input,
|
| 603 |
+
t,
|
| 604 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 605 |
+
timestep_cond=timestep_cond,
|
| 606 |
+
cross_attention_kwargs=self.cross_attention_kwargs,
|
| 607 |
+
added_cond_kwargs=added_cond_kwargs,
|
| 608 |
+
return_dict=False,
|
| 609 |
+
)[0]
|
| 610 |
+
|
| 611 |
+
# perform guidance
|
| 612 |
+
if self.do_classifier_free_guidance:
|
| 613 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
| 614 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
| 615 |
+
|
| 616 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 617 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
| 618 |
+
|
| 619 |
+
if callback_on_step_end is not None:
|
| 620 |
+
callback_kwargs = {}
|
| 621 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 622 |
+
callback_kwargs[k] = locals()[k]
|
| 623 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 624 |
+
|
| 625 |
+
latents = callback_outputs.pop("latents", latents)
|
| 626 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 627 |
+
negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
|
| 628 |
+
|
| 629 |
+
# call the callback, if provided
|
| 630 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 631 |
+
progress_bar.update()
|
| 632 |
+
if callback is not None and i % callback_steps == 0:
|
| 633 |
+
step_idx = i // getattr(self.scheduler, "order", 1)
|
| 634 |
+
callback(step_idx, t, latents)
|
| 635 |
+
|
| 636 |
+
if not output_type == "latent":
|
| 637 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
| 638 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
| 639 |
+
|
| 640 |
+
if needs_upcasting:
|
| 641 |
+
self.upcast_vae()
|
| 642 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
| 643 |
+
|
| 644 |
+
# unscale/denormalize the latents
|
| 645 |
+
# denormalize with the mean and std if available and not None
|
| 646 |
+
has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
|
| 647 |
+
has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
|
| 648 |
+
if has_latents_mean and has_latents_std:
|
| 649 |
+
latents_mean = (
|
| 650 |
+
torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
| 651 |
+
)
|
| 652 |
+
latents_std = (
|
| 653 |
+
torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
|
| 654 |
+
)
|
| 655 |
+
latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
|
| 656 |
+
else:
|
| 657 |
+
latents = latents / self.vae.config.scaling_factor
|
| 658 |
+
|
| 659 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
| 660 |
+
|
| 661 |
+
# cast back to fp16 if needed
|
| 662 |
+
if needs_upcasting:
|
| 663 |
+
self.vae.to(dtype=torch.float16)
|
| 664 |
+
else:
|
| 665 |
+
image = latents
|
| 666 |
+
|
| 667 |
+
if not output_type == "latent":
|
| 668 |
+
# apply watermark if available
|
| 669 |
+
if self.watermark is not None:
|
| 670 |
+
image = self.watermark.apply_watermark(image)
|
| 671 |
+
|
| 672 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
| 673 |
+
|
| 674 |
+
# Offload all models
|
| 675 |
+
self.maybe_free_model_hooks()
|
| 676 |
+
|
| 677 |
+
if not return_dict:
|
| 678 |
+
return (image,)
|
| 679 |
+
|
| 680 |
+
return StableDiffusionXLPipelineOutput(images=image)
|