| 11 | |
| 12 | class PositionalEncoding(nn.Module): |
| 13 | def __init__(self, d_model=384, max_len=5000): |
| 14 | super(PositionalEncoding, self).__init__() |
| 15 | pe = torch.zeros(max_len, d_model) |
| 16 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 17 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) |
| 18 | pe[:, 0::2] = torch.sin(position * div_term) |
| 19 | pe[:, 1::2] = torch.cos(position * div_term) |
| 20 | pe = pe.unsqueeze(0) |
| 21 | self.register_buffer('pe', pe) |
| 22 | |
| 23 | def forward(self, x): |
| 24 | b, seq_len, d_model = x.size() |