ROCmLoops.cuh 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. #pragma once
  2. // This file provides two functions to help write GPU elementwise kernels:
  3. //
  4. // gpu_kernel(TensorIterator iter, <lambda>)
  5. // gpu_kernel_with_scalars(TensorIterator iter, <lambda>)
  6. //
  7. // The gpu_kernel_with_scalars generates specializations that support a
  8. // single scalar CPU argument, such as from `cuda_tensor + 5`. The CPU scalar
  9. // is lifted to a kernel parameter instead of copying to device memory.
  10. // This should be used in conjunction with TensorIterator::allow_cpu_scalars_,
  11. // which is the default for TensorIterator::binary_op. Otherwise, all inputs
  12. // and the output must be on the GPU.
  13. //
  14. // For example, to write a reciprocal kernel for GPU float Tensors:
  15. //
  16. // gpu_kernel(iter, []GPU_LAMBDA(float a) {
  17. // return 1.0f / a;
  18. // });
  19. //
  20. // To write a multiplication kernel for GPU float Tensors where one argument
  21. // may be a CPU scalar:
  22. //
  23. // gpu_kernel_with_scalars(iter, []GPU_LAMBDA(float a, float b) {
  24. // return a * b;
  25. // });
  26. //
  27. // See BinaryOpsKernel.cu for the complete implementation
  28. //
  29. #include <type_traits>
  30. #include <ATen/cuda/CUDAContext.h>
  31. #include <ATen/core/Array.h>
  32. #include <ATen/cuda/detail/OffsetCalculator.cuh>
  33. #include <ATen/detail/FunctionTraits.h>
  34. #include <ATen/native/TensorIterator.h>
  35. #include <c10/macros/Macros.h>
  36. #include <c10/core/ScalarType.h>
  37. #include <c10/core/DynamicCast.h>
  38. #ifdef __NVCC__
  39. #define ASSERT_HOST_DEVICE_LAMBDA(type) \
  40. static_assert(__nv_is_extended_host_device_lambda_closure_type(type), \
  41. #type " must be a __host__ __device__ lambda")
  42. #else
  43. #define ASSERT_HOST_DEVICE_LAMBDA(type)
  44. #endif
  45. static constexpr int launch_size_1d = 512;
  46. static constexpr int launch_size_nd = 128;
  47. static constexpr int launch_bound2 = 4;
  48. namespace at { namespace native {
  49. // See [NOTE: Complex Operator Unification]
  50. // std::complex and thrust::complex don't work with some !needs_dynamic_casting optimizations.
  51. // They always currently map to !needs_dynamic_casting even though we sometimes rely on the ability
  52. // to reinterpret_cast between these representations.
  53. // In order to separate these concerns, we have a check for non-c10 complex separately.
  54. template<typename func_t, int nargs=function_traits<func_t>::arity>
  55. struct uses_non_c10_complex {
  56. constexpr static bool check() {
  57. using traits = function_traits<func_t>;
  58. using type = typename traits::template arg<nargs - 1>::type;
  59. constexpr bool non_c10_complex =
  60. std::is_same<std::complex<float>, type>::value
  61. || std::is_same<std::complex<double>, type>::value
  62. || std::is_same<thrust::complex<float>, type>::value
  63. || std::is_same<thrust::complex<double>, type>::value;
  64. return c10::guts::if_constexpr<non_c10_complex>([]() {
  65. return true;
  66. }, /* else */ []() {
  67. return uses_non_c10_complex<func_t, nargs - 1>::check();
  68. });
  69. }
  70. };
  71. template<typename func_t>
  72. struct uses_non_c10_complex<func_t, 0> {
  73. constexpr static bool check() {
  74. using traits = function_traits<func_t>;
  75. using type = typename traits::result_type;
  76. constexpr bool non_c10_complex =
  77. std::is_same<std::complex<float>, type>::value
  78. || std::is_same<std::complex<double>, type>::value
  79. || std::is_same<thrust::complex<float>, type>::value
  80. || std::is_same<thrust::complex<double>, type>::value;
  81. return non_c10_complex;
  82. }
  83. };
  84. // NOTE: @zasdfgbnm is currently working on rewriting the gpu loops.
  85. // Some of the old codes has been moved to namespace legacy, and
  86. // new codes will be put into namespace modern. These two namespaces
  87. // will coexists for a while until the rewrite is done. Once the rewrite
  88. // is done, we will remove the legacy and modern namespace and everything
  89. // will be in at::native directly.
  90. namespace legacy {
  91. template<int nt, int vt, typename func_t>
  92. C10_LAUNCH_BOUNDS_2(nt, launch_bound2)
  93. __global__ void elementwise_kernel(int N, func_t f) {
  94. int tid = threadIdx.x;
  95. int nv = nt * vt;
  96. int idx = nv * blockIdx.x + tid;
  97. #pragma unroll
  98. for (int i = 0; i < vt; i++) {
  99. if (idx < N) {
  100. f(idx);
  101. idx += nt;
  102. }
  103. }
  104. }
  105. template<int nt, int vt, typename func_t>
  106. static void launch_kernel(int64_t N, const func_t& f) {
  107. TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits<int32_t>::max());
  108. if (N == 0) {
  109. return;
  110. }
  111. dim3 block(nt);
  112. dim3 grid((N + block.x * vt - 1) / (block.x * vt));
  113. auto stream = at::cuda::getCurrentCUDAStream();
  114. elementwise_kernel<nt, vt, func_t><<<grid, block, 0, stream>>>(N, f);
  115. C10_CUDA_KERNEL_LAUNCH_CHECK();
  116. }
  117. template <typename traits, typename func_t, typename index_t, size_t... INDEX>
  118. C10_HOST_DEVICE typename traits::result_type
  119. invoke_impl(const func_t &f, char *const C10_RESTRICT data[], const index_t strides[], int i,
  120. std::index_sequence<INDEX...>) {
  121. return f(c10::load<typename traits::template arg<INDEX>::type>(data[INDEX] + i * strides[INDEX])...);
  122. }
  123. template <typename func_t, typename index_t, typename traits = function_traits<func_t>>
  124. C10_HOST_DEVICE typename traits::result_type
  125. invoke(const func_t &f, char *const C10_RESTRICT data[], const index_t strides[], int i) {
  126. using Indices = std::make_index_sequence<traits::arity>;
  127. return invoke_impl<traits>(f, data, strides, i, Indices{});
  128. }
  129. template <typename traits, typename func_t, typename index_t, size_t... I>
  130. C10_HOST_DEVICE typename traits::result_type
  131. invoke_impl(const func_t &f, char *const C10_RESTRICT data[], const index_t strides[], const ScalarType dtypes[], int i,
  132. std::index_sequence<I...>) {
  133. return f(c10::fetch_and_cast<typename traits::template arg<I>::type>(dtypes[I], data[I] + i * strides[I])...);
  134. }
  135. template <typename func_t, typename index_t, typename traits = function_traits<func_t>>
  136. C10_HOST_DEVICE typename traits::result_type
  137. invoke(const func_t &f, char *const C10_RESTRICT data[], const index_t strides[], const ScalarType dtypes[], int i) {
  138. using Indices = std::make_index_sequence<traits::arity>;
  139. return invoke_impl<traits>(f, data, strides, dtypes, i, Indices{});
  140. }
  141. } // namespace legacy
  142. // See the note for namespace legacy above.
  143. namespace modern {
  144. namespace detail {
  145. template <typename func_t, typename array_t, std::size_t... I>
  146. __device__ inline constexpr decltype(auto) invoke_with_array_impl(func_t f, array_t t, std::index_sequence<I...>)
  147. {
  148. return f(t[I]...);
  149. }
  150. template <typename func_t, typename array_t>
  151. __device__ inline constexpr decltype(auto) invoke_with_array(func_t f, array_t a) {
  152. constexpr auto arity = function_traits<func_t>::arity;
  153. return invoke_with_array_impl(f, a, std::make_index_sequence<arity>{});
  154. }
  155. namespace arg_type {
  156. // We need a way to compute the argument type of a function. But
  157. // for nullary function, it does not really have an argument type
  158. // in this case, we still need to return a valid type, but we don't
  159. // really care what type this is.
  160. struct dont_care {};
  161. template <typename func_t, std::size_t arity>
  162. struct arg_type_helper {
  163. using type = typename function_traits<func_t>::template arg<0>::type;
  164. };
  165. template <typename func_t>
  166. struct arg_type_helper<func_t, 0> {
  167. using type = dont_care;
  168. };
  169. template <typename func_t>
  170. using type = typename arg_type_helper<func_t, function_traits<func_t>::arity>::type;
  171. } // namespace arg_type
  172. template<typename func_t, int remaining=function_traits<func_t>::arity-1>
  173. struct has_same_arg_types {
  174. using traits = function_traits<func_t>;
  175. static constexpr bool value = std::is_same<
  176. typename traits::template arg<remaining>::type,
  177. typename traits::template arg<remaining-1>::type
  178. >::value && has_same_arg_types<func_t, remaining-1>::value;
  179. };
  180. template<typename func_t>
  181. struct has_same_arg_types<func_t, 0> {
  182. static constexpr bool value = true;
  183. };
  184. template<typename func_t>
  185. struct has_same_arg_types<func_t, -1> {
  186. static constexpr bool value = true;
  187. };
  188. } // namespace detail
  189. template<typename func_t, typename array_t>
  190. C10_LAUNCH_BOUNDS_1(num_threads())
  191. __global__ void elementwise_kernel(int N, func_t f, array_t data) {
  192. // Assumption:
  193. // 1. all arguments of `f` have the same type, which could be different from the return type of `f`
  194. // 2. all tensors are contiguous, that is: stride == sizeof(type) for all tensors
  195. using traits = function_traits<func_t>;
  196. using return_t = typename traits::result_type;
  197. using arg_t = detail::arg_type::type<func_t>;
  198. constexpr int arity = traits::arity;
  199. // We need to create array to hold all the arguments, for nullary `f`, this means array of size 0.
  200. // Unfortunately the compiler don't allow us to create array of 0 size, so for this case, we create
  201. // an array of size 1 and just don't use it.
  202. constexpr int nargs = traits::arity == 0 ? 1 : traits::arity;
  203. int tid = threadIdx.x;
  204. int idx = block_work_size() * blockIdx.x + tid;
  205. // compute base pointers
  206. return_t *result_base = reinterpret_cast<return_t *>(data[0]) + idx;
  207. arg_t *args_base[nargs];
  208. #pragma unroll
  209. for (int i = 0; i < arity; i++) {
  210. args_base[i] = reinterpret_cast<arg_t *>(data[i + 1]) + idx;
  211. }
  212. // fetch data
  213. return_t results[thread_work_size()];
  214. arg_t args[thread_work_size()][nargs];
  215. #pragma unroll
  216. for (int i = 0; i < thread_work_size(); i++) {
  217. if (idx + num_threads() * i < N) {
  218. #pragma unroll
  219. for (int j = 0; j < arity; j++) {
  220. args[i][j] = c10::load(args_base[j] + i * num_threads());
  221. }
  222. }
  223. }
  224. // compute
  225. #pragma unroll
  226. for (int i = 0; i < thread_work_size(); i++) {
  227. if (idx + num_threads() * i < N) {
  228. results[i] = detail::invoke_with_array<func_t, arg_t[nargs]>(f, args[i]);
  229. }
  230. }
  231. // store data
  232. #pragma unroll
  233. for (int i = 0; i < thread_work_size(); i++) {
  234. if (idx + num_threads() * i < N) {
  235. *(result_base + i * num_threads()) = results[i];
  236. }
  237. }
  238. }
  239. // TODO (@zasdfgbnm): this function assume trivial 1d and no dynamic casting
  240. template<typename func_t, typename array_t, std::enable_if_t<detail::has_same_arg_types<func_t>::value, int> = 0>
  241. static void launch_kernel(int64_t N, const func_t& f, array_t data) {
  242. TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits<int32_t>::max());
  243. if (N == 0) {
  244. return;
  245. }
  246. int64_t grid = (N + block_work_size() - 1) / block_work_size();
  247. auto stream = at::cuda::getCurrentCUDAStream();
  248. elementwise_kernel<func_t, array_t><<<grid, num_threads(), 0, stream>>>(N, f, data);
  249. C10_CUDA_KERNEL_LAUNCH_CHECK();
  250. }
  251. template<typename func_t, typename array_t, std::enable_if_t<!detail::has_same_arg_types<func_t>::value, int> = 0>
  252. static void launch_kernel(int64_t N, const func_t& f, array_t data) {}
  253. } // namespace modern
  254. template <typename func_t>
  255. void gpu_kernel_impl(TensorIteratorBase& iter, const func_t& f) {
  256. using traits = function_traits<func_t>;
  257. using arg0_t = typename traits::result_type;
  258. constexpr int ntensors = traits::arity + 1;
  259. TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
  260. TORCH_INTERNAL_ASSERT(iter.ntensors() == traits::arity + 1);
  261. bool non_c10_complex = uses_non_c10_complex<func_t>::check();
  262. at::detail::Array<char*, ntensors> data;
  263. for (int i = 0; i < ntensors; i++) {
  264. data[i] = (char*)iter.data_ptr(i);
  265. }
  266. at::detail::Array<ScalarType, ntensors> dtypes;
  267. for (int i = 0; i < ntensors; i++) {
  268. dtypes[i] = iter.dtype(i);
  269. }
  270. int64_t numel = iter.numel();
  271. if (iter.is_trivial_1d()) {
  272. auto inner_strides = iter.get_inner_strides();
  273. at::detail::Array<int, ntensors> strides;
  274. for (int i = 0; i < ntensors; i++) {
  275. strides[i] = inner_strides[i];
  276. }
  277. // TODO: can non_c10_complex go through the other path? Need to verify.
  278. if (needs_dynamic_casting<func_t>::check(iter) || non_c10_complex) {
  279. legacy::launch_kernel<launch_size_1d, 1>(numel, [=]GPU_LAMBDA(int idx) {
  280. void* out = data[0] + strides[0] * idx;
  281. arg0_t result = legacy::invoke(f, &data.data[1], &strides.data[1], &dtypes.data[1], idx);
  282. c10::cast_and_store<arg0_t>(dtypes[0], out, result);
  283. });
  284. } else if (iter.has_contiguous_first_dim() && modern::detail::has_same_arg_types<func_t>::value) {
  285. modern::launch_kernel(numel, f, data);
  286. } else {
  287. legacy::launch_kernel<launch_size_1d, 1>(numel, [=]GPU_LAMBDA(int idx) {
  288. arg0_t* out = (arg0_t*)(data[0] + strides[0] * idx);
  289. *out = legacy::invoke(f, &data.data[1], &strides.data[1], idx);
  290. });
  291. }
  292. } else {
  293. auto offset_calc = ::make_offset_calculator<traits::arity + 1>(iter);
  294. // TODO: can non_c10_complex go through the other path? Need to verify.
  295. if (needs_dynamic_casting<func_t>::check(iter) || non_c10_complex) {
  296. legacy::launch_kernel<launch_size_nd, launch_bound2>(numel, [=]GPU_LAMBDA(int idx) {
  297. auto offsets = offset_calc.get(idx);
  298. void* out = data[0] + offsets[0];
  299. arg0_t result = legacy::invoke(f, &data.data[1], &offsets.data[1], &dtypes.data[1], 1);
  300. c10::cast_and_store<arg0_t>(dtypes[0], out, result);
  301. });
  302. } else {
  303. legacy::launch_kernel<launch_size_nd, launch_bound2>(numel, [=]GPU_LAMBDA(int idx) {
  304. auto offsets = offset_calc.get(idx);
  305. arg0_t* out = (arg0_t*)(data[0] + offsets[0]);
  306. *out = legacy::invoke(f, &data.data[1], &offsets.data[1], 1);
  307. });
  308. }
  309. }
  310. }
  311. }} // namespace at::native