Reduce.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #pragma once
  2. #include <ATen/native/cpu/Loops.h>
  3. #include <ATen/Parallel.h>
  4. #include <c10/util/TypeList.h>
  5. #include <c10/core/Scalar.h>
  6. #include <c10/util/irange.h>
  7. #include <sstream>
  8. namespace at { namespace native { inline namespace CPU_CAPABILITY {
  9. using namespace vec;
  10. #define VEC_LOOP_HEADER(func_t, data) \
  11. using scalar_t = typename function_traits<func_t>::result_type; \
  12. using Vec = Vectorized<scalar_t>; \
  13. char* out_ptr = data[0]; \
  14. (void) out_ptr;
  15. // reduction that is contiguous over the input in dim 0
  16. template <typename traits>
  17. static inline bool is_contiguous_reduction(const int64_t* strides) {
  18. return strides[0] == 0 &&
  19. strides[1] == sizeof(typename traits::arg2_t);
  20. }
  21. // reduction that is contiguous over the input in dim 1
  22. template <typename traits>
  23. static inline bool is_outer_reduction(const int64_t* strides) {
  24. return strides[0] == 0 &&
  25. strides[2] == sizeof(typename traits::result_type) &&
  26. strides[3] == sizeof(typename traits::arg2_t);
  27. }
  28. template <typename func_t, typename vec_func_t>
  29. static inline void vectorized_reduction(char** data, int64_t n, int64_t stride,
  30. func_t op, vec_func_t vop, bool reduce) {
  31. VEC_LOOP_HEADER(func_t, data)
  32. const char* in1_ptr = data[1];
  33. Vec acc[4];
  34. for (const auto j : c10::irange(4)) {
  35. acc[j] = Vec::loadu(in1_ptr + j * Vec::size() * sizeof(scalar_t));
  36. }
  37. for (const auto i : c10::irange(1, n)) {
  38. const char* ptr = in1_ptr + stride * i;
  39. acc[0] = vop(acc[0], Vec::loadu(ptr + (0 * Vec::size() * sizeof(scalar_t))));
  40. acc[1] = vop(acc[1], Vec::loadu(ptr + (1 * Vec::size() * sizeof(scalar_t))));
  41. acc[2] = vop(acc[2], Vec::loadu(ptr + (2 * Vec::size() * sizeof(scalar_t))));
  42. acc[3] = vop(acc[3], Vec::loadu(ptr + (3 * Vec::size() * sizeof(scalar_t))));
  43. }
  44. if (reduce) {
  45. scalar_t buffer[Vec::size()];
  46. acc[0] = vop(vop(acc[0], acc[1]), vop(acc[2], acc[3]));
  47. acc[0].store(buffer);
  48. for (const auto j : c10::irange(1, Vec::size())) {
  49. buffer[0] = op(buffer[0], buffer[j]);
  50. }
  51. auto dst = (scalar_t*)out_ptr;
  52. *dst = op(*dst, buffer[0]);
  53. } else {
  54. for (const auto j : c10::irange(4)) {
  55. auto dst = out_ptr + j * Vec::size() * sizeof(scalar_t);
  56. acc[j] = vop(acc[j], Vec::loadu(dst));
  57. acc[j].store(dst);
  58. }
  59. }
  60. }
  61. template <typename F>
  62. static inline void UNARY_OUTER_LOOP(char* data[2], const int64_t strides[2], int64_t n, F f) {
  63. for (const auto j C10_UNUSED : c10::irange(n)) {
  64. f();
  65. data[0] += strides[0];
  66. data[1] += strides[1];
  67. }
  68. }
  69. // computes the reduction out = op(out, in)
  70. template <typename func_t, typename vec_func_t>
  71. static inline void vectorized_inner_reduction(char** data, int64_t n, func_t op, vec_func_t vop) {
  72. VEC_LOOP_HEADER(func_t, data)
  73. int64_t vector_stride = 4 * Vec::size() * sizeof(scalar_t);
  74. int64_t count = n / (4 * Vec::size());
  75. if (count > 0) {
  76. vectorized_reduction(data, count, vector_stride, op, vop, /*reduce=*/true);
  77. }
  78. char* ptrs[3] = { data[0], data[0], data[1] };
  79. int64_t strides[] = { 0, 0, sizeof(scalar_t) };
  80. basic_loop(ptrs, strides, count * 4 * Vec::size(), n, op);
  81. }
  82. // computes the reduction out = op(out, in)
  83. template <typename func_t, typename vec_func_t>
  84. static inline void vectorized_outer_reduction(char** data, int64_t inner_stride, int64_t size0, int64_t size1, func_t op, vec_func_t vop) {
  85. VEC_LOOP_HEADER(func_t, data)
  86. // reduce down each column of 4 * Vec::size() elements (128 or 256 bytes)
  87. #if defined(CPU_CAPABILITY_AVX512)
  88. int64_t outer_stride[2] = { 256, 256 };
  89. #else
  90. int64_t outer_stride[2] = { 128, 128 };
  91. #endif
  92. UNARY_OUTER_LOOP(data, outer_stride, size1 / (4 * Vec::size()), [&] {
  93. vectorized_reduction(data, size0, inner_stride, op, vop, /*reduce=*/false);
  94. });
  95. // reduce down the remaining columns
  96. int64_t step[] = { sizeof(scalar_t), sizeof(scalar_t) };
  97. int64_t remaining = size1 % (4 * Vec::size());
  98. UNARY_OUTER_LOOP(data, step, remaining, [&] {
  99. char* ptrs[3] = { data[0], data[0], data[1] };
  100. int64_t strides[] = { 0, 0, inner_stride };
  101. basic_loop(ptrs, strides, 0, size0, op);
  102. });
  103. }
  104. template<typename traits, typename res_t>
  105. static void set_result(const int index, const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
  106. // static_assert(std::is_same<res_t, typename traits::arg2_t>::value, "data types must match");
  107. if (index < num_outputs) {
  108. char *out = (char *) iter.data_ptr(index);
  109. *(res_t *) out = result;
  110. }
  111. }
  112. template<typename traits, typename res_t>
  113. static void set_results(const res_t result, const TensorIteratorBase &iter, const int num_outputs) {
  114. AT_ASSERT(num_outputs == 1);
  115. set_result<traits>(0, result, iter, num_outputs);
  116. }
  117. template<typename traits, std::size_t i = 0, typename... tuple_t>
  118. static inline typename std::enable_if<i == sizeof...(tuple_t), std::size_t>::type
  119. for_each_in_tuple(const std::tuple<tuple_t...>& /*t*/, const TensorIteratorBase& /*iter*/, const int /*num_outputs*/) {
  120. return i;
  121. }
  122. template<typename traits, std::size_t i = 0, typename... tuple_t>
  123. static inline typename std::enable_if<i < sizeof...(tuple_t), std::size_t>::type
  124. for_each_in_tuple(const std::tuple<tuple_t...>& t, const TensorIteratorBase &iter, const int num_outputs) {
  125. if (i < (size_t)num_outputs) {
  126. set_result<traits>(i, std::get<i>(t), iter, num_outputs);
  127. return for_each_in_tuple<traits, i + 1, tuple_t...>(t, iter, num_outputs);
  128. }
  129. return i;
  130. }
  131. template<typename traits, typename... res_t>
  132. static void set_results(const std::tuple<res_t...>& result, const TensorIteratorBase &iter, const int num_outputs) {
  133. AT_ASSERT(num_outputs >= 1);
  134. std::size_t result_size = for_each_in_tuple<traits>(result, iter, num_outputs);
  135. AT_ASSERT((size_t)num_outputs == result_size);
  136. }
  137. template <typename T, typename... Args>
  138. struct all_same : guts::conjunction<
  139. std::is_same<T, Args>...
  140. > {};
  141. // data_t is the input/output data type.
  142. // acc_t is a type that contains all the necessary data
  143. // to continue reducing.
  144. // index_t is a one-dimensional index
  145. //
  146. // ops_t is such that &ops_t::reduce, &ops_t::combine, and &ops_t::project exist and satisfy
  147. // the following.
  148. // reduce: (acc_t, data_t, index_t) -> acc_t adds one data point to the accumulated value.
  149. // combine: (acc_t, acc_t) -> acc_t combines two accumulated values into one.
  150. // project: acc_t -> out_t finishes the reduction, getting the required output.
  151. //
  152. // Additionally, acc_t must be default-constructible:
  153. // acc_t {} is an identity for combine,
  154. // and project(acc_t {}) is the value of the operation on zero elements.
  155. //
  156. // The point of `combine` is to support parallelization -
  157. // the idea is to one sequence of `reduce` calls per thread of execution,
  158. // and then to combine them at the end with `combine`.
  159. //
  160. // If there is more than one output element,
  161. // our parallelization strategy is to use one thread for each of them,
  162. // which means that `combine` will never be called.
  163. //
  164. // If, on the other hand, there is only one, then we split the input into
  165. // into several pieces, reduce each separately, and then combine them.
  166. template <typename ops_t, typename init_t>
  167. void binary_kernel_reduce(TensorIteratorBase& iter, ops_t ops, init_t init) {
  168. using rf_t = decltype(&ops_t::reduce);
  169. using cf_t = decltype(&ops_t::combine);
  170. using pf_t = decltype(&ops_t::project);
  171. using r_traits = binary_function_traits<rf_t>;
  172. using c_traits = binary_function_traits<cf_t>;
  173. using p_traits = unary_function_traits<pf_t>;
  174. using acc_t = typename p_traits::arg1_t;
  175. using data_t = typename r_traits::arg2_t;
  176. static_assert(
  177. all_same<
  178. acc_t,
  179. init_t,
  180. typename r_traits::arg1_t,
  181. typename r_traits::result_type,
  182. typename c_traits::arg1_t,
  183. typename c_traits::arg2_t,
  184. typename c_traits::result_type>::value,
  185. "all accumulate types must match");
  186. static_assert(
  187. std::is_default_constructible<acc_t>::value,
  188. "the accumulate type must be default-constructible"
  189. );
  190. const int num_outputs = iter.noutputs();
  191. iter.foreach_reduced_elt([&ops, &init, num_outputs](TensorIteratorBase &sub_iter) {
  192. auto reduction_body = [&ops, &sub_iter, num_outputs](acc_t acc, int64_t begin, int64_t end) -> acc_t {
  193. int ntensors = sub_iter.ntensors();
  194. sub_iter.serial_for_each([&acc, &ops, num_outputs, ntensors, begin](char** data, const int64_t* strides, int64_t size) {
  195. AT_ASSERT(ntensors - num_outputs == 1);
  196. char *in = data[ntensors - 1];
  197. int64_t stride = strides[ntensors - 1];
  198. for (const auto i : c10::irange(size)) {
  199. acc = ops.reduce(acc, c10::load<data_t>(in), begin + i);
  200. in += stride;
  201. }
  202. }, {begin, end});
  203. return ops.translate_idx(acc, sub_iter.view_offsets()[0]);
  204. };
  205. acc_t total_acc = init;
  206. auto numel = sub_iter.numel();
  207. if (numel < at::internal::GRAIN_SIZE || at::get_num_threads() == 1 ||
  208. at::in_parallel_region()) {
  209. total_acc = reduction_body(total_acc, 0, numel);
  210. } else {
  211. int max_threads = at::get_num_threads();
  212. AT_ASSERT(max_threads > 0);
  213. static_assert(
  214. !std::is_same<acc_t, bool>::value,
  215. "Concurrently modifying different references into std::vector<bool> is UB."
  216. );
  217. std::vector<acc_t> buffer((unsigned)max_threads, init);
  218. at::parallel_for(0, numel, internal::GRAIN_SIZE,
  219. [&](int64_t begin, int64_t end) {
  220. auto& acc = buffer[at::get_thread_num()];
  221. acc = reduction_body(acc, begin, end);
  222. }
  223. );
  224. for (const auto i : c10::irange(max_threads)) {
  225. total_acc = ops.combine(total_acc, buffer[i]);
  226. }
  227. }
  228. set_results<r_traits>(ops.project(total_acc), sub_iter, num_outputs);
  229. });
  230. }
  231. template <typename func_t, typename vec_func_t>
  232. void binary_kernel_reduce_vec(TensorIteratorBase& iter, func_t op, vec_func_t vop, double ident = 0) {
  233. using traits = binary_function_traits<func_t>;
  234. static_assert(
  235. all_same<
  236. typename traits::result_type,
  237. typename traits::arg1_t,
  238. typename traits::arg2_t>::value,
  239. "all types must match");
  240. iter.output_base().fill_(ident);
  241. iter.parallel_reduce([&](char** data, const int64_t* strides, int64_t size0, int64_t size1) {
  242. int64_t outer_strides[] = { strides[2], strides[3] };
  243. if (is_contiguous_reduction<traits>(strides)) {
  244. // input is contiguous in dim 0, output is reduced in dim 0
  245. UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
  246. vectorized_inner_reduction(data, size0, op, vop);
  247. });
  248. } else if (is_outer_reduction<traits>(strides)) {
  249. // input and output are contiguous in dim 1
  250. int64_t inner_stride = strides[1]; // stride of input in dim 0
  251. vectorized_outer_reduction(data, inner_stride, size0, size1, op, vop);
  252. } else {
  253. UNARY_OUTER_LOOP(data, outer_strides, size1, [&] {
  254. char* ptrs[3] = { data[0], data[0], data[1] };
  255. int64_t inner_strides[3] = { strides[0], strides[0], strides[1] };
  256. basic_loop(ptrs, inner_strides, 0, size0, op);
  257. });
  258. }
  259. });
  260. }
  261. // when reduction is on most inner dimension (dim 0 in TensorIterator)
  262. // and input has contiguous most inner dimension, `binary_kernel_reduce_lastdim`
  263. // can be used.
  264. static inline bool is_reduce_lastdim(TensorIteratorBase& iter) {
  265. return iter.num_reduce_dims() == 1 && iter.is_dim_reduced(0)
  266. && iter.ninputs() == 1 && iter.strides(1)[0] == iter.element_size(1);
  267. }
  268. template <typename reduce_func_t>
  269. void binary_kernel_reduce_lastdim(TensorIteratorBase& iter, reduce_func_t reduce_op) {
  270. auto shape = iter.shape();
  271. int64_t dim_size = shape[0];
  272. int64_t grain_size = std::max((int64_t) 1, at::internal::GRAIN_SIZE / dim_size);
  273. TensorIterator sub_iter(iter);
  274. // create sub iterator to parallel on all non-reduce-dims
  275. sub_iter.narrow(0, 0, 1);
  276. auto loop = [&](char** data, const int64_t* strides, int64_t size) {
  277. char* out = data[0];
  278. char* in = data[1];
  279. for (int64_t i = 0; i < size; ++i) {
  280. reduce_op(out, in, dim_size);
  281. out += strides[0];
  282. in += strides[1];
  283. }
  284. };
  285. sub_iter.for_each(loop, grain_size);
  286. }
  287. }}} // namespace at::native::<anonymous>