code: def test_forward_pulls_out_correct_tensor_with_sequence_lengths(self):
      lstm = LSTM(
          bidirectional=True,
          num_layers=3,
          input_size=3,
          hidden_size=7,
          batch_first=True,
      )
      encoder = PytorchSeq2VecWrapper(lstm)
  
      input_tensor = torch.rand([5, 7, 3])
      input_tensor[1, 6:, :] = 0
      input_tensor[2, 4:, :] = 0
      input_tensor[3, 2:, :] = 0
      input_tensor[4, 1:, :] = 0
      mask = torch.ones(5, 7)
      mask[1, 6:] = 0
      mask[2, 4:] = 0
      mask[3, 2:] = 0
      mask[4, 1:] = 0
  
      sequence_lengths = get_lengths_from_binary_sequence_mask(mask)
      packed_sequence = pack_padded_sequence(
          input_tensor, sequence_lengths.tolist(), batch_first=True
      )
      _, state = lstm(packed_sequence)
      # Transpose output state, extract the last forward and backward states and
      # reshape to be of dimension (batch_size, 2 * hidden_size).
      reshaped_state = state[0].transpose(0, 1)[:, -2:, :].contiguous()
      explicitly_concatenated_state = torch.cat(
          [
              reshaped_state[:, 0, :].squeeze(1),
              reshaped_state[:, 1, :].squeeze(1),
          ],
          -1,
      )
      encoder_output = encoder(input_tensor, mask)
      assert_almost_equal(
          encoder_output.data.numpy(),
          explicitly_concatenated_state.data.numpy(),
      )
  
file_path: magnitude/pymagnitude/third_party/allennlp/tests/modules/seq2vec_encoders/pytorch_seq2vec_wrapper_test.py
imports: from __future__ import with_statement
  from __future__ import absolute_import
  import pytest
  from numpy.testing import assert_almost_equal
  import torch
  from torch.nn import LSTM
  from torch.nn.utils.rnn import pack_padded_sequence
  from allennlp.common.checks import ConfigurationError
  from allennlp.common.testing import AllenNlpTestCase
  from allennlp.modules.seq2vec_encoders import PytorchSeq2VecWrapper
  from allennlp.nn.util import sort_batch_by_length, get_lengths_from_binary_sequence_mask
label_desc: Use image node_id 3 for calling the TestPytorchSeq2VecWrapper obj's underlying member method code with example usage: obj.test_forward_pulls_out_correct_tensor_with_sequence_lengths() without return types