forked from numba/numba
-
Notifications
You must be signed in to change notification settings - Fork 2
/
parfor.py
3181 lines (2838 loc) · 129 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.
"""
from __future__ import print_function, division, absolute_import
import types as pytypes # avoid confusion with numba.types
import sys, math
from functools import reduce
from collections import defaultdict, namedtuple
from contextlib import contextmanager
import operator
import numba
from numba import ir, ir_utils, types, typing, rewrites, config, analysis, prange, pndindex
from numba import array_analysis, postproc, typeinfer
from numba.numpy_support import as_dtype
from numba.typing.templates import infer_global, AbstractTemplate
from numba import stencilparfor
from numba.stencilparfor import StencilPass
from numba.extending import register_jitable
from numba.ir_utils import (
mk_unique_var,
next_label,
mk_alloc,
get_np_ufunc_typ,
mk_range_block,
mk_loop_header,
find_op_typ,
get_name_var_table,
replace_vars,
replace_vars_inner,
visit_vars,
visit_vars_inner,
remove_dels,
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)
from numba.analysis import (compute_use_defs, compute_live_map,
compute_dead_maps, compute_cfg_from_blocks)
from numba.controlflow import CFGraph
from numba.typing import npydecl, signature
from numba.types.functions import Function
from numba.array_analysis import (random_int_args, random_1arg_size,
random_2arg_sizelast, random_3arg_sizelast,
random_calls, assert_equiv)
from numba.extending import overload
import copy
import numpy
import numpy as np
# circular dependency: import numba.npyufunc.dufunc.DUFunc
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 == 1:
def min_1(in_arr):
numba.parfor.init_prange()
min_checker(len(in_arr))
val = numba.targets.builtins.get_type_max_value(in_arr.dtype)
for i in numba.parfor.internal_prange(len(in_arr)):
val = min(val, in_arr[i])
return val
else:
def min_1(in_arr):
numba.parfor.init_prange()
min_checker(len(in_arr))
val = numba.targets.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 == 1:
def max_1(in_arr):
numba.parfor.init_prange()
max_checker(len(in_arr))
val = numba.targets.builtins.get_type_min_value(in_arr.dtype)
for i in numba.parfor.internal_prange(len(in_arr)):
val = max(val, in_arr[i])
return val
else:
def max_1(in_arr):
numba.parfor.init_prange()
max_checker(len(in_arr))
val = numba.targets.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.parfor.init_prange()
argmin_checker(len(in_arr))
A = in_arr.ravel()
init_val = numba.targets.builtins.get_type_max_value(A.dtype)
ival = numba.typing.builtins.IndexValue(0, init_val)
for i in numba.parfor.internal_prange(len(A)):
curr_ival = numba.typing.builtins.IndexValue(i, A[i])
ival = min(ival, curr_ival)
return ival.index
def argmax_parallel_impl(in_arr):
numba.parfor.init_prange()
argmax_checker(len(in_arr))
A = in_arr.ravel()
init_val = numba.targets.builtins.get_type_min_value(A.dtype)
ival = numba.typing.builtins.IndexValue(0, init_val)
for i in numba.parfor.internal_prange(len(A)):
curr_ival = numba.typing.builtins.IndexValue(i, A[i])
ival = max(ival, curr_ival)
return ival.index
def dotvv_parallel_impl(a, b):
numba.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.parfor.internal_prange(l):
s += a[i] * b[i]
return s
def dotvm_parallel_impl(a, b):
numba.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.parfor.internal_prange(m):
c += a[i] * b[i, :]
return c
def dotmv_parallel_impl(a, b):
numba.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.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 == 1:
def sum_1(in_arr):
numba.parfor.init_prange()
val = zero
for i in numba.parfor.internal_prange(len(in_arr)):
val += in_arr[i]
return val
else:
def sum_1(in_arr):
numba.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 == 1:
def prod_1(in_arr):
numba.parfor.init_prange()
val = one
for i in numba.parfor.internal_prange(len(in_arr)):
val *= in_arr[i]
return val
else:
def prod_1(in_arr):
numba.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 == 1:
def mean_1(in_arr):
numba.parfor.init_prange()
val = zero
for i in numba.parfor.internal_prange(len(in_arr)):
val += in_arr[i]
return val/len(in_arr)
else:
def mean_1(in_arr):
numba.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 == 1:
def var_1(in_arr):
# Compute the mean
m = in_arr.mean()
# Compute the sum of square diffs
numba.parfor.init_prange()
ssd = 0
for i in numba.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.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 = as_dtype(return_type.dtype)
def arange_1(stop):
return np.arange(0, stop, 1, dtype)
def arange_2(start, stop):
return np.arange(start, stop, 1, dtype)
def arange_3(start, stop, step):
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.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.parfor.internal_prange(nitems):
arr[i] = start + i * step
return arr
else:
def arange_4(start, stop, step, dtype):
numba.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.parfor.internal_prange(nitems):
arr[i] = start + i * step
return arr
if len(args) == 1:
return arange_1
elif len(args) == 2:
return arange_2
elif len(args) == 3:
return arange_3
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.parfor.init_prange()
arr = np.empty(num, dtype)
div = num - 1
delta = stop - start
arr[0] = start
for i in numba.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))
replace_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,
}
@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,
no_sequential_lowering=False,
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
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
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 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)
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 _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 PreParforPass(object):
"""Preprocessing for the Parfor pass. It mostly inlines parallel
implementations of numpy functions if available.
"""
def __init__(self, func_ir, typemap, calltypes, typingctx, options):
self.func_ir = func_ir
self.typemap = typemap
self.calltypes = calltypes
self.typingctx = typingctx
self.options = options
def run(self):
"""Run pre-parfor processing pass.
"""
# e.g. convert A.sum() to np.sum(A) for easier match and optimization
canonicalize_array_math(self.func_ir, self.typemap,
self.calltypes, self.typingctx)
if self.options.numpy:
self._replace_parallel_functions(self.func_ir.blocks)
self.func_ir.blocks = simplify_CFG(self.func_ir.blocks)
def _replace_parallel_functions(self, blocks):
"""
Replace functions with their parallel implemntation in
replace_functions_map if available.
The implementation code is inlined to enable more optimization.
"""
from numba.inline_closurecall import inline_closure_call
work_list = list(blocks.items())
while work_list:
label, block = work_list.pop()
for i, instr in enumerate(block.body):
if isinstance(instr, ir.Assign):
lhs = instr.target
lhs_typ = self.typemap[lhs.name]
expr = instr.value
if isinstance(expr, ir.Expr) and expr.op == 'call':
# Try inline known calls with their parallel implementations
def replace_func():
func_def = get_definition(self.func_ir, expr.func)
callname = find_callname(self.func_ir, expr)
repl_func = replace_functions_map.get(callname, None)
require(repl_func != None)
typs = tuple(self.typemap[x.name] for x in expr.args)
try:
new_func = repl_func(lhs_typ, *typs)
except:
new_func = None
require(new_func != None)
g = copy.copy(self.func_ir.func_id.func.__globals__)
g['numba'] = numba
g['np'] = numpy
g['math'] = math
# if the function being inlined has a function
# checking the inputs, find it and add it to globals
check = replace_functions_checkers_map.get(callname,
None)
if check is not None:
g[check.name] = check.func
# inline the parallel implementation
inline_closure_call(self.func_ir, g,
block, i, new_func, self.typingctx, typs,
self.typemap, self.calltypes, work_list)
return True
if guard(replace_func):
break
elif (isinstance(expr, ir.Expr) and expr.op == 'getattr' and
expr.attr == 'dtype'):
# Replace getattr call "A.dtype" with numpy.dtype(<actual type>).
# This helps remove superfluous dependencies from parfor.
typ = self.typemap[expr.value.name]
if isinstance(typ, types.npytypes.Array):
# Convert A.dtype to four statements.
# 1) Get numpy global.
# 2) Create var for known type of array, e.g., numpy.float64
# 3) Get dtype function from numpy module.
# 4) Create var for numpy.dtype(var from #2).
# Create var for numpy module.
dtype = typ.dtype
scope = block.scope
loc = instr.loc
g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc)
self.typemap[g_np_var.name] = types.misc.Module(numpy)
g_np = ir.Global('np', numpy, loc)
g_np_assign = ir.Assign(g_np, g_np_var, loc)
# Create var for type infered type of the array, e.g., numpy.float64.
typ_var = ir.Var(scope, mk_unique_var("$np_typ_var"), loc)
self.typemap[typ_var.name] = types.functions.NumberClass(dtype)
dtype_str = str(dtype)
if dtype_str == 'bool':
dtype_str = 'bool_'
np_typ_getattr = ir.Expr.getattr(g_np_var, dtype_str, loc)
typ_var_assign = ir.Assign(np_typ_getattr, typ_var, loc)
# Get the dtype function from the numpy module.
dtype_attr_var = ir.Var(scope, mk_unique_var("$dtype_attr_var"), loc)
temp = find_template(numpy.dtype)
tfunc = numba.types.Function(temp)
tfunc.get_call_type(self.typingctx, (self.typemap[typ_var.name],), {})
self.typemap[dtype_attr_var.name] = types.functions.Function(temp)
dtype_attr_getattr = ir.Expr.getattr(g_np_var, 'dtype', loc)
dtype_attr_assign = ir.Assign(dtype_attr_getattr, dtype_attr_var, loc)
# Call numpy.dtype on the statically coded type two steps above.
dtype_var = ir.Var(scope, mk_unique_var("$dtype_var"), loc)
self.typemap[dtype_var.name] = types.npytypes.DType(dtype)
dtype_getattr = ir.Expr.call(dtype_attr_var, [typ_var], (), loc)
dtype_assign = ir.Assign(dtype_getattr, dtype_var, loc)
self.calltypes[dtype_getattr] = signature(
self.typemap[dtype_var.name], self.typemap[typ_var.name])
# The original A.dtype rhs is replaced with result of this call.
instr.value = dtype_var
# Add statements to body of the code.
block.body.insert(0, dtype_assign)
block.body.insert(0, dtype_attr_assign)
block.body.insert(0, typ_var_assign)
block.body.insert(0, g_np_assign)
break
def find_template(op):
for ft in numba.typing.templates.builtin_registry.functions:
if ft.key == op:
return ft
class ParforPass(object):
"""ParforPass class is responsible for converting Numpy
calls in Numba intermediate representation to Parfors, which
will lower into either sequential or parallel loops during lowering
stage.
"""
def __init__(self, func_ir, typemap, calltypes, return_type, typingctx, options, flags):
self.func_ir = func_ir
self.typemap = typemap
self.calltypes = calltypes
self.typingctx = typingctx
self.return_type = return_type
self.options = options
self.array_analysis = array_analysis.ArrayAnalysis(typingctx, func_ir, typemap,
calltypes)
ir_utils._max_label = max(func_ir.blocks.keys())
self.flags = flags
def run(self):
"""run parfor conversion pass: replace Numpy calls
with Parfors when possible and optimize the IR."""
# run array analysis, a pre-requisite for parfor translation
remove_dels(self.func_ir.blocks)
self.array_analysis.run(self.func_ir.blocks)
# run stencil translation to parfor
if self.options.stencil:
stencil_pass = StencilPass(self.func_ir, self.typemap, self.calltypes,
self.array_analysis, self.typingctx, self.flags)
stencil_pass.run()
if self.options.setitem:
self._convert_setitem(self.func_ir.blocks)
if self.options.numpy:
self._convert_numpy(self.func_ir.blocks)
if self.options.reduction:
self._convert_reduce(self.func_ir.blocks)
if self.options.prange:
self._convert_loop(self.func_ir.blocks)
dprint_func_ir(self.func_ir, "after parfor pass")
# simplify CFG of parfor body loops since nested parfors with extra
# jumps can be created with prange conversion
simplify_parfor_body_CFG(self.func_ir.blocks)
# simplify before fusion
simplify(self.func_ir, self.typemap, self.calltypes)
# need two rounds of copy propagation to enable fusion of long sequences
# of parfors like test_fuse_argmin (some PYTHONHASHSEED values since
# apply_copies_parfor depends on set order for creating dummy assigns)
simplify(self.func_ir, self.typemap, self.calltypes)
if self.options.fusion:
self.func_ir._definitions = build_definitions(self.func_ir.blocks)
self.array_analysis.equiv_sets = dict()
self.array_analysis.run(self.func_ir.blocks)
# reorder statements to maximize fusion
# push non-parfors down
maximize_fusion(self.func_ir, self.func_ir.blocks,
up_direction=False)
dprint_func_ir(self.func_ir, "after maximize fusion down")
self.fuse_parfors(self.array_analysis, self.func_ir.blocks)
# push non-parfors up
maximize_fusion(self.func_ir, self.func_ir.blocks)
dprint_func_ir(self.func_ir, "after maximize fusion up")
# try fuse again after maximize
self.fuse_parfors(self.array_analysis, self.func_ir.blocks)
dprint_func_ir(self.func_ir, "after fusion")
# simplify again
simplify(self.func_ir, self.typemap, self.calltypes)
# push function call variables inside parfors so gufunc function
# wouldn't need function variables as argument
push_call_vars(self.func_ir.blocks, {}, {})
# simplify again
simplify(self.func_ir, self.typemap, self.calltypes)
dprint_func_ir(self.func_ir, "after optimization")
if config.DEBUG_ARRAY_OPT == 1:
print("variable types: ", sorted(self.typemap.items()))
print("call types: ", self.calltypes)
# run post processor again to generate Del nodes
post_proc = postproc.PostProcessor(self.func_ir)
post_proc.run()
if self.func_ir.is_generator:
fix_generator_types(self.func_ir.generator_info, self.return_type,
self.typemap)
if sequential_parfor_lowering:
lower_parfor_sequential(
self.typingctx, self.func_ir, self.typemap, self.calltypes)
else:
# prepare for parallel lowering
# add parfor params to parfors here since lowering is destructive
# changing the IR after this is not allowed
parfor_ids = get_parfor_params(self.func_ir.blocks, self.options.fusion)
if config.DEBUG_ARRAY_OPT_STATS:
name = self.func_ir.func_id.func_qualname
n_parfors = len(parfor_ids)
if n_parfors > 0:
after_fusion = ("After fusion" if self.options.fusion
else "With fusion disabled")
print(('{}, function {} has '
'{} parallel for-loop(s) #{}.').format(
after_fusion, name, n_parfors, parfor_ids))
else:
print('Function {} has no Parfor.'.format(name))
return
def _convert_numpy(self, blocks):
"""
Convert supported Numpy functions, as well as arrayexpr nodes, to
parfor nodes.
"""
topo_order = find_topo_order(blocks)
# variables available in the program so far (used for finding map
# functions in array_expr lowering)
avail_vars = []
for label in topo_order:
block = blocks[label]
new_body = []
equiv_set = self.array_analysis.get_equiv_set(label)
for instr in block.body:
if isinstance(instr, ir.Assign):
expr = instr.value
lhs = instr.target
if self._is_C_order(lhs.name):
# only translate C order since we can't allocate F
if guard(self._is_supported_npycall, expr):
instr = self._numpy_to_parfor(equiv_set, lhs, expr)
if isinstance(instr, tuple):
pre_stmts, instr = instr
new_body.extend(pre_stmts)
elif isinstance(expr, ir.Expr) and expr.op == 'arrayexpr':
instr = self._arrayexpr_to_parfor(
equiv_set, lhs, expr, avail_vars)
avail_vars.append(lhs.name)
new_body.append(instr)
block.body = new_body
def _convert_reduce(self, blocks):
"""
Find reduce() calls and convert them to parfors.
"""
topo_order = find_topo_order(blocks)
for label in topo_order:
block = blocks[label]
new_body = []
equiv_set = self.array_analysis.get_equiv_set(label)
for instr in block.body:
parfor = None
if isinstance(instr, ir.Assign):
loc = instr.loc
lhs = instr.target
expr = instr.value
callname = guard(find_callname, self.func_ir, expr)
if (callname == ('reduce', 'builtins')
or callname == ('reduce', '_functools')):
# reduce function with generic function
parfor = guard(self._reduce_to_parfor, equiv_set, lhs,
expr.args, loc)
if parfor:
instr = parfor
new_body.append(instr)
block.body = new_body
return
def _convert_setitem(self, blocks):
# convert setitem expressions like A[C] = c or A[C] = B[C] to parfor,
# where C is a boolean array.
topo_order = find_topo_order(blocks)
# variables available in the program so far (used for finding map
# functions in array_expr lowering)
avail_vars = []
for label in topo_order:
block = blocks[label]
new_body = []
equiv_set = self.array_analysis.get_equiv_set(label)
for instr in block.body:
if isinstance(instr, ir.StaticSetItem) or isinstance(instr, ir.SetItem):
loc = instr.loc
target = instr.target
index = instr.index if isinstance(instr, ir.SetItem) else instr.index_var
value = instr.value
target_typ = self.typemap[target.name]
index_typ = self.typemap[index.name]
value_typ = self.typemap[value.name]
if isinstance(target_typ, types.npytypes.Array):
if (isinstance(index_typ, types.npytypes.Array) and
isinstance(index_typ.dtype, types.Boolean) and
target_typ.ndim == index_typ.ndim):
if isinstance(value_typ, types.Number):
instr = self._setitem_to_parfor(equiv_set,
loc, target, index, value)
elif isinstance(value_typ, types.npytypes.Array):
val_def = guard(get_definition, self.func_ir,
value.name)
if (isinstance(val_def, ir.Expr) and
val_def.op == 'getitem' and
val_def.index.name == index.name):
instr = self._setitem_to_parfor(equiv_set,
loc, target, index, val_def.value)
else:
shape = equiv_set.get_shape(instr)
if shape != None:
instr = self._setitem_to_parfor(equiv_set,
loc, target, index, value, shape=shape)
new_body.append(instr)
block.body = new_body
def _convert_loop(self, blocks):
call_table, _ = get_call_table(blocks)
cfg = compute_cfg_from_blocks(blocks)
usedefs = compute_use_defs(blocks)
live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap)
loops = cfg.loops()
sized_loops = [(loops[k], len(loops[k].body)) for k in loops.keys()]
moved_blocks = []
# We go over all loops, smaller loops first (inner first)
for loop, s in sorted(sized_loops, key=lambda tup: tup[1]):
if len(loop.entries) != 1 or len(loop.exits) != 1:
continue
entry = list(loop.entries)[0]
for inst in blocks[entry].body:
# if prange or pndindex call
if (isinstance(inst, ir.Assign)
and isinstance(inst.value, ir.Expr)
and inst.value.op == 'call'
and self._is_parallel_loop(inst.value.func.name, call_table)):
body_labels = [ l for l in loop.body if
l in blocks and l != loop.header ]
args = inst.value.args
loop_kind = self._get_loop_kind(inst.value.func.name,
call_table)
# find loop index variable (pair_first in header block)
for stmt in blocks[loop.header].body:
if (isinstance(stmt, ir.Assign)
and isinstance(stmt.value, ir.Expr)
and stmt.value.op == 'pair_first'):
loop_index = stmt.target.name
break
# loop_index may be assigned to other vars
# get header copies to find all of them
cps, _ = get_block_copies({0: blocks[loop.header]},
self.typemap)
cps = cps[0]
loop_index_vars = set(t for t, v in cps if v == loop_index)
loop_index_vars.add(loop_index)
scope = blocks[entry].scope
loc = inst.loc
equiv_set = self.array_analysis.get_equiv_set(loop.header)
init_block = ir.Block(scope, loc)
init_block.body = self._get_prange_init_block(blocks[entry],
call_table, args)
# set l=l for remove dead prange call
inst.value = inst.target
loop_body = {l: blocks[l] for l in body_labels}
# Add an empty block to the end of loop body
end_label = next_label()
loop_body[end_label] = ir.Block(scope, loc)
# Detect races in the prange.
# Races are defs in the parfor body that are live at the exit block.
bodydefs = set()
for bl in body_labels:
bodydefs = bodydefs.union(usedefs.defmap[bl])
exit_lives = set()
for bl in loop.exits:
exit_lives = exit_lives.union(live_map[bl])
races = bodydefs.intersection(exit_lives)
# replace jumps to header block with the end block
for l in body_labels:
last_inst = loop_body[l].body[-1]
if (isinstance(last_inst, ir.Jump) and
last_inst.target == loop.header):
last_inst.target = end_label
def find_indexed_arrays():
"""find expressions that involve getitem using the
index variable. Return both the arrays and expressions.
"""
indices = copy.copy(loop_index_vars)
for block in loop_body.values():
for inst in block.find_insts(ir.Assign):
if (isinstance(inst.value, ir.Var) and
inst.value.name in indices):
indices.add(inst.target.name)
arrs = []
exprs = []
for block in loop_body.values():
for inst in block.body:
lv = set(x.name for x in inst.list_vars())
if lv & indices:
if lv.issubset(indices):
continue
require(isinstance(inst, ir.Assign))