Download src/PositionalEncoding.py from frankzye/gmock: direct link, hf CLI and curl.
- Browser
- Download file 647 Bytes
-
https://huggingface.co/frankzye/gmock/resolve/main/src/PositionalEncoding.py
- Command line
-
hf download hf://frankzye/gmock/src/PositionalEncoding.py
-
curl -L -o PositionalEncoding.py https://huggingface.co/frankzye/gmock/resolve/main/src/PositionalEncoding.py
647 Bytes
| import math | |
| import torch | |
| from torch import nn | |
| class PositionalEncoding(nn.Module): | |
| def __init__(self, d_model, max_seq_length): | |
| super(PositionalEncoding, self).__init__() | |
| pe = torch.zeros(max_seq_length, d_model) | |
| position = torch.arange(0, max_seq_length, dtype=torch.float).unsqueeze(1) | |
| div_term = torch.exp(torch.arange(0, d_model, 2).float() * -(math.log(10000.0) / d_model)) | |
| pe[:, 0::2] = torch.sin(position * div_term) | |
| pe[:, 1::2] = torch.cos(position * div_term) | |
| self.register_buffer('pe', pe.unsqueeze(0)) | |
| def forward(self, x): | |
| return x + self.pe[:, :x.size(1)] |