Skip to content

Instantly share code, notes, and snippets.

@mmsamiei
Created June 28, 2022 07:59
Show Gist options
  • Save mmsamiei/e2ff97edf709cda96c77bc176d8f403d to your computer and use it in GitHub Desktop.
Save mmsamiei/e2ff97edf709cda96c77bc176d8f403d to your computer and use it in GitHub Desktop.
sinusoid position embedding in pytorch
class PositionalEncoding(nn.Module):
def __init__(self, d_model: int, dropout: float = 0.1, max_len: int = 5000):
super().__init__()
self.dropout = nn.Dropout(p=dropout)
position = torch.arange(max_len).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
pe = torch.zeros(max_len, 1, d_model)
pe[:, 0, 0::2] = torch.sin(position * div_term)
pe[:, 0, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe)
def forward(self, x):
"""
Args:
x: Tensor, shape [batch_size, seq_len, embedding_dim]
x: Tensor, shape [seq_len, batch_size, embedding_dim]
"""
temp = torch.permute(x, (1, 0, 2))
temp = self.pe[:temp.size(0)]
temp = torch.permute(temp, (1, 0, 2))
temp = temp.repeat(x.shape[0], 1, 1)
#temp = torch.permute(x, (1, 0, 2))
return self.dropout(temp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment