| 79 | """ |
| 80 | |
| 81 | def __init__(self, d_model, dropout=0.1, max_len=5000): |
| 82 | super(PositionalEncoding, self).__init__() |
| 83 | self.dropout = nn.Dropout(p=dropout) |
| 84 | |
| 85 | pe = torch.zeros(max_len, d_model) |
| 86 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 87 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) |
| 88 | pe[:, 0::2] = torch.sin(position * div_term) |
| 89 | pe[:, 1::2] = torch.cos(position * div_term) |
| 90 | pe = pe.unsqueeze(0).transpose(0, 1) |
| 91 | self.register_buffer('pe', pe) |
| 92 | |
| 93 | def forward(self, x): |
| 94 | r"""Inputs of forward function |