MCPcopy Index your code
hub / github.com/VisionXLab/OF-Diff / AttentionBlock

Class AttentionBlock

ldm/modules/diffusionmodules/openaimodel.py:279–325  ·  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

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

Callers 2

__init__Method · 0.90
__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected