Parallel-inl.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #pragma once
  2. #include <c10/util/Exception.h>
  3. #include <c10/util/SmallVector.h>
  4. namespace at {
  5. template <class F>
  6. inline void parallel_for(
  7. const int64_t begin,
  8. const int64_t end,
  9. const int64_t grain_size,
  10. const F& f) {
  11. TORCH_INTERNAL_ASSERT_DEBUG_ONLY(grain_size >= 0);
  12. if (begin >= end) {
  13. return;
  14. }
  15. #ifdef INTRA_OP_PARALLEL
  16. at::internal::lazy_init_num_threads();
  17. const auto numiter = end - begin;
  18. const bool use_parallel =
  19. (numiter > grain_size && numiter > 1 && !at::in_parallel_region() &&
  20. at::get_num_threads() > 1);
  21. if (!use_parallel) {
  22. internal::ThreadIdGuard tid_guard(0);
  23. f(begin, end);
  24. return;
  25. }
  26. internal::invoke_parallel(begin, end, grain_size, f);
  27. #else
  28. internal::ThreadIdGuard tid_guard(0);
  29. f(begin, end);
  30. #endif
  31. }
  32. template <class scalar_t, class F, class SF>
  33. inline scalar_t parallel_reduce(
  34. const int64_t begin,
  35. const int64_t end,
  36. const int64_t grain_size,
  37. const scalar_t ident,
  38. const F& f,
  39. const SF& sf) {
  40. TORCH_CHECK(grain_size >= 0);
  41. if (begin >= end) {
  42. return ident;
  43. }
  44. #ifdef INTRA_OP_PARALLEL
  45. at::internal::lazy_init_num_threads();
  46. const auto max_threads = at::get_num_threads();
  47. const bool use_parallel =
  48. ((end - begin) > grain_size && !at::in_parallel_region() &&
  49. max_threads > 1);
  50. if (!use_parallel) {
  51. internal::ThreadIdGuard tid_guard(0);
  52. return f(begin, end, ident);
  53. }
  54. c10::SmallVector<scalar_t, 64> results(max_threads, ident);
  55. internal::invoke_parallel(
  56. begin,
  57. end,
  58. grain_size,
  59. [&](const int64_t my_begin, const int64_t my_end) {
  60. const auto tid = at::get_thread_num();
  61. results[tid] = f(my_begin, my_end, ident);
  62. });
  63. scalar_t result = ident;
  64. for (auto partial_result : results) {
  65. result = sf(result, partial_result);
  66. }
  67. return result;
  68. #else
  69. internal::ThreadIdGuard tid_guard(0);
  70. return f(begin, end, ident);
  71. #endif
  72. }
  73. } // namespace at