-
Notifications
You must be signed in to change notification settings - Fork 166
/
Copy pathTopToTpuPass.cpp
1921 lines (1816 loc) · 67.7 KB
/
TopToTpuPass.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
//===----------------------------------------------------------------------===//
//
// Copyright (C) 2022 Sophgo Technologies Inc. All rights reserved.
//
// TPU-MLIR is licensed under the 2-Clause BSD License except for the
// third-party components.
//
//===----------------------------------------------------------------------===//
#include "tpu_mlir/Backend/Arch.h"
#include "tpu_mlir/Conversion/TopToTpu/ConvertTopToTpu.h"
#include "tpu_mlir/Conversion/TopToTpu/LoweringBM1684.h"
#include "tpu_mlir/Conversion/TopToTpu/LoweringBM1684X.h"
#include "tpu_mlir/Conversion/TopToTpu/LoweringCV18xx.h"
#include "tpu_mlir/Support/ActiveUtils.h"
#include "tpu_mlir/Support/Float8.h"
#include <regex>
namespace tpu_mlir {
template <typename OpTy>
static void BackwardOp(OpTy op) {
Value in = op.getInput();
Value out = op.getOutput();
auto new_type = module::getTypeLike(out, module::getShape(in));
in.setType(new_type);
}
static void Backward(Value in) {
if (auto reshapeOp = dyn_cast<top::ReshapeOp>(in.getDefiningOp())) {
BackwardOp(reshapeOp);
// Backward(reshapeOp.getInput());
} else if (auto permuteOp = dyn_cast<top::PermuteOp>(in.getDefiningOp())) {
BackwardOp(permuteOp);
// Backward(permuteOp.getInput());
} else if (auto d2s = dyn_cast<top::Depth2SpaceOp>(in.getDefiningOp())) {
BackwardOp(d2s);
}
}
template <typename OpTy>
static void ForwardOp(OpTy op) {
Value in = op.getInput();
Value out = op.getOutput();
auto new_type = module::getTypeLike(in, module::getShape(out));
out.setType(new_type);
}
static void Forward(Value out) {
for (auto user : out.getUsers()) {
if (auto reshapeOp = dyn_cast<top::ReshapeOp>(user)) {
ForwardOp(reshapeOp);
// Forward(reshapeOp.getOutput());
} else if (auto permuteOp = dyn_cast<top::PermuteOp>(user)) {
ForwardOp(permuteOp);
// Forward(permuteOp.getOutput());
}
}
}
static void ForwardSign(Value out) {
for (auto user : out.getUsers()) {
if (auto avpOp = dyn_cast<top::AvgPoolOp>(user)) {
ForwardOp(avpOp);
} else if (auto mxpOp = dyn_cast<top::MaxPoolOp>(user)) {
ForwardOp(mxpOp);
} else if (auto absOp = dyn_cast<top::AbsOp>(user)) {
ForwardOp(absOp);
} else {
Forward(out);
}
}
}
template <typename OpTy>
struct ForwardCalibartion : public OpRewriterPatternEx<OpTy> {
public:
ForwardCalibartion(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "ForwardCalibartion") {}
mlir::LogicalResult
matchAndRewriteImpl(OpTy op, mlir::PatternRewriter &rewriter) const override {
if constexpr (std::is_same_v<OpTy, top::ReduceOp>) {
std::string mode = op.getMode().str();
if (mode != "ReduceMax" && mode != "ReduceMin") {
return failure();
}
}
Value in = op.getInput();
Value out = op.getOutput();
if (!module::isCalibratedType(in)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
if (module::isCalibratedType(out)) {
auto out_qtype = module::getCalibratedType(out);
if (in_qtype.getMax() == out_qtype.getMax() &&
in_qtype.getMin() == out_qtype.getMin()) {
return failure();
}
}
auto new_type = RankedTensorType::get(module::getShape(out), in_qtype);
out.setType(new_type);
Forward(out);
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
struct ForwardMulConst : public OpRewriterPatternEx<top::MulConstOp> {
ForwardMulConst(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::MulConstOp>(context, "ForwardMulConst") {}
LogicalResult matchAndRewriteImpl(top::MulConstOp op,
PatternRewriter &rewriter) const override {
Value in = op.getInput();
Value out = op.getOutput();
if (!module::isCalibratedType(in)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
auto const_v = op.getConstVal().convertToDouble();
auto in_min = in_qtype.getMin();
auto in_max = in_qtype.getMax();
auto out_max = (const_v >= 0 ? in_max : in_min);
auto out_min = (const_v >= 0 ? in_min : in_max);
if (const_v != (double)0) {
out_max *= const_v;
out_min *= const_v;
}
if (module::isCalibratedType(out)) {
auto out_qtype = module::getCalibratedType(out);
if (out_max == out_qtype.getMax() && out_min == out_qtype.getMin()) {
return failure();
}
}
auto new_out_type = quant::CalibratedQuantizedType::get(
module::getStorageType(out), out_min, out_max);
auto new_type = RankedTensorType::get(module::getShape(out), new_out_type);
out.setType(new_type);
Forward(out);
return success();
}
bool shouldPrint(top::MulConstOp op) const override { return false; }
};
struct ForwardArg : public OpRewriterPatternEx<top::ArgOp> {
ForwardArg(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::ArgOp>(context, "ForwardArg") {}
LogicalResult matchAndRewriteImpl(top::ArgOp op,
PatternRewriter &rewriter) const override {
if (module::isNone(op.getValues())) {
return failure();
}
auto in = op.getInput();
auto out = op.getValues();
if (!module::isCalibratedType(in)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
if (module::isCalibratedType(out)) {
auto out_qtype = module::getCalibratedType(out);
if (in_qtype.getMax() == out_qtype.getMax() &&
in_qtype.getMin() == out_qtype.getMin()) {
return failure();
}
}
auto out_type = out.getType().cast<RankedTensorType>();
auto new_type = RankedTensorType::get(out_type.getShape(), in_qtype);
out.setType(new_type);
Forward(out);
return success();
}
bool shouldPrint(top::ArgOp op) const override { return false; }
};
template <typename OpTy>
struct KeepSignPattern : public OpRewriterPatternEx<OpTy> {
public:
KeepSignPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "KeepSignPattern") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
Value in = op.getInput();
Value out = op.getOutput();
if (!module::isCalibratedType(in, out)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
auto out_qtype = module::getCalibratedType(out);
float min;
if (in_qtype.getMin() < 0) {
if (out_qtype.getMin() < 0) {
return failure();
}
min = -out_qtype.getMax() * 0.1;
} else {
if (out_qtype.getMin() >= 0) {
return failure();
}
min = 0;
}
auto etype = module::getStorageType(out);
auto new_qtype =
quant::CalibratedQuantizedType::get(etype, min, out_qtype.getMax());
auto new_type = RankedTensorType::get(module::getShape(out), new_qtype);
out.setType(new_type);
ForwardSign(out);
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
template <typename OpTy>
struct KeepMulSignPattern : public OpRewriterPatternEx<OpTy> {
public:
KeepMulSignPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "KeepMulSignPattern") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
auto num_inputs = op.getInputs().size();
if (num_inputs != 2)
return failure();
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
auto out_qtype = module::getCalibratedType(out);
bool out_signed = out_qtype.getMin() < 0.0;
bool in_signed[2] = {true, true};
int idx = 0;
for (auto i : op.getInputs()) {
if (isa<top::WeightOp>(i.getDefiningOp())) {
top::WeightOp w = dyn_cast<top::WeightOp>(i.getDefiningOp());
auto filter_f32 = w.read<float>();
if (filter_f32->size() != 1)
return failure();
if (filter_f32->at(0) >= 0.0)
in_signed[idx] = false;
} else {
auto in_qtype = module::getCalibratedType(i);
if (in_qtype.getMin() >= 0.0)
in_signed[idx] = false;
}
idx++;
}
if (in_signed[0] == out_signed)
return failure();
else if (in_signed[1] == out_signed) {
// switch inputs
std::vector<Value> operands;
for (auto in : op.getOperands()) {
operands.insert(operands.begin(), in);
}
op.getOperation()->setOperands(operands);
return success();
} else {
// two inputs are same but output is not the same
if (in_signed[0]) {
// in all signed, output unsigned, set output to signed, though possible
// eg. sqr, but ic has the restriction
float min = -out_qtype.getMax() * 0.1;
auto etype = module::getStorageType(out);
auto new_qtype =
quant::CalibratedQuantizedType::get(etype, min, out_qtype.getMax());
auto new_type = RankedTensorType::get(module::getShape(out), new_qtype);
out.setType(new_type);
Forward(out);
return success();
} else {
// in all unsigned, output signed, may be caused by other pass? bad
// cali_table?
llvm_unreachable(
(std::string("not reasonable, two unsigned get signed, check "
"cali-table and graph op is:") +
std::string(module::getName(op.getOperation()).str()))
.data());
}
}
return failure();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
struct KeepAddSignPattern : public OpRewriterPatternEx<top::AddOp> {
public:
KeepAddSignPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::AddOp>(context, "KeepAddSignPattern") {}
LogicalResult matchAndRewriteImpl(top::AddOp op,
PatternRewriter &rewriter) const override {
bool is_sign = false;
auto num_inputs = op.getInputs().size();
auto coeffs = module::getF64Array(op.getCoeff(), num_inputs, 1.0);
for (int i = 0; i < num_inputs; i++) {
auto in = op.getInputs()[i];
auto coeff = coeffs->at(i);
if (!module::isCalibratedType(in)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
if (in_qtype.getMin() * coeff < 0 || in_qtype.getMax() * coeff < 0) {
is_sign = true;
break;
}
}
auto out = op.getOutput();
auto out_qtype = module::getCalibratedType(out);
double min = out_qtype.getMin();
if (is_sign && min >= 0) {
min = -out_qtype.getMax() * 0.1;
} else if (is_sign == false && min < 0) {
min = 0;
} else {
return failure();
}
auto etype = module::getStorageType(out);
auto new_qtype =
quant::CalibratedQuantizedType::get(etype, min, out_qtype.getMax());
auto new_type = RankedTensorType::get(module::getShape(out), new_qtype);
out.setType(new_type);
Forward(out);
return success();
}
bool shouldPrint(top::AddOp op) const override { return false; }
};
struct SetSubConstSignPattern : public OpRewriterPatternEx<top::SubConstOp> {
public:
SetSubConstSignPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::SubConstOp>(context,
"SetSubConstSignPattern") {}
LogicalResult matchAndRewriteImpl(top::SubConstOp op,
PatternRewriter &rewriter) const override {
Value in = op.getInput();
Value out = op.getOutput();
if (!module::isCalibratedType(in) || !module::isCalibratedType(out)) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
if (module::isCalibratedType(out)) {
auto out_qtype = module::getCalibratedType(out);
auto out_type = out.getType().cast<RankedTensorType>();
if (in_qtype.getMin() >= 0 && out_qtype.getMin() >= 0) {
auto new_out_type = quant::CalibratedQuantizedType::get(
module::getStorageType(out), out_qtype.getMax() * (-0.1),
out_qtype.getMax());
auto new_type =
RankedTensorType::get(out_type.getShape(), new_out_type);
out.setType(new_type);
Forward(out);
return success();
} else {
return failure();
}
}
return failure();
}
bool shouldPrint(top::SubConstOp op) const override { return false; }
};
struct SetSubSignPattern : public OpRewriterPatternEx<top::SubOp> {
public:
SetSubSignPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::SubOp>(context, "SetSubSignPattern") {}
LogicalResult matchAndRewriteImpl(top::SubOp op,
PatternRewriter &rewriter) const override {
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
auto out_qtype = module::getCalibratedType(out);
auto out_type = out.getType().cast<RankedTensorType>();
if (out_qtype.getMin() >= 0) {
auto new_out_type = quant::CalibratedQuantizedType::get(
module::getStorageType(out), out_qtype.getMax() * (-0.1),
out_qtype.getMax());
auto new_type = RankedTensorType::get(out_type.getShape(), new_out_type);
out.setType(new_type);
Forward(out);
return success();
} else {
return failure();
}
}
bool shouldPrint(top::SubOp op) const override { return false; }
};
template <typename OpTy, bool KeepMin = false>
struct BackwardCalibartion : public OpRewriterPatternEx<OpTy> {
public:
BackwardCalibartion(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "BackwardCalibartion") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
Value in = op->getOperand(0);
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
if (in.hasOneUse() == false) {
return failure();
}
auto in_qtype = module::getCalibratedType(in);
auto out_qtype = module::getCalibratedType(out);
if (module::isCalibratedType(in)) {
auto in_qtype = module::getCalibratedType(in);
if (in_qtype.getMax() == out_qtype.getMax() &&
(KeepMin || in_qtype.getMin() == out_qtype.getMin())) {
return failure();
}
}
auto in_type = in.getType().cast<RankedTensorType>();
if (KeepMin) {
auto etype = module::getStorageType(out);
out_qtype = quant::CalibratedQuantizedType::get(etype, in_qtype.getMin(),
out_qtype.getMax());
}
auto new_type = RankedTensorType::get(in_type.getShape(), out_qtype);
in.setType(new_type);
Backward(in);
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
template <typename OpTy>
struct ForwardTypePattern : public OpRewriterPatternEx<OpTy> {
public:
ForwardTypePattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "ForwardTypePattern") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
if (module::isCV18xx()) {
// for case input -> reshape -> anyOp
// |___anyOp
// here should do quant manner otherwise will insert cast after shapeOp
auto pre_op = op->getOperand(0).getDefiningOp();
if (isa<top::InputOp>(pre_op))
return failure();
}
Value in = op.getInput();
Value out = op.getOutput();
auto in_type = in.getType().cast<RankedTensorType>();
auto out_type = out.getType().cast<RankedTensorType>();
auto in_etype = in_type.getElementType();
auto out_etype = out_type.getElementType();
if (in_etype == out_etype) {
return failure();
}
auto new_type = RankedTensorType::get(out_type.getShape(), in_etype);
out.setType(new_type);
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
template <typename OpTy>
struct ForwardInt32TypePattern : public OpRewriterPatternEx<OpTy> {
public:
ForwardInt32TypePattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "ForwardInt32TypePattern") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
auto pre_op = op->getOperand(0).getDefiningOp();
if (isa<top::InputOp>(pre_op))
return failure();
Value in = op.getInput();
Value out = op.getOutput();
auto in_type = in.getType().cast<RankedTensorType>();
auto out_type = out.getType().cast<RankedTensorType>();
auto in_etype = in_type.getElementType();
auto out_etype = out_type.getElementType();
if (in_etype == out_etype || !in_etype.isInteger(32)) {
return failure();
}
auto new_type = RankedTensorType::get(out_type.getShape(), in_etype);
out.setType(new_type);
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
// to make compare inputs have the same min max
struct CompareCalibartion : public OpRewriterPatternEx<top::CompareOp> {
public:
CompareCalibartion(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::CompareOp>(context, "CompareCalibartion") {}
LogicalResult matchAndRewriteImpl(top::CompareOp op,
PatternRewriter &rewriter) const override {
Value l = op.getLhs();
Value r = op.getRhs();
if (false == module::isCalibratedType(l) ||
false == module::isCalibratedType(r)) {
return failure();
}
auto stype = module::getStorageType(l);
auto l_ctype = module::getCalibratedType(l);
auto r_ctype = module::getCalibratedType(r);
auto max = std::max(l_ctype.getMax(), r_ctype.getMax());
auto min = std::min(l_ctype.getMin(), r_ctype.getMin());
if (l_ctype.getMax() == r_ctype.getMax() &&
l_ctype.getMin() == r_ctype.getMin()) {
return failure();
}
auto new_ctype = quant::CalibratedQuantizedType::get(stype, min, max);
auto new_ltype = RankedTensorType::get(module::getShape(l), new_ctype);
auto new_rtype = RankedTensorType::get(module::getShape(r), new_ctype);
l.setType(new_ltype);
r.setType(new_rtype);
return success();
}
bool shouldPrint(top::CompareOp op) const override { return false; }
};
template <typename OpTy>
struct BackwardMutiInSingleOut : public OpRewriterPatternEx<OpTy> {
public:
BackwardMutiInSingleOut(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "BackwardMutiInSingleOut") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
// TODO: need to be more clever
for (auto in : op.getInputs()) {
if (!module::isCalibratedType(in)) {
return failure();
}
if (in.hasOneUse()) {
continue;
}
for (auto user : in.getUsers()) {
if (!isa<top::MaxPoolOp>(user) && user != op.getOperation()) {
return failure();
}
}
}
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
// checkout all inputs have the same sign
auto in_0 = op.getInputs()[0];
auto in_0_qtype = module::getCalibratedType(in_0);
bool un_signed = in_0_qtype.getMin() >= 0;
for (uint i = 1; i < op.getInputs().size(); i++) {
auto qtype = module::getCalibratedType(op.getInputs()[i]);
if (un_signed != (qtype.getMin() >= 0)) {
if (isa<top::ConcatOp>(op))
return failure();
}
}
auto out_qtype = module::getCalibratedType(out);
// checkout all input cali is the same
bool same = true;
for (uint i = 1; i < op.getInputs().size(); i++) {
auto qtype = module::getCalibratedType(op.getInputs()[i]);
if (qtype.getMin() != in_0_qtype.getMin() ||
qtype.getMax() != in_0_qtype.getMax()) {
same = false;
break;
}
}
if (same) {
if (out_qtype.getMin() == in_0_qtype.getMin() &&
out_qtype.getMax() == in_0_qtype.getMax()) {
// do nothing
return failure();
}
auto out_type = out.getType().cast<RankedTensorType>();
auto new_type = RankedTensorType::get(out_type.getShape(), in_0_qtype);
out.setType(new_type);
return success();
}
for (Value in : op.getInputs()) {
auto in_type = in.getType().cast<RankedTensorType>();
auto new_type = RankedTensorType::get(in_type.getShape(), out_qtype);
in.setType(new_type);
Backward(in);
}
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
template <typename OpTy>
struct BackwardAddThToMuls : public OpRewriterPatternEx<OpTy> {
public:
BackwardAddThToMuls(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "BackwardAddThToMuls") {}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
// TODO: need to be more clever
for (auto in : op.getInputs()) {
if (!module::isCalibratedType(in)) {
return failure();
}
if (!isa<top::MulOp>(in.getDefiningOp()))
return failure();
if (!in.hasOneUse()) {
return failure();
}
}
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
auto out_qtype = module::getCalibratedType(out);
for (Value in : op.getInputs()) {
auto in_type = in.getType().cast<RankedTensorType>();
auto new_type = RankedTensorType::get(in_type.getShape(), out_qtype);
in.setType(new_type);
Backward(in);
}
return success();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
struct SelectiveWhere : public OpRewriterPatternEx<top::WhereOp> {
public:
SelectiveWhere(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::WhereOp>(context, "SelectiveWhere") {}
LogicalResult matchAndRewriteImpl(top::WhereOp op,
PatternRewriter &rewriter) const override {
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
float const_v = 0.0;
bool const_signed = false;
if (op.getYIsConst()) {
float c = op.getYConstVal().convertToDouble();
const_signed = c < 0.;
const_v = std::abs(c);
}
if (op.getXIsConst()) {
float c = op.getXConstVal().convertToDouble();
const_signed |= c < 0.;
const_v = std::max(std::abs(c), const_v);
}
auto out_qtype = module::getCalibratedType(out);
// if output th is less than const(if exists), make it larger to include
// const val
bool out_to_constv = false;
if (out_qtype.getMax() < const_v) {
auto out_qtype = module::getCalibratedType(out);
auto new_qtype = quant::CalibratedQuantizedType::get(
out_qtype.getExpressedType(),
(const_signed || out_qtype.getMin() < 0.) ? -const_v * 0.1 : 0.0f,
const_v);
auto new_type = RankedTensorType::get(
out.getType().cast<RankedTensorType>().getShape(), new_qtype);
out.setType(new_type);
out_to_constv = true;
}
// but if where is set float, don't backward the th
bool float_where = false;
if (LoweringConfig::quantize_map.find(
module::getName(op.getOperation()).str()) !=
LoweringConfig::quantize_map.end()) {
if (LoweringConfig::quantize_map
.find(module::getName(op.getOperation()).str())
->second == module::Mode::F32 ||
LoweringConfig::quantize_map
.find(module::getName(op.getOperation()).str())
->second == module::Mode::F16)
float_where = true;
}
// if input is not the same with out, set the input to follow output
// don't backward to condition, and don't backward to input if output has
// been enlarged to const_v
bool changed = false;
if (!op.getXIsConst() && !out_to_constv && !float_where) {
auto in = op.getTbrn();
if (!module::isCalibratedType(in))
return failure();
if (module::getCalibratedType(in).getMin() != out_qtype.getMin() ||
module::getCalibratedType(in).getMax() != out_qtype.getMax()) {
auto in_qtype = module::getCalibratedType(in);
auto new_qtype = quant::CalibratedQuantizedType::get(
in_qtype.getExpressedType(), out_qtype.getMin(),
out_qtype.getMax());
auto new_type = RankedTensorType::get(
in.getType().cast<RankedTensorType>().getShape(), new_qtype);
in.setType(new_type);
changed |= true;
}
}
if (!op.getYIsConst() && !out_to_constv && !float_where) {
auto in = op.getFbrn();
if (!module::isCalibratedType(in))
return failure();
if (module::getCalibratedType(in).getMin() != out_qtype.getMin() ||
module::getCalibratedType(in).getMax() != out_qtype.getMax()) {
auto in_qtype = module::getCalibratedType(in);
auto new_qtype = quant::CalibratedQuantizedType::get(
in_qtype.getExpressedType(), out_qtype.getMin(),
out_qtype.getMax());
auto new_type = RankedTensorType::get(
in.getType().cast<RankedTensorType>().getShape(), new_qtype);
in.setType(new_type);
changed |= true;
}
}
if (changed)
return success();
else
return failure();
}
bool shouldPrint(top::WhereOp op) const override { return false; }
};
struct SelectiveMaskedFill : public OpRewriterPatternEx<top::MaskedFillOp> {
public:
SelectiveMaskedFill(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::MaskedFillOp>(context, "SelectiveMaskedFill") {
}
LogicalResult matchAndRewriteImpl(top::MaskedFillOp op,
PatternRewriter &rewriter) const override {
// TODO: need to be more clever
for (auto in : op->getOperands()) {
if (!module::isCalibratedType(in)) {
return failure();
}
if (!in.hasOneUse()) {
return failure();
}
}
Value out = op.getOutput();
if (!module::isCalibratedType(out)) {
return failure();
}
float const_v = 0.0;
bool const_signed = false;
float c = op.getConstVal().convertToDouble();
const_signed = c < 0.;
const_v = std::abs(c);
auto out_qtype = module::getCalibratedType(out);
// if output th is less than const(if exists), make it larger to include
// const val
bool out_to_constv = false;
if (out_qtype.getMax() < const_v) {
auto out_qtype = module::getCalibratedType(out);
auto new_qtype = quant::CalibratedQuantizedType::get(
out_qtype.getExpressedType(),
(const_signed || out_qtype.getMin() < 0.) ? -const_v * 0.1 : 0.0f,
const_v);
auto new_type = RankedTensorType::get(
out.getType().cast<RankedTensorType>().getShape(), new_qtype);
out.setType(new_type);
out_to_constv = true;
}
// if input is not the same with out, set the input to follow output
// don't backward to condition
// but if where is set float, don't backward the th
bool float_mf = false;
if (LoweringConfig::quantize_map.find(
module::getName(op.getOperation()).str()) !=
LoweringConfig::quantize_map.end()) {
if (LoweringConfig::quantize_map
.find(module::getName(op.getOperation()).str())
->second == module::Mode::F32 ||
LoweringConfig::quantize_map
.find(module::getName(op.getOperation()).str())
->second == module::Mode::F16)
float_mf = true;
}
bool changed = false;
auto in = op.getOperand(1);
if ((module::getCalibratedType(in).getMin() != out_qtype.getMin() ||
module::getCalibratedType(in).getMax() != out_qtype.getMax()) &&
!out_to_constv && !float_mf) {
auto in_qtype = module::getCalibratedType(in);
auto new_qtype = quant::CalibratedQuantizedType::get(
in_qtype.getExpressedType(), out_qtype.getMin(), out_qtype.getMax());
auto new_type = RankedTensorType::get(
in.getType().cast<RankedTensorType>().getShape(), new_qtype);
in.setType(new_type);
changed |= true;
}
if (changed)
return success();
else
return failure();
}
bool shouldPrint(top::MaskedFillOp op) const override { return false; }
};
struct CastInputCV18xxPattern : public OpRewriterPatternEx<tpu::CastOp> {
public:
CastInputCV18xxPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<tpu::CastOp>(context, "CastInputCV18xxPattern") {}
LogicalResult matchAndRewriteImpl(tpu::CastOp op,
PatternRewriter &rewriter) const override {
auto setOpResultType = [](Value value, Type eltType) {
auto shape = module::getShape(value);
auto type = RankedTensorType::get(shape, eltType);
value.setType(type);
};
auto prevOp = op->getOperand(0).getDefiningOp();
if (isa<tpu::ReshapeOp>(prevOp)) {
prevOp = prevOp->getOperand(0).getDefiningOp();
}
if (!isa<top::InputOp>(prevOp)) {
return failure();
}
auto storage_type = module::getStorageType(op->getResult(0));
if (storage_type.isIntOrIndex() &&
storage_type.getIntOrFloatBitWidth() == 16) {
// setOpResultType(prevOp->getOperand(0), storage_type);
setOpResultType(prevOp->getResult(0), storage_type);
setOpResultType(op->getOperand(0), storage_type);
rewriter.replaceOp(op, {op->getOperand(0)});
return success();
}
return failure();
}
bool shouldPrint(tpu::CastOp op) const override { return false; }
};
/**
* @brief Try insert tile since shapes cannot merge to 4d in some case
*/
template <typename OpTy>
struct TryInsertTileBinaryPattern : public OpRewriterPatternEx<OpTy> {
public:
TryInsertTileBinaryPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<OpTy>(context, "TryInsertTileBinaryPattern") {}
bool can_be_merged(int64_t a1, int64_t a2, int64_t b1, int64_t b2) const {
// case 0: both dims are same --- always true
if (a1 == b1 && a2 == b2)
return true;
// case 1: only one dim is same --- only when another is 1 can be merged
if ((a1 == b1 && a2 != b2 && a1 == 1) || (a1 != b1 && a2 == b2 && a2 == 1))
return true;
// case 2: both dims are not same --- only a or b broadcast can be merged
if (a1 != b1 && a2 != b2 && (a1 == a2 || b1 == b2))
return true;
return false;
}
static inline void merge_two_dims(std::vector<int64_t> &ashape,
std::vector<int64_t> &bshape, int dims,
int d_th) {
ashape[d_th] *= ashape[d_th + 1];
bshape[d_th] *= bshape[d_th + 1];
for (int i = d_th + 1; i < dims - 1; i++) {
ashape[i] = ashape[i + 1];
bshape[i] = bshape[i + 1];
}
}
bool canMergeTo4D(const std::vector<int64_t> &ashape,
const std::vector<int64_t> &bshape, int shape_dim) const {
std::vector<int64_t> ashape_(8, 1);
std::vector<int64_t> bshape_(8, 1);
for (int i = 0; i < ashape.size(); i++) {
ashape_[i] = ashape[i];
}
for (int i = 0; i < bshape.size(); i++) {
bshape_[i] = bshape[i];
}
if (shape_dim > 4) {
int i = 0;
while (i < shape_dim - 1) {
if (can_be_merged(ashape_[i], ashape_[i + 1], bshape_[i],
bshape_[i + 1])) {
merge_two_dims(ashape_, bshape_, shape_dim, i);
--shape_dim;
} else {
++i;
}
if (shape_dim == 4)
break;
}
}
return shape_dim <= 4;
}
bool needBroadcast(const std::vector<int64_t> &shape1,
const std::vector<int64_t> &shape2) const {
int dim1 = shape1.size();
int dim2 = shape2.size();
int maxDim = std::max(dim1, dim2);
for (int i = 1; i <= maxDim; ++i) {
int size1 = (dim1 - i >= 0) ? shape1[dim1 - i] : 1;
int size2 = (dim2 - i >= 0) ? shape2[dim2 - i] : 1;
if (size1 != size2 && (size1 != 1 || size2 != 1)) {
return true;
}
}
return false;
}
static void try_insert_tile(OpTy &op, PatternRewriter &rewriter, int idx,
int axis, int tile) {
Value opd = op.getOperand(idx);
auto def_op = opd.getDefiningOp();
auto input_shape = module::getShape(opd);
auto newType =
RankedTensorType::get(input_shape, module::getElementType(opd));
auto name = module::getName(opd).str();
if (opd && !isa<ReturnOp>(def_op)) {
name += "_" + module::getName(op.getOperation()).str();
}
name += "_tile";
auto loc = NameLoc::get(rewriter.getStringAttr(name));
std::vector<NamedAttribute> attrs;
std::vector<int64_t> weight_tile(input_shape.size(), 1);
weight_tile[axis] = tile;
attrs.emplace_back(
rewriter.getNamedAttr("tile", rewriter.getI64ArrayAttr(weight_tile)));
auto tileOp =
rewriter.create<top::TileOp>(loc, newType, ValueRange{opd}, attrs);
op->setOperand(idx, tileOp);
std::vector<int64_t> output_shape = input_shape;
output_shape[axis] = tile;
module::setShape(tileOp.getOutput(), output_shape);
}
LogicalResult matchAndRewriteImpl(OpTy op,
PatternRewriter &rewriter) const override {
int max_allow_dim_backend = 4;
Value out = op.getOutput();
if (isa<ReturnOp>(op))
return failure();
int opd_num = op.getNumOperands();
if (opd_num != 2)
return failure();
Value opd1 = op.getOperand(0);
Value opd2 = op.getOperand(1);
const std::vector<int64_t> shape1 = module::getShape(opd1);
const std::vector<int64_t> shape2 = module::getShape(opd2);
int shape_dim = std::max(shape1.size(), shape2.size());
if (needBroadcast(shape1, shape2) &&
!canMergeTo4D(shape1, shape2, shape_dim)) {
for (int i = 0; i <= shape_dim - max_allow_dim_backend; ++i) {
if (shape1[i] == shape2[i]) {
continue;
} else if (shape1[i] == 1) {
try_insert_tile(op, rewriter, 0, i, shape2[i]);
} else if (shape2[i] == 1) {
try_insert_tile(op, rewriter, 1, i, shape1[i]);
}
}
return success();
}
return failure();
}
bool shouldPrint(OpTy opTy) const override { return false; }
};
struct TryInsertTileMatMulPattern : public OpRewriterPatternEx<top::MatMulOp> {
public:
TryInsertTileMatMulPattern(mlir::MLIRContext *context)
: OpRewriterPatternEx<top::MatMulOp>(context,
"TryInsertTileMatMulPattern") {}
LogicalResult matchAndRewriteImpl(top::MatMulOp op,
PatternRewriter &rewriter) const override {
Value opd1 = op.getOperand(0);
Value opd2 = op.getOperand(1);
const std::vector<int64_t> shape1 = module::getShape(opd1);
const std::vector<int64_t> shape2 = module::getShape(opd2);
if (shape1.size() <= 2 || shape2.size() <= 2)
return failure();