CUDALoops.cuh 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 <iostream>
  30. #include <tuple>
  31. #include <type_traits>
  32. #include <ATen/core/Array.h>
  33. #include <ATen/cuda/CUDAContext.h>
  34. #include <ATen/detail/FunctionTraits.h>
  35. #include <ATen/native/TensorIterator.h>
  36. #include <c10/core/DynamicCast.h>
  37. #include <c10/core/ScalarType.h>
  38. #include <c10/macros/Macros.h>
  39. #include <c10/util/TypeCast.h>
  40. #ifdef __NVCC__
  41. #define ASSERT_HOST_DEVICE_LAMBDA(type) \
  42. static_assert( \
  43. __nv_is_extended_host_device_lambda_closure_type(type), \
  44. #type " must be a __host__ __device__ lambda")
  45. #else
  46. #define ASSERT_HOST_DEVICE_LAMBDA(type)
  47. #endif
  48. namespace at {
  49. namespace native {
  50. template <int vec_size, typename func_t, typename array_t>
  51. C10_LAUNCH_BOUNDS_1(num_threads())
  52. __global__ void vectorized_elementwise_kernel(int N, func_t f, array_t data) {
  53. using traits = function_traits<func_t>;
  54. int remaining = N - block_work_size() * blockIdx.x;
  55. if (remaining < block_work_size()) { // if this block handles the reminder,
  56. // just do a naive unrolled loop
  57. auto input_calc = TrivialOffsetCalculator<traits::arity>();
  58. auto output_calc = TrivialOffsetCalculator<1>();
  59. auto loader = memory::LoadWithoutCast();
  60. auto storer = memory::StoreWithoutCast();
  61. auto policy = memory::policies::unroll<
  62. array_t,
  63. decltype(input_calc),
  64. decltype(output_calc),
  65. memory::LoadWithoutCast,
  66. memory::StoreWithoutCast>(
  67. data, remaining, input_calc, output_calc, loader, storer);
  68. elementwise_kernel_helper(f, policy);
  69. } else { // if this block has a full `block_work_size` data to handle, use
  70. // vectorized memory access
  71. elementwise_kernel_helper(
  72. f, memory::policies::vectorized<vec_size, array_t>(data));
  73. }
  74. }
  75. template <
  76. typename func_t,
  77. typename array_t,
  78. typename inp_calc_t,
  79. typename out_calc_t,
  80. typename loader_t,
  81. typename storer_t>
  82. C10_LAUNCH_BOUNDS_1(num_threads())
  83. __global__ void unrolled_elementwise_kernel(
  84. int N,
  85. func_t f,
  86. array_t data,
  87. inp_calc_t ic,
  88. out_calc_t oc,
  89. loader_t l,
  90. storer_t s) {
  91. int remaining = N - block_work_size() * blockIdx.x;
  92. auto policy = memory::policies::
  93. unroll<array_t, inp_calc_t, out_calc_t, loader_t, storer_t>(
  94. data, remaining, ic, oc, l, s);
  95. elementwise_kernel_helper(f, policy);
  96. }
  97. // this function assume trivial 1d and no dynamic casting
  98. template <typename func_t, typename array_t>
  99. static inline void launch_vectorized_kernel(
  100. int64_t N,
  101. const func_t& f,
  102. array_t data) {
  103. TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
  104. using traits = function_traits<func_t>;
  105. int64_t grid = (N + block_work_size() - 1) / block_work_size();
  106. auto stream = at::cuda::getCurrentCUDAStream();
  107. int vec_size = memory::can_vectorize_up_to<func_t>(data);
  108. switch (vec_size) {
  109. case 4:
  110. vectorized_elementwise_kernel<4, func_t, array_t>
  111. <<<grid, num_threads(), 0, stream>>>(N, f, data);
  112. C10_CUDA_KERNEL_LAUNCH_CHECK();
  113. break;
  114. case 2:
  115. vectorized_elementwise_kernel<2, func_t, array_t>
  116. <<<grid, num_threads(), 0, stream>>>(N, f, data);
  117. C10_CUDA_KERNEL_LAUNCH_CHECK();
  118. break;
  119. case 1: {
  120. auto input_calc = TrivialOffsetCalculator<traits::arity>();
  121. auto output_calc = TrivialOffsetCalculator<1>();
  122. auto loader = memory::LoadWithoutCast();
  123. auto storer = memory::StoreWithoutCast();
  124. unrolled_elementwise_kernel<func_t, array_t>
  125. <<<grid, num_threads(), 0, stream>>>(
  126. N, f, data, input_calc, output_calc, loader, storer);
  127. C10_CUDA_KERNEL_LAUNCH_CHECK();
  128. break;
  129. }
  130. default:
  131. TORCH_INTERNAL_ASSERT(false, "Unexpected vectorization size");
  132. }
  133. }
  134. template <
  135. typename func_t,
  136. typename array_t,
  137. typename inp_calc_t,
  138. typename out_calc_t,
  139. typename loader_t,
  140. typename storer_t>
  141. static inline void launch_unrolled_kernel(
  142. int64_t N,
  143. const func_t& f,
  144. array_t data,
  145. inp_calc_t ic,
  146. out_calc_t oc,
  147. loader_t l,
  148. storer_t s) {
  149. TORCH_INTERNAL_ASSERT(N > 0 && N <= std::numeric_limits<int32_t>::max());
  150. int64_t grid = (N + block_work_size() - 1) / block_work_size();
  151. auto stream = at::cuda::getCurrentCUDAStream();
  152. unrolled_elementwise_kernel<func_t, array_t>
  153. <<<grid, num_threads(), 0, stream>>>(N, f, data, ic, oc, l, s);
  154. C10_CUDA_KERNEL_LAUNCH_CHECK();
  155. }
  156. template <int nt, int vt, typename func_t>
  157. C10_LAUNCH_BOUNDS_2(nt, 4)
  158. __global__ void elementwise_kernel(int N, func_t f) {
  159. int tid = threadIdx.x;
  160. int nv = nt * vt;
  161. int idx = nv * blockIdx.x + tid;
  162. #pragma unroll
  163. for (int i = 0; i < vt; i++) {
  164. if (idx < N) {
  165. f(idx);
  166. idx += nt;
  167. }
  168. }
  169. }
  170. template <int nt, int vt, typename func_t>
  171. static void launch_legacy_kernel(int64_t N, const func_t& f) {
  172. TORCH_INTERNAL_ASSERT(N >= 0 && N <= std::numeric_limits<int32_t>::max());
  173. if (N == 0) {
  174. return;
  175. }
  176. dim3 block(nt);
  177. dim3 grid((N + block.x * vt - 1) / (block.x * vt));
  178. auto stream = at::cuda::getCurrentCUDAStream();
  179. elementwise_kernel<nt, vt, func_t><<<grid, block, 0, stream>>>(N, f);
  180. C10_CUDA_KERNEL_LAUNCH_CHECK();
  181. }
  182. template <typename traits, typename func_t, typename index_t, size_t... INDEX>
  183. C10_HOST_DEVICE typename traits::result_type invoke_impl(
  184. const func_t& f,
  185. char* const C10_RESTRICT data[],
  186. const index_t strides[],
  187. int i,
  188. std::index_sequence<INDEX...>) {
  189. (void)strides;
  190. (void)i;
  191. return f(c10::load<typename traits::template arg<INDEX>::type>(
  192. data[INDEX] + i * strides[INDEX])...);
  193. }
  194. template <
  195. typename func_t,
  196. typename index_t,
  197. typename traits = function_traits<func_t>>
  198. C10_HOST_DEVICE typename traits::result_type invoke(
  199. const func_t& f,
  200. char* const C10_RESTRICT data[],
  201. const index_t strides[],
  202. int i) {
  203. using Indices = std::make_index_sequence<traits::arity>;
  204. return invoke_impl<traits>(f, data, strides, i, Indices{});
  205. }
  206. template <typename traits, typename func_t, typename index_t, size_t... I>
  207. C10_HOST_DEVICE typename traits::result_type invoke_impl(
  208. const func_t& f,
  209. char* const C10_RESTRICT data[],
  210. const index_t strides[],
  211. const ScalarType dtypes[],
  212. int i,
  213. std::index_sequence<I...>) {
  214. (void)strides;
  215. (void)i;
  216. return f(c10::fetch_and_cast<typename traits::template arg<I>::type>(
  217. dtypes[I], data[I] + i * strides[I])...);
  218. }
  219. template <
  220. typename func_t,
  221. typename index_t,
  222. typename traits = function_traits<func_t>>
  223. C10_HOST_DEVICE typename traits::result_type invoke(
  224. const func_t& f,
  225. char* const C10_RESTRICT data[],
  226. const index_t strides[],
  227. const ScalarType dtypes[],
  228. int i) {
  229. using Indices = std::make_index_sequence<traits::arity>;
  230. return invoke_impl<traits>(f, data, strides, dtypes, i, Indices{});
  231. }
  232. template <typename func_t>
  233. void gpu_kernel_impl_nocast(TensorIteratorBase& iter, const func_t& f) {
  234. using traits = function_traits<func_t>;
  235. using arg0_t = typename traits::result_type;
  236. constexpr int ntensors = traits::arity + 1;
  237. TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
  238. TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
  239. TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
  240. TORCH_INTERNAL_ASSERT(!needs_dynamic_casting<func_t>::check(iter));
  241. at::detail::Array<char*, ntensors> data;
  242. for (int i = 0; i < ntensors; i++) {
  243. data[i] = (char*)iter.data_ptr(i);
  244. }
  245. int64_t numel = iter.numel();
  246. bool contiguous = iter.is_contiguous();
  247. if (contiguous) {
  248. return launch_vectorized_kernel(numel, f, data);
  249. }
  250. auto offset_calc = ::make_offset_calculator<traits::arity + 1>(iter);
  251. constexpr int unroll_factor = sizeof(arg0_t) >= 4 ? 2 : 4;
  252. launch_legacy_kernel<128, unroll_factor>(numel, [=] GPU_LAMBDA(int idx) {
  253. auto offsets = offset_calc.get(idx);
  254. arg0_t* out = (arg0_t*)(data[0] + offsets[0]);
  255. *out = invoke(f, &data.data[1], &offsets.data[1], 1);
  256. });
  257. }
  258. template <typename func_t>
  259. void gpu_kernel_impl(TensorIteratorBase& iter, const func_t& f) {
  260. if (!needs_dynamic_casting<func_t>::check(iter)) {
  261. return gpu_kernel_impl_nocast(iter, f);
  262. }
  263. using traits = function_traits<func_t>;
  264. using arg0_t = typename traits::result_type;
  265. constexpr int ntensors = traits::arity + 1;
  266. TORCH_INTERNAL_ASSERT(iter.can_use_32bit_indexing());
  267. TORCH_INTERNAL_ASSERT(iter.ninputs() == traits::arity);
  268. TORCH_INTERNAL_ASSERT(iter.noutputs() == 1);
  269. at::detail::Array<char*, ntensors> data;
  270. for (int i = 0; i < ntensors; i++) {
  271. data[i] = (char*)iter.data_ptr(i);
  272. }
  273. int64_t numel = iter.numel();
  274. bool contiguous = iter.is_contiguous();
  275. if (contiguous) {
  276. #ifdef USE_ROCM
  277. at::detail::Array<ScalarType, ntensors> dtypes;
  278. auto inner_strides = iter.get_inner_strides();
  279. at::detail::Array<int, ntensors> strides;
  280. for (int i = 0; i < ntensors; i++) {
  281. dtypes[i] = iter.dtype(i);
  282. strides[i] = inner_strides[i];
  283. }
  284. launch_legacy_kernel<512, 1>(numel, [=]GPU_LAMBDA(int idx) {
  285. void* out = data[0] + strides[0] * idx;
  286. arg0_t result = invoke(f, &data.data[1], &strides.data[1], &dtypes.data[1], idx);
  287. c10::cast_and_store<arg0_t>(dtypes[0], out, result);
  288. });
  289. #else
  290. auto loader = memory::LoadWithCast<traits::arity>(iter);
  291. auto storer = memory::StoreWithCast<1>(iter);
  292. auto input_offset_calculator = TrivialOffsetCalculator<traits::arity>();
  293. auto output_offset_calculator = TrivialOffsetCalculator<1>();
  294. launch_unrolled_kernel(
  295. numel,
  296. f,
  297. data,
  298. input_offset_calculator,
  299. output_offset_calculator,
  300. loader,
  301. storer);
  302. #endif
  303. } else {
  304. at::detail::Array<ScalarType, ntensors> dtypes;
  305. for (int i = 0; i < ntensors; i++) {
  306. dtypes[i] = iter.dtype(i);
  307. }
  308. auto offset_calc = ::make_offset_calculator<traits::arity + 1>(iter);
  309. launch_legacy_kernel<128, 4>(numel, [=] GPU_LAMBDA(int idx) {
  310. auto offsets = offset_calc.get(idx);
  311. void* out = data[0] + offsets[0];
  312. arg0_t result = invoke(f, &data.data[1], &offsets.data[1], &dtypes.data[1], 1);
  313. c10::cast_and_store<arg0_t>(dtypes[0], out, result);
  314. });
  315. }
  316. }
  317. } // namespace native
  318. } // namespace at