| 14 | class PositionalEncoding(nn.Module): |
| 15 | |
| 16 | def __init__(self, d_model, dropout=0.0, max_len=5000): |
| 17 | super(PositionalEncoding, self).__init__() |
| 18 | self.dropout = nn.Dropout(p=dropout) |
| 19 | |
| 20 | pe = torch.zeros(max_len, d_model) |
| 21 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 22 | div_term = torch.arange(0, d_model, 2).float() * \ |
| 23 | (-np.log(10000.0) / d_model) |
| 24 | div_term = torch.exp(div_term) |
| 25 | pe[:, 0::2] = torch.sin(position * div_term) |
| 26 | pe[:, 1::2] = torch.cos(position * div_term) |
| 27 | # pe = pe.unsqueeze(0)#.transpose(0, 1) |
| 28 | |
| 29 | self.register_buffer('pe', pe) |
| 30 | |
| 31 | def forward(self, x): |
| 32 | # not used in the final model |