| 1975 | self.dim_per_head = embed_dim // self.num_heads |
| 1976 | |
| 1977 | def forward(self, x): |
| 1978 | bs, length, width = x.size() |
| 1979 | |
| 1980 | def shape(x): |
| 1981 | # (bs, length, width) --> (bs, length, n_heads, dim_per_head) |
| 1982 | x = x.view(bs, -1, self.num_heads, self.dim_per_head) |
| 1983 | # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) |
| 1984 | x = x.transpose(1, 2) |
| 1985 | # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) |
| 1986 | x = x.reshape(bs * self.num_heads, -1, self.dim_per_head) |
| 1987 | # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length) |
| 1988 | x = x.transpose(1, 2) |
| 1989 | return x |
| 1990 | |
| 1991 | class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype) |
| 1992 | x = torch.cat([class_token, x], dim=1) # (bs, length+1, width) |
| 1993 | |
| 1994 | # (bs*n_heads, class_token_length, dim_per_head) |
| 1995 | q = shape(self.q_proj(class_token)) |
| 1996 | # (bs*n_heads, length+class_token_length, dim_per_head) |
| 1997 | k = shape(self.k_proj(x)) |
| 1998 | v = shape(self.v_proj(x)) |
| 1999 | |
| 2000 | # (bs*n_heads, class_token_length, length+class_token_length): |
| 2001 | scale = 1 / math.sqrt(math.sqrt(self.dim_per_head)) |
| 2002 | weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards |
| 2003 | weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) |
| 2004 | |
| 2005 | # (bs*n_heads, dim_per_head, class_token_length) |
| 2006 | a = torch.einsum("bts,bcs->bct", weight, v) |
| 2007 | |
| 2008 | # (bs, length+1, width) |
| 2009 | a = a.reshape(bs, -1, 1).transpose(1, 2) |
| 2010 | |
| 2011 | return a[:, 0, :] # cls_token |
| 2012 | |
| 2013 | |
| 2014 | class MochiAttentionPool(nn.Module): |