| 260 | |
| 261 | |
| 262 | class PositionalEncoding(nn.Module): |
| 263 | def __init__(self, d_model, dropout=0.0, max_len=24): |
| 264 | super().__init__() |
| 265 | self.dropout = nn.Dropout(p=dropout) |
| 266 | position = torch.arange(max_len).unsqueeze(1) |
| 267 | div_term = torch.exp( |
| 268 | torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model) |
| 269 | ) |
| 270 | pe = torch.zeros(1, max_len, d_model) |
| 271 | pe[0, :, 0::2] = torch.sin(position * div_term) |
| 272 | pe[0, :, 1::2] = torch.cos(position * div_term) |
| 273 | self.register_buffer("pe", pe) |
| 274 | |
| 275 | def forward(self, x): |
| 276 | x = x + self.pe[:, : x.size(1)] |
| 277 | return self.dropout(x) |
| 278 | |
| 279 | |
| 280 | class VersatileAttention(Attention): |