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

Class AttentionPool2d

diff2flow/models/unet/openaimodel.py:35–62  ·  view source on GitHub ↗

Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py

Source from the content-addressed store, hash-verified

33
34## go
35class AttentionPool2d(nn.Module):
36 """
37 Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
38 """
39
40 def __init__(
41 self,
42 spacial_dim: int,
43 embed_dim: int,
44 num_heads_channels: int,
45 output_dim: int = None,
46 ):
47 super().__init__()
48 self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
49 self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
50 self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
51 self.num_heads = embed_dim // num_heads_channels
52 self.attention = QKVAttention(self.num_heads)
53
54 def forward(self, x):
55 b, c, *_spatial = x.shape
56 x = x.reshape(b, c, -1) # NC(HW)
57 x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
58 x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
59 x = self.qkv_proj(x)
60 x = self.attention(x)
61 x = self.c_proj(x)
62 return x[:, :, 0]
63
64
65class TimestepBlock(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected