| 156 | |
| 157 | |
| 158 | class AttentionPool(nn.Module): |
| 159 | |
| 160 | def __init__(self, |
| 161 | dim, |
| 162 | mlp_ratio, |
| 163 | num_heads, |
| 164 | activation='gelu', |
| 165 | proj_dropout=0.0, |
| 166 | norm_eps=1e-5): |
| 167 | assert dim % num_heads == 0 |
| 168 | super().__init__() |
| 169 | self.dim = dim |
| 170 | self.mlp_ratio = mlp_ratio |
| 171 | self.num_heads = num_heads |
| 172 | self.head_dim = dim // num_heads |
| 173 | self.proj_dropout = proj_dropout |
| 174 | self.norm_eps = norm_eps |
| 175 | |
| 176 | # layers |
| 177 | gain = 1.0 / math.sqrt(dim) |
| 178 | self.cls_embedding = nn.Parameter(gain * torch.randn(1, 1, dim)) |
| 179 | self.to_q = nn.Linear(dim, dim) |
| 180 | self.to_kv = nn.Linear(dim, dim * 2) |
| 181 | self.proj = nn.Linear(dim, dim) |
| 182 | self.norm = LayerNorm(dim, eps=norm_eps) |
| 183 | self.mlp = nn.Sequential( |
| 184 | nn.Linear(dim, int(dim * mlp_ratio)), |
| 185 | QuickGELU() if activation == 'quick_gelu' else nn.GELU(), |
| 186 | nn.Linear(int(dim * mlp_ratio), dim), nn.Dropout(proj_dropout)) |
| 187 | |
| 188 | def forward(self, x): |
| 189 | """ |
| 190 | x: [B, L, C]. |
| 191 | """ |
| 192 | b, s, c, n, d = *x.size(), self.num_heads, self.head_dim |
| 193 | |
| 194 | # compute query, key, value |
| 195 | q = self.to_q(self.cls_embedding).view(1, 1, n, d).expand(b, -1, -1, -1) |
| 196 | k, v = self.to_kv(x).view(b, s, 2, n, d).unbind(2) |
| 197 | |
| 198 | # compute attention |
| 199 | x = flash_attention(q, k, v, version=2) |
| 200 | x = x.reshape(b, 1, c) |
| 201 | |
| 202 | # output |
| 203 | x = self.proj(x) |
| 204 | x = F.dropout(x, self.proj_dropout, self.training) |
| 205 | |
| 206 | # mlp |
| 207 | x = x + self.mlp(self.norm(x)) |
| 208 | return x[:, 0] |
| 209 | |
| 210 | |
| 211 | class VisionTransformer(nn.Module): |