_creation.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """
  2. This module contains tensor creation utilities.
  3. """
  4. import collections.abc
  5. import math
  6. from typing import cast, List, Optional, Tuple, Union
  7. import torch
  8. # Used by make_tensor for generating complex tensor.
  9. complex_to_corresponding_float_type_map = {
  10. torch.complex32: torch.float16,
  11. torch.complex64: torch.float32,
  12. torch.complex128: torch.float64,
  13. }
  14. float_to_corresponding_complex_type_map = {
  15. v: k for k, v in complex_to_corresponding_float_type_map.items()
  16. }
  17. def _uniform_random(t: torch.Tensor, low: float, high: float):
  18. # uniform_ requires to-from <= std::numeric_limits<scalar_t>::max()
  19. # Work around this by scaling the range before and after the PRNG
  20. if high - low >= torch.finfo(t.dtype).max:
  21. return t.uniform_(low / 2, high / 2).mul_(2)
  22. else:
  23. return t.uniform_(low, high)
  24. def make_tensor(
  25. *shape: Union[int, torch.Size, List[int], Tuple[int, ...]],
  26. dtype: torch.dtype,
  27. device: Union[str, torch.device],
  28. low: Optional[float] = None,
  29. high: Optional[float] = None,
  30. requires_grad: bool = False,
  31. noncontiguous: bool = False,
  32. exclude_zero: bool = False,
  33. memory_format: Optional[torch.memory_format] = None,
  34. ) -> torch.Tensor:
  35. r"""Creates a tensor with the given :attr:`shape`, :attr:`device`, and :attr:`dtype`, and filled with
  36. values uniformly drawn from ``[low, high)``.
  37. If :attr:`low` or :attr:`high` are specified and are outside the range of the :attr:`dtype`'s representable
  38. finite values then they are clamped to the lowest or highest representable finite value, respectively.
  39. If ``None``, then the following table describes the default values for :attr:`low` and :attr:`high`,
  40. which depend on :attr:`dtype`.
  41. +---------------------------+------------+----------+
  42. | ``dtype`` | ``low`` | ``high`` |
  43. +===========================+============+==========+
  44. | boolean type | ``0`` | ``2`` |
  45. +---------------------------+------------+----------+
  46. | unsigned integral type | ``0`` | ``10`` |
  47. +---------------------------+------------+----------+
  48. | signed integral types | ``-9`` | ``10`` |
  49. +---------------------------+------------+----------+
  50. | floating types | ``-9`` | ``9`` |
  51. +---------------------------+------------+----------+
  52. | complex types | ``-9`` | ``9`` |
  53. +---------------------------+------------+----------+
  54. Args:
  55. shape (Tuple[int, ...]): Single integer or a sequence of integers defining the shape of the output tensor.
  56. dtype (:class:`torch.dtype`): The data type of the returned tensor.
  57. device (Union[str, torch.device]): The device of the returned tensor.
  58. low (Optional[Number]): Sets the lower limit (inclusive) of the given range. If a number is provided it is
  59. clamped to the least representable finite value of the given dtype. When ``None`` (default),
  60. this value is determined based on the :attr:`dtype` (see the table above). Default: ``None``.
  61. high (Optional[Number]): Sets the upper limit (exclusive) of the given range. If a number is provided it is
  62. clamped to the greatest representable finite value of the given dtype. When ``None`` (default) this value
  63. is determined based on the :attr:`dtype` (see the table above). Default: ``None``.
  64. requires_grad (Optional[bool]): If autograd should record operations on the returned tensor. Default: ``False``.
  65. noncontiguous (Optional[bool]): If `True`, the returned tensor will be noncontiguous. This argument is
  66. ignored if the constructed tensor has fewer than two elements.
  67. exclude_zero (Optional[bool]): If ``True`` then zeros are replaced with the dtype's small positive value
  68. depending on the :attr:`dtype`. For bool and integer types zero is replaced with one. For floating
  69. point types it is replaced with the dtype's smallest positive normal number (the "tiny" value of the
  70. :attr:`dtype`'s :func:`~torch.finfo` object), and for complex types it is replaced with a complex number
  71. whose real and imaginary parts are both the smallest positive normal number representable by the complex
  72. type. Default ``False``.
  73. memory_format (Optional[torch.memory_format]): The memory format of the returned tensor. Incompatible
  74. with :attr:`noncontiguous`.
  75. Raises:
  76. ValueError: if ``requires_grad=True`` is passed for integral `dtype`
  77. ValueError: If ``low > high``.
  78. ValueError: If either :attr:`low` or :attr:`high` is ``nan``.
  79. TypeError: If :attr:`dtype` isn't supported by this function.
  80. Examples:
  81. >>> # xdoctest: +SKIP
  82. >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA)
  83. >>> from torch.testing import make_tensor
  84. >>> # Creates a float tensor with values in [-1, 1)
  85. >>> make_tensor((3,), device='cpu', dtype=torch.float32, low=-1, high=1)
  86. >>> # xdoctest: +SKIP
  87. tensor([ 0.1205, 0.2282, -0.6380])
  88. >>> # Creates a bool tensor on CUDA
  89. >>> make_tensor((2, 2), device='cuda', dtype=torch.bool)
  90. tensor([[False, False],
  91. [False, True]], device='cuda:0')
  92. """
  93. def _modify_low_high(low, high, lowest, highest, default_low, default_high, dtype):
  94. """
  95. Modifies (and raises ValueError when appropriate) low and high values given by the user (input_low, input_high) if required.
  96. """
  97. def clamp(a, l, h):
  98. return min(max(a, l), h)
  99. low = low if low is not None else default_low
  100. high = high if high is not None else default_high
  101. # Checks for error cases
  102. if low != low or high != high:
  103. raise ValueError("make_tensor: one of low or high was NaN!")
  104. if low > high:
  105. raise ValueError("make_tensor: low must be weakly less than high!")
  106. low = clamp(low, lowest, highest)
  107. high = clamp(high, lowest, highest)
  108. if dtype in [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]:
  109. return math.floor(low), math.ceil(high)
  110. return low, high
  111. if len(shape) == 1 and isinstance(shape[0], collections.abc.Sequence):
  112. shape = shape[0] # type: ignore[assignment]
  113. shape = cast(Tuple[int, ...], tuple(shape))
  114. _integral_types = [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]
  115. _floating_types = [torch.float16, torch.bfloat16, torch.float32, torch.float64]
  116. _complex_types = [torch.complex32, torch.complex64, torch.complex128]
  117. if requires_grad and dtype not in _floating_types and dtype not in _complex_types:
  118. raise ValueError("make_tensor: requires_grad must be False for integral dtype")
  119. if dtype is torch.bool:
  120. result = torch.randint(0, 2, shape, device=device, dtype=dtype) # type: ignore[call-overload]
  121. elif dtype is torch.uint8:
  122. ranges = (torch.iinfo(dtype).min, torch.iinfo(dtype).max)
  123. low, high = cast(
  124. Tuple[int, int],
  125. _modify_low_high(low, high, ranges[0], ranges[1], 0, 10, dtype),
  126. )
  127. result = torch.randint(low, high, shape, device=device, dtype=dtype) # type: ignore[call-overload]
  128. elif dtype in _integral_types:
  129. ranges = (torch.iinfo(dtype).min, torch.iinfo(dtype).max)
  130. low, high = _modify_low_high(low, high, ranges[0], ranges[1], -9, 10, dtype)
  131. result = torch.randint(low, high, shape, device=device, dtype=dtype) # type: ignore[call-overload]
  132. elif dtype in _floating_types:
  133. ranges_floats = (torch.finfo(dtype).min, torch.finfo(dtype).max)
  134. m_low, m_high = _modify_low_high(
  135. low, high, ranges_floats[0], ranges_floats[1], -9, 9, dtype
  136. )
  137. result = torch.empty(shape, device=device, dtype=dtype)
  138. _uniform_random(result, m_low, m_high)
  139. elif dtype in _complex_types:
  140. float_dtype = complex_to_corresponding_float_type_map[dtype]
  141. ranges_floats = (torch.finfo(float_dtype).min, torch.finfo(float_dtype).max)
  142. m_low, m_high = _modify_low_high(
  143. low, high, ranges_floats[0], ranges_floats[1], -9, 9, dtype
  144. )
  145. result = torch.empty(shape, device=device, dtype=dtype)
  146. result_real = torch.view_as_real(result)
  147. _uniform_random(result_real, m_low, m_high)
  148. else:
  149. raise TypeError(
  150. f"The requested dtype '{dtype}' is not supported by torch.testing.make_tensor()."
  151. " To request support, file an issue at: https://github.com/pytorch/pytorch/issues"
  152. )
  153. assert not (noncontiguous and memory_format is not None)
  154. if noncontiguous and result.numel() > 1:
  155. result = torch.repeat_interleave(result, 2, dim=-1)
  156. result = result[..., ::2]
  157. elif memory_format is not None:
  158. result = result.clone(memory_format=memory_format)
  159. if exclude_zero:
  160. if dtype in _integral_types or dtype is torch.bool:
  161. replace_with = torch.tensor(1, device=device, dtype=dtype)
  162. elif dtype in _floating_types:
  163. replace_with = torch.tensor(
  164. torch.finfo(dtype).tiny, device=device, dtype=dtype
  165. )
  166. else: # dtype in _complex_types:
  167. float_dtype = complex_to_corresponding_float_type_map[dtype]
  168. float_eps = torch.tensor(
  169. torch.finfo(float_dtype).tiny, device=device, dtype=float_dtype
  170. )
  171. replace_with = torch.complex(float_eps, float_eps)
  172. result[result == 0] = replace_with
  173. if dtype in _floating_types + _complex_types:
  174. result.requires_grad = requires_grad
  175. return result