appinitdev commited on
Commit
c3c74c9
·
verified ·
1 Parent(s): 97ec6fc

Create attention_processor_faceid.py

Browse files
ip_adapter/attention_processor_faceid.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from diffusers.models.lora import LoRALinearLayer
7
+
8
+
9
+ class LoRAAttnProcessor(nn.Module):
10
+ r"""
11
+ Default processor for performing attention-related computations.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ hidden_size=None,
17
+ cross_attention_dim=None,
18
+ rank=4,
19
+ network_alpha=None,
20
+ lora_scale=1.0,
21
+ ):
22
+ super().__init__()
23
+
24
+ self.rank = rank
25
+ self.lora_scale = lora_scale
26
+
27
+ self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
28
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
29
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
30
+ self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
31
+
32
+ def __call__(
33
+ self,
34
+ attn,
35
+ hidden_states,
36
+ encoder_hidden_states=None,
37
+ attention_mask=None,
38
+ temb=None,
39
+ *args,
40
+ **kwargs,
41
+ ):
42
+ residual = hidden_states
43
+
44
+ if attn.spatial_norm is not None:
45
+ hidden_states = attn.spatial_norm(hidden_states, temb)
46
+
47
+ input_ndim = hidden_states.ndim
48
+
49
+ if input_ndim == 4:
50
+ batch_size, channel, height, width = hidden_states.shape
51
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
52
+
53
+ batch_size, sequence_length, _ = (
54
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
55
+ )
56
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
57
+
58
+ if attn.group_norm is not None:
59
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
60
+
61
+ query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
62
+
63
+ if encoder_hidden_states is None:
64
+ encoder_hidden_states = hidden_states
65
+ elif attn.norm_cross:
66
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
67
+
68
+ key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
69
+ value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
70
+
71
+ query = attn.head_to_batch_dim(query)
72
+ key = attn.head_to_batch_dim(key)
73
+ value = attn.head_to_batch_dim(value)
74
+
75
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
76
+ hidden_states = torch.bmm(attention_probs, value)
77
+ hidden_states = attn.batch_to_head_dim(hidden_states)
78
+
79
+ # linear proj
80
+ hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
81
+ # dropout
82
+ hidden_states = attn.to_out[1](hidden_states)
83
+
84
+ if input_ndim == 4:
85
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
86
+
87
+ if attn.residual_connection:
88
+ hidden_states = hidden_states + residual
89
+
90
+ hidden_states = hidden_states / attn.rescale_output_factor
91
+
92
+ return hidden_states
93
+
94
+
95
+ class LoRAIPAttnProcessor(nn.Module):
96
+ r"""
97
+ Attention processor for IP-Adapater.
98
+ Args:
99
+ hidden_size (`int`):
100
+ The hidden size of the attention layer.
101
+ cross_attention_dim (`int`):
102
+ The number of channels in the `encoder_hidden_states`.
103
+ scale (`float`, defaults to 1.0):
104
+ the weight scale of image prompt.
105
+ num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
106
+ The context length of the image features.
107
+ """
108
+
109
+ def __init__(self, hidden_size, cross_attention_dim=None, rank=4, network_alpha=None, lora_scale=1.0, scale=1.0, num_tokens=4):
110
+ super().__init__()
111
+
112
+ self.rank = rank
113
+ self.lora_scale = lora_scale
114
+
115
+ self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
116
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
117
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
118
+ self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
119
+
120
+ self.hidden_size = hidden_size
121
+ self.cross_attention_dim = cross_attention_dim
122
+ self.scale = scale
123
+ self.num_tokens = num_tokens
124
+
125
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
126
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
127
+
128
+ def __call__(
129
+ self,
130
+ attn,
131
+ hidden_states,
132
+ encoder_hidden_states=None,
133
+ attention_mask=None,
134
+ temb=None,
135
+ *args,
136
+ **kwargs,
137
+ ):
138
+ residual = hidden_states
139
+
140
+ if attn.spatial_norm is not None:
141
+ hidden_states = attn.spatial_norm(hidden_states, temb)
142
+
143
+ input_ndim = hidden_states.ndim
144
+
145
+ if input_ndim == 4:
146
+ batch_size, channel, height, width = hidden_states.shape
147
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
148
+
149
+ batch_size, sequence_length, _ = (
150
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
151
+ )
152
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
153
+
154
+ if attn.group_norm is not None:
155
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
156
+
157
+ query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
158
+
159
+ if encoder_hidden_states is None:
160
+ encoder_hidden_states = hidden_states
161
+ else:
162
+ # get encoder_hidden_states, ip_hidden_states
163
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
164
+ encoder_hidden_states, ip_hidden_states = (
165
+ encoder_hidden_states[:, :end_pos, :],
166
+ encoder_hidden_states[:, end_pos:, :],
167
+ )
168
+ if attn.norm_cross:
169
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
170
+
171
+ key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
172
+ value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
173
+
174
+ query = attn.head_to_batch_dim(query)
175
+ key = attn.head_to_batch_dim(key)
176
+ value = attn.head_to_batch_dim(value)
177
+
178
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
179
+ hidden_states = torch.bmm(attention_probs, value)
180
+ hidden_states = attn.batch_to_head_dim(hidden_states)
181
+
182
+ # for ip-adapter
183
+ ip_key = self.to_k_ip(ip_hidden_states)
184
+ ip_value = self.to_v_ip(ip_hidden_states)
185
+
186
+ ip_key = attn.head_to_batch_dim(ip_key)
187
+ ip_value = attn.head_to_batch_dim(ip_value)
188
+
189
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
190
+ self.attn_map = ip_attention_probs
191
+ ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
192
+ ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
193
+
194
+ hidden_states = hidden_states + self.scale * ip_hidden_states
195
+
196
+ # linear proj
197
+ hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
198
+ # dropout
199
+ hidden_states = attn.to_out[1](hidden_states)
200
+
201
+ if input_ndim == 4:
202
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
203
+
204
+ if attn.residual_connection:
205
+ hidden_states = hidden_states + residual
206
+
207
+ hidden_states = hidden_states / attn.rescale_output_factor
208
+
209
+ return hidden_states
210
+
211
+
212
+ class LoRAAttnProcessor2_0(nn.Module):
213
+
214
+ r"""
215
+ Default processor for performing attention-related computations.
216
+ """
217
+
218
+ def __init__(
219
+ self,
220
+ hidden_size=None,
221
+ cross_attention_dim=None,
222
+ rank=4,
223
+ network_alpha=None,
224
+ lora_scale=1.0,
225
+ ):
226
+ super().__init__()
227
+
228
+ self.rank = rank
229
+ self.lora_scale = lora_scale
230
+
231
+ self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
232
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
233
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
234
+ self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
235
+
236
+ def __call__(
237
+ self,
238
+ attn,
239
+ hidden_states,
240
+ encoder_hidden_states=None,
241
+ attention_mask=None,
242
+ temb=None,
243
+ *args,
244
+ **kwargs,
245
+ ):
246
+ residual = hidden_states
247
+
248
+ if attn.spatial_norm is not None:
249
+ hidden_states = attn.spatial_norm(hidden_states, temb)
250
+
251
+ input_ndim = hidden_states.ndim
252
+
253
+ if input_ndim == 4:
254
+ batch_size, channel, height, width = hidden_states.shape
255
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
256
+
257
+ batch_size, sequence_length, _ = (
258
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
259
+ )
260
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
261
+
262
+ if attn.group_norm is not None:
263
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
264
+
265
+ query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
266
+
267
+ if encoder_hidden_states is None:
268
+ encoder_hidden_states = hidden_states
269
+ elif attn.norm_cross:
270
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
271
+
272
+ key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
273
+ value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
274
+
275
+ inner_dim = key.shape[-1]
276
+ head_dim = inner_dim // attn.heads
277
+
278
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
279
+
280
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
281
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
282
+
283
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
284
+ # TODO: add support for attn.scale when we move to Torch 2.1
285
+ hidden_states = F.scaled_dot_product_attention(
286
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
287
+ )
288
+
289
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
290
+ hidden_states = hidden_states.to(query.dtype)
291
+
292
+ # linear proj
293
+ hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
294
+ # dropout
295
+ hidden_states = attn.to_out[1](hidden_states)
296
+
297
+ if input_ndim == 4:
298
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
299
+
300
+ if attn.residual_connection:
301
+ hidden_states = hidden_states + residual
302
+
303
+ hidden_states = hidden_states / attn.rescale_output_factor
304
+
305
+ return hidden_states
306
+
307
+
308
+ class LoRAIPAttnProcessor2_0(nn.Module):
309
+ r"""
310
+ Processor for implementing the LoRA attention mechanism.
311
+
312
+ Args:
313
+ hidden_size (`int`, *optional*):
314
+ The hidden size of the attention layer.
315
+ cross_attention_dim (`int`, *optional*):
316
+ The number of channels in the `encoder_hidden_states`.
317
+ rank (`int`, defaults to 4):
318
+ The dimension of the LoRA update matrices.
319
+ network_alpha (`int`, *optional*):
320
+ Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
321
+ """
322
+
323
+ def __init__(self, hidden_size, cross_attention_dim=None, rank=4, network_alpha=None, lora_scale=1.0, scale=1.0, num_tokens=4):
324
+ super().__init__()
325
+
326
+ self.rank = rank
327
+ self.lora_scale = lora_scale
328
+ self.num_tokens = num_tokens
329
+
330
+ self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
331
+ self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
332
+ self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
333
+ self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
334
+
335
+
336
+ self.hidden_size = hidden_size
337
+ self.cross_attention_dim = cross_attention_dim
338
+ self.scale = scale
339
+
340
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
341
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
342
+
343
+ def __call__(
344
+ self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0, temb=None, *args, **kwargs,
345
+ ):
346
+ residual = hidden_states
347
+
348
+ if attn.spatial_norm is not None:
349
+ hidden_states = attn.spatial_norm(hidden_states, temb)
350
+
351
+ input_ndim = hidden_states.ndim
352
+
353
+ if input_ndim == 4:
354
+ batch_size, channel, height, width = hidden_states.shape
355
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
356
+
357
+ batch_size, sequence_length, _ = (
358
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
359
+ )
360
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
361
+
362
+ if attn.group_norm is not None:
363
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
364
+
365
+ query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
366
+ #query = attn.head_to_batch_dim(query)
367
+
368
+ if encoder_hidden_states is None:
369
+ encoder_hidden_states = hidden_states
370
+ else:
371
+ # get encoder_hidden_states, ip_hidden_states
372
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens
373
+ encoder_hidden_states, ip_hidden_states = (
374
+ encoder_hidden_states[:, :end_pos, :],
375
+ encoder_hidden_states[:, end_pos:, :],
376
+ )
377
+ if attn.norm_cross:
378
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
379
+
380
+ # for text
381
+ key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
382
+ value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
383
+
384
+ inner_dim = key.shape[-1]
385
+ head_dim = inner_dim // attn.heads
386
+
387
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
388
+
389
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
390
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
391
+
392
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
393
+ # TODO: add support for attn.scale when we move to Torch 2.1
394
+ hidden_states = F.scaled_dot_product_attention(
395
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
396
+ )
397
+
398
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
399
+ hidden_states = hidden_states.to(query.dtype)
400
+
401
+ # for ip
402
+ ip_key = self.to_k_ip(ip_hidden_states)
403
+ ip_value = self.to_v_ip(ip_hidden_states)
404
+
405
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
406
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
407
+
408
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
409
+ # TODO: add support for attn.scale when we move to Torch 2.1
410
+ ip_hidden_states = F.scaled_dot_product_attention(
411
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
412
+ )
413
+
414
+
415
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
416
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
417
+
418
+ hidden_states = hidden_states + self.scale * ip_hidden_states
419
+
420
+ # linear proj
421
+ hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
422
+ # dropout
423
+ hidden_states = attn.to_out[1](hidden_states)
424
+
425
+ if input_ndim == 4:
426
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
427
+
428
+ if attn.residual_connection:
429
+ hidden_states = hidden_states + residual
430
+
431
+ hidden_states = hidden_states / attn.rescale_output_factor
432
+
433
+ return hidden_states