| 1294 | |
| 1295 | |
| 1296 | class AttentionPooling(nn.Module): |
| 1297 | # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54 |
| 1298 | |
| 1299 | def __init__(self, num_heads, embed_dim, dtype=None): |
| 1300 | super().__init__() |
| 1301 | self.dtype = dtype |
| 1302 | self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5) |
| 1303 | self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 1304 | self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 1305 | self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 1306 | self.num_heads = num_heads |
| 1307 | self.dim_per_head = embed_dim // self.num_heads |
| 1308 | |
| 1309 | def forward(self, x): |
| 1310 | bs, length, width = x.size() |
| 1311 | |
| 1312 | def shape(x): |
| 1313 | # (bs, length, width) --> (bs, length, n_heads, dim_per_head) |
| 1314 | x = x.view(bs, -1, self.num_heads, self.dim_per_head) |
| 1315 | # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) |
| 1316 | x = x.transpose(1, 2) |
| 1317 | # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) |
| 1318 | x = x.reshape(bs * self.num_heads, -1, self.dim_per_head) |
| 1319 | # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length) |
| 1320 | x = x.transpose(1, 2) |
| 1321 | return x |
| 1322 | |
| 1323 | class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype) |
| 1324 | x = torch.cat([class_token, x], dim=1) # (bs, length+1, width) |
| 1325 | |
| 1326 | # (bs*n_heads, class_token_length, dim_per_head) |
| 1327 | q = shape(self.q_proj(class_token)) |
| 1328 | # (bs*n_heads, length+class_token_length, dim_per_head) |
| 1329 | k = shape(self.k_proj(x)) |
| 1330 | v = shape(self.v_proj(x)) |
| 1331 | |
| 1332 | # (bs*n_heads, class_token_length, length+class_token_length): |
| 1333 | scale = 1 / math.sqrt(math.sqrt(self.dim_per_head)) |
| 1334 | weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards |
| 1335 | weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 1336 | |
| 1337 | # (bs*n_heads, dim_per_head, class_token_length) |
| 1338 | a = torch.einsum("bts,bcs->bct", weight, v) |
| 1339 | |
| 1340 | # (bs, length+1, width) |
| 1341 | a = a.reshape(bs, -1, 1).transpose(1, 2) |
| 1342 | |
| 1343 | return a[:, 0, :] # cls_token |
| 1344 | |
| 1345 | |
| 1346 | def get_fourier_embeds_from_boundingbox(embed_dim, box): |