| 20 | import torch.nn.functional as F |
| 21 | |
| 22 | class PositionalEncoding(nn.Module): |
| 23 | def __init__(self, embed_dim, max_len=1000): |
| 24 | super(PositionalEncoding, self).__init__() |
| 25 | pe = torch.zeros(max_len, embed_dim) |
| 26 | position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) |
| 27 | div_term = torch.exp(torch.arange(0, embed_dim, 2).float() * (-math.log(10000.0) / embed_dim)) |
| 28 | pe[:, 0::2] = torch.sin(position * div_term) |
| 29 | pe[:, 1::2] = torch.cos(position * div_term) |
| 30 | pe = pe.unsqueeze(0).transpose(0, 1) |
| 31 | self.register_buffer('pe', pe) |
| 32 | |
| 33 | def forward(self, x): |
| 34 | x = x + self.pe[:x.size(0), :] |
| 35 | return x |
| 36 | |
| 37 | class EncoderBlock(nn.Module): |
| 38 | def __init__(self, embed_dim, n_heads, dropout): |