11#ifndef EIGEN_PARALLELIZER_H
12#define EIGEN_PARALLELIZER_H
15#include "../InternalHeaderCheck.h"
38#if defined(EIGEN_HAS_OPENMP) && defined(EIGEN_GEMM_THREADPOOL)
39#error "EIGEN_HAS_OPENMP and EIGEN_GEMM_THREADPOOL may not both be defined."
45inline void manage_multi_threading(Action action,
int* v);
51EIGEN_DEPRECATED_WITH_REASON(
"Initialization is no longer needed.") inline
void initParallel() {}
57inline int nbThreads() {
59 internal::manage_multi_threading(GetAction, &ret);
67inline void setNbThreads(
int v) { internal::manage_multi_threading(SetAction, &v); }
69#ifdef EIGEN_VECTORIZE_SME
70#ifndef EIGEN_SME_MIN_TASK_SIZE
71#define EIGEN_SME_MIN_TASK_SIZE (double(1 << 20))
76template <
typename Scalar>
78 static constexpr double value = (std::is_same<typename NumTraits<Scalar>::Real,
double>::value ? 4.0 : 1.0) *
79 (NumTraits<Scalar>::IsComplex ? 4.0 : 1.0);
84inline int detect_sme_units() {
85#if defined(EIGEN_SME_UNITS)
86 return EIGEN_SME_UNITS;
90 int32_t cores = 0, per_l2 = 0;
91 size_t sz =
sizeof(cores);
92 if (sysctlbyname(
"hw.perflevel0.physicalcpu", &cores, &sz,
nullptr, 0) != 0 || cores <= 0)
return 0;
94 if (sysctlbyname(
"hw.perflevel0.cpusperl2", &per_l2, &sz,
nullptr, 0) != 0 || per_l2 <= 0)
return 0;
95 return numext::maxi<int32_t>(1, cores / per_l2);
100inline void manage_sme_units(Action action,
int* v) {
101 static int m_units = detect_sme_units();
102 if (action == SetAction)
113inline int nbSmeUnits() {
114#ifdef EIGEN_VECTORIZE_SME
116 internal::manage_sme_units(GetAction, &ret);
127inline void setNbSmeUnits(
int v) {
128#ifdef EIGEN_VECTORIZE_SME
129 internal::manage_sme_units(SetAction, &v);
131 EIGEN_UNUSED_VARIABLE(v);
136#if defined(EIGEN_GEMM_THREADPOOL) || defined(EIGEN_PARSED_BY_DOXYGEN)
170 static ThreadPool* pool =
nullptr;
171 if (new_pool !=
nullptr) {
178 setNbThreads(pool->NumThreads());
196constexpr int kGemmColGrain = 4;
204template <
typename Index>
205EIGEN_ALWAYS_INLINE
void balanced_gemm_range(Index total, Index parts, Index grain, Index part, Index& start,
207 const Index chunks = numext::div_ceil(total, grain);
208 const Index base = chunks / parts;
209 const Index extra = chunks % parts;
210 const Index first_chunk = part * base + numext::mini(part, extra);
211 const Index chunk_count = base + (part < extra ? 1 : 0);
212 start = numext::mini(first_chunk * grain, total);
213 length = numext::mini(chunk_count * grain, total - start);
216#if defined(EIGEN_USE_BLAS) || (!defined(EIGEN_HAS_OPENMP) && !defined(EIGEN_GEMM_THREADPOOL))
218inline void manage_multi_threading(Action action,
int* v) {
219 if (action == SetAction) {
220 eigen_internal_assert(v !=
nullptr);
221 }
else if (action == GetAction) {
222 eigen_internal_assert(v !=
nullptr);
225 eigen_internal_assert(
false);
228template <
typename Index>
229struct GemmParallelInfo {};
230template <
bool Condition,
typename Functor,
typename Index>
231EIGEN_STRONG_INLINE
void parallelize_gemm(
const Functor& func, Index rows, Index cols, Index ,
233 func(0, rows, 0, cols);
238template <
typename Index>
239struct GemmParallelTaskInfo {
240 GemmParallelTaskInfo() {}
241 std::atomic<Index> sync{Index(-1)};
242 std::atomic<int> users{0};
244 Index lhs_length = 0;
247template <
typename Index>
248struct GemmParallelInfo {
249 const int logical_thread_id;
250 const int num_threads;
251 GemmParallelTaskInfo<Index>* task_info;
253 GemmParallelInfo(
int logical_thread_id_,
int num_threads_, GemmParallelTaskInfo<Index>* task_info_)
254 : logical_thread_id(logical_thread_id_), num_threads(num_threads_), task_info(task_info_) {}
257inline void manage_multi_threading(Action action,
int* v) {
258 static int m_maxThreads = -1;
259 if (action == SetAction) {
260 eigen_internal_assert(v !=
nullptr);
261#if defined(EIGEN_HAS_OPENMP)
265 eigen_internal_assert(*v >= 0);
266 int omp_threads = omp_get_max_threads();
267 m_maxThreads = (*v == 0 ? omp_threads : std::min<int>(*v, omp_threads));
268#elif defined(EIGEN_GEMM_THREADPOOL)
272 eigen_internal_assert(*v >= 0);
274 int pool_threads = pool !=
nullptr ? pool->NumThreads() : 1;
275 m_maxThreads = (*v == 0 ? pool_threads : numext::mini(pool_threads, *v));
277 }
else if (action == GetAction) {
278 eigen_internal_assert(v !=
nullptr);
279#if defined(EIGEN_HAS_OPENMP)
280 if (m_maxThreads > 0)
283 *v = omp_get_max_threads();
286 *v = m_maxThreads > 0 ? m_maxThreads : 1;
289 eigen_internal_assert(
false);
293#if defined(EIGEN_GEMM_THREADPOOL)
301class gemm_session_guard {
303 gemm_session_guard() : m_owns(!busy().exchange(true, std::memory_order_acquire)) {}
304 ~gemm_session_guard() {
305 if (m_owns) busy().store(
false, std::memory_order_release);
307 gemm_session_guard(
const gemm_session_guard&) =
delete;
308 gemm_session_guard& operator=(
const gemm_session_guard&) =
delete;
309 bool owns()
const {
return m_owns; }
312 static std::atomic<bool>& busy() {
313 static std::atomic<bool> flag(
false);
320template <
bool Condition,
typename Functor,
typename Index>
321EIGEN_STRONG_INLINE
void parallelize_gemm(
const Functor& func, Index rows, Index cols, Index depth,
bool transpose) {
331 Index size = transpose ? rows : cols;
332 Index pb_max_threads = std::max<Index>(1, size / Functor::Traits::nr);
335 double work =
static_cast<double>(rows) *
static_cast<double>(cols) *
static_cast<double>(depth);
336 double kMinTaskSize = 50000;
337#ifdef EIGEN_VECTORIZE_SME
341 constexpr bool kSme =
342 sme_has_gebp_kernel<typename Functor::Traits::LhsScalar, typename Functor::Traits::RhsScalar>::value;
343 const bool sme_units_known = kSme && nbSmeUnits() > 0;
344 const bool sme_disjoint = sme_units_known && func.ownsNoBuffers();
346 kMinTaskSize = EIGEN_SME_MIN_TASK_SIZE / sme_madd_cost<typename Functor::Traits::LhsScalar>::value;
348 const Index kernel_rows = transpose ? cols : rows, kernel_cols = transpose ? rows : cols;
350 std::max<Index>(1, (std::max)(kernel_rows / Functor::Traits::mr, kernel_cols / Functor::Traits::nr));
353 pb_max_threads = std::max<Index>(1, std::min<Index>(pb_max_threads,
static_cast<Index
>(work / kMinTaskSize)));
356 int threads = std::min<int>(nbThreads(),
static_cast<int>(pb_max_threads));
357#ifdef EIGEN_VECTORIZE_SME
359 EIGEN_IF_CONSTEXPR (kSme) {
360 const int units = nbSmeUnits();
361 if (units > 0) threads = std::min<int>(threads, units);
367 bool dont_parallelize = (!Condition) || (threads <= 1);
368#if defined(EIGEN_HAS_OPENMP)
370 dont_parallelize |= omp_get_num_threads() > 1;
371#elif defined(EIGEN_GEMM_THREADPOOL)
377 dont_parallelize |= (pool ==
nullptr || pool->CurrentThreadId() != -1);
379 if (dont_parallelize)
return func(0, rows, 0, cols);
381#ifdef EIGEN_VECTORIZE_SME
385 EIGEN_IF_CONSTEXPR (kSme) {
390 const Index kernel_rows = transpose ? cols : rows, kernel_cols = transpose ? rows : cols;
391 const Index row_parts = kernel_rows / (8 * Functor::Traits::mr);
392 const bool split_kernel_rows = kernel_rows >= 2 * kernel_cols && row_parts >= 2;
393 const bool split_rows = transpose ? !split_kernel_rows : split_kernel_rows;
394 if (split_kernel_rows) threads =
static_cast<int>((std::min)(Index(threads), row_parts));
396 const Index row_grain = transpose ? Functor::Traits::nr : Functor::Traits::mr;
397 const Index col_grain = transpose ? Functor::Traits::mr : Functor::Traits::nr;
398 const Index chunks = split_rows ? (rows + row_grain - 1) / row_grain : (cols + col_grain - 1) / col_grain;
399 threads =
static_cast<int>((std::min)(Index(threads), chunks));
400 if (threads <= 1)
return func(0, rows, 0, cols);
401 auto part = [&func, rows, cols, threads, split_rows, row_grain, col_grain](
int i) {
404 balanced_gemm_range<Index>(rows, threads, row_grain, i, start, length);
405 if (length > 0) func(start, length, 0, cols);
407 balanced_gemm_range<Index>(cols, threads, col_grain, i, start, length);
408 if (length > 0) func(0, rows, start, length);
411#if defined(EIGEN_HAS_OPENMP)
412#pragma omp parallel for num_threads(threads) schedule(static, 1)
413 for (
int i = 0; i < threads; ++i) part(i);
414#elif defined(EIGEN_GEMM_THREADPOOL)
418 std::atomic<int> pending(threads - 1);
419 Barrier done(threads - 1);
420 for (
int i = 0; i < threads - 1; ++i)
421 pool->Schedule([&part, &pending, &done, i] {
423 pending.fetch_sub(1, std::memory_order_release);
426 const auto wait = [&pending, &done] {
427 for (
int spin = 0; spin < 65536 && pending.load(std::memory_order_acquire) != 0; ++spin) {
431 EIGEN_TRY { part(threads - 1); }
443#if defined(EIGEN_GEMM_THREADPOOL)
444 const gemm_session_guard session;
445 if (!session.owns())
return func(0, rows, 0, cols);
448 func.initParallelSession(threads);
450 if (transpose) std::swap(rows, cols);
452 ei_declare_aligned_stack_constructed_variable(GemmParallelTaskInfo<Index>, task_info, threads, 0);
454#if defined(EIGEN_HAS_OPENMP)
455#pragma omp parallel num_threads(threads)
457 Index i = omp_get_thread_num();
460 Index actual_threads = omp_get_num_threads();
461 GemmParallelInfo<Index> info(
static_cast<int>(i),
static_cast<int>(actual_threads), task_info);
463 Index r0, actualBlockRows;
464 balanced_gemm_range<Index>(rows, actual_threads, Index(Functor::Traits::mr), i, r0, actualBlockRows);
466 Index c0, actualBlockCols;
467 balanced_gemm_range<Index>(cols, actual_threads, Index(kGemmColGrain), i, c0, actualBlockCols);
469 info.task_info[i].lhs_start = r0;
470 info.task_info[i].lhs_length = actualBlockRows;
473 func(c0, actualBlockCols, 0, rows, &info);
475 func(0, rows, c0, actualBlockCols, &info);
478#elif defined(EIGEN_GEMM_THREADPOOL)
479 Barrier barrier(threads);
480 auto task = [=, &func, &barrier, &task_info](
int i) {
481 Index actual_threads = threads;
482 GemmParallelInfo<Index> info(i,
static_cast<int>(actual_threads), task_info);
483 Index r0, actualBlockRows;
484 balanced_gemm_range<Index>(rows, actual_threads, Index(Functor::Traits::mr), i, r0, actualBlockRows);
486 Index c0, actualBlockCols;
487 balanced_gemm_range<Index>(cols, actual_threads, Index(kGemmColGrain), i, c0, actualBlockCols);
489 info.task_info[i].lhs_start = r0;
490 info.task_info[i].lhs_length = actualBlockRows;
493 func(c0, actualBlockCols, 0, rows, &info);
495 func(0, rows, c0, actualBlockCols, &info);
502 for (
int i = 0; i < threads - 1; ++i) {
503 pool->Schedule([task, i] { task(i); });
ThreadPool * getGemmThreadPool()
Definition Parallelizer.h:185
ThreadPool * setGemmThreadPool(ThreadPool *new_pool)
Definition Parallelizer.h:169