| 23 | |
| 24 | |
| 25 | class SinusoidalPositionEncoder(torch.nn.Module): |
| 26 | """ """ |
| 27 | |
| 28 | def __init__(self, d_model=80, dropout_rate=0.1): |
| 29 | """Initialize SinusoidalPositionEncoder. |
| 30 | |
| 31 | Args: |
| 32 | d_model: D Model instance. |
| 33 | dropout_rate: TODO. |
| 34 | """ |
| 35 | super().__init__() |
| 36 | |
| 37 | def encode( |
| 38 | self, positions: torch.Tensor = None, depth: int = None, dtype: torch.dtype = torch.float32 |
| 39 | ): |
| 40 | """Encode. |
| 41 | |
| 42 | Args: |
| 43 | positions: TODO. |
| 44 | depth: TODO. |
| 45 | dtype: TODO. |
| 46 | """ |
| 47 | batch_size = positions.size(0) |
| 48 | positions = positions.type(dtype) |
| 49 | device = positions.device |
| 50 | log_timescale_increment = torch.log(torch.tensor([10000], dtype=dtype, device=device)) / ( |
| 51 | depth / 2 - 1 |
| 52 | ) |
| 53 | inv_timescales = torch.exp( |
| 54 | torch.arange(depth / 2, device=device).type(dtype) * (-log_timescale_increment) |
| 55 | ) |
| 56 | inv_timescales = torch.reshape(inv_timescales, [batch_size, -1]) |
| 57 | scaled_time = torch.reshape(positions, [1, -1, 1]) * torch.reshape( |
| 58 | inv_timescales, [1, 1, -1] |
| 59 | ) |
| 60 | encoding = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim=2) |
| 61 | return encoding.type(dtype) |
| 62 | |
| 63 | def forward(self, x): |
| 64 | """Forward pass for training. |
| 65 | |
| 66 | Args: |
| 67 | x: TODO. |
| 68 | """ |
| 69 | batch_size, timesteps, input_dim = x.size() |
| 70 | positions = torch.arange(1, timesteps + 1, device=x.device)[None, :] |
| 71 | position_encoding = self.encode(positions, input_dim, x.dtype).to(x.device) |
| 72 | |
| 73 | return x + position_encoding |
| 74 | |
| 75 | |
| 76 | class PositionwiseFeedForward(torch.nn.Module): |
no outgoing calls
no test coverage detected
searching dependent graphs…