qianyuchen commited on
Commit
f706ef4
·
verified ·
1 Parent(s): 45387f9

Create resampler.py

Browse files

resampler.py的attn模块不适应zero3训练,在以往的finetuning脚本里只能强制性的聚拢参数,但当使用lora时这些变量名会修改,这里修改了attn模块的实现方式,主要将multihead attention的实现改成了使用直接召唤模型

Files changed (1) hide show
  1. resampler.py +739 -68
resampler.py CHANGED
@@ -1,27 +1,76 @@
 
 
 
 
 
 
 
 
 
1
  from functools import partial
 
 
2
  import numpy as np
3
 
4
  import torch
5
  from torch import nn
 
6
  from torch.nn.init import trunc_normal_
 
 
7
 
8
- def get_2d_sincos_pos_embed(embed_dim, image_size):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  """
10
- image_size: image_size or (image_height, image_width)
11
  return:
12
- pos_embed: [image_height, image_width, embed_dim]
13
  """
14
- if isinstance(image_size, int):
15
- grid_h_size, grid_w_size = image_size, image_size
16
  else:
17
- grid_h_size, grid_w_size = image_size[0], image_size[1]
18
 
19
  grid_h = np.arange(grid_h_size, dtype=np.float32)
20
  grid_w = np.arange(grid_w_size, dtype=np.float32)
21
  grid = np.meshgrid(grid_w, grid_h) # here w goes first
22
  grid = np.stack(grid, axis=0)
23
 
 
24
  pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
 
 
25
  return pos_embed
26
 
27
 
@@ -29,57 +78,60 @@ def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
29
  assert embed_dim % 2 == 0
30
 
31
  # use half of dimensions to encode grid_h
