forked from graphnet-team/graphnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dd504bd
commit e30b52a
Showing
1 changed file
with
27 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
"""Classes for performing embedding of input data.""" | ||
import torch | ||
|
||
|
||
class SinusoidalPosEmb(torch.nn.Module): | ||
"""Sinusoidal positional embedding layer.""" | ||
|
||
def __init__(self, dim: int = 16, M: int = 10000) -> None: | ||
"""Construct `SinusoidalPosEmb`. | ||
Args: | ||
dim: Embedding dimension. | ||
M: Number of frequencies. | ||
""" | ||
super().__init__() | ||
self.dim = dim | ||
self.M = M | ||
|
||
def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
"""Apply learnable forward pass to the layer.""" | ||
device = x.device | ||
half_dim = self.dim | ||
emb = torch.log(torch.tensor(self.M, device=device)) / half_dim | ||
emb = torch.exp(torch.arange(half_dim, device=device) * (-emb)) | ||
emb = x[..., None] * emb[None, ...] | ||
emb = torch.cat((emb.sin(), emb.cos()), dim=-1) | ||
return emb |