| 35 | |
| 36 | class PositionalEmbedding_new(nn.Module): |
| 37 | def __init__(self, d_model, max_len=5000): |
| 38 | super(PositionalEmbedding_new, self).__init__() |
| 39 | # Compute the positional encodings once in log space. |
| 40 | pe = torch.zeros(max_len, d_model).float() |
| 41 | pe.require_grad = False |
| 42 | |
| 43 | position = torch.arange(0, max_len).float().unsqueeze(1) |
| 44 | div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp() |
| 45 | |
| 46 | pe[:, 0::2] = torch.sin(position * div_term) |
| 47 | pe[:, 1::2] = torch.cos(position * div_term) |
| 48 | |
| 49 | pe = pe.unsqueeze(0) |
| 50 | self.register_buffer('pe', pe) |
| 51 | |
| 52 | def forward(self, x, scale=1): |
| 53 | return self.pe[:, scale:x.size(1)*scale+1:scale] |