blob: fe8e026e95a8e18ef8495777e14a862bfe9f2110 [file] [log] [blame]
arovir01b0717b52018-09-05 17:03:25 +01001//
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002// Copyright © 2017 Arm Ltd and Contributors. All rights reserved.
arovir01b0717b52018-09-05 17:03:25 +01003// SPDX-License-Identifier: MIT
4//
5
6#pragma once
7
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01008#include "Utils.hpp"
9
arovir01b0717b52018-09-05 17:03:25 +010010#include <armnn/ArmNN.hpp>
Ferran Balaguerd30093c2019-07-09 17:04:47 +010011#include <armnn/ILayerSupport.hpp>
12#include <armnn/BackendHelper.hpp>
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +010013#include <armnn/utility/Assert.hpp>
Jan Eilers0b7a4192020-03-09 18:20:42 +000014#include <armnn/utility/IgnoreUnused.hpp>
arovir01b0717b52018-09-05 17:03:25 +010015
Matteo Martincigh00d6ed12019-11-28 17:13:24 +000016#include <armnnUtils/DataLayoutIndexed.hpp>
Mike Kelly4a956582020-02-28 10:32:09 +000017#include <armnnUtils/Transpose.hpp>
arovir01b0717b52018-09-05 17:03:25 +010018
Mike Kelly46272802019-08-14 17:00:48 +010019#include "1.0/FullyConnected.hpp"
20
arovir01b0717b52018-09-05 17:03:25 +010021#include <ActivationFunctor.h>
22#include <CpuExecutor.h>
23#include <OperationsUtils.h>
24
Aron Virginas-Tar0e7ab542019-04-10 15:02:31 +010025#include <boost/numeric/conversion/cast.hpp>
arovir01b0717b52018-09-05 17:03:25 +010026#include <boost/test/tools/floating_point_comparison.hpp>
27
28#include <log/log.h>
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010029#include <vector>
arovir01b0717b52018-09-05 17:03:25 +010030
31namespace armnn_driver
32{
33
34///
35/// Helper classes
36///
37
Kevin Mayec1e5b82020-02-26 17:00:39 +000038#ifdef ARMNN_ANDROID_R
39using OperandType = android::nn::hal::OperandType;
40#endif
41
arovir01b0717b52018-09-05 17:03:25 +010042struct ConversionData
43{
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010044 ConversionData(const std::vector<armnn::BackendId>& backends)
45 : m_Backends(backends)
46 , m_Network(nullptr, nullptr)
Finn Williams291a16b2020-08-19 22:54:00 +010047 , m_DynamicInputsEncountered(false)
arovir01b0717b52018-09-05 17:03:25 +010048 {}
49
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010050 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010051 armnn::INetworkPtr m_Network;
52 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
53 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
Finn Williams291a16b2020-08-19 22:54:00 +010054 bool m_DynamicInputsEncountered;
arovir01b0717b52018-09-05 17:03:25 +010055};
56
57class LayerInputHandle
58{
59public:
60 LayerInputHandle();
61 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
62
63 bool IsValid() const;
64
65 void Connect(armnn::IInputSlot& inputSlot);
66
Finn Williamsa4983ce2020-07-23 12:55:12 +010067 void Disconnect(armnn::IInputSlot& inputSlot);
68
arovir01b0717b52018-09-05 17:03:25 +010069 const armnn::TensorInfo& GetTensorInfo() const;
70
71private:
72 armnn::IOutputSlot* m_OutputSlot;
73 bool m_Valid;
74 armnn::TensorInfo m_TensorInfo;
75};
76
77class ConstTensorPin
78{
79public:
80 // Creates an invalid tensor pin (can be used to signal errors)
81 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
82 ConstTensorPin(bool optional = false);
83
84 // @param tensorInfo TensorInfo associated with the tensor.
85 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
86 // the model being converted.
87 // @param numBytes Number of bytes for the tensor data.
88 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
89 const armnn::PermutationVector& mappings);
90
91 ConstTensorPin(const ConstTensorPin& other) = delete;
92 ConstTensorPin(ConstTensorPin&& other) = default;
93
94 bool IsValid() const;
95 bool IsOptional() const;
96
97 const armnn::ConstTensor& GetConstTensor() const;
98 const armnn::ConstTensor* GetConstTensorPtr() const;
99
100private:
101 armnn::ConstTensor m_ConstTensor;
102
103 // Owned memory for swizzled tensor data, only required if the tensor needed
104 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
105 // the pools associated with the model being converted.
106 std::vector<uint8_t> m_SwizzledTensorData;
107
108 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
109 bool m_Optional;
110};
111
112} // namespace armnn_driver
113
114///
115/// Utility functions
116///
117
118namespace
119{
120
121using namespace armnn_driver;
122using namespace android::nn;
123
124// Convenience function to log the reason for failing to convert a model.
125// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
126template<class... Args>
127static bool Fail(const char* formatStr, Args&&... args)
128{
129 ALOGD(formatStr, std::forward<Args>(args)...);
130 return false;
131}
132
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100133// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
134// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
135#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100136try \
137{ \
138 for (auto&& backendId : backends) \
139 { \
140 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
141 if (layerSupportObject) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100142 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100143 std::string reasonIfUnsupported; \
144 supported = \
145 layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
146 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100147 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100148 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100149 } \
150 else \
151 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100152 if (reasonIfUnsupported.size() > 0) \
153 { \
154 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
155 } \
156 else \
157 { \
158 ALOGD("%s: not supported by armnn", funcName); \
159 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100160 } \
161 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100162 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100163 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100164 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100165 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100166 } \
167 if (!supported) \
168 { \
169 ALOGD("%s: not supported by any specified backend", funcName); \
170 } \
171} \
172catch (const armnn::InvalidArgumentException &e) \
173{ \
174 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
175}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100176
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000177template<typename HalOperand>
178armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100179{
180 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
181}
182
Matthew Bentham912b3622019-05-03 15:49:14 +0100183inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100184{
Matthew Bentham912b3622019-05-03 15:49:14 +0100185 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
186 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
187 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100188}
189
Kevin May42477c12020-03-26 13:34:14 +0000190#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100191
Keith Davis71006492020-01-06 17:44:16 +0000192// Support within the 1.2 driver for specific tensor data types
Mike Kellyb5fdf382019-06-11 16:35:25 +0100193inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
194{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000195 return type == V1_2::OperandType::BOOL ||
Sadik Armagan793a70c2020-03-19 13:54:04 +0000196 type == V1_2::OperandType::TENSOR_BOOL8 ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000197 type == V1_2::OperandType::TENSOR_FLOAT16 ||
198 type == V1_2::OperandType::TENSOR_FLOAT32 ||
199 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
Keith Davis71006492020-01-06 17:44:16 +0000200 type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000201 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
202 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100203 type == V1_2::OperandType::TENSOR_INT32;
204}
205
206#endif
207
Kevin May42477c12020-03-26 13:34:14 +0000208#ifdef ARMNN_ANDROID_NN_V1_3
209
210// Support within the 1.3 driver for specific tensor data types
211inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
212{
213 return type == V1_3::OperandType::BOOL ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100214 type == V1_3::OperandType::TENSOR_BOOL8 ||
Kevin May42477c12020-03-26 13:34:14 +0000215 type == V1_3::OperandType::TENSOR_FLOAT16 ||
216 type == V1_3::OperandType::TENSOR_FLOAT32 ||
217 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100218 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
Kevin May42477c12020-03-26 13:34:14 +0000219 type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
220 type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
221 type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
222 type == V1_3::OperandType::TENSOR_INT32;
223}
224
225#endif
226
Mike Kellyb5fdf382019-06-11 16:35:25 +0100227inline bool IsBool(V1_0::Operand)
228{
229 return false;
230}
231
Kevin May42477c12020-03-26 13:34:14 +0000232inline bool Is12OrLaterOperand(V1_0::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100233{
234 return false;
235}
236
Kevin May42477c12020-03-26 13:34:14 +0000237#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100238
239inline bool IsBool(V1_2::Operand operand)
240{
241 return operand.type == V1_2::OperandType::BOOL;
242}
243
Sadik Armagan61113162019-07-25 09:09:40 +0100244/// Checks if a operand is 1_2 Operand
Kevin May42477c12020-03-26 13:34:14 +0000245inline bool Is12OrLaterOperand(V1_2::Operand)
246{
247 return true;
248}
249
250#endif
251
252#ifdef ARMNN_ANDROID_NN_V1_3
253
254inline bool IsBool(V1_3::Operand operand)
255{
256 return operand.type == V1_3::OperandType::BOOL;
257}
258
259/// Checks if a operand is 1_2 Operand
260inline bool Is12OrLaterOperand(V1_3::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100261{
262 return true;
263}
264
Mike Kellyb5fdf382019-06-11 16:35:25 +0100265#endif
266
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100267template<typename LayerHandleType>
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000268armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
269 LayerHandleType& inputLayer,
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100270 armnn::TensorInfo reshapeInfo)
271{
272 armnn::ReshapeDescriptor reshapeDescriptor;
273 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
274
275 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100276 ARMNN_ASSERT(reshapeLayer != nullptr);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100277
278 // Attach the input layer to the reshape layer
279 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
280 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
281
282 return *reshapeLayer;
283}
284
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000285bool BroadcastTensor(LayerInputHandle& input0,
286 LayerInputHandle& input1,
287 armnn::IConnectableLayer* startLayer,
288 ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100289{
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100290 ARMNN_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100291
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100292 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
293 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
294
295 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
296 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
297
298 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100299 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100300 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
301 input0.Connect(startLayer->GetInputSlot(0));
302 input1.Connect(startLayer->GetInputSlot(1));
303
Sadik Armagan64b19b52019-08-19 09:49:58 +0100304 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100305 }
306
307 // Since the number of dimensions do not match then we need to add degenerate dimensions
308 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
309
310 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
311 unsigned int sizeDifference = std::abs(boost::numeric_cast<int>(inputDimensions0) -
312 boost::numeric_cast<int>(inputDimensions1));
313
314 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
315 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
316 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
317
318 const armnn::TensorShape& smallShape = smallInfo.GetShape();
319 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
320 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
321 {
322 reshapedDimensions[i] = smallShape[i - sizeDifference];
323 }
324
325 armnn::TensorInfo reshapedInfo = smallInfo;
326 reshapedInfo.SetShape(armnn::TensorShape{ boost::numeric_cast<unsigned int>(reshapedDimensions.size()),
327 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100328
329 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
330 armnn::ReshapeDescriptor reshapeDescriptor;
331
332 bool isSupported = false;
333 FORWARD_LAYER_SUPPORT_FUNC(__func__,
334 IsReshapeSupported,
335 data.m_Backends,
336 isSupported,
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +0000337 smallInfo,
Sadik Armagan64b19b52019-08-19 09:49:58 +0100338 reshapedInfo,
339 reshapeDescriptor);
340 if (!isSupported)
341 {
342 return false;
343 }
344
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100345 ARMNN_ASSERT(data.m_Network != nullptr);
Sadik Armagan64b19b52019-08-19 09:49:58 +0100346 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100347
348 if (input0IsSmaller)
349 {
350 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
351 //
352 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100353 // | |
354 // Reshape |
355 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100356 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100357
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100358 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
359 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100360 }
361 else
362 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100363 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
364 //
365 // Input0 Input1
366 // | |
367 // | Reshape
368 // \ /
369 // StartLayer
370
arovir01b0717b52018-09-05 17:03:25 +0100371 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100372 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100373 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100374
375 return true;
arovir01b0717b52018-09-05 17:03:25 +0100376}
377
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000378void CalcPadding(uint32_t input,
379 uint32_t kernel,
380 uint32_t stride,
381 uint32_t& outPadHead,
382 uint32_t& outPadTail,
arovir01b0717b52018-09-05 17:03:25 +0100383 android::nn::PaddingScheme scheme)
384{
385 int32_t padHead;
386 int32_t padTail;
387 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
388 outPadHead = boost::numeric_cast<uint32_t>(padHead);
389 outPadTail = boost::numeric_cast<uint32_t>(padTail);
390}
391
Kevin May42477c12020-03-26 13:34:14 +0000392#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly86b36d42019-07-12 16:39:33 +0100393
394void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
395 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
396{
397 int32_t padHead;
398 int32_t padTail;
399 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
400 outPadHead = boost::numeric_cast<uint32_t>(padHead);
401 outPadTail = boost::numeric_cast<uint32_t>(padTail);
402}
403
Mike Kelly26123db2020-01-15 10:02:33 +0000404void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100405 int32_t& outPadTail, android::nn::PaddingScheme scheme)
406{
407 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
408}
409
Mike Kelly86b36d42019-07-12 16:39:33 +0100410#endif
411
Matthew Bentham912b3622019-05-03 15:49:14 +0100412Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100413{
414 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100415 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100416 shape.dimensions = operand.dimensions;
417 shape.scale = operand.scale;
418 shape.offset = operand.zeroPoint;
419 return shape;
420}
421
Kevin May42477c12020-03-26 13:34:14 +0000422#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly46272802019-08-14 17:00:48 +0100423
424Shape GetOperandShape(const V1_2::Operand& operand)
425{
426 Shape shape;
427 shape.type = OperandType(operand.type);
428 shape.dimensions = operand.dimensions;
429 shape.scale = operand.scale;
430 shape.offset = operand.zeroPoint;
431 return shape;
432}
433
434#endif
435
Kevin May42477c12020-03-26 13:34:14 +0000436#ifdef ARMNN_ANDROID_NN_V1_3
437
438Shape GetOperandShape(const V1_3::Operand& operand)
439{
440 Shape shape;
441 shape.type = OperandType(operand.type);
442 shape.dimensions = operand.dimensions;
443 shape.scale = operand.scale;
444 shape.offset = operand.zeroPoint;
445 return shape;
446}
447
448#endif
449
arovir01b0717b52018-09-05 17:03:25 +0100450// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
451// what AndroidNN requires. However for some of the AndroidNN tests the values don't exactly match so
Aron Virginas-Tara0baa172019-08-01 11:24:08 +0100452// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
453// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100454void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000455 const armnn::TensorInfo& weightInfo,
456 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100457{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000458 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100459 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000460 // NOTE: Bias scale is always set to 0 for per-axis quantization and
461 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
462 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100463 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000464 return biasScale * inputInfo.GetQuantizationScale();
465 };
466
467 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
468 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
469
470 biasInfo.SetQuantizationScales(biasScales);
471 biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
472
473 ALOGV("Bias quantization params have been updated for per-axis quantization");
474 }
475 else
476 {
477 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
478 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
479 {
480 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
481 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
482 {
483 ALOGW("Bias quantization scale has been modified to match input * weights");
484 biasInfo.SetQuantizationScale(expectedBiasScale);
485 }
arovir01b0717b52018-09-05 17:03:25 +0100486 }
487 }
488}
489
490// 4D Tensor Permutations
491const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
arovir01b0717b52018-09-05 17:03:25 +0100492const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
493
494// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000495const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
496const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100497
498template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000499armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
500 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100501{
502 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000503 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
arovir01b0717b52018-09-05 17:03:25 +0100504
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100505 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100506
507 // Connect input to swizzle layer
508 input.Connect(layer->GetInputSlot(0));
509
510 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000511 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100512 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
513
514 return *layer;
515}
516
arovir01b0717b52018-09-05 17:03:25 +0100517bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
518 const armnn::TensorShape & outputShape,
519 uint32_t concatDim)
520{
521 // Validate the output shape is correct given the input shapes (which have just been validated)
522 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
523 if (outputShape.GetNumDimensions() != numDimensions)
524 {
525 return Fail("%s: Output shape has wrong number of dimensions", __func__);
526 }
527
528 unsigned int outputSizeAlongConcatenatedDimension = 0;
529 for (unsigned int i = 0; i < inputShapes.size(); i++)
530 {
531 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
532 }
533
534 for (unsigned int i = 0; i < numDimensions; ++i)
535 {
536 if (i == concatDim)
537 {
538 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
539 {
540 return Fail(
541 "%s: Invalid output shape for dimension %d (%d != %d)",
542 __func__,
543 i,
544 outputShape[i],
545 outputSizeAlongConcatenatedDimension);
546 }
547 }
548 else
549 {
550 if (outputShape[i] != inputShapes[0][i])
551 {
552 return Fail("%s: Invalid output shape", __func__);
553 }
554 }
555 }
556
557 return true;
558}
559
560bool RequiresReshape(armnn::TensorShape & inputShape)
561{
562 return inputShape.GetNumDimensions() < 3;
563}
564
arovir01b0717b52018-09-05 17:03:25 +0100565void SwizzleInputs(armnn::INetwork& network,
566 std::vector<LayerInputHandle>& inputs,
567 std::vector<armnn::TensorShape>& inputShapes,
568 const armnn::PermutationVector& mapping)
569{
570 if (!mapping.IsEqual(IdentityPermutation4D))
571 {
572 size_t nInputs = inputs.size();
573 for (size_t i=0; i<nInputs; ++i)
574 {
575 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000576 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100577 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
578 auto& outputInfo = outputSlot.GetTensorInfo();
579 // replace inputs with the swizzled ones
580 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
581 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
582 }
583 }
584}
585
Teresa Charlin185f5882020-04-06 21:59:18 +0100586bool TransposeInputTensors(ConversionData& data,
587 std::vector<LayerInputHandle>& inputs,
588 std::vector<armnn::TensorShape>& inputShapes,
589 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000590{
591 if (!mapping.IsEqual(IdentityPermutation4D))
592 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100593 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000594 size_t nInputs = inputs.size();
595 for (size_t i=0; i<nInputs; ++i)
596 {
597 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000598 armnn::TransposeDescriptor transposeDesc;
599 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100600 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000601
602 bool isSupported = false;
603 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000604 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000605 data.m_Backends,
606 isSupported,
607 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100608 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000609 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000610 if (!isSupported)
611 {
612 return false;
613 }
614
615 }
616 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
617 }
618 return true;
619}
620
621
narpra01f176d5a2018-11-18 20:17:48 +0000622bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
623 int32_t & concatDimension,
624 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100625{
narpra01f176d5a2018-11-18 20:17:48 +0000626 bool needPermute = false;
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100627 ARMNN_ASSERT(numberOfDimensions >= 3);
arovir01b0717b52018-09-05 17:03:25 +0100628
629 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000630 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
631 // or along dimension 0 or 2 for a 3-D tensor.
632 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100633 {
narpra01f176d5a2018-11-18 20:17:48 +0000634 concatDimension = 1;
635 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
636 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100637 }
narpra01f176d5a2018-11-18 20:17:48 +0000638 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100639 {
narpra01f176d5a2018-11-18 20:17:48 +0000640 concatDimension = 0;
641 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
642 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100643 }
narpra01f176d5a2018-11-18 20:17:48 +0000644 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100645}
646
647} // anonymous namespace
648
649namespace armnn_driver
650{
651
652//// Creates an ArmNN activation layer and connects it to the given layer, if the
653//// passed in AndroidNN activation function requires so.
654//// @return The end layer of the sequence of layers built for the given AndroidNN
655//// activation function or nullptr if an error occurred (e.g. unsupported activation).
656//// Note that the end layer matches the input layer if no activation is required
657//// (the sequence of layers has length 1).
658armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
659 ActivationFn activation,
660 armnn::IConnectableLayer* prevLayer,
661 ConversionData& data);
662
663} // namespace armnn_driver
664
665///
666/// Utility templates
667///
668
669namespace armnn_driver
670{
671
672using namespace android::nn;
673
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100674template<typename HalPolicy,
675 typename HalOperand = typename HalPolicy::Operand,
676 typename HalOperation = typename HalPolicy::Operation,
677 typename HalModel = typename HalPolicy::Model>
678const HalOperand* GetInputOperand(const HalOperation& operation,
679 uint32_t inputIndex,
680 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100681 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100682{
683 if (inputIndex >= operation.inputs.size())
684 {
saoste01b8471482018-10-10 09:44:51 +0100685 if (failOnIndexOutOfBounds)
686 {
687 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
688 }
arovir01b0717b52018-09-05 17:03:25 +0100689 return nullptr;
690 }
691
Kevin May42477c12020-03-26 13:34:14 +0000692 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100693 ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
Kevin May42477c12020-03-26 13:34:14 +0000694 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100695}
696
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100697template<typename HalPolicy,
698 typename HalOperand = typename HalPolicy::Operand,
699 typename HalOperation = typename HalPolicy::Operation,
700 typename HalModel = typename HalPolicy::Model>
701const HalOperand* GetOutputOperand(const HalOperation& operation,
702 uint32_t outputIndex,
703 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100704{
705 if (outputIndex >= operation.outputs.size())
706 {
707 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
708 return nullptr;
709 }
710
711 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100712 ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
arovir01b0717b52018-09-05 17:03:25 +0100713
Kevin May42477c12020-03-26 13:34:14 +0000714 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100715}
716
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100717template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100718 typename HalOperand = typename HalPolicy::Operand,
719 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100720const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100721 const HalModel& model,
722 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000723 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100724{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100725 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100726
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100727 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100728 switch (operand.lifetime)
729 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100730 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100731 {
732 // Constant found in model.operandValues
733 valueStart = &model.operandValues[operand.location.offset];
734 break;
735 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100736 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100737 {
738 // Constant specified via a Memory object
739 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
740 break;
741 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100742 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000743 {
744 // An optional input tensor with no values is not an error so should not register as a fail
745 if (optional)
746 {
747 valueStart = nullptr;
748 break;
749 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100750 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000751 }
arovir01b0717b52018-09-05 17:03:25 +0100752 default:
753 {
754 // Unsupported/invalid (e.g. can't get value of an input to the model)
755 Fail("%s: unsupported/invalid operand lifetime: %s",
756 __func__, toString(operand.lifetime).c_str());
757 valueStart = nullptr;
758 }
759 }
760
761 return valueStart;
762}
763
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100764template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100765 typename HalOperation = typename HalPolicy::Operation,
766 typename HalModel = typename HalPolicy::Model,
767 typename HalOperandType = typename HalPolicy::OperandType>
768bool GetOperandType(const HalOperation& operation,
769 uint32_t inputIndex,
770 const HalModel& model,
771 HalOperandType& type)
772{
773 using HalOperand = typename HalPolicy::Operand;
774
775 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
776 if (!operand)
777 {
778 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
779 }
780
781 type = operand->type;
782 return true;
783}
784
785template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000786 typename HalOperand = typename HalPolicy::Operand>
787bool IsOperandConstant(const HalOperand& operand)
788{
789 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
790
791 HalOperandLifeTime lifetime = operand.lifetime;
792
793 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
794 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
795 lifetime == HalOperandLifeTime::NO_VALUE;
796}
797
798template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100799 typename HalOperand = typename HalPolicy::Operand,
800 typename HalModel = typename HalPolicy::Model>
801ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
802 const HalModel& model,
803 const ConversionData& data,
804 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
805 const armnn::TensorShape* overrideTensorShape = nullptr,
806 bool optional = false)
807{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100808 if (!IsOperandTypeSupportedForTensors(operand.type))
809 {
810 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
811 return ConstTensorPin();
812 }
813
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000814 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100815 {
816 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
817 return ConstTensorPin();
818 }
819
820 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
821 if (!valueStart)
822 {
823 if (optional)
824 {
825 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
826 return ConstTensorPin(true);
827 }
828 // mandatory tensor with no values
829 Fail("%s: failed to get operand address", __func__);
830 return ConstTensorPin();
831 }
832
833 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000834 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
835 if (tensorInfo.HasPerAxisQuantization())
836 {
837 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
838 }
839
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100840 if (overrideTensorShape != nullptr)
841 {
842 tensorInfo.SetShape(*overrideTensorShape);
843 }
844 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
845}
846
847template<typename HalPolicy,
848 typename HalOperation = typename HalPolicy::Operation,
849 typename HalModel = typename HalPolicy::Model>
850ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
851 uint32_t inputIndex,
852 const HalModel& model,
853 const ConversionData& data,
854 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
855 const armnn::TensorShape* overrideTensorShape = nullptr,
856 bool optional = false)
857{
858 using HalOperand = typename HalPolicy::Operand;
859
860 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
861 if (!operand)
862 {
863 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
864 return ConstTensorPin();
865 }
866 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
867 model,
868 data,
869 dimensionMappings,
870 overrideTensorShape,
871 optional);
872}
873
874template<typename HalPolicy,
875 typename OutputType,
876 typename HalOperandType = typename HalPolicy::OperandType,
877 typename HalOperation = typename HalPolicy::Operation,
878 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100879bool GetInputScalar(const HalOperation& operation,
880 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100881 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100882 OutputType& outValue,
883 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100884 const ConversionData& data,
885 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100886{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100887 using HalOperand = typename HalPolicy::Operand;
888
889 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100890 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100891 {
892 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
893 }
894
Sadik Armagan813f2302020-05-19 14:10:30 +0100895 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100896 {
897 return Fail("%s: unexpected operand type: %s (should be %s)",
898 __func__, toString(operand->type).c_str(), toString(type).c_str());
899 }
900
Sadik Armagan813f2302020-05-19 14:10:30 +0100901 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100902 {
903 return Fail("%s: incorrect operand location length: %i (should be %i)",
904 __func__, operand->location.length, sizeof(OutputType));
905 }
906
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100907 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100908 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100909 {
910 return Fail("%s: failed to get address for operand", __func__);
911 }
912
Sadik Armagan813f2302020-05-19 14:10:30 +0100913 if(!optional)
914 {
915 outValue = *(static_cast<const OutputType*>(valueAddress));
916 }
917
arovir01b0717b52018-09-05 17:03:25 +0100918 return true;
919}
920
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100921template<typename HalPolicy,
922 typename HalOperation = typename HalPolicy::Operation,
923 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100924bool GetInputInt32(const HalOperation& operation,
925 uint32_t inputIndex,
926 int32_t& outValue,
927 const HalModel& model,
928 const ConversionData& data)
929{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100930 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100931}
932
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100933template<typename HalPolicy,
934 typename HalOperation = typename HalPolicy::Operation,
935 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100936bool GetInputFloat32(const HalOperation& operation,
937 uint32_t inputIndex,
938 float& outValue,
939 const HalModel& model,
940 const ConversionData& data)
941{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100942 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100943}
944
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100945template<typename HalPolicy,
946 typename HalOperation = typename HalPolicy::Operation,
947 typename HalOperandType = typename HalPolicy::OperandType,
948 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100949bool GetInputActivationFunctionImpl(const HalOperation& operation,
950 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100951 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100952 ActivationFn& outActivationFunction,
953 const HalModel& model,
954 const ConversionData& data)
955{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100956 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100957 {
958 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
959 __func__,
960 toString(type).c_str(),
961 toString(OperandType::INT32).c_str(),
962 toString(OperandType::TENSOR_INT32).c_str());
963 }
964
965 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100966 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100967 {
968 return Fail("%s: failed to get activation input value", __func__);
969 }
970 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
971 return true;
972}
973
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100974template<typename HalPolicy,
975 typename HalOperation = typename HalPolicy::Operation,
976 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100977bool GetInputActivationFunction(const HalOperation& operation,
978 uint32_t inputIndex,
979 ActivationFn& outActivationFunction,
980 const HalModel& model,
981 const ConversionData& data)
982{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100983 return GetInputActivationFunctionImpl<HalPolicy>(operation,
984 inputIndex,
985 HalPolicy::OperandType::INT32,
986 outActivationFunction,
987 model,
988 data);
arovir01b0717b52018-09-05 17:03:25 +0100989}
990
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100991template<typename HalPolicy,
992 typename HalOperation = typename HalPolicy::Operation,
993 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100994bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
995 uint32_t inputIndex,
996 ActivationFn& outActivationFunction,
997 const HalModel& model,
998 const ConversionData& data)
999{
1000 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001001 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1002 inputIndex,
1003 HalPolicy::OperandType::INT32,
1004 outActivationFunction,
1005 model,
1006 data);
arovir01b0717b52018-09-05 17:03:25 +01001007}
1008
1009
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001010template<typename HalPolicy,
1011 typename HalOperation = typename HalPolicy::Operation,
1012 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001013bool GetOptionalInputActivation(const HalOperation& operation,
1014 uint32_t inputIndex,
1015 ActivationFn& activationFunction,
1016 const HalModel& model,
1017 const ConversionData& data)
1018{
1019 if (operation.inputs.size() <= inputIndex)
1020 {
1021 activationFunction = ActivationFn::kActivationNone;
1022 }
1023 else
1024 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001025 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001026 {
1027 return Fail("%s: Operation has invalid inputs", __func__);
1028 }
1029 }
1030 return true;
1031}
1032
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001033template<typename HalPolicy,
1034 typename ConvolutionDescriptor,
1035 typename HalOperation = typename HalPolicy::Operation,
1036 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001037bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1038 uint32_t dilationXIndex,
1039 ConvolutionDescriptor& descriptor,
1040 const HalModel& model,
1041 const ConversionData& data)
1042{
1043 bool success = true;
1044 if (operation.inputs.size() >= dilationXIndex + 2)
1045 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001046 success &= GetInputScalar<HalPolicy>(operation,
1047 dilationXIndex,
1048 HalPolicy::OperandType::INT32,
1049 descriptor.m_DilationX,
1050 model,
1051 data);
1052 success &= GetInputScalar<HalPolicy>(operation,
1053 dilationXIndex + 1,
1054 HalPolicy::OperandType::INT32,
1055 descriptor.m_DilationY,
1056 model,
1057 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001058 }
1059
1060 return success;
1061}
1062
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001063template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001064 typename HalOperation = typename HalPolicy::Operation,
1065 typename HalModel = typename HalPolicy::Model>
1066bool GetOptionalBool(const HalOperation& operation,
1067 uint32_t inputIndex,
1068 const HalModel& model,
1069 const ConversionData& data)
1070{
1071 using HalOperand = typename HalPolicy::Operand;
1072
1073 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1074 if (!operand)
1075 {
1076 return false;
1077 }
1078
1079 if (!IsBool(*operand))
1080 {
1081 return false;
1082 }
1083
1084 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1085 if (!valueAddress)
1086 {
1087 return false;
1088 }
1089
1090 if (*(static_cast<const bool*>(valueAddress)))
1091 {
1092 return true;
1093 }
1094 else
1095 {
1096 return false;
1097 }
1098}
1099
1100template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001101 typename HalOperand = typename HalPolicy::Operand,
1102 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001103bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001104 std::vector<int32_t>& outValues,
1105 const HalModel& model,
1106 const ConversionData& data)
1107{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001108 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001109 {
1110 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1111 }
1112
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001113 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001114 if (!startAddress)
1115 {
1116 return Fail("%s: failed to get operand address", __func__, operand.type);
1117 }
1118
1119 // Check number of bytes is sensible
1120 const uint32_t numBytes = operand.location.length;
1121 if (numBytes % sizeof(int32_t) != 0)
1122 {
1123 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1124 __func__, numBytes, sizeof(int32_t));
1125 }
1126
1127 outValues.resize(numBytes / sizeof(int32_t));
1128 memcpy(outValues.data(), startAddress, numBytes);
1129 return true;
1130}
1131
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001132template<typename HalPolicy,
1133 typename HalOperation = typename HalPolicy::Operation,
1134 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001135bool GetInputPaddingScheme(const HalOperation& operation,
1136 uint32_t inputIndex,
1137 PaddingScheme& outPaddingScheme,
1138 const HalModel& model,
1139 const ConversionData& data)
1140{
1141 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001142 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001143 {
1144 return Fail("%s: failed to get padding scheme input value", __func__);
1145 }
1146
1147 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1148 return true;
1149}
1150
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001151template<typename HalPolicy,
1152 typename HalOperation = typename HalPolicy::Operation,
1153 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001154LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1155 uint32_t inputIndex,
1156 const HalModel& model,
1157 ConversionData& data)
1158{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001159 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001160 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001161 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1162
1163 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001164 if (!operand)
1165 {
1166 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1167 return LayerInputHandle();
1168 }
1169
1170 if (!IsOperandTypeSupportedForTensors(operand->type))
1171 {
1172 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1173 return LayerInputHandle();
1174 }
1175
Sadik Armagan44bcc022019-06-18 17:21:36 +01001176 try
arovir01b0717b52018-09-05 17:03:25 +01001177 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001178 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001179 if (IsDynamicTensor(operandTensorInfo))
1180 {
1181 Fail("%s: dynamic input tensors are not supported", __func__);
1182 return LayerInputHandle();
1183 }
arovir01b0717b52018-09-05 17:03:25 +01001184
Sadik Armagan44bcc022019-06-18 17:21:36 +01001185 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001186 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001187 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001188 {
1189 // NOTE: We must check whether we can support the input tensor on at least one
1190 // of the provided backends; otherwise we cannot convert the operation
1191 bool isInputSupported = false;
1192 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1193 IsInputSupported,
1194 data.m_Backends,
1195 isInputSupported,
1196 operandTensorInfo);
1197
1198 if (!isInputSupported)
1199 {
1200 Fail("%s: unsupported input tensor", __func__);
1201 return LayerInputHandle();
1202 }
1203
1204 BOOST_FALLTHROUGH; // intentional fallthrough
1205 }
1206 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001207 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001208 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001209 // The tensor is either an operand internal to the model, or a model input.
1210 // It can be associated with an ArmNN output slot for an existing layer.
1211
1212 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1213 const uint32_t operandIndex = operation.inputs[inputIndex];
1214 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001215 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001216 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001217 case HalOperandLifeTime::CONSTANT_REFERENCE:
1218 {
1219 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1220 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1221 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001222 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001223 bool isSupported = false;
1224 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1225 IsConstantSupported,
1226 data.m_Backends,
1227 isSupported,
1228 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001229 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001230 {
1231 return LayerInputHandle();
1232 }
1233
1234 armnn::IConnectableLayer* constantLayer =
1235 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1236 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1237 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1238
1239 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1240 }
1241 else
1242 {
1243 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001244 return LayerInputHandle();
1245 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001246 break;
arovir01b0717b52018-09-05 17:03:25 +01001247 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001248 default:
arovir01b0717b52018-09-05 17:03:25 +01001249 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001250 // Unsupported lifetime for an input tensor
1251 Fail("%s: unsupported lifetime for input tensor: %s",
1252 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001253 return LayerInputHandle();
1254 }
arovir01b0717b52018-09-05 17:03:25 +01001255 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001256 }
1257 catch (UnsupportedOperand<HalOperandType>& e)
1258 {
1259 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1260 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001261 }
1262}
1263
Kevin May42477c12020-03-26 13:34:14 +00001264
1265#ifdef ARMNN_ANDROID_NN_V1_3
1266template<typename HalPolicy>
1267LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1268 uint32_t inputIndex,
1269 const::android::hardware::neuralnetworks::V1_3::Model& model,
1270 ConversionData& data)
1271{
1272 using HalOperand = typename HalPolicy::Operand;
1273 using HalOperandType = typename HalPolicy::OperandType;
1274 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1275
1276 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1277 if (!operand)
1278 {
1279 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1280 return LayerInputHandle();
1281 }
1282
1283 if (!IsOperandTypeSupportedForTensors(operand->type))
1284 {
1285 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1286 return LayerInputHandle();
1287 }
1288
1289 try
1290 {
1291 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Finn Williams9a044412020-08-17 19:08:35 +01001292
Kevin May42477c12020-03-26 13:34:14 +00001293 if (IsDynamicTensor(operandTensorInfo))
1294 {
Finn Williams291a16b2020-08-19 22:54:00 +01001295 data.m_DynamicInputsEncountered = true;
1296
Finn Williams9a044412020-08-17 19:08:35 +01001297 const uint32_t operandIndex = operation.inputs[inputIndex];
1298
1299 // Check if the dynamic input tensors have been inferred by one of the previous layers
1300 // If not we can't support them
Finn Williams291a16b2020-08-19 22:54:00 +01001301 if (data.m_OutputSlotForOperand.size() >= operandIndex && data.m_OutputSlotForOperand[operandIndex])
Finn Williams9a044412020-08-17 19:08:35 +01001302 {
1303 operandTensorInfo = data.m_OutputSlotForOperand[operandIndex]->GetTensorInfo();
1304 }
1305 else
1306 {
1307 Fail("%s: Type 2 dynamic input tensors are not supported", __func__);
1308 return LayerInputHandle();
1309 }
Kevin May42477c12020-03-26 13:34:14 +00001310 }
1311
1312 switch (operand->lifetime)
1313 {
1314 case HalOperandLifeTime::SUBGRAPH_INPUT:
1315 {
1316 // NOTE: We must check whether we can support the input tensor on at least one
1317 // of the provided backends; otherwise we cannot convert the operation
1318 bool isInputSupported = false;
1319 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1320 IsInputSupported,
1321 data.m_Backends,
1322 isInputSupported,
1323 operandTensorInfo);
1324
1325 if (!isInputSupported)
1326 {
1327 Fail("%s: unsupported input tensor", __func__);
1328 return LayerInputHandle();
1329 }
1330
1331 BOOST_FALLTHROUGH; // intentional fallthrough
1332 }
1333 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1334 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1335 {
1336 // The tensor is either an operand internal to the model, or a model input.
1337 // It can be associated with an ArmNN output slot for an existing layer.
1338
1339 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1340 const uint32_t operandIndex = operation.inputs[inputIndex];
1341 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1342 }
1343 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1344 case HalOperandLifeTime::CONSTANT_REFERENCE:
1345 {
1346 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1347 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1348 if (tensorPin.IsValid())
1349 {
1350 bool isSupported = false;
1351 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1352 IsConstantSupported,
1353 data.m_Backends,
1354 isSupported,
1355 tensorPin.GetConstTensor().GetInfo());
1356 if (!isSupported)
1357 {
1358 return LayerInputHandle();
1359 }
1360
1361 armnn::IConnectableLayer* constantLayer =
1362 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1363 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1364 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1365
1366 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1367 }
1368 else
1369 {
1370 Fail("%s: invalid operand tensor", __func__);
1371 return LayerInputHandle();
1372 }
1373 break;
1374 }
1375 default:
1376 {
1377 // Unsupported lifetime for an input tensor
1378 Fail("%s: unsupported lifetime for input tensor: %s",
1379 __func__, toString(operand->lifetime).c_str());
1380 return LayerInputHandle();
1381 }
1382 }
1383 }
1384 catch (UnsupportedOperand<HalOperandType>& e)
1385 {
1386 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1387 return LayerInputHandle();
1388 }
1389}
1390#endif
1391
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001392template<typename HalPolicy,
1393 typename HalOperation = typename HalPolicy::Operation,
1394 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001395bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1396 uint32_t operationOutputIndex,
1397 armnn::IConnectableLayer& layer,
1398 uint32_t layerOutputIndex,
1399 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001400 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001401 const armnn::TensorInfo* overrideOutputInfo = nullptr,
Sadik Armagandbda4b72020-09-03 11:33:07 +01001402 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr,
1403 bool inferOutputShapes = false)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001404{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001405 using HalOperand = typename HalPolicy::Operand;
1406
1407 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001408 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1409 {
1410 return false;
1411 }
1412
1413 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001414 if (overrideOutputInfo == nullptr)
1415 {
1416 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1417 }
1418 else
1419 {
1420 outputSlot.SetTensorInfo(*overrideOutputInfo);
1421 }
1422
Finn Williamsa4983ce2020-07-23 12:55:12 +01001423 bool isSupported = false;
Sadik Armagandbda4b72020-09-03 11:33:07 +01001424 if (validateFunc && (IsDynamicTensor(outputSlot.GetTensorInfo()) || inferOutputShapes))
Sadik Armagan813f2302020-05-19 14:10:30 +01001425 {
Sadik Armagandbda4b72020-09-03 11:33:07 +01001426 // Type one dynamic tensors require the previous layer's output shape for inference
1427 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1428 {
1429 if(!layer.GetInputSlot(inputSlotIndex).GetConnection())
1430 {
1431 return false;
1432 }
1433 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001434 // IsTensorInfoSet will infer the dynamic output shape
Finn Williamsa4983ce2020-07-23 12:55:12 +01001435 outputSlot.IsTensorInfoSet();
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001436 // Once the shape is inferred we can validate it
Finn Williamsa4983ce2020-07-23 12:55:12 +01001437 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1438
Sadik Armagandbda4b72020-09-03 11:33:07 +01001439 if(!isSupported)
1440 {
1441 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1442 {
1443 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1444 }
1445 return false;
1446 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001447 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001448
Finn Williamsa4983ce2020-07-23 12:55:12 +01001449 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1450 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1451
Mike Kellyb5fdf382019-06-11 16:35:25 +01001452 return true;
1453}
1454
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001455template<typename HalPolicy,
1456 typename HalOperation = typename HalPolicy::Operation,
1457 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001458armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1459 uint32_t inputIndex,
1460 const HalModel& model,
1461 ConversionData& data)
1462{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001463 using HalOperand = typename HalPolicy::Operand;
1464
1465 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001466 if (!operand)
1467 {
1468 return armnn::DataLayout::NHWC;
1469 }
1470
1471 if (!IsBool(*operand))
1472 {
1473 return armnn::DataLayout::NHWC;
1474 }
1475
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001476 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001477 if (!valueAddress)
1478 {
1479 return armnn::DataLayout::NHWC;
1480 }
1481
1482 if (*(static_cast<const bool*>(valueAddress)))
1483 {
1484 return armnn::DataLayout::NCHW;
1485 }
1486 else
1487 {
1488 return armnn::DataLayout::NHWC;
1489 }
1490}
1491
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001492template<typename HalPolicy,
1493 typename HalOperation = typename HalPolicy::Operation,
1494 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001495bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1496 uint32_t outputIndex,
1497 armnn::IConnectableLayer& layer,
1498 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001499 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001500 const armnn::TensorInfo* overrideOutputInfo = nullptr,
1501 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001502{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001503 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1504 outputIndex,
1505 layer,
1506 outputIndex,
1507 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001508 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001509 overrideOutputInfo,
1510 validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001511}
1512
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001513template<typename HalPolicy,
1514 typename HalOperation = typename HalPolicy::Operation,
1515 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001516bool ConvertToActivation(const HalOperation& operation,
1517 const char* operationName,
1518 const armnn::ActivationDescriptor& activationDesc,
1519 const HalModel& model,
1520 ConversionData& data)
1521{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001522 using HalOperand = typename HalPolicy::Operand;
1523
1524 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001525 if (!input.IsValid())
1526 {
1527 return Fail("%s: Input 0 is invalid", operationName);
1528 }
1529
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001530 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001531 if (!outputOperand)
1532 {
1533 return false;
1534 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001535
1536 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001537
1538 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001539
1540 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1541 {
1542 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1543 IsActivationSupported,
1544 data.m_Backends,
1545 isSupported,
1546 input.GetTensorInfo(),
1547 outInfo,
1548 activationDesc);
1549 };
1550
1551 if(IsDynamicTensor(outInfo))
1552 {
1553 isSupported = AreDynamicTensorsSupported();
1554 }
1555 else
1556 {
1557 validateFunc(outInfo, isSupported);
1558 }
1559
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001560 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001561 {
1562 return false;
1563 }
1564
1565 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001566 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001567 input.Connect(layer->GetInputSlot(0));
1568
Finn Williamsa4983ce2020-07-23 12:55:12 +01001569 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001570}
1571
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001572template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001573 typename HalOperation = typename HalPolicy::Operation,
1574 typename HalModel = typename HalPolicy::Model>
1575bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1576{
1577 armnn::ActivationDescriptor desc;
1578 desc.m_Function = armnn::ActivationFunction::ReLu;
1579
1580 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1581}
1582
1583template<typename HalPolicy,
1584 typename HalOperation = typename HalPolicy::Operation,
1585 typename HalModel = typename HalPolicy::Model>
1586bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1587{
1588 armnn::ActivationDescriptor desc;
1589 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1590 desc.m_A = 1.0f;
1591 desc.m_B = -1.0f;
1592
1593 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1594}
1595
1596template<typename HalPolicy,
1597 typename HalOperation = typename HalPolicy::Operation,
1598 typename HalModel = typename HalPolicy::Model>
1599bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1600{
1601 armnn::ActivationDescriptor desc;
1602 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1603 desc.m_A = 6.0f;
1604
1605 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1606}
1607
1608template<typename HalPolicy,
1609 typename HalOperation = typename HalPolicy::Operation,
1610 typename HalModel = typename HalPolicy::Model>
1611bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1612{
1613 armnn::ActivationDescriptor desc;
1614 desc.m_Function = armnn::ActivationFunction::TanH;
1615 desc.m_A = 1.0f; // android nn does not support tanH parameters
1616 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1617
1618 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1619}
1620
1621template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001622 typename HalOperation = typename HalPolicy::Operation,
1623 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001624bool ConvertPaddings(const HalOperation& operation,
1625 const HalModel& model,
1626 ConversionData& data,
1627 unsigned int rank,
1628 armnn::PadDescriptor& padDescriptor)
1629{
1630 using HalOperand = typename HalPolicy::Operand;
1631
1632 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1633 if (!paddingsOperand)
1634 {
1635 return Fail("%s: Could not read paddings operand", __func__);
1636 }
1637
1638 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1639 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1640 {
1641 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1642 }
1643
1644 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001645 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1646 {
1647 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1648 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001649
1650 // add padding for each dimension of input tensor.
1651 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1652 {
1653 int paddingBeforeInput = paddings[i];
1654 int paddingAfterInput = paddings[i + 1];
1655
1656 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1657 {
1658 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1659 }
1660
1661 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1662 }
1663
1664 return true;
1665}
1666
1667template<typename HalPolicy,
1668 typename HalOperation = typename HalPolicy::Operation,
1669 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001670bool ConvertPooling2d(const HalOperation& operation,
1671 const char* operationName,
1672 armnn::PoolingAlgorithm poolType,
1673 const HalModel& model,
1674 ConversionData& data)
1675{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001676 using HalOperand = typename HalPolicy::Operand;
1677 using HalOperandType = typename HalPolicy::OperandType;
1678
1679 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001680 if (!input.IsValid())
1681 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001682 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001683 }
1684
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001685 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001686 if (!output)
1687 {
1688 return Fail("%s: Could not read output 0", __func__);
1689 }
1690
1691 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1692 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1693
arovir01b0717b52018-09-05 17:03:25 +01001694 armnn::Pooling2dDescriptor desc;
1695 desc.m_PoolType = poolType;
1696 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001697 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001698
1699 ActivationFn activation;
1700
Sadik Armagan15d63e22019-07-26 16:59:35 +01001701 auto inputSize = operation.inputs.size();
1702
1703 if (inputSize >= 10)
1704 {
1705 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1706 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1707 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1708 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1709 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1710 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1711 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1712 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1713 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1714 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1715 {
1716 return Fail("%s: Operation has invalid inputs", operationName);
1717 }
1718
Kevin May42477c12020-03-26 13:34:14 +00001719 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001720 {
1721 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1722 }
1723 }
1724 else
arovir01b0717b52018-09-05 17:03:25 +01001725 {
1726 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1727 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001728 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1729 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1730 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1731 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1732 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1733 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001734 {
1735 return Fail("%s: Operation has invalid inputs", operationName);
1736 }
1737
Kevin May42477c12020-03-26 13:34:14 +00001738 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001739 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001740 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001741 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001742
1743 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1744 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1745 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1746
1747 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1748 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001749 }
1750
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001751 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001752
1753 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1754 {
1755 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1756 IsPooling2dSupported,
1757 data.m_Backends,
1758 isSupported,
1759 inputInfo,
1760 outputInfo,
1761 desc);
1762
1763 };
1764
1765 if(IsDynamicTensor(outputInfo))
1766 {
1767 isSupported = AreDynamicTensorsSupported();
1768 }
1769 else
1770 {
1771 validateFunc(outputInfo, isSupported);
1772 }
1773
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001774 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001775 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001776 return false;
arovir01b0717b52018-09-05 17:03:25 +01001777 }
arovir01b0717b52018-09-05 17:03:25 +01001778
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001779 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1780 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001781 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001782 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001783 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001784
1785 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1786 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001787 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001788 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001789 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001790
1791 input.Connect(pooling2dLayer->GetInputSlot(0));
1792
Finn Williamsa4983ce2020-07-23 12:55:12 +01001793 if (!isSupported)
1794 {
1795 return false;
1796 }
1797
1798 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001799}
1800
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001801template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001802 typename HalOperation = typename HalPolicy::Operation,
1803 typename HalModel = typename HalPolicy::Model>
1804bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001805{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001806 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001807
1808 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1809 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1810
1811 if (!input0.IsValid() || !input1.IsValid())
1812 {
1813 return Fail("%s: Operation has invalid inputs", __func__);
1814 }
1815
1816 // The FuseActivation parameter is always the input index 2
1817 // and it should be optional
1818 ActivationFn activationFunction;
1819 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1820 {
1821 return Fail("%s: Operation has invalid inputs", __func__);
1822 }
1823
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001824 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001825 if (!outputOperand)
1826 {
1827 return false;
1828 }
1829
1830 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1831 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1832
1833 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01001834
1835 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001836 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1837 {
1838 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1839 IsAdditionSupported,
1840 data.m_Backends,
1841 isSupported,
1842 inputInfo0,
1843 inputInfo1,
1844 outputInfo);
1845 };
1846
1847 if(!IsDynamicTensor(outputInfo))
1848 {
1849 validateFunc(outputInfo, isSupported);
1850 }
1851 else
1852 {
1853 isSupported = AreDynamicTensorsSupported();
1854 }
1855
Mike Kelly46272802019-08-14 17:00:48 +01001856 if (!isSupported)
1857 {
1858 return false;
1859 }
1860
1861 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
1862 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
1863
1864 if (endLayer != nullptr)
1865 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00001866 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01001867 if (!isReshapeSupported)
1868 {
1869 return false;
1870 }
1871
Teresa Charlin4bd9a742020-08-12 12:58:50 +01001872 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01001873 }
1874 else
1875 {
1876 return Fail("%s: ProcessActivation failed", __func__);
1877 }
1878}
1879
1880template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001881 typename HalOperation = typename HalPolicy::Operation,
1882 typename HalModel = typename HalPolicy::Model>
1883bool ConvertArgMinMax(const HalOperation& operation,
1884 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001885 ConversionData& data,
1886 armnn::ArgMinMaxFunction argMinMaxFunction)
1887{
1888 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1889
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001890 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001891 using HalOperandType = typename HalPolicy::OperandType;
1892
1893 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1894
1895 if (!input0.IsValid())
1896 {
1897 return Fail("%s: Operation has invalid inputs", __func__);
1898 }
1899
1900 int32_t axis;
1901 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1902 {
1903 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1904 }
1905
1906 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1907 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1908
1909 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1910 {
1911 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1912 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1913 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1914 return Fail("%s: Axis must be in range [-n, n)", __func__);
1915 }
1916
1917 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1918 if (!output)
1919 {
1920 return Fail("%s: Could not read output 0", __func__);
1921 }
1922
1923 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1924
1925 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001926
1927 armnn::ArgMinMaxDescriptor descriptor;
1928 descriptor.m_Function = argMinMaxFunction;
1929 descriptor.m_Axis = axis;
1930
1931 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001932
1933 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1934 {
1935 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1936 IsArgMinMaxSupported,
1937 data.m_Backends,
1938 isSupported,
1939 inputInfo0,
1940 outputInfo,
1941 descriptor);
1942 };
1943
1944 if(IsDynamicTensor(outputInfo))
1945 {
1946 isSupported = AreDynamicTensorsSupported();
1947 }
1948 else
1949 {
1950 validateFunc(outputInfo, isSupported);
1951 }
1952
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001953 if (!isSupported)
1954 {
1955 return false;
1956 }
1957
1958 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1959 assert(layer != nullptr);
1960
1961 input0.Connect(layer->GetInputSlot(0));
1962
Finn Williamsa4983ce2020-07-23 12:55:12 +01001963 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001964}
1965
1966template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001967 typename HalOperation = typename HalPolicy::Operation,
1968 typename HalModel = typename HalPolicy::Model>
1969bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001970{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001971 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001972 using HalOperandType = typename HalPolicy::OperandType;
1973
1974 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1975 if (operation.inputs.size() <= 1)
1976 {
1977 return Fail("%s: Operation has insufficient arguments", __func__);
1978 }
1979
1980 // Get inputs and outputs
1981 const std::size_t numInputTensors = operation.inputs.size() - 1;
1982
1983 int32_t concatDim;
1984 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1985 {
1986 return Fail("%s: Operation has invalid inputs", __func__);
1987 }
1988
1989 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1990 if (!outputOperand)
1991 {
1992 return Fail("%s: Operation has no outputs", __func__);
1993 }
1994
Mike Kellyb8805202019-07-31 17:25:43 +01001995 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
1996 armnn::TensorShape outputShape = outputInfo.GetShape();
1997
1998 //
1999 // handle negative concat dims along the lines of tensorflow as described here:
2000 // https://www.tensorflow.org/api_docs/python/tf/concat
2001 // "negative axis refers to axis + rank(values)-th dimension"
2002 //
2003 if (concatDim < 0)
2004 {
2005 concatDim += outputShape.GetNumDimensions();
2006 }
2007
2008 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
2009 {
2010 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
2011 }
2012
2013 std::vector<LayerInputHandle> inputHandles;
2014 std::vector<armnn::TensorShape> inputShapes;
2015
2016 inputHandles.reserve(numInputTensors);
2017 inputShapes.reserve(numInputTensors);
2018
2019 bool inputsHaveBeenReshaped = false;
2020 unsigned int tensorDimensionsAdded = 0;
2021
2022 for (uint32_t i = 0; i < numInputTensors; ++i)
2023 {
2024 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
2025 if (!operand)
2026 {
2027 return Fail("%s: Operation has invalid inputs", __func__);
2028 }
2029
Teresa Charlin3b959602019-10-31 17:05:47 +00002030 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2031 if (!operandInputHandle.IsValid())
2032 {
2033 return Fail("%s: Operation has invalid inputs", __func__);
2034 }
Mike Kellyb8805202019-07-31 17:25:43 +01002035
Teresa Charlin3b959602019-10-31 17:05:47 +00002036 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002037 if (operandShape.GetNumDimensions() == 0)
2038 {
2039 return Fail("%s: Operands with rank 0 are not supported", __func__);
2040 }
2041
2042 if (RequiresReshape(operandShape))
2043 {
2044 inputsHaveBeenReshaped = true;
2045
2046 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2047
2048 // Expand the tensor to three dimensions
2049 if (operandShape.GetNumDimensions() == 2)
2050 {
2051 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2052 tensorDimensionsAdded = 1;
2053 }
2054 else
2055 {
2056 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2057 tensorDimensionsAdded = 2;
2058 }
2059
Kevin Mayaed08ac2019-12-12 16:33:31 +00002060 armnn::ReshapeDescriptor reshapeDescriptor;
2061 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2062
2063 bool isSupported = false;
2064 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2065 IsReshapeSupported,
2066 data.m_Backends,
2067 isSupported,
2068 operandInputHandle.GetTensorInfo(),
2069 reshapeInfo,
2070 reshapeDescriptor);
2071 if (!isSupported)
2072 {
2073 return false;
2074 }
2075
Mike Kellyb8805202019-07-31 17:25:43 +01002076 armnn::IConnectableLayer& newReshape = AddReshapeLayer(
2077 *data.m_Network,
2078 operandInputHandle,
2079 reshapeInfo
2080 );
2081
2082 // Point to the reshape operation rather then the input operation
2083 operandShape = reshapeInfo.GetShape();
2084 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2085 }
2086
2087 inputShapes.emplace_back(operandShape);
2088 inputHandles.emplace_back(operandInputHandle);
2089
2090 if (!inputHandles.back().IsValid())
2091 {
2092 return Fail("%s: Operation has invalid inputs", __func__);
2093 }
2094 }
2095
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002096 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002097
2098 if (inputsHaveBeenReshaped)
2099 {
2100 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2101 concatDim += tensorDimensionsAdded;
2102
2103 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2104 if (tensorDimensionsAdded == 1)
2105 {
2106 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2107 }
2108 else if (tensorDimensionsAdded == 2)
2109 {
2110 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2111 }
2112 }
2113
2114 // Check if permutations is required and get the pair of permutations required for the concatenation.
2115 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2116 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
2117 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
2118
2119 bool needPermute =
2120 CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(), concatDim, permutationPair);
2121
2122 if (needPermute)
2123 {
Mike Kelly4a956582020-02-28 10:32:09 +00002124 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
Mike Kellyb8805202019-07-31 17:25:43 +01002125 }
2126
2127 outputInfo.SetShape(outputShape);
2128
2129 // this is no-op for identity swizzles, otherwise it replaces both
2130 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002131 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002132 {
2133 return false;
2134 }
Mike Kellyb8805202019-07-31 17:25:43 +01002135
2136 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2137 armnn::OriginsDescriptor concatDescriptor;
2138
2139 try
2140 {
2141 // The concat descriptor is always created across the only supported concat dimension
2142 // which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
2143 concatDescriptor =
2144 armnn::CreateDescriptorForConcatenation(inputShapes.begin(), inputShapes.end(), concatDim);
2145 }
Derek Lambertib9cb8442019-11-28 13:34:48 +00002146 catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002147 {
2148 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2149 }
2150
2151 // Validate the output shape is correct given the input shapes based on the
2152 // only valid concat dimension which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
2153 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2154 {
2155 return Fail("%s: Error validating the output shape for concat", __func__);
2156 }
2157
2158 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2159 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
2160 [](const LayerInputHandle& h) -> const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
2161
2162 bool isSupported = false;
2163 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2164 IsConcatSupported,
2165 data.m_Backends,
2166 isSupported,
2167 inputTensorInfos,
2168 outputInfo,
2169 concatDescriptor);
2170 if (!isSupported)
2171 {
2172 return false;
2173 }
2174
2175 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2176 assert(layer != nullptr);
2177 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2178
2179 // Connect inputs to the layer
2180 const int numInputSlots = layer->GetNumInputSlots();
2181 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2182 for (int i = 0; i < numInputSlots; ++i)
2183 {
2184 // connect the input directly to the merge (concat) layer
2185 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2186 }
2187
2188 if (needPermute)
2189 {
Mike Kelly4a956582020-02-28 10:32:09 +00002190 armnn::TransposeDescriptor transposeDesc;
2191 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002192 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2193 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2194 permutationPair.second);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002195
2196 bool isSupported = false;
2197 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002198 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002199 data.m_Backends,
2200 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002201 inputTransposeInfo,
2202 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002203 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002204 if (!isSupported)
2205 {
2206 return false;
2207 }
Mike Kellyb8805202019-07-31 17:25:43 +01002208 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Mike Kelly4a956582020-02-28 10:32:09 +00002209 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network,
2210 layer->GetOutputSlot(0),
2211 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002212 layer = &deswizzleLayer;
2213 }
2214
2215 if (inputsHaveBeenReshaped)
2216 {
2217 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
2218
2219 // Undo the reshape knowing the amount of dimensions added
2220 if (tensorDimensionsAdded == 1)
2221 {
2222 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[1],
2223 afterConcatInfo.GetShape()[2] }));
2224 }
2225 else if (tensorDimensionsAdded == 2)
2226 {
2227 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[2] }));
2228 }
2229
Kevin Mayaed08ac2019-12-12 16:33:31 +00002230 armnn::ReshapeDescriptor reshapeDescriptor;
2231 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
2232
2233 bool isSupported = false;
2234 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2235 IsReshapeSupported,
2236 data.m_Backends,
2237 isSupported,
2238 layer->GetOutputSlot(0).GetTensorInfo(),
2239 afterConcatInfo,
2240 reshapeDescriptor);
2241 if (!isSupported)
2242 {
2243 return false;
2244 }
2245
Mike Kellyb8805202019-07-31 17:25:43 +01002246 layer = &AddReshapeLayer(
2247 *data.m_Network,
2248 layer->GetOutputSlot(0),
2249 afterConcatInfo
2250 );
2251 }
2252
2253 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2254}
2255
2256template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002257 typename HalOperation = typename HalPolicy::Operation,
2258 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002259bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2260{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002261 using HalOperand = typename HalPolicy::Operand;
2262 using HalOperandType = typename HalPolicy::OperandType;
2263
2264 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002265 if (!input.IsValid())
2266 {
2267 return Fail("%s: Operation has invalid inputs", __func__);
2268 }
2269
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002270 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002271 if (!output)
2272 {
2273 return Fail("%s: Could not read output 0", __func__);
2274 }
2275
2276 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002277 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002278
2279 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002280 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2281 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002282
2283 if (!weightsPin.IsValid() || !biasPin.IsValid())
2284 {
2285 return Fail("%s: Operation has invalid inputs", __func__);
2286 }
2287
2288 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002289 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002290 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2291
2292 armnn::Convolution2dDescriptor desc;
2293 desc.m_DataLayout = armnn::DataLayout::NHWC;
2294 ActivationFn activation;
2295
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002296 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002297 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002298 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2299 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2300 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2301 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2302 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2303 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002304 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002305 {
2306 return Fail("%s: Operation has invalid inputs", __func__);
2307 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002308 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002309 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002310 {
2311 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002312 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2313 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2314 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002315 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002316 {
2317 return Fail("%s: Operation has invalid inputs", __func__);
2318 }
2319
2320 const uint32_t kernelX = weights.GetShape()[2];
2321 const uint32_t kernelY = weights.GetShape()[1];
2322 const uint32_t inputX = inputInfo.GetShape()[2];
2323 const uint32_t inputY = inputInfo.GetShape()[1];
2324
2325 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2326 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002327 }
2328 else
2329 {
2330 return Fail("%s: Unsupported number of operation inputs", __func__);
2331 }
2332
2333 desc.m_BiasEnabled = true;
2334 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2335
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002336 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002337 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2338 {
2339 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2340 IsConvolution2dSupported,
2341 data.m_Backends,
2342 isSupported,
2343 inputInfo,
2344 outputInfo,
2345 desc,
2346 weights.GetInfo(),
2347 biases);
2348 };
2349
2350 if(!IsDynamicTensor(outputInfo))
2351 {
2352 validateFunc(outputInfo, isSupported);
2353 }
2354 else
2355 {
2356 isSupported = AreDynamicTensorsSupported();
2357 }
2358
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002359 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002360 {
2361 return false;
2362 }
2363
2364 armnn::IConnectableLayer* startLayer =
2365 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2366
2367 if (!startLayer)
2368 {
2369 return Fail("%s: AddConvolution2dLayer failed", __func__);
2370 }
2371
2372 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2373
2374 if (!endLayer)
2375 {
2376 return Fail("%s: ProcessActivation failed", __func__);
2377 }
2378
2379 input.Connect(startLayer->GetInputSlot(0));
2380
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002381 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002382}
2383
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002384template<typename HalPolicy,
2385 typename HalOperation = typename HalPolicy::Operation,
2386 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002387bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2388{
2389 using HalOperand = typename HalPolicy::Operand;
2390 using HalOperandType = typename HalPolicy::OperandType;
2391
2392 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2393 if (!input.IsValid() )
2394 {
2395 return Fail("%s: Operation has invalid inputs", __func__);
2396 }
2397
2398 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2399 unsigned int rank = inputInfo.GetNumDimensions();
2400 if (rank != 4)
2401 {
2402 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2403 }
2404
2405 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2406 if (!output)
2407 {
2408 return Fail("%s: Could not read output 0", __func__);
2409 }
2410
2411 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002412
2413 armnn::DepthToSpaceDescriptor descriptor;
2414
2415 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2416 if (descriptor.m_BlockSize <= 1)
2417 {
2418 return Fail("%s: Block size must be at least 1 in all dimensions");
2419 }
2420
2421 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002422 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002423 {
2424 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2425 }
2426
2427 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002428 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2429 {
2430 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2431 IsDepthToSpaceSupported,
2432 data.m_Backends,
2433 isSupported,
2434 inputInfo,
2435 outputInfo,
2436 descriptor);
2437 };
2438
2439 if(!IsDynamicTensor(outputInfo))
2440 {
2441 validateFunc(outputInfo, isSupported);
2442 }
2443 else
2444 {
2445 isSupported = AreDynamicTensorsSupported();
2446 }
2447
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002448 if (!isSupported)
2449 {
2450 return false;
2451 }
2452
2453 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2454 assert(layer != nullptr);
2455 input.Connect(layer->GetInputSlot(0));
2456
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002457 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002458}
2459
2460template<typename HalPolicy,
2461 typename HalOperation = typename HalPolicy::Operation,
2462 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002463bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2464{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002465 using HalOperand = typename HalPolicy::Operand;
2466 using HalOperandType = typename HalPolicy::OperandType;
2467
2468 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002469
2470 if (!input.IsValid())
2471 {
2472 return Fail("%s: Operation has invalid inputs", __func__);
2473 }
2474
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002475 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002476
2477 if (!output)
2478 {
2479 return Fail("%s: Could not read output 0", __func__);
2480 }
2481
2482 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002483 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002484
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002485 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002486 // Find the shape of the weights tensor. In AndroidNN this will be [ 1, H, W, I * M ]
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002487 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002488
2489 if (weightsOperand == nullptr)
2490 {
2491 return Fail("%s: Operand is invalid", __func__);
2492 }
2493 armnn::DepthwiseConvolution2dDescriptor desc;
2494 desc.m_DataLayout = armnn::DataLayout::NHWC;
2495
Mike Kellyb5fdf382019-06-11 16:35:25 +01002496 // Reinterpret weight data as [ H, W, I, M ]
2497 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2498 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002499 inputInfo.GetShape()[3],
2500 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002501
2502 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2503 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2504
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002505 const ConstTensorPin weightsPin =
2506 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2507 1,
2508 model,
2509 data,
2510 HWIMToMIHW,
2511 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002512
2513 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002514 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002515
2516 if (!weightsPin.IsValid() || !biasPin.IsValid())
2517 {
2518 return Fail("%s: Operation has invalid inputs", __func__);
2519 }
2520
2521 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2522 armnn::ConstTensor bias = biasPin.GetConstTensor();
2523 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2524
2525 ActivationFn activation;
2526
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002527 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002528 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002529 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2530 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2531 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2532 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2533 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2534 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002535 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002536 {
2537 return Fail("%s: Operation has invalid inputs", __func__);
2538 }
2539 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002540 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002541 {
2542 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002543 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2544 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2545 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002546 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002547 {
2548 return Fail("%s: Operation has invalid inputs", __func__);
2549 }
2550
2551 const uint32_t kernelX = weights.GetShape()[3];
2552 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002553 const uint32_t inputX = inputInfo.GetShape()[2];
2554 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002555
2556 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2557 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2558 }
2559 else
2560 {
2561 return Fail("%s: Unsupported number of operation inputs", __func__);
2562 }
2563
2564 desc.m_BiasEnabled = true;
2565 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2566
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002567 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002568 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2569 {
2570 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2571 IsDepthwiseConvolutionSupported,
2572 data.m_Backends,
2573 isSupported,
2574 inputInfo,
2575 outputInfo,
2576 desc,
2577 weights.GetInfo(),
2578 biases);
2579 };
2580
2581 if(!IsDynamicTensor(outputInfo))
2582 {
2583 validateFunc(outputInfo, isSupported);
2584 }
2585 else
2586 {
2587 isSupported = AreDynamicTensorsSupported();
2588 }
2589
2590
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002591 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002592 {
2593 return false;
2594 }
2595
2596 armnn::IConnectableLayer* startLayer =
2597 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2598 if (!startLayer)
2599 {
2600 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2601 }
2602
2603 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2604 if (!endLayer)
2605 {
2606 return Fail("%s: ProcessActivation failed", __func__);
2607 }
2608
2609 input.Connect(startLayer->GetInputSlot(0));
2610
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002611 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01002612}
2613
Mike Kelly3c673942019-07-25 09:26:06 +01002614template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002615 typename HalOperation = typename HalPolicy::Operation,
2616 typename HalModel = typename HalPolicy::Model>
2617bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002618{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002619 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002620
2621 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2622 if (!input.IsValid())
2623 {
2624 return Fail("%s: Operation has invalid input", __func__);
2625 }
2626
Sadik Armagan98c0f662019-11-21 15:54:36 +00002627 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2628 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2629 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2630 {
2631 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2632 }
2633
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002634 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002635 if (!outputOperand)
2636 {
2637 return Fail("%s: Operation has invalid outputs", __func__);
2638 }
2639
2640 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002641
2642 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002643 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2644 {
2645 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2646 IsDequantizeSupported,
2647 data.m_Backends,
2648 isSupported,
2649 inputInfo,
2650 outputInfo);
2651 };
2652
2653 if(IsDynamicTensor(outputInfo))
2654 {
2655 isSupported = AreDynamicTensorsSupported();
2656 }
2657 else
2658 {
2659 validateFunc(outputInfo, isSupported);
2660 }
2661
Mike Kelly46272802019-08-14 17:00:48 +01002662 if (!isSupported)
2663 {
2664 return false;
2665 }
2666
2667 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2668 assert(layer != nullptr);
2669 input.Connect(layer->GetInputSlot(0));
2670
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002671 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002672}
2673
2674template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002675 typename HalOperation = typename HalPolicy::Operation,
2676 typename HalModel = typename HalPolicy::Model>
2677bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002678{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002679 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002680
2681 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2682 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2683
2684 if (!input0.IsValid() || !input1.IsValid())
2685 {
2686 return Fail("%s: Operation has invalid inputs", __func__);
2687 }
2688
2689 // The FuseActivation parameter is always the input index 2
2690 // and it should be optional
2691 ActivationFn activationFunction;
2692 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2693 {
2694 return Fail("%s: Operation has invalid inputs", __func__);
2695 }
2696
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002697 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002698 if (!output)
2699 {
2700 return Fail("%s: Could not read output 0", __func__);
2701 }
2702
2703 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01002704
2705 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002706 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2707 {
2708 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2709 IsDivisionSupported,
2710 data.m_Backends,
2711 isSupported,
2712 input0.GetTensorInfo(),
2713 input1.GetTensorInfo(),
2714 outputInfo);
2715 };
2716
2717 if(!IsDynamicTensor(outputInfo))
2718 {
2719 validateFunc(outputInfo, isSupported);
2720 }
2721 else
2722 {
2723 isSupported = AreDynamicTensorsSupported();
2724 }
2725
Mike Kelly46272802019-08-14 17:00:48 +01002726 if (!isSupported)
2727 {
2728 return false;
2729 }
2730
2731 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
2732 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2733
2734 if (endLayer)
2735 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00002736 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01002737 if (!isReshapeSupported)
2738 {
2739 return false;
2740 }
2741
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002742 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002743 }
2744 return Fail("%s: ProcessActivation failed", __func__);
2745}
2746
2747template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002748 typename HalOperation = typename HalPolicy::Operation,
2749 typename HalModel = typename HalPolicy::Model>
2750bool ConvertFloor(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002751{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002752 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002753
2754 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2755 if (!input.IsValid())
2756 {
2757 return Fail("%s: Operation has invalid inputs", __func__);
2758 }
2759
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002760 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002761 if (!outputOperand)
2762 {
2763 return Fail("%s: Operation has invalid outputs", __func__);
2764 }
2765
2766 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01002767
2768 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002769 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
2770 {
2771 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2772 IsFloorSupported,
2773 data.m_Backends,
2774 isSupported,
2775 input.GetTensorInfo(),
2776 outputInfo);
2777 };
2778
2779 if(!IsDynamicTensor(outputInfo))
2780 {
2781 validateFunc(outputInfo, isSupported);
2782 }
2783 else
2784 {
2785 isSupported = AreDynamicTensorsSupported();
2786 }
2787
Mike Kelly46272802019-08-14 17:00:48 +01002788 if (!isSupported)
2789 {
2790 return false;
2791 }
2792
2793 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2794 assert(layer != nullptr);
2795 input.Connect(layer->GetInputSlot(0));
2796
Teresa Charlin4bd9a742020-08-12 12:58:50 +01002797 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01002798}
2799
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002800inline bool IsQSymm8(const V1_0::Operand&)
2801{
2802 return false;
2803}
2804
Kevin May42477c12020-03-26 13:34:14 +00002805#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002806
2807inline bool IsQSymm8(const V1_2::Operand& operand)
2808{
2809 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2810}
2811
2812#endif
2813
Kevin May42477c12020-03-26 13:34:14 +00002814#ifdef ARMNN_ANDROID_NN_V1_3
2815
2816inline bool IsQSymm8(const V1_3::Operand& operand)
2817{
2818 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2819}
2820
2821#endif
2822
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002823enum class DequantizeStatus
2824{
2825 SUCCESS,
2826 NOT_REQUIRED,
2827 INVALID_OPERAND
2828};
2829
2830using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2831
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002832template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002833 typename HalOperation = typename HalPolicy::Operation,
2834 typename HalModel = typename HalPolicy::Model>
2835DequantizeResult DequantizeIfRequired(size_t operand_index,
2836 const HalOperation& operation,
2837 const HalModel& model,
2838 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002839{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002840 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002841
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002842 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002843 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002844 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002845 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002846 }
2847
2848 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2849 {
2850 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002851 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002852 }
2853
2854 const size_t weightsInputIndex = operation.inputs[operand_index];
2855
2856 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2857 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002858 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002859 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002860 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002861 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002862 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2863 {
2864 continue;
2865 }
2866
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002867 size_t outOpIndex = weightsInputIndex + 1;
2868 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002869 {
2870 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002871 }
2872
2873 if (outOpIndex != weightsInputIndex)
2874 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002875 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002876 }
2877
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002878 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002879 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002880
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002881 if (!IsQSymm8(*operand))
2882 {
2883 // Only supporting dequantize from QSYMM8 to FLOAT
2884 break;
2885 }
2886
2887 // Allocate a new buffer for the dequantized data and manually dequantize
2888 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2889 if (!startValue)
2890 {
2891 // Failed to get the operand address
2892 break;
2893 }
2894
2895 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2896 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002897 const float quantizationScale = operand->scale;
2898
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002899 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2900 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2901 {
2902 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002903 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002904 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2905 }
2906
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002907 // Construct tensor info for dequantized ConstTensor
2908 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2909 operand->dimensions.data(),
2910 armnn::DataType::Float32);
2911
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002912 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2913 std::move(tensorInfo),
2914 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002915 }
2916
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002917 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002918}
2919
2920template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002921 typename HalOperation = typename HalPolicy::Operation,
2922 typename HalModel = typename HalPolicy::Model>
2923ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2924 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002925 const ConversionData& data,
2926 size_t operandIndex,
2927 bool optional = false)
2928{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002929 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2930
2931 DequantizeStatus status = std::get<3>(dequantized);
2932 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002933 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002934 case DequantizeStatus::INVALID_OPERAND:
2935 {
2936 // return invalid const tensor pin
2937 return ConstTensorPin();
2938 }
2939 case DequantizeStatus::NOT_REQUIRED:
2940 {
2941 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2942 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
2943 }
2944 case DequantizeStatus::SUCCESS:
2945 default:
2946 {
2947 return ConstTensorPin(
2948 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
2949 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002950 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002951}
2952
2953
Mike Kelly46272802019-08-14 17:00:48 +01002954template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002955 typename HalOperation = typename HalPolicy::Operation,
2956 typename HalModel = typename HalPolicy::Model>
2957bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002958{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002959 using HalOperand = typename HalPolicy::Operand;
2960
Mike Kelly46272802019-08-14 17:00:48 +01002961 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2962 if (!input.IsValid())
2963 {
2964 return Fail("%s: Operation has invalid inputs", __func__);
2965 }
2966
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002967 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002968 if (!output)
2969 {
2970 return Fail("%s: Could not read output 0", __func__);
2971 }
2972
2973 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2974 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2975
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002976 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
2977 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002978
2979 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01002980 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002981 return Fail("%s: Operation has invalid weights", __func__);
2982 }
2983
2984 if (!biasPin.IsValid())
2985 {
2986 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01002987 }
2988
2989 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2990 armnn::ConstTensor bias = biasPin.GetConstTensor();
2991 armnn::TensorInfo reshapedInfo = inputInfo;
2992
2993 try
2994 {
2995 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002996 }
2997 catch (const std::exception& e)
2998 {
Mike Kelly46272802019-08-14 17:00:48 +01002999 return Fail("%s: %s", __func__, e.what());
3000 }
3001
3002 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
3003 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
3004
3005 ActivationFn activationFunction;
3006 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
3007 {
3008 return Fail("%s: Operation has invalid inputs", __func__);
3009 }
3010
3011 armnn::FullyConnectedDescriptor desc;
3012 desc.m_TransposeWeightMatrix = true;
3013 desc.m_BiasEnabled = true;
3014
FinnWilliamsArm7b8d2e62020-01-08 14:57:47 +00003015 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
3016 weights.GetInfo().GetShape(),
3017 outputInfo.GetShape(),
3018 desc.m_TransposeWeightMatrix))
3019 {
3020 return Fail("%s: Expected outputShape does not match actual outputShape", __func__);
3021 }
3022
Mike Kelly46272802019-08-14 17:00:48 +01003023 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003024 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3025 {
3026 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly46272802019-08-14 17:00:48 +01003027 IsFullyConnectedSupported,
3028 data.m_Backends,
3029 isSupported,
3030 reshapedInfo,
3031 outputInfo,
3032 weights.GetInfo(),
3033 bias.GetInfo(),
3034 desc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003035 };
3036
3037 if(!IsDynamicTensor(outputInfo))
3038 {
3039 validateFunc(outputInfo, isSupported);
3040 }
3041 else
3042 {
3043 isSupported = AreDynamicTensorsSupported();
3044 }
3045
Mike Kelly46272802019-08-14 17:00:48 +01003046 if (!isSupported)
3047 {
3048 return false;
3049 }
3050
3051 armnn::IConnectableLayer* startLayer =
3052 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
3053 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3054
3055 if (endLayer != nullptr)
3056 {
3057 if (inputInfo.GetNumDimensions() > 2U)
3058 {
3059 armnn::ReshapeDescriptor reshapeDescriptor;
3060 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
3061
3062 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3063 assert(reshapeLayer != nullptr);
3064 input.Connect(reshapeLayer->GetInputSlot(0));
3065 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
3066 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
3067 }
3068 else
3069 {
3070 input.Connect(startLayer->GetInputSlot(0));
3071 }
3072
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003073 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003074 }
3075 else
3076 {
3077 return Fail("%s: ProcessActivation failed", __func__);
3078 }
3079}
3080
3081template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003082 typename HalOperation = typename HalPolicy::Operation,
3083 typename HalModel = typename HalPolicy::Model>
3084bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003085{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003086 using HalOperand = typename HalPolicy::Operand;
3087
Mike Kelly999e2092019-08-15 10:46:46 +01003088 if (operation.inputs.size() != 1)
3089 {
3090 return Fail("%s: Optional inputs are not supported", __func__);
3091 }
3092
Mike Kelly46272802019-08-14 17:00:48 +01003093 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3094 if (!input.IsValid())
3095 {
3096 return Fail("%s: Operation has invalid inputs", __func__);
3097 }
3098
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003099 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003100 if (!output)
3101 {
3102 return Fail("%s: Could not read output 0", __func__);
3103 }
3104
3105 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3106 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3107
Mike Kelly46272802019-08-14 17:00:48 +01003108 if (outputInfo.GetNumDimensions() != 4u)
3109 {
3110 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3111 }
3112
3113 armnn::L2NormalizationDescriptor desc;
3114 desc.m_DataLayout = armnn::DataLayout::NHWC;
3115
3116 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003117 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3118 {
3119 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3120 IsL2NormalizationSupported,
3121 data.m_Backends,
3122 isSupported,
3123 inputInfo,
3124 outputInfo,
3125 desc);
3126 };
3127
3128 if(!IsDynamicTensor(outputInfo))
3129 {
3130 validateFunc(outputInfo, isSupported);
3131 }
3132 else
3133 {
3134 isSupported = AreDynamicTensorsSupported();
3135 }
3136
Mike Kelly46272802019-08-14 17:00:48 +01003137 if (!isSupported)
3138 {
3139 return false;
3140 }
3141
3142 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3143 assert(layer != nullptr);
3144 input.Connect(layer->GetInputSlot(0));
3145
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003146 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003147}
3148
3149template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003150 typename HalOperation = typename HalPolicy::Operation,
3151 typename HalModel = typename HalPolicy::Model>
3152bool ConvertLocalResponseNormalization(const HalOperation& operation,
3153 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003154 ConversionData& data)
3155{
Mike Kelly999e2092019-08-15 10:46:46 +01003156 if (operation.inputs.size() != 5)
3157 {
3158 return Fail("%s: Optional inputs are not supported", __func__);
3159 }
3160
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003161 using HalOperand = typename HalPolicy::Operand;
3162 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003163
3164 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3165 if (!input.IsValid())
3166 {
3167 return Fail("%s: Operation has invalid inputs", __func__);
3168 }
3169
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003170 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003171 if (!output)
3172 {
3173 return Fail("%s: Could not read output 0", __func__);
3174 }
3175
3176 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3177 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3178
Mike Kelly46272802019-08-14 17:00:48 +01003179 if (outputInfo.GetNumDimensions() != 4u)
3180 {
3181 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3182 }
3183
3184 armnn::NormalizationDescriptor descriptor;
3185 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3186 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3187 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3188
3189 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003190 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003191 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3192 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3193 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3194 {
3195 return Fail("%s: Operation has invalid inputs", __func__);
3196 }
3197
3198 // ArmNN expects normSize to be the full size of the normalization
3199 // window rather than the radius as in AndroidNN.
3200 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3201
3202 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003203 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3204 {
3205 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3206 IsNormalizationSupported,
3207 data.m_Backends,
3208 isSupported,
3209 inputInfo,
3210 outputInfo,
3211 descriptor);
3212 };
3213
3214 if(!IsDynamicTensor(outputInfo))
3215 {
3216 validateFunc(outputInfo, isSupported);
3217 }
3218 else
3219 {
3220 isSupported = AreDynamicTensorsSupported();
3221 }
3222
Mike Kelly46272802019-08-14 17:00:48 +01003223 if (!isSupported)
3224 {
3225 return false;
3226 }
3227
3228
3229 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3230 assert(layer != nullptr);
3231 input.Connect(layer->GetInputSlot(0));
3232
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003233 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003234}
3235
3236template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003237 typename HalOperation = typename HalPolicy::Operation,
3238 typename HalModel = typename HalPolicy::Model>
3239bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003240{
Mike Kelly46272802019-08-14 17:00:48 +01003241 armnn::ActivationDescriptor desc;
3242 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3243
3244 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3245}
3246
3247template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003248 typename HalOperation = typename HalPolicy::Operation,
3249 typename HalModel = typename HalPolicy::Model>
3250bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003251{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003252 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003253
3254 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3255 if (!input.IsValid())
3256 {
3257 return Fail("%s: Operation has invalid inputs", __func__);
3258 }
3259
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003260 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003261 if (!output)
3262 {
3263 return Fail("%s: Could not read output 0", __func__);
3264 }
3265
3266 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003267
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003268 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003269 if (!axisOperand)
3270 {
3271 return Fail("%s: Could not read input 1", __func__);
3272 }
3273
3274 std::vector<int32_t> axis;
3275 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3276 {
3277 return Fail("%s: Input 1 has invalid values", __func__);
3278 }
3279
3280 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3281
3282 // Convert the axis to unsigned int and remove duplicates.
3283 unsigned int rank = inputInfo.GetNumDimensions();
3284 std::set<unsigned int> uniqueAxis;
3285 std::transform(axis.begin(), axis.end(),
3286 std::inserter(uniqueAxis, uniqueAxis.begin()),
3287 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3288
3289 // Get the "keep dims" flag.
3290 int32_t keepDims = 0;
3291 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3292 {
3293 return Fail("%s: Could not read input 2", __func__);
3294 }
3295
3296 armnn::MeanDescriptor descriptor;
3297 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3298 descriptor.m_KeepDims = keepDims > 0;
3299
3300 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003301 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3302 {
3303 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3304 IsMeanSupported,
3305 data.m_Backends,
3306 isSupported,
3307 inputInfo,
3308 outputInfo,
3309 descriptor);
3310 };
3311
3312 if(!IsDynamicTensor(outputInfo))
3313 {
3314 validateFunc(outputInfo, isSupported);
3315 }
3316 else
3317 {
3318 isSupported = AreDynamicTensorsSupported();
3319 }
3320
Mike Kelly46272802019-08-14 17:00:48 +01003321 if (!isSupported)
3322 {
3323 return false;
3324 }
3325
3326 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3327 assert(layer != nullptr);
3328 input.Connect(layer->GetInputSlot(0));
3329
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003330 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003331}
3332
3333template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003334 typename HalOperation = typename HalPolicy::Operation,
3335 typename HalModel = typename HalPolicy::Model>
3336bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003337{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003338 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003339
3340 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3341 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3342
3343 if (!input0.IsValid() || !input1.IsValid())
3344 {
3345 return Fail("%s: Operation has invalid inputs", __func__);
3346 }
3347
3348 // The FuseActivation parameter is always the input index 2
3349 // and it should be optional
3350 ActivationFn activationFunction;
3351 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3352 {
3353 return Fail("%s: Operation has invalid inputs", __func__);
3354 }
3355
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003356 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003357
3358 if (outputOperand == nullptr)
3359 {
3360 return false;
3361 }
3362
3363 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
Mike Kelly46272802019-08-14 17:00:48 +01003364
3365 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003366 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3367 {
3368 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3369 IsMultiplicationSupported,
3370 data.m_Backends,
3371 isSupported,
3372 input0.GetTensorInfo(),
3373 input1.GetTensorInfo(),
3374 outputInfo);
3375 };
3376
3377 if(!IsDynamicTensor(outputInfo))
3378 {
3379 validateFunc(outputInfo, isSupported);
3380 }
3381 else
3382 {
3383 isSupported = AreDynamicTensorsSupported();
3384 }
3385
Mike Kelly46272802019-08-14 17:00:48 +01003386 if (!isSupported)
3387 {
3388 return false;
3389 }
3390
3391 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
3392 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3393
3394 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3395 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3396
3397 if (endLayer != nullptr)
3398 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003399 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003400 if (!isReshapeSupported)
3401 {
3402 return false;
3403 }
3404
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003405 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003406 }
3407 else
3408 {
3409 return Fail("%s: ProcessActivation failed", __func__);
3410 }
3411}
3412
3413template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003414 typename HalOperation = typename HalPolicy::Operation,
3415 typename HalModel = typename HalPolicy::Model>
3416bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003417{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003418 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003419
Mike Kelly3c673942019-07-25 09:26:06 +01003420 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3421 if (!input.IsValid())
3422 {
3423 return Fail("%s: Operation has invalid inputs", __func__);
3424 }
3425
3426 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3427 unsigned int rank = inputInfo.GetNumDimensions();
3428
3429 armnn::PadDescriptor descriptor;
3430 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3431 {
3432 return Fail("%s: Could not convert paddings", __func__);
3433 }
3434
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003435 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3436 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003437 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3438 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3439 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003440 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003441 {
3442 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3443 }
3444
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003445 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003446 if (!output)
3447 {
3448 return Fail("%s: Could not read output", __func__);
3449 }
3450
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003451 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003452
3453 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003454 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3455 {
3456 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3457 IsPadSupported,
3458 data.m_Backends,
3459 isSupported,
3460 inputInfo,
3461 outputInfo,
3462 descriptor);
3463 };
3464
3465 if(!IsDynamicTensor(outputInfo))
3466 {
3467 validateFunc(outputInfo, isSupported);
3468 }
3469 else
3470 {
3471 isSupported = AreDynamicTensorsSupported();
3472 }
3473
Mike Kelly3c673942019-07-25 09:26:06 +01003474 if (!isSupported)
3475 {
3476 return false;
3477 }
3478
3479 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3480 assert(layer != nullptr);
3481 input.Connect(layer->GetInputSlot(0));
Mike Kelly3c673942019-07-25 09:26:06 +01003482
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003483 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly3c673942019-07-25 09:26:06 +01003484}
3485
Mike Kelly0a879362019-07-29 16:56:31 +01003486template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003487 typename HalOperation = typename HalPolicy::Operation,
3488 typename HalModel = typename HalPolicy::Model>
3489bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003490{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003491 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003492
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003493 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3494 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3495 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003496
3497 if (inputOperand == nullptr
3498 || requestedShapeOperand == nullptr
3499 || outputOperand == nullptr)
3500 {
3501 return Fail("%s: Operation has invalid inputs", __func__);
3502 }
3503
3504 if (requestedShapeOperand->dimensions.size() != 1)
3505 {
3506 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3507 __func__, requestedShapeOperand->dimensions.size());
3508 }
3509
3510 std::vector<int32_t> targetDimensions;
3511 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3512 {
3513 return Fail("%s: Could not read values of input 1", __func__);
3514 }
3515
3516 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3517
3518 Shape requestedShape;
3519 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3520 // function that resolves these values into a fully specified tensor shape.
3521 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3522 {
3523 return Fail("%s: Failed to resolve the requested shape", __func__);
3524 }
3525
Mike Kelly46272802019-08-14 17:00:48 +01003526 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3527 if (!input.IsValid())
3528 {
3529 return Fail("%s: Could not read input 0", __func__);
3530 }
3531
3532 armnn::ReshapeDescriptor reshapeDescriptor;
3533 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3534 requestedShape.dimensions.data());
3535
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003536 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3537
Mike Kelly46272802019-08-14 17:00:48 +01003538 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003539 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3540 {
3541 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3542 IsReshapeSupported,
3543 data.m_Backends,
3544 isSupported,
3545 input.GetTensorInfo(),
3546 outputInfo,
3547 reshapeDescriptor);
3548 };
3549
3550 if(!IsDynamicTensor(outputInfo))
3551 {
3552 validateFunc(outputInfo, isSupported);
3553 }
3554 else
3555 {
3556 isSupported = AreDynamicTensorsSupported();
3557 }
3558
Mike Kelly46272802019-08-14 17:00:48 +01003559 if (!isSupported)
3560 {
3561 return false;
3562 }
3563
3564 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3565 assert(layer != nullptr);
3566 input.Connect(layer->GetInputSlot(0));
3567
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003568 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003569}
3570
3571template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003572 typename HalOperation = typename HalPolicy::Operation,
3573 typename HalModel = typename HalPolicy::Model>
3574bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003575{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003576 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003577
Mike Kelly0a879362019-07-29 16:56:31 +01003578 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3579 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3580
3581 if (!input0.IsValid() || !input1.IsValid())
3582 {
3583 return Fail("%s: Operation has invalid inputs", __func__);
3584 }
3585
3586 // The FuseActivation parameter is always the input index 2
3587 // and it should be optional
3588 ActivationFn activationFunction;
3589 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3590 {
3591 return Fail("%s: Operation has invalid inputs", __func__);
3592 }
3593
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003594 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003595 if (!output)
3596 {
3597 return Fail("%s: Could not read output 0", __func__);
3598 }
3599
3600 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly0a879362019-07-29 16:56:31 +01003601
3602 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003603 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3604 {
3605 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3606 IsSubtractionSupported,
3607 data.m_Backends,
3608 isSupported,
3609 input0.GetTensorInfo(),
3610 input1.GetTensorInfo(),
3611 outputInfo);
3612 };
3613
3614 if(IsDynamicTensor(outputInfo))
3615 {
3616 isSupported = AreDynamicTensorsSupported();
3617 }
3618 else
3619 {
3620 validateFunc(outputInfo, isSupported);
3621 }
3622
Mike Kelly0a879362019-07-29 16:56:31 +01003623 if (!isSupported)
3624 {
3625 return false;
3626 }
3627
3628 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
3629 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3630
3631 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3632 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3633
3634 if (endLayer)
3635 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003636 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003637 if (!isReshapeSupported)
3638 {
3639 return false;
3640 }
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003641 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kelly0a879362019-07-29 16:56:31 +01003642 }
3643
3644 return Fail("%s: ProcessActivation failed", __func__);
3645}
3646
Finn Williams23b87b32019-07-30 11:44:05 +01003647template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003648 typename HalOperation = typename HalPolicy::Operation,
3649 typename HalModel = typename HalPolicy::Model>
3650bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003651{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003652 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003653
3654 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3655 if (!input.IsValid())
3656 {
3657 return Fail("%s: Operation has invalid inputs", __func__);
3658 }
3659
3660 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3661 unsigned int rank = inputInfo.GetNumDimensions();
3662 if (rank > 4)
3663 {
3664 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3665 }
3666
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003667 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003668 if (!output)
3669 {
3670 return Fail("%s: Could not read output 0", __func__);
3671 }
Sadik Armagan346e8112020-09-02 09:55:14 +01003672
3673 if (IsDynamicTensor(GetTensorInfoForOperand(*output)) && !(AreDynamicTensorsSupported()))
Mike Kelly46272802019-08-14 17:00:48 +01003674 {
3675 return Fail("%s: Dynamic output tensors are not supported", __func__);
3676 }
3677
3678 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3679 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003680 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003681
3682 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3683
3684 std::vector<int32_t> axis;
3685 if (!axisOperand)
3686 {
3687 axis.assign(dimensionSequence,
3688 dimensionSequence + rank);
3689 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003690 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003691 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003692 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003693 }
3694
3695 std::vector<uint32_t> outputDims;
3696 for (unsigned int i = 0; i < rank; i++)
3697 {
3698 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3699 auto currentDimension = inputInfo.GetShape()[i];
3700 if (skipSqueeze || currentDimension != 1)
3701 {
3702 outputDims.push_back(currentDimension);
3703 }
3704 }
3705
3706 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3707
3708 armnn::TensorInfo outputInfo = inputInfo;
3709 outputInfo.SetShape(outShape);
3710
3711 armnn::ReshapeDescriptor reshapeDesc;
3712 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3713
3714 bool isSupported = false;
3715 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3716 IsReshapeSupported,
3717 data.m_Backends,
3718 isSupported,
3719 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003720 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003721 reshapeDesc);
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003722
Mike Kelly46272802019-08-14 17:00:48 +01003723 if (!isSupported)
3724 {
3725 return false;
3726 }
3727
3728 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3729 assert(layer != nullptr);
3730 input.Connect(layer->GetInputSlot(0));
3731
3732 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3733}
3734
3735template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003736 typename HalOperation = typename HalPolicy::Operation,
3737 typename HalModel = typename HalPolicy::Model>
3738bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003739{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003740 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003741
3742 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3743 if (!input.IsValid())
3744 {
3745 return Fail("%s: Operation has invalid inputs", __func__);
3746 }
3747
3748 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3749 unsigned int rank = inputInfo.GetNumDimensions();
3750 if (rank > 4)
3751 {
3752 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3753 }
3754
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003755 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003756 if (!output)
3757 {
3758 return Fail("%s: Could not read output 0", __func__);
3759 }
3760
3761 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly46272802019-08-14 17:00:48 +01003762
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003763 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3764 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3765 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003766
3767 std::vector<int32_t> beginValues;
3768 std::vector<int32_t> endValues;
3769 std::vector<int32_t> stridesValues;
3770
3771 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003772 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003773 {
3774 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3775 {
3776 return false;
3777 }
3778
3779 if (operandValues.size() != rank)
3780 {
3781 return false;
3782 }
3783
3784 return true;
3785 };
3786
3787 if (!ValidateInputOperands(*beginOperand, beginValues)
3788 || !ValidateInputOperands(*endOperand, endValues)
3789 || !ValidateInputOperands(*stridesOperand, stridesValues))
3790 {
3791 return Fail("%s: Operation has invalid input operand", __func__);
3792 }
3793
3794 // Stride cannot have value '0'
3795 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3796 {
3797 return Fail("%s: Stride must be non-zero value.", __func__);
3798 }
3799
3800 armnn::StridedSliceDescriptor descriptor;
3801 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3802 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3803 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3804 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3805
3806 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3807 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3808 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3809 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3810 {
3811 return Fail("%s: Operation has invalid inputs", __func__);
3812 }
3813
3814 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003815 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3816 {
3817 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3818 IsStridedSliceSupported,
3819 data.m_Backends,
3820 isSupported,
3821 inputInfo,
3822 outputInfo,
3823 descriptor);
3824 };
3825
3826 if(IsDynamicTensor(outputInfo))
3827 {
3828 isSupported = AreDynamicTensorsSupported();
3829 }
3830 else
3831 {
3832 validateFunc(outputInfo, isSupported);
3833 }
3834
Mike Kelly46272802019-08-14 17:00:48 +01003835 if (!isSupported)
3836 {
3837 return false;
3838 }
3839
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003840 // Check if slice can fit in a inferred output
3841 armnn::TensorShape inputShape = inputInfo.GetShape();
3842 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3843 {
3844 int stride = descriptor.m_Stride[i];
3845 int start = descriptor.GetStartForAxis(inputShape, i);
3846 int stop = descriptor.GetStopForAxis(inputShape, i, start);
3847
3848 if (descriptor.m_ShrinkAxisMask & (1 << i))
3849 {
3850 // If the difference between the start point and the end point of the slice on an axis being shrunk
3851 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3852 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3853 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3854 {
3855 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3856 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003857
3858 if(stride < 0)
3859 {
3860 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3861 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003862 }
3863 }
3864
Mike Kelly46272802019-08-14 17:00:48 +01003865 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3866 assert(layer != nullptr);
3867 input.Connect(layer->GetInputSlot(0));
3868
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003869 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003870}
3871
3872template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003873 typename HalOperation = typename HalPolicy::Operation,
3874 typename HalModel = typename HalPolicy::Model>
3875bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003876{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003877 using HalOperand = typename HalPolicy::Operand;
Kevin May81f27fd2020-08-20 10:22:53 +01003878 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
Mike Kelly46272802019-08-14 17:00:48 +01003879
3880 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3881 if (!input.IsValid())
3882 {
3883 return Fail("%s: Operation has invalid inputs", __func__);
3884 }
3885
3886 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3887 unsigned int rank = inputInfo.GetNumDimensions();
3888 if (rank > 4)
3889 {
3890 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3891 }
3892
3893 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3894 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003895 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003896
3897 std::vector<int32_t> perm(rank);
Kevin May81f27fd2020-08-20 10:22:53 +01003898 if (!permOperand || (permOperand->lifetime == HalOperandLifeTime::NO_VALUE))
Mike Kelly46272802019-08-14 17:00:48 +01003899 {
Mike Kelly46272802019-08-14 17:00:48 +01003900 for (unsigned int i = rank; i > 0; i--)
3901 {
3902 perm[rank - i] = boost::numeric_cast<int> (i - 1);
3903 }
3904 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003905 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003906 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003907 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003908 }
3909
3910 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3911
Mike Kelly4a956582020-02-28 10:32:09 +00003912 armnn::TransposeDescriptor transposeDesc;
3913 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003914
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003915 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003916 if (!output)
3917 {
3918 return Fail("%s: Could not read output 0", __func__);
3919 }
3920
3921 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3922
3923 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003924 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
3925 {
3926 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3927 IsTransposeSupported,
3928 data.m_Backends,
3929 isSupported,
3930 inputInfo,
3931 outputInfo,
3932 transposeDesc);
3933 };
3934
3935 if(IsDynamicTensor(outputInfo))
3936 {
3937 isSupported = AreDynamicTensorsSupported();
3938 }
3939 else
3940 {
3941 validateFunc(outputInfo, isSupported);
3942 }
3943
Mike Kelly46272802019-08-14 17:00:48 +01003944 if (!isSupported)
3945 {
3946 return false;
3947 }
3948
Mike Kelly4a956582020-02-28 10:32:09 +00003949 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003950 assert(layer != nullptr);
3951 input.Connect(layer->GetInputSlot(0));
3952
Teresa Charlin4bd9a742020-08-12 12:58:50 +01003953 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Mike Kelly46272802019-08-14 17:00:48 +01003954}
3955
3956template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003957 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003958 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003959 typename HalModel = typename HalPolicy::Model>
3960bool ConvertBatchToSpaceNd(const HalOperation& operation,
3961 const HalModel& model,
3962 ConversionData& data)
3963{
Finn Williams23b87b32019-07-30 11:44:05 +01003964
3965 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3966 if (!input.IsValid())
3967 {
3968 return Fail("%s: Operation has invalid inputs", __func__);
3969 }
3970
3971 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3972 if (!output)
3973 {
3974 return Fail("%s: Could not read output 0", __func__);
3975 }
3976
3977 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williams23b87b32019-07-30 11:44:05 +01003978
3979 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3980 if (!blockOperand)
3981 {
3982 return Fail("%s: Could not read input 1", __func__);
3983 }
3984
3985 // Convert the block operand to int32
3986 std::vector<int32_t> block;
3987 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
3988 {
3989 return Fail("%s: Input 1 has invalid values", __func__);
3990 }
3991
3992 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3993
3994 unsigned int rank = inputInfo.GetNumDimensions();
3995 if (rank != 4)
3996 {
3997 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
3998 }
3999
4000 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
4001 {
4002 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
4003 " greater than or equal to 1", __func__);
4004 }
4005
4006 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
4007 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
4008 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
4009
Kevin May42477c12020-03-26 13:34:14 +00004010 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01004011 {
Finn Williams0e4e4392019-07-31 10:56:27 +01004012 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01004013 }
4014 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
4015 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
4016
4017 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004018 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4019 {
4020 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4021 IsBatchToSpaceNdSupported,
4022 data.m_Backends,
4023 isSupported,
4024 inputInfo,
4025 outputInfo,
4026 batchToSpaceNdDesc);
4027 };
4028
4029 if(!IsDynamicTensor(outputInfo))
4030 {
4031 validateFunc(outputInfo, isSupported);
4032 }
4033 else
4034 {
4035 isSupported = AreDynamicTensorsSupported();
4036 }
4037
4038
Finn Williams23b87b32019-07-30 11:44:05 +01004039 if (!isSupported)
4040 {
4041 return false;
4042 }
4043
4044 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
4045 assert(layer != nullptr);
4046 input.Connect(layer->GetInputSlot(0));
4047
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004048 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williams23b87b32019-07-30 11:44:05 +01004049}
Mike Kelly0a879362019-07-29 16:56:31 +01004050
Finn Williamsd74c5052019-07-30 17:06:00 +01004051template<typename HalPolicy,
4052 typename HalOperation = typename HalPolicy::Operation,
4053 typename HalOperand = typename HalPolicy::Operand,
4054 typename HalModel = typename HalPolicy::Model>
4055bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
4056{
4057 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
4058 if (!input.IsValid())
4059 {
4060 return Fail("%s: Operation has invalid inputs", __func__);
4061 }
4062
4063 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
4064 unsigned int rank = inputInfo.GetNumDimensions();
4065 unsigned int spatialDim = rank - 2;
4066
4067 if (rank != 4)
4068 {
4069 Fail("%s: Only inputs with rank 4 are supported", __func__);
4070 }
4071
4072 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
4073 if (!output)
4074 {
4075 return Fail("%s: Could not read output 0", __func__);
4076 }
4077
4078 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Finn Williamsd74c5052019-07-30 17:06:00 +01004079
4080 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
4081 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
4082
4083 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
4084 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
4085 {
4086 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
4087 }
4088
4089 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00004090 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
4091 {
4092 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
4093 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004094 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
4095 {
4096 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
4097 }
4098
4099 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
4100 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
4101 {
4102 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
4103 }
4104
4105 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
4106 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00004107 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
4108 {
4109 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
4110 }
Finn Williamsd74c5052019-07-30 17:06:00 +01004111 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
4112 {
4113 int paddingBeforeInput = paddings[i];
4114 int paddingAfterInput = paddings[i + 1];
4115 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
4116 {
4117 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
4118 }
4119
4120 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
4121 }
4122
4123 armnn::SpaceToBatchNdDescriptor descriptor;
4124 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
4125 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
4126 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
4127
Kevin May42477c12020-03-26 13:34:14 +00004128 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01004129 {
4130 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
4131 }
4132
4133 bool isSupported = false;
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004134 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
4135 {
4136 FORWARD_LAYER_SUPPORT_FUNC(__func__,
4137 IsSpaceToBatchNdSupported,
4138 data.m_Backends,
4139 isSupported,
4140 inputInfo,
4141 outputInfo,
4142 descriptor);
4143 };
4144
4145 if(IsDynamicTensor(outputInfo))
4146 {
4147 isSupported = AreDynamicTensorsSupported();
4148 }
4149 else
4150 {
4151 validateFunc(outputInfo, isSupported);
4152 }
4153
Finn Williamsd74c5052019-07-30 17:06:00 +01004154 if (!isSupported)
4155 {
4156 return false;
4157 }
4158
4159 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
4160 assert(layer != nullptr);
4161 input.Connect(layer->GetInputSlot(0));
4162
Teresa Charlin4bd9a742020-08-12 12:58:50 +01004163 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Finn Williamsd74c5052019-07-30 17:06:00 +01004164}
4165
saoste01b8471482018-10-10 09:44:51 +01004166} // namespace armnn_driver