rnn.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. import warnings
  2. from collections.abc import Iterable
  3. from typing import Any, Callable, NamedTuple, Optional, overload, TypeVar, Union
  4. from typing_extensions import Self
  5. import torch
  6. from torch import _VF, Tensor
  7. __all__ = [
  8. "PackedSequence",
  9. "invert_permutation",
  10. "pack_padded_sequence",
  11. "pad_packed_sequence",
  12. "pad_sequence",
  13. "unpad_sequence",
  14. "pack_sequence",
  15. "unpack_sequence",
  16. ]
  17. _T = TypeVar("_T")
  18. _R = TypeVar("_R")
  19. class PackedSequence_(NamedTuple):
  20. data: torch.Tensor
  21. batch_sizes: torch.Tensor
  22. sorted_indices: Optional[torch.Tensor]
  23. unsorted_indices: Optional[torch.Tensor]
  24. def bind(optional: Optional[_T], fn: Callable[[_T], _R]) -> Optional[_R]:
  25. if optional is None:
  26. return None
  27. return fn(optional)
  28. class PackedSequence(PackedSequence_):
  29. r"""Holds the data and list of :attr:`batch_sizes` of a packed sequence.
  30. All RNN modules accept packed sequences as inputs.
  31. Note:
  32. Instances of this class should never be created manually. They are meant
  33. to be instantiated by functions like :func:`pack_padded_sequence`.
  34. Batch sizes represent the number elements at each sequence step in
  35. the batch, not the varying sequence lengths passed to
  36. :func:`pack_padded_sequence`. For instance, given data ``abc`` and ``x``
  37. the :class:`PackedSequence` would contain data ``axbc`` with
  38. ``batch_sizes=[2,1,1]``.
  39. Attributes:
  40. data (Tensor): Tensor containing packed sequence
  41. batch_sizes (Tensor): Tensor of integers holding
  42. information about the batch size at each sequence step
  43. sorted_indices (Tensor, optional): Tensor of integers holding how this
  44. :class:`PackedSequence` is constructed from sequences.
  45. unsorted_indices (Tensor, optional): Tensor of integers holding how this
  46. to recover the original sequences with correct order.
  47. .. note::
  48. :attr:`data` can be on arbitrary device and of arbitrary dtype.
  49. :attr:`sorted_indices` and :attr:`unsorted_indices` must be ``torch.int64``
  50. tensors on the same device as :attr:`data`.
  51. However, :attr:`batch_sizes` should always be a CPU ``torch.int64`` tensor.
  52. This invariant is maintained throughout :class:`PackedSequence` class,
  53. and all functions that construct a :class:`PackedSequence` in PyTorch
  54. (i.e., they only pass in tensors conforming to this constraint).
  55. """
  56. def __new__(
  57. cls,
  58. data: Tensor,
  59. batch_sizes: Optional[Tensor] = None,
  60. sorted_indices: Optional[Tensor] = None,
  61. unsorted_indices: Optional[Tensor] = None,
  62. ) -> Self:
  63. return super().__new__(
  64. cls,
  65. *_packed_sequence_init_args(
  66. data, batch_sizes, sorted_indices, unsorted_indices
  67. ),
  68. )
  69. # NOTE [ device and dtype of a PackedSequence ]
  70. #
  71. # See the note above in doc string (starting with ":attr:`data` can be on
  72. # arbitrary device...").
  73. def pin_memory(self) -> Self:
  74. # Why not convert `batch_sizes`?
  75. # See NOTE [ device and dtype of a PackedSequence ]
  76. return type(self)(
  77. self.data.pin_memory(),
  78. self.batch_sizes,
  79. bind(self.sorted_indices, lambda t: t.pin_memory()),
  80. bind(self.unsorted_indices, lambda t: t.pin_memory()),
  81. )
  82. @overload
  83. def to(
  84. self,
  85. dtype: torch.dtype,
  86. non_blocking: bool = ...,
  87. copy: bool = ...,
  88. ) -> Self: ...
  89. @overload
  90. def to(
  91. self,
  92. device: Optional[Union[str, torch.device, int]] = ...,
  93. dtype: Optional[torch.dtype] = ...,
  94. non_blocking: bool = ...,
  95. copy: bool = ...,
  96. ) -> Self: ...
  97. @overload
  98. def to(
  99. self,
  100. other: Tensor,
  101. non_blocking: bool = ...,
  102. copy: bool = ...,
  103. ) -> Self: ...
  104. def to(self, *args: Any, **kwargs: Any) -> Self:
  105. r"""Perform dtype and/or device conversion on `self.data`.
  106. It has similar signature as :meth:`torch.Tensor.to`, except optional
  107. arguments like `non_blocking` and `copy` should be passed as kwargs,
  108. not args, or they will not apply to the index tensors.
  109. .. note::
  110. If the ``self.data`` Tensor already has the correct :class:`torch.dtype`
  111. and :class:`torch.device`, then ``self`` is returned.
  112. Otherwise, returns a copy with the desired configuration.
  113. """
  114. # Why not convert `batch_sizes`?
  115. # See NOTE [ device and dtype of a PackedSequence ]
  116. data = self.data.to(*args, **kwargs)
  117. if data is self.data:
  118. return self
  119. else:
  120. # Does not forward device or dtype arg/kwargs, device is set from data.device
  121. kwargs = dict(
  122. filter(lambda t: t[0] != "device" and t[0] != "dtype", kwargs.items())
  123. )
  124. sorted_indices = bind(
  125. self.sorted_indices, lambda t: t.to(data.device, **kwargs)
  126. )
  127. unsorted_indices = bind(
  128. self.unsorted_indices, lambda t: t.to(data.device, **kwargs)
  129. )
  130. return type(self)(data, self.batch_sizes, sorted_indices, unsorted_indices)
  131. def cuda(self, *args: Any, **kwargs: Any) -> Self:
  132. # Tests to see if 'cuda' should be added to kwargs
  133. ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to(
  134. *args, **kwargs
  135. )
  136. if ex.is_cuda:
  137. return self.to(*args, **kwargs)
  138. kwargs["device"] = "cuda"
  139. return self.to(*args, **kwargs)
  140. def cpu(self, *args: Any, **kwargs: Any) -> Self:
  141. ex = torch.tensor((), dtype=self.data.dtype, device=self.data.device).to(
  142. *args, **kwargs
  143. )
  144. if ex.device.type == "cpu":
  145. return self.to(*args, **kwargs)
  146. kwargs["device"] = "cpu"
  147. return self.to(*args, **kwargs)
  148. def double(self) -> Self:
  149. return self.to(dtype=torch.double)
  150. def float(self) -> Self:
  151. return self.to(dtype=torch.float)
  152. def half(self) -> Self:
  153. return self.to(dtype=torch.half)
  154. def long(self) -> Self:
  155. return self.to(dtype=torch.long)
  156. def int(self) -> Self:
  157. return self.to(dtype=torch.int)
  158. def short(self) -> Self:
  159. return self.to(dtype=torch.short)
  160. def char(self) -> Self:
  161. return self.to(dtype=torch.int8)
  162. def byte(self) -> Self:
  163. return self.to(dtype=torch.uint8)
  164. @property
  165. def is_cuda(self) -> bool:
  166. r"""Return true if `self.data` stored on a gpu."""
  167. return self.data.is_cuda
  168. def is_pinned(self) -> bool:
  169. r"""Return true if `self.data` stored on in pinned memory."""
  170. return self.data.is_pinned()
  171. # TorchScript doesn't support constructors on named tuples, so we use this helper
  172. # method to construct PackedSequence
  173. def _packed_sequence_init_args(
  174. data: Tensor,
  175. batch_sizes: Optional[Tensor] = None,
  176. sorted_indices: Optional[Tensor] = None,
  177. unsorted_indices: Optional[Tensor] = None,
  178. ) -> tuple[Tensor, Tensor, Optional[Tensor], Optional[Tensor]]:
  179. # NB: if unsorted_indices is provided, it should be the inverse permutation
  180. # to sorted_indices. Don't assert it here because the PackedSequence ctor
  181. # should only be used internally.
  182. if unsorted_indices is None:
  183. unsorted_indices = invert_permutation(sorted_indices)
  184. # support being called as `PackedSequence(data, batch_sizes, sorted_indices)`
  185. if batch_sizes is not None:
  186. # TODO: Re-enable this check (.type isn't supported in TorchScript)
  187. if batch_sizes.device.type != "cpu":
  188. raise ValueError(
  189. "batch_sizes should always be on CPU. "
  190. "Instances of PackedSequence should never be created manually. "
  191. "They should be instantiated by functions like pack_sequence "
  192. "and pack_padded_sequences in nn.utils.rnn. "
  193. "https://pytorch.org/docs/stable/nn.html#torch.nn.utils.rnn.pack_sequence"
  194. )
  195. return data, batch_sizes, sorted_indices, unsorted_indices
  196. # support being called as `PackedSequence((data, batch_sizes), *, sorted_indices)`
  197. else:
  198. assert isinstance(data, (list, tuple)) and len(data) == 2
  199. return data[0], data[1], sorted_indices, unsorted_indices
  200. def _packed_sequence_init(
  201. data: Tensor,
  202. batch_sizes: Optional[Tensor] = None,
  203. sorted_indices: Optional[Tensor] = None,
  204. unsorted_indices: Optional[Tensor] = None,
  205. ) -> PackedSequence:
  206. data, batch_sizes, sorted_indices, unsorted_indices = _packed_sequence_init_args(
  207. data, batch_sizes, sorted_indices, unsorted_indices
  208. )
  209. return PackedSequence(data, batch_sizes, sorted_indices, unsorted_indices)
  210. def invert_permutation(permutation: Optional[Tensor]) -> Optional[Tensor]:
  211. """Returns the inverse of ``permutation``.
  212. This is useful for converting between sorted and unsorted indices in
  213. a :class:`~nn.utils.rnn.PackedSequence`.
  214. Args:
  215. permutation (Tensor, optional): a 1-D tensor of indices to invert
  216. """
  217. if permutation is None:
  218. return None
  219. output = torch.empty_like(permutation, memory_format=torch.legacy_contiguous_format)
  220. output.scatter_(
  221. 0, permutation, torch.arange(0, permutation.numel(), device=permutation.device)
  222. )
  223. return output
  224. def pack_padded_sequence(
  225. input: Tensor,
  226. lengths: Union[Tensor, list[int]],
  227. batch_first: bool = False,
  228. enforce_sorted: bool = True,
  229. ) -> PackedSequence:
  230. r"""Packs a Tensor containing padded sequences of variable length.
  231. :attr:`input` can be of size ``T x B x *`` (if :attr:`batch_first` is ``False``)
  232. or ``B x T x *`` (if :attr:`batch_first` is ``True``) where ``T`` is the length
  233. of the longest sequence, ``B`` is the batch size, and ``*`` is any number of dimensions
  234. (including 0).
  235. For unsorted sequences, use `enforce_sorted = False`. If :attr:`enforce_sorted` is
  236. ``True``, the sequences should be sorted by length in a decreasing order, i.e.
  237. ``input[:,0]`` should be the longest sequence, and ``input[:,B-1]`` the shortest
  238. one. `enforce_sorted = True` is only necessary for ONNX export.
  239. It is an inverse operation to :func:`pad_packed_sequence`, and hence :func:`pad_packed_sequence`
  240. can be used to recover the underlying tensor packed in :class:`PackedSequence`.
  241. Note:
  242. This function accepts any input that has at least two dimensions. You
  243. can apply it to pack the labels, and use the output of the RNN with
  244. them to compute the loss directly. A Tensor can be retrieved from
  245. a :class:`PackedSequence` object by accessing its ``.data`` attribute.
  246. Args:
  247. input (Tensor): padded batch of variable length sequences.
  248. lengths (Tensor or list(int)): list of sequence lengths of each batch
  249. element (must be on the CPU if provided as a tensor).
  250. batch_first (bool, optional): if ``True``, the input is expected in ``B x T x *``
  251. format, ``T x B x *`` otherwise. Default: ``False``.
  252. enforce_sorted (bool, optional): if ``True``, the input is expected to
  253. contain sequences sorted by length in a decreasing order. If
  254. ``False``, the input will get sorted unconditionally. Default: ``True``.
  255. .. warning::
  256. The dim of ``input`` tensor will be truncated if its length larger than
  257. correspond value in ``length``.
  258. Returns:
  259. a :class:`PackedSequence` object
  260. """
  261. if not isinstance(lengths, torch.Tensor):
  262. if torch._C._get_tracing_state():
  263. warnings.warn(
  264. "pack_padded_sequence has been called with a Python list of "
  265. "sequence lengths. The tracer cannot track the data flow of Python "
  266. "values, and it will treat them as constants, likely rendering "
  267. "the trace incorrect for any other combination of lengths.",
  268. stacklevel=2,
  269. )
  270. lengths = torch.as_tensor(lengths, dtype=torch.int64, device="cpu")
  271. else:
  272. lengths = lengths.to(dtype=torch.int64)
  273. if enforce_sorted:
  274. sorted_indices = None
  275. else:
  276. lengths, sorted_indices = torch.sort(lengths, descending=True)
  277. sorted_indices = sorted_indices.to(input.device)
  278. batch_dim = 0 if batch_first else 1
  279. input = input.index_select(batch_dim, sorted_indices)
  280. data, batch_sizes = _VF._pack_padded_sequence(input, lengths, batch_first)
  281. return _packed_sequence_init(data, batch_sizes, sorted_indices, None)
  282. def pad_packed_sequence(
  283. sequence: PackedSequence,
  284. batch_first: bool = False,
  285. padding_value: float = 0.0,
  286. total_length: Optional[int] = None,
  287. ) -> tuple[Tensor, Tensor]:
  288. r"""Pad a packed batch of variable length sequences.
  289. It is an inverse operation to :func:`pack_padded_sequence`.
  290. The returned Tensor's data will be of size ``T x B x *`` (if :attr:`batch_first` is ``False``)
  291. or ``B x T x *`` (if :attr:`batch_first` is ``True``) , where ``T`` is the length of the longest
  292. sequence and ``B`` is the batch size.
  293. Example:
  294. >>> from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
  295. >>> seq = torch.tensor([[1, 2, 0], [3, 0, 0], [4, 5, 6]])
  296. >>> lens = [2, 1, 3]
  297. >>> packed = pack_padded_sequence(
  298. ... seq, lens, batch_first=True, enforce_sorted=False
  299. ... )
  300. >>> packed
  301. PackedSequence(data=tensor([4, 1, 3, 5, 2, 6]), batch_sizes=tensor([3, 2, 1]),
  302. sorted_indices=tensor([2, 0, 1]), unsorted_indices=tensor([1, 2, 0]))
  303. >>> seq_unpacked, lens_unpacked = pad_packed_sequence(packed, batch_first=True)
  304. >>> seq_unpacked
  305. tensor([[1, 2, 0],
  306. [3, 0, 0],
  307. [4, 5, 6]])
  308. >>> lens_unpacked
  309. tensor([2, 1, 3])
  310. .. note::
  311. :attr:`total_length` is useful to implement the
  312. ``pack sequence -> recurrent network -> unpack sequence`` pattern in a
  313. :class:`~torch.nn.Module` wrapped in :class:`~torch.nn.DataParallel`.
  314. See :ref:`this FAQ section <pack-rnn-unpack-with-data-parallelism>` for
  315. details.
  316. Args:
  317. sequence (PackedSequence): batch to pad
  318. batch_first (bool, optional): if ``True``, the output will be in ``B x T x *``
  319. format, ``T x B x *`` otherwise.
  320. padding_value (float, optional): values for padded elements.
  321. total_length (int, optional): if not ``None``, the output will be padded to
  322. have length :attr:`total_length`. This method will throw :class:`ValueError`
  323. if :attr:`total_length` is less than the max sequence length in
  324. :attr:`sequence`.
  325. Returns:
  326. Tuple of Tensor containing the padded sequence, and a Tensor
  327. containing the list of lengths of each sequence in the batch.
  328. Batch elements will be re-ordered as they were ordered originally when
  329. the batch was passed to ``pack_padded_sequence`` or ``pack_sequence``.
  330. """
  331. max_seq_length = sequence.batch_sizes.size(0)
  332. if total_length is not None:
  333. if total_length < max_seq_length:
  334. raise ValueError(
  335. "Expected total_length to be at least the length "
  336. "of the longest sequence in input, but got "
  337. f"total_length={total_length} and max sequence length being {max_seq_length}"
  338. )
  339. max_seq_length = total_length
  340. padded_output, lengths = _VF._pad_packed_sequence(
  341. sequence.data, sequence.batch_sizes, batch_first, padding_value, max_seq_length
  342. )
  343. unsorted_indices = sequence.unsorted_indices
  344. if unsorted_indices is not None:
  345. batch_dim = 0 if batch_first else 1
  346. return (
  347. padded_output.index_select(batch_dim, unsorted_indices),
  348. lengths[unsorted_indices.cpu()],
  349. )
  350. return padded_output, lengths
  351. # NOTE: for JIT-compatibility, we need to be more restrictive here and use specific types instead of Iterable.
  352. def pad_sequence(
  353. sequences: Union[Tensor, list[Tensor]],
  354. batch_first: bool = False,
  355. padding_value: float = 0.0,
  356. padding_side: str = "right",
  357. ) -> Tensor:
  358. r"""Pad a list of variable length Tensors with :attr:`padding_value`.
  359. ``pad_sequence`` stacks a list of Tensors along a new dimension, and pads them
  360. to equal length. :attr:`sequences` can be list of sequences with size ``L x *``,
  361. where `L` is length of the sequence and ``*`` is any number of dimensions
  362. (including ``0``). If :attr:`batch_first` is ``False``, the output is of size
  363. ``T x B x *``, and ``B x T x *`` otherwise, where ``B`` is the batch size
  364. (the number of elements in :attr:`sequences`), ``T`` is the length of the longest
  365. sequence.
  366. Example:
  367. >>> from torch.nn.utils.rnn import pad_sequence
  368. >>> a = torch.ones(25, 300)
  369. >>> b = torch.ones(22, 300)
  370. >>> c = torch.ones(15, 300)
  371. >>> pad_sequence([a, b, c]).size()
  372. torch.Size([25, 3, 300])
  373. Note:
  374. This function returns a Tensor of size ``T x B x *`` or ``B x T x *``
  375. where `T` is the length of the longest sequence. This function assumes
  376. trailing dimensions and type of all the Tensors in sequences are same.
  377. Args:
  378. sequences (list[Tensor]): list of variable length sequences.
  379. batch_first (bool, optional): if ``True``, the output will be in ``B x T x *``
  380. format, ``T x B x *`` otherwise.
  381. padding_value (float, optional): value for padded elements. Default: ``0``.
  382. padding_side (str, optional): the side to pad the sequences on.
  383. Default: ``'right'``.
  384. Returns:
  385. Tensor of size ``T x B x *`` if :attr:`batch_first` is ``False``.
  386. Tensor of size ``B x T x *`` otherwise
  387. """
  388. if not (torch.jit.is_tracing() or torch.jit.is_scripting()):
  389. # JIT doesn't support `Iterable`
  390. if not isinstance(sequences, Iterable):
  391. msg = (
  392. "pad_sequence: Expected iterable for input sequences, but got arg of type: "
  393. f"{type(sequences)}"
  394. )
  395. raise RuntimeError(msg)
  396. # In JIT context this leads to,
  397. # RuntimeError: cannot statically infer the expected size of a list in this context
  398. sequences = tuple(sequences) # type: ignore[assignment]
  399. else:
  400. # For JIT, we only support Union[Tensor, Tuple[Tensor]]
  401. if isinstance(sequences, torch.Tensor):
  402. sequences = sequences.unbind(0) # type: ignore[assignment]
  403. # assuming trailing dimensions and type of all the Tensors
  404. # in sequences are same and fetching those from sequences[0]
  405. return torch._C._nn.pad_sequence(
  406. sequences, # type: ignore[arg-type]
  407. batch_first,
  408. padding_value,
  409. padding_side, # type: ignore[arg-type]
  410. )
  411. def unpad_sequence(
  412. padded_sequences: Tensor,
  413. lengths: Tensor,
  414. batch_first: bool = False,
  415. ) -> list[Tensor]:
  416. r"""Unpad padded Tensor into a list of variable length Tensors.
  417. ``unpad_sequence`` unstacks padded Tensor into a list of variable length Tensors.
  418. Example:
  419. >>> from torch.nn.utils.rnn import pad_sequence, unpad_sequence
  420. >>> a = torch.ones(25, 300)
  421. >>> b = torch.ones(22, 300)
  422. >>> c = torch.ones(15, 300)
  423. >>> sequences = [a, b, c]
  424. >>> padded_sequences = pad_sequence(sequences)
  425. >>> lengths = torch.as_tensor([v.size(0) for v in sequences])
  426. >>> unpadded_sequences = unpad_sequence(padded_sequences, lengths)
  427. >>> torch.allclose(sequences[0], unpadded_sequences[0])
  428. True
  429. >>> torch.allclose(sequences[1], unpadded_sequences[1])
  430. True
  431. >>> torch.allclose(sequences[2], unpadded_sequences[2])
  432. True
  433. Args:
  434. padded_sequences (Tensor): padded sequences.
  435. lengths (Tensor): length of original (unpadded) sequences.
  436. batch_first (bool, optional): whether batch dimension first or not. Default: ``False``.
  437. Returns:
  438. a list of :class:`Tensor` objects
  439. """
  440. unpadded_sequences = []
  441. if not batch_first:
  442. padded_sequences.transpose_(0, 1)
  443. max_length = padded_sequences.shape[1]
  444. idx = torch.arange(max_length, device=lengths.device)
  445. for seq, length in zip(padded_sequences, lengths):
  446. mask = idx < length
  447. unpacked_seq = seq[mask]
  448. unpadded_sequences.append(unpacked_seq)
  449. return unpadded_sequences
  450. def pack_sequence(
  451. sequences: list[Tensor],
  452. enforce_sorted: bool = True,
  453. ) -> PackedSequence:
  454. r"""Packs a list of variable length Tensors.
  455. Consecutive call of the next functions: ``pad_sequence``, ``pack_padded_sequence``.
  456. ``sequences`` should be a list of Tensors of size ``L x *``, where `L` is
  457. the length of a sequence and `*` is any number of trailing dimensions,
  458. including ``0``.
  459. For unsorted sequences, use `enforce_sorted = False`. If ``enforce_sorted``
  460. is ``True``, the sequences should be sorted in the order of decreasing length.
  461. ``enforce_sorted = True`` is only necessary for ONNX export.
  462. Example:
  463. >>> from torch.nn.utils.rnn import pack_sequence
  464. >>> a = torch.tensor([1, 2, 3])
  465. >>> b = torch.tensor([4, 5])
  466. >>> c = torch.tensor([6])
  467. >>> pack_sequence([a, b, c])
  468. PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)
  469. Args:
  470. sequences (list[Tensor]): A list of sequences of decreasing length.
  471. enforce_sorted (bool, optional): if ``True``, checks that the input
  472. contains sequences sorted by length in a decreasing order. If
  473. ``False``, this condition is not checked. Default: ``True``.
  474. Returns:
  475. a :class:`PackedSequence` object
  476. """
  477. lengths = torch.as_tensor([v.size(0) for v in sequences])
  478. return pack_padded_sequence(
  479. pad_sequence(sequences), lengths, enforce_sorted=enforce_sorted
  480. )
  481. def unpack_sequence(packed_sequences: PackedSequence) -> list[Tensor]:
  482. r"""Unpack PackedSequence into a list of variable length Tensors.
  483. ``packed_sequences`` should be a PackedSequence object.
  484. Example:
  485. >>> from torch.nn.utils.rnn import pack_sequence, unpack_sequence
  486. >>> a = torch.tensor([1, 2, 3])
  487. >>> b = torch.tensor([4, 5])
  488. >>> c = torch.tensor([6])
  489. >>> sequences = [a, b, c]
  490. >>> print(sequences)
  491. [tensor([1, 2, 3]), tensor([4, 5]), tensor([6])]
  492. >>> packed_sequences = pack_sequence(sequences)
  493. >>> print(packed_sequences)
  494. PackedSequence(data=tensor([1, 4, 6, 2, 5, 3]), batch_sizes=tensor([3, 2, 1]), sorted_indices=None, unsorted_indices=None)
  495. >>> unpacked_sequences = unpack_sequence(packed_sequences)
  496. >>> print(unpacked_sequences)
  497. [tensor([1, 2, 3]), tensor([4, 5]), tensor([6])]
  498. Args:
  499. packed_sequences (PackedSequence): A PackedSequence object.
  500. Returns:
  501. a list of :class:`Tensor` objects
  502. """
  503. padded_sequences, lengths = pad_packed_sequence(packed_sequences, batch_first=True)
  504. unpacked_sequences = unpad_sequence(padded_sequences, lengths, batch_first=True)
  505. return unpacked_sequences