Inject some information about the relative or absolute position of the tokens in the sequence. The positional encodings have the same dimension as the embeddings, so that the two can be summed. Here, we use sine and cosine functions of different frequencies. .. math:: \text{
| 306 | |
| 307 | |
| 308 | class PositionalEncoding(nn.Module): |
| 309 | """Inject some information about the relative or absolute position of the |
| 310 | tokens in the sequence. The positional encodings have the same dimension as |
| 311 | the embeddings, so that the two can be summed. Here, we use sine and cosine |
| 312 | functions of different frequencies. |
| 313 | |
| 314 | .. math:: |
| 315 | \text{PosEncoder}(pos, 2i) = sin(pos/10000^(2i/d_model)) |
| 316 | \text{PosEncoder}(pos, 2i+1) = cos(pos/10000^(2i/d_model)) |
| 317 | \text{where pos is the word position and i is the embed idx) |
| 318 | Args: |
| 319 | d_model: the embed dim (required). |
| 320 | dropout: the dropout value (default=0.1). |
| 321 | max_len: the max. length of the incoming sequence (default=5000). |
| 322 | Examples: |
| 323 | >>> pos_encoder = PositionalEncoding(d_model) |
| 324 | """ |
| 325 | |
| 326 | def __init__(self, dropout, dim, max_len=5000): |
| 327 | super(PositionalEncoding, self).__init__() |
| 328 | self.dropout = nn.Dropout(p=dropout) |
| 329 | |
| 330 | pe = torch.zeros([max_len, dim]) |
| 331 | position = torch.arange(0, max_len, dtype=torch.float32).unsqueeze(1) |
| 332 | div_term = torch.exp( |
| 333 | torch.arange(0, dim, 2).float() * (-math.log(10000.0) / dim)) |
| 334 | pe[:, 0::2] = torch.sin(position * div_term) |
| 335 | pe[:, 1::2] = torch.cos(position * div_term) |
| 336 | pe = torch.unsqueeze(pe, 0) |
| 337 | # pe = torch.permute(pe, [1, 0, 2]) |
| 338 | self.register_buffer('pe', pe) |
| 339 | |
| 340 | def forward(self, x): |
| 341 | """Inputs of forward function |
| 342 | Args: |
| 343 | x: the sequence fed to the positional encoder model (required). |
| 344 | Shape: |
| 345 | x: [sequence length, batch size, embed dim] |
| 346 | output: [sequence length, batch size, embed dim] |
| 347 | Examples: |
| 348 | >>> output = pos_encoder(x) |
| 349 | """ |
| 350 | # x = x.permute([1, 0, 2]) |
| 351 | # x = x + self.pe[:x.shape[0], :] |
| 352 | x = x + self.pe[:, :x.shape[1], :] |
| 353 | return self.dropout(x) # .permute([1, 0, 2]) |
| 354 | |
| 355 | |
| 356 | class PositionalEncoding_2d(nn.Module): |
no outgoing calls
no test coverage detected