| 282 | |
| 283 | |
| 284 | class PositionalEncoding(nn.Module): |
| 285 | def __init__(self, d_model, max_len=5000): |
| 286 | super().__init__() |
| 287 | assert d_model % 2 == 0 |
| 288 | pe = torch.zeros(max_len, d_model, requires_grad=False) |
| 289 | position = torch.arange(0, max_len).unsqueeze(1).float() |
| 290 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * |
| 291 | -(torch.log(torch.tensor(10000.0)).item()/d_model)) |
| 292 | pe[:, 0::2] = torch.sin(position * div_term) |
| 293 | pe[:, 1::2] = torch.cos(position * div_term) |
| 294 | pe = pe.unsqueeze(0) |
| 295 | self.register_buffer('pe', pe) |
| 296 | |
| 297 | def forward(self, x): |
| 298 | length = x.size(1) |
| 299 | return self.pe[:, :length].clone().detach() |