-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
test_mixed_tuple_unroller.py
1978 lines (1620 loc) · 58 KB
/
test_mixed_tuple_unroller.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
from collections import namedtuple
import numpy as np
from numba.tests.support import (TestCase, MemoryLeakMixin,
skip_parfors_unsupported, captured_stdout)
from numba import njit, typed, literal_unroll, prange
from numba.core import types, errors, ir
from numba.testing import unittest
from numba.core.extending import overload
from numba.core.compiler_machinery import (PassManager, register_pass,
FunctionPass, AnalysisPass)
from numba.core.compiler import CompilerBase
from numba.core.untyped_passes import (FixupArgs, TranslateByteCode,
IRProcessing, InlineClosureLikes,
SimplifyCFG, IterLoopCanonicalization,
LiteralUnroll, PreserveIR)
from numba.core.typed_passes import (NopythonTypeInference, IRLegalization,
NoPythonBackend, PartialTypeInference)
from numba.core.ir_utils import (compute_cfg_from_blocks, flatten_labels)
_X_GLOBAL = (10, 11)
class TestLiteralTupleInterpretation(MemoryLeakMixin, TestCase):
def check(self, func, var):
cres = func.overloads[func.signatures[0]]
ty = cres.fndesc.typemap[var]
self.assertTrue(isinstance(ty, types.Tuple))
for subty in ty:
self.assertTrue(isinstance(subty, types.Literal), "non literal")
def test_homogeneous_literal(self):
@njit
def foo():
x = (1, 2, 3)
return x[1]
self.assertEqual(foo(), foo.py_func())
self.check(foo, 'x')
def test_heterogeneous_literal(self):
@njit
def foo():
x = (1, 2, 3, 'a')
return x[3]
self.assertEqual(foo(), foo.py_func())
self.check(foo, 'x')
def test_non_literal(self):
@njit
def foo():
x = (1, 2, 3, 'a', 1j)
return x[4]
self.assertEqual(foo(), foo.py_func())
with self.assertRaises(AssertionError) as e:
self.check(foo, 'x')
self.assertIn("non literal", str(e.exception))
@register_pass(mutates_CFG=False, analysis_only=False)
class ResetTypeInfo(FunctionPass):
_name = "reset_the_type_information"
def __init__(self):
FunctionPass.__init__(self)
def run_pass(self, state):
state.typemap = None
state.return_type = None
state.calltypes = None
return True
class TestLoopCanonicalisation(MemoryLeakMixin, TestCase):
def get_pipeline(use_canonicaliser, use_partial_typing=False):
class NewCompiler(CompilerBase):
def define_pipelines(self):
pm = PassManager("custom_pipeline")
# untyped
pm.add_pass(TranslateByteCode, "analyzing bytecode")
pm.add_pass(IRProcessing, "processing IR")
pm.add_pass(InlineClosureLikes,
"inline calls to locally defined closures")
if use_partial_typing:
pm.add_pass(PartialTypeInference, "do partial typing")
if use_canonicaliser:
pm.add_pass(IterLoopCanonicalization, "Canonicalise loops")
pm.add_pass(SimplifyCFG, "Simplify the CFG")
# typed
if use_partial_typing:
pm.add_pass(ResetTypeInfo, "resets the type info state")
pm.add_pass(NopythonTypeInference, "nopython frontend")
# legalise
pm.add_pass(IRLegalization, "ensure IR is legal")
# preserve
pm.add_pass(PreserveIR, "save IR for later inspection")
# lower
pm.add_pass(NoPythonBackend, "nopython mode backend")
# finalise the contents
pm.finalize()
return [pm]
return NewCompiler
# generate variants
LoopIgnoringCompiler = get_pipeline(False)
LoopCanonicalisingCompiler = get_pipeline(True)
TypedLoopCanonicalisingCompiler = get_pipeline(True, True)
def test_simple_loop_in_depth(self):
""" This heavily checks a simple loop transform """
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo(tup):
acc = 0
for i in tup:
acc += i
return acc
x = (1, 2, 3)
self.assertEqual(foo(x), foo.py_func(x))
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['preserved_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.LoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's three more call types in the canonicalised one:
# len(tuple arg)
# range(of the len() above)
# getitem(tuple arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 3,
len(canonicalise_loops_fndesc.calltypes))
def find_getX(fd, op):
return [x for x in fd.calltypes.keys()
if isinstance(x, ir.Expr) and x.op == op]
il_getiters = find_getX(ignore_loops_fndesc, "getiter")
self.assertEqual(len(il_getiters), 1) # tuple iterator
cl_getiters = find_getX(canonicalise_loops_fndesc, "getiter")
self.assertEqual(len(cl_getiters), 1) # loop range iterator
cl_getitems = find_getX(canonicalise_loops_fndesc, "getitem")
self.assertEqual(len(cl_getitems), 1) # tuple getitem induced by loop
# check the value of the untransformed IR getiter is now the value of
# the transformed getitem
self.assertEqual(il_getiters[0].value.name, cl_getitems[0].value.name)
# check the type of the transformed IR getiter is a range iter
range_inst = canonicalise_loops_fndesc.calltypes[cl_getiters[0]].args[0]
self.assertTrue(isinstance(range_inst, types.RangeType))
def test_transform_scope(self):
""" This checks the transform, when there's no typemap, will happily
transform a loop on something that's not tuple-like
"""
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo():
acc = 0
for i in [1, 2, 3]:
acc += i
return acc
self.assertEqual(foo(), foo.py_func())
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['preserved_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.LoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's three more call types in the canonicalised one:
# len(literal list)
# range(of the len() above)
# getitem(literal list arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 3,
len(canonicalise_loops_fndesc.calltypes))
def find_getX(fd, op):
return [x for x in fd.calltypes.keys()
if isinstance(x, ir.Expr) and x.op == op]
il_getiters = find_getX(ignore_loops_fndesc, "getiter")
self.assertEqual(len(il_getiters), 1) # list iterator
cl_getiters = find_getX(canonicalise_loops_fndesc, "getiter")
self.assertEqual(len(cl_getiters), 1) # loop range iterator
cl_getitems = find_getX(canonicalise_loops_fndesc, "getitem")
self.assertEqual(len(cl_getitems), 1) # list getitem induced by loop
# check the value of the untransformed IR getiter is now the value of
# the transformed getitem
self.assertEqual(il_getiters[0].value.name, cl_getitems[0].value.name)
# check the type of the transformed IR getiter is a range iter
range_inst = canonicalise_loops_fndesc.calltypes[cl_getiters[0]].args[0]
self.assertTrue(isinstance(range_inst, types.RangeType))
@unittest.skip("Waiting for pass to be enabled for all tuples")
def test_influence_of_typed_transform(self):
""" This heavily checks a typed transformation only impacts tuple
induced loops"""
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo(tup):
acc = 0
for i in range(4):
for y in tup:
for j in range(3):
acc += 1
return acc
x = (1, 2, 3)
self.assertEqual(foo(x), foo.py_func(x))
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['func_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.TypedLoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's three more call types in the canonicalised one:
# len(tuple arg)
# range(of the len() above)
# getitem(tuple arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 3,
len(canonicalise_loops_fndesc.calltypes))
def find_getX(fd, op):
return [x for x in fd.calltypes.keys()
if isinstance(x, ir.Expr) and x.op == op]
il_getiters = find_getX(ignore_loops_fndesc, "getiter")
self.assertEqual(len(il_getiters), 3) # 1 * tuple + 2 * loop range
cl_getiters = find_getX(canonicalise_loops_fndesc, "getiter")
self.assertEqual(len(cl_getiters), 3) # 3 * loop range iterator
cl_getitems = find_getX(canonicalise_loops_fndesc, "getitem")
self.assertEqual(len(cl_getitems), 1) # tuple getitem induced by loop
# check the value of the untransformed IR getiter is now the value of
# the transformed getitem
self.assertEqual(il_getiters[1].value.name, cl_getitems[0].value.name)
# check the type of the transformed IR getiter's are all range iter
for x in cl_getiters:
range_inst = canonicalise_loops_fndesc.calltypes[x].args[0]
self.assertTrue(isinstance(range_inst, types.RangeType))
def test_influence_of_typed_transform_literal_unroll(self):
""" This heavily checks a typed transformation only impacts loops with
literal_unroll marker"""
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo(tup):
acc = 0
for i in range(4):
for y in literal_unroll(tup):
for j in range(3):
acc += 1
return acc
x = (1, 2, 3)
self.assertEqual(foo(x), foo.py_func(x))
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['preserved_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.TypedLoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's three more call types in the canonicalised one:
# len(tuple arg)
# range(of the len() above)
# getitem(tuple arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 3,
len(canonicalise_loops_fndesc.calltypes))
def find_getX(fd, op):
return [x for x in fd.calltypes.keys()
if isinstance(x, ir.Expr) and x.op == op]
il_getiters = find_getX(ignore_loops_fndesc, "getiter")
self.assertEqual(len(il_getiters), 3) # 1 * tuple + 2 * loop range
cl_getiters = find_getX(canonicalise_loops_fndesc, "getiter")
self.assertEqual(len(cl_getiters), 3) # 3 * loop range iterator
cl_getitems = find_getX(canonicalise_loops_fndesc, "getitem")
self.assertEqual(len(cl_getitems), 1) # tuple getitem induced by loop
# check the value of the untransformed IR getiter is now the value of
# the transformed getitem
self.assertEqual(il_getiters[1].value.name, cl_getitems[0].value.name)
# check the type of the transformed IR getiter's are all range iter
for x in cl_getiters:
range_inst = canonicalise_loops_fndesc.calltypes[x].args[0]
self.assertTrue(isinstance(range_inst, types.RangeType))
@unittest.skip("Waiting for pass to be enabled for all tuples")
def test_lots_of_loops(self):
""" This heavily checks a simple loop transform """
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo(tup):
acc = 0
for i in tup:
acc += i
for j in tup + (4, 5, 6):
acc += 1 - j
if j > 5:
break
else:
acc -= 2
for i in tup:
acc -= i % 2
return acc
x = (1, 2, 3)
self.assertEqual(foo(x), foo.py_func(x))
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['preserved_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.LoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's three * N more call types in the canonicalised one:
# len(tuple arg)
# range(of the len() above)
# getitem(tuple arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 3 * 3,
len(canonicalise_loops_fndesc.calltypes))
def test_inlined_loops(self):
""" Checks a loop appearing from a closure """
def get_info(pipeline):
@njit(pipeline_class=pipeline)
def foo(tup):
def bar(n):
acc = 0
for i in range(n):
acc += 1
return acc
acc = 0
for i in tup:
acc += i
acc += bar(i)
return acc
x = (1, 2, 3)
self.assertEqual(foo(x), foo.py_func(x))
cres = foo.overloads[foo.signatures[0]]
func_ir = cres.metadata['preserved_ir']
return func_ir, cres.fndesc
ignore_loops_ir, ignore_loops_fndesc = \
get_info(self.LoopIgnoringCompiler)
canonicalise_loops_ir, canonicalise_loops_fndesc = \
get_info(self.LoopCanonicalisingCompiler)
# check CFG is the same
def compare_cfg(a, b):
a_cfg = compute_cfg_from_blocks(flatten_labels(a.blocks))
b_cfg = compute_cfg_from_blocks(flatten_labels(b.blocks))
self.assertEqual(a_cfg, b_cfg)
compare_cfg(ignore_loops_ir, canonicalise_loops_ir)
# check there's 2 * N - 1 more call types in the canonicalised one:
# The -1 comes from the closure being inlined and and the call removed.
# len(tuple arg)
# range(of the len() above)
# getitem(tuple arg, index)
self.assertEqual(len(ignore_loops_fndesc.calltypes) + 5,
len(canonicalise_loops_fndesc.calltypes))
class TestMixedTupleUnroll(MemoryLeakMixin, TestCase):
def test_01(self):
# test a case which is already in loop canonical form
@njit
def foo(idx, z):
a = (12, 12.7, 3j, 4, z, 2 * z)
acc = 0
for i in range(len(literal_unroll(a))):
acc += a[i]
if acc.real < 26:
acc -= 1
else:
break
return acc
f = 9
k = f
self.assertEqual(foo(2, k), foo.py_func(2, k))
def test_02(self):
# same as test_1 but without the explicit loop canonicalisation
@njit
def foo(idx, z):
x = (12, 12.7, 3j, 4, z, 2 * z)
acc = 0
for a in literal_unroll(x):
acc += a
if acc.real < 26:
acc -= 1
else:
break
return acc
f = 9
k = f
self.assertEqual(foo(2, k), foo.py_func(2, k))
def test_03(self):
# two unrolls
@njit
def foo(idx, z):
x = (12, 12.7, 3j, 4, z, 2 * z)
y = ('foo', z, 2 * z)
acc = 0
for a in literal_unroll(x):
acc += a
if acc.real < 26:
acc -= 1
else:
for t in literal_unroll(y):
acc += t is False
break
return acc
f = 9
k = f
self.assertEqual(foo(2, k), foo.py_func(2, k))
def test_04(self):
# mixed ref counted types
@njit
def foo(tup):
acc = 0
for a in literal_unroll(tup):
acc += a.sum()
return acc
n = 10
tup = (np.ones((n,)), np.ones((n, n)), np.ones((n, n, n)))
self.assertEqual(foo(tup), foo.py_func(tup))
def test_05(self):
# mix unroll and static_getitem
@njit
def foo(tup1, tup2):
acc = 0
for a in literal_unroll(tup1):
if a == 'a':
acc += tup2[0].sum()
elif a == 'b':
acc += tup2[1].sum()
elif a == 'c':
acc += tup2[2].sum()
elif a == 12:
acc += tup2[3].sum()
elif a == 3j:
acc += tup2[4].sum()
else:
raise RuntimeError("Unreachable")
return acc
n = 10
tup1 = ('a', 'b', 'c', 12, 3j,)
tup2 = (np.ones((n,)), np.ones((n, n)), np.ones((n, n, n)),
np.ones((n, n, n, n)), np.ones((n, n, n, n, n)))
self.assertEqual(foo(tup1, tup2), foo.py_func(tup1, tup2))
@unittest.skip("needs more clever branch prune")
def test_06(self):
# This wont work because both sides of the branch need typing as neither
# can be pruned by the current pruner
@njit
def foo(tup):
acc = 0
str_buf = typed.List.empty_list(types.unicode_type)
for a in literal_unroll(tup):
if a == 'a':
str_buf.append(a)
else:
acc += a
return acc
tup = ('a', 12)
self.assertEqual(foo(tup), foo.py_func(tup))
def test_07(self):
# A mix bag of stuff as an arg to a function that unifies as `intp`.
@njit
def foo(tup):
acc = 0
for a in literal_unroll(tup):
acc += len(a)
return acc
n = 10
tup = (np.ones((n,)), np.ones((n, n)), "ABCDEFGHJI", (1, 2, 3),
(1, 'foo', 2, 'bar'), {3, 4, 5, 6, 7})
self.assertEqual(foo(tup), foo.py_func(tup))
def test_08(self):
# dispatch to functions
@njit
def foo(tup1, tup2):
acc = 0
for a in literal_unroll(tup1):
if a == 'a':
acc += tup2[0]()
elif a == 'b':
acc += tup2[1]()
elif a == 'c':
acc += tup2[2]()
return acc
def gen(x):
def impl():
return x
return njit(impl)
tup1 = ('a', 'b', 'c', 12, 3j, ('f',))
tup2 = (gen(1), gen(2), gen(3))
self.assertEqual(foo(tup1, tup2), foo.py_func(tup1, tup2))
def test_09(self):
# illegal RHS, has a mixed tuple being index dynamically
@njit
def foo(tup1, tup2):
acc = 0
idx = 0
for a in literal_unroll(tup1):
if a == 'a':
acc += tup2[idx]
elif a == 'b':
acc += tup2[idx]
elif a == 'c':
acc += tup2[idx]
idx += 1
return idx, acc
@njit
def func1():
return 1
@njit
def func2():
return 2
@njit
def func3():
return 3
tup1 = ('a', 'b', 'c')
tup2 = (1j, 1, 2)
with self.assertRaises(errors.TypingError) as raises:
foo(tup1, tup2)
self.assertIn("Invalid use", str(raises.exception))
def test_10(self):
# dispatch on literals triggering @overload resolution
def dt(value):
if value == "apple":
return 1
elif value == "orange":
return 2
elif value == "banana":
return 3
elif value == 0xca11ab1e:
return 0x5ca1ab1e + value
@overload(dt, inline='always')
def ol_dt(li):
if isinstance(li, types.StringLiteral):
value = li.literal_value
if value == "apple":
def impl(li):
return 1
elif value == "orange":
def impl(li):
return 2
elif value == "banana":
def impl(li):
return 3
return impl
elif isinstance(li, types.IntegerLiteral):
value = li.literal_value
if value == 0xca11ab1e:
def impl(li):
# close over the dispatcher :)
return 0x5ca1ab1e + value
return impl
@njit
def foo():
acc = 0
for t in literal_unroll(('apple', 'orange', 'banana', 3390155550)):
acc += dt(t)
return acc
self.assertEqual(foo(), foo.py_func())
def test_11(self):
@njit
def foo():
x = []
z = ('apple', 'orange', 'banana')
for i in range(len(literal_unroll(z))):
t = z[i]
if t == "apple":
x.append("0")
elif t == "orange":
x.append(t)
elif t == "banana":
x.append("2.0")
return x
self.assertEqual(foo(), foo.py_func())
def test_11a(self):
@njit
def foo():
x = typed.List()
z = ('apple', 'orange', 'banana')
for i in range(len(literal_unroll(z))):
t = z[i]
if t == "apple":
x.append("0")
elif t == "orange":
x.append(t)
elif t == "banana":
x.append("2.0")
return x
self.assertEqual(foo(), foo.py_func())
def test_12(self):
# unroll the same target twice
@njit
def foo(idx, z):
a = (12, 12.7, 3j, 4, z, 2 * z)
acc = 0
for i in literal_unroll(a):
acc += i
if acc.real < 26:
acc -= 1
else:
for x in literal_unroll(a):
acc += x
break
if a[0] < 23:
acc += 2
return acc
f = 9
k = f
self.assertEqual(foo(2, k), foo.py_func(2, k))
def test_13(self):
# nesting unrolls is illegal
@njit
def foo(idx, z):
a = (12, 12.7, 3j, 4, z, 2 * z)
acc = 0
for i in literal_unroll(a):
acc += i
if acc.real < 26:
acc -= 1
else:
for x in literal_unroll(a):
for j in literal_unroll(a):
acc += j
acc += x
for x in literal_unroll(a):
acc += x
for x in literal_unroll(a):
acc += x
if a[0] < 23:
acc += 2
return acc
f = 9
k = f
with self.assertRaises(errors.UnsupportedError) as raises:
foo(2, k)
self.assertIn("Nesting of literal_unroll is unsupported",
str(raises.exception))
def test_14(self):
# unituple unroll can return derivative of the induction var
@njit
def foo():
x = (1, 2, 3, 4)
acc = 0
for a in literal_unroll(x):
acc += a
return a
self.assertEqual(foo(), foo.py_func())
def test_15(self):
# mixed tuple unroll cannot return derivative of the induction var
@njit
def foo(x):
acc = 0
for a in literal_unroll(x):
acc += len(a)
return a
n = 5
tup = (np.ones((n,)), np.ones((n, n)), "ABCDEFGHJI", (1, 2, 3),
(1, 'foo', 2, 'bar'), {3, 4, 5, 6, 7})
with self.assertRaises(errors.TypingError) as raises:
foo(tup)
self.assertIn("Cannot unify", str(raises.exception))
def test_16(self):
# unituple slice and unroll is ok
def dt(value):
if value == 1000:
return "a"
elif value == 2000:
return "b"
elif value == 3000:
return "c"
elif value == 4000:
return "d"
@overload(dt, inline='always')
def ol_dt(li):
if isinstance(li, types.IntegerLiteral):
value = li.literal_value
if value == 1000:
def impl(li):
return "a"
elif value == 2000:
def impl(li):
return "b"
elif value == 3000:
def impl(li):
return "c"
elif value == 4000:
def impl(li):
return "d"
return impl
@njit
def foo():
x = (1000, 2000, 3000, 4000)
acc = ""
for a in literal_unroll(x[:2]):
acc += dt(a)
return acc
self.assertEqual(foo(), foo.py_func())
def test_17(self):
# mixed tuple slice and unroll is ok
def dt(value):
if value == 1000:
return "a"
elif value == 2000:
return "b"
elif value == 3000:
return "c"
elif value == 4000:
return "d"
elif value == 'f':
return "EFF"
@overload(dt, inline='always')
def ol_dt(li):
if isinstance(li, types.IntegerLiteral):
value = li.literal_value
if value == 1000:
def impl(li):
return "a"
elif value == 2000:
def impl(li):
return "b"
elif value == 3000:
def impl(li):
return "c"
elif value == 4000:
def impl(li):
return "d"
return impl
elif isinstance(li, types.StringLiteral):
value = li.literal_value
if value == 'f':
def impl(li):
return "EFF"
return impl
@njit
def foo():
x = (1000, 2000, 3000, 'f')
acc = ""
for a in literal_unroll(x[1:]):
acc += dt(a)
return acc
self.assertEqual(foo(), foo.py_func())
def test_18(self):
# unituple backwards slice
@njit
def foo():
x = (1000, 2000, 3000, 4000, 5000, 6000)
count = 0
for a in literal_unroll(x[::-1]):
count += 1
if a < 3000:
break
return count
self.assertEqual(foo(), foo.py_func())
def test_19(self):
# mixed bag of refcounted
@njit
def foo():
acc = 0
l1 = [1, 2, 3, 4]
l2 = [10, 20]
tup = (l1, l2)
a1 = np.arange(20)
a2 = np.ones(5, dtype=np.complex128)
tup = (l1, a1, l2, a2)
for t in literal_unroll(tup):
acc += len(t)
return acc
self.assertEqual(foo(), foo.py_func())
def test_20(self):
# testing partial type inference survives as the list append in the
# unrolled version is full inferable
@njit
def foo():
l = []
a1 = np.arange(20)
a2 = np.ones(5, dtype=np.complex128)
tup = (a1, a2)
for t in literal_unroll(tup):
l.append(t.sum())
return l
self.assertEqual(foo(), foo.py_func())
def test_21(self):
# unroll in closure that gets inlined
@njit
def foo(z):
b = (23, 23.9, 6j, 8)
def bar():
acc = 0
for j in literal_unroll(b):
acc += j
return acc
outer_acc = 0
for x in (1, 2, 3, 4):
outer_acc += bar() + x
return outer_acc
f = 9
k = f
self.assertEqual(foo(k), foo.py_func(k))
def test_22(self):
@njit
def foo(z):
a = (12, 12.7, 3j, 4, z, 2 * z)
b = (23, 23.9, 6j, 8)
def bar():
acc = 0
for j in literal_unroll(b):
acc += j
return acc
acc = 0
# this loop is induced in `x` but `x` is not used, there is a nest
# here by virtue of inlining
for x in literal_unroll(a):
acc += bar()
return acc
f = 9
k = f
self.assertEqual(foo(k), foo.py_func(k))
def test_23(self):