| 294 | |
| 295 | |
| 296 | class PositionalEncoding(nn.Module): |
| 297 | def __init__(self, d_model, dropout=0.1, max_len=5000): |
| 298 | super(PositionalEncoding, self).__init__() |
| 299 | self.dropout = nn.Dropout(p=dropout) |
| 300 | |
| 301 | pe = torch.zeros(max_len, d_model) |
| 302 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 303 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-np.log(10000.0) / d_model)) |
| 304 | pe[:, 0::2] = torch.sin(position * div_term) |
| 305 | pe[:, 1::2] = torch.cos(position * div_term) |
| 306 | pe = pe.unsqueeze(0).transpose(0, 1) |
| 307 | |
| 308 | self.register_buffer('pe', pe) |
| 309 | |
| 310 | def forward(self, x): |
| 311 | # not used in the final model |
| 312 | x = x + self.pe[:x.shape[0], :] |
| 313 | return self.dropout(x) |
| 314 | |
| 315 | |
| 316 | class TimestepEmbedder(nn.Module): |