hezhihui commited on
Commit
0a74acd
1 Parent(s): b07c810

restore resampler to 0830407

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