MCPcopy Create free account
hub / github.com/DPS2022/diffusion-posterior-sampling / AttentionPool2d

Class AttentionPool2d

guided_diffusion/unet.py:93–122  ·  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

91 return model
92
93class AttentionPool2d(nn.Module):
94 """
95 Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
96 """
97
98 def __init__(
99 self,
100 spacial_dim: int,
101 embed_dim: int,
102 num_heads_channels: int,
103 output_dim: int = None,
104 ):
105 super().__init__()
106 self.positional_embedding = nn.Parameter(
107 th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
108 )
109 self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
110 self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
111 self.num_heads = embed_dim // num_heads_channels
112 self.attention = QKVAttention(self.num_heads)
113
114 def forward(self, x):
115 b, c, *_spatial = x.shape
116 x = x.reshape(b, c, -1) # NC(HW)
117 x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
118 x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
119 x = self.qkv_proj(x)
120 x = self.attention(x)
121 x = self.c_proj(x)
122 return x[:, :, 0]
123
124
125class TimestepBlock(nn.Module):

Callers 1

__init__Method · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected