| 226 | |
| 227 | |
| 228 | class PositionalEncoding(nn.Module): |
| 229 | def __init__( |
| 230 | self, |
| 231 | d_model, |
| 232 | dropout = 0., |
| 233 | max_len = 24 |
| 234 | ): |
| 235 | super().__init__() |
| 236 | self.dropout = nn.Dropout(p=dropout) |
| 237 | position = torch.arange(max_len).unsqueeze(1) |
| 238 | div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)) |
| 239 | pe = torch.zeros(1, max_len, d_model) |
| 240 | pe[0, :, 0::2] = torch.sin(position * div_term) |
| 241 | pe[0, :, 1::2] = torch.cos(position * div_term) |
| 242 | self.register_buffer('pe', pe) |
| 243 | |
| 244 | def forward(self, x): |
| 245 | x = x + self.pe[:, :x.size(1)] |
| 246 | return self.dropout(x) |
| 247 | |
| 248 | |
| 249 | class VersatileAttention(CrossAttention): |