Functions 7
invert_permutation
functionFull reference ↗- tensorplay.nn.utils.rnn.invert_permutation(permutation: TensorBase | None) TensorBase | None[source]
Returns the inverse of
permutation.This is useful for converting between sorted and unsorted indices in a
PackedSequence.- Parameters:
permutation (Tensor, optional) – a 1-D tensor of indices to invert
pack_padded_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.pack_padded_sequence(input: TensorBase, lengths, batch_first: bool = False, enforce_sorted: bool = True) PackedSequence[source]
Packs a Tensor containing padded sequences of variable length.
inputcan be of sizeT x B x *(ifbatch_firstisFalse) orB x T x *(ifbatch_firstisTrue) whereTis the length of the longest sequence,Bis the batch size, and*is any number of dimensions (including 0).For unsorted sequences, use enforce_sorted = False. If
enforce_sortedisTrue, the sequences should be sorted by length in a decreasing order, i.e.input[:,0]should be the longest sequence, andinput[:,B-1]the shortest one. enforce_sorted = True is only necessary for ONNX export.It is an inverse operation to
pad_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. You can apply it to pack the labels, and use the output of the RNN with them to compute the loss directly. A Tensor can be retrieved from a
PackedSequenceobject by accessing its.dataattribute.- Parameters:
input (Tensor) – padded batch of variable length sequences.
lengths (Tensor or list(int)) – list of sequence lengths of each batch element (must be on the CPU if provided as a tensor).
batch_first (bool, optional) – if
True, the input is expected inB x T x *format,T x B x *otherwise. Default:False.enforce_sorted (bool, optional) – if
True, the input is expected to contain sequences sorted by length in a decreasing order. IfFalse, the input will get sorted unconditionally. Default:True.
Warning
The dim of
inputtensor will be truncated if its length larger than correspond value inlength.- Returns:
a
PackedSequenceobject
pack_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.pack_sequence(sequences, enforce_sorted: bool = True) PackedSequence[source]
Packs a list of variable length Tensors.
Consecutive call of the next functions:
pad_sequence,pack_padded_sequence.sequencesshould be a list of Tensors of sizeL x *, where L is the length of a sequence and*is any number of trailing dimensions, including0.For unsorted sequences, use enforce_sorted = False. If
enforce_sortedisTrue, the sequences should be sorted in the order of decreasing length. enforce_sorted = True is only necessary for ONNX export.Example
>>> from tensorplay.nn.utils.rnn import pack_sequence >>> a = tp.tensor([1, 2, 3]) >>> b = tp.tensor([4, 5]) >>> c = tp.tensor([6]) >>> pack_sequence([a, b, c]) PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)- Parameters:
- Returns:
a
PackedSequenceobject
pad_packed_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.pad_packed_sequence(sequence: PackedSequence, batch_first: bool = False, padding_value: float = 0.0, total_length: int | None = None)[source]
Pad a packed batch of variable length sequences.
It is an inverse operation to
pack_padded_sequence().The returned Tensor’s data will be of size
T x B x *(ifbatch_firstisFalse) orB x T x *(ifbatch_firstisTrue) , whereTis the length of the longest sequence andBis the batch size.Example
>>> from tensorplay.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence >>> seq = tp.tensor([[1, 2, 0], [3, 0, 0], [4, 5, 6]]) >>> lens = [2, 1, 3] >>> packed = pack_padded_sequence( ... seq, lens, batch_first=True, enforce_sorted=False ... ) >>> packed PackedSequence(data=tensor([4, 1, 3, 5, 2, 6]), batch_sizes=tensor([3, 2, 1]), sorted_indices=tensor([2, 0, 1]), unsorted_indices=tensor([1, 2, 0])) >>> seq_unpacked, lens_unpacked = pad_packed_sequence(packed, batch_first=True) >>> seq_unpacked tensor([[1, 2, 0], [3, 0, 0], [4, 5, 6]]) >>> lens_unpacked tensor([2, 1, 3])Note
total_lengthis useful to implement thepack sequence -> recurrent network -> unpack sequencepattern in a model wrapped in DataParallel.- Parameters:
sequence (PackedSequence) – batch to pad
batch_first (bool, optional) – if
True, the output will be inB x T x *format,T x B x *otherwise.padding_value (float, optional) – values for padded elements.
total_length (int, optional) – if not
None, the output will be padded to have lengthtotal_length. This method will throwValueErroriftotal_lengthis less than the max sequence length insequence.
- Returns:
Tuple of Tensor containing the padded sequence, and a Tensor containing the list of lengths of each sequence in the batch. Batch elements will be re-ordered as they were ordered originally when the batch was passed to
pack_padded_sequence()orpack_sequence().
pad_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.pad_sequence(sequences, batch_first: bool = False, padding_value: float = 0.0, padding_side: str = 'right') TensorBase[source]
Pad a list of variable length Tensors with
padding_value.pad_sequencestacks a list of Tensors along a new dimension, and pads them to equal length.sequencescan be list of sequences with sizeL x *, where L is length of the sequence and*is any number of dimensions (including0). Ifbatch_firstisFalse, the output is of sizeT x B x *, andB x T x *otherwise, whereBis the batch size (the number of elements insequences`),Tis the length of the longest sequence.Example
>>> from tensorplay.nn.utils.rnn import pad_sequence >>> a = tp.ones(25, 300) >>> b = tp.ones(22, 300) >>> c = tp.ones(15, 300) >>> pad_sequence([a, b, c]).size() tensorplay.Size([25, 3, 300])Note
This function returns a Tensor of size
T x B x *orB x T x *where T is the length of the longest sequence. This function assumes trailing dimensions and type of all the Tensors in sequences are same.- Parameters:
sequences (list[Tensor]) – list of variable length sequences.
batch_first (bool, optional) – if
True, the output will be inB x T x *format,T x B x *otherwise. Default:False.padding_value (float, optional) – value for padded elements. Default:
0.padding_side (str, optional) – the side to pad the sequences on. Default:
'right'.
- Returns:
Tensor of size
T x B x *ifbatch_firstisFalse. Tensor of sizeB x T x *otherwise
unpack_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.unpack_sequence(packed_sequences: PackedSequence)[source]
Unpack PackedSequence into a list of variable length Tensors.
packed_sequencesshould be a PackedSequence object.Example
>>> from tensorplay.nn.utils.rnn import pack_sequence, unpack_sequence >>> a = tp.tensor([1, 2, 3]) >>> b = tp.tensor([4, 5]) >>> c = tp.tensor([6]) >>> sequences = [a, b, c] >>> packed_sequences = pack_sequence(sequences) >>> unpacked_sequences = unpack_sequence(packed_sequences)- Parameters:
packed_sequences (PackedSequence) – A PackedSequence object.
- Returns:
a list of
Tensorobjects
unpad_sequence
functionFull reference ↗- tensorplay.nn.utils.rnn.unpad_sequence(padded_sequences: TensorBase, lengths: TensorBase, batch_first: bool = False)[source]
Unpad padded Tensor into a list of variable length Tensors.
unpad_sequenceunstacks padded Tensor into a list of variable length Tensors.Example
>>> from tensorplay.nn.utils.rnn import pad_sequence, unpad_sequence >>> a = tp.ones(25, 300) >>> b = tp.ones(22, 300) >>> c = tp.ones(15, 300) >>> sequences = [a, b, c] >>> padded_sequences = pad_sequence(sequences) >>> lengths = tp.as_tensor([v.size(0) for v in sequences]) >>> unpadded_sequences = unpad_sequence(padded_sequences, lengths) >>> tp.allclose(sequences[0], unpadded_sequences[0]) True
Classes 1
PackedSequence
classFull reference ↗- class tensorplay.nn.utils.rnn.PackedSequence(data, batch_sizes=None, sorted_indices=None, unsorted_indices=None)[source]
Holds the data and list of
batch_sizesof a packed sequence.All RNN modules accept packed sequences as inputs.
Note
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 dataabcandxthePackedSequencewould contain dataaxbcwithbatch_sizes=[2,1,1].- Variables:
data (Tensor) – Tensor containing packed sequence
batch_sizes (Tensor) – Tensor of integers holding information about the batch size at each sequence step
sorted_indices (Tensor, optional) – Tensor of integers holding how this
PackedSequenceis constructed from sequences.unsorted_indices (Tensor, optional) – Tensor of integers holding how this to recover the original sequences with correct order.
Note
datacan be on arbitrary device and of arbitrary dtype.sorted_indicesandunsorted_indicesmust beint64tensors on the same device asdata.However,
batch_sizesshould always be a CPUint64tensor.This invariant is maintained throughout
PackedSequenceclass, and all functions that construct aPackedSequencein TensorPlay (i.e. they only pass in tensors conforming to this constraint).- batch_sizes: TensorBase
Alias for field number 1
- count(value, /)
Return number of occurrences of value.
- data: TensorBase
Alias for field number 0
- index(value, start=0, stop=9223372036854775807, /)
Return first index of value.
Raises ValueError if the value is not present.
- property is_cuda: bool
Return true if self.data stored on a gpu.
- sorted_indices: TensorBase | None
Alias for field number 2
- to(*args: Any, **kwargs: Any)[source]
Perform dtype and/or device conversion on self.data.
It has similar signature as
tensorplay.Tensor.to()Note
If the
self.dataTensor already has the correcttensorplay.DTypeandtensorplay.Device, thenselfis returned. Otherwise, returns a copy with the desired configuration.
- unsorted_indices: TensorBase | None
Alias for field number 3

