| 198 | class PositionalEncoding(nn.Module): |
| 199 | "Implement the PE function." |
| 200 | def __init__(self, d_model, dropout, max_len=5000): |
| 201 | super(PositionalEncoding, self).__init__() |
| 202 | self.dropout = nn.Dropout(p=dropout) |
| 203 | |
| 204 | # Compute the positional encodings once in log space. |
| 205 | pe = torch.zeros(max_len, d_model).to(device) |
| 206 | position = torch.arange(0, max_len).unsqueeze(1) |
| 207 | div_term = torch.exp(torch.arange(0, d_model, 2) * |
| 208 | -(math.log(10000.0) / d_model)) |
| 209 | pe[:, 0::2] = torch.sin(position * div_term) |
| 210 | pe[:, 1::2] = torch.cos(position * div_term) |
| 211 | pe = pe.unsqueeze(0) |
| 212 | self.register_buffer('pe', pe) |
| 213 | |
| 214 | def forward(self, x): |
| 215 | x = x + self.pe[:, :x.size(1)] |