An attention block that allows spatial positions to attend to each other. Originally ported from here, but adapted to the N-d case. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
| 257 | |
| 258 | |
| 259 | class AttentionBlock(nn.Module): |
| 260 | """ |
| 261 | An attention block that allows spatial positions to attend to each other. |
| 262 | |
| 263 | Originally ported from here, but adapted to the N-d case. |
| 264 | https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. |
| 265 | """ |
| 266 | |
| 267 | def __init__( |
| 268 | self, |
| 269 | channels, |
| 270 | num_heads=1, |
| 271 | num_head_channels=-1, |
| 272 | use_checkpoint=False, |
| 273 | use_new_attention_order=False, |
| 274 | ): |
| 275 | super().__init__() |
| 276 | self.channels = channels |
| 277 | if num_head_channels == -1: |
| 278 | self.num_heads = num_heads |
| 279 | else: |
| 280 | assert ( |
| 281 | channels % num_head_channels == 0 |
| 282 | ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" |
| 283 | self.num_heads = channels // num_head_channels |
| 284 | self.use_checkpoint = use_checkpoint |
| 285 | self.norm = normalization(channels) |
| 286 | self.qkv = conv_nd(1, channels, channels * 3, 1) |
| 287 | if use_new_attention_order: |
| 288 | # split qkv before split heads |
| 289 | self.attention = QKVAttention(self.num_heads) |
| 290 | else: |
| 291 | # split heads before split qkv |
| 292 | self.attention = QKVAttentionLegacy(self.num_heads) |
| 293 | |
| 294 | self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) |
| 295 | |
| 296 | def forward(self, x): |
| 297 | return checkpoint(self._forward, (x,), self.parameters(), True) |
| 298 | |
| 299 | def _forward(self, x): |
| 300 | b, c, *spatial = x.shape |
| 301 | x = x.reshape(b, c, -1) |
| 302 | qkv = self.qkv(self.norm(x)) |
| 303 | h = self.attention(qkv) |
| 304 | h = self.proj_out(h) |
| 305 | return (x + h).reshape(b, c, *spatial) |
| 306 | |
| 307 | |
| 308 | def count_flops_attn(model, _x, y): |