| 132 | |
| 133 | |
| 134 | class PositionalEncoding(nn.Module): |
| 135 | |
| 136 | def __init__(self, d_model, dropout, max_len=7000): |
| 137 | super(PositionalEncoding, self).__init__() |
| 138 | self.dropout = nn.Dropout(p=dropout) |
| 139 | |
| 140 | pe = torch.zeros(max_len, d_model) |
| 141 | position = torch.arange(0, max_len).unsqueeze(1).float() |
| 142 | div_term = torch.exp(torch.arange(0, d_model, 2).float() * |
| 143 | -(math.log(10000.0) / d_model)) |
| 144 | pe[:, 0::2] = torch.sin(position * div_term) |
| 145 | pe[:, 1::2] = torch.cos(position * div_term) |
| 146 | pe = pe.unsqueeze(0) |
| 147 | self.register_buffer('pe', pe) |
| 148 | |
| 149 | def forward(self, x): |
| 150 | x = x + Variable(self.pe[:, :x.size(1)], |
| 151 | requires_grad=False) |
| 152 | return self.dropout(x) |
| 153 | |
| 154 | |
| 155 | class MultiHeadedAttention(nn.Module): |