Self-attention block for the U-Net. §3.3 — "self-attention... at the 16×16 feature map resolution" Appendix B — "We add one head of self-attention at the 16×16 resolution" [FROM_OFFICIAL_CODE] Uses a single attention head with GroupNorm.
| 147 | |
| 148 | |
| 149 | class AttentionBlock(nn.Module): |
| 150 | """Self-attention block for the U-Net. |
| 151 | |
| 152 | §3.3 — "self-attention... at the 16×16 feature map resolution" |
| 153 | Appendix B — "We add one head of self-attention at the 16×16 resolution" |
| 154 | |
| 155 | [FROM_OFFICIAL_CODE] Uses a single attention head with GroupNorm. |
| 156 | """ |
| 157 | |
| 158 | def __init__(self, channels: int, num_groups: int = 32): |
| 159 | super().__init__() |
| 160 | self.norm = nn.GroupNorm(num_groups, channels) |
| 161 | self.qkv = nn.Conv1d(channels, channels * 3, kernel_size=1) |
| 162 | self.proj = nn.Conv1d(channels, channels, kernel_size=1) |
| 163 | |
| 164 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 165 | """ |
| 166 | Args: |
| 167 | x: (batch, channels, H, W) |
| 168 | Returns: |
| 169 | (batch, channels, H, W) |
| 170 | """ |
| 171 | batch, channels, h, w = x.shape |
| 172 | residual = x |
| 173 | |
| 174 | x = self.norm(x) |
| 175 | x = x.view(batch, channels, h * w) # (batch, channels, H*W) |
| 176 | |
| 177 | qkv = self.qkv(x) # (batch, 3*channels, H*W) |
| 178 | q, k, v = qkv.chunk(3, dim=1) # each: (batch, channels, H*W) |
| 179 | |
| 180 | # Scaled dot-product attention |
| 181 | scale = 1.0 / math.sqrt(channels) |
| 182 | attn = torch.bmm(q.transpose(1, 2), k) * scale # (batch, H*W, H*W) |
| 183 | attn = F.softmax(attn, dim=-1) |
| 184 | |
| 185 | out = torch.bmm(v, attn.transpose(1, 2)) # (batch, channels, H*W) |
| 186 | out = self.proj(out) # (batch, channels, H*W) |
| 187 | out = out.view(batch, channels, h, w) # (batch, channels, H, W) |
| 188 | |
| 189 | return out + residual |
| 190 | |
| 191 | |
| 192 | class Downsample(nn.Module): |