MCPcopy Create free account
hub / github.com/CompVis/diff2flow / AttentionBlock

Class AttentionBlock

diff2flow/models/unet/openaimodel.py:281–327  ·  view source on GitHub ↗

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.

Source from the content-addressed store, hash-verified

279
280
281class AttentionBlock(nn.Module):
282 """
283 An attention block that allows spatial positions to attend to each other.
284 Originally ported from here, but adapted to the N-d case.
285 https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
286 """
287
288 def __init__(
289 self,
290 channels,
291 num_heads=1,
292 num_head_channels=-1,
293 use_checkpoint=False,
294 use_new_attention_order=False,
295 ):
296 super().__init__()
297 self.channels = channels
298 if num_head_channels == -1:
299 self.num_heads = num_heads
300 else:
301 assert (
302 channels % num_head_channels == 0
303 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
304 self.num_heads = channels // num_head_channels
305 self.use_checkpoint = use_checkpoint
306 self.norm = normalization(channels)
307 self.qkv = conv_nd(1, channels, channels * 3, 1)
308 if use_new_attention_order:
309 # split qkv before split heads
310 self.attention = QKVAttention(self.num_heads)
311 else:
312 # split heads before split qkv
313 self.attention = QKVAttentionLegacy(self.num_heads)
314
315 self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
316
317 def forward(self, x):
318 return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
319 #return pt_checkpoint(self._forward, x) # pytorch
320
321 def _forward(self, x):
322 b, c, *spatial = x.shape
323 x = x.reshape(b, c, -1)
324 qkv = self.qkv(self.norm(x))
325 h = self.attention(qkv)
326 h = self.proj_out(h)
327 return (x + h).reshape(b, c, *spatial)
328
329
330def count_flops_attn(model, _x, y):

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected