| 572 | |
| 573 | |
| 574 | class AttentionPooling(nn.Module): |
| 575 | # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54 |
| 576 | |
| 577 | def __init__(self, num_heads, embed_dim, dtype=None): |
| 578 | super().__init__() |
| 579 | self.dtype = dtype |
| 580 | self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5) |
| 581 | self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 582 | self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 583 | self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype) |
| 584 | self.num_heads = num_heads |
| 585 | self.dim_per_head = embed_dim // self.num_heads |
| 586 | |
| 587 | def forward(self, x): |
| 588 | bs, length, width = x.size() |
| 589 | |
| 590 | def shape(x): |
| 591 | # (bs, length, width) --> (bs, length, n_heads, dim_per_head) |
| 592 | x = x.view(bs, -1, self.num_heads, self.dim_per_head) |
| 593 | # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) |
| 594 | x = x.transpose(1, 2) |
| 595 | # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) |
| 596 | x = x.reshape(bs * self.num_heads, -1, self.dim_per_head) |
| 597 | # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length) |
| 598 | x = x.transpose(1, 2) |
| 599 | return x |
| 600 | |
| 601 | class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype) |
| 602 | x = torch.cat([class_token, x], dim=1) # (bs, length+1, width) |
| 603 | |
| 604 | # (bs*n_heads, class_token_length, dim_per_head) |
| 605 | q = shape(self.q_proj(class_token)) |
| 606 | # (bs*n_heads, length+class_token_length, dim_per_head) |
| 607 | k = shape(self.k_proj(x)) |
| 608 | v = shape(self.v_proj(x)) |
| 609 | |
| 610 | # (bs*n_heads, class_token_length, length+class_token_length): |
| 611 | scale = 1 / math.sqrt(math.sqrt(self.dim_per_head)) |
| 612 | weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards |
| 613 | weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 614 | |
| 615 | # (bs*n_heads, dim_per_head, class_token_length) |
| 616 | a = torch.einsum("bts,bcs->bct", weight, v) |
| 617 | |
| 618 | # (bs, length+1, width) |
| 619 | a = a.reshape(bs, -1, 1).transpose(1, 2) |
| 620 | |
| 621 | return a[:, 0, :] # cls_token |
| 622 | |
| 623 | |
| 624 | def get_fourier_embeds_from_boundingbox(embed_dim, box): |