philgram commited on
Commit
65f1391
·
verified ·
1 Parent(s): ac635b7

Upload 17 files

Browse files
checkpoints/ControlNetModel/config.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "ControlNetModel",
3
+ "_diffusers_version": "0.21.2",
4
+ "_name_or_path": "/mnt/nj-aigc/usr/guiwan/workspace/diffusion_output/face_xl_ipc_v4_2_XiezhenAnimeForeigner/checkpoint-150000/ControlNetModel",
5
+ "act_fn": "silu",
6
+ "addition_embed_type": "text_time",
7
+ "addition_embed_type_num_heads": 64,
8
+ "addition_time_embed_dim": 256,
9
+ "attention_head_dim": [
10
+ 5,
11
+ 10,
12
+ 20
13
+ ],
14
+ "block_out_channels": [
15
+ 320,
16
+ 640,
17
+ 1280
18
+ ],
19
+ "class_embed_type": null,
20
+ "conditioning_channels": 3,
21
+ "conditioning_embedding_out_channels": [
22
+ 16,
23
+ 32,
24
+ 96,
25
+ 256
26
+ ],
27
+ "controlnet_conditioning_channel_order": "rgb",
28
+ "cross_attention_dim": 2048,
29
+ "down_block_types": [
30
+ "DownBlock2D",
31
+ "CrossAttnDownBlock2D",
32
+ "CrossAttnDownBlock2D"
33
+ ],
34
+ "downsample_padding": 1,
35
+ "encoder_hid_dim": null,
36
+ "encoder_hid_dim_type": null,
37
+ "flip_sin_to_cos": true,
38
+ "freq_shift": 0,
39
+ "global_pool_conditions": false,
40
+ "in_channels": 4,
41
+ "layers_per_block": 2,
42
+ "mid_block_scale_factor": 1,
43
+ "norm_eps": 1e-05,
44
+ "norm_num_groups": 32,
45
+ "num_attention_heads": null,
46
+ "num_class_embeds": null,
47
+ "only_cross_attention": false,
48
+ "projection_class_embeddings_input_dim": 2816,
49
+ "resnet_time_scale_shift": "default",
50
+ "transformer_layers_per_block": [
51
+ 1,
52
+ 2,
53
+ 10
54
+ ],
55
+ "upcast_attention": null,
56
+ "use_linear_projection": true
57
+ }
checkpoints/ControlNetModel/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8127be9f174101ebdafee9964d856b49b634435cf6daa396d3f593cf0bbbb05
3
+ size 2502139136
checkpoints/ip-adapter.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02b3618e36d803784166660520098089a81388e61a93ef8002aa79a5b1c546e1
3
+ size 1691134141
checkpoints/pytorch_lora_weights.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a764e6859b6e04047cd761c08ff0cee96413a8e004c9f07707530cd776b19141
3
+ size 393855224
controlnet_util.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from PIL import Image
4
+ from controlnet_aux import OpenposeDetector
5
+ from src.dependencies.instantid.model_util import get_torch_device
6
+ import cv2
7
+
8
+
9
+ from transformers import DPTImageProcessor, DPTForDepthEstimation
10
+
11
+ device = get_torch_device()
12
+ depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)
13
+ feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")
14
+ openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
15
+
16
+ def get_depth_map(image):
17
+ image = feature_extractor(images=image, return_tensors="pt").pixel_values.to("cuda")
18
+ with torch.no_grad(), torch.autocast("cuda"):
19
+ depth_map = depth_estimator(image).predicted_depth
20
+
21
+ depth_map = torch.nn.functional.interpolate(
22
+ depth_map.unsqueeze(1),
23
+ size=(1024, 1024),
24
+ mode="bicubic",
25
+ align_corners=False,
26
+ )
27
+ depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
28
+ depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
29
+ depth_map = (depth_map - depth_min) / (depth_max - depth_min)
30
+ image = torch.cat([depth_map] * 3, dim=1)
31
+
32
+ image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
33
+ image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
34
+ return image
35
+
36
+ def get_canny_image(image, t1=100, t2=200):
37
+ image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
38
+ edges = cv2.Canny(image, t1, t2)
39
+ return Image.fromarray(edges, "L")
download_models.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import hf_hub_download
2
+ import gdown
3
+ import os
4
+
5
+ # download models
6
+ hf_hub_download(
7
+ repo_id="InstantX/InstantID",
8
+ filename="ControlNetModel/config.json",
9
+ local_dir="./checkpoints",
10
+ )
11
+ hf_hub_download(
12
+ repo_id="InstantX/InstantID",
13
+ filename="ControlNetModel/diffusion_pytorch_model.safetensors",
14
+ local_dir="./checkpoints",
15
+ )
16
+ hf_hub_download(
17
+ repo_id="InstantX/InstantID", filename="ip-adapter.bin", local_dir="./checkpoints"
18
+ )
19
+ hf_hub_download(
20
+ repo_id="latent-consistency/lcm-lora-sdxl",
21
+ filename="pytorch_lora_weights.safetensors",
22
+ local_dir="./checkpoints",
23
+ )
24
+ # download antelopev2
25
+ gdown.download(url="https://drive.google.com/file/d/18wEUfMNohBJ4K3Ly5wpTejPfDzp-8fI8/view?usp=sharing", output="./models/", quiet=False, fuzzy=True)
26
+ # unzip antelopev2.zip
27
+ os.system("unzip ./models/antelopev2.zip -d ./models/")
ip_adapter/attention_processor.py ADDED
@@ -0,0 +1,447 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py
2
+ import torch
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+
6
+ try:
7
+ import xformers
8
+ import xformers.ops
9
+ xformers_available = True
10
+ except Exception as e:
11
+ xformers_available = False
12
+
13
+ class RegionControler(object):
14
+ def __init__(self) -> None:
15
+ self.prompt_image_conditioning = []
16
+ region_control = RegionControler()
17
+
18
+ class AttnProcessor(nn.Module):
19
+ r"""
20
+ Default processor for performing attention-related computations.
21
+ """
22
+ def __init__(
23
+ self,
24
+ hidden_size=None,
25
+ cross_attention_dim=None,
26
+ ):
27
+ super().__init__()
28
+
29
+ def forward(
30
+ self,
31
+ attn,
32
+ hidden_states,
33
+ encoder_hidden_states=None,
34
+ attention_mask=None,
35
+ temb=None,
36
+ ):
37
+ residual = hidden_states
38
+
39
+ if attn.spatial_norm is not None:
40
+ hidden_states = attn.spatial_norm(hidden_states, temb)
41
+
42
+ input_ndim = hidden_states.ndim
43
+
44
+ if input_ndim == 4:
45
+ batch_size, channel, height, width = hidden_states.shape
46
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
47
+
48
+ batch_size, sequence_length, _ = (
49
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
50
+ )
51
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
52
+
53
+ if attn.group_norm is not None:
54
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
55
+
56
+ query = attn.to_q(hidden_states)
57
+
58
+ if encoder_hidden_states is None:
59
+ encoder_hidden_states = hidden_states
60
+ elif attn.norm_cross:
61
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
62
+
63
+ key = attn.to_k(encoder_hidden_states)
64
+ value = attn.to_v(encoder_hidden_states)
65
+
66
+ query = attn.head_to_batch_dim(query)
67
+ key = attn.head_to_batch_dim(key)
68
+ value = attn.head_to_batch_dim(value)
69
+
70
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
71
+ hidden_states = torch.bmm(attention_probs, value)
72
+ hidden_states = attn.batch_to_head_dim(hidden_states)
73
+
74
+ # linear proj
75
+ hidden_states = attn.to_out[0](hidden_states)
76
+ # dropout
77
+ hidden_states = attn.to_out[1](hidden_states)
78
+
79
+ if input_ndim == 4:
80
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
81
+
82
+ if attn.residual_connection:
83
+ hidden_states = hidden_states + residual
84
+
85
+ hidden_states = hidden_states / attn.rescale_output_factor
86
+
87
+ return hidden_states
88
+
89
+
90
+ class IPAttnProcessor(nn.Module):
91
+ r"""
92
+ Attention processor for IP-Adapater.
93
+ Args:
94
+ hidden_size (`int`):
95
+ The hidden size of the attention layer.
96
+ cross_attention_dim (`int`):
97
+ The number of channels in the `encoder_hidden_states`.
98
+ scale (`float`, defaults to 1.0):
99
+ the weight scale of image prompt.
100
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
101
+ The context length of the image features.
102
+ """
103
+
104
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
105
+ super().__init__()
106
+
107
+ self.hidden_size = hidden_size
108
+ self.cross_attention_dim = cross_attention_dim
109
+ self.scale = scale
110
+ self.num_tokens = num_tokens
111
+
112
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
113
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
114
+
115
+ def forward(
116
+ self,
117
+ attn,
118
+ hidden_states,
119
+ encoder_hidden_states=None,
120
+ attention_mask=None,
121
+ temb=None,
122
+ ):
123
+ residual = hidden_states
124
+
125
+ if attn.spatial_norm is not None:
126
+ hidden_states = attn.spatial_norm(hidden_states, temb)
127
+
128
+ input_ndim = hidden_states.ndim
129
+
130
+ if input_ndim == 4:
131
+ batch_size, channel, height, width = hidden_states.shape
132
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
133
+
134
+ batch_size, sequence_length, _ = (
135
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
136
+ )
137
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
138
+
139
+ if attn.group_norm is not None:
140
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
141
+
142
+ query = attn.to_q(hidden_states)
143
+
144
+ if encoder_hidden_states is None:
145
+ encoder_hidden_states = hidden_states
146
+ else:
147
+ # get encoder_hidden_states, ip_hidden_states
148
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
149
+ encoder_hidden_states, ip_hidden_states = encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :]
150
+ if attn.norm_cross:
151
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
152
+
153
+ key = attn.to_k(encoder_hidden_states)
154
+ value = attn.to_v(encoder_hidden_states)
155
+
156
+ query = attn.head_to_batch_dim(query)
157
+ key = attn.head_to_batch_dim(key)
158
+ value = attn.head_to_batch_dim(value)
159
+
160
+ if xformers_available:
161
+ hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
162
+ else:
163
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
164
+ hidden_states = torch.bmm(attention_probs, value)
165
+ hidden_states = attn.batch_to_head_dim(hidden_states)
166
+
167
+ # for ip-adapter
168
+ ip_key = self.to_k_ip(ip_hidden_states)
169
+ ip_value = self.to_v_ip(ip_hidden_states)
170
+
171
+ ip_key = attn.head_to_batch_dim(ip_key)
172
+ ip_value = attn.head_to_batch_dim(ip_value)
173
+
174
+ if xformers_available:
175
+ ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None)
176
+ else:
177
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
178
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
179
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
180
+
181
+ # region control
182
+ if len(region_control.prompt_image_conditioning) == 1:
183
+ region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)
184
+ if region_mask is not None:
185
+ h, w = region_mask.shape[:2]
186
+ ratio = (h * w / query.shape[1]) ** 0.5
187
+ mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])
188
+ else:
189
+ mask = torch.ones_like(ip_hidden_states)
190
+ ip_hidden_states = ip_hidden_states * mask
191
+
192
+ hidden_states = hidden_states + self.scale * ip_hidden_states
193
+
194
+ # linear proj
195
+ hidden_states = attn.to_out[0](hidden_states)
196
+ # dropout
197
+ hidden_states = attn.to_out[1](hidden_states)
198
+
199
+ if input_ndim == 4:
200
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
201
+
202
+ if attn.residual_connection:
203
+ hidden_states = hidden_states + residual
204
+
205
+ hidden_states = hidden_states / attn.rescale_output_factor
206
+
207
+ return hidden_states
208
+
209
+
210
+ def _memory_efficient_attention_xformers(self, query, key, value, attention_mask):
211
+ # TODO attention_mask
212
+ query = query.contiguous()
213
+ key = key.contiguous()
214
+ value = value.contiguous()
215
+ hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask)
216
+ # hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
217
+ return hidden_states
218
+
219
+
220
+ class AttnProcessor2_0(torch.nn.Module):
221
+ r"""
222
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
223
+ """
224
+ def __init__(
225
+ self,
226
+ hidden_size=None,
227
+ cross_attention_dim=None,
228
+ ):
229
+ super().__init__()
230
+ if not hasattr(F, "scaled_dot_product_attention"):
231
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
232
+
233
+ def forward(
234
+ self,
235
+ attn,
236
+ hidden_states,
237
+ encoder_hidden_states=None,
238
+ attention_mask=None,
239
+ temb=None,
240
+ ):
241
+ residual = hidden_states
242
+
243
+ if attn.spatial_norm is not None:
244
+ hidden_states = attn.spatial_norm(hidden_states, temb)
245
+
246
+ input_ndim = hidden_states.ndim
247
+
248
+ if input_ndim == 4:
249
+ batch_size, channel, height, width = hidden_states.shape
250
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
251
+
252
+ batch_size, sequence_length, _ = (
253
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
254
+ )
255
+
256
+ if attention_mask is not None:
257
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
258
+ # scaled_dot_product_attention expects attention_mask shape to be
259
+ # (batch, heads, source_length, target_length)
260
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
261
+
262
+ if attn.group_norm is not None:
263
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
264
+
265
+ query = attn.to_q(hidden_states)
266
+
267
+ if encoder_hidden_states is None:
268
+ encoder_hidden_states = hidden_states
269
+ elif attn.norm_cross:
270
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
271
+
272
+ key = attn.to_k(encoder_hidden_states)
273
+ value = attn.to_v(encoder_hidden_states)
274
+
275
+ inner_dim = key.shape[-1]
276
+ head_dim = inner_dim // attn.heads
277
+
278
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
279
+
280
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
281
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
282
+
283
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
284
+ # TODO: add support for attn.scale when we move to Torch 2.1
285
+ hidden_states = F.scaled_dot_product_attention(
286
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
287
+ )
288
+
289
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
290
+ hidden_states = hidden_states.to(query.dtype)
291
+
292
+ # linear proj
293
+ hidden_states = attn.to_out[0](hidden_states)
294
+ # dropout
295
+ hidden_states = attn.to_out[1](hidden_states)
296
+
297
+ if input_ndim == 4:
298
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
299
+
300
+ if attn.residual_connection:
301
+ hidden_states = hidden_states + residual
302
+
303
+ hidden_states = hidden_states / attn.rescale_output_factor
304
+
305
+ return hidden_states
306
+
307
+ class IPAttnProcessor2_0(torch.nn.Module):
308
+ r"""
309
+ Attention processor for IP-Adapater for PyTorch 2.0.
310
+ Args:
311
+ hidden_size (`int`):
312
+ The hidden size of the attention layer.
313
+ cross_attention_dim (`int`):
314
+ The number of channels in the `encoder_hidden_states`.
315
+ scale (`float`, defaults to 1.0):
316
+ the weight scale of image prompt.
317
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
318
+ The context length of the image features.
319
+ """
320
+
321
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
322
+ super().__init__()
323
+
324
+ if not hasattr(F, "scaled_dot_product_attention"):
325
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
326
+
327
+ self.hidden_size = hidden_size
328
+ self.cross_attention_dim = cross_attention_dim
329
+ self.scale = scale
330
+ self.num_tokens = num_tokens
331
+
332
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
333
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
334
+
335
+ def forward(
336
+ self,
337
+ attn,
338
+ hidden_states,
339
+ encoder_hidden_states=None,
340
+ attention_mask=None,
341
+ temb=None,
342
+ ):
343
+ residual = hidden_states
344
+
345
+ if attn.spatial_norm is not None:
346
+ hidden_states = attn.spatial_norm(hidden_states, temb)
347
+
348
+ input_ndim = hidden_states.ndim
349
+
350
+ if input_ndim == 4:
351
+ batch_size, channel, height, width = hidden_states.shape
352
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
353
+
354
+ batch_size, sequence_length, _ = (
355
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
356
+ )
357
+
358
+ if attention_mask is not None:
359
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
360
+ # scaled_dot_product_attention expects attention_mask shape to be
361
+ # (batch, heads, source_length, target_length)
362
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
363
+
364
+ if attn.group_norm is not None:
365
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
366
+
367
+ query = attn.to_q(hidden_states)
368
+
369
+ if encoder_hidden_states is None:
370
+ encoder_hidden_states = hidden_states
371
+ else:
372
+ # get encoder_hidden_states, ip_hidden_states
373
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
374
+ encoder_hidden_states, ip_hidden_states = (
375
+ encoder_hidden_states[:, :end_pos, :],
376
+ encoder_hidden_states[:, end_pos:, :],
377
+ )
378
+ if attn.norm_cross:
379
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
380
+
381
+ key = attn.to_k(encoder_hidden_states)
382
+ value = attn.to_v(encoder_hidden_states)
383
+
384
+ inner_dim = key.shape[-1]
385
+ head_dim = inner_dim // attn.heads
386
+
387
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
388
+
389
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
390
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
391
+
392
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
393
+ # TODO: add support for attn.scale when we move to Torch 2.1
394
+ hidden_states = F.scaled_dot_product_attention(
395
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
396
+ )
397
+
398
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
399
+ hidden_states = hidden_states.to(query.dtype)
400
+
401
+ # for ip-adapter
402
+ ip_key = self.to_k_ip(ip_hidden_states)
403
+ ip_value = self.to_v_ip(ip_hidden_states)
404
+
405
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
406
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
407
+
408
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
409
+ # TODO: add support for attn.scale when we move to Torch 2.1
410
+ ip_hidden_states = F.scaled_dot_product_attention(
411
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
412
+ )
413
+ with torch.no_grad():
414
+ self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1)
415
+ #print(self.attn_map.shape)
416
+
417
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
418
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
419
+
420
+ # region control
421
+ if len(region_control.prompt_image_conditioning) == 1:
422
+ region_mask = region_control.prompt_image_conditioning[0].get('region_mask', None)
423
+ if region_mask is not None:
424
+ query = query.reshape([-1, query.shape[-2], query.shape[-1]])
425
+ h, w = region_mask.shape[:2]
426
+ ratio = (h * w / query.shape[1]) ** 0.5
427
+ mask = F.interpolate(region_mask[None, None], scale_factor=1/ratio, mode='nearest').reshape([1, -1, 1])
428
+ else:
429
+ mask = torch.ones_like(ip_hidden_states)
430
+ ip_hidden_states = ip_hidden_states * mask
431
+
432
+ hidden_states = hidden_states + self.scale * ip_hidden_states
433
+
434
+ # linear proj
435
+ hidden_states = attn.to_out[0](hidden_states)
436
+ # dropout
437
+ hidden_states = attn.to_out[1](hidden_states)
438
+
439
+ if input_ndim == 4:
440
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
441
+
442
+ if attn.residual_connection:
443
+ hidden_states = hidden_states + residual
444
+
445
+ hidden_states = hidden_states / attn.rescale_output_factor
446
+
447
+ return hidden_states
ip_adapter/resampler.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+ import math
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+
7
+
8
+ # FFN
9
+ def FeedForward(dim, mult=4):
10
+ inner_dim = int(dim * mult)
11
+ return nn.Sequential(
12
+ nn.LayerNorm(dim),
13
+ nn.Linear(dim, inner_dim, bias=False),
14
+ nn.GELU(),
15
+ nn.Linear(inner_dim, dim, bias=False),
16
+ )
17
+
18
+
19
+ def reshape_tensor(x, heads):
20
+ bs, length, width = x.shape
21
+ #(bs, length, width) --> (bs, length, n_heads, dim_per_head)
22
+ x = x.view(bs, length, heads, -1)
23
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
24
+ x = x.transpose(1, 2)
25
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
26
+ x = x.reshape(bs, heads, length, -1)
27
+ return x
28
+
29
+
30
+ class PerceiverAttention(nn.Module):
31
+ def __init__(self, *, dim, dim_head=64, heads=8):
32
+ super().__init__()
33
+ self.scale = dim_head**-0.5
34
+ self.dim_head = dim_head
35
+ self.heads = heads
36
+ inner_dim = dim_head * heads
37
+
38
+ self.norm1 = nn.LayerNorm(dim)
39
+ self.norm2 = nn.LayerNorm(dim)
40
+
41
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
42
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
43
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
44
+
45
+
46
+ def forward(self, x, latents):
47
+ """
48
+ Args:
49
+ x (torch.Tensor): image features
50
+ shape (b, n1, D)
51
+ latent (torch.Tensor): latent features
52
+ shape (b, n2, D)
53
+ """
54
+ x = self.norm1(x)
55
+ latents = self.norm2(latents)
56
+
57
+ b, l, _ = latents.shape
58
+
59
+ q = self.to_q(latents)
60
+ kv_input = torch.cat((x, latents), dim=-2)
61
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
62
+
63
+ q = reshape_tensor(q, self.heads)
64
+ k = reshape_tensor(k, self.heads)
65
+ v = reshape_tensor(v, self.heads)
66
+
67
+ # attention
68
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
69
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
70
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
71
+ out = weight @ v
72
+
73
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
74
+
75
+ return self.to_out(out)
76
+
77
+
78
+ class Resampler(nn.Module):
79
+ def __init__(
80
+ self,
81
+ dim=1024,
82
+ depth=8,
83
+ dim_head=64,
84
+ heads=16,
85
+ num_queries=8,
86
+ embedding_dim=768,
87
+ output_dim=1024,
88
+ ff_mult=4,
89
+ ):
90
+ super().__init__()
91
+
92
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
93
+
94
+ self.proj_in = nn.Linear(embedding_dim, dim)
95
+
96
+ self.proj_out = nn.Linear(dim, output_dim)
97
+ self.norm_out = nn.LayerNorm(output_dim)
98
+
99
+ self.layers = nn.ModuleList([])
100
+ for _ in range(depth):
101
+ self.layers.append(
102
+ nn.ModuleList(
103
+ [
104
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
105
+ FeedForward(dim=dim, mult=ff_mult),
106
+ ]
107
+ )
108
+ )
109
+
110
+ def forward(self, x):
111
+
112
+ latents = self.latents.repeat(x.size(0), 1, 1)
113
+
114
+ x = self.proj_in(x)
115
+
116
+ for attn, ff in self.layers:
117
+ latents = attn(x, latents) + latents
118
+ latents = ff(latents) + latents
119
+
120
+ latents = self.proj_out(latents)
121
+ return self.norm_out(latents)
ip_adapter/utils.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import torch.nn.functional as F
2
+
3
+
4
+ def is_torch2_available():
5
+ return hasattr(F, "scaled_dot_product_attention")
model_util.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal, Union, Optional, Tuple, List
2
+
3
+ import torch
4
+ from transformers import CLIPTextModel, CLIPTokenizer, CLIPTextModelWithProjection
5
+ from diffusers import (
6
+ UNet2DConditionModel,
7
+ SchedulerMixin,
8
+ StableDiffusionPipeline,
9
+ StableDiffusionXLPipeline,
10
+ AutoencoderKL,
11
+ )
12
+ from diffusers.pipelines.stable_diffusion.convert_from_ckpt import (
13
+ convert_ldm_unet_checkpoint,
14
+ )
15
+ from safetensors.torch import load_file
16
+ from diffusers.schedulers import (
17
+ DDIMScheduler,
18
+ DDPMScheduler,
19
+ LMSDiscreteScheduler,
20
+ EulerDiscreteScheduler,
21
+ EulerAncestralDiscreteScheduler,
22
+ UniPCMultistepScheduler,
23
+ )
24
+
25
+ from omegaconf import OmegaConf
26
+
27
+ # DiffUsers版StableDiffusionのモデルパラメータ
28
+ NUM_TRAIN_TIMESTEPS = 1000
29
+ BETA_START = 0.00085
30
+ BETA_END = 0.0120
31
+
32
+ UNET_PARAMS_MODEL_CHANNELS = 320
33
+ UNET_PARAMS_CHANNEL_MULT = [1, 2, 4, 4]
34
+ UNET_PARAMS_ATTENTION_RESOLUTIONS = [4, 2, 1]
35
+ UNET_PARAMS_IMAGE_SIZE = 64 # fixed from old invalid value `32`
36
+ UNET_PARAMS_IN_CHANNELS = 4
37
+ UNET_PARAMS_OUT_CHANNELS = 4
38
+ UNET_PARAMS_NUM_RES_BLOCKS = 2
39
+ UNET_PARAMS_CONTEXT_DIM = 768
40
+ UNET_PARAMS_NUM_HEADS = 8
41
+ # UNET_PARAMS_USE_LINEAR_PROJECTION = False
42
+
43
+ VAE_PARAMS_Z_CHANNELS = 4
44
+ VAE_PARAMS_RESOLUTION = 256
45
+ VAE_PARAMS_IN_CHANNELS = 3
46
+ VAE_PARAMS_OUT_CH = 3
47
+ VAE_PARAMS_CH = 128
48
+ VAE_PARAMS_CH_MULT = [1, 2, 4, 4]
49
+ VAE_PARAMS_NUM_RES_BLOCKS = 2
50
+
51
+ # V2
52
+ V2_UNET_PARAMS_ATTENTION_HEAD_DIM = [5, 10, 20, 20]
53
+ V2_UNET_PARAMS_CONTEXT_DIM = 1024
54
+ # V2_UNET_PARAMS_USE_LINEAR_PROJECTION = True
55
+
56
+ TOKENIZER_V1_MODEL_NAME = "CompVis/stable-diffusion-v1-4"
57
+ TOKENIZER_V2_MODEL_NAME = "stabilityai/stable-diffusion-2-1"
58
+
59
+ AVAILABLE_SCHEDULERS = Literal["ddim", "ddpm", "lms", "euler_a", "euler", "uniPC"]
60
+
61
+ SDXL_TEXT_ENCODER_TYPE = Union[CLIPTextModel, CLIPTextModelWithProjection]
62
+
63
+ DIFFUSERS_CACHE_DIR = None # if you want to change the cache dir, change this
64
+
65
+
66
+ def load_checkpoint_with_text_encoder_conversion(ckpt_path: str, device="cpu"):
67
+ # text encoderの格納形式が違うモデルに対応する ('text_model'がない)
68
+ TEXT_ENCODER_KEY_REPLACEMENTS = [
69
+ (
70
+ "cond_stage_model.transformer.embeddings.",
71
+ "cond_stage_model.transformer.text_model.embeddings.",
72
+ ),
73
+ (
74
+ "cond_stage_model.transformer.encoder.",
75
+ "cond_stage_model.transformer.text_model.encoder.",
76
+ ),
77
+ (
78
+ "cond_stage_model.transformer.final_layer_norm.",
79
+ "cond_stage_model.transformer.text_model.final_layer_norm.",
80
+ ),
81
+ ]
82
+
83
+ if ckpt_path.endswith(".safetensors"):
84
+ checkpoint = None
85
+ state_dict = load_file(ckpt_path) # , device) # may causes error
86
+ else:
87
+ checkpoint = torch.load(ckpt_path, map_location=device)
88
+ if "state_dict" in checkpoint:
89
+ state_dict = checkpoint["state_dict"]
90
+ else:
91
+ state_dict = checkpoint
92
+ checkpoint = None
93
+
94
+ key_reps = []
95
+ for rep_from, rep_to in TEXT_ENCODER_KEY_REPLACEMENTS:
96
+ for key in state_dict.keys():
97
+ if key.startswith(rep_from):
98
+ new_key = rep_to + key[len(rep_from) :]
99
+ key_reps.append((key, new_key))
100
+
101
+ for key, new_key in key_reps:
102
+ state_dict[new_key] = state_dict[key]
103
+ del state_dict[key]
104
+
105
+ return checkpoint, state_dict
106
+
107
+
108
+ def create_unet_diffusers_config(v2, use_linear_projection_in_v2=False):
109
+ """
110
+ Creates a config for the diffusers based on the config of the LDM model.
111
+ """
112
+ # unet_params = original_config.model.params.unet_config.params
113
+
114
+ block_out_channels = [
115
+ UNET_PARAMS_MODEL_CHANNELS * mult for mult in UNET_PARAMS_CHANNEL_MULT
116
+ ]
117
+
118
+ down_block_types = []
119
+ resolution = 1
120
+ for i in range(len(block_out_channels)):
121
+ block_type = (
122
+ "CrossAttnDownBlock2D"
123
+ if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS
124
+ else "DownBlock2D"
125
+ )
126
+ down_block_types.append(block_type)
127
+ if i != len(block_out_channels) - 1:
128
+ resolution *= 2
129
+
130
+ up_block_types = []
131
+ for i in range(len(block_out_channels)):
132
+ block_type = (
133
+ "CrossAttnUpBlock2D"
134
+ if resolution in UNET_PARAMS_ATTENTION_RESOLUTIONS
135
+ else "UpBlock2D"
136
+ )
137
+ up_block_types.append(block_type)
138
+ resolution //= 2
139
+
140
+ config = dict(
141
+ sample_size=UNET_PARAMS_IMAGE_SIZE,
142
+ in_channels=UNET_PARAMS_IN_CHANNELS,
143
+ out_channels=UNET_PARAMS_OUT_CHANNELS,
144
+ down_block_types=tuple(down_block_types),
145
+ up_block_types=tuple(up_block_types),
146
+ block_out_channels=tuple(block_out_channels),
147
+ layers_per_block=UNET_PARAMS_NUM_RES_BLOCKS,
148
+ cross_attention_dim=UNET_PARAMS_CONTEXT_DIM
149
+ if not v2
150
+ else V2_UNET_PARAMS_CONTEXT_DIM,
151
+ attention_head_dim=UNET_PARAMS_NUM_HEADS
152
+ if not v2
153
+ else V2_UNET_PARAMS_ATTENTION_HEAD_DIM,
154
+ # use_linear_projection=UNET_PARAMS_USE_LINEAR_PROJECTION if not v2 else V2_UNET_PARAMS_USE_LINEAR_PROJECTION,
155
+ )
156
+ if v2 and use_linear_projection_in_v2:
157
+ config["use_linear_projection"] = True
158
+
159
+ return config
160
+
161
+
162
+ def load_diffusers_model(
163
+ pretrained_model_name_or_path: str,
164
+ v2: bool = False,
165
+ clip_skip: Optional[int] = None,
166
+ weight_dtype: torch.dtype = torch.float32,
167
+ ) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel,]:
168
+ if v2:
169
+ tokenizer = CLIPTokenizer.from_pretrained(
170
+ TOKENIZER_V2_MODEL_NAME,
171
+ subfolder="tokenizer",
172
+ torch_dtype=weight_dtype,
173
+ cache_dir=DIFFUSERS_CACHE_DIR,
174
+ )
175
+ text_encoder = CLIPTextModel.from_pretrained(
176
+ pretrained_model_name_or_path,
177
+ subfolder="text_encoder",
178
+ # default is clip skip 2
179
+ num_hidden_layers=24 - (clip_skip - 1) if clip_skip is not None else 23,
180
+ torch_dtype=weight_dtype,
181
+ cache_dir=DIFFUSERS_CACHE_DIR,
182
+ )
183
+ else:
184
+ tokenizer = CLIPTokenizer.from_pretrained(
185
+ TOKENIZER_V1_MODEL_NAME,
186
+ subfolder="tokenizer",
187
+ torch_dtype=weight_dtype,
188
+ cache_dir=DIFFUSERS_CACHE_DIR,
189
+ )
190
+ text_encoder = CLIPTextModel.from_pretrained(
191
+ pretrained_model_name_or_path,
192
+ subfolder="text_encoder",
193
+ num_hidden_layers=12 - (clip_skip - 1) if clip_skip is not None else 12,
194
+ torch_dtype=weight_dtype,
195
+ cache_dir=DIFFUSERS_CACHE_DIR,
196
+ )
197
+
198
+ unet = UNet2DConditionModel.from_pretrained(
199
+ pretrained_model_name_or_path,
200
+ subfolder="unet",
201
+ torch_dtype=weight_dtype,
202
+ cache_dir=DIFFUSERS_CACHE_DIR,
203
+ )
204
+
205
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
206
+
207
+ return tokenizer, text_encoder, unet, vae
208
+
209
+
210
+ def load_checkpoint_model(
211
+ checkpoint_path: str,
212
+ v2: bool = False,
213
+ clip_skip: Optional[int] = None,
214
+ weight_dtype: torch.dtype = torch.float32,
215
+ ) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel,]:
216
+ pipe = StableDiffusionPipeline.from_single_file(
217
+ checkpoint_path,
218
+ upcast_attention=True if v2 else False,
219
+ torch_dtype=weight_dtype,
220
+ cache_dir=DIFFUSERS_CACHE_DIR,
221
+ )
222
+
223
+ _, state_dict = load_checkpoint_with_text_encoder_conversion(checkpoint_path)
224
+ unet_config = create_unet_diffusers_config(v2, use_linear_projection_in_v2=v2)
225
+ unet_config["class_embed_type"] = None
226
+ unet_config["addition_embed_type"] = None
227
+ converted_unet_checkpoint = convert_ldm_unet_checkpoint(state_dict, unet_config)
228
+ unet = UNet2DConditionModel(**unet_config)
229
+ unet.load_state_dict(converted_unet_checkpoint)
230
+
231
+ tokenizer = pipe.tokenizer
232
+ text_encoder = pipe.text_encoder
233
+ vae = pipe.vae
234
+ if clip_skip is not None:
235
+ if v2:
236
+ text_encoder.config.num_hidden_layers = 24 - (clip_skip - 1)
237
+ else:
238
+ text_encoder.config.num_hidden_layers = 12 - (clip_skip - 1)
239
+
240
+ del pipe
241
+
242
+ return tokenizer, text_encoder, unet, vae
243
+
244
+
245
+ def load_models(
246
+ pretrained_model_name_or_path: str,
247
+ scheduler_name: str,
248
+ v2: bool = False,
249
+ v_pred: bool = False,
250
+ weight_dtype: torch.dtype = torch.float32,
251
+ ) -> Tuple[CLIPTokenizer, CLIPTextModel, UNet2DConditionModel, SchedulerMixin,]:
252
+ if pretrained_model_name_or_path.endswith(
253
+ ".ckpt"
254
+ ) or pretrained_model_name_or_path.endswith(".safetensors"):
255
+ tokenizer, text_encoder, unet, vae = load_checkpoint_model(
256
+ pretrained_model_name_or_path, v2=v2, weight_dtype=weight_dtype
257
+ )
258
+ else: # diffusers
259
+ tokenizer, text_encoder, unet, vae = load_diffusers_model(
260
+ pretrained_model_name_or_path, v2=v2, weight_dtype=weight_dtype
261
+ )
262
+
263
+ if scheduler_name:
264
+ scheduler = create_noise_scheduler(
265
+ scheduler_name,
266
+ prediction_type="v_prediction" if v_pred else "epsilon",
267
+ )
268
+ else:
269
+ scheduler = None
270
+
271
+ return tokenizer, text_encoder, unet, scheduler, vae
272
+
273
+
274
+ def load_diffusers_model_xl(
275
+ pretrained_model_name_or_path: str,
276
+ weight_dtype: torch.dtype = torch.float32,
277
+ ) -> Tuple[List[CLIPTokenizer], List[SDXL_TEXT_ENCODER_TYPE], UNet2DConditionModel,]:
278
+ # returns tokenizer, tokenizer_2, text_encoder, text_encoder_2, unet
279
+
280
+ tokenizers = [
281
+ CLIPTokenizer.from_pretrained(
282
+ pretrained_model_name_or_path,
283
+ subfolder="tokenizer",
284
+ torch_dtype=weight_dtype,
285
+ cache_dir=DIFFUSERS_CACHE_DIR,
286
+ ),
287
+ CLIPTokenizer.from_pretrained(
288
+ pretrained_model_name_or_path,
289
+ subfolder="tokenizer_2",
290
+ torch_dtype=weight_dtype,
291
+ cache_dir=DIFFUSERS_CACHE_DIR,
292
+ pad_token_id=0, # same as open clip
293
+ ),
294
+ ]
295
+
296
+ text_encoders = [
297
+ CLIPTextModel.from_pretrained(
298
+ pretrained_model_name_or_path,
299
+ subfolder="text_encoder",
300
+ torch_dtype=weight_dtype,
301
+ cache_dir=DIFFUSERS_CACHE_DIR,
302
+ ),
303
+ CLIPTextModelWithProjection.from_pretrained(
304
+ pretrained_model_name_or_path,
305
+ subfolder="text_encoder_2",
306
+ torch_dtype=weight_dtype,
307
+ cache_dir=DIFFUSERS_CACHE_DIR,
308
+ ),
309
+ ]
310
+
311
+ unet = UNet2DConditionModel.from_pretrained(
312
+ pretrained_model_name_or_path,
313
+ subfolder="unet",
314
+ torch_dtype=weight_dtype,
315
+ cache_dir=DIFFUSERS_CACHE_DIR,
316
+ )
317
+ vae = AutoencoderKL.from_pretrained(pretrained_model_name_or_path, subfolder="vae")
318
+ return tokenizers, text_encoders, unet, vae
319
+
320
+
321
+ def load_checkpoint_model_xl(
322
+ checkpoint_path: str,
323
+ weight_dtype: torch.dtype = torch.float32,
324
+ ) -> Tuple[List[CLIPTokenizer], List[SDXL_TEXT_ENCODER_TYPE], UNet2DConditionModel,]:
325
+ pipe = StableDiffusionXLPipeline.from_single_file(
326
+ checkpoint_path,
327
+ torch_dtype=weight_dtype,
328
+ cache_dir=DIFFUSERS_CACHE_DIR,
329
+ )
330
+
331
+ unet = pipe.unet
332
+ vae = pipe.vae
333
+ tokenizers = [pipe.tokenizer, pipe.tokenizer_2]
334
+ text_encoders = [pipe.text_encoder, pipe.text_encoder_2]
335
+ if len(text_encoders) == 2:
336
+ text_encoders[1].pad_token_id = 0
337
+
338
+ del pipe
339
+
340
+ return tokenizers, text_encoders, unet, vae
341
+
342
+
343
+ def load_models_xl(
344
+ pretrained_model_name_or_path: str,
345
+ scheduler_name: str,
346
+ weight_dtype: torch.dtype = torch.float32,
347
+ noise_scheduler_kwargs=None,
348
+ ) -> Tuple[
349
+ List[CLIPTokenizer],
350
+ List[SDXL_TEXT_ENCODER_TYPE],
351
+ UNet2DConditionModel,
352
+ SchedulerMixin,
353
+ ]:
354
+ if pretrained_model_name_or_path.endswith(
355
+ ".ckpt"
356
+ ) or pretrained_model_name_or_path.endswith(".safetensors"):
357
+ (tokenizers, text_encoders, unet, vae) = load_checkpoint_model_xl(
358
+ pretrained_model_name_or_path, weight_dtype
359
+ )
360
+ else: # diffusers
361
+ (tokenizers, text_encoders, unet, vae) = load_diffusers_model_xl(
362
+ pretrained_model_name_or_path, weight_dtype
363
+ )
364
+ if scheduler_name:
365
+ scheduler = create_noise_scheduler(scheduler_name, noise_scheduler_kwargs)
366
+ else:
367
+ scheduler = None
368
+
369
+ return tokenizers, text_encoders, unet, scheduler, vae
370
+
371
+ def create_noise_scheduler(
372
+ scheduler_name: AVAILABLE_SCHEDULERS = "ddpm",
373
+ noise_scheduler_kwargs=None,
374
+ prediction_type: Literal["epsilon", "v_prediction"] = "epsilon",
375
+ ) -> SchedulerMixin:
376
+ name = scheduler_name.lower().replace(" ", "_")
377
+ if name.lower() == "ddim":
378
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/ddim
379
+ scheduler = DDIMScheduler(**OmegaConf.to_container(noise_scheduler_kwargs))
380
+ elif name.lower() == "ddpm":
381
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/ddpm
382
+ scheduler = DDPMScheduler(**OmegaConf.to_container(noise_scheduler_kwargs))
383
+ elif name.lower() == "lms":
384
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/lms_discrete
385
+ scheduler = LMSDiscreteScheduler(
386
+ **OmegaConf.to_container(noise_scheduler_kwargs)
387
+ )
388
+ elif name.lower() == "euler_a":
389
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/euler_ancestral
390
+ scheduler = EulerAncestralDiscreteScheduler(
391
+ **OmegaConf.to_container(noise_scheduler_kwargs)
392
+ )
393
+ elif name.lower() == "euler":
394
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/euler_ancestral
395
+ scheduler = EulerDiscreteScheduler(
396
+ **OmegaConf.to_container(noise_scheduler_kwargs)
397
+ )
398
+ elif name.lower() == "unipc":
399
+ # https://huggingface.co/docs/diffusers/v0.17.1/en/api/schedulers/unipc
400
+ scheduler = UniPCMultistepScheduler(
401
+ **OmegaConf.to_container(noise_scheduler_kwargs)
402
+ )
403
+ else:
404
+ raise ValueError(f"Unknown scheduler name: {name}")
405
+
406
+ return scheduler
407
+
408
+
409
+ def torch_gc():
410
+ import gc
411
+
412
+ gc.collect()
413
+ if torch.cuda.is_available():
414
+ with torch.cuda.device("cuda"):
415
+ torch.cuda.empty_cache()
416
+ torch.cuda.ipc_collect()
417
+
418
+
419
+ from enum import Enum
420
+
421
+
422
+ class CPUState(Enum):
423
+ GPU = 0
424
+ CPU = 1
425
+ MPS = 2
426
+
427
+
428
+ cpu_state = CPUState.GPU
429
+ xpu_available = False
430
+ directml_enabled = False
431
+
432
+
433
+ def is_intel_xpu():
434
+ global cpu_state
435
+ global xpu_available
436
+ if cpu_state == CPUState.GPU:
437
+ if xpu_available:
438
+ return True
439
+ return False
440
+
441
+
442
+ try:
443
+ import intel_extension_for_pytorch as ipex
444
+
445
+ if torch.xpu.is_available():
446
+ xpu_available = True
447
+ except:
448
+ pass
449
+
450
+ try:
451
+ if torch.backends.mps.is_available():
452
+ cpu_state = CPUState.MPS
453
+ import torch.mps
454
+ except:
455
+ pass
456
+
457
+
458
+ def get_torch_device():
459
+ global directml_enabled
460
+ global cpu_state
461
+ if directml_enabled:
462
+ global directml_device
463
+ return directml_device
464
+ if cpu_state == CPUState.MPS:
465
+ return torch.device("mps")
466
+ if cpu_state == CPUState.CPU:
467
+ return torch.device("cpu")
468
+ else:
469
+ if is_intel_xpu():
470
+ return torch.device("xpu")
471
+ else:
472
+ return torch.device(torch.cuda.current_device())
models/antelopev2.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8e182f14fc6e80b3bfa375b33eb6cff7ee05d8ef7633e738d1c89021dcf0c5c5
3
+ size 360662982
models/antelopev2/1k3d68.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:df5c06b8a0c12e422b2ed8947b8869faa4105387f199c477af038aa01f9a45cc
3
+ size 143607619
models/antelopev2/2d106det.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f001b856447c413801ef5c42091ed0cd516fcd21f2d6b79635b1e733a7109dbf
3
+ size 5030888
models/antelopev2/genderage.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4fde69b1c810857b88c64a335084f1c3fe8f01246c9a191b48c7bb756d6652fb
3
+ size 1322532
models/antelopev2/glintr100.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ab1d6435d639628a6f3e5008dd4f929edf4c4124b1a7169e1048f9fef534cdf
3
+ size 260665334
models/antelopev2/scrfd_10g_bnkps.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5838f7fe053675b1c7a08b633df49e7af5495cee0493c7dcf6697200b85b5b91
3
+ size 16923827
pipeline_stable_diffusion_xl_instantid_full.py ADDED
@@ -0,0 +1,1227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ 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
+ class RegionControler(object):
51
+ def __init__(self) -> None:
52
+ self.prompt_image_conditioning = []
53
+ region_control = RegionControler()
54
+
55
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
56
+
57
+ EXAMPLE_DOC_STRING = """
58
+ Examples:
59
+ ```py
60
+ >>> # !pip install opencv-python transformers accelerate insightface
61
+ >>> import diffusers
62
+ >>> from diffusers.utils import load_image
63
+ >>> from diffusers.models import ControlNetModel
64
+
65
+ >>> import cv2
66
+ >>> import torch
67
+ >>> import numpy as np
68
+ >>> from PIL import Image
69
+
70
+ >>> from insightface.app import FaceAnalysis
71
+ >>> from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps
72
+
73
+ >>> # download 'antelopev2' under ./models
74
+ >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
75
+ >>> app.prepare(ctx_id=0, det_size=(640, 640))
76
+
77
+ >>> # download models under ./checkpoints
78
+ >>> face_adapter = f'./checkpoints/ip-adapter.bin'
79
+ >>> controlnet_path = f'./checkpoints/ControlNetModel'
80
+
81
+ >>> # load IdentityNet
82
+ >>> controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
83
+
84
+ >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
85
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
86
+ ... )
87
+ >>> pipe.cuda()
88
+
89
+ >>> # load adapter
90
+ >>> pipe.load_ip_adapter_instantid(face_adapter)
91
+
92
+ >>> 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"
93
+ >>> 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"
94
+
95
+ >>> # load an image
96
+ >>> image = load_image("your-example.jpg")
97
+
98
+ >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1]
99
+ >>> face_emb = face_info['embedding']
100
+ >>> face_kps = draw_kps(face_image, face_info['kps'])
101
+
102
+ >>> pipe.set_ip_adapter_scale(0.8)
103
+
104
+ >>> # generate image
105
+ >>> image = pipe(
106
+ ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8
107
+ ... ).images[0]
108
+ ```
109
+ """
110
+
111
+ from transformers import CLIPTokenizer
112
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipeline
113
+ class LongPromptWeight(object):
114
+
115
+ """
116
+ Copied from https://github.com/huggingface/diffusers/blob/main/examples/community/lpw_stable_diffusion_xl.py
117
+ """
118
+
119
+ def __init__(self) -> None:
120
+ pass
121
+
122
+ def parse_prompt_attention(self, text):
123
+ """
124
+ Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
125
+ Accepted tokens are:
126
+ (abc) - increases attention to abc by a multiplier of 1.1
127
+ (abc:3.12) - increases attention to abc by a multiplier of 3.12
128
+ [abc] - decreases attention to abc by a multiplier of 1.1
129
+ \( - literal character '('
130
+ \[ - literal character '['
131
+ \) - literal character ')'
132
+ \] - literal character ']'
133
+ \\ - literal character '\'
134
+ anything else - just text
135
+
136
+ >>> parse_prompt_attention('normal text')
137
+ [['normal text', 1.0]]
138
+ >>> parse_prompt_attention('an (important) word')
139
+ [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
140
+ >>> parse_prompt_attention('(unbalanced')
141
+ [['unbalanced', 1.1]]
142
+ >>> parse_prompt_attention('\(literal\]')
143
+ [['(literal]', 1.0]]
144
+ >>> parse_prompt_attention('(unnecessary)(parens)')
145
+ [['unnecessaryparens', 1.1]]
146
+ >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
147
+ [['a ', 1.0],
148
+ ['house', 1.5730000000000004],
149
+ [' ', 1.1],
150
+ ['on', 1.0],
151
+ [' a ', 1.1],
152
+ ['hill', 0.55],
153
+ [', sun, ', 1.1],
154
+ ['sky', 1.4641000000000006],
155
+ ['.', 1.1]]
156
+ """
157
+ import re
158
+
159
+ re_attention = re.compile(
160
+ r"""
161
+ \\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)|
162
+ \)|]|[^\\()\[\]:]+|:
163
+ """,
164
+ re.X,
165
+ )
166
+
167
+ re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
168
+
169
+ res = []
170
+ round_brackets = []
171
+ square_brackets = []
172
+
173
+ round_bracket_multiplier = 1.1
174
+ square_bracket_multiplier = 1 / 1.1
175
+
176
+ def multiply_range(start_position, multiplier):
177
+ for p in range(start_position, len(res)):
178
+ res[p][1] *= multiplier
179
+
180
+ for m in re_attention.finditer(text):
181
+ text = m.group(0)
182
+ weight = m.group(1)
183
+
184
+ if text.startswith("\\"):
185
+ res.append([text[1:], 1.0])
186
+ elif text == "(":
187
+ round_brackets.append(len(res))
188
+ elif text == "[":
189
+ square_brackets.append(len(res))
190
+ elif weight is not None and len(round_brackets) > 0:
191
+ multiply_range(round_brackets.pop(), float(weight))
192
+ elif text == ")" and len(round_brackets) > 0:
193
+ multiply_range(round_brackets.pop(), round_bracket_multiplier)
194
+ elif text == "]" and len(square_brackets) > 0:
195
+ multiply_range(square_brackets.pop(), square_bracket_multiplier)
196
+ else:
197
+ parts = re.split(re_break, text)
198
+ for i, part in enumerate(parts):
199
+ if i > 0:
200
+ res.append(["BREAK", -1])
201
+ res.append([part, 1.0])
202
+
203
+ for pos in round_brackets:
204
+ multiply_range(pos, round_bracket_multiplier)
205
+
206
+ for pos in square_brackets:
207
+ multiply_range(pos, square_bracket_multiplier)
208
+
209
+ if len(res) == 0:
210
+ res = [["", 1.0]]
211
+
212
+ # merge runs of identical weights
213
+ i = 0
214
+ while i + 1 < len(res):
215
+ if res[i][1] == res[i + 1][1]:
216
+ res[i][0] += res[i + 1][0]
217
+ res.pop(i + 1)
218
+ else:
219
+ i += 1
220
+
221
+ return res
222
+
223
+ def get_prompts_tokens_with_weights(self, clip_tokenizer: CLIPTokenizer, prompt: str):
224
+ """
225
+ Get prompt token ids and weights, this function works for both prompt and negative prompt
226
+
227
+ Args:
228
+ pipe (CLIPTokenizer)
229
+ A CLIPTokenizer
230
+ prompt (str)
231
+ A prompt string with weights
232
+
233
+ Returns:
234
+ text_tokens (list)
235
+ A list contains token ids
236
+ text_weight (list)
237
+ A list contains the correspodent weight of token ids
238
+
239
+ Example:
240
+ import torch
241
+ from transformers import CLIPTokenizer
242
+
243
+ clip_tokenizer = CLIPTokenizer.from_pretrained(
244
+ "stablediffusionapi/deliberate-v2"
245
+ , subfolder = "tokenizer"
246
+ , dtype = torch.float16
247
+ )
248
+
249
+ token_id_list, token_weight_list = get_prompts_tokens_with_weights(
250
+ clip_tokenizer = clip_tokenizer
251
+ ,prompt = "a (red:1.5) cat"*70
252
+ )
253
+ """
254
+ texts_and_weights = self.parse_prompt_attention(prompt)
255
+ text_tokens, text_weights = [], []
256
+ for word, weight in texts_and_weights:
257
+ # tokenize and discard the starting and the ending token
258
+ token = clip_tokenizer(word, truncation=False).input_ids[1:-1] # so that tokenize whatever length prompt
259
+ # the returned token is a 1d list: [320, 1125, 539, 320]
260
+
261
+ # merge the new tokens to the all tokens holder: text_tokens
262
+ text_tokens = [*text_tokens, *token]
263
+
264
+ # each token chunk will come with one weight, like ['red cat', 2.0]
265
+ # need to expand weight for each token.
266
+ chunk_weights = [weight] * len(token)
267
+
268
+ # append the weight back to the weight holder: text_weights
269
+ text_weights = [*text_weights, *chunk_weights]
270
+ return text_tokens, text_weights
271
+
272
+ def group_tokens_and_weights(self, token_ids: list, weights: list, pad_last_block=False):
273
+ """
274
+ Produce tokens and weights in groups and pad the missing tokens
275
+
276
+ Args:
277
+ token_ids (list)
278
+ The token ids from tokenizer
279
+ weights (list)
280
+ The weights list from function get_prompts_tokens_with_weights
281
+ pad_last_block (bool)
282
+ Control if fill the last token list to 75 tokens with eos
283
+ Returns:
284
+ new_token_ids (2d list)
285
+ new_weights (2d list)
286
+
287
+ Example:
288
+ token_groups,weight_groups = group_tokens_and_weights(
289
+ token_ids = token_id_list
290
+ , weights = token_weight_list
291
+ )
292
+ """
293
+ bos, eos = 49406, 49407
294
+
295
+ # this will be a 2d list
296
+ new_token_ids = []
297
+ new_weights = []
298
+ while len(token_ids) >= 75:
299
+ # get the first 75 tokens
300
+ head_75_tokens = [token_ids.pop(0) for _ in range(75)]
301
+ head_75_weights = [weights.pop(0) for _ in range(75)]
302
+
303
+ # extract token ids and weights
304
+ temp_77_token_ids = [bos] + head_75_tokens + [eos]
305
+ temp_77_weights = [1.0] + head_75_weights + [1.0]
306
+
307
+ # add 77 token and weights chunk to the holder list
308
+ new_token_ids.append(temp_77_token_ids)
309
+ new_weights.append(temp_77_weights)
310
+
311
+ # padding the left
312
+ if len(token_ids) >= 0:
313
+ padding_len = 75 - len(token_ids) if pad_last_block else 0
314
+
315
+ temp_77_token_ids = [bos] + token_ids + [eos] * padding_len + [eos]
316
+ new_token_ids.append(temp_77_token_ids)
317
+
318
+ temp_77_weights = [1.0] + weights + [1.0] * padding_len + [1.0]
319
+ new_weights.append(temp_77_weights)
320
+
321
+ return new_token_ids, new_weights
322
+
323
+ def get_weighted_text_embeddings_sdxl(
324
+ self,
325
+ pipe: StableDiffusionXLPipeline,
326
+ prompt: str = "",
327
+ prompt_2: str = None,
328
+ neg_prompt: str = "",
329
+ neg_prompt_2: str = None,
330
+ prompt_embeds=None,
331
+ negative_prompt_embeds=None,
332
+ pooled_prompt_embeds=None,
333
+ negative_pooled_prompt_embeds=None,
334
+ extra_emb=None,
335
+ extra_emb_alpha=0.6,
336
+ ):
337
+ """
338
+ This function can process long prompt with weights, no length limitation
339
+ for Stable Diffusion XL
340
+
341
+ Args:
342
+ pipe (StableDiffusionPipeline)
343
+ prompt (str)
344
+ prompt_2 (str)
345
+ neg_prompt (str)
346
+ neg_prompt_2 (str)
347
+ Returns:
348
+ prompt_embeds (torch.Tensor)
349
+ neg_prompt_embeds (torch.Tensor)
350
+ """
351
+ #
352
+ if prompt_embeds is not None and \
353
+ negative_prompt_embeds is not None and \
354
+ pooled_prompt_embeds is not None and \
355
+ negative_pooled_prompt_embeds is not None:
356
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
357
+
358
+ if prompt_2:
359
+ prompt = f"{prompt} {prompt_2}"
360
+
361
+ if neg_prompt_2:
362
+ neg_prompt = f"{neg_prompt} {neg_prompt_2}"
363
+
364
+ eos = pipe.tokenizer.eos_token_id
365
+
366
+ # tokenizer 1
367
+ prompt_tokens, prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
368
+ neg_prompt_tokens, neg_prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
369
+
370
+ # tokenizer 2
371
+ # prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, prompt)
372
+ # neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, neg_prompt)
373
+ # tokenizer 2 遇到 !! !!!! 等多感叹号和tokenizer 1的效果不一致
374
+ prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
375
+ neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
376
+
377
+ # padding the shorter one for prompt set 1
378
+ prompt_token_len = len(prompt_tokens)
379
+ neg_prompt_token_len = len(neg_prompt_tokens)
380
+
381
+ if prompt_token_len > neg_prompt_token_len:
382
+ # padding the neg_prompt with eos token
383
+ neg_prompt_tokens = neg_prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
384
+ neg_prompt_weights = neg_prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
385
+ else:
386
+ # padding the prompt
387
+ prompt_tokens = prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
388
+ prompt_weights = prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
389
+
390
+ # padding the shorter one for token set 2
391
+ prompt_token_len_2 = len(prompt_tokens_2)
392
+ neg_prompt_token_len_2 = len(neg_prompt_tokens_2)
393
+
394
+ if prompt_token_len_2 > neg_prompt_token_len_2:
395
+ # padding the neg_prompt with eos token
396
+ neg_prompt_tokens_2 = neg_prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
397
+ neg_prompt_weights_2 = neg_prompt_weights_2 + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
398
+ else:
399
+ # padding the prompt
400
+ prompt_tokens_2 = prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
401
+ prompt_weights_2 = prompt_weights + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
402
+
403
+ embeds = []
404
+ neg_embeds = []
405
+
406
+ prompt_token_groups, prompt_weight_groups = self.group_tokens_and_weights(prompt_tokens.copy(), prompt_weights.copy())
407
+
408
+ neg_prompt_token_groups, neg_prompt_weight_groups = self.group_tokens_and_weights(
409
+ neg_prompt_tokens.copy(), neg_prompt_weights.copy()
410
+ )
411
+
412
+ prompt_token_groups_2, prompt_weight_groups_2 = self.group_tokens_and_weights(
413
+ prompt_tokens_2.copy(), prompt_weights_2.copy()
414
+ )
415
+
416
+ neg_prompt_token_groups_2, neg_prompt_weight_groups_2 = self.group_tokens_and_weights(
417
+ neg_prompt_tokens_2.copy(), neg_prompt_weights_2.copy()
418
+ )
419
+
420
+ # get prompt embeddings one by one is not working.
421
+ for i in range(len(prompt_token_groups)):
422
+ # get positive prompt embeddings with weights
423
+ token_tensor = torch.tensor([prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
424
+ weight_tensor = torch.tensor(prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
425
+
426
+ token_tensor_2 = torch.tensor([prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
427
+
428
+ # use first text encoder
429
+ prompt_embeds_1 = pipe.text_encoder(token_tensor.to(pipe.device), output_hidden_states=True)
430
+ prompt_embeds_1_hidden_states = prompt_embeds_1.hidden_states[-2]
431
+
432
+ # use second text encoder
433
+ prompt_embeds_2 = pipe.text_encoder_2(token_tensor_2.to(pipe.device), output_hidden_states=True)
434
+ prompt_embeds_2_hidden_states = prompt_embeds_2.hidden_states[-2]
435
+ pooled_prompt_embeds = prompt_embeds_2[0]
436
+
437
+ prompt_embeds_list = [prompt_embeds_1_hidden_states, prompt_embeds_2_hidden_states]
438
+ token_embedding = torch.concat(prompt_embeds_list, dim=-1).squeeze(0)
439
+
440
+ for j in range(len(weight_tensor)):
441
+ if weight_tensor[j] != 1.0:
442
+ token_embedding[j] = (
443
+ token_embedding[-1] + (token_embedding[j] - token_embedding[-1]) * weight_tensor[j]
444
+ )
445
+
446
+ token_embedding = token_embedding.unsqueeze(0)
447
+ embeds.append(token_embedding)
448
+
449
+ # get negative prompt embeddings with weights
450
+ neg_token_tensor = torch.tensor([neg_prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
451
+ neg_token_tensor_2 = torch.tensor([neg_prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
452
+ neg_weight_tensor = torch.tensor(neg_prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
453
+
454
+ # use first text encoder
455
+ neg_prompt_embeds_1 = pipe.text_encoder(neg_token_tensor.to(pipe.device), output_hidden_states=True)
456
+ neg_prompt_embeds_1_hidden_states = neg_prompt_embeds_1.hidden_states[-2]
457
+
458
+ # use second text encoder
459
+ neg_prompt_embeds_2 = pipe.text_encoder_2(neg_token_tensor_2.to(pipe.device), output_hidden_states=True)
460
+ neg_prompt_embeds_2_hidden_states = neg_prompt_embeds_2.hidden_states[-2]
461
+ negative_pooled_prompt_embeds = neg_prompt_embeds_2[0]
462
+
463
+ neg_prompt_embeds_list = [neg_prompt_embeds_1_hidden_states, neg_prompt_embeds_2_hidden_states]
464
+ neg_token_embedding = torch.concat(neg_prompt_embeds_list, dim=-1).squeeze(0)
465
+
466
+ for z in range(len(neg_weight_tensor)):
467
+ if neg_weight_tensor[z] != 1.0:
468
+ neg_token_embedding[z] = (
469
+ neg_token_embedding[-1] + (neg_token_embedding[z] - neg_token_embedding[-1]) * neg_weight_tensor[z]
470
+ )
471
+
472
+ neg_token_embedding = neg_token_embedding.unsqueeze(0)
473
+ neg_embeds.append(neg_token_embedding)
474
+
475
+ prompt_embeds = torch.cat(embeds, dim=1)
476
+ negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
477
+
478
+ if extra_emb is not None:
479
+ extra_emb = extra_emb.to(prompt_embeds.device, dtype=prompt_embeds.dtype) * extra_emb_alpha
480
+ prompt_embeds = torch.cat([prompt_embeds, extra_emb], 1)
481
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, torch.zeros_like(extra_emb)], 1)
482
+ print(f'fix prompt_embeds, extra_emb_alpha={extra_emb_alpha}')
483
+
484
+ return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
485
+
486
+ def get_prompt_embeds(self, *args, **kwargs):
487
+ prompt_embeds, negative_prompt_embeds, _, _ = self.get_weighted_text_embeddings_sdxl(*args, **kwargs)
488
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
489
+ return prompt_embeds
490
+
491
+ def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
492
+
493
+ stickwidth = 4
494
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
495
+ kps = np.array(kps)
496
+
497
+ w, h = image_pil.size
498
+ out_img = np.zeros([h, w, 3])
499
+
500
+ for i in range(len(limbSeq)):
501
+ index = limbSeq[i]
502
+ color = color_list[index[0]]
503
+
504
+ x = kps[index][:, 0]
505
+ y = kps[index][:, 1]
506
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
507
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
508
+ polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
509
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
510
+ out_img = (out_img * 0.6).astype(np.uint8)
511
+
512
+ for idx_kp, kp in enumerate(kps):
513
+ color = color_list[idx_kp]
514
+ x, y = kp
515
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
516
+
517
+ out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))
518
+ return out_img_pil
519
+
520
+ class StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline):
521
+
522
+ def cuda(self, dtype=torch.float16, use_xformers=False):
523
+ self.to('cuda', dtype)
524
+
525
+ if hasattr(self, 'image_proj_model'):
526
+ self.image_proj_model.to(self.unet.device).to(self.unet.dtype)
527
+
528
+ if use_xformers:
529
+ if is_xformers_available():
530
+ import xformers
531
+ from packaging import version
532
+
533
+ xformers_version = version.parse(xformers.__version__)
534
+ if xformers_version == version.parse("0.0.16"):
535
+ logger.warn(
536
+ "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."
537
+ )
538
+ self.enable_xformers_memory_efficient_attention()
539
+ else:
540
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
541
+
542
+ def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=0.5):
543
+ self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens)
544
+ self.set_ip_adapter(model_ckpt, num_tokens, scale)
545
+
546
+ def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16):
547
+
548
+ image_proj_model = Resampler(
549
+ dim=1280,
550
+ depth=4,
551
+ dim_head=64,
552
+ heads=20,
553
+ num_queries=num_tokens,
554
+ embedding_dim=image_emb_dim,
555
+ output_dim=self.unet.config.cross_attention_dim,
556
+ ff_mult=4,
557
+ )
558
+
559
+ image_proj_model.eval()
560
+
561
+ self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype)
562
+ state_dict = torch.load(model_ckpt, map_location="cpu")
563
+ if 'image_proj' in state_dict:
564
+ state_dict = state_dict["image_proj"]
565
+ self.image_proj_model.load_state_dict(state_dict)
566
+
567
+ self.image_proj_model_in_features = image_emb_dim
568
+
569
+ def set_ip_adapter(self, model_ckpt, num_tokens, scale):
570
+
571
+ unet = self.unet
572
+ attn_procs = {}
573
+ for name in unet.attn_processors.keys():
574
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
575
+ if name.startswith("mid_block"):
576
+ hidden_size = unet.config.block_out_channels[-1]
577
+ elif name.startswith("up_blocks"):
578
+ block_id = int(name[len("up_blocks.")])
579
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
580
+ elif name.startswith("down_blocks"):
581
+ block_id = int(name[len("down_blocks.")])
582
+ hidden_size = unet.config.block_out_channels[block_id]
583
+ if cross_attention_dim is None:
584
+ attn_procs[name] = AttnProcessor().to(unet.device, dtype=unet.dtype)
585
+ else:
586
+ attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size,
587
+ cross_attention_dim=cross_attention_dim,
588
+ scale=scale,
589
+ num_tokens=num_tokens).to(unet.device, dtype=unet.dtype)
590
+ unet.set_attn_processor(attn_procs)
591
+
592
+ state_dict = torch.load(model_ckpt, map_location="cpu")
593
+ ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
594
+ if 'ip_adapter' in state_dict:
595
+ state_dict = state_dict['ip_adapter']
596
+ ip_layers.load_state_dict(state_dict)
597
+
598
+ def set_ip_adapter_scale(self, scale):
599
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
600
+ for attn_processor in unet.attn_processors.values():
601
+ if isinstance(attn_processor, IPAttnProcessor):
602
+ attn_processor.scale = scale
603
+
604
+ def _encode_prompt_image_emb(self, prompt_image_emb, device, num_images_per_prompt, dtype, do_classifier_free_guidance):
605
+
606
+ if isinstance(prompt_image_emb, torch.Tensor):
607
+ prompt_image_emb = prompt_image_emb.clone().detach()
608
+ else:
609
+ prompt_image_emb = torch.tensor(prompt_image_emb)
610
+
611
+ prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features])
612
+
613
+ if do_classifier_free_guidance:
614
+ prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0)
615
+ else:
616
+ prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
617
+
618
+ prompt_image_emb = prompt_image_emb.to(device=self.image_proj_model.latents.device,
619
+ dtype=self.image_proj_model.latents.dtype)
620
+ prompt_image_emb = self.image_proj_model(prompt_image_emb)
621
+
622
+ bs_embed, seq_len, _ = prompt_image_emb.shape
623
+ prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
624
+ prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
625
+
626
+ return prompt_image_emb.to(device=device, dtype=dtype)
627
+
628
+ @torch.no_grad()
629
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
630
+ def __call__(
631
+ self,
632
+ prompt: Union[str, List[str]] = None,
633
+ prompt_2: Optional[Union[str, List[str]]] = None,
634
+ image: PipelineImageInput = None,
635
+ height: Optional[int] = None,
636
+ width: Optional[int] = None,
637
+ num_inference_steps: int = 50,
638
+ guidance_scale: float = 5.0,
639
+ negative_prompt: Optional[Union[str, List[str]]] = None,
640
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
641
+ num_images_per_prompt: Optional[int] = 1,
642
+ eta: float = 0.0,
643
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
644
+ latents: Optional[torch.FloatTensor] = None,
645
+ prompt_embeds: Optional[torch.FloatTensor] = None,
646
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
647
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
648
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
649
+ image_embeds: Optional[torch.FloatTensor] = None,
650
+ output_type: Optional[str] = "pil",
651
+ return_dict: bool = True,
652
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
653
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
654
+ guess_mode: bool = False,
655
+ control_guidance_start: Union[float, List[float]] = 0.0,
656
+ control_guidance_end: Union[float, List[float]] = 1.0,
657
+ original_size: Tuple[int, int] = None,
658
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
659
+ target_size: Tuple[int, int] = None,
660
+ negative_original_size: Optional[Tuple[int, int]] = None,
661
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
662
+ negative_target_size: Optional[Tuple[int, int]] = None,
663
+ clip_skip: Optional[int] = None,
664
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
665
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
666
+
667
+ # IP adapter
668
+ ip_adapter_scale=None,
669
+
670
+ # Enhance Face Region
671
+ control_mask = None,
672
+
673
+ **kwargs,
674
+ ):
675
+ r"""
676
+ The call function to the pipeline for generation.
677
+
678
+ Args:
679
+ prompt (`str` or `List[str]`, *optional*):
680
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
681
+ prompt_2 (`str` or `List[str]`, *optional*):
682
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
683
+ used in both text-encoders.
684
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
685
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
686
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
687
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
688
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
689
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
690
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
691
+ input to a single ControlNet.
692
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
693
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
694
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
695
+ and checkpoints that are not specifically fine-tuned on low resolutions.
696
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
697
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
698
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
699
+ and checkpoints that are not specifically fine-tuned on low resolutions.
700
+ num_inference_steps (`int`, *optional*, defaults to 50):
701
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
702
+ expense of slower inference.
703
+ guidance_scale (`float`, *optional*, defaults to 5.0):
704
+ A higher guidance scale value encourages the model to generate images closely linked to the text
705
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
706
+ negative_prompt (`str` or `List[str]`, *optional*):
707
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
708
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
709
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
710
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
711
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
712
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
713
+ The number of images to generate per prompt.
714
+ eta (`float`, *optional*, defaults to 0.0):
715
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
716
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
717
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
718
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
719
+ generation deterministic.
720
+ latents (`torch.FloatTensor`, *optional*):
721
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
722
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
723
+ tensor is generated by sampling using the supplied random `generator`.
724
+ prompt_embeds (`torch.FloatTensor`, *optional*):
725
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
726
+ provided, text embeddings are generated from the `prompt` input argument.
727
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
728
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
729
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
730
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
731
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
732
+ not provided, pooled text embeddings are generated from `prompt` input argument.
733
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
734
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
735
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
736
+ argument.
737
+ image_embeds (`torch.FloatTensor`, *optional*):
738
+ Pre-generated image embeddings.
739
+ output_type (`str`, *optional*, defaults to `"pil"`):
740
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
741
+ return_dict (`bool`, *optional*, defaults to `True`):
742
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
743
+ plain tuple.
744
+ cross_attention_kwargs (`dict`, *optional*):
745
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
746
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
747
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
748
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
749
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
750
+ the corresponding scale as a list.
751
+ guess_mode (`bool`, *optional*, defaults to `False`):
752
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
753
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
754
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
755
+ The percentage of total steps at which the ControlNet starts applying.
756
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
757
+ The percentage of total steps at which the ControlNet stops applying.
758
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
759
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
760
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
761
+ explained in section 2.2 of
762
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
763
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
764
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
765
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
766
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
767
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
768
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
769
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
770
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
771
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
772
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
773
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
774
+ micro-conditioning as explained in section 2.2 of
775
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
776
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
777
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
778
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
779
+ micro-conditioning as explained in section 2.2 of
780
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
781
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
782
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
783
+ To negatively condition the generation process based on a target image resolution. It should be as same
784
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
785
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
786
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
787
+ clip_skip (`int`, *optional*):
788
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
789
+ the output of the pre-final layer will be used for computing the prompt embeddings.
790
+ callback_on_step_end (`Callable`, *optional*):
791
+ A function that calls at the end of each denoising steps during the inference. The function is called
792
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
793
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
794
+ `callback_on_step_end_tensor_inputs`.
795
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
796
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
797
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
798
+ `._callback_tensor_inputs` attribute of your pipeine class.
799
+
800
+ Examples:
801
+
802
+ Returns:
803
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
804
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
805
+ otherwise a `tuple` is returned containing the output images.
806
+ """
807
+
808
+ lpw = LongPromptWeight()
809
+
810
+ callback = kwargs.pop("callback", None)
811
+ callback_steps = kwargs.pop("callback_steps", None)
812
+
813
+ if callback is not None:
814
+ deprecate(
815
+ "callback",
816
+ "1.0.0",
817
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
818
+ )
819
+ if callback_steps is not None:
820
+ deprecate(
821
+ "callback_steps",
822
+ "1.0.0",
823
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
824
+ )
825
+
826
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
827
+
828
+ # align format for control guidance
829
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
830
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
831
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
832
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
833
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
834
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
835
+ control_guidance_start, control_guidance_end = (
836
+ mult * [control_guidance_start],
837
+ mult * [control_guidance_end],
838
+ )
839
+
840
+ # 0. set ip_adapter_scale
841
+ if ip_adapter_scale is not None:
842
+ self.set_ip_adapter_scale(ip_adapter_scale)
843
+
844
+ # 1. Check inputs. Raise error if not correct
845
+ self.check_inputs(
846
+ prompt=prompt,
847
+ prompt_2=prompt_2,
848
+ image=image,
849
+ callback_steps=callback_steps,
850
+ negative_prompt=negative_prompt,
851
+ negative_prompt_2=negative_prompt_2,
852
+ prompt_embeds=prompt_embeds,
853
+ negative_prompt_embeds=negative_prompt_embeds,
854
+ pooled_prompt_embeds=pooled_prompt_embeds,
855
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
856
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
857
+ control_guidance_start=control_guidance_start,
858
+ control_guidance_end=control_guidance_end,
859
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
860
+ )
861
+
862
+ self._guidance_scale = guidance_scale
863
+ self._clip_skip = clip_skip
864
+ self._cross_attention_kwargs = cross_attention_kwargs
865
+
866
+ # 2. Define call parameters
867
+ if prompt is not None and isinstance(prompt, str):
868
+ batch_size = 1
869
+ elif prompt is not None and isinstance(prompt, list):
870
+ batch_size = len(prompt)
871
+ else:
872
+ batch_size = prompt_embeds.shape[0]
873
+
874
+ device = self._execution_device
875
+
876
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
877
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
878
+
879
+ global_pool_conditions = (
880
+ controlnet.config.global_pool_conditions
881
+ if isinstance(controlnet, ControlNetModel)
882
+ else controlnet.nets[0].config.global_pool_conditions
883
+ )
884
+ guess_mode = guess_mode or global_pool_conditions
885
+
886
+ # 3.1 Encode input prompt
887
+ (
888
+ prompt_embeds,
889
+ negative_prompt_embeds,
890
+ pooled_prompt_embeds,
891
+ negative_pooled_prompt_embeds,
892
+ ) = lpw.get_weighted_text_embeddings_sdxl(
893
+ pipe=self,
894
+ prompt=prompt,
895
+ neg_prompt=negative_prompt,
896
+ prompt_embeds=prompt_embeds,
897
+ negative_prompt_embeds=negative_prompt_embeds,
898
+ pooled_prompt_embeds=pooled_prompt_embeds,
899
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
900
+ )
901
+
902
+ # 3.2 Encode image prompt
903
+ prompt_image_emb = self._encode_prompt_image_emb(image_embeds,
904
+ device,
905
+ num_images_per_prompt,
906
+ self.unet.dtype,
907
+ self.do_classifier_free_guidance)
908
+
909
+ # 4. Prepare image
910
+ if isinstance(controlnet, ControlNetModel):
911
+ image = self.prepare_image(
912
+ image=image,
913
+ width=width,
914
+ height=height,
915
+ batch_size=batch_size * num_images_per_prompt,
916
+ num_images_per_prompt=num_images_per_prompt,
917
+ device=device,
918
+ dtype=controlnet.dtype,
919
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
920
+ guess_mode=guess_mode,
921
+ )
922
+ height, width = image.shape[-2:]
923
+ elif isinstance(controlnet, MultiControlNetModel):
924
+ images = []
925
+
926
+ for image_ in image:
927
+ image_ = self.prepare_image(
928
+ image=image_,
929
+ width=width,
930
+ height=height,
931
+ batch_size=batch_size * num_images_per_prompt,
932
+ num_images_per_prompt=num_images_per_prompt,
933
+ device=device,
934
+ dtype=controlnet.dtype,
935
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
936
+ guess_mode=guess_mode,
937
+ )
938
+
939
+ images.append(image_)
940
+
941
+ image = images
942
+ height, width = image[0].shape[-2:]
943
+ else:
944
+ assert False
945
+
946
+ # 4.1 Region control
947
+ if control_mask is not None:
948
+ mask_weight_image = control_mask
949
+ mask_weight_image = np.array(mask_weight_image)
950
+ mask_weight_image_tensor = torch.from_numpy(mask_weight_image).to(device=device, dtype=prompt_embeds.dtype)
951
+ mask_weight_image_tensor = mask_weight_image_tensor[:, :, 0] / 255.
952
+ mask_weight_image_tensor = mask_weight_image_tensor[None, None]
953
+ h, w = mask_weight_image_tensor.shape[-2:]
954
+ control_mask_wight_image_list = []
955
+ for scale in [8, 8, 8, 16, 16, 16, 32, 32, 32]:
956
+ scale_mask_weight_image_tensor = F.interpolate(
957
+ mask_weight_image_tensor,(h // scale, w // scale), mode='bilinear')
958
+ control_mask_wight_image_list.append(scale_mask_weight_image_tensor)
959
+ region_mask = torch.from_numpy(np.array(control_mask)[:, :, 0]).to(self.unet.device, dtype=self.unet.dtype) / 255.
960
+ region_control.prompt_image_conditioning = [dict(region_mask=region_mask)]
961
+ else:
962
+ control_mask_wight_image_list = None
963
+ region_control.prompt_image_conditioning = [dict(region_mask=None)]
964
+
965
+ # 5. Prepare timesteps
966
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
967
+ timesteps = self.scheduler.timesteps
968
+ self._num_timesteps = len(timesteps)
969
+
970
+ # 6. Prepare latent variables
971
+ num_channels_latents = self.unet.config.in_channels
972
+ latents = self.prepare_latents(
973
+ batch_size * num_images_per_prompt,
974
+ num_channels_latents,
975
+ height,
976
+ width,
977
+ prompt_embeds.dtype,
978
+ device,
979
+ generator,
980
+ latents,
981
+ )
982
+
983
+ # 6.5 Optionally get Guidance Scale Embedding
984
+ timestep_cond = None
985
+ if self.unet.config.time_cond_proj_dim is not None:
986
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
987
+ timestep_cond = self.get_guidance_scale_embedding(
988
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
989
+ ).to(device=device, dtype=latents.dtype)
990
+
991
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
992
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
993
+
994
+ # 7.1 Create tensor stating which controlnets to keep
995
+ controlnet_keep = []
996
+ for i in range(len(timesteps)):
997
+ keeps = [
998
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
999
+ for s, e in zip(control_guidance_start, control_guidance_end)
1000
+ ]
1001
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
1002
+
1003
+ # 7.2 Prepare added time ids & embeddings
1004
+ if isinstance(image, list):
1005
+ original_size = original_size or image[0].shape[-2:]
1006
+ else:
1007
+ original_size = original_size or image.shape[-2:]
1008
+ target_size = target_size or (height, width)
1009
+
1010
+ add_text_embeds = pooled_prompt_embeds
1011
+ if self.text_encoder_2 is None:
1012
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
1013
+ else:
1014
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
1015
+
1016
+ add_time_ids = self._get_add_time_ids(
1017
+ original_size,
1018
+ crops_coords_top_left,
1019
+ target_size,
1020
+ dtype=prompt_embeds.dtype,
1021
+ text_encoder_projection_dim=text_encoder_projection_dim,
1022
+ )
1023
+
1024
+ if negative_original_size is not None and negative_target_size is not None:
1025
+ negative_add_time_ids = self._get_add_time_ids(
1026
+ negative_original_size,
1027
+ negative_crops_coords_top_left,
1028
+ negative_target_size,
1029
+ dtype=prompt_embeds.dtype,
1030
+ text_encoder_projection_dim=text_encoder_projection_dim,
1031
+ )
1032
+ else:
1033
+ negative_add_time_ids = add_time_ids
1034
+
1035
+ if self.do_classifier_free_guidance:
1036
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1037
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1038
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1039
+
1040
+ prompt_embeds = prompt_embeds.to(device)
1041
+ add_text_embeds = add_text_embeds.to(device)
1042
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1043
+ encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
1044
+
1045
+ # 8. Denoising loop
1046
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1047
+ is_unet_compiled = is_compiled_module(self.unet)
1048
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
1049
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1050
+
1051
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1052
+ for i, t in enumerate(timesteps):
1053
+ # Relevant thread:
1054
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1055
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1056
+ torch._inductor.cudagraph_mark_step_begin()
1057
+ # expand the latents if we are doing classifier free guidance
1058
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1059
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1060
+
1061
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1062
+
1063
+ # controlnet(s) inference
1064
+ if guess_mode and self.do_classifier_free_guidance:
1065
+ # Infer ControlNet only for the conditional batch.
1066
+ control_model_input = latents
1067
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1068
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1069
+ controlnet_added_cond_kwargs = {
1070
+ "text_embeds": add_text_embeds.chunk(2)[1],
1071
+ "time_ids": add_time_ids.chunk(2)[1],
1072
+ }
1073
+ else:
1074
+ control_model_input = latent_model_input
1075
+ controlnet_prompt_embeds = prompt_embeds
1076
+ controlnet_added_cond_kwargs = added_cond_kwargs
1077
+
1078
+ if isinstance(controlnet_keep[i], list):
1079
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1080
+ else:
1081
+ controlnet_cond_scale = controlnet_conditioning_scale
1082
+ if isinstance(controlnet_cond_scale, list):
1083
+ controlnet_cond_scale = controlnet_cond_scale[0]
1084
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
1085
+
1086
+ if isinstance(self.controlnet, MultiControlNetModel):
1087
+ down_block_res_samples_list, mid_block_res_sample_list = [], []
1088
+ for control_index in range(len(self.controlnet.nets)):
1089
+ controlnet = self.controlnet.nets[control_index]
1090
+ if control_index == 0:
1091
+ # assume fhe first controlnet is IdentityNet
1092
+ controlnet_prompt_embeds = prompt_image_emb
1093
+ else:
1094
+ controlnet_prompt_embeds = prompt_embeds
1095
+ down_block_res_samples, mid_block_res_sample = controlnet(control_model_input,
1096
+ t,
1097
+ encoder_hidden_states=controlnet_prompt_embeds,
1098
+ controlnet_cond=image[control_index],
1099
+ conditioning_scale=cond_scale[control_index],
1100
+ guess_mode=guess_mode,
1101
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1102
+ return_dict=False)
1103
+
1104
+ # controlnet mask
1105
+ if control_index == 0 and control_mask_wight_image_list is not None:
1106
+ down_block_res_samples = [
1107
+ down_block_res_sample * mask_weight
1108
+ for down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)
1109
+ ]
1110
+ mid_block_res_sample *= control_mask_wight_image_list[-1]
1111
+
1112
+ down_block_res_samples_list.append(down_block_res_samples)
1113
+ mid_block_res_sample_list.append(mid_block_res_sample)
1114
+
1115
+ mid_block_res_sample = torch.stack(mid_block_res_sample_list).sum(dim=0)
1116
+ down_block_res_samples = [torch.stack(down_block_res_samples).sum(dim=0) for down_block_res_samples in
1117
+ zip(*down_block_res_samples_list)]
1118
+ else:
1119
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
1120
+ control_model_input,
1121
+ t,
1122
+ encoder_hidden_states=prompt_image_emb,
1123
+ controlnet_cond=image,
1124
+ conditioning_scale=cond_scale,
1125
+ guess_mode=guess_mode,
1126
+ added_cond_kwargs=controlnet_added_cond_kwargs,
1127
+ return_dict=False,
1128
+ )
1129
+
1130
+ # controlnet mask
1131
+ if control_mask_wight_image_list is not None:
1132
+ down_block_res_samples = [
1133
+ down_block_res_sample * mask_weight
1134
+ for down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)
1135
+ ]
1136
+ mid_block_res_sample *= control_mask_wight_image_list[-1]
1137
+
1138
+ if guess_mode and self.do_classifier_free_guidance:
1139
+ # Infered ControlNet only for the conditional batch.
1140
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1141
+ # add 0 to the unconditional batch to keep it unchanged.
1142
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1143
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1144
+
1145
+ # predict the noise residual
1146
+ noise_pred = self.unet(
1147
+ latent_model_input,
1148
+ t,
1149
+ encoder_hidden_states=encoder_hidden_states,
1150
+ timestep_cond=timestep_cond,
1151
+ cross_attention_kwargs=self.cross_attention_kwargs,
1152
+ down_block_additional_residuals=down_block_res_samples,
1153
+ mid_block_additional_residual=mid_block_res_sample,
1154
+ added_cond_kwargs=added_cond_kwargs,
1155
+ return_dict=False,
1156
+ )[0]
1157
+
1158
+ # perform guidance
1159
+ if self.do_classifier_free_guidance:
1160
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1161
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1162
+
1163
+ # compute the previous noisy sample x_t -> x_t-1
1164
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1165
+
1166
+ if callback_on_step_end is not None:
1167
+ callback_kwargs = {}
1168
+ for k in callback_on_step_end_tensor_inputs:
1169
+ callback_kwargs[k] = locals()[k]
1170
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1171
+
1172
+ latents = callback_outputs.pop("latents", latents)
1173
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1174
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1175
+
1176
+ # call the callback, if provided
1177
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1178
+ progress_bar.update()
1179
+ if callback is not None and i % callback_steps == 0:
1180
+ step_idx = i // getattr(self.scheduler, "order", 1)
1181
+ callback(step_idx, t, latents)
1182
+
1183
+ if not output_type == "latent":
1184
+ # make sure the VAE is in float32 mode, as it overflows in float16
1185
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1186
+
1187
+ if needs_upcasting:
1188
+ self.upcast_vae()
1189
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1190
+
1191
+ # unscale/denormalize the latents
1192
+ # denormalize with the mean and std if available and not None
1193
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
1194
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
1195
+ if has_latents_mean and has_latents_std:
1196
+ latents_mean = (
1197
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1198
+ )
1199
+ latents_std = (
1200
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
1201
+ )
1202
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
1203
+ else:
1204
+ latents = latents / self.vae.config.scaling_factor
1205
+
1206
+ image = self.vae.decode(latents, return_dict=False)[0]
1207
+
1208
+ # cast back to fp16 if needed
1209
+ if needs_upcasting:
1210
+ self.vae.to(dtype=torch.float16)
1211
+ else:
1212
+ image = latents
1213
+
1214
+ if not output_type == "latent":
1215
+ # apply watermark if available
1216
+ if self.watermark is not None:
1217
+ image = self.watermark.apply_watermark(image)
1218
+
1219
+ image = self.image_processor.postprocess(image, output_type=output_type)
1220
+
1221
+ # Offload all models
1222
+ self.maybe_free_model_hooks()
1223
+
1224
+ if not return_dict:
1225
+ return (image,)
1226
+
1227
+ return StableDiffusionXLPipelineOutput(images=image)