32
- emb_h = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[0]) # (H, W, D/2)
33
- emb_w = get_1d_sincos_pos_embed_from_grid_new(embed_dim // 2, grid[1]) # (H, W, D/2)
34
 
35
- emb = np.concatenate([emb_h, emb_w], axis=-1) # (H, W, D)
36
  return emb
37
 
38
 
39
- def get_1d_sincos_pos_embed_from_grid_new(embed_dim, pos):
40
  """
41
  embed_dim: output dimension for each position
42
- pos: a list of positions to be encoded: size (H, W)
43
- out: (H, W, D)
44
  """
45
  assert embed_dim % 2 == 0
46
  omega = np.arange(embed_dim // 2, dtype=np.float32)
47
  omega /= embed_dim / 2.
48
  omega = 1. / 10000 ** omega # (D/2,)
49
 
50
- out = np.einsum('hw,d->hwd', pos, omega) # (H, W, D/2), outer product
 
51
 
52
- emb_sin = np.sin(out) # (H, W, D/2)
53
- emb_cos = np.cos(out) # (H, W, D/2)
54
 
55
- emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (H, W, D)
56
  return emb
57
 
58
 
59
  class Resampler(nn.Module):
60
  """
61
  A 2D perceiver-resampler network with one cross attention layers by
62
- given learnable queries and 2d sincos pos_emb
63
  Outputs:
64
- A tensor with the shape of (batch_size, num_queries, embed_dim)
65
  """
66
 
67
  def __init__(
68
  self,
69
- num_queries,
70
  embed_dim,
71
  num_heads,
72
  kv_dim=None,
73
  norm_layer=partial(nn.LayerNorm, eps=1e-6),
74
- adaptive=False,
75
- max_size=(70, 70),
76
  ):
77
  super().__init__()
78
- self.num_queries = num_queries
79
  self.embed_dim = embed_dim
80
  self.num_heads = num_heads
81
  self.adaptive = adaptive
82
- self.max_size = max_size
 
 
 
83
 
84
  self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
85
  trunc_normal_(self.query, std=.02)
@@ -89,27 +141,15 @@ class Resampler(nn.Module):
89
  else:
90
  self.kv_proj = nn.Identity()
91
 
92
- self.attn = nn.MultiheadAttention(embed_dim, num_heads)
93
  self.ln_q = norm_layer(embed_dim)
94
  self.ln_kv = norm_layer(embed_dim)
95
 
96
  self.ln_post = norm_layer(embed_dim)
97
  self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
98
 
99
- self._set_2d_pos_cache(self.max_size)
100
  self.apply(self._init_weights)
101
 
102
- def _set_2d_pos_cache(self, max_size, device='cpu'):
103
- pos_embed = torch.from_numpy(get_2d_sincos_pos_embed(self.embed_dim, max_size)).float().to(device)
104
- self.register_buffer("pos_embed", pos_embed, persistent=False)
105
-
106
- def _adjust_pos_cache(self, tgt_sizes, device):
107
- max_h = torch.max(tgt_sizes[:, 0])
108
- max_w = torch.max(tgt_sizes[:, 1])
109
- if max_h > self.max_size[0] or max_w > self.max_size[1]:
110
- self.max_size = [max(max_h, self.max_size[0]), max(max_w, self.max_size[1])]
111
- self._set_2d_pos_cache(self.max_size, device)
112
-
113
  def _init_weights(self, m):
114
  if isinstance(m, nn.Linear):
115
  trunc_normal_(m.weight, std=.02)
@@ -119,45 +159,676 @@ class Resampler(nn.Module):
119
  nn.init.constant_(m.bias, 0)
120
  nn.init.constant_(m.weight, 1.0)
121
 
122
- def forward(self, x, tgt_sizes=None):
123
- assert x.shape[0] == tgt_sizes.shape[0]
124
- bs = x.shape[0]
125
-
126
- device = x.device
127
- dtype = x.dtype
128
-
129
- patch_len = tgt_sizes[:, 0] * tgt_sizes[:, 1]
130
-
131
- self._adjust_pos_cache(tgt_sizes, device=device)
132
-
133
- max_patch_len = torch.max(patch_len)
134
- key_padding_mask = torch.zeros((bs, max_patch_len), dtype=torch.bool, device=device)
135
-
136
- pos_embed = []
137
- for i in range(bs):
138
- tgt_h, tgt_w = tgt_sizes[i]
139
- pos_embed.append(self.pos_embed[:tgt_h, :tgt_w, :].reshape((tgt_h * tgt_w, -1)).to(dtype)) # patches * D
140
- key_padding_mask[i, patch_len[i]:] = True
141
-
142
- pos_embed = torch.nn.utils.rnn.pad_sequence(
143
- pos_embed, batch_first=True, padding_value=0.0).permute(1, 0, 2) # BLD => L * B * D
144
-
145
- x = self.kv_proj(x) # B * L * D
146
- x = self.ln_kv(x).permute(1, 0, 2) # L * B * D
147
 
148
- q = self.ln_q(self.query) # Q * D
 
149
 
 
 
150
  out = self.attn(
151
- self._repeat(q, bs), # Q * B * D
152
- x + pos_embed, # L * B * D + L * B * D
153
  x,
154
- key_padding_mask=key_padding_mask)[0]
155
- # out: Q * B * D
156
- x = out.permute(1, 0, 2) # B * Q * D
157
 
158
  x = self.ln_post(x)
159
  x = x @ self.proj
160
  return x
161
 
162
  def _repeat(self, query, N: int):
163
- return query.unsqueeze(1).repeat(1, N, 1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Alibaba Cloud.
2
+ #
3
+ # This source code is licensed under the license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ from collections import OrderedDict
7
+ import math
8
+ import requests
9
+ from io import BytesIO
10
  from functools import partial
11
+ from PIL import Image
12
+ from typing import Callable, Optional, Sequence, Tuple, List, Union
13
  import numpy as np
14
 
15
  import torch
16
  from torch import nn
17
+ from torch.nn import functional as F
18
  from torch.nn.init import trunc_normal_
19
+ from torchvision import transforms
20
+ from torchvision.transforms import InterpolationMode
21
 
22
+ from functools import partial
23
+ import numpy as np
24
+ import warnings
25
+ from typing import Optional, Tuple
26
+ import torch
27
+ from torch import nn
28
+ from torch import Tensor
29
+ import deepspeed
30
+ import torch.nn.functional as F
31
+ from torch.nn.functional import *
32
+ from torch.nn.modules.activation import *
33
+ from torch.nn.init import trunc_normal_
34
+ from torch.nn.init import constant_, xavier_normal_, xavier_uniform_
35
+ from transformers import PreTrainedModel
36
+ from transformers.integrations import is_deepspeed_zero3_enabled
37
+ def get_abs_pos(abs_pos, tgt_size):
38
+ # abs_pos: L, C
39
+ # tgt_size: (H, W)
40
+ # return: M, C
41
+ src_size = int(math.sqrt(abs_pos.size(0)))
42
+ # tgt_size = int(math.sqrt(tgt_size))
43
+ dtype = abs_pos.dtype
44
+
45
+ return F.interpolate(
46
+ abs_pos.float().reshape(1, src_size, src_size, -1).permute(0, 3, 1, 2),
47
+ size=(tgt_size[0], tgt_size[1]),
48
+ mode="bicubic",
49
+ align_corners=False,
50
+ ).permute(0, 2, 3, 1).flatten(0, 2).to(dtype=dtype)
51
+
52
+
53
+ # https://github.com/facebookresearch/mae/blob/efb2a8062c206524e35e47d04501ed4f544c0ae8/util/pos_embed.py#L20
54
+ def get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False):
55
  """
56
+ grid_size: int of the grid height and width
57
  return:
58
+ pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
59
  """
60
+ if isinstance(grid_size, int):
61
+ grid_h_size, grid_w_size = grid_size, grid_size
62
  else:
63
+ grid_h_size, grid_w_size = grid_size[0], grid_size[1]
64
 
65
  grid_h = np.arange(grid_h_size, dtype=np.float32)
66
  grid_w = np.arange(grid_w_size, dtype=np.float32)
67
  grid = np.meshgrid(grid_w, grid_h) # here w goes first
68
  grid = np.stack(grid, axis=0)
69
 
70
+ grid = grid.reshape([2, 1, grid_h_size, grid_w_size])
71
  pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
72
+ if cls_token:
73
+ pos_embed = np.concatenate([np.zeros([1, embed_dim]), pos_embed], axis=0)
74
  return pos_embed
75
 
76
 
 
78
  assert embed_dim % 2 == 0
79
 
80
  # use half of dimensions to encode grid_h
81
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
82
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
83
 
84
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
85
  return emb
86
 
87
 
88
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
89
  """
90
  embed_dim: output dimension for each position
91
+ pos: a list of positions to be encoded: size (M,)
92
+ out: (M, D)
93
  """
94
  assert embed_dim % 2 == 0
95
  omega = np.arange(embed_dim // 2, dtype=np.float32)
96
  omega /= embed_dim / 2.
97
  omega = 1. / 10000 ** omega # (D/2,)
98
 
99
+ pos = pos.reshape(-1) # (M,)
100
+ out = np.einsum('m,d->md', pos, omega) # (M, D/2), outer product
101
 
102
+ emb_sin = np.sin(out) # (M, D/2)
103
+ emb_cos = np.cos(out) # (M, D/2)
104
 
105
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
106
  return emb
107
 
108
 
109
  class Resampler(nn.Module):
110
  """
111
  A 2D perceiver-resampler network with one cross attention layers by
112
+ (grid_size**2) learnable queries and 2d sincos pos_emb
113
  Outputs:
114
+ A tensor with the shape of (grid_size**2, embed_dim)
115
  """
116
 
117
  def __init__(
118
  self,
119
+ grid_size,
120
  embed_dim,
121
  num_heads,
122
  kv_dim=None,
123
  norm_layer=partial(nn.LayerNorm, eps=1e-6),
124
+ adaptive=False
 
125
  ):
126
  super().__init__()
127
+ self.num_queries = grid_size ** 2
128
  self.embed_dim = embed_dim
129
  self.num_heads = num_heads
130
  self.adaptive = adaptive
131
+
132
+ self.pos_embed = nn.Parameter(
133
+ torch.from_numpy(get_2d_sincos_pos_embed(embed_dim, grid_size)).float()
134
+ ).requires_grad_(False)
135
 
136
  self.query = nn.Parameter(torch.zeros(self.num_queries, embed_dim))
137
  trunc_normal_(self.query, std=.02)
 
141
  else:
142
  self.kv_proj = nn.Identity()
143
 
144
+ self.attn = MultiheadAttention(embed_dim, num_heads)
145
  self.ln_q = norm_layer(embed_dim)
146
  self.ln_kv = norm_layer(embed_dim)
147
 
148
  self.ln_post = norm_layer(embed_dim)
149
  self.proj = nn.Parameter((embed_dim ** -0.5) * torch.randn(embed_dim, embed_dim))
150
 
 
151
  self.apply(self._init_weights)
152
 
 
 
 
 
 
 
 
 
 
 
 
153
  def _init_weights(self, m):
154
  if isinstance(m, nn.Linear):
155
  trunc_normal_(m.weight, std=.02)
 
159
  nn.init.constant_(m.bias, 0)
160
  nn.init.constant_(m.weight, 1.0)
161
 
162
+ def forward(self, x, tgt_size=None, attn_mask=None):
163
+ if self.adaptive:
164
+ pos_embed = torch.Tensor(get_2d_sincos_pos_embed(self.embed_dim, tgt_size)).float().to(device=x.device, dtype=x.dtype)
165
+ else:
166
+ pos_embed = get_abs_pos(self.pos_embed, tgt_size)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
 
168
+ x = self.kv_proj(x)
169
+ x = self.ln_kv(x).permute(1, 0, 2)
170
 
171
+ N = x.shape[1]
172
+ q = self.ln_q(self.query)
173
  out = self.attn(
174
+ self._repeat(q, N) + self.pos_embed.unsqueeze(1),
175
+ x + pos_embed.unsqueeze(1),
176
  x,
177
+ attn_mask=attn_mask)[0]
178
+ x = out.permute(1, 0, 2)
 
179
 
180
  x = self.ln_post(x)
181
  x = x @ self.proj
182
  return x
183
 
184
  def _repeat(self, query, N: int):
185
+ return query.unsqueeze(1).repeat(1, N, 1)
186
+
187
+
188
+
189
+ class MultiheadAttention(nn.MultiheadAttention):
190
+ def __init__(self, embed_dim, num_heads, dropout=0., bias=True, add_bias_kv=False,
191
+ add_zero_attn=False, kdim=None, vdim=None, batch_first=False, device=None, dtype=None):
192
+ super().__init__(embed_dim, num_heads, dropout, bias, add_bias_kv, add_zero_attn, kdim, vdim, batch_first, device, dtype)
193
+
194
+ # rewrite out_proj layer,with nn.Linear
195
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, device=device, dtype=dtype)
196
+
197
+ def forward(
198
+ self,
199
+ query: Tensor,
200
+ key: Tensor,
201
+ value: Tensor,
202
+ key_padding_mask: Optional[Tensor] = None,
203
+ need_weights: bool = True,
204
+ attn_mask: Optional[Tensor] = None,
205
+ average_attn_weights: bool = True,
206
+ is_causal : bool = False) -> Tuple[Tensor, Optional[Tensor]]:
207
+ why_not_fast_path = ''
208
+ if ((attn_mask is not None and torch.is_floating_point(attn_mask))
209
+ or (key_padding_mask is not None) and torch.is_floating_point(key_padding_mask)):
210
+ why_not_fast_path = "floating-point masks are not supported for fast path."
211
+
212
+ is_batched = query.dim() == 3
213
+
214
+ key_padding_mask = F._canonical_mask(
215
+ mask=key_padding_mask,
216
+ mask_name="key_padding_mask",
217
+ other_type=F._none_or_dtype(attn_mask),
218
+ other_name="attn_mask",
219
+ target_type=query.dtype
220
+ )
221
+
222
+ attn_mask = F._canonical_mask(
223
+ mask=attn_mask,
224
+ mask_name="attn_mask",
225
+ other_type=None,
226
+ other_name="",
227
+ target_type=query.dtype,
228
+ check_other=False,
229
+ )
230
+
231
+
232
+ if not is_batched:
233
+ why_not_fast_path = f"input not batched; expected query.dim() of 3 but got {query.dim()}"
234
+ elif query is not key or key is not value:
235
+ # When lifting this restriction, don't forget to either
236
+ # enforce that the dtypes all match or test cases where
237
+ # they don't!
238
+ why_not_fast_path = "non-self attention was used (query, key, and value are not the same Tensor)"
239
+ elif self.in_proj_bias is not None and query.dtype != self.in_proj_bias.dtype:
240
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_bias ({self.in_proj_bias.dtype}) don't match"
241
+ elif self.in_proj_weight is None:
242
+ why_not_fast_path = "in_proj_weight was None"
243
+ elif query.dtype != self.in_proj_weight.dtype:
244
+ # this case will fail anyway, but at least they'll get a useful error message.
245
+ why_not_fast_path = f"dtypes of query ({query.dtype}) and self.in_proj_weight ({self.in_proj_weight.dtype}) don't match"
246
+ elif self.training:
247
+ why_not_fast_path = "training is enabled"
248
+ elif (self.num_heads % 2) != 0:
249
+ why_not_fast_path = "self.num_heads is not even"
250
+ elif not self.batch_first:
251
+ why_not_fast_path = "batch_first was not True"
252
+ elif self.bias_k is not None:
253
+ why_not_fast_path = "self.bias_k was not None"
254
+ elif self.bias_v is not None:
255
+ why_not_fast_path = "self.bias_v was not None"
256
+ elif self.add_zero_attn:
257
+ why_not_fast_path = "add_zero_attn was enabled"
258
+ elif not self._qkv_same_embed_dim:
259
+ why_not_fast_path = "_qkv_same_embed_dim was not True"
260
+ elif query.is_nested and (key_padding_mask is not None or attn_mask is not None):
261
+ why_not_fast_path = "supplying both src_key_padding_mask and src_mask at the same time \
262
+ is not supported with NestedTensor input"
263
+ elif torch.is_autocast_enabled():
264
+ why_not_fast_path = "autocast is enabled"
265
+
266
+ if not why_not_fast_path:
267
+ tensor_args = (
268
+ query,
269
+ key,
270
+ value,
271
+ self.in_proj_weight,
272
+ self.in_proj_bias,
273
+ self.out_proj.weight,
274
+ self.out_proj.bias,
275
+ )
276
+ # We have to use list comprehensions below because TorchScript does not support
277
+ # generator expressions.
278
+ if torch.overrides.has_torch_function(tensor_args):
279
+ why_not_fast_path = "some Tensor argument has_torch_function"
280
+ elif _is_make_fx_tracing():
281
+ why_not_fast_path = "we are running make_fx tracing"
282
+ elif not all(_check_arg_device(x) for x in tensor_args):
283
+ why_not_fast_path = ("some Tensor argument's device is neither one of "
284
+ f"cpu, cuda or {torch.utils.backend_registration._privateuse1_backend_name}")
285
+ elif torch.is_grad_enabled() and any(_arg_requires_grad(x) for x in tensor_args):
286
+ why_not_fast_path = ("grad is enabled and at least one of query or the "
287
+ "input/output projection weights or biases requires_grad")
288
+ if not why_not_fast_path:
289
+ merged_mask, mask_type = self.merge_masks(attn_mask, key_padding_mask, query)
290
+
291
+ if self.in_proj_bias is not None and self.in_proj_weight is not None:
292
+ return torch._native_multi_head_attention(
293
+ query,
294
+ key,
295
+ value,
296
+ self.embed_dim,
297
+ self.num_heads,
298
+ self.in_proj_weight,
299
+ self.in_proj_bias,
300
+ self.out_proj.weight,
301
+ self.out_proj.bias,
302
+ merged_mask,
303
+ need_weights,
304
+ average_attn_weights,
305
+ mask_type)
306
+
307
+ any_nested = query.is_nested or key.is_nested or value.is_nested
308
+ assert not any_nested, ("MultiheadAttention does not support NestedTensor outside of its fast path. " +
309
+ f"The fast path was not hit because {why_not_fast_path}")
310
+
311
+ if self.batch_first and is_batched:
312
+ # make sure that the transpose op does not affect the "is" property
313
+ if key is value:
314
+ if query is key:
315
+ query = key = value = query.transpose(1, 0)
316
+ else:
317
+ query, key = (x.transpose(1, 0) for x in (query, key))
318
+ value = key
319
+ else:
320
+ query, key, value = (x.transpose(1, 0) for x in (query, key, value))
321
+
322
+ if not self._qkv_same_embed_dim:
323
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
324
+ query, key, value, self.embed_dim, self.num_heads,
325
+ self.in_proj_weight, self.in_proj_bias,
326
+ self.bias_k, self.bias_v, self.add_zero_attn,
327
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
328
+ training=self.training,
329
+ key_padding_mask=key_padding_mask, need_weights=need_weights,
330
+ attn_mask=attn_mask,
331
+ use_separate_proj_weight=True,
332
+ q_proj_weight=self.q_proj_weight, k_proj_weight=self.k_proj_weight,
333
+ v_proj_weight=self.v_proj_weight,
334
+ average_attn_weights=average_attn_weights,
335
+ is_causal=is_causal)
336
+ else:
337
+ attn_output, attn_output_weights = self.multi_head_attention_forward(
338
+ query, key, value, self.embed_dim, self.num_heads,
339
+ self.in_proj_weight, self.in_proj_bias,
340
+ self.bias_k, self.bias_v, self.add_zero_attn,
341
+ self.dropout, self.out_proj.weight, self.out_proj.bias,
342
+ training=self.training,
343
+ key_padding_mask=key_padding_mask,
344
+ need_weights=need_weights,
345
+ attn_mask=attn_mask,
346
+ average_attn_weights=average_attn_weights,
347
+ is_causal=is_causal)
348
+ if self.batch_first and is_batched:
349
+ return attn_output.transpose(1, 0), attn_output_weights
350
+ else:
351
+ return attn_output, attn_output_weights
352
+
353
+ def multi_head_attention_forward(
354
+ self,
355
+ query: Tensor,
356
+ key: Tensor,
357
+ value: Tensor,
358
+ embed_dim_to_check: int,
359
+ num_heads: int,
360
+ in_proj_weight: Optional[Tensor],
361
+ in_proj_bias: Optional[Tensor],
362
+ bias_k: Optional[Tensor],
363
+ bias_v: Optional[Tensor],
364
+ add_zero_attn: bool,
365
+ dropout_p: float,
366
+ out_proj_weight: Tensor,
367
+ out_proj_bias: Optional[Tensor],
368
+ training: bool = True,
369
+ key_padding_mask: Optional[Tensor] = None,
370
+ need_weights: bool = True,
371
+ attn_mask: Optional[Tensor] = None,
372
+ use_separate_proj_weight: bool = False,
373
+ q_proj_weight: Optional[Tensor] = None,
374
+ k_proj_weight: Optional[Tensor] = None,
375
+ v_proj_weight: Optional[Tensor] = None,
376
+ static_k: Optional[Tensor] = None,
377
+ static_v: Optional[Tensor] = None,
378
+ average_attn_weights: bool = True,
379
+ is_causal: bool = False,
380
+ ) -> Tuple[Tensor, Optional[Tensor]]:
381
+ tens_ops = (query, key, value, in_proj_weight, in_proj_bias, bias_k, bias_v, out_proj_weight, out_proj_bias)
382
+ if has_torch_function(tens_ops):
383
+ return handle_torch_function(
384
+ multi_head_attention_forward,
385
+ tens_ops,
386
+ query,
387
+ key,
388
+ value,
389
+ embed_dim_to_check,
390
+ num_heads,
391
+ in_proj_weight,
392
+ in_proj_bias,
393
+ bias_k,
394
+ bias_v,
395
+ add_zero_attn,
396
+ dropout_p,
397
+ out_proj_weight,
398
+ out_proj_bias,
399
+ training=training,
400
+ key_padding_mask=key_padding_mask,
401
+ need_weights=need_weights,
402
+ attn_mask=attn_mask,
403
+ is_causal=is_causal,
404
+ use_separate_proj_weight=use_separate_proj_weight,
405
+ q_proj_weight=q_proj_weight,
406
+ k_proj_weight=k_proj_weight,
407
+ v_proj_weight=v_proj_weight,
408
+ static_k=static_k,
409
+ static_v=static_v,
410
+ average_attn_weights=average_attn_weights,
411
+ )
412
+
413
+ is_batched = _mha_shape_check(query, key, value, key_padding_mask, attn_mask, num_heads)
414
+
415
+ # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
416
+ # is batched, run the computation and before returning squeeze the
417
+ # batch dimension so that the output doesn't carry this temporary batch dimension.
418
+ if not is_batched:
419
+ # unsqueeze if the input is unbatched
420
+ query = query.unsqueeze(1)
421
+ key = key.unsqueeze(1)
422
+ value = value.unsqueeze(1)
423
+ if key_padding_mask is not None:
424
+ key_padding_mask = key_padding_mask.unsqueeze(0)
425
+
426
+ # set up shape vars
427
+ tgt_len, bsz, embed_dim = query.shape
428
+ src_len, _, _ = key.shape
429
+
430
+ key_padding_mask = _canonical_mask(
431
+ mask=key_padding_mask,
432
+ mask_name="key_padding_mask",
433
+ other_type=_none_or_dtype(attn_mask),
434
+ other_name="attn_mask",
435
+ target_type=query.dtype
436
+ )
437
+
438
+ if is_causal and attn_mask is None:
439
+ raise RuntimeError(
440
+ "Need attn_mask if specifying the is_causal hint. "
441
+ "You may use the Transformer module method "
442
+ "`generate_square_subsequent_mask` to create this mask."
443
+ )
444
+
445
+ if is_causal and key_padding_mask is None and not need_weights:
446
+ # when we have a kpm or need weights, we need attn_mask
447
+ # Otherwise, we use the is_causal hint go as is_causal
448
+ # indicator to SDPA.
449
+ attn_mask = None
450
+ else:
451
+ attn_mask = _canonical_mask(
452
+ mask=attn_mask,
453
+ mask_name="attn_mask",
454
+ other_type=None,
455
+ other_name="",
456
+ target_type=query.dtype,
457
+ check_other=False,
458
+ )
459
+
460
+ if key_padding_mask is not None:
461
+ # We have the attn_mask, and use that to merge kpm into it.
462
+ # Turn off use of is_causal hint, as the merged mask is no
463
+ # longer causal.
464
+ is_causal = False
465
+
466
+ assert embed_dim == embed_dim_to_check, \
467
+ f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
468
+ if isinstance(embed_dim, torch.Tensor):
469
+ # embed_dim can be a tensor when JIT tracing
470
+ head_dim = embed_dim.div(num_heads, rounding_mode='trunc')
471
+ else:
472
+ head_dim = embed_dim // num_heads
473
+ assert head_dim * num_heads == embed_dim, f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
474
+ if use_separate_proj_weight:
475
+ # allow MHA to have different embedding dimensions when separate projection weights are used
476
+ assert key.shape[:2] == value.shape[:2], \
477
+ f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
478
+ else:
479
+ assert key.shape == value.shape, f"key shape {key.shape} does not match value shape {value.shape}"
480
+
481
+ #
482
+ # compute in-projection
483
+ #
484
+ if not use_separate_proj_weight:
485
+ assert in_proj_weight is not None, "use_separate_proj_weight is False but in_proj_weight is None"
486
+ q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
487
+ else:
488
+ assert q_proj_weight is not None, "use_separate_proj_weight is True but q_proj_weight is None"
489
+ assert k_proj_weight is not None, "use_separate_proj_weight is True but k_proj_weight is None"
490
+ assert v_proj_weight is not None, "use_separate_proj_weight is True but v_proj_weight is None"
491
+ if in_proj_bias is None:
492
+ b_q = b_k = b_v = None
493
+ else:
494
+ b_q, b_k, b_v = in_proj_bias.chunk(3)
495
+ q, k, v = _in_projection(query, key, value, q_proj_weight, k_proj_weight, v_proj_weight, b_q, b_k, b_v)
496
+
497
+ # prep attention mask
498
+
499
+ if attn_mask is not None:
500
+ # ensure attn_mask's dim is 3
501
+ if attn_mask.dim() == 2:
502
+ correct_2d_size = (tgt_len, src_len)
503
+ if attn_mask.shape != correct_2d_size:
504
+ raise RuntimeError(f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}.")
505
+ attn_mask = attn_mask.unsqueeze(0)
506
+ elif attn_mask.dim() == 3:
507
+ correct_3d_size = (bsz * num_heads, tgt_len, src_len)
508
+ if attn_mask.shape != correct_3d_size:
509
+ raise RuntimeError(f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}.")
510
+ else:
511
+ raise RuntimeError(f"attn_mask's dimension {attn_mask.dim()} is not supported")
512
+
513
+ # add bias along batch dimension (currently second)
514
+ if bias_k is not None and bias_v is not None:
515
+ assert static_k is None, "bias cannot be added to static key."
516
+ assert static_v is None, "bias cannot be added to static value."
517
+ k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
518
+ v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
519
+ if attn_mask is not None:
520
+ attn_mask = pad(attn_mask, (0, 1))
521
+ if key_padding_mask is not None:
522
+ key_padding_mask = pad(key_padding_mask, (0, 1))
523
+ else:
524
+ assert bias_k is None
525
+ assert bias_v is None
526
+
527
+ #
528
+ # reshape q, k, v for multihead attention and make em batch first
529
+ #
530
+ q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
531
+ if static_k is None:
532
+ k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
533
+ else:
534
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
535
+ assert static_k.size(0) == bsz * num_heads, \
536
+ f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
537
+ assert static_k.size(2) == head_dim, \
538
+ f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
539
+ k = static_k
540
+ if static_v is None:
541
+ v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
542
+ else:
543
+ # TODO finish disentangling control flow so we don't do in-projections when statics are passed
544
+ assert static_v.size(0) == bsz * num_heads, \
545
+ f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
546
+ assert static_v.size(2) == head_dim, \
547
+ f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
548
+ v = static_v
549
+
550
+ # add zero attention along batch dimension (now first)
551
+ if add_zero_attn:
552
+ zero_attn_shape = (bsz * num_heads, 1, head_dim)
553
+ k = torch.cat([k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)], dim=1)
554
+ v = torch.cat([v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)], dim=1)
555
+ if attn_mask is not None:
556
+ attn_mask = pad(attn_mask, (0, 1))
557
+ if key_padding_mask is not None:
558
+ key_padding_mask = pad(key_padding_mask, (0, 1))
559
+
560
+ # update source sequence length after adjustments
561
+ src_len = k.size(1)
562
+
563
+ # merge key padding and attention masks
564
+ if key_padding_mask is not None:
565
+ assert key_padding_mask.shape == (bsz, src_len), \
566
+ f"expecting key_padding_mask shape of {(bsz, src_len)}, but got {key_padding_mask.shape}"
567
+ key_padding_mask = key_padding_mask.view(bsz, 1, 1, src_len). \
568
+ expand(-1, num_heads, -1, -1).reshape(bsz * num_heads, 1, src_len)
569
+ if attn_mask is None:
570
+ attn_mask = key_padding_mask
571
+ else:
572
+ attn_mask = attn_mask + key_padding_mask
573
+
574
+ # adjust dropout probability
575
+ if not training:
576
+ dropout_p = 0.0
577
+
578
+ #
579
+ # (deep breath) calculate attention and out projection
580
+ #
581
+
582
+ if need_weights:
583
+ B, Nt, E = q.shape
584
+ q_scaled = q / math.sqrt(E)
585
+
586
+ assert not (is_causal and attn_mask is None), "FIXME: is_causal not implemented for need_weights"
587
+
588
+ if attn_mask is not None:
589
+ attn_output_weights = torch.baddbmm(attn_mask, q_scaled, k.transpose(-2, -1))
590
+ else:
591
+ attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
592
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
593
+ if dropout_p > 0.0:
594
+ attn_output_weights = dropout(attn_output_weights, p=dropout_p)
595
+
596
+ attn_output = torch.bmm(attn_output_weights, v)
597
+
598
+ attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
599
+ attn_output = self.out_proj(attn_output)
600
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
601
+
602
+ # optionally average attention weights over heads
603
+ attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
604
+ if average_attn_weights:
605
+ attn_output_weights = attn_output_weights.mean(dim=1)
606
+
607
+ if not is_batched:
608
+ # squeeze the output if input was unbatched
609
+ attn_output = attn_output.squeeze(1)
610
+ attn_output_weights = attn_output_weights.squeeze(0)
611
+ return attn_output, attn_output_weights
612
+ else:
613
+ # attn_mask can be either (L,S) or (N*num_heads, L, S)
614
+ # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
615
+ # in order to match the input for SDPA of (N, num_heads, L, S)
616
+ if attn_mask is not None:
617
+ if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
618
+ attn_mask = attn_mask.unsqueeze(0)
619
+ else:
620
+ attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
621
+
622
+ q = q.view(bsz, num_heads, tgt_len, head_dim)
623
+ k = k.view(bsz, num_heads, src_len, head_dim)
624
+ v = v.view(bsz, num_heads, src_len, head_dim)
625
+
626
+ attn_output = F.scaled_dot_product_attention(q, k, v, attn_mask, dropout_p, is_causal)
627
+ attn_output = attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
628
+
629
+ attn_output = self.out_proj(attn_output)
630
+ attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
631
+ if not is_batched:
632
+ # squeeze the output if input was unbatched
633
+ attn_output = attn_output.squeeze(1)
634
+ return attn_output, None
635
+
636
+
637
+ def _mha_shape_check(query: Tensor, key: Tensor, value: Tensor,
638
+ key_padding_mask: Optional[Tensor], attn_mask: Optional[Tensor], num_heads: int):
639
+ # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
640
+ # and returns if the input is batched or not.
641
+ # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
642
+
643
+ # Shape check.
644
+ if query.dim() == 3:
645
+ # Batched Inputs
646
+ is_batched = True
647
+ assert key.dim() == 3 and value.dim() == 3, \
648
+ ("For batched (3-D) `query`, expected `key` and `value` to be 3-D"
649
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
650
+ if key_padding_mask is not None:
651
+ assert key_padding_mask.dim() == 2, \
652
+ ("For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
653
+ f" but found {key_padding_mask.dim()}-D tensor instead")
654
+ if attn_mask is not None:
655
+ assert attn_mask.dim() in (2, 3), \
656
+ ("For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
657
+ f" but found {attn_mask.dim()}-D tensor instead")
658
+ elif query.dim() == 2:
659
+ # Unbatched Inputs
660
+ is_batched = False
661
+ assert key.dim() == 2 and value.dim() == 2, \
662
+ ("For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
663
+ f" but found {key.dim()}-D and {value.dim()}-D tensors respectively")
664
+
665
+ if key_padding_mask is not None:
666
+ assert key_padding_mask.dim() == 1, \
667
+ ("For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
668
+ f" but found {key_padding_mask.dim()}-D tensor instead")
669
+
670
+ if attn_mask is not None:
671
+ assert attn_mask.dim() in (2, 3), \
672
+ ("For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
673
+ f" but found {attn_mask.dim()}-D tensor instead")
674
+ if attn_mask.dim() == 3:
675
+ expected_shape = (num_heads, query.shape[0], key.shape[0])
676
+ assert attn_mask.shape == expected_shape, \
677
+ (f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}")
678
+ else:
679
+ raise AssertionError(
680
+ f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor")
681
+
682
+ return is_batched
683
+
684
+
685
+ def _canonical_mask(
686
+ mask: Optional[Tensor],
687
+ mask_name: str,
688
+ other_type: Optional[DType],
689
+ other_name: str,
690
+ target_type: DType,
691
+ check_other: bool = True,
692
+ ) -> Optional[Tensor]:
693
+
694
+ if mask is not None:
695
+ _mask_dtype = mask.dtype
696
+ _mask_is_float = torch.is_floating_point(mask)
697
+ if _mask_dtype != torch.bool and not _mask_is_float:
698
+ raise AssertionError(
699
+ f"only bool and floating types of {mask_name} are supported")
700
+ if check_other and other_type is not None:
701
+ if _mask_dtype != other_type:
702
+ warnings.warn(
703
+ f"Support for mismatched {mask_name} and {other_name} "
704
+ "is deprecated. Use same type for both instead."
705
+ )
706
+ if not _mask_is_float:
707
+ mask = (
708
+ torch.zeros_like(mask, dtype=target_type)
709
+ .masked_fill_(mask, float("-inf"))
710
+ )
711
+ return mask
712
+
713
+
714
+ def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
715
+ if input is None:
716
+ return None
717
+ elif isinstance(input, torch.Tensor):
718
+ return input.dtype
719
+ raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
720
+
721
+ def _in_projection_packed(
722
+ q: Tensor,
723
+ k: Tensor,
724
+ v: Tensor,
725
+ w: Tensor,
726
+ b: Optional[Tensor] = None,
727
+ ) -> List[Tensor]:
728
+ r"""
729
+ Performs the in-projection step of the attention operation, using packed weights.
730
+ Output is a triple containing projection tensors for query, key and value.
731
+
732
+ Args:
733
+ q, k, v: query, key and value tensors to be projected. For self-attention,
734
+ these are typically the same tensor; for encoder-decoder attention,
735
+ k and v are typically the same tensor. (We take advantage of these
736
+ identities for performance if they are present.) Regardless, q, k and v
737
+ must share a common embedding dimension; otherwise their shapes may vary.
738
+ w: projection weights for q, k and v, packed into a single tensor. Weights
739
+ are packed along dimension 0, in q, k, v order.
740
+ b: optional projection biases for q, k and v, packed into a single tensor
741
+ in q, k, v order.
742
+
743
+ Shape:
744
+ Inputs:
745
+ - q: :math:`(..., E)` where E is the embedding dimension
746
+ - k: :math:`(..., E)` where E is the embedding dimension
747
+ - v: :math:`(..., E)` where E is the embedding dimension
748
+ - w: :math:`(E * 3, E)` where E is the embedding dimension
749
+ - b: :math:`E * 3` where E is the embedding dimension
750
+
751
+ Output:
752
+ - in output list :math:`[q', k', v']`, each output tensor will have the
753
+ same shape as the corresponding input tensor.
754
+ """
755
+ E = q.size(-1)
756
+ if k is v:
757
+ if q is k:
758
+ # self-attention
759
+ proj = linear(q, w, b)
760
+ # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
761
+ proj = proj.unflatten(-1, (3, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
762
+ return proj[0], proj[1], proj[2]
763
+ else:
764
+ # encoder-decoder attention
765
+ w_q, w_kv = w.split([E, E * 2])
766
+ if b is None:
767
+ b_q = b_kv = None
768
+ else:
769
+ b_q, b_kv = b.split([E, E * 2])
770
+ q_proj = linear(q, w_q, b_q)
771
+ kv_proj = linear(k, w_kv, b_kv)
772
+ # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
773
+ kv_proj = kv_proj.unflatten(-1, (2, E)).unsqueeze(0).transpose(0, -2).squeeze(-2).contiguous()
774
+ return (q_proj, kv_proj[0], kv_proj[1])
775
+ else:
776
+ w_q, w_k, w_v = w.chunk(3)
777
+ if b is None:
778
+ b_q = b_k = b_v = None
779
+ else:
780
+ b_q, b_k, b_v = b.chunk(3)
781
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
782
+
783
+
784
+ def _in_projection(
785
+ q: Tensor,
786
+ k: Tensor,
787
+ v: Tensor,
788
+ w_q: Tensor,
789
+ w_k: Tensor,
790
+ w_v: Tensor,
791
+ b_q: Optional[Tensor] = None,
792
+ b_k: Optional[Tensor] = None,
793
+ b_v: Optional[Tensor] = None,
794
+ ) -> Tuple[Tensor, Tensor, Tensor]:
795
+ r"""
796
+ Performs the in-projection step of the attention operation. This is simply
797
+ a triple of linear projections, with shape constraints on the weights which
798
+ ensure embedding dimension uniformity in the projected outputs.
799
+ Output is a triple containing projection tensors for query, key and value.
800
+
801
+ Args:
802
+ q, k, v: query, key and value tensors to be projected.
803
+ w_q, w_k, w_v: weights for q, k and v, respectively.
804
+ b_q, b_k, b_v: optional biases for q, k and v, respectively.
805
+
806
+ Shape:
807
+ Inputs:
808
+ - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
809
+ number of leading dimensions.
810
+ - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
811
+ number of leading dimensions.
812
+ - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
813
+ number of leading dimensions.
814
+ - w_q: :math:`(Eq, Eq)`
815
+ - w_k: :math:`(Eq, Ek)`
816
+ - w_v: :math:`(Eq, Ev)`
817
+ - b_q: :math:`(Eq)`
818
+ - b_k: :math:`(Eq)`
819
+ - b_v: :math:`(Eq)`
820
+
821
+ Output: in output triple :math:`(q', k', v')`,
822
+ - q': :math:`[Qdims..., Eq]`
823
+ - k': :math:`[Kdims..., Eq]`
824
+ - v': :math:`[Vdims..., Eq]`
825
+
826
+ """
827
+ Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
828
+ assert w_q.shape == (Eq, Eq), f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
829
+ assert w_k.shape == (Eq, Ek), f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
830
+ assert w_v.shape == (Eq, Ev), f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
831
+ assert b_q is None or b_q.shape == (Eq,), f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
832
+ assert b_k is None or b_k.shape == (Eq,), f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
833
+ assert b_v is None or b_v.shape == (Eq,), f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
834
+ return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)