Skip to content
fn

pad_packed_sequence

→Tensor
pad_packed_sequence(sequence: PackedSequence, batch_first: bool = False, padding_value: float = 0.0, total_length: int | None = None)

Inverse of pack_padded_sequence — produce a padded tensor.

Re-inflates a PackedSequence into a dense (Tmax,B,∗)(T_\text{max}, B, *) (or (B,Tmax,∗)(B, T_\text{max}, *)) tensor with the original batch order restored. The freshly created cells beyond each sequence's true length are filled with padding_value.

Parameters

Packed batch to unpack.
batch_firstbool= False
Output layout. False (default) yields (T, B, *), True yields (B, T, *).
padding_valuefloat= 0.0
Fill value for padded entries. Default 0.0.
total_lengthint= None
If given, pad up to this length instead of the longest packed sequence. Useful when downstream code expects a fixed T_max (e.g. fully-static export graphs). Must be >= the longest sequence.

Returns

Tensor

Padded batch tensor, on the packed data's device.

Raises

ValueError
If total_length is shorter than the longest sequence, if batch_sizes is not a non-empty non-increasing run of positive counts summing to the packed row count, or if unsorted_indices is not a permutation of the batch.

Notes

Output time dimension is max⁡bℓb\max_b \ell_b (or total_length when given). The function honours unsorted_indices on the packed sequence so the rows of the returned tensor match the order the caller used at pack time.

Examples

>>> import lucid
>>> from lucid.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
>>> x = lucid.randn(3, 4, 5)                 # (B=3, T=4, F=5)
>>> packed = pack_padded_sequence(x, lengths=[4, 3, 2], batch_first=True)
>>> padded, lens = pad_packed_sequence(packed, batch_first=True)
>>> padded.shape, lens.tolist()
((3, 4, 5), [4, 3, 2])

Used by 1