| 143 | |
| 144 | |
| 145 | class SelfAttention(nn.Module): |
| 146 | def __init__(self, in_channel, n_head=1, norm_groups=32): |
| 147 | super().__init__() |
| 148 | |
| 149 | self.n_head = n_head |
| 150 | |
| 151 | # self.norm = nn.BatchNorm2d(in_channel) |
| 152 | self.norm = nn.GroupNorm(norm_groups, in_channel) |
| 153 | # self.norm = LayerNorm2d(in_channel) |
| 154 | self.qkv = nn.Conv2d(in_channel, in_channel * 3, 1, bias=False) |
| 155 | self.out = nn.Conv2d(in_channel, in_channel, 1) |
| 156 | |
| 157 | def forward(self, input): |
| 158 | batch, channel, height, width = input.shape |
| 159 | n_head = self.n_head |
| 160 | head_dim = channel // n_head |
| 161 | |
| 162 | norm = self.norm(input) |
| 163 | qkv = self.qkv(norm).view(batch, n_head, head_dim * 3, height, width) |
| 164 | query, key, value = qkv.chunk(3, dim=2) # bhdyx |
| 165 | |
| 166 | attn = torch.einsum( |
| 167 | "bnchw, bncyx -> bnhwyx", query, key |
| 168 | ).contiguous() / math.sqrt(channel) |
| 169 | attn = attn.view(batch, n_head, height, width, -1) |
| 170 | attn = torch.softmax(attn, -1) |
| 171 | attn = attn.view(batch, n_head, height, width, height, width) |
| 172 | |
| 173 | out = torch.einsum("bnhwyx, bncyx -> bnchw", attn, value).contiguous() |
| 174 | out = self.out(out.view(batch, channel, height, width)) |
| 175 | |
| 176 | return out + input |
| 177 | |
| 178 | |
| 179 | class ResnetBlocWithAttn(nn.Module): |