-
Notifications
You must be signed in to change notification settings - Fork 10
/
rewrites.rs
4865 lines (4509 loc) · 164 KB
/
rewrites.rs
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
use super::{Language, MyAnalysis, MyAnalysisData, PadType, RangeSet2};
use egg::{rewrite, Applier, ConditionalApplier, EGraph, Id, Pattern, Rewrite, Subst, Var};
use ndarray::Dimension;
use ndarray::IxDyn;
type EG = EGraph<Language, MyAnalysis>;
type RW = Rewrite<Language, MyAnalysis>;
fn constrain_vars(
vars: Vec<Var>,
constraint: impl Fn(Vec<MyAnalysisData>) -> bool,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _, subst| {
constraint(
vars.iter()
.map(|var| &egraph[subst[*var]].data)
.cloned()
.collect::<Vec<_>>(),
)
}
}
fn constrain_access(
access: Var,
constraint: impl Fn(&super::language::AccessPatternData) -> bool,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _, subst| match &egraph[subst[access]].data {
MyAnalysisData::AccessPattern(a) => constraint(a),
_ => false,
}
}
fn access_has_axis(axis: usize) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, id, _subst| match &egraph[id].data {
MyAnalysisData::AccessPattern(a) => axis < a.shape.ndim() + a.item_shape.ndim(),
_ => panic!(),
}
}
fn is_access() -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, id, _| match &egraph[id].data {
MyAnalysisData::AccessPattern(_) => true,
_ => false,
}
}
/// True if a list is equal to 0..len(list)
fn list_is_0_through_len(list: Var) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _id, subst| {
let list = match &egraph[subst[list]].data {
MyAnalysisData::List(l) => l,
_ => panic!(),
};
*list == (0..list.len()).collect::<Vec<_>>()
}
}
fn same_item_axis(
axis0: Var,
access0: Var,
axis1: Var,
access1: Var,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _id, subst| {
let (a0, a1) = match (&egraph[subst[access0]].data, &egraph[subst[access1]].data) {
(MyAnalysisData::AccessPattern(a0), MyAnalysisData::AccessPattern(a1)) => (a0, a1),
_ => panic!(),
};
let axis0 = MyAnalysis::get_usize(subst[axis0], egraph);
let axis1 = MyAnalysis::get_usize(subst[axis1], egraph);
axis0 >= a0.shape.ndim()
&& axis1 >= a1.shape.ndim()
&& axis0 - a0.shape.ndim() == axis1 - a1.shape.ndim()
}
}
fn not_item_axis(axis: Var, access: Var) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _id, subst| match &egraph[subst[access]].data {
MyAnalysisData::AccessPattern(a) => {
MyAnalysis::get_usize(subst[axis], egraph) < a.shape.ndim()
}
_ => panic!(),
}
}
fn item_axis(axis: Var, access: Var) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _id, subst| match &egraph[subst[access]].data {
MyAnalysisData::AccessPattern(a) => {
MyAnalysis::get_usize(subst[axis], egraph) >= a.shape.ndim()
}
_ => panic!(),
}
}
// TODO(@gussmith23) I think I should make this a conditional applier, and fold in
// checks to make sure it has a shape and that it's an input
pub fn has_shape(var: &'static str) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
move |egraph, _, subst| match &egraph[subst[var]].data {
MyAnalysisData::Legacy(s) => !s.shape.is_none(),
_ => panic!(),
}
}
/// short_circuit lets us return early if we don't actually care about the
/// result of this check. This is the easiest way I could find to do this using
/// egg's conditional appliers.
/// TODO(@gussmith23) make this cleaner
pub fn is_symbol(
short_circuit: bool,
var: &'static str,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
// TODO(@gussmith23) should this be `all` or `any` or something else entirely?
move |egraph, _, subst| {
if short_circuit {
true
} else {
egraph[subst[var]]
.nodes
.iter()
.map(|enode| match enode {
Language::Symbol(_) => true,
_ => false,
})
.all(|x| x)
}
}
}
fn has_axis(var: &'static str, axis: usize) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
move |egraph, _, subst| axis < MyAnalysis::get_shape(subst[var], egraph).ndim()
}
fn dimension_greater_than(
var: &'static str,
axis: usize,
greater_than: usize,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
move |egraph, _, subst| MyAnalysis::get_shape(subst[var], egraph)[axis] > greater_than
}
fn dimension_is_even(
var: &'static str,
axis: usize,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
move |egraph, _, subst| MyAnalysis::get_shape(subst[var], egraph)[axis] % 2 == 0
}
// TODO(@gussmith23) not sure all this should be public.
pub struct RewriteNonMatchingCartConcatenateApplier {
pub a1: egg::Var,
pub a2: egg::Var,
pub a_axis: usize,
pub b1: egg::Var,
pub b2: egg::Var,
pub b_axis: usize,
}
impl egg::Applier<Language, MyAnalysis> for RewriteNonMatchingCartConcatenateApplier {
fn apply_one(
&self,
_egraph: &mut EG,
_id: egg::Id,
_subst: &egg::Subst,
) -> std::vec::Vec<egg::Id> {
// For now, just want to handle these cases.
assert!(self.a_axis == 0 || self.a_axis == 1);
assert!(self.b_axis == 0 || self.b_axis == 1);
assert_ne!(self.a_axis, self.b_axis);
// We will break up the as into smaller chunks and the bs into
// smaller chunks, so that they all match in size.
// The goal is to have the innermost concatenates be along axis 0, and
// the outermost concatenates to be along axis 1. Additionally, the goal
// is that the result should only involve cartesian products of
// concatenates, where the left and right concatenate use the same axis.
// Then, existing rewrites can be used to bubble the concatenates up
// through the cartesian products.
// Each a needs to be split into 4; each b needs to be split into 4.
// First we want to construct all of the concatenates along the 1 axis.
// These will become our innermost concatenates.
// One of these is already concatenateted along the 1 axis!
// TODO(@gussmith23) left off here, I think I should actually do something
// simpler here and just rewrite the two concatenates that are the
// children of this cartesian product.
// It needs some information from elsewhere in the graph, though,
// that's the tough thing.
// So we're going to slice-and-concatenate all 4 tensors. We'll slice the
// as based on the bs size, and slice the bs based on the as size.
// TODO(@gussmith23) I could write an even simpler rewrite rule that slices
// more indiscriminately, everywhere. Right now I'm using some
// context clue (the overarching cartesian product) to only apply
// this where needed.
// All I actually want to do is to rewrite that second concatenate.
// (cartesian-product
// (concatenate ?a1 ?a2 0)
// (concatenate ?b1 ?b2 1)
// )
// (cartesian-product
// (concatenate ?a1 ?a2 0)
// (concatenate (concatenate (slice ?b1) (slice ?b1) 0)
// )
//
vec![]
}
}
struct SplitApplier {
axis: usize,
}
impl egg::Applier<Language, MyAnalysis> for SplitApplier {
fn apply_one(
&self,
egraph: &mut EG,
id: egg::Id,
_subst: &egg::Subst,
) -> std::vec::Vec<egg::Id> {
let shape: ndarray::IxDyn = MyAnalysis::get_shape(id, egraph).clone();
assert_eq!(shape[self.axis] % 2, 0);
let low_bound = 0;
let low_bound_id = egraph.add(Language::Usize(low_bound));
let high_bound = shape[self.axis];
let high_bound_id = egraph.add(Language::Usize(high_bound));
let middle_bound = high_bound / 2;
let middle_bound_id = egraph.add(Language::Usize(middle_bound));
let axis_id = egraph.add(Language::Usize(self.axis));
let slice_0_id = egraph.add(Language::Slice([
id,
axis_id,
low_bound_id,
middle_bound_id,
]));
let slice_1_id = egraph.add(Language::Slice([
id,
axis_id,
middle_bound_id,
high_bound_id,
]));
let id: egg::Id = egraph.add(Language::Concatenate([slice_0_id, slice_1_id, axis_id]));
vec![id]
}
}
pub fn split(
axis: usize,
dimension_greater_than: usize,
split_all_nodes: bool,
) -> Rewrite<Language, MyAnalysis> {
rewrite!(format!("split-axis-{}", axis); "?a" =>
{SplitApplier{axis: axis}}
if is_symbol(split_all_nodes, "?a")
if has_shape("?a")
if has_axis("?a", axis)
if dimension_is_even("?a", axis)
if self::dimension_greater_than("?a", axis, dimension_greater_than))
}
pub fn collapse_nested_slices() -> Rewrite<Language, MyAnalysis> {
struct CollapseNestedSlicesApplier {
low0: Var,
high0: Var,
low1: Var,
high1: Var,
}
impl Applier<Language, MyAnalysis> for CollapseNestedSlicesApplier {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let low0: usize = MyAnalysis::get_usize(subst[self.low0], egraph);
let high0: usize = MyAnalysis::get_usize(subst[self.high0], egraph);
let low1: usize = MyAnalysis::get_usize(subst[self.low1], egraph);
let high1: usize = MyAnalysis::get_usize(subst[self.high1], egraph);
let new_low: usize = low0 + low1;
assert!(high1 - low1 <= high0 - low0);
let new_high: usize = new_low + (high1 - low1);
format!("(slice ?t ?axis {} {})", new_low, new_high)
.parse::<Pattern<Language>>()
.unwrap()
.apply_one(egraph, eclass, subst)
}
}
rewrite!("collapse-nested-slices";
"(slice (slice ?t ?axis ?low0 ?high0) ?axis ?low1 ?high1)" =>
{ CollapseNestedSlicesApplier {
low0: "?low0".parse().unwrap(),
low1: "?low1".parse().unwrap(),
high0: "?high0".parse().unwrap(),
high1: "?high1".parse().unwrap(),
}})
}
pub fn bubble_concatenate_through_move_axis() -> Rewrite<Language, MyAnalysis> {
struct MoveAxisApplier {
concatenate_axis: Var,
src_axis: Var,
dst_axis: Var,
}
impl Applier<Language, MyAnalysis> for MoveAxisApplier {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let original_concatenate_axis: usize =
MyAnalysis::get_usize(subst[self.concatenate_axis], egraph);
let src_axis: usize = MyAnalysis::get_usize(subst[self.src_axis], egraph);
let dst_axis: usize = MyAnalysis::get_usize(subst[self.dst_axis], egraph);
// If the move now happens /before/ the concatenate, we have to
// figure out what the new axis for the concatenate is.
// TODO(@gussmith23) Would be nice to have a more principled system of
// keeping track of axes. This is where Remy's relational algebra
// stuff could be really useful!
let new_concatenate_axis: usize = if (original_concatenate_axis < src_axis
&& original_concatenate_axis < dst_axis)
|| (original_concatenate_axis > src_axis && original_concatenate_axis > dst_axis)
{
// Axis is unaffected if it's not between src and dst.
original_concatenate_axis
} else if original_concatenate_axis == src_axis {
dst_axis
} else if original_concatenate_axis < src_axis && original_concatenate_axis >= dst_axis
{
original_concatenate_axis + 1
} else if original_concatenate_axis > src_axis && original_concatenate_axis <= dst_axis
{
original_concatenate_axis - 1
} else {
unreachable!()
};
format!(
"(concatenate
(move-axis ?a ?src-axis ?dst-axis)
(move-axis ?b ?src-axis ?dst-axis) {})",
new_concatenate_axis
)
.parse::<Pattern<_>>()
.unwrap()
.apply_one(egraph, eclass, subst)
}
}
rewrite!("bubble-concatenate-through-move-axis";
"(move-axis (concatenate ?a ?b ?concatenate-axis) ?src-axis ?dst-axis)" =>
{
MoveAxisApplier {
concatenate_axis: "?concatenate-axis".parse().unwrap(),
src_axis:"?src-axis".parse().unwrap(),
dst_axis:"?dst-axis".parse().unwrap()
}
})
}
/// Whether an axis is the last axis of a given tensor
fn last_axis(
var: &'static str,
axis: &'static str,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let var = var.parse().unwrap();
let axis_id = axis.parse().unwrap();
move |egraph, _, subst| {
MyAnalysis::get_usize(subst[axis_id], egraph)
== MyAnalysis::get_shape(subst[var], egraph).ndim() - 1
}
}
fn not_last_axis(
var: &'static str,
axis: &'static str,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, id, subst| !(last_axis(var, axis)(egraph, id, subst))
}
fn same_number_of_dimensions(
a: &'static str,
b: &'static str,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
let a = a.parse().unwrap();
let b = b.parse().unwrap();
move |egraph, _, subst| {
MyAnalysis::get_shape(subst[a], egraph).ndim()
== MyAnalysis::get_shape(subst[b], egraph).ndim()
}
}
// TODO(@gussmith23) naming
pub fn bubble_concatenate_through_cartesian_product_not_last_axis_left(
) -> Rewrite<Language, MyAnalysis> {
rewrite!("bubble-concatenate-through-cartesian-product-not-last-axis-left";
"(cartesian-product (concatenate ?t1 ?t2 ?axis) ?right)" =>
"(concatenate
(cartesian-product ?t1 ?right)
(cartesian-product ?t2 ?right)
?axis)"
if not_last_axis("?t1", "?axis")
// This should always be true, for now. Just making extra sure
if same_number_of_dimensions("?t1", "?t2"))
}
struct BubbleConcatenateThroughCartesianProductNotLastAxisRightApplier {
left: Var,
axis: Var,
}
impl Applier<Language, MyAnalysis>
for BubbleConcatenateThroughCartesianProductNotLastAxisRightApplier
{
fn apply_one(&self, egraph: &mut EG, matched_id: Id, subst: &Subst) -> Vec<Id> {
// cart-prod [a1, ..., an, c] [b1, ..., bm, c]
// = [a1, ..., an, b1, ..., bm, 2, c]
// So the axis gets shifted over by the a1, ..., an added in.
let left_shape = MyAnalysis::get_shape(subst[self.left], egraph);
let left_shape_length: usize = left_shape.as_array_view().len();
let old_axis: usize = MyAnalysis::get_usize(subst[self.axis], egraph);
let new_axis = old_axis + left_shape_length - 1;
let applier: Pattern<Language> = format!(
"(concatenate
(cartesian-product ?left ?t1)
(cartesian-product ?left ?t2)
{})",
new_axis
)
.parse()
.unwrap();
applier.apply_one(egraph, matched_id, subst)
}
}
// TODO(@gussmith23) naming
pub fn bubble_concatenate_through_cartesian_product_not_last_axis_right(
) -> Rewrite<Language, MyAnalysis> {
rewrite!("bubble-concatenate-through-cartesian-product-not-last-axis-right";
"(cartesian-product ?left (concatenate ?t1 ?t2 ?axis))" =>
{
ConditionalApplier {
applier: ConditionalApplier {
applier:
BubbleConcatenateThroughCartesianProductNotLastAxisRightApplier {
left: "?left".parse().unwrap(),
axis: "?axis".parse().unwrap(),
},
condition: not_last_axis("?t1", "?axis")
},
condition: same_number_of_dimensions("?t1", "?t2")
}
})
}
struct BubbleConcatenateThroughCartesianProductLastAxisApplier {
// Note that we're assuming a1's shape is the same as a2; same with b1 and
// b2.
a1: Var,
b1: Var,
}
impl Applier<Language, MyAnalysis> for BubbleConcatenateThroughCartesianProductLastAxisApplier {
fn apply_one(&self, egraph: &mut EG, matched_id: Id, subst: &Subst) -> Vec<Id> {
// cart-prod [a1, ..., an, c] [b1, ..., bm, c]
// = [a1, ..., an, b1, ..., bm, 2, c]
// axis1 and axis2 both point to their c dimension.
let a_shape = MyAnalysis::get_shape(subst[self.a1], egraph);
let a_shape_length: usize = a_shape.as_array_view().len();
let b_shape = MyAnalysis::get_shape(subst[self.b1], egraph);
let b_shape_length: usize = b_shape.as_array_view().len();
let new_axis = a_shape_length - 1 // skip [a1, ..., an]
+ b_shape_length - 1 // skip [b1, ..., bm]
+ 1; // skip [2]
// TODO
let applier: Pattern<Language> = format!(
// "(concatenate
// (concatenate
// (cartesian-product ?a1 ?b1)
// (cartesian-product ?a1 ?b2)
// {0})
// (concatenate
// (cartesian-product ?a2 ?b1)
// (cartesian-product ?a2 ?b2)
// {0})
// {0})",
"(concatenate
(cartesian-product ?a1 ?b1)
(cartesian-product ?a2 ?b2)
{0})",
new_axis
)
.parse()
.unwrap();
applier.apply_one(egraph, matched_id, subst)
}
}
// TODO(@gussmith23) naming
pub fn bubble_concatenate_through_cartesian_product_last_axis() -> Rewrite<Language, MyAnalysis> {
// TODO(@gussmith23) I think we need more checks here, to make sure that the sizes
// actually line up correctly.
rewrite!("bubble-concatenate-through-cartesian-product-last-axis";
"(cartesian-product (concatenate ?a1 ?a2 ?axis1) (concatenate ?b1 ?b2 ?axis2))" =>
{
ConditionalApplier {
condition: same_number_of_dimensions("?a1", "?a2"),
applier: ConditionalApplier {
condition: last_axis("?a1", "?axis1"),
applier: ConditionalApplier {
condition: same_number_of_dimensions("?b1", "?b2"),
applier: ConditionalApplier {
condition: last_axis("?b1", "?axis2"),
applier: BubbleConcatenateThroughCartesianProductLastAxisApplier {
a1: "?a1".parse().unwrap(),
b1: "?b1".parse().unwrap(),
}
}
}
}
}
})
}
pub fn bubble_concatenate_through_cartesian_product_axis_0_0() -> Rewrite<Language, MyAnalysis> {
// TODO(@gussmith23) this isn't the only way this could be done.
// Also there's gotta be a name for this in terms of algebraic rules
// TODO(@gussmith23) would it make our pattern-matching life easier if (1) we
// put the axes at the start of concatenate and (2) we used cons cells?
rewrite!("bubble-concatenate-through-cartesian-product-axes-0-0";
"(cartesian-product (concatenate ?a1 ?a2 0) (concatenate ?b1 ?b2 0))"
// TODO(@gussmith23) check this
=> "(concatenate
(concatenate (cartesian-product ?a1 ?b1)
(cartesian-product ?a1 ?b2) 1)
(concatenate (cartesian-product ?a2 ?b1)
(cartesian-product ?a2 ?b2) 1)
0)"
)
}
pub fn rewrite_nonmatching_cartesian_product_concatenate() -> Rewrite<Language, MyAnalysis> {
rewrite!(
"rewrite-nonmatching-cartesian-product-concatenate";
"(cartesian-product
(concatenate ?a1 ?a2 0)
(concatenate ?b1 ?b2 1)
)" =>
{RewriteNonMatchingCartConcatenateApplier{
a1:"?a1".parse().unwrap(),
a2:"?a2".parse().unwrap(),
a_axis:0,
b1:"?b1".parse().unwrap(),
b2:"?b2".parse().unwrap(),
b_axis:1,
}})
}
pub fn bubble_concatenate_through_map_dot_product_not_last_axis() -> Rewrite<Language, MyAnalysis> {
rewrite!(
"bubble-concatenate-through-map-dot-product-not-last-axis";
"(map-dot-product
(concatenate ?left ?right ?axis)
)" =>
"(concatenate
(map-dot-product ?left)
(map-dot-product ?right)
?axis)"
if not_last_axis("?left", "?axis")
// This should always be true, for now. Just making extra sure
if same_number_of_dimensions("?left", "?right")
)
}
pub fn bubble_concatenate_through_map_dot_product_last_axis() -> Rewrite<Language, MyAnalysis> {
rewrite!(
"bubble-concatenate-through-map-dot-product-last-axis";
"(map-dot-product
(concatenate ?left ?right ?axis)
)" =>
"(elementwise-add
(map-dot-product ?left)
(map-dot-product ?right)
)"
if last_axis("?left", "?axis")
// This should always be true, for now. Just making extra sure
if same_number_of_dimensions("?left", "?right")
)
}
pub fn slice_move_axis_composition_commutative() -> Rewrite<Language, MyAnalysis> {
struct SliceMoveAxisCompositionCommutativeApplier {
move_axis_src: Var,
move_axis_dest: Var,
slice_axis: Var,
}
impl Applier<Language, MyAnalysis> for SliceMoveAxisCompositionCommutativeApplier {
fn apply_one(&self, egraph: &mut EG, matched_id: Id, subst: &Subst) -> Vec<Id> {
let src_axis: usize = MyAnalysis::get_usize(subst[self.move_axis_src], egraph);
let dst_axis: usize = MyAnalysis::get_usize(subst[self.move_axis_dest], egraph);
let old_slice_axis: usize = MyAnalysis::get_usize(subst[self.slice_axis], egraph);
let new_slice_axis = if (old_slice_axis < src_axis && old_slice_axis < dst_axis)
|| (old_slice_axis > src_axis && old_slice_axis > dst_axis)
{
// Axis is unaffected if it's not between src and dst.
old_slice_axis
} else if old_slice_axis == src_axis {
dst_axis
} else if old_slice_axis < src_axis && old_slice_axis >= dst_axis {
old_slice_axis + 1
} else if old_slice_axis > src_axis && old_slice_axis <= dst_axis {
old_slice_axis - 1
} else {
unreachable!()
};
format!(
"(move-axis (slice ?tensor {} ?bottom ?top) ?src ?dest)",
new_slice_axis
)
.parse::<Pattern<Language>>()
.unwrap()
.apply_one(egraph, matched_id, subst)
}
}
rewrite!(
"slice-move-axis-composition-commutative";
"(slice (move-axis ?tensor ?src ?dest) ?axis ?bottom ?top)" =>
{ SliceMoveAxisCompositionCommutativeApplier {
move_axis_src: "?src".parse().unwrap(),
move_axis_dest: "?dest".parse().unwrap(),
slice_axis: "?axis".parse().unwrap(),
}}
)
}
pub fn systolic_array_vector_matrix() -> Rewrite<Language, MyAnalysis> {
struct SystolicArrayApplier {
a: Var,
b: Var,
}
impl Applier<Language, MyAnalysis> for SystolicArrayApplier {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let a_shape = MyAnalysis::get_shape(subst[self.a], egraph);
let b_shape = MyAnalysis::get_shape(subst[self.b], egraph);
assert_eq!(a_shape.as_array_view().len(), 1);
assert_eq!(b_shape.as_array_view().len(), 2);
let rows: usize = b_shape.as_array_view()[0];
let cols: usize = b_shape.as_array_view()[1];
let pattern: Pattern<Language> =
format!("(bsg-systolic-array {} {} ?a ?b)", rows, cols)
.parse()
.unwrap();
pattern.apply_one(egraph, eclass, subst)
}
}
rewrite!("systolic-array";
// TODO(@gussmith23) should check that ?a is a vector.
"(map-dot-product (cartesian-product ?a (move-axis ?b 1 0)))" =>
{SystolicArrayApplier{a: "?a".parse().unwrap(), b: "?b".parse().unwrap(),}})
}
// pub fn flatten_unflatten_access_windows() -> RW {
// rewrite!("access-windows-to-im2col";
// "(access-windows ?access ?kernel-shape ?stride-0 ?stride-1)" =>
// "(access-reshape
// (access-flatten
// (access-windows ?access ?kernel-shape ?stride-0 ?stride-1)
// )
// (get-access-shape
// (access-windows ?access ?kernel-shape ?stride-0 ?stride-1)
// )
// )")
// }
pub fn flatten_unflatten_any_access() -> RW {
struct ApplierImpl(Var);
impl Applier<Language, MyAnalysis> for ApplierImpl {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let shape = match &egraph[subst[self.0]].data {
MyAnalysisData::AccessPattern(a) => a,
_ => panic!(),
};
format!(
"(access-reshape
(access-flatten
?access
)
(access-shape
(shape {})
(shape {})
)
)",
shape
.shape
.slice()
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
shape
.item_shape
.slice()
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" ")
)
.parse::<Pattern<_>>()
.unwrap()
.apply_one(egraph, eclass, subst)
}
}
rewrite!("flatten-unflatten-all-accesses";
"?access" =>
{ ApplierImpl("?access".parse().unwrap()) }
if is_access())
}
pub fn bubble_reshape_through_cartesian_product() -> RW {
fn access_item_shapes_equal(
left: Var,
right: Var,
) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _, subst| match (&egraph[subst[left]].data, &egraph[subst[right]].data) {
(MyAnalysisData::AccessPattern(left), MyAnalysisData::AccessPattern(right)) => {
left.item_shape == right.item_shape
}
_ => false,
}
}
struct ApplierImpl {
left_shape: Var,
right_shape: Var,
}
impl Applier<Language, MyAnalysis> for ApplierImpl {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let left_shape = match &egraph[subst[self.left_shape]].data {
MyAnalysisData::AccessPattern(a) => a,
_ => panic!(),
};
let right_shape = match &egraph[subst[self.right_shape]].data {
MyAnalysisData::AccessPattern(a) => a,
_ => panic!(),
};
// TODO(@gussmith23) Duplicated logic for cartprod shape calculation
assert_eq!(
left_shape.item_shape, right_shape.item_shape,
"Cartesian product argument shapes must match"
);
let new_shape = IxDyn(
left_shape
.shape
.as_array_view()
.iter()
.cloned()
.chain(right_shape.shape.as_array_view().iter().cloned())
.collect::<Vec<usize>>()
.as_slice(),
);
let new_item_shape = IxDyn(
std::iter::once(2)
.chain(left_shape.item_shape.as_array_view().iter().cloned())
.collect::<Vec<usize>>()
.as_slice(),
);
assert_eq!(
new_shape.as_array_view().iter().product::<usize>()
* new_item_shape.as_array_view().iter().product::<usize>(),
left_shape.shape.as_array_view().iter().product::<usize>()
* right_shape.shape.as_array_view().iter().product::<usize>()
* 2
* left_shape
.item_shape
.as_array_view()
.iter()
.product::<usize>()
);
format!(
"(access-reshape
(access-cartesian-product
?left-access
?right-access
)
(access-shape
(shape {})
(shape {})
)
)",
new_shape
.slice()
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" "),
new_item_shape
.slice()
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join(" ")
)
.parse::<Pattern<_>>()
.unwrap()
.apply_one(egraph, eclass, subst)
}
}
rewrite!("bubble-reshape-through-cartesian-product";
"(access-cartesian-product
(access-reshape
?left-access
?left-shape
)
(access-reshape
?right-access
?right-shape
)
)" =>
{ ApplierImpl {
left_shape: "?left-shape".parse().unwrap(),
right_shape: "?right-shape".parse().unwrap(),
}}
if access_item_shapes_equal("?left-access".parse().unwrap(),
"?right-access".parse().unwrap()))
}
pub fn bubble_reshape_through_compute_dot_product() -> RW {
fn is_dot_product(op: Var) -> impl Fn(&mut EG, egg::Id, &egg::Subst) -> bool {
move |egraph, _, subst| match &egraph[subst[op]].data {
MyAnalysisData::ComputeType(c) => *c == super::language::ComputeType::DotProduct,
_ => false,
}
}
struct ApplierImpl(Var);
impl Applier<Language, MyAnalysis> for ApplierImpl {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let a = match &egraph[subst[self.0]].data {
MyAnalysisData::AccessPattern(a) => a,
_ => panic!(),
};
format!(
"(access-reshape (compute ?op ?a) (access-shape (shape {}) (shape)))",
a.shape
.as_array_view()
.iter()
.map(|u: &usize| { format!("{}", u) })
.collect::<Vec<_>>()
.join(" ")
)
.parse::<Pattern<Language>>()
.unwrap()
.apply_one(egraph, eclass, subst)
}
}
rewrite!("bubble-reshape-through-compute";
"(compute ?op (access-reshape ?a ?shape))" =>
{ ApplierImpl("?shape".parse().unwrap()) }
if is_dot_product("?op".parse().unwrap()))
}
/// Tensorizes a computation to an externally-blocked systolic array.
///
/// `rows` and `cols` define the size of the systolic array to map to. This
/// rewrite will map any matrix multiplication MxN X NxO to this size systolic
/// array as long as:
/// - N is a multiple of `rows`, and
/// - O is a multiple of `columns`.
pub fn systolic_array_with_blocking(rows: usize, cols: usize) -> Rewrite<Language, MyAnalysis> {
struct ApplierImpl {
rows: usize,
cols: usize,
a: Var,
b: Var,
}
impl Applier<Language, MyAnalysis> for ApplierImpl {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let (a, b) = match (&egraph[subst[self.a]].data, &egraph[subst[self.b]].data) {
(MyAnalysisData::AccessPattern(a), MyAnalysisData::AccessPattern(b)) => (a, b),
_ => panic!(),
};
assert_eq!(a.item_shape.ndim(), 1);
assert_eq!(b.shape.ndim(), 1);
assert_eq!(b.item_shape.ndim(), 1);
let pattern: Pattern<Language> = format!(
"(systolic-array-with-blocking {} {}
?access-1
(access (access-transpose ?access-2 (list 1 0)) 0)
)",
self.rows, self.cols
)
.parse()
.unwrap();
pattern.apply_one(egraph, eclass, subst)
}
}
rewrite!(format!("systolic-array-with-blocking-{}-{}", rows, cols);
"(compute dot-product
(access-cartesian-product
?access-1
?access-2
)
)
" =>
{ ApplierImpl{rows, cols, a: "?access-1".parse().unwrap(), b: "?access-2".parse().unwrap(),}}
// Remember: the accesses look like [M] [N] and [O] [N] for an
// MxN X NxO multiplication.
if constrain_access("?access-1".parse().unwrap(),
move |a| a.shape.ndim() <= 1 && a.item_shape.ndim() == 1
&& a.item_shape.slice()[0] % rows == 0)
if constrain_access("?access-2".parse().unwrap(),
move |a| a.shape.ndim() == 1 && a.item_shape.ndim() == 1
&& a.shape.slice()[0] % cols == 0))
}
pub fn systolic_array() -> Rewrite<Language, MyAnalysis> {
struct ApplierImpl {
a: Var,
b: Var,
}
impl Applier<Language, MyAnalysis> for ApplierImpl {
fn apply_one(&self, egraph: &mut EG, eclass: Id, subst: &Subst) -> Vec<Id> {
let (a, b) = match (&egraph[subst[self.a]].data, &egraph[subst[self.b]].data) {
(MyAnalysisData::AccessPattern(a), MyAnalysisData::AccessPattern(b)) => (a, b),
_ => panic!(),
};
assert_eq!(a.item_shape.ndim(), 1);
assert_eq!(b.shape.ndim(), 1);
assert_eq!(b.item_shape.ndim(), 1);
let rows: usize = b.item_shape.slice()[0];
let cols: usize = b.shape.slice()[0];
let pattern: Pattern<Language> = format!(
"(systolic-array {} {}
?access-1
(access (access-transpose ?access-2 (list 1 0)) 0)
)",
rows, cols
)
.parse()
.unwrap();
pattern.apply_one(egraph, eclass, subst)
}
}
rewrite!("systolic-array";
"(compute dot-product
(access-cartesian-product
?access-1
?access-2
)
)
" =>
{ ApplierImpl{a: "?access-1".parse().unwrap(), b: "?access-2".parse().unwrap(),}}
if constrain_access("?access-1".parse().unwrap(),
|a| a.shape.ndim() <= 1 && a.item_shape.ndim() == 1)
if constrain_access("?access-2".parse().unwrap(),
|a| a.shape.ndim() == 1 && a.item_shape.ndim() == 1))
}
pub enum SliceConcatenateStrategy {
/// Divides the axis by `divisor`; does not divide anything less than or
/// equal to `limit`.
DivideBy {
divisor: usize,
limit: usize,
},
DivideInto {
segment_size: usize,
},
/// Slice into a dimension just once at the beginning, if there's at least
/// `segment_size` remaining in the dimension.
// TODO(@gussmith23) Test this
SliceOnce {
segment_size: usize,
},
}
pub fn slice_concatenate_accesses(
axis: usize,
strategy: SliceConcatenateStrategy,