Elffuss BraidHub

kikocis/ncnn public

master · 19.3 KiBRawPermalink
1# Tencent is pleased to support the open source community by making ncnn available.
2#
3# Copyright (C) 2023 THL A29 Limited, a Tencent company. All rights reserved.
4#
5# Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
6# in compliance with the License. You may obtain a copy of the License at
7#
8# https://opensource.org/licenses/BSD-3-Clause
9#
10# Unless required by applicable law or agreed to in writing, software distributed
11# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
12# CONDITIONS OF ANY KIND, either express or implied. See the License for the
13# specific language governing permissions and limitations under the License.
14
15import torch
16import torch.nn as nn
17import torch.nn.functional as F
18from packaging import version
19
20from einops import rearrange
21from typing import Any, Optional, Tuple, Union
22import math
23
24class Attention(nn.Module):
25 def __init__(self, embed_dim, num_heads, qkv_bias=True):
26 super().__init__()
27 self.num_heads = num_heads
28 head_dim = embed_dim // num_heads
29 self.scale = head_dim ** -0.5
30
31 self.qkv = nn.Linear(embed_dim, embed_dim * 3, bias=qkv_bias)
32 self.proj = nn.Linear(embed_dim, embed_dim)
33
34 def forward(self, x):
35 _, N, C = x.shape
36 qkv = self.qkv(x).reshape((-1, N, 3, self.num_heads, C // self.num_heads)).permute((2, 0, 3, 1, 4))
37 q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
38
39 attn = q.matmul(k.permute((0, 1, 3, 2)))
40 attn = F.softmax(attn, dim=-1)
41
42 x = (attn.matmul(v)).permute((0, 2, 1, 3)).reshape((-1, N, C))
43 x = self.proj(x)
44 return x
45
46class CrossAttention(nn.Module):
47 def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.):
48 super().__init__()
49 inner_dim = dim_head * heads
50 if context_dim is None:
51 context_dim = query_dim
52
53 self.scale = dim_head ** -0.5
54 self.heads = heads
55
56 self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
57 self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
58 self.to_v = nn.Linear(context_dim, inner_dim, bias=False)
59
60 self.to_out = nn.Sequential(
61 nn.Linear(inner_dim, query_dim),
62 nn.Dropout(dropout)
63 )
64
65 def forward(self, x, context=None):
66 h = self.heads
67
68 q = self.to_q(x)
69 if context is None:
70 context = x
71 k = self.to_k(context)
72 v = self.to_v(context)
73
74 q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
75
76 sim = torch.einsum('b i d, b j d -> b i j', q, k) * self.scale
77
78 # attention, what we cannot get enough of
79 attn = sim.softmax(dim=-1)
80
81 out = torch.einsum('b i j, b j d -> b i d', attn, v)
82 out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
83 return self.to_out(out)
84
85class diffusers_CrossAttnProcessor:
86 def __call__(self, attn, hidden_states, encoder_hidden_states=None):
87 batch_size, sequence_length, _ = hidden_states.shape
88 query = attn.to_q(hidden_states)
89
90 if encoder_hidden_states is None:
91 encoder_hidden_states = hidden_states
92
93 key = attn.to_k(encoder_hidden_states)
94 value = attn.to_v(encoder_hidden_states)
95
96 query = attn.head_to_batch_dim(query)
97 key = attn.head_to_batch_dim(key)
98 value = attn.head_to_batch_dim(value)
99
100 attention_probs = attn.get_attention_scores(query, key)
101 hidden_states = torch.bmm(attention_probs, value)
102 hidden_states = attn.batch_to_head_dim(hidden_states)
103
104 # linear proj
105 hidden_states = attn.to_out[0](hidden_states)
106 # dropout
107 hidden_states = attn.to_out[1](hidden_states)
108
109 return hidden_states
110
111class diffusers_AttnProcessor2_0:
112 def __call__(self, attn: Attention, hidden_states, encoder_hidden_states=None, attention_mask=None):
113 batch_size, sequence_length, _ = (
114 hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
115 )
116 inner_dim = hidden_states.shape[-1]
117
118 if attention_mask is not None:
119 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
120 # scaled_dot_product_attention expects attention_mask shape to be
121 # (batch, heads, source_length, target_length)
122 attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
123
124 query = attn.to_q(hidden_states)
125
126 if encoder_hidden_states is None:
127 encoder_hidden_states = hidden_states
128
129 key = attn.to_k(encoder_hidden_states)
130 value = attn.to_v(encoder_hidden_states)
131
132 head_dim = inner_dim // attn.heads
133 query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
134 key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
135 value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
136
137 # the output of sdp = (batch, num_heads, seq_len, head_dim)
138 # TODO: add support for attn.scale when we move to Torch 2.1
139 hidden_states = F.scaled_dot_product_attention(
140 query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
141 )
142
143 hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
144 hidden_states = hidden_states.to(query.dtype)
145
146 # linear proj
147 hidden_states = attn.to_out[0](hidden_states)
148 # dropout
149 hidden_states = attn.to_out[1](hidden_states)
150 return hidden_states
151
152class diffusers_CrossAttention(nn.Module):
153 def __init__(self, query_dim, cross_attention_dim=None, heads=8, dim_head=64, dropout=0.0, bias=False):
154 super().__init__()
155 inner_dim = dim_head * heads
156 cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
157
158 self.scale = dim_head ** -0.5
159 self.heads = heads
160
161 self.to_q = nn.Linear(query_dim, inner_dim, bias=bias)
162 self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=bias)
163 self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=bias)
164
165 self.to_out = nn.ModuleList([])
166 self.to_out.append(nn.Linear(inner_dim, query_dim))
167 self.to_out.append(nn.Dropout(dropout))
168
169 if version.parse(torch.__version__) >= version.parse('2.0'):
170 self.processor = diffusers_AttnProcessor2_0()
171 else:
172 self.processor = diffusers_CrossAttnProcessor()
173
174 def forward(self, hidden_states, encoder_hidden_states=None):
175 return self.processor(self, hidden_states, encoder_hidden_states=encoder_hidden_states)
176
177 def batch_to_head_dim(self, tensor):
178 head_size = self.heads
179 batch_size, seq_len, dim = tensor.shape
180 tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
181 tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
182 return tensor
183
184 def head_to_batch_dim(self, tensor):
185 head_size = self.heads
186 batch_size, seq_len, dim = tensor.shape
187 tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
188 tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size * head_size, seq_len, dim // head_size)
189 return tensor
190
191 def get_attention_scores(self, query, key):
192 dtype = query.dtype
193
194 baddbmm_input = torch.empty(
195 query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
196 )
197 beta = 0
198
199 attention_scores = torch.baddbmm(
200 baddbmm_input,
201 query,
202 key.transpose(-1, -2),
203 beta=beta,
204 alpha=self.scale,
205 )
206
207 attention_probs = attention_scores.softmax(dim=-1)
208 attention_probs = attention_probs.to(dtype)
209
210 return attention_probs
211
212class vit_pytorch_Attention(nn.Module):
213 def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.):
214 super().__init__()
215 inner_dim = dim_head * heads
216 project_out = not (heads == 1 and dim_head == dim)
217
218 self.heads = heads
219 self.scale = dim_head ** -0.5
220
221 self.attend = nn.Softmax(dim = -1)
222 self.dropout = nn.Dropout(dropout)
223
224 self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False)
225
226 self.to_out = nn.Sequential(
227 nn.Linear(inner_dim, dim),
228 nn.Dropout(dropout)
229 ) if project_out else nn.Identity()
230
231 def forward(self, x):
232 qkv = self.to_qkv(x).chunk(3, dim = -1)
233 q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h = self.heads), qkv)
234
235 dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale
236
237 attn = self.attend(dots)
238 attn = self.dropout(attn)
239
240 out = torch.matmul(attn, v)
241 out = rearrange(out, 'b h n d -> b n (h d)')
242 return self.to_out(out)
243
244class CLIPAttention(nn.Module):
245 """Multi-headed attention from 'Attention Is All You Need' paper"""
246
247 def __init__(self, embed_dim, num_heads):
248 super().__init__()
249 self.embed_dim = embed_dim
250 self.num_heads = num_heads
251 self.head_dim = self.embed_dim // self.num_heads
252 if self.head_dim * self.num_heads != self.embed_dim:
253 raise ValueError(
254 f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
255 f" {self.num_heads})."
256 )
257 self.scale = self.head_dim**-0.5
258 self.dropout = 0.
259
260 self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
261 self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
262 self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
263 self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
264
265 def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
266 return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
267
268 def forward(
269 self,
270 hidden_states: torch.Tensor,
271 attention_mask: Optional[torch.Tensor] = None,
272 causal_attention_mask: Optional[torch.Tensor] = None,
273 output_attentions: Optional[bool] = False,
274 ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
275 """Input shape: Batch x Time x Channel"""
276
277 bsz, tgt_len, embed_dim = hidden_states.size()
278
279 # get query proj
280 query_states = self.q_proj(hidden_states) * self.scale
281 key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
282 value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
283
284 proj_shape = (bsz * self.num_heads, -1, self.head_dim)
285 query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
286 key_states = key_states.view(*proj_shape)
287 value_states = value_states.view(*proj_shape)
288
289 src_len = key_states.size(1)
290 attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
291
292 if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
293 raise ValueError(
294 f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
295 f" {attn_weights.size()}"
296 )
297
298 # apply the causal_attention_mask first
299 if causal_attention_mask is not None:
300 if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
301 raise ValueError(
302 f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
303 f" {causal_attention_mask.size()}"
304 )
305 attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
306 attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
307
308 if attention_mask is not None:
309 if attention_mask.size() != (bsz, 1, tgt_len, src_len):
310 raise ValueError(
311 f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
312 )
313 attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
314 attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
315
316 attn_weights = nn.functional.softmax(attn_weights, dim=-1)
317
318 attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
319
320 attn_output = torch.bmm(attn_probs, value_states)
321
322 if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
323 raise ValueError(
324 f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
325 f" {attn_output.size()}"
326 )
327
328 attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
329 attn_output = attn_output.transpose(1, 2)
330 attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
331
332 attn_output = self.out_proj(attn_output)
333
334 return attn_output
335
336class diffusers_AttentionBlock(nn.Module):
337 def __init__(
338 self,
339 channels: int,
340 num_head_channels: Optional[int] = None,
341 norm_num_groups: int = 32,
342 rescale_output_factor: float = 1.0,
343 eps: float = 1e-5,
344 ):
345 super().__init__()
346 self.channels = channels
347
348 self.num_heads = channels // num_head_channels if num_head_channels is not None else 1
349 self.group_norm = nn.GroupNorm(num_channels=channels, num_groups=norm_num_groups, eps=eps, affine=True)
350
351 # define q,k,v as linear layers
352 self.query = nn.Linear(channels, channels)
353 self.key = nn.Linear(channels, channels)
354 self.value = nn.Linear(channels, channels)
355
356 self.rescale_output_factor = rescale_output_factor
357 self.proj_attn = nn.Linear(channels, channels, bias=True)
358
359 def reshape_heads_to_batch_dim(self, tensor, merge_head_and_batch=True):
360 batch_size, seq_len, dim = tensor.shape
361 head_size = self.num_heads
362 tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
363 tensor = tensor.permute(0, 2, 1, 3)
364 if merge_head_and_batch:
365 tensor = tensor.reshape(batch_size * head_size, seq_len, dim // head_size)
366 return tensor
367
368 def reshape_batch_dim_to_heads(self, tensor, unmerge_head_and_batch=True):
369 head_size = self.num_heads
370
371 if unmerge_head_and_batch:
372 batch_head_size, seq_len, dim = tensor.shape
373 batch_size = batch_head_size // head_size
374
375 tensor = tensor.reshape(batch_size, head_size, seq_len, dim)
376 else:
377 batch_size, _, seq_len, dim = tensor.shape
378
379 tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size, seq_len, dim * head_size)
380 return tensor
381
382 def forward(self, hidden_states):
383 residual = hidden_states
384 batch, channel, height, width = hidden_states.shape
385
386 # norm
387 hidden_states = self.group_norm(hidden_states)
388
389 hidden_states = hidden_states.view(batch, channel, height * width).transpose(1, 2)
390
391 # proj to q, k, v
392 query_proj = self.query(hidden_states)
393 key_proj = self.key(hidden_states)
394 value_proj = self.value(hidden_states)
395
396 scale = 1 / math.sqrt(self.channels / self.num_heads)
397
398 use_torch_2_0_attn = hasattr(F, "scaled_dot_product_attention")
399
400 query_proj = self.reshape_heads_to_batch_dim(query_proj, merge_head_and_batch=not use_torch_2_0_attn)
401 key_proj = self.reshape_heads_to_batch_dim(key_proj, merge_head_and_batch=not use_torch_2_0_attn)
402 value_proj = self.reshape_heads_to_batch_dim(value_proj, merge_head_and_batch=not use_torch_2_0_attn)
403
404 if use_torch_2_0_attn:
405 # the output of sdp = (batch, num_heads, seq_len, head_dim)
406 # TODO: add support for attn.scale when we move to Torch 2.1
407 hidden_states = F.scaled_dot_product_attention(
408 query_proj, key_proj, value_proj, dropout_p=0.0, is_causal=False
409 )
410 hidden_states = hidden_states.to(query_proj.dtype)
411 else:
412 attention_scores = torch.baddbmm(
413 torch.empty(
414 query_proj.shape[0],
415 query_proj.shape[1],
416 key_proj.shape[1],
417 dtype=query_proj.dtype,
418 device=query_proj.device,
419 ),
420 query_proj,
421 key_proj.transpose(-1, -2),
422 beta=0,
423 alpha=scale,
424 )
425 attention_probs = torch.softmax(attention_scores.float(), dim=-1).type(attention_scores.dtype)
426 hidden_states = torch.bmm(attention_probs, value_proj)
427
428 # reshape hidden_states
429 hidden_states = self.reshape_batch_dim_to_heads(hidden_states, unmerge_head_and_batch=not use_torch_2_0_attn)
430
431 # compute next hidden_states
432 hidden_states = self.proj_attn(hidden_states)
433
434 hidden_states = hidden_states.transpose(-1, -2).reshape(batch, channel, height, width)
435
436 # res connect and rescale
437 hidden_states = (hidden_states + residual) / self.rescale_output_factor
438 return hidden_states
439
440class Model(nn.Module):
441 def __init__(self):
442 super(Model, self).__init__()
443
444 self.attention_0_0 = Attention(embed_dim=64, num_heads=4)
445 self.attention_0_1 = Attention(embed_dim=64, num_heads=8, qkv_bias=False)
446
447 self.attention_1_0 = CrossAttention(query_dim=64, heads=4, dim_head=16)
448 self.attention_1_1 = CrossAttention(query_dim=64, heads=8, dim_head=8, context_dim=17)
449
450 self.attention_2_0 = diffusers_CrossAttention(query_dim=64, heads=4, dim_head=16)
451 self.attention_2_1 = diffusers_CrossAttention(query_dim=64, heads=8, dim_head=8, cross_attention_dim=17)
452
453 self.attention_3 = vit_pytorch_Attention(dim=64, heads=4, dim_head=16)
454
455 self.attention_4_0 = CLIPAttention(embed_dim=64, num_heads=4)
456 self.attention_4_1 = CLIPAttention(embed_dim=64, num_heads=4)
457 self.mask = nn.Parameter(torch.rand(1, 1, 20, 20))
458
459 self.attention_5 = diffusers_AttentionBlock(channels=64, num_head_channels=16)
460
461 def forward(self, x, y, z):
462 a = self.attention_0_0(x)
463 a = self.attention_0_1(a)
464
465 b = self.attention_1_0(x)
466 b = self.attention_1_1(b, y)
467
468 c = self.attention_2_0(x)
469 c = self.attention_2_1(c, y)
470
471 d = self.attention_3(x)
472
473 e = self.attention_4_0(x)
474 f = self.attention_4_1(x, causal_attention_mask=self.mask)
475
476 g = self.attention_5(z)
477
478 return a, b, c, d, e, f, g
479
480def test():
481 if version.parse(torch.__version__) < version.parse('1.9'):
482 return True
483
484 net = Model()
485 net.eval()
486
487 torch.manual_seed(0)
488 x = torch.rand(1, 20, 64)
489 y = torch.rand(1, 20, 17)
490 z = torch.rand(1, 64, 6, 6)
491
492 a = net(x, y, z)
493
494 # export torchscript
495 mod = torch.jit.trace(net, (x, y, z))
496 mod.save("test_pnnx_fuse_multiheadattention.pt")
497
498 # torchscript to pnnx
499 import os
500 os.system("../src/pnnx test_pnnx_fuse_multiheadattention.pt inputshape=[1,20,64],[1,20,17],[1,64,6,6]")
501
502 # pnnx inference
503 import test_pnnx_fuse_multiheadattention_pnnx
504 b = test_pnnx_fuse_multiheadattention_pnnx.test_inference()
505
506 for a0, b0 in zip(a, b):
507 if not torch.allclose(a0, b0, 1e-4, 1e-4):
508 return False
509 return True
510
511if __name__ == "__main__":
512 if test():
513 exit(0)
514 else:
515 exit(1)