| 6 | |
| 7 | |
| 8 | class PositionalEmbedding(nn.Module): |
| 9 | def __init__(self, d_model, max_len=5000): |
| 10 | super(PositionalEmbedding, self).__init__() |
| 11 | # Compute the positional encodings once in log space. |
| 12 | pe = torch.zeros(max_len, d_model).float() |
| 13 | pe.require_grad = False |
| 14 | |
| 15 | position = torch.arange(0, max_len).float().unsqueeze(1) |
| 16 | div_term = (torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)).exp() |
| 17 | |
| 18 | pe[:, 0::2] = torch.sin(position * div_term) |
| 19 | pe[:, 1::2] = torch.cos(position * div_term) |
| 20 | |
| 21 | pe = pe.unsqueeze(0) |
| 22 | self.register_buffer('pe', pe) |
| 23 | |
| 24 | def forward(self, x): |
| 25 | return self.pe[:, :x.size(1)] |
| 26 | |
| 27 | |
| 28 | class TokenEmbedding(nn.Module): |