yonishafir commited on
Commit
e21dae7
·
verified ·
1 Parent(s): 89dc5e2

Create pipeline_stable_diffusion_xl_instantid.py

Browse files
pipeline_stable_diffusion_xl_instantid.py ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import os
21
+ import numpy as np
22
+ import PIL.Image
23
+ import torch
24
+ import torch.nn.functional as F
25
+
26
+ from diffusers.image_processor import PipelineImageInput
27
+
28
+ from diffusers.models import ControlNetModel
29
+
30
+ from diffusers.utils import (
31
+ deprecate,
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version
36
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
37
+
38
+ from diffusers import StableDiffusionXLControlNetPipeline
39
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
40
+ from diffusers.utils.import_utils import is_xformers_available
41
+
42
+ from ip_adapter.resampler import Resampler
43
+ from ip_adapter.utils import is_torch2_available
44
+
45
+ if is_torch2_available():
46
+ from ip_adapter.attention_processor import IPAttnProcessor2_0 as IPAttnProcessor, AttnProcessor2_0 as AttnProcessor
47
+ else:
48
+ from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessor
49
+
50
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
51
+
52
+
53
+ EXAMPLE_DOC_STRING = """
54
+ Examples:
55
+ ```py
56
+ >>> # !pip install opencv-python transformers accelerate insightface
57
+ >>> import diffusers
58
+ >>> from diffusers.utils import load_image
59
+ >>> from diffusers.models import ControlNetModel
60
+
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_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps
68
+
69
+ >>> # download 'antelopev2' under ./models
70
+ >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
71
+ >>> app.prepare(ctx_id=0, det_size=(640, 640))
72
+
73
+ >>> # download models under ./checkpoints
74
+ >>> face_adapter = f'./checkpoints/ip-adapter.bin'
75
+ >>> controlnet_path = f'./checkpoints/ControlNetModel'
76
+
77
+ >>> # load IdentityNet
78
+ >>> controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
79
+
80
+ >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
81
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
82
+ ... )
83
+ >>> pipe.cuda()
84
+
85
+ >>> # load adapter
86
+ >>> pipe.load_ip_adapter_instantid(face_adapter)
87
+
88
+ >>> prompt = "analog film photo of a man. faded film, desaturated, 35mm photo, grainy, vignette, vintage, Kodachrome, Lomography, stained, highly detailed, found footage, masterpiece, best quality"
89
+ >>> negative_prompt = "(lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch, deformed, mutated, cross-eyed, ugly, disfigured (lowres, low quality, worst quality:1.2), (text:1.2), watermark, painting, drawing, illustration, glitch,deformed, mutated, cross-eyed, ugly, disfigured"
90
+
91
+ >>> # load an image
92
+ >>> image = load_image("your-example.jpg")
93
+
94
+ >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1]
95
+ >>> face_emb = face_info['embedding']
96
+ >>> face_kps = draw_kps(face_image, face_info['kps'])
97
+
98
+ >>> pipe.set_ip_adapter_scale(0.8)
99
+
100
+ >>> # generate image
101
+ >>> image = pipe(
102
+ ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8
103
+ ... ).images[0]
104
+ ```
105
+ """
106
+
107
+ def draw_kps(image_pil, kps, rad=10, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
108
+
109
+ stickwidth = 4
110
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
111
+ kps = np.array(kps)
112
+
113
+ w, h = image_pil.size
114
+ out_img = np.zeros([h, w, 3])
115
+
116
+ for i in range(len(limbSeq)):
117
+ index = limbSeq[i]
118
+ color = color_list[index[0]]
119
+
120
+ x = kps[index][:, 0]
121
+ y = kps[index][:, 1]
122
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
123
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
124
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
125
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
126
+ out_img = (out_img * 0.6).astype(np.uint8)
127
+
128
+ for idx_kp, kp in enumerate(kps):
129
+ color = color_list[idx_kp]
130
+ x, y = kp
131
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
132
+
133
+ out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))
134
+ return out_img_pil
135
+
136
+ class StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline):
137
+
138
+ def cuda(self, dtype=torch.float16, use_xformers=False):
139
+ self.to('cuda', dtype)
140
+
141
+ if hasattr(self, 'image_proj_model'):
142
+ self.image_proj_model.to(self.unet.device).to(self.unet.dtype)
143
+
144
+ if use_xformers:
145
+ if is_xformers_available():
146
+ import xformers
147
+ from packaging import version
148
+
149
+ xformers_version = version.parse(xformers.__version__)
150
+ if xformers_version == version.parse("0.0.16"):
151
+ logger.warn(
152
+ "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
153
+ )
154
+ self.enable_xformers_memory_efficient_attention()
155
+ else:
156
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
157
+
158
+ def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=1):
159
+ if type(model_ckpt)==list:
160
+ model_ckpt_instant=model_ckpt[0]
161
+ else:
162
+ model_ckpt_instant = model_ckpt
163
+
164
+ self.set_image_proj_model(model_ckpt_instant, image_emb_dim, num_tokens)
165
+
166
+ if type(model_ckpt)==list:
167
+ dir_models = os.path.dirname(model_ckpt[0])
168
+ weight_name = [os.path.basename(m) for m in model_ckpt]
169
+ else:
170
+ dir_models = os.path.dirname(model_ckpt)
171
+ weight_name = os.path.basename(model_ckpt)
172
+
173
+ if self.use_native_ip_adapter:
174
+ self.load_ip_adapter(
175
+ dir_models,
176
+ # subfolder="sdxl_models",
177
+ subfolder=None,
178
+ # weight_name=["ip-adapter-instant-id.bin", "ip-adapter-plus_sdxl_vit-h.bin"],
179
+ weight_name = weight_name,#,"ip-adapter-instant-id.bin",
180
+ image_encoder_folder=None,
181
+ )
182
+ self.unet.encoder_hid_proj.image_projection_layers[0] = self.image_proj_model
183
+ else:
184
+ self.set_ip_adapter(model_ckpt_instant, num_tokens, scale)
185
+
186
+ def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16):
187
+
188
+ image_proj_model = Resampler(
189
+ dim=1280,
190
+ depth=4,
191
+ dim_head=64,
192
+ heads=20,
193
+ num_queries=num_tokens,
194
+ embedding_dim=image_emb_dim,
195
+ output_dim=self.unet.config.cross_attention_dim,
196
+ ff_mult=4,
197
+ )
198
+
199
+ image_proj_model.eval()
200
+
201
+ self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype)
202
+ state_dict = torch.load(model_ckpt, map_location="cpu")
203
+ if 'image_proj' in state_dict:
204
+ state_dict = state_dict["image_proj"]
205
+ self.image_proj_model.load_state_dict(state_dict)
206
+
207
+ self.image_proj_model_in_features = image_emb_dim
208
+
209
+ def set_ip_adapter(self, model_ckpt, num_tokens, scale):
210
+
211
+ unet = self.unet
212
+ attn_procs = {}
213
+ for name in unet.attn_processors.keys():
214
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
215
+ if name.startswith("mid_block"):
216
+ hidden_size = unet.config.block_out_channels[-1]
217
+ elif name.startswith("up_blocks"):
218
+ block_id = int(name[len("up_blocks.")])
219
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
220
+ elif name.startswith("down_blocks"):
221
+ block_id = int(name[len("down_blocks.")])
222
+ hidden_size = unet.config.block_out_channels[block_id]
223
+ if cross_attention_dim is None:
224
+ attn_procs[name] = AttnProcessor().to(unet.device, dtype=unet.dtype)
225
+ else:
226
+ attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size,
227
+ cross_attention_dim=cross_attention_dim,
228
+ scale=scale,
229
+ num_tokens=num_tokens).to(unet.device, dtype=unet.dtype)
230
+ unet.set_attn_processor(attn_procs)
231
+
232
+ state_dict = torch.load(model_ckpt, map_location="cpu")
233
+ ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
234
+ if 'ip_adapter' in state_dict:
235
+ state_dict = state_dict['ip_adapter']
236
+ ip_layers.load_state_dict(state_dict)
237
+
238
+
239
+
240
+ def set_ip_adapter_scale(self, scale):
241
+ if self.use_native_ip_adapter:
242
+ super().set_ip_adapter_scale(scale)
243
+ else:
244
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
245
+ for attn_processor in unet.attn_processors.values():
246
+ if isinstance(attn_processor, IPAttnProcessor):
247
+ attn_processor.scale = scale
248
+
249
+ def _encode_prompt_image_emb(self, prompt_image_emb, device, num_images_per_prompt, dtype, do_classifier_free_guidance):
250
+
251
+ if isinstance(prompt_image_emb, torch.Tensor):
252
+ prompt_image_emb = prompt_image_emb.clone().detach()
253
+ else:
254
+ prompt_image_emb = torch.tensor(prompt_image_emb)
255
+
256
+ prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features])
257
+
258
+ if do_classifier_free_guidance:
259
+ prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0)
260
+ else:
261
+ prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
262
+
263
+ prompt_image_emb = prompt_image_emb.to(device=self.image_proj_model.latents.device,
264
+ dtype=self.image_proj_model.latents.dtype)
265
+
266
+ orig_embeds = prompt_image_emb
267
+ prompt_image_emb = self.image_proj_model(prompt_image_emb)
268
+
269
+ bs_embed, seq_len, _ = prompt_image_emb.shape
270
+ prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
271
+ prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
272
+
273
+ return prompt_image_emb.to(device=device, dtype=dtype), orig_embeds.to(device=device, dtype=dtype)
274
+
275
+ @torch.no_grad()
276
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
277
+ def __call__(
278
+ self,
279
+ prompt: Union[str, List[str]] = None,
280
+ prompt_2: Optional[Union[str, List[str]]] = None,
281
+ image: PipelineImageInput = None,
282
+ height: Optional[int] = None,
283
+ width: Optional[int] = None,
284
+ num_inference_steps: int = 50,
285
+ guidance_scale: float = 5.0,
286
+ negative_prompt: Optional[Union[str, List[str]]] = None,
287
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
288
+ num_images_per_prompt: Optional[int] = 1,
289
+ eta: float = 0.0,
290
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
291
+ latents: Optional[torch.FloatTensor] = None,
292
+ prompt_embeds: Optional[torch.FloatTensor] = None,
293
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
294
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
295
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
296
+ image_embeds: Optional[torch.FloatTensor] = None,
297
+ output_type: Optional[str] = "pil",
298
+ return_dict: bool = True,
299
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
300
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
301
+ guess_mode: bool = False,
302
+ control_guidance_start: Union[float, List[float]] = 0.0,
303
+ control_guidance_end: Union[float, List[float]] = 1.0,
304
+ original_size: Tuple[int, int] = None,
305
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
306
+ target_size: Tuple[int, int] = None,
307
+ negative_original_size: Optional[Tuple[int, int]] = None,
308
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
309
+ negative_target_size: Optional[Tuple[int, int]] = None,
310
+ clip_skip: Optional[int] = None,
311
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
312
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
313
+ visual_prompt_embds=None,
314
+
315
+ # IP adapter
316
+ ip_adapter_scale=None,
317
+
318
+ **kwargs,
319
+ ):
320
+ r"""
321
+ The call function to the pipeline for generation.
322
+
323
+ Args:
324
+ prompt (`str` or `List[str]`, *optional*):
325
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
326
+ prompt_2 (`str` or `List[str]`, *optional*):
327
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
328
+ used in both text-encoders.
329
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
330
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
331
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
332
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
333
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
334
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
335
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
336
+ input to a single ControlNet.
337
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
338
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
339
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
340
+ and checkpoints that are not specifically fine-tuned on low resolutions.
341
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
342
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
343
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
344
+ and checkpoints that are not specifically fine-tuned on low resolutions.
345
+ num_inference_steps (`int`, *optional*, defaults to 50):
346
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
347
+ expense of slower inference.
348
+ guidance_scale (`float`, *optional*, defaults to 5.0):
349
+ A higher guidance scale value encourages the model to generate images closely linked to the text
350
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
351
+ negative_prompt (`str` or `List[str]`, *optional*):
352
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
353
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
354
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
355
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
356
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
357
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
358
+ The number of images to generate per prompt.
359
+ eta (`float`, *optional*, defaults to 0.0):
360
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
361
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
362
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
363
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
364
+ generation deterministic.
365
+ latents (`torch.FloatTensor`, *optional*):
366
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
367
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
368
+ tensor is generated by sampling using the supplied random `generator`.
369
+ prompt_embeds (`torch.FloatTensor`, *optional*):
370
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
371
+ provided, text embeddings are generated from the `prompt` input argument.
372
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
373
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
374
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
375
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
376
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
377
+ not provided, pooled text embeddings are generated from `prompt` input argument.
378
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
379
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
380
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
381
+ argument.
382
+ image_embeds (`torch.FloatTensor`, *optional*):
383
+ Pre-generated image embeddings.
384
+ output_type (`str`, *optional*, defaults to `"pil"`):
385
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
386
+ return_dict (`bool`, *optional*, defaults to `True`):
387
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
388
+ plain tuple.
389
+ cross_attention_kwargs (`dict`, *optional*):
390
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
391
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
392
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
393
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
394
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
395
+ the corresponding scale as a list.
396
+ guess_mode (`bool`, *optional*, defaults to `False`):
397
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
398
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
399
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
400
+ The percentage of total steps at which the ControlNet starts applying.
401
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
402
+ The percentage of total steps at which the ControlNet stops applying.
403
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
404
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
405
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
406
+ explained in section 2.2 of
407
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
408
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
409
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
410
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
411
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
412
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
413
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
414
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
415
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
416
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
417
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
418
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
419
+ micro-conditioning as explained in section 2.2 of
420
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
421
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
422
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
423
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
424
+ micro-conditioning as explained in section 2.2 of
425
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
426
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
427
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
428
+ To negatively condition the generation process based on a target image resolution. It should be as same
429
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
430
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
431
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
432
+ clip_skip (`int`, *optional*):
433
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
434
+ the output of the pre-final layer will be used for computing the prompt embeddings.
435
+ callback_on_step_end (`Callable`, *optional*):
436
+ A function that calls at the end of each denoising steps during the inference. The function is called
437
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
438
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
439
+ `callback_on_step_end_tensor_inputs`.
440
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
441
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
442
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
443
+ `._callback_tensor_inputs` attribute of your pipeine class.
444
+
445
+ Examples:
446
+
447
+ Returns:
448
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
449
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
450
+ otherwise a `tuple` is returned containing the output images.
451
+ """
452
+
453
+ callback = kwargs.pop("callback", None)
454
+ callback_steps = kwargs.pop("callback_steps", None)
455
+
456
+ if callback is not None:
457
+ deprecate(
458
+ "callback",
459
+ "1.0.0",
460
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
461
+ )
462
+ if callback_steps is not None:
463
+ deprecate(
464
+ "callback_steps",
465
+ "1.0.0",
466
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
467
+ )
468
+
469
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
470
+
471
+ # align format for control guidance
472
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
473
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
474
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
475
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
476
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
477
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
478
+ control_guidance_start, control_guidance_end = (
479
+ mult * [control_guidance_start],
480
+ mult * [control_guidance_end],
481
+ )
482
+
483
+ # 0. set ip_adapter_scale
484
+ if ip_adapter_scale is not None:
485
+ self.set_ip_adapter_scale(ip_adapter_scale)
486
+
487
+ # 1. Check inputs. Raise error if not correct
488
+ self.check_inputs(
489
+ prompt=prompt,
490
+ prompt_2=prompt_2,
491
+ image=image,
492
+ callback_steps=callback_steps,
493
+ negative_prompt=negative_prompt,
494
+ negative_prompt_2=negative_prompt_2,
495
+ prompt_embeds=prompt_embeds,
496
+ negative_prompt_embeds=negative_prompt_embeds,
497
+ pooled_prompt_embeds=pooled_prompt_embeds,
498
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
499
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
500
+ control_guidance_start=control_guidance_start,
501
+ control_guidance_end=control_guidance_end,
502
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
503
+ )
504
+
505
+ self._guidance_scale = guidance_scale
506
+ self._clip_skip = clip_skip
507
+ self._cross_attention_kwargs = cross_attention_kwargs
508
+
509
+ # 2. Define call parameters
510
+ if prompt is not None and isinstance(prompt, str):
511
+ batch_size = 1
512
+ elif prompt is not None and isinstance(prompt, list):
513
+ batch_size = len(prompt)
514
+ else:
515
+ batch_size = prompt_embeds.shape[0]
516
+
517
+ device = self._execution_device
518
+
519
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
520
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
521
+
522
+ global_pool_conditions = (
523
+ controlnet.config.global_pool_conditions
524
+ if isinstance(controlnet, ControlNetModel)
525
+ else controlnet.nets[0].config.global_pool_conditions
526
+ )
527
+ guess_mode = guess_mode or global_pool_conditions
528
+
529
+ # 3.1 Encode input prompt
530
+ text_encoder_lora_scale = (
531
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
532
+ )
533
+ (
534
+ prompt_embeds,
535
+ negative_prompt_embeds,
536
+ pooled_prompt_embeds,
537
+ negative_pooled_prompt_embeds,
538
+ ) = self.encode_prompt(
539
+ prompt,
540
+ prompt_2,
541
+ device,
542
+ num_images_per_prompt,
543
+ self.do_classifier_free_guidance,
544
+ negative_prompt,
545
+ negative_prompt_2,
546
+ prompt_embeds=prompt_embeds,
547
+ negative_prompt_embeds=negative_prompt_embeds,
548
+ pooled_prompt_embeds=pooled_prompt_embeds,
549
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
550
+ lora_scale=text_encoder_lora_scale,
551
+ clip_skip=self.clip_skip,
552
+ )
553
+
554
+ # 3.2 Encode image prompt
555
+ prompt_image_emb , image_embeds = self._encode_prompt_image_emb(image_embeds,
556
+ device,
557
+ num_images_per_prompt,
558
+ self.unet.dtype,
559
+ self.do_classifier_free_guidance)
560
+
561
+ # 4. Prepare image
562
+ if isinstance(controlnet, ControlNetModel):
563
+ image = self.prepare_image(
564
+ image=image,
565
+ width=width,
566
+ height=height,
567
+ batch_size=batch_size * num_images_per_prompt,
568
+ num_images_per_prompt=num_images_per_prompt,
569
+ device=device,
570
+ dtype=controlnet.dtype,
571
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
572
+ guess_mode=guess_mode,
573
+ )
574
+ height, width = image.shape[-2:]
575
+ elif isinstance(controlnet, MultiControlNetModel):
576
+ images = []
577
+
578
+ for image_ in image:
579
+ image_ = self.prepare_image(
580
+ image=image_,
581
+ width=width,
582
+ height=height,
583
+ batch_size=batch_size * num_images_per_prompt,
584
+ num_images_per_prompt=num_images_per_prompt,
585
+ device=device,
586
+ dtype=controlnet.dtype,
587
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
588
+ guess_mode=guess_mode,
589
+ )
590
+
591
+ images.append(image_)
592
+
593
+ image = images
594
+ height, width = image[0].shape[-2:]
595
+ else:
596
+ assert False
597
+
598
+ # 5. Prepare timesteps
599
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
600
+ timesteps = self.scheduler.timesteps
601
+ self._num_timesteps = len(timesteps)
602
+
603
+ # 6. Prepare latent variables
604
+ num_channels_latents = self.unet.config.in_channels
605
+ latents = self.prepare_latents(
606
+ batch_size * num_images_per_prompt,
607
+ num_channels_latents,
608
+ height,
609
+ width,
610
+ prompt_embeds.dtype,
611
+ device,
612
+ generator,
613
+ latents,
614
+ )
615
+
616
+ # 6.5 Optionally get Guidance Scale Embedding
617
+ timestep_cond = None
618
+ if self.unet.config.time_cond_proj_dim is not None:
619
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
620
+ timestep_cond = self.get_guidance_scale_embedding(
621
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
622
+ ).to(device=device, dtype=latents.dtype)
623
+
624
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
625
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
626
+
627
+ # 7.1 Create tensor stating which controlnets to keep
628
+ controlnet_keep = []
629
+ for i in range(len(timesteps)):
630
+ keeps = [
631
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
632
+ for s, e in zip(control_guidance_start, control_guidance_end)
633
+ ]
634
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
635
+
636
+ # 7.2 Prepare added time ids & embeddings
637
+ if isinstance(image, list):
638
+ original_size = original_size or image[0].shape[-2:]
639
+ else:
640
+ original_size = original_size or image.shape[-2:]
641
+ target_size = target_size or (height, width)
642
+
643
+ add_text_embeds = pooled_prompt_embeds
644
+ if self.text_encoder_2 is None:
645
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
646
+ else:
647
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
648
+
649
+ add_time_ids = self._get_add_time_ids(
650
+ original_size,
651
+ crops_coords_top_left,
652
+ target_size,
653
+ dtype=prompt_embeds.dtype,
654
+ text_encoder_projection_dim=text_encoder_projection_dim,
655
+ )
656
+
657
+ if negative_original_size is not None and negative_target_size is not None:
658
+ negative_add_time_ids = self._get_add_time_ids(
659
+ negative_original_size,
660
+ negative_crops_coords_top_left,
661
+ negative_target_size,
662
+ dtype=prompt_embeds.dtype,
663
+ text_encoder_projection_dim=text_encoder_projection_dim,
664
+ )
665
+ else:
666
+ negative_add_time_ids = add_time_ids
667
+
668
+ if self.do_classifier_free_guidance:
669
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
670
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
671
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
672
+
673
+ prompt_embeds = prompt_embeds.to(device)
674
+ add_text_embeds = add_text_embeds.to(device)
675
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
676
+ # encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
677
+
678
+ # 8. Denoising loop
679
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
680
+ is_unet_compiled = is_compiled_module(self.unet)
681
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
682
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
683
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
684
+ for i, t in enumerate(timesteps):
685
+ # Relevant thread:
686
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
687
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
688
+ torch._inductor.cudagraph_mark_step_begin()
689
+ # expand the latents if we are doing classifier free guidance
690
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
691
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
692
+
693
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
694
+
695
+ new_conditions = {k:v for k,v in added_cond_kwargs.items()}
696
+ # visual_prompt_embds = image_embeds #torch.from_numpy(image_embeds).repeat(1,1,1).to(device=self.unet.device,dtype = self.unet.dtype)
697
+ # if self.do_classifier_free_guidance:
698
+ # visual_prompt_embds = torch.concat([torch.zeros_like(image_embeds),image_embeds])
699
+ if visual_prompt_embds is not None:
700
+ new_conditions['image_embeds']= [image_embeds.unsqueeze(dim=1),visual_prompt_embds]
701
+ else:
702
+ new_conditions['image_embeds']= [image_embeds.unsqueeze(dim=1)]
703
+
704
+
705
+ # controlnet(s) inference
706
+ if guess_mode and self.do_classifier_free_guidance:
707
+ # Infer ControlNet only for the conditional batch.
708
+ control_model_input = latents
709
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
710
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
711
+ controlnet_added_cond_kwargs = {
712
+ "text_embeds": add_text_embeds.chunk(2)[1],
713
+ "time_ids": add_time_ids.chunk(2)[1],
714
+ }
715
+ else:
716
+ control_model_input = latent_model_input
717
+ controlnet_prompt_embeds = prompt_embeds
718
+ controlnet_added_cond_kwargs = added_cond_kwargs
719
+
720
+ if isinstance(controlnet_keep[i], list):
721
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
722
+ else:
723
+ controlnet_cond_scale = controlnet_conditioning_scale
724
+ if isinstance(controlnet_cond_scale, list):
725
+ controlnet_cond_scale = controlnet_cond_scale[0]
726
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
727
+
728
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
729
+ control_model_input,
730
+ t,
731
+ encoder_hidden_states=prompt_image_emb,
732
+ controlnet_cond=image,
733
+ conditioning_scale=cond_scale,
734
+ guess_mode=guess_mode,
735
+ added_cond_kwargs=controlnet_added_cond_kwargs,
736
+ return_dict=False,
737
+ )
738
+
739
+ if guess_mode and self.do_classifier_free_guidance:
740
+ # Infered ControlNet only for the conditional batch.
741
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
742
+ # add 0 to the unconditional batch to keep it unchanged.
743
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
744
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
745
+ # predict the noise residual
746
+
747
+
748
+ if self.use_native_ip_adapter:
749
+ encoder_embeds =prompt_embeds
750
+ conds = new_conditions
751
+ else:
752
+ encoder_embeds = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
753
+ conds = added_cond_kwargs
754
+
755
+
756
+ noise_pred = self.unet(
757
+ latent_model_input,
758
+ t,
759
+ # encoder_hidden_states=prompt_embeds,
760
+ # image_embeds=prompt_image_emb,
761
+ encoder_hidden_states= encoder_embeds,
762
+ timestep_cond=timestep_cond,
763
+ cross_attention_kwargs=self.cross_attention_kwargs,
764
+ down_block_additional_residuals=down_block_res_samples,
765
+ mid_block_additional_residual=mid_block_res_sample,
766
+ # added_cond_kwargs=new_conditions,#added_cond_kwargs,
767
+ added_cond_kwargs= conds,
768
+ return_dict=False,
769
+ )[0]
770
+
771
+ # perform guidance
772
+ if self.do_classifier_free_guidance:
773
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
774
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
775
+
776
+ # compute the previous noisy sample x_t -> x_t-1
777
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
778
+
779
+ if callback_on_step_end is not None:
780
+ callback_kwargs = {}
781
+ for k in callback_on_step_end_tensor_inputs:
782
+ callback_kwargs[k] = locals()[k]
783
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
784
+
785
+ latents = callback_outputs.pop("latents", latents)
786
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
787
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
788
+
789
+ # call the callback, if provided
790
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
791
+ progress_bar.update()
792
+ if callback is not None and i % callback_steps == 0:
793
+ step_idx = i // getattr(self.scheduler, "order", 1)
794
+ callback(step_idx, t, latents)
795
+
796
+ if not output_type == "latent":
797
+ # make sure the VAE is in float32 mode, as it overflows in float16
798
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
799
+
800
+ if needs_upcasting:
801
+ self.upcast_vae()
802
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
803
+
804
+ # unscale/denormalize the latents
805
+ # denormalize with the mean and std if available and not None
806
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
807
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
808
+ if has_latents_mean and has_latents_std:
809
+ latents_mean = (
810
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
811
+ )
812
+ latents_std = (
813
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
814
+ )
815
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
816
+ else:
817
+ latents = latents / self.vae.config.scaling_factor
818
+
819
+ image = self.vae.decode(latents, return_dict=False)[0]
820
+
821
+ # cast back to fp16 if needed
822
+ if needs_upcasting:
823
+ self.vae.to(dtype=torch.float16)
824
+ else:
825
+ image = latents
826
+
827
+ if not output_type == "latent":
828
+ # apply watermark if available
829
+ if self.watermark is not None:
830
+ image = self.watermark.apply_watermark(image)
831
+
832
+ image = self.image_processor.postprocess(image, output_type=output_type)
833
+
834
+ # Offload all models
835
+ self.maybe_free_model_hooks()
836
+
837
+ if not return_dict:
838
+ return (image,)
839
+
840
+ return StableDiffusionXLPipelineOutput(images=image)