flatten.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  1. from .module import Module
  2. from typing import Tuple, Union
  3. from torch import Tensor
  4. from torch.types import _size
  5. class Flatten(Module):
  6. r"""
  7. Flattens a contiguous range of dims into a tensor. For use with :class:`~nn.Sequential`.
  8. Shape:
  9. - Input: :math:`(*, S_{\text{start}},..., S_{i}, ..., S_{\text{end}}, *)`,'
  10. where :math:`S_{i}` is the size at dimension :math:`i` and :math:`*` means any
  11. number of dimensions including none.
  12. - Output: :math:`(*, \prod_{i=\text{start}}^{\text{end}} S_{i}, *)`.
  13. Args:
  14. start_dim: first dim to flatten (default = 1).
  15. end_dim: last dim to flatten (default = -1).
  16. Examples::
  17. >>> input = torch.randn(32, 1, 5, 5)
  18. >>> # With default parameters
  19. >>> m = nn.Flatten()
  20. >>> output = m(input)
  21. >>> output.size()
  22. torch.Size([32, 25])
  23. >>> # With non-default parameters
  24. >>> m = nn.Flatten(0, 2)
  25. >>> output = m(input)
  26. >>> output.size()
  27. torch.Size([160, 5])
  28. """
  29. __constants__ = ['start_dim', 'end_dim']
  30. start_dim: int
  31. end_dim: int
  32. def __init__(self, start_dim: int = 1, end_dim: int = -1) -> None:
  33. super(Flatten, self).__init__()
  34. self.start_dim = start_dim
  35. self.end_dim = end_dim
  36. def forward(self, input: Tensor) -> Tensor:
  37. return input.flatten(self.start_dim, self.end_dim)
  38. def extra_repr(self) -> str:
  39. return 'start_dim={}, end_dim={}'.format(
  40. self.start_dim, self.end_dim
  41. )
  42. class Unflatten(Module):
  43. r"""
  44. Unflattens a tensor dim expanding it to a desired shape. For use with :class:`~nn.Sequential`.
  45. * :attr:`dim` specifies the dimension of the input tensor to be unflattened, and it can
  46. be either `int` or `str` when `Tensor` or `NamedTensor` is used, respectively.
  47. * :attr:`unflattened_size` is the new shape of the unflattened dimension of the tensor and it can be
  48. a `tuple` of ints or a `list` of ints or `torch.Size` for `Tensor` input; a `NamedShape`
  49. (tuple of `(name, size)` tuples) for `NamedTensor` input.
  50. Shape:
  51. - Input: :math:`(*, S_{\text{dim}}, *)`, where :math:`S_{\text{dim}}` is the size at
  52. dimension :attr:`dim` and :math:`*` means any number of dimensions including none.
  53. - Output: :math:`(*, U_1, ..., U_n, *)`, where :math:`U` = :attr:`unflattened_size` and
  54. :math:`\prod_{i=1}^n U_i = S_{\text{dim}}`.
  55. Args:
  56. dim (Union[int, str]): Dimension to be unflattened
  57. unflattened_size (Union[torch.Size, Tuple, List, NamedShape]): New shape of the unflattened dimension
  58. Examples:
  59. >>> input = torch.randn(2, 50)
  60. >>> # With tuple of ints
  61. >>> m = nn.Sequential(
  62. >>> nn.Linear(50, 50),
  63. >>> nn.Unflatten(1, (2, 5, 5))
  64. >>> )
  65. >>> output = m(input)
  66. >>> output.size()
  67. torch.Size([2, 2, 5, 5])
  68. >>> # With torch.Size
  69. >>> m = nn.Sequential(
  70. >>> nn.Linear(50, 50),
  71. >>> nn.Unflatten(1, torch.Size([2, 5, 5]))
  72. >>> )
  73. >>> output = m(input)
  74. >>> output.size()
  75. torch.Size([2, 2, 5, 5])
  76. >>> # With namedshape (tuple of tuples)
  77. >>> input = torch.randn(2, 50, names=('N', 'features'))
  78. >>> unflatten = nn.Unflatten('features', (('C', 2), ('H', 5), ('W', 5)))
  79. >>> output = unflatten(input)
  80. >>> output.size()
  81. torch.Size([2, 2, 5, 5])
  82. """
  83. NamedShape = Tuple[Tuple[str, int]]
  84. __constants__ = ['dim', 'unflattened_size']
  85. dim: Union[int, str]
  86. unflattened_size: Union[_size, NamedShape]
  87. def __init__(self, dim: Union[int, str], unflattened_size: Union[_size, NamedShape]) -> None:
  88. super(Unflatten, self).__init__()
  89. if isinstance(dim, int):
  90. self._require_tuple_int(unflattened_size)
  91. elif isinstance(dim, str):
  92. self._require_tuple_tuple(unflattened_size)
  93. else:
  94. raise TypeError("invalid argument type for dim parameter")
  95. self.dim = dim
  96. self.unflattened_size = unflattened_size
  97. def _require_tuple_tuple(self, input):
  98. if (isinstance(input, tuple)):
  99. for idx, elem in enumerate(input):
  100. if not isinstance(elem, tuple):
  101. raise TypeError("unflattened_size must be tuple of tuples, " +
  102. "but found element of type {} at pos {}".format(type(elem).__name__, idx))
  103. return
  104. raise TypeError("unflattened_size must be a tuple of tuples, " +
  105. "but found type {}".format(type(input).__name__))
  106. def _require_tuple_int(self, input):
  107. if (isinstance(input, (tuple, list))):
  108. for idx, elem in enumerate(input):
  109. if not isinstance(elem, int):
  110. raise TypeError("unflattened_size must be tuple of ints, " +
  111. "but found element of type {} at pos {}".format(type(elem).__name__, idx))
  112. return
  113. raise TypeError("unflattened_size must be a tuple of ints, but found type {}".format(type(input).__name__))
  114. def forward(self, input: Tensor) -> Tensor:
  115. return input.unflatten(self.dim, self.unflattened_size)
  116. def extra_repr(self) -> str:
  117. return 'dim={}, unflattened_size={}'.format(self.dim, self.unflattened_size)