-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathparfor.py
5253 lines (4694 loc) · 220 KB
/
parfor.py
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
#
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
"""
This module transforms data-parallel operations such as Numpy calls into
'Parfor' nodes, which are nested loops that can be parallelized.
It also implements optimizations such as loop fusion, and extends the rest of
compiler analysis and optimizations to support Parfors.
This is similar to ParallelAccelerator package in Julia:
https://github.com/IntelLabs/ParallelAccelerator.jl
'Parallelizing Julia with a Non-invasive DSL', T. Anderson et al., ECOOP'17.
"""
import types as pytypes # avoid confusion with numba.types
import sys, math
import os
import textwrap
import copy
import inspect
import linecache
from functools import reduce
from collections import defaultdict, OrderedDict, namedtuple
from contextlib import contextmanager
import operator
from dataclasses import make_dataclass
import warnings
from llvmlite import ir as lir
from numba.core.imputils import impl_ret_untracked
import numba.core.ir
from numba.core import types, typing, utils, errors, ir, analysis, postproc, rewrites, typeinfer, config, ir_utils
from numba import prange, pndindex
from numba.np.npdatetime_helpers import datetime_minimum, datetime_maximum
from numba.np.numpy_support import as_dtype, numpy_version
from numba.core.typing.templates import infer_global, AbstractTemplate
from numba.stencils.stencilparfor import StencilPass
from numba.core.extending import register_jitable, lower_builtin
from numba.core.ir_utils import (
mk_unique_var,
next_label,
mk_alloc,
get_np_ufunc_typ,
mk_range_block,
mk_loop_header,
get_name_var_table,
replace_vars,
replace_vars_inner,
visit_vars,
visit_vars_inner,
remove_dead,
copy_propagate,
get_block_copies,
apply_copy_propagate,
dprint_func_ir,
find_topo_order,
get_stmt_writes,
rename_labels,
get_call_table,
simplify,
simplify_CFG,
has_no_side_effect,
canonicalize_array_math,
add_offset_to_labels,
find_callname,
find_build_sequence,
guard,
require,
GuardException,
compile_to_numba_ir,
get_definition,
build_definitions,
replace_arg_nodes,
replace_returns,
is_getitem,
is_setitem,
is_get_setitem,
index_var_of_get_setitem,
set_index_var_of_get_setitem,
find_potential_aliases,
replace_var_names,
transfer_scope,
)
from numba.core.analysis import (compute_use_defs, compute_live_map,
compute_dead_maps, compute_cfg_from_blocks)
from numba.core.controlflow import CFGraph
from numba.core.typing import npydecl, signature
from numba.core.types.functions import Function
from numba.parfors.array_analysis import (random_int_args, random_1arg_size,
random_2arg_sizelast, random_3arg_sizelast,
random_calls, assert_equiv)
from numba.core.extending import overload
import copy
import numpy
import numpy as np
from numba.parfors import array_analysis
import numba.cpython.builtins
from numba.stencils import stencilparfor
# circular dependency: import numba.npyufunc.dufunc.DUFunc
# wrapped pretty print
_termwidth = 80
_txtwrapper = textwrap.TextWrapper(width=_termwidth, drop_whitespace=False)
def print_wrapped(x):
for l in x.splitlines():
[print(y) for y in _txtwrapper.wrap(l)]
sequential_parfor_lowering = False
# init_prange is a sentinel call that specifies the start of the initialization
# code for the computation in the upcoming prange call
# This lets the prange pass to put the code in the generated parfor's init_block
def init_prange():
return
@overload(init_prange)
def init_prange_overload():
def no_op():
return
return no_op
class internal_prange(object):
def __new__(cls, *args):
return range(*args)
def min_parallel_impl(return_type, arg):
# XXX: use prange for 1D arrays since pndindex returns a 1-tuple instead of
# integer. This causes type and fusion issues.
if arg.ndim == 0:
def min_1(in_arr):
return in_arr[()]
elif arg.ndim == 1:
if isinstance(arg.dtype, (types.NPDatetime, types.NPTimedelta)):
# NaT is always returned if it is in the array
def min_1(in_arr):
numba.parfors.parfor.init_prange()
min_checker(len(in_arr))
val = numba.cpython.builtins.get_type_max_value(in_arr.dtype)
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val = datetime_minimum(val, in_arr[i])
return val
else:
def min_1(in_arr):
numba.parfors.parfor.init_prange()
min_checker(len(in_arr))
val = numba.cpython.builtins.get_type_max_value(in_arr.dtype)
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val = min(val, in_arr[i])
return val
else:
def min_1(in_arr):
numba.parfors.parfor.init_prange()
min_checker(len(in_arr))
val = numba.cpython.builtins.get_type_max_value(in_arr.dtype)
for i in numba.pndindex(in_arr.shape):
val = min(val, in_arr[i])
return val
return min_1
def max_parallel_impl(return_type, arg):
if arg.ndim == 0:
def max_1(in_arr):
return in_arr[()]
elif arg.ndim == 1:
if isinstance(arg.dtype, (types.NPDatetime, types.NPTimedelta)):
# NaT is always returned if it is in the array
def max_1(in_arr):
numba.parfors.parfor.init_prange()
max_checker(len(in_arr))
val = numba.cpython.builtins.get_type_min_value(in_arr.dtype)
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val = datetime_maximum(val, in_arr[i])
return val
else:
def max_1(in_arr):
numba.parfors.parfor.init_prange()
max_checker(len(in_arr))
val = numba.cpython.builtins.get_type_min_value(in_arr.dtype)
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val = max(val, in_arr[i])
return val
else:
def max_1(in_arr):
numba.parfors.parfor.init_prange()
max_checker(len(in_arr))
val = numba.cpython.builtins.get_type_min_value(in_arr.dtype)
for i in numba.pndindex(in_arr.shape):
val = max(val, in_arr[i])
return val
return max_1
def argmin_parallel_impl(in_arr):
numba.parfors.parfor.init_prange()
argmin_checker(len(in_arr))
A = in_arr.ravel()
init_val = numba.cpython.builtins.get_type_max_value(A.dtype)
ival = typing.builtins.IndexValue(0, init_val)
for i in numba.parfors.parfor.internal_prange(len(A)):
curr_ival = typing.builtins.IndexValue(i, A[i])
ival = min(ival, curr_ival)
return ival.index
def argmax_parallel_impl(in_arr):
numba.parfors.parfor.init_prange()
argmax_checker(len(in_arr))
A = in_arr.ravel()
init_val = numba.cpython.builtins.get_type_min_value(A.dtype)
ival = typing.builtins.IndexValue(0, init_val)
for i in numba.parfors.parfor.internal_prange(len(A)):
curr_ival = typing.builtins.IndexValue(i, A[i])
ival = max(ival, curr_ival)
return ival.index
def dotvv_parallel_impl(a, b):
numba.parfors.parfor.init_prange()
l = a.shape[0]
m = b.shape[0]
# TODO: investigate assert_equiv
#assert_equiv("sizes of l, m do not match", l, m)
s = 0
for i in numba.parfors.parfor.internal_prange(l):
s += a[i] * b[i]
return s
def dotvm_parallel_impl(a, b):
numba.parfors.parfor.init_prange()
l = a.shape
m, n = b.shape
# TODO: investigate assert_equiv
#assert_equiv("Sizes of l, m do not match", l, m)
c = np.zeros(n, a.dtype)
# TODO: evaluate dotvm implementation options
#for i in prange(n):
# s = 0
# for j in range(m):
# s += a[j] * b[j, i]
# c[i] = s
for i in numba.parfors.parfor.internal_prange(m):
c += a[i] * b[i, :]
return c
def dotmv_parallel_impl(a, b):
numba.parfors.parfor.init_prange()
m, n = a.shape
l = b.shape
# TODO: investigate assert_equiv
#assert_equiv("sizes of n, l do not match", n, l)
c = np.empty(m, a.dtype)
for i in numba.parfors.parfor.internal_prange(m):
s = 0
for j in range(n):
s += a[i, j] * b[j]
c[i] = s
return c
def dot_parallel_impl(return_type, atyp, btyp):
# Note that matrix matrix multiply is not translated.
if (isinstance(atyp, types.npytypes.Array) and
isinstance(btyp, types.npytypes.Array)):
if atyp.ndim == btyp.ndim == 1:
return dotvv_parallel_impl
# TODO: evaluate support for dotvm and enable
#elif atyp.ndim == 1 and btyp.ndim == 2:
# return dotvm_parallel_impl
elif atyp.ndim == 2 and btyp.ndim == 1:
return dotmv_parallel_impl
def sum_parallel_impl(return_type, arg):
zero = return_type(0)
if arg.ndim == 0:
def sum_1(in_arr):
return in_arr[()]
elif arg.ndim == 1:
def sum_1(in_arr):
numba.parfors.parfor.init_prange()
val = zero
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val += in_arr[i]
return val
else:
def sum_1(in_arr):
numba.parfors.parfor.init_prange()
val = zero
for i in numba.pndindex(in_arr.shape):
val += in_arr[i]
return val
return sum_1
def prod_parallel_impl(return_type, arg):
one = return_type(1)
if arg.ndim == 0:
def prod_1(in_arr):
return in_arr[()]
elif arg.ndim == 1:
def prod_1(in_arr):
numba.parfors.parfor.init_prange()
val = one
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val *= in_arr[i]
return val
else:
def prod_1(in_arr):
numba.parfors.parfor.init_prange()
val = one
for i in numba.pndindex(in_arr.shape):
val *= in_arr[i]
return val
return prod_1
def mean_parallel_impl(return_type, arg):
# can't reuse sum since output type is different
zero = return_type(0)
if arg.ndim == 0:
def mean_1(in_arr):
return in_arr[()]
elif arg.ndim == 1:
def mean_1(in_arr):
numba.parfors.parfor.init_prange()
val = zero
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val += in_arr[i]
return val/len(in_arr)
else:
def mean_1(in_arr):
numba.parfors.parfor.init_prange()
val = zero
for i in numba.pndindex(in_arr.shape):
val += in_arr[i]
return val/in_arr.size
return mean_1
def var_parallel_impl(return_type, arg):
if arg.ndim == 0:
def var_1(in_arr):
return 0
elif arg.ndim == 1:
def var_1(in_arr):
# Compute the mean
m = in_arr.mean()
# Compute the sum of square diffs
numba.parfors.parfor.init_prange()
ssd = 0
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
val = in_arr[i] - m
ssd += np.real(val * np.conj(val))
return ssd / len(in_arr)
else:
def var_1(in_arr):
# Compute the mean
m = in_arr.mean()
# Compute the sum of square diffs
numba.parfors.parfor.init_prange()
ssd = 0
for i in numba.pndindex(in_arr.shape):
val = in_arr[i] - m
ssd += np.real(val * np.conj(val))
return ssd / in_arr.size
return var_1
def std_parallel_impl(return_type, arg):
def std_1(in_arr):
return in_arr.var() ** 0.5
return std_1
def arange_parallel_impl(return_type, *args, dtype=None):
inferred_dtype = as_dtype(return_type.dtype)
def arange_1(stop):
return np.arange(0, stop, 1, inferred_dtype)
def arange_1_dtype(stop, dtype):
return np.arange(0, stop, 1, dtype)
def arange_2(start, stop):
return np.arange(start, stop, 1, inferred_dtype)
def arange_2_dtype(start, stop, dtype):
return np.arange(start, stop, 1, dtype)
def arange_3(start, stop, step):
return np.arange(start, stop, step, inferred_dtype)
def arange_3_dtype(start, stop, step, dtype):
return np.arange(start, stop, step, dtype)
if any(isinstance(a, types.Complex) for a in args):
def arange_4(start, stop, step, dtype):
numba.parfors.parfor.init_prange()
nitems_c = (stop - start) / step
nitems_r = math.ceil(nitems_c.real)
nitems_i = math.ceil(nitems_c.imag)
nitems = int(max(min(nitems_i, nitems_r), 0))
arr = np.empty(nitems, dtype)
for i in numba.parfors.parfor.internal_prange(nitems):
arr[i] = start + i * step
return arr
else:
def arange_4(start, stop, step, dtype):
numba.parfors.parfor.init_prange()
nitems_r = math.ceil((stop - start) / step)
nitems = int(max(nitems_r, 0))
arr = np.empty(nitems, dtype)
val = start
for i in numba.parfors.parfor.internal_prange(nitems):
arr[i] = start + i * step
return arr
if len(args) == 1:
return arange_1 if dtype is None else arange_1_dtype
elif len(args) == 2:
return arange_2 if dtype is None else arange_2_dtype
elif len(args) == 3:
return arange_3 if dtype is None else arange_3_dtype
elif len(args) == 4:
return arange_4
else:
raise ValueError("parallel arange with types {}".format(args))
def linspace_parallel_impl(return_type, *args):
dtype = as_dtype(return_type.dtype)
def linspace_2(start, stop):
return np.linspace(start, stop, 50)
def linspace_3(start, stop, num):
numba.parfors.parfor.init_prange()
arr = np.empty(num, dtype)
div = num - 1
delta = stop - start
arr[0] = start
for i in numba.parfors.parfor.internal_prange(num):
arr[i] = start + delta * (i / div)
return arr
if len(args) == 2:
return linspace_2
elif len(args) == 3:
return linspace_3
else:
raise ValueError("parallel linspace with types {}".format(args))
swap_functions_map = {
('argmin', 'numpy'): lambda r,a: argmin_parallel_impl,
('argmax', 'numpy'): lambda r,a: argmax_parallel_impl,
('min', 'numpy'): min_parallel_impl,
('max', 'numpy'): max_parallel_impl,
('amin', 'numpy'): min_parallel_impl,
('amax', 'numpy'): max_parallel_impl,
('sum', 'numpy'): sum_parallel_impl,
('prod', 'numpy'): prod_parallel_impl,
('mean', 'numpy'): mean_parallel_impl,
('var', 'numpy'): var_parallel_impl,
('std', 'numpy'): std_parallel_impl,
('dot', 'numpy'): dot_parallel_impl,
('arange', 'numpy'): arange_parallel_impl,
('linspace', 'numpy'): linspace_parallel_impl,
}
def fill_parallel_impl(return_type, arr, val):
"""Parallel implementation of ndarray.fill. The array on
which to operate is retrieved from get_call_name and
is passed along with the value to fill.
"""
if arr.ndim == 1:
def fill_1(in_arr, val):
numba.parfors.parfor.init_prange()
for i in numba.parfors.parfor.internal_prange(len(in_arr)):
in_arr[i] = val
return None
else:
def fill_1(in_arr, val):
numba.parfors.parfor.init_prange()
for i in numba.pndindex(in_arr.shape):
in_arr[i] = val
return None
return fill_1
replace_functions_ndarray = {
'fill': fill_parallel_impl,
}
@register_jitable
def max_checker(arr_size):
if arr_size == 0:
raise ValueError(("zero-size array to reduction operation "
"maximum which has no identity"))
@register_jitable
def min_checker(arr_size):
if arr_size == 0:
raise ValueError(("zero-size array to reduction operation "
"minimum which has no identity"))
@register_jitable
def argmin_checker(arr_size):
if arr_size == 0:
raise ValueError("attempt to get argmin of an empty sequence")
@register_jitable
def argmax_checker(arr_size):
if arr_size == 0:
raise ValueError("attempt to get argmax of an empty sequence")
checker_impl = namedtuple('checker_impl', ['name', 'func'])
replace_functions_checkers_map = {
('argmin', 'numpy') : checker_impl('argmin_checker', argmin_checker),
('argmax', 'numpy') : checker_impl('argmax_checker', argmax_checker),
('min', 'numpy') : checker_impl('min_checker', min_checker),
('max', 'numpy') : checker_impl('max_checker', max_checker),
('amin', 'numpy') : checker_impl('min_checker', min_checker),
('amax', 'numpy') : checker_impl('max_checker', max_checker),
}
class LoopNest(object):
'''The LoopNest class holds information of a single loop including
the index variable (of a non-negative integer value), and the
range variable, e.g. range(r) is 0 to r-1 with step size 1.
'''
def __init__(self, index_variable, start, stop, step):
self.index_variable = index_variable
self.start = start
self.stop = stop
self.step = step
def __repr__(self):
return ("LoopNest(index_variable = {}, range = ({}, {}, {}))".
format(self.index_variable, self.start, self.stop, self.step))
def list_vars(self):
all_uses = []
all_uses.append(self.index_variable)
if isinstance(self.start, ir.Var):
all_uses.append(self.start)
if isinstance(self.stop, ir.Var):
all_uses.append(self.stop)
if isinstance(self.step, ir.Var):
all_uses.append(self.step)
return all_uses
class Parfor(ir.Expr, ir.Stmt):
id_counter = 0
def __init__(
self,
loop_nests,
init_block,
loop_body,
loc,
index_var,
equiv_set,
pattern,
flags,
*, #only specify the options below by keyword
no_sequential_lowering=False,
races=None):
if races is None:
races = set()
super(Parfor, self).__init__(
op='parfor',
loc=loc
)
self.id = type(self).id_counter
type(self).id_counter += 1
#self.input_info = input_info
#self.output_info = output_info
self.loop_nests = loop_nests
self.init_block = init_block
self.loop_body = loop_body
self.index_var = index_var
self.params = None # filled right before parallel lowering
self.equiv_set = equiv_set
# The parallel patterns this parfor was generated from and their options
# for example, a parfor could be from the stencil pattern with
# the neighborhood option
assert len(pattern) > 1
self.patterns = [pattern]
self.flags = flags
# if True, this parfor shouldn't be lowered sequentially even with the
# sequential lowering option
self.no_sequential_lowering = no_sequential_lowering
self.races = races
self.redvars = []
self.reddict = {}
# If the lowerer is None then the standard lowerer will be used.
# This can be set to a function to have that function act as the lowerer
# for this parfor. This lowerer field will also prevent parfors from
# being fused unless they have use the same lowerer.
self.lowerer = None
if config.DEBUG_ARRAY_OPT_STATS:
fmt = 'Parallel for-loop #{} is produced from pattern \'{}\' at {}'
print(fmt.format(
self.id, pattern, loc))
def __repr__(self):
return "id=" + str(self.id) + repr(self.loop_nests) + \
repr(self.loop_body) + repr(self.index_var)
def get_loop_nest_vars(self):
return [x.index_variable for x in self.loop_nests]
def list_vars(self):
"""list variables used (read/written) in this parfor by
traversing the body and combining block uses.
"""
all_uses = []
for l, b in self.loop_body.items():
for stmt in b.body:
all_uses += stmt.list_vars()
for loop in self.loop_nests:
all_uses += loop.list_vars()
for stmt in self.init_block.body:
all_uses += stmt.list_vars()
return all_uses
def get_shape_classes(self, var, typemap=None):
"""get the shape classes for a given variable.
If a typemap is specified then use it for type resolution
"""
# We get shape classes from the equivalence set but that
# keeps its own typemap at a time prior to lowering. So
# if something is added during lowering then we can pass
# in a type map to use. We temporarily replace the
# equivalence set typemap, do the work and then restore
# the original on the way out.
if typemap is not None:
save_typemap = self.equiv_set.typemap
self.equiv_set.typemap = typemap
res = self.equiv_set.get_shape_classes(var)
if typemap is not None:
self.equiv_set.typemap = save_typemap
return res
def dump(self, file=None):
file = file or sys.stdout
print(("begin parfor {}".format(self.id)).center(20, '-'), file=file)
print("index_var = ", self.index_var, file=file)
print("params = ", self.params, file=file)
print("races = ", self.races, file=file)
for loopnest in self.loop_nests:
print(loopnest, file=file)
print("init block:", file=file)
self.init_block.dump(file)
for offset, block in sorted(self.loop_body.items()):
print('label %s:' % (offset,), file=file)
block.dump(file)
print(("end parfor {}".format(self.id)).center(20, '-'), file=file)
def validate_params(self, typemap):
"""
Check that Parfors params are of valid types.
"""
if self.params is None:
msg = ("Cannot run parameter validation on a Parfor with params "
"not set")
raise ValueError(msg)
for p in self.params:
ty = typemap.get(p)
if ty is None:
msg = ("Cannot validate parameter %s, there is no type "
"information available")
raise ValueError(msg)
if isinstance(ty, types.BaseTuple):
if ty.count > config.PARFOR_MAX_TUPLE_SIZE:
msg = ("Use of a tuple (%s) of length %d in a parallel region "
"exceeds the maximum supported tuple size. Since "
"Generalized Universal Functions back parallel regions "
"and those do not support tuples, tuples passed to "
"parallel regions are unpacked if their size is below "
"a certain threshold, currently configured to be %d. "
"This threshold can be modified using the Numba "
"environment variable NUMBA_PARFOR_MAX_TUPLE_SIZE.")
raise errors.UnsupportedParforsError(msg %
(p, ty.count, config.PARFOR_MAX_TUPLE_SIZE),
self.loc)
def _analyze_parfor(parfor, equiv_set, typemap, array_analysis):
"""Recursive array analysis for parfor nodes.
"""
func_ir = array_analysis.func_ir
parfor_blocks = wrap_parfor_blocks(parfor)
# Since init_block get label 0 after wrap, we need to save
# the equivset for the real block label 0.
backup_equivset = array_analysis.equiv_sets.get(0, None)
array_analysis.run(parfor_blocks, equiv_set)
unwrap_parfor_blocks(parfor, parfor_blocks)
parfor.equiv_set = array_analysis.equiv_sets[0]
# Restore equivset for block 0 after parfor is unwrapped
if backup_equivset:
array_analysis.equiv_sets[0] = backup_equivset
return [], []
array_analysis.array_analysis_extensions[Parfor] = _analyze_parfor
class ParforDiagnostics(object):
"""Holds parfor diagnostic info, this is accumulated throughout the
PreParforPass and ParforPass, also in the closure inlining!
"""
def __init__(self):
# holds ref to the function for which this is providing diagnostics
self.func = None
# holds a map of the replaced functions
self.replaced_fns = dict()
# used to identify "internal" parfor functions
self.internal_name = '__numba_parfor_gufunc'
self.fusion_info = defaultdict(list)
self.nested_fusion_info = defaultdict(list)
self.fusion_reports = []
self.hoist_info = {}
self.has_setup = False
def setup(self, func_ir, fusion_enabled):
self.func_ir = func_ir
self.name = self.func_ir.func_id.func_qualname
self.line = self.func_ir.loc
self.fusion_enabled = fusion_enabled
if self.internal_name in self.name:
self.purpose = 'Internal parallel function'
else:
self.purpose = 'Function %s, %s' % (self.name, self.line)
# we store a reference to the parfors prior to fusion etc, the parfors
# do get mangled in the fusion process but in a predetermined manner
# and by holding a reference here the "before" state can be printed
self.initial_parfors = self.get_parfors()
self.has_setup = True
@property
def has_setup(self):
return self._has_setup
@has_setup.setter
def has_setup(self, state):
self._has_setup = state
def count_parfors(self, blocks=None):
return len(self.get_parfors())
def _get_nested_parfors(self, parfor, parfors_list):
blocks = wrap_parfor_blocks(parfor)
self._get_parfors(blocks, parfors_list)
unwrap_parfor_blocks(parfor)
def _get_parfors(self, blocks, parfors_list):
for label, blk in blocks.items():
for stmt in blk.body:
if isinstance(stmt, Parfor):
parfors_list.append(stmt)
self._get_nested_parfors(stmt, parfors_list)
def get_parfors(self):
parfors_list = []
self._get_parfors(self.func_ir.blocks, parfors_list)
return parfors_list
def hoisted_allocations(self):
allocs = []
for pf_id, data in self.hoist_info.items():
stmt = data.get('hoisted', [])
for inst in stmt:
if isinstance(inst.value, ir.Expr):
if inst.value.op == 'call':
call = guard(find_callname, self.func_ir, inst.value)
if call is not None and call == ('empty', 'numpy'):
allocs.append(inst)
return allocs
def compute_graph_info(self, _a):
"""
compute adjacency list of the fused loops
and find the roots in of the lists
"""
a = copy.deepcopy(_a)
if a == {}:
return [], set()
vtx = set()
for v in a.values():
for x in v:
vtx.add(x)
# find roots
potential_roots = set(a.keys())
roots = potential_roots - vtx
if roots is None:
roots = set()
# populate rest of adjacency list
not_roots = set()
for x in range(max(set(a.keys()).union(vtx)) + 1):
val = a.get(x)
if val is not None:
a[x] = val
elif val == []:
not_roots.add(x) # debug only
else:
a[x] = []
# fold adjacency list into an actual list ordered
# by vtx
l = []
for x in sorted(a.keys()):
l.append(a[x])
return l, roots #, not_roots
def get_stats(self, fadj, nadj, root):
"""
Computes the number of fused and serialized loops
based on a fusion adjacency list `fadj` and a nested
parfors adjacency list `nadj` for the root, `root`
"""
def count_root(fadj, nadj, root, nfused, nserial):
for k in nadj[root]:
nserial += 1
if nadj[k] == []:
nfused += len(fadj[k])
else:
nf, ns = count_root(fadj, nadj, k, nfused, nserial)
nfused += nf
nserial = ns
return nfused, nserial
nfused, nserial = count_root(fadj, nadj, root, 0, 0)
return nfused, nserial
def reachable_nodes(self, adj, root):
"""
returns a list of nodes reachable in an adjacency list from a
specified root
"""
fusers = []
fusers.extend(adj[root])
for k in adj[root]:
if adj[k] != []:
fusers.extend(self.reachable_nodes(adj, k))
return fusers
def sort_pf_by_line(self, pf_id, parfors_simple):
"""
pd_id - the parfors id
parfors_simple - the simple parfors map
"""
# this sorts parfors by source line number
pf = parfors_simple[pf_id][0]
pattern = pf.patterns[0]
line = max(0, pf.loc.line - 1) # why are these out by 1 ?!
filename = self.func_ir.loc.filename
nadj, nroots = self.compute_graph_info(self.nested_fusion_info)
fadj, froots = self.compute_graph_info(self.fusion_info)
graphs = [nadj, fadj]
# If the parfor is internal, like internal prange, then the
# default line number is from its location in the numba source
# To get a more accurate line number, this first checks the
# adjacency graph for fused parfors that might not be internal
# and uses the minimum line number from there. If that fails
# (case where there's just a single internal parfor) the IR
# is walked backwards from the parfor location and the first non
# parfor statement line number is used.
if isinstance(pattern, tuple):
if pattern[1] == 'internal':
reported_loc = pattern[2][1]
if reported_loc.filename == filename:
return max(0, reported_loc.line - 1)
else:
# first recurse and check the adjacency list for
# something that is not an in internal parfor
tmp = []
for adj in graphs:
if adj: # graph may be empty, e.g. no nesting
for k in adj[pf_id]:
tmp.append(self.sort_pf_by_line(k, parfors_simple))
if tmp:
return max(0, min(tmp) - 1)
# second run through the parfor block to see if there's
# and reference to a line number in the user source
for blk in pf.loop_body.values():
for stmt in blk.body:
if stmt.loc.filename == filename:
return max(0, stmt.loc.line - 1)
# finally run through the func_ir and look for the
# first non-parfor statement prior to this one and
# grab the line from that
for blk in self.func_ir.blocks.values():
try:
idx = blk.body.index(pf)
for i in range(idx - 1, 0, -1):
stmt = blk.body[i]
if not isinstance(stmt, Parfor):
line = max(0, stmt.loc.line - 1)
break
except ValueError:
pass
return line
def get_parfors_simple(self, print_loop_search):
parfors_simple = dict()
# print in line order, parfors loop id is based on discovery order
for pf in sorted(self.initial_parfors, key=lambda x: x.loc.line):
# use 0 here, the parfors are mutated by the time this routine
# is called, however, fusion appends the patterns so we can just
# pull in the first as a "before fusion" emulation
r_pattern = pf.patterns[0]
pattern = pf.patterns[0]
loc = pf.loc
if isinstance(pattern, tuple):
if pattern[0] == 'prange':
if pattern[1] == 'internal':
replfn = '.'.join(reversed(list(pattern[2][0])))
loc = pattern[2][1]
r_pattern = '%s %s' % (replfn, '(internal parallel version)')
elif pattern[1] == 'user':
r_pattern = "user defined prange"
elif pattern[1] == 'pndindex':
r_pattern = "internal pndindex" #FIXME: trace this!
else:
assert 0
fmt = 'Parallel for-loop #%s: is produced from %s:\n %s\n \n'
if print_loop_search:
print_wrapped(fmt % (pf.id, loc, r_pattern))
parfors_simple[pf.id] = (pf, loc, r_pattern)
return parfors_simple
def get_all_lines(self, parfors_simple):
# ensure adjacency lists are the same size for both sets of info
# (nests and fusion may not traverse the same space, for
# convenience [] is used as a condition to halt recursion)
fadj, froots = self.compute_graph_info(self.fusion_info)
nadj, _nroots = self.compute_graph_info(self.nested_fusion_info)
if len(fadj) > len(nadj):
lim = len(fadj)
tmp = nadj
else:
lim = len(nadj)
tmp = fadj
for x in range(len(tmp), lim):
tmp.append([])
# This computes the roots of true loop nests (i.e. loops containing
# loops opposed to just a loop that's a root).
nroots = set()
if _nroots:
for r in _nroots:
if nadj[r] != []:
nroots.add(r)
all_roots = froots ^ nroots
# This computes all the parfors at the top level that are either:
# - roots of loop fusion
# - roots of true loop nests
# it then combines these based on source line number for ease of
# producing output ordered in a manner similar to the code structure
froots_lines = {}
for x in froots:
line = self.sort_pf_by_line(x, parfors_simple)
froots_lines[line] = 'fuse', x, fadj
nroots_lines = {}
for x in nroots:
line = self.sort_pf_by_line(x, parfors_simple)
nroots_lines[line] = 'nest', x, nadj
all_lines = froots_lines.copy()
all_lines.update(nroots_lines)
return all_lines
def source_listing(self, parfors_simple, purpose_str):
filename = self.func_ir.loc.filename
count = self.count_parfors()
func_name = self.func_ir.func_id.func
try:
lines = inspect.getsource(func_name).splitlines()
except OSError: # generated function
lines = None
if lines and parfors_simple:
src_width = max([len(x) for x in lines])
map_line_to_pf = defaultdict(list) # parfors can alias lines
for k, v in parfors_simple.items():
# TODO: do a better job of tracking parfors that are not in
# this file but are referred to, e.g. np.arange()