Rate this Page

torch.nn.utils.rnn.pack_padded_sequence#

torch.nn.utils.rnn.pack_padded_sequence(input,lengths,batch_first=False,enforce_sorted=True)[source]#

Packs a Tensor containing padded sequences of variable length.

input can be of sizeTxBx* (ifbatch_first isFalse)orBxTx* (ifbatch_first isTrue) whereT is the lengthof the longest sequence,B is the batch size, and* is any number of dimensions(including 0).

For unsorted sequences, useenforce_sorted = False. Ifenforce_sorted isTrue, the sequences should be sorted by length in a decreasing order, i.e.input[:,0] should be the longest sequence, andinput[:,B-1] the shortestone.enforce_sorted = True is only necessary for ONNX export.

It is an inverse operation topad_packed_sequence(), and hencepad_packed_sequence()can be used to recover the underlying tensor packed inPackedSequence.

Note

This function accepts any input that has at least two dimensions. Youcan apply it to pack the labels, and use the output of the RNN withthem to compute the loss directly. A Tensor can be retrieved fromaPackedSequence object by accessing its.data attribute.

Parameters:
  • input (Tensor) – padded batch of variable length sequences.

  • lengths (Tensor orlist(int)) – list of sequence lengths of each batchelement (must be on the CPU if provided as a tensor).

  • batch_first (bool,optional) – ifTrue, the input is expected inBxTx*format,TxBx* otherwise. Default:False.

  • enforce_sorted (bool,optional) – ifTrue, the input is expected tocontain sequences sorted by length in a decreasing order. IfFalse, the input will get sorted unconditionally. Default:True.

Return type:

PackedSequence

Warning

The dim ofinput tensor will be truncated if its length larger thancorrespond value inlength.

Returns:

aPackedSequence object

Return type:

PackedSequence