-
Notifications
You must be signed in to change notification settings - Fork 10
/
language.rs
5612 lines (5244 loc) · 211 KB
/
language.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 egg::{define_language, merge_if_different, EGraph, Id};
use itertools::{multizip, EitherOrBoth::*, Itertools};
use log::debug;
use ndarray::{s, Dimension, Ix, IxDyn};
use ordered_float::NotNan;
use std::collections::{HashMap, HashSet};
use std::fmt::Display;
use std::iter::FromIterator;
use std::str::FromStr;
define_language! {
pub enum Language {
// (move-axis <tensor> <axis (usize)> <dest (usize)>)
// Moves axis <axis> so that it is now axis <dest>.
// Replaces the "rows" and "cols" operators.
"move-axis" = MoveAxis([Id; 3]),
// (cartesian-product <t0> <t1>)
// Expects tensors of shape
// [a1, ..., an, c]
// [b1, ..., bm, c]
// Outputs a tensor of shape
// [a1, ..., an, b1, ..., bm, 2, c]
// which represents the cartesian product of the c-length vectors stored
// in the two tensors.
"cartesian-product" = CartesianProduct([Id; 2]),
// (map-dot-product <tensor>)
// for a tensor with shape
// [a1, ..., an, 2, c],
// the result is a new tensor with shape
// [a1, ..., an]
// Whose elements are the dot product of the two c-length vectors at
// each position in the original array.
"map-dot-product" = MapDotProduct(Id),
// (slice <tensor> <axis (usize)> <low (usize)> <high (usize)>)
// Slices into <tensor> at axis <axis>, slicing the half-open range
// [<low>, <high>).
"slice" = Slice([Id; 4]),
// (concatenate <t0> <t1> <axis (usize)>)
// Concatenate tensors <t0> and <t1> along <axis>.
"concatenate" = Concatenate([Id; 3]),
// (elementwise-add <t0> <t1>)
// TODO(@gussmith23) this will probably need to be signed at some point?
// TODO(@gussmith23) ^^ what did I mean by this?
"elementwise-add" = ElementwiseAdd([Id; 2]),
// (bsg-systolic-array <rows (usize)> <cols (usize)> <t0> <t1>)
// Represents a systolic array of size rows X cols, fed with tensors t0
// and t1.
// TODO(@gussmith23) do we need to specify rows and cols? You can infer these
// from the size of the input, but it's also useful for searching.
"bsg-systolic-array" = BsgSystolicArray([Id; 4]),
// (systolic-array <rows (usize)> <cols (usize)> <access-0> <access-1>)
// Represents a systolic array of size rows X cols, fed with two
// accesses.
// This is Scott's weight-stationary systolic array design. It reads in
// two matrices: first matrix is in the layout [M, N] and second is in
// the layout [N, O]. The systolic array computes the matrix
// multiplication, leading to a matrix with layout [M, O].
// The systolic array expects exactly one shape for the second argument:
// [N, O]. These correspond directly to the rows/cols parameters of the
// systolic array. The first argument is partially constrained: its
// second dimension must be N, but its first dimension may be any
// length.
// In terms of Glenside accesses, we expect <access-0> to have shape [M]
// [N], and <access-1> to have shape [] [N, O].
// TODO(@gussmith23) How to make the M argument "programmable"?
// TODO(@gussmith23) do we need to specify rows and cols? You can infer these
// from the size of the input, but it's also useful for searching.
"systolic-array" = SystolicArray([Id; 4]),
// Same as the systolic array above, but relies on Scott's blocking code
// instead of relying on Glenside to discover the blocking. By
// "blocking", we mean splitting up a matrix multiply to run on a
// smaller systolic array.
"systolic-array-with-blocking" = SystolicArrayWithBlocking([Id; 4]),
// (systolic-array-conv2d-nchw-oihw-with-blocking
// <rows: Usize> <cols: Usize>
// <weights: Access> <data: Access>
// <kh: Usize> <kw: Usize>
// <stride-h: Usize> <stride-w: Usize>)
// A systolic array operating in conv2d mode, with data in layout NCHW
// and weights in layout OIHW. We don't actually have an atom for this,
// but it's currently used as an intermediate to help discover
// systolic-array-conv2d-nhwc-hwio-with-blocking.
"systolic-array-conv2d-nchw-oihw-with-blocking" = SystolicArrayConv2dNchwOihwWithBlocking([Id; 8]),
// (systolic-array-conv2d-nhwc-hwio-with-blocking
// <rows: Usize> <cols: Usize>
// <weights: Access> <data: Access>
// <kh: Usize> <kw: Usize>
// <stride-h: Usize> <stride-w: Usize>)
// A systolic array operating in conv2d mode, with data in layout NHWC
// and weights in layout HWIO. Scott should have an atom for this at
// some point.
"systolic-array-conv2d-nhwc-hwio-with-blocking" = SystolicArrayConv2dNhwcHwioWithBlocking([Id; 8]),
// (systolic-array-conv2d-im2col-nchw-oihw-with-blocking <rows: Usize>
// <cols: Usize> <weights: Access> <data: Access> <kh: Usize> <kw:
// Usize> <stride-h: Usize> <stride-w: Usize>)
// A systolic array operating in conv2d-im2col mode, with data in layout
// NCHW and weights in layout OIHW. We don't actually have an atom for
// this, but it's currently used as an intermediate to help discover
// systolic-array-conv2d-im2col-nhwc-hwio-with-blocking. Conv2d im2col
// mode indicates that the systolic array is reading in the image data
// and transforming it to im2col on the fly.
"systolic-array-conv2d-im2col-nchw-oihw-with-blocking" = SystolicArrayConv2dIm2colNchwOihwWithBlocking([Id; 8]),
"systolic-array-conv2d-im2col-nhwc-hwio-with-blocking" = SystolicArrayConv2dIm2colNhwcHwioWithBlocking([Id; 8]),
// (access-windows <access> <filters-shape: Shape> <stride-shape: Shape>)
// Form the windows which will be convolved over.
// TODO(@gussmith23) AccessWindows shouldn't be specific to filters.
// AccessWindows is used in other contexts too, i.e. pooling.
"access-windows" = AccessWindows([Id; 3]),
// (shape-of <tensor>)
// Returns the shape of the tensor.
// TODO(@gussmith) Choose between ([Id; 1]) and (Id) and be consistent
// When describing the arguments of a construct that takes a single Id
// argument (like shape-of), we can use (Id) or ([Id; 1]). I'm not sure
// which is better, but I should choose one and be consistent.
"shape-of" = ShapeOf([Id; 1]),
// (slice-shape <shape> <dim>)
// Slices a shape by taking dimensions >= <dim>.
"slice-shape" = SliceShape([Id; 2]),
// (shape-insert-axis <shape: Shape> <axis: usize>)
// Inserts an axis with value 1.
"shape-insert-axis" = ShapeInsertAxis([Id; 2]),
// (shape-remove-axis <shape: Shape> <axis: usize>)
// Removes axis from shape.
"shape-remove-axis" = ShapeRemoveAxis([Id; 2]),
// (access <tensor> <dim>)
// The most basic access pattern.
// Let <tensor> have dims d0, .., dn.
// Interprets <tensor> as a shaped list of shape d0, .., d(<dim>-1)
// whose elements are of shape d<dim>, .., dn.
"access" = Access([Id; 2]),
// (access-transpose <a: access> <new-order: list>)
// Uses numpy.transpose() semantics. Reorders axes in an access.
// Does not change the access dimension.
"access-transpose" = AccessTranspose([Id; 2]),
// (access-cartesian-product <access1> <access2>)
// Cartesian product access pattern.
// Assume <access1> has shape
// [a1, ..., an]
// and <access2> has shape
// [b1, ..., bm].
// Both must have the same item shape,
// [c1, ..., co]
// Outputs a tensor of shape
// [a1, ..., an, b1, ..., bm, 2, c1, ..., co]
// which represents the cartesian product of the items in both accesses.
"access-cartesian-product" = AccessCartesianProduct([Id; 2]),
// (compute <compute-type> <access>)
// Compute over the items in <access>.
//
// Compute types:
//
// dot-product
// Expects an item shape of
// [n, a0, ..., am]
// Where n specifies the tuple multiplicity and [a0, ..., am] is the
// shape of the tensors to be dot-producted with one another.
"compute" = Compute([Id; 2]),
// (get-access-shape <access>)
// Returns the shape of the access.
// "get-access-shape" = GetAccessShape(Id),
// This shouldn't actually be needed at the moment. We are handling all
// statically-sized networks, and so anywhere where we would have used
// this, we should be able to just plug in a literal access-shape. If
// and when we start supporting dynamic networks, this will become
// needed.
// (access-reshape <access> <shape>)
// Reshapes the access to have the given
"access-reshape" = AccessReshape([Id; 2]),
// (access-flatten <access>)
// Flattens the access's shape and item shape.
"access-flatten" = AccessFlatten(Id),
// (shape <usize>...)
// Shape literal.
"shape" = Shape(Box<[Id]>),
// (list <usize>...)
// List literal
"list" = List(Box<[Id]>),
// (construct-tuple <access> <access> ...)
// Tuple Construction
"construct-tuple" = ConstructTuple(Box<[Id]>),
// (tuple-get-item <tuple> <i>)
// Get the item at the ith index of tuple
"tuple-get-item" = TupleGetItem([Id;2]),
// (access-shape <shape: shape> <item-shape: shape>)
// Access shape literal.
"access-shape" = AccessShape([Id;2]),
// (access-slice <access> <axis (usize)> <low (usize)> <high (usize)>)
// Slices into <access> at axis <axis>, slicing the half-open range
// [<low>, <high>).
// TODO(@gussmith23) Implement access-slice-item
// If axis >= access.shape.ndim(), it slices into access.item_shape.
// This is me being lazy and not wanting to implement separate
// access-slice-shape and access-slice-item operators for right now.
"access-slice" = AccessSlice([Id; 4]),
// (access-concatenate <a0> <a1> <axis (usize)>)
// Concatenate accesses <a0> and <a1> along <axis>.
// TODO(@gussmith23) Implement access-concatenate-item
// If axis >= access.shape.ndim(), it concatenates along dimensions in
// access.item_shape.
"access-concatenate" = AccessConcatenate([Id; 3]),
// (access-pair <a0> <a1>)
// Simply pair every item of a0 with every item of a1.
"access-pair" = AccessPair([Id; 2]),
// (access-shift-right <a0>)
// Shifts a dimension from shape to item shape.
"access-shift-right" = AccessShiftRight(Id),
// (access-tensor <t>)
// Access a tensor literal.
"access-tensor" = AccessTensor(Id),
// (access-pad <a>
// <pad-type (PadType)>
// <axis (usize)> <pad-before (usize)> <pad-after (usize)>)
// Pads a tensor at the given axis.
"access-pad" = AccessPad([Id; 5]),
// (access-squeeze <a> <axis (usize)>)
"access-squeeze" = AccessSqueeze([Id; 2]),
// (access-insert-axis <a> <axis (usize)>)
"access-insert-axis" = AccessInsertAxis([Id; 2]),
// (access-broadcast <a> <shape: shape>)
// Simple broadcasting. <a> and <shape> must have the same total number
// of dimensions. All dimensions in <a> must either match the
// corresponding dimension in <shape> or be 1.
"access-broadcast" = AccessBroadcast([Id; 2]),
// (access-literal <literal: Literal>)
// Access a literal. This may be able to be folded in to some other
// access pattern, later on. It fits in with access-tensor as a "access
// pattern constructor"; it takes something that isn't an access pattern
// and converts it to an access pattern.
"access-literal" = AccessLiteral(Id),
// (literal <val: Float64>)
// A literal value. Can only represent 0-dimensional values for now, but
// in the future, we can and should support array constants.
"literal" = Literal(Id),
// (relay-operator-call <relay-operator: RelayOperator> <args>...)
"relay-operator-call" = RelayOperatorCall(Box<[Id]>),
Usize(usize),
// Important that this go after usize, so that usizes are parsed as
// usizes, not as floats.
NotNanFloat64(NotNan<f64>),
RelayOperator(RelayOperator),
RelayActivationLayout(RelayActivationLayout),
RelayKernelLayout(RelayKernelLayout),
// pad-type: zero-padding
// (No other options right now)
PadType(PadType),
ComputeType(ComputeType),
Symbol(String),
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RelayOperator {
/// (relay-operator relay-batch-norm-inference <data: access>
/// <gamma: access> <beta: access>
/// <moving_mean: access> <moving_var: access>
/// <axis: usize> <epsilon: float>)
/// The batch-norm-at-inference-time operator. We don't currently support
/// normal batch norm, which is a training-time operator, but we do support
/// its inference-time simplified version.
/// TODO(@gussmith23) How to handle batch norms?
RelayBatchNormInference,
/// (relay-operator relay-softmax <data: access> <axis: usize>)
RelaySoftmax,
/// (relay-operator relay-relu <data: access>)
RelayReLU,
/// (relay-operator relay-leaky-relu <data: access> <alpha: Float64>)
RelayLeakyReLU,
/// (relay-operator relay-max-pool2d <data: access>
/// <pool size: shape> <strides: shape> <padding: shape>
/// <layout: RelayActivationLayout>)
RelayMaxPool2D,
/// (relay-operator relay-global-avg-pool2d <data: access>
/// <layout: RelayActivationLayout>)
RelayGlobalAvgPool2D,
/// (relay-operator relay-avg-pool2d <data: access>
/// <pool_size: shape> <strides: shape> <padding: shape> <layout: RelayActivationLayout>
/// )
RelayAvgPool2D,
/// (relay-operator relay-upsampling <data: access> <scale_h: Float64> <scale_w: Float64>
/// <layout: RelayActivationLayout>)
RelayUpSampling,
/// (relay-operator relay-batch-flatten <data: access>)
RelayBatchFlatten,
/// (relay-operator relay-bias-add <data: access> <bias: access>
/// <axis: usize>)
RelayBiasAdd,
/// (relay-operator relay-add <a: access> <b: access>)
RelayAdd,
/// (relay-operator relay-sigmoid <data: access>)
RelaySigmoid,
/// (relay-operator relay-maximum <a: access> <b: access>)
RelayMaximum,
/// (relay-operator relay-minimum <a:access> <b: access>)
RelayMinimum,
}
impl FromStr for RelayOperator {
type Err = ();
fn from_str(input: &str) -> Result<RelayOperator, Self::Err> {
match input {
"relay-batch-norm-inference" => Ok(RelayOperator::RelayBatchNormInference),
"relay-softmax" => Ok(RelayOperator::RelaySoftmax),
"relay-relu" => Ok(RelayOperator::RelayReLU),
"relay-max-pool2d" => Ok(RelayOperator::RelayMaxPool2D),
"relay-global-avg-pool2d" => Ok(RelayOperator::RelayGlobalAvgPool2D),
"relay-batch-flatten" => Ok(RelayOperator::RelayBatchFlatten),
"relay-bias-add" => Ok(RelayOperator::RelayBiasAdd),
"relay-add" => Ok(RelayOperator::RelayAdd),
"relay-sigmoid" => Ok(RelayOperator::RelaySigmoid),
"relay-avg-pool2d" => Ok(RelayOperator::RelayAvgPool2D),
"relay-upsampling" => Ok(RelayOperator::RelayUpSampling),
"relay-maximum" => Ok(RelayOperator::RelayMaximum),
"relay-minimum" => Ok(RelayOperator::RelayMinimum),
"relay-leaky-relu" => Ok(RelayOperator::RelayLeakyReLU),
_ => Err(()),
}
}
}
impl Display for RelayOperator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
RelayOperator::RelayBatchNormInference => "relay-batch-norm-inference",
RelayOperator::RelaySoftmax => "relay-softmax",
RelayOperator::RelayReLU => "relay-relu",
RelayOperator::RelayLeakyReLU => "relay-leaky-relu",
RelayOperator::RelayMaxPool2D => "relay-max-pool2d",
RelayOperator::RelayGlobalAvgPool2D => "relay-global-avg-pool2d",
RelayOperator::RelayBatchFlatten => "relay-batch-flatten",
RelayOperator::RelayBiasAdd => "relay-bias-add",
RelayOperator::RelayAdd => "relay-add",
RelayOperator::RelaySigmoid => "relay-sigmoid",
RelayOperator::RelayAvgPool2D => "relay-avg-pool2d",
RelayOperator::RelayUpSampling => "relay-upsampling",
RelayOperator::RelayMaximum => "relay-maximum",
RelayOperator::RelayMinimum => "relay-minimum",
}
)
}
}
/// Only for use in [`RelayOperatorCall`]s.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RelayActivationLayout {
NCHW,
NHWC,
}
impl FromStr for RelayActivationLayout {
type Err = ();
fn from_str(input: &str) -> Result<RelayActivationLayout, Self::Err> {
match input {
"relay-activation-layout-nhwc" => Ok(RelayActivationLayout::NHWC),
"relay-activation-layout-nchw" => Ok(RelayActivationLayout::NCHW),
_ => Err(()),
}
}
}
impl Display for RelayActivationLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
RelayActivationLayout::NHWC => "relay-activation-layout-nhwc",
RelayActivationLayout::NCHW => "relay-activation-layout-nchw",
}
)
}
}
/// Only for use in [`RelayOperatorCall`]s.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RelayKernelLayout {
OIHW,
HWIO,
}
impl FromStr for RelayKernelLayout {
type Err = ();
fn from_str(input: &str) -> Result<RelayKernelLayout, Self::Err> {
match input {
"relay-kernel-layout-hwio" => Ok(RelayKernelLayout::HWIO),
"relay-kernel-layout-oihw" => Ok(RelayKernelLayout::OIHW),
_ => Err(()),
}
}
}
impl Display for RelayKernelLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
RelayKernelLayout::HWIO => "relay-kernel-layout-hwio",
RelayKernelLayout::OIHW => "relay-kernel-layout-oihw",
}
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ComputeType {
DotProduct,
ReduceSum,
ReLU,
Sqrt,
Negative,
/// Expects item shape of `a x b1 x .. x bn`. Performs an elementwise
/// addition of the `a` tensors of size `b1 x .. x bn`.
/// TODO(@gussmith) Multiple-arg compute feels clunky and ad-hoc.
/// Should figure out an explicit way to define access multiple-stream
/// access patterns.
ElementwiseAdd,
/// Expects item shape of `a x b1 x .. x bn`. Performs an elementwise
/// multiplication of the `a` tensors of size `b1 x .. x bn`.
ElementwiseMul,
ElementwiseDiv,
/// Takes the max across all elements in each item. Reduces any item shape
/// to a scalar.
ReduceMax,
/// Computes softmax. Currently expects access axis to be 0. Unsure how to
/// define softmax for other access patterns.
Softmax,
/// For an item shape of `a1 x a2 x ...`, returns an item shape of `1` where
/// the returned scalar is the mean of the `a1 x a2 x ...`-shaped tensor.
ReduceMean,
}
impl FromStr for ComputeType {
type Err = ();
fn from_str(input: &str) -> Result<ComputeType, Self::Err> {
match input {
"dot-product" => Ok(ComputeType::DotProduct),
"reduce-sum" => Ok(ComputeType::ReduceSum),
"reduce-max" => Ok(ComputeType::ReduceMax),
"relu" => Ok(ComputeType::ReLU),
"sqrt" => Ok(ComputeType::Sqrt),
"negative" => Ok(ComputeType::Negative),
"elementwise-add" => Ok(ComputeType::ElementwiseAdd),
"elementwise-mul" => Ok(ComputeType::ElementwiseMul),
"elementwise-div" => Ok(ComputeType::ElementwiseDiv),
"softmax" => Ok(ComputeType::Softmax),
"reduce-mean" => Ok(ComputeType::ReduceMean),
_ => Err(()),
}
}
}
impl Display for ComputeType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
ComputeType::DotProduct => "dot-product",
ComputeType::ReduceSum => "reduce-sum",
ComputeType::ReduceMax => "reduce-max",
ComputeType::ReLU => "relu",
ComputeType::Sqrt => "sqrt",
ComputeType::Negative => "negative",
ComputeType::ElementwiseAdd => "elementwise-add",
ComputeType::ElementwiseMul => "elementwise-mul",
ComputeType::ElementwiseDiv => "elementwise-div",
ComputeType::Softmax => "softmax",
ComputeType::ReduceMean => "reduce-mean",
}
)
}
}
/// Specifies how to pick the values we pad with.
#[derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord, Copy)]
pub enum PadType {
/// Pad with zeroes.
ZeroPadding,
/// Pad with minimum representable number in the number system.
MinPadding,
}
impl FromStr for PadType {
type Err = ();
fn from_str(input: &str) -> Result<PadType, Self::Err> {
match input {
"zero-padding" => Ok(PadType::ZeroPadding),
"min-padding" => Ok(PadType::MinPadding),
_ => Err(()),
}
}
}
impl Display for PadType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match self {
PadType::ZeroPadding => "zero-padding",
PadType::MinPadding => "min-padding",
}
)
}
}
// TODO(@gussmith23) Pick a better analysis name.
#[derive(Debug, Clone, PartialEq)]
pub enum MyAnalysisData {
Literal(ndarray::ArrayD<f64>),
Legacy(MyAnalysisDataLegacyData),
AccessPattern(AccessPatternData),
Shape(ShapeData),
Tuple(Vec<MyAnalysisData>),
// TODO(@gussmith23) Needed?
//Tensor(TensorData),
ComputeType(ComputeType),
PadType(PadType),
List(Vec<usize>),
RelayOperator(RelayOperator),
RelayActivationLayout(RelayActivationLayout),
RelayKernelLayout(RelayKernelLayout),
}
#[derive(Debug, Clone, PartialEq)]
pub struct ShapeData {
shape: IxDyn,
}
/// New version of rangeset.
pub trait RangeSet2 {
type Index;
/// Inserts elements, shifting existing ranges as needed.
fn insert_elements(&mut self, index: Self::Index, num_elements_inserted: usize);
/// Updates ranges as if `num_elements_removed` elements were removed at
/// `index`.
fn remove_elements(&mut self, index: Self::Index, num_elements_removed: usize);
/// Checks whether `range` is covered by the ranges in this set.
fn covered(&self, range: (Self::Index, Self::Index)) -> bool;
/// Adds range. Ranges are half-open.
fn add_range(&mut self, range: (Self::Index, Self::Index));
}
type BoolVecRangeSet = Vec<bool>;
impl RangeSet2 for BoolVecRangeSet {
type Index = usize;
fn insert_elements(&mut self, index: Self::Index, num_elements_inserted: usize) {
// Make index-1 the last valid index.
if index >= self.len() {
self.resize(index, false);
}
*self = self[..index]
.iter()
.chain(std::iter::repeat(&false).take(num_elements_inserted))
.chain(self[index..].iter())
.cloned()
.collect();
}
fn remove_elements(&mut self, index: Self::Index, num_elements_removed: usize) {
*self = self[..index]
.iter()
.chain(self[index + num_elements_removed..].iter())
.cloned()
.collect()
}
fn covered(&self, range: (Self::Index, Self::Index)) -> bool {
// If the top end of the range is not actually represented, then those
// values are implicitly false and so the range is not covered.
// Otherwise, check that the values are all true.
range.1 <= self.len() && self[range.0..range.1].iter().all(|v| *v)
}
fn add_range(&mut self, range: (Self::Index, Self::Index)) {
// Make range.1-1 the last valid index.
if range.1 > self.len() {
self.resize(range.1, false);
}
for i in range.0..range.1 {
self[i] = true;
}
}
}
#[cfg(test)]
mod bool_vec_range_set_tests {
use super::*;
#[test]
fn insert_elements_0() {
let mut range_set = BoolVecRangeSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((4, 8));
range_set.add_range((7, 10));
range_set.insert_elements(5, 5);
assert!(range_set.covered((0, 3)));
assert!(range_set.covered((2, 5)));
assert!(range_set.covered((10, 11)));
assert!(range_set.covered((4, 5)));
assert!(range_set.covered((10, 13)));
assert!(range_set.covered((12, 15)));
}
#[test]
fn insert_elements_1() {
let mut range_set = BoolVecRangeSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((4, 8));
range_set.add_range((7, 10));
range_set.insert_elements(5, 5);
range_set.add_range((5, 10));
assert!(range_set.covered((0, 3)));
assert!(range_set.covered((2, 11)));
assert!(range_set.covered((4, 13)));
assert!(range_set.covered((12, 15)));
}
#[test]
fn remove_elements() {
let mut range_set = BoolVecRangeSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((5, 8));
range_set.add_range((9, 12));
range_set.add_range((10, 14));
range_set.remove_elements(5, 5);
assert!(range_set.covered((0, 3)));
assert!(range_set.covered((2, 5)));
assert!(range_set.covered((5, 7)));
assert!(range_set.covered((5, 9)));
}
#[test]
fn covered() {
let mut range_set = BoolVecRangeSet::default();
range_set.add_range((0, 3));
range_set.add_range((5, 6));
range_set.add_range((6, 8));
range_set.add_range((10, 12));
range_set.add_range((11, 14));
assert!(range_set.covered((0, 2)));
assert!(!range_set.covered((0, 4)));
assert!(!range_set.covered((2, 5)));
assert!(!range_set.covered((3, 5)));
assert!(range_set.covered((5, 7)));
assert!(range_set.covered((5, 8)));
assert!(!range_set.covered((5, 9)));
assert!(range_set.covered((10, 14)));
assert!(!range_set.covered((10, 16)));
assert!(!range_set.covered((22, 23)));
}
#[test]
fn test() {
let mut range_set = BoolVecRangeSet::default();
range_set.insert_elements(0, 1);
range_set.add_range((0, 1));
range_set.insert_elements(33, 2);
range_set.add_range((33, 35));
assert!(range_set.covered((0, 1)));
assert!(!range_set.covered((1, 33)));
assert!(range_set.covered((33, 35)));
}
}
/// Used to represent ranges over a set from 0..n, for some n. Ranges are
/// half-open.
type RangeHashSet = HashSet<(usize, usize)>;
pub enum RangeInsertStrategy {
/// If elements are inserted in the middle of a range, the range gets split
/// in two.
BreakRanges,
/// If elements are inserted in the middle of a range, they get folded into
/// the range.
PreserveRanges,
}
pub trait RangeSet {
type Index;
/// Updates ranges as if `num_elements_inserted` elements were inserted at
/// `index`, according to `strategy`.
fn insert_elements(
&mut self,
strategy: RangeInsertStrategy,
index: Self::Index,
num_elements_inserted: usize,
);
/// Updates ranges as if `num_elements_removed` elements were removed at
/// `index`.
fn remove_elements(&mut self, index: Self::Index, num_elements_removed: usize);
/// Checks whether `range` is covered by the ranges in this set.
fn covered(&self, range: (Self::Index, Self::Index)) -> bool;
/// Adds range. Ranges are half-open.
fn add_range(&mut self, range: (Self::Index, Self::Index));
}
impl RangeSet for RangeHashSet {
type Index = usize;
fn insert_elements(
&mut self,
strategy: RangeInsertStrategy,
index: usize,
num_elements_inserted: usize,
) {
let mut new_ranges = Vec::default();
for (low, high) in self.drain() {
assert!(low <= high);
match strategy {
RangeInsertStrategy::PreserveRanges => {
let (new_low, new_high) = if index < low {
(low + num_elements_inserted, high + num_elements_inserted)
} else if index >= low && index <= high {
(low, high + num_elements_inserted)
} else if index > high {
(low, high)
} else {
unreachable!()
};
new_ranges.push((new_low, new_high));
}
RangeInsertStrategy::BreakRanges => {
match {
if index <= low {
(
Some((low + num_elements_inserted, high + num_elements_inserted)),
None,
)
} else if index > low && index < high {
(
Some((low, index)),
Some((index + num_elements_inserted, high + num_elements_inserted)),
)
} else if index >= high {
(Some((low, high)), None)
} else {
unreachable!()
}
} {
(Some(range1), Some(range2)) => {
new_ranges.push(range1);
new_ranges.push(range2);
}
(Some(range1), None) => {
new_ranges.push(range1);
}
_ => panic!(),
};
}
}
}
for range in new_ranges.iter() {
self.insert(*range);
}
}
fn remove_elements(&mut self, index: usize, num_elements_removed: usize) {
let new_ranges = self
.drain()
.filter_map(|(low, high): (usize, usize)| {
let new_low = if low <= index {
low
} else if low > index {
low - std::cmp::min(num_elements_removed, low - index)
} else {
unreachable!()
};
let new_high = if index >= high {
high
} else if index < high {
high - std::cmp::min(num_elements_removed, high - index)
} else {
unreachable!()
};
// If the range is valid and nonempty
if new_low < new_high {
Some((new_low, new_high))
} else {
None
}
})
.collect::<Vec<_>>();
for new_range in new_ranges {
self.insert(new_range);
}
}
/// I'm hoping this implementation will be fast.
fn covered(&self, range: (Self::Index, Self::Index)) -> bool {
let mut to_be_covered =
HashSet::<_, std::collections::hash_map::RandomState>::from_iter(range.0..range.1);
for (low, high) in self.iter() {
to_be_covered = to_be_covered
.difference(&HashSet::from_iter(*low..*high))
.cloned()
.collect();
}
to_be_covered.is_empty()
}
/// Adds range. Ranges are half-open.
fn add_range(&mut self, range: (Self::Index, Self::Index)) {
self.insert(range);
}
}
#[cfg(test)]
mod range_hash_set_tests {
use super::*;
#[test]
fn insert_elements_break_ranges() {
let mut range_set = RangeHashSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((4, 8));
range_set.add_range((7, 10));
range_set.insert_elements(RangeInsertStrategy::BreakRanges, 5, 5);
assert_eq!(range_set.len(), 6);
assert!(range_set.contains(&(0, 3)));
assert!(range_set.contains(&(2, 5)));
assert!(range_set.contains(&(10, 11)));
assert!(range_set.contains(&(4, 5)));
assert!(range_set.contains(&(10, 13)));
assert!(range_set.contains(&(12, 15)));
}
#[test]
fn insert_elements_preserve_ranges() {
let mut range_set = RangeHashSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((4, 8));
range_set.add_range((7, 10));
range_set.insert_elements(RangeInsertStrategy::PreserveRanges, 5, 5);
assert_eq!(range_set.len(), 4);
assert!(range_set.contains(&(0, 3)));
assert!(range_set.contains(&(2, 11)));
assert!(range_set.contains(&(4, 13)));
assert!(range_set.contains(&(12, 15)));
}
#[test]
fn remove_elements() {
let mut range_set = RangeHashSet::default();
range_set.add_range((0, 3));
range_set.add_range((2, 6));
range_set.add_range((5, 8));
range_set.add_range((9, 12));
range_set.add_range((10, 14));
range_set.remove_elements(5, 5);
assert_eq!(range_set.len(), 4);
assert!(range_set.contains(&(0, 3)));
assert!(range_set.contains(&(2, 5)));
assert!(range_set.contains(&(5, 7)));
assert!(range_set.contains(&(5, 9)));
}
#[test]
fn covered() {
let mut range_set = RangeHashSet::default();
range_set.add_range((0, 3));
range_set.add_range((5, 6));
range_set.add_range((6, 8));
range_set.add_range((10, 12));
range_set.add_range((11, 14));
assert!(range_set.covered((0, 2)));
assert!(!range_set.covered((0, 4)));
assert!(!range_set.covered((2, 5)));
assert!(!range_set.covered((3, 5)));
assert!(range_set.covered((5, 7)));
assert!(range_set.covered((5, 8)));
assert!(!range_set.covered((5, 9)));
assert!(range_set.covered((10, 14)));
assert!(!range_set.covered((10, 16)));
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct AccessPatternData {
pub shape: IxDyn,
pub item_shape: IxDyn,
/// Regions proven to be zero-valued. The outermost map maps a axis index to
/// a set of usize tuples, indicating the half-open indices [low, high)
/// which are known to be zero in that axis.
/// TODO(@gussmith23) Might want to replace this with full partial eval
/// I realized while implementing this that I could just implement partial
/// eval, and it would do the same for me. I don't think it would be more
/// time efficient, though, and I'm even more certain that it wouldn't be
/// space efficient.
pub zero_regions: HashMap<Ix, BoolVecRangeSet>,
}
impl AccessPatternData {
/// Convenience method for getting the access pattern dimensions as a
/// vector.
/// ```
/// assert_eq!(
/// glenside::language::AccessPatternData {
/// shape: ndarray::IxDyn(&[1, 2, 3]),
/// item_shape: ndarray::IxDyn(&[4, 5]),
/// zero_regions: std::collections::HashMap::default()
/// }
/// .as_vec(),
/// vec![1, 2, 3, 4, 5]
/// );
/// ```
pub fn as_vec(&self) -> Vec<usize> {
self.shape
.slice()
.iter()
.chain(self.item_shape.slice().iter())
.cloned()
.collect::<Vec<_>>()
}
}
impl std::ops::Index<usize> for AccessPatternData {
type Output = ndarray::Ix;
fn index(&self, index: usize) -> &Self::Output {
if index < self.shape.ndim() {
&self.shape[index]
} else {
&self.item_shape[index - self.shape.ndim()]
}
}
}
impl std::ops::IndexMut<usize> for AccessPatternData {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
if index < self.shape.ndim() {
&mut self.shape[index]