MCPcopy Create free account
hub / github.com/OpenDriveLab/ReSim / AttentionBlock

Class AttentionBlock

sat/sgm/modules/diffusionmodules/openaimodel.py:349–398  ·  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

347
348
349class AttentionBlock(nn.Module):
350 """
351 An attention block that allows spatial positions to attend to each other.
352 Originally ported from here, but adapted to the N-d case.
353 https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
354 """
355
356 def __init__(
357 self,
358 channels,
359 num_heads=1,
360 num_head_channels=-1,
361 use_checkpoint=False,
362 use_new_attention_order=False,
363 ):
364 super().__init__()
365 self.channels = channels
366 if num_head_channels == -1:
367 self.num_heads = num_heads
368 else:
369 assert (
370 channels % num_head_channels == 0
371 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
372 self.num_heads = channels // num_head_channels
373 self.use_checkpoint = use_checkpoint
374 self.norm = normalization(channels)
375 self.qkv = conv_nd(1, channels, channels * 3, 1)
376 if use_new_attention_order:
377 # split qkv before split heads
378 self.attention = QKVAttention(self.num_heads)
379 else:
380 # split heads before split qkv
381 self.attention = QKVAttentionLegacy(self.num_heads)
382
383 self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
384
385 def forward(self, x, **kwargs):
386 # TODO add crossframe attention and use mixed checkpoint
387 return checkpoint(
388 self._forward, (x,), self.parameters(), True
389 ) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
390 # return pt_checkpoint(self._forward, x) # pytorch
391
392 def _forward(self, x):
393 b, c, *spatial = x.shape
394 x = x.reshape(b, c, -1)
395 qkv = self.qkv(self.norm(x))
396 h = self.attention(qkv)
397 h = self.proj_out(h)
398 return (x + h).reshape(b, c, *spatial)
399
400
401def count_flops_attn(model, _x, y):

Callers 2

__init__Method · 0.85
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected