Repository navigation
Expand file tree
/
Copy pathtbb_validation.cpp
More file actions
845 lines (797 loc) · 31.6 KB
/
Copy pathtbb_validation.cpp
File metadata and controls
845 lines (797 loc) · 31.6 KB
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
/*
* Copyright 2026 CEA (www.cea.fr)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// ============================================================================
// Arrays driven from a TBB application through shrink_array::tbb::parallel_for
// (chunk/tbb_adaptor.h, docs/threading_backends.md, step 8). Variant-agnostic,
// like the other harnesses here.
// ============================================================================
//
// The adaptor runs oneapi::tbb::parallel_for with begin_parallel_phase() before
// every piece of the range and finalize_parallel_phase() once after the tasks.
// Under the std backend each TBB thread takes a rank of the registry; under
// the serial backend the adaptor runs the body on the calling thread.
//
// WHAT IT CHECKS, per element type (double, int, bool), in a task_arena of T
// threads (T: the backend's team size, OMP_NUM_THREADS of the test)
//
// - the range form with each partitioner: auto (the default), simple with a
// small grain (many pieces per thread: begin_parallel_phase() again and
// again on one thread), static (the same piece on the same thread from
// one call to the next); the pieces write runs of the first constant, of
// the second and varied values, every other phase compress() at the
// serial point;
// - the index form, step 1 and step 3 (the elements the step skips keep the
// previous phase's values);
// - in every piece: in_parallel() and the application phase are on, the
// rank is the thread's (get_thr_rank_fast() == shrink_array::thread_rank()), below
// the capacity, the same for a thread all phase long and distinct between
// threads; after the call: no phase, no parallel;
// - work in the phase: one index per array (grain 1), each compresses its
// array in the middle of its piece (a pass on the calling thread: no team
// of the std backend in the phase), rewrites part of it and writes its share of
// a shared array, one write in 7 deferred (test_hooks::force_defer_every,
// check builds) -- drained by the adaptor's finalize_parallel_phase();
// - a nested oneapi::tbb::parallel_for inside the body, with phase_body();
// - a body that throws: the exception reaches the caller, the phase is
// closed, and the next call runs normally; a step of 0 is refused
// (std::invalid_argument, as TBB) before any phase opens;
// - the library's own teams on TBB's threads (use_tbb_for_library_teams()):
// 2000 teams with a static loop, a barrier, a single and a dynamic loop,
// every rank above 0 on a TBB thread; then 500 more from a second thread
// while every TBB thread is busy (the teams shrink, they still end);
// - a narrower task_arena (2 threads) for one call;
// - 64-bit indices: an Array<char, long> of more than INT_MAX elements,
// written through the index form with a step that lands on both sides of
// 2^31 and through the range form on a blocked_range<long> straddling
// 2^31, then read back. Almost every chunk stays at the first constant,
// so the array costs its chunk metadata (a few hundred MB), not 2 GB, as
// in index64_validation. Skipped under ThreadSanitizer (its shadow memory
// over that metadata).
//
// After every phase the array is compared, element by element, with a
// std::vector that received the same writes.
//
// Std and serial builds with CHUNK_WITH_TBB=ON (CMake registers it there):
// an OpenMP build refuses the adaptor. Exit 0 = every element matches.
#include <algorithm> // std::max, std::min
#include <atomic> // std::atomic
#include <climits> // INT_MAX (past_int_max)
#include <map> // std::map (thread -> rank)
#include <mutex> // std::mutex, std::scoped_lock
#include <stdexcept> // std::runtime_error (the throwing body), std::invalid_argument (step 0)
#include <thread> // std::this_thread::get_id, std::thread (library_teams)
#include <type_traits> // std::conditional_t
#include <utility> // std::as_const (past_int_max)
#include <vector> // std::vector (the reference)
#include <oneapi/tbb/blocked_range.h> // oneapi::tbb::blocked_range
#include <oneapi/tbb/global_control.h> // oneapi::tbb::global_control (max_allowed_parallelism)
#include <oneapi/tbb/parallel_for.h> // oneapi::tbb::parallel_for (nested), the partitioners
#include <oneapi/tbb/task_arena.h> // oneapi::tbb::task_arena
#include "chunk/internal/chunk_traits.h" // forward decls + default IntType = int
#include "chunk/zero_array.h" // zero::Array
#include "chunk/zero_or_value_array.h" // zero_or_value::Array
#include "chunk/zero_any_array.h" // zero_any::Array
#include "chunk/runtime.h" // Runtime::init
#include "chunk/internal/zero_chunk.h" // release_chunk_pools, Runtime::shutdown
#include "chunk/config.h" // chunk_config::use_zero*
#include "chunk/internal/pmp_chunk.h" // pmp::*, CHUNK_PMP_* (THREAD_CAPACITY: the registry), get_thr_rank_fast
#include "chunk/threads.h" // shrink_array::thread_rank (each piece's rank, against the registry's)
#include "chunk/tbb_adaptor.h" // shrink_array::tbb::parallel_for, phase_body, use_tbb_for_library_teams
#include "chunk/internal/env_parse.h" // arg_number
#include "chunk/print.h" // shrink_array::println
#include "chunk/internal/test_hooks.h" // force_defer_every (the in-phase case)
#include "validation_harness.h" // run() is called by validation_driver.cpp
namespace validation::tbb_validation
{
using namespace shrink_array;
using oneapi::tbb::blocked_range;
template <typename T, typename I = int>
using Array = std::conditional_t<
chunk_config::use_zero_any,
zero_any::Array<T, I>,
std::conditional_t<chunk_config::use_zero_or_value, zero_or_value::Array<T, I>, zero::Array<T, I>>>;
constexpr const char* variant_name()
{
if constexpr (chunk_config::use_zero_any)
{
return "zero_any";
}
else if constexpr (chunk_config::use_zero_or_value)
{
return "zero_or_value";
}
else
{
return "zero";
}
}
constexpr bool std_build = pmp::backend == pmp::BackendKind::std_threads;
template <typename Arr, typename Val>
void maybe_set_second_value(Arr& a, const Val& v)
{
if constexpr (requires(Arr x) { x.set_second_value(v); })
{
a.set_second_value(v);
}
}
/// Runs of run_len elements: a whole number of chunks at every geometry built.
constexpr long run_len = 4096;
template <typename T>
struct Scenario
{
T second; ///< the second constant
T (*varied)(long, int); ///< a varied value of element i at phase p
};
/// The value phase @p p writes into element @p i.
template <typename T>
T value_at(const Scenario<T>& sc, long i, int p)
{
switch ((i / run_len + p) % 3)
{
case 0:
return T(0);
case 1:
return sc.second;
default:
return sc.varied(i, p);
}
}
/// Compare @p arr with @p ref; report the first mismatch.
template <typename T>
bool compare(const char* what, const char* label, int p, const Array<T>& arr, const std::vector<T>& ref)
{
long bad = 0;
long first = -1;
for (long i = 0; i < static_cast<long>(ref.size()); ++i)
{
if (arr[i] != ref[static_cast<std::size_t>(i)])
{
if (first < 0)
{
first = i;
}
++bad;
}
}
if (bad != 0)
{
println("[{}/{}] {}: FAIL after phase {}: {}/{} mismatches, first at i={} got={:g} expected={:g}",
variant_name(), label, what, p, bad, ref.size(), first, static_cast<double>(arr[first]),
static_cast<double>(ref[static_cast<std::size_t>(first)]));
}
return bad == 0;
}
/**
* What the pieces of one phase saw: every thread's rank (the same all phase,
* distinct between threads), and the failures of the in-piece checks.
*/
class PhaseRecord
{
public:
/// In a piece, after the adaptor's begin_parallel_phase().
void piece()
{
if constexpr (std_build)
{
if (!CHUNK_PMP_IN_PARALLEL_REGION || !pmp::in_application_phase())
{
fail("a piece runs outside the application phase");
}
}
const int r = get_thr_rank_fast();
if (r < 0 || r >= CHUNK_PMP_THREAD_CAPACITY || r != shrink_array::thread_rank())
{
println("FAIL: piece rank {} (thread_rank {}, capacity {})", r, shrink_array::thread_rank(),
CHUNK_PMP_THREAD_CAPACITY);
fails_.fetch_add(1, std::memory_order_relaxed);
}
const std::scoped_lock lock(mutex_);
const auto [it, inserted] = rank_of_.try_emplace(std::this_thread::get_id(), r);
if (!inserted && it->second != r)
{
println("FAIL: one thread with ranks {} and {} in the same phase", it->second, r);
fails_.fetch_add(1, std::memory_order_relaxed);
}
}
/// After the adaptor returned: no phase, distinct ranks; the failures.
[[nodiscard]] int close()
{
if (CHUNK_PMP_IN_PARALLEL_REGION || pmp::in_application_phase())
{
fail("in_parallel() still true after the adaptor returned");
}
std::vector<int> ranks;
for (const auto& [tid, r] : rank_of_)
{
ranks.push_back(r);
}
std::sort(ranks.begin(), ranks.end());
if (std::adjacent_find(ranks.begin(), ranks.end()) != ranks.end())
{
fail("two threads of the same phase share a rank");
}
threads_ = static_cast<int>(rank_of_.size());
rank_of_.clear();
return fails_.exchange(0);
}
/// Threads that ran a piece of the last closed phase.
[[nodiscard]] int threads() const noexcept
{
return threads_;
}
void fail(const char* msg)
{
println("FAIL: {}", msg);
fails_.fetch_add(1, std::memory_order_relaxed);
}
private:
std::mutex mutex_;
std::map<std::thread::id, int> rank_of_;
std::atomic<int> fails_{0};
int threads_ = 0;
};
enum class Part
{
automatic,
simple,
fixed, ///< static_partitioner
};
constexpr const char* part_name(Part k)
{
switch (k)
{
case Part::automatic:
return "auto";
case Part::simple:
return "simple";
case Part::fixed:
return "static";
}
return "?";
}
/// The range form, with partitioner @p k.
template <typename T>
int range_form(const char* label, long N, int phases, Part k, const Scenario<T>& sc)
{
Array<T> arr(N);
std::vector<T> ref(static_cast<std::size_t>(N), T(0));
maybe_set_second_value(arr, sc.second);
PhaseRecord rec;
int fails = 0;
int max_threads = 0;
for (int p = 0; p < phases; ++p)
{
auto body = [&](const blocked_range<long>& r)
{
rec.piece();
for (long i = r.begin(); i != r.end(); ++i)
{
arr[i] = value_at(sc, i, p);
}
};
switch (k)
{
case Part::automatic:
shrink_array::tbb::parallel_for(blocked_range<long>(0, N), body);
break;
case Part::simple:
shrink_array::tbb::parallel_for(blocked_range<long>(0, N, run_len / 4), body,
oneapi::tbb::simple_partitioner{});
break;
case Part::fixed:
shrink_array::tbb::parallel_for(blocked_range<long>(0, N), body, oneapi::tbb::static_partitioner{});
break;
}
fails += rec.close();
max_threads = std::max(max_threads, rec.threads());
for (long i = 0; i < N; ++i)
{
ref[static_cast<std::size_t>(i)] = value_at(sc, i, p);
}
if (p % 2 == 1)
{
arr.compress(); // a serial point: the pass runs on a team of the std backend
}
if (!compare("range", label, p, arr, ref))
{
++fails;
break;
}
}
println("[{}/{}] range form, {} partitioner, {} phases, up to {} threads: {}", variant_name(), label, part_name(k),
phases, max_threads, fails == 0 ? "OK" : "FAIL");
arr.clear();
return fails == 0 ? 0 : 1;
}
/// The index form, step @p step: the skipped elements keep their values.
template <typename T>
int index_form(const char* label, long N, int phases, long step, const Scenario<T>& sc)
{
Array<T> arr(N);
std::vector<T> ref(static_cast<std::size_t>(N), T(0));
maybe_set_second_value(arr, sc.second);
PhaseRecord rec;
int fails = 0;
for (int p = 0; p < phases; ++p)
{
// The piece check once per index here: the index form has no piece hook.
auto f = [&](long i)
{
if (i % run_len == 0)
{
rec.piece();
}
arr[i] = value_at(sc, i, p);
};
const long first = p % step; // a different subset each phase when step > 1
if (step == 1)
{
shrink_array::tbb::parallel_for(first, N, f);
}
else
{
shrink_array::tbb::parallel_for(first, N, step, f, oneapi::tbb::static_partitioner{});
}
fails += rec.close();
for (long i = first; i < N; i += step)
{
ref[static_cast<std::size_t>(i)] = value_at(sc, i, p);
}
if (p % 2 == 0)
{
arr.compress();
}
if (!compare("index", label, p, arr, ref))
{
++fails;
break;
}
}
println("[{}/{}] index form, step {}, {} phases: {}", variant_name(), label, step, phases,
fails == 0 ? "OK" : "FAIL");
arr.clear();
return fails == 0 ? 0 : 1;
}
/// Compression, rewrites and deferred writes inside the phase: one index per array.
template <typename T>
int in_phase_work(const char* label, long N, int nt, int phases, const Scenario<T>& sc)
{
const int na = std::max(2, nt);
const long n_own = N / 4;
std::vector<Array<T>> own;
std::vector<std::vector<T>> own_ref(static_cast<std::size_t>(na),
std::vector<T>(static_cast<std::size_t>(n_own), T(0)));
own.reserve(static_cast<std::size_t>(na));
for (int t = 0; t < na; ++t)
{
own.emplace_back(n_own);
maybe_set_second_value(own.back(), sc.second);
}
Array<T> shared(N);
std::vector<T> ref(static_cast<std::size_t>(N), T(0));
maybe_set_second_value(shared, sc.second);
if constexpr (test_hooks::force_defer_compiled)
{
test_hooks::force_defer_every = 7U;
}
const unsigned long deferred0 = test_hooks::forced_deferrals.load();
PhaseRecord rec;
int fails = 0;
for (int p = 0; p < phases; ++p)
{
shrink_array::tbb::parallel_for(
blocked_range<int>(0, na, 1),
[&](const blocked_range<int>& r)
{
rec.piece();
for (int t = r.begin(); t != r.end(); ++t)
{
auto& a = own[static_cast<std::size_t>(t)];
for (long i = 0; i < n_own; ++i)
{
a[i] = value_at(sc, i, p);
}
const long b = N * t / na;
const long e = N * (t + 1) / na;
for (long i = b; i < e; ++i)
{
shared[i] = value_at(sc, i, p);
}
a.compress(); // in the phase: on this thread, no team
if (CHUNK_PMP_NUM_THREADS != 1)
{
rec.fail("a pass in the application phase ran on a team");
}
for (long i = 0; i < n_own / 3; ++i)
{
a[i] = value_at(sc, i + run_len, p + 1);
}
for (long i = b; i < e; i += 5)
{
shared[i] = value_at(sc, i, p + 1);
}
}
},
oneapi::tbb::simple_partitioner{});
fails += rec.close();
// The reference: each share, then every 5th element of it from its start.
for (int t = 0; t < na; ++t)
{
const long b = N * t / na;
const long e = N * (t + 1) / na;
for (long i = b; i < e; ++i)
{
ref[static_cast<std::size_t>(i)] = ((i - b) % 5 == 0) ? value_at(sc, i, p + 1) : value_at(sc, i, p);
}
}
bool ok = compare("in-phase shared", label, p, shared, ref);
for (int t = 0; t < na && ok; ++t)
{
auto& r = own_ref[static_cast<std::size_t>(t)];
for (long i = 0; i < n_own; ++i)
{
r[static_cast<std::size_t>(i)] = i < n_own / 3 ? value_at(sc, i + run_len, p + 1) : value_at(sc, i, p);
}
ok = compare("in-phase own", label, p, own[static_cast<std::size_t>(t)], r);
}
if (!ok)
{
++fails;
break;
}
if (p % 2 == 0)
{
shared.compress();
}
}
if constexpr (test_hooks::force_defer_compiled)
{
test_hooks::force_defer_every = 0U;
}
const unsigned long deferred = test_hooks::forced_deferrals.load() - deferred0;
println("[{}/{}] in-phase passes and deferrals x{}, {} phases, {} writes deferred: {}", variant_name(), label, na,
phases, deferred, fails == 0 ? "OK" : "FAIL");
for (auto& a : own)
{
a.clear();
}
shared.clear();
return fails == 0 ? 0 : 1;
}
/// A oneapi::tbb::parallel_for nested in the adaptor's body, with phase_body().
template <typename T>
int nested(const char* label, long N, int phases, const Scenario<T>& sc)
{
Array<T> arr(N);
std::vector<T> ref(static_cast<std::size_t>(N), T(0));
maybe_set_second_value(arr, sc.second);
PhaseRecord rec;
int fails = 0;
const long blocks = 4;
for (int p = 0; p < phases; ++p)
{
auto inner = [&](const blocked_range<long>& r)
{
rec.piece();
for (long i = r.begin(); i != r.end(); ++i)
{
arr[i] = value_at(sc, i, p);
}
};
shrink_array::tbb::parallel_for(blocked_range<long>(0, blocks, 1),
[&](const blocked_range<long>& outer)
{
for (long b = outer.begin(); b != outer.end(); ++b)
{
oneapi::tbb::parallel_for(
blocked_range<long>(N * b / blocks, N * (b + 1) / blocks),
shrink_array::tbb::phase_body(inner));
}
});
fails += rec.close();
for (long i = 0; i < N; ++i)
{
ref[static_cast<std::size_t>(i)] = value_at(sc, i, p);
}
if (p % 2 == 1)
{
arr.compress();
}
if (!compare("nested", label, p, arr, ref))
{
++fails;
break;
}
}
println("[{}/{}] nested parallel_for, {} phases: {}", variant_name(), label, phases, fails == 0 ? "OK" : "FAIL");
arr.clear();
return fails == 0 ? 0 : 1;
}
/// A body that throws: the exception reaches the caller, the phase is closed.
template <typename T>
int throwing_body(const char* label, long N, const Scenario<T>& sc)
{
Array<T> arr(N);
std::vector<T> ref(static_cast<std::size_t>(N), T(0));
maybe_set_second_value(arr, sc.second);
PhaseRecord rec;
int fails = 0;
bool caught = false;
try
{
shrink_array::tbb::parallel_for(blocked_range<long>(0, N, run_len),
[&](const blocked_range<long>& r)
{
for (long i = r.begin(); i != r.end(); ++i)
{
arr[i] = value_at(sc, i, 0);
}
if (r.begin() <= N / 2 && N / 2 < r.end())
{
throw std::runtime_error("thrown by one piece");
}
});
}
catch (const std::runtime_error&)
{
caught = true;
}
if (!caught)
{
rec.fail("the body's exception did not reach the caller");
}
fails += rec.close();
// A step that is not positive: refused before any task, as TBB does.
bool refused = false;
try
{
shrink_array::tbb::parallel_for(0L, N, 0L, [&](long i) { arr[i] = T(0); });
}
catch (const std::invalid_argument&)
{
refused = true;
}
if (!refused)
{
rec.fail("a step of 0 was not refused");
}
fails += rec.close();
// The next phase runs normally and leaves every element known.
shrink_array::tbb::parallel_for(blocked_range<long>(0, N),
[&](const blocked_range<long>& r)
{
rec.piece();
for (long i = r.begin(); i != r.end(); ++i)
{
arr[i] = value_at(sc, i, 1);
}
});
fails += rec.close();
for (long i = 0; i < N; ++i)
{
ref[static_cast<std::size_t>(i)] = value_at(sc, i, 1);
}
arr.compress();
if (!compare("throw", label, 1, arr, ref))
{
++fails;
}
println("[{}/{}] throwing body: {}", variant_name(), label, fails == 0 ? "OK" : "FAIL");
arr.clear();
return fails == 0 ? 0 : 1;
}
/// @brief 64-bit indices through the adaptor: an Array<char, long> past
/// INT_MAX, written by the index form (a step landing on both sides of
/// 2^31) and by the range form (a blocked_range<long> straddling 2^31),
/// read back; an element neither form wrote reads 0.
int past_int_max()
{
using Big = Array<char, long>;
const long count = static_cast<long>(INT_MAX) + (3L * 4096) + 5; // three chunks past INT_MAX at 4096
const long step = (1L << 20) + 7; // ~2048 positions, some past INT_MAX
const long lo = static_cast<long>(INT_MAX) - 2048; // the range form's first index
const auto value = [](long i) { return static_cast<char>(1 + (i % 120)); };
Big big(count);
shrink_array::tbb::parallel_for(0L, count, step, [&](long i) { big[i] = value(i); });
shrink_array::tbb::parallel_for(blocked_range<long>(lo, count),
[&](const blocked_range<long>& r)
{
for (long i = r.begin(); i != r.end(); ++i)
{
big[i] = value(i);
}
});
const auto& cb = std::as_const(big);
long bad = 0;
long n = 0;
for (long i = 0; i < count; i += step, ++n)
{
bad += cb[i] != value(i) ? 1 : 0;
}
for (long i = lo; i < count; ++i)
{
bad += cb[i] != value(i) ? 1 : 0;
}
for (const long i : {1L, step + 1, lo - 1})
{
bad += cb[i] != 0 ? 1 : 0;
}
if (bad != 0)
{
println("[{}/past-int-max] FAIL: {} element(s) wrong of N={} (INT_MAX + {})", variant_name(), bad, count,
count - static_cast<long>(INT_MAX));
return 1;
}
println("[{}/past-int-max] OK: N={} (INT_MAX + {}), {} index-form positions, range [{}, {})", variant_name(), count,
count - static_cast<long>(INT_MAX), n, lo, count);
return 0;
}
/**
* @brief The library's own teams on TBB's threads (use_tbb_for_library_teams()):
* @p teams teams of @p nt threads opened from the calling thread, each a
* static loop, a barrier, a single and a dynamic loop over @p m
* iterations; then the same from a second thread while every TBB
* thread is busy, where the teams must still end (smaller: TBB starts
* the tasks late, and a late task leaves the team without it).
* @details Every iteration runs once per loop, every single once per team,
* and every rank above 0 runs on a TBB thread (not the std backend's
* pool). Std builds only.
*/
int library_teams(int nt, int teams)
{
if constexpr (!std_build)
{
(void)nt;
(void)teams;
return 0;
}
shrink_array::tbb::use_tbb_for_library_teams();
constexpr int m = 4096;
std::atomic<long> bad{0};
std::atomic<long> off_tbb{0};
std::atomic<long> wide{0};
std::atomic<int> largest{1};
const auto one_team = [&]
{
std::vector<std::atomic<int>> hits(2 * m);
std::atomic<int> singles{0};
pmp::team(pmp::Options{.num_threads = nt},
[&](pmp::Team& t)
{
if (t.rank() > 0 && oneapi::tbb::this_task_arena::current_thread_index() ==
oneapi::tbb::task_arena::not_initialized)
{
off_tbb.fetch_add(1);
}
if (t.rank() == 0)
{
wide.fetch_add(t.size() > 1 ? 1 : 0);
largest.store(std::max(largest.load(), t.size()));
}
t.for_static<int>(0, m, [&](int i) { hits[static_cast<std::size_t>(i)].fetch_add(1); });
t.barrier();
t.single([&] { singles.fetch_add(1); });
t.for_dynamic<int>(m, 2 * m, 16, [&](int i) { hits[static_cast<std::size_t>(i)].fetch_add(1); });
});
for (const auto& h : hits)
{
bad += h.load() != 1 ? 1 : 0;
}
bad += singles.load() != 1 ? 1 : 0;
};
for (int k = 0; k < teams; ++k)
{
one_team();
}
const long wide_idle = wide.load();
// Every TBB thread busy (no phase: a team may open) while a second thread
// opens teams: their tasks start late or never, the teams still end.
// The busy tasks capture nothing: the index form calls the caller's
// lambda itself, which an uninstrumented libtbb hands over unseen by
// ThreadSanitizer (tsan_tbb.supp); a static flag needs no hand-over.
static std::atomic<bool> stop{false};
stop.store(false);
std::thread opener(
[&]
{
for (int k = 0; k < teams / 4; ++k)
{
one_team();
}
stop.store(true);
});
oneapi::tbb::parallel_for(0, nt, 1,
[](int)
{
while (!stop.load())
{
std::this_thread::yield();
}
});
opener.join();
const bool ok = bad.load() == 0 && off_tbb.load() == 0;
println("[{}/library-teams] {}: {} + {} teams of up to {} threads, {} wide when TBB idle, largest {}, {} wrong, "
"{} rank(s) off TBB",
variant_name(), ok ? "OK" : "FAIL", teams, teams / 4, nt, wide_idle, largest.load(), bad.load(),
off_tbb.load());
return ok ? 0 : 1;
}
int run(int argc, char** argv)
{
const long N = argc > 1 ? shrink_array::arg_number<long>(argv[1], 1L << 18, "N") : (1L << 18);
const int phases = argc > 2 ? shrink_array::arg_number<int>(argv[2], 6, "phases") : 6;
Runtime::init(true);
// TBB's threads: the backend's team size (OMP_NUM_THREADS of the test),
// the calling thread among them -- within the capacity of the registry.
const int nt = std_build ? std::max(1, std::min(CHUNK_PMP_MAX_THREADS, CHUNK_PMP_THREAD_CAPACITY)) : 1;
println("=== tbb_validation [variant = {}, backend = {}] N={} threads={} phases={} capacity={} ===",
variant_name(), std_build ? "std" : "serial", N, nt, phases, CHUNK_PMP_THREAD_CAPACITY);
const oneapi::tbb::global_control limit(oneapi::tbb::global_control::max_allowed_parallelism,
static_cast<std::size_t>(nt));
oneapi::tbb::task_arena arena(nt);
int fails = 0;
const Scenario<double> sd{3.5, [](long i, int p) { return 1.0 + static_cast<double>(i) + (0.25 * p); }};
const Scenario<int> si{7, [](long i, int p) { return 100 + static_cast<int>(i % 100000) + p; }};
const Scenario<bool> sb{true, [](long i, int p) { return ((i + p) % 3) == 0; }};
arena.execute(
[&]
{
for (const Part k : {Part::automatic, Part::simple, Part::fixed})
{
fails += range_form<double>("double", N, phases, k, sd);
fails += range_form<int>("int", N, phases, k, si);
fails += range_form<bool>("bool", N, phases, k, sb);
}
for (const long step : {1L, 3L})
{
fails += index_form<double>("double", N, phases, step, sd);
fails += index_form<int>("int", N, phases, step, si);
fails += index_form<bool>("bool", N, phases, step, sb);
}
fails += in_phase_work<double>("double", N, nt, phases, sd);
fails += in_phase_work<int>("int", N, nt, phases, si);
fails += in_phase_work<bool>("bool", N, nt, phases, sb);
fails += nested<double>("double", N, phases, sd);
fails += nested<int>("int", N, phases, si);
fails += throwing_body<double>("double", N, sd);
fails += library_teams(nt, 2000);
if constexpr (chunk_config::tsan_build)
{
println("[{}/past-int-max] skipped under ThreadSanitizer", variant_name());
}
else
{
fails += past_int_max();
}
});
// A narrower arena for one call: its threads are TBB's same workers.
oneapi::tbb::task_arena narrow(std::min(nt, 2));
narrow.execute([&] { fails += range_form<double>("double, arena of 2", N, phases, Part::fixed, sd); });
if constexpr (std_build)
{
const auto& reg = ::fast_alloc::pmp::thread_rank_registry();
if (reg.high_water() > reg.capacity())
{
println("FAIL: registry high water {} past its capacity {}", reg.high_water(), reg.capacity());
++fails;
}
}
release_chunk_pools();
Runtime::shutdown();
println("\n[{}] {}", variant_name(), fails == 0 ? "=== TBB OK ===" : "=== TBB FAILURES ===");
return fails == 0 ? 0 : 1;
}
} // namespace validation::tbb_validation