| 44 | # Periodic Positional Encoding |
| 45 | class PeriodicPositionalEncoding(nn.Module): |
| 46 | def __init__(self, d_model, dropout=0.1, period=25, max_seq_len=600): |
| 47 | super(PeriodicPositionalEncoding, self).__init__() |
| 48 | self.dropout = nn.Dropout(p=dropout) |
| 49 | pe = torch.zeros(period, d_model) |
| 50 | position = torch.arange(0, period, dtype=torch.float).unsqueeze(1) |
| 51 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) |
| 52 | pe[:, 0::2] = torch.sin(position * div_term) |
| 53 | pe[:, 1::2] = torch.cos(position * div_term) |
| 54 | pe = pe.unsqueeze(0) # (1, period, d_model) |
| 55 | repeat_num = (max_seq_len//period) + 1 |
| 56 | pe = pe.repeat(1, repeat_num, 1) |
| 57 | self.register_buffer('pe', pe) |
| 58 | def forward(self, x): |
| 59 | x = x + self.pe[:, :x.size(1), :] |
| 60 | return self.dropout(x) |