Repository navigation
Expand file tree
/
Copy pathtest_parallel_backend.py
More file actions
1115 lines (930 loc) · 35.8 KB
/
Copy pathtest_parallel_backend.py
File metadata and controls
1115 lines (930 loc) · 35.8 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
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
# -*- coding: utf-8 -*-
"""
Tests the parallel backend
"""
import faulthandler
import itertools
import multiprocessing
import os
import random
import subprocess
import sys
import threading
import unittest
import numpy as np
from numba import jit, vectorize, guvectorize, set_num_threads
from numba.tests.support import (temp_directory, override_config, TestCase, tag,
skip_parfors_unsupported, linux_only)
import queue as t_queue
from numba.testing.main import _TIMEOUT as _RUNNER_TIMEOUT
from numba.core import config
_TEST_TIMEOUT = _RUNNER_TIMEOUT - 60.
# Check which backends are available
# TODO: Put this in a subprocess so the address space is kept clean
try:
# Check it's a compatible TBB before loading it
from numba.np.ufunc.parallel import _check_tbb_version_compatible
_check_tbb_version_compatible()
from numba.np.ufunc import tbbpool # noqa: F401
_HAVE_TBB_POOL = True
except ImportError:
_HAVE_TBB_POOL = False
try:
from numba.np.ufunc import omppool
_HAVE_OMP_POOL = True
except ImportError:
_HAVE_OMP_POOL = False
try:
import scipy.linalg.cython_lapack # noqa: F401
_HAVE_LAPACK = True
except ImportError:
_HAVE_LAPACK = False
# test skipping decorators
skip_no_omp = unittest.skipUnless(_HAVE_OMP_POOL, "OpenMP threadpool required")
skip_no_tbb = unittest.skipUnless(_HAVE_TBB_POOL, "TBB threadpool required")
_gnuomp = _HAVE_OMP_POOL and omppool.openmp_vendor == "GNU"
skip_unless_gnu_omp = unittest.skipUnless(_gnuomp, "GNU OpenMP only tests")
_windows = sys.platform.startswith('win')
_osx = sys.platform.startswith('darwin')
_32bit = sys.maxsize <= 2 ** 32
_parfors_unsupported = _32bit
_HAVE_OS_FORK = not _windows
# some functions to jit
def foo(n, v):
return np.ones(n) + v
if _HAVE_LAPACK:
def linalg(n, v):
x = np.dot(np.ones((n, n)), np.ones((n, n)))
return x + np.arange(n) + v
else:
def linalg(n, v):
# no way to trigger MKL without the lapack bindings.
return np.arange(n) + v
def ufunc_foo(a, b):
return a + b
def gufunc_foo(a, b, out):
out[0] = a + b
class runnable(object):
def __init__(self, **options):
self._options = options
class jit_runner(runnable):
def __call__(self):
cfunc = jit(**self._options)(foo)
a = 4
b = 10
expected = foo(a, b)
got = cfunc(a, b)
np.testing.assert_allclose(expected, got)
class mask_runner(object):
def __init__(self, runner, mask, **options):
self.runner = runner
self.mask = mask
def __call__(self):
if self.mask:
# Tests are all run in isolated subprocesses, so we
# don't have to worry about this affecting other tests
set_num_threads(self.mask)
self.runner()
class linalg_runner(runnable):
def __call__(self):
cfunc = jit(**self._options)(linalg)
a = 4
b = 10
expected = linalg(a, b)
got = cfunc(a, b)
np.testing.assert_allclose(expected, got)
class vectorize_runner(runnable):
def __call__(self):
cfunc = vectorize(['(f4, f4)'], **self._options)(ufunc_foo)
a = b = np.random.random(10).astype(np.float32)
expected = ufunc_foo(a, b)
got = cfunc(a, b)
np.testing.assert_allclose(expected, got)
class guvectorize_runner(runnable):
def __call__(self):
sig = ['(f4, f4, f4[:])']
cfunc = guvectorize(sig, '(),()->()', **self._options)(gufunc_foo)
a = b = np.random.random(10).astype(np.float32)
expected = ufunc_foo(a, b)
got = cfunc(a, b)
np.testing.assert_allclose(expected, got)
def chooser(fnlist, **kwargs):
q = kwargs.get('queue')
try:
faulthandler.enable()
for _ in range(int(len(fnlist) * 1.5)):
fn = random.choice(fnlist)
fn()
except Exception as e:
q.put(e)
def compile_factory(parallel_class, queue_impl):
def run_compile(fnlist):
q = queue_impl()
kws = {'queue': q}
ths = [parallel_class(target=chooser, args=(fnlist,), kwargs=kws)
for i in range(4)]
for th in ths:
th.start()
for th in ths:
th.join()
if not q.empty():
errors = []
while not q.empty():
errors.append(q.get(False))
_msg = "Error(s) occurred in delegated runner:\n%s"
raise RuntimeError(_msg % '\n'.join([repr(x) for x in errors]))
return run_compile
# workers
_thread_class = threading.Thread
class _proc_class_impl(object):
def __init__(self, method):
self._method = method
def __call__(self, *args, **kwargs):
ctx = multiprocessing.get_context(self._method)
return ctx.Process(*args, **kwargs)
def _get_mp_classes(method):
if method == 'default':
method = None
ctx = multiprocessing.get_context(method)
proc = _proc_class_impl(method)
queue = ctx.Queue
return proc, queue
thread_impl = compile_factory(_thread_class, t_queue.Queue)
spawn_proc_impl = compile_factory(*_get_mp_classes('spawn'))
if not _windows:
fork_proc_impl = compile_factory(*_get_mp_classes('fork'))
forkserver_proc_impl = compile_factory(*_get_mp_classes('forkserver'))
# this is duplication as Py27, linux uses fork, windows uses spawn, it however
# is kept like this so that when tests fail it's less confusing!
default_proc_impl = compile_factory(*_get_mp_classes('default'))
class TestParallelBackendBase(TestCase):
"""
Base class for testing the parallel backends
"""
all_impls = [
jit_runner(nopython=True),
jit_runner(nopython=True, cache=True),
jit_runner(nopython=True, nogil=True),
linalg_runner(nopython=True),
linalg_runner(nopython=True, nogil=True),
vectorize_runner(nopython=True),
vectorize_runner(nopython=True, target='parallel'),
vectorize_runner(nopython=True, target='parallel', cache=True),
guvectorize_runner(nopython=True),
guvectorize_runner(nopython=True, target='parallel'),
guvectorize_runner(nopython=True, target='parallel', cache=True),
]
if not _parfors_unsupported:
parfor_impls = [
jit_runner(nopython=True, parallel=True),
jit_runner(nopython=True, parallel=True, cache=True),
linalg_runner(nopython=True, parallel=True),
linalg_runner(nopython=True, parallel=True, cache=True),
]
all_impls.extend(parfor_impls)
if config.NUMBA_NUM_THREADS < 2:
# Not enough cores
masks = []
else:
masks = [1, 2]
mask_impls = []
for impl in all_impls:
for mask in masks:
mask_impls.append(mask_runner(impl, mask))
parallelism = ['threading', 'random']
parallelism.append('multiprocessing_spawn')
if _HAVE_OS_FORK:
parallelism.append('multiprocessing_fork')
parallelism.append('multiprocessing_forkserver')
runners = {
'concurrent_jit': [
jit_runner(nopython=True, parallel=(not _parfors_unsupported)),
],
'concurrect_vectorize': [
vectorize_runner(nopython=True, target='parallel'),
],
'concurrent_guvectorize': [
guvectorize_runner(nopython=True, target='parallel'),
],
'concurrent_mix_use': all_impls,
'concurrent_mix_use_masks': mask_impls,
}
safe_backends = {'omp', 'tbb'}
def run_compile(self, fnlist, parallelism='threading'):
self._cache_dir = temp_directory(self.__class__.__name__)
with override_config('CACHE_DIR', self._cache_dir):
if parallelism == 'threading':
thread_impl(fnlist)
elif parallelism == 'multiprocessing_fork':
fork_proc_impl(fnlist)
elif parallelism == 'multiprocessing_forkserver':
forkserver_proc_impl(fnlist)
elif parallelism == 'multiprocessing_spawn':
spawn_proc_impl(fnlist)
elif parallelism == 'multiprocessing_default':
default_proc_impl(fnlist)
elif parallelism == 'random':
ps = [thread_impl, spawn_proc_impl]
if _HAVE_OS_FORK:
ps.append(fork_proc_impl)
ps.append(forkserver_proc_impl)
random.shuffle(ps)
for impl in ps:
impl(fnlist)
else:
raise ValueError(
'Unknown parallelism supplied %s' % parallelism)
_specific_backends = config.THREADING_LAYER in ('omp', 'tbb', 'workqueue')
@unittest.skipUnless(_specific_backends, "Threading layer not explicit")
class TestParallelBackend(TestParallelBackendBase):
""" These are like the numba.tests.test_threadsafety tests but designed
instead to torture the parallel backend.
If a suitable backend is supplied via NUMBA_THREADING_LAYER these tests
can be run directly. This test class cannot be run using the multiprocessing
option to the test runner (i.e. `./runtests -m`) as daemon processes cannot
have children.
"""
# NOTE: All tests are generated based on what a platform supports concurrent
# execution wise from Python, irrespective of whether the native libraries
# can actually handle the behaviour present.
@classmethod
def generate(cls):
for p in cls.parallelism:
for name, impl in cls.runners.items():
methname = "test_" + p + '_' + name
def methgen(impl, p):
def test_method(self):
selfproc = multiprocessing.current_process()
# daemonized processes cannot have children
if selfproc.daemon:
_msg = 'daemonized processes cannot have children'
self.skipTest(_msg)
else:
self.run_compile(impl, parallelism=p)
return test_method
fn = methgen(impl, p)
fn.__name__ = methname
setattr(cls, methname, fn)
TestParallelBackend.generate()
class TestInSubprocess(object):
backends = {'tbb': skip_no_tbb,
'omp': skip_no_omp,
'workqueue': unittest.skipIf(False, '')}
def run_cmd(self, cmdline, env):
popen = subprocess.Popen(cmdline,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env)
# finish in _TEST_TIMEOUT seconds or kill it
timeout = threading.Timer(_TEST_TIMEOUT, popen.kill)
try:
timeout.start()
out, err = popen.communicate()
if popen.returncode != 0:
raise AssertionError(
"process failed with code %s: stderr follows\n%s\n" %
(popen.returncode, err.decode()))
return out.decode(), err.decode()
finally:
timeout.cancel()
return None, None
def run_test_in_separate_process(self, test, threading_layer):
env_copy = os.environ.copy()
env_copy['NUMBA_THREADING_LAYER'] = str(threading_layer)
cmdline = [sys.executable, "-m", "numba.runtests", test]
return self.run_cmd(cmdline, env_copy)
class TestSpecificBackend(TestInSubprocess, TestParallelBackendBase):
"""
This is quite contrived, for each test in the TestParallelBackend tests it
generates a test that will run the TestParallelBackend test in a new python
process with an environment modified to ensure a specific threadsafe backend
is used. This is with view of testing the backends independently and in an
isolated manner such that if they hang/crash/have issues, it doesn't kill
the test suite.
"""
_DEBUG = False
@classmethod
def _inject(cls, p, name, backend, backend_guard):
themod = cls.__module__
thecls = TestParallelBackend.__name__
methname = "test_" + p + '_' + name
injected_method = '%s.%s.%s' % (themod, thecls, methname)
def test_template(self):
o, e = self.run_test_in_separate_process(injected_method, backend)
if self._DEBUG:
print('stdout:\n "%s"\n stderr:\n "%s"' % (o, e))
self.assertIn('OK', e)
self.assertTrue('FAIL' not in e)
self.assertTrue('ERROR' not in e)
injected_test = "test_%s_%s_%s" % (p, name, backend)
# Mark as long_running
setattr(cls, injected_test,
tag('long_running')(backend_guard(test_template)))
@classmethod
def generate(cls):
for backend, backend_guard in cls.backends.items():
for p in cls.parallelism:
for name in cls.runners.keys():
# handle known problem cases...
# GNU OpenMP is not fork safe
if (p in ('multiprocessing_fork', 'random') and
backend == 'omp' and
sys.platform.startswith('linux')):
continue
# workqueue is not thread safe
if (p in ('threading', 'random') and
backend == 'workqueue'):
continue
cls._inject(p, name, backend, backend_guard)
TestSpecificBackend.generate()
class ThreadLayerTestHelper(TestCase):
"""
Helper class for running an isolated piece of code based on a template
"""
# sys path injection and separate usecase module to make sure everything
# is importable by children of multiprocessing
_here = "%r" % os.path.dirname(__file__)
template = """if 1:
import sys
sys.path.insert(0, "%(here)r")
import multiprocessing
import numpy as np
from numba import njit
import numba
try:
import threading_backend_usecases
except ImportError as e:
print("DEBUG:", sys.path)
raise e
import os
sigterm_handler = threading_backend_usecases.sigterm_handler
busy_func = threading_backend_usecases.busy_func
def the_test():
%%s
if __name__ == "__main__":
the_test()
""" % {'here': _here}
def run_cmd(self, cmdline, env=None):
if env is None:
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = str("omp")
popen = subprocess.Popen(cmdline,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env)
# finish in _TEST_TIMEOUT seconds or kill it
timeout = threading.Timer(_TEST_TIMEOUT, popen.kill)
try:
timeout.start()
out, err = popen.communicate()
if popen.returncode != 0:
raise AssertionError(
"process failed with code %s: stderr follows\n%s\n" %
(popen.returncode, err.decode()))
finally:
timeout.cancel()
return out.decode(), err.decode()
@skip_parfors_unsupported
class TestThreadingLayerSelection(ThreadLayerTestHelper):
"""
Checks that numba.threading_layer() reports correctly.
"""
_DEBUG = False
backends = {'tbb': skip_no_tbb,
'omp': skip_no_omp,
'workqueue': unittest.skipIf(False, '')}
@classmethod
def _inject(cls, backend, backend_guard):
def test_template(self):
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
Z = busy_func(X, Y)
assert numba.threading_layer() == '%s'
"""
runme = self.template % (body % backend)
cmdline = [sys.executable, '-c', runme]
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = str(backend)
out, err = self.run_cmd(cmdline, env=env)
if self._DEBUG:
print(out, err)
injected_test = "test_threading_layer_selector_%s" % backend
setattr(cls, injected_test,
tag("important")(backend_guard(test_template)))
@classmethod
def generate(cls):
for backend, backend_guard in cls.backends.items():
cls._inject(backend, backend_guard)
TestThreadingLayerSelection.generate()
@skip_parfors_unsupported
class TestThreadingLayerPriority(ThreadLayerTestHelper):
def each_env_var(self, env_var: str):
"""Test setting priority via env var NUMBA_THREADING_LAYER_PRIORITY.
:return: threading_layer_priority, stderr
(containing ``@threading_layer@``)
"""
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = 'default'
env['NUMBA_THREADING_LAYER_PRIORITY'] = env_var
code = """import sys
import numba
# trigger threading layer decision
# hence catching invalid THREADING_LAYER_PRIORITY
@numba.jit(
'float64[::1](float64[::1], float64[::1])',
nopython=True,
parallel=True,
)
def plus(x, y):
return x + y
print(' '.join(numba.config.THREADING_LAYER_PRIORITY))
print("@%s@" % numba.threading_layer(), file=sys.stderr)
"""
cmd = [
sys.executable,
'-c',
code,
]
return self.run_cmd(cmd, env=env)
def test_valid_env_var(self):
default = ['tbb', 'omp', 'workqueue']
for p in itertools.permutations(default):
env_var = ' '.join(p)
threading_layer_priority, _ = self.each_env_var(env_var)
self.assertEqual(threading_layer_priority.strip(), env_var)
def test_invalid_env_var(self):
env_var = 'tbb omp workqueue notvalidhere'
with self.assertRaises(AssertionError) as raises:
self.each_env_var(env_var)
for msg in (
"THREADING_LAYER_PRIORITY invalid:",
"It must be a permutation of"
):
self.assertIn(f"{msg}", str(raises.exception))
@skip_no_omp
def test_omp(self):
for env_var in ("omp tbb workqueue", "omp workqueue tbb"):
threading_layer_priority, out = self.each_env_var(env_var)
self.assertEqual(threading_layer_priority.strip(), env_var)
self.assertIn("@omp@", out)
@skip_no_tbb
def test_tbb(self):
for env_var in ("tbb omp workqueue", "tbb workqueue omp"):
threading_layer_priority, out = self.each_env_var(env_var)
self.assertEqual(threading_layer_priority.strip(), env_var)
self.assertIn("@tbb@", out)
def test_workqueue(self):
for env_var in ("workqueue tbb omp", "workqueue omp tbb"):
threading_layer_priority, out = self.each_env_var(env_var)
self.assertEqual(threading_layer_priority.strip(), env_var)
self.assertIn("@workqueue@", out)
@skip_parfors_unsupported
class TestMiscBackendIssues(ThreadLayerTestHelper):
"""
Checks fixes for the issues with threading backends implementation
"""
_DEBUG = False
@skip_no_omp
def test_omp_stack_overflow(self):
"""
Tests that OMP does not overflow stack
"""
runme = """if 1:
from numba import vectorize, threading_layer
import numpy as np
@vectorize(['f4(f4,f4,f4,f4,f4,f4,f4,f4)'],>
def foo(a, b, c, d, e, f, g, h):
return a+b+c+d+e+f+g+h
x = np.ones(2**20, np.float32)
foo(*([x]*8))
print("@%s@" % threading_layer())
"""
cmdline = [sys.executable, '-c', runme]
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = "omp"
env['OMP_STACKSIZE'] = "100K"
out, err = self.run_cmd(cmdline, env=env)
if self._DEBUG:
print(out, err)
self.assertIn("@omp@", out)
@skip_no_tbb
def test_single_thread_tbb(self):
"""
Tests that TBB works well with single thread
https://github.com/numba/numba/issues/3440
"""
runme = """if 1:
from numba import njit, prange, threading_layer
@njit(parallel=True)
def foo(n):
acc = 0
for i in prange(n):
acc += i
return acc
foo(100)
print("@%s@" % threading_layer())
"""
cmdline = [sys.executable, '-c', runme]
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = "tbb"
env['NUMBA_NUM_THREADS'] = "1"
out, err = self.run_cmd(cmdline, env=env)
if self._DEBUG:
print(out, err)
self.assertIn("@tbb@", out)
def test_workqueue_aborts_on_nested_parallelism(self):
"""
Tests workqueue raises sigabrt if a nested parallel call is performed
"""
runme = """if 1:
from numba import njit, prange
import numpy as np
@njit(parallel=True)
def nested(x):
for i in prange(len(x)):
x[i] += 1
@njit(parallel=True)
def main():
Z = np.zeros((5, 10))
for i in prange(Z.shape[0]):
nested(Z[i])
return Z
main()
"""
cmdline = [sys.executable, '-c', runme]
env = os.environ.copy()
env['NUMBA_THREADING_LAYER'] = "workqueue"
env['NUMBA_NUM_THREADS'] = "4"
try:
out, err = self.run_cmd(cmdline, env=env)
except AssertionError as e:
if self._DEBUG:
print(out, err)
e_msg = str(e)
self.assertIn("failed with code", e_msg)
# raised a SIGABRT, but the value is platform specific so just check
# the error message
self.assertIn("Terminating: Nested parallel kernel launch detected",
e_msg)
# 32bit or windows py27 (not that this runs on windows)
@skip_parfors_unsupported
@skip_unless_gnu_omp
class TestForkSafetyIssues(ThreadLayerTestHelper):
"""
Checks Numba's behaviour in various situations involving GNU OpenMP and fork
"""
_DEBUG = False
def test_check_threading_layer_is_gnu(self):
runme = """if 1:
from numba.np.ufunc import omppool
assert omppool.openmp_vendor == 'GNU'
"""
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
def test_par_parent_os_fork_par_child(self):
"""
Whilst normally valid, this actually isn't for Numba invariant of OpenMP
Checks SIGABRT is received.
"""
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
Z = busy_func(X, Y)
pid = os.fork()
if pid == 0:
Z = busy_func(X, Y)
else:
os.wait()
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
try:
out, err = self.run_cmd(cmdline)
except AssertionError as e:
self.assertIn("failed with code -6", str(e))
def test_par_parent_implicit_mp_fork_par_child(self):
"""
Implicit use of multiprocessing fork context.
Does this:
1. Start with OpenMP
2. Fork to processes using OpenMP (this is invalid)
3. Joins fork
4. Check the exception pushed onto the queue that is a result of
catching SIGTERM coming from the C++ aborting on illegal fork
pattern for GNU OpenMP
"""
body = """if 1:
mp = multiprocessing.get_context('fork')
X = np.arange(1000000.)
Y = np.arange(1000000.)
q = mp.Queue()
# Start OpenMP runtime on parent via parallel function
Z = busy_func(X, Y, q)
# fork() underneath with no exec, will abort
proc = mp.Process(target = busy_func, args=(X, Y, q))
proc.start()
err = q.get()
assert "Caught SIGTERM" in str(err)
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
if self._DEBUG:
print(out, err)
@linux_only
def test_par_parent_explicit_mp_fork_par_child(self):
"""
Explicit use of multiprocessing fork context.
Does this:
1. Start with OpenMP
2. Fork to processes using OpenMP (this is invalid)
3. Joins fork
4. Check the exception pushed onto the queue that is a result of
catching SIGTERM coming from the C++ aborting on illegal fork
pattern for GNU OpenMP
"""
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
q = multiprocessing.Queue()
# Start OpenMP runtime on parent via parallel function
Z = busy_func(X, Y, q)
# fork() underneath with no exec, will abort
ctx = multiprocessing.get_context('fork')
proc = ctx.Process(target = busy_func, args=(X, Y, q))
proc.start()
proc.join()
err = q.get()
assert "Caught SIGTERM" in str(err)
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
if self._DEBUG:
print(out, err)
def test_par_parent_mp_spawn_par_child_par_parent(self):
"""
Explicit use of multiprocessing spawn, this is safe.
Does this:
1. Start with OpenMP
2. Spawn to processes using OpenMP
3. Join spawns
4. Run some more OpenMP
"""
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
q = multiprocessing.Queue()
# Start OpenMP runtime and run on parent via parallel function
Z = busy_func(X, Y, q)
procs = []
ctx = multiprocessing.get_context('spawn')
for x in range(20): # start a lot to try and get overlap
## fork() + exec() to run some OpenMP on children
proc = ctx.Process(target = busy_func, args=(X, Y, q))
procs.append(proc)
sys.stdout.flush()
sys.stderr.flush()
proc.start()
[p.join() for p in procs]
try:
q.get(False)
except multiprocessing.queues.Empty:
pass
else:
raise RuntimeError("Queue was not empty")
# Run some more OpenMP on parent
Z = busy_func(X, Y, q)
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
if self._DEBUG:
print(out, err)
def test_serial_parent_implicit_mp_fork_par_child_then_par_parent(self):
"""
Implicit use of multiprocessing (will be fork, but cannot declare that
in Py2.7 as there's no process launch context).
Does this:
1. Start with no OpenMP
2. Fork to processes using OpenMP
3. Join forks
4. Run some OpenMP
"""
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
q = multiprocessing.Queue()
# this is ok
procs = []
for x in range(10):
# fork() underneath with but no OpenMP in parent, this is ok
proc = multiprocessing.Process(target = busy_func,
args=(X, Y, q))
procs.append(proc)
proc.start()
[p.join() for p in procs]
# and this is still ok as the OpenMP happened in forks
Z = busy_func(X, Y, q)
try:
q.get(False)
except multiprocessing.queues.Empty:
pass
else:
raise RuntimeError("Queue was not empty")
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
if self._DEBUG:
print(out, err)
@linux_only
def test_serial_parent_explicit_mp_fork_par_child_then_par_parent(self):
"""
Explicit use of multiprocessing 'fork'.
Does this:
1. Start with no OpenMP
2. Fork to processes using OpenMP
3. Join forks
4. Run some OpenMP
"""
body = """if 1:
X = np.arange(1000000.)
Y = np.arange(1000000.)
q = multiprocessing.Queue()
# this is ok
procs = []
ctx = multiprocessing.get_context('fork')
for x in range(10):
# fork() underneath with but no OpenMP in parent, this is ok
proc = ctx.Process(target = busy_func, args=(X, Y, q))
procs.append(proc)
proc.start()
[p.join() for p in procs]
# and this is still ok as the OpenMP happened in forks
Z = busy_func(X, Y, q)
try:
q.get(False)
except multiprocessing.queues.Empty:
pass
else:
raise RuntimeError("Queue was not empty")
"""
runme = self.template % body
cmdline = [sys.executable, '-c', runme]
out, err = self.run_cmd(cmdline)
if self._DEBUG:
print(out, err)
@skip_parfors_unsupported
@skip_no_tbb
class TestTBBSpecificIssues(ThreadLayerTestHelper):
_DEBUG = False
@linux_only # os.fork required.
def test_fork_from_non_main_thread(self):
# See issue #5973 and PR #6208 for original context.
# See issue #6963 for context on the following comments:
#
# Important things to note:
# 1. Compilation of code containing an objmode block will result in the
# use of and `ObjModeLiftedWith` as the dispatcher. This inherits
# from `LiftedCode` which handles the serialization. In that
# serialization is a call to uuid.uuid1() which causes a fork_exec in
# CPython internals.
# 2. The selected parallel backend thread pool is started during the
# compilation of a function that has `parallel=True`.
# 3. The TBB backend can handle forks from the main thread, it will
# safely reinitialise after so doing. If a fork occurs from a
# non-main thread it will warn and the state is invalid in the child
# process.
#
# Due to 1. and 2. the `obj_mode_func` function separated out and is
# `njit` decorated. This means during type inference of `work` it will
# trigger a standard compilation of the function and the thread pools
# won't have started yet as the parallelisation compiler passes for
# `work` won't yet have run. This mitigates the fork() call from 1.
# occuring after 2. The result of this is that 3. can be tested using
# the threading etc herein with the state being known as the above
# described, i.e. the TBB threading layer has not experienced a fork().
runme = """if 1:
import threading
import numba
numba.config.THREADING_LAYER='tbb'
from numba import njit, prange, objmode
from numba.core.serialize import PickleCallableByPath
import os
e_running = threading.Event()
e_proceed = threading.Event()
def indirect_core():
e_running.set()
# wait for forker() to have forked
while not e_proceed.isSet():
pass
indirect = PickleCallableByPath(indirect_core)
@njit
def obj_mode_func():
with objmode():
indirect()
@njit(parallel=True, nogil=True)
def work():
acc = 0
for x in prange(10):
acc += x
obj_mode_func()
return acc
def runner():