CUDAApplyUtils.cuh 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. #pragma once
  2. #include <ATen/cuda/ApplyGridUtils.cuh>
  3. #include <ATen/cuda/detail/IndexUtils.cuh>
  4. #include <ATen/core/TensorBase.h>
  5. #include <ATen/ceil_div.h>
  6. #include <ATen/cuda/Atomic.cuh>
  7. #include <ATen/cuda/CUDAContext.h>
  8. #include <c10/macros/Macros.h>
  9. #include <ATen/native/Copy.h>
  10. #include <math.h>
  11. //
  12. // This file contains pointwise operation functions and kernels that
  13. // work on both contiguous and non-contiguous tensor arguments of
  14. // arbitrary (up to MAX_CUTORCH_DIMS) dimensioned arguments without
  15. // copying or temporary storage.
  16. //
  17. /*
  18. NOTE [ CUDA_tensor_applyN helpers ]
  19. The following CUDA_tensor_applyN (where N currently can be 1, 2, 3, or 4)
  20. functions apply a pointwise operator to N tensor(s).
  21. The calling convention is
  22. 1. The template arguments should be, sequentially,
  23. - First N typename args specify the scalar types of each of the N tensors.
  24. - (Optional) `int step` arg specifies the number of elements processed
  25. together at the same time.
  26. Default is 1.
  27. - A usually omitted (i.e., inferred) typename arg specifies the type of the
  28. function/functor applied on `N * step` values in each iteration of each
  29. CUDA thread.
  30. 2. The arguments should be, sequentially,
  31. - N tensors
  32. - op: a function/functor that processes `N * step` values at the same time.
  33. - If `step == 1`, it must have signature
  34. `void(*)(scalar1_t&, scalar2_t&, ..., scalarN_t&)`, where
  35. `scalar*_t`s are the first N typename template args, and the inputs
  36. are the `N` values from the `N` tensors retrieved at a common index.
  37. - Otherwise, it must must have signature
  38. void(*)(int n, scalar1_t&, scalar1_t&, ..., scalar1_t&, // repeat `step` times
  39. scalar2_t&, scalar2_t&, ..., scalar2_t&, // repeat `step` times
  40. ...,
  41. scalarN_t&, scalarN_t&, ..., scalarN_t&) // repeat `step` times
  42. Different from `step == 1` case, it processes `N * step` values taken
  43. from `step` common indices. Moreover, the first input `n` represents the
  44. number of valid indices (it will always have `0 < n <= step`). It will
  45. almost always be `step`, but at the boundary we may not have full `step`
  46. elements and `n` can be a lesser value.
  47. E.g., if `step == 4` and `N == 2`, `op` could be
  48. [](int n, scalar1_t &u1, scalar1_t &u2, scalar1_t &u3, scalar1_t &u4,
  49. scalar2_t &v1, scalar2_t &v2, scalar2_t &v3, scalar2_t &v4) {
  50. // Only process u1, ..., un and v1, ..., vn.
  51. // So if `n == 3`, `u4` and `v4` need not to be considered.
  52. }
  53. In both cases, the references can actually be const, but at least one of
  54. them should be non-const in order to write the output.
  55. - (Optional, but recommended) N TensorArgType args that specify for each
  56. tensor whether `op` reads AND writes ] (i.e., TensorArgType::ReadWrite),
  57. or only reads (i.e., TensorArgType::ReadOnly).
  58. Default is TensorArgType::ReadWrite for first Tensor, and
  59. TensorArgType::ReadOnly for the rest.
  60. E.g.,
  61. to compute a = b^2 for a and b of same dtype, we can call
  62. CUDA_tensor_apply2<scalar, scalar>(
  63. a, b,
  64. [] __device__ (scalar &a_val, const scalar &b_val) { a_val = b_val * b_val; }
  65. );
  66. to work on 2 values at the same time, we can call
  67. CUDA_tensor_apply2<scalar1, scalar2, 2>(
  68. a, b,
  69. [] __device__ (int n, scalar1 &a_val1, scalar1 &a_val2,
  70. const scalar2 &b_val1, const scalar2 &b_val2) {
  71. // call special vectorized op here, or just do elementwise and enjoy unrolling...
  72. // if n == 1, only process a_val1 and b_val1
  73. }
  74. );
  75. */
  76. namespace at::cuda {
  77. // TODO: combine with TensorArg? So far that's been for debugging, and this is functional...
  78. enum class TensorArgType { ReadWrite, ReadOnly };
  79. namespace {
  80. // Rearrange dimensions for pointwise operations so that strides are in
  81. // decreasing order as much as possible, so that kernels have better memory
  82. // access patterns.
  83. //
  84. // For example, consider a binary operation on two "transposed" 2-dim tensors:
  85. // sizes: 256 512
  86. // aInfo->strides: 1 256
  87. // bInfo->strides: 1 256
  88. //
  89. // Given this, each concurrent memory access inside kernelPointwiseApply2() is
  90. // exactly 256 elements apart, resulting in poor performance.
  91. //
  92. // This function exchanges dimensions so that memory access is contiguous:
  93. // sizes: 512 256
  94. // aInfo->strides: 256 1
  95. // bInfo->strides: 256 1
  96. //
  97. // (Actually, it becomes even better because now collapseDims() can turn each
  98. // input into one contiguous array.)
  99. //
  100. // In general, given M (<=4) TensorInfo's with N dimensions, we can view each
  101. // strides[i] (0 <= i < N) as an M-tuple. Given each pair i < j, we exchange
  102. // strides[i] and [j] if
  103. // (1) strides[i][k] < strides[j][k] for some k (0 <= k < M)
  104. // (exchanging them will benefit input #k), and
  105. // (2) strides[i][k] <= strieds[j][k] for all k
  106. // (exchanging them will not make any input worse).
  107. template <typename T1, typename IndexType,
  108. typename T2 = void, typename T3 = void, typename T4 = void>
  109. inline void rearrangeDims(detail::TensorInfo<T1, IndexType>* aInfo,
  110. detail::TensorInfo<T2, IndexType>* bInfo = nullptr,
  111. detail::TensorInfo<T3, IndexType>* cInfo = nullptr,
  112. detail::TensorInfo<T4, IndexType>* dInfo = nullptr) {
  113. int numInfos = 1;
  114. int dims = aInfo->dims;
  115. IndexType *sizes[4] = { aInfo->sizes, };
  116. IndexType *strides[4] = { aInfo->strides, };
  117. if (bInfo != nullptr) {
  118. ++numInfos;
  119. if (bInfo->dims != dims) return;
  120. sizes[1] = bInfo->sizes;
  121. strides[1] = bInfo->strides;
  122. }
  123. if (cInfo != nullptr) {
  124. ++numInfos;
  125. if (cInfo->dims != dims) return;
  126. sizes[2] = cInfo->sizes;
  127. strides[2] = cInfo->strides;
  128. }
  129. if (dInfo != nullptr) {
  130. ++numInfos;
  131. if (dInfo->dims != dims) return;
  132. sizes[3] = dInfo->sizes;
  133. strides[3] = dInfo->strides;
  134. }
  135. // Bail out if sizes do not match: we are using "deprecated pointwise
  136. // behavior" among tensors of different shapes but same number of elements.
  137. for (int i = 1; i < numInfos; ++i) {
  138. for (int j = 0; j < dims; ++j) {
  139. if (sizes[i][j] != sizes[0][j]) return;
  140. }
  141. }
  142. for (int i = 0; i < dims - 1; ++i) {
  143. // No need to consider dimensions of size 1.
  144. if (sizes[0][i] == 1) continue;
  145. for (int j = i + 1; j < dims; ++j) {
  146. if (sizes[0][j] == 1) continue;
  147. // Compare the relative sizes of strides between dim #i and dim #j.
  148. bool hasIncreasingStrides = false;
  149. bool hasDecreasingStrides = false;
  150. for (int k = 0; k < numInfos; k++) {
  151. IndexType stride_i = strides[k][i];
  152. IndexType stride_j = strides[k][j];
  153. if (stride_i < stride_j) {
  154. hasIncreasingStrides = true;
  155. } else if (stride_i > stride_j) {
  156. hasDecreasingStrides = true;
  157. }
  158. }
  159. if (hasIncreasingStrides && !hasDecreasingStrides) {
  160. for (int k = 0; k < numInfos; k++) {
  161. IndexType size = sizes[k][i];
  162. sizes[k][i] = sizes[k][j];
  163. sizes[k][j] = size;
  164. IndexType stride = strides[k][i];
  165. strides[k][i] = strides[k][j];
  166. strides[k][j] = stride;
  167. }
  168. }
  169. }
  170. }
  171. }
  172. // The `remaining_steps` argument is used to support Op that operates on
  173. // multiple elements at the same time. Generally, the strategy of ApplyOpN is to
  174. // 1. Initialize `remaining_steps = step`, where `step` is the template arg of
  175. // CUDA_tensor_applyN helpers. The input arg `n` to `apply()` represents the
  176. // number of elements in bound for this call. It will almost always equal to
  177. // `step` except at boundaries.
  178. // 2. If `remaining_steps > 0` convert the current linearIndex to offset (if in
  179. // bound), and recursively call `ApplyOpN` with `remaining_steps - 1`.
  180. // 3. At `remaining_steps = 0`,
  181. // if `step = 1`, call `op(tensor1_val, tensor2_val, ...)`;
  182. // if `step > 1`, call `op(n, tensor1_val1, tensor1_val2, ..., tesor1_valstep,
  183. // tensor2_val1, tensor2_val2, ..., tesor2_valstep,
  184. // ...
  185. // tensorN_val1, tensorN_val2, ..., tesorN_valstep);`
  186. //
  187. // See NOTE [ CUDA_tensor_applyN helpers ] above for how Op may look like.
  188. template <typename Op,
  189. typename scalar,
  190. typename IndexType,
  191. int ADims,
  192. int remaining_steps,
  193. typename... Offsets>
  194. struct ApplyOp1 {
  195. __device__ __forceinline__
  196. static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
  197. IndexType linearIndex, Offsets... aOffsets) {
  198. // Convert `linearIndex` into an offset of `a`
  199. const IndexType aOffset = sizeof...(Offsets) < n ?
  200. detail::IndexToOffset<scalar, IndexType, ADims>::get(linearIndex, a) : 0;
  201. ApplyOp1<Op, scalar, IndexType, ADims, remaining_steps - 1, const IndexType, Offsets...>::apply(
  202. a, op, n, linearIndex + 1, aOffsets..., aOffset
  203. );
  204. }
  205. };
  206. // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
  207. // We don't need to pass in how many elements need to processed in this case.
  208. template <typename Op,
  209. typename scalar,
  210. typename IndexType,
  211. int ADims,
  212. typename Offset>
  213. struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offset> {
  214. __device__ __forceinline__
  215. static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op,
  216. int n, IndexType linearIndex, Offset offset) {
  217. op(a.data[offset]);
  218. }
  219. };
  220. template <typename Op,
  221. typename scalar,
  222. typename IndexType,
  223. int ADims,
  224. typename... Offsets>
  225. struct ApplyOp1<Op, scalar, IndexType, ADims, 0, Offsets...> {
  226. __device__ __forceinline__
  227. static void apply(detail::TensorInfo<scalar, IndexType> &a, const Op &op, int n,
  228. IndexType linearIndex, Offsets... offsets) {
  229. op(n, a.data[offsets]...);
  230. }
  231. };
  232. template <typename Op,
  233. typename scalar,
  234. typename IndexType,
  235. int ADims,
  236. int step>
  237. #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
  238. C10_LAUNCH_BOUNDS_2(AT_APPLY_THREADS_PER_BLOCK, AT_APPLY_BLOCKS_PER_SM)
  239. #endif
  240. __global__ void kernelPointwiseApply1(detail::TensorInfo<scalar, IndexType> a,
  241. IndexType totalElements, const Op op) {
  242. for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
  243. linearIndex < totalElements;
  244. linearIndex += gridDim.x * blockDim.x * step) {
  245. ApplyOp1<Op, scalar, IndexType, ADims, step>::apply(
  246. a, op, ::min(step, static_cast<int>(totalElements - linearIndex)), linearIndex);
  247. }
  248. }
  249. template <typename Op,
  250. typename scalar1,
  251. typename scalar2,
  252. typename IndexType,
  253. int ADims,
  254. int BDims,
  255. int remaining_steps,
  256. typename... Offsets>
  257. struct ApplyOp2 {
  258. __device__ __forceinline__
  259. static void apply(detail::TensorInfo<scalar1, IndexType> &a,
  260. detail::TensorInfo<scalar2, IndexType> &b,
  261. const Op &op, int64_t n, IndexType linearIndex,
  262. Offsets... aOffsets, Offsets... bOffsets) {
  263. // Convert `linearIndex` into an offset of `a`
  264. const IndexType aOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
  265. detail::IndexToOffset<scalar1, IndexType, ADims>::get(linearIndex, a) : 0;
  266. // Convert `linearIndex` into an offset of `b`
  267. const IndexType bOffset = static_cast<int64_t>(sizeof...(Offsets)) < n ?
  268. detail::IndexToOffset<scalar2, IndexType, BDims>::get(linearIndex, b) : 0;
  269. ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, remaining_steps - 1, const IndexType, Offsets...>::apply(
  270. a, b, op, n, linearIndex + 1, aOffsets..., aOffset, bOffsets..., bOffset
  271. );
  272. }
  273. };
  274. // Specialize `step=1` case (i.e., `remaining_steps=0` and `len(Offsets)=1`).
  275. // We don't need to pass in how many elements need to processed in this case.
  276. template <typename Op,
  277. typename scalar1,
  278. typename scalar2,
  279. typename IndexType,
  280. int ADims,
  281. int BDims,
  282. typename Offset>
  283. struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offset> {
  284. __device__ __forceinline__
  285. static void apply(detail::TensorInfo<scalar1, IndexType> &a,
  286. detail::TensorInfo<scalar2, IndexType> &b,
  287. const Op &op, int /*n*/, IndexType /*linearIndex*/,
  288. Offset aOffset, Offset bOffset) {
  289. op(a.data[aOffset], b.data[bOffset]);
  290. }
  291. };
  292. template <typename Op,
  293. typename scalar1,
  294. typename scalar2,
  295. typename IndexType,
  296. int ADims,
  297. int BDims,
  298. typename... Offsets>
  299. struct ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, 0, Offsets...> {
  300. __device__ __forceinline__
  301. static void apply(detail::TensorInfo<scalar1, IndexType> &a,
  302. detail::TensorInfo<scalar2, IndexType> &b,
  303. const Op &op, int n, IndexType linearIndex,
  304. Offsets... aOffsets, Offsets... bOffsets) {
  305. op(n, a.data[aOffsets]..., b.data[bOffsets]...);
  306. }
  307. };
  308. template <typename Op,
  309. typename scalar1,
  310. typename scalar2,
  311. typename IndexType,
  312. int ADims, int BDims,
  313. int step,
  314. int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
  315. int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
  316. #if __CUDA_ARCH__ >= 350 || defined(USE_ROCM)
  317. C10_LAUNCH_BOUNDS_2(max_threads_per_block, min_blocks_per_sm)
  318. #endif
  319. __global__ void
  320. kernelPointwiseApply2(detail::TensorInfo<scalar1, IndexType> a,
  321. detail::TensorInfo<scalar2, IndexType> b,
  322. IndexType totalElements,
  323. const Op op) {
  324. for (IndexType linearIndex = (blockIdx.x * blockDim.x + threadIdx.x) * step;
  325. linearIndex < totalElements;
  326. linearIndex += gridDim.x * blockDim.x * step) {
  327. ApplyOp2<Op, scalar1, scalar2, IndexType, ADims, BDims, step>::apply(
  328. a, b, op, ::min(step, static_cast<int>(totalElements - linearIndex)),
  329. linearIndex);
  330. }
  331. }
  332. } // anonymous namespace
  333. template <typename scalar1, typename scalar2, int step, typename Op,
  334. int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
  335. int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
  336. inline bool CUDA_tensor_apply2(at::TensorBase a,
  337. at::TensorBase b,
  338. const Op op,
  339. TensorArgType aType = TensorArgType::ReadWrite,
  340. TensorArgType bType = TensorArgType::ReadOnly) {
  341. TORCH_CHECK(a.device().is_cuda() && b.device().is_cuda(),
  342. "CUDA_tensor_apply2: Expected tensors to have CUDA DeviceType, but got "
  343. "tensors with type ", a.device().type(), " and ", b.device().type());
  344. int64_t totalElements = a.numel();
  345. if (totalElements != b.numel()) {
  346. return false;
  347. }
  348. if (a.dim() > MAX_TENSORINFO_DIMS ||
  349. b.dim() > MAX_TENSORINFO_DIMS) {
  350. return false;
  351. }
  352. if (a.numel() == 0) {
  353. // Empty tensor; do nothing
  354. return true;
  355. }
  356. const dim3 block = getApplyBlock(max_threads_per_block);
  357. dim3 grid;
  358. auto curDevice = current_device();
  359. if (curDevice == -1) return false;
  360. if (!getApplyGrid<step>(totalElements, grid, curDevice, max_threads_per_block)) {
  361. return false;
  362. }
  363. /*
  364. Expands readable/writable tensors whose indices may be "overlapped."
  365. This ensures that each element of the tensor is operated on once and only
  366. once.
  367. */
  368. TensorBase oldA;
  369. TensorBase oldB;
  370. if (aType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(a)) {
  371. // Must perform in contiguous space
  372. oldA = std::exchange(a, a.contiguous());
  373. }
  374. if (bType == TensorArgType::ReadWrite && detail::maybeOverlappingIndices(b)) {
  375. // Must perform in contiguous space
  376. oldB = std::exchange(b, b.contiguous());
  377. }
  378. // It is possible that the tensor dimensions are able to be collapsed,
  379. // and thus we can reduce the actual code complexity of the copy by
  380. // exploiting this knowledge statically, since the div/mod is the
  381. // most expensive part of the operation, more so than memory accesses.
  382. // For instance, when copying a non-contiguous to a contiguous tensor
  383. // (or vice versa), the contiguous tensor can be collapsed to one
  384. // dimension, and the loop to translate the linear index to the array
  385. // index can be similarly collapsed. That is what this unrolling is for.
  386. #define HANDLE_CASE(TYPE, A, B) \
  387. kernelPointwiseApply2<Op, \
  388. scalar1, \
  389. scalar2, \
  390. TYPE, A, B, step, \
  391. max_threads_per_block, \
  392. min_blocks_per_sm> \
  393. <<<grid, block, 0, at::cuda::getCurrentCUDAStream(curDevice)>>>( \
  394. aInfo, bInfo, static_cast<TYPE>(totalElements), op); \
  395. C10_CUDA_KERNEL_LAUNCH_CHECK();
  396. #define HANDLE_B_CASE(TYPE, A, B) { \
  397. switch (B) { \
  398. case 1: \
  399. HANDLE_CASE(TYPE, A, 1); \
  400. break; \
  401. case 2: \
  402. HANDLE_CASE(TYPE, A, 2); \
  403. break; \
  404. default: \
  405. HANDLE_CASE(TYPE, A, -1); \
  406. break; \
  407. } \
  408. }
  409. #define HANDLE_A_CASE(TYPE, A, B) { \
  410. switch (A) { \
  411. case 1: \
  412. HANDLE_B_CASE(TYPE, 1, B); \
  413. break; \
  414. case 2: \
  415. HANDLE_B_CASE(TYPE, 2, B); \
  416. break; \
  417. default: \
  418. HANDLE_B_CASE(TYPE, -1, B); \
  419. break; \
  420. } \
  421. }
  422. if (detail::canUse32BitIndexMath(a) &&
  423. detail::canUse32BitIndexMath(b)) {
  424. detail::TensorInfo<scalar1, unsigned int> aInfo =
  425. detail::getTensorInfo<scalar1, unsigned int>(a);
  426. detail::TensorInfo<scalar2, unsigned int> bInfo =
  427. detail::getTensorInfo<scalar2, unsigned int>(b);
  428. rearrangeDims(&aInfo, &bInfo);
  429. aInfo.collapseDims();
  430. bInfo.collapseDims();
  431. HANDLE_A_CASE(unsigned int, aInfo.dims, bInfo.dims);
  432. } else {
  433. detail::TensorInfo<scalar1, uint64_t> aInfo =
  434. detail::getTensorInfo<scalar1, uint64_t>(a);
  435. detail::TensorInfo<scalar2, uint64_t> bInfo =
  436. detail::getTensorInfo<scalar2, uint64_t>(b);
  437. rearrangeDims(&aInfo, &bInfo);
  438. aInfo.collapseDims();
  439. bInfo.collapseDims();
  440. /*
  441. Only instantiates the all 1D special case and the fallback all nD case for
  442. large (64-bit indexed) tensors to reduce compilation time.
  443. */
  444. if (aInfo.dims == 1 && bInfo.dims == 1) {
  445. HANDLE_CASE(uint64_t, 1, 1);
  446. } else {
  447. HANDLE_CASE(uint64_t, -1, -1);
  448. }
  449. }
  450. #undef HANDLE_CASE
  451. #undef HANDLE_B_CASE
  452. #undef HANDLE_A_CASE
  453. if (oldA.defined()) {
  454. at::native::copy_ignoring_overlaps(oldA, a);
  455. }
  456. if (oldB.defined()) {
  457. at::native::copy_ignoring_overlaps(oldB, b);
  458. }
  459. return true;
  460. }
  461. /* Provides default step = 1 to CUDA_tensor_apply2. */
  462. template <typename scalar1, typename scalar2, typename Op,
  463. int max_threads_per_block=AT_APPLY_THREADS_PER_BLOCK,
  464. int min_blocks_per_sm=AT_APPLY_BLOCKS_PER_SM>
  465. inline bool CUDA_tensor_apply2(const at::TensorBase &a,
  466. const at::TensorBase &b,
  467. const Op op,
  468. TensorArgType aType = TensorArgType::ReadWrite,
  469. TensorArgType bType = TensorArgType::ReadOnly) {
  470. return CUDA_tensor_apply2<scalar1, scalar2, 1, Op,
  471. max_threads_per_block, min_blocks_per_sm>(a, b, op, aType, bType);
  472. }
  473. } // namespace at::cuda