forked from VeriSilicon/tflite-vx-delegate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
op_map.cc
3872 lines (3417 loc) · 148 KB
/
op_map.cc
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) 2021 Vivante Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*****************************************************************************/
#include <algorithm>
#include <array>
#include <cstring>
#include <iostream>
#include <limits>
#include <memory>
#include <numeric>
#include <tuple>
#include <vector>
#include "op_map.h"
#include "tensorflow/lite/context_util.h"
#include "tensorflow/lite/kernels/internal/reference/reference_ops.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/internal/types.h"
#include "tensorflow/lite/minimal_logging.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/lstm_shared.h"
#include "tim/vx/ops.h"
#include "tim/vx/tensor.h"
#include "utils.h"
#include "vsi_npu_custom_op.h"
#include "delegate_main.h"
#include "tim/vx/graph.h"
using namespace tflite;
using namespace tflite::ops::builtin;
namespace {
template <typename T>
bool CompareToMax(T* data, T max, int64_t bytes) {
int size = sizeof(T);
for (int i = 0; i< bytes/size;i++){
if(data[i] != max){
return true;
}
}
return false;
}
inline tim::vx::PadType TflitePadTypeToVsiPadType(TfLitePadding pad) {
switch (pad) {
case kTfLitePaddingUnknown:
return tim::vx::PadType::AUTO;
case kTfLitePaddingValid:
return tim::vx::PadType::VALID;
case kTfLitePaddingSame:
return tim::vx::PadType::SAME;
default:
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Unsuppoted pad type: %d", pad);
break;
}
return tim::vx::PadType::AUTO;
}
/// Insert activation layer before the `original_tensor`
/// Return the input tensor of new activation layer
std::shared_ptr<tim::vx::Tensor> ProcessFusedActivation(
vx::delegate::Delegate* delegate,
TfLiteFusedActivation fused_activation,
const std::shared_ptr<tim::vx::Tensor>& original_tensor) {
std::shared_ptr<tim::vx::Operation> op = nullptr;
switch (fused_activation) {
case kTfLiteActNone:
return original_tensor;
case kTfLiteActRelu:
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Relu>();
break;
case kTfLiteActReluN1To1:
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Relu1>();
break;
case kTfLiteActRelu6:
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Relu6>();
break;
case kTfLiteActTanh:
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Tanh>();
break;
case kTfLiteActSigmoid:
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Sigmoid>();
break;
default:
TFLITE_LOG_PROD(TFLITE_LOG_WARNING,
"Unsupported fused activation: %d",
fused_activation);
}
auto processed_tensor = delegate->GetGraph()->CreateTensor(
original_tensor->GetSpec().AsTransientSpec());
(*op).BindInput(processed_tensor);
(*op).BindOutput(original_tensor);
delegate->GetOps().push_back(op);
// delegate->GetTensors().push_back(processed_tensor);
// To prevent the id conflict between processed_tensor and model tensor,
// add an offset to the processed_tensor tensor id
delegate->GetTensors().insert(
std::make_pair(delegate->GetTensors().size() + 0x40000000, processed_tensor));
return processed_tensor;
}
std::shared_ptr<tim::vx::Tensor> ReverseInputTensor(
vx::delegate::Delegate* delegate,
const std::shared_ptr<tim::vx::Tensor>& original_tensor,
std::vector<int32_t> axis) {
auto spec = original_tensor->GetSpec();
spec.SetAttribute(tim::vx::TensorAttribute::TRANSIENT);
auto reversed_tensor = delegate->GetGraph()->CreateTensor(spec);
std::shared_ptr<tim::vx::Operation> op =
delegate->GetGraph()->CreateOperation<tim::vx::ops::Reverse>(axis);
(*op).BindInput(original_tensor);
(*op).BindOutput(reversed_tensor);
delegate->GetOps().push_back(op);
// delegate->GetTensors().push_back(reversed_tensor);
// To prevent the id conflict between processed_tensor and model tensor,
// add an offset to the processed_tensor tensor id
delegate->GetTensors().insert(
std::make_pair(delegate->GetTensors().size() + 0x40000000, reversed_tensor));
return reversed_tensor;
}
bool ResizeToTransposeConv(
vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
tim::vx::ResizeType resizeType,
uint32_t channel,
uint32_t scale_w,
uint32_t scale_h) {
uint32_t kernel_w = 0;
uint32_t kernel_h = 0;
uint32_t pad_w = 0;
uint32_t pad_h = 0;
std::vector<float> weight_data;
if (resizeType == tim::vx::ResizeType::BILINEAR) {
kernel_w = vx::delegate::utils::CalcWeightSizeForBilinear(scale_w);
kernel_h = vx::delegate::utils::CalcWeightSizeForBilinear(scale_h);
pad_w = vx::delegate::utils::CalcPadSizeForBilinear(scale_w);
pad_h = vx::delegate::utils::CalcPadSizeForBilinear(scale_h);
weight_data.resize(kernel_h * kernel_w * channel * channel);
vx::delegate::utils::GenerateWeightsDataForBilinear(
weight_data.data(),
{kernel_w, kernel_h, channel, channel},
scale_w,
scale_h);
} else if (resizeType == tim::vx::ResizeType::NEAREST_NEIGHBOR) {
kernel_w = scale_w;
kernel_h = scale_h;
pad_w = 0;
pad_h = 0;
weight_data.resize(kernel_h * kernel_w * channel * channel);
vx::delegate::utils::GenerateWeightDataForNearest(
weight_data.data(), {kernel_w, kernel_h, channel, channel});
}
auto weight_spec = tim::vx::TensorSpec(tim::vx::DataType::FLOAT32,
{kernel_w, kernel_h, channel, channel},
tim::vx::TensorAttribute::CONSTANT);
std::shared_ptr<tim::vx::Tensor> weight_tensor;
auto input_type = inputs[0]->GetDataType();
auto input_quant = inputs[0]->GetQuantization();
uint32_t kernel_size = kernel_h * kernel_w * channel * channel;
std::vector<uint8_t> weight_quant_data(kernel_size);
if (input_quant.Type() == tim::vx::QuantType::ASYMMETRIC) {
float scale = input_quant.Scales()[0];
int32_t zp = input_quant.ZeroPoints()[0];
if (input_type == tim::vx::DataType::INT8) {
std::vector<int8_t> quant_i8;
vx::delegate::utils::Quantize<int8_t>(weight_data, scale, zp, quant_i8);
weight_spec.SetDataType(tim::vx::DataType::INT8);
memcpy(weight_quant_data.data(), quant_i8.data(), kernel_size);
} else if (input_type == tim::vx::DataType::UINT8) {
std::vector<uint8_t> quant_u8;
vx::delegate::utils::Quantize<uint8_t>(weight_data, scale, zp, quant_u8);
weight_spec.SetDataType(tim::vx::DataType::UINT8);
memcpy(weight_quant_data.data(), quant_u8.data(), kernel_size);
}
weight_spec.SetQuantization(input_quant);
weight_tensor = delegate->GetGraph()->CreateTensor(
weight_spec, weight_quant_data.data());
} else {
weight_tensor =
delegate->GetGraph()->CreateTensor(weight_spec, weight_data.data());
}
std::array<uint32_t, 2> ksize{kernel_w, kernel_h};
std::array<uint32_t, 2> stride{scale_w, scale_h};
std::array<uint32_t, 2> output_padding{0, 0};
std::array<uint32_t, 4> pad{pad_w, pad_w, pad_h, pad_h};
auto op = delegate->GetGraph()->CreateOperation<tim::vx::ops::DeConv2d>(
channel,
tim::vx::PadType::SAME,
ksize,
stride,
output_padding,
pad,
1,
tim::vx::DataLayout::CWHN,
tim::vx::DataLayout::IcWHOc);
std::vector<std::shared_ptr<tim::vx::Tensor>> final_inputs;
final_inputs.push_back(inputs[0]);
final_inputs.push_back(weight_tensor);
(*op).BindInputs(final_inputs);
(*op).BindOutput(outputs[0]);
delegate->GetOps().push_back(std::move(op));
return true;
}
enum class ActionTargetType { INPUT, OUTPUT, STATE };
struct IAction {
virtual ActionTargetType GetActionTargetType() const = 0;
virtual bool process(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& states,
const void* params) const = 0;
virtual ~IAction(){};
};
template <ActionTargetType type, int Port>
struct ActionBase : public IAction {
ActionTargetType type_{type};
int port_{Port};
bool process(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& states,
const void* params) const override {
return true;
}
ActionTargetType GetActionTargetType() const final { return type_; }
};
template <int Port, typename T_Param>
struct FusedActivationAction
: public ActionBase<ActionTargetType::OUTPUT, Port> {
bool process(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& states,
const void* params) const final {
const auto builtin = reinterpret_cast<const T_Param*>(params);
outputs[this->port_] = ProcessFusedActivation(
delegate, builtin->activation, outputs[this->port_]);
return true;
}
};
template <typename T_Param, typename... Actions>
struct OpMapperBase : public vx::op_map::IOpMapper {
std::vector<std::unique_ptr<IAction>> actions_;
OpMapperBase() {
(void)std::initializer_list<int>{
0, (actions_.emplace_back(std::make_unique<Actions>()), 0)...};
}
size_t GetParamSize() const override { return sizeof(T_Param); }
bool IsSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
for (int i = 0; i < node->inputs->size; i++) {
int input_index = node->inputs->data[i];
if (input_index < 0) {
continue;
}
if (context->tensors[input_index].type == kTfLiteInt64 &&
registration->builtin_code != 130) {
// op 130 (BroadcastTo) can be bypassed because the next op will do broadcast automatically.
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Int64 input is not supported");
return false;
}
if (context->tensors[input_index].type == kTfLiteString) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "String input is not supported");
return false;
}
if (context->tensors[input_index].dims->size > 6) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"vx-delegate doesn't support the tensor whose dimension "
"is greater than 6.");
return false;
}
for (int j = 0; j < context->tensors[input_index].dims->size; j++) {
if (context->tensors[input_index].dims->data[j] == 0) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"vx-delegate doesn't support the tensor of which one "
"of dims is 0");
return false;
}
if ((context->tensors[input_index].dims->data[j] > 65535) && (j > 0)) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"vx-delegate doesn't support tensor height/width > "
"65535");
return false;
}
}
}
for (int i = 0; i < node->outputs->size; i++) {
int output_index = node->outputs->data[i];
if (context->tensors[output_index].type == kTfLiteInt16) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Int16 output is not supported");
return false;
}
if (context->tensors[output_index].type == kTfLiteInt64) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Int64 output is not supported");
return false;
}
for (int j = 0; j < context->tensors[output_index].dims->size; j++) {
if (context->tensors[output_index].dims->data[j] == 0) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"vx-delegate doesn't support the tensor of which one "
"of dims is 0");
return false;
}
}
}
return IsOpSupported(context, node, registration);
}
virtual bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const {
return true;
}
bool MapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>> inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>> outputs,
std::vector<std::shared_ptr<tim::vx::Tensor>> states,
const void* params) {
bool status = true;
for (auto& a : actions_) {
if (a->GetActionTargetType() == ActionTargetType::INPUT) {
a->process(delegate, inputs, outputs, states, params);
}
}
for (auto it = actions_.rbegin(); it != actions_.rend(); it++) {
if ((*it)->GetActionTargetType() == ActionTargetType::OUTPUT) {
(*it)->process(delegate, inputs, outputs, states, params);
}
}
status = HandleMapOp(delegate, inputs, outputs, states, params);
return status;
}
virtual bool HandleMapOp(
vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& states,
const void* params) {
return HandleMapOp(delegate, inputs, outputs, params);
}
virtual bool HandleMapOp(
vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) {
return false;
}
std::vector<uint32_t> ExtendReshape(const std::shared_ptr<tim::vx::Tensor>& base_shape_tensor,
const std::shared_ptr<tim::vx::Tensor>& required_reshape_tensor){
std::vector<uint32_t> shape (base_shape_tensor->GetShape().size());
std::vector<uint32_t> reshape_param;
for(int i = 0; i < base_shape_tensor->GetShape().size();i++){
shape[i] = i < required_reshape_tensor->GetShape().size() ?
required_reshape_tensor->GetShape()[i] : 1;
reshape_param.push_back(shape[i]);
}
return reshape_param;
}
std::vector<std::shared_ptr<tim::vx::Tensor>> HandleNeedReshapeOp(
vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) {
bool reshape_required = (inputs[0]->GetShape().size() != inputs[1]->GetShape().size());
std::vector<std::shared_ptr<tim::vx::Tensor>> elementwise_inputs;
for (auto &t : inputs){
if(delegate->map_BroadcastTo.find(t) != delegate->map_BroadcastTo.end())
{
t = delegate->map_BroadcastTo[t];
}
}
if (reshape_required) {
int base_shape_idx = inputs[0]->GetShape().size() >
inputs[1]->GetShape().size()? 0 : 1;
std::vector<uint32_t> reshape_param;
reshape_param = ExtendReshape(inputs[base_shape_idx], inputs[1-base_shape_idx]);
tim::vx::TensorSpec reshape_spec (inputs[1-base_shape_idx]->GetSpec().AsTransientSpec());
reshape_spec.SetShape(reshape_param);
auto reshape_out = delegate->GetGraph()->CreateTensor(reshape_spec);
auto op_reshape =
delegate->GetGraph()->CreateOperation<tim::vx::ops::Reshape>(
reshape_param);
(*op_reshape).BindInput(inputs[1-base_shape_idx]).BindOutput(reshape_out);
if(base_shape_idx == 0){
elementwise_inputs.push_back(inputs[base_shape_idx]);
elementwise_inputs.push_back(reshape_out);
}
else{
elementwise_inputs.push_back(reshape_out);
elementwise_inputs.push_back(inputs[base_shape_idx]);
}
return elementwise_inputs;
}
return inputs;
}
};
void TransposeNHWC2NCHW(std::vector<uint8_t>& perm_data, uint8_t* data, const std::vector<uint32_t>& nhwc_shape){
int N=nhwc_shape[0], H=nhwc_shape[1], W=nhwc_shape[2], C=nhwc_shape[3];
int old_idx, new_idx;
for (int n=0; n<N; ++n) {
for (int h=0; h<H; ++h) {
for (int w=0; w<W; ++w) {
for (int c=0; c<C; ++c) {
old_idx = n*H*W*C + h*W*C + w*C + c;
new_idx = n*C*H*W + c*H*W + h*W + w;
perm_data[new_idx] = *(data + old_idx);
}
}
}
}
}
} // namespace
namespace vx {
namespace op_map {
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
static std::vector<uint8_t> weight_buff;
static std::string md5_calculate;
static const std::string md5_yolov4("1A5FF0C2D9D6377CC53CE56BE85663E8");
static int conv_count = 0;
static uint8_t* yolo_const_tensor1_data; //first const tensor data for yolo op
static uint8_t* yolo_const_tensor2_data; //second const tensor data for yolo op
#endif
template <typename T_OperationType>
struct SimpleOpMapper : public OpMapperBase<EmptyStructPlaceholder> {
std::string name_;
SimpleOpMapper(std::string name) : name_(name) {}
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
if (!((conv_count == 18 || conv_count == 21) && md5_calculate == md5_yolov4)) {
#endif
TFLITE_LOG(TFLITE_LOG_INFO, "Creating %s op", name_.c_str());
auto op = delegate->GetGraph()->CreateOperation<T_OperationType>();
(*op).BindInputs(inputs).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
}
#endif
return true;
}
};
template <typename T_OperationType>
struct PowMapper : public SimpleOpMapper<T_OperationType> {
PowMapper(std::string name) : SimpleOpMapper<T_OperationType>(name) {}
bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
auto input_tensor0 = context->tensors[node->inputs->data[0]];
auto input_tensor1 = context->tensors[node->inputs->data[1]];
if (input_tensor0.type == kTfLiteInt32 &&
input_tensor1.type == kTfLiteInt32) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"I32 input/I32 output is not supported in pow.");
return false;
}
return true;
}
};
template <typename T_OperationType>
struct DequantizeMapper : public SimpleOpMapper<T_OperationType> {
DequantizeMapper(std::string name) : SimpleOpMapper<T_OperationType>(name) {}
bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
auto input_tensor = context->tensors[node->inputs->data[0]];
auto output_tensor = context->tensors[node->outputs->data[0]];
const TfLiteAffineQuantization* params =
reinterpret_cast<const TfLiteAffineQuantization*>(
input_tensor.quantization.params);
if ((input_tensor.type == kTfLiteInt16 ||
input_tensor.type == kTfLiteFloat16) &&
output_tensor.type == kTfLiteFloat32 &&
input_tensor.quantization.type == kTfLiteAffineQuantization) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"ASYM I16/F16 input / F32 output is not supported");
return false;
}
if ((input_tensor.type == kTfLiteInt8 ||
input_tensor.type == kTfLiteUInt8) &&
output_tensor.type == kTfLiteFloat32 &&
input_tensor.quantization.type == kTfLiteAffineQuantization &&
params->scale->size>1) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"SYMM PerChannel I8/U8 input / F32 output is not supported");
return false;
}
return true;
}
};
template <typename T_OperationType>
struct QuantizeMapper : public SimpleOpMapper<T_OperationType> {
QuantizeMapper(std::string name) : SimpleOpMapper<T_OperationType>(name) {}
bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
auto input_tensor = context->tensors[node->inputs->data[0]];
auto output_tensor = context->tensors[node->outputs->data[0]];
const TfLiteAffineQuantization* params =
reinterpret_cast<const TfLiteAffineQuantization*>(
output_tensor.quantization.params);
if (input_tensor.type == kTfLiteInt32 &&
(output_tensor.type == kTfLiteUInt8||output_tensor.type == kTfLiteInt8) &&
input_tensor.quantization.type == kTfLiteAffineQuantization) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"ASYM I16 input / ASYM U8/ASYM I8 output is not supported");
return false;
}
if (input_tensor.type == kTfLiteInt16 &&
(output_tensor.type == kTfLiteUInt8||output_tensor.type == kTfLiteInt8) &&
input_tensor.quantization.type == kTfLiteAffineQuantization) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"ASYM I32 input / ASYM U8/ASYM I8 output is not supported");
return false;
}
if (input_tensor.type == kTfLiteInt16 &&
output_tensor.type == kTfLiteInt32 &&
input_tensor.quantization.type == kTfLiteAffineQuantization) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"ASYM I16 input / ASYM I32 output is not supported");
return false;
}
if (input_tensor.type == kTfLiteFloat32 &&
(output_tensor.type == kTfLiteUInt8||output_tensor.type == kTfLiteInt8) &&
output_tensor.quantization.type == kTfLiteAffineQuantization &&
params->scale->size>1) {
TFLITE_LOG_PROD(
TFLITE_LOG_ERROR,
"F32 input / SYMM PerChannel I8/U8 output is not supported");
return false;
}
return true;
}
};
template <typename T_OperationType, typename T_Param>
struct SimpleOpWithFusedActivationMapper
: public OpMapperBase<T_Param, FusedActivationAction<0, T_Param>> {
std::string name_;
SimpleOpWithFusedActivationMapper(std::string name) : name_(name) {}
bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
const auto builtin = reinterpret_cast<const T_Param*>(node->builtin_data);
auto in_tensor0 = context->tensors[node->inputs->data[0]];
auto out_tensor0 = context->tensors[node->outputs->data[0]];
if (in_tensor0.type == kTfLiteInt16 &&
(out_tensor0.type == kTfLiteUInt8 || out_tensor0.type == kTfLiteInt8) &&
in_tensor0.quantization.type == kTfLiteAffineQuantization &&
out_tensor0.quantization.type == kTfLiteAffineQuantization) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"ASYM I16 input0 / ASYM U8/I8 output is not supported");
return false;
}
if (builtin->activation == kTfLiteActReluN1To1 &&
context->tensors[node->inputs->data[0]].type == kTfLiteInt32 &&
context->tensors[node->outputs->data[0]].type == kTfLiteInt32) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"I32 input/I32 output is not supported in Relu1.");
return false;
}
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
static int add_cnt = 0;
if(registration->builtin_code == 0 && node->inputs->size == 2) {
auto in_tensor1 = context->tensors[node->inputs->data[1]];
++add_cnt;
if(add_cnt == 1 && in_tensor1.allocation_type == kTfLiteMmapRo){
yolo_const_tensor1_data = GetTensorData<uint8_t>(&in_tensor1);
}
if (add_cnt == 4 && in_tensor1.allocation_type == kTfLiteMmapRo){
yolo_const_tensor2_data = GetTensorData<uint8_t>(&in_tensor1);
}
}
#endif
return true;
}
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
if (!((conv_count == 18 || conv_count == 21) && md5_calculate == md5_yolov4)) {
#endif
TFLITE_LOG(TFLITE_LOG_INFO, "Creating %s op", name_.c_str());
auto reshaped_inputs = this->HandleNeedReshapeOp(delegate, inputs, outputs, params);
auto op = delegate->GetGraph()->CreateOperation<T_OperationType>();
(*op).BindInputs(reshaped_inputs);
(*op).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
}
#endif
return true;
}
};
template <typename T_OperationType>
struct SimpleOpWithBroadcastNoActivationMapper
: public OpMapperBase<EmptyStructPlaceholder> {
std::string name_;
SimpleOpWithBroadcastNoActivationMapper(std::string name) : name_(name) {}
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating %s op", name_.c_str());
auto reshaped_inputs = this->HandleNeedReshapeOp(delegate, inputs, outputs, params);
auto op = delegate->GetGraph()->CreateOperation<T_OperationType>();
(*op).BindInputs(reshaped_inputs);
(*op).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
return true;
}
};
using MaximumMapper =
SimpleOpWithBroadcastNoActivationMapper<tim::vx::ops::Maximum>;
struct MinimumMapper : public OpMapperBase<tim::vx::ops::Minimum> {
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating Minimum op");
if (inputs[1]->GetSpec().attr_ == tim::vx::TensorAttribute::CONSTANT &&
inputs[1]->GetQuantization() == inputs[0]->GetQuantization()) {
int64_t bytes = inputs[1]->GetSpec().GetByteSize();
void* data_ptr = malloc(bytes);
bool NeedBind = false;
inputs[1]->CopyDataFromTensor(data_ptr);
// bool NeedBind = false;
switch (inputs[1]->GetDataType()) {
case tim::vx::DataType::INT8: {
int8_t* int8_data = (int8_t*)data_ptr;
int8_t i8max = std::numeric_limits<int8_t>::max();
NeedBind = CompareToMax(int8_data, i8max, bytes);
} break;
case tim::vx::DataType::UINT8: {
uint8_t* uint8_data = (uint8_t*)data_ptr;
uint8_t u8max = std::numeric_limits<uint8_t>::max();
NeedBind = CompareToMax(uint8_data, u8max, bytes);
} break;
case tim::vx::DataType::INT16: {
int16_t* int16_data = (int16_t*)data_ptr;
int16_t i16max = std::numeric_limits<int16_t>::max();
NeedBind = CompareToMax(int16_data, i16max, bytes);
} break;
case tim::vx::DataType::UINT16: {
uint16_t* uint16_data = (uint16_t*)data_ptr;
uint16_t u16max = std::numeric_limits<uint16_t>::max();
NeedBind = CompareToMax(uint16_data, u16max, bytes);
} break;
case tim::vx::DataType::INT32: {
int32_t* int32_data = (int32_t*)data_ptr;
int32_t i32max = std::numeric_limits<int32_t>::max();
NeedBind = CompareToMax(int32_data, i32max, bytes);
} break;
case tim::vx::DataType::UINT32: {
uint32_t* uint32_data = (uint32_t*)data_ptr;
uint32_t u32max = std::numeric_limits<uint32_t>::max();
NeedBind = CompareToMax(uint32_data, u32max, bytes);
} break;
case tim::vx::DataType::FLOAT16:
case tim::vx::DataType::FLOAT32:
default:
NeedBind = true;
break;
}
if (!NeedBind) {
std::map<int32_t, std::shared_ptr<tim::vx::Tensor>>::iterator it =
delegate->GetTensors().begin();
int32_t tensor_index = -1;
for (it; it != delegate->GetTensors().end(); it++) {
if (it->second == outputs[0]) {
tensor_index = it->first;
break;
}
}
delegate->GetTensors()[tensor_index] =
inputs[0]; // update tensormap to bypass operation
return true;
}
} // handle constant second input
auto reshaped_inputs =
this->HandleNeedReshapeOp(delegate, inputs, outputs, params);
auto op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Minimum>();
(*op).BindInputs(reshaped_inputs); // Bind if second input is not
// constant or not suitable to bypass
(*op).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
return true;
} // handle map op
};
template <typename T_Param>
struct Conv2dKind
: public OpMapperBase<T_Param, FusedActivationAction<0, T_Param>> {};
struct FullyConnectedMapper
: public OpMapperBase<
TfLiteFullyConnectedParams,
FusedActivationAction<0, TfLiteFullyConnectedParams>> {
bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const override {
const auto builtin =
reinterpret_cast<const TfLiteFullyConnectedParams*>(node->builtin_data);
auto input_tensor = context->tensors[node->inputs->data[0]];
auto weight_tensor = context->tensors[node->inputs->data[1]];
if (input_tensor.type != weight_tensor.type) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"hybrid data type is not supported in fullyconnected.");
return false;
}
if (builtin->weights_format ==
kTfLiteFullyConnectedWeightsFormatShuffled4x16Int8) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Shuffled weight is not supported");
return false;
}
for (int i = 0; i < node->inputs->size; i++) {
int input_index = node->inputs->data[i];
if (input_index >= 0 && input_index < context->tensors_size &&
context->tensors[input_index].type == kTfLiteInt16) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR, "Int16 input is not supported");
return false;
}
}
return true;
}
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating fully connected op");
const auto builtin =
reinterpret_cast<const TfLiteFullyConnectedParams*>(params);
auto input_tensor = inputs[0];
auto weight_tensor = inputs[1];
uint32_t temp_batch = 1;
if (input_tensor->GetShape().size() > 2 ||
(input_tensor->GetShape().size() == 2 &&
input_tensor->GetShape()[0] != weight_tensor->GetShape()[0])) {
uint32_t input_size = weight_tensor->GetShape()[0];
uint32_t total_input_size = 1;
for (int i = 0; i < input_tensor->GetShape().size(); i++) {
total_input_size *= input_tensor->GetShape()[i];
}
temp_batch = total_input_size / input_size;
auto reshape_output = delegate->GetGraph()->CreateTensor(
input_tensor->GetSpec().AsTransientSpec());
std::vector<uint32_t> new_shape{input_size, temp_batch};
auto reshape_op =
delegate->GetGraph()->CreateOperation<tim::vx::ops::Reshape>(
new_shape);
(*reshape_op).BindInput(inputs[0]);
(*reshape_op).BindOutput(reshape_output);
delegate->GetOps().push_back(reshape_op);
inputs[0] = reshape_output;
}
auto op =
delegate->GetGraph()->CreateOperation<tim::vx::ops::FullyConnected>(
0, weight_tensor->GetShape()[1]);
(*op).BindInputs(inputs);
if (outputs[0]->GetShape().size() > 2) {
std::vector<uint32_t> real_output_shape = { weight_tensor->GetShape()[1],
temp_batch};
tim::vx::TensorSpec real_output_spec(outputs[0]->GetSpec());
real_output_spec.SetShape(real_output_shape);
auto real_output = delegate->GetGraph()->CreateTensor(real_output_spec);
(*op).BindOutput(real_output);
delegate->GetOps().push_back(std::move(op));
auto reshape_op =
delegate->GetGraph()->CreateOperation<tim::vx::ops::Reshape>(
outputs[0]->GetShape());
(*reshape_op).BindInput(real_output);
(*reshape_op).BindOutput(outputs[0]);
delegate->GetOps().push_back(reshape_op);
}
else {
(*op).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
}
return true;
}
};
struct SoftmaxMapper : public OpMapperBase<TfLiteSoftmaxParams> {
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating softmax op");
auto builtin = reinterpret_cast<const TfLiteSoftmaxParams*>(params);
auto op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Softmax>(
builtin->beta, 0);
(*op).BindInputs(inputs).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
return true;
}
};
struct Conv2dMapper : public Conv2dKind<TfLiteConvParams> {
virtual bool IsOpSupported(TfLiteContext* context,
TfLiteNode* node,
const TfLiteRegistration* registration) const {
auto input_tensor = context->tensors[node->inputs->data[0]];
auto weight_tensor = context->tensors[node->inputs->data[1]];
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
if(weight_tensor.allocation_type == kTfLiteMmapRo) {
uint8_t* data = GetTensorData<uint8_t>(&weight_tensor);
std::vector<uint8_t> temp_buff(data, data + weight_tensor.bytes);
int length = weight_tensor.bytes;
static int cnt = 0;
if (cnt % 2 == 0) {
length < 512
? std::copy_n(temp_buff.begin(), temp_buff.size(), std::back_inserter(weight_buff))
: std::copy_n(temp_buff.begin(), 512, std::back_inserter(weight_buff));
}
++cnt;
if (cnt == 21) {
md5_calculate = tim::vx::calculateMd5Secret32(std::string((const char*)weight_buff.data(), weight_buff.size()));
}
}
#endif
if (input_tensor.type != weight_tensor.type) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"hybrid data type is not supported in conv2d.");
return false;
}
bool is_grouped = (input_tensor.dims->data[3] != weight_tensor.dims->data[3]);
bool is_batched = (input_tensor.dims->data[0] != 1);
if (is_grouped && is_batched) {
TFLITE_LOG_PROD(TFLITE_LOG_ERROR,
"batch is not supported in grouped conv2d.");
return false;
}
return true;
}
bool HandleMapOp(vx::delegate::Delegate* delegate,
std::vector<std::shared_ptr<tim::vx::Tensor>>& inputs,
std::vector<std::shared_ptr<tim::vx::Tensor>>& outputs,
const void* params) override {
// input layout CWHN, weight layout IWHO
uint32_t groups = inputs[0]->GetShape()[0] / inputs[1]->GetShape()[0];
uint32_t weights = inputs[1]->GetShape()[3];
uint32_t kernel_h = inputs[1]->GetShape()[2];
uint32_t kernel_w = inputs[1]->GetShape()[1];
const auto builtin = reinterpret_cast<const TfLiteConvParams*>(params);
std::shared_ptr<tim::vx::Operation> op;
if (inputs[0]->GetShape()[0] == inputs[1]->GetShape()[0]) {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating Conv2d op");
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::Conv2d>(
static_cast<int32_t>(weights),
TflitePadTypeToVsiPadType(builtin->padding),
std::array<uint32_t, 2>({kernel_w, kernel_h}),
std::array<uint32_t, 2>(
{builtin->stride_width, builtin->stride_height}),
std::array<uint32_t, 2>({builtin->dilation_width_factor,
builtin->dilation_height_factor}),
0,
tim::vx::DataLayout::CWHN,
tim::vx::DataLayout::IcWHOc);
} else {
TFLITE_LOG(TFLITE_LOG_INFO, "Creating Grouped Conv2d op");
op = delegate->GetGraph()->CreateOperation<tim::vx::ops::GroupedConv2d>(
TflitePadTypeToVsiPadType(builtin->padding),
std::array<uint32_t, 2>(
{builtin->stride_width, builtin->stride_height}),
std::array<uint32_t, 2>({builtin->dilation_width_factor,
builtin->dilation_height_factor}),
groups,
tim::vx::DataLayout::CWHN,
tim::vx::DataLayout::IcWHOc);
}
(*op).BindInputs(inputs);
(*op).BindOutputs(outputs);
delegate->GetOps().push_back(std::move(op));
#ifdef VSI_FEAT_OP_CUSTOM_TINY_YOLOV4_POSTPROCESS
++conv_count;
if (md5_calculate == md5_yolov4 && (conv_count == 18 || conv_count == 21)) {
int output_idx;
if(conv_count == 18) {