| 692 | |
| 693 | class PositionalEncoding(nn.Module): |
| 694 | def __init__( |
| 695 | self, |
| 696 | d_model, |
| 697 | dropout = 0., |
| 698 | max_len = 24 |
| 699 | ): |
| 700 | super().__init__() |
| 701 | self.dropout = nn.Dropout(p=dropout) |
| 702 | position = torch.arange(max_len).unsqueeze(1) |
| 703 | div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)) |
| 704 | pe = torch.zeros(1, max_len, d_model) |
| 705 | pe[0, :, 0::2] = torch.sin(position * div_term) |
| 706 | pe[0, :, 1::2] = torch.cos(position * div_term) |
| 707 | self.register_buffer('pe', pe) |
| 708 | |
| 709 | def forward(self, x): |
| 710 | x = x + self.pe[:, :x.size(1)] |