| 123 | uses_flash: bool |
| 124 | |
| 125 | def __init__( |
| 126 | self, |
| 127 | embedding_dim: int, |
| 128 | num_heads: int, |
| 129 | causal: bool, |
| 130 | dropout: float, |
| 131 | bias: bool = True, |
| 132 | ): |
| 133 | super().__init__() |
| 134 | if embedding_dim % num_heads != 0: |
| 135 | raise ValueError("embedding_dim should be divisible by num_heads") |
| 136 | |
| 137 | self.embedding_dim = embedding_dim |
| 138 | self.num_heads = num_heads |
| 139 | self.dropout = dropout |
| 140 | self.causal = causal |
| 141 | |
| 142 | # key, query, value projections for all heads, but in a batch |
| 143 | self.attention = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias) |
| 144 | |
| 145 | # output projection |
| 146 | self.projection = nn.Linear(embedding_dim, embedding_dim, bias=bias) |
| 147 | |
| 148 | # regularization |
| 149 | self.attention_dropout = nn.Dropout(dropout) |
| 150 | self.residual_dropout = nn.Dropout(dropout) |
| 151 | |
| 152 | # flash attention makes GPU go brrrrr but support is only in PyTorch >= 2.0 |
| 153 | self.uses_flash = hasattr(F, "scaled_dot_product_attention") |
| 154 | if not self.uses_flash: |
| 155 | print("Using slow attention. Flash Attention requires PyTorch >= 2.0.") |
| 156 | |
| 157 | if self.causal: |
| 158 | self.register_buffer("mask", torch.empty((1, 1, 0, 0), dtype=bool)) |
| 159 | |
| 160 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 161 | # batch size, sequence length, embedding dimensionality |