1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class LSTMCell(nn.Module): def __init__( self, input_dim, hidden_dim ): super().__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.fc3 = nn.Linear(input_dim, hidden_dim) self.fc4 = nn.Linear(hidden_dim, hidden_dim) self.fc5 = nn.Linear(input_dim, hidden_dim) self.fc6 = nn.Linear(hidden_dim, hidden_dim) self.fc7 = nn.Linear(input_dim, hidden_dim) self.fc8 = nn.Linear(hidden_dim, hidden_dim) def forward(self, x, lm, sm): lm = lm * F.sigmoid(self.fc1(x) + self.fc2(sm)) new_lm = F.tanh(self.fc3(x) + self.fc4(sm)) new_lm = F.sigmoid(self.fc5(x) + self.fc6(sm)) * new_lm lm = lm + new_lm sm = F.sigmoid(self.fc7(x) + self.fc8(sm)) * F.tanh(lm) return lm, sm class LSTM(nn.Module): def __init__( self, input_dim, hidden_dim ): super().__init__() self.hidden_dim = hidden_dim self.cell = LSTMCell(input_dim, hidden_dim) def forward(self, x): B, T, C = x.shape lm = torch.zeros((B, self.hidden_dim), device=x.device) sm = torch.zeros((B, self.hidden_dim), device=x.device) outputs = [] for t in range(T): lm, sm = self.cell(x[:, t, :], lm, sm) outputs.append(sm) return torch.stack(outputs, dim=1)
|