-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathConversionUtils.hpp
4214 lines (3565 loc) · 152 KB
/
ConversionUtils.hpp
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 © 2017 Arm Ltd and Contributors. All rights reserved.
// SPDX-License-Identifier: MIT
//
#pragma once
#include "Utils.hpp"
#include <armnn/ArmNN.hpp>
#include <armnn/ILayerSupport.hpp>
#include <armnn/BackendHelper.hpp>
#include <armnn/utility/Assert.hpp>
#include <armnn/utility/IgnoreUnused.hpp>
#include <armnn/utility/NumericCast.hpp>
#include <armnnUtils/DataLayoutIndexed.hpp>
#include <armnnUtils/Transpose.hpp>
#include "1.0/FullyConnected.hpp"
#include <ActivationFunctor.h>
#include <CpuExecutor.h>
#include <OperationsUtils.h>
#include <armnnUtils/FloatingPointComparison.hpp>
#include <log/log.h>
#include <vector>
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunneeded-internal-declaration"
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
namespace armnn_driver
{
///
/// Helper classes
///
#ifdef ARMNN_ANDROID_R
using OperandType = android::nn::OperandType;
#endif
struct ConversionData
{
ConversionData(const std::vector<armnn::BackendId>& backends)
: m_Backends(backends)
, m_Network(nullptr, nullptr)
, m_DynamicInputsEncountered(false)
{}
const std::vector<armnn::BackendId> m_Backends;
armnn::INetworkPtr m_Network;
std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
std::vector<android::nn::RunTimePoolInfo> m_MemPools;
bool m_DynamicInputsEncountered;
};
class LayerInputHandle
{
public:
LayerInputHandle();
LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
bool IsValid() const;
void Connect(armnn::IInputSlot& inputSlot);
void Disconnect(armnn::IInputSlot& inputSlot);
const armnn::TensorInfo& GetTensorInfo() const;
private:
armnn::IOutputSlot* m_OutputSlot;
bool m_Valid;
armnn::TensorInfo m_TensorInfo;
};
class ConstTensorPin
{
public:
// Creates an invalid tensor pin (can be used to signal errors)
// The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
ConstTensorPin(bool optional = false);
// @param tensorInfo TensorInfo associated with the tensor.
// @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
// the model being converted.
// @param numBytes Number of bytes for the tensor data.
ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
const armnn::PermutationVector& mappings);
ConstTensorPin(const ConstTensorPin& other) = delete;
ConstTensorPin(ConstTensorPin&& other) = default;
bool IsValid() const;
bool IsOptional() const;
const armnn::ConstTensor& GetConstTensor() const;
const armnn::ConstTensor* GetConstTensorPtr() const;
private:
armnn::ConstTensor m_ConstTensor;
// Owned memory for swizzled tensor data, only required if the tensor needed
// swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
// the pools associated with the model being converted.
std::vector<uint8_t> m_SwizzledTensorData;
// optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
bool m_Optional;
};
} // namespace armnn_driver
///
/// Utility functions
///
namespace
{
using namespace armnn_driver;
using namespace android::nn;
// Convenience function to log the reason for failing to convert a model.
// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
template<class... Args>
static bool Fail(const char* formatStr, Args&&... args)
{
ALOGD(formatStr, std::forward<Args>(args)...);
return false;
}
// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
try \
{ \
for (auto&& backendId : backends) \
{ \
auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
if (layerSupportObject) \
{ \
std::string reasonIfUnsupported; \
supported = \
layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
if (supported) \
{ \
break; \
} \
else \
{ \
if (reasonIfUnsupported.size() > 0) \
{ \
ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
} \
else \
{ \
ALOGD("%s: not supported by armnn", funcName); \
} \
} \
} \
else \
{ \
ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
} \
} \
if (!supported) \
{ \
ALOGD("%s: not supported by any specified backend", funcName); \
} \
} \
catch (const armnn::InvalidArgumentException &e) \
{ \
throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
}
template<typename HalOperand>
armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
{
return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
}
inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
{
return type == V1_0::OperandType::TENSOR_FLOAT32 ||
type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
type == V1_0::OperandType::TENSOR_INT32;
}
#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
// Support within the 1.2 driver for specific tensor data types
inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
{
return type == V1_2::OperandType::BOOL ||
type == V1_2::OperandType::TENSOR_BOOL8 ||
type == V1_2::OperandType::TENSOR_FLOAT16 ||
type == V1_2::OperandType::TENSOR_FLOAT32 ||
type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
type == V1_2::OperandType::TENSOR_INT32;
}
#endif
#ifdef ARMNN_ANDROID_NN_V1_3
// Support within the 1.3 driver for specific tensor data types
inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
{
return type == V1_3::OperandType::BOOL ||
type == V1_3::OperandType::TENSOR_BOOL8 ||
type == V1_3::OperandType::TENSOR_FLOAT16 ||
type == V1_3::OperandType::TENSOR_FLOAT32 ||
type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
type == V1_3::OperandType::TENSOR_INT32;
}
#endif
inline bool IsBool(V1_0::Operand)
{
return false;
}
inline bool Is12OrLaterOperand(V1_0::Operand)
{
return false;
}
#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
inline bool IsBool(V1_2::Operand operand)
{
return operand.type == V1_2::OperandType::BOOL;
}
/// Checks if a operand is 1_2 Operand
inline bool Is12OrLaterOperand(V1_2::Operand)
{
return true;
}
#endif
#ifdef ARMNN_ANDROID_NN_V1_3
inline bool IsBool(V1_3::Operand operand)
{
return operand.type == V1_3::OperandType::BOOL;
}
/// Checks if a operand is 1_2 Operand
inline bool Is12OrLaterOperand(V1_3::Operand)
{
return true;
}
#endif
template<typename LayerHandleType>
armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
LayerHandleType& inputLayer,
armnn::TensorInfo reshapeInfo)
{
armnn::ReshapeDescriptor reshapeDescriptor;
reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
ARMNN_ASSERT(reshapeLayer != nullptr);
// Attach the input layer to the reshape layer
inputLayer.Connect(reshapeLayer->GetInputSlot(0));
reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
return *reshapeLayer;
}
bool BroadcastTensor(LayerInputHandle& input0,
LayerInputHandle& input1,
armnn::IConnectableLayer* startLayer,
ConversionData& data)
{
ARMNN_ASSERT(startLayer != nullptr);
const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
if (inputDimensions0 == inputDimensions1)
{
// The inputs have the same number of dimensions, simply connect them to the given layer as they are
input0.Connect(startLayer->GetInputSlot(0));
input1.Connect(startLayer->GetInputSlot(1));
return true;
}
// Since the number of dimensions do not match then we need to add degenerate dimensions
// to the "smaller" tensor using a reshape, while keeping the order of the inputs.
unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
unsigned int sizeDifference = std::abs(armnn::numeric_cast<int>(inputDimensions0) -
armnn::numeric_cast<int>(inputDimensions1));
bool input0IsSmaller = inputDimensions0 < inputDimensions1;
LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
const armnn::TensorShape& smallShape = smallInfo.GetShape();
std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
{
reshapedDimensions[i] = smallShape[i - sizeDifference];
}
armnn::TensorInfo reshapedInfo = smallInfo;
reshapedInfo.SetShape(armnn::TensorShape{ armnn::numeric_cast<unsigned int>(reshapedDimensions.size()),
reshapedDimensions.data() });
// RehsapeDescriptor that is ignored in the IsReshapeSupported function
armnn::ReshapeDescriptor reshapeDescriptor;
bool isSupported = false;
FORWARD_LAYER_SUPPORT_FUNC(__func__,
IsReshapeSupported,
data.m_Backends,
isSupported,
smallInfo,
reshapedInfo,
reshapeDescriptor);
if (!isSupported)
{
return false;
}
ARMNN_ASSERT(data.m_Network != nullptr);
armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
if (input0IsSmaller)
{
// Input0 is the "smaller" tensor, connect the reshape layer as follows:
//
// Input0 Input1
// | |
// Reshape |
// \ /
// StartLayer
reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
input1.Connect(startLayer->GetInputSlot(1));
}
else
{
// Input1 is the "smaller" tensor, connect the reshape layer as follows:
//
// Input0 Input1
// | |
// | Reshape
// \ /
// StartLayer
input0.Connect(startLayer->GetInputSlot(0));
reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
}
return true;
}
void CalcPadding(uint32_t input,
uint32_t kernel,
uint32_t stride,
uint32_t& outPadHead,
uint32_t& outPadTail,
android::nn::PaddingScheme scheme)
{
int32_t padHead;
int32_t padTail;
calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
outPadHead = armnn::numeric_cast<uint32_t>(padHead);
outPadTail = armnn::numeric_cast<uint32_t>(padTail);
}
#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
uint32_t& outPadTail, android::nn::PaddingScheme scheme)
{
int32_t padHead;
int32_t padTail;
calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
outPadHead = armnn::numeric_cast<uint32_t>(padHead);
outPadTail = armnn::numeric_cast<uint32_t>(padTail);
}
void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
int32_t& outPadTail, android::nn::PaddingScheme scheme)
{
calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
}
#endif
Shape GetOperandShape(const V1_0::Operand& operand)
{
Shape shape;
shape.type = android::nn::OperandType(operand.type);
shape.dimensions = operand.dimensions;
shape.scale = operand.scale;
shape.offset = operand.zeroPoint;
return shape;
}
#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Shape GetOperandShape(const V1_2::Operand& operand)
{
Shape shape;
shape.type = android::nn::OperandType(operand.type);
shape.dimensions = operand.dimensions;
shape.scale = operand.scale;
shape.offset = operand.zeroPoint;
return shape;
}
#endif
#ifdef ARMNN_ANDROID_NN_V1_3
Shape GetOperandShape(const V1_3::Operand& operand)
{
Shape shape;
shape.type = OperandType(operand.type);
shape.dimensions = operand.dimensions;
shape.scale = operand.scale;
shape.offset = operand.zeroPoint;
return shape;
}
#endif
// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
// what AndroidNN requires. However for some of the AndroidNN tests the values don't exactly match so
// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
// user (us, in this case) to ensure they match.
void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
const armnn::TensorInfo& weightInfo,
const armnn::TensorInfo& inputInfo)
{
if (weightInfo.HasPerAxisQuantization())
{
// NOTE: Bias scale is always set to 0 for per-axis quantization and
// it needs to be calculated: scale[i] = input_scale * weight_scale[i]
auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
{
return biasScale * inputInfo.GetQuantizationScale();
};
std::vector<float> biasScales(weightInfo.GetQuantizationScales());
std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
biasInfo.SetQuantizationScales(biasScales);
biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
ALOGV("Bias quantization params have been updated for per-axis quantization");
}
else
{
const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
if (biasInfo.GetQuantizationScale() != expectedBiasScale)
{
if (armnnUtils::within_percentage_tolerance(biasInfo.GetQuantizationScale(), expectedBiasScale, 1.0f))
{
ALOGW("Bias quantization scale has been modified to match input * weights");
biasInfo.SetQuantizationScale(expectedBiasScale);
}
}
}
}
// 4D Tensor Permutations
const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
const armnn::PermutationVector IdentityPermutation3D({ 0U, 1U, 2U });
const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
// 3D Permutation Vectors
const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
template<typename OSlot>
armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
const armnn::PermutationVector& mappings)
{
// Add swizzle layer
armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
ARMNN_ASSERT(layer != nullptr);
// Connect input to swizzle layer
input.Connect(layer->GetInputSlot(0));
// Setup swizzled output
const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
layer->GetOutputSlot(0).SetTensorInfo(outInfo);
return *layer;
}
bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
const armnn::TensorShape & outputShape,
uint32_t concatDim)
{
// Validate the output shape is correct given the input shapes (which have just been validated)
unsigned int numDimensions = inputShapes[0].GetNumDimensions();
if (outputShape.GetNumDimensions() != numDimensions)
{
return Fail("%s: Output shape has wrong number of dimensions", __func__);
}
unsigned int outputSizeAlongConcatenatedDimension = 0;
for (unsigned int i = 0; i < inputShapes.size(); i++)
{
outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
}
for (unsigned int i = 0; i < numDimensions; ++i)
{
if (i == concatDim)
{
if (outputShape[i] != outputSizeAlongConcatenatedDimension)
{
return Fail(
"%s: Invalid output shape for dimension %d (%d != %d)",
__func__,
i,
outputShape[i],
outputSizeAlongConcatenatedDimension);
}
}
else
{
if (outputShape[i] != inputShapes[0][i])
{
return Fail("%s: Invalid output shape", __func__);
}
}
}
return true;
}
bool RequiresReshape(armnn::TensorShape & inputShape)
{
return inputShape.GetNumDimensions() < 3;
}
void SwizzleInputs(armnn::INetwork& network,
std::vector<LayerInputHandle>& inputs,
std::vector<armnn::TensorShape>& inputShapes,
const armnn::PermutationVector& mapping)
{
if (!mapping.IsEqual(IdentityPermutation4D))
{
size_t nInputs = inputs.size();
for (size_t i=0; i<nInputs; ++i)
{
// add swizzle layer
armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
auto& outputSlot = swizzleLayer.GetOutputSlot(0);
auto& outputInfo = outputSlot.GetTensorInfo();
// replace inputs with the swizzled ones
inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
}
}
}
bool TransposeInputTensors(ConversionData& data,
std::vector<LayerInputHandle>& inputs,
std::vector<armnn::TensorShape>& inputShapes,
const armnn::PermutationVector& mapping)
{
// If we have a IdentityPermutation4D or IdentityPermutation3D then we are not permuting
if (!mapping.IsEqual(IdentityPermutation4D) && !mapping.IsEqual(IdentityPermutation3D))
{
armnn::TensorInfo outputTransposeInfo;
size_t nInputs = inputs.size();
for (size_t i=0; i<nInputs; ++i)
{
// check permute layer
armnn::TransposeDescriptor transposeDesc;
transposeDesc.m_DimMappings = mapping;
outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
bool isSupported = false;
FORWARD_LAYER_SUPPORT_FUNC(__func__,
IsTransposeSupported,
data.m_Backends,
isSupported,
inputs[i].GetTensorInfo(),
outputTransposeInfo,
transposeDesc);
if (!isSupported)
{
return false;
}
}
SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
}
return true;
}
bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
int32_t & concatDimension,
std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
{
bool needPermute = false;
ARMNN_ASSERT(numberOfDimensions >= 3);
// ArmNN uses Compute Library subtensors to perform concatenation
// This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
// or along dimension 0 or 2 for a 3-D tensor.
if (numberOfDimensions == 4 && concatDimension == 2)
{
concatDimension = 1;
permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
needPermute = true;
}
else if (numberOfDimensions == 3 && concatDimension == 1)
{
concatDimension = 0;
permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
needPermute = true;
}
// If the tensor is 3-D and the concat dimension is 2 then we don't need to permute but we do need to change the
// permutation identity to only have 3 dimensions
else if (numberOfDimensions == 3 && concatDimension == 2)
{
permutationPair = std::make_pair(IdentityPermutation3D, IdentityPermutation3D);
}
return needPermute;
}
} // anonymous namespace
namespace armnn_driver
{
//// Creates an ArmNN activation layer and connects it to the given layer, if the
//// passed in AndroidNN activation function requires so.
//// @return The end layer of the sequence of layers built for the given AndroidNN
//// activation function or nullptr if an error occurred (e.g. unsupported activation).
//// Note that the end layer matches the input layer if no activation is required
//// (the sequence of layers has length 1).
armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
ActivationFn activation,
armnn::IConnectableLayer* prevLayer,
ConversionData& data);
} // namespace armnn_driver
///
/// Utility templates
///
namespace armnn_driver
{
using namespace android::nn;
template<typename HalPolicy,
typename HalOperand = typename HalPolicy::Operand,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
const HalOperand* GetInputOperand(const HalOperation& operation,
uint32_t inputIndex,
const HalModel& model,
bool failOnIndexOutOfBounds = true)
{
if (inputIndex >= operation.inputs.size())
{
if (failOnIndexOutOfBounds)
{
Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
}
return nullptr;
}
// Model should have been validated beforehand
ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
return &getMainModel(model).operands[operation.inputs[inputIndex]];
}
template<typename HalPolicy,
typename HalOperand = typename HalPolicy::Operand,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
const HalOperand* GetOutputOperand(const HalOperation& operation,
uint32_t outputIndex,
const HalModel& model)
{
if (outputIndex >= operation.outputs.size())
{
Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
return nullptr;
}
// Model should have been validated beforehand
ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
return &getMainModel(model).operands[operation.outputs[outputIndex]];
}
template<typename HalPolicy,
typename HalOperand = typename HalPolicy::Operand,
typename HalModel = typename HalPolicy::Model>
const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
const HalModel& model,
const ConversionData& data,
bool optional = false)
{
using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
const void* valueStart = nullptr;
switch (operand.lifetime)
{
case HalOperandLifeTime::CONSTANT_COPY:
{
// Constant found in model.operandValues
valueStart = &model.operandValues[operand.location.offset];
break;
}
case HalOperandLifeTime::CONSTANT_REFERENCE:
{
// Constant specified via a Memory object
valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
break;
}
case HalOperandLifeTime::NO_VALUE:
{
// An optional input tensor with no values is not an error so should not register as a fail
if (optional)
{
valueStart = nullptr;
break;
}
[[fallthrough]];
}
default:
{
// Unsupported/invalid (e.g. can't get value of an input to the model)
Fail("%s: unsupported/invalid operand lifetime: %s",
__func__, toString(operand.lifetime).c_str());
valueStart = nullptr;
}
}
return valueStart;
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model,
typename HalOperandType = typename HalPolicy::OperandType>
bool GetOperandType(const HalOperation& operation,
uint32_t inputIndex,
const HalModel& model,
HalOperandType& type)
{
using HalOperand = typename HalPolicy::Operand;
const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
if (!operand)
{
return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
}
type = operand->type;
return true;
}
template<typename HalPolicy,
typename HalOperand = typename HalPolicy::Operand>
bool IsOperandConstant(const HalOperand& operand)
{
using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
HalOperandLifeTime lifetime = operand.lifetime;
return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
lifetime == HalOperandLifeTime::NO_VALUE;
}
template<typename HalPolicy,
typename HalOperand = typename HalPolicy::Operand,
typename HalModel = typename HalPolicy::Model>
ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
const HalModel& model,
const ConversionData& data,
const armnn::PermutationVector& dimensionMappings = g_DontPermute,
const armnn::TensorShape* overrideTensorShape = nullptr,
bool optional = false)
{
if (!IsOperandTypeSupportedForTensors(operand.type))
{
Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
return ConstTensorPin();
}
if (!optional && !IsOperandConstant<HalPolicy>(operand))
{
Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
return ConstTensorPin();
}
const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
if (!valueStart)
{
if (optional)
{
// optional tensor with no values is not really an error; return it as invalid, but marked as optional
return ConstTensorPin(true);
}
// mandatory tensor with no values
Fail("%s: failed to get operand address", __func__);
return ConstTensorPin();
}
armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
// Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
if (tensorInfo.HasPerAxisQuantization())
{
tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
}
if (overrideTensorShape != nullptr)
{
tensorInfo.SetShape(*overrideTensorShape);
}
return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
uint32_t inputIndex,
const HalModel& model,
const ConversionData& data,
const armnn::PermutationVector& dimensionMappings = g_DontPermute,
const armnn::TensorShape* overrideTensorShape = nullptr,
bool optional = false)
{
using HalOperand = typename HalPolicy::Operand;
const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
if (!operand)
{
Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
return ConstTensorPin();
}
return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
model,
data,
dimensionMappings,
overrideTensorShape,
optional);
}
template<typename HalPolicy,
typename OutputType,
typename HalOperandType = typename HalPolicy::OperandType,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
bool GetInputScalar(const HalOperation& operation,
uint32_t inputIndex,
HalOperandType type,
OutputType& outValue,
const HalModel& model,
const ConversionData& data,
bool optional = false)
{
using HalOperand = typename HalPolicy::Operand;
const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
if (!optional && !operand)
{
return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
}
if (!optional && operand->type != type)
{
return Fail("%s: unexpected operand type: %s (should be %s)",
__func__, toString(operand->type).c_str(), toString(type).c_str());
}
if (!optional && operand->location.length != sizeof(OutputType))
{
return Fail("%s: incorrect operand location length: %i (should be %i)",
__func__, operand->location.length, sizeof(OutputType));
}
const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
if (!optional && !valueAddress)
{
return Fail("%s: failed to get address for operand", __func__);
}
if(!optional)
{
outValue = *(static_cast<const OutputType*>(valueAddress));
}
return true;
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
bool GetInputInt32(const HalOperation& operation,
uint32_t inputIndex,
int32_t& outValue,
const HalModel& model,
const ConversionData& data)
{
return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
bool GetInputFloat32(const HalOperation& operation,
uint32_t inputIndex,
float& outValue,
const HalModel& model,
const ConversionData& data)
{
return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalOperandType = typename HalPolicy::OperandType,
typename HalModel = typename HalPolicy::Model>
bool GetInputActivationFunctionImpl(const HalOperation& operation,
uint32_t inputIndex,
HalOperandType type,
ActivationFn& outActivationFunction,
const HalModel& model,
const ConversionData& data)
{
if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
{
return Fail("%s: unexpected operand type: %s (should be %s or %s)",
__func__,
toString(type).c_str(),
toString(HalOperandType::INT32).c_str(),
toString(HalOperandType::TENSOR_INT32).c_str());
}
int32_t activationFunctionAsInt;
if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
{
return Fail("%s: failed to get activation input value", __func__);
}
outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
return true;
}
template<typename HalPolicy,
typename HalOperation = typename HalPolicy::Operation,
typename HalModel = typename HalPolicy::Model>
bool GetInputActivationFunction(const HalOperation& operation,
uint32_t inputIndex,
ActivationFn& outActivationFunction,
const HalModel& model,
const ConversionData& data)
{
return GetInputActivationFunctionImpl<HalPolicy>(operation,
inputIndex,
HalPolicy::OperandType::INT32,
outActivationFunction,
model,