yuxinjiang11 commited on
Commit
25ba35e
·
verified ·
1 Parent(s): bf85faa

Upload 15 files

Browse files
ip_adapter/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from .ip_adapter import IPAdapter, IPAdapterPlus, IPAdapterPlusXL, IPAdapterXL, IPAdapterFull
2
+
3
+ __all__ = [
4
+ "IPAdapter",
5
+ "IPAdapterPlus",
6
+ "IPAdapterPlusXL",
7
+ "IPAdapterXL",
8
+ "IPAdapterFull",
9
+ ]
ip_adapter/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (336 Bytes). View file
 
ip_adapter/__pycache__/attention_processor.cpython-38.pyc ADDED
Binary file (10.1 kB). View file
 
ip_adapter/__pycache__/ip_adapter.cpython-38.pyc ADDED
Binary file (13.3 kB). View file
 
ip_adapter/__pycache__/ip_adapter_anomagic.cpython-38.pyc ADDED
Binary file (15.6 kB). View file
 
ip_adapter/__pycache__/resampler.cpython-38.pyc ADDED
Binary file (4.2 kB). View file
 
ip_adapter/__pycache__/utils.cpython-38.pyc ADDED
Binary file (2.81 kB). View file
 
ip_adapter/attention_processor.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
7
+ class AttnProcessor(nn.Module):
8
+ r"""
9
+ Default processor for performing attention-related computations.
10
+ """
11
+
12
+ def __init__(
13
+ self,
14
+ hidden_size=None,
15
+ cross_attention_dim=None,
16
+ ):
17
+ super().__init__()
18
+
19
+ def __call__(
20
+ self,
21
+ attn,
22
+ hidden_states,
23
+ encoder_hidden_states=None,
24
+ attention_mask=None,
25
+ temb=None,
26
+ *args,
27
+ **kwargs,
28
+ ):
29
+ residual = hidden_states
30
+
31
+ if attn.spatial_norm is not None:
32
+ hidden_states = attn.spatial_norm(hidden_states, temb)
33
+
34
+ input_ndim = hidden_states.ndim
35
+
36
+ if input_ndim == 4:
37
+ batch_size, channel, height, width = hidden_states.shape
38
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
39
+
40
+ batch_size, sequence_length, _ = (
41
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
42
+ )
43
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
44
+
45
+ if attn.group_norm is not None:
46
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
47
+
48
+ query = attn.to_q(hidden_states)
49
+
50
+ if encoder_hidden_states is None:
51
+ encoder_hidden_states = hidden_states
52
+ elif attn.norm_cross:
53
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
54
+
55
+ key = attn.to_k(encoder_hidden_states)
56
+ value = attn.to_v(encoder_hidden_states)
57
+
58
+ query = attn.head_to_batch_dim(query)
59
+ key = attn.head_to_batch_dim(key)
60
+ value = attn.head_to_batch_dim(value)
61
+
62
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
63
+ hidden_states = torch.bmm(attention_probs, value)
64
+ hidden_states = attn.batch_to_head_dim(hidden_states)
65
+
66
+ # linear proj
67
+ hidden_states = attn.to_out[0](hidden_states)
68
+ # dropout
69
+ hidden_states = attn.to_out[1](hidden_states)
70
+
71
+ if input_ndim == 4:
72
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
73
+
74
+ if attn.residual_connection:
75
+ hidden_states = hidden_states + residual
76
+
77
+ hidden_states = hidden_states / attn.rescale_output_factor
78
+
79
+ return hidden_states
80
+
81
+
82
+ class IPAttnProcessor(nn.Module):
83
+ r"""
84
+ Attention processor for IP-Adapater.
85
+ Args:
86
+ hidden_size (`int`):
87
+ The hidden size of the attention layer.
88
+ cross_attention_dim (`int`):
89
+ The number of channels in the `encoder_hidden_states`.
90
+ scale (`float`, defaults to 1.0):
91
+ the weight scale of image prompt.
92
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
93
+ The context length of the image features.
94
+ """
95
+
96
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
97
+ super().__init__()
98
+
99
+ self.hidden_size = hidden_size
100
+ self.cross_attention_dim = cross_attention_dim
101
+ self.scale = scale
102
+ self.num_tokens = num_tokens
103
+
104
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
105
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
106
+
107
+ def __call__(
108
+ self,
109
+ attn,
110
+ hidden_states,
111
+ encoder_hidden_states=None,
112
+ attention_mask=None,
113
+ temb=None,
114
+ *args,
115
+ **kwargs,
116
+ ):
117
+ residual = hidden_states
118
+
119
+ if attn.spatial_norm is not None:
120
+ hidden_states = attn.spatial_norm(hidden_states, temb)
121
+
122
+ input_ndim = hidden_states.ndim
123
+
124
+ if input_ndim == 4:
125
+ batch_size, channel, height, width = hidden_states.shape
126
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
127
+
128
+ batch_size, sequence_length, _ = (
129
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
130
+ )
131
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
132
+
133
+ if attn.group_norm is not None:
134
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
135
+
136
+ query = attn.to_q(hidden_states)
137
+
138
+ if encoder_hidden_states is None:
139
+ encoder_hidden_states = hidden_states
140
+ else:
141
+ # get encoder_hidden_states, ip_hidden_states
142
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
143
+ encoder_hidden_states, ip_hidden_states = (
144
+ encoder_hidden_states[:, :end_pos, :],
145
+ encoder_hidden_states[:, end_pos:, :],
146
+ )
147
+ if attn.norm_cross:
148
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
149
+
150
+ key = attn.to_k(encoder_hidden_states)
151
+ value = attn.to_v(encoder_hidden_states)
152
+
153
+ query = attn.head_to_batch_dim(query)
154
+ key = attn.head_to_batch_dim(key)
155
+ value = attn.head_to_batch_dim(value)
156
+
157
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
158
+ hidden_states = torch.bmm(attention_probs, value)
159
+ hidden_states = attn.batch_to_head_dim(hidden_states)
160
+
161
+ # for ip-adapter
162
+ ip_key = self.to_k_ip(ip_hidden_states)
163
+ ip_value = self.to_v_ip(ip_hidden_states)
164
+
165
+ ip_key = attn.head_to_batch_dim(ip_key)
166
+ ip_value = attn.head_to_batch_dim(ip_value)
167
+
168
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
169
+ self.attn_map = ip_attention_probs
170
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
171
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
172
+
173
+ hidden_states = hidden_states + self.scale * ip_hidden_states
174
+
175
+ # linear proj
176
+ hidden_states = attn.to_out[0](hidden_states)
177
+ # dropout
178
+ hidden_states = attn.to_out[1](hidden_states)
179
+
180
+ if input_ndim == 4:
181
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
182
+
183
+ if attn.residual_connection:
184
+ hidden_states = hidden_states + residual
185
+
186
+ hidden_states = hidden_states / attn.rescale_output_factor
187
+
188
+ return hidden_states
189
+
190
+
191
+ class AttnProcessor2_0(torch.nn.Module):
192
+ r"""
193
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ hidden_size=None,
199
+ cross_attention_dim=None,
200
+ ):
201
+ super().__init__()
202
+ if not hasattr(F, "scaled_dot_product_attention"):
203
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
204
+
205
+ def __call__(
206
+ self,
207
+ attn,
208
+ hidden_states,
209
+ encoder_hidden_states=None,
210
+ attention_mask=None,
211
+ temb=None,
212
+ *args,
213
+ **kwargs,
214
+ ):
215
+ residual = hidden_states
216
+
217
+ if attn.spatial_norm is not None:
218
+ hidden_states = attn.spatial_norm(hidden_states, temb)
219
+
220
+ input_ndim = hidden_states.ndim
221
+
222
+ if input_ndim == 4:
223
+ batch_size, channel, height, width = hidden_states.shape
224
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
225
+
226
+ batch_size, sequence_length, _ = (
227
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
228
+ )
229
+
230
+ if attention_mask is not None:
231
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
232
+ # scaled_dot_product_attention expects attention_mask shape to be
233
+ # (batch, heads, source_length, target_length)
234
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
235
+
236
+ if attn.group_norm is not None:
237
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
238
+
239
+ query = attn.to_q(hidden_states)
240
+
241
+ if encoder_hidden_states is None:
242
+ encoder_hidden_states = hidden_states
243
+ elif attn.norm_cross:
244
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
245
+
246
+ key = attn.to_k(encoder_hidden_states)
247
+ value = attn.to_v(encoder_hidden_states)
248
+
249
+ inner_dim = key.shape[-1]
250
+ head_dim = inner_dim // attn.heads
251
+
252
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
253
+
254
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
255
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
256
+
257
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
258
+ # TODO: add support for attn.scale when we move to Torch 2.1
259
+ hidden_states = F.scaled_dot_product_attention(
260
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
261
+ )
262
+
263
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
264
+ hidden_states = hidden_states.to(query.dtype)
265
+
266
+ # linear proj
267
+ hidden_states = attn.to_out[0](hidden_states)
268
+ # dropout
269
+ hidden_states = attn.to_out[1](hidden_states)
270
+
271
+ if input_ndim == 4:
272
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
273
+
274
+ if attn.residual_connection:
275
+ hidden_states = hidden_states + residual
276
+
277
+ hidden_states = hidden_states / attn.rescale_output_factor
278
+
279
+ return hidden_states
280
+
281
+
282
+ class IPAttnProcessor2_0(torch.nn.Module):
283
+ r"""
284
+ Attention processor for IP-Adapater for PyTorch 2.0.
285
+ Args:
286
+ hidden_size (`int`):
287
+ The hidden size of the attention layer.
288
+ cross_attention_dim (`int`):
289
+ The number of channels in the `encoder_hidden_states`.
290
+ scale (`float`, defaults to 1.0):
291
+ the weight scale of image prompt.
292
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
293
+ The context length of the image features.
294
+ """
295
+
296
+ def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
297
+ super().__init__()
298
+
299
+ if not hasattr(F, "scaled_dot_product_attention"):
300
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
301
+
302
+ self.hidden_size = hidden_size
303
+ self.cross_attention_dim = cross_attention_dim
304
+ self.scale = scale
305
+ self.num_tokens = num_tokens
306
+
307
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
308
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
309
+
310
+ def __call__(
311
+ self,
312
+ attn,
313
+ hidden_states,
314
+ encoder_hidden_states=None,
315
+ attention_mask=None,
316
+ temb=None,
317
+ *args,
318
+ **kwargs,
319
+ ):
320
+ residual = hidden_states
321
+
322
+ if attn.spatial_norm is not None:
323
+ hidden_states = attn.spatial_norm(hidden_states, temb)
324
+
325
+ input_ndim = hidden_states.ndim
326
+
327
+ if input_ndim == 4:
328
+ batch_size, channel, height, width = hidden_states.shape
329
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
330
+
331
+ batch_size, sequence_length, _ = (
332
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
333
+ )
334
+
335
+ if attention_mask is not None:
336
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
337
+ # scaled_dot_product_attention expects attention_mask shape to be
338
+ # (batch, heads, source_length, target_length)
339
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
340
+
341
+ if attn.group_norm is not None:
342
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
343
+
344
+ query = attn.to_q(hidden_states)
345
+
346
+ if encoder_hidden_states is None:
347
+ encoder_hidden_states = hidden_states
348
+ else:
349
+ # get encoder_hidden_states, ip_hidden_states
350
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
351
+ # print("end_pos", end_pos)
352
+ encoder_hidden_states, ip_hidden_states = (
353
+ encoder_hidden_states[:, :end_pos, :],
354
+ encoder_hidden_states[:, end_pos:, :],
355
+ )
356
+ # encoder_hidden_states, ip_hidden_states = (
357
+ # encoder_hidden_states[:, :1, :],
358
+ # encoder_hidden_states[:, 1:, :],
359
+ # )
360
+ if attn.norm_cross:
361
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
362
+
363
+ key = attn.to_k(encoder_hidden_states)
364
+ value = attn.to_v(encoder_hidden_states)
365
+
366
+ inner_dim = key.shape[-1]
367
+ head_dim = inner_dim // attn.heads
368
+
369
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
370
+
371
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
372
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
373
+
374
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
375
+ # TODO: add support for attn.scale when we move to Torch 2.1
376
+ hidden_states = F.scaled_dot_product_attention(
377
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
378
+ )
379
+
380
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
381
+ hidden_states = hidden_states.to(query.dtype)
382
+
383
+ # for ip-adapter
384
+ ip_key = self.to_k_ip(ip_hidden_states)
385
+ ip_value = self.to_v_ip(ip_hidden_states)
386
+
387
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
388
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
389
+
390
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
391
+ # TODO: add support for attn.scale when we move to Torch 2.1
392
+ ip_hidden_states = F.scaled_dot_product_attention(
393
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
394
+ )
395
+ with torch.no_grad():
396
+ self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1)
397
+ #print(self.attn_map.shape)
398
+
399
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
400
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
401
+
402
+ hidden_states = hidden_states + self.scale * ip_hidden_states
403
+ # linear proj
404
+ hidden_states = attn.to_out[0](hidden_states)
405
+ # dropout
406
+ hidden_states = attn.to_out[1](hidden_states)
407
+
408
+ if input_ndim == 4:
409
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
410
+
411
+ if attn.residual_connection:
412
+ hidden_states = hidden_states + residual
413
+
414
+ hidden_states = hidden_states / attn.rescale_output_factor
415
+
416
+ return hidden_states
417
+
418
+
419
+ ## for controlnet
420
+ class CNAttnProcessor:
421
+ r"""
422
+ Default processor for performing attention-related computations.
423
+ """
424
+
425
+ def __init__(self, num_tokens=4):
426
+ self.num_tokens = num_tokens
427
+
428
+ def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, *args, **kwargs,):
429
+ residual = hidden_states
430
+
431
+ if attn.spatial_norm is not None:
432
+ hidden_states = attn.spatial_norm(hidden_states, temb)
433
+
434
+ input_ndim = hidden_states.ndim
435
+
436
+ if input_ndim == 4:
437
+ batch_size, channel, height, width = hidden_states.shape
438
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
439
+
440
+ batch_size, sequence_length, _ = (
441
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
442
+ )
443
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
444
+
445
+ if attn.group_norm is not None:
446
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
447
+
448
+ query = attn.to_q(hidden_states)
449
+
450
+ if encoder_hidden_states is None:
451
+ encoder_hidden_states = hidden_states
452
+ else:
453
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
454
+ encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
455
+ if attn.norm_cross:
456
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
457
+
458
+ key = attn.to_k(encoder_hidden_states)
459
+ value = attn.to_v(encoder_hidden_states)
460
+
461
+ query = attn.head_to_batch_dim(query)
462
+ key = attn.head_to_batch_dim(key)
463
+ value = attn.head_to_batch_dim(value)
464
+
465
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
466
+ hidden_states = torch.bmm(attention_probs, value)
467
+ hidden_states = attn.batch_to_head_dim(hidden_states)
468
+
469
+ # linear proj
470
+ hidden_states = attn.to_out[0](hidden_states)
471
+ # dropout
472
+ hidden_states = attn.to_out[1](hidden_states)
473
+
474
+ if input_ndim == 4:
475
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
476
+
477
+ if attn.residual_connection:
478
+ hidden_states = hidden_states + residual
479
+
480
+ hidden_states = hidden_states / attn.rescale_output_factor
481
+
482
+ return hidden_states
483
+
484
+
485
+ class CNAttnProcessor2_0:
486
+ r"""
487
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
488
+ """
489
+
490
+ def __init__(self, num_tokens=4):
491
+ if not hasattr(F, "scaled_dot_product_attention"):
492
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
493
+ self.num_tokens = num_tokens
494
+
495
+ def __call__(
496
+ self,
497
+ attn,
498
+ hidden_states,
499
+ encoder_hidden_states=None,
500
+ attention_mask=None,
501
+ temb=None,
502
+ *args,
503
+ **kwargs,
504
+ ):
505
+ residual = hidden_states
506
+
507
+ if attn.spatial_norm is not None:
508
+ hidden_states = attn.spatial_norm(hidden_states, temb)
509
+
510
+ input_ndim = hidden_states.ndim
511
+
512
+ if input_ndim == 4:
513
+ batch_size, channel, height, width = hidden_states.shape
514
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
515
+
516
+ batch_size, sequence_length, _ = (
517
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
518
+ )
519
+
520
+ if attention_mask is not None:
521
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
522
+ # scaled_dot_product_attention expects attention_mask shape to be
523
+ # (batch, heads, source_length, target_length)
524
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
525
+
526
+ if attn.group_norm is not None:
527
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
528
+
529
+ query = attn.to_q(hidden_states)
530
+
531
+ if encoder_hidden_states is None:
532
+ encoder_hidden_states = hidden_states
533
+ else:
534
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
535
+ encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
536
+ if attn.norm_cross:
537
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
538
+
539
+ key = attn.to_k(encoder_hidden_states)
540
+ value = attn.to_v(encoder_hidden_states)
541
+
542
+ inner_dim = key.shape[-1]
543
+ head_dim = inner_dim // attn.heads
544
+
545
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
546
+
547
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
548
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
549
+
550
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
551
+ # TODO: add support for attn.scale when we move to Torch 2.1
552
+ hidden_states = F.scaled_dot_product_attention(
553
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
554
+ )
555
+
556
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
557
+ hidden_states = hidden_states.to(query.dtype)
558
+
559
+ # linear proj
560
+ hidden_states = attn.to_out[0](hidden_states)
561
+ # dropout
562
+ hidden_states = attn.to_out[1](hidden_states)
563
+
564
+ if input_ndim == 4:
565
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
566
+
567
+ if attn.residual_connection:
568
+ hidden_states = hidden_states + residual
569
+
570
+ hidden_states = hidden_states / attn.rescale_output_factor
571
+
572
+ return hidden_states
ip_adapter/custom_pipelines.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ from diffusers import StableDiffusionXLPipeline
5
+ from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
6
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import rescale_noise_cfg
7
+
8
+ from .utils import is_torch2_available
9
+
10
+ if is_torch2_available():
11
+ from .attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
12
+ else:
13
+ from .attention_processor import IPAttnProcessor
14
+
15
+
16
+ class StableDiffusionXLCustomPipeline(StableDiffusionXLPipeline):
17
+ def set_scale(self, scale):
18
+ for attn_processor in self.unet.attn_processors.values():
19
+ if isinstance(attn_processor, IPAttnProcessor):
20
+ attn_processor.scale = scale
21
+
22
+ @torch.no_grad()
23
+ def __call__( # noqa: C901
24
+ self,
25
+ prompt: Optional[Union[str, List[str]]] = None,
26
+ prompt_2: Optional[Union[str, List[str]]] = None,
27
+ height: Optional[int] = None,
28
+ width: Optional[int] = None,
29
+ num_inference_steps: int = 50,
30
+ denoising_end: Optional[float] = None,
31
+ guidance_scale: float = 5.0,
32
+ negative_prompt: Optional[Union[str, List[str]]] = None,
33
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
34
+ num_images_per_prompt: Optional[int] = 1,
35
+ eta: float = 0.0,
36
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
37
+ latents: Optional[torch.FloatTensor] = None,
38
+ prompt_embeds: Optional[torch.FloatTensor] = None,
39
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
40
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
41
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
42
+ output_type: Optional[str] = "pil",
43
+ return_dict: bool = True,
44
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
45
+ callback_steps: int = 1,
46
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
47
+ guidance_rescale: float = 0.0,
48
+ original_size: Optional[Tuple[int, int]] = None,
49
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
50
+ target_size: Optional[Tuple[int, int]] = None,
51
+ negative_original_size: Optional[Tuple[int, int]] = None,
52
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
53
+ negative_target_size: Optional[Tuple[int, int]] = None,
54
+ control_guidance_start: float = 0.0,
55
+ control_guidance_end: float = 1.0,
56
+ ):
57
+ r"""
58
+ Function invoked when calling the pipeline for generation.
59
+
60
+ Args:
61
+ prompt (`str` or `List[str]`, *optional*):
62
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
63
+ instead.
64
+ prompt_2 (`str` or `List[str]`, *optional*):
65
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
66
+ used in both text-encoders
67
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
68
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
69
+ Anything below 512 pixels won't work well for
70
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
71
+ and checkpoints that are not specifically fine-tuned on low resolutions.
72
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
73
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
74
+ Anything below 512 pixels won't work well for
75
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
76
+ and checkpoints that are not specifically fine-tuned on low resolutions.
77
+ num_inference_steps (`int`, *optional*, defaults to 50):
78
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
79
+ expense of slower inference.
80
+ denoising_end (`float`, *optional*):
81
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
82
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
83
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
84
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
85
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
86
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
87
+ guidance_scale (`float`, *optional*, defaults to 5.0):
88
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
89
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
90
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
91
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
92
+ usually at the expense of lower image quality.
93
+ negative_prompt (`str` or `List[str]`, *optional*):
94
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
95
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
96
+ less than `1`).
97
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
98
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
99
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
100
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
101
+ The number of images to generate per prompt.
102
+ eta (`float`, *optional*, defaults to 0.0):
103
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
104
+ [`schedulers.DDIMScheduler`], will be ignored for others.
105
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
106
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
107
+ to make generation deterministic.
108
+ latents (`torch.FloatTensor`, *optional*):
109
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
110
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
111
+ tensor will ge generated by sampling using the supplied random `generator`.
112
+ prompt_embeds (`torch.FloatTensor`, *optional*):
113
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
114
+ provided, text embeddings will be generated from `prompt` input argument.
115
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
116
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
117
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
118
+ argument.
119
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
120
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
121
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
122
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
123
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
124
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
125
+ input argument.
126
+ output_type (`str`, *optional*, defaults to `"pil"`):
127
+ The output format of the generate image. Choose between
128
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
129
+ return_dict (`bool`, *optional*, defaults to `True`):
130
+ Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
131
+ of a plain tuple.
132
+ callback (`Callable`, *optional*):
133
+ A function that will be called every `callback_steps` steps during inference. The function will be
134
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
135
+ callback_steps (`int`, *optional*, defaults to 1):
136
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
137
+ called at every step.
138
+ cross_attention_kwargs (`dict`, *optional*):
139
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
140
+ `self.processor` in
141
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
142
+ guidance_rescale (`float`, *optional*, defaults to 0.7):
143
+ Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
144
+ Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `φ` in equation 16. of
145
+ [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
146
+ Guidance rescale factor should fix overexposure when using zero terminal SNR.
147
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
148
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
149
+ `original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
150
+ explained in section 2.2 of
151
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
152
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
153
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
154
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
155
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
156
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
157
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
158
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
159
+ not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
160
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
161
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
162
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
163
+ micro-conditioning as explained in section 2.2 of
164
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
165
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
166
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
167
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
168
+ micro-conditioning as explained in section 2.2 of
169
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
170
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
171
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
172
+ To negatively condition the generation process based on a target image resolution. It should be as same
173
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
174
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
175
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
176
+ control_guidance_start (`float`, *optional*, defaults to 0.0):
177
+ The percentage of total steps at which the ControlNet starts applying.
178
+ control_guidance_end (`float`, *optional*, defaults to 1.0):
179
+ The percentage of total steps at which the ControlNet stops applying.
180
+
181
+ Examples:
182
+
183
+ Returns:
184
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
185
+ [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
186
+ `tuple`. When returning a tuple, the first element is a list with the generated images.
187
+ """
188
+ # 0. Default height and width to unet
189
+ height = height or self.default_sample_size * self.vae_scale_factor
190
+ width = width or self.default_sample_size * self.vae_scale_factor
191
+
192
+ original_size = original_size or (height, width)
193
+ target_size = target_size or (height, width)
194
+
195
+ # 1. Check inputs. Raise error if not correct
196
+ self.check_inputs(
197
+ prompt,
198
+ prompt_2,
199
+ height,
200
+ width,
201
+ callback_steps,
202
+ negative_prompt,
203
+ negative_prompt_2,
204
+ prompt_embeds,
205
+ negative_prompt_embeds,
206
+ pooled_prompt_embeds,
207
+ negative_pooled_prompt_embeds,
208
+ )
209
+
210
+ # 2. Define call parameters
211
+ if prompt is not None and isinstance(prompt, str):
212
+ batch_size = 1
213
+ elif prompt is not None and isinstance(prompt, list):
214
+ batch_size = len(prompt)
215
+ else:
216
+ batch_size = prompt_embeds.shape[0]
217
+
218
+ device = self._execution_device
219
+
220
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
221
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
222
+ # corresponds to doing no classifier free guidance.
223
+ do_classifier_free_guidance = guidance_scale > 1.0
224
+
225
+ # 3. Encode input prompt
226
+ text_encoder_lora_scale = (
227
+ cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
228
+ )
229
+ (
230
+ prompt_embeds,
231
+ negative_prompt_embeds,
232
+ pooled_prompt_embeds,
233
+ negative_pooled_prompt_embeds,
234
+ ) = self.encode_prompt(
235
+ prompt=prompt,
236
+ prompt_2=prompt_2,
237
+ device=device,
238
+ num_images_per_prompt=num_images_per_prompt,
239
+ do_classifier_free_guidance=do_classifier_free_guidance,
240
+ negative_prompt=negative_prompt,
241
+ negative_prompt_2=negative_prompt_2,
242
+ prompt_embeds=prompt_embeds,
243
+ negative_prompt_embeds=negative_prompt_embeds,
244
+ pooled_prompt_embeds=pooled_prompt_embeds,
245
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
246
+ lora_scale=text_encoder_lora_scale,
247
+ )
248
+
249
+ # 4. Prepare timesteps
250
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
251
+
252
+ timesteps = self.scheduler.timesteps
253
+
254
+ # 5. Prepare latent variables
255
+ num_channels_latents = self.unet.config.in_channels
256
+ latents = self.prepare_latents(
257
+ batch_size * num_images_per_prompt,
258
+ num_channels_latents,
259
+ height,
260
+ width,
261
+ prompt_embeds.dtype,
262
+ device,
263
+ generator,
264
+ latents,
265
+ )
266
+
267
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
268
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
269
+
270
+ # 7. Prepare added time ids & embeddings
271
+ add_text_embeds = pooled_prompt_embeds
272
+ if self.text_encoder_2 is None:
273
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
274
+ else:
275
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
276
+
277
+ add_time_ids = self._get_add_time_ids(
278
+ original_size,
279
+ crops_coords_top_left,
280
+ target_size,
281
+ dtype=prompt_embeds.dtype,
282
+ text_encoder_projection_dim=text_encoder_projection_dim,
283
+ )
284
+ if negative_original_size is not None and negative_target_size is not None:
285
+ negative_add_time_ids = self._get_add_time_ids(
286
+ negative_original_size,
287
+ negative_crops_coords_top_left,
288
+ negative_target_size,
289
+ dtype=prompt_embeds.dtype,
290
+ text_encoder_projection_dim=text_encoder_projection_dim,
291
+ )
292
+ else:
293
+ negative_add_time_ids = add_time_ids
294
+
295
+ if do_classifier_free_guidance:
296
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
297
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
298
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
299
+
300
+ prompt_embeds = prompt_embeds.to(device)
301
+ add_text_embeds = add_text_embeds.to(device)
302
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
303
+
304
+ # 8. Denoising loop
305
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
306
+
307
+ # 7.1 Apply denoising_end
308
+ if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
309
+ discrete_timestep_cutoff = int(
310
+ round(
311
+ self.scheduler.config.num_train_timesteps
312
+ - (denoising_end * self.scheduler.config.num_train_timesteps)
313
+ )
314
+ )
315
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
316
+ timesteps = timesteps[:num_inference_steps]
317
+
318
+ # get init conditioning scale
319
+ for attn_processor in self.unet.attn_processors.values():
320
+ if isinstance(attn_processor, IPAttnProcessor):
321
+ conditioning_scale = attn_processor.scale
322
+ break
323
+
324
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
325
+ for i, t in enumerate(timesteps):
326
+ if (i / len(timesteps) < control_guidance_start) or ((i + 1) / len(timesteps) > control_guidance_end):
327
+ self.set_scale(0.0)
328
+ else:
329
+ self.set_scale(conditioning_scale)
330
+
331
+ # expand the latents if we are doing classifier free guidance
332
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
333
+
334
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
335
+
336
+ # predict the noise residual
337
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
338
+ noise_pred = self.unet(
339
+ latent_model_input,
340
+ t,
341
+ encoder_hidden_states=prompt_embeds,
342
+ cross_attention_kwargs=cross_attention_kwargs,
343
+ added_cond_kwargs=added_cond_kwargs,
344
+ return_dict=False,
345
+ )[0]
346
+
347
+ # perform guidance
348
+ if do_classifier_free_guidance:
349
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
350
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
351
+
352
+ if do_classifier_free_guidance and guidance_rescale > 0.0:
353
+ # Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
354
+ noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
355
+
356
+ # compute the previous noisy sample x_t -> x_t-1
357
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
358
+
359
+ # call the callback, if provided
360
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
361
+ progress_bar.update()
362
+ if callback is not None and i % callback_steps == 0:
363
+ callback(i, t, latents)
364
+
365
+ if not output_type == "latent":
366
+ # make sure the VAE is in float32 mode, as it overflows in float16
367
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
368
+
369
+ if needs_upcasting:
370
+ self.upcast_vae()
371
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
372
+
373
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
374
+
375
+ # cast back to fp16 if needed
376
+ if needs_upcasting:
377
+ self.vae.to(dtype=torch.float16)
378
+ else:
379
+ image = latents
380
+
381
+ if output_type != "latent":
382
+ # apply watermark if available
383
+ if self.watermark is not None:
384
+ image = self.watermark.apply_watermark(image)
385
+
386
+ image = self.image_processor.postprocess(image, output_type=output_type)
387
+
388
+ # Offload all models
389
+ self.maybe_free_model_hooks()
390
+
391
+ if not return_dict:
392
+ return (image,)
393
+
394
+ return StableDiffusionXLPipelineOutput(images=image)
ip_adapter/ip_adapter.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List
3
+ from peft import LoraConfig, LoraModel
4
+ import torch
5
+ from diffusers import StableDiffusionPipeline
6
+ from diffusers.pipelines.controlnet import MultiControlNetModel
7
+ from PIL import Image
8
+ from safetensors import safe_open
9
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
10
+ import torch.nn as nn
11
+ import math
12
+ from .utils import is_torch2_available, get_generator
13
+ import numpy as np
14
+ if is_torch2_available():
15
+ from .attention_processor import (
16
+ AttnProcessor2_0 as AttnProcessor,
17
+ )
18
+ from .attention_processor import (
19
+ CNAttnProcessor2_0 as CNAttnProcessor,
20
+ )
21
+ from .attention_processor import (
22
+ IPAttnProcessor2_0 as IPAttnProcessor,
23
+ )
24
+ else:
25
+ from .attention_processor import AttnProcessor, CNAttnProcessor, IPAttnProcessor
26
+ from .resampler import Resampler
27
+
28
+
29
+ def load_lora_model(unet, device, diffusion_model_learning_rate):
30
+ for param in unet.parameters():
31
+ param.requires_grad_(False)
32
+
33
+ unet_lora_config = LoraConfig(
34
+ r=16,
35
+ lora_alpha=16,
36
+ init_lora_weights="gaussian",
37
+ target_modules=["to_k", "to_q", "to_v", "to_out.0"],
38
+ )
39
+
40
+ unet.add_adapter(unet_lora_config)
41
+ lora_layers = filter(lambda p: p.requires_grad, unet.parameters())
42
+
43
+ optimizer = torch.optim.AdamW(
44
+ lora_layers,
45
+ lr=diffusion_model_learning_rate,
46
+ )
47
+ return unet, lora_layers
48
+
49
+ class ImageProjModel(torch.nn.Module):
50
+ """Projection Model"""
51
+
52
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
53
+ super().__init__()
54
+
55
+ self.generator = None
56
+ self.cross_attention_dim = cross_attention_dim
57
+ self.clip_extra_context_tokens = clip_extra_context_tokens
58
+ self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
59
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
60
+
61
+ def forward(self, image_embeds):
62
+ embeds = image_embeds
63
+ b = embeds.shape[0]
64
+ # clip_extra_context_tokens = self.proj(embeds).reshape(
65
+ # -1, self.clip_extra_context_tokens, self.cross_attention_dim
66
+ # )
67
+ clip_extra_context_tokens = self.proj(embeds).reshape(
68
+ b, -1, self.cross_attention_dim
69
+ )
70
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
71
+ return clip_extra_context_tokens
72
+
73
+
74
+ class MLPProjModel(torch.nn.Module):
75
+ """SD model with image prompt"""
76
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024):
77
+ super().__init__()
78
+
79
+ self.proj = torch.nn.Sequential(
80
+ torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
81
+ torch.nn.GELU(),
82
+ torch.nn.Linear(clip_embeddings_dim, cross_attention_dim),
83
+ torch.nn.LayerNorm(cross_attention_dim)
84
+ )
85
+
86
+ def forward(self, image_embeds):
87
+ clip_extra_context_tokens = self.proj(image_embeds)
88
+ return clip_extra_context_tokens
89
+
90
+ class SelfAttention(nn.Module):
91
+ def __init__(self, in_channels, device):
92
+ super(SelfAttention, self).__init__()
93
+ self.query = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1).to(device)
94
+ self.key = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1).to(device)
95
+ self.value = nn.Conv2d(in_channels, in_channels, kernel_size=1).to(device)
96
+ self.gamma = nn.Parameter(torch.zeros(1)).to(device)
97
+ self.softmax = nn.Softmax(dim=-1).to(device)
98
+ self.proj_out = nn.Linear(1280, 1024).to(device)
99
+
100
+ def forward(self, x, mask=None):
101
+ x = x.permute(0,2,1)
102
+ batch_size, channels, h = x.size()
103
+ height = int(math.sqrt(h))
104
+ width = height
105
+ x = x.view(batch_size, channels, width, height)
106
+ batch_size, channels, height, width = x.size()
107
+ # 计算 query, key, value
108
+ q = self.query(x).view(batch_size, -1, height * width).permute(0, 2, 1)
109
+ k = self.key(x).view(batch_size, -1, height * width)
110
+ v = self.value(x).view(batch_size, -1, height * width)
111
+
112
+ # 计算注意力分数
113
+ attention_scores = torch.bmm(q, k)
114
+
115
+ if mask is not None:
116
+ # 将 mask 的尺寸调整为和 x 一致
117
+ mask = nn.functional.interpolate(mask, size=(height, width), mode='nearest')
118
+ mask = mask.view(batch_size, 1, height * width)
119
+ # 对掩码为 0 的区域的注意力分数减去一个较大的常数
120
+ large_constant = 1e6
121
+ attention_scores = attention_scores - (1 - mask) * large_constant
122
+
123
+ # 计算注意力权重
124
+ attention_weights = self.softmax(attention_scores)
125
+
126
+ # 应用注意力权重
127
+ out = torch.bmm(v, attention_weights.permute(0, 2, 1))
128
+ out = out.view(batch_size, channels, height, width)
129
+
130
+ # 加权求和
131
+ out = self.gamma * out + x
132
+ out = out.view(batch_size, channels, height * width)
133
+ out = out.permute(0,2,1)
134
+ out = self.proj_out(out)
135
+
136
+ return out
137
+
138
+ class IPAdapter:
139
+ def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4):
140
+ self.device = device
141
+ self.image_encoder_path = image_encoder_path
142
+ self.ip_ckpt = ip_ckpt
143
+ self.num_tokens = num_tokens
144
+ self.attention_module = SelfAttention(1280, device)
145
+ self.pipe = sd_pipe.to(self.device)
146
+ self.set_ip_adapter()
147
+
148
+ # load image encoder
149
+ self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to(
150
+ self.device, dtype=torch.float16
151
+ )
152
+ self.clip_image_processor = CLIPImageProcessor()
153
+ # image proj model
154
+ self.image_proj_model = self.init_proj()
155
+
156
+ self.load_ip_adapter()
157
+
158
+ def init_proj(self):
159
+ image_proj_model = ImageProjModel(
160
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
161
+ clip_embeddings_dim=self.image_encoder.config.projection_dim,
162
+ clip_extra_context_tokens=self.num_tokens,
163
+ ).to(self.device, dtype=torch.float16)
164
+
165
+ return image_proj_model
166
+
167
+ def set_ip_adapter(self):
168
+ unet = self.pipe.unet
169
+ attn_procs = {}
170
+ for name in unet.attn_processors.keys():
171
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
172
+ if name.startswith("mid_block"):
173
+ hidden_size = unet.config.block_out_channels[-1]
174
+ elif name.startswith("up_blocks"):
175
+ block_id = int(name[len("up_blocks.")])
176
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
177
+ elif name.startswith("down_blocks"):
178
+ block_id = int(name[len("down_blocks.")])
179
+ hidden_size = unet.config.block_out_channels[block_id]
180
+ if cross_attention_dim is None:
181
+ attn_procs[name] = AttnProcessor()
182
+ else:
183
+ attn_procs[name] = IPAttnProcessor(
184
+ hidden_size=hidden_size,
185
+ cross_attention_dim=cross_attention_dim,
186
+ scale=1.0,
187
+ num_tokens=self.num_tokens,
188
+ ).to(self.device, dtype=torch.float16)
189
+ unet.set_attn_processor(attn_procs)
190
+ unet, lora_layers = load_lora_model(unet, self.device, 4e-4)
191
+ if hasattr(self.pipe, "controlnet"):
192
+ if isinstance(self.pipe.controlnet, MultiControlNetModel):
193
+ for controlnet in self.pipe.controlnet.nets:
194
+ controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
195
+ else:
196
+ self.pipe.controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
197
+
198
+ def load_ip_adapter(self):
199
+ if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
200
+ state_dict = {"image_proj": {}, "ip_adapter": {}}
201
+ with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
202
+ for key in f.keys():
203
+ if key.startswith("image_proj_model."):
204
+ state_dict["image_proj"][key.replace("image_proj_model.", "")] = f.get_tensor(key)
205
+ elif key.startswith("ip_adapter_model."):
206
+ state_dict["ip_adapter"][key.replace("ip_adapter_model.", "")] = f.get_tensor(key)
207
+ else:
208
+ state_dict = torch.load(self.ip_ckpt, map_location="cpu")
209
+ self.image_proj_model.load_state_dict(state_dict["image_proj"])
210
+ ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
211
+ ip_layers.load_state_dict(state_dict["ip_adapter"])
212
+ self.pipe.unet.load_state_dict(state_dict["unet"])
213
+
214
+ @torch.inference_mode()
215
+ def get_image_embeds(self, pil_image=None, clip_image_embeds=None, mask_image_0=None):
216
+ if pil_image is not None:
217
+ if isinstance(pil_image, Image.Image):
218
+ pil_image = [pil_image]
219
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
220
+ clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds
221
+ outputs =self.image_encoder(clip_image.to(self.device, dtype=torch.float16))
222
+ clip_image_embeds = outputs.image_embeds
223
+ last_feature_layer_output = outputs.last_hidden_state
224
+ else:
225
+ clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
226
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
227
+ mask_image_0 = mask_image_0.resize((64, 64))
228
+ mask_image_0 = mask_image_0.convert('L')
229
+ mask_image_0 = torch.tensor(np.array(mask_image_0), dtype=torch.float32)
230
+ mask_image_0 = (mask_image_0 > 0.5).float().to(self.device)
231
+ image_embeds = self.attention_module(last_feature_layer_output[:, :256, :].float(), mask_image_0.unsqueeze(0).unsqueeze(0))
232
+ image_prompt_embeds = self.image_proj_model(image_embeds.half())
233
+ uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(image_embeds).half())
234
+ # uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(clip_image_embeds).half())
235
+ return image_prompt_embeds, uncond_image_prompt_embeds
236
+
237
+ def set_scale(self, scale):
238
+ for attn_processor in self.pipe.unet.attn_processors.values():
239
+ if isinstance(attn_processor, IPAttnProcessor):
240
+ attn_processor.scale = scale
241
+
242
+ def generate(
243
+ self,
244
+ pil_image=None,
245
+ clip_image_embeds=None,
246
+ prompt=None,
247
+ negative_prompt=None,
248
+ scale=1.0,
249
+ num_samples=4,
250
+ seed=None,
251
+ guidance_scale=7.5,
252
+ # guidance_scale=10,
253
+ num_inference_steps=30,
254
+ mask_image_0=None,
255
+ **kwargs,
256
+ ):
257
+ self.set_scale(scale)
258
+
259
+ if pil_image is not None:
260
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
261
+ else:
262
+ num_prompts = clip_image_embeds.size(0)
263
+
264
+ if prompt is None:
265
+ prompt = "best quality, high quality"
266
+ if negative_prompt is None:
267
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
268
+
269
+ if not isinstance(prompt, List):
270
+ prompt = [prompt] * num_prompts
271
+ if not isinstance(negative_prompt, List):
272
+ negative_prompt = [negative_prompt] * num_prompts
273
+
274
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(
275
+ pil_image=pil_image, clip_image_embeds=clip_image_embeds, mask_image_0=mask_image_0,
276
+ )
277
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
278
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
279
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
280
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
281
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
282
+
283
+ with torch.inference_mode():
284
+ prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
285
+ prompt,
286
+ device=self.device,
287
+ num_images_per_prompt=num_samples,
288
+ do_classifier_free_guidance=True,
289
+ negative_prompt=negative_prompt,
290
+ )
291
+ prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
292
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
293
+ # prompt_embeds = prompt_embeds_
294
+ # negative_prompt_embeds = image_prompt_embeds
295
+
296
+ generator = get_generator(seed, self.device)
297
+
298
+ images = self.pipe(
299
+ prompt_embeds=prompt_embeds,
300
+ negative_prompt_embeds=negative_prompt_embeds,
301
+ guidance_scale=guidance_scale,
302
+ num_inference_steps=num_inference_steps,
303
+ generator=generator,
304
+ **kwargs,
305
+ ).images
306
+
307
+ return images
308
+
309
+
310
+ class IPAdapterXL(IPAdapter):
311
+ """SDXL"""
312
+
313
+ def generate(
314
+ self,
315
+ pil_image,
316
+ prompt=None,
317
+ negative_prompt=None,
318
+ scale=1.0,
319
+ num_samples=4,
320
+ seed=None,
321
+ num_inference_steps=30,
322
+ **kwargs,
323
+ ):
324
+ self.set_scale(scale)
325
+
326
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
327
+
328
+ if prompt is None:
329
+ prompt = "best quality, high quality"
330
+ if negative_prompt is None:
331
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
332
+
333
+ if not isinstance(prompt, List):
334
+ prompt = [prompt] * num_prompts
335
+ if not isinstance(negative_prompt, List):
336
+ negative_prompt = [negative_prompt] * num_prompts
337
+
338
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
339
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
340
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
341
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
342
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
343
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
344
+
345
+ with torch.inference_mode():
346
+ (
347
+ prompt_embeds,
348
+ negative_prompt_embeds,
349
+ pooled_prompt_embeds,
350
+ negative_pooled_prompt_embeds,
351
+ ) = self.pipe.encode_prompt(
352
+ prompt,
353
+ num_images_per_prompt=num_samples,
354
+ do_classifier_free_guidance=True,
355
+ negative_prompt=negative_prompt,
356
+ )
357
+ prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
358
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
359
+
360
+ self.generator = get_generator(seed, self.device)
361
+
362
+ images = self.pipe(
363
+ prompt_embeds=prompt_embeds,
364
+ negative_prompt_embeds=negative_prompt_embeds,
365
+ pooled_prompt_embeds=pooled_prompt_embeds,
366
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
367
+ num_inference_steps=num_inference_steps,
368
+ generator=self.generator,
369
+ **kwargs,
370
+ ).images
371
+
372
+ return images
373
+
374
+
375
+ class IPAdapterPlus(IPAdapter):
376
+ """IP-Adapter with fine-grained features"""
377
+
378
+ def init_proj(self):
379
+ image_proj_model = Resampler(
380
+ dim=self.pipe.unet.config.cross_attention_dim,
381
+ depth=4,
382
+ dim_head=64,
383
+ heads=12,
384
+ num_queries=self.num_tokens,
385
+ embedding_dim=self.image_encoder.config.hidden_size,
386
+ output_dim=self.pipe.unet.config.cross_attention_dim,
387
+ ff_mult=4,
388
+ ).to(self.device, dtype=torch.float16)
389
+ return image_proj_model
390
+
391
+ @torch.inference_mode()
392
+ def get_image_embeds(self, pil_image=None, clip_image_embeds=None):
393
+ if isinstance(pil_image, Image.Image):
394
+ pil_image = [pil_image]
395
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
396
+ clip_image = clip_image.to(self.device, dtype=torch.float16)
397
+ clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
398
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
399
+ uncond_clip_image_embeds = self.image_encoder(
400
+ torch.zeros_like(clip_image), output_hidden_states=True
401
+ ).hidden_states[-2]
402
+ uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
403
+ return image_prompt_embeds, uncond_image_prompt_embeds
404
+
405
+
406
+ class IPAdapterFull(IPAdapterPlus):
407
+ """IP-Adapter with full features"""
408
+
409
+ def init_proj(self):
410
+ image_proj_model = MLPProjModel(
411
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
412
+ clip_embeddings_dim=self.image_encoder.config.hidden_size,
413
+ ).to(self.device, dtype=torch.float16)
414
+ return image_proj_model
415
+
416
+
417
+ class IPAdapterPlusXL(IPAdapter):
418
+ """SDXL"""
419
+
420
+ def init_proj(self):
421
+ image_proj_model = Resampler(
422
+ dim=1280,
423
+ depth=4,
424
+ dim_head=64,
425
+ heads=20,
426
+ num_queries=self.num_tokens,
427
+ embedding_dim=self.image_encoder.config.hidden_size,
428
+ output_dim=self.pipe.unet.config.cross_attention_dim,
429
+ ff_mult=4,
430
+ ).to(self.device, dtype=torch.float16)
431
+ return image_proj_model
432
+
433
+ @torch.inference_mode()
434
+ def get_image_embeds(self, pil_image):
435
+ if isinstance(pil_image, Image.Image):
436
+ pil_image = [pil_image]
437
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
438
+ clip_image = clip_image.to(self.device, dtype=torch.float16)
439
+ clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
440
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
441
+ uncond_clip_image_embeds = self.image_encoder(
442
+ torch.zeros_like(clip_image), output_hidden_states=True
443
+ ).hidden_states[-2]
444
+ uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
445
+ return image_prompt_embeds, uncond_image_prompt_embeds
446
+
447
+ def generate(
448
+ self,
449
+ pil_image,
450
+ prompt=None,
451
+ negative_prompt=None,
452
+ scale=1.0,
453
+ num_samples=4,
454
+ seed=None,
455
+ num_inference_steps=30,
456
+ **kwargs,
457
+ ):
458
+ self.set_scale(scale)
459
+
460
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
461
+
462
+ if prompt is None:
463
+ prompt = "best quality, high quality"
464
+ if negative_prompt is None:
465
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
466
+
467
+ if not isinstance(prompt, List):
468
+ prompt = [prompt] * num_prompts
469
+ if not isinstance(negative_prompt, List):
470
+ negative_prompt = [negative_prompt] * num_prompts
471
+
472
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
473
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
474
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
475
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
476
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
477
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
478
+
479
+ with torch.inference_mode():
480
+ (
481
+ prompt_embeds,
482
+ negative_prompt_embeds,
483
+ pooled_prompt_embeds,
484
+ negative_pooled_prompt_embeds,
485
+ ) = self.pipe.encode_prompt(
486
+ prompt,
487
+ num_images_per_prompt=num_samples,
488
+ do_classifier_free_guidance=True,
489
+ negative_prompt=negative_prompt,
490
+ )
491
+ prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
492
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
493
+
494
+ generator = get_generator(seed, self.device)
495
+
496
+ images = self.pipe(
497
+ prompt_embeds=prompt_embeds,
498
+ negative_prompt_embeds=negative_prompt_embeds,
499
+ pooled_prompt_embeds=pooled_prompt_embeds,
500
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
501
+ num_inference_steps=num_inference_steps,
502
+ generator=generator,
503
+ **kwargs,
504
+ ).images
505
+
506
+ return images
ip_adapter/ip_adapter_anomagic.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import List, Optional, Union
3
+ from peft import LoraConfig
4
+ import torch
5
+ from diffusers import StableDiffusionPipeline
6
+ from diffusers.pipelines.controlnet import MultiControlNetModel
7
+ from PIL import Image
8
+ from safetensors import safe_open
9
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection, CLIPTokenizer, CLIPTextModel
10
+ import torch.nn as nn
11
+ import math
12
+ from .utils import is_torch2_available, get_generator
13
+ import numpy as np
14
+
15
+ if is_torch2_available():
16
+ from .attention_processor import (
17
+ AttnProcessor2_0 as AttnProcessor,
18
+ CNAttnProcessor2_0 as CNAttnProcessor,
19
+ IPAttnProcessor2_0 as IPAttnProcessor,
20
+ )
21
+ else:
22
+ from .attention_processor import AttnProcessor, CNAttnProcessor, IPAttnProcessor
23
+ from .resampler import Resampler
24
+
25
+
26
+ def load_lora_model(unet, device, diffusion_model_learning_rate, dtype):
27
+ for param in unet.parameters():
28
+ param.requires_grad_(False)
29
+
30
+ unet_lora_config = LoraConfig(
31
+ r=16,
32
+ lora_alpha=16,
33
+ init_lora_weights="gaussian",
34
+ target_modules=["to_k", "to_q", "to_v", "to_out.0"],
35
+ )
36
+
37
+ unet.add_adapter(unet_lora_config)
38
+ lora_layers = filter(lambda p: p.requires_grad, unet.parameters())
39
+
40
+ optimizer = torch.optim.AdamW(
41
+ lora_layers,
42
+ lr=diffusion_model_learning_rate,
43
+ )
44
+
45
+ # 确保LoRA层使用正确的dtype
46
+ for layer in lora_layers:
47
+ layer.data = layer.data.to(dtype)
48
+
49
+ return unet, lora_layers
50
+
51
+
52
+ class ImageProjModel(torch.nn.Module):
53
+ """Projection Model"""
54
+
55
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
56
+ super().__init__()
57
+
58
+ self.generator = None
59
+ self.cross_attention_dim = cross_attention_dim
60
+ self.clip_extra_context_tokens = clip_extra_context_tokens
61
+ self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
62
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
63
+
64
+ def forward(self, image_embeds):
65
+ embeds = image_embeds
66
+ b = embeds.shape[0]
67
+ clip_extra_context_tokens = self.proj(embeds).reshape(
68
+ b, -1, self.cross_attention_dim
69
+ )
70
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
71
+ return clip_extra_context_tokens
72
+
73
+
74
+ class MLPProjModel(torch.nn.Module):
75
+ """SD model with image prompt"""
76
+
77
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024):
78
+ super().__init__()
79
+
80
+ self.proj = torch.nn.Sequential(
81
+ torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
82
+ torch.nn.GELU(),
83
+ torch.nn.Linear(clip_embeddings_dim, cross_attention_dim),
84
+ torch.nn.LayerNorm(cross_attention_dim)
85
+ )
86
+
87
+ def forward(self, image_embeds):
88
+ clip_extra_context_tokens = self.proj(image_embeds)
89
+ return clip_extra_context_tokens
90
+
91
+
92
+ class SelfAttention(nn.Module):
93
+ def __init__(self, in_channels, device, dtype=torch.float16):
94
+ super(SelfAttention, self).__init__()
95
+ self.dtype = dtype
96
+ self.query = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1).to(device, dtype=dtype)
97
+ self.key = nn.Conv2d(in_channels, in_channels // 8, kernel_size=1).to(device, dtype=dtype)
98
+ self.value = nn.Conv2d(in_channels, in_channels, kernel_size=1).to(device, dtype=dtype)
99
+ self.gamma = nn.Parameter(torch.zeros(1, dtype=dtype, device=device))
100
+ self.softmax = nn.Softmax(dim=-1)
101
+ self.proj_out = nn.Linear(1280, 1024).to(device, dtype=dtype)
102
+
103
+ def forward(self, x, mask=None):
104
+ # 统一转换为模型dtype
105
+ x = x.to(dtype=self.dtype)
106
+
107
+ x = x.permute(0, 2, 1)
108
+ batch_size, channels, h = x.size()
109
+ height = int(math.sqrt(h))
110
+ width = height
111
+ x = x.view(batch_size, channels, width, height)
112
+ batch_size, channels, height, width = x.size()
113
+
114
+ # 计算 query, key, value
115
+ q = self.query(x).view(batch_size, -1, height * width).permute(0, 2, 1)
116
+ k = self.key(x).view(batch_size, -1, height * width)
117
+ v = self.value(x).view(batch_size, -1, height * width)
118
+
119
+ # 计算注意力分数
120
+ attention_scores = torch.bmm(q, k)
121
+
122
+ if mask is not None:
123
+ # 将 mask 转换为正确的dtype并移到正确设备
124
+ mask = mask.to(device=x.device, dtype=self.dtype)
125
+
126
+ # 将 mask 的尺寸调整为和 x 一致
127
+ mask = nn.functional.interpolate(mask, size=(height, width), mode='nearest')
128
+ mask = mask.view(batch_size, 1, height * width)
129
+
130
+ # 应用mask
131
+ large_constant = torch.tensor(1e6, dtype=self.dtype, device=x.device)
132
+ attention_scores = attention_scores - (1 - mask) * large_constant
133
+
134
+ # 计算注意力权重
135
+ attention_weights = self.softmax(attention_scores)
136
+
137
+ # 应用注意力权重
138
+ out = torch.bmm(v, attention_weights.permute(0, 2, 1))
139
+ out = out.view(batch_size, channels, height, width)
140
+
141
+ # 加权求和
142
+ out = self.gamma * out + x
143
+ out = out.view(batch_size, channels, height * width)
144
+ out = out.permute(0, 2, 1)
145
+ out = self.proj_out(out)
146
+
147
+ return out
148
+
149
+
150
+ class Anomagic:
151
+ def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, ip_ckpt_1, device, num_tokens=4, dtype=torch.float16):
152
+ self.device = device
153
+ self.dtype = dtype
154
+ self.image_encoder_path = image_encoder_path
155
+ self.ip_ckpt = ip_ckpt
156
+ self.ip_ckpt_1 = ip_ckpt_1
157
+ self.num_tokens = num_tokens
158
+
159
+ # 使用统一的dtype初始化SelfAttention
160
+ self.attention_module = SelfAttention(1280, device, dtype=dtype)
161
+
162
+ self.pipe = sd_pipe.to(self.device, dtype=self.dtype)
163
+ self.set_anomagic()
164
+
165
+ # load image encoder with统一dtype
166
+ self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(
167
+ self.image_encoder_path
168
+ ).to(self.device, dtype=self.dtype)
169
+
170
+ self.clip_image_processor = CLIPImageProcessor()
171
+
172
+ # image proj model with统一dtype
173
+ self.image_proj_model = self.init_proj()
174
+
175
+ self.load_anomagic()
176
+
177
+ def init_proj(self):
178
+ image_proj_model = ImageProjModel(
179
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
180
+ clip_embeddings_dim=self.image_encoder.config.projection_dim,
181
+ clip_extra_context_tokens=self.num_tokens,
182
+ ).to(self.device, dtype=self.dtype)
183
+
184
+ return image_proj_model
185
+
186
+ def set_anomagic(self):
187
+ unet = self.pipe.unet
188
+ attn_procs = {}
189
+ for name in unet.attn_processors.keys():
190
+ cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
191
+ if name.startswith("mid_block"):
192
+ hidden_size = unet.config.block_out_channels[-1]
193
+ elif name.startswith("up_blocks"):
194
+ block_id = int(name[len("up_blocks.")])
195
+ hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
196
+ elif name.startswith("down_blocks"):
197
+ block_id = int(name[len("down_blocks.")])
198
+ hidden_size = unet.config.block_out_channels[block_id]
199
+
200
+ if cross_attention_dim is None:
201
+ attn_procs[name] = AttnProcessor()
202
+ else:
203
+ attn_procs[name] = IPAttnProcessor(
204
+ hidden_size=hidden_size,
205
+ cross_attention_dim=cross_attention_dim,
206
+ scale=1.0,
207
+ num_tokens=self.num_tokens,
208
+ ).to(self.device, dtype=self.dtype)
209
+
210
+ unet.set_attn_processor(attn_procs)
211
+ unet, lora_layers = load_lora_model(unet, self.device, 4e-4, self.dtype)
212
+
213
+ if hasattr(self.pipe, "controlnet"):
214
+ if isinstance(self.pipe.controlnet, MultiControlNetModel):
215
+ for controlnet in self.pipe.controlnet.nets:
216
+ controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
217
+ controlnet.to(self.device, dtype=self.dtype)
218
+ else:
219
+ self.pipe.controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
220
+ self.pipe.controlnet.to(self.device, dtype=self.dtype)
221
+
222
+ def load_anomagic(self):
223
+ if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
224
+ state_dict = {"image_proj": {}, "ip_adapter": {}, "unet": {}}
225
+ with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
226
+ for key in f.keys():
227
+ tensor = f.get_tensor(key)
228
+ if key.startswith("image_proj_model."):
229
+ state_dict["image_proj"][key.replace("image_proj_model.", "")] = tensor.to(self.dtype)
230
+ elif key.startswith("ip_adapter_model."):
231
+ state_dict["ip_adapter"][key.replace("ip_adapter_model.", "")] = tensor.to(self.dtype)
232
+ elif key.startswith("unet."):
233
+ state_dict["unet"][key] = tensor.to(self.dtype)
234
+ else:
235
+ state_dict = torch.load(self.ip_ckpt, map_location="cpu")
236
+ # 转换所有张量到正确的dtype
237
+ for key in state_dict:
238
+ if isinstance(state_dict[key], dict):
239
+ for subkey in state_dict[key]:
240
+ state_dict[key][subkey] = state_dict[key][subkey].to(self.dtype)
241
+ elif torch.is_tensor(state_dict[key]):
242
+ state_dict[key] = state_dict[key].to(self.dtype)
243
+
244
+ self.image_proj_model.load_state_dict(state_dict["image_proj"])
245
+ ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
246
+ ip_layers.load_state_dict(state_dict["ip_adapter"])
247
+
248
+ if "unet" in state_dict:
249
+ self.pipe.unet.load_state_dict(state_dict["unet"], strict=False)
250
+
251
+ # 加载attention模块
252
+ state_dict_1 = torch.load(self.ip_ckpt_1, map_location="cpu")
253
+ if "att" in state_dict_1:
254
+ att_state_dict = state_dict_1["att"]
255
+ # 转换attention模块参数到正确的dtype
256
+ for key in att_state_dict:
257
+ if torch.is_tensor(att_state_dict[key]):
258
+ att_state_dict[key] = att_state_dict[key].to(self.dtype)
259
+ self.attention_module.load_state_dict(att_state_dict)
260
+
261
+ @torch.inference_mode()
262
+ def get_image_embeds(self, pil_image=None, clip_image_embeds=None, mask_image_0=None):
263
+ if pil_image is not None:
264
+ if isinstance(pil_image, Image.Image):
265
+ pil_image = [pil_image]
266
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
267
+ clip_image = clip_image.to(self.device, dtype=self.dtype)
268
+
269
+ outputs = self.image_encoder(clip_image)
270
+ clip_image_embeds = outputs.image_embeds
271
+ last_feature_layer_output = outputs.last_hidden_state
272
+ else:
273
+ clip_image_embeds = clip_image_embeds.to(self.device, dtype=self.dtype)
274
+
275
+ # 处理mask_image_0
276
+ if mask_image_0 is not None:
277
+ mask_image_0 = mask_image_0.resize((64, 64))
278
+ mask_image_0 = mask_image_0.convert('L')
279
+ mask_image_0 = torch.tensor(np.array(mask_image_0), dtype=self.dtype, device=self.device)
280
+ mask_image_0 = (mask_image_0 > 0.5).float()
281
+ mask_image_0 = mask_image_0.unsqueeze(0).unsqueeze(0) # 添加batch和channel维度
282
+ else:
283
+ mask_image_0 = None
284
+
285
+ # 使用统一的dtype处理特征
286
+ image_embeds = self.attention_module(
287
+ last_feature_layer_output[:, :256, :],
288
+ mask_image_0
289
+ )
290
+
291
+ # 生成image_prompt_embeds
292
+ image_prompt_embeds = self.image_proj_model(image_embeds)
293
+ uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(image_embeds))
294
+
295
+ return image_prompt_embeds, uncond_image_prompt_embeds
296
+
297
+ def set_scale(self, scale):
298
+ for attn_processor in self.pipe.unet.attn_processors.values():
299
+ if isinstance(attn_processor, IPAttnProcessor):
300
+ attn_processor.scale = scale
301
+
302
+ def encode_long_text(self,
303
+ input_ids: torch.Tensor,
304
+ tokenizer: CLIPTokenizer,
305
+ text_encoder: CLIPTextModel,
306
+ max_length: int = 77,
307
+ device: str = None
308
+ ) -> torch.Tensor:
309
+ device = device or self.device
310
+
311
+ if input_ids.dim() == 1:
312
+ input_ids = input_ids.unsqueeze(0)
313
+
314
+ batch_size = input_ids.size(0)
315
+ hidden_dim = text_encoder.config.hidden_size
316
+
317
+ combined_embeddings = torch.zeros(batch_size, hidden_dim, device=device, dtype=self.dtype)
318
+
319
+ for batch_idx in range(batch_size):
320
+ current_input_ids = input_ids[batch_idx]
321
+
322
+ chunks = [
323
+ current_input_ids[i:i + max_length]
324
+ for i in range(0, len(current_input_ids), max_length)
325
+ ]
326
+
327
+ embeddings = []
328
+ for chunk in chunks:
329
+ chunk_len = len(chunk)
330
+ padding_len = max_length - chunk_len
331
+
332
+ chunk_input = {
333
+ "input_ids": torch.cat([
334
+ chunk.unsqueeze(0).to(device),
335
+ torch.zeros(1, padding_len, dtype=torch.long, device=device)
336
+ ], dim=1),
337
+ "attention_mask": torch.cat([
338
+ torch.ones(1, chunk_len, dtype=torch.long, device=device),
339
+ torch.zeros(1, padding_len, dtype=torch.long, device=device)
340
+ ], dim=1)
341
+ }
342
+
343
+ with torch.no_grad():
344
+ chunk_emb = text_encoder(**chunk_input).last_hidden_state
345
+ embeddings.append(chunk_emb[:, :chunk_len, :].mean(dim=1))
346
+
347
+ if embeddings:
348
+ combined_embeddings[batch_idx] = torch.mean(torch.cat(embeddings, dim=0), dim=0)
349
+
350
+ return combined_embeddings.unsqueeze(1)
351
+
352
+ def generate(
353
+ self,
354
+ pil_image=None,
355
+ clip_image_embeds=None,
356
+ prompt=None,
357
+ negative_prompt=None,
358
+ scale=1.0,
359
+ num_samples=4,
360
+ seed=None,
361
+ guidance_scale=7.5,
362
+ num_inference_steps=30,
363
+ mask_image_0=None,
364
+ **kwargs,
365
+ ):
366
+ self.set_scale(scale)
367
+
368
+ if pil_image is not None:
369
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
370
+ else:
371
+ num_prompts = clip_image_embeds.size(0) if clip_image_embeds is not None else 1
372
+
373
+ if prompt is None:
374
+ prompt = "best quality, high quality"
375
+ if negative_prompt is None:
376
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
377
+
378
+ if not isinstance(prompt, List):
379
+ prompt = [prompt] * num_prompts
380
+ if not isinstance(negative_prompt, List):
381
+ negative_prompt = [negative_prompt] * num_prompts
382
+
383
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(
384
+ pil_image=pil_image, clip_image_embeds=clip_image_embeds, mask_image_0=mask_image_0,
385
+ )
386
+
387
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
388
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
389
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
390
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
391
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
392
+
393
+ with torch.inference_mode():
394
+ # 编码文本提示
395
+ prompt_embeds_list = []
396
+ for p in prompt:
397
+ inputs = self.pipe.tokenizer(
398
+ p,
399
+ padding="max_length",
400
+ max_length=self.pipe.tokenizer.model_max_length,
401
+ truncation=True,
402
+ return_tensors="pt"
403
+ )
404
+ input_ids = inputs.input_ids.to(self.device)
405
+
406
+ prompt_embed = self.encode_long_text(
407
+ input_ids=input_ids,
408
+ tokenizer=self.pipe.tokenizer,
409
+ text_encoder=self.pipe.text_encoder,
410
+ device=self.device
411
+ )
412
+ prompt_embeds_list.append(prompt_embed)
413
+
414
+ prompt_embeds = torch.cat(prompt_embeds_list, dim=0)
415
+
416
+ # 编码负向提示
417
+ negative_prompt_embeds_list = []
418
+ for p in negative_prompt:
419
+ inputs = self.pipe.tokenizer(
420
+ p,
421
+ padding="max_length",
422
+ max_length=self.pipe.tokenizer.model_max_length,
423
+ truncation=True,
424
+ return_tensors="pt"
425
+ )
426
+ input_ids = inputs.input_ids.to(self.device)
427
+
428
+ negative_prompt_embed = self.encode_long_text(
429
+ input_ids=input_ids,
430
+ tokenizer=self.pipe.tokenizer,
431
+ text_encoder=self.pipe.text_encoder,
432
+ device=self.device
433
+ )
434
+ negative_prompt_embeds_list.append(negative_prompt_embed)
435
+
436
+ negative_prompt_embeds = torch.cat(negative_prompt_embeds_list, dim=0)
437
+
438
+ # 合并图像嵌入与文本嵌入
439
+ prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
440
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
441
+
442
+ generator = get_generator(seed, self.device)
443
+
444
+ images = self.pipe(
445
+ prompt_embeds=prompt_embeds,
446
+ negative_prompt_embeds=negative_prompt_embeds,
447
+ guidance_scale=guidance_scale,
448
+ num_inference_steps=num_inference_steps,
449
+ generator=generator, **kwargs,
450
+ ).images
451
+
452
+ return images
453
+
454
+
455
+ class AnomagicXL(Anomagic):
456
+ """SDXL"""
457
+
458
+ def generate(
459
+ self,
460
+ pil_image,
461
+ prompt=None,
462
+ negative_prompt=None,
463
+ scale=1.0,
464
+ num_samples=4,
465
+ seed=None,
466
+ num_inference_steps=30, **kwargs,
467
+ ):
468
+ self.set_scale(scale)
469
+
470
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
471
+
472
+ if prompt is None:
473
+ prompt = "best quality, high quality"
474
+ if negative_prompt is None:
475
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
476
+
477
+ if not isinstance(prompt, List):
478
+ prompt = [prompt] * num_prompts
479
+ if not isinstance(negative_prompt, List):
480
+ negative_prompt = [negative_prompt] * num_prompts
481
+
482
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
483
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
484
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
485
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
486
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
487
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
488
+
489
+ with torch.inference_mode():
490
+ (
491
+ prompt_embeds,
492
+ negative_prompt_embeds,
493
+ pooled_prompt_embeds,
494
+ negative_pooled_prompt_embeds,
495
+ ) = self.pipe.encode_prompt(
496
+ prompt,
497
+ num_images_per_prompt=num_samples,
498
+ do_classifier_free_guidance=True,
499
+ negative_prompt=negative_prompt,
500
+ )
501
+ prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
502
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
503
+
504
+ self.generator = get_generator(seed, self.device)
505
+
506
+ images = self.pipe(
507
+ prompt_embeds=prompt_embeds,
508
+ negative_prompt_embeds=negative_prompt_embeds,
509
+ pooled_prompt_embeds=pooled_prompt_embeds,
510
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
511
+ num_inference_steps=num_inference_steps,
512
+ generator=self.generator, **kwargs,
513
+ ).images
514
+
515
+ return images
516
+
517
+
518
+ class AnomagicPlus(Anomagic):
519
+ """Anomagic with fine-grained features"""
520
+
521
+ def init_proj(self):
522
+ image_proj_model = Resampler(
523
+ dim=self.pipe.unet.config.cross_attention_dim,
524
+ depth=4,
525
+ dim_head=64,
526
+ heads=12,
527
+ num_queries=self.num_tokens,
528
+ embedding_dim=self.image_encoder.config.hidden_size,
529
+ output_dim=self.pipe.unet.config.cross_attention_dim,
530
+ ff_mult=4,
531
+ ).to(self.device, dtype=self.dtype)
532
+ return image_proj_model
533
+
534
+ @torch.inference_mode()
535
+ def get_image_embeds(self, pil_image=None, clip_image_embeds=None):
536
+ if isinstance(pil_image, Image.Image):
537
+ pil_image = [pil_image]
538
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
539
+ clip_image = clip_image.to(self.device, dtype=self.dtype)
540
+
541
+ clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
542
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
543
+
544
+ uncond_clip_image_embeds = self.image_encoder(
545
+ torch.zeros_like(clip_image), output_hidden_states=True
546
+ ).hidden_states[-2]
547
+ uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
548
+
549
+ return image_prompt_embeds, uncond_image_prompt_embeds
550
+
551
+
552
+ class AnomagicFull(AnomagicPlus):
553
+ """Anomagic with full features"""
554
+
555
+ def init_proj(self):
556
+ image_proj_model = MLPProjModel(
557
+ cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
558
+ clip_embeddings_dim=self.image_encoder.config.hidden_size,
559
+ ).to(self.device, dtype=self.dtype)
560
+ return image_proj_model
561
+
562
+
563
+ class AnomagicPlusXL(Anomagic):
564
+ """SDXL"""
565
+
566
+ def init_proj(self):
567
+ image_proj_model = Resampler(
568
+ dim=1280,
569
+ depth=4,
570
+ dim_head=64,
571
+ heads=20,
572
+ num_queries=self.num_tokens,
573
+ embedding_dim=self.image_encoder.config.hidden_size,
574
+ output_dim=self.pipe.unet.config.cross_attention_dim,
575
+ ff_mult=4,
576
+ ).to(self.device, dtype=self.dtype)
577
+ return image_proj_model
578
+
579
+ @torch.inference_mode()
580
+ def get_image_embeds(self, pil_image):
581
+ if isinstance(pil_image, Image.Image):
582
+ pil_image = [pil_image]
583
+ clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
584
+ clip_image = clip_image.to(self.device, dtype=self.dtype)
585
+
586
+ clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
587
+ image_prompt_embeds = self.image_proj_model(clip_image_embeds)
588
+
589
+ uncond_clip_image_embeds = self.image_encoder(
590
+ torch.zeros_like(clip_image), output_hidden_states=True
591
+ ).hidden_states[-2]
592
+ uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
593
+
594
+ return image_prompt_embeds, uncond_image_prompt_embeds
595
+
596
+ def generate(
597
+ self,
598
+ pil_image,
599
+ prompt=None,
600
+ negative_prompt=None,
601
+ scale=1.0,
602
+ num_samples=4,
603
+ seed=None,
604
+ num_inference_steps=30, **kwargs,
605
+ ):
606
+ self.set_scale(scale)
607
+
608
+ num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
609
+
610
+ if prompt is None:
611
+ prompt = "best quality, high quality"
612
+ if negative_prompt is None:
613
+ negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
614
+
615
+ if not isinstance(prompt, List):
616
+ prompt = [prompt] * num_prompts
617
+ if not isinstance(negative_prompt, List):
618
+ negative_prompt = [negative_prompt] * num_prompts
619
+
620
+ image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
621
+ bs_embed, seq_len, _ = image_prompt_embeds.shape
622
+ image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
623
+ image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
624
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
625
+ uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
626
+
627
+ with torch.inference_mode():
628
+ (
629
+ prompt_embeds,
630
+ negative_prompt_embeds,
631
+ pooled_prompt_embeds,
632
+ negative_pooled_prompt_embeds,
633
+ ) = self.pipe.encode_prompt(
634
+ prompt,
635
+ num_images_per_prompt=num_samples,
636
+ do_classifier_free_guidance=True,
637
+ negative_prompt=negative_prompt,
638
+ )
639
+ prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
640
+ negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
641
+
642
+ generator = get_generator(seed, self.device)
643
+
644
+ images = self.pipe(
645
+ prompt_embeds=prompt_embeds,
646
+ negative_prompt_embeds=negative_prompt_embeds,
647
+ pooled_prompt_embeds=pooled_prompt_embeds,
648
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
649
+ num_inference_steps=num_inference_steps,
650
+ generator=generator, **kwargs,
651
+ ).images
652
+
653
+ return images
ip_adapter/resampler.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
2
+ # and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
3
+
4
+ import math
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from einops import rearrange
9
+ from einops.layers.torch import Rearrange
10
+
11
+
12
+ # FFN
13
+ def FeedForward(dim, mult=4):
14
+ inner_dim = int(dim * mult)
15
+ return nn.Sequential(
16
+ nn.LayerNorm(dim),
17
+ nn.Linear(dim, inner_dim, bias=False),
18
+ nn.GELU(),
19
+ nn.Linear(inner_dim, dim, bias=False),
20
+ )
21
+
22
+
23
+ def reshape_tensor(x, heads):
24
+ bs, length, width = x.shape
25
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
26
+ x = x.view(bs, length, heads, -1)
27
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
28
+ x = x.transpose(1, 2)
29
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
30
+ x = x.reshape(bs, heads, length, -1)
31
+ return x
32
+
33
+
34
+ class PerceiverAttention(nn.Module):
35
+ def __init__(self, *, dim, dim_head=64, heads=8):
36
+ super().__init__()
37
+ self.scale = dim_head**-0.5
38
+ self.dim_head = dim_head
39
+ self.heads = heads
40
+ inner_dim = dim_head * heads
41
+
42
+ self.norm1 = nn.LayerNorm(dim)
43
+ self.norm2 = nn.LayerNorm(dim)
44
+
45
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
46
+ self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
47
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
48
+
49
+ def forward(self, x, latents):
50
+ """
51
+ Args:
52
+ x (torch.Tensor): image features
53
+ shape (b, n1, D)
54
+ latent (torch.Tensor): latent features
55
+ shape (b, n2, D)
56
+ """
57
+ x = self.norm1(x)
58
+ latents = self.norm2(latents)
59
+
60
+ b, l, _ = latents.shape
61
+
62
+ q = self.to_q(latents)
63
+ kv_input = torch.cat((x, latents), dim=-2)
64
+ k, v = self.to_kv(kv_input).chunk(2, dim=-1)
65
+
66
+ q = reshape_tensor(q, self.heads)
67
+ k = reshape_tensor(k, self.heads)
68
+ v = reshape_tensor(v, self.heads)
69
+
70
+ # attention
71
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
72
+ weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
73
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
74
+ out = weight @ v
75
+
76
+ out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
77
+
78
+ return self.to_out(out)
79
+
80
+
81
+ class Resampler(nn.Module):
82
+ def __init__(
83
+ self,
84
+ dim=1024,
85
+ depth=8,
86
+ dim_head=64,
87
+ heads=16,
88
+ num_queries=8,
89
+ embedding_dim=768,
90
+ output_dim=1024,
91
+ ff_mult=4,
92
+ max_seq_len: int = 257, # CLIP tokens + CLS token
93
+ apply_pos_emb: bool = False,
94
+ num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
95
+ ):
96
+ super().__init__()
97
+ self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
98
+
99
+ self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
100
+
101
+ self.proj_in = nn.Linear(embedding_dim, dim)
102
+
103
+ self.proj_out = nn.Linear(dim, output_dim)
104
+ self.norm_out = nn.LayerNorm(output_dim)
105
+
106
+ self.to_latents_from_mean_pooled_seq = (
107
+ nn.Sequential(
108
+ nn.LayerNorm(dim),
109
+ nn.Linear(dim, dim * num_latents_mean_pooled),
110
+ Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
111
+ )
112
+ if num_latents_mean_pooled > 0
113
+ else None
114
+ )
115
+
116
+ self.layers = nn.ModuleList([])
117
+ for _ in range(depth):
118
+ self.layers.append(
119
+ nn.ModuleList(
120
+ [
121
+ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
122
+ FeedForward(dim=dim, mult=ff_mult),
123
+ ]
124
+ )
125
+ )
126
+
127
+ def forward(self, x):
128
+ if self.pos_emb is not None:
129
+ n, device = x.shape[1], x.device
130
+ pos_emb = self.pos_emb(torch.arange(n, device=device))
131
+ x = x + pos_emb
132
+
133
+ latents = self.latents.repeat(x.size(0), 1, 1)
134
+
135
+ x = self.proj_in(x)
136
+
137
+ if self.to_latents_from_mean_pooled_seq:
138
+ meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
139
+ meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
140
+ latents = torch.cat((meanpooled_latents, latents), dim=-2)
141
+
142
+ for attn, ff in self.layers:
143
+ latents = attn(x, latents) + latents
144
+ latents = ff(latents) + latents
145
+
146
+ latents = self.proj_out(latents)
147
+ return self.norm_out(latents)
148
+
149
+
150
+ def masked_mean(t, *, dim, mask=None):
151
+ if mask is None:
152
+ return t.mean(dim=dim)
153
+
154
+ denom = mask.sum(dim=dim, keepdim=True)
155
+ mask = rearrange(mask, "b n -> b n 1")
156
+ masked_t = t.masked_fill(~mask, 0.0)
157
+
158
+ return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
ip_adapter/sd3_attention_processor.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, List, Optional, Union
2
+
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from torch import nn
6
+ from diffusers.models.attention_processor import Attention
7
+
8
+
9
+ class JointAttnProcessor2_0:
10
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
11
+
12
+ def __init__(self):
13
+ if not hasattr(F, "scaled_dot_product_attention"):
14
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
15
+
16
+ def __call__(
17
+ self,
18
+ attn: Attention,
19
+ hidden_states: torch.FloatTensor,
20
+ encoder_hidden_states: torch.FloatTensor = None,
21
+ attention_mask: Optional[torch.FloatTensor] = None,
22
+ *args,
23
+ **kwargs,
24
+ ) -> torch.FloatTensor:
25
+ residual = hidden_states
26
+
27
+ input_ndim = hidden_states.ndim
28
+ if input_ndim == 4:
29
+ batch_size, channel, height, width = hidden_states.shape
30
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
31
+ context_input_ndim = encoder_hidden_states.ndim
32
+ if context_input_ndim == 4:
33
+ batch_size, channel, height, width = encoder_hidden_states.shape
34
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
35
+
36
+ batch_size = encoder_hidden_states.shape[0]
37
+
38
+ # `sample` projections.
39
+ query = attn.to_q(hidden_states)
40
+ key = attn.to_k(hidden_states)
41
+ value = attn.to_v(hidden_states)
42
+
43
+ # `context` projections.
44
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
45
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
46
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
47
+
48
+ # attention
49
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=1)
50
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=1)
51
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=1)
52
+
53
+ inner_dim = key.shape[-1]
54
+ head_dim = inner_dim // attn.heads
55
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
56
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
57
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
58
+
59
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
60
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
61
+ hidden_states = hidden_states.to(query.dtype)
62
+
63
+ # Split the attention outputs.
64
+ hidden_states, encoder_hidden_states = (
65
+ hidden_states[:, : residual.shape[1]],
66
+ hidden_states[:, residual.shape[1] :],
67
+ )
68
+
69
+ # linear proj
70
+ hidden_states = attn.to_out[0](hidden_states)
71
+ # dropout
72
+ hidden_states = attn.to_out[1](hidden_states)
73
+ if not attn.context_pre_only:
74
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
75
+
76
+ if input_ndim == 4:
77
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
78
+ if context_input_ndim == 4:
79
+ encoder_hidden_states = encoder_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
80
+
81
+ return hidden_states, encoder_hidden_states
82
+
83
+
84
+ class IPJointAttnProcessor2_0(torch.nn.Module):
85
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
86
+
87
+ def __init__(self, context_dim, hidden_dim, scale=1.0):
88
+ if not hasattr(F, "scaled_dot_product_attention"):
89
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
90
+ super().__init__()
91
+ self.scale = scale
92
+
93
+ self.add_k_proj_ip = nn.Linear(context_dim, hidden_dim)
94
+ self.add_v_proj_ip = nn.Linear(context_dim, hidden_dim)
95
+
96
+
97
+ def __call__(
98
+ self,
99
+ attn: Attention,
100
+ hidden_states: torch.FloatTensor,
101
+ encoder_hidden_states: torch.FloatTensor = None,
102
+ attention_mask: Optional[torch.FloatTensor] = None,
103
+ ip_hidden_states: torch.FloatTensor = None,
104
+ *args,
105
+ **kwargs,
106
+ ) -> torch.FloatTensor:
107
+ residual = hidden_states
108
+
109
+ input_ndim = hidden_states.ndim
110
+ if input_ndim == 4:
111
+ batch_size, channel, height, width = hidden_states.shape
112
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
113
+ context_input_ndim = encoder_hidden_states.ndim
114
+ if context_input_ndim == 4:
115
+ batch_size, channel, height, width = encoder_hidden_states.shape
116
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
117
+
118
+ batch_size = encoder_hidden_states.shape[0]
119
+
120
+ # `sample` projections.
121
+ query = attn.to_q(hidden_states)
122
+ key = attn.to_k(hidden_states)
123
+ value = attn.to_v(hidden_states)
124
+
125
+ sample_query = query # latent query
126
+
127
+ # `context` projections.
128
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
129
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
130
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
131
+
132
+ # attention
133
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=1)
134
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=1)
135
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=1)
136
+
137
+ inner_dim = key.shape[-1]
138
+ head_dim = inner_dim // attn.heads
139
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
140
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
141
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
142
+
143
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
144
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
145
+ hidden_states = hidden_states.to(query.dtype)
146
+
147
+ # Split the attention outputs.
148
+ hidden_states, encoder_hidden_states = (
149
+ hidden_states[:, : residual.shape[1]],
150
+ hidden_states[:, residual.shape[1] :],
151
+ )
152
+
153
+ # for ip-adapter
154
+ ip_key = self.add_k_proj_ip(ip_hidden_states)
155
+ ip_value = self.add_v_proj_ip(ip_hidden_states)
156
+ ip_query = sample_query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
157
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
158
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
159
+
160
+ ip_hidden_states = F.scaled_dot_product_attention(ip_query, ip_key, ip_value, dropout_p=0.0, is_causal=False)
161
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
162
+ ip_hidden_states = ip_hidden_states.to(ip_query.dtype)
163
+
164
+ hidden_states = hidden_states + self.scale * ip_hidden_states
165
+
166
+ # linear proj
167
+ hidden_states = attn.to_out[0](hidden_states)
168
+ # dropout
169
+ hidden_states = attn.to_out[1](hidden_states)
170
+ if not attn.context_pre_only:
171
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
172
+
173
+ if input_ndim == 4:
174
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
175
+ if context_input_ndim == 4:
176
+ encoder_hidden_states = encoder_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
177
+
178
+ return hidden_states, encoder_hidden_states
179
+
ip_adapter/test_resampler.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from resampler import Resampler
3
+ from transformers import CLIPVisionModel
4
+
5
+ BATCH_SIZE = 2
6
+ OUTPUT_DIM = 1280
7
+ NUM_QUERIES = 8
8
+ NUM_LATENTS_MEAN_POOLED = 4 # 0 for no mean pooling (previous behavior)
9
+ APPLY_POS_EMB = True # False for no positional embeddings (previous behavior)
10
+ IMAGE_ENCODER_NAME_OR_PATH = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
11
+
12
+
13
+ def main():
14
+ image_encoder = CLIPVisionModel.from_pretrained(IMAGE_ENCODER_NAME_OR_PATH)
15
+ embedding_dim = image_encoder.config.hidden_size
16
+ print(f"image_encoder hidden size: ", embedding_dim)
17
+
18
+ image_proj_model = Resampler(
19
+ dim=1024,
20
+ depth=2,
21
+ dim_head=64,
22
+ heads=16,
23
+ num_queries=NUM_QUERIES,
24
+ embedding_dim=embedding_dim,
25
+ output_dim=OUTPUT_DIM,
26
+ ff_mult=2,
27
+ max_seq_len=257,
28
+ apply_pos_emb=APPLY_POS_EMB,
29
+ num_latents_mean_pooled=NUM_LATENTS_MEAN_POOLED,
30
+ )
31
+
32
+ dummy_images = torch.randn(BATCH_SIZE, 3, 224, 224)
33
+ with torch.no_grad():
34
+ image_embeds = image_encoder(dummy_images, output_hidden_states=True).hidden_states[-2]
35
+ print("image_embds shape: ", image_embeds.shape)
36
+
37
+ with torch.no_grad():
38
+ ip_tokens = image_proj_model(image_embeds)
39
+ print("ip_tokens shape:", ip_tokens.shape)
40
+ assert ip_tokens.shape == (BATCH_SIZE, NUM_QUERIES + NUM_LATENTS_MEAN_POOLED, OUTPUT_DIM)
41
+
42
+
43
+ if __name__ == "__main__":
44
+ main()
ip_adapter/utils.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+ attn_maps = {}
7
+ def hook_fn(name):
8
+ def forward_hook(module, input, output):
9
+ if hasattr(module.processor, "attn_map"):
10
+ attn_maps[name] = module.processor.attn_map
11
+ del module.processor.attn_map
12
+
13
+ return forward_hook
14
+
15
+ def register_cross_attention_hook(unet):
16
+ for name, module in unet.named_modules():
17
+ if name.split('.')[-1].startswith('attn2'):
18
+ module.register_forward_hook(hook_fn(name))
19
+
20
+ return unet
21
+
22
+ def upscale(attn_map, target_size):
23
+ attn_map = torch.mean(attn_map, dim=0)
24
+ attn_map = attn_map.permute(1,0)
25
+ temp_size = None
26
+
27
+ for i in range(0,5):
28
+ scale = 2 ** i
29
+ if ( target_size[0] // scale ) * ( target_size[1] // scale) == attn_map.shape[1]*64:
30
+ temp_size = (target_size[0]//(scale*8), target_size[1]//(scale*8))
31
+ break
32
+
33
+ assert temp_size is not None, "temp_size cannot is None"
34
+
35
+ attn_map = attn_map.view(attn_map.shape[0], *temp_size)
36
+
37
+ attn_map = F.interpolate(
38
+ attn_map.unsqueeze(0).to(dtype=torch.float32),
39
+ size=target_size,
40
+ mode='bilinear',
41
+ align_corners=False
42
+ )[0]
43
+
44
+ attn_map = torch.softmax(attn_map, dim=0)
45
+ return attn_map
46
+ def get_net_attn_map(image_size, batch_size=2, instance_or_negative=False, detach=True):
47
+
48
+ idx = 0 if instance_or_negative else 1
49
+ net_attn_maps = []
50
+
51
+ for name, attn_map in attn_maps.items():
52
+ attn_map = attn_map.cpu() if detach else attn_map
53
+ attn_map = torch.chunk(attn_map, batch_size)[idx].squeeze()
54
+ attn_map = upscale(attn_map, image_size)
55
+ net_attn_maps.append(attn_map)
56
+
57
+ net_attn_maps = torch.mean(torch.stack(net_attn_maps,dim=0),dim=0)
58
+
59
+ return net_attn_maps
60
+
61
+ def attnmaps2images(net_attn_maps):
62
+
63
+ #total_attn_scores = 0
64
+ images = []
65
+
66
+ for attn_map in net_attn_maps:
67
+ attn_map = attn_map.cpu().numpy()
68
+ #total_attn_scores += attn_map.mean().item()
69
+
70
+ normalized_attn_map = (attn_map - np.min(attn_map)) / (np.max(attn_map) - np.min(attn_map)) * 255
71
+ normalized_attn_map = normalized_attn_map.astype(np.uint8)
72
+ #print("norm: ", normalized_attn_map.shape)
73
+ image = Image.fromarray(normalized_attn_map)
74
+
75
+ #image = fix_save_attn_map(attn_map)
76
+ images.append(image)
77
+
78
+ #print(total_attn_scores)
79
+ return images
80
+ def is_torch2_available():
81
+ return hasattr(F, "scaled_dot_product_attention")
82
+
83
+ def get_generator(seed, device):
84
+
85
+ if seed is not None:
86
+ if isinstance(seed, list):
87
+ generator = [torch.Generator(device).manual_seed(seed_item) for seed_item in seed]
88
+ else:
89
+ generator = torch.Generator(device).manual_seed(seed)
90
+ else:
91
+ generator = None
92
+
93
+ return generator