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