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