ReduceOpsUtils.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #pragma once
  2. #include <limits>
  3. #include <ATen/core/Tensor.h>
  4. #include <ATen/native/Resize.h>
  5. #include <ATen/native/TensorIterator.h>
  6. #include <ATen/native/NonEmptyUtils.h>
  7. #include <ATen/WrapDimUtilsMulti.h>
  8. #include <c10/core/ScalarType.h>
  9. #include <c10/util/irange.h>
  10. #ifndef AT_PER_OPERATOR_HEADERS
  11. #include <ATen/Functions.h>
  12. #else
  13. #include <ATen/ops/empty.h>
  14. #include <ATen/ops/scalar_tensor.h>
  15. #endif
  16. namespace at::native {
  17. // Maximum and minimum possible scalar values, including infinities
  18. template <typename scalar_t>
  19. constexpr scalar_t upper_bound() {
  20. using lim = std::numeric_limits<scalar_t>;
  21. return lim::has_infinity ? lim::infinity() : lim::max();
  22. }
  23. template <typename scalar_t>
  24. constexpr scalar_t lower_bound() {
  25. using lim = std::numeric_limits<scalar_t>;
  26. return lim::has_infinity ? -lim::infinity() : lim::lowest();
  27. }
  28. inline Tensor restride_dim(
  29. const Tensor& src, int64_t dim,
  30. IntArrayRef replacement_shape
  31. ) {
  32. auto strides = ensure_nonempty_vec(src.strides().vec());
  33. strides[dim] = 0;
  34. return src.as_strided(replacement_shape, strides);
  35. }
  36. inline void _dimreduce_setup(const Tensor &result, const Tensor &self,
  37. int64_t dim) {
  38. IntArrayRef self_sizes = self.sizes();
  39. std::vector<int64_t> result_sizes;
  40. result_sizes.insert(result_sizes.end(), self_sizes.begin(), self_sizes.end());
  41. result_sizes[dim] = 1;
  42. result.resize_(result_sizes);
  43. }
  44. inline bool _dimreduce_return_trivial(const Tensor &result, const Tensor &self,
  45. const Scalar& ident, int64_t dim, bool keepdim) {
  46. if (self.numel() == 1 && self.ndimension() == 0) {
  47. result.resize_({});
  48. result.fill_(self);
  49. return true;
  50. }
  51. // Return identity
  52. if (self.numel() == 0) {
  53. _dimreduce_setup(result, self, dim);
  54. result.fill_(ident);
  55. if (!keepdim) result.squeeze_(dim);
  56. return true;
  57. }
  58. return false;
  59. }
  60. inline bool _dimreduce_return_trivial_no_ident(Tensor &result, const Tensor &self,
  61. int64_t /*dim*/, bool /*keepdim*/, const char* /*fn_name*/) {
  62. if (self.numel() == 1 && self.ndimension() == 0) {
  63. result.resize_({});
  64. result.fill_(self);
  65. return true;
  66. }
  67. return false;
  68. }
  69. inline std::optional<Tensor> _allreduce_return_trivial(
  70. const Tensor& self,
  71. const Scalar& ident) {
  72. // Return identity
  73. if (self.numel() == 0) {
  74. return at::scalar_tensor(ident, self.options());
  75. }
  76. return std::nullopt;
  77. }
  78. #define OPTION_TYPE_EQUALITY_CHECK(option, out, self) \
  79. { \
  80. TORCH_CHECK(\
  81. out.option() == self.option(),\
  82. "expected ", #option, " ",\
  83. self.option(),\
  84. " but found ", out.option())\
  85. }
  86. inline void check_scalar_type_device_layout_equal(const Tensor& out, const Tensor& self) {
  87. OPTION_TYPE_EQUALITY_CHECK(scalar_type, out, self);
  88. OPTION_TYPE_EQUALITY_CHECK(device, out.options(), self.options());
  89. OPTION_TYPE_EQUALITY_CHECK(layout, out.options(), self.options());
  90. }
  91. inline Tensor integer_upcast(const Tensor& self, std::optional<ScalarType> dtype) {
  92. ScalarType scalarType = self.scalar_type();
  93. TORCH_CHECK(!isBarebonesUnsignedType(scalarType), "integer upcasting for uint16, uint32 and uint64 is not currently implemented");
  94. ScalarType upcast_scalarType = dtype.value_or(at::isIntegralType(scalarType, /*includeBool=*/true) ? ScalarType::Long : scalarType);
  95. return self.toType(upcast_scalarType);
  96. }
  97. using DimMask = TensorIterator::DimMask;
  98. inline DimVector make_dim_vector(OptionalIntArrayRef opt_dims, int64_t ndim) {
  99. if (opt_dims.has_value()) {
  100. return DimVector(opt_dims.value());
  101. } else {
  102. std::vector<int64_t> all_dims(ndim);
  103. std::iota(all_dims.begin(), all_dims.end(), 0);
  104. return DimVector(all_dims);
  105. }
  106. }
  107. inline DimMask make_dim_mask(OptionalIntArrayRef opt_dims, int64_t ndim, bool allow_empty_dims=false) {
  108. DimMask mask;
  109. if (opt_dims.has_value()) {
  110. auto dims = opt_dims.value();
  111. if (dims.empty() && !allow_empty_dims) {
  112. mask = DimMask().flip();
  113. } else {
  114. mask = at::dim_list_to_bitset(dims, ndim);
  115. }
  116. } else {
  117. mask = DimMask().flip();
  118. }
  119. return mask;
  120. }
  121. inline DimVector shape_from_dim_mask(const Tensor& self, DimMask mask, bool keepdim) {
  122. auto shape = DimVector(self.sizes());
  123. for (int dim = shape.size() - 1; dim >= 0; dim--) {
  124. if (mask[dim]) {
  125. if (keepdim) {
  126. shape[dim] = 1;
  127. } else {
  128. shape.erase(shape.begin() + dim);
  129. }
  130. }
  131. }
  132. return shape;
  133. }
  134. inline void resize_reduction_result(
  135. Tensor& result, const Tensor& self, DimMask mask, bool keepdim,
  136. ScalarType /*dtype*/)
  137. {
  138. auto shape = shape_from_dim_mask(self, mask, keepdim);
  139. TORCH_CHECK(result.defined(), "Cannot create a new tensor inside a reduction op. You likely tried to call an operator with an out argument but the out argument was an undefined tensor.");
  140. at::native::resize_output(result, shape);
  141. }
  142. inline Tensor create_reduction_result(
  143. const Tensor& self, at::OptionalIntArrayRef dim, bool keepdim, ScalarType dtype
  144. ) {
  145. DimMask mask = make_dim_mask(dim, self.dim());
  146. auto shape = shape_from_dim_mask(self, mask, keepdim);
  147. return at::empty(shape, self.options().dtype(dtype));
  148. }
  149. inline Tensor review_reduce_result(const Tensor& result, int ndim, DimMask mask, bool keepdim) {
  150. if (keepdim) {
  151. return result;
  152. }
  153. auto shape = DimVector(result.sizes());
  154. auto stride = DimVector(result.strides());
  155. for (const auto dim : c10::irange(ndim)) {
  156. if (mask[dim]) {
  157. shape.insert(shape.begin() + dim, 1);
  158. stride.insert(stride.begin() + dim, 0);
  159. }
  160. }
  161. return result.as_strided(shape, stride);
  162. }
  163. inline TensorIterator make_reduction(
  164. const char* name, Tensor& result, const Tensor& self,
  165. at::OptionalIntArrayRef dim_opt,
  166. bool keepdim, ScalarType in_dtype, ScalarType out_dtype) {
  167. // check that result type and dtype match if provided
  168. TORCH_CHECK(
  169. !result.defined() || result.scalar_type() == out_dtype,
  170. name, ": provided dtype must match dtype of result. Got ",
  171. toString(result.scalar_type()),
  172. " and ",
  173. toString(out_dtype),
  174. ".");
  175. // dim={} performs an all-reduce, same as dim=None
  176. IntArrayRef dim = dim_opt.value_or(IntArrayRef{});
  177. int64_t ndim = self.dim();
  178. auto mask = make_dim_mask(dim, ndim);
  179. resize_reduction_result(result, self, mask, keepdim, out_dtype);
  180. auto viewed_result = review_reduce_result(result, ndim, mask, keepdim);
  181. namedinference::propagate_names_for_reduction(result, self, dim, keepdim);
  182. if (self.scalar_type() == in_dtype) {
  183. return TensorIterator::reduce_op(viewed_result, self);
  184. }
  185. return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
  186. }
  187. [[maybe_unused]] inline TensorIterator make_reduction(
  188. const char* name,
  189. Tensor& result,
  190. const Tensor& self,
  191. at::OptionalIntArrayRef dim,
  192. bool keepdim,
  193. ScalarType out_dtype) {
  194. // special case for type promotion in mixed precision, improves computational
  195. // efficiency.
  196. // not generalize this to common mismatched input/output types to avoid cross
  197. // product of templated kernel launches.
  198. const bool gpu_lowp_to_f32 = (
  199. (self.is_cuda() || self.is_xpu()) && (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) && out_dtype == kFloat);
  200. auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type()
  201. : self.is_complex() ? c10::toComplexType(out_dtype)
  202. : out_dtype;
  203. return make_reduction(name, result, self, dim, keepdim, in_dtype, out_dtype);
  204. }
  205. inline TensorIterator make_reduction(
  206. const char* name, Tensor& result1, Tensor& result2, const Tensor& self,
  207. at::OptionalIntArrayRef dim_opt, bool keepdim, ScalarType dtype1,
  208. ScalarType dtype2) {
  209. // check that result type and dtype match if provided
  210. TORCH_CHECK(
  211. (!result1.defined() || result1.scalar_type() == dtype1) && (!result2.defined() || result2.scalar_type() == dtype2),
  212. name, ": provided dtype must match dtype of result. Got ",
  213. toString(result1.scalar_type()), toString(result2.scalar_type()),
  214. " and ",
  215. toString(dtype1), toString(dtype2),
  216. ".");
  217. // dim={} performs an all-reduce, same as dim=None
  218. auto dim = dim_opt.value_or(IntArrayRef{});
  219. int64_t ndim = self.dim();
  220. DimMask mask = make_dim_mask(dim, ndim);
  221. resize_reduction_result(result1, self, mask, keepdim, dtype1);
  222. auto viewed_result1 = review_reduce_result(result1, ndim, mask, keepdim);
  223. resize_reduction_result(result2, self, mask, keepdim, dtype2);
  224. auto viewed_result2 = review_reduce_result(result2, ndim, mask, keepdim);
  225. namedinference::propagate_names_for_reduction(result1, self, dim, keepdim);
  226. namedinference::propagate_names_for_reduction(result2, self, dim, keepdim);
  227. // special case for type promotion in mixed precision, improves computational
  228. // efficiency.
  229. // We don't generalize this to common mismatched input/output types to avoid cross
  230. // product of templated kernel launches.
  231. if (self.scalar_type() == dtype1 ||
  232. (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
  233. return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
  234. }
  235. return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
  236. }
  237. [[maybe_unused]] inline TensorIterator make_reduction(
  238. const char* name,
  239. Tensor& result1,
  240. Tensor& result2,
  241. const Tensor& self,
  242. at::OptionalIntArrayRef dim,
  243. bool keepdim,
  244. ScalarType dtype) {
  245. return make_reduction(name, result1, result2, self, dim, keepdim, dtype, dtype);
  246. }
  247. inline void zero_numel_check_dims(const Tensor& self, const int64_t dim, const char *fn_name) {
  248. if (self.ndimension() == 0) {
  249. TORCH_CHECK_INDEX(dim == 0 || dim == -1, fn_name,
  250. ": Expected reduction dim -1 or 0 for scalar but got ", dim);
  251. }
  252. else {
  253. TORCH_CHECK_INDEX(self.size(dim) != 0, fn_name,
  254. ": Expected reduction dim ", dim, " to have non-zero size.");
  255. }
  256. }
  257. inline void zero_numel_check_dims(const Tensor& self, const IntArrayRef dim, const char *fn_name) {
  258. TORCH_CHECK(
  259. !dim.empty(),
  260. fn_name, ": Expected reduction dim to be specified for input.numel() == 0. ",
  261. "Specify the reduction dim with the 'dim' argument.");
  262. for (const int64_t d : dim) {
  263. zero_numel_check_dims(self, d, fn_name);
  264. }
  265. }
  266. inline std::vector<int64_t> get_zero_numel_tensor_size(
  267. const Tensor& self,
  268. const int64_t dim,
  269. const bool keepdim,
  270. const char* fn_name) {
  271. TORCH_INTERNAL_ASSERT(self.numel() == 0, fn_name, ": Expected self.numel() == 0.");
  272. zero_numel_check_dims(self, dim, fn_name);
  273. std::vector<int64_t> sizes;
  274. if (keepdim) {
  275. sizes = self.sizes().vec();
  276. sizes[dim] = 1;
  277. }
  278. else {
  279. for (const auto d : c10::irange(self.dim())) {
  280. if (d != dim) {
  281. sizes.push_back(self.sizes()[d]);
  282. }
  283. }
  284. }
  285. return sizes;
  286. }
  287. // Resize the result tensor and indices when result.numel() == 0 depending on values of
  288. // dim and keepdim for returning tensors containing reduction results.
  289. // This function should be called when you are reducing a zero-numel tensor and want to
  290. // resize the output and return it. This function exists for resizing zero-numel
  291. // tensors when the size of the reduction dimension is non-zero.
  292. [[maybe_unused]] inline void zero_numel_tensor_resize(
  293. Tensor& result,
  294. Tensor& result_indices,
  295. const Tensor& self,
  296. const int64_t dim,
  297. const bool keepdim,
  298. const char* fn_name) {
  299. auto sizes = get_zero_numel_tensor_size(self, dim, keepdim, fn_name);
  300. at::native::resize_output(result, sizes);
  301. at::native::resize_output(result_indices, sizes);
  302. }
  303. inline ScalarType get_dtype_from_self(
  304. const Tensor& self,
  305. const std::optional<ScalarType>& dtype,
  306. bool promote_integers) {
  307. if (dtype.has_value()) {
  308. return dtype.value();
  309. }
  310. ScalarType src_type = self.scalar_type();
  311. if (promote_integers && at::isIntegralType(src_type, /*includeBool=*/true)) {
  312. return kLong;
  313. }
  314. return src_type;
  315. }
  316. inline ScalarType get_dtype_from_result(Tensor& result, std::optional<ScalarType> dtype) {
  317. TORCH_CHECK(result.defined(), "Cannot create a new tensor inside a reduction op. You likely tried to call an operator with an out argument but the out argument was an undefined tensor.");
  318. if (dtype.has_value()) {
  319. return dtype.value();
  320. } else {
  321. return result.scalar_type();
  322. }
  323. }
  324. } // namespace at::native
  325. namespace at::meta {
  326. [[maybe_unused]] inline DimVector get_reduction_shape(
  327. const Tensor& self,
  328. IntArrayRef dims,
  329. bool keepdim,
  330. bool allow_empty_dims = false) {
  331. auto mask = native::make_dim_mask(dims, self.dim(), allow_empty_dims);
  332. return native::shape_from_dim_mask(self, mask, keepdim);
  333. }
  334. inline void resize_reduction(
  335. impl::MetaBase& meta,
  336. const Tensor& self,
  337. OptionalIntArrayRef opt_dims,
  338. bool keepdim,
  339. ScalarType out_dtype,
  340. bool allow_empty_dims=false) {
  341. DimVector dims_ = at::native::make_dim_vector(opt_dims, self.dim());
  342. maybe_wrap_dims(dims_, self.dim());
  343. auto shape = get_reduction_shape(self, dims_, keepdim, allow_empty_dims);
  344. if (self.layout() == kStrided) {
  345. meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
  346. } else if (shape.empty()) {
  347. meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype).layout(kStrided));
  348. } else {
  349. TORCH_CHECK(false, "resize_reduction: support for output with ", self.layout(), " layout is not implemented yet");
  350. }
  351. namedinference::propagate_names_for_reduction(
  352. meta.maybe_get_output(), self, dims_, keepdim);
  353. }
  354. inline void resize_reduction_with_indices(
  355. impl::MetaBase& meta,
  356. const Tensor& self,
  357. IntArrayRef dims,
  358. bool keepdim,
  359. ScalarType out_dtype) {
  360. DimVector dims_(dims);
  361. maybe_wrap_dims(dims_, self.dim());
  362. auto shape = get_reduction_shape(self, dims_, keepdim);
  363. meta.set_output_raw_strided(0, shape, {}, self.options().dtype(out_dtype));
  364. meta.set_output_raw_strided(1, shape, {}, self.options().dtype(kLong));
  365. namedinference::propagate_names_for_reduction(
  366. meta.maybe_get_output(0), self, dims_, keepdim);
  367. namedinference::propagate_names_for_reduction(
  368. meta.maybe_get_output(1), self, dims_, keepdim);
  369. }
  370. inline TensorIterator make_reduction(
  371. const Tensor& self,
  372. const Tensor& result,
  373. OptionalIntArrayRef opt_dims,
  374. bool keepdim,
  375. ScalarType in_dtype) {
  376. int64_t ndim = self.dim();
  377. auto mask = at::native::make_dim_mask(opt_dims, ndim);
  378. auto viewed_result =
  379. at::native::review_reduce_result(result, ndim, mask, keepdim);
  380. if (self.scalar_type() == in_dtype) {
  381. return TensorIterator::reduce_op(viewed_result, self);
  382. }
  383. return TensorIterator::reduce_op(viewed_result, self.to(in_dtype));
  384. }
  385. inline TensorIterator make_reduction(
  386. const Tensor& self,
  387. const Tensor& result1,
  388. const Tensor& result2,
  389. IntArrayRef dims,
  390. bool keepdim,
  391. ScalarType dtype1,
  392. ScalarType /*dtype2*/) {
  393. int64_t ndim = self.dim();
  394. auto mask = at::native::make_dim_mask(dims, ndim);
  395. auto viewed_result1 = at::native::review_reduce_result(result1, ndim, mask, keepdim);
  396. auto viewed_result2 = at::native::review_reduce_result(result2, ndim, mask, keepdim);
  397. // special case for type promotion in mixed precision, improves computational efficiency.
  398. // We don't generalize this to common mismatched input/output types to avoid cross product
  399. // of templated kernel launches.
  400. if (self.scalar_type() == dtype1 ||
  401. (self.is_cuda() && self.scalar_type() == kHalf && dtype1 == kFloat)) {
  402. return TensorIterator::reduce_op(viewed_result1, viewed_result2, self);
  403. }
  404. return TensorIterator::reduce_op(viewed_result1, viewed_result2, self.to(dtype1));
  405. }
  406. [[maybe_unused]] inline TensorIterator make_reduction_from_out_ty(
  407. const Tensor& self,
  408. const Tensor& result,
  409. OptionalIntArrayRef opt_dims,
  410. bool keepdim,
  411. ScalarType out_dtype) {
  412. // special case for type promotion in mixed precision, improves computational
  413. // efficiency.
  414. // not generalize this to common mismatched input/output types to avoid cross
  415. // product of templated kernel launches.
  416. const bool gpu_lowp_to_f32 =
  417. (self.is_cuda() &&
  418. (self.scalar_type() == kHalf || self.scalar_type() == kBFloat16) &&
  419. out_dtype == kFloat);
  420. auto in_dtype = gpu_lowp_to_f32 ? self.scalar_type() : out_dtype;
  421. return make_reduction(self, result, opt_dims, keepdim, in_dtype);
  422. }
  423. } // namespace at::meta