| 6 | |
| 7 | |
| 8 | class SinusoidalPositionalEncoding(nn.Module): |
| 9 | |
| 10 | def __init__(self, d_model, dropout=0.1, max_len=5000): |
| 11 | super(SinusoidalPositionalEncoding, self).__init__() |
| 12 | self.dropout = nn.Dropout(p=dropout) |
| 13 | |
| 14 | pe = torch.zeros(max_len, d_model) |
| 15 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 16 | div_term = torch.arange(0, d_model, 2).float() |
| 17 | div_term = div_term * (-np.log(10000.0) / d_model) |
| 18 | div_term = torch.exp(div_term) |
| 19 | pe[:, 0::2] = torch.sin(position * div_term) |
| 20 | pe[:, 1::2] = torch.cos(position * div_term) |
| 21 | pe = pe.unsqueeze(0).transpose(0, 1) |
| 22 | # T, 1, D |
| 23 | self.register_buffer('pe', pe) |
| 24 | |
| 25 | def forward(self, x): |
| 26 | x = x + self.pe[:x.shape[0]] |
| 27 | return self.dropout(x) |
| 28 | |
| 29 | |
| 30 | class LearnedPositionalEncoding(nn.Module): |