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