torch.nn.utils.pack_padded_sequence
function pack_padded_sequence(input: Tensor, lengths: number[], options?: PackPaddedSequenceOptions): PackedSequencefunction pack_padded_sequence(input: Tensor, lengths: number[], batch_first: boolean, enforce_sorted: boolean, options?: PackPaddedSequenceOptions): PackedSequencePacks a Tensor containing padded sequences of variable length.
input must be of size T x B x * where T is the length of the longest sequence (equal to lengths[0]), B is the batch size, and
- is any number of dimensions (including 0).
For unsorted sequences, use enforce_sorted=false.
Parameters
inputTensor- Padded batch of variable length sequences
lengthsnumber[]- List of sequence lengths of each batch element
optionsPackPaddedSequenceOptionsoptional- Optional settings for packing
Returns
PackedSequence– A PackedSequence objectExamples
const sequences = torch.tensor([
[[1, 2], [3, 4], [5, 6]], // length 3
[[7, 8], [9, 10], [0, 0]], // length 2 (padded)
[[11, 12], [0, 0], [0, 0]] // length 1 (padded)
]); // shape: [3, 3, 2] (batch_first)
const lengths = [3, 2, 1];
const packed = await torch.nn.utils.rnn.pack_padded_sequence(sequences, lengths, { batch_first: true });