| 44 | |
| 45 | class Attention(nn.Module): |
| 46 | def __init__(self, dim, heads = 8, dim_head = 64, dropout = 0.): |
| 47 | super().__init__() |
| 48 | inner_dim = dim_head * heads |
| 49 | project_out = not (heads == 1 and dim_head == dim) |
| 50 | |
| 51 | self.heads = heads |
| 52 | self.scale = dim_head ** -0.5 |
| 53 | |
| 54 | self.norm = nn.LayerNorm(dim) |
| 55 | self.attend = nn.Softmax(dim = -1) |
| 56 | self.dropout = nn.Dropout(dropout) |
| 57 | |
| 58 | self.to_qkv = nn.Linear(dim, inner_dim * 3, bias = False) |
| 59 | |
| 60 | self.to_out = nn.Sequential( |
| 61 | nn.Linear(inner_dim, dim), |
| 62 | nn.Dropout(dropout) |
| 63 | ) if project_out else nn.Identity() |
| 64 | |
| 65 | def forward(self, x): |
| 66 | x = self.norm(x) |