utils.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. # mypy: ignore-errors
  2. import collections
  3. import warnings
  4. from functools import partial, wraps
  5. from typing import Sequence
  6. import numpy as np
  7. import torch
  8. from torch.testing._internal.common_cuda import TEST_CUDA
  9. from torch.testing._internal.common_dtype import (
  10. _dispatch_dtypes,
  11. all_types,
  12. all_types_and,
  13. all_types_and_complex,
  14. all_types_and_complex_and,
  15. all_types_and_half,
  16. complex_types,
  17. floating_and_complex_types,
  18. floating_and_complex_types_and,
  19. floating_types,
  20. floating_types_and,
  21. floating_types_and_half,
  22. integral_types,
  23. integral_types_and,
  24. )
  25. from torch.testing._internal.common_utils import torch_to_numpy_dtype_dict
  26. COMPLETE_DTYPES_DISPATCH = (
  27. all_types,
  28. all_types_and_complex,
  29. all_types_and_half,
  30. floating_types,
  31. floating_and_complex_types,
  32. floating_types_and_half,
  33. integral_types,
  34. complex_types,
  35. )
  36. EXTENSIBLE_DTYPE_DISPATCH = (
  37. all_types_and_complex_and,
  38. floating_types_and,
  39. floating_and_complex_types_and,
  40. integral_types_and,
  41. all_types_and,
  42. )
  43. # Better way to acquire devices?
  44. DEVICES = ["cpu"] + (["cuda"] if TEST_CUDA else [])
  45. class _dynamic_dispatch_dtypes(_dispatch_dtypes):
  46. # Class to tag the dynamically generated types.
  47. pass
  48. def get_supported_dtypes(op, sample_inputs_fn, device_type):
  49. # Returns the supported dtypes for the given operator and device_type pair.
  50. assert device_type in ["cpu", "cuda"]
  51. if not TEST_CUDA and device_type == "cuda":
  52. warnings.warn(
  53. "WARNING: CUDA is not available, empty_dtypes dispatch will be returned!"
  54. )
  55. return _dynamic_dispatch_dtypes(())
  56. supported_dtypes = set()
  57. for dtype in all_types_and_complex_and(torch.bool, torch.bfloat16, torch.half):
  58. try:
  59. samples = sample_inputs_fn(op, device_type, dtype, False)
  60. except RuntimeError:
  61. # If `sample_inputs_fn` doesn't support sampling for a given
  62. # `dtype`, we assume that the `dtype` is not supported.
  63. # We raise a warning, so that user knows that this was the case
  64. # and can investigate if there was an issue with the `sample_inputs_fn`.
  65. warnings.warn(
  66. f"WARNING: Unable to generate sample for device:{device_type} and dtype:{dtype}"
  67. )
  68. continue
  69. # We assume the dtype is supported
  70. # only if all samples pass for the given dtype.
  71. supported = True
  72. for sample in samples:
  73. try:
  74. op(sample.input, *sample.args, **sample.kwargs)
  75. except RuntimeError as re:
  76. # dtype is not supported
  77. supported = False
  78. break
  79. if supported:
  80. supported_dtypes.add(dtype)
  81. return _dynamic_dispatch_dtypes(supported_dtypes)
  82. def dtypes_dispatch_hint(dtypes):
  83. # Function returns the appropriate dispatch function (from COMPLETE_DTYPES_DISPATCH and EXTENSIBLE_DTYPE_DISPATCH)
  84. # and its string representation for the passed `dtypes`.
  85. return_type = collections.namedtuple("return_type", "dispatch_fn dispatch_fn_str")
  86. # CUDA is not available, dtypes will be empty.
  87. if len(dtypes) == 0:
  88. return return_type((), str(tuple()))
  89. set_dtypes = set(dtypes)
  90. for dispatch in COMPLETE_DTYPES_DISPATCH:
  91. # Short circuit if we get an exact match.
  92. if set(dispatch()) == set_dtypes:
  93. return return_type(dispatch, dispatch.__name__ + "()")
  94. chosen_dispatch = None
  95. chosen_dispatch_score = 0.0
  96. for dispatch in EXTENSIBLE_DTYPE_DISPATCH:
  97. dispatch_dtypes = set(dispatch())
  98. if not dispatch_dtypes.issubset(set_dtypes):
  99. continue
  100. score = len(dispatch_dtypes)
  101. if score > chosen_dispatch_score:
  102. chosen_dispatch_score = score
  103. chosen_dispatch = dispatch
  104. # If user passed dtypes which are lower than the lowest
  105. # dispatch type available (not likely but possible in code path).
  106. if chosen_dispatch is None:
  107. return return_type((), str(dtypes))
  108. return return_type(
  109. partial(dispatch, *tuple(set(dtypes) - set(dispatch()))),
  110. dispatch.__name__ + str(tuple(set(dtypes) - set(dispatch()))),
  111. )
  112. def is_dynamic_dtype_set(op):
  113. # Detect if the OpInfo entry acquired dtypes dynamically
  114. # using `get_supported_dtypes`.
  115. return op.dynamic_dtypes
  116. def str_format_dynamic_dtype(op):
  117. fmt_str = f"""
  118. OpInfo({op.name},
  119. dtypes={dtypes_dispatch_hint(op.dtypes).dispatch_fn_str},
  120. dtypesIfCUDA={dtypes_dispatch_hint(op.dtypesIfCUDA).dispatch_fn_str},
  121. )
  122. """
  123. return fmt_str
  124. def np_unary_ufunc_integer_promotion_wrapper(fn):
  125. # Wrapper that passes PyTorch's default scalar
  126. # type as an argument to the wrapped NumPy
  127. # unary ufunc when given an integer input.
  128. # This mimicks PyTorch's integer->floating point
  129. # type promotion.
  130. #
  131. # This is necessary when NumPy promotes
  132. # integer types to double, since PyTorch promotes
  133. # integer types to the default scalar type.
  134. # Helper to determine if promotion is needed
  135. def is_integral(dtype):
  136. return dtype in [
  137. np.bool_,
  138. bool,
  139. np.uint8,
  140. np.int8,
  141. np.int16,
  142. np.int32,
  143. np.int64,
  144. ]
  145. @wraps(fn)
  146. def wrapped_fn(x):
  147. # As the default dtype can change, acquire it when function is called.
  148. # NOTE: Promotion in PyTorch is from integer types to the default dtype
  149. np_dtype = torch_to_numpy_dtype_dict[torch.get_default_dtype()]
  150. if is_integral(x.dtype):
  151. return fn(x.astype(np_dtype))
  152. return fn(x)
  153. return wrapped_fn
  154. def reference_reduction_numpy(f, supports_keepdims=True):
  155. """Wraps a NumPy reduction operator.
  156. The wrapper function will forward dim, keepdim, mask, and identity
  157. kwargs to the wrapped function as the NumPy equivalent axis,
  158. keepdims, where, and initiak kwargs, respectively.
  159. Args:
  160. f: NumPy reduction operator to wrap
  161. supports_keepdims (bool, optional): Whether the NumPy operator accepts
  162. keepdims parameter. If it does not, the wrapper will manually unsqueeze
  163. the reduced dimensions if it was called with keepdim=True. Defaults to True.
  164. Returns:
  165. Wrapped function
  166. """
  167. @wraps(f)
  168. def wrapper(x: np.ndarray, *args, **kwargs):
  169. # Copy keys into a set
  170. keys = set(kwargs.keys())
  171. dim = kwargs.pop("dim", None)
  172. keepdim = kwargs.pop("keepdim", False)
  173. if "dim" in keys:
  174. dim = tuple(dim) if isinstance(dim, Sequence) else dim
  175. # NumPy reductions don't accept dim=0 for scalar inputs
  176. # so we convert it to None if and only if dim is equivalent
  177. if x.ndim == 0 and dim in {0, -1, (0,), (-1,)}:
  178. kwargs["axis"] = None
  179. else:
  180. kwargs["axis"] = dim
  181. if "keepdim" in keys and supports_keepdims:
  182. kwargs["keepdims"] = keepdim
  183. if "mask" in keys:
  184. mask = kwargs.pop("mask")
  185. if mask is not None:
  186. assert mask.layout == torch.strided
  187. kwargs["where"] = mask.cpu().numpy()
  188. if "identity" in keys:
  189. identity = kwargs.pop("identity")
  190. if identity is not None:
  191. if identity.dtype is torch.bfloat16:
  192. identity = identity.cpu().to(torch.float32)
  193. else:
  194. identity = identity.cpu()
  195. kwargs["initial"] = identity.numpy()
  196. result = f(x, *args, **kwargs)
  197. # Unsqueeze reduced dimensions if NumPy does not support keepdims
  198. if keepdim and not supports_keepdims and x.ndim > 0:
  199. dim = list(range(x.ndim)) if dim is None else dim
  200. result = np.expand_dims(result, dim)
  201. return result
  202. return wrapper
  203. def prod_numpy(a, *args, **kwargs):
  204. """
  205. The function will call np.prod with type as np.int64 if the input type
  206. is int or uint64 if is uint. This is necessary because windows np.prod uses by default
  207. int32 while on linux it uses int64.
  208. This is for fixing integer overflow https://github.com/pytorch/pytorch/issues/77320
  209. Returns:
  210. np.prod of input
  211. """
  212. if "dtype" not in kwargs:
  213. if np.issubdtype(a.dtype, np.signedinteger):
  214. a = a.astype(np.int64)
  215. elif np.issubdtype(a.dtype, np.unsignedinteger):
  216. a = a.astype(np.uint64)
  217. fn = reference_reduction_numpy(np.prod)
  218. return fn(a, *args, **kwargs)