-
Notifications
You must be signed in to change notification settings - Fork 663
Expand file tree
/
Copy pathTorchToTosa.cpp
More file actions
10761 lines (9092 loc) · 418 KB
/
TorchToTosa.cpp
File metadata and controls
10761 lines (9092 loc) · 418 KB
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
//===----------------------------------------------------------------------===//
////
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// Also available under a BSD-style license. See LICENSE.
//
//===----------------------------------------------------------------------===//
#include "torch-mlir/Conversion/TorchToTosa/TorchToTosa.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/Quant/IR/QuantTypes.h"
#include "mlir/Dialect/Tensor/IR/Tensor.h"
#include "mlir/Dialect/Tosa/IR/TosaOps.h"
#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h"
#include "mlir/IR/DialectResourceBlobManager.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/DialectConversion.h"
#include "torch-mlir/Conversion/Passes.h"
#include "torch-mlir/Conversion/TorchToTosa/TosaLegalizeCommon.h"
#include "torch-mlir/Conversion/TorchToTosa/TosaLegalizeUtils.h"
#include "torch-mlir/Conversion/Utils/Utils.h"
#include "torch-mlir/Dialect/Torch/IR/TorchDialect.h"
#include "torch-mlir/Dialect/Torch/IR/TorchOps.h"
#include "torch-mlir/Dialect/Torch/IR/TorchTypes.h"
#include "torch-mlir/Dialect/Torch/Utils/Utils.h"
#include "torch-mlir/Dialect/TorchConversion/Transforms/BackendTypeConversion.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/TypeSwitch.h"
#include <cmath>
#include <numeric>
#include <optional>
#include <random>
#include <tuple>
#include <type_traits>
#include "mlir/Dialect/Tosa/Utils/QuantUtils.h"
using namespace mlir;
using namespace mlir::torch;
using namespace mlir::torch::Torch;
namespace mlir::torch {
#define GEN_PASS_DEF_CONVERTTORCHTOTOSA
#include "torch-mlir/Conversion/Passes.h.inc"
namespace {
// Runs an in-place inclusive prefix sum along the middle dimension (K) of
// `running` using a binary lifting scheme. The input must have shape [N, K, C].
// After the loop, `running` holds the cumsum result with respect to axis=1.
static Value emitInclusiveScanByPowersOfTwo(Value running,
ConversionPatternRewriter &rewriter,
Location loc) {
auto nkcTy = cast<RankedTensorType>(running.getType());
SmallVector<int64_t> nkcShape(makeShapeTorchCompatible(nkcTy.getShape()));
int64_t outer = nkcShape[0];
int64_t dimSize = nkcShape[1];
int64_t inner = nkcShape[2];
auto zeroConstOr =
tosa::createZeroPointTensor(rewriter, loc, nkcTy.getElementType(), 0);
if (!zeroConstOr)
return nullptr;
Value zeroConst = *zeroConstOr;
SmallVector<int64_t, 3> sliceStart(3, 0);
SmallVector<int64_t, 3> sliceSize = {outer, dimSize, inner};
Value sliceStartConstShape =
tosa::getTosaConstShape(rewriter, loc, sliceStart);
Value sliceSizeConstShape = tosa::getTosaConstShape(rewriter, loc, sliceSize);
for (int64_t offset = 1; offset < dimSize; offset <<= 1) {
SmallVector<int64_t, 6> padSpec = {0, 0, offset, 0, 0, 0};
auto padShape = tosa::getTosaConstShape(rewriter, loc, padSpec);
SmallVector<int64_t> paddedShape = {outer, dimSize + offset, inner};
auto paddedTy = RankedTensorType::get(makeShapeLLVMCompatible(paddedShape),
nkcTy.getElementType());
Value padded = tosa::PadOp::create(rewriter, loc, paddedTy, running,
padShape, zeroConst)
.getResult();
Value shifted =
tosa::SliceOp::create(rewriter, loc, nkcTy, padded,
sliceStartConstShape, sliceSizeConstShape)
.getResult();
running =
tosa::AddOp::create(rewriter, loc, nkcTy, running, shifted).getResult();
}
return running;
}
static SmallVector<int64_t> permuteShape(ArrayRef<int64_t> originalShape,
ArrayRef<int32_t> permutation) {
SmallVector<int64_t> result;
result.reserve(permutation.size());
for (int32_t dim : permutation)
result.push_back(originalShape[dim]);
return result;
}
struct ZeroInsertionResult {
Value value;
bool trimmedTail;
};
static FailureOr<ZeroInsertionResult>
insertZerosAlongAxis(Value input, int axis, int64_t stride,
ConversionPatternRewriter &rewriter, Location loc) {
if (stride == 1)
return ZeroInsertionResult{input, /*trimmedTail=*/true};
if (stride <= 0)
return failure();
auto inputType = dyn_cast<RankedTensorType>(input.getType());
if (!inputType)
return failure();
auto elementType = inputType.getElementType();
// Work on a mutable copy of the shape since we insert/drop singleton dims
// and update the axis extent below.
SmallVector<int64_t> shape(inputType.getShape().begin(),
inputType.getShape().end());
if (axis < 0 || axis >= static_cast<int>(shape.size()))
return failure();
int64_t dim = shape[axis];
// The slice at the end requires a static trip count, so we can only upsample
// axes with a known length when we later trim the padded tail.
if (stride > 1 && ShapedType::isDynamic(dim))
return failure();
SmallVector<int64_t> expandedShape;
expandedShape.reserve(shape.size() + 1);
for (int i = 0; i < static_cast<int>(shape.size()); ++i) {
expandedShape.push_back(shape[i]);
if (i == axis)
expandedShape.push_back(1);
}
auto expandedType = RankedTensorType::get(
makeShapeLLVMCompatible(expandedShape), elementType);
Value reshapeToExpanded = tosa::ReshapeOp::create(
rewriter, loc, expandedType, input,
tosa::getTosaConstShape(rewriter, loc, expandedShape));
SmallVector<int64_t> paddedShape = expandedShape;
paddedShape[axis + 1] = stride;
SmallVector<int64_t> pads(2 * expandedShape.size(), 0);
pads[2 * (axis + 1) + 1] = stride - 1;
Value padsConst = tosa::getTosaConstShape(rewriter, loc, pads);
// Torch IR does not convey quantization params via tensor element types, so
// we use a literal zero here. Quantized frontends will insert the necessary
// rescale ops before we hit this lowering.
auto padValueOr =
tosa::createZeroPointTensor(rewriter, loc, elementType, /*zeroPoint=*/0);
if (!padValueOr.has_value())
return failure();
Value padValue = *padValueOr;
auto paddedType =
RankedTensorType::get(makeShapeLLVMCompatible(paddedShape), elementType);
Value padded = tosa::PadOp::create(rewriter, loc, paddedType,
reshapeToExpanded, padsConst, padValue);
SmallVector<int64_t> collapsedShape = shape;
collapsedShape[axis] =
ShapedType::isDynamic(dim) ? ShapedType::kDynamic : dim * stride;
auto collapsedType = RankedTensorType::get(
makeShapeLLVMCompatible(collapsedShape), elementType);
Value result = tosa::ReshapeOp::create(
rewriter, loc, collapsedType, padded,
tosa::getTosaConstShape(rewriter, loc, collapsedShape));
bool trimmedTail = stride > 1;
if (stride > 1) {
// Padding adds (stride - 1) zeros after every element, so the collapsed
// tensor has an extra run of zeros at the tail. Slice those zeros to get
// the `(dim - 1) * stride + 1` elements that PyTorch expects.
int64_t trimmedLength = (dim - 1) * stride + 1;
if (trimmedLength < collapsedShape[axis]) {
SmallVector<int64_t> startIndices(collapsedShape.size(), 0);
SmallVector<int64_t> sliceSizes = collapsedShape;
sliceSizes[axis] = trimmedLength;
SmallVector<int64_t> trimmedShape =
llvm::to_vector(collapsedType.getShape());
trimmedShape[axis] = trimmedLength;
auto trimmedType = RankedTensorType::get(
makeShapeLLVMCompatible(trimmedShape), elementType);
result = tosa::SliceOp::create(
rewriter, loc, trimmedType, result,
tosa::getTosaConstShape(rewriter, loc, startIndices),
tosa::getTosaConstShape(rewriter, loc, sliceSizes));
}
trimmedTail = true;
}
return ZeroInsertionResult{result, trimmedTail};
}
static LogicalResult
getTorchToTosaPermutations(Location loc, int64_t rank,
SmallVectorImpl<int32_t> &torchToTosa,
SmallVectorImpl<int32_t> &tosaToTorch) {
if (rank < 3)
return emitError(loc) << "expected convolution tensor rank >= 3, got "
<< rank;
torchToTosa.clear();
tosaToTorch.clear();
torchToTosa.push_back(0); // batch dim stays first
for (int64_t dim = 2; dim < rank; ++dim)
torchToTosa.push_back(dim); // spatial dims in order
torchToTosa.push_back(1); // channel moves to last position
tosaToTorch.resize(torchToTosa.size());
for (auto pair : llvm::enumerate(torchToTosa))
tosaToTorch[pair.value()] = pair.index();
return success();
}
static LogicalResult
getTorchConvWeightPermutation(Location loc, int64_t rank, bool isTransposed,
SmallVectorImpl<int32_t> &permutation) {
if (rank < 3)
return emitError(loc) << "expected convolution weight rank >= 3, got "
<< rank;
permutation.clear();
if (!isTransposed) {
// Torch weight layout: [O, I, spatial...]; TOSA expects [O, spatial..., I].
permutation.push_back(0);
for (int64_t dim = 2; dim < rank; ++dim)
permutation.push_back(dim);
permutation.push_back(1);
} else {
// Transposed layout: [I, O, spatial...] -> [O, spatial..., I].
permutation.push_back(1);
for (int64_t dim = 2; dim < rank; ++dim)
permutation.push_back(dim);
permutation.push_back(0);
}
return success();
}
// Base class for all Torch-to-TOSA conversion patterns.
//
// It enforces the common checks that should be performed for legalizing any
// torch op to tosa. Currently we check for : no input tensor operand may have
// zero-sized dimension. TOSA does not support zero-dimension tensors, so we
// must reject such Torch IR before attempting to lower to TOSA.
//
// Subclasses should implement `matchAndRewriteImpl` instead of
// `matchAndRewrite`. The base `matchAndRewrite` is final and performs the
// common pre-check before delegating.
template <typename AtenOpT>
class TorchToTosaOpConversionPattern : public OpConversionPattern<AtenOpT> {
public:
using OpConversionPattern<AtenOpT>::OpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewrite(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const final {
// Pre-check: all tensor operands and outputs must have no zero-sized
// dimensions.
for (auto v : adaptor.getOperands()) {
auto rankedInputType = dyn_cast<RankedTensorType>(v.getType());
if (rankedInputType && mlir::tosa::typeHasZeroDim(rankedInputType)) {
return rewriter.notifyMatchFailure(
op,
"TOSA lowering does not support input tensors with a zero-sized "
"dimension");
}
}
// not all adaptors have results, instead get the result from the op
// directly
const TypeConverter *typeConverter = this->getTypeConverter();
for (auto res : op->getResults()) {
auto rankedOutputType =
dyn_cast<RankedTensorType>(typeConverter->convertType(res.getType()));
if (rankedOutputType && mlir::tosa::typeHasZeroDim(rankedOutputType)) {
return rewriter.notifyMatchFailure(
op,
"TOSA lowering does not support output tensors with a zero-sized "
"dimension");
}
}
return matchAndRewriteImpl(op, adaptor, rewriter);
}
protected:
virtual LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const = 0;
};
// These legalizations are for unary ops with promoting input to floating-point
// datatypes only. There is no supported quantized integer mode for these.
template <typename AtenOpT, typename TosaOpT>
class ConvertAtenUnaryPromoteToFPOp
: public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Value self = adaptor.getSelf();
auto selfTy = cast<TensorType>(self.getType());
if (!selfTy)
return rewriter.notifyMatchFailure(op,
"Only Tensor types supported in TOSA");
auto resultTy = dyn_cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
if (!isa<mlir::FloatType>(resultTy.getElementType()))
return rewriter.notifyMatchFailure(
op, "Only floating-point datatype result types are supported");
// Non floating point inputs are not supported in TOSA so we cast the input
// to result type
if (!isa<mlir::FloatType>(selfTy.getElementType()))
self = tosa::tosaCastTensorToType(rewriter, self, resultTy).value();
rewriter.replaceOpWithNewOp<TosaOpT>(op, resultTy, self);
return success();
}
};
// These unary op legalizations are identical for floating-point
// or quantized types
template <typename AtenOpT, typename TosaOpT>
class ConvertAtenUnaryOp : public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
auto self = adaptor.getSelf();
auto outType = dyn_cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
self = tosa::tosaCastTensorToType(rewriter, self, outType).value();
if constexpr (std::is_same_v<AtenOpT, AtenBitwiseNotOp>) {
if (auto intTy = dyn_cast<IntegerType>(outType.getElementType())) {
if (intTy.getWidth() == 1) {
rewriter.replaceOpWithNewOp<tosa::LogicalNotOp>(op, outType, self);
return success();
}
}
// otherwise fall through to standard emission
}
rewriter.replaceOpWithNewOp<TosaOpT>(op, outType, self);
return success();
}
};
// These binary op legalizations are identical for floating-point
// or quantized types
template <typename AtenOpT, typename TosaOpT>
class ConvertAtenBinaryOp : public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Value lhs = adaptor.getSelf();
auto lhsTy = cast<TensorType>(lhs.getType());
Value rhs = adaptor.getOther();
auto rhsTy = cast<TensorType>(rhs.getType());
if (!lhsTy || !rhsTy)
return rewriter.notifyMatchFailure(op,
"Only Tensor types supported in TOSA");
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, rhs).failed())
return rewriter.notifyMatchFailure(
op, "Failed to equalize ranks among operands and result");
auto outTy = cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
Value binaryOp;
if constexpr (std::is_same<AtenOpT, AtenBitwiseRightShiftTensorOp>()) {
// TOSA ArithmeticRightShiftOp has a round parameter.
binaryOp = TosaOpT::create(rewriter, op->getLoc(), outTy, lhs, rhs,
/*round=*/false);
} else if constexpr (std::is_same<TosaOpT, tosa::MaximumOp>() ||
std::is_same<TosaOpT, tosa::MinimumOp>()) {
lhs = tosa::tosaCastTensorToType(rewriter, lhs, outTy).value();
rhs = tosa::tosaCastTensorToType(rewriter, rhs, outTy).value();
// Use default NaN Propagation mode "PROPAGATE" for tosa.maximum and
// tosa.minimum
binaryOp = TosaOpT::create(
rewriter, op->getLoc(), outTy, lhs, rhs,
/*nan_mode=*/
tosa::NanPropagationModeAttr::get(
rewriter.getContext(), tosa::NanPropagationMode::PROPAGATE));
} else {
binaryOp =
tosa::createBinaryOpAndCast<TosaOpT>(rewriter, op, outTy, lhs, rhs);
}
rewriter.replaceOp(op, binaryOp);
return success();
}
};
template <typename T>
static bool isInValidRange(bool isFloat, const double &doubleValue, bool isInt,
const int64_t &intValue) {
if (isFloat) {
return (doubleValue >=
static_cast<double>(std::numeric_limits<T>::min())) &&
(doubleValue <= static_cast<double>(std::numeric_limits<T>::max()));
} else if (isInt) {
return (intValue >= static_cast<int64_t>(std::numeric_limits<T>::min())) &&
(intValue <= static_cast<int64_t>(std::numeric_limits<T>::max()));
}
return false;
}
// FIXME: This will eventually go into a Tosa*Utils file.
LogicalResult torchScalarToTosaTensor(ConversionPatternRewriter &rewriter,
Operation *op, Value torchScalarValue,
Value &tosaTensor, Type dtype,
llvm::ArrayRef<int64_t> dshape) {
// Retrieve a const float or int value but create the out Tensor with dtype.
double doubleValue;
auto isFloat =
matchPattern(torchScalarValue, m_TorchConstantFloat(&doubleValue));
int64_t intValue;
auto isInt = matchPattern(torchScalarValue, m_TorchConstantInt(&intValue));
if (!isFloat && !isInt)
return rewriter.notifyMatchFailure(op,
"Unable to extract the scalar constant");
int64_t numElem = 1;
for (int64_t dim : dshape)
numElem *= dim;
if (isa<mlir::FloatType>(dtype)) {
tosaTensor =
tosa::getConstTensor<float>(
rewriter, op,
SmallVector<float>(numElem, (isFloat ? doubleValue : intValue)),
dshape, dtype)
.value();
} else if (auto intType = dyn_cast<mlir::IntegerType>(dtype)) {
auto width = intType.getWidth();
if (width != 1 && width != 8 && width != 32 && width != 64)
return rewriter.notifyMatchFailure(op, [&](Diagnostic &diag) {
diag << "Unsupported integer type: " << intType;
});
if (width == 1) {
if (!isInValidRange<bool>(isFloat, doubleValue, isInt, intValue)) {
return rewriter.notifyMatchFailure(
op, "Supplied value of scalar constant exceeds limits "
"of destination type");
}
bool d = isFloat ? static_cast<bool>(doubleValue)
: static_cast<bool>(intValue);
tosaTensor = tosa::getConstTensor<bool>(
rewriter, op, SmallVector<bool>(numElem, d), dshape)
.value();
} else if (width == 8) {
if (!isInValidRange<int8_t>(isFloat, doubleValue, isInt, intValue)) {
return rewriter.notifyMatchFailure(
op, "Supplied value of scalar constant exceeds limits "
"of destination type");
}
int8_t d = isFloat ? static_cast<int8_t>(doubleValue)
: static_cast<int8_t>(intValue);
tosaTensor = tosa::getConstTensor<int8_t>(
rewriter, op, SmallVector<int8_t>(numElem, d), dshape)
.value();
} else if (width == 32) {
if (!isInValidRange<int32_t>(isFloat, doubleValue, isInt, intValue)) {
return rewriter.notifyMatchFailure(
op, "Supplied value of scalar constant exceeds limits "
"of destination type");
}
int32_t d = isFloat ? static_cast<int32_t>(doubleValue)
: static_cast<int32_t>(intValue);
tosaTensor = tosa::getConstTensor<int32_t>(
rewriter, op, SmallVector<int32_t>(numElem, d), dshape)
.value();
} else if (width == 64) {
if (!isInValidRange<int64_t>(isFloat, doubleValue, isInt, intValue)) {
return rewriter.notifyMatchFailure(
op, "Supplied value of scalar constant exceeds limits "
"of destination type");
}
int64_t d = (isFloat ? static_cast<int64_t>(doubleValue) : intValue);
tosaTensor = tosa::getConstTensor<int64_t>(
rewriter, op, SmallVector<int64_t>(numElem, d), dshape)
.value();
}
} else {
return rewriter.notifyMatchFailure(op, "Usupported element type");
}
return success();
}
LogicalResult torchAlphaToTosaTensor(ConversionPatternRewriter &rewriter,
Operation *op, Value alphaScalar,
Value &alphaTensor, Type dtype,
bool checkForUnity) {
if (succeeded(torchScalarToTosaTensor(rewriter, op, alphaScalar, alphaTensor,
dtype, {})))
return success();
// `alpha` has not been specified.
int64_t alphaValue;
if (!matchPattern(alphaScalar, m_TorchConstantInt(&alphaValue)))
return rewriter.notifyMatchFailure(
op, "Currently only scalar constants are supported for "
"alpha in TOSA operation");
// When no alpha has been specified, this must be 1.
if (checkForUnity && alphaValue != 1)
return rewriter.notifyMatchFailure(op,
"Unsupported integer value for alpha");
alphaTensor = tosa::getConstTensor<float>(
rewriter, op, {static_cast<float>(alphaValue)}, {}, dtype)
.value();
return success();
}
// These binary op legalizations are specific to add/sub which have an
// alpha multiplier.
template <typename AtenOpT, typename TosaOpT>
class ConvertAtenAddSubOp : public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// left : tensor: tensor<i32/i64/f32>
// right : scalar: i32/i64/f32
// tensor: tensor<i32/i64/f32>
// alpha : scalar: i32/i64/f32
// output: tensor: tensor<i32/i64/f32>
Value lhs = adaptor.getSelf();
auto lhsType = dyn_cast<TensorType>(lhs.getType());
Value rhs = adaptor.getOther();
auto rhsType = dyn_cast<TensorType>(rhs.getType());
if (!lhsType)
return rewriter.notifyMatchFailure(op,
"Only Tensor types supported in TOSA");
if (auto lhsElemTy = dyn_cast<IntegerType>(lhsType.getElementType())) {
if (lhsElemTy.getWidth() > 64)
return rewriter.notifyMatchFailure(
op, "Integers with widths greater than 64 are not supported");
}
// Get output type: tensor<i32/i64/f32>
auto outType = cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
Type outElemTy = outType.getElementType();
if (!outElemTy.isIntOrFloat()) {
return rewriter.notifyMatchFailure(
op, "Only floating-point or integer datatype legalization supported");
}
Type rhsAlphaMulElemType;
if (isa<mlir::FloatType>(outElemTy)) {
rhsAlphaMulElemType = outElemTy;
} else {
// if output type is 64, input type should also be 32
rhsAlphaMulElemType = rewriter.getIntegerType(32);
}
// if right is scalar, rhgType==None, which need to be manually cast to
// TensorType else right is tensor, rhsType==tensor<i32/i64/f32>
Value rhsAsTensor;
if (!rhsType) {
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
rhsAsTensor, rhsAlphaMulElemType, {})))
return rewriter.notifyMatchFailure(
op, "Currently only scalar constants are supported for "
"conversion in TOSA operation");
} else {
if (rhsType.getElementType() != rhsAlphaMulElemType) {
// right is tensor, rhsType == tensor<i32/i64/f32>
// right must be cast to same type as the alpha, so MulOp success
rhs =
tosa::tosaCastTensorToType(
rewriter, rhs,
RankedTensorType::get(rhsType.getShape(), rhsAlphaMulElemType))
.value();
// reinitialize right value type to tensor<i32/f32>
rhsType = dyn_cast<TensorType>(rhs.getType());
}
}
auto rhsTensor = rhsType ? rhs : rhsAsTensor;
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, rhsTensor)
.failed())
return rewriter.notifyMatchFailure(
op, "Failed to equalize ranks among operands and result");
auto rhsTensorType = dyn_cast<TensorType>(rhsTensor.getType());
// Handle scalar value alpha.
// It should be either f32/i32
Value alphaTensor;
if (failed(torchAlphaToTosaTensor(rewriter, op.getOperation(),
op.getAlpha(), alphaTensor,
rhsAlphaMulElemType,
/*checkForUnity=*/false))) {
return rewriter.notifyMatchFailure(
op, "Currently only scalar constants are supported for "
"alpha in conversion to TOSA operation");
}
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, alphaTensor)
.failed())
return rewriter.notifyMatchFailure(
op, "Failed to equalize ranks among operands and result");
auto mulAlphaOp = tosa::createMulOpAndCast(
rewriter, op, rhsTensorType, rhsTensor, alphaTensor, /*shift=*/0);
if (outElemTy.isInteger(64)) {
// Tosa doesn't support 64-bit elementwise addition and subtraction.
// if outElemTy tensor<i64>, mulTensor must be tensor<i32>,
// left value could be tensor<f32/i32/i64> type, cast left value to
// tensor<i32> type
auto addOrSubi64Op = tosa::createBinaryOpAndCast<TosaOpT>(
rewriter, op,
RankedTensorType::get(outType.getShape(), rhsAlphaMulElemType), lhs,
mulAlphaOp);
// cast tensor<i32> back to tensor<i64>
auto result =
tosa::tosaCastTensorToType(rewriter, addOrSubi64Op, outType).value();
rewriter.replaceOp(op, result);
return success();
}
auto binaryOp = tosa::createBinaryOpAndCast<TosaOpT>(rewriter, op, outType,
lhs, mulAlphaOp);
rewriter.replaceOp(op, binaryOp.getResult());
return success();
}
}; // namespace
// Binary op legalizations for comparator ops.
template <typename AtenOpT, typename TosaOpT>
class ConvertAtenCompareOp : public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Value lhs = adaptor.getSelf();
auto lhsTy = dyn_cast<TensorType>(lhs.getType());
Value rhs = adaptor.getOther();
auto rhsTy = dyn_cast<TensorType>(rhs.getType());
if (!lhsTy)
return rewriter.notifyMatchFailure(op,
"Only Tensor types supported in TOSA");
auto lhsElemTy = lhsTy.getElementType();
if (!lhsElemTy.isIntOrFloat())
return rewriter.notifyMatchFailure(
op, "Only floating-point or integer datatype legalization supported");
// For bitwise operators, only integer datatype legalization is supported
constexpr bool isBitwiseOp =
std::is_same<AtenOpT, AtenBitwiseAndTensorOp>() ||
std::is_same<AtenOpT, AtenBitwiseAndScalarOp>() ||
std::is_same<AtenOpT, AtenBitwiseOrTensorOp>() ||
std::is_same<AtenOpT, AtenBitwiseXorTensorOp>();
if (isa<mlir::FloatType>(lhsElemTy) && isBitwiseOp) {
return rewriter.notifyMatchFailure(op,
"For bitwise operators, only integer "
"datatype legalization is supported");
}
Value rhsAsTensor;
if (!rhsTy) {
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
rhsAsTensor, rhs.getType(), {})))
return rewriter.notifyMatchFailure(
op, "Currently only scalar constants are supported for "
"conversion in TOSA operation");
}
auto rhsTensor = rhsTy ? rhs : rhsAsTensor;
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, rhsTensor)
.failed())
return rewriter.notifyMatchFailure(
op, "Failed to equalize ranks among operands and result");
auto rhsTensorTy = dyn_cast<TensorType>(rhsTensor.getType());
auto rhsElemTy = rhsTensorTy.getElementType();
// There is no Lesser operator in TOSA.
constexpr auto swapLhsRhs = (std::is_same<AtenOpT, AtenLtTensorOp>() ||
std::is_same<AtenOpT, AtenLtScalarOp>() ||
std::is_same<AtenOpT, AtenLeTensorOp>() ||
std::is_same<AtenOpT, AtenLeScalarOp>());
// Promote lhs and rhs dtypes for bitwise operators.
TensorType resultTy = cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
if (isBitwiseOp) {
lhs = tosa::tosaCastTensorToType(rewriter, lhs, resultTy).value();
rhsTensor =
tosa::tosaCastTensorToType(rewriter, rhsTensor, resultTy).value();
}
// Support different types comparisons
auto isLhsElemFloat = isa<mlir::FloatType>(lhsElemTy);
auto isRhsElemFloat = isa<mlir::FloatType>(rhsElemTy);
if (lhsElemTy != rhsElemTy && !isBitwiseOp) {
if (isLhsElemFloat && !isRhsElemFloat) {
rhsTensor =
tosa::tosaCastTensorToType(rewriter, rhsTensor, lhsTy).value();
} else if (!isLhsElemFloat && isRhsElemFloat) {
lhs = tosa::tosaCastTensorToType(rewriter, lhs, rhsTensorTy).value();
} else if (isLhsElemFloat && isRhsElemFloat) {
auto lhsElemFloatTy = dyn_cast<mlir::FloatType>(lhsElemTy);
auto rhsElemFloatTy = dyn_cast<mlir::FloatType>(rhsElemTy);
if (lhsElemFloatTy.getWidth() > rhsElemFloatTy.getWidth()) {
rhsTensor =
tosa::tosaCastTensorToType(rewriter, rhsTensor, lhsTy).value();
} else {
lhs = tosa::tosaCastTensorToType(rewriter, lhs, rhsTensorTy).value();
}
} else {
auto lhsElemIntTy = dyn_cast<mlir::IntegerType>(lhsElemTy);
auto rhsElemIntTy = dyn_cast<mlir::IntegerType>(rhsElemTy);
if (lhsElemIntTy.getWidth() > rhsElemIntTy.getWidth()) {
rhsTensor =
tosa::tosaCastTensorToType(rewriter, rhsTensor, lhsTy).value();
} else {
lhs = tosa::tosaCastTensorToType(rewriter, lhs, rhsTensorTy).value();
}
}
}
auto resultOp = TosaOpT::create(rewriter, op.getLoc(), resultTy,
(swapLhsRhs ? rhsTensor : lhs),
(swapLhsRhs ? lhs : rhsTensor));
// There is no NE operator in TOSA.
if constexpr (std::is_same<AtenOpT, AtenNeTensorOp>() ||
std::is_same<AtenOpT, AtenNeScalarOp>()) {
rewriter.replaceOpWithNewOp<tosa::LogicalNotOp>(op, resultTy,
resultOp.getResult());
} else {
rewriter.replaceOp(op, resultOp.getResult());
}
return success();
}
};
// Binary op legalizations for Mul variants.
template <typename AtenOpT>
class ConvertAtenMulOp : public TorchToTosaOpConversionPattern<AtenOpT> {
public:
using TorchToTosaOpConversionPattern<AtenOpT>::TorchToTosaOpConversionPattern;
using OpAdaptor = typename AtenOpT::Adaptor;
LogicalResult
matchAndRewriteImpl(AtenOpT op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
Value lhs = adaptor.getSelf();
auto lhsType = dyn_cast<TensorType>(lhs.getType());
if (!lhsType)
return rewriter.notifyMatchFailure(op,
"Only Tensor types supported in TOSA");
auto outType = cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
Type outElemTy = outType.getElementType();
if (!outElemTy.isIntOrFloat())
return rewriter.notifyMatchFailure(
op, "Only floating-point or integer datatype legalization supported");
Value rhsTensor;
if constexpr (std::is_same<AtenOpT, AtenSquareOp>()) {
rhsTensor = lhs;
} else {
Value rhsAsTensor;
Value rhs = adaptor.getOther();
auto rhsType = dyn_cast<TensorType>(rhs.getType());
if (!rhsType) {
if (failed(torchScalarToTosaTensor(rewriter, op, op.getOther(),
rhsAsTensor, outElemTy, {}))) {
return rewriter.notifyMatchFailure(
op, "Currently only scalar constants are supported for "
"conversion in TOSA operation");
}
}
rhsTensor = rhsType ? rhs : rhsAsTensor;
}
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, rhsTensor)
.failed())
return rewriter.notifyMatchFailure(
op, "Failed to equalize ranks among operands and result");
if (isa<mlir::FloatType>(outElemTy) || isa<mlir::IntegerType>(outElemTy)) {
auto outType = cast<TensorType>(
OpConversionPattern<AtenOpT>::getTypeConverter()->convertType(
op.getType()));
auto mulOp = tosa::createMulOpAndCast(rewriter, op, outType, lhs,
rhsTensor, /*shift=*/0);
rewriter.replaceOp(op, mulOp.getResult());
return success();
}
// Quantized multiplication may need to rescale inputs.
return rewriter.notifyMatchFailure(
op, "Only floating-point or integer datatype "
"legalization currently supported");
}
};
// Function to perform division with trunc rounding mode (rounding result
// towards zero) for float type inputs.
// This function takes in the division result between lhs and rhs rather
// than takes in the original lhs and rhs tensors as parameters.
std::optional<Value> truncFloatDivWithDivResult(PatternRewriter &rewriter,
Operation *op,
TensorType outType,
Value divResult) {
// To implement trunc mode for float inputs, multiply the floored abs
// of the tensor with the elementwise signedness of the tensor.
// div_result = lhs / rhs
// trunc_val = floor(abs(div_result)) * sign(div_result)
auto zero =
tosa::getConstTensor<float>(rewriter, op, 0, {}, outType.getElementType())
.value();
auto one =
tosa::getConstTensor<float>(rewriter, op, 1, {}, outType.getElementType())
.value();
auto minusOne = tosa::getConstTensor<float>(rewriter, op, -1, {},
outType.getElementType())
.value();
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), divResult, one)
.failed() ||
mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), divResult, zero)
.failed() ||
mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), divResult, minusOne)
.failed())
return std::nullopt;
auto cond = tosa::GreaterEqualOp::create(
rewriter, op->getLoc(),
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(1)),
divResult, zero);
auto selectOp = tosa::SelectOp::create(rewriter, op->getLoc(), outType, cond,
one, minusOne);
auto absDivResult =
tosa::AbsOp::create(rewriter, op->getLoc(), outType, divResult);
auto flooredAbsDivResult =
tosa::FloorOp::create(rewriter, op->getLoc(), outType, absDivResult);
Value result =
tosa::createMulOpAndCast(rewriter, op, outType, flooredAbsDivResult,
selectOp, /*shift=*/0)
.getResult();
return result;
}
// Function to perform division with trunc rounding mode (rounding result
// towards zero) for float type inputs
Value truncFloatDiv(PatternRewriter &rewriter, Operation *op,
TensorType outType, Value lhs, Value rhs) {
rhs = tosa::tosaCastTensorToType(rewriter, rhs, outType).value();
auto rhsRcp =
tosa::ReciprocalOp::create(rewriter, op->getLoc(), rhs.getType(), rhs);
auto divResult = tosa::createMulOpAndCast(rewriter, op, outType, lhs, rhsRcp,
/*shift=*/0);
return truncFloatDivWithDivResult(rewriter, op, outType, divResult).value();
}
// Function to perform division with floor rounding mode (rounding result
// down) for integer type inputs.
std::optional<Value> floorIntDiv(PatternRewriter &rewriter, Operation *op,
TensorType outType, Value lhs, Value rhs) {
// To implement floor mode int input, utilize tosa::IntDivOp (trunc div
// result) with the following formula elementwise:
// floor_val = trunc_val - ((trunc_val * rhs != lhs)
// && (sign(lhs) != sign(rhs)))
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, rhs).failed())
return std::nullopt;
// TOSA IntDiv requires inputs to be i32
auto i32Type =
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(32));
lhs = tosa::tosaCastTensorToType(rewriter, lhs, i32Type).value();
rhs = tosa::tosaCastTensorToType(rewriter, rhs, i32Type).value();
auto intDivOp =
tosa::IntDivOp::create(rewriter, op->getLoc(), i32Type, lhs, rhs);
auto zero = tosa::getConstTensor<int32_t>(rewriter, op, 0, {}).value();
auto one = tosa::getConstTensor<int32_t>(rewriter, op, 1, {}).value();
if (mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, one).failed() ||
mlir::tosa::EqualizeRanks(rewriter, op->getLoc(), lhs, zero).failed())
return std::nullopt;
auto boolType =
RankedTensorType::get(outType.getShape(), rewriter.getIntegerType(1));
auto lhsMulRhs = tosa::createMulOpAndCast(rewriter, op, i32Type, lhs, rhs,
/*shift=*/0);
auto lhsRhsDifferentSign = tosa::GreaterOp::create(rewriter, op->getLoc(),
boolType, zero, lhsMulRhs);
auto truncMulRhs = tosa::createMulOpAndCast(rewriter, op, i32Type, intDivOp,
rhs, /*shift=*/0);
auto truncMulRhsEqualLhs =
tosa::EqualOp::create(rewriter, op->getLoc(), boolType, truncMulRhs, lhs);
auto truncMulRhsNotEqualLhs = tosa::LogicalNotOp::create(
rewriter, op->getLoc(), boolType, truncMulRhsEqualLhs);
auto truncMinusOne =
tosa::SubOp::create(rewriter, op->getLoc(), i32Type, intDivOp, one);
auto cond =
tosa::LogicalAndOp::create(rewriter, op->getLoc(), boolType,
lhsRhsDifferentSign, truncMulRhsNotEqualLhs);
auto selectOp = tosa::SelectOp::create(rewriter, op->getLoc(), i32Type, cond,
truncMinusOne, intDivOp);
Value result =
tosa::tosaCastTensorToType(rewriter, selectOp, outType).value();
return result;
}