class torch.nn.utils.rnn.PackedSequence[source]

Holds the data and list of batch_sizes of a packed sequence.

All RNN modules accept packed sequences as inputs.


Instances of this class should never be created manually. They are meant to be instantiated by functions like pack_padded_sequence().

Batch sizes represent the number elements at each sequence step in the batch, not the varying sequence lengths passed to pack_padded_sequence(). For instance, given data abc and x the PackedSequence would contain data axbc with batch_sizes=[2,1,1].

  • (Tensor) – Tensor containing packed sequence

  • ~PackedSequence.batch_sizes (Tensor) – Tensor of integers holding information about the batch size at each sequence step

  • ~PackedSequence.sorted_indices (Tensor, optional) – Tensor of integers holding how this PackedSequence is constructed from sequences.

  • ~PackedSequence.unsorted_indices (Tensor, optional) – Tensor of integers holding how this to recover the original sequences with correct order.


data can be on arbitrary device and of arbitrary dtype. sorted_indices and unsorted_indices must be torch.int64 tensors on the same device as data.

However, batch_sizes should always be a CPU torch.int64 tensor.

This invariant is maintained throughout PackedSequence class, and all functions that construct a :class:PackedSequence in PyTorch (i.e., they only pass in tensors conforming to this constraint).

property batch_sizes

Alias for field number 1

count(value) → integer -- return number of occurrences of value
property data

Alias for field number 0

index(value[, start[, stop]]) → integer -- return first index of value.

Raises ValueError if the value is not present.

property is_cuda

Returns true if stored on a gpu


Returns true if stored on in pinned memory

property sorted_indices

Alias for field number 2

to(*args, **kwargs)[source]

Performs dtype and/or device conversion on

It has similar signature as, except optional arguments like non_blocking and copy should be passed as kwargs, not args, or they will not apply to the index tensors.


If the Tensor already has the correct torch.dtype and torch.device, then self is returned. Otherwise, returns a copy with the desired configuration.

property unsorted_indices

Alias for field number 3


Access comprehensive developer documentation for PyTorch

View Docs


Get in-depth tutorials for beginners and advanced developers

View Tutorials


Find development resources and get your questions answered

View Resources