multimodalart HF staff commited on
Commit
be88838
1 Parent(s): 8e4e611

Upload 4 files

Browse files
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")
pipeline_stable_diffusion_xl_instantid_img2img.py ADDED
@@ -0,0 +1,1072 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import math
17
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
18
+
19
+ import cv2
20
+ import numpy as np
21
+ import PIL.Image
22
+ import torch
23
+ import torch.nn as nn
24
+
25
+ from diffusers import StableDiffusionXLControlNetImg2ImgPipeline
26
+ from diffusers.image_processor import PipelineImageInput
27
+ from diffusers.models import ControlNetModel
28
+ from diffusers.pipelines.controlnet.multicontrolnet import MultiControlNetModel
29
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
30
+ from diffusers.utils import (
31
+ deprecate,
32
+ logging,
33
+ replace_example_docstring,
34
+ )
35
+ from diffusers.utils.import_utils import is_xformers_available
36
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version
37
+
38
+
39
+ try:
40
+ import xformers
41
+ import xformers.ops
42
+
43
+ xformers_available = True
44
+ except Exception:
45
+ xformers_available = False
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+
50
+ def FeedForward(dim, mult=4):
51
+ inner_dim = int(dim * mult)
52
+ return nn.Sequential(
53
+ nn.LayerNorm(dim),
54
+ nn.Linear(dim, inner_dim, bias=False),
55
+ nn.GELU(),
56
+ nn.Linear(inner_dim, dim, bias=False),
57
+ )
58
+
59
+
60
+ def reshape_tensor(x, heads):
61
+ bs, length, width = x.shape
62
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
63
+ x = x.view(bs, length, heads, -1)
64
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
65
+ x = x.transpose(1, 2)
66
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
67
+ x = x.reshape(bs, heads, length, -1)
68
+ return x
69
+
70
+
71
+ class PerceiverAttention(nn.Module):
72
+ def __init__(self, *, dim, dim_head=64, heads=8):
73
+ super().__init__()
74
+ self.scale = dim_head**-0.5
75
+ self.dim_head = dim_head
76
+ self.heads = heads
77
+ inner_dim = dim_head * heads
78
+
79
+ self.norm1 = nn.LayerNorm(dim)
80
+ self.norm2 = nn.LayerNorm(dim)
81
+
82
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
83
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
84
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
85
+
86
+ def forward(self, x, latents):
87
+ """
88
+ Args:
89
+ x (torch.Tensor): image features
90
+ shape (b, n1, D)
91
+ latent (torch.Tensor): latent features
92
+ shape (b, n2, D)
93
+ """
94
+ x = self.norm1(x)
95
+ latents = self.norm2(latents)
96
+
97
+ b, l, _ = latents.shape
98
+
99
+ q = self.to_q(latents)
100
+ kv_input = torch.cat((x, latents), dim=-2)
101
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
102
+
103
+ q = reshape_tensor(q, self.heads)
104
+ k = reshape_tensor(k, self.heads)
105
+ v = reshape_tensor(v, self.heads)
106
+
107
+ # attention
108
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
109
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
110
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
111
+ out = weight @ v
112
+
113
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
114
+
115
+ return self.to_out(out)
116
+
117
+
118
+ class Resampler(nn.Module):
119
+ def __init__(
120
+ self,
121
+ dim=1024,
122
+ depth=8,
123
+ dim_head=64,
124
+ heads=16,
125
+ num_queries=8,
126
+ embedding_dim=768,
127
+ output_dim=1024,
128
+ ff_mult=4,
129
+ ):
130
+ super().__init__()
131
+
132
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
133
+
134
+ self.proj_in = nn.Linear(embedding_dim, dim)
135
+
136
+ self.proj_out = nn.Linear(dim, output_dim)
137
+ self.norm_out = nn.LayerNorm(output_dim)
138
+
139
+ self.layers = nn.ModuleList([])
140
+ for _ in range(depth):
141
+ self.layers.append(
142
+ nn.ModuleList(
143
+ [
144
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
145
+ FeedForward(dim=dim, mult=ff_mult),
146
+ ]
147
+ )
148
+ )
149
+
150
+ def forward(self, x):
151
+ latents = self.latents.repeat(x.size(0), 1, 1)
152
+ x = self.proj_in(x)
153
+
154
+ for attn, ff in self.layers:
155
+ latents = attn(x, latents) + latents
156
+ latents = ff(latents) + latents
157
+
158
+ latents = self.proj_out(latents)
159
+ return self.norm_out(latents)
160
+
161
+
162
+ class AttnProcessor(nn.Module):
163
+ r"""
164
+ Default processor for performing attention-related computations.
165
+ """
166
+
167
+ def __init__(
168
+ self,
169
+ hidden_size=None,
170
+ cross_attention_dim=None,
171
+ ):
172
+ super().__init__()
173
+
174
+ def __call__(
175
+ self,
176
+ attn,
177
+ hidden_states,
178
+ encoder_hidden_states=None,
179
+ attention_mask=None,
180
+ temb=None,
181
+ ):
182
+ residual = hidden_states
183
+
184
+ if attn.spatial_norm is not None:
185
+ hidden_states = attn.spatial_norm(hidden_states, temb)
186
+
187
+ input_ndim = hidden_states.ndim
188
+
189
+ if input_ndim == 4:
190
+ batch_size, channel, height, width = hidden_states.shape
191
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
192
+
193
+ batch_size, sequence_length, _ = (
194
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
195
+ )
196
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
197
+
198
+ if attn.group_norm is not None:
199
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
200
+
201
+ query = attn.to_q(hidden_states)
202
+
203
+ if encoder_hidden_states is None:
204
+ encoder_hidden_states = hidden_states
205
+ elif attn.norm_cross:
206
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
207
+
208
+ key = attn.to_k(encoder_hidden_states)
209
+ value = attn.to_v(encoder_hidden_states)
210
+
211
+ query = attn.head_to_batch_dim(query)
212
+ key = attn.head_to_batch_dim(key)
213
+ value = attn.head_to_batch_dim(value)
214
+
215
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
216
+ hidden_states = torch.bmm(attention_probs, value)
217
+ hidden_states = attn.batch_to_head_dim(hidden_states)
218
+
219
+ # linear proj
220
+ hidden_states = attn.to_out[0](hidden_states)
221
+ # dropout
222
+ hidden_states = attn.to_out[1](hidden_states)
223
+
224
+ if input_ndim == 4:
225
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
226
+
227
+ if attn.residual_connection:
228
+ hidden_states = hidden_states + residual
229
+
230
+ hidden_states = hidden_states / attn.rescale_output_factor
231
+
232
+ return hidden_states
233
+
234
+
235
+ class IPAttnProcessor(nn.Module):
236
+ r"""
237
+ Attention processor for IP-Adapater.
238
+ Args:
239
+ hidden_size (`int`):
240
+ The hidden size of the attention layer.
241
+ cross_attention_dim (`int`):
242
+ The number of channels in the `encoder_hidden_states`.
243
+ scale (`float`, defaults to 1.0):
244
+ the weight scale of image prompt.
245
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
246
+ The context length of the image features.
247
+ """
248
+
249
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
250
+ super().__init__()
251
+
252
+ self.hidden_size = hidden_size
253
+ self.cross_attention_dim = cross_attention_dim
254
+ self.scale = scale
255
+ self.num_tokens = num_tokens
256
+
257
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
258
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
259
+
260
+ def __call__(
261
+ self,
262
+ attn,
263
+ hidden_states,
264
+ encoder_hidden_states=None,
265
+ attention_mask=None,
266
+ temb=None,
267
+ ):
268
+ residual = hidden_states
269
+
270
+ if attn.spatial_norm is not None:
271
+ hidden_states = attn.spatial_norm(hidden_states, temb)
272
+
273
+ input_ndim = hidden_states.ndim
274
+
275
+ if input_ndim == 4:
276
+ batch_size, channel, height, width = hidden_states.shape
277
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
278
+
279
+ batch_size, sequence_length, _ = (
280
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
281
+ )
282
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
283
+
284
+ if attn.group_norm is not None:
285
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
286
+
287
+ query = attn.to_q(hidden_states)
288
+
289
+ if encoder_hidden_states is None:
290
+ encoder_hidden_states = hidden_states
291
+ else:
292
+ # get encoder_hidden_states, ip_hidden_states
293
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
294
+ encoder_hidden_states, ip_hidden_states = (
295
+ encoder_hidden_states[:, :end_pos, :],
296
+ encoder_hidden_states[:, end_pos:, :],
297
+ )
298
+ if attn.norm_cross:
299
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
300
+
301
+ key = attn.to_k(encoder_hidden_states)
302
+ value = attn.to_v(encoder_hidden_states)
303
+
304
+ query = attn.head_to_batch_dim(query)
305
+ key = attn.head_to_batch_dim(key)
306
+ value = attn.head_to_batch_dim(value)
307
+
308
+ if xformers_available:
309
+ hidden_states = self._memory_efficient_attention_xformers(query, key, value, attention_mask)
310
+ else:
311
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
312
+ hidden_states = torch.bmm(attention_probs, value)
313
+ hidden_states = attn.batch_to_head_dim(hidden_states)
314
+
315
+ # for ip-adapter
316
+ ip_key = self.to_k_ip(ip_hidden_states)
317
+ ip_value = self.to_v_ip(ip_hidden_states)
318
+
319
+ ip_key = attn.head_to_batch_dim(ip_key)
320
+ ip_value = attn.head_to_batch_dim(ip_value)
321
+
322
+ if xformers_available:
323
+ ip_hidden_states = self._memory_efficient_attention_xformers(query, ip_key, ip_value, None)
324
+ else:
325
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
326
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
327
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
328
+
329
+ hidden_states = hidden_states + self.scale * ip_hidden_states
330
+
331
+ # linear proj
332
+ hidden_states = attn.to_out[0](hidden_states)
333
+ # dropout
334
+ hidden_states = attn.to_out[1](hidden_states)
335
+
336
+ if input_ndim == 4:
337
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
338
+
339
+ if attn.residual_connection:
340
+ hidden_states = hidden_states + residual
341
+
342
+ hidden_states = hidden_states / attn.rescale_output_factor
343
+
344
+ return hidden_states
345
+
346
+ def _memory_efficient_attention_xformers(self, query, key, value, attention_mask):
347
+ # TODO attention_mask
348
+ query = query.contiguous()
349
+ key = key.contiguous()
350
+ value = value.contiguous()
351
+ hidden_states = xformers.ops.memory_efficient_attention(query, key, value, attn_bias=attention_mask)
352
+ return hidden_states
353
+
354
+
355
+ EXAMPLE_DOC_STRING = """
356
+ Examples:
357
+ ```py
358
+ >>> # !pip install opencv-python transformers accelerate insightface
359
+ >>> import diffusers
360
+ >>> from diffusers.utils import load_image
361
+ >>> from diffusers.models import ControlNetModel
362
+
363
+ >>> import cv2
364
+ >>> import torch
365
+ >>> import numpy as np
366
+ >>> from PIL import Image
367
+
368
+ >>> from insightface.app import FaceAnalysis
369
+ >>> from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps
370
+
371
+ >>> # download 'antelopev2' under ./models
372
+ >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
373
+ >>> app.prepare(ctx_id=0, det_size=(640, 640))
374
+
375
+ >>> # download models under ./checkpoints
376
+ >>> face_adapter = f'./checkpoints/ip-adapter.bin'
377
+ >>> controlnet_path = f'./checkpoints/ControlNetModel'
378
+
379
+ >>> # load IdentityNet
380
+ >>> controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
381
+
382
+ >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
383
+ ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
384
+ ... )
385
+ >>> pipe.cuda()
386
+
387
+ >>> # load adapter
388
+ >>> pipe.load_ip_adapter_instantid(face_adapter)
389
+
390
+ >>> 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"
391
+ >>> 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"
392
+
393
+ >>> # load an image
394
+ >>> image = load_image("your-example.jpg")
395
+
396
+ >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1]
397
+ >>> face_emb = face_info['embedding']
398
+ >>> face_kps = draw_kps(face_image, face_info['kps'])
399
+
400
+ >>> pipe.set_ip_adapter_scale(0.8)
401
+
402
+ >>> # generate image
403
+ >>> image = pipe(
404
+ ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8
405
+ ... ).images[0]
406
+ ```
407
+ """
408
+
409
+
410
+ def draw_kps(image_pil, kps, color_list=[(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255)]):
411
+ stickwidth = 4
412
+ limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
413
+ kps = np.array(kps)
414
+
415
+ w, h = image_pil.size
416
+ out_img = np.zeros([h, w, 3])
417
+
418
+ for i in range(len(limbSeq)):
419
+ index = limbSeq[i]
420
+ color = color_list[index[0]]
421
+
422
+ x = kps[index][:, 0]
423
+ y = kps[index][:, 1]
424
+ length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
425
+ angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
426
+ polygon = cv2.ellipse2Poly(
427
+ (int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1
428
+ )
429
+ out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
430
+ out_img = (out_img * 0.6).astype(np.uint8)
431
+
432
+ for idx_kp, kp in enumerate(kps):
433
+ color = color_list[idx_kp]
434
+ x, y = kp
435
+ out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
436
+
437
+ out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))
438
+ return out_img_pil
439
+
440
+
441
+ class StableDiffusionXLInstantIDImg2ImgPipeline(StableDiffusionXLControlNetImg2ImgPipeline):
442
+ def cuda(self, dtype=torch.float16, use_xformers=False):
443
+ self.to("cuda", dtype)
444
+
445
+ if hasattr(self, "image_proj_model"):
446
+ self.image_proj_model.to(self.unet.device).to(self.unet.dtype)
447
+
448
+ if use_xformers:
449
+ if is_xformers_available():
450
+ import xformers
451
+ from packaging import version
452
+
453
+ xformers_version = version.parse(xformers.__version__)
454
+ if xformers_version == version.parse("0.0.16"):
455
+ logger.warning(
456
+ "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."
457
+ )
458
+ self.enable_xformers_memory_efficient_attention()
459
+ else:
460
+ raise ValueError("xformers is not available. Make sure it is installed correctly")
461
+
462
+ def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=0.5):
463
+ self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens)
464
+ self.set_ip_adapter(model_ckpt, num_tokens, scale)
465
+
466
+ def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16):
467
+ image_proj_model = Resampler(
468
+ dim=1280,
469
+ depth=4,
470
+ dim_head=64,
471
+ heads=20,
472
+ num_queries=num_tokens,
473
+ embedding_dim=image_emb_dim,
474
+ output_dim=self.unet.config.cross_attention_dim,
475
+ ff_mult=4,
476
+ )
477
+
478
+ image_proj_model.eval()
479
+
480
+ self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype)
481
+ state_dict = torch.load(model_ckpt, map_location="cpu")
482
+ if "image_proj" in state_dict:
483
+ state_dict = state_dict["image_proj"]
484
+ self.image_proj_model.load_state_dict(state_dict)
485
+
486
+ self.image_proj_model_in_features = image_emb_dim
487
+
488
+ def set_ip_adapter(self, model_ckpt, num_tokens, scale):
489
+ unet = self.unet
490
+ attn_procs = {}
491
+ for name in unet.attn_processors.keys():
492
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
493
+ if name.startswith("mid_block"):
494
+ hidden_size = unet.config.block_out_channels[-1]
495
+ elif name.startswith("up_blocks"):
496
+ block_id = int(name[len("up_blocks.")])
497
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
498
+ elif name.startswith("down_blocks"):
499
+ block_id = int(name[len("down_blocks.")])
500
+ hidden_size = unet.config.block_out_channels[block_id]
501
+ if cross_attention_dim is None:
502
+ attn_procs[name] = AttnProcessor().to(unet.device, dtype=unet.dtype)
503
+ else:
504
+ attn_procs[name] = IPAttnProcessor(
505
+ hidden_size=hidden_size,
506
+ cross_attention_dim=cross_attention_dim,
507
+ scale=scale,
508
+ num_tokens=num_tokens,
509
+ ).to(unet.device, dtype=unet.dtype)
510
+ unet.set_attn_processor(attn_procs)
511
+
512
+ state_dict = torch.load(model_ckpt, map_location="cpu")
513
+ ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
514
+ if "ip_adapter" in state_dict:
515
+ state_dict = state_dict["ip_adapter"]
516
+ ip_layers.load_state_dict(state_dict)
517
+
518
+ def set_ip_adapter_scale(self, scale):
519
+ unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
520
+ for attn_processor in unet.attn_processors.values():
521
+ if isinstance(attn_processor, IPAttnProcessor):
522
+ attn_processor.scale = scale
523
+
524
+ def _encode_prompt_image_emb(self, prompt_image_emb, device, dtype, do_classifier_free_guidance):
525
+ if isinstance(prompt_image_emb, torch.Tensor):
526
+ prompt_image_emb = prompt_image_emb.clone().detach()
527
+ else:
528
+ prompt_image_emb = torch.tensor(prompt_image_emb)
529
+
530
+ prompt_image_emb = prompt_image_emb.to(device=device, dtype=dtype)
531
+ prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features])
532
+
533
+ if do_classifier_free_guidance:
534
+ prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0)
535
+ else:
536
+ prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
537
+
538
+ prompt_image_emb = self.image_proj_model(prompt_image_emb)
539
+ return prompt_image_emb
540
+
541
+ @torch.no_grad()
542
+ @replace_example_docstring(EXAMPLE_DOC_STRING)
543
+ def __call__(
544
+ self,
545
+ prompt: Union[str, List[str]] = None,
546
+ prompt_2: Optional[Union[str, List[str]]] = None,
547
+ image: PipelineImageInput = None,
548
+ control_image: PipelineImageInput = None,
549
+ strength: float = 0.8,
550
+ height: Optional[int] = None,
551
+ width: Optional[int] = None,
552
+ num_inference_steps: int = 50,
553
+ guidance_scale: float = 5.0,
554
+ negative_prompt: Optional[Union[str, List[str]]] = None,
555
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
556
+ num_images_per_prompt: Optional[int] = 1,
557
+ eta: float = 0.0,
558
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
559
+ latents: Optional[torch.FloatTensor] = None,
560
+ prompt_embeds: Optional[torch.FloatTensor] = None,
561
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
562
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
563
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
564
+ image_embeds: Optional[torch.FloatTensor] = None,
565
+ output_type: Optional[str] = "pil",
566
+ return_dict: bool = True,
567
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
568
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
569
+ guess_mode: bool = False,
570
+ control_guidance_start: Union[float, List[float]] = 0.0,
571
+ control_guidance_end: Union[float, List[float]] = 1.0,
572
+ original_size: Tuple[int, int] = None,
573
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
574
+ target_size: Tuple[int, int] = None,
575
+ negative_original_size: Optional[Tuple[int, int]] = None,
576
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
577
+ negative_target_size: Optional[Tuple[int, int]] = None,
578
+ aesthetic_score: float = 6.0,
579
+ negative_aesthetic_score: float = 2.5,
580
+ clip_skip: Optional[int] = None,
581
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
582
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
583
+ **kwargs,
584
+ ):
585
+ r"""
586
+ The call function to the pipeline for generation.
587
+
588
+ Args:
589
+ prompt (`str` or `List[str]`, *optional*):
590
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
591
+ prompt_2 (`str` or `List[str]`, *optional*):
592
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
593
+ used in both text-encoders.
594
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
595
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
596
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
597
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
598
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
599
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
600
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
601
+ input to a single ControlNet.
602
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
603
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
604
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
605
+ and checkpoints that are not specifically fine-tuned on low resolutions.
606
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
607
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
608
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
609
+ and checkpoints that are not specifically fine-tuned on low resolutions.
610
+ num_inference_steps (`int`, *optional*, defaults to 50):
611
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
612
+ expense of slower inference.
613
+ guidance_scale (`float`, *optional*, defaults to 5.0):
614
+ A higher guidance scale value encourages the model to generate images closely linked to the text
615
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
616
+ negative_prompt (`str` or `List[str]`, *optional*):
617
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
618
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
619
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
620
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
621
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
622
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
623
+ The number of images to generate per prompt.
624
+ eta (`float`, *optional*, defaults to 0.0):
625
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
626
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
627
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
628
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
629
+ generation deterministic.
630
+ latents (`torch.FloatTensor`, *optional*):
631
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
632
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
633
+ tensor is generated by sampling using the supplied random `generator`.
634
+ prompt_embeds (`torch.FloatTensor`, *optional*):
635
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
636
+ provided, text embeddings are generated from the `prompt` input argument.
637
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
638
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
639
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
640
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
641
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
642
+ not provided, pooled text embeddings are generated from `prompt` input argument.
643
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
644
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
645
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
646
+ argument.
647
+ image_embeds (`torch.FloatTensor`, *optional*):
648
+ Pre-generated image embeddings.
649
+ output_type (`str`, *optional*, defaults to `"pil"`):
650
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
651
+ return_dict (`bool`, *optional*, defaults to `True`):
652
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
653
+ plain tuple.
654
+ cross_attention_kwargs (`dict`, *optional*):
655
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
656
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
657
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
658
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
659
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
660
+ the corresponding scale as a list.
661
+ guess_mode (`bool`, *optional*, defaults to `False`):
662
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
663
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
664
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
665
+ The percentage of total steps at which the ControlNet starts applying.
666
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
667
+ The percentage of total steps at which the ControlNet stops applying.
668
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
669
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
670
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
671
+ explained in section 2.2 of
672
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
673
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
674
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
675
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
676
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
677
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
678
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
679
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
680
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
681
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
682
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
683
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
684
+ micro-conditioning as explained in section 2.2 of
685
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
686
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
687
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
688
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
689
+ micro-conditioning as explained in section 2.2 of
690
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
691
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
692
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
693
+ To negatively condition the generation process based on a target image resolution. It should be as same
694
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
695
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
696
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
697
+ clip_skip (`int`, *optional*):
698
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
699
+ the output of the pre-final layer will be used for computing the prompt embeddings.
700
+ callback_on_step_end (`Callable`, *optional*):
701
+ A function that calls at the end of each denoising steps during the inference. The function is called
702
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
703
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
704
+ `callback_on_step_end_tensor_inputs`.
705
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
706
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
707
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
708
+ `._callback_tensor_inputs` attribute of your pipeline class.
709
+
710
+ Examples:
711
+
712
+ Returns:
713
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
714
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
715
+ otherwise a `tuple` is returned containing the output images.
716
+ """
717
+
718
+ callback = kwargs.pop("callback", None)
719
+ callback_steps = kwargs.pop("callback_steps", None)
720
+
721
+ if callback is not None:
722
+ deprecate(
723
+ "callback",
724
+ "1.0.0",
725
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
726
+ )
727
+ if callback_steps is not None:
728
+ deprecate(
729
+ "callback_steps",
730
+ "1.0.0",
731
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
732
+ )
733
+
734
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
735
+
736
+ # align format for control guidance
737
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
738
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
739
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
740
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
741
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
742
+ mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
743
+ control_guidance_start, control_guidance_end = (
744
+ mult * [control_guidance_start],
745
+ mult * [control_guidance_end],
746
+ )
747
+
748
+ # 1. Check inputs. Raise error if not correct
749
+ self.check_inputs(
750
+ prompt,
751
+ prompt_2,
752
+ control_image,
753
+ strength,
754
+ num_inference_steps,
755
+ callback_steps,
756
+ negative_prompt,
757
+ negative_prompt_2,
758
+ prompt_embeds,
759
+ negative_prompt_embeds,
760
+ pooled_prompt_embeds,
761
+ negative_pooled_prompt_embeds,
762
+ None,
763
+ None,
764
+ controlnet_conditioning_scale,
765
+ control_guidance_start,
766
+ control_guidance_end,
767
+ callback_on_step_end_tensor_inputs,
768
+ )
769
+
770
+ self._guidance_scale = guidance_scale
771
+ self._clip_skip = clip_skip
772
+ self._cross_attention_kwargs = cross_attention_kwargs
773
+
774
+ # 2. Define call parameters
775
+ if prompt is not None and isinstance(prompt, str):
776
+ batch_size = 1
777
+ elif prompt is not None and isinstance(prompt, list):
778
+ batch_size = len(prompt)
779
+ else:
780
+ batch_size = prompt_embeds.shape[0]
781
+
782
+ device = self._execution_device
783
+
784
+ if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
785
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
786
+
787
+ global_pool_conditions = (
788
+ controlnet.config.global_pool_conditions
789
+ if isinstance(controlnet, ControlNetModel)
790
+ else controlnet.nets[0].config.global_pool_conditions
791
+ )
792
+ guess_mode = guess_mode or global_pool_conditions
793
+
794
+ # 3.1 Encode input prompt
795
+ text_encoder_lora_scale = (
796
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
797
+ )
798
+ (
799
+ prompt_embeds,
800
+ negative_prompt_embeds,
801
+ pooled_prompt_embeds,
802
+ negative_pooled_prompt_embeds,
803
+ ) = self.encode_prompt(
804
+ prompt,
805
+ prompt_2,
806
+ device,
807
+ num_images_per_prompt,
808
+ self.do_classifier_free_guidance,
809
+ negative_prompt,
810
+ negative_prompt_2,
811
+ prompt_embeds=prompt_embeds,
812
+ negative_prompt_embeds=negative_prompt_embeds,
813
+ pooled_prompt_embeds=pooled_prompt_embeds,
814
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
815
+ lora_scale=text_encoder_lora_scale,
816
+ clip_skip=self.clip_skip,
817
+ )
818
+
819
+ # 3.2 Encode image prompt
820
+ prompt_image_emb = self._encode_prompt_image_emb(
821
+ image_embeds, device, self.unet.dtype, self.do_classifier_free_guidance
822
+ )
823
+ bs_embed, seq_len, _ = prompt_image_emb.shape
824
+ prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
825
+ prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
826
+
827
+ # 4. Prepare image and controlnet_conditioning_image
828
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
829
+
830
+ if isinstance(controlnet, ControlNetModel):
831
+ control_image = self.prepare_control_image(
832
+ image=control_image,
833
+ width=width,
834
+ height=height,
835
+ batch_size=batch_size * num_images_per_prompt,
836
+ num_images_per_prompt=num_images_per_prompt,
837
+ device=device,
838
+ dtype=controlnet.dtype,
839
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
840
+ guess_mode=guess_mode,
841
+ )
842
+ height, width = control_image.shape[-2:]
843
+ elif isinstance(controlnet, MultiControlNetModel):
844
+ control_images = []
845
+
846
+ for control_image_ in control_image:
847
+ control_image_ = self.prepare_control_image(
848
+ image=control_image_,
849
+ width=width,
850
+ height=height,
851
+ batch_size=batch_size * num_images_per_prompt,
852
+ num_images_per_prompt=num_images_per_prompt,
853
+ device=device,
854
+ dtype=controlnet.dtype,
855
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
856
+ guess_mode=guess_mode,
857
+ )
858
+
859
+ control_images.append(control_image_)
860
+
861
+ control_image = control_images
862
+ height, width = control_image[0].shape[-2:]
863
+ else:
864
+ assert False
865
+
866
+ # 5. Prepare timesteps
867
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
868
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
869
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
870
+ self._num_timesteps = len(timesteps)
871
+
872
+ # 6. Prepare latent variables
873
+ latents = self.prepare_latents(
874
+ image,
875
+ latent_timestep,
876
+ batch_size,
877
+ num_images_per_prompt,
878
+ prompt_embeds.dtype,
879
+ device,
880
+ generator,
881
+ True,
882
+ )
883
+
884
+ # # 6.5 Optionally get Guidance Scale Embedding
885
+ timestep_cond = None
886
+ if self.unet.config.time_cond_proj_dim is not None:
887
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
888
+ timestep_cond = self.get_guidance_scale_embedding(
889
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
890
+ ).to(device=device, dtype=latents.dtype)
891
+
892
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
893
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
894
+
895
+ # 7.1 Create tensor stating which controlnets to keep
896
+ controlnet_keep = []
897
+ for i in range(len(timesteps)):
898
+ keeps = [
899
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
900
+ for s, e in zip(control_guidance_start, control_guidance_end)
901
+ ]
902
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
903
+
904
+ # 7.2 Prepare added time ids & embeddings
905
+ if isinstance(control_image, list):
906
+ original_size = original_size or control_image[0].shape[-2:]
907
+ else:
908
+ original_size = original_size or control_image.shape[-2:]
909
+ target_size = target_size or (height, width)
910
+
911
+ if negative_original_size is None:
912
+ negative_original_size = original_size
913
+ if negative_target_size is None:
914
+ negative_target_size = target_size
915
+ add_text_embeds = pooled_prompt_embeds
916
+
917
+ if self.text_encoder_2 is None:
918
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
919
+ else:
920
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
921
+
922
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
923
+ original_size,
924
+ crops_coords_top_left,
925
+ target_size,
926
+ aesthetic_score,
927
+ negative_aesthetic_score,
928
+ negative_original_size,
929
+ negative_crops_coords_top_left,
930
+ negative_target_size,
931
+ dtype=prompt_embeds.dtype,
932
+ text_encoder_projection_dim=text_encoder_projection_dim,
933
+ )
934
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
935
+
936
+ if self.do_classifier_free_guidance:
937
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
938
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
939
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
940
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
941
+
942
+ prompt_embeds = prompt_embeds.to(device)
943
+ add_text_embeds = add_text_embeds.to(device)
944
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
945
+ encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
946
+
947
+ # 8. Denoising loop
948
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
949
+ is_unet_compiled = is_compiled_module(self.unet)
950
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
951
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
952
+
953
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
954
+ for i, t in enumerate(timesteps):
955
+ # Relevant thread:
956
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
957
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
958
+ torch._inductor.cudagraph_mark_step_begin()
959
+ # expand the latents if we are doing classifier free guidance
960
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
961
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
962
+
963
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
964
+
965
+ # controlnet(s) inference
966
+ if guess_mode and self.do_classifier_free_guidance:
967
+ # Infer ControlNet only for the conditional batch.
968
+ control_model_input = latents
969
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
970
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
971
+ controlnet_added_cond_kwargs = {
972
+ "text_embeds": add_text_embeds.chunk(2)[1],
973
+ "time_ids": add_time_ids.chunk(2)[1],
974
+ }
975
+ else:
976
+ control_model_input = latent_model_input
977
+ controlnet_prompt_embeds = prompt_embeds
978
+ controlnet_added_cond_kwargs = added_cond_kwargs
979
+
980
+ if isinstance(controlnet_keep[i], list):
981
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
982
+ else:
983
+ controlnet_cond_scale = controlnet_conditioning_scale
984
+ if isinstance(controlnet_cond_scale, list):
985
+ controlnet_cond_scale = controlnet_cond_scale[0]
986
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
987
+
988
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
989
+ control_model_input,
990
+ t,
991
+ encoder_hidden_states=prompt_image_emb,
992
+ controlnet_cond=control_image,
993
+ conditioning_scale=cond_scale,
994
+ guess_mode=guess_mode,
995
+ added_cond_kwargs=controlnet_added_cond_kwargs,
996
+ return_dict=False,
997
+ )
998
+
999
+ if guess_mode and self.do_classifier_free_guidance:
1000
+ # Infered ControlNet only for the conditional batch.
1001
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
1002
+ # add 0 to the unconditional batch to keep it unchanged.
1003
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1004
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1005
+
1006
+ # predict the noise residual
1007
+ noise_pred = self.unet(
1008
+ latent_model_input,
1009
+ t,
1010
+ encoder_hidden_states=encoder_hidden_states,
1011
+ timestep_cond=timestep_cond,
1012
+ cross_attention_kwargs=self.cross_attention_kwargs,
1013
+ down_block_additional_residuals=down_block_res_samples,
1014
+ mid_block_additional_residual=mid_block_res_sample,
1015
+ added_cond_kwargs=added_cond_kwargs,
1016
+ return_dict=False,
1017
+ )[0]
1018
+
1019
+ # perform guidance
1020
+ if self.do_classifier_free_guidance:
1021
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1022
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1023
+
1024
+ # compute the previous noisy sample x_t -> x_t-1
1025
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1026
+
1027
+ if callback_on_step_end is not None:
1028
+ callback_kwargs = {}
1029
+ for k in callback_on_step_end_tensor_inputs:
1030
+ callback_kwargs[k] = locals()[k]
1031
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1032
+
1033
+ latents = callback_outputs.pop("latents", latents)
1034
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1035
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1036
+
1037
+ # call the callback, if provided
1038
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1039
+ progress_bar.update()
1040
+ if callback is not None and i % callback_steps == 0:
1041
+ step_idx = i // getattr(self.scheduler, "order", 1)
1042
+ callback(step_idx, t, latents)
1043
+
1044
+ if not output_type == "latent":
1045
+ # make sure the VAE is in float32 mode, as it overflows in float16
1046
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1047
+ if needs_upcasting:
1048
+ self.upcast_vae()
1049
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1050
+
1051
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1052
+
1053
+ # cast back to fp16 if needed
1054
+ if needs_upcasting:
1055
+ self.vae.to(dtype=torch.float16)
1056
+ else:
1057
+ image = latents
1058
+
1059
+ if not output_type == "latent":
1060
+ # apply watermark if available
1061
+ if self.watermark is not None:
1062
+ image = self.watermark.apply_watermark(image)
1063
+
1064
+ image = self.image_processor.postprocess(image, output_type=output_type)
1065
+
1066
+ # Offload all models
1067
+ self.maybe_free_model_hooks()
1068
+
1069
+ if not return_dict:
1070
+ return (image,)
1071
+
1072
+ return StableDiffusionXLPipelineOutput(images=image)