Args: inputs: seq_lengths: init_state: ori_state: If true, will return ori state generate by rnn. Else will will return formatted state :return:
(self, inputs, seq_lengths=None, init_state=None,
ori_state=False)
| 61 | rnn_type, RNNType.str())) |
| 62 | |
| 63 | def forward(self, inputs, seq_lengths=None, init_state=None, |
| 64 | ori_state=False): |
| 65 | """ |
| 66 | Args: |
| 67 | inputs: |
| 68 | seq_lengths: |
| 69 | init_state: |
| 70 | ori_state: If true, will return ori state generate by rnn. Else will |
| 71 | will return formatted state |
| 72 | :return: |
| 73 | """ |
| 74 | if seq_lengths is not None: |
| 75 | seq_lengths = seq_lengths.int() |
| 76 | sorted_seq_lengths, indices = torch.sort(seq_lengths, |
| 77 | descending=True) |
| 78 | if self.batch_first: |
| 79 | sorted_inputs = inputs[indices] |
| 80 | else: |
| 81 | sorted_inputs = inputs[:, indices] |
| 82 | packed_inputs = torch.nn.utils.rnn.pack_padded_sequence( |
| 83 | sorted_inputs, sorted_seq_lengths.cpu(), batch_first=self.batch_first) |
| 84 | outputs, state = self.rnn(packed_inputs, init_state) |
| 85 | else: |
| 86 | outputs, state = self.rnn(inputs, init_state) |
| 87 | |
| 88 | if ori_state: |
| 89 | return outputs, state |
| 90 | if self.rnn_type == RNNType.LSTM: |
| 91 | state = state[0] |
| 92 | if self.bidirectional: |
| 93 | last_layers_hn = state[2 * (self.num_layers - 1):] |
| 94 | last_layers_hn = torch.cat( |
| 95 | (last_layers_hn[0], last_layers_hn[1]), 1) |
| 96 | else: |
| 97 | last_layers_hn = state[self.num_layers - 1:] |
| 98 | last_layers_hn = last_layers_hn[0] |
| 99 | |
| 100 | _, revert_indices = torch.sort(indices, descending=False) |
| 101 | last_layers_hn = last_layers_hn[revert_indices] |
| 102 | pad_output, _ = torch.nn.utils.rnn.pad_packed_sequence( |
| 103 | outputs, batch_first=self.batch_first) |
| 104 | if self.batch_first: |
| 105 | pad_output = pad_output[revert_indices] |
| 106 | else: |
| 107 | pad_output = pad_output[:, revert_indices] |
| 108 | return pad_output, last_layers_hn |
nothing calls this directly
no outgoing calls
no test coverage detected