-
Notifications
You must be signed in to change notification settings - Fork 3.5k
/
Copy pathtest_tir_transform_simplify.py
1692 lines (1238 loc) · 51.2 KB
/
test_tir_transform_simplify.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
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import tvm
import tvm.testing
from tvm import te
from tvm.script import tir as T
def test_stmt_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
with ib.for_range(0, n, name="i") as i:
with ib.if_scope(i < 12):
A[i] = C[i]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body, tvm.tir.BufferStore)
def test_thread_extent_simplify():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(tx, "thread_extent", n)
ib.scope_attr(ty, "thread_extent", 1)
with ib.if_scope(tx + ty < 12):
A[tx] = C[tx + ty]
body = tvm.tir.LetStmt(n, 10, ib.get())
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body.body, tvm.tir.BufferStore)
def test_if_likely():
ib = tvm.tir.ir_builder.create()
A = ib.pointer("float32", name="A")
C = ib.pointer("float32", name="C")
n = te.size_var("n")
tx = te.thread_axis("threadIdx.x")
ty = te.thread_axis("threadIdx.y")
ib.scope_attr(tx, "thread_extent", 32)
ib.scope_attr(ty, "thread_extent", 32)
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
with ib.if_scope(ib.likely(tx * 32 + ty < n)):
A[tx] = C[tx * 32 + ty]
body = ib.get()
mod = tvm.IRModule.from_expr(tvm.tir.PrimFunc([A, C, n], body))
body = tvm.tir.transform.Simplify()(mod)["main"].body
assert isinstance(body.body.body, tvm.tir.IfThenElse)
assert not isinstance(body.body.body.then_case, tvm.tir.IfThenElse)
def test_basic_likely_elimination():
n = te.size_var("n")
X = te.placeholder(shape=(n,), name="x")
W = te.placeholder(shape=(n + 1,), dtype="int32", name="w")
def f(i):
start = W[i]
extent = W[i + 1] - W[i]
rv = te.reduce_axis((0, extent))
return te.sum(X[rv + start], axis=rv)
Y = te.compute(X.shape, f, name="y")
s = te.create_schedule([Y.op])
stmt = tvm.lower(s, [X, W, Y], simple_mode=True)
assert "if" not in str(stmt)
def test_complex_likely_elimination():
def cumsum(X):
"""
Y[i] = sum(X[:i])
"""
(m,) = X.shape
s_state = te.placeholder((m + 1,), dtype="int32", name="state")
s_init = te.compute((1,), lambda _: tvm.tir.const(0, "int32"))
s_update = te.compute((m + 1,), lambda l: s_state[l - 1] + X[l - 1])
return tvm.te.scan(s_init, s_update, s_state, inputs=[X], name="cumsum")
def sparse_lengths_sum(data, indices, lengths):
oshape = list(data.shape)
oshape[0] = lengths.shape[0]
length_offsets = cumsum(lengths)
def sls(n, d):
gg = te.reduce_axis((0, lengths[n]))
indices_idx = length_offsets[n] + gg
data_idx = indices[indices_idx]
data_val = data[data_idx, d]
return te.sum(data_val, axis=gg)
return te.compute(oshape, sls)
m, n, d, i, l = (
te.size_var("m"),
te.size_var("n"),
te.size_var("d"),
te.size_var("i"),
te.size_var("l"),
)
data_ph = te.placeholder((m, d * 32), name="data")
indices_ph = te.placeholder((i,), name="indices", dtype="int32")
lengths_ph = te.placeholder((n,), name="lengths", dtype="int32")
Y = sparse_lengths_sum(data_ph, indices_ph, lengths_ph)
s = te.create_schedule([Y.op])
(n, d) = s[Y].op.axis
(do, di) = s[Y].split(d, factor=32)
(gg,) = s[Y].op.reduce_axis
s[Y].reorder(n, do, gg, di)
s[Y].vectorize(di)
stmt = tvm.lower(s, [data_ph, indices_ph, lengths_ph, Y], simple_mode=True)
assert "if" not in str(stmt)
class BaseBeforeAfter(tvm.testing.CompareBeforeAfter):
transitively_prove_inequalities = False
convert_boolean_to_and_of_ors = False
apply_constraints_to_boolean_branches = False
propagate_knowns_to_prove_conditional = False
propagate_knowns_to_simplify_expressions = False
def transform(self):
def inner(mod):
config = {
"tir.Simplify": {
"transitively_prove_inequalities": self.transitively_prove_inequalities,
"convert_boolean_to_and_of_ors": self.convert_boolean_to_and_of_ors,
"apply_constraints_to_boolean_branches": self.apply_constraints_to_boolean_branches,
"propagate_knowns_to_prove_conditional": self.propagate_knowns_to_prove_conditional,
"propagate_knowns_to_simplify_expressions": self.propagate_knowns_to_simplify_expressions,
}
}
with tvm.transform.PassContext(config=config):
mod = tvm.tir.transform.Simplify()(mod)
return mod
return inner
class TestLoadStoreNoop(BaseBeforeAfter):
"""Store of a value that was just read from the same location is a no-op."""
def before(A: T.Buffer[(1,), "float32"]):
A[0] = A[0]
def expected(A: T.Buffer[(1,), "float32"]):
T.evaluate(0)
class TestLoadStoreNoopAfterSimplify(BaseBeforeAfter):
"""As test_load_store_noop, but requiring simplification to identify.
Previously, a bug caused the self-assignment of a buffer to
checked based on the pre-simplification assignment, not the
post-simplification. This test is to identify any similar
regression.
"""
def before(A: T.Buffer[(1,), "float32"]):
A[0] = A[0] + (5.0 - 5.0)
def expected(A: T.Buffer[(1,), "float32"]):
T.evaluate(0)
class TestNestedCondition(BaseBeforeAfter):
"""Nested IfThenElse with the same condition can be simplified.
Requires const_int_bound to narrow scope of i within the
conditional, or for rewrite_simplify to recognize the literal
constraint.
"""
def before(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
if i == 5:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
A[i] = 0.0
class TestNestedProvableCondition(BaseBeforeAfter):
"""Simplify inner conditional using constraint from outer.
Requires const_int_bound to narrow scope of i within the
conditional.
"""
def before(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
if i < 7:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"]):
for i in T.serial(16):
if i == 5:
A[i] = 0.0
class TestNestedVarCondition(BaseBeforeAfter):
"""Simplify inner conditional using constraint from outer.
Requires for rewrite_simplify to recognize the repeated
constraint.
"""
def before(A: T.Buffer[(16,), "float32"], n: T.int32):
for i in T.serial(16):
if i == n:
if i == n:
A[i] = 0.0
def expected(A: T.Buffer[(16,), "float32"], n: T.int32):
for i in T.serial(16):
if i == n:
A[i] = 0.0
class TestAlteredBufferContents(BaseBeforeAfter):
"""No simplification of data-dependent conditionals.
A literal constraint must not be propagated if the values
referenced may change. TIR requires single assignment of
variables, so Var objects may be assumed constant, but BufferLoad
may not.
"""
def before(A: T.Buffer[(1,), "int32"], n: T.int32):
if A[0] == n:
A[0] = A[0] + 1
if A[0] == n:
A[0] = 0
expected = before
class TestNegationOfCondition(BaseBeforeAfter):
"""Use negation of outer condition to simplify innner.
Within the body of an if statement, the negation of the
condition is known to be false.
"""
def before(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i == 5:
if i != 5:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i == 5:
A[i] = 1
class TestNegationOfNotEqual(BaseBeforeAfter):
"""As TestNegationOfVarCondition, but with a != outer condition.
Because ConstIntBoundAnalyzer only tracks the min and max allowed
values, the outer i!=5 condition does provide a constraint on the
bounds. This test relies on RewriteSimplifier to recognize
``i==5`` as the negation of a literal constraint.
"""
def before(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i != 5:
if i == 5:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"]):
for i in T.serial(16):
if i != 5:
A[i] = 1
class TestNegationOfVarCondition(BaseBeforeAfter):
"""As TestNegationOfVarCondition, but with a dynamic condition.
This simplification cannot be done with ConstIntBoundAnalyzer, and
must rely on RewriteSimplifier recognizing the repeated literal.
"""
def before(A: T.Buffer[(16,), "int32"], n: T.int32):
for i in T.serial(16):
if i == n:
if i != n:
A[i] = 0
else:
A[i] = 1
def expected(A: T.Buffer[(16,), "int32"], n: T.int32):
for i in T.serial(16):
if i == n:
A[i] = 1
class TestLiteralConstraintSplitBooleanAnd(BaseBeforeAfter):
"""Split a boolean AND into independent constraints
A single if condition may impose multiple literal constraints.
Each constraint that is ANDed together to form the condition
should be treated as an independent constraint. The use of n in
the condition is to ensure we exercise RewriteSimplifier.
"""
def before(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n and j == n:
if i == n:
A[i, j] = 0
def expected(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n and j == n:
A[i, j] = 0
class TestLiteralConstraintSplitBooleanOr(BaseBeforeAfter):
"""Split a boolean OR into independent constraints
Similar to TestLiteralConstraintSplitBooleanAnd, but splitting a
boolean OR into independent conditions. This uses the
simplification that ``!(x || y) == !x && !y``.
The use of ``n`` in the condition is to ensure we exercise
RewriteSimplifier.
"""
def before(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n or j == n:
A[i, j] = 0
else:
if i == n:
A[i, j] = 1
else:
A[i, j] = 2
def expected(A: T.Buffer[(16, 16), "int32"], n: T.int32):
for i, j in T.grid(16, 16):
if i == n or j == n:
A[i, j] = 0
else:
A[i, j] = 2
class TestProveConditionUsingLet(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
Not all let bindings are inlined when they occur in later
expressions. However, even if they are not inlined, they may be
used to prove the value of a condition.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition or i >= 3:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
A[i] = condition
class TestProveLetCondition(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
Not all let bindings are inlined when they occur in later
expressions. However, even if they are not inlined, they may be
used to prove the value of a condition.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if i < 3:
if condition:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if i < 3:
A[i] = condition
class TestProveRepeatedLetCondition(BaseBeforeAfter):
"""Simplify conditions using non-inlined let bindings
A variable may be used as a literal constraint, and be recognized
as being True within the context of the constraint.
"""
@T.prim_func
def before(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition:
if condition:
A[i] = condition
@T.prim_func
def expected(A: T.Buffer[4, "bool"]):
for i in T.serial(4):
condition = i < 3
if condition:
A[i] = True
class TestIfThenElseExpr(BaseBeforeAfter):
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if i < 12:
A[i] = T.if_then_else(i < 12, 1.0, 2.0, dtype="float32")
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if i < 12:
A[i] = 1.0
class TestCeilLog2Int(BaseBeforeAfter):
"""Simplify expressions resulting from topi.math.ceil_log2"""
@T.prim_func
def before(A: T.Buffer[1, "int32"]):
A[0] = T.cast(
T.ceil(T.log2(T.cast(14, "float64"), dtype="float64"), dtype="float64"), dtype="int32"
)
@T.prim_func
def expected(A: T.Buffer[1, "int32"]):
A[0] = 4
class TestLeftCeilLog2LowerBound(BaseBeforeAfter):
"""Integer bounds are propagated through topi.math.ceil_log2"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
x = T.cast(
T.ceil(T.log2(T.cast(i + 1024 + 1, "float64"), dtype="float64"), dtype="float64"),
dtype="int32",
)
if x == 11:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0
class TestLeftShiftLowerBound(BaseBeforeAfter):
"""Integer bounds are propagated through left shift
min(1 << i) = 1 << min(i)
= 1 << 0
= 1
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(1, i, dtype="int32") >= 1:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0
class TestLeftShiftUpperBound(BaseBeforeAfter):
"""Integer bounds are propagated through left shift
max(31 << i) = 31 << max(i)
= 31 << 15
= 1015808
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(31, i, dtype="int32") <= 1015808:
A[i] = 0.0
@T.prim_func
def expected(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
A[i] = 0.0
class TestLeftShiftOfNegativeValue(BaseBeforeAfter):
"""No const int bounds of left shift of negative value.
This is target dependent, and does not currently have a specified
behavior in TIR. For example, in CodeGenC, this generates C code
with undefined behavior.
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if -64 <= T.shift_left(-i, 4, dtype="int32"):
A[i] = 0.0
expected = before
class TestLeftShiftByNegativeValue(BaseBeforeAfter):
"""No const int bounds of left shift by negative bit count.
This is target dependent, and does not currently have a specified
behavior in TIR. For example, in CodeGenC, this generates C code
with undefined behavior.
"""
@T.prim_func
def before(A: T.Buffer[16, "float32"]):
for i in T.serial(16):
if T.shift_left(16, -i, dtype="int32") <= 16:
A[i] = 0.0
expected = before
class TestRemoveTransitivelyProvableCondition(BaseBeforeAfter):
"""Remove comparisons that may be proven using multiple others
For example, the `0 < i` and `i <= j` conditions can be used to prove
that `0 < j`.
"""
transitively_prove_inequalities = True
i, j, k = [tvm.tir.Var(name, "int32") for name in "ijk"]
zero = tvm.tir.IntImm("int32", 0)
test_case = tvm.testing.parameter(
(tvm.tir.all(zero < i, i <= j), zero < j, True),
# Transitive comparisons from LT
(tvm.tir.all(i < j, j < k), i < k, True),
(tvm.tir.all(i < j, j == k), i < k, True),
(tvm.tir.all(i < j, j <= k), i < k, True),
(tvm.tir.all(i < j, j > k), i < k, False),
(tvm.tir.all(i < j, j >= k), i < k, False),
(tvm.tir.all(i < j, j != k), i < k, False),
# Transitive comparisons from LE
(tvm.tir.all(i <= j, j < k), i < k, True),
(tvm.tir.all(i <= j, j == k), i == k, False),
(tvm.tir.all(i <= j, j == k), i <= k, True),
(tvm.tir.all(i <= j, j <= k), i <= k, True),
(tvm.tir.all(i <= j, j <= k), i < k, False),
(tvm.tir.all(i <= j, j > k), i < k, False),
(tvm.tir.all(i <= j, j >= k), i < k, False),
(tvm.tir.all(i <= j, j != k), i < k, False),
# Transitive comparisons from GT
(tvm.tir.all(i > j, j > k), i > k, True),
(tvm.tir.all(i > j, j == k), i > k, True),
(tvm.tir.all(i > j, j >= k), i > k, True),
(tvm.tir.all(i > j, j < k), i > k, False),
(tvm.tir.all(i > j, j <= k), i > k, False),
(tvm.tir.all(i > j, j != k), i > k, False),
# Transitive comparisons from GE
(tvm.tir.all(i >= j, j > k), i > k, True),
(tvm.tir.all(i >= j, j == k), i == k, False),
(tvm.tir.all(i >= j, j == k), i >= k, True),
(tvm.tir.all(i >= j, j >= k), i >= k, True),
(tvm.tir.all(i >= j, j >= k), i > k, False),
(tvm.tir.all(i >= j, j < k), i > k, False),
(tvm.tir.all(i >= j, j <= k), i > k, False),
(tvm.tir.all(i >= j, j != k), i > k, False),
# GT or LT may be used to prove NE
(tvm.tir.all(i == j, j != k), i != k, True),
(tvm.tir.all(i == j, j < k), i != k, True),
(tvm.tir.all(i == j, j > k), i != k, True),
(tvm.tir.all(i == j, j != k), i < k, False),
(tvm.tir.all(i == j, j != k), i > k, False),
# Because these are integers, x<y is equivalent to x <= y-1,
# and may be used in equivalent simplifications.
(tvm.tir.all(i <= j - 1, j < k), i < k, True),
(tvm.tir.all(i <= j - 1, j == k), i < k, True),
(tvm.tir.all(i <= j - 1, j <= k), i < k, True),
(tvm.tir.all(i <= j - 1, j > k), i < k, False),
(tvm.tir.all(i <= j - 1, j >= k), i < k, False),
(tvm.tir.all(i <= j - 1, j != k), i < k, False),
# Either or both inequalities may have an additive offset.
(tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 12, True),
(tvm.tir.all(i <= j + 5, j <= k + 7), i <= k + 11, False),
# For floats, x < y + c1 and y < z + c2 implies that x < z + (c1 + c2).
# Because this simplification applies to integers, transitive
# application of LT or GT can give a tighter constraint.
#
# i < j + c1, j < k + c2
# i <= j + c1 - 1, j <= k + c2 - 1
# i + 1 - c1 <= j, j <= k + c2 - 1
# i + 1 - c1 <= k + c2 - 1
# i <= k + c1 + c2 - 2
# i < k + (c1 + c2 - 1)
#
(tvm.tir.all(i < j + 5, j < k + 7), i < k + 11, True),
(tvm.tir.all(i < j + 5, j < k + 7), i < k + 10, False),
)
@tvm.testing.fixture
def before(self, test_case):
priors, postulate, _ = test_case
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = postulate
return func
@tvm.testing.fixture
def expected(self, test_case):
priors, postulate, provable = test_case
analyzer = tvm.arith.Analyzer()
priors = analyzer.canonical_simplify(priors)
if provable:
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = True
return func
else:
postulate = analyzer.canonical_simplify(postulate)
@T.prim_func
def func(A: T.Buffer[1, "bool"]):
if priors:
A[0] = postulate
return func
class TestSuppressTransitivelyProvableCondition(BaseBeforeAfter):
transitively_prove_inequalities = False
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
if i < j and j < k:
A[0] = i < k
expected = before
class TestRewriteAsAndOfOrs(BaseBeforeAfter):
"""If enabled, rewrite boolean expressions into AND of OR"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[3, "bool"]):
T.evaluate(A[0] or (A[1] and A[2]))
def expected(A: T.Buffer[3, "bool"]):
T.evaluate((A[0] or A[1]) and (A[0] or A[2]))
class TestSuppressRewriteAsAndOfOrs(BaseBeforeAfter):
"""Only rewrite into AND of OR when allowed"""
convert_boolean_to_and_of_ors = False
def before(A: T.Buffer[3, "bool"]):
T.evaluate(A[0] or (A[1] and A[2]))
expected = before
class TestRewriteAsAndOfOrsWithTopLevelAnd(BaseBeforeAfter):
"""The expression being rewritten may start with an AND
Like TestRewriteAsAndOfOrs, but with an AndNode as the outermost
booelan operator. Even though it is primarily OR nodes that are
being rewritten, the call to SimplifyAsAndOfOrs should apply to
the outermost AndNode or OrNode in order to enable better
simplification.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[4, "bool"]):
T.evaluate((A[0] or A[1]) and (A[1] or (A[0] and A[2] and A[3])))
def expected(A: T.Buffer[4, "bool"]):
# If the simplification is applied to the OrNode, then a
# redundant `(A[1] or A[0])` would't be canceled out. When
# applying SimplifyAsAndOfOrs to the top-level AndNode, the
# internal representation is `[[0,1], [1,0], [1,2], [1,3]]`, and
# the redundant `[1,0]` can be removed.
#
# If the simplification were only applied when encountering an
# OrNode, the internal representation would be `[[0,1]]` during
# the first call and `[[1,0], [1,2], [1,3]]` during the second
# call. As a result, the `[0,1]` and `[1,0]` representations
# wouldn't occur within the same call, and the redundant `[1,0]`
# wouldn't be removed.
T.evaluate((A[0] or A[1]) and (A[1] or A[2]) and (A[1] or A[3]))
class TestRewriteAsAndOfOrsWithSimplificationBetweenGroups(BaseBeforeAfter):
"""Apply rewrite rules between OR groups that differ by a single element
The expression `(k==20 and k!=30)` could be rewritten into `(k==20)`.
However, by default these two terms must appear as part of an explict part
of the simplified expression. The AndOfOr simplification checks for
rewrite patterns of the form `(A or B) and (A or C)`, where `(B and C)` can
simplify to a single expression `D`. These can be rewritten to `(A or D)`.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 0 or j == 10 or k == 20) and (i == 0 or j == 10 or k != 30)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = i == 0 or j == 10 or k == 20
class TestRewriteAsAndOfOrsWithSimplificationBetweenReorderedGroups(BaseBeforeAfter):
"""Rewrite rules between OR groups do not depend on order
Like TestRewriteAsAndOfOrsWithSimplificationBetweenGroups, but the groups
are ordered differently. If this removes a group entirely, the result is
ordered according to the first group in the expression.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 0 or j == 10 or k == 20) and (j == 10 or k != 30 or i == 0)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = j == 10 or k == 20 or i == 0
class TestRewriteAsAndOfOrUsingSimplificationAcrossAnd(BaseBeforeAfter):
"""Apply AndNode rewrites to non-adjacent expressions
The RewriteSimplifier rules only check for simplifications between
left/right branches of an And/Or node. Simplifications that would require
rearranging components in a chain of And/Or nodes are not performed.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (k == 20) and ((i == 0 or j == 10) and (k != 30))
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 0 or j == 10) and (k == 20)
class TestRewriteAsAndOfOrUsingSimplificationWithinOr(BaseBeforeAfter):
"""Rewrite rules between OR groups do not depend on order
The RewriteSimplifier rules only check for simplifications between
left/right branches of an And/Or node. Simplifications that would require
rearranging components in a chain of And/Or nodes are not performed.
This test validates that `(i == 20) or (i != 30)` can be rewritten to
`(i != 30)`, even when there's an intervening clause between the
clauses being simplified.
"""
convert_boolean_to_and_of_ors = True
def before(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (i == 20) or (j == 0) or (i != 30)
def expected(A: T.Buffer[1, "bool"], i: T.int32, j: T.int32, k: T.int32):
A[0] = (j == 0) or (i != 30)
class TestConditionalFloorMod(BaseBeforeAfter):
"""A regression test for negative floormod denominator
Previously, simplifying this function could throw an error. First, the
`canonical_simplify` would rewrite `floormod(0-i,2)` to the equivalent
`floormod(i,-2)`. Then, the rewrite_simplifier would enter a
constrained context in which `floormod(i,-2)==1`. Passing this
expression to `ModularSet::EnterConstraint`, which previously did not
support a negative value for the second argument, threw an error.
The analogous failure mode never occurred for `truncmod`, because
`truncmod(0-i,2)` would be canonicalized to `truncmod(i, -2) * -1`, and
the pattern matching in `ModularSet` didn't recognize the constant
factor.
This failure mode was resolved by supporting negative arguments in
`ModularSet`, using the same sign convention as is used by
`canonical_simplify`.
"""
def before(A: T.Buffer[1, "bool"], i: T.int32):
if T.floormod(0 - i, 2) == 0:
A[0] = T.floormod(i, 2) == 0
def expected(A: T.Buffer[1, "bool"], i: T.int32):
if T.floormod(i, -2) == 0:
A[0] = True
class TestSimplifyRHSOfBooleanAndUsingLHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
In `A and B`, the result of `B` only matters when `A` is
true, and can be simplified under that context. This test
simplifies `n < 10` under the assumption that `n < 5`.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 and n < 10
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5
class TestSimplifyLHSOfBooleanAndUsingRHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyRHSOfBooleanAndUsingLHS, but using the RHS to
simplify the LHS.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 and n < 5
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5
class TestSimplifyRHSOfBooleanOrUsingLHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
In `A or B`, the result of `B` only matters when `A` is false, so
`B` can be simplified under the assumption that `A` is false.
This test simplifies `n < 5` under the assumption that `!(n < 10)`
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10 or n < 5
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10
class TestSimplifyLHSOfBooleanOrUsingRHS(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyRHSOfBooleanOrUsingLHS, but using the RHS to
simplify the LHS.
"""
apply_constraints_to_boolean_branches = True
def before(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 5 or n < 10
def expected(A: T.Buffer[1, "bool"], n: T.int32):
A[0] = n < 10
class TestSimplifyRHSOfBooleanAndUsingLHSWithoutConst(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
Like TestSimplifyRHSOfBooleanAndUsingLHS, but with variables in
the conditions, preventing ConstIntBoundAnalyzer from handling it.
This proof requires the extension to transitively prove
inequalities.
"""
apply_constraints_to_boolean_branches = True
transitively_prove_inequalities = True
def before(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 5 and n < m + 10
def expected(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 5
class TestSimplifyLHSOfBooleanAndUsingRHSWithoutConst(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyLHSOfBooleanAndUsingRHS, but with variables in
the conditions, preventing ConstIntBoundAnalyzer from handling it.
This proof requires the extension to transitively prove
inequalities.
"""
apply_constraints_to_boolean_branches = True
transitively_prove_inequalities = True
def before(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 10 and n < m + 5
def expected(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 5
class TestSimplifyRHSOfBooleanOrUsingLHSWithoutConst(BaseBeforeAfter):
"""Boolean expressions can introduce contexts.
Like TestSimplifyRHSOfBooleanOrUsingLHS, but with variables in the
conditions, preventing ConstIntBoundAnalyzer from handling it.
This proof requires the extension to transitively prove
inequalities.
"""
apply_constraints_to_boolean_branches = True
transitively_prove_inequalities = True
def before(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 10 or n < m + 5
def expected(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 10
class TestSimplifyLHSOfBooleanOrUsingRHSWithoutConst(BaseBeforeAfter):
"""Boolean expressions can introduce contexts for their arguments.
Like TestSimplifyLHSOfBooleanOrUsingRHS, but with variables in the
conditions, preventing ConstIntBoundAnalyzer from handling it.
This proof requires the extension to transitively prove
inequalities.
"""
apply_constraints_to_boolean_branches = True
transitively_prove_inequalities = True
def before(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 5 or n < m + 10
def expected(A: T.Buffer[1, "bool"], n: T.int32, m: T.int32):
A[0] = n < m + 10
class TestProvableConditionWithOffset(BaseBeforeAfter):
"""Use scoped-constraint to prove inequalities"""
transitively_prove_inequalities = False