Nad54 commited on
Commit
1eb99e8
·
verified ·
1 Parent(s): 38fd38e

Delete instantid

Browse files
instantid/ip_adapter/attention_processor.py DELETED
@@ -1,447 +0,0 @@
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
instantid/ip_adapter/resampler.py DELETED
@@ -1,121 +0,0 @@
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
instantid/ip_adapter/utils.py DELETED
@@ -1,5 +0,0 @@
1
- import torch.nn.functional as F
2
-
3
-
4
- def is_torch2_available():
5
- return hasattr(F, "scaled_dot_product_attention")
 
 
 
 
 
 
instantid/pipeline_stable_diffusion_xl_instantid_full.py DELETED
@@ -1,1184 +0,0 @@
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
- from ip_adapter.attention_processor import IPAttnProcessor, AttnProcessor
46
- from ip_adapter.attention_processor import region_control
47
-
48
- logger = logging.get_logger(__name__) # pylint: disable=invalid-name
49
-
50
-
51
- EXAMPLE_DOC_STRING = """
52
- Examples:
53
- ```py
54
- >>> # !pip install opencv-python transformers accelerate insightface
55
- >>> import diffusers
56
- >>> from diffusers.utils import load_image
57
- >>> from diffusers.models import ControlNetModel
58
- >>> import cv2
59
- >>> import torch
60
- >>> import numpy as np
61
- >>> from PIL import Image
62
-
63
- >>> from insightface.app import FaceAnalysis
64
- >>> from pipeline_stable_diffusion_xl_instantid import StableDiffusionXLInstantIDPipeline, draw_kps
65
- >>> # download 'antelopev2' under ./models
66
- >>> app = FaceAnalysis(name='antelopev2', root='./', providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
67
- >>> app.prepare(ctx_id=0, det_size=(640, 640))
68
-
69
- >>> # download models under ./checkpoints
70
- >>> face_adapter = f'./checkpoints/ip-adapter.bin'
71
- >>> controlnet_path = f'./checkpoints/ControlNetModel'
72
-
73
- >>> # load IdentityNet
74
- >>> controlnet = ControlNetModel.from_pretrained(controlnet_path, torch_dtype=torch.float16)
75
-
76
- >>> pipe = StableDiffusionXLInstantIDPipeline.from_pretrained(
77
- ... "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
78
- ... )
79
- >>> pipe.cuda()
80
-
81
- >>> # load adapter
82
- >>> pipe.load_ip_adapter_instantid(face_adapter)
83
- >>> 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"
84
- >>> 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"
85
- >>> # load an image
86
- >>> image = load_image("your-example.jpg")
87
-
88
- >>> face_info = app.get(cv2.cvtColor(np.array(face_image), cv2.COLOR_RGB2BGR))[-1]
89
- >>> face_emb = face_info['embedding']
90
- >>> face_kps = draw_kps(face_image, face_info['kps'])
91
-
92
- >>> pipe.set_ip_adapter_scale(0.8)
93
- >>> # generate image
94
- >>> image = pipe(
95
- ... prompt, image_embeds=face_emb, image=face_kps, controlnet_conditioning_scale=0.8
96
- ... ).images[0]
97
- ```
98
- """
99
-
100
- from transformers import CLIPTokenizer
101
- from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipeline
102
- class LongPromptWeight(object):
103
-
104
- """
105
- Copied from https://github.com/huggingface/diffusers/blob/main/examples/community/lpw_stable_diffusion_xl.py
106
- """
107
-
108
- def __init__(self) -> None:
109
- pass
110
-
111
- def parse_prompt_attention(self, text):
112
- """
113
- Parses a string with attention tokens and returns a list of pairs: text and its associated weight.
114
- Accepted tokens are:
115
- (abc) - increases attention to abc by a multiplier of 1.1
116
- (abc:3.12) - increases attention to abc by a multiplier of 3.12
117
- [abc] - decreases attention to abc by a multiplier of 1.1
118
- \( - literal character '('
119
- \[ - literal character '['
120
- \) - literal character ')'
121
- \] - literal character ']'
122
- \\ - literal character '\'
123
- anything else - just text
124
- >>> parse_prompt_attention('normal text')
125
- [['normal text', 1.0]]
126
- >>> parse_prompt_attention('an (important) word')
127
- [['an ', 1.0], ['important', 1.1], [' word', 1.0]]
128
- >>> parse_prompt_attention('(unbalanced')
129
- [['unbalanced', 1.1]]
130
- >>> parse_prompt_attention('\(literal\]')
131
- [['(literal]', 1.0]]
132
- >>> parse_prompt_attention('(unnecessary)(parens)')
133
- [['unnecessaryparens', 1.1]]
134
- >>> parse_prompt_attention('a (((house:1.3)) [on] a (hill:0.5), sun, (((sky))).')
135
- [['a ', 1.0],
136
- ['house', 1.5730000000000004],
137
- [' ', 1.1],
138
- ['on', 1.0],
139
- [' a ', 1.1],
140
- ['hill', 0.55],
141
- [', sun, ', 1.1],
142
- ['sky', 1.4641000000000006],
143
- ['.', 1.1]]
144
- """
145
- import re
146
-
147
- re_attention = re.compile(
148
- r"""
149
- \\\(|\\\)|\\\[|\\]|\\\\|\\|\(|\[|:([+-]?[.\d]+)\)|
150
- \)|]|[^\\()\[\]:]+|:
151
- """,
152
- re.X,
153
- )
154
-
155
- re_break = re.compile(r"\s*\bBREAK\b\s*", re.S)
156
-
157
- res = []
158
- round_brackets = []
159
- square_brackets = []
160
-
161
- round_bracket_multiplier = 1.1
162
- square_bracket_multiplier = 1 / 1.1
163
-
164
- def multiply_range(start_position, multiplier):
165
- for p in range(start_position, len(res)):
166
- res[p][1] *= multiplier
167
-
168
- for m in re_attention.finditer(text):
169
- text = m.group(0)
170
- weight = m.group(1)
171
-
172
- if text.startswith("\\"):
173
- res.append([text[1:], 1.0])
174
- elif text == "(":
175
- round_brackets.append(len(res))
176
- elif text == "[":
177
- square_brackets.append(len(res))
178
- elif weight is not None and len(round_brackets) > 0:
179
- multiply_range(round_brackets.pop(), float(weight))
180
- elif text == ")" and len(round_brackets) > 0:
181
- multiply_range(round_brackets.pop(), round_bracket_multiplier)
182
- elif text == "]" and len(square_brackets) > 0:
183
- multiply_range(square_brackets.pop(), square_bracket_multiplier)
184
- else:
185
- parts = re.split(re_break, text)
186
- for i, part in enumerate(parts):
187
- if i > 0:
188
- res.append(["BREAK", -1])
189
- res.append([part, 1.0])
190
-
191
- for pos in round_brackets:
192
- multiply_range(pos, round_bracket_multiplier)
193
-
194
- for pos in square_brackets:
195
- multiply_range(pos, square_bracket_multiplier)
196
-
197
- if len(res) == 0:
198
- res = [["", 1.0]]
199
-
200
- # merge runs of identical weights
201
- i = 0
202
- while i + 1 < len(res):
203
- if res[i][1] == res[i + 1][1]:
204
- res[i][0] += res[i + 1][0]
205
- res.pop(i + 1)
206
- else:
207
- i += 1
208
-
209
- return res
210
-
211
- def get_prompts_tokens_with_weights(self, clip_tokenizer: CLIPTokenizer, prompt: str):
212
- """
213
- Get prompt token ids and weights, this function works for both prompt and negative prompt
214
- Args:
215
- pipe (CLIPTokenizer)
216
- A CLIPTokenizer
217
- prompt (str)
218
- A prompt string with weights
219
- Returns:
220
- text_tokens (list)
221
- A list contains token ids
222
- text_weight (list)
223
- A list contains the correspodent weight of token ids
224
- Example:
225
- import torch
226
- from transformers import CLIPTokenizer
227
- clip_tokenizer = CLIPTokenizer.from_pretrained(
228
- "stablediffusionapi/deliberate-v2"
229
- , subfolder = "tokenizer"
230
- , dtype = torch.float16
231
- )
232
- token_id_list, token_weight_list = get_prompts_tokens_with_weights(
233
- clip_tokenizer = clip_tokenizer
234
- ,prompt = "a (red:1.5) cat"*70
235
- )
236
- """
237
- texts_and_weights = self.parse_prompt_attention(prompt)
238
- text_tokens, text_weights = [], []
239
- for word, weight in texts_and_weights:
240
- # tokenize and discard the starting and the ending token
241
- token = clip_tokenizer(word, truncation=False).input_ids[1:-1] # so that tokenize whatever length prompt
242
- # the returned token is a 1d list: [320, 1125, 539, 320]
243
-
244
- # merge the new tokens to the all tokens holder: text_tokens
245
- text_tokens = [*text_tokens, *token]
246
-
247
- # each token chunk will come with one weight, like ['red cat', 2.0]
248
- # need to expand weight for each token.
249
- chunk_weights = [weight] * len(token)
250
-
251
- # append the weight back to the weight holder: text_weights
252
- text_weights = [*text_weights, *chunk_weights]
253
- return text_tokens, text_weights
254
-
255
- def group_tokens_and_weights(self, token_ids: list, weights: list, pad_last_block=False):
256
- """
257
- Produce tokens and weights in groups and pad the missing tokens
258
- Args:
259
- token_ids (list)
260
- The token ids from tokenizer
261
- weights (list)
262
- The weights list from function get_prompts_tokens_with_weights
263
- pad_last_block (bool)
264
- Control if fill the last token list to 75 tokens with eos
265
- Returns:
266
- new_token_ids (2d list)
267
- new_weights (2d list)
268
- Example:
269
- token_groups,weight_groups = group_tokens_and_weights(
270
- token_ids = token_id_list
271
- , weights = token_weight_list
272
- )
273
- """
274
- bos, eos = 49406, 49407
275
-
276
- # this will be a 2d list
277
- new_token_ids = []
278
- new_weights = []
279
- while len(token_ids) >= 75:
280
- # get the first 75 tokens
281
- head_75_tokens = [token_ids.pop(0) for _ in range(75)]
282
- head_75_weights = [weights.pop(0) for _ in range(75)]
283
-
284
- # extract token ids and weights
285
- temp_77_token_ids = [bos] + head_75_tokens + [eos]
286
- temp_77_weights = [1.0] + head_75_weights + [1.0]
287
-
288
- # add 77 token and weights chunk to the holder list
289
- new_token_ids.append(temp_77_token_ids)
290
- new_weights.append(temp_77_weights)
291
-
292
- # padding the left
293
- if len(token_ids) >= 0:
294
- padding_len = 75 - len(token_ids) if pad_last_block else 0
295
-
296
- temp_77_token_ids = [bos] + token_ids + [eos] * padding_len + [eos]
297
- new_token_ids.append(temp_77_token_ids)
298
-
299
- temp_77_weights = [1.0] + weights + [1.0] * padding_len + [1.0]
300
- new_weights.append(temp_77_weights)
301
-
302
- return new_token_ids, new_weights
303
-
304
- def get_weighted_text_embeddings_sdxl(
305
- self,
306
- pipe: StableDiffusionXLPipeline,
307
- prompt: str = "",
308
- prompt_2: str = None,
309
- neg_prompt: str = "",
310
- neg_prompt_2: str = None,
311
- prompt_embeds=None,
312
- negative_prompt_embeds=None,
313
- pooled_prompt_embeds=None,
314
- negative_pooled_prompt_embeds=None,
315
- extra_emb=None,
316
- extra_emb_alpha=0.6,
317
- ):
318
- """
319
- This function can process long prompt with weights, no length limitation
320
- for Stable Diffusion XL
321
- Args:
322
- pipe (StableDiffusionPipeline)
323
- prompt (str)
324
- prompt_2 (str)
325
- neg_prompt (str)
326
- neg_prompt_2 (str)
327
- Returns:
328
- prompt_embeds (torch.Tensor)
329
- neg_prompt_embeds (torch.Tensor)
330
- """
331
- #
332
- if prompt_embeds is not None and \
333
- negative_prompt_embeds is not None and \
334
- pooled_prompt_embeds is not None and \
335
- negative_pooled_prompt_embeds is not None:
336
- return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
337
-
338
- if prompt_2:
339
- prompt = f"{prompt} {prompt_2}"
340
-
341
- if neg_prompt_2:
342
- neg_prompt = f"{neg_prompt} {neg_prompt_2}"
343
-
344
- eos = pipe.tokenizer.eos_token_id
345
-
346
- # tokenizer 1
347
- prompt_tokens, prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
348
- neg_prompt_tokens, neg_prompt_weights = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
349
-
350
- # tokenizer 2
351
- # prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, prompt)
352
- # neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer_2, neg_prompt)
353
- # tokenizer 2 遇到 !! !!!! 等多感叹号和tokenizer 1的效果不一致
354
- prompt_tokens_2, prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, prompt)
355
- neg_prompt_tokens_2, neg_prompt_weights_2 = self.get_prompts_tokens_with_weights(pipe.tokenizer, neg_prompt)
356
-
357
- # padding the shorter one for prompt set 1
358
- prompt_token_len = len(prompt_tokens)
359
- neg_prompt_token_len = len(neg_prompt_tokens)
360
-
361
- if prompt_token_len > neg_prompt_token_len:
362
- # padding the neg_prompt with eos token
363
- neg_prompt_tokens = neg_prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
364
- neg_prompt_weights = neg_prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
365
- else:
366
- # padding the prompt
367
- prompt_tokens = prompt_tokens + [eos] * abs(prompt_token_len - neg_prompt_token_len)
368
- prompt_weights = prompt_weights + [1.0] * abs(prompt_token_len - neg_prompt_token_len)
369
-
370
- # padding the shorter one for token set 2
371
- prompt_token_len_2 = len(prompt_tokens_2)
372
- neg_prompt_token_len_2 = len(neg_prompt_tokens_2)
373
-
374
- if prompt_token_len_2 > neg_prompt_token_len_2:
375
- # padding the neg_prompt with eos token
376
- neg_prompt_tokens_2 = neg_prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
377
- neg_prompt_weights_2 = neg_prompt_weights_2 + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
378
- else:
379
- # padding the prompt
380
- prompt_tokens_2 = prompt_tokens_2 + [eos] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
381
- prompt_weights_2 = prompt_weights + [1.0] * abs(prompt_token_len_2 - neg_prompt_token_len_2)
382
-
383
- embeds = []
384
- neg_embeds = []
385
-
386
- prompt_token_groups, prompt_weight_groups = self.group_tokens_and_weights(prompt_tokens.copy(), prompt_weights.copy())
387
-
388
- neg_prompt_token_groups, neg_prompt_weight_groups = self.group_tokens_and_weights(
389
- neg_prompt_tokens.copy(), neg_prompt_weights.copy()
390
- )
391
-
392
- prompt_token_groups_2, prompt_weight_groups_2 = self.group_tokens_and_weights(
393
- prompt_tokens_2.copy(), prompt_weights_2.copy()
394
- )
395
-
396
- neg_prompt_token_groups_2, neg_prompt_weight_groups_2 = self.group_tokens_and_weights(
397
- neg_prompt_tokens_2.copy(), neg_prompt_weights_2.copy()
398
- )
399
-
400
- # get prompt embeddings one by one is not working.
401
- for i in range(len(prompt_token_groups)):
402
- # get positive prompt embeddings with weights
403
- token_tensor = torch.tensor([prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
404
- weight_tensor = torch.tensor(prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
405
-
406
- token_tensor_2 = torch.tensor([prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
407
-
408
- # use first text encoder
409
- prompt_embeds_1 = pipe.text_encoder(token_tensor.to(pipe.device), output_hidden_states=True)
410
- prompt_embeds_1_hidden_states = prompt_embeds_1.hidden_states[-2]
411
-
412
- # use second text encoder
413
- prompt_embeds_2 = pipe.text_encoder_2(token_tensor_2.to(pipe.device), output_hidden_states=True)
414
- prompt_embeds_2_hidden_states = prompt_embeds_2.hidden_states[-2]
415
- pooled_prompt_embeds = prompt_embeds_2[0]
416
-
417
- prompt_embeds_list = [prompt_embeds_1_hidden_states, prompt_embeds_2_hidden_states]
418
- token_embedding = torch.concat(prompt_embeds_list, dim=-1).squeeze(0)
419
-
420
- for j in range(len(weight_tensor)):
421
- if weight_tensor[j] != 1.0:
422
- token_embedding[j] = (
423
- token_embedding[-1] + (token_embedding[j] - token_embedding[-1]) * weight_tensor[j]
424
- )
425
-
426
- token_embedding = token_embedding.unsqueeze(0)
427
- embeds.append(token_embedding)
428
-
429
- # get negative prompt embeddings with weights
430
- neg_token_tensor = torch.tensor([neg_prompt_token_groups[i]], dtype=torch.long, device=pipe.device)
431
- neg_token_tensor_2 = torch.tensor([neg_prompt_token_groups_2[i]], dtype=torch.long, device=pipe.device)
432
- neg_weight_tensor = torch.tensor(neg_prompt_weight_groups[i], dtype=torch.float16, device=pipe.device)
433
-
434
- # use first text encoder
435
- neg_prompt_embeds_1 = pipe.text_encoder(neg_token_tensor.to(pipe.device), output_hidden_states=True)
436
- neg_prompt_embeds_1_hidden_states = neg_prompt_embeds_1.hidden_states[-2]
437
-
438
- # use second text encoder
439
- neg_prompt_embeds_2 = pipe.text_encoder_2(neg_token_tensor_2.to(pipe.device), output_hidden_states=True)
440
- neg_prompt_embeds_2_hidden_states = neg_prompt_embeds_2.hidden_states[-2]
441
- negative_pooled_prompt_embeds = neg_prompt_embeds_2[0]
442
-
443
- neg_prompt_embeds_list = [neg_prompt_embeds_1_hidden_states, neg_prompt_embeds_2_hidden_states]
444
- neg_token_embedding = torch.concat(neg_prompt_embeds_list, dim=-1).squeeze(0)
445
-
446
- for z in range(len(neg_weight_tensor)):
447
- if neg_weight_tensor[z] != 1.0:
448
- neg_token_embedding[z] = (
449
- neg_token_embedding[-1] + (neg_token_embedding[z] - neg_token_embedding[-1]) * neg_weight_tensor[z]
450
- )
451
-
452
- neg_token_embedding = neg_token_embedding.unsqueeze(0)
453
- neg_embeds.append(neg_token_embedding)
454
-
455
- prompt_embeds = torch.cat(embeds, dim=1)
456
- negative_prompt_embeds = torch.cat(neg_embeds, dim=1)
457
-
458
- if extra_emb is not None:
459
- extra_emb = extra_emb.to(prompt_embeds.device, dtype=prompt_embeds.dtype) * extra_emb_alpha
460
- prompt_embeds = torch.cat([prompt_embeds, extra_emb], 1)
461
- negative_prompt_embeds = torch.cat([negative_prompt_embeds, torch.zeros_like(extra_emb)], 1)
462
- print(f'fix prompt_embeds, extra_emb_alpha={extra_emb_alpha}')
463
-
464
- return prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds
465
-
466
- def get_prompt_embeds(self, *args, **kwargs):
467
- prompt_embeds, negative_prompt_embeds, _, _ = self.get_weighted_text_embeddings_sdxl(*args, **kwargs)
468
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
469
- return prompt_embeds
470
-
471
- def draw_kps(image_pil, kps, color_list=[(255,0,0), (0,255,0), (0,0,255), (255,255,0), (255,0,255)]):
472
-
473
- stickwidth = 4
474
- limbSeq = np.array([[0, 2], [1, 2], [3, 2], [4, 2]])
475
- kps = np.array(kps)
476
-
477
- w, h = image_pil.size
478
- out_img = np.zeros([h, w, 3])
479
-
480
- for i in range(len(limbSeq)):
481
- index = limbSeq[i]
482
- color = color_list[index[0]]
483
-
484
- x = kps[index][:, 0]
485
- y = kps[index][:, 1]
486
- length = ((x[0] - x[1]) ** 2 + (y[0] - y[1]) ** 2) ** 0.5
487
- angle = math.degrees(math.atan2(y[0] - y[1], x[0] - x[1]))
488
- polygon = cv2.ellipse2Poly((int(np.mean(x)), int(np.mean(y))), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
489
- out_img = cv2.fillConvexPoly(out_img.copy(), polygon, color)
490
- out_img = (out_img * 0.6).astype(np.uint8)
491
-
492
- for idx_kp, kp in enumerate(kps):
493
- color = color_list[idx_kp]
494
- x, y = kp
495
- out_img = cv2.circle(out_img.copy(), (int(x), int(y)), 10, color, -1)
496
-
497
- out_img_pil = PIL.Image.fromarray(out_img.astype(np.uint8))
498
- return out_img_pil
499
-
500
- class StableDiffusionXLInstantIDPipeline(StableDiffusionXLControlNetPipeline):
501
-
502
- def cuda(self, dtype=torch.float16, use_xformers=False):
503
- self.to('cuda', dtype)
504
-
505
- if hasattr(self, 'image_proj_model'):
506
- self.image_proj_model.to(self.unet.device).to(self.unet.dtype)
507
-
508
- if use_xformers:
509
- if is_xformers_available():
510
- import xformers
511
- from packaging import version
512
-
513
- xformers_version = version.parse(xformers.__version__)
514
- if xformers_version == version.parse("0.0.16"):
515
- logger.warn(
516
- "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."
517
- )
518
- self.enable_xformers_memory_efficient_attention()
519
- else:
520
- raise ValueError("xformers is not available. Make sure it is installed correctly")
521
-
522
- def load_ip_adapter_instantid(self, model_ckpt, image_emb_dim=512, num_tokens=16, scale=0.5):
523
- self.set_image_proj_model(model_ckpt, image_emb_dim, num_tokens)
524
- self.set_ip_adapter(model_ckpt, num_tokens, scale)
525
-
526
- def set_image_proj_model(self, model_ckpt, image_emb_dim=512, num_tokens=16):
527
-
528
- image_proj_model = Resampler(
529
- dim=1280,
530
- depth=4,
531
- dim_head=64,
532
- heads=20,
533
- num_queries=num_tokens,
534
- embedding_dim=image_emb_dim,
535
- output_dim=self.unet.config.cross_attention_dim,
536
- ff_mult=4,
537
- )
538
-
539
- image_proj_model.eval()
540
-
541
- self.image_proj_model = image_proj_model.to(self.device, dtype=self.dtype)
542
- state_dict = torch.load(model_ckpt, map_location="cpu")
543
- if 'image_proj' in state_dict:
544
- state_dict = state_dict["image_proj"]
545
- self.image_proj_model.load_state_dict(state_dict)
546
-
547
- self.image_proj_model_in_features = image_emb_dim
548
-
549
- def set_ip_adapter(self, model_ckpt, num_tokens, scale):
550
-
551
- unet = self.unet
552
- attn_procs = {}
553
- for name in unet.attn_processors.keys():
554
- cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
555
- if name.startswith("mid_block"):
556
- hidden_size = unet.config.block_out_channels[-1]
557
- elif name.startswith("up_blocks"):
558
- block_id = int(name[len("up_blocks.")])
559
- hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
560
- elif name.startswith("down_blocks"):
561
- block_id = int(name[len("down_blocks.")])
562
- hidden_size = unet.config.block_out_channels[block_id]
563
- if cross_attention_dim is None:
564
- attn_procs[name] = AttnProcessor().to(unet.device, dtype=unet.dtype)
565
- else:
566
- attn_procs[name] = IPAttnProcessor(hidden_size=hidden_size,
567
- cross_attention_dim=cross_attention_dim,
568
- scale=scale,
569
- num_tokens=num_tokens).to(unet.device, dtype=unet.dtype)
570
- unet.set_attn_processor(attn_procs)
571
-
572
- state_dict = torch.load(model_ckpt, map_location="cpu")
573
- ip_layers = torch.nn.ModuleList(self.unet.attn_processors.values())
574
- if 'ip_adapter' in state_dict:
575
- state_dict = state_dict['ip_adapter']
576
- ip_layers.load_state_dict(state_dict)
577
-
578
- def set_ip_adapter_scale(self, scale):
579
- unet = getattr(self, self.unet_name) if not hasattr(self, "unet") else self.unet
580
- for attn_processor in unet.attn_processors.values():
581
- if isinstance(attn_processor, IPAttnProcessor):
582
- attn_processor.scale = scale
583
-
584
- def _encode_prompt_image_emb(self, prompt_image_emb, device, num_images_per_prompt, dtype, do_classifier_free_guidance):
585
-
586
- if isinstance(prompt_image_emb, torch.Tensor):
587
- prompt_image_emb = prompt_image_emb.clone().detach()
588
- else:
589
- prompt_image_emb = torch.tensor(prompt_image_emb)
590
-
591
- prompt_image_emb = prompt_image_emb.to(device=device, dtype=dtype)
592
- prompt_image_emb = prompt_image_emb.reshape([1, -1, self.image_proj_model_in_features])
593
-
594
- if do_classifier_free_guidance:
595
- prompt_image_emb = torch.cat([torch.zeros_like(prompt_image_emb), prompt_image_emb], dim=0)
596
- else:
597
- prompt_image_emb = torch.cat([prompt_image_emb], dim=0)
598
-
599
- prompt_image_emb = self.image_proj_model(prompt_image_emb)
600
-
601
- bs_embed, seq_len, _ = prompt_image_emb.shape
602
- prompt_image_emb = prompt_image_emb.repeat(1, num_images_per_prompt, 1)
603
- prompt_image_emb = prompt_image_emb.view(bs_embed * num_images_per_prompt, seq_len, -1)
604
-
605
- return prompt_image_emb
606
-
607
- @torch.no_grad()
608
- @replace_example_docstring(EXAMPLE_DOC_STRING)
609
- def __call__(
610
- self,
611
- prompt: Union[str, List[str]] = None,
612
- prompt_2: Optional[Union[str, List[str]]] = None,
613
- image: PipelineImageInput = None,
614
- height: Optional[int] = None,
615
- width: Optional[int] = None,
616
- num_inference_steps: int = 50,
617
- guidance_scale: float = 5.0,
618
- negative_prompt: Optional[Union[str, List[str]]] = None,
619
- negative_prompt_2: Optional[Union[str, List[str]]] = None,
620
- num_images_per_prompt: Optional[int] = 1,
621
- eta: float = 0.0,
622
- generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
623
- latents: Optional[torch.FloatTensor] = None,
624
- prompt_embeds: Optional[torch.FloatTensor] = None,
625
- negative_prompt_embeds: Optional[torch.FloatTensor] = None,
626
- pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
627
- negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
628
- image_embeds: Optional[torch.FloatTensor] = None,
629
- output_type: Optional[str] = "pil",
630
- return_dict: bool = True,
631
- cross_attention_kwargs: Optional[Dict[str, Any]] = None,
632
- controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
633
- guess_mode: bool = False,
634
- control_guidance_start: Union[float, List[float]] = 0.0,
635
- control_guidance_end: Union[float, List[float]] = 1.0,
636
- original_size: Tuple[int, int] = None,
637
- crops_coords_top_left: Tuple[int, int] = (0, 0),
638
- target_size: Tuple[int, int] = None,
639
- negative_original_size: Optional[Tuple[int, int]] = None,
640
- negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
641
- negative_target_size: Optional[Tuple[int, int]] = None,
642
- clip_skip: Optional[int] = None,
643
- callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
644
- callback_on_step_end_tensor_inputs: List[str] = ["latents"],
645
- # IP adapter
646
- ip_adapter_scale=None,
647
- # Enhance Face Region
648
- control_mask = None,
649
- **kwargs,
650
- ):
651
- r"""
652
- The call function to the pipeline for generation.
653
- Args:
654
- prompt (`str` or `List[str]`, *optional*):
655
- The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
656
- prompt_2 (`str` or `List[str]`, *optional*):
657
- The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
658
- used in both text-encoders.
659
- image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
660
- `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
661
- The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
662
- specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
663
- accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
664
- and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
665
- `init`, images must be passed as a list such that each element of the list can be correctly batched for
666
- input to a single ControlNet.
667
- height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
668
- The height in pixels of the generated image. Anything below 512 pixels won't work well for
669
- [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
670
- and checkpoints that are not specifically fine-tuned on low resolutions.
671
- width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
672
- The width in pixels of the generated image. Anything below 512 pixels won't work well for
673
- [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
674
- and checkpoints that are not specifically fine-tuned on low resolutions.
675
- num_inference_steps (`int`, *optional*, defaults to 50):
676
- The number of denoising steps. More denoising steps usually lead to a higher quality image at the
677
- expense of slower inference.
678
- guidance_scale (`float`, *optional*, defaults to 5.0):
679
- A higher guidance scale value encourages the model to generate images closely linked to the text
680
- `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
681
- negative_prompt (`str` or `List[str]`, *optional*):
682
- The prompt or prompts to guide what to not include in image generation. If not defined, you need to
683
- pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
684
- negative_prompt_2 (`str` or `List[str]`, *optional*):
685
- The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
686
- and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
687
- num_images_per_prompt (`int`, *optional*, defaults to 1):
688
- The number of images to generate per prompt.
689
- eta (`float`, *optional*, defaults to 0.0):
690
- Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
691
- to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
692
- generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
693
- A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
694
- generation deterministic.
695
- latents (`torch.FloatTensor`, *optional*):
696
- Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
697
- generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
698
- tensor is generated by sampling using the supplied random `generator`.
699
- prompt_embeds (`torch.FloatTensor`, *optional*):
700
- Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
701
- provided, text embeddings are generated from the `prompt` input argument.
702
- negative_prompt_embeds (`torch.FloatTensor`, *optional*):
703
- Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
704
- not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
705
- pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
706
- Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
707
- not provided, pooled text embeddings are generated from `prompt` input argument.
708
- negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
709
- Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
710
- weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
711
- argument.
712
- image_embeds (`torch.FloatTensor`, *optional*):
713
- Pre-generated image embeddings.
714
- output_type (`str`, *optional*, defaults to `"pil"`):
715
- The output format of the generated image. Choose between `PIL.Image` or `np.array`.
716
- return_dict (`bool`, *optional*, defaults to `True`):
717
- Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
718
- plain tuple.
719
- cross_attention_kwargs (`dict`, *optional*):
720
- A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
721
- [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
722
- controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
723
- The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
724
- to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
725
- the corresponding scale as a list.
726
- guess_mode (`bool`, *optional*, defaults to `False`):
727
- The ControlNet encoder tries to recognize the content of the input image even if you remove all
728
- prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
729
- control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
730
- The percentage of total steps at which the ControlNet starts applying.
731
- control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
732
- The percentage of total steps at which the ControlNet stops applying.
733
- original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
734
- If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
735
- `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
736
- explained in section 2.2 of
737
- [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
738
- crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
739
- `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
740
- `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
741
- `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
742
- [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
743
- target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
744
- For most cases, `target_size` should be set to the desired height and width of the generated image. If
745
- not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
746
- section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
747
- negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
748
- To negatively condition the generation process based on a specific image resolution. Part of SDXL's
749
- micro-conditioning as explained in section 2.2 of
750
- [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
751
- information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
752
- negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
753
- To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
754
- micro-conditioning as explained in section 2.2 of
755
- [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
756
- information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
757
- negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
758
- To negatively condition the generation process based on a target image resolution. It should be as same
759
- as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
760
- [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
761
- information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
762
- clip_skip (`int`, *optional*):
763
- Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
764
- the output of the pre-final layer will be used for computing the prompt embeddings.
765
- callback_on_step_end (`Callable`, *optional*):
766
- A function that calls at the end of each denoising steps during the inference. The function is called
767
- with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
768
- callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
769
- `callback_on_step_end_tensor_inputs`.
770
- callback_on_step_end_tensor_inputs (`List`, *optional*):
771
- The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
772
- will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
773
- `._callback_tensor_inputs` attribute of your pipeine class.
774
- Examples:
775
- Returns:
776
- [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
777
- If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
778
- otherwise a `tuple` is returned containing the output images.
779
- """
780
-
781
- lpw = LongPromptWeight()
782
-
783
- callback = kwargs.pop("callback", None)
784
- callback_steps = kwargs.pop("callback_steps", None)
785
-
786
- if callback is not None:
787
- deprecate(
788
- "callback",
789
- "1.0.0",
790
- "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
791
- )
792
- if callback_steps is not None:
793
- deprecate(
794
- "callback_steps",
795
- "1.0.0",
796
- "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
797
- )
798
-
799
- controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
800
-
801
- # align format for control guidance
802
- if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
803
- control_guidance_start = len(control_guidance_end) * [control_guidance_start]
804
- elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
805
- control_guidance_end = len(control_guidance_start) * [control_guidance_end]
806
- elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
807
- mult = len(controlnet.nets) if isinstance(controlnet, MultiControlNetModel) else 1
808
- control_guidance_start, control_guidance_end = (
809
- mult * [control_guidance_start],
810
- mult * [control_guidance_end],
811
- )
812
-
813
- # 0. set ip_adapter_scale
814
- if ip_adapter_scale is not None:
815
- self.set_ip_adapter_scale(ip_adapter_scale)
816
-
817
- # 1. Check inputs. Raise error if not correct
818
- self.check_inputs(
819
- prompt=prompt,
820
- prompt_2=prompt_2,
821
- image=image,
822
- callback_steps=callback_steps,
823
- negative_prompt=negative_prompt,
824
- negative_prompt_2=negative_prompt_2,
825
- prompt_embeds=prompt_embeds,
826
- negative_prompt_embeds=negative_prompt_embeds,
827
- pooled_prompt_embeds=pooled_prompt_embeds,
828
- negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
829
- controlnet_conditioning_scale=controlnet_conditioning_scale,
830
- control_guidance_start=control_guidance_start,
831
- control_guidance_end=control_guidance_end,
832
- callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
833
- )
834
-
835
- self._guidance_scale = guidance_scale
836
- self._clip_skip = clip_skip
837
- self._cross_attention_kwargs = cross_attention_kwargs
838
-
839
- # 2. Define call parameters
840
- if prompt is not None and isinstance(prompt, str):
841
- batch_size = 1
842
- elif prompt is not None and isinstance(prompt, list):
843
- batch_size = len(prompt)
844
- else:
845
- batch_size = prompt_embeds.shape[0]
846
-
847
- device = self._execution_device
848
-
849
- if isinstance(controlnet, MultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
850
- controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
851
-
852
- global_pool_conditions = (
853
- controlnet.config.global_pool_conditions
854
- if isinstance(controlnet, ControlNetModel)
855
- else controlnet.nets[0].config.global_pool_conditions
856
- )
857
- guess_mode = guess_mode or global_pool_conditions
858
-
859
- # 3.1 Encode input prompt
860
- (
861
- prompt_embeds,
862
- negative_prompt_embeds,
863
- pooled_prompt_embeds,
864
- negative_pooled_prompt_embeds,
865
- ) = lpw.get_weighted_text_embeddings_sdxl(
866
- pipe=self,
867
- prompt=prompt,
868
- neg_prompt=negative_prompt,
869
- prompt_embeds=prompt_embeds,
870
- negative_prompt_embeds=negative_prompt_embeds,
871
- pooled_prompt_embeds=pooled_prompt_embeds,
872
- negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
873
- )
874
-
875
- # 3.2 Encode image prompt
876
- prompt_image_emb = self._encode_prompt_image_emb(image_embeds,
877
- device,
878
- num_images_per_prompt,
879
- self.unet.dtype,
880
- self.do_classifier_free_guidance)
881
-
882
- # 4. Prepare image
883
- if isinstance(controlnet, ControlNetModel):
884
- image = self.prepare_image(
885
- image=image,
886
- width=width,
887
- height=height,
888
- batch_size=batch_size * num_images_per_prompt,
889
- num_images_per_prompt=num_images_per_prompt,
890
- device=device,
891
- dtype=controlnet.dtype,
892
- do_classifier_free_guidance=self.do_classifier_free_guidance,
893
- guess_mode=guess_mode,
894
- )
895
- height, width = image.shape[-2:]
896
- elif isinstance(controlnet, MultiControlNetModel):
897
- images = []
898
-
899
- for image_ in image:
900
- image_ = self.prepare_image(
901
- image=image_,
902
- width=width,
903
- height=height,
904
- batch_size=batch_size * num_images_per_prompt,
905
- num_images_per_prompt=num_images_per_prompt,
906
- device=device,
907
- dtype=controlnet.dtype,
908
- do_classifier_free_guidance=self.do_classifier_free_guidance,
909
- guess_mode=guess_mode,
910
- )
911
-
912
- images.append(image_)
913
-
914
- image = images
915
- height, width = image[0].shape[-2:]
916
- else:
917
- assert False
918
-
919
- # 4.1 Region control
920
- if control_mask is not None:
921
- mask_weight_image = control_mask
922
- mask_weight_image = np.array(mask_weight_image)
923
- mask_weight_image_tensor = torch.from_numpy(mask_weight_image).to(device=device, dtype=prompt_embeds.dtype)
924
- mask_weight_image_tensor = mask_weight_image_tensor[:, :, 0] / 255.
925
- mask_weight_image_tensor = mask_weight_image_tensor[None, None]
926
- h, w = mask_weight_image_tensor.shape[-2:]
927
- control_mask_wight_image_list = []
928
- for scale in [8, 8, 8, 16, 16, 16, 32, 32, 32]:
929
- scale_mask_weight_image_tensor = F.interpolate(
930
- mask_weight_image_tensor,(h // scale, w // scale), mode='bilinear')
931
- control_mask_wight_image_list.append(scale_mask_weight_image_tensor)
932
- region_mask = torch.from_numpy(np.array(control_mask)[:, :, 0]).to(self.unet.device, dtype=self.unet.dtype) / 255.
933
- region_control.prompt_image_conditioning = [dict(region_mask=region_mask)]
934
- else:
935
- control_mask_wight_image_list = None
936
- region_control.prompt_image_conditioning = [dict(region_mask=None)]
937
-
938
- # 5. Prepare timesteps
939
- self.scheduler.set_timesteps(num_inference_steps, device=device)
940
- timesteps = self.scheduler.timesteps
941
- self._num_timesteps = len(timesteps)
942
-
943
- # 6. Prepare latent variables
944
- num_channels_latents = self.unet.config.in_channels
945
- latents = self.prepare_latents(
946
- batch_size * num_images_per_prompt,
947
- num_channels_latents,
948
- height,
949
- width,
950
- prompt_embeds.dtype,
951
- device,
952
- generator,
953
- latents,
954
- )
955
-
956
- # 6.5 Optionally get Guidance Scale Embedding
957
- timestep_cond = None
958
- if self.unet.config.time_cond_proj_dim is not None:
959
- guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
960
- timestep_cond = self.get_guidance_scale_embedding(
961
- guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
962
- ).to(device=device, dtype=latents.dtype)
963
-
964
- # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
965
- extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
966
-
967
- # 7.1 Create tensor stating which controlnets to keep
968
- controlnet_keep = []
969
- for i in range(len(timesteps)):
970
- keeps = [
971
- 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
972
- for s, e in zip(control_guidance_start, control_guidance_end)
973
- ]
974
- controlnet_keep.append(keeps[0] if isinstance(controlnet, ControlNetModel) else keeps)
975
-
976
- # 7.2 Prepare added time ids & embeddings
977
- if isinstance(image, list):
978
- original_size = original_size or image[0].shape[-2:]
979
- else:
980
- original_size = original_size or image.shape[-2:]
981
- target_size = target_size or (height, width)
982
-
983
- add_text_embeds = pooled_prompt_embeds
984
- if self.text_encoder_2 is None:
985
- text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
986
- else:
987
- text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
988
-
989
- add_time_ids = self._get_add_time_ids(
990
- original_size,
991
- crops_coords_top_left,
992
- target_size,
993
- dtype=prompt_embeds.dtype,
994
- text_encoder_projection_dim=text_encoder_projection_dim,
995
- )
996
-
997
- if negative_original_size is not None and negative_target_size is not None:
998
- negative_add_time_ids = self._get_add_time_ids(
999
- negative_original_size,
1000
- negative_crops_coords_top_left,
1001
- negative_target_size,
1002
- dtype=prompt_embeds.dtype,
1003
- text_encoder_projection_dim=text_encoder_projection_dim,
1004
- )
1005
- else:
1006
- negative_add_time_ids = add_time_ids
1007
-
1008
- if self.do_classifier_free_guidance:
1009
- prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
1010
- add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
1011
- add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
1012
-
1013
- prompt_embeds = prompt_embeds.to(device)
1014
- add_text_embeds = add_text_embeds.to(device)
1015
- add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
1016
- encoder_hidden_states = torch.cat([prompt_embeds, prompt_image_emb], dim=1)
1017
-
1018
- # 8. Denoising loop
1019
- num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
1020
- is_unet_compiled = is_compiled_module(self.unet)
1021
- is_controlnet_compiled = is_compiled_module(self.controlnet)
1022
- is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
1023
-
1024
- with self.progress_bar(total=num_inference_steps) as progress_bar:
1025
- for i, t in enumerate(timesteps):
1026
- # Relevant thread:
1027
- # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
1028
- if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
1029
- torch._inductor.cudagraph_mark_step_begin()
1030
- # expand the latents if we are doing classifier free guidance
1031
- latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
1032
- latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
1033
-
1034
- added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
1035
-
1036
- # controlnet(s) inference
1037
- if guess_mode and self.do_classifier_free_guidance:
1038
- # Infer ControlNet only for the conditional batch.
1039
- control_model_input = latents
1040
- control_model_input = self.scheduler.scale_model_input(control_model_input, t)
1041
- controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
1042
- controlnet_added_cond_kwargs = {
1043
- "text_embeds": add_text_embeds.chunk(2)[1],
1044
- "time_ids": add_time_ids.chunk(2)[1],
1045
- }
1046
- else:
1047
- control_model_input = latent_model_input
1048
- controlnet_prompt_embeds = prompt_embeds
1049
- controlnet_added_cond_kwargs = added_cond_kwargs
1050
-
1051
- if isinstance(controlnet_keep[i], list):
1052
- cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
1053
- else:
1054
- controlnet_cond_scale = controlnet_conditioning_scale
1055
- if isinstance(controlnet_cond_scale, list):
1056
- controlnet_cond_scale = controlnet_cond_scale[0]
1057
- cond_scale = controlnet_cond_scale * controlnet_keep[i]
1058
-
1059
- if isinstance(self.controlnet, MultiControlNetModel):
1060
- down_block_res_samples_list, mid_block_res_sample_list = [], []
1061
- for control_index in range(len(self.controlnet.nets)):
1062
- controlnet = self.controlnet.nets[control_index]
1063
- if control_index == 0:
1064
- # assume fhe first controlnet is IdentityNet
1065
- controlnet_prompt_embeds = prompt_image_emb
1066
- else:
1067
- controlnet_prompt_embeds = prompt_embeds
1068
- down_block_res_samples, mid_block_res_sample = controlnet(control_model_input,
1069
- t,
1070
- encoder_hidden_states=controlnet_prompt_embeds,
1071
- controlnet_cond=image[control_index],
1072
- conditioning_scale=cond_scale[control_index],
1073
- guess_mode=guess_mode,
1074
- added_cond_kwargs=controlnet_added_cond_kwargs,
1075
- return_dict=False)
1076
-
1077
- # controlnet mask
1078
- if control_index == 0 and control_mask_wight_image_list is not None:
1079
- down_block_res_samples = [
1080
- down_block_res_sample * mask_weight
1081
- for down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)
1082
- ]
1083
- mid_block_res_sample *= control_mask_wight_image_list[-1]
1084
-
1085
- down_block_res_samples_list.append(down_block_res_samples)
1086
- mid_block_res_sample_list.append(mid_block_res_sample)
1087
-
1088
- mid_block_res_sample = torch.stack(mid_block_res_sample_list).sum(dim=0)
1089
- down_block_res_samples = [torch.stack(down_block_res_samples).sum(dim=0) for down_block_res_samples in
1090
- zip(*down_block_res_samples_list)]
1091
- else:
1092
- down_block_res_samples, mid_block_res_sample = self.controlnet(
1093
- control_model_input,
1094
- t,
1095
- encoder_hidden_states=prompt_image_emb,
1096
- controlnet_cond=image,
1097
- conditioning_scale=cond_scale,
1098
- guess_mode=guess_mode,
1099
- added_cond_kwargs=controlnet_added_cond_kwargs,
1100
- return_dict=False,
1101
- )
1102
-
1103
- # controlnet mask
1104
- if control_mask_wight_image_list is not None:
1105
- down_block_res_samples = [
1106
- down_block_res_sample * mask_weight
1107
- for down_block_res_sample, mask_weight in zip(down_block_res_samples, control_mask_wight_image_list)
1108
- ]
1109
- mid_block_res_sample *= control_mask_wight_image_list[-1]
1110
-
1111
- if guess_mode and self.do_classifier_free_guidance:
1112
- # Infered ControlNet only for the conditional batch.
1113
- # To apply the output of ControlNet to both the unconditional and conditional batches,
1114
- # add 0 to the unconditional batch to keep it unchanged.
1115
- down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
1116
- mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
1117
-
1118
- # predict the noise residual
1119
- noise_pred = self.unet(
1120
- latent_model_input,
1121
- t,
1122
- encoder_hidden_states=encoder_hidden_states,
1123
- timestep_cond=timestep_cond,
1124
- cross_attention_kwargs=self.cross_attention_kwargs,
1125
- down_block_additional_residuals=down_block_res_samples,
1126
- mid_block_additional_residual=mid_block_res_sample,
1127
- added_cond_kwargs=added_cond_kwargs,
1128
- return_dict=False,
1129
- )[0]
1130
-
1131
- # perform guidance
1132
- if self.do_classifier_free_guidance:
1133
- noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
1134
- noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
1135
-
1136
- # compute the previous noisy sample x_t -> x_t-1
1137
- latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
1138
-
1139
- if callback_on_step_end is not None:
1140
- callback_kwargs = {}
1141
- for k in callback_on_step_end_tensor_inputs:
1142
- callback_kwargs[k] = locals()[k]
1143
- callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
1144
-
1145
- latents = callback_outputs.pop("latents", latents)
1146
- prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
1147
- negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
1148
-
1149
- # call the callback, if provided
1150
- if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
1151
- progress_bar.update()
1152
- if callback is not None and i % callback_steps == 0:
1153
- step_idx = i // getattr(self.scheduler, "order", 1)
1154
- callback(step_idx, t, latents)
1155
-
1156
- if not output_type == "latent":
1157
- # make sure the VAE is in float32 mode, as it overflows in float16
1158
- needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
1159
- if needs_upcasting:
1160
- self.upcast_vae()
1161
- latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
1162
-
1163
- image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
1164
-
1165
- # cast back to fp16 if needed
1166
- if needs_upcasting:
1167
- self.vae.to(dtype=torch.float16)
1168
- else:
1169
- image = latents
1170
-
1171
- if not output_type == "latent":
1172
- # apply watermark if available
1173
- if self.watermark is not None:
1174
- image = self.watermark.apply_watermark(image)
1175
-
1176
- image = self.image_processor.postprocess(image, output_type=output_type)
1177
-
1178
- # Offload all models
1179
- self.maybe_free_model_hooks()
1180
-
1181
- if not return_dict:
1182
- return (image,)
1183
-
1184
- return StableDiffusionXLPipelineOutput(images=image)