| 187 | |
| 188 | class BertSelfAttention(nn.Module): |
| 189 | def __init__(self, config): |
| 190 | super().__init__() |
| 191 | if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): |
| 192 | raise ValueError( |
| 193 | "The hidden size (%d) is not a multiple of the number of attention " |
| 194 | "heads (%d)" % (config.hidden_size, config.num_attention_heads) |
| 195 | ) |
| 196 | |
| 197 | self.num_attention_heads = config.num_attention_heads |
| 198 | self.attention_head_size = int(config.hidden_size / config.num_attention_heads) |
| 199 | self.all_head_size = self.num_attention_heads * self.attention_head_size |
| 200 | |
| 201 | self.query = nn.Linear(config.hidden_size, self.all_head_size) |
| 202 | self.key = nn.Linear(config.hidden_size, self.all_head_size) |
| 203 | self.value = nn.Linear(config.hidden_size, self.all_head_size) |
| 204 | |
| 205 | self.dropout = nn.Dropout(config.attention_probs_dropout_prob) |
| 206 | |
| 207 | def transpose_for_scores(self, x): |
| 208 | new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) |