forked from onnx/onnx-mlir
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathONNXOps.cpp
executable file
·5089 lines (4418 loc) · 189 KB
/
ONNXOps.cpp
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
/*
* SPDX-License-Identifier: Apache-2.0
*/
//===------------------ ONNXOps.cpp - ONNX Operations ---------------------===//
//
// Copyright 2019-2022 The IBM Research Authors.
//
// =============================================================================
//
// This file provides definition of ONNX dialect operations.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Traits.h"
#include "mlir/IR/Block.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/DialectImplementation.h"
#include "mlir/IR/IntegerSet.h"
#include "mlir/IR/Matchers.h"
#include "mlir/IR/OpImplementation.h"
#include "mlir/IR/PatternMatch.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/Support/FormatVariadic.h"
#include "src/Dialect/ONNX/ONNXOps.hpp"
#include "src/Dialect/ONNX/ONNXOpsHelper.hpp"
#include "src/Dialect/ONNX/ShapeInference/ONNXShapeHelper.hpp"
#include <string>
using namespace mlir;
using namespace mlir::OpTrait::util;
//===----------------------------------------------------------------------===//
// Tablegen Type Definitions
//===----------------------------------------------------------------------===//
// Explanation: the type implementation is used in dialect initialization.
// If ONNXTypes.cpp.inc is included in ONNXTypes.cpp, compilation error occurs.
#define GET_TYPEDEF_CLASSES
#include "src/Dialect/ONNX/ONNXTypes.cpp.inc"
//===----------------------------------------------------------------------===//
// ONNXDialect initialization
//===----------------------------------------------------------------------===//
/// Dialect creation, the instance will be owned by the context. This is the
/// point of registration of custom types and operations for the dialect.
void ONNXDialect::initialize() {
addOperations<
#define GET_OP_LIST
#include "src/Dialect/ONNX/ONNXOps.cpp.inc"
>();
addTypes<
#define GET_TYPEDEF_LIST
#include "src/Dialect/ONNX/ONNXTypes.cpp.inc"
>();
}
//===----------------------------------------------------------------------===//
// ONNX Helper functions for shape helpers
//===----------------------------------------------------------------------===//
// Handle shapes for operations with a single output.
template <class SHAPE_HELPER, class OP, class ADAPTOR>
LogicalResult shapeHelperInferShapes(OP *op, Value typeOper) {
SHAPE_HELPER shapeHelper(op);
ADAPTOR operandAdaptor(*op);
if (failed(shapeHelper.computeShape(operandAdaptor)))
return op->emitError("Failed to scan " + OP::getOperationName() +
" parameters successfully");
SmallVector<int64_t, 4> outputDims;
IndexExpr::getShape(shapeHelper.dimsForOutput(0), outputDims);
auto elementType = typeOper.getType().cast<ShapedType>().getElementType();
op->getResult().setType(RankedTensorType::get(outputDims, elementType));
return success();
}
// Handle shapes for operations with multiple outputs.
template <class SHAPE_HELPER, class OP, class ADAPTOR>
LogicalResult shapeHelperInferMultipleShapes(OP *op, Value typeOper) {
SHAPE_HELPER shapeHelper(op);
ADAPTOR operandAdaptor(*op);
if (failed(shapeHelper.computeShape(operandAdaptor)))
return op->emitError("Failed to scan " + OP::getOperationName() +
" parameters successfully");
SmallVector<int64_t, 4> outputDims;
IndexExpr::getShape(shapeHelper.dimsForOutput(0), outputDims);
auto elementType = typeOper.getType().cast<ShapedType>().getElementType();
for (unsigned int i = 0; i < op->getNumResults(); ++i) {
SmallVector<int64_t, 4> outputDims;
IndexExpr::getShape(shapeHelper.dimsForOutput(i), outputDims);
op->getResults()[i].setType(RankedTensorType::get(outputDims, elementType));
}
return success();
}
#define NOT_IMPLEMENTED_MESSAGE \
(getOperationName() + \
": is not supported at this time. Please open an issue on " \
"https://github.com/onnx/onnx-mlir and/or consider contribute code. " \
"Error encountered in shape inference.")
//===----------------------------------------------------------------------===//
// ONNX Helper functions
//===----------------------------------------------------------------------===//
// This method substitutes any uses of dimensions and symbols (e.g.
// dim#0 with dimReplacements[0]) in an affine map, simplifies the modified
// affine map, and returns an integer constant.
int64_t AffineMapIntConstant(Builder &builder, AffineMap map,
ArrayRef<int64_t> dimReplacements, ArrayRef<int64_t> symReplacements,
unsigned numResultDims, unsigned numResultSyms) {
// Prepare affine expressions.
SmallVector<AffineExpr, 4> dimExprs, symExprs;
for (int64_t dim : dimReplacements) {
AffineExpr exp = builder.getAffineConstantExpr(dim);
dimExprs.emplace_back(exp);
}
for (int64_t sym : symReplacements) {
AffineExpr exp = builder.getAffineConstantExpr(sym);
symExprs.emplace_back(exp);
}
// Replace all the affine map's arguments with real values and evaluate the
// map.
AffineMap replacedDimMap = map.replaceDimsAndSymbols(
dimExprs, symExprs, numResultDims, numResultSyms);
AffineMap simplifiedMap = simplifyAffineMap(replacedDimMap);
return simplifiedMap.getSingleConstantResult();
}
//===----------------------------------------------------------------------===//
// Get reduction type
//===----------------------------------------------------------------------===//
RankedTensorType getReductionOutputType(RankedTensorType operandTy,
Optional<ArrayAttr> axesAttrs, uint64_t keepdims) {
int64_t rank = operandTy.getRank();
SmallVector<int64_t, 4> axes;
if (axesAttrs != llvm::None) {
for (auto axisAttr : axesAttrs.getValue()) {
int64_t axis = axisAttr.cast<IntegerAttr>().getInt();
axis = axis >= 0 ? axis : (rank + axis);
assert(axis >= -rank && axis <= rank - 1);
if (std::find(axes.begin(), axes.end(), axis) == axes.end())
axes.emplace_back(axis);
}
} else {
for (decltype(rank) i = 0; i < rank; ++i) {
axes.emplace_back(i);
}
}
// Mark reduction axes.
SmallVector<bool, 4> isReductionAxis;
for (decltype(rank) i = 0; i < rank; ++i) {
if (std::find(axes.begin(), axes.end(), i) != axes.end())
isReductionAxis.emplace_back(true);
else
isReductionAxis.emplace_back(false);
}
// KeepDims
bool isKeepdims = (keepdims == 1) ? true : false;
SmallVector<int64_t, 4> dims;
for (decltype(rank) i = 0; i < rank; ++i) {
if (isReductionAxis[i]) {
if (isKeepdims)
dims.emplace_back(1); // reduction dimension
} else {
dims.emplace_back(operandTy.getShape()[i]);
}
}
return RankedTensorType::get(dims, operandTy.getElementType());
}
// Reduction with axes is from ConstantOp.
// Only ReduceSum call this function now.
static RankedTensorType getReductionOutputType(RankedTensorType operandTy,
DenseElementsAttr axesAttrs, uint64_t keepdims,
uint64_t noop_with_empty_axes) {
int64_t rank = operandTy.getRank();
SmallVector<int64_t, 4> axes;
if (axesAttrs) {
for (auto element : axesAttrs.getValues<IntegerAttr>()) {
int64_t axis = element.getInt();
if (axis < -rank || axis > rank - 1) {
return RankedTensorType();
}
axis = axis >= 0 ? axis : (rank + axis);
if (std::find(axes.begin(), axes.end(), axis) == axes.end())
axes.emplace_back(axis);
}
}
if (axes.size() == 0) {
if (!noop_with_empty_axes) {
for (decltype(rank) i = 0; i < rank; ++i) {
axes.emplace_back(i);
}
}
}
// Mark reduction axes.
SmallVector<bool, 4> isReductionAxis;
for (decltype(rank) i = 0; i < rank; ++i) {
if (std::find(axes.begin(), axes.end(), i) != axes.end())
isReductionAxis.emplace_back(true);
else
isReductionAxis.emplace_back(false);
}
// KeepDims
bool isKeepdims = (keepdims == 1) ? true : false;
SmallVector<int64_t, 4> dims;
for (decltype(rank) i = 0; i < rank; ++i) {
if (isReductionAxis[i]) {
if (isKeepdims)
dims.emplace_back(1); // reduction dimension
} else {
dims.emplace_back(operandTy.getShape()[i]);
}
}
return RankedTensorType::get(dims, operandTy.getElementType());
}
//===----------------------------------------------------------------------===//
// Support function that computes default values for dilations.
//===----------------------------------------------------------------------===//
template <class T>
static LogicalResult processConvDilationParam(
T *op, Optional<ArrayAttr> kernelShape) {
auto builder = mlir::Builder(op->getContext());
auto kernelRank = ArrayAttrSize(kernelShape);
auto dilationsOpt = op->dilations();
if (dilationsOpt.hasValue()) {
if (ArrayAttrSize(dilationsOpt) != kernelRank) {
return op->emitError("dilation rank is not the same as the spatial rank");
}
// Test values to be greater than 0.
for (decltype(kernelRank) i = 0; i < kernelRank; ++i) {
if (ArrayAttrIntVal(dilationsOpt, i) < 1) {
return op->emitError("dilation value must be nonzero positive");
}
}
} else {
// Default dilatation is needed, all dimensions init with 1.
SmallVector<int64_t, 4> defaultVals(kernelRank, 1);
// Convert to ArrayRef, then build attribute, then store attribute.
ArrayRef<int64_t> defaultRefs(defaultVals);
op->dilationsAttr(builder.getI64ArrayAttr(defaultRefs));
}
return success();
}
//===----------------------------------------------------------------------===//
// Support function that computes default values for strides.
//===----------------------------------------------------------------------===//
template <class T>
static LogicalResult processConvStrideParam(
T *op, Optional<ArrayAttr> kernelShape) {
auto builder = mlir::Builder(op->getContext());
auto kernelRank = ArrayAttrSize(kernelShape);
auto stridesOpt = op->strides();
if (stridesOpt.hasValue()) {
if (ArrayAttrSize(stridesOpt) != kernelRank)
return op->emitError("strides rank is not the same as the spatial rank");
// Check values to be greater than 0.
for (decltype(kernelRank) i = 0; i < kernelRank; ++i) {
if (ArrayAttrIntVal(stridesOpt, i) < 1)
return op->emitError("strides value must be nonzero positive");
}
} else {
// Default stride is needed, all dimensions init with 1.
SmallVector<int64_t, 4> defaultVals(kernelRank, 1);
// Convert to ArrayRef, then build attribute, then store attribute.
ArrayRef<int64_t> defaultRefs(defaultVals);
op->stridesAttr(builder.getI64ArrayAttr(defaultRefs));
}
return success();
}
//===----------------------------------------------------------------------===//
// Support function that computes default values for pads.
//===----------------------------------------------------------------------===//
template <class T>
static LogicalResult processConvPadParam(T *op, ArrayRef<int64_t> inputShape,
Optional<ArrayAttr> kernelShape, Optional<ArrayAttr> stridesOpt,
Optional<ArrayAttr> dilationsOpt = llvm::None) {
auto builder = mlir::Builder(op->getContext());
auto inputRank = inputShape.size();
auto kernelRank = ArrayAttrSize(kernelShape);
auto kernelOffset = inputRank - kernelRank;
// Try to find padding, getting auto_pad attribute first.
auto autoPad = op->auto_pad();
// And then investigate the various different cases. Prefill pad values with
// zeros, the most common case.
SmallVector<int64_t, 4> actualPads(2 * kernelRank, 0);
bool updatedPad = false;
if (autoPad == "NOTSET") {
auto padsOpt = op->pads();
if (padsOpt.hasValue()) {
// Only option where pads are not updated. Pads consists of two entries
// for each spatial axis.
if (ArrayAttrSize(padsOpt) != 2 * kernelRank) {
return op->emitError("pads rank is not twice the spatial rank");
}
// Check values, pads cannot be negative.
for (decltype(kernelRank) i = 0; i < 2 * kernelRank; ++i) {
if (ArrayAttrIntVal(padsOpt, i) < 0) {
return op->emitError("pads value must be nonnegative");
}
}
} else {
// We have notset with no pads, they are assumed to be all zero.
updatedPad = true;
}
} else if (autoPad == "SAME_UPPER" || autoPad == "SAME_LOWER") {
// Reload dilation and strides as they may have gotten default values.
updatedPad = true;
int64_t dilationVal = 1;
for (decltype(kernelRank) i = 0; i < kernelRank; ++i) {
auto inputSize = inputShape[kernelOffset + i];
if (inputSize < 0)
return op->emitError("Conv Pads defined as SAME_UPPER or SAME_LOWER "
"requires compile time X sizes");
auto kernelSize = ArrayAttrIntVal(kernelShape, i);
if (dilationsOpt.hasValue())
dilationVal = ArrayAttrIntVal(dilationsOpt, i);
auto strideVal = ArrayAttrIntVal(stridesOpt, i);
// Output size is input size divided by stride. When stride is 1, then
// input and output are the same size, which is the usual case. When
// stride is greater than 1, take the ceil to be sure to have each input
// value used, as padding will be used to fill the gaps.
int64_t outputSize = ceil((1.0 * inputSize) / (1.0 * strideVal));
// Formula is from ONNX MaxPool, and can be explained as follows. Pads
// is the difference between the needed values for the computations,
// minus the input values. The needed values for the computation is the
// effective side of the kernel plus the number of times we jump to the
// next kernel. Number of time we jump is (outputSize - 1). That number
// is multiplied with the size of the jump, namely strideVal. Now for
// the effective kernel size. It is the kernelSize + the number of times
// we have dilation holes time the dilation. The number of dilation
// holes is (kernelSize -1). Thus the effective size is "kernelSize +
// (kernelSize-1)*dilation". This simplifies to "(kernelSize
// -1)*dilation + 1".
auto sumOfPad = (outputSize - 1) * strideVal +
((kernelSize - 1) * dilationVal + 1) - inputSize;
// Pad values are assumed equal on both size, at half the total value.
actualPads[i] = actualPads[kernelRank + i] = sumOfPad / 2;
// But if the total pad value is odd, we add 1 to begining or end
// depending on autoPad value.
if (sumOfPad % 2 != 0) {
if (autoPad == "SAME_UPPER") {
actualPads[kernelRank + i] += 1;
} else {
actualPads[i] += 1;
}
}
}
} else if (autoPad == "VALID") {
// No pad, default value was set to zero, we are all set.
updatedPad = true;
} else {
return op->emitError("auto_pad of unknown / unsupported value");
}
// Set pads values in attributes, if it is needed.
if (updatedPad) {
ArrayRef<int64_t> defaultRefs(actualPads);
op->padsAttr(builder.getI64ArrayAttr(defaultRefs));
}
// In all cases now, the actual pad values are found in the pads attribute.
op->auto_padAttr(builder.getStringAttr("NOTSET"));
return success();
}
//===----------------------------------------------------------------------===//
// Support function computing default values for dilations, strides, and pads.
//===----------------------------------------------------------------------===//
template <class T>
static LogicalResult processConvTypeParams(T *op, Value inputOperand) {
// 1) Get shape of input. Shape is not guaranteed to be compile time constant.
auto inputShape = inputOperand.getType().cast<RankedTensorType>().getShape();
// 2) Get kernel_shape attribute. They were previously computed. At this time,
// they are guranteed to be compile time constant.
auto kernelShape = op->kernel_shape();
// Dilation. It is compile time constants (filled to default 1 value if not
// explicitely given as input).
LogicalResult res = processConvDilationParam<T>(op, kernelShape);
if (failed(res))
return res;
auto dilationsOpt = op->dilations();
// Strides. It is compile time constants (filled to default 1 value if not
// explicitely given as input).
res = processConvStrideParam<T>(op, kernelShape);
if (failed(res))
return res;
auto stridesOpt = op->strides();
// Pads.
return processConvPadParam<T>(
op, inputShape, kernelShape, stridesOpt, dilationsOpt);
}
//===----------------------------------------------------------------------===//
// Compute spatial dimensions given dilations, strides, pads, and ceil mode.
//===----------------------------------------------------------------------===//
static void insertConvSpatialDim(SmallVector<int64_t, 4> *outputDims,
Builder &builder, ArrayRef<int64_t> xShape, Optional<ArrayAttr> kernelShape,
Optional<ArrayAttr> padsOpt, Optional<ArrayAttr> stridesOpt,
Optional<ArrayAttr> dilationsOpt = llvm::None, bool ceilMode = false) {
auto spatialRank = ArrayAttrSize(kernelShape);
auto spatialOffset = xShape.size() - spatialRank;
// Get an affine map to compute the output dimension.
AffineMap dimMap = getConvDimMap(builder, ceilMode);
for (unsigned int i = 0; i < spatialRank; ++i) {
int64_t res = -1;
if (xShape[spatialOffset + i] != -1) {
auto inputSize = xShape[spatialOffset + i];
auto kernelSize = ArrayAttrIntVal(kernelShape, i);
auto sumOfPads = ArrayAttrIntVal(padsOpt, i) +
ArrayAttrIntVal(padsOpt, spatialRank + i);
auto strideVal = ArrayAttrIntVal(stridesOpt, i);
int64_t dilationVal = 1;
if (dilationsOpt.hasValue())
dilationVal = ArrayAttrIntVal(dilationsOpt, i);
res = AffineMapIntConstant(builder, dimMap, {inputSize},
{kernelSize, sumOfPads, strideVal, dilationVal}, 1, 4);
}
outputDims->emplace_back(res);
}
}
//===----------------------------------------------------------------------===//
// Support function that infers shape for RNN operations.
//===----------------------------------------------------------------------===//
template <typename T>
static LogicalResult RNNShapeInference(T *op) {
Value X = op->X();
Value W = op->W();
Value R = op->R();
if (!X.getType().isa<RankedTensorType>() ||
!W.getType().isa<RankedTensorType>() ||
!R.getType().isa<RankedTensorType>()) {
return success();
}
auto xTy = X.getType().cast<RankedTensorType>();
auto elementType = xTy.getElementType();
// xShape :: [seq_length, batch_size, input_size]
auto xShape = xTy.getShape();
// wShape :: [num_directions, 4*hidden_size, input_size]
auto wShape = W.getType().cast<RankedTensorType>().getShape();
// rShape :: [num_directions, 4*hidden_size, hidden_size]
auto rShape = R.getType().cast<RankedTensorType>().getShape();
if (xShape.size() != 3) {
return op->emitError("The first input tensor must have rank 3");
}
if (wShape.size() != 3) {
return op->emitError("The second input tensor must have rank 3");
}
if (rShape.size() != 3) {
return op->emitError("The third input tensor must have rank 3");
}
// Get sequence length, batch size and input size.
auto sequenceLength = xShape[0];
auto batchSize = xShape[1];
// Get hidden size from hidden_size attribute.
int64_t hiddenSize = -1;
if (op->hidden_size().hasValue()) {
hiddenSize = op->hidden_size().getValue();
} else {
// Infer hidden_size from wShape and rShape if possible.
if (rShape[2] != -1)
hiddenSize = rShape[2];
else if (rShape[1] != -1)
hiddenSize = rShape[1] / 4;
else if (wShape[1] != -1)
hiddenSize = wShape[1] / 4;
// Update hidden_size attribute.
if (hiddenSize != -1) {
auto builder = mlir::Builder(op->getContext());
auto hiddenSizeAttr =
IntegerAttr::get(builder.getIntegerType(64, /*isSigned=*/true),
APInt(64, /*value=*/hiddenSize, /*isSigned=*/true));
op->hidden_sizeAttr(hiddenSizeAttr);
}
}
// Get direction.
int numDirection;
if ((op->direction() == "forward") || (op->direction() == "reverse"))
numDirection = 1;
else if (op->direction() == "bidirectional")
numDirection = 2;
else
numDirection = -1;
if (numDirection == -1) {
return op->emitError(
"direction attribute must be one of the strings: forward, "
"reverse, and bidirectional");
}
// Set result types.
unsigned numOfResults = op->getNumResults();
if (numOfResults > 0) {
// Y :: [seq_length, num_directions, batch_size, hidden_size]
Type yTy = op->getResults()[0].getType();
if (!yTy.isa<NoneType>()) {
yTy = RankedTensorType::get(
{sequenceLength, numDirection, batchSize, hiddenSize}, elementType);
op->getResults()[0].setType(yTy);
}
}
if (numOfResults > 1) {
// Y_h :: [num_directions, batch_size, hidden_size]
Type yhTy = op->getResults()[1].getType();
if (!yhTy.isa<NoneType>()) {
yhTy = RankedTensorType::get(
{numDirection, batchSize, hiddenSize}, elementType);
op->getResults()[1].setType(yhTy);
}
}
if (numOfResults > 2) {
// Y_c :: [num_directions, batch_size, hidden_size]
Type ycTy = op->getResults()[2].getType();
if (!ycTy.isa<NoneType>()) {
ycTy = RankedTensorType::get(
{numDirection, batchSize, hiddenSize}, elementType);
op->getResults()[2].setType(ycTy);
}
}
return success();
}
static void insertConvTransposeSpatialDim(SmallVectorImpl<int64_t> &outputDims,
ArrayRef<int64_t> xShape, Optional<ArrayAttr> kernelShape,
Optional<ArrayAttr> padsOpt, Optional<ArrayAttr> stridesOpt,
Optional<ArrayAttr> outputPadsOpt, Optional<ArrayAttr> outputShapeOpt,
Optional<ArrayAttr> dilationsOpt = llvm::None, bool ceilMode = false) {
auto xRank = xShape.size();
auto spatialRank = ArrayAttrSize(kernelShape);
auto spatialOffset = xRank - spatialRank;
int64_t dilationVal = 1;
int64_t outputPadsVal = 0;
// output_shape[i] = stride[i] * (input_size[i] - 1) + output_padding[i] +
// ((kernel_shape[i] - 1) * dilations[i] + 1) - pads[start_i] - pads[end_i]
for (unsigned int i = 0; i < spatialRank; ++i) {
auto inputSize = xShape[spatialOffset + i];
auto sumOfPads =
ArrayAttrIntVal(padsOpt, i) + ArrayAttrIntVal(padsOpt, spatialRank + i);
auto kernelSize = ArrayAttrIntVal(kernelShape, i);
if (dilationsOpt.hasValue())
dilationVal = ArrayAttrIntVal(dilationsOpt, i);
auto strideVal = ArrayAttrIntVal(stridesOpt, i);
if (outputPadsOpt.hasValue())
outputPadsVal = ArrayAttrIntVal(outputPadsOpt, i);
// Number of useful values: input plus pad - effective size of kernel (see
// processConvTypeParams comments to see how this value is derived).
int64_t res = strideVal * (inputSize - 1) + outputPadsVal +
((kernelSize - 1) * dilationVal + 1) - sumOfPads;
outputDims.emplace_back(res);
}
}
//===----------------------------------------------------------------------===//
// ONNXEntryPointOp
//===----------------------------------------------------------------------===//
void ONNXEntryPointOp::build(mlir::OpBuilder &builder,
mlir::OperationState &state, mlir::FuncOp function, int numInputs,
int numOutputs, std::string signature) {
state.addAttribute(ONNXEntryPointOp::getEntryPointFuncAttrName(),
SymbolRefAttr::get(function));
state.addAttribute(ONNXEntryPointOp::getNumInputsAttrName(),
builder.getI32IntegerAttr(numInputs));
state.addAttribute(ONNXEntryPointOp::getNumOutputsAttrName(),
builder.getI32IntegerAttr(numOutputs));
state.addAttribute(ONNXEntryPointOp::getSignatureAttrName(),
builder.getStringAttr(signature));
}
ONNXEntryPointOp ONNXEntryPointOp::create(mlir::Location location,
mlir::FuncOp &func, int numInputs, int numOutputs, std::string signature) {
mlir::OperationState state(location, "onnx.EntryPoint");
OpBuilder builder(location->getContext());
mlir::ONNXEntryPointOp::build(
builder, state, func, numInputs, numOutputs, signature);
Operation *op = mlir::Operation::create(state);
auto onnxEntryOp = llvm::cast<mlir::ONNXEntryPointOp>(op);
return onnxEntryOp;
}
//===----------------------------------------------------------------------===//
// ONNXNoneOp
//===----------------------------------------------------------------------===//
OpFoldResult ONNXNoneOp::fold(ArrayRef<Attribute> operands) {
return valueAttr();
}
//===----------------------------------------------------------------------===//
// ONNX Operations
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Exp
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXExpOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXExpOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Atan
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAtanOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAtanOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Tan
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXTanOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXTanOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Tanh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXTanhOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXTanhOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Sin
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXSinOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXSinOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Sinh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXSinhOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXSinhOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Cosh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXCoshOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXCoshOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Cos
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXCosOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXCosOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Acos
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAcosOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAcosOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Acosh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAcoshOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAcoshOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Asin
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAsinOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAsinOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Asinh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAsinhOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAsinhOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Atanh
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXAtanhOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXAtanhOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Log
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXLogOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXLogOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// HardSigmoid
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXHardSigmoidOp. This method is required by
/// the shape inference interface.
LogicalResult ONNXHardSigmoidOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Sigmoid
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXSigmoidOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXSigmoidOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Elu
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXEluOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXEluOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Relu
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXReluOp. This method is required by the
/// shape inference interface.
LogicalResult ONNXReluOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// LeakyRelu
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXLeakyReluOp. This method is required by
/// the shape inference interface.
LogicalResult ONNXLeakyReluOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
//===----------------------------------------------------------------------===//
// Selu
//===----------------------------------------------------------------------===//
/// Infer the output shape of the ONNXSeluOp. This method is required by
/// the shape inference interface.
LogicalResult ONNXSeluOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
getResult().setType(getOperand().getType());
return success();
}
// Sequence related operations
// The general form for seq is seq<tensor<*xT>>
// Tensors will be add to or removed from a seq dynamically.
// The tensor type in a seq should be a summary of all the tensor type in
// the seq.
// It is possible seq<tensor<*xT>> can be refined into seq<RankedTensor>,
// or even seq<StaticShapedTensor> if all the tensors have common shape info
// It is important to refine the type for seq in onnx-mlir because static
// type is used. If seq of unranked tensor remains, onnx-mlir can not handle
// the unranked tensor retrieved from the seq.
// Here is the rules for shape inferences of seq-related ops:
// * A seq is started empty as the result of SequenceEmpty. We can track this
// property with a tag in seq type or along dataflow.
// * When the an element is added, we can merge its shape with that in seq.
// * when an element is removed from seq, the seq becomes empty if it is the
// last tenor in the seq (known statically).
// Since the seq is usually used as a parameter of a graph (e.g. for LoopOp),
// shape inference for region may need improvement.
//===----------------------------------------------------------------------===//
// SequenceInsertOp
//===----------------------------------------------------------------------===//
LogicalResult ONNXSequenceInsertOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
SeqType seqType = input_sequence().getType().dyn_cast<mlir::SeqType>();
ShapedType tensorType = tensor().getType().dyn_cast<ShapedType>();
ShapedType seqTensorType = seqType.getElementType().cast<ShapedType>();
// Merge the tensor type for the seq and the inserted tensor
// Pick the weaker attr: known dim > unknown dim > unranked
// If inference gets an unranked tensor, no need to update the result
// When the input seq is empty, inherit the tensor type
if (seqType.getLength() == 0) {
getResult().setType(SeqType::get(tensorType, 1));
return success();
}
auto newLength = seqType.getLength() == -1 ? -1 : seqType.getLength() + 1;
// When one of the tensor is unranked
if (!tensorType.hasRank()) {
getResult().setType(SeqType::get(tensorType, newLength));
return success();
}
if (!seqTensorType.hasRank()) {
getResult().setType(SeqType::get(seqTensorType, newLength));
return success();
}
// Merge when both are ranked
auto seqShape = seqTensorType.getShape();
auto seqRank = seqTensorType.getRank();
if (seqRank == -1)
return success();
auto tensorShape = tensorType.getShape();
auto tensorRank = tensorType.getRank();
if (tensorRank != seqRank)
return success();
SmallVector<int64_t, 4> dims;
for (auto i = 0; i < tensorRank; i++) {
dims.emplace_back(seqShape[i] != tensorShape[i] ? -1 : tensorShape[i]);
}
getResult().setType(SeqType::get(
mlir::RankedTensorType::get(dims, tensorType.getElementType()),
newLength));
return success();
}
LogicalResult ONNXSequenceInsertOp::verify() {
ONNXSequenceInsertOpAdaptor operandAdaptor =
ONNXSequenceInsertOpAdaptor(*this);
// These cast should be guaranteed by default verifier
Type seqElementType = operandAdaptor.input_sequence()
.getType()
.dyn_cast<mlir::SeqType>()
.getElementType();
Type elementType1 = seqElementType.dyn_cast<ShapedType>().getElementType();
ShapedType insertType =
operandAdaptor.tensor().getType().dyn_cast<ShapedType>();
Type elementType2 = insertType.getElementType();
if (elementType1 != elementType2) {
return emitError("Element types of the tensor in seqence and input "
"have to be the same");
}
return success();
}
//===----------------------------------------------------------------------===//
// ConcatFromSequenceOp
//===----------------------------------------------------------------------===//
LogicalResult ONNXConcatFromSequenceOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
return success();
}
//===----------------------------------------------------------------------===//
// SequenceAtOp
//===----------------------------------------------------------------------===//
LogicalResult ONNXSequenceAtOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
auto outputType = getResult().getType();
auto inputElementType =
input_sequence().getType().cast<SeqType>().getElementType();
if (!inputElementType.isa<UnrankedTensorType>() &&
outputType.isa<UnrankedTensorType>()) {
getResult().setType(inputElementType);
}
return success();
}
//===----------------------------------------------------------------------===//
// SequenceConstructOp
//===----------------------------------------------------------------------===//
LogicalResult ONNXSequenceConstructOp::inferShapes(
std::function<void(mlir::Region &)> doShapeInference) {
return success();
}
//===----------------------------------------------------------------------===//
// SequenceEmptyOp
//===----------------------------------------------------------------------===//
LogicalResult ONNXSequenceEmptyOp::verify() {
// For the Optional dtypeAttr, the default type is F32
auto builder = mlir::OpBuilder(getContext());
Type elementType;
if (dtypeAttr()) {
elementType = convertONNXTypeToMLIRType(builder,
(onnx::TensorProto_DataType)dtypeAttr().getValue().getSExtValue());
} else {
elementType = builder.getF32Type();
}
// Get element type for seq from the output
ShapedType outputSeqElementType =
getResult().getType().cast<SeqType>().getElementType();
if (outputSeqElementType.getElementType() != elementType)
return emitError("SequenceEmpty dtype() does not match the output type");
return success();