Update sam2/modeling/sam/transformer.py
Browse files- sam2/modeling/sam/transformer.py +335 -317
sam2/modeling/sam/transformer.py
CHANGED
|
@@ -1,317 +1,335 @@
|
|
| 1 |
-
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
-
# All rights reserved.
|
| 3 |
-
|
| 4 |
-
# This source code is licensed under the license found in the
|
| 5 |
-
# LICENSE file in the root directory of this source tree.
|
| 6 |
-
|
| 7 |
-
import math
|
| 8 |
-
import warnings
|
| 9 |
-
from functools import partial
|
| 10 |
-
from typing import Tuple, Type
|
| 11 |
-
|
| 12 |
-
import torch
|
| 13 |
-
import torch.nn.functional as F
|
| 14 |
-
from torch import Tensor, nn
|
| 15 |
-
|
| 16 |
-
from sam2.modeling.position_encoding import apply_rotary_enc, compute_axial_cis
|
| 17 |
-
from sam2.modeling.sam2_utils import MLP
|
| 18 |
-
from sam2.utils.misc import get_sdp_backends
|
| 19 |
-
|
| 20 |
-
warnings.simplefilter(action="ignore", category=FutureWarning)
|
| 21 |
-
# OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
class TwoWayTransformer(nn.Module):
|
| 25 |
-
def __init__(
|
| 26 |
-
self,
|
| 27 |
-
depth: int,
|
| 28 |
-
embedding_dim: int,
|
| 29 |
-
num_heads: int,
|
| 30 |
-
mlp_dim: int,
|
| 31 |
-
activation: Type[nn.Module] = nn.ReLU,
|
| 32 |
-
attention_downsample_rate: int = 2,
|
| 33 |
-
) -> None:
|
| 34 |
-
"""
|
| 35 |
-
A transformer decoder that attends to an input image using
|
| 36 |
-
queries whose positional embedding is supplied.
|
| 37 |
-
|
| 38 |
-
Args:
|
| 39 |
-
depth (int): number of layers in the transformer
|
| 40 |
-
embedding_dim (int): the channel dimension for the input embeddings
|
| 41 |
-
num_heads (int): the number of heads for multihead attention. Must
|
| 42 |
-
divide embedding_dim
|
| 43 |
-
mlp_dim (int): the channel dimension internal to the MLP block
|
| 44 |
-
activation (nn.Module): the activation to use in the MLP block
|
| 45 |
-
"""
|
| 46 |
-
super().__init__()
|
| 47 |
-
self.depth = depth
|
| 48 |
-
self.embedding_dim = embedding_dim
|
| 49 |
-
self.num_heads = num_heads
|
| 50 |
-
self.mlp_dim = mlp_dim
|
| 51 |
-
self.layers = nn.ModuleList()
|
| 52 |
-
|
| 53 |
-
for i in range(depth):
|
| 54 |
-
self.layers.append(
|
| 55 |
-
TwoWayAttentionBlock(
|
| 56 |
-
embedding_dim=embedding_dim,
|
| 57 |
-
num_heads=num_heads,
|
| 58 |
-
mlp_dim=mlp_dim,
|
| 59 |
-
activation=activation,
|
| 60 |
-
attention_downsample_rate=attention_downsample_rate,
|
| 61 |
-
skip_first_layer_pe=(i == 0),
|
| 62 |
-
)
|
| 63 |
-
)
|
| 64 |
-
|
| 65 |
-
self.final_attn_token_to_image = Attention(
|
| 66 |
-
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 67 |
-
)
|
| 68 |
-
self.norm_final_attn = nn.LayerNorm(embedding_dim)
|
| 69 |
-
|
| 70 |
-
def forward(
|
| 71 |
-
self,
|
| 72 |
-
image_embedding: Tensor,
|
| 73 |
-
image_pe: Tensor,
|
| 74 |
-
point_embedding: Tensor,
|
| 75 |
-
) -> Tuple[Tensor, Tensor]:
|
| 76 |
-
"""
|
| 77 |
-
Args:
|
| 78 |
-
image_embedding (torch.Tensor): image to attend to. Should be shape
|
| 79 |
-
B x embedding_dim x h x w for any h and w.
|
| 80 |
-
image_pe (torch.Tensor): the positional encoding to add to the image. Must
|
| 81 |
-
have the same shape as image_embedding.
|
| 82 |
-
point_embedding (torch.Tensor): the embedding to add to the query points.
|
| 83 |
-
Must have shape B x N_points x embedding_dim for any N_points.
|
| 84 |
-
|
| 85 |
-
Returns:
|
| 86 |
-
torch.Tensor: the processed point_embedding
|
| 87 |
-
torch.Tensor: the processed image_embedding
|
| 88 |
-
"""
|
| 89 |
-
# BxCxHxW -> BxHWxC == B x N_image_tokens x C
|
| 90 |
-
bs, c, h, w = image_embedding.shape
|
| 91 |
-
image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
|
| 92 |
-
image_pe = image_pe.flatten(2).permute(0, 2, 1)
|
| 93 |
-
|
| 94 |
-
# Prepare queries
|
| 95 |
-
queries = point_embedding
|
| 96 |
-
keys = image_embedding
|
| 97 |
-
|
| 98 |
-
# Apply transformer blocks and final layernorm
|
| 99 |
-
for layer in self.layers:
|
| 100 |
-
queries, keys = layer(
|
| 101 |
-
queries=queries,
|
| 102 |
-
keys=keys,
|
| 103 |
-
query_pe=point_embedding,
|
| 104 |
-
key_pe=image_pe,
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
# Apply the final attention layer from the points to the image
|
| 108 |
-
q = queries + point_embedding
|
| 109 |
-
k = keys + image_pe
|
| 110 |
-
attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
|
| 111 |
-
queries = queries + attn_out
|
| 112 |
-
queries = self.norm_final_attn(queries)
|
| 113 |
-
|
| 114 |
-
return queries, keys
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
class TwoWayAttentionBlock(nn.Module):
|
| 118 |
-
def __init__(
|
| 119 |
-
self,
|
| 120 |
-
embedding_dim: int,
|
| 121 |
-
num_heads: int,
|
| 122 |
-
mlp_dim: int = 2048,
|
| 123 |
-
activation: Type[nn.Module] = nn.ReLU,
|
| 124 |
-
attention_downsample_rate: int = 2,
|
| 125 |
-
skip_first_layer_pe: bool = False,
|
| 126 |
-
) -> None:
|
| 127 |
-
"""
|
| 128 |
-
A transformer block with four layers: (1) self-attention of sparse
|
| 129 |
-
inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
|
| 130 |
-
block on sparse inputs, and (4) cross attention of dense inputs to sparse
|
| 131 |
-
inputs.
|
| 132 |
-
|
| 133 |
-
Arguments:
|
| 134 |
-
embedding_dim (int): the channel dimension of the embeddings
|
| 135 |
-
num_heads (int): the number of heads in the attention layers
|
| 136 |
-
mlp_dim (int): the hidden dimension of the mlp block
|
| 137 |
-
activation (nn.Module): the activation of the mlp block
|
| 138 |
-
skip_first_layer_pe (bool): skip the PE on the first layer
|
| 139 |
-
"""
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.self_attn = Attention(embedding_dim, num_heads)
|
| 142 |
-
self.norm1 = nn.LayerNorm(embedding_dim)
|
| 143 |
-
|
| 144 |
-
self.cross_attn_token_to_image = Attention(
|
| 145 |
-
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 146 |
-
)
|
| 147 |
-
self.norm2 = nn.LayerNorm(embedding_dim)
|
| 148 |
-
|
| 149 |
-
self.mlp = MLP(
|
| 150 |
-
embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation
|
| 151 |
-
)
|
| 152 |
-
self.norm3 = nn.LayerNorm(embedding_dim)
|
| 153 |
-
|
| 154 |
-
self.norm4 = nn.LayerNorm(embedding_dim)
|
| 155 |
-
self.cross_attn_image_to_token = Attention(
|
| 156 |
-
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
self.skip_first_layer_pe = skip_first_layer_pe
|
| 160 |
-
|
| 161 |
-
def forward(
|
| 162 |
-
self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
|
| 163 |
-
) -> Tuple[Tensor, Tensor]:
|
| 164 |
-
# Self attention block
|
| 165 |
-
if self.skip_first_layer_pe:
|
| 166 |
-
queries = self.self_attn(q=queries, k=queries, v=queries)
|
| 167 |
-
else:
|
| 168 |
-
q = queries + query_pe
|
| 169 |
-
attn_out = self.self_attn(q=q, k=q, v=queries)
|
| 170 |
-
queries = queries + attn_out
|
| 171 |
-
queries = self.norm1(queries)
|
| 172 |
-
|
| 173 |
-
# Cross attention block, tokens attending to image embedding
|
| 174 |
-
q = queries + query_pe
|
| 175 |
-
k = keys + key_pe
|
| 176 |
-
attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
|
| 177 |
-
queries = queries + attn_out
|
| 178 |
-
queries = self.norm2(queries)
|
| 179 |
-
|
| 180 |
-
# MLP block
|
| 181 |
-
mlp_out = self.mlp(queries)
|
| 182 |
-
queries = queries + mlp_out
|
| 183 |
-
queries = self.norm3(queries)
|
| 184 |
-
|
| 185 |
-
# Cross attention block, image embedding attending to tokens
|
| 186 |
-
q = queries + query_pe
|
| 187 |
-
k = keys + key_pe
|
| 188 |
-
attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
|
| 189 |
-
keys = keys + attn_out
|
| 190 |
-
keys = self.norm4(keys)
|
| 191 |
-
|
| 192 |
-
return queries, keys
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
class Attention(nn.Module):
|
| 196 |
-
"""
|
| 197 |
-
An attention layer that allows for downscaling the size of the embedding
|
| 198 |
-
after projection to queries, keys, and values.
|
| 199 |
-
"""
|
| 200 |
-
|
| 201 |
-
def __init__(
|
| 202 |
-
self,
|
| 203 |
-
embedding_dim: int,
|
| 204 |
-
num_heads: int,
|
| 205 |
-
downsample_rate: int = 1,
|
| 206 |
-
dropout: float = 0.0,
|
| 207 |
-
kv_in_dim: int = None,
|
| 208 |
-
) -> None:
|
| 209 |
-
super().__init__()
|
| 210 |
-
self.embedding_dim = embedding_dim
|
| 211 |
-
self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
|
| 212 |
-
self.internal_dim = embedding_dim // downsample_rate
|
| 213 |
-
self.num_heads = num_heads
|
| 214 |
-
assert (
|
| 215 |
-
self.internal_dim % num_heads == 0
|
| 216 |
-
), "num_heads must divide embedding_dim."
|
| 217 |
-
|
| 218 |
-
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
|
| 219 |
-
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
| 220 |
-
self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
| 221 |
-
self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
|
| 222 |
-
|
| 223 |
-
self.dropout_p = dropout
|
| 224 |
-
|
| 225 |
-
def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
|
| 226 |
-
b, n, c = x.shape
|
| 227 |
-
x = x.reshape(b, n, num_heads, c // num_heads)
|
| 228 |
-
return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
|
| 229 |
-
|
| 230 |
-
def _recombine_heads(self, x: Tensor) -> Tensor:
|
| 231 |
-
b, n_heads, n_tokens, c_per_head = x.shape
|
| 232 |
-
x = x.transpose(1, 2)
|
| 233 |
-
return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
|
| 234 |
-
|
| 235 |
-
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
|
| 236 |
-
# Input projections
|
| 237 |
-
q = self.q_proj(q)
|
| 238 |
-
k = self.k_proj(k)
|
| 239 |
-
v = self.v_proj(v)
|
| 240 |
-
|
| 241 |
-
# Separate into heads
|
| 242 |
-
q = self._separate_heads(q, self.num_heads)
|
| 243 |
-
k = self._separate_heads(k, self.num_heads)
|
| 244 |
-
v = self._separate_heads(v, self.num_heads)
|
| 245 |
-
|
| 246 |
-
dropout_p = self.dropout_p if self.training else 0.0
|
| 247 |
-
# Attention
|
| 248 |
-
|
| 249 |
-
#with torch.nn.attention.sdpa_kernel(get_sdp_backends(dropout_p)):
|
| 250 |
-
out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
|
| 251 |
-
|
| 252 |
-
out = self._recombine_heads(out)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
self
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
q,
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
)
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Meta Platforms, Inc. and affiliates.
|
| 2 |
+
# All rights reserved.
|
| 3 |
+
|
| 4 |
+
# This source code is licensed under the license found in the
|
| 5 |
+
# LICENSE file in the root directory of this source tree.
|
| 6 |
+
|
| 7 |
+
import math
|
| 8 |
+
import warnings
|
| 9 |
+
from functools import partial
|
| 10 |
+
from typing import Tuple, Type
|
| 11 |
+
|
| 12 |
+
import torch
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch import Tensor, nn
|
| 15 |
+
|
| 16 |
+
from sam2.modeling.position_encoding import apply_rotary_enc, compute_axial_cis
|
| 17 |
+
from sam2.modeling.sam2_utils import MLP
|
| 18 |
+
from sam2.utils.misc import get_sdp_backends
|
| 19 |
+
|
| 20 |
+
warnings.simplefilter(action="ignore", category=FutureWarning)
|
| 21 |
+
# OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class TwoWayTransformer(nn.Module):
|
| 25 |
+
def __init__(
|
| 26 |
+
self,
|
| 27 |
+
depth: int,
|
| 28 |
+
embedding_dim: int,
|
| 29 |
+
num_heads: int,
|
| 30 |
+
mlp_dim: int,
|
| 31 |
+
activation: Type[nn.Module] = nn.ReLU,
|
| 32 |
+
attention_downsample_rate: int = 2,
|
| 33 |
+
) -> None:
|
| 34 |
+
"""
|
| 35 |
+
A transformer decoder that attends to an input image using
|
| 36 |
+
queries whose positional embedding is supplied.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
depth (int): number of layers in the transformer
|
| 40 |
+
embedding_dim (int): the channel dimension for the input embeddings
|
| 41 |
+
num_heads (int): the number of heads for multihead attention. Must
|
| 42 |
+
divide embedding_dim
|
| 43 |
+
mlp_dim (int): the channel dimension internal to the MLP block
|
| 44 |
+
activation (nn.Module): the activation to use in the MLP block
|
| 45 |
+
"""
|
| 46 |
+
super().__init__()
|
| 47 |
+
self.depth = depth
|
| 48 |
+
self.embedding_dim = embedding_dim
|
| 49 |
+
self.num_heads = num_heads
|
| 50 |
+
self.mlp_dim = mlp_dim
|
| 51 |
+
self.layers = nn.ModuleList()
|
| 52 |
+
|
| 53 |
+
for i in range(depth):
|
| 54 |
+
self.layers.append(
|
| 55 |
+
TwoWayAttentionBlock(
|
| 56 |
+
embedding_dim=embedding_dim,
|
| 57 |
+
num_heads=num_heads,
|
| 58 |
+
mlp_dim=mlp_dim,
|
| 59 |
+
activation=activation,
|
| 60 |
+
attention_downsample_rate=attention_downsample_rate,
|
| 61 |
+
skip_first_layer_pe=(i == 0),
|
| 62 |
+
)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
self.final_attn_token_to_image = Attention(
|
| 66 |
+
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 67 |
+
)
|
| 68 |
+
self.norm_final_attn = nn.LayerNorm(embedding_dim)
|
| 69 |
+
|
| 70 |
+
def forward(
|
| 71 |
+
self,
|
| 72 |
+
image_embedding: Tensor,
|
| 73 |
+
image_pe: Tensor,
|
| 74 |
+
point_embedding: Tensor,
|
| 75 |
+
) -> Tuple[Tensor, Tensor]:
|
| 76 |
+
"""
|
| 77 |
+
Args:
|
| 78 |
+
image_embedding (torch.Tensor): image to attend to. Should be shape
|
| 79 |
+
B x embedding_dim x h x w for any h and w.
|
| 80 |
+
image_pe (torch.Tensor): the positional encoding to add to the image. Must
|
| 81 |
+
have the same shape as image_embedding.
|
| 82 |
+
point_embedding (torch.Tensor): the embedding to add to the query points.
|
| 83 |
+
Must have shape B x N_points x embedding_dim for any N_points.
|
| 84 |
+
|
| 85 |
+
Returns:
|
| 86 |
+
torch.Tensor: the processed point_embedding
|
| 87 |
+
torch.Tensor: the processed image_embedding
|
| 88 |
+
"""
|
| 89 |
+
# BxCxHxW -> BxHWxC == B x N_image_tokens x C
|
| 90 |
+
bs, c, h, w = image_embedding.shape
|
| 91 |
+
image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
|
| 92 |
+
image_pe = image_pe.flatten(2).permute(0, 2, 1)
|
| 93 |
+
|
| 94 |
+
# Prepare queries
|
| 95 |
+
queries = point_embedding
|
| 96 |
+
keys = image_embedding
|
| 97 |
+
|
| 98 |
+
# Apply transformer blocks and final layernorm
|
| 99 |
+
for layer in self.layers:
|
| 100 |
+
queries, keys = layer(
|
| 101 |
+
queries=queries,
|
| 102 |
+
keys=keys,
|
| 103 |
+
query_pe=point_embedding,
|
| 104 |
+
key_pe=image_pe,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
# Apply the final attention layer from the points to the image
|
| 108 |
+
q = queries + point_embedding
|
| 109 |
+
k = keys + image_pe
|
| 110 |
+
attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
|
| 111 |
+
queries = queries + attn_out
|
| 112 |
+
queries = self.norm_final_attn(queries)
|
| 113 |
+
|
| 114 |
+
return queries, keys
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
class TwoWayAttentionBlock(nn.Module):
|
| 118 |
+
def __init__(
|
| 119 |
+
self,
|
| 120 |
+
embedding_dim: int,
|
| 121 |
+
num_heads: int,
|
| 122 |
+
mlp_dim: int = 2048,
|
| 123 |
+
activation: Type[nn.Module] = nn.ReLU,
|
| 124 |
+
attention_downsample_rate: int = 2,
|
| 125 |
+
skip_first_layer_pe: bool = False,
|
| 126 |
+
) -> None:
|
| 127 |
+
"""
|
| 128 |
+
A transformer block with four layers: (1) self-attention of sparse
|
| 129 |
+
inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
|
| 130 |
+
block on sparse inputs, and (4) cross attention of dense inputs to sparse
|
| 131 |
+
inputs.
|
| 132 |
+
|
| 133 |
+
Arguments:
|
| 134 |
+
embedding_dim (int): the channel dimension of the embeddings
|
| 135 |
+
num_heads (int): the number of heads in the attention layers
|
| 136 |
+
mlp_dim (int): the hidden dimension of the mlp block
|
| 137 |
+
activation (nn.Module): the activation of the mlp block
|
| 138 |
+
skip_first_layer_pe (bool): skip the PE on the first layer
|
| 139 |
+
"""
|
| 140 |
+
super().__init__()
|
| 141 |
+
self.self_attn = Attention(embedding_dim, num_heads)
|
| 142 |
+
self.norm1 = nn.LayerNorm(embedding_dim)
|
| 143 |
+
|
| 144 |
+
self.cross_attn_token_to_image = Attention(
|
| 145 |
+
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 146 |
+
)
|
| 147 |
+
self.norm2 = nn.LayerNorm(embedding_dim)
|
| 148 |
+
|
| 149 |
+
self.mlp = MLP(
|
| 150 |
+
embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation
|
| 151 |
+
)
|
| 152 |
+
self.norm3 = nn.LayerNorm(embedding_dim)
|
| 153 |
+
|
| 154 |
+
self.norm4 = nn.LayerNorm(embedding_dim)
|
| 155 |
+
self.cross_attn_image_to_token = Attention(
|
| 156 |
+
embedding_dim, num_heads, downsample_rate=attention_downsample_rate
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
self.skip_first_layer_pe = skip_first_layer_pe
|
| 160 |
+
|
| 161 |
+
def forward(
|
| 162 |
+
self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
|
| 163 |
+
) -> Tuple[Tensor, Tensor]:
|
| 164 |
+
# Self attention block
|
| 165 |
+
if self.skip_first_layer_pe:
|
| 166 |
+
queries = self.self_attn(q=queries, k=queries, v=queries)
|
| 167 |
+
else:
|
| 168 |
+
q = queries + query_pe
|
| 169 |
+
attn_out = self.self_attn(q=q, k=q, v=queries)
|
| 170 |
+
queries = queries + attn_out
|
| 171 |
+
queries = self.norm1(queries)
|
| 172 |
+
|
| 173 |
+
# Cross attention block, tokens attending to image embedding
|
| 174 |
+
q = queries + query_pe
|
| 175 |
+
k = keys + key_pe
|
| 176 |
+
attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
|
| 177 |
+
queries = queries + attn_out
|
| 178 |
+
queries = self.norm2(queries)
|
| 179 |
+
|
| 180 |
+
# MLP block
|
| 181 |
+
mlp_out = self.mlp(queries)
|
| 182 |
+
queries = queries + mlp_out
|
| 183 |
+
queries = self.norm3(queries)
|
| 184 |
+
|
| 185 |
+
# Cross attention block, image embedding attending to tokens
|
| 186 |
+
q = queries + query_pe
|
| 187 |
+
k = keys + key_pe
|
| 188 |
+
attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
|
| 189 |
+
keys = keys + attn_out
|
| 190 |
+
keys = self.norm4(keys)
|
| 191 |
+
|
| 192 |
+
return queries, keys
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class Attention(nn.Module):
|
| 196 |
+
"""
|
| 197 |
+
An attention layer that allows for downscaling the size of the embedding
|
| 198 |
+
after projection to queries, keys, and values.
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def __init__(
|
| 202 |
+
self,
|
| 203 |
+
embedding_dim: int,
|
| 204 |
+
num_heads: int,
|
| 205 |
+
downsample_rate: int = 1,
|
| 206 |
+
dropout: float = 0.0,
|
| 207 |
+
kv_in_dim: int = None,
|
| 208 |
+
) -> None:
|
| 209 |
+
super().__init__()
|
| 210 |
+
self.embedding_dim = embedding_dim
|
| 211 |
+
self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
|
| 212 |
+
self.internal_dim = embedding_dim // downsample_rate
|
| 213 |
+
self.num_heads = num_heads
|
| 214 |
+
assert (
|
| 215 |
+
self.internal_dim % num_heads == 0
|
| 216 |
+
), "num_heads must divide embedding_dim."
|
| 217 |
+
|
| 218 |
+
self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
|
| 219 |
+
self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
| 220 |
+
self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
|
| 221 |
+
self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
|
| 222 |
+
|
| 223 |
+
self.dropout_p = dropout
|
| 224 |
+
|
| 225 |
+
def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
|
| 226 |
+
b, n, c = x.shape
|
| 227 |
+
x = x.reshape(b, n, num_heads, c // num_heads)
|
| 228 |
+
return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
|
| 229 |
+
|
| 230 |
+
def _recombine_heads(self, x: Tensor) -> Tensor:
|
| 231 |
+
b, n_heads, n_tokens, c_per_head = x.shape
|
| 232 |
+
x = x.transpose(1, 2)
|
| 233 |
+
return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
|
| 234 |
+
|
| 235 |
+
def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
|
| 236 |
+
# Input projections
|
| 237 |
+
q = self.q_proj(q)
|
| 238 |
+
k = self.k_proj(k)
|
| 239 |
+
v = self.v_proj(v)
|
| 240 |
+
|
| 241 |
+
# # Separate into heads
|
| 242 |
+
# q = self._separate_heads(q, self.num_heads)
|
| 243 |
+
# k = self._separate_heads(k, self.num_heads)
|
| 244 |
+
# v = self._separate_heads(v, self.num_heads)
|
| 245 |
+
|
| 246 |
+
# dropout_p = self.dropout_p if self.training else 0.0
|
| 247 |
+
# # Attention
|
| 248 |
+
|
| 249 |
+
# #with torch.nn.attention.sdpa_kernel(get_sdp_backends(dropout_p)):
|
| 250 |
+
# out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
|
| 251 |
+
|
| 252 |
+
# out = self._recombine_heads(out)
|
| 253 |
+
|
| 254 |
+
q = rearrange(q, "b s (n d) -> b s n d", n=self.num_heads)
|
| 255 |
+
k = rearrange(k, "b s (n d) -> b s n d", n=self.num_heads)
|
| 256 |
+
v = rearrange(v, "b s (n d) -> b s n d", n=self.num_heads)
|
| 257 |
+
|
| 258 |
+
out = flash_attn_interface.flash_attn_func(q, k, v) # -> [b, s_q, n, d]
|
| 259 |
+
|
| 260 |
+
out = rearrange(out, "b s n d -> b s (n d)", n=self.num_heads)
|
| 261 |
+
|
| 262 |
+
out = self.out_proj(out)
|
| 263 |
+
|
| 264 |
+
return out
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
class RoPEAttention(Attention):
|
| 268 |
+
"""Attention with rotary position encoding."""
|
| 269 |
+
|
| 270 |
+
def __init__(
|
| 271 |
+
self,
|
| 272 |
+
*args,
|
| 273 |
+
rope_theta=10000.0,
|
| 274 |
+
# whether to repeat q rope to match k length
|
| 275 |
+
# this is needed for cross-attention to memories
|
| 276 |
+
rope_k_repeat=False,
|
| 277 |
+
feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution
|
| 278 |
+
**kwargs,
|
| 279 |
+
):
|
| 280 |
+
super().__init__(*args, **kwargs)
|
| 281 |
+
|
| 282 |
+
self.compute_cis = partial(
|
| 283 |
+
compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta
|
| 284 |
+
)
|
| 285 |
+
freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1])
|
| 286 |
+
self.freqs_cis = freqs_cis
|
| 287 |
+
self.rope_k_repeat = rope_k_repeat
|
| 288 |
+
|
| 289 |
+
def forward(
|
| 290 |
+
self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0
|
| 291 |
+
) -> Tensor:
|
| 292 |
+
# Input projections
|
| 293 |
+
q = self.q_proj(q)
|
| 294 |
+
k = self.k_proj(k)
|
| 295 |
+
v = self.v_proj(v)
|
| 296 |
+
|
| 297 |
+
# # Separate into heads
|
| 298 |
+
# q = self._separate_heads(q, self.num_heads)
|
| 299 |
+
# k = self._separate_heads(k, self.num_heads)
|
| 300 |
+
# v = self._separate_heads(v, self.num_heads)
|
| 301 |
+
|
| 302 |
+
q = rearrange(q, "b s (n d) -> b s n d", n=self.num_heads)
|
| 303 |
+
k = rearrange(k, "b s (n d) -> b s n d", n=self.num_heads)
|
| 304 |
+
v = rearrange(v, "b s (n d) -> b s n d", n=self.num_heads)
|
| 305 |
+
|
| 306 |
+
# Apply rotary position encoding
|
| 307 |
+
w = h = math.sqrt(q.shape[-2])
|
| 308 |
+
self.freqs_cis = self.freqs_cis.to(q.device)
|
| 309 |
+
if self.freqs_cis.shape[0] != q.shape[-2]:
|
| 310 |
+
self.freqs_cis = self.compute_cis(end_x=w, end_y=h).to(q.device)
|
| 311 |
+
if q.shape[-2] != k.shape[-2]:
|
| 312 |
+
assert self.rope_k_repeat
|
| 313 |
+
|
| 314 |
+
num_k_rope = k.size(-2) - num_k_exclude_rope
|
| 315 |
+
q, k[:, :, :num_k_rope] = apply_rotary_enc(
|
| 316 |
+
q,
|
| 317 |
+
k[:, :, :num_k_rope],
|
| 318 |
+
freqs_cis=self.freqs_cis,
|
| 319 |
+
repeat_freqs_k=self.rope_k_repeat,
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
dropout_p = self.dropout_p if self.training else 0.0
|
| 323 |
+
|
| 324 |
+
# #with torch.nn.attention.sdpa_kernel(get_sdp_backends(dropout_p)):
|
| 325 |
+
# out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
|
| 326 |
+
|
| 327 |
+
# out = self._recombine_heads(out)
|
| 328 |
+
|
| 329 |
+
out = flash_attn_interface.flash_attn_func(q, k, v) # -> [b, s_q, n, d]
|
| 330 |
+
|
| 331 |
+
out = rearrange(out, "b s n d -> b s (n d)", n=self.num_heads)
|
| 332 |
+
|
| 333 |
+
out = self.out_proj(out)
|
| 334 |
+
|
| 335 |
+
return out
|