-
Notifications
You must be signed in to change notification settings - Fork 3k
/
EigenNonBlockingThreadPool.h
1716 lines (1552 loc) · 66.5 KB
/
EigenNonBlockingThreadPool.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2016 Dmitry Vyukov <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
/* Modifications Copyright (c) Microsoft. */
#include <type_traits>
#pragma once
#include "onnxruntime_config.h"
// build/external/eigen/unsupported/Eigen/CXX11/src/Tensor/TensorEvaluator.h:162:71:
// error: ignoring attributes on template argument "Eigen::PacketType<const float, Eigen::DefaultDevice>::type {aka
// __vector(4) float}" [-Werror=ignored-attributes]
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-result"
// cmake/external/eigen/unsupported/Eigen/CXX11/../../../Eigen/src/Core/arch/NEON/PacketMath.h:1633:9:
// error: ‘void* memcpy(void*, const void*, size_t)’ copying an object of non-trivial type ‘Eigen::internal::Packet4c’
// {aka ‘struct Eigen::internal::eigen_packet_wrapper<int, 2>’} from an array of ‘const int8_t’
// {aka ‘const signed char’} [-Werror=class-memaccess]
#ifdef HAS_CLASS_MEMACCESS
#pragma GCC diagnostic ignored "-Wclass-memaccess"
#endif
// eigen-src/unsupported/Eigen/CXX11/src/ThreadPool/EventCount.h:231:56: error: implicit conversion loses integer
// precision: 'uint64_t' (aka 'unsigned long long') to 'size_t' (aka 'unsigned long') [-Werror,-Wshorten-64-to-32]
// next = wnext == kStackMask ? nullptr : &waiters_[wnext];
// ~~~~~~~~ ^~~~~
#ifdef HAS_SHORTEN_64_TO_32
#pragma GCC diagnostic ignored "-Wshorten-64-to-32"
#endif
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#pragma warning(disable : 4805)
#endif
#include <memory>
#include "unsupported/Eigen/CXX11/ThreadPool"
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif
#include "core/common/denormal.h"
#include "core/common/inlined_containers_fwd.h"
#include "core/common/spin_pause.h"
#include "core/platform/ort_mutex.h"
#include "core/platform/ort_spin_lock.h"
#include "core/platform/Barrier.h"
// ORT thread pool overview
// ------------------------
//
// The ORT thread pool implementation is split into two layers. This
// file provides the low-level component. See the accompanying
// comments in threadpool.h for the high-level component.
//
// The code here is derived from the Eigen non-blocking thread pool,
// although many parts have been updated over time. The main
// abstractions used here are:
//
// - The thread pool maintains a set of OS threads running
// ThreadPoolTempl::WorkerLoop.
//
// Each thread has its own RunQueue object, holding a queue of tasks
// that have been pushed to the thread for execution. The main work
// loop is to pop a task from the head of the queue, and to execute
// it to completion. If the worker's run queue is empty then it
// will spin waiting for work, then attempt to steal tasks from
// other threads' queues, and then block in the OS if it cannot find
// work.
//
// This spin-then-block behavior is configured via a flag provided
// when creating the thread pool, and by the constant spin_count.
//
// - Although all tasks are simple void()->void functions,
// conceptually there are three different kinds:
//
// - One-shot tasks submitted externally via the Schedule() method.
// These tasks are used to support asynchronous work. These are
// used in the parallel executor, but otherwise are not widely
// used outside of test harnesses (see threadpool_test.cc for some
// examples).
//
// - Tasks for running a parallel loop.
//
// The tasks themselves are defined in threadpool.cc, and are
// submitted to the run queues via RunInParallel->SummonWorkers.
// Each task will loop internally, picking off iterations from the
// user's code via atoic-fetch-and-add, until the loop is
// complete.
//
// This two-layer approach lets us separate out the
// super-lightweight per-iteration-batch work from the more
// costly per-loop work of managing Task objects.
//
// - Tasks for running a parallel section. This is an extension of
// the approach taken for parallel loops. However, the Tasks are
// defined in this file, and can pick up iterations from a series
// of different parallel loops. The tasks are defined in
// RunInParallelSection->SummonWorkers.
//
// The additional layer of parallel sections is a further way to
// amortize costs: the work done creating the tasks can be
// performed once, and then exploited over a series of loops.
//
// There are a few aspects of the modified Eigen thread pool to
// highlight:
//
// - The run queues follow the usual approach of having push/pop
// operations on the front/back, and optimizing the PopFront case
// for single-threaded use by the thread owning the run queue.
// Two points to note here are:
//
// * We should experiment with simplifying these queues. In ORT, we
// use the CAS-based scheduling layer in threadpool.cc for the
// fine-grained allocation of individual loop iterations to worker
// threads. This means we do not have the form of recursive
// sub-division of work that motivates the original design.
//
// * We support an additional Revoke operation to replace an item in
// the middle of a queue with a tombstone. This operation is used
// at the end of parallel loops and parallel sections to remove
// any tasks that were created but not yet executed. Once
// revoked, a thread can rely on the fact that the task will no
// longer execute. Revocation helps manage captured state in
// parallel loops: the alternatives would be (i) waiting for all
// tasks that captured state to reach the head of their queues and
// execute, or (ii) use heap-allocated state in tasks, and use a
// technique such as reference counting to de-allocate it.
//
// To support revocation, each thread has a unique "Tag" to
// identify the items that it adds to the work queues. A thread
// can revoke an item only if it has the thread's own tag.
//
// - When entering a parallel loop (or parallel section), a thread
// maintains a set of "preferred" worker hints, and initially
// submits tasks to these workers.
// When a task executes, it updates the submitting thread's
// preferred workers to reflect the worker that the task ran on.
// Hence, if a task is submitted to thread T1's queue, and then
// stolen by T2 for execution, then T2 will become preferred.
//
// This "stickiness" aims to retain locality between successive
// loops submitted by the same thread, to maintain the same set of
// active threads over time (when the entire pool is not needed),
// and to allow concurrent requests to submit works to their own
// respective sets of preferred workers.
namespace onnxruntime {
namespace concurrency {
#ifdef _WIN32
using CHAR_TYPE = wchar_t;
#else
using CHAR_TYPE = char;
#endif
class ThreadPoolParallelSection;
class ThreadPoolLoop;
enum class StealAttemptKind {
TRY_ONE,
TRY_ALL,
};
enum class PushResult {
REJECTED,
ACCEPTED_IDLE,
ACCEPTED_BUSY
};
// Align to avoid false sharing with prior fields. If required,
// alignment or padding must be added subsequently to avoid false
// sharing with later fields. Note that:
//
// - The __x86_64__ value is twice the line size (64 bytes). This
// accounts for 2-line prefetch behavior on some cores.
//
// - Ideally, ORT_ALIGN_TO_AVOID_FALSE_SHARING is used. However, the
// definition of ThreadPoolParallelSection uses naive padding
// because C++11 does not support alignment constraints on
// allocation or expose stdlib.h aligned_alloc. C++17 introduces
// support for aligned allocation which we could use here.
#if defined(__x86_64__)
#define ORT_FALSE_SHARING_BYTES 128
#else
#define ORT_FALSE_SHARING_BYTES 64
#endif
#define ORT_ALIGN_TO_AVOID_FALSE_SHARING alignas(ORT_FALSE_SHARING_BYTES)
struct PaddingToAvoidFalseSharing {
char padding[ORT_FALSE_SHARING_BYTES];
};
/* Usage:
1. In executor, call Start() before profiling and Stop() to get profiled numbers;
2. Inside thread pool, call LogStart() before interested section and LogEnd... after to log elapsed time;
3. To extend, just add more events in enum Event before "All", and update GetEventName(...) accordingly;
4. Note LogStart must pair with either LogEnd or LogEndAndStart, otherwise ORT_ENFORCE will fail;
5. ThreadPoolProfiler is thread-safe.
*/
#ifdef ORT_MINIMAL_BUILD
class ThreadPoolProfiler {
public:
enum ThreadPoolEvent {
DISTRIBUTION = 0,
DISTRIBUTION_ENQUEUE,
RUN,
WAIT,
WAIT_REVOKE,
MAX_EVENT
};
ThreadPoolProfiler(int, const CHAR_TYPE*){};
~ThreadPoolProfiler() = default;
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ThreadPoolProfiler);
void Start(){};
std::string Stop() { return "not available for minimal build"; }
void LogStart(){};
void LogEnd(ThreadPoolEvent){};
void LogEndAndStart(ThreadPoolEvent){};
void LogStartAndCoreAndBlock(std::ptrdiff_t){};
void LogCoreAndBlock(std::ptrdiff_t){};
void LogThreadId(int){};
void LogRun(int){};
std::string DumpChildThreadStat() { return {}; }
};
#else
class ThreadPoolProfiler {
public:
enum ThreadPoolEvent {
DISTRIBUTION = 0,
DISTRIBUTION_ENQUEUE,
RUN,
WAIT,
WAIT_REVOKE,
MAX_EVENT
};
ThreadPoolProfiler(int num_threads, const CHAR_TYPE* threal_pool_name);
~ThreadPoolProfiler();
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ThreadPoolProfiler);
using Clock = std::chrono::high_resolution_clock;
void Start(); // called by executor to start profiling
std::string Stop(); // called by executor to stop profiling and return collected numbers
void LogStart(); // called in main thread to record the starting time point
void LogEnd(ThreadPoolEvent); // called in main thread to calculate and save the time elapsed from last start point
void LogEndAndStart(ThreadPoolEvent);
void LogStartAndCoreAndBlock(std::ptrdiff_t block_size);
void LogCoreAndBlock(std::ptrdiff_t block_size); // called in main thread to log core and block size for task breakdown
void LogThreadId(int thread_idx); // called in child thread to log its id
void LogRun(int thread_idx); // called in child thread to log num of run
std::string DumpChildThreadStat(); // return all child statitics collected so far
private:
static const char* GetEventName(ThreadPoolEvent);
struct MainThreadStat {
uint64_t events_[MAX_EVENT] = {};
int32_t core_ = -1;
std::vector<std::ptrdiff_t> blocks_; // block size determined by cost model
std::vector<onnxruntime::TimePoint> points_;
void LogCore();
void LogBlockSize(std::ptrdiff_t block_size);
void LogStart();
void LogEnd(ThreadPoolEvent);
void LogEndAndStart(ThreadPoolEvent);
std::string Reset();
};
bool enabled_ = false;
MainThreadStat& GetMainThreadStat(); // return thread local stat
int num_threads_;
#ifdef _MSC_VER
#pragma warning(push)
// C4324: structure was padded due to alignment specifier
#pragma warning(disable : 4324)
#endif // _MSC_VER
struct ORT_ALIGN_TO_AVOID_FALSE_SHARING ChildThreadStat {
std::thread::id thread_id_;
uint64_t num_run_ = 0;
onnxruntime::TimePoint last_logged_point_ = Clock::now();
int32_t core_ = -1; // core that the child thread is running on
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif // _MSC_VER
std::vector<ChildThreadStat> child_thread_stats_;
std::string thread_pool_name_;
};
#endif
// Extended Eigen thread pool interface, avoiding the need to modify
// the ThreadPoolInterface.h header from the external Eigen
// repository.
class ExtendedThreadPoolInterface : public Eigen::ThreadPoolInterface {
public:
// Start/end a parallel section, within which calls to
// RunInParallelSection may be made. Parallel sections are
// non-nesting.
virtual void StartParallelSection(ThreadPoolParallelSection& ps) = 0;
virtual void EndParallelSection(ThreadPoolParallelSection& ps) = 0;
// Run fn with up to n degree-of-parallelism enlisting the thread
// pool for help. The degree-of-parallelism includes the caller,
// and so if n==1 then the function will run directly in the caller.
//
// The fork-join synchronization is handled in the thread pool, and
// so any state captured by fn() is safe from concurrent access once
// RunInParallelSection returns.
//
// The parameter idx provides a loop-local thread ID in the range
// [0,k) where k<=n.
virtual void RunInParallelSection(ThreadPoolParallelSection& ps,
std::function<void(unsigned idx)> fn,
unsigned n, std::ptrdiff_t block_size) = 0;
// Special case alternative to RunInParallelSection for use without
// an existing parallel section. Ideally we would use a single
// implementation and a stack-allocated ThreadPoolParallelSection.
//
// However, on the BM_ThreadPoolParallelFor micro-benchmark I saw
// ~20% overhead on the resulting single-loop parallel sections.
// There are some additional costs (~5%) for additional invocations
// through lambda functions on loop entry. Most significantly, on
// loop exit, we incurred ~15% cost by no longer being able to
// overlap clean-up of unused Task objects in EndParallelSection
// with waiting for loop iterations to complete.
//
// [ Note that this 20% overhead is more than paid for when we have
// two loops execute in series in a parallel section. ]
virtual void RunInParallel(std::function<void(unsigned idx)> fn,
unsigned n, std::ptrdiff_t block_size) = 0;
virtual void StartProfiling() = 0;
virtual std::string StopProfiling() = 0;
};
class ThreadPoolParallelSection {
public:
// State accessed only by the main thread
// --------------------------------------
// Tasks successfully submitted to the work queues. This sets the
// maximum degree of parallelism that the section will support.
InlinedVector<std::pair<int, unsigned>> tasks;
// Number of tasks revoked (i.e., removed from the queues prior to
// execution). We count this at various points, and omit waiting
// for them at the end of a loop.
unsigned tasks_revoked{0};
// Current degree of parallelism, including work in the main thread
// and in the dispatcher.
unsigned current_dop{0};
// State shared between the main thread and worker threads
// -------------------------------------------------------
// Flag to signal termination of the parallel section
std::atomic<bool> active{false};
// Count of the number of tasks that completed normally. Other
// tasks may be running currently, or may be present in work queues,
// or may have been removed from the queues by
// RunQueue::RevokeWithTag.
PaddingToAvoidFalseSharing padding_1;
std::atomic<unsigned> tasks_finished{0};
PaddingToAvoidFalseSharing padding_2;
// If non-null, the current loop that tasks should be executing. We
// need to be careful on access to the contents of current_loop
// because it can be stack allocated on the thread entering the
// loop:
//
// - Readers increment workers_in_loop and then read current_loop
//
// - Writers wishing to deallocate *current_loop must first clear
// current_loop and then wait for workers_in_loop==0
std::atomic<ThreadPoolLoop*> current_loop{nullptr};
std::atomic<unsigned> workers_in_loop{0};
// Members to track asynchronous dispatching
int dispatch_q_idx = -1; // index of thread that dispatch work to all other threads
unsigned dispatch_w_idx = 0; // index of enqueued work
std::atomic<bool> dispatch_started{false};
std::atomic<bool> dispatch_done{false};
std::atomic<bool> work_done{false};
};
class ThreadPoolLoop {
public:
ThreadPoolLoop(std::function<void(unsigned)> f, unsigned t) : fn(std::move(f)), threads_needed(t) {
}
const std::function<void(unsigned)> fn;
const unsigned threads_needed;
private:
ORT_DISALLOW_COPY_ASSIGNMENT_AND_MOVE(ThreadPoolLoop);
};
template <typename Work, typename Tag, unsigned kSize>
class RunQueue {
public:
RunQueue() : front_(0), back_(0) {
// require power-of-two for fast masking
assert((kSize & (kSize - 1)) == 0);
assert(kSize > 2); // why would you do this?
assert(kSize <= (64 << 10)); // leave enough space for counter
for (unsigned i = 0; i < kSize; i++) array_[i].state.store(ElemState::kEmpty, std::memory_order_relaxed);
}
~RunQueue() {
assert(Size() == 0);
}
// PopFront removes and returns the first element in the queue.
// If the queue was empty returns default-constructed Work.
Work PopFront() {
unsigned front;
Elem* e;
ElemState s;
// Drain revoked items from the front of the queue. CAS to busy to synchronize with
// any attempt to take the same item from the back of the queue.
do {
front = front_.load(std::memory_order_relaxed);
e = &array_[(front - 1) & kMask];
s = e->state.load(std::memory_order_relaxed);
if (s == ElemState::kRevoked &&
e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
e->state.store(ElemState::kEmpty, std::memory_order_release);
front = ((front - 1) & kMask2) | (front & ~kMask2);
front_.store(front, std::memory_order_relaxed);
}
} while (s == ElemState::kRevoked);
// Attempt to take next item. State kEmpty shows the queue is empty, kBusy shows
// the work is in progress on the item at the front of the queue.
if (s != ElemState::kReady ||
!e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
return Work();
Work w = std::move(e->w);
e->tag = Tag();
e->state.store(ElemState::kEmpty, std::memory_order_release);
front = ((front - 1) & kMask2) | (front & ~kMask2);
front_.store(front, std::memory_order_relaxed);
return w;
}
// PushBack adds w at the end of the queue.
// If queue is full returns w, otherwise returns default-constructed Work.
Work PushBack(Work w) {
#ifdef USE_LOCK_FREE_QUEUE
std::lock_guard<OrtSpinLock> mtx(spin_lock_);
#else
std::lock_guard<OrtMutex> lock(mutex_);
#endif
unsigned back = back_.load(std::memory_order_relaxed);
Elem& e = array_[(back - 1) & kMask];
ElemState s = e.state.load(std::memory_order_relaxed);
if (s != ElemState::kEmpty ||
!e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
return w;
back = ((back - 1) & kMask2) | (back & ~kMask2);
back_.store(back, std::memory_order_relaxed);
e.w = std::move(w);
e.tag = Tag();
e.state.store(ElemState::kReady, std::memory_order_release);
return Work();
}
// PushBackWithTag adds w at the end of the queue. The tag value can be used on a
// subsequent call to RevokeWithTag to remove the item from the queue in combination
// with w_idx. Typically the tag will be a per-thread ID to distinguish work
// submitted from different threads.
PushResult PushBackWithTag(Work w, Tag tag, unsigned& w_idx) {
#ifdef USE_LOCK_FREE_QUEUE
std::lock_guard<OrtSpinLock> mtx(spin_lock_);
#else
std::lock_guard<OrtMutex> lock(mutex_);
#endif
unsigned back = back_.load(std::memory_order_relaxed);
w_idx = (back - 1) & kMask;
Elem& e = array_[w_idx];
ElemState s = e.state.load(std::memory_order_relaxed);
if (s != ElemState::kEmpty ||
!e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
return PushResult::REJECTED; /* Not enqueued */
bool was_ready = (((back ^ (front_.load(std::memory_order_relaxed))) & kMask) == 0);
back = ((back - 1) & kMask2) | (back & ~kMask2);
back_.store(back, std::memory_order_relaxed);
e.w = std::move(w);
e.tag = tag;
e.state.store(ElemState::kReady, std::memory_order_release);
return was_ready ? PushResult::ACCEPTED_IDLE : PushResult::ACCEPTED_BUSY; /* Enqueued */
}
// PopBack removes and returns the last elements in the queue.
Work PopBack() {
if (Empty())
return Work();
#ifdef USE_LOCK_FREE_QUEUE
std::lock_guard<OrtSpinLock> mtx(spin_lock_);
#else
std::lock_guard<OrtMutex> lock(mutex_);
#endif
unsigned back;
Elem* e;
ElemState s;
// Drain revoked items from the back of the queue. CAS to busy to synchronize with
// any attempt to take the same item from the front of the queue.
do {
back = back_.load(std::memory_order_relaxed);
e = &array_[back & kMask];
s = e->state.load(std::memory_order_relaxed);
if (s == ElemState::kRevoked &&
e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
e->state.store(ElemState::kEmpty, std::memory_order_release);
back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
}
} while (s == ElemState::kRevoked);
if (s != ElemState::kReady ||
!e->state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire))
return Work();
Work w = std::move(e->w);
e->tag = Tag();
e->state.store(ElemState::kEmpty, std::memory_order_release);
back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
return w;
}
// RevokeItem removes a work item from the queue. Items are identified positionally,
// and so a tag is used to detect whether the same position is occupied by a
// different work item at the time of removal. RevokeWithTags lets threads offer work
// for parallel execution, and then revoke the offer prior to the work executing (for
// instance if the thread itself completes all of the work). Revoking the work
// lets the thread deallocate state that might otherwise have been captured by the work item
// and accessed by it.
//
// Return true iff the item is successfully revoked. If the item is not revoked then
// the caller must assume that it may still execute, for instance because it
// has been pop'd from the queue concurrent with the revocation request.
bool RevokeWithTag(Tag tag, unsigned w_idx) {
bool revoked = false;
#ifdef USE_LOCK_FREE_QUEUE
std::lock_guard<OrtSpinLock> mtx(spin_lock_);
#else
std::lock_guard<OrtMutex> lock(mutex_);
#endif
Elem& e = array_[w_idx];
ElemState s = e.state.load(std::memory_order_relaxed);
// We have acquired a lock on the queue, synchronizing with
// operations aside from the PopFront fast-path. Synchronize with
// that by attempting the same kReady->kBusy transition via CAS.
if (s == ElemState::kReady &&
e.state.compare_exchange_strong(s, ElemState::kBusy, std::memory_order_acquire)) {
if (e.tag == tag) {
unsigned back = back_.load(std::memory_order_relaxed);
unsigned back_idx = back & kMask;
if (back_idx != w_idx) {
// Item is not at the back of the queue, mark it in-place as revoked
e.tag = Tag();
e.w = Work();
e.state.store(ElemState::kRevoked, std::memory_order_release);
revoked = true;
} else {
// Item being removed as still at the back; shift the back pointer over it,
// and bump the version number.
e.tag = Tag();
e.w = Work();
e.state.store(ElemState::kEmpty, std::memory_order_release);
back_.store(back + 1 + (kSize << 1), std::memory_order_relaxed);
revoked = true;
}
} else {
// Tag mismatch, i.e. work queue slot re-used
e.state.store(ElemState::kReady, std::memory_order_release);
}
}
return revoked;
}
// Size returns current queue size.
// Can be called by any thread at any time.
unsigned Size() const {
return SizeOrNotEmpty<true>();
}
// Empty tests whether container is empty.
// Can be called by any thread at any time.
bool Empty() const {
return SizeOrNotEmpty<false>() == 0;
}
private:
static const unsigned kMask = kSize - 1;
static const unsigned kMask2 = (kSize << 1) - 1;
enum class ElemState : uint8_t {
kEmpty,
kBusy,
kReady,
kRevoked,
};
// Updates to an element are bracketed by a std::memory_order_acquire
// load from the state, and a std::memory_order_release store. Accesses
// to the front/back indices for the work queue use relaxed semantics,
// with the state of the elements being authoritative.
//
// TODO: Revisit whether there is a significant benefit for the current
// workloads in the complexity here.
struct Elem {
std::atomic<ElemState> state;
Tag tag;
Work w;
};
#ifdef USE_LOCK_FREE_QUEUE
OrtSpinLock spin_lock_;
#else
OrtMutex mutex_;
#endif
// Low log(kSize) + 1 bits in front_ and back_ contain rolling index of
// front/back, respectively. The remaining bits contain modification counters
// that are incremented on Push operations. This allows us to (1) distinguish
// between empty and full conditions (if we would use log(kSize) bits for
// position, these conditions would be indistinguishable); (2) obtain
// consistent snapshot of front_/back_ for Size operation using the
// modification counters.
ORT_ALIGN_TO_AVOID_FALSE_SHARING std::atomic<unsigned> front_;
ORT_ALIGN_TO_AVOID_FALSE_SHARING std::atomic<unsigned> back_;
ORT_ALIGN_TO_AVOID_FALSE_SHARING Elem array_[kSize];
// SizeOrNotEmpty returns current queue size; if NeedSizeEstimate is false,
// only whether the size is 0 is guaranteed to be correct.
// Can be called by any thread at any time.
template <bool NeedSizeEstimate>
unsigned SizeOrNotEmpty() const {
// Emptiness plays critical role in thread pool blocking. So we go to great
// effort to not produce false positives (claim non-empty queue as empty).
unsigned front = front_.load(std::memory_order_acquire);
for (;;) {
// Capture a consistent snapshot of front/tail.
unsigned back = back_.load(std::memory_order_acquire);
unsigned front1 = front_.load(std::memory_order_relaxed);
if (front != front1) {
front = front1;
std::atomic_thread_fence(std::memory_order_acquire);
continue;
}
if (NeedSizeEstimate) {
return CalculateSize(front, back);
}
// This value will be 0 if the queue is empty, and undefined otherwise.
unsigned maybe_zero = ((front ^ back) & kMask2);
// Queue size estimate must agree with maybe zero check on the queue
// empty/non-empty state.
eigen_assert((CalculateSize(front, back) == 0) == (maybe_zero == 0));
return maybe_zero;
}
}
EIGEN_ALWAYS_INLINE
unsigned CalculateSize(unsigned front, unsigned back) const {
int size = (front & kMask2) - (back & kMask2);
// Fix overflow.
if (size < 0)
size += 2 * kSize;
// Order of modification in push/pop is crafted to make the queue look
// larger than it is during concurrent modifications. E.g. push can
// increment size before the corresponding pop has decremented it.
// So the computed size can be up to kSize + 1, fix it.
if (size > static_cast<int>(kSize))
size = kSize;
return static_cast<unsigned>(size);
}
RunQueue(const RunQueue&) = delete;
void operator=(const RunQueue&) = delete;
};
static std::atomic<uint32_t> next_tag{1};
template <typename Environment>
class ThreadPoolTempl : public onnxruntime::concurrency::ExtendedThreadPoolInterface {
private:
struct PerThread;
static unsigned WorkerLoop(int id, Eigen::ThreadPoolInterface* param) {
// unsafe downcast
ThreadPoolTempl* this_ptr = (ThreadPoolTempl*)param;
this_ptr->WorkerLoop(id);
return 0;
}
ThreadPoolProfiler profiler_;
void SignalAllAndWait() {
done_ = true;
// Now if all threads block without work, they will start exiting.
// But note that threads can continue to work arbitrary long,
// block, submit new work, unblock and otherwise live full life.
WakeAllWorkersForExit();
// Join threads explicitly (by destroying) to avoid destruction order within
// this class.
for (size_t i = 0; i < worker_data_.size(); ++i) worker_data_[i].thread.reset();
}
public:
void StartProfiling() override {
profiler_.Start();
}
std::string StopProfiling() override {
return profiler_.Stop();
}
struct Tag {
constexpr Tag() : v_(0) {
}
Tag(uint32_t v) : v_(v) {
}
// Allocate a new tag to use to identify work items from a given
// thread in a parallel section. Ideally, threads will have
// unique tags, but re-use is not incorrect if the counter wraps
// (for intsance, if a long-running workload is calling into ORT
// from a fresh thread for each request). We must not re-use the
// default tag 0 which is used to identify work items added via
// Schedule as opposed to requests for help in parallel sections.
static Tag GetNext() {
Tag t = Tag(next_tag++);
if (t.v_ == 0) {
t = Tag(next_tag++);
}
return t;
}
uint32_t Get() const {
return v_;
}
bool operator==(const Tag& other) const {
return v_ == other.v_;
}
uint32_t v_ = 0;
};
typedef std::function<void()> Task;
typedef RunQueue<Task, Tag, 1024> Queue;
ThreadPoolTempl(const CHAR_TYPE* name, int num_threads, bool allow_spinning, Environment& env,
const ThreadOptions& thread_options)
: profiler_(num_threads, name),
env_(env),
num_threads_(num_threads),
allow_spinning_(allow_spinning),
set_denormal_as_zero_(thread_options.set_denormal_as_zero),
worker_data_(num_threads),
all_coprimes_(num_threads),
blocked_(0),
done_(false) {
// Calculate coprimes of all numbers [1, num_threads].
// Coprimes are used for random walks over all threads in Steal
// and NonEmptyQueueIndex. Iteration is based on the fact that if we take
// a random starting thread index t and calculate num_threads - 1 subsequent
// indices as (t + coprime) % num_threads, we will cover all threads without
// repetitions (effectively getting a presudo-random permutation of thread
// indices).
for (auto i = 1u; i <= num_threads_; ++i) {
all_coprimes_.emplace_back(i);
ComputeCoprimes(i, &all_coprimes_.back());
}
// Eigen::MaxSizeVector has neither essential exception safety features
// such as swap, nor it is movable. So we have to join threads right here
// on exception
ORT_TRY {
worker_data_.resize(num_threads_);
for (auto i = 0u; i < num_threads_; i++) {
worker_data_[i].thread.reset(env_.CreateThread(name, i, WorkerLoop, this, thread_options));
}
}
ORT_CATCH(...) {
ORT_HANDLE_EXCEPTION([&]() {
SignalAllAndWait();
throw;
});
}
}
~ThreadPoolTempl() override {
SignalAllAndWait();
}
// Run fn(). Ordinarily, the function will be added to the thread pool and executed
// by a worker thread. If the thread pool rejects the work then fn() will instead
// execute synchronously during Schedule(fn). Currently the thread pool will only
// reject work if the queue of pending work is full.
void Schedule(std::function<void()> fn) override {
PerThread* pt = GetPerThread();
int q_idx = Rand(&pt->rand) % num_threads_;
WorkerData& td = worker_data_[q_idx];
Queue& q = td.queue;
fn = q.PushBack(std::move(fn));
if (!fn) {
// The queue accepted the work; ensure that the thread will pick it up
td.EnsureAwake();
} else {
// Run the work directly if the queue rejected the work
fn();
}
}
//......................................................................
//
// Parallel sections
// -----------------
//
// Start a parallel section, using a caller-provided
// ThreadPoolParallelSection for maintaining the per-section state.
// Starting a parallel section is just book-keeping; threads are
// "summoned" to help with the parallel section once it enters
// parallel loops. The threads are then retained until the end of the
// section, being re-used over subsequent loops.
void StartParallelSectionInternal(PerThread& pt,
ThreadPoolParallelSection& ps) {
assert((!pt.leading_par_section) && "Nested parallelism not supported");
assert((!ps.active) && "Starting parallel section, but active already");
pt.leading_par_section = true;
if (!pt.tag.Get()) {
pt.tag = Tag::GetNext();
}
ps.dispatch_q_idx = -1;
ps.dispatch_started = false;
ps.dispatch_done = false;
ps.work_done = false;
ps.tasks_revoked = 0;
ps.current_dop = 1;
ps.active = true;
}
void StartParallelSection(ThreadPoolParallelSection& ps) override {
PerThread* pt = GetPerThread();
StartParallelSectionInternal(*pt, ps);
}
// End a parallel section, waiting for all worker threads to exit from
// section. Hence, on return, the ThreadPoolParallelSection object
// can be dealloacted.
void EndParallelSectionInternal(PerThread& pt,
ThreadPoolParallelSection& ps) {
assert((pt.leading_par_section) && "Ending parallel section, but none started");
assert((ps.active) && "Ending parallel section, but not active");
pt.leading_par_section = false;
// Notify workers to exit from the section
ps.active = false;
// First, attempt to revoke the dispatch task. If we succeed then
// we know we revoked _something_ pushed for the current loop. That
// may be the dispatch task itself, or it may be a task pushed by
// the dispatch task. Those cases are distinguished by whether or
// not the dispatch task itself has started -- if it has not started
// then it cannot have pushed tasks.
if (ps.dispatch_q_idx != -1) {
Queue& q = worker_data_[ps.dispatch_q_idx].queue;
if (q.RevokeWithTag(pt.tag, ps.dispatch_w_idx)) {
if (!ps.dispatch_started.load(std::memory_order_acquire)) {
// We successfully revoked a task, and saw the dispatch task
// not started. Hence we know we revoked the dispatch task.
// This should be the common case.
ps.dispatch_q_idx = -1;
} else {
// We successfully revoked a task, but saw the dispatch task
// had started. Hence we know we revoked one of the _new_
// tasks created by the dispatcher (not the dispatcher
// itself). This should be the rare case, but can occur if
// one of the tasks created by the dispatcher occupies the
// exact same slot in a work queue that the dispatcher used.
ps.tasks_revoked++;
}
}
}
// Second, if we failed to revoke the dispatch task, wait for it to
// finish dispatch work. This avoids new tasks being started
// concurrently with us attempting to end the parallel section.
if (ps.dispatch_q_idx != -1) {
while (!ps.dispatch_done.load(std::memory_order_acquire)) {
onnxruntime::concurrency::SpinPause();
}
}
// Now we know that dispatch is finshed, we synchronize with the
// tasks that were created (if any) for the parallel section. We
// revoke tasks still in queues, and then wait for any that are
// still running.
profiler_.LogStart();
unsigned tasks_started = static_cast<unsigned>(ps.tasks.size());
while (!ps.tasks.empty()) {
const auto& item = ps.tasks.back();
Queue& q = worker_data_[item.first].queue;
if (q.RevokeWithTag(pt.tag, item.second)) {
ps.tasks_revoked++;
}
ps.tasks.pop_back();
}
profiler_.LogEnd(ThreadPoolProfiler::WAIT_REVOKE);
// Wait for the dispatch task's own work...
if (ps.dispatch_q_idx > -1) {
while (!ps.work_done.load(std::memory_order_acquire)) {
onnxruntime::concurrency::SpinPause();
}
}
// ...and wait for any other tasks not revoked to finish their work
auto tasks_to_wait_for = tasks_started - ps.tasks_revoked;
while (ps.tasks_finished < tasks_to_wait_for) {
onnxruntime::concurrency::SpinPause();
}
// Clear status to allow the ThreadPoolParallelSection to be
// re-used.
ps.tasks_finished = 0;
}
void EndParallelSection(ThreadPoolParallelSection& ps) override {
PerThread* pt = GetPerThread();
EndParallelSectionInternal(*pt, ps);
}
//----------------------------------------------------------------------
//
// Preferred workers
// -----------------
//
// Initialize the set of hints for preferred worker threads we will
// use. We do this once, covering the maximum num_threads_ items,
// in order to avoid resizing preferred_workers concurrent with
// access from worker threads.
//
// For simplicity we initialize with hints round-robin among the
// workers. For simple workloads with 1 main thread this means we
// will distribute work across the pool of workers. For workers
// with multiple main threads it attempts to balance the load.
//
// These hints are just used as a starting point, and are updated by
// the worker thread that actually claims an item (e.g., if an item
// initially assigned to thread T1 is stolen and executed by T2,
// then T2 is assigned at the new preferred worker).
//
// Note that the hints are held in the _main_ thread that submits
// work to the pool. We assume that a thread is primarily
// submitting work to just one pool, but allow for the pool to
// change over time. Hence we allow the hints vector to grow over
// time.
//
// A note on terminology used in the variable names here:
//
// dop - degree of parallelism, as seen by the user. For instance
// dop=4 means 4 threads in total: 1 main thread that enters the
// loop, plus 1 dispatcher thread, plus 2 additional worker
// threads.
//
// par_idx - a thread's index within the loop, in the range [0,dop).
//
// num_threads_ - the number of worker threads in the thread pool. A
// loop with dop=4 will be common on a pool with 3 threads
// (given that the main thread will also participate).
//
// q_idx - a worker queue index, in the range [0,num_threads_).
//
// preferred_workers - this maps from par_idx values to q_idx. Hence,
// with dop=4 the vector will have length 4, and will identify
// which of the workers (0,1,2) should run tasks for the loop.
// Note that mapping from par_idx values means that only slots
// [1,dop) are actually used in preferred_workers.