| 187 | class PositionalEncoding(nn.Module): |
| 188 | |
| 189 | def __init__(self, d_model, dropout=0.1, max_len=5000): |
| 190 | super(PositionalEncoding, self).__init__() |
| 191 | self.dropout = nn.Dropout(p=dropout) |
| 192 | |
| 193 | pe = torch.zeros(max_len, d_model) |
| 194 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 195 | div_term = torch.arange(0, d_model, 2).float() * \ |
| 196 | (-np.log(10000.0) / d_model) |
| 197 | div_term = torch.exp(div_term) |
| 198 | pe[:, 0::2] = torch.sin(position * div_term) |
| 199 | pe[:, 1::2] = torch.cos(position * div_term) |
| 200 | pe = pe.unsqueeze(0).transpose(0, 1) |
| 201 | |
| 202 | self.register_buffer('pe', pe) |
| 203 | |
| 204 | def forward(self, x): |
| 205 | # not used in the final model |