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