| 24 | |
| 25 | |
| 26 | class PositionalEncoding(nn.Module): |
| 27 | def __init__(self, model_dim: int, max_len: int = 5000) -> None: |
| 28 | super(PositionalEncoding, self).__init__() |
| 29 | pe = torch.zeros(max_len, model_dim) |
| 30 | position = torch.arange(0, max_len).float().unsqueeze(1) |
| 31 | exponent = torch.arange(0, model_dim, 2).float() * -(math.log(10000.0) / model_dim) |
| 32 | div_term = torch.exp(exponent) |
| 33 | pe[:, 0::2] = torch.sin(position * div_term) |
| 34 | pe[:, 1::2] = torch.cos(position * div_term) |
| 35 | self.pos_enc = pe |
| 36 | |
| 37 | def forward(self, x: Tensor) -> Tensor: |
| 38 | return x + self.pos_enc[:x.shape[2]].cuda() |
| 39 | |
| 40 | |
| 41 | class SelfAttention(nn.Module): |