yonishafir commited on
Commit
52141a6
·
verified ·
1 Parent(s): cc76133

Upload pipeline_bria_id_preservation.py

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