hypothesis_utils.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. from collections import defaultdict
  2. from collections.abc import Iterable
  3. import numpy as np
  4. import torch
  5. import hypothesis
  6. from functools import reduce
  7. from hypothesis import assume
  8. from hypothesis import settings
  9. from hypothesis import strategies as st
  10. from hypothesis.extra import numpy as stnp
  11. from hypothesis.strategies import SearchStrategy
  12. from torch.testing._internal.common_quantized import _calculate_dynamic_qparams, _calculate_dynamic_per_channel_qparams
  13. # Setup for the hypothesis tests.
  14. # The tuples are (torch_quantized_dtype, zero_point_enforce), where the last
  15. # element is enforced zero_point. If None, any zero_point point within the
  16. # range of the data type is OK.
  17. # Tuple with all quantized data types.
  18. _ALL_QINT_TYPES = (
  19. torch.quint8,
  20. torch.qint8,
  21. torch.qint32,
  22. )
  23. # Enforced zero point for every quantized data type.
  24. # If None, any zero_point point within the range of the data type is OK.
  25. _ENFORCED_ZERO_POINT = defaultdict(lambda: None, {
  26. torch.quint8: None,
  27. torch.qint8: None,
  28. torch.qint32: 0
  29. })
  30. def _get_valid_min_max(qparams):
  31. scale, zero_point, quantized_type = qparams
  32. adjustment = 1 + torch.finfo(torch.float).eps
  33. _long_type_info = torch.iinfo(torch.long)
  34. long_min, long_max = _long_type_info.min / adjustment, _long_type_info.max / adjustment
  35. # make sure intermediate results are within the range of long
  36. min_value = max((long_min - zero_point) * scale, (long_min / scale + zero_point))
  37. max_value = min((long_max - zero_point) * scale, (long_max / scale + zero_point))
  38. return np.float32(min_value), np.float32(max_value)
  39. # This wrapper wraps around `st.floats` and checks the version of `hypothesis`, if
  40. # it is too old, removes the `width` parameter (which was introduced)
  41. # in 3.67.0
  42. def _floats_wrapper(*args, **kwargs):
  43. if 'width' in kwargs and hypothesis.version.__version_info__ < (3, 67, 0):
  44. # As long as nan, inf, min, max are not specified, reimplement the width
  45. # parameter for older versions of hypothesis.
  46. no_nan_and_inf = (
  47. (('allow_nan' in kwargs and not kwargs['allow_nan']) or
  48. 'allow_nan' not in kwargs) and
  49. (('allow_infinity' in kwargs and not kwargs['allow_infinity']) or
  50. 'allow_infinity' not in kwargs))
  51. min_and_max_not_specified = (
  52. len(args) == 0 and
  53. 'min_value' not in kwargs and
  54. 'max_value' not in kwargs
  55. )
  56. if no_nan_and_inf and min_and_max_not_specified:
  57. if kwargs['width'] == 16:
  58. kwargs['min_value'] = torch.finfo(torch.float16).min
  59. kwargs['max_value'] = torch.finfo(torch.float16).max
  60. elif kwargs['width'] == 32:
  61. kwargs['min_value'] = torch.finfo(torch.float32).min
  62. kwargs['max_value'] = torch.finfo(torch.float32).max
  63. elif kwargs['width'] == 64:
  64. kwargs['min_value'] = torch.finfo(torch.float64).min
  65. kwargs['max_value'] = torch.finfo(torch.float64).max
  66. kwargs.pop('width')
  67. return st.floats(*args, **kwargs)
  68. def floats(*args, **kwargs):
  69. if 'width' not in kwargs:
  70. kwargs['width'] = 32
  71. return _floats_wrapper(*args, **kwargs)
  72. """Hypothesis filter to avoid overflows with quantized tensors.
  73. Args:
  74. tensor: Tensor of floats to filter
  75. qparams: Quantization parameters as returned by the `qparams`.
  76. Returns:
  77. True
  78. Raises:
  79. hypothesis.UnsatisfiedAssumption
  80. Note: This filter is slow. Use it only when filtering of the test cases is
  81. absolutely necessary!
  82. """
  83. def assume_not_overflowing(tensor, qparams):
  84. min_value, max_value = _get_valid_min_max(qparams)
  85. assume(tensor.min() >= min_value)
  86. assume(tensor.max() <= max_value)
  87. return True
  88. """Strategy for generating the quantization parameters.
  89. Args:
  90. dtypes: quantized data types to sample from.
  91. scale_min / scale_max: Min and max scales. If None, set to 1e-3 / 1e3.
  92. zero_point_min / zero_point_max: Min and max for the zero point. If None,
  93. set to the minimum and maximum of the quantized data type.
  94. Note: The min and max are only valid if the zero_point is not enforced
  95. by the data type itself.
  96. Generates:
  97. scale: Sampled scale.
  98. zero_point: Sampled zero point.
  99. quantized_type: Sampled quantized type.
  100. """
  101. @st.composite
  102. def qparams(draw, dtypes=None, scale_min=None, scale_max=None,
  103. zero_point_min=None, zero_point_max=None):
  104. if dtypes is None:
  105. dtypes = _ALL_QINT_TYPES
  106. if not isinstance(dtypes, (list, tuple)):
  107. dtypes = (dtypes,)
  108. quantized_type = draw(st.sampled_from(dtypes))
  109. _type_info = torch.iinfo(quantized_type)
  110. qmin, qmax = _type_info.min, _type_info.max
  111. # TODO: Maybe embed the enforced zero_point in the `torch.iinfo`.
  112. _zp_enforced = _ENFORCED_ZERO_POINT[quantized_type]
  113. if _zp_enforced is not None:
  114. zero_point = _zp_enforced
  115. else:
  116. _zp_min = qmin if zero_point_min is None else zero_point_min
  117. _zp_max = qmax if zero_point_max is None else zero_point_max
  118. zero_point = draw(st.integers(min_value=_zp_min, max_value=_zp_max))
  119. if scale_min is None:
  120. scale_min = torch.finfo(torch.float).eps
  121. if scale_max is None:
  122. scale_max = torch.finfo(torch.float).max
  123. scale = draw(floats(min_value=scale_min, max_value=scale_max, width=32))
  124. return scale, zero_point, quantized_type
  125. """Strategy to create different shapes.
  126. Args:
  127. min_dims / max_dims: minimum and maximum rank.
  128. min_side / max_side: minimum and maximum dimensions per rank.
  129. Generates:
  130. Possible shapes for a tensor, constrained to the rank and dimensionality.
  131. Example:
  132. # Generates 3D and 4D tensors.
  133. @given(Q = qtensor(shapes=array_shapes(min_dims=3, max_dims=4))
  134. some_test(self, Q):...
  135. """
  136. @st.composite
  137. def array_shapes(draw, min_dims=1, max_dims=None, min_side=1, max_side=None, max_numel=None):
  138. """Return a strategy for array shapes (tuples of int >= 1)."""
  139. assert(min_dims < 32)
  140. if max_dims is None:
  141. max_dims = min(min_dims + 2, 32)
  142. assert(max_dims < 32)
  143. if max_side is None:
  144. max_side = min_side + 5
  145. candidate = st.lists(st.integers(min_side, max_side), min_size=min_dims, max_size=max_dims)
  146. if max_numel is not None:
  147. candidate = candidate.filter(lambda x: reduce(int.__mul__, x, 1) <= max_numel)
  148. return draw(candidate.map(tuple))
  149. """Strategy for generating test cases for tensors.
  150. The resulting tensor is in float32 format.
  151. Args:
  152. shapes: Shapes under test for the tensor. Could be either a hypothesis
  153. strategy, or an iterable of different shapes to sample from.
  154. elements: Elements to generate from for the returned data type.
  155. If None, the strategy resolves to float within range [-1e6, 1e6].
  156. qparams: Instance of the qparams strategy. This is used to filter the tensor
  157. such that the overflow would not happen.
  158. Generates:
  159. X: Tensor of type float32. Note that NaN and +/-inf is not included.
  160. qparams: (If `qparams` arg is set) Quantization parameters for X.
  161. The returned parameters are `(scale, zero_point, quantization_type)`.
  162. (If `qparams` arg is None), returns None.
  163. """
  164. @st.composite
  165. def tensor(draw, shapes=None, elements=None, qparams=None):
  166. if isinstance(shapes, SearchStrategy):
  167. _shape = draw(shapes)
  168. else:
  169. _shape = draw(st.sampled_from(shapes))
  170. if qparams is None:
  171. if elements is None:
  172. elements = floats(-1e6, 1e6, allow_nan=False, width=32)
  173. X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
  174. assume(not (np.isnan(X).any() or np.isinf(X).any()))
  175. return X, None
  176. qparams = draw(qparams)
  177. if elements is None:
  178. min_value, max_value = _get_valid_min_max(qparams)
  179. elements = floats(min_value, max_value, allow_infinity=False,
  180. allow_nan=False, width=32)
  181. X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
  182. # Recompute the scale and zero_points according to the X statistics.
  183. scale, zp = _calculate_dynamic_qparams(X, qparams[2])
  184. enforced_zp = _ENFORCED_ZERO_POINT.get(qparams[2], None)
  185. if enforced_zp is not None:
  186. zp = enforced_zp
  187. return X, (scale, zp, qparams[2])
  188. @st.composite
  189. def per_channel_tensor(draw, shapes=None, elements=None, qparams=None):
  190. if isinstance(shapes, SearchStrategy):
  191. _shape = draw(shapes)
  192. else:
  193. _shape = draw(st.sampled_from(shapes))
  194. if qparams is None:
  195. if elements is None:
  196. elements = floats(-1e6, 1e6, allow_nan=False, width=32)
  197. X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
  198. assume(not (np.isnan(X).any() or np.isinf(X).any()))
  199. return X, None
  200. qparams = draw(qparams)
  201. if elements is None:
  202. min_value, max_value = _get_valid_min_max(qparams)
  203. elements = floats(min_value, max_value, allow_infinity=False,
  204. allow_nan=False, width=32)
  205. X = draw(stnp.arrays(dtype=np.float32, elements=elements, shape=_shape))
  206. # Recompute the scale and zero_points according to the X statistics.
  207. scale, zp = _calculate_dynamic_per_channel_qparams(X, qparams[2])
  208. enforced_zp = _ENFORCED_ZERO_POINT.get(qparams[2], None)
  209. if enforced_zp is not None:
  210. zp = enforced_zp
  211. # Permute to model quantization along an axis
  212. axis = int(np.random.randint(0, X.ndim, 1))
  213. permute_axes = np.arange(X.ndim)
  214. permute_axes[0] = axis
  215. permute_axes[axis] = 0
  216. X = np.transpose(X, permute_axes)
  217. return X, (scale, zp, axis, qparams[2])
  218. """Strategy for generating test cases for tensors used in Conv.
  219. The resulting tensors is in float32 format.
  220. Args:
  221. spatial_dim: Spatial Dim for feature maps. If given as an iterable, randomly
  222. picks one from the pool to make it the spatial dimension
  223. batch_size_range: Range to generate `batch_size`.
  224. Must be tuple of `(min, max)`.
  225. input_channels_per_group_range:
  226. Range to generate `input_channels_per_group`.
  227. Must be tuple of `(min, max)`.
  228. output_channels_per_group_range:
  229. Range to generate `output_channels_per_group`.
  230. Must be tuple of `(min, max)`.
  231. feature_map_range: Range to generate feature map size for each spatial_dim.
  232. Must be tuple of `(min, max)`.
  233. kernel_range: Range to generate kernel size for each spatial_dim. Must be
  234. tuple of `(min, max)`.
  235. max_groups: Maximum number of groups to generate.
  236. elements: Elements to generate from for the returned data type.
  237. If None, the strategy resolves to float within range [-1e6, 1e6].
  238. qparams: Strategy for quantization parameters. for X, w, and b.
  239. Could be either a single strategy (used for all) or a list of
  240. three strategies for X, w, b.
  241. Generates:
  242. (X, W, b, g): Tensors of type `float32` of the following drawen shapes:
  243. X: (`batch_size, input_channels, H, W`)
  244. W: (`output_channels, input_channels_per_group) + kernel_shape
  245. b: `(output_channels,)`
  246. groups: Number of groups the input is divided into
  247. Note: X, W, b are tuples of (Tensor, qparams), where qparams could be either
  248. None or (scale, zero_point, quantized_type)
  249. Example:
  250. @given(tensor_conv(
  251. spatial_dim=2,
  252. batch_size_range=(1, 3),
  253. input_channels_per_group_range=(1, 7),
  254. output_channels_per_group_range=(1, 7),
  255. feature_map_range=(6, 12),
  256. kernel_range=(3, 5),
  257. max_groups=4,
  258. elements=st.floats(-1.0, 1.0),
  259. qparams=qparams()
  260. ))
  261. """
  262. @st.composite
  263. def tensor_conv(
  264. draw, spatial_dim=2, batch_size_range=(1, 4),
  265. input_channels_per_group_range=(3, 7),
  266. output_channels_per_group_range=(3, 7), feature_map_range=(6, 12),
  267. kernel_range=(3, 7), max_groups=1, can_be_transposed=False,
  268. elements=None, qparams=None
  269. ):
  270. # Resolve the minibatch, in_channels, out_channels, iH/iW, iK/iW
  271. batch_size = draw(st.integers(*batch_size_range))
  272. input_channels_per_group = draw(
  273. st.integers(*input_channels_per_group_range))
  274. output_channels_per_group = draw(
  275. st.integers(*output_channels_per_group_range))
  276. groups = draw(st.integers(1, max_groups))
  277. input_channels = input_channels_per_group * groups
  278. output_channels = output_channels_per_group * groups
  279. if isinstance(spatial_dim, Iterable):
  280. spatial_dim = draw(st.sampled_from(spatial_dim))
  281. feature_map_shape = []
  282. for i in range(spatial_dim):
  283. feature_map_shape.append(draw(st.integers(*feature_map_range)))
  284. kernels = []
  285. for i in range(spatial_dim):
  286. kernels.append(draw(st.integers(*kernel_range)))
  287. tr = False
  288. weight_shape = (output_channels, input_channels_per_group) + tuple(kernels)
  289. bias_shape = output_channels
  290. if can_be_transposed:
  291. tr = draw(st.booleans())
  292. if tr:
  293. weight_shape = (input_channels, output_channels_per_group) + tuple(kernels)
  294. bias_shape = output_channels
  295. # Resolve the tensors
  296. if qparams is not None:
  297. if isinstance(qparams, (list, tuple)):
  298. assert(len(qparams) == 3), "Need 3 qparams for X, w, b"
  299. else:
  300. qparams = [qparams] * 3
  301. X = draw(tensor(shapes=(
  302. (batch_size, input_channels) + tuple(feature_map_shape),),
  303. elements=elements, qparams=qparams[0]))
  304. W = draw(tensor(shapes=(weight_shape,), elements=elements,
  305. qparams=qparams[1]))
  306. b = draw(tensor(shapes=(bias_shape,), elements=elements,
  307. qparams=qparams[2]))
  308. return X, W, b, groups, tr
  309. # We set the deadline in the currently loaded profile.
  310. # Creating (and loading) a separate profile overrides any settings the user
  311. # already specified.
  312. hypothesis_version = hypothesis.version.__version_info__
  313. current_settings = settings._profiles[settings._current_profile].__dict__
  314. current_settings['deadline'] = None
  315. if hypothesis_version >= (3, 16, 0) and hypothesis_version < (5, 0, 0):
  316. current_settings['timeout'] = hypothesis.unlimited
  317. def assert_deadline_disabled():
  318. if hypothesis_version < (3, 27, 0):
  319. import warnings
  320. warning_message = (
  321. "Your version of hypothesis is outdated. "
  322. "To avoid `DeadlineExceeded` errors, please update. "
  323. "Current hypothesis version: {}".format(hypothesis.__version__)
  324. )
  325. warnings.warn(warning_message)
  326. else:
  327. assert settings().deadline is None