Eigen  5.0.1-dev+master
 
Loading...
Searching...
No Matches
Parallelizer.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2010 Gael Guennebaud <gael.guennebaud@inria.fr>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9// SPDX-License-Identifier: MPL-2.0
10
11#ifndef EIGEN_PARALLELIZER_H
12#define EIGEN_PARALLELIZER_H
13
14// IWYU pragma: private
15#include "../InternalHeaderCheck.h"
16
17// Note that in the following, there are 3 different uses of the concept
18// "number of threads":
19// 1. Max number of threads used by OpenMP or ThreadPool.
20// * For OpenMP this is typically the value set by the OMP_NUM_THREADS
21// environment variable, or by a call to omp_set_num_threads() prior to
22// calling Eigen.
23// * For ThreadPool, this is the number of threads in the ThreadPool.
24// 2. Max number of threads currently allowed to be used by parallel Eigen
25// operations. This is set by setNbThreads(), and cannot exceed the value
26// in 1.
27// 3. The actual number of threads used for a given parallel Eigen operation.
28// This is typically computed on the fly using a cost model and cannot exceed
29// the value in 2.
30// * For OpenMP, this is typically the number of threads specified in individual
31// "omp parallel" pragmas associated with an Eigen operation.
32// * For ThreadPool, it is the number of concurrent tasks scheduled in the
33// threadpool for a given Eigen operation. Notice that since the threadpool
34// uses task stealing, there is no way to limit the number of concurrently
35// executing tasks to below the number in 1. except by limiting the total
36// number of tasks in flight.
37
38#if defined(EIGEN_HAS_OPENMP) && defined(EIGEN_GEMM_THREADPOOL)
39#error "EIGEN_HAS_OPENMP and EIGEN_GEMM_THREADPOOL may not both be defined."
40#endif
41
42namespace Eigen {
43
44namespace internal {
45inline void manage_multi_threading(Action action, int* v);
46}
47
48// Public APIs.
49
51EIGEN_DEPRECATED_WITH_REASON("Initialization is no longer needed.") inline void initParallel() {}
52
57inline int nbThreads() {
58 int ret;
59 internal::manage_multi_threading(GetAction, &ret);
60 return ret;
61}
62
67inline void setNbThreads(int v) { internal::manage_multi_threading(SetAction, &v); }
68
69#ifdef EIGEN_VECTORIZE_SME
70#ifndef EIGEN_SME_MIN_TASK_SIZE
71#define EIGEN_SME_MIN_TASK_SIZE (double(1 << 20))
72#endif
73namespace internal {
74// Time of one multiply-add on the SME kernel in fp32 multiply-adds: an FP64 outer product covers a quarter of the
75// elements of an FP32 one at the same vector length, and a complex multiply-add is four real ones.
76template <typename Scalar>
77struct sme_madd_cost {
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);
80};
81// Apple silicon shares one SME unit per core cluster, so more threads than clusters only contend for the units; other
82// SME implementations may have one per core. The count comes from macOS's performance-cluster topology and is 0 (no
83// cap) everywhere else, where EIGEN_SME_UNITS or setNbSmeUnits() supply it.
84inline int detect_sme_units() {
85#if defined(EIGEN_SME_UNITS)
86 return EIGEN_SME_UNITS;
87#elif EIGEN_OS_MAC
88 // Performance clusters only (a cluster shares one L2): the work is split evenly over the threads,
89 // so a thread on the efficiency cluster's slower unit would set the finishing time.
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;
93 sz = sizeof(per_l2);
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);
96#else
97 return 0;
98#endif
99}
100inline void manage_sme_units(Action action, int* v) {
101 static int m_units = detect_sme_units();
102 if (action == SetAction)
103 m_units = *v;
104 else
105 *v = m_units;
106}
107} // namespace internal
108#endif
109
113inline int nbSmeUnits() {
114#ifdef EIGEN_VECTORIZE_SME
115 int ret;
116 internal::manage_sme_units(GetAction, &ret);
117 return ret;
118#else
119 return 0;
120#endif
121}
127inline void setNbSmeUnits(int v) {
128#ifdef EIGEN_VECTORIZE_SME
129 internal::manage_sme_units(SetAction, &v);
130#else
131 EIGEN_UNUSED_VARIABLE(v);
132#endif
133}
134
135// Doxygen does not define EIGEN_GEMM_THREADPOOL; it reads the declarations below through EIGEN_PARSED_BY_DOXYGEN.
136#if defined(EIGEN_GEMM_THREADPOOL) || defined(EIGEN_PARSED_BY_DOXYGEN)
137// TODO(rmlarsen): Make the device API available instead of
138// storing a local static pointer variable to avoid the race condition below.
139
169inline ThreadPool* setGemmThreadPool(ThreadPool* new_pool) {
170 static ThreadPool* pool = nullptr;
171 if (new_pool != nullptr) {
172 // This only replaces the stored pointer: work already scheduled on the old
173 // ThreadPool is not waited for, and the old pool is not destroyed. Since
174 // this returns the new pool, the caller must keep its own pointer to the
175 // old one to dispose of it.
176 pool = new_pool;
177 // Reset the number of threads to the number of threads on the new pool.
178 setNbThreads(pool->NumThreads());
179 }
180 return pool;
181}
182
185inline ThreadPool* getGemmThreadPool() { return setGemmThreadPool(nullptr); }
186#endif // EIGEN_GEMM_THREADPOOL || EIGEN_PARSED_BY_DOXYGEN
187
188namespace internal {
189
190// Implementation.
191
192// Granularity of the column split. Aligning to Traits::nr instead would avoid a partial leading
193// rhs panel per thread, but nr is 8 on several backends and the coarser split balances worse: on a
194// 72-core Neoverse V2, nr-alignment cost 3.5-4.5% at high thread counts (8192x8192 float, 72
195// threads: 5132 vs 5315 GFLOP/s). gebp handles a partial panel, so prefer the finer balance.
196constexpr int kGemmColGrain = 4;
197
204template <typename Index>
205EIGEN_ALWAYS_INLINE void balanced_gemm_range(Index total, Index parts, Index grain, Index part, Index& start,
206 Index& length) {
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);
214}
215
216#if defined(EIGEN_USE_BLAS) || (!defined(EIGEN_HAS_OPENMP) && !defined(EIGEN_GEMM_THREADPOOL))
217
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);
223 *v = 1;
224 } else {
225 eigen_internal_assert(false);
226 }
227}
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 /*unused*/,
232 bool /*unused*/) {
233 func(0, rows, 0, cols);
234}
235
236#else
237
238template <typename Index>
239struct GemmParallelTaskInfo {
240 GemmParallelTaskInfo() {}
241 std::atomic<Index> sync{Index(-1)};
242 std::atomic<int> users{0};
243 Index lhs_start = 0;
244 Index lhs_length = 0;
245};
246
247template <typename Index>
248struct GemmParallelInfo {
249 const int logical_thread_id;
250 const int num_threads;
251 GemmParallelTaskInfo<Index>* task_info;
252
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_) {}
255};
256
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)
262 // Calling action == SetAction and *v = 0 means
263 // restoring m_maxThreads to the maximum number of threads specified
264 // for 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)
269 // Calling action == SetAction and *v = 0 means
270 // restoring m_maxThreads to the number of threads in the ThreadPool,
271 // which defaults to 1 if no pool was provided.
272 eigen_internal_assert(*v >= 0);
273 ThreadPool* pool = getGemmThreadPool();
274 int pool_threads = pool != nullptr ? pool->NumThreads() : 1;
275 m_maxThreads = (*v == 0 ? pool_threads : numext::mini(pool_threads, *v));
276#endif
277 } else if (action == GetAction) {
278 eigen_internal_assert(v != nullptr);
279#if defined(EIGEN_HAS_OPENMP)
280 if (m_maxThreads > 0)
281 *v = m_maxThreads;
282 else
283 *v = omp_get_max_threads();
284#else
285 // m_maxThreads is -1 until a pool is registered or setNbThreads is called.
286 *v = m_maxThreads > 0 ? m_maxThreads : 1;
287#endif
288 } else {
289 eigen_internal_assert(false);
290 }
291}
292
293#if defined(EIGEN_GEMM_THREADPOOL)
294// The parts of one shared parallel session wait for each other's packed panels. Sessions of different products on one
295// pool could each occupy some workers while their other parts wait in the queue, so only one session at a time uses
296// the pool. A product that finds it busy runs on its calling thread.
297//
298// The flag is an atomic rather than a std::mutex because the thread that holds the session can issue another product
299// from inside it, when the scalar's own multiplication is a matrix product. std::mutex::try_lock is undefined for the
300// owning thread; the exchange reports the session as busy.
301class gemm_session_guard {
302 public:
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);
306 }
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; }
310
311 private:
312 static std::atomic<bool>& busy() {
313 static std::atomic<bool> flag(false);
314 return flag;
315 }
316 const bool m_owns;
317};
318#endif
319
320template <bool Condition, typename Functor, typename Index>
321EIGEN_STRONG_INLINE void parallelize_gemm(const Functor& func, Index rows, Index cols, Index depth, bool transpose) {
322 // Dynamically check whether we should even try to execute in parallel.
323 // The conditions are:
324 // - the max number of threads we can create is greater than 1
325 // - we are not already in a parallel code
326 // - the sizes are large enough
327
328 // compute the maximal number of threads from the size of the product:
329 // This first heuristic takes into account that the product kernel is fully optimized when working with nr columns at
330 // once.
331 Index size = transpose ? rows : cols;
332 Index pb_max_threads = std::max<Index>(1, size / Functor::Traits::nr);
333
334 // compute the maximal number of threads from the total amount of work:
335 double work = static_cast<double>(rows) * static_cast<double>(cols) * static_cast<double>(depth);
336 double kMinTaskSize = 50000; // FIXME: tune this minimum task-size heuristic based on architecture and scalar type.
337#ifdef EIGEN_VECTORIZE_SME
338 // With a known SME unit count (one unit per core cluster), the SME kernel does far more work per unit of time than
339 // the generic one, so a thread needs more of it to repay the handoff; elsewhere the size is not measured and the
340 // generic one applies. With no preallocated buffers, each thread runs a disjoint part of the result (below).
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();
345 if (sme_units_known)
346 kMinTaskSize = EIGEN_SME_MIN_TASK_SIZE / sme_madd_cost<typename Functor::Traits::LhsScalar>::value;
347 if (sme_disjoint) {
348 const Index kernel_rows = transpose ? cols : rows, kernel_cols = transpose ? rows : cols;
349 pb_max_threads =
350 std::max<Index>(1, (std::max)(kernel_rows / Functor::Traits::mr, kernel_cols / Functor::Traits::nr));
351 }
352#endif
353 pb_max_threads = std::max<Index>(1, std::min<Index>(pb_max_threads, static_cast<Index>(work / kMinTaskSize)));
354
355 // compute the number of threads we are going to use
356 int threads = std::min<int>(nbThreads(), static_cast<int>(pb_max_threads));
357#ifdef EIGEN_VECTORIZE_SME
358 // The SME kernels share one unit per cluster; more threads than units only contend.
359 EIGEN_IF_CONSTEXPR (kSme) {
360 const int units = nbSmeUnits();
361 if (units > 0) threads = std::min<int>(threads, units);
362 }
363#endif
364
365 // if multi-threading is explicitly disabled, not useful, or if we already are
366 // inside a parallel session, then abort multi-threading
367 bool dont_parallelize = (!Condition) || (threads <= 1);
368#if defined(EIGEN_HAS_OPENMP)
369 // don't parallelize if we are executing in a parallel context already.
370 dont_parallelize |= omp_get_num_threads() > 1;
371#elif defined(EIGEN_GEMM_THREADPOOL)
372 // don't parallelize if we have a trivial threadpool or the current thread id
373 // is != -1, indicating that we are already executing on a thread inside the pool.
374 // In other words, we do not allow nested parallelism, since this would lead to
375 // deadlocks due to the workstealing nature of the threadpool.
376 ThreadPool* pool = getGemmThreadPool();
377 dont_parallelize |= (pool == nullptr || pool->CurrentThreadId() != -1);
378#endif
379 if (dont_parallelize) return func(0, rows, 0, cols);
380
381#ifdef EIGEN_VECTORIZE_SME
382 // A known unit count stands for one SME unit per core cluster, each with its own L2 (see nbSmeUnits): the
383 // cooperative session below would read the other cluster's packed LHS and wait for it at every depth step, so each
384 // thread runs a disjoint part of the result instead.
385 EIGEN_IF_CONSTEXPR (kSme) {
386 if (sme_disjoint) {
387 // On the kernel's problem (the transposed one for a row-major result), a row split repacks the whole RHS per
388 // thread and a column split the whole LHS (a copy, or nothing when read in place): split the rows only when
389 // they are twice the columns and give 8 LHS panels per part, since a narrower result already runs close to peak.
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));
395 // The result's rows are the kernel's columns for a row-major result. No part may be empty.
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) {
402 Index start, length;
403 if (split_rows) {
404 balanced_gemm_range<Index>(rows, threads, row_grain, i, start, length);
405 if (length > 0) func(start, length, 0, cols);
406 } else {
407 balanced_gemm_range<Index>(cols, threads, col_grain, i, start, length);
408 if (length > 0) func(0, rows, start, length);
409 }
410 };
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)
415 // The parts take about as long as each other, so the caller spins for the others (tens of microseconds, less than
416 // a blocking wake-up costs a short product) before it blocks on the barrier, which it always passes, also
417 // before an exception from its own part leaves this frame.
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] {
422 part(i);
423 pending.fetch_sub(1, std::memory_order_release);
424 done.Notify();
425 });
426 const auto wait = [&pending, &done] {
427 for (int spin = 0; spin < 65536 && pending.load(std::memory_order_acquire) != 0; ++spin) {
428 }
429 done.Wait();
430 };
431 EIGEN_TRY { part(threads - 1); }
432 EIGEN_CATCH(...) {
433 wait();
434 EIGEN_THROW;
435 }
436 wait();
437#endif
438 return;
439 }
440 }
441#endif
442
443#if defined(EIGEN_GEMM_THREADPOOL)
444 const gemm_session_guard session;
445 if (!session.owns()) return func(0, rows, 0, cols);
446#endif
447
448 func.initParallelSession(threads);
449
450 if (transpose) std::swap(rows, cols);
451
452 ei_declare_aligned_stack_constructed_variable(GemmParallelTaskInfo<Index>, task_info, threads, 0);
453
454#if defined(EIGEN_HAS_OPENMP)
455#pragma omp parallel num_threads(threads)
456 {
457 Index i = omp_get_thread_num();
458 // Note that the actual number of threads might be lower than the number of
459 // requested ones
460 Index actual_threads = omp_get_num_threads();
461 GemmParallelInfo<Index> info(static_cast<int>(i), static_cast<int>(actual_threads), task_info);
462
463 Index r0, actualBlockRows;
464 balanced_gemm_range<Index>(rows, actual_threads, Index(Functor::Traits::mr), i, r0, actualBlockRows);
465
466 Index c0, actualBlockCols;
467 balanced_gemm_range<Index>(cols, actual_threads, Index(kGemmColGrain), i, c0, actualBlockCols);
468
469 info.task_info[i].lhs_start = r0;
470 info.task_info[i].lhs_length = actualBlockRows;
471
472 if (transpose)
473 func(c0, actualBlockCols, 0, rows, &info);
474 else
475 func(0, rows, c0, actualBlockCols, &info);
476 }
477
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);
485
486 Index c0, actualBlockCols;
487 balanced_gemm_range<Index>(cols, actual_threads, Index(kGemmColGrain), i, c0, actualBlockCols);
488
489 info.task_info[i].lhs_start = r0;
490 info.task_info[i].lhs_length = actualBlockRows;
491
492 if (transpose)
493 func(c0, actualBlockCols, 0, rows, &info);
494 else
495 func(0, rows, c0, actualBlockCols, &info);
496
497 barrier.Notify();
498 };
499 // Notice that we do not schedule more than "threads" tasks, which allows us to
500 // limit number of running threads, even if the threadpool itself was constructed
501 // with a larger number of threads.
502 for (int i = 0; i < threads - 1; ++i) {
503 pool->Schedule([task, i] { task(i); });
504 }
505 task(threads - 1);
506 barrier.Wait();
507#endif
508}
509
510#endif
511
512} // end namespace internal
513} // end namespace Eigen
514
515#endif // EIGEN_PARALLELIZER_H
ThreadPool * getGemmThreadPool()
Definition Parallelizer.h:185
ThreadPool * setGemmThreadPool(ThreadPool *new_pool)
Definition Parallelizer.h:169