blob: 474d1a58e1801dfee58b58423cdc2a01cbf9ce5a [file] [log] [blame]
arovir01b0717b52018-09-05 17:03:25 +01001//
2// Copyright © 2017 Arm Ltd. All rights reserved.
3// 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)
arovir01b0717b52018-09-05 17:03:25 +010047 {}
48
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +010049 const std::vector<armnn::BackendId> m_Backends;
arovir01b0717b52018-09-05 17:03:25 +010050 armnn::INetworkPtr m_Network;
51 std::vector<armnn::IOutputSlot*> m_OutputSlotForOperand;
52 std::vector<android::nn::RunTimePoolInfo> m_MemPools;
53};
54
55class LayerInputHandle
56{
57public:
58 LayerInputHandle();
59 LayerInputHandle(bool valid, armnn::IOutputSlot* outputSlot, armnn::TensorInfo tensorInfo);
60
61 bool IsValid() const;
62
63 void Connect(armnn::IInputSlot& inputSlot);
64
Finn Williamsa4983ce2020-07-23 12:55:12 +010065 void Disconnect(armnn::IInputSlot& inputSlot);
66
arovir01b0717b52018-09-05 17:03:25 +010067 const armnn::TensorInfo& GetTensorInfo() const;
68
69private:
70 armnn::IOutputSlot* m_OutputSlot;
71 bool m_Valid;
72 armnn::TensorInfo m_TensorInfo;
73};
74
75class ConstTensorPin
76{
77public:
78 // Creates an invalid tensor pin (can be used to signal errors)
79 // The optional flag can be set to indicate the tensor values were missing, but it was otherwise valid
80 ConstTensorPin(bool optional = false);
81
82 // @param tensorInfo TensorInfo associated with the tensor.
83 // @param valueStart Start address of tensor data. Belongs to one of the memory pools associated with
84 // the model being converted.
85 // @param numBytes Number of bytes for the tensor data.
86 ConstTensorPin(const armnn::TensorInfo& tensorInfo, const void* valueStart, uint32_t numBytes,
87 const armnn::PermutationVector& mappings);
88
89 ConstTensorPin(const ConstTensorPin& other) = delete;
90 ConstTensorPin(ConstTensorPin&& other) = default;
91
92 bool IsValid() const;
93 bool IsOptional() const;
94
95 const armnn::ConstTensor& GetConstTensor() const;
96 const armnn::ConstTensor* GetConstTensorPtr() const;
97
98private:
99 armnn::ConstTensor m_ConstTensor;
100
101 // Owned memory for swizzled tensor data, only required if the tensor needed
102 // swizzling. Otherwise, @ref m_ConstTensor will reference memory from one of
103 // the pools associated with the model being converted.
104 std::vector<uint8_t> m_SwizzledTensorData;
105
106 // optional flag to indicate that an invalid tensor pin is not an error, but the optional values were not given
107 bool m_Optional;
108};
109
110} // namespace armnn_driver
111
112///
113/// Utility functions
114///
115
116namespace
117{
118
119using namespace armnn_driver;
120using namespace android::nn;
121
122// Convenience function to log the reason for failing to convert a model.
123// @return Always returns false (so that it can be used by callers as a quick way to signal an error and return)
124template<class... Args>
125static bool Fail(const char* formatStr, Args&&... args)
126{
127 ALOGD(formatStr, std::forward<Args>(args)...);
128 return false;
129}
130
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100131// Convenience macro to call an Is*Supported function and log caller name together with reason for lack of support.
132// Called as: FORWARD_LAYER_SUPPORT_FUNC(__func__, Is*Supported, backends, a, b, c, d, e)
133#define FORWARD_LAYER_SUPPORT_FUNC(funcName, func, backends, supported, ...) \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100134try \
135{ \
136 for (auto&& backendId : backends) \
137 { \
138 auto layerSupportObject = armnn::GetILayerSupportByBackendId(backendId); \
139 if (layerSupportObject) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100140 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100141 std::string reasonIfUnsupported; \
142 supported = \
143 layerSupportObject->func(__VA_ARGS__, armnn::Optional<std::string&>(reasonIfUnsupported)); \
144 if (supported) \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100145 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100146 break; \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100147 } \
148 else \
149 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100150 if (reasonIfUnsupported.size() > 0) \
151 { \
152 ALOGD("%s: not supported by armnn: %s", funcName, reasonIfUnsupported.c_str()); \
153 } \
154 else \
155 { \
156 ALOGD("%s: not supported by armnn", funcName); \
157 } \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100158 } \
159 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100160 else \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100161 { \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100162 ALOGD("%s: backend not registered: %s", funcName, backendId.Get().c_str()); \
Ferran Balaguerd30093c2019-07-09 17:04:47 +0100163 } \
Teresa Charlin8f6429d2019-10-01 13:10:15 +0100164 } \
165 if (!supported) \
166 { \
167 ALOGD("%s: not supported by any specified backend", funcName); \
168 } \
169} \
170catch (const armnn::InvalidArgumentException &e) \
171{ \
172 throw armnn::InvalidArgumentException(e, "Failed to check layer support", CHECK_LOCATION()); \
173}
Nattapat Chaimanowongd5fd9762019-04-04 13:33:10 +0100174
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000175template<typename HalOperand>
176armnn::TensorShape GetTensorShapeForOperand(const HalOperand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100177{
178 return armnn::TensorShape(operand.dimensions.size(), operand.dimensions.data());
179}
180
Matthew Bentham912b3622019-05-03 15:49:14 +0100181inline bool IsOperandTypeSupportedForTensors(V1_0::OperandType type)
arovir01b0717b52018-09-05 17:03:25 +0100182{
Matthew Bentham912b3622019-05-03 15:49:14 +0100183 return type == V1_0::OperandType::TENSOR_FLOAT32 ||
184 type == V1_0::OperandType::TENSOR_QUANT8_ASYMM ||
185 type == V1_0::OperandType::TENSOR_INT32;
arovir01b0717b52018-09-05 17:03:25 +0100186}
187
Kevin May42477c12020-03-26 13:34:14 +0000188#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100189
Keith Davis71006492020-01-06 17:44:16 +0000190// Support within the 1.2 driver for specific tensor data types
Mike Kellyb5fdf382019-06-11 16:35:25 +0100191inline bool IsOperandTypeSupportedForTensors(V1_2::OperandType type)
192{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000193 return type == V1_2::OperandType::BOOL ||
Sadik Armagan793a70c2020-03-19 13:54:04 +0000194 type == V1_2::OperandType::TENSOR_BOOL8 ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000195 type == V1_2::OperandType::TENSOR_FLOAT16 ||
196 type == V1_2::OperandType::TENSOR_FLOAT32 ||
197 type == V1_2::OperandType::TENSOR_QUANT8_ASYMM ||
Keith Davis71006492020-01-06 17:44:16 +0000198 type == V1_2::OperandType::TENSOR_QUANT8_SYMM ||
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000199 type == V1_2::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
200 type == V1_2::OperandType::TENSOR_QUANT16_SYMM ||
Mike Kellyb5fdf382019-06-11 16:35:25 +0100201 type == V1_2::OperandType::TENSOR_INT32;
202}
203
204#endif
205
Kevin May42477c12020-03-26 13:34:14 +0000206#ifdef ARMNN_ANDROID_NN_V1_3
207
208// Support within the 1.3 driver for specific tensor data types
209inline bool IsOperandTypeSupportedForTensors(V1_3::OperandType type)
210{
211 return type == V1_3::OperandType::BOOL ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100212 type == V1_3::OperandType::TENSOR_BOOL8 ||
Kevin May42477c12020-03-26 13:34:14 +0000213 type == V1_3::OperandType::TENSOR_FLOAT16 ||
214 type == V1_3::OperandType::TENSOR_FLOAT32 ||
215 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM ||
Sadik Armagan51ba2c62020-03-31 15:36:25 +0100216 type == V1_3::OperandType::TENSOR_QUANT8_ASYMM_SIGNED ||
Kevin May42477c12020-03-26 13:34:14 +0000217 type == V1_3::OperandType::TENSOR_QUANT8_SYMM ||
218 type == V1_3::OperandType::TENSOR_QUANT8_SYMM_PER_CHANNEL ||
219 type == V1_3::OperandType::TENSOR_QUANT16_SYMM ||
220 type == V1_3::OperandType::TENSOR_INT32;
221}
222
223#endif
224
Mike Kellyb5fdf382019-06-11 16:35:25 +0100225inline bool IsBool(V1_0::Operand)
226{
227 return false;
228}
229
Kevin May42477c12020-03-26 13:34:14 +0000230inline bool Is12OrLaterOperand(V1_0::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100231{
232 return false;
233}
234
Kevin May42477c12020-03-26 13:34:14 +0000235#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kellyb5fdf382019-06-11 16:35:25 +0100236
237inline bool IsBool(V1_2::Operand operand)
238{
239 return operand.type == V1_2::OperandType::BOOL;
240}
241
Sadik Armagan61113162019-07-25 09:09:40 +0100242/// Checks if a operand is 1_2 Operand
Kevin May42477c12020-03-26 13:34:14 +0000243inline bool Is12OrLaterOperand(V1_2::Operand)
244{
245 return true;
246}
247
248#endif
249
250#ifdef ARMNN_ANDROID_NN_V1_3
251
252inline bool IsBool(V1_3::Operand operand)
253{
254 return operand.type == V1_3::OperandType::BOOL;
255}
256
257/// Checks if a operand is 1_2 Operand
258inline bool Is12OrLaterOperand(V1_3::Operand)
Sadik Armagan61113162019-07-25 09:09:40 +0100259{
260 return true;
261}
262
Mike Kellyb5fdf382019-06-11 16:35:25 +0100263#endif
264
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100265template<typename LayerHandleType>
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000266armnn::IConnectableLayer& AddReshapeLayer(armnn::INetwork& network,
267 LayerHandleType& inputLayer,
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100268 armnn::TensorInfo reshapeInfo)
269{
270 armnn::ReshapeDescriptor reshapeDescriptor;
271 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
272
273 armnn::IConnectableLayer* reshapeLayer = network.AddReshapeLayer(reshapeDescriptor);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100274 ARMNN_ASSERT(reshapeLayer != nullptr);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100275
276 // Attach the input layer to the reshape layer
277 inputLayer.Connect(reshapeLayer->GetInputSlot(0));
278 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapeInfo);
279
280 return *reshapeLayer;
281}
282
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000283bool BroadcastTensor(LayerInputHandle& input0,
284 LayerInputHandle& input1,
285 armnn::IConnectableLayer* startLayer,
286 ConversionData& data)
arovir01b0717b52018-09-05 17:03:25 +0100287{
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100288 ARMNN_ASSERT(startLayer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100289
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100290 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
291 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
292
293 unsigned int inputDimensions0 = inputInfo0.GetNumDimensions();
294 unsigned int inputDimensions1 = inputInfo1.GetNumDimensions();
295
296 if (inputDimensions0 == inputDimensions1)
arovir01b0717b52018-09-05 17:03:25 +0100297 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100298 // The inputs have the same number of dimensions, simply connect them to the given layer as they are
299 input0.Connect(startLayer->GetInputSlot(0));
300 input1.Connect(startLayer->GetInputSlot(1));
301
Sadik Armagan64b19b52019-08-19 09:49:58 +0100302 return true;
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100303 }
304
305 // Since the number of dimensions do not match then we need to add degenerate dimensions
306 // to the "smaller" tensor using a reshape, while keeping the order of the inputs.
307
308 unsigned int maxInputDimensions = std::max(inputDimensions0, inputDimensions1);
309 unsigned int sizeDifference = std::abs(boost::numeric_cast<int>(inputDimensions0) -
310 boost::numeric_cast<int>(inputDimensions1));
311
312 bool input0IsSmaller = inputDimensions0 < inputDimensions1;
313 LayerInputHandle& smallInputHandle = input0IsSmaller ? input0 : input1;
314 const armnn::TensorInfo& smallInfo = smallInputHandle.GetTensorInfo();
315
316 const armnn::TensorShape& smallShape = smallInfo.GetShape();
317 std::vector<unsigned int> reshapedDimensions(maxInputDimensions, 1);
318 for (unsigned int i = sizeDifference; i < maxInputDimensions; i++)
319 {
320 reshapedDimensions[i] = smallShape[i - sizeDifference];
321 }
322
323 armnn::TensorInfo reshapedInfo = smallInfo;
324 reshapedInfo.SetShape(armnn::TensorShape{ boost::numeric_cast<unsigned int>(reshapedDimensions.size()),
325 reshapedDimensions.data() });
Sadik Armagan64b19b52019-08-19 09:49:58 +0100326
327 // RehsapeDescriptor that is ignored in the IsReshapeSupported function
328 armnn::ReshapeDescriptor reshapeDescriptor;
329
330 bool isSupported = false;
331 FORWARD_LAYER_SUPPORT_FUNC(__func__,
332 IsReshapeSupported,
333 data.m_Backends,
334 isSupported,
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +0000335 smallInfo,
Sadik Armagan64b19b52019-08-19 09:49:58 +0100336 reshapedInfo,
337 reshapeDescriptor);
338 if (!isSupported)
339 {
340 return false;
341 }
342
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100343 ARMNN_ASSERT(data.m_Network != nullptr);
Sadik Armagan64b19b52019-08-19 09:49:58 +0100344 armnn::IConnectableLayer& reshapeLayer = AddReshapeLayer(*data.m_Network, smallInputHandle, reshapedInfo);
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100345
346 if (input0IsSmaller)
347 {
348 // Input0 is the "smaller" tensor, connect the reshape layer as follows:
349 //
350 // Input0 Input1
arovir01b0717b52018-09-05 17:03:25 +0100351 // | |
352 // Reshape |
353 // \ /
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100354 // StartLayer
arovir01b0717b52018-09-05 17:03:25 +0100355
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100356 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
357 input1.Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100358 }
359 else
360 {
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100361 // Input1 is the "smaller" tensor, connect the reshape layer as follows:
362 //
363 // Input0 Input1
364 // | |
365 // | Reshape
366 // \ /
367 // StartLayer
368
arovir01b0717b52018-09-05 17:03:25 +0100369 input0.Connect(startLayer->GetInputSlot(0));
Matteo Martincigh0bd89a82019-07-02 16:53:10 +0100370 reshapeLayer.GetOutputSlot(0).Connect(startLayer->GetInputSlot(1));
arovir01b0717b52018-09-05 17:03:25 +0100371 }
Sadik Armagan64b19b52019-08-19 09:49:58 +0100372
373 return true;
arovir01b0717b52018-09-05 17:03:25 +0100374}
375
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +0000376void CalcPadding(uint32_t input,
377 uint32_t kernel,
378 uint32_t stride,
379 uint32_t& outPadHead,
380 uint32_t& outPadTail,
arovir01b0717b52018-09-05 17:03:25 +0100381 android::nn::PaddingScheme scheme)
382{
383 int32_t padHead;
384 int32_t padTail;
385 calculateExplicitPadding(input, stride, kernel, scheme, &padHead, &padTail);
386 outPadHead = boost::numeric_cast<uint32_t>(padHead);
387 outPadTail = boost::numeric_cast<uint32_t>(padTail);
388}
389
Kevin May42477c12020-03-26 13:34:14 +0000390#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly86b36d42019-07-12 16:39:33 +0100391
392void CalcPadding(uint32_t input, uint32_t kernel, uint32_t stride, uint32_t dilation, uint32_t& outPadHead,
393 uint32_t& outPadTail, android::nn::PaddingScheme scheme)
394{
395 int32_t padHead;
396 int32_t padTail;
397 calculateExplicitPadding(input, stride, dilation, kernel, scheme, &padHead, &padTail);
398 outPadHead = boost::numeric_cast<uint32_t>(padHead);
399 outPadTail = boost::numeric_cast<uint32_t>(padTail);
400}
401
Mike Kelly26123db2020-01-15 10:02:33 +0000402void CalcPaddingTransposeConv(uint32_t output, uint32_t kernel, int32_t stride, int32_t& outPadHead,
Narumol Prangnawaratc8bdb392019-08-01 15:51:44 +0100403 int32_t& outPadTail, android::nn::PaddingScheme scheme)
404{
405 calculateExplicitPaddingTransposeConv(output, stride, kernel, scheme, &outPadHead, &outPadTail);
406}
407
Mike Kelly86b36d42019-07-12 16:39:33 +0100408#endif
409
Matthew Bentham912b3622019-05-03 15:49:14 +0100410Shape GetOperandShape(const V1_0::Operand& operand)
arovir01b0717b52018-09-05 17:03:25 +0100411{
412 Shape shape;
Matthew Bentham912b3622019-05-03 15:49:14 +0100413 shape.type = OperandType(operand.type);
arovir01b0717b52018-09-05 17:03:25 +0100414 shape.dimensions = operand.dimensions;
415 shape.scale = operand.scale;
416 shape.offset = operand.zeroPoint;
417 return shape;
418}
419
Kevin May42477c12020-03-26 13:34:14 +0000420#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Mike Kelly46272802019-08-14 17:00:48 +0100421
422Shape GetOperandShape(const V1_2::Operand& operand)
423{
424 Shape shape;
425 shape.type = OperandType(operand.type);
426 shape.dimensions = operand.dimensions;
427 shape.scale = operand.scale;
428 shape.offset = operand.zeroPoint;
429 return shape;
430}
431
432#endif
433
Kevin May42477c12020-03-26 13:34:14 +0000434#ifdef ARMNN_ANDROID_NN_V1_3
435
436Shape GetOperandShape(const V1_3::Operand& operand)
437{
438 Shape shape;
439 shape.type = OperandType(operand.type);
440 shape.dimensions = operand.dimensions;
441 shape.scale = operand.scale;
442 shape.offset = operand.zeroPoint;
443 return shape;
444}
445
446#endif
447
arovir01b0717b52018-09-05 17:03:25 +0100448// ArmNN requires the bias scale to be equal to the product of the weight and input scales, which is also
449// 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 +0100450// we accept some tolerance. We don't want ArmNN itself to accept these inconsistencies as it is up to the
451// user (us, in this case) to ensure they match.
arovir01b0717b52018-09-05 17:03:25 +0100452void SanitizeBiasQuantizationScale(armnn::TensorInfo& biasInfo,
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000453 const armnn::TensorInfo& weightInfo,
454 const armnn::TensorInfo& inputInfo)
arovir01b0717b52018-09-05 17:03:25 +0100455{
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000456 if (weightInfo.HasPerAxisQuantization())
arovir01b0717b52018-09-05 17:03:25 +0100457 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000458 // NOTE: Bias scale is always set to 0 for per-axis quantization and
459 // it needs to be calculated: scale[i] = input_scale * weight_scale[i]
460 auto UpdateBiasScaleValue = [&inputInfo](float biasScale) -> float
arovir01b0717b52018-09-05 17:03:25 +0100461 {
Aron Virginas-Tar9f0693b2019-11-06 14:32:30 +0000462 return biasScale * inputInfo.GetQuantizationScale();
463 };
464
465 std::vector<float> biasScales(weightInfo.GetQuantizationScales());
466 std::transform(biasScales.begin(), biasScales.end(), biasScales.begin(), UpdateBiasScaleValue);
467
468 biasInfo.SetQuantizationScales(biasScales);
469 biasInfo.SetQuantizationDim(weightInfo.GetQuantizationDim());
470
471 ALOGV("Bias quantization params have been updated for per-axis quantization");
472 }
473 else
474 {
475 const float expectedBiasScale = weightInfo.GetQuantizationScale() * inputInfo.GetQuantizationScale();
476 if (biasInfo.GetQuantizationScale() != expectedBiasScale)
477 {
478 boost::math::fpc::close_at_tolerance<float> comparer(boost::math::fpc::percent_tolerance(1.0f));
479 if (comparer(biasInfo.GetQuantizationScale(), expectedBiasScale))
480 {
481 ALOGW("Bias quantization scale has been modified to match input * weights");
482 biasInfo.SetQuantizationScale(expectedBiasScale);
483 }
arovir01b0717b52018-09-05 17:03:25 +0100484 }
485 }
486}
487
488// 4D Tensor Permutations
489const armnn::PermutationVector IdentityPermutation4D({ 0U, 1U, 2U, 3U });
arovir01b0717b52018-09-05 17:03:25 +0100490const armnn::PermutationVector SwapDim1And2({ 0U, 2U, 1U, 3U });
491
492// 3D Permutation Vectors
Mike Kelly4a956582020-02-28 10:32:09 +0000493const armnn::PermutationVector RotateTensorLeft({ 1U, 2U, 0U });
494const armnn::PermutationVector RotateTensorRight({ 2U, 0U, 1U });
arovir01b0717b52018-09-05 17:03:25 +0100495
496template<typename OSlot>
Mike Kelly4a956582020-02-28 10:32:09 +0000497armnn::IConnectableLayer& AddTransposeLayer(armnn::INetwork& network, OSlot& input,
498 const armnn::PermutationVector& mappings)
arovir01b0717b52018-09-05 17:03:25 +0100499{
500 // Add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000501 armnn::IConnectableLayer* const layer = network.AddTransposeLayer(mappings);
arovir01b0717b52018-09-05 17:03:25 +0100502
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100503 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +0100504
505 // Connect input to swizzle layer
506 input.Connect(layer->GetInputSlot(0));
507
508 // Setup swizzled output
Mike Kelly4a956582020-02-28 10:32:09 +0000509 const armnn::TensorInfo outInfo = armnnUtils::TransposeTensorShape(input.GetTensorInfo(), mappings);
arovir01b0717b52018-09-05 17:03:25 +0100510 layer->GetOutputSlot(0).SetTensorInfo(outInfo);
511
512 return *layer;
513}
514
arovir01b0717b52018-09-05 17:03:25 +0100515bool ValidateConcatOutputShape(const std::vector<armnn::TensorShape> & inputShapes,
516 const armnn::TensorShape & outputShape,
517 uint32_t concatDim)
518{
519 // Validate the output shape is correct given the input shapes (which have just been validated)
520 unsigned int numDimensions = inputShapes[0].GetNumDimensions();
521 if (outputShape.GetNumDimensions() != numDimensions)
522 {
523 return Fail("%s: Output shape has wrong number of dimensions", __func__);
524 }
525
526 unsigned int outputSizeAlongConcatenatedDimension = 0;
527 for (unsigned int i = 0; i < inputShapes.size(); i++)
528 {
529 outputSizeAlongConcatenatedDimension += inputShapes[i][concatDim];
530 }
531
532 for (unsigned int i = 0; i < numDimensions; ++i)
533 {
534 if (i == concatDim)
535 {
536 if (outputShape[i] != outputSizeAlongConcatenatedDimension)
537 {
538 return Fail(
539 "%s: Invalid output shape for dimension %d (%d != %d)",
540 __func__,
541 i,
542 outputShape[i],
543 outputSizeAlongConcatenatedDimension);
544 }
545 }
546 else
547 {
548 if (outputShape[i] != inputShapes[0][i])
549 {
550 return Fail("%s: Invalid output shape", __func__);
551 }
552 }
553 }
554
555 return true;
556}
557
558bool RequiresReshape(armnn::TensorShape & inputShape)
559{
560 return inputShape.GetNumDimensions() < 3;
561}
562
arovir01b0717b52018-09-05 17:03:25 +0100563void SwizzleInputs(armnn::INetwork& network,
564 std::vector<LayerInputHandle>& inputs,
565 std::vector<armnn::TensorShape>& inputShapes,
566 const armnn::PermutationVector& mapping)
567{
568 if (!mapping.IsEqual(IdentityPermutation4D))
569 {
570 size_t nInputs = inputs.size();
571 for (size_t i=0; i<nInputs; ++i)
572 {
573 // add swizzle layer
Mike Kelly4a956582020-02-28 10:32:09 +0000574 armnn::IConnectableLayer& swizzleLayer = AddTransposeLayer(network, inputs[i], mapping);
arovir01b0717b52018-09-05 17:03:25 +0100575 auto& outputSlot = swizzleLayer.GetOutputSlot(0);
576 auto& outputInfo = outputSlot.GetTensorInfo();
577 // replace inputs with the swizzled ones
578 inputs[i] = LayerInputHandle(true, &outputSlot, outputInfo);
579 inputShapes[i] = inputs[i].GetTensorInfo().GetShape();
580 }
581 }
582}
583
Teresa Charlin185f5882020-04-06 21:59:18 +0100584bool TransposeInputTensors(ConversionData& data,
585 std::vector<LayerInputHandle>& inputs,
586 std::vector<armnn::TensorShape>& inputShapes,
587 const armnn::PermutationVector& mapping)
Kevin Mayaed08ac2019-12-12 16:33:31 +0000588{
589 if (!mapping.IsEqual(IdentityPermutation4D))
590 {
Teresa Charlin185f5882020-04-06 21:59:18 +0100591 armnn::TensorInfo outputTransposeInfo;
Kevin Mayaed08ac2019-12-12 16:33:31 +0000592 size_t nInputs = inputs.size();
593 for (size_t i=0; i<nInputs; ++i)
594 {
595 // check permute layer
Mike Kelly4a956582020-02-28 10:32:09 +0000596 armnn::TransposeDescriptor transposeDesc;
597 transposeDesc.m_DimMappings = mapping;
Teresa Charlin185f5882020-04-06 21:59:18 +0100598 outputTransposeInfo = armnnUtils::TransposeTensorShape(inputs[i].GetTensorInfo(), mapping);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000599
600 bool isSupported = false;
601 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +0000602 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +0000603 data.m_Backends,
604 isSupported,
605 inputs[i].GetTensorInfo(),
Teresa Charlin185f5882020-04-06 21:59:18 +0100606 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +0000607 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +0000608 if (!isSupported)
609 {
610 return false;
611 }
612
613 }
614 SwizzleInputs(*data.m_Network, inputs, inputShapes, mapping);
615 }
616 return true;
617}
618
619
narpra01f176d5a2018-11-18 20:17:48 +0000620bool CreateConcatPermutationParameters(const unsigned int numberOfDimensions,
621 int32_t & concatDimension,
622 std::pair<armnn::PermutationVector, armnn::PermutationVector> & permutationPair)
arovir01b0717b52018-09-05 17:03:25 +0100623{
narpra01f176d5a2018-11-18 20:17:48 +0000624 bool needPermute = false;
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100625 ARMNN_ASSERT(numberOfDimensions >= 3);
arovir01b0717b52018-09-05 17:03:25 +0100626
627 // ArmNN uses Compute Library subtensors to perform concatenation
narpra01f176d5a2018-11-18 20:17:48 +0000628 // This only works when concatenating along dimension 0, 1 or 3 for a 4-D tensor,
629 // or along dimension 0 or 2 for a 3-D tensor.
630 if (numberOfDimensions == 4 && concatDimension == 2)
arovir01b0717b52018-09-05 17:03:25 +0100631 {
narpra01f176d5a2018-11-18 20:17:48 +0000632 concatDimension = 1;
633 permutationPair = std::make_pair(SwapDim1And2, SwapDim1And2);
634 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100635 }
narpra01f176d5a2018-11-18 20:17:48 +0000636 else if (numberOfDimensions == 3 && concatDimension == 1)
arovir01b0717b52018-09-05 17:03:25 +0100637 {
narpra01f176d5a2018-11-18 20:17:48 +0000638 concatDimension = 0;
639 permutationPair = std::make_pair(RotateTensorLeft, RotateTensorRight);
640 needPermute = true;
arovir01b0717b52018-09-05 17:03:25 +0100641 }
narpra01f176d5a2018-11-18 20:17:48 +0000642 return needPermute;
arovir01b0717b52018-09-05 17:03:25 +0100643}
644
645} // anonymous namespace
646
647namespace armnn_driver
648{
649
650//// Creates an ArmNN activation layer and connects it to the given layer, if the
651//// passed in AndroidNN activation function requires so.
652//// @return The end layer of the sequence of layers built for the given AndroidNN
653//// activation function or nullptr if an error occurred (e.g. unsupported activation).
654//// Note that the end layer matches the input layer if no activation is required
655//// (the sequence of layers has length 1).
656armnn::IConnectableLayer* ProcessActivation(const armnn::TensorInfo& tensorInfo,
657 ActivationFn activation,
658 armnn::IConnectableLayer* prevLayer,
659 ConversionData& data);
660
661} // namespace armnn_driver
662
663///
664/// Utility templates
665///
666
667namespace armnn_driver
668{
669
670using namespace android::nn;
671
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100672template<typename HalPolicy,
673 typename HalOperand = typename HalPolicy::Operand,
674 typename HalOperation = typename HalPolicy::Operation,
675 typename HalModel = typename HalPolicy::Model>
676const HalOperand* GetInputOperand(const HalOperation& operation,
677 uint32_t inputIndex,
678 const HalModel& model,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100679 bool failOnIndexOutOfBounds = true)
arovir01b0717b52018-09-05 17:03:25 +0100680{
681 if (inputIndex >= operation.inputs.size())
682 {
saoste01b8471482018-10-10 09:44:51 +0100683 if (failOnIndexOutOfBounds)
684 {
685 Fail("%s: invalid input index: %i out of %i", __func__, inputIndex, operation.inputs.size());
686 }
arovir01b0717b52018-09-05 17:03:25 +0100687 return nullptr;
688 }
689
Kevin May42477c12020-03-26 13:34:14 +0000690 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100691 ARMNN_ASSERT(operation.inputs[inputIndex] < getMainModel(model).operands.size());
Kevin May42477c12020-03-26 13:34:14 +0000692 return &getMainModel(model).operands[operation.inputs[inputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100693}
694
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100695template<typename HalPolicy,
696 typename HalOperand = typename HalPolicy::Operand,
697 typename HalOperation = typename HalPolicy::Operation,
698 typename HalModel = typename HalPolicy::Model>
699const HalOperand* GetOutputOperand(const HalOperation& operation,
700 uint32_t outputIndex,
701 const HalModel& model)
arovir01b0717b52018-09-05 17:03:25 +0100702{
703 if (outputIndex >= operation.outputs.size())
704 {
705 Fail("%s: invalid output index: %i out of %i", __func__, outputIndex, operation.outputs.size());
706 return nullptr;
707 }
708
709 // Model should have been validated beforehand
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +0100710 ARMNN_ASSERT(operation.outputs[outputIndex] < getMainModel(model).operands.size());
arovir01b0717b52018-09-05 17:03:25 +0100711
Kevin May42477c12020-03-26 13:34:14 +0000712 return &getMainModel(model).operands[operation.outputs[outputIndex]];
arovir01b0717b52018-09-05 17:03:25 +0100713}
714
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100715template<typename HalPolicy,
Pablo Tellofb45e2f2019-10-18 16:51:57 +0100716 typename HalOperand = typename HalPolicy::Operand,
717 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +0100718const void* GetOperandValueReadOnlyAddress(const HalOperand& operand,
Matthew Bentham912b3622019-05-03 15:49:14 +0100719 const HalModel& model,
720 const ConversionData& data,
Kevin Mayf29a2c52019-03-14 11:56:32 +0000721 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100722{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100723 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
arovir01b0717b52018-09-05 17:03:25 +0100724
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100725 const void* valueStart = nullptr;
arovir01b0717b52018-09-05 17:03:25 +0100726 switch (operand.lifetime)
727 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100728 case HalOperandLifeTime::CONSTANT_COPY:
arovir01b0717b52018-09-05 17:03:25 +0100729 {
730 // Constant found in model.operandValues
731 valueStart = &model.operandValues[operand.location.offset];
732 break;
733 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100734 case HalOperandLifeTime::CONSTANT_REFERENCE:
arovir01b0717b52018-09-05 17:03:25 +0100735 {
736 // Constant specified via a Memory object
737 valueStart = GetMemoryFromPool(operand.location, data.m_MemPools);
738 break;
739 }
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100740 case HalOperandLifeTime::NO_VALUE:
Kevin Mayf29a2c52019-03-14 11:56:32 +0000741 {
742 // An optional input tensor with no values is not an error so should not register as a fail
743 if (optional)
744 {
745 valueStart = nullptr;
746 break;
747 }
Matthew Bentham912b3622019-05-03 15:49:14 +0100748 [[fallthrough]];
Kevin Mayf29a2c52019-03-14 11:56:32 +0000749 }
arovir01b0717b52018-09-05 17:03:25 +0100750 default:
751 {
752 // Unsupported/invalid (e.g. can't get value of an input to the model)
753 Fail("%s: unsupported/invalid operand lifetime: %s",
754 __func__, toString(operand.lifetime).c_str());
755 valueStart = nullptr;
756 }
757 }
758
759 return valueStart;
760}
761
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100762template<typename HalPolicy,
Aron Virginas-Tar7a6d11b2019-07-03 15:27:08 +0100763 typename HalOperation = typename HalPolicy::Operation,
764 typename HalModel = typename HalPolicy::Model,
765 typename HalOperandType = typename HalPolicy::OperandType>
766bool GetOperandType(const HalOperation& operation,
767 uint32_t inputIndex,
768 const HalModel& model,
769 HalOperandType& type)
770{
771 using HalOperand = typename HalPolicy::Operand;
772
773 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
774 if (!operand)
775 {
776 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
777 }
778
779 type = operand->type;
780 return true;
781}
782
783template<typename HalPolicy,
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000784 typename HalOperand = typename HalPolicy::Operand>
785bool IsOperandConstant(const HalOperand& operand)
786{
787 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
788
789 HalOperandLifeTime lifetime = operand.lifetime;
790
791 return lifetime == HalOperandLifeTime::CONSTANT_COPY ||
792 lifetime == HalOperandLifeTime::CONSTANT_REFERENCE ||
793 lifetime == HalOperandLifeTime::NO_VALUE;
794}
795
796template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100797 typename HalOperand = typename HalPolicy::Operand,
798 typename HalModel = typename HalPolicy::Model>
799ConstTensorPin ConvertOperandToConstTensorPin(const HalOperand& operand,
800 const HalModel& model,
801 const ConversionData& data,
802 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
803 const armnn::TensorShape* overrideTensorShape = nullptr,
804 bool optional = false)
805{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100806 if (!IsOperandTypeSupportedForTensors(operand.type))
807 {
808 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand.type).c_str());
809 return ConstTensorPin();
810 }
811
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +0000812 if (!optional && !IsOperandConstant<HalPolicy>(operand))
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100813 {
814 Fail("%s: invalid operand lifetime: %s", __func__, toString(operand.lifetime).c_str());
815 return ConstTensorPin();
816 }
817
818 const void* const valueStart = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data, optional);
819 if (!valueStart)
820 {
821 if (optional)
822 {
823 // optional tensor with no values is not really an error; return it as invalid, but marked as optional
824 return ConstTensorPin(true);
825 }
826 // mandatory tensor with no values
827 Fail("%s: failed to get operand address", __func__);
828 return ConstTensorPin();
829 }
830
831 armnn::TensorInfo tensorInfo = GetTensorInfoForOperand(operand);
Teresa Charlin02dce092019-11-11 17:06:23 +0000832 // Android datalayout might be different than armnn datalayout, e.g. the kernel for the depthwise convolution.
833 if (tensorInfo.HasPerAxisQuantization())
834 {
835 tensorInfo.SetQuantizationDim(dimensionMappings[tensorInfo.GetQuantizationDim().value()]);
836 }
837
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100838 if (overrideTensorShape != nullptr)
839 {
840 tensorInfo.SetShape(*overrideTensorShape);
841 }
842 return ConstTensorPin(tensorInfo, valueStart, operand.location.length, dimensionMappings);
843}
844
845template<typename HalPolicy,
846 typename HalOperation = typename HalPolicy::Operation,
847 typename HalModel = typename HalPolicy::Model>
848ConstTensorPin ConvertOperationInputToConstTensorPin(const HalOperation& operation,
849 uint32_t inputIndex,
850 const HalModel& model,
851 const ConversionData& data,
852 const armnn::PermutationVector& dimensionMappings = g_DontPermute,
853 const armnn::TensorShape* overrideTensorShape = nullptr,
854 bool optional = false)
855{
856 using HalOperand = typename HalPolicy::Operand;
857
858 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
859 if (!operand)
860 {
861 Fail("%s: failed to get input operand: index=%u", __func__, inputIndex);
862 return ConstTensorPin();
863 }
864 return ConvertOperandToConstTensorPin<HalPolicy>(*operand,
865 model,
866 data,
867 dimensionMappings,
868 overrideTensorShape,
869 optional);
870}
871
872template<typename HalPolicy,
873 typename OutputType,
874 typename HalOperandType = typename HalPolicy::OperandType,
875 typename HalOperation = typename HalPolicy::Operation,
876 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100877bool GetInputScalar(const HalOperation& operation,
878 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100879 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100880 OutputType& outValue,
881 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +0100882 const ConversionData& data,
883 bool optional = false)
arovir01b0717b52018-09-05 17:03:25 +0100884{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100885 using HalOperand = typename HalPolicy::Operand;
886
887 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Sadik Armagan813f2302020-05-19 14:10:30 +0100888 if (!optional && !operand)
arovir01b0717b52018-09-05 17:03:25 +0100889 {
890 return Fail("%s: invalid input operand at index %i", __func__, inputIndex);
891 }
892
Sadik Armagan813f2302020-05-19 14:10:30 +0100893 if (!optional && operand->type != type)
arovir01b0717b52018-09-05 17:03:25 +0100894 {
895 return Fail("%s: unexpected operand type: %s (should be %s)",
896 __func__, toString(operand->type).c_str(), toString(type).c_str());
897 }
898
Sadik Armagan813f2302020-05-19 14:10:30 +0100899 if (!optional && operand->location.length != sizeof(OutputType))
arovir01b0717b52018-09-05 17:03:25 +0100900 {
901 return Fail("%s: incorrect operand location length: %i (should be %i)",
902 __func__, operand->location.length, sizeof(OutputType));
903 }
904
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100905 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Sadik Armagan813f2302020-05-19 14:10:30 +0100906 if (!optional && !valueAddress)
arovir01b0717b52018-09-05 17:03:25 +0100907 {
908 return Fail("%s: failed to get address for operand", __func__);
909 }
910
Sadik Armagan813f2302020-05-19 14:10:30 +0100911 if(!optional)
912 {
913 outValue = *(static_cast<const OutputType*>(valueAddress));
914 }
915
arovir01b0717b52018-09-05 17:03:25 +0100916 return true;
917}
918
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100919template<typename HalPolicy,
920 typename HalOperation = typename HalPolicy::Operation,
921 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100922bool GetInputInt32(const HalOperation& operation,
923 uint32_t inputIndex,
924 int32_t& outValue,
925 const HalModel& model,
926 const ConversionData& data)
927{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100928 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::INT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100929}
930
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100931template<typename HalPolicy,
932 typename HalOperation = typename HalPolicy::Operation,
933 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100934bool GetInputFloat32(const HalOperation& operation,
935 uint32_t inputIndex,
936 float& outValue,
937 const HalModel& model,
938 const ConversionData& data)
939{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100940 return GetInputScalar<HalPolicy>(operation, inputIndex, HalPolicy::OperandType::FLOAT32, outValue, model, data);
arovir01b0717b52018-09-05 17:03:25 +0100941}
942
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100943template<typename HalPolicy,
944 typename HalOperation = typename HalPolicy::Operation,
945 typename HalOperandType = typename HalPolicy::OperandType,
946 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100947bool GetInputActivationFunctionImpl(const HalOperation& operation,
948 uint32_t inputIndex,
Mike Kellyb5fdf382019-06-11 16:35:25 +0100949 HalOperandType type,
arovir01b0717b52018-09-05 17:03:25 +0100950 ActivationFn& outActivationFunction,
951 const HalModel& model,
952 const ConversionData& data)
953{
Mike Kellyb5fdf382019-06-11 16:35:25 +0100954 if (type != HalOperandType::INT32 && type != HalOperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +0100955 {
956 return Fail("%s: unexpected operand type: %s (should be %s or %s)",
957 __func__,
958 toString(type).c_str(),
959 toString(OperandType::INT32).c_str(),
960 toString(OperandType::TENSOR_INT32).c_str());
961 }
962
963 int32_t activationFunctionAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100964 if (!GetInputScalar<HalPolicy>(operation, inputIndex, type, activationFunctionAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +0100965 {
966 return Fail("%s: failed to get activation input value", __func__);
967 }
968 outActivationFunction = static_cast<ActivationFn>(activationFunctionAsInt);
969 return true;
970}
971
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100972template<typename HalPolicy,
973 typename HalOperation = typename HalPolicy::Operation,
974 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100975bool GetInputActivationFunction(const HalOperation& operation,
976 uint32_t inputIndex,
977 ActivationFn& outActivationFunction,
978 const HalModel& model,
979 const ConversionData& data)
980{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100981 return GetInputActivationFunctionImpl<HalPolicy>(operation,
982 inputIndex,
983 HalPolicy::OperandType::INT32,
984 outActivationFunction,
985 model,
986 data);
arovir01b0717b52018-09-05 17:03:25 +0100987}
988
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100989template<typename HalPolicy,
990 typename HalOperation = typename HalPolicy::Operation,
991 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +0100992bool GetInputActivationFunctionFromTensor(const HalOperation& operation,
993 uint32_t inputIndex,
994 ActivationFn& outActivationFunction,
995 const HalModel& model,
996 const ConversionData& data)
997{
998 // This only accepts a 1-D tensor of size 1
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +0100999 return GetInputActivationFunctionImpl<HalPolicy>(operation,
1000 inputIndex,
1001 HalPolicy::OperandType::INT32,
1002 outActivationFunction,
1003 model,
1004 data);
arovir01b0717b52018-09-05 17:03:25 +01001005}
1006
1007
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001008template<typename HalPolicy,
1009 typename HalOperation = typename HalPolicy::Operation,
1010 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001011bool GetOptionalInputActivation(const HalOperation& operation,
1012 uint32_t inputIndex,
1013 ActivationFn& activationFunction,
1014 const HalModel& model,
1015 const ConversionData& data)
1016{
1017 if (operation.inputs.size() <= inputIndex)
1018 {
1019 activationFunction = ActivationFn::kActivationNone;
1020 }
1021 else
1022 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001023 if (!GetInputActivationFunction<HalPolicy>(operation, inputIndex, activationFunction, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001024 {
1025 return Fail("%s: Operation has invalid inputs", __func__);
1026 }
1027 }
1028 return true;
1029}
1030
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001031template<typename HalPolicy,
1032 typename ConvolutionDescriptor,
1033 typename HalOperation = typename HalPolicy::Operation,
1034 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001035bool GetOptionalConvolutionDilationParams(const HalOperation& operation,
1036 uint32_t dilationXIndex,
1037 ConvolutionDescriptor& descriptor,
1038 const HalModel& model,
1039 const ConversionData& data)
1040{
1041 bool success = true;
1042 if (operation.inputs.size() >= dilationXIndex + 2)
1043 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001044 success &= GetInputScalar<HalPolicy>(operation,
1045 dilationXIndex,
1046 HalPolicy::OperandType::INT32,
1047 descriptor.m_DilationX,
1048 model,
1049 data);
1050 success &= GetInputScalar<HalPolicy>(operation,
1051 dilationXIndex + 1,
1052 HalPolicy::OperandType::INT32,
1053 descriptor.m_DilationY,
1054 model,
1055 data);
Aron Virginas-Tar07c7c9a2019-06-12 14:03:35 +01001056 }
1057
1058 return success;
1059}
1060
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001061template<typename HalPolicy,
David Monahan51e0b132020-04-20 16:12:06 +01001062 typename HalOperation = typename HalPolicy::Operation,
1063 typename HalModel = typename HalPolicy::Model>
1064bool GetOptionalBool(const HalOperation& operation,
1065 uint32_t inputIndex,
1066 const HalModel& model,
1067 const ConversionData& data)
1068{
1069 using HalOperand = typename HalPolicy::Operand;
1070
1071 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1072 if (!operand)
1073 {
1074 return false;
1075 }
1076
1077 if (!IsBool(*operand))
1078 {
1079 return false;
1080 }
1081
1082 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
1083 if (!valueAddress)
1084 {
1085 return false;
1086 }
1087
1088 if (*(static_cast<const bool*>(valueAddress)))
1089 {
1090 return true;
1091 }
1092 else
1093 {
1094 return false;
1095 }
1096}
1097
1098template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001099 typename HalOperand = typename HalPolicy::Operand,
1100 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001101bool GetTensorInt32Values(const HalOperand& operand,
arovir01b0717b52018-09-05 17:03:25 +01001102 std::vector<int32_t>& outValues,
1103 const HalModel& model,
1104 const ConversionData& data)
1105{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001106 if (operand.type != HalPolicy::OperandType::TENSOR_INT32)
arovir01b0717b52018-09-05 17:03:25 +01001107 {
1108 return Fail("%s: invalid operand type: %s", __func__, toString(operand.type).c_str());
1109 }
1110
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001111 const void* startAddress = GetOperandValueReadOnlyAddress<HalPolicy>(operand, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001112 if (!startAddress)
1113 {
1114 return Fail("%s: failed to get operand address", __func__, operand.type);
1115 }
1116
1117 // Check number of bytes is sensible
1118 const uint32_t numBytes = operand.location.length;
1119 if (numBytes % sizeof(int32_t) != 0)
1120 {
1121 return Fail("%s: invalid number of bytes: %i, expected to be a multiple of %i",
1122 __func__, numBytes, sizeof(int32_t));
1123 }
1124
1125 outValues.resize(numBytes / sizeof(int32_t));
1126 memcpy(outValues.data(), startAddress, numBytes);
1127 return true;
1128}
1129
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001130template<typename HalPolicy,
1131 typename HalOperation = typename HalPolicy::Operation,
1132 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001133bool GetInputPaddingScheme(const HalOperation& operation,
1134 uint32_t inputIndex,
1135 PaddingScheme& outPaddingScheme,
1136 const HalModel& model,
1137 const ConversionData& data)
1138{
1139 int32_t paddingSchemeAsInt;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001140 if (!GetInputInt32<HalPolicy>(operation, inputIndex, paddingSchemeAsInt, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001141 {
1142 return Fail("%s: failed to get padding scheme input value", __func__);
1143 }
1144
1145 outPaddingScheme = static_cast<android::nn::PaddingScheme>(paddingSchemeAsInt);
1146 return true;
1147}
1148
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001149template<typename HalPolicy,
1150 typename HalOperation = typename HalPolicy::Operation,
1151 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001152LayerInputHandle ConvertToLayerInputHandle(const HalOperation& operation,
1153 uint32_t inputIndex,
1154 const HalModel& model,
1155 ConversionData& data)
1156{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001157 using HalOperand = typename HalPolicy::Operand;
Sadik Armagan44bcc022019-06-18 17:21:36 +01001158 using HalOperandType = typename HalPolicy::OperandType;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001159 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1160
1161 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
arovir01b0717b52018-09-05 17:03:25 +01001162 if (!operand)
1163 {
1164 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1165 return LayerInputHandle();
1166 }
1167
1168 if (!IsOperandTypeSupportedForTensors(operand->type))
1169 {
1170 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1171 return LayerInputHandle();
1172 }
1173
Sadik Armagan44bcc022019-06-18 17:21:36 +01001174 try
arovir01b0717b52018-09-05 17:03:25 +01001175 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001176 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
Aron Virginas-Tar573a8fa2019-07-23 14:01:37 +01001177 if (IsDynamicTensor(operandTensorInfo))
1178 {
1179 Fail("%s: dynamic input tensors are not supported", __func__);
1180 return LayerInputHandle();
1181 }
arovir01b0717b52018-09-05 17:03:25 +01001182
Sadik Armagan44bcc022019-06-18 17:21:36 +01001183 switch (operand->lifetime)
arovir01b0717b52018-09-05 17:03:25 +01001184 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001185 case HalOperandLifeTime::MODEL_INPUT:
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001186 {
1187 // NOTE: We must check whether we can support the input tensor on at least one
1188 // of the provided backends; otherwise we cannot convert the operation
1189 bool isInputSupported = false;
1190 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1191 IsInputSupported,
1192 data.m_Backends,
1193 isInputSupported,
1194 operandTensorInfo);
1195
1196 if (!isInputSupported)
1197 {
1198 Fail("%s: unsupported input tensor", __func__);
1199 return LayerInputHandle();
1200 }
1201
1202 BOOST_FALLTHROUGH; // intentional fallthrough
1203 }
1204 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001205 case HalOperandLifeTime::MODEL_OUTPUT:
arovir01b0717b52018-09-05 17:03:25 +01001206 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001207 // The tensor is either an operand internal to the model, or a model input.
1208 // It can be associated with an ArmNN output slot for an existing layer.
1209
1210 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1211 const uint32_t operandIndex = operation.inputs[inputIndex];
1212 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
Sadik Armagan44bcc022019-06-18 17:21:36 +01001213 }
Aron Virginas-Tar000117b2019-07-25 16:24:49 +01001214 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
Sadik Armagan44bcc022019-06-18 17:21:36 +01001215 case HalOperandLifeTime::CONSTANT_REFERENCE:
1216 {
1217 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1218 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1219 if (tensorPin.IsValid())
arovir01b0717b52018-09-05 17:03:25 +01001220 {
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001221 bool isSupported = false;
1222 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1223 IsConstantSupported,
1224 data.m_Backends,
1225 isSupported,
1226 tensorPin.GetConstTensor().GetInfo());
Mike Kelly28e3d9f2019-08-07 14:55:04 +01001227 if (!isSupported)
Sadik Armagan44bcc022019-06-18 17:21:36 +01001228 {
1229 return LayerInputHandle();
1230 }
1231
1232 armnn::IConnectableLayer* constantLayer =
1233 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1234 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1235 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1236
1237 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1238 }
1239 else
1240 {
1241 Fail("%s: invalid operand tensor", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001242 return LayerInputHandle();
1243 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001244 break;
arovir01b0717b52018-09-05 17:03:25 +01001245 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001246 default:
arovir01b0717b52018-09-05 17:03:25 +01001247 {
Sadik Armagan44bcc022019-06-18 17:21:36 +01001248 // Unsupported lifetime for an input tensor
1249 Fail("%s: unsupported lifetime for input tensor: %s",
1250 __func__, toString(operand->lifetime).c_str());
arovir01b0717b52018-09-05 17:03:25 +01001251 return LayerInputHandle();
1252 }
arovir01b0717b52018-09-05 17:03:25 +01001253 }
Sadik Armagan44bcc022019-06-18 17:21:36 +01001254 }
1255 catch (UnsupportedOperand<HalOperandType>& e)
1256 {
1257 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1258 return LayerInputHandle();
arovir01b0717b52018-09-05 17:03:25 +01001259 }
1260}
1261
Kevin May42477c12020-03-26 13:34:14 +00001262
1263#ifdef ARMNN_ANDROID_NN_V1_3
1264template<typename HalPolicy>
1265LayerInputHandle ConvertToLayerInputHandle(const ::android::hardware::neuralnetworks::V1_3::Operation& operation,
1266 uint32_t inputIndex,
1267 const::android::hardware::neuralnetworks::V1_3::Model& model,
1268 ConversionData& data)
1269{
1270 using HalOperand = typename HalPolicy::Operand;
1271 using HalOperandType = typename HalPolicy::OperandType;
1272 using HalOperandLifeTime = typename HalPolicy::OperandLifeTime;
1273
1274 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
1275 if (!operand)
1276 {
1277 Fail("%s: failed to get input operand %i", __func__, inputIndex);
1278 return LayerInputHandle();
1279 }
1280
1281 if (!IsOperandTypeSupportedForTensors(operand->type))
1282 {
1283 Fail("%s: unsupported operand type for tensor %s", __func__, toString(operand->type).c_str());
1284 return LayerInputHandle();
1285 }
1286
1287 try
1288 {
1289 armnn::TensorInfo operandTensorInfo = GetTensorInfoForOperand(*operand);
1290 if (IsDynamicTensor(operandTensorInfo))
1291 {
1292 Fail("%s: dynamic input tensors are not supported", __func__);
1293 return LayerInputHandle();
1294 }
1295
1296 switch (operand->lifetime)
1297 {
1298 case HalOperandLifeTime::SUBGRAPH_INPUT:
1299 {
1300 // NOTE: We must check whether we can support the input tensor on at least one
1301 // of the provided backends; otherwise we cannot convert the operation
1302 bool isInputSupported = false;
1303 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1304 IsInputSupported,
1305 data.m_Backends,
1306 isInputSupported,
1307 operandTensorInfo);
1308
1309 if (!isInputSupported)
1310 {
1311 Fail("%s: unsupported input tensor", __func__);
1312 return LayerInputHandle();
1313 }
1314
1315 BOOST_FALLTHROUGH; // intentional fallthrough
1316 }
1317 case HalOperandLifeTime::TEMPORARY_VARIABLE: // intentional fallthrough
1318 case HalOperandLifeTime::SUBGRAPH_OUTPUT:
1319 {
1320 // The tensor is either an operand internal to the model, or a model input.
1321 // It can be associated with an ArmNN output slot for an existing layer.
1322
1323 // m_OutputSlotForOperand[...] can be nullptr if the previous layer could not be converted
1324 const uint32_t operandIndex = operation.inputs[inputIndex];
1325 return LayerInputHandle(true, data.m_OutputSlotForOperand[operandIndex], operandTensorInfo);
1326 }
1327 case HalOperandLifeTime::CONSTANT_COPY: // intentional fallthrough
1328 case HalOperandLifeTime::CONSTANT_REFERENCE:
1329 {
1330 // The tensor has an already known constant value, and can be converted into an ArmNN Constant layer.
1331 ConstTensorPin tensorPin = ConvertOperandToConstTensorPin<HalPolicy>(*operand, model, data);
1332 if (tensorPin.IsValid())
1333 {
1334 bool isSupported = false;
1335 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1336 IsConstantSupported,
1337 data.m_Backends,
1338 isSupported,
1339 tensorPin.GetConstTensor().GetInfo());
1340 if (!isSupported)
1341 {
1342 return LayerInputHandle();
1343 }
1344
1345 armnn::IConnectableLayer* constantLayer =
1346 data.m_Network->AddConstantLayer(tensorPin.GetConstTensor());
1347 armnn::IOutputSlot& outputSlot = constantLayer->GetOutputSlot(0);
1348 outputSlot.SetTensorInfo(tensorPin.GetConstTensor().GetInfo());
1349
1350 return LayerInputHandle(true, &outputSlot, operandTensorInfo);
1351 }
1352 else
1353 {
1354 Fail("%s: invalid operand tensor", __func__);
1355 return LayerInputHandle();
1356 }
1357 break;
1358 }
1359 default:
1360 {
1361 // Unsupported lifetime for an input tensor
1362 Fail("%s: unsupported lifetime for input tensor: %s",
1363 __func__, toString(operand->lifetime).c_str());
1364 return LayerInputHandle();
1365 }
1366 }
1367 }
1368 catch (UnsupportedOperand<HalOperandType>& e)
1369 {
1370 Fail("%s: Operand type %s not supported in ArmnnDriver", __func__, toString(e.m_type).c_str());
1371 return LayerInputHandle();
1372 }
1373}
1374#endif
1375
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001376template<typename HalPolicy,
1377 typename HalOperation = typename HalPolicy::Operation,
1378 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001379bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1380 uint32_t operationOutputIndex,
1381 armnn::IConnectableLayer& layer,
1382 uint32_t layerOutputIndex,
1383 const HalModel& model,
Sadik Armagan813f2302020-05-19 14:10:30 +01001384 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001385 const armnn::TensorInfo* overrideOutputInfo = nullptr,
1386 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001387{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001388 using HalOperand = typename HalPolicy::Operand;
1389
1390 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, operationOutputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001391 if ((outputOperand == nullptr) || (operationOutputIndex >= layer.GetNumOutputSlots()))
1392 {
1393 return false;
1394 }
1395
1396 armnn::IOutputSlot& outputSlot = layer.GetOutputSlot(layerOutputIndex);
1397
Finn Williamsa4983ce2020-07-23 12:55:12 +01001398 bool isSupported = false;
1399 if (validateFunc &&
1400 layer.GetInputSlot(0).GetConnection() &&
1401 IsDynamicTensor(outputSlot.GetTensorInfo()))
Sadik Armagan813f2302020-05-19 14:10:30 +01001402 {
Finn Williamsa4983ce2020-07-23 12:55:12 +01001403 outputSlot.IsTensorInfoSet();
1404 validateFunc(outputSlot.GetTensorInfo(), isSupported);
1405
1406 if(!isSupported)
1407 {
1408 for (unsigned int inputSlotIndex = 0; inputSlotIndex < layer.GetNumInputSlots(); ++inputSlotIndex)
1409 {
1410 layer.GetInputSlot(inputSlotIndex).GetConnection()->Disconnect(layer.GetInputSlot(inputSlotIndex));
1411 }
1412
1413 return false;
1414 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001415 }
1416 else
1417 {
Finn Williamsa4983ce2020-07-23 12:55:12 +01001418 if (overrideOutputInfo == nullptr)
1419 {
1420 outputSlot.SetTensorInfo(GetTensorInfoForOperand(*outputOperand));
1421 }
1422 else
1423 {
1424 outputSlot.SetTensorInfo(*overrideOutputInfo);
1425 }
Sadik Armagan813f2302020-05-19 14:10:30 +01001426 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01001427
Finn Williamsa4983ce2020-07-23 12:55:12 +01001428 const uint32_t operandIndex = operation.outputs[operationOutputIndex];
1429 data.m_OutputSlotForOperand[operandIndex] = &outputSlot;
1430
Mike Kellyb5fdf382019-06-11 16:35:25 +01001431 return true;
1432}
1433
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001434template<typename HalPolicy,
1435 typename HalOperation = typename HalPolicy::Operation,
1436 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001437armnn::DataLayout OptionalDataLayout(const HalOperation& operation,
1438 uint32_t inputIndex,
1439 const HalModel& model,
1440 ConversionData& data)
1441{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001442 using HalOperand = typename HalPolicy::Operand;
1443
1444 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, inputIndex, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001445 if (!operand)
1446 {
1447 return armnn::DataLayout::NHWC;
1448 }
1449
1450 if (!IsBool(*operand))
1451 {
1452 return armnn::DataLayout::NHWC;
1453 }
1454
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001455 const void* valueAddress = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001456 if (!valueAddress)
1457 {
1458 return armnn::DataLayout::NHWC;
1459 }
1460
1461 if (*(static_cast<const bool*>(valueAddress)))
1462 {
1463 return armnn::DataLayout::NCHW;
1464 }
1465 else
1466 {
1467 return armnn::DataLayout::NHWC;
1468 }
1469}
1470
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001471template<typename HalPolicy,
1472 typename HalOperation = typename HalPolicy::Operation,
1473 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01001474bool SetupAndTrackLayerOutputSlot(const HalOperation& operation,
1475 uint32_t outputIndex,
1476 armnn::IConnectableLayer& layer,
1477 const HalModel& model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001478 ConversionData& data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001479 const armnn::TensorInfo* overrideOutputInfo = nullptr,
1480 const std::function <void (const armnn::TensorInfo&, bool&)>& validateFunc = nullptr)
Mike Kellyb5fdf382019-06-11 16:35:25 +01001481{
Aron Virginas-Tarf03fcf02019-07-09 17:44:24 +01001482 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation,
1483 outputIndex,
1484 layer,
1485 outputIndex,
1486 model,
Finn Williamsfc884b42020-06-11 17:35:44 +01001487 data,
Finn Williamsa4983ce2020-07-23 12:55:12 +01001488 overrideOutputInfo,
1489 validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001490}
1491
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001492template<typename HalPolicy,
1493 typename HalOperation = typename HalPolicy::Operation,
1494 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001495bool ConvertToActivation(const HalOperation& operation,
1496 const char* operationName,
1497 const armnn::ActivationDescriptor& activationDesc,
1498 const HalModel& model,
1499 ConversionData& data)
1500{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001501 using HalOperand = typename HalPolicy::Operand;
1502
1503 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001504 if (!input.IsValid())
1505 {
1506 return Fail("%s: Input 0 is invalid", operationName);
1507 }
1508
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001509 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001510 if (!outputOperand)
1511 {
1512 return false;
1513 }
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01001514
1515 const armnn::TensorInfo& outInfo = GetTensorInfoForOperand(*outputOperand);
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001516
1517 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001518
1519 auto validateFunc = [&](const armnn::TensorInfo& outInfo, bool& isSupported)
1520 {
1521 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1522 IsActivationSupported,
1523 data.m_Backends,
1524 isSupported,
1525 input.GetTensorInfo(),
1526 outInfo,
1527 activationDesc);
1528 };
1529
1530 if(IsDynamicTensor(outInfo))
1531 {
1532 isSupported = AreDynamicTensorsSupported();
1533 }
1534 else
1535 {
1536 validateFunc(outInfo, isSupported);
1537 }
1538
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001539 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001540 {
1541 return false;
1542 }
1543
1544 armnn::IConnectableLayer* layer = data.m_Network->AddActivationLayer(activationDesc);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01001545 ARMNN_ASSERT(layer != nullptr);
arovir01b0717b52018-09-05 17:03:25 +01001546 input.Connect(layer->GetInputSlot(0));
1547
Finn Williamsa4983ce2020-07-23 12:55:12 +01001548 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
arovir01b0717b52018-09-05 17:03:25 +01001549}
1550
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001551template<typename HalPolicy,
Sadik Armagan61113162019-07-25 09:09:40 +01001552 typename HalOperation = typename HalPolicy::Operation,
1553 typename HalModel = typename HalPolicy::Model>
1554bool ConvertReLu(const HalOperation& operation, const HalModel& model, ConversionData& data)
1555{
1556 armnn::ActivationDescriptor desc;
1557 desc.m_Function = armnn::ActivationFunction::ReLu;
1558
1559 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1560}
1561
1562template<typename HalPolicy,
1563 typename HalOperation = typename HalPolicy::Operation,
1564 typename HalModel = typename HalPolicy::Model>
1565bool ConvertReLu1(const HalOperation& operation, const HalModel& model, ConversionData& data)
1566{
1567 armnn::ActivationDescriptor desc;
1568 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1569 desc.m_A = 1.0f;
1570 desc.m_B = -1.0f;
1571
1572 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1573}
1574
1575template<typename HalPolicy,
1576 typename HalOperation = typename HalPolicy::Operation,
1577 typename HalModel = typename HalPolicy::Model>
1578bool ConvertReLu6(const HalOperation& operation, const HalModel& model, ConversionData& data)
1579{
1580 armnn::ActivationDescriptor desc;
1581 desc.m_Function = armnn::ActivationFunction::BoundedReLu;
1582 desc.m_A = 6.0f;
1583
1584 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1585}
1586
1587template<typename HalPolicy,
1588 typename HalOperation = typename HalPolicy::Operation,
1589 typename HalModel = typename HalPolicy::Model>
1590bool ConvertTanH(const HalOperation& operation, const HalModel& model, ConversionData& data)
1591{
1592 armnn::ActivationDescriptor desc;
1593 desc.m_Function = armnn::ActivationFunction::TanH;
1594 desc.m_A = 1.0f; // android nn does not support tanH parameters
1595 desc.m_B = 1.0f; // set to 1.0f for unity scaling
1596
1597 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
1598}
1599
1600template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001601 typename HalOperation = typename HalPolicy::Operation,
1602 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001603bool ConvertPaddings(const HalOperation& operation,
1604 const HalModel& model,
1605 ConversionData& data,
1606 unsigned int rank,
1607 armnn::PadDescriptor& padDescriptor)
1608{
1609 using HalOperand = typename HalPolicy::Operand;
1610
1611 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
1612 if (!paddingsOperand)
1613 {
1614 return Fail("%s: Could not read paddings operand", __func__);
1615 }
1616
1617 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
1618 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != rank * 2)
1619 {
1620 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, rank);
1621 }
1622
1623 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00001624 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
1625 {
1626 return Fail("%s: Operation has invalid or unsupported paddings operand", __func__);
1627 }
Aron Virginas-Tarcb8ac842019-07-05 15:47:07 +01001628
1629 // add padding for each dimension of input tensor.
1630 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
1631 {
1632 int paddingBeforeInput = paddings[i];
1633 int paddingAfterInput = paddings[i + 1];
1634
1635 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
1636 {
1637 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
1638 }
1639
1640 padDescriptor.m_PadList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
1641 }
1642
1643 return true;
1644}
1645
1646template<typename HalPolicy,
1647 typename HalOperation = typename HalPolicy::Operation,
1648 typename HalModel = typename HalPolicy::Model>
arovir01b0717b52018-09-05 17:03:25 +01001649bool ConvertPooling2d(const HalOperation& operation,
1650 const char* operationName,
1651 armnn::PoolingAlgorithm poolType,
1652 const HalModel& model,
1653 ConversionData& data)
1654{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001655 using HalOperand = typename HalPolicy::Operand;
1656 using HalOperandType = typename HalPolicy::OperandType;
1657
1658 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001659 if (!input.IsValid())
1660 {
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001661 return Fail("%s: Operation Could not read input 0", operationName);
arovir01b0717b52018-09-05 17:03:25 +01001662 }
1663
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001664 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
arovir01b0717b52018-09-05 17:03:25 +01001665 if (!output)
1666 {
1667 return Fail("%s: Could not read output 0", __func__);
1668 }
1669
1670 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
1671 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
1672
arovir01b0717b52018-09-05 17:03:25 +01001673 armnn::Pooling2dDescriptor desc;
1674 desc.m_PoolType = poolType;
1675 desc.m_OutputShapeRounding = armnn::OutputShapeRounding::Floor;
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001676 desc.m_DataLayout = armnn::DataLayout::NHWC;
arovir01b0717b52018-09-05 17:03:25 +01001677
1678 ActivationFn activation;
1679
Sadik Armagan15d63e22019-07-26 16:59:35 +01001680 auto inputSize = operation.inputs.size();
1681
1682 if (inputSize >= 10)
1683 {
1684 // one input, 9 parameters (padding l r t b, stridex, stridey, width, height, activation type)
1685 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
1686 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_PadRight, model, data) ||
1687 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadTop, model, data) ||
1688 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
1689 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1690 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1691 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1692 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1693 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
1694 {
1695 return Fail("%s: Operation has invalid inputs", operationName);
1696 }
1697
Kevin May42477c12020-03-26 13:34:14 +00001698 if (Is12OrLaterOperand(*output))
Sadik Armagan15d63e22019-07-26 16:59:35 +01001699 {
1700 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 10, model, data);
1701 }
1702 }
1703 else
arovir01b0717b52018-09-05 17:03:25 +01001704 {
1705 // one input, 6 parameters (padding, stridex, stridey, width, height, activation type)
1706 android::nn::PaddingScheme scheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001707 if (!GetInputPaddingScheme<HalPolicy>(operation, 1, scheme, model, data) ||
1708 !GetInputScalar<HalPolicy>(operation, 2, HalOperandType::INT32, desc.m_StrideX, model, data) ||
1709 !GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_StrideY, model, data) ||
1710 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PoolWidth, model, data) ||
1711 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PoolHeight, model, data) ||
1712 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
arovir01b0717b52018-09-05 17:03:25 +01001713 {
1714 return Fail("%s: Operation has invalid inputs", operationName);
1715 }
1716
Kevin May42477c12020-03-26 13:34:14 +00001717 if (Is12OrLaterOperand(*output))
arovir01b0717b52018-09-05 17:03:25 +01001718 {
Sadik Armagan15d63e22019-07-26 16:59:35 +01001719 desc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 7, model, data);
arovir01b0717b52018-09-05 17:03:25 +01001720 }
FinnWilliamsArm493e9b72019-11-25 16:02:07 +00001721
1722 const armnnUtils::DataLayoutIndexed dataLayout(desc.m_DataLayout);
1723 const unsigned int inputWidth = inputInfo.GetShape()[dataLayout.GetWidthIndex()];
1724 const unsigned int inputHeight = inputInfo.GetShape()[dataLayout.GetHeightIndex()];
1725
1726 CalcPadding(inputWidth, desc.m_PoolWidth, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, scheme);
1727 CalcPadding(inputHeight, desc.m_PoolHeight, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, scheme);
arovir01b0717b52018-09-05 17:03:25 +01001728 }
1729
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001730 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001731
1732 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1733 {
1734 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1735 IsPooling2dSupported,
1736 data.m_Backends,
1737 isSupported,
1738 inputInfo,
1739 outputInfo,
1740 desc);
1741
1742 };
1743
1744 if(IsDynamicTensor(outputInfo))
1745 {
1746 isSupported = AreDynamicTensorsSupported();
1747 }
1748 else
1749 {
1750 validateFunc(outputInfo, isSupported);
1751 }
1752
Ferran Balaguerd30093c2019-07-09 17:04:47 +01001753 if (!isSupported)
arovir01b0717b52018-09-05 17:03:25 +01001754 {
Éanna Ó Catháin3d1059c2018-10-11 15:53:04 +01001755 return false;
arovir01b0717b52018-09-05 17:03:25 +01001756 }
arovir01b0717b52018-09-05 17:03:25 +01001757
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001758 armnn::IConnectableLayer* pooling2dLayer = data.m_Network->AddPooling2dLayer(desc);
1759 if (!pooling2dLayer)
arovir01b0717b52018-09-05 17:03:25 +01001760 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001761 return Fail("%s: AddPooling2dLayer failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001762 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001763
1764 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, pooling2dLayer, data);
1765 if (!endLayer)
arovir01b0717b52018-09-05 17:03:25 +01001766 {
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001767 return Fail("%s: ProcessActivation failed", __func__);
arovir01b0717b52018-09-05 17:03:25 +01001768 }
Matteo Martincigh39fc5472018-10-26 16:39:28 +01001769
1770 input.Connect(pooling2dLayer->GetInputSlot(0));
1771
Finn Williamsa4983ce2020-07-23 12:55:12 +01001772 if (!isSupported)
1773 {
1774 return false;
1775 }
1776
1777 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data, nullptr, validateFunc);
Mike Kellyb5fdf382019-06-11 16:35:25 +01001778}
1779
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01001780template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001781 typename HalOperation = typename HalPolicy::Operation,
1782 typename HalModel = typename HalPolicy::Model>
1783bool ConvertAdd(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01001784{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001785 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01001786
1787 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1788 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
1789
1790 if (!input0.IsValid() || !input1.IsValid())
1791 {
1792 return Fail("%s: Operation has invalid inputs", __func__);
1793 }
1794
1795 // The FuseActivation parameter is always the input index 2
1796 // and it should be optional
1797 ActivationFn activationFunction;
1798 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
1799 {
1800 return Fail("%s: Operation has invalid inputs", __func__);
1801 }
1802
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001803 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01001804 if (!outputOperand)
1805 {
1806 return false;
1807 }
1808
1809 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1810 const armnn::TensorInfo& inputInfo1 = input1.GetTensorInfo();
1811
1812 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
1813 if (IsDynamicTensor(outputInfo))
1814 {
1815 return Fail("%s: Dynamic output tensors are not supported", __func__);
1816 }
1817
1818 bool isSupported = false;
1819 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1820 IsAdditionSupported,
1821 data.m_Backends,
1822 isSupported,
1823 inputInfo0,
1824 inputInfo1,
1825 outputInfo);
1826 if (!isSupported)
1827 {
1828 return false;
1829 }
1830
1831 armnn::IConnectableLayer* const startLayer = data.m_Network->AddAdditionLayer();
1832 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
1833
1834 if (endLayer != nullptr)
1835 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00001836 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01001837 if (!isReshapeSupported)
1838 {
1839 return false;
1840 }
1841
Mike Kelly46272802019-08-14 17:00:48 +01001842 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
1843 }
1844 else
1845 {
1846 return Fail("%s: ProcessActivation failed", __func__);
1847 }
1848}
1849
1850template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001851 typename HalOperation = typename HalPolicy::Operation,
1852 typename HalModel = typename HalPolicy::Model>
1853bool ConvertArgMinMax(const HalOperation& operation,
1854 const HalModel& model,
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001855 ConversionData& data,
1856 armnn::ArgMinMaxFunction argMinMaxFunction)
1857{
1858 ALOGV("argMinMaxFunction = %s", GetArgMinMaxFunctionAsCString(argMinMaxFunction));
1859
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001860 using HalOperand = typename HalPolicy::Operand;
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001861 using HalOperandType = typename HalPolicy::OperandType;
1862
1863 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
1864
1865 if (!input0.IsValid())
1866 {
1867 return Fail("%s: Operation has invalid inputs", __func__);
1868 }
1869
1870 int32_t axis;
1871 if (!GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, axis, model, data))
1872 {
1873 return Fail("%s: Operation has invalid inputs. Failed to read axis.", __func__);
1874 }
1875
1876 const armnn::TensorInfo& inputInfo = input0.GetTensorInfo();
1877 int rank = static_cast<int>(inputInfo.GetNumDimensions());
1878
1879 if (((axis < -rank) && (axis < 0)) || ((axis >= rank) && (axis > 0)))
1880 {
1881 // Square bracket denotes inclusive n while parenthesis denotes exclusive n
1882 // E.g. Rank 4 tensor can have axis in range [-4, 3)
1883 // -1 == 3, -2 == 2, -3 == 1, -4 == 0
1884 return Fail("%s: Axis must be in range [-n, n)", __func__);
1885 }
1886
1887 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
1888 if (!output)
1889 {
1890 return Fail("%s: Could not read output 0", __func__);
1891 }
1892
1893 const armnn::TensorInfo& inputInfo0 = input0.GetTensorInfo();
1894
1895 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001896
1897 armnn::ArgMinMaxDescriptor descriptor;
1898 descriptor.m_Function = argMinMaxFunction;
1899 descriptor.m_Axis = axis;
1900
1901 bool isSupported = false;
Finn Williamsa4983ce2020-07-23 12:55:12 +01001902
1903 auto validateFunc = [&](const armnn::TensorInfo& outputInfo, bool& isSupported)
1904 {
1905 FORWARD_LAYER_SUPPORT_FUNC(__func__,
1906 IsArgMinMaxSupported,
1907 data.m_Backends,
1908 isSupported,
1909 inputInfo0,
1910 outputInfo,
1911 descriptor);
1912 };
1913
1914 if(IsDynamicTensor(outputInfo))
1915 {
1916 isSupported = AreDynamicTensorsSupported();
1917 }
1918 else
1919 {
1920 validateFunc(outputInfo, isSupported);
1921 }
1922
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001923 if (!isSupported)
1924 {
1925 return false;
1926 }
1927
1928 armnn::IConnectableLayer* layer = data.m_Network->AddArgMinMaxLayer(descriptor);
1929 assert(layer != nullptr);
1930
1931 input0.Connect(layer->GetInputSlot(0));
1932
Finn Williamsa4983ce2020-07-23 12:55:12 +01001933 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data, nullptr, validateFunc);
Francis Murtagh19fa0cc2019-11-19 12:06:47 +00001934}
1935
1936template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001937 typename HalOperation = typename HalPolicy::Operation,
1938 typename HalModel = typename HalPolicy::Model>
1939bool ConvertConcatenation(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kellyb8805202019-07-31 17:25:43 +01001940{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00001941 using HalOperand = typename HalPolicy::Operand;
Mike Kellyb8805202019-07-31 17:25:43 +01001942 using HalOperandType = typename HalPolicy::OperandType;
1943
1944 // The first N (0..N-1) inputs are tensors. The Nth input is the concatenation axis.
1945 if (operation.inputs.size() <= 1)
1946 {
1947 return Fail("%s: Operation has insufficient arguments", __func__);
1948 }
1949
1950 // Get inputs and outputs
1951 const std::size_t numInputTensors = operation.inputs.size() - 1;
1952
1953 int32_t concatDim;
1954 if (!GetInputScalar<HalPolicy>(operation, numInputTensors, HalOperandType::INT32, concatDim, model, data))
1955 {
1956 return Fail("%s: Operation has invalid inputs", __func__);
1957 }
1958
1959 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
1960 if (!outputOperand)
1961 {
1962 return Fail("%s: Operation has no outputs", __func__);
1963 }
1964
1965
1966 armnn::TensorInfo outputInfo = GetTensorInfoForOperand(*outputOperand);
1967 armnn::TensorShape outputShape = outputInfo.GetShape();
1968
1969 //
1970 // handle negative concat dims along the lines of tensorflow as described here:
1971 // https://www.tensorflow.org/api_docs/python/tf/concat
1972 // "negative axis refers to axis + rank(values)-th dimension"
1973 //
1974 if (concatDim < 0)
1975 {
1976 concatDim += outputShape.GetNumDimensions();
1977 }
1978
1979 if (concatDim >= static_cast<int32_t>(outputShape.GetNumDimensions()) || concatDim < 0)
1980 {
1981 return Fail("%s: Operation has invalid concat axis: %d", __func__, concatDim);
1982 }
1983
1984 std::vector<LayerInputHandle> inputHandles;
1985 std::vector<armnn::TensorShape> inputShapes;
1986
1987 inputHandles.reserve(numInputTensors);
1988 inputShapes.reserve(numInputTensors);
1989
1990 bool inputsHaveBeenReshaped = false;
1991 unsigned int tensorDimensionsAdded = 0;
1992
1993 for (uint32_t i = 0; i < numInputTensors; ++i)
1994 {
1995 const HalOperand* operand = GetInputOperand<HalPolicy>(operation, i, model);
1996 if (!operand)
1997 {
1998 return Fail("%s: Operation has invalid inputs", __func__);
1999 }
2000
Teresa Charlin3b959602019-10-31 17:05:47 +00002001 LayerInputHandle operandInputHandle = ConvertToLayerInputHandle<HalPolicy>(operation, i, model, data);
2002 if (!operandInputHandle.IsValid())
2003 {
2004 return Fail("%s: Operation has invalid inputs", __func__);
2005 }
Mike Kellyb8805202019-07-31 17:25:43 +01002006
Teresa Charlin3b959602019-10-31 17:05:47 +00002007 armnn::TensorShape operandShape = GetTensorShapeForOperand(*operand);
Mike Kellyb8805202019-07-31 17:25:43 +01002008 if (operandShape.GetNumDimensions() == 0)
2009 {
2010 return Fail("%s: Operands with rank 0 are not supported", __func__);
2011 }
2012
2013 if (RequiresReshape(operandShape))
2014 {
2015 inputsHaveBeenReshaped = true;
2016
2017 armnn::TensorInfo reshapeInfo = operandInputHandle.GetTensorInfo();
2018
2019 // Expand the tensor to three dimensions
2020 if (operandShape.GetNumDimensions() == 2)
2021 {
2022 reshapeInfo.SetShape(armnn::TensorShape({1, operandShape[0], operandShape[1]}));
2023 tensorDimensionsAdded = 1;
2024 }
2025 else
2026 {
2027 reshapeInfo.SetShape(armnn::TensorShape({1, 1, operandShape[0]}));
2028 tensorDimensionsAdded = 2;
2029 }
2030
Kevin Mayaed08ac2019-12-12 16:33:31 +00002031 armnn::ReshapeDescriptor reshapeDescriptor;
2032 reshapeDescriptor.m_TargetShape = reshapeInfo.GetShape();
2033
2034 bool isSupported = false;
2035 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2036 IsReshapeSupported,
2037 data.m_Backends,
2038 isSupported,
2039 operandInputHandle.GetTensorInfo(),
2040 reshapeInfo,
2041 reshapeDescriptor);
2042 if (!isSupported)
2043 {
2044 return false;
2045 }
2046
Mike Kellyb8805202019-07-31 17:25:43 +01002047 armnn::IConnectableLayer& newReshape = AddReshapeLayer(
2048 *data.m_Network,
2049 operandInputHandle,
2050 reshapeInfo
2051 );
2052
2053 // Point to the reshape operation rather then the input operation
2054 operandShape = reshapeInfo.GetShape();
2055 operandInputHandle = LayerInputHandle(true, &newReshape.GetOutputSlot(0), reshapeInfo);
2056 }
2057
2058 inputShapes.emplace_back(operandShape);
2059 inputHandles.emplace_back(operandInputHandle);
2060
2061 if (!inputHandles.back().IsValid())
2062 {
2063 return Fail("%s: Operation has invalid inputs", __func__);
2064 }
2065 }
2066
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002067 ARMNN_ASSERT(inputShapes.size() == inputHandles.size());
Mike Kellyb8805202019-07-31 17:25:43 +01002068
2069 if (inputsHaveBeenReshaped)
2070 {
2071 // Adjust the concatenation dimension by the amount of dimensions added (if any)
2072 concatDim += tensorDimensionsAdded;
2073
2074 // Add extra dimensions to the output shape to reflect the addition of the reshape layers
2075 if (tensorDimensionsAdded == 1)
2076 {
2077 outputShape = armnn::TensorShape({1, outputShape[0], outputShape[1]});
2078 }
2079 else if (tensorDimensionsAdded == 2)
2080 {
2081 outputShape = armnn::TensorShape({1, 1, outputShape[0]});
2082 }
2083 }
2084
2085 // Check if permutations is required and get the pair of permutations required for the concatenation.
2086 // Permutation is required when the concat dimension is 2 for a 4D tensor or 1 for a 3D tensor.
2087 std::pair<armnn::PermutationVector, armnn::PermutationVector> permutationPair =
2088 std::make_pair(IdentityPermutation4D, IdentityPermutation4D);
2089
2090 bool needPermute =
2091 CreateConcatPermutationParameters(inputShapes[0].GetNumDimensions(), concatDim, permutationPair);
2092
2093 if (needPermute)
2094 {
Mike Kelly4a956582020-02-28 10:32:09 +00002095 outputShape = armnnUtils::TransposeTensorShape(outputShape, permutationPair.first);
Mike Kellyb8805202019-07-31 17:25:43 +01002096 }
2097
2098 outputInfo.SetShape(outputShape);
2099
2100 // this is no-op for identity swizzles, otherwise it replaces both
2101 // the handles and shapes with the swizzled layer output handles and shapes
Teresa Charlin185f5882020-04-06 21:59:18 +01002102 if (!TransposeInputTensors(data, inputHandles, inputShapes, permutationPair.first))
Kevin Mayaed08ac2019-12-12 16:33:31 +00002103 {
2104 return false;
2105 }
Mike Kellyb8805202019-07-31 17:25:43 +01002106
2107 // Create an armnn concat layer descriptor - this will also perform validation on the input shapes
2108 armnn::OriginsDescriptor concatDescriptor;
2109
2110 try
2111 {
2112 // The concat descriptor is always created across the only supported concat dimension
2113 // which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
2114 concatDescriptor =
2115 armnn::CreateDescriptorForConcatenation(inputShapes.begin(), inputShapes.end(), concatDim);
2116 }
Derek Lambertib9cb8442019-11-28 13:34:48 +00002117 catch (std::exception& error)
Mike Kellyb8805202019-07-31 17:25:43 +01002118 {
2119 return Fail("%s: Error preparing concat descriptor. %s", __func__, error.what());
2120 }
2121
2122 // Validate the output shape is correct given the input shapes based on the
2123 // only valid concat dimension which is 0, 1 or 3 for a 4-D tensor, or 0 or 2 for a 3-D tensor.
2124 if (!ValidateConcatOutputShape(inputShapes, outputShape, concatDim))
2125 {
2126 return Fail("%s: Error validating the output shape for concat", __func__);
2127 }
2128
2129 std::vector<const armnn::TensorInfo*> inputTensorInfos;
2130 std::transform(inputHandles.begin(), inputHandles.end(), std::back_inserter(inputTensorInfos),
2131 [](const LayerInputHandle& h) -> const armnn::TensorInfo*{ return &h.GetTensorInfo(); });
2132
2133 bool isSupported = false;
2134 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2135 IsConcatSupported,
2136 data.m_Backends,
2137 isSupported,
2138 inputTensorInfos,
2139 outputInfo,
2140 concatDescriptor);
2141 if (!isSupported)
2142 {
2143 return false;
2144 }
2145
2146 armnn::IConnectableLayer* layer = data.m_Network->AddConcatLayer(concatDescriptor);
2147 assert(layer != nullptr);
2148 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
2149
2150 // Connect inputs to the layer
2151 const int numInputSlots = layer->GetNumInputSlots();
2152 assert(static_cast<std::size_t>(numInputSlots) == inputHandles.size());
2153 for (int i = 0; i < numInputSlots; ++i)
2154 {
2155 // connect the input directly to the merge (concat) layer
2156 inputHandles[static_cast<unsigned int>(i)].Connect(layer->GetInputSlot(i));
2157 }
2158
2159 if (needPermute)
2160 {
Mike Kelly4a956582020-02-28 10:32:09 +00002161 armnn::TransposeDescriptor transposeDesc;
2162 transposeDesc.m_DimMappings = permutationPair.second;
Teresa Charlin185f5882020-04-06 21:59:18 +01002163 armnn::TensorInfo inputTransposeInfo = layer->GetOutputSlot(0).GetTensorInfo();
2164 armnn::TensorInfo outputTransposeInfo = armnnUtils::TransposeTensorShape(inputTransposeInfo,
2165 permutationPair.second);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002166
2167 bool isSupported = false;
2168 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00002169 IsTransposeSupported,
Kevin Mayaed08ac2019-12-12 16:33:31 +00002170 data.m_Backends,
2171 isSupported,
Teresa Charlin185f5882020-04-06 21:59:18 +01002172 inputTransposeInfo,
2173 outputTransposeInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00002174 transposeDesc);
Kevin Mayaed08ac2019-12-12 16:33:31 +00002175 if (!isSupported)
2176 {
2177 return false;
2178 }
Mike Kellyb8805202019-07-31 17:25:43 +01002179 // Add permutation layer and connect the output to it, the permutation becomes the output layer
Mike Kelly4a956582020-02-28 10:32:09 +00002180 armnn::IConnectableLayer& deswizzleLayer = AddTransposeLayer(*data.m_Network,
2181 layer->GetOutputSlot(0),
2182 permutationPair.second);
Mike Kellyb8805202019-07-31 17:25:43 +01002183 layer = &deswizzleLayer;
2184 }
2185
2186 if (inputsHaveBeenReshaped)
2187 {
2188 armnn::TensorInfo afterConcatInfo = layer->GetOutputSlot(0).GetTensorInfo();
2189
2190 // Undo the reshape knowing the amount of dimensions added
2191 if (tensorDimensionsAdded == 1)
2192 {
2193 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[1],
2194 afterConcatInfo.GetShape()[2] }));
2195 }
2196 else if (tensorDimensionsAdded == 2)
2197 {
2198 afterConcatInfo.SetShape(armnn::TensorShape({ afterConcatInfo.GetShape()[2] }));
2199 }
2200
Kevin Mayaed08ac2019-12-12 16:33:31 +00002201 armnn::ReshapeDescriptor reshapeDescriptor;
2202 reshapeDescriptor.m_TargetShape = afterConcatInfo.GetShape();
2203
2204 bool isSupported = false;
2205 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2206 IsReshapeSupported,
2207 data.m_Backends,
2208 isSupported,
2209 layer->GetOutputSlot(0).GetTensorInfo(),
2210 afterConcatInfo,
2211 reshapeDescriptor);
2212 if (!isSupported)
2213 {
2214 return false;
2215 }
2216
Mike Kellyb8805202019-07-31 17:25:43 +01002217 layer = &AddReshapeLayer(
2218 *data.m_Network,
2219 layer->GetOutputSlot(0),
2220 afterConcatInfo
2221 );
2222 }
2223
2224 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2225}
2226
2227template<typename HalPolicy,
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002228 typename HalOperation = typename HalPolicy::Operation,
2229 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002230bool ConvertConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2231{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002232 using HalOperand = typename HalPolicy::Operand;
2233 using HalOperandType = typename HalPolicy::OperandType;
2234
2235 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002236 if (!input.IsValid())
2237 {
2238 return Fail("%s: Operation has invalid inputs", __func__);
2239 }
2240
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002241 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002242 if (!output)
2243 {
2244 return Fail("%s: Could not read output 0", __func__);
2245 }
2246
2247 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002248 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002249
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002250 if (IsDynamicTensor(outputInfo))
2251 {
2252 return Fail("%s: Dynamic output tensors are not supported", __func__);
2253 }
2254
Mike Kellyb5fdf382019-06-11 16:35:25 +01002255 // ArmNN does not currently support non-fixed weights or bias
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002256 const ConstTensorPin weightsPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 1, model, data);
2257 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002258
2259 if (!weightsPin.IsValid() || !biasPin.IsValid())
2260 {
2261 return Fail("%s: Operation has invalid inputs", __func__);
2262 }
2263
2264 armnn::ConstTensor weights = weightsPin.GetConstTensor();
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002265 armnn::ConstTensor bias = biasPin.GetConstTensor();
Mike Kellyb5fdf382019-06-11 16:35:25 +01002266 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2267
2268 armnn::Convolution2dDescriptor desc;
2269 desc.m_DataLayout = armnn::DataLayout::NHWC;
2270 ActivationFn activation;
2271
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002272 if (operation.inputs.size() == 10)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002273 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002274 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2275 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2276 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2277 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2278 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2279 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002280 !GetInputActivationFunction<HalPolicy>(operation, 9, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002281 {
2282 return Fail("%s: Operation has invalid inputs", __func__);
2283 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002284 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002285 else if (operation.inputs.size() == 7)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002286 {
2287 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002288 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2289 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2290 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002291 !GetInputActivationFunction<HalPolicy>(operation, 6, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002292 {
2293 return Fail("%s: Operation has invalid inputs", __func__);
2294 }
2295
2296 const uint32_t kernelX = weights.GetShape()[2];
2297 const uint32_t kernelY = weights.GetShape()[1];
2298 const uint32_t inputX = inputInfo.GetShape()[2];
2299 const uint32_t inputY = inputInfo.GetShape()[1];
2300
2301 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2302 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002303 }
2304 else
2305 {
2306 return Fail("%s: Unsupported number of operation inputs", __func__);
2307 }
2308
2309 desc.m_BiasEnabled = true;
2310 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2311
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002312 bool isSupported = false;
2313 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2314 IsConvolution2dSupported,
2315 data.m_Backends,
2316 isSupported,
2317 inputInfo,
2318 outputInfo,
2319 desc,
2320 weights.GetInfo(),
2321 biases);
2322 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002323 {
2324 return false;
2325 }
2326
2327 armnn::IConnectableLayer* startLayer =
2328 data.m_Network->AddConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2329
2330 if (!startLayer)
2331 {
2332 return Fail("%s: AddConvolution2dLayer failed", __func__);
2333 }
2334
2335 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2336
2337 if (!endLayer)
2338 {
2339 return Fail("%s: ProcessActivation failed", __func__);
2340 }
2341
2342 input.Connect(startLayer->GetInputSlot(0));
2343
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002344 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002345}
2346
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002347template<typename HalPolicy,
2348 typename HalOperation = typename HalPolicy::Operation,
2349 typename HalModel = typename HalPolicy::Model>
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002350bool ConvertDepthToSpace(const HalOperation& operation, const HalModel& model, ConversionData& data)
2351{
2352 using HalOperand = typename HalPolicy::Operand;
2353 using HalOperandType = typename HalPolicy::OperandType;
2354
2355 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2356 if (!input.IsValid() )
2357 {
2358 return Fail("%s: Operation has invalid inputs", __func__);
2359 }
2360
2361 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2362 unsigned int rank = inputInfo.GetNumDimensions();
2363 if (rank != 4)
2364 {
2365 return Fail("%s: Only inputs with rank 4 are supported", __func__);
2366 }
2367
2368 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
2369 if (!output)
2370 {
2371 return Fail("%s: Could not read output 0", __func__);
2372 }
2373
2374 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2375 if (IsDynamicTensor(outputInfo))
2376 {
2377 return Fail("%s: Dynamic output tensors are not supported", __func__);
2378 }
2379
2380 armnn::DepthToSpaceDescriptor descriptor;
2381
2382 GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_BlockSize, model, data);
2383 if (descriptor.m_BlockSize <= 1)
2384 {
2385 return Fail("%s: Block size must be at least 1 in all dimensions");
2386 }
2387
2388 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
Kevin May42477c12020-03-26 13:34:14 +00002389 if (Is12OrLaterOperand(*output))
Aron Virginas-Tar8edb16d2019-10-01 13:34:59 +01002390 {
2391 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
2392 }
2393
2394 bool isSupported = false;
2395 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2396 IsDepthToSpaceSupported,
2397 data.m_Backends,
2398 isSupported,
2399 inputInfo,
2400 outputInfo,
2401 descriptor);
2402 if (!isSupported)
2403 {
2404 return false;
2405 }
2406
2407 armnn::IConnectableLayer* const layer = data.m_Network->AddDepthToSpaceLayer(descriptor);
2408 assert(layer != nullptr);
2409 input.Connect(layer->GetInputSlot(0));
2410
2411 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2412}
2413
2414template<typename HalPolicy,
2415 typename HalOperation = typename HalPolicy::Operation,
2416 typename HalModel = typename HalPolicy::Model>
Mike Kellyb5fdf382019-06-11 16:35:25 +01002417bool ConvertDepthwiseConv2d(const HalOperation& operation, const HalModel& model, ConversionData& data)
2418{
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002419 using HalOperand = typename HalPolicy::Operand;
2420 using HalOperandType = typename HalPolicy::OperandType;
2421
2422 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002423
2424 if (!input.IsValid())
2425 {
2426 return Fail("%s: Operation has invalid inputs", __func__);
2427 }
2428
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002429 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002430
2431 if (!output)
2432 {
2433 return Fail("%s: Could not read output 0", __func__);
2434 }
2435
2436 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002437 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002438
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002439 if (IsDynamicTensor(outputInfo))
2440 {
2441 return Fail("%s: Dynamic output tensors are not supported", __func__);
2442 }
Mike Kellyb5fdf382019-06-11 16:35:25 +01002443
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002444 // ArmNN does not currently support non-fixed weights or bias
Mike Kellyb5fdf382019-06-11 16:35:25 +01002445 // 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 +01002446 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002447
2448 if (weightsOperand == nullptr)
2449 {
2450 return Fail("%s: Operand is invalid", __func__);
2451 }
2452 armnn::DepthwiseConvolution2dDescriptor desc;
2453 desc.m_DataLayout = armnn::DataLayout::NHWC;
2454
Mike Kellyb5fdf382019-06-11 16:35:25 +01002455 // Reinterpret weight data as [ H, W, I, M ]
2456 armnn::TensorShape weightsShape({ weightsOperand->dimensions[1],
2457 weightsOperand->dimensions[2],
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002458 inputInfo.GetShape()[3],
2459 weightsOperand->dimensions[3] / inputInfo.GetShape()[3] });
Mike Kellyb5fdf382019-06-11 16:35:25 +01002460
2461 // Swizzle weight data [ H, W, I, M ] -> [ M, I, H, W ]
2462 const armnn::PermutationVector HWIMToMIHW = { 2U, 3U, 1U, 0U };
2463
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002464 const ConstTensorPin weightsPin =
2465 ConvertOperationInputToConstTensorPin<HalPolicy>(operation,
2466 1,
2467 model,
2468 data,
2469 HWIMToMIHW,
2470 &weightsShape);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002471
2472 // Bias is a 1D tensor
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002473 const ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data);
Mike Kellyb5fdf382019-06-11 16:35:25 +01002474
2475 if (!weightsPin.IsValid() || !biasPin.IsValid())
2476 {
2477 return Fail("%s: Operation has invalid inputs", __func__);
2478 }
2479
2480 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2481 armnn::ConstTensor bias = biasPin.GetConstTensor();
2482 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), inputInfo);
2483
2484 ActivationFn activation;
2485
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002486 if (operation.inputs.size() == 11)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002487 {
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002488 if (!GetInputScalar<HalPolicy>(operation, 3, HalOperandType::INT32, desc.m_PadLeft, model, data) ||
2489 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_PadRight, model, data) ||
2490 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_PadTop, model, data) ||
2491 !GetInputScalar<HalPolicy>(operation, 6, HalOperandType::INT32, desc.m_PadBottom, model, data) ||
2492 !GetInputScalar<HalPolicy>(operation, 7, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2493 !GetInputScalar<HalPolicy>(operation, 8, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002494 !GetInputActivationFunction<HalPolicy>(operation, 10, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002495 {
2496 return Fail("%s: Operation has invalid inputs", __func__);
2497 }
2498 }
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002499 else if (operation.inputs.size() == 8)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002500 {
2501 android::nn::PaddingScheme paddingScheme;
Aron Virginas-Tarcd700e42019-06-14 14:54:52 +01002502 if (!GetInputPaddingScheme<HalPolicy>(operation, 3, paddingScheme, model, data) ||
2503 !GetInputScalar<HalPolicy>(operation, 4, HalOperandType::INT32, desc.m_StrideX, model, data) ||
2504 !GetInputScalar<HalPolicy>(operation, 5, HalOperandType::INT32, desc.m_StrideY, model, data) ||
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002505 !GetInputActivationFunction<HalPolicy>(operation, 7, activation, model, data))
Mike Kellyb5fdf382019-06-11 16:35:25 +01002506 {
2507 return Fail("%s: Operation has invalid inputs", __func__);
2508 }
2509
2510 const uint32_t kernelX = weights.GetShape()[3];
2511 const uint32_t kernelY = weights.GetShape()[2];
Aron Virginas-Tara5e2a452019-07-29 16:13:19 +01002512 const uint32_t inputX = inputInfo.GetShape()[2];
2513 const uint32_t inputY = inputInfo.GetShape()[1];
Mike Kellyb5fdf382019-06-11 16:35:25 +01002514
2515 CalcPadding(inputX, kernelX, desc.m_StrideX, desc.m_PadLeft, desc.m_PadRight, paddingScheme);
2516 CalcPadding(inputY, kernelY, desc.m_StrideY, desc.m_PadTop, desc.m_PadBottom, paddingScheme);
2517 }
2518 else
2519 {
2520 return Fail("%s: Unsupported number of operation inputs", __func__);
2521 }
2522
2523 desc.m_BiasEnabled = true;
2524 armnn::Optional<armnn::TensorInfo> biases(bias.GetInfo());
2525
Ferran Balaguerd30093c2019-07-09 17:04:47 +01002526 bool isSupported = false;
2527 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2528 IsDepthwiseConvolutionSupported,
2529 data.m_Backends,
2530 isSupported,
2531 inputInfo,
2532 outputInfo,
2533 desc,
2534 weights.GetInfo(),
2535 biases);
2536 if (!isSupported)
Mike Kellyb5fdf382019-06-11 16:35:25 +01002537 {
2538 return false;
2539 }
2540
2541 armnn::IConnectableLayer* startLayer =
2542 data.m_Network->AddDepthwiseConvolution2dLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2543 if (!startLayer)
2544 {
2545 return Fail("%s: AddDepthwiseConvolution2dLayer failed", __func__);
2546 }
2547
2548 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activation, startLayer, data);
2549 if (!endLayer)
2550 {
2551 return Fail("%s: ProcessActivation failed", __func__);
2552 }
2553
2554 input.Connect(startLayer->GetInputSlot(0));
2555
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01002556 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
arovir01b0717b52018-09-05 17:03:25 +01002557}
2558
Mike Kelly3c673942019-07-25 09:26:06 +01002559template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002560 typename HalOperation = typename HalPolicy::Operation,
2561 typename HalModel = typename HalPolicy::Model>
2562bool ConvertDequantize(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly3c673942019-07-25 09:26:06 +01002563{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002564 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002565
2566 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2567 if (!input.IsValid())
2568 {
2569 return Fail("%s: Operation has invalid input", __func__);
2570 }
2571
Sadik Armagan98c0f662019-11-21 15:54:36 +00002572 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2573 const armnn::Optional<unsigned int>& quantizationDim = inputInfo.GetQuantizationDim();
2574 if (quantizationDim.has_value() && quantizationDim.value() != 0)
2575 {
2576 return Fail("%s: Operation has quantization dimension different than 0", __func__);
2577 }
2578
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002579 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002580 if (!outputOperand)
2581 {
2582 return Fail("%s: Operation has invalid outputs", __func__);
2583 }
2584
2585 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2586 if (IsDynamicTensor(outputInfo))
2587 {
2588 return Fail("%s: Dynamic output tensors are not supported", __func__);
2589 }
2590
2591 bool isSupported = false;
2592 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2593 IsDequantizeSupported,
2594 data.m_Backends,
2595 isSupported,
Sadik Armagan98c0f662019-11-21 15:54:36 +00002596 inputInfo,
2597 outputInfo);
Mike Kelly46272802019-08-14 17:00:48 +01002598 if (!isSupported)
2599 {
2600 return false;
2601 }
2602
2603 armnn::IConnectableLayer* const layer = data.m_Network->AddDequantizeLayer();
2604 assert(layer != nullptr);
2605 input.Connect(layer->GetInputSlot(0));
2606
2607 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2608}
2609
2610template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002611 typename HalOperation = typename HalPolicy::Operation,
2612 typename HalModel = typename HalPolicy::Model>
2613bool ConvertDiv(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002614{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002615 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01002616
2617 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2618 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
2619
2620 if (!input0.IsValid() || !input1.IsValid())
2621 {
2622 return Fail("%s: Operation has invalid inputs", __func__);
2623 }
2624
2625 // The FuseActivation parameter is always the input index 2
2626 // and it should be optional
2627 ActivationFn activationFunction;
2628 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
2629 {
2630 return Fail("%s: Operation has invalid inputs", __func__);
2631 }
2632
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002633 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002634 if (!output)
2635 {
2636 return Fail("%s: Could not read output 0", __func__);
2637 }
2638
2639 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2640 if (IsDynamicTensor(outputInfo))
2641 {
2642 return Fail("%s: Dynamic output tensors are not supported", __func__);
2643 }
2644
2645 bool isSupported = false;
2646 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2647 IsDivisionSupported,
2648 data.m_Backends,
2649 isSupported,
2650 input0.GetTensorInfo(),
2651 input1.GetTensorInfo(),
2652 outputInfo);
2653 if (!isSupported)
2654 {
2655 return false;
2656 }
2657
2658 armnn::IConnectableLayer* const startLayer = data.m_Network->AddDivisionLayer();
2659 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2660
2661 if (endLayer)
2662 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00002663 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01002664 if (!isReshapeSupported)
2665 {
2666 return false;
2667 }
2668
Mike Kelly46272802019-08-14 17:00:48 +01002669 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2670 }
2671 return Fail("%s: ProcessActivation failed", __func__);
2672}
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 ConvertFloor(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 input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2682 if (!input.IsValid())
2683 {
2684 return Fail("%s: Operation has invalid inputs", __func__);
2685 }
2686
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002687 const HalOperand* const outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002688 if (!outputOperand)
2689 {
2690 return Fail("%s: Operation has invalid outputs", __func__);
2691 }
2692
2693 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
2694 if (IsDynamicTensor(outputInfo))
2695 {
2696 return Fail("%s: Dynamic output tensors are not supported", __func__);
2697 }
2698
2699 bool isSupported = false;
2700 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2701 IsFloorSupported,
2702 data.m_Backends,
2703 isSupported,
2704 input.GetTensorInfo(),
2705 outputInfo);
2706 if (!isSupported)
2707 {
2708 return false;
2709 }
2710
2711 armnn::IConnectableLayer* layer = data.m_Network->AddFloorLayer();
2712 assert(layer != nullptr);
2713 input.Connect(layer->GetInputSlot(0));
2714
2715 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
2716}
2717
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002718inline bool IsQSymm8(const V1_0::Operand&)
2719{
2720 return false;
2721}
2722
Kevin May42477c12020-03-26 13:34:14 +00002723#if defined(ARMNN_ANDROID_NN_V1_2) || defined(ARMNN_ANDROID_NN_V1_3)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002724
2725inline bool IsQSymm8(const V1_2::Operand& operand)
2726{
2727 return operand.type == V1_2::OperandType::TENSOR_QUANT8_SYMM;
2728}
2729
2730#endif
2731
Kevin May42477c12020-03-26 13:34:14 +00002732#ifdef ARMNN_ANDROID_NN_V1_3
2733
2734inline bool IsQSymm8(const V1_3::Operand& operand)
2735{
2736 return operand.type == V1_3::OperandType::TENSOR_QUANT8_SYMM;
2737}
2738
2739#endif
2740
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002741enum class DequantizeStatus
2742{
2743 SUCCESS,
2744 NOT_REQUIRED,
2745 INVALID_OPERAND
2746};
2747
2748using DequantizeResult = std::tuple<std::unique_ptr<float[]>, size_t, armnn::TensorInfo, DequantizeStatus>;
2749
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002750template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002751 typename HalOperation = typename HalPolicy::Operation,
2752 typename HalModel = typename HalPolicy::Model>
2753DequantizeResult DequantizeIfRequired(size_t operand_index,
2754 const HalOperation& operation,
2755 const HalModel& model,
2756 const ConversionData& data)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002757{
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002758 using HalOperand = typename HalPolicy::Operand;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002759
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002760 const HalOperand* weightsOperand = GetInputOperand<HalPolicy>(operation, operand_index, model);
Sadik Armagand0811942019-11-18 17:11:21 +00002761 if (!weightsOperand)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002762 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002763 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::INVALID_OPERAND };
Sadik Armagand0811942019-11-18 17:11:21 +00002764 }
2765
2766 if (IsOperandConstant<HalPolicy>(*weightsOperand))
2767 {
2768 // Weights are already constant
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002769 return { nullptr, 0, armnn::TensorInfo(), DequantizeStatus::NOT_REQUIRED };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002770 }
2771
2772 const size_t weightsInputIndex = operation.inputs[operand_index];
2773
2774 // The weights are a non const tensor, this indicates they might be the output of a dequantize op.
2775 // Iterate over the nodes and find the previous operation which should be DEQUANTIZE
Kevin May42477c12020-03-26 13:34:14 +00002776 for (uint32_t operationIdx = 0; operationIdx < getMainModel(model).operations.size(); ++operationIdx)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002777 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002778 // Search for the DEQUANTIZE op which has the operand with index equal to operandIndex
Kevin May42477c12020-03-26 13:34:14 +00002779 const auto& operationIt = getMainModel(model).operations[operationIdx];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002780 if (operationIt.type != HalPolicy::OperationType::DEQUANTIZE)
2781 {
2782 continue;
2783 }
2784
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002785 size_t outOpIndex = weightsInputIndex + 1;
2786 for (size_t i = 0; outOpIndex != weightsInputIndex && i < operationIt.outputs.size(); ++i)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002787 {
2788 outOpIndex = operationIt.outputs[i];
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002789 }
2790
2791 if (outOpIndex != weightsInputIndex)
2792 {
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002793 continue;
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002794 }
2795
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002796 const HalOperand* operand = GetInputOperand<HalPolicy>(operationIt, 0, model);
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002797 ARMNN_ASSERT(operand);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002798
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002799 if (!IsQSymm8(*operand))
2800 {
2801 // Only supporting dequantize from QSYMM8 to FLOAT
2802 break;
2803 }
2804
2805 // Allocate a new buffer for the dequantized data and manually dequantize
2806 const void* startValue = GetOperandValueReadOnlyAddress<HalPolicy>(*operand, model, data);
2807 if (!startValue)
2808 {
2809 // Failed to get the operand address
2810 break;
2811 }
2812
2813 const uint8_t* quantizedBuffer = reinterpret_cast<const uint8_t*>(startValue);
2814 size_t dequantizedBufferLength = operand->location.length;
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002815 const float quantizationScale = operand->scale;
2816
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002817 auto dequantizedBuffer = std::make_unique<float[]>(dequantizedBufferLength + 1);
2818 for (size_t i = 0; i < dequantizedBufferLength; ++i)
2819 {
2820 float* dstPtr = dequantizedBuffer.get();
Narumol Prangnawarat4d07e5e2020-04-06 16:46:21 +01002821 ARMNN_ASSERT(dstPtr);
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002822 *dstPtr++ = quantizedBuffer[i] * quantizationScale;
2823 }
2824
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002825 // Construct tensor info for dequantized ConstTensor
2826 armnn::TensorInfo tensorInfo(operand->dimensions.size(),
2827 operand->dimensions.data(),
2828 armnn::DataType::Float32);
2829
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002830 return { std::move(dequantizedBuffer), dequantizedBufferLength * sizeof(float),
2831 std::move(tensorInfo),
2832 DequantizeStatus::SUCCESS };
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002833 }
2834
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002835 return { nullptr, 0, armnn::TensorInfo() , DequantizeStatus::NOT_REQUIRED};
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002836}
2837
2838template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002839 typename HalOperation = typename HalPolicy::Operation,
2840 typename HalModel = typename HalPolicy::Model>
2841ConstTensorPin DequantizeAndMakeConstTensorPin(const HalOperation& operation,
2842 const HalModel& model,
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002843 const ConversionData& data,
2844 size_t operandIndex,
2845 bool optional = false)
2846{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002847 DequantizeResult dequantized = DequantizeIfRequired<HalPolicy>(operandIndex,operation, model, data);
2848
2849 DequantizeStatus status = std::get<3>(dequantized);
2850 switch (status)
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002851 {
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002852 case DequantizeStatus::INVALID_OPERAND:
2853 {
2854 // return invalid const tensor pin
2855 return ConstTensorPin();
2856 }
2857 case DequantizeStatus::NOT_REQUIRED:
2858 {
2859 return ConvertOperationInputToConstTensorPin<HalPolicy>(
2860 operation, operandIndex, model, data, g_DontPermute, nullptr, optional);
2861 }
2862 case DequantizeStatus::SUCCESS:
2863 default:
2864 {
2865 return ConstTensorPin(
2866 std::get<2>(dequantized), std::get<0>(dequantized).get(), std::get<1>(dequantized), g_DontPermute);
2867 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002868 }
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002869}
2870
2871
Mike Kelly46272802019-08-14 17:00:48 +01002872template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002873 typename HalOperation = typename HalPolicy::Operation,
2874 typename HalModel = typename HalPolicy::Model>
2875bool ConvertFullyConnected(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002876{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002877 using HalOperand = typename HalPolicy::Operand;
2878
Mike Kelly46272802019-08-14 17:00:48 +01002879 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
2880 if (!input.IsValid())
2881 {
2882 return Fail("%s: Operation has invalid inputs", __func__);
2883 }
2884
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002885 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01002886 if (!output)
2887 {
2888 return Fail("%s: Could not read output 0", __func__);
2889 }
2890
2891 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
2892 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
2893
2894 if (IsDynamicTensor(outputInfo))
2895 {
2896 return Fail("%s: Dynamic output tensors are not supported", __func__);
2897 }
2898
Aron Virginas-Tar65a1b1d2019-11-15 15:59:51 +00002899 ConstTensorPin weightsPin = DequantizeAndMakeConstTensorPin<HalPolicy>(operation, model, data, 1);
2900 ConstTensorPin biasPin = ConvertOperationInputToConstTensorPin<HalPolicy>(operation, 2, model, data); // 1D
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002901
2902 if (!weightsPin.IsValid())
Mike Kelly46272802019-08-14 17:00:48 +01002903 {
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002904 return Fail("%s: Operation has invalid weights", __func__);
2905 }
2906
2907 if (!biasPin.IsValid())
2908 {
2909 return Fail("%s: Operation has invalid bias", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01002910 }
2911
2912 armnn::ConstTensor weights = weightsPin.GetConstTensor();
2913 armnn::ConstTensor bias = biasPin.GetConstTensor();
2914 armnn::TensorInfo reshapedInfo = inputInfo;
2915
2916 try
2917 {
2918 reshapedInfo.SetShape(FlattenFullyConnectedInput(inputInfo.GetShape(), weights.GetInfo().GetShape()));
Pablo Tellofb45e2f2019-10-18 16:51:57 +01002919 }
2920 catch (const std::exception& e)
2921 {
Mike Kelly46272802019-08-14 17:00:48 +01002922 return Fail("%s: %s", __func__, e.what());
2923 }
2924
2925 // ensuring that the bias value is within 1% of the weights input (small float differences can exist)
2926 SanitizeBiasQuantizationScale(bias.GetInfo(), weights.GetInfo(), reshapedInfo);
2927
2928 ActivationFn activationFunction;
2929 if (!GetInputActivationFunction<HalPolicy>(operation, 3, activationFunction, model, data))
2930 {
2931 return Fail("%s: Operation has invalid inputs", __func__);
2932 }
2933
2934 armnn::FullyConnectedDescriptor desc;
2935 desc.m_TransposeWeightMatrix = true;
2936 desc.m_BiasEnabled = true;
2937
FinnWilliamsArm7b8d2e62020-01-08 14:57:47 +00002938 if (!VerifyFullyConnectedShapes(reshapedInfo.GetShape(),
2939 weights.GetInfo().GetShape(),
2940 outputInfo.GetShape(),
2941 desc.m_TransposeWeightMatrix))
2942 {
2943 return Fail("%s: Expected outputShape does not match actual outputShape", __func__);
2944 }
2945
Mike Kelly46272802019-08-14 17:00:48 +01002946 bool isSupported = false;
2947 FORWARD_LAYER_SUPPORT_FUNC(__func__,
2948 IsFullyConnectedSupported,
2949 data.m_Backends,
2950 isSupported,
2951 reshapedInfo,
2952 outputInfo,
2953 weights.GetInfo(),
2954 bias.GetInfo(),
2955 desc);
2956 if (!isSupported)
2957 {
2958 return false;
2959 }
2960
2961 armnn::IConnectableLayer* startLayer =
2962 data.m_Network->AddFullyConnectedLayer(desc, weights, armnn::Optional<armnn::ConstTensor>(bias));
2963 armnn::IConnectableLayer* endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
2964
2965 if (endLayer != nullptr)
2966 {
2967 if (inputInfo.GetNumDimensions() > 2U)
2968 {
2969 armnn::ReshapeDescriptor reshapeDescriptor;
2970 reshapeDescriptor.m_TargetShape = reshapedInfo.GetShape();
2971
2972 armnn::IConnectableLayer* reshapeLayer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
2973 assert(reshapeLayer != nullptr);
2974 input.Connect(reshapeLayer->GetInputSlot(0));
2975 reshapeLayer->GetOutputSlot(0).SetTensorInfo(reshapedInfo);
2976 reshapeLayer->GetOutputSlot(0).Connect(startLayer->GetInputSlot(0));
2977 }
2978 else
2979 {
2980 input.Connect(startLayer->GetInputSlot(0));
2981 }
2982
2983 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
2984 }
2985 else
2986 {
2987 return Fail("%s: ProcessActivation failed", __func__);
2988 }
2989}
2990
2991template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002992 typename HalOperation = typename HalPolicy::Operation,
2993 typename HalModel = typename HalPolicy::Model>
2994bool ConvertL2Normalization(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01002995{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00002996 using HalOperand = typename HalPolicy::Operand;
2997
Mike Kelly999e2092019-08-15 10:46:46 +01002998 if (operation.inputs.size() != 1)
2999 {
3000 return Fail("%s: Optional inputs are not supported", __func__);
3001 }
3002
Mike Kelly46272802019-08-14 17:00:48 +01003003 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3004 if (!input.IsValid())
3005 {
3006 return Fail("%s: Operation has invalid inputs", __func__);
3007 }
3008
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003009 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003010 if (!output)
3011 {
3012 return Fail("%s: Could not read output 0", __func__);
3013 }
3014
3015 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3016 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3017
3018 if (IsDynamicTensor(outputInfo))
3019 {
3020 return Fail("%s: Dynamic output tensors are not supported", __func__);
3021 }
3022 if (outputInfo.GetNumDimensions() != 4u)
3023 {
3024 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3025 }
3026
3027 armnn::L2NormalizationDescriptor desc;
3028 desc.m_DataLayout = armnn::DataLayout::NHWC;
3029
3030 bool isSupported = false;
3031 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3032 IsL2NormalizationSupported,
3033 data.m_Backends,
3034 isSupported,
3035 inputInfo,
3036 outputInfo,
3037 desc);
3038 if (!isSupported)
3039 {
3040 return false;
3041 }
3042
3043 armnn::IConnectableLayer* layer = data.m_Network->AddL2NormalizationLayer(desc);
3044 assert(layer != nullptr);
3045 input.Connect(layer->GetInputSlot(0));
3046
3047 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3048}
3049
3050template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003051 typename HalOperation = typename HalPolicy::Operation,
3052 typename HalModel = typename HalPolicy::Model>
3053bool ConvertLocalResponseNormalization(const HalOperation& operation,
3054 const HalModel& model,
Mike Kelly46272802019-08-14 17:00:48 +01003055 ConversionData& data)
3056{
Mike Kelly999e2092019-08-15 10:46:46 +01003057 if (operation.inputs.size() != 5)
3058 {
3059 return Fail("%s: Optional inputs are not supported", __func__);
3060 }
3061
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003062 using HalOperand = typename HalPolicy::Operand;
3063 using HalOperandType = typename HalPolicy::OperandType;
Mike Kelly46272802019-08-14 17:00:48 +01003064
3065 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3066 if (!input.IsValid())
3067 {
3068 return Fail("%s: Operation has invalid inputs", __func__);
3069 }
3070
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003071 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003072 if (!output)
3073 {
3074 return Fail("%s: Could not read output 0", __func__);
3075 }
3076
3077 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3078 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3079
3080 if (IsDynamicTensor(outputInfo))
3081 {
3082 return Fail("%s: Dynamic output tensors are not supported", __func__);
3083 }
3084 if (outputInfo.GetNumDimensions() != 4u)
3085 {
3086 return Fail("%s: Tensor Rank other than 4 is not supported", __func__);
3087 }
3088
3089 armnn::NormalizationDescriptor descriptor;
3090 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3091 descriptor.m_NormChannelType = armnn::NormalizationAlgorithmChannel::Across;
3092 descriptor.m_NormMethodType = armnn::NormalizationAlgorithmMethod::LocalBrightness;
3093
3094 if (!input.IsValid() ||
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003095 !GetInputScalar<HalPolicy>(operation, 1, HalOperandType::INT32, descriptor.m_NormSize, model, data) ||
Mike Kelly46272802019-08-14 17:00:48 +01003096 !GetInputFloat32<HalPolicy>(operation, 2, descriptor.m_K, model, data) ||
3097 !GetInputFloat32<HalPolicy>(operation, 3, descriptor.m_Alpha, model, data) ||
3098 !GetInputFloat32<HalPolicy>(operation, 4, descriptor.m_Beta, model, data))
3099 {
3100 return Fail("%s: Operation has invalid inputs", __func__);
3101 }
3102
3103 // ArmNN expects normSize to be the full size of the normalization
3104 // window rather than the radius as in AndroidNN.
3105 descriptor.m_NormSize = 1 + (2 * descriptor.m_NormSize);
3106
3107 bool isSupported = false;
3108 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3109 IsNormalizationSupported,
3110 data.m_Backends,
3111 isSupported,
3112 inputInfo,
3113 outputInfo,
3114 descriptor);
3115 if (!isSupported)
3116 {
3117 return false;
3118 }
3119
3120
3121 armnn::IConnectableLayer* layer = data.m_Network->AddNormalizationLayer(descriptor);
3122 assert(layer != nullptr);
3123 input.Connect(layer->GetInputSlot(0));
3124
3125 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3126}
3127
3128template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003129 typename HalOperation = typename HalPolicy::Operation,
3130 typename HalModel = typename HalPolicy::Model>
3131bool ConvertLogistic(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003132{
Mike Kelly46272802019-08-14 17:00:48 +01003133 armnn::ActivationDescriptor desc;
3134 desc.m_Function = armnn::ActivationFunction::Sigmoid;
3135
3136 return ConvertToActivation<HalPolicy>(operation, __func__, desc, model, data);
3137}
3138
3139template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003140 typename HalOperation = typename HalPolicy::Operation,
3141 typename HalModel = typename HalPolicy::Model>
3142bool ConvertMean(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003143{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003144 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003145
3146 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3147 if (!input.IsValid())
3148 {
3149 return Fail("%s: Operation has invalid inputs", __func__);
3150 }
3151
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003152 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003153 if (!output)
3154 {
3155 return Fail("%s: Could not read output 0", __func__);
3156 }
3157
3158 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3159 if (IsDynamicTensor(outputInfo))
3160 {
3161 return Fail("%s: Dynamic output tensors are not supported", __func__);
3162 }
3163
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003164 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model);
Mike Kelly46272802019-08-14 17:00:48 +01003165 if (!axisOperand)
3166 {
3167 return Fail("%s: Could not read input 1", __func__);
3168 }
3169
3170 std::vector<int32_t> axis;
3171 if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
3172 {
3173 return Fail("%s: Input 1 has invalid values", __func__);
3174 }
3175
3176 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3177
3178 // Convert the axis to unsigned int and remove duplicates.
3179 unsigned int rank = inputInfo.GetNumDimensions();
3180 std::set<unsigned int> uniqueAxis;
3181 std::transform(axis.begin(), axis.end(),
3182 std::inserter(uniqueAxis, uniqueAxis.begin()),
3183 [rank](int i) -> unsigned int { return (i + rank) % rank; });
3184
3185 // Get the "keep dims" flag.
3186 int32_t keepDims = 0;
3187 if (!GetInputInt32<HalPolicy>(operation, 2, keepDims, model, data))
3188 {
3189 return Fail("%s: Could not read input 2", __func__);
3190 }
3191
3192 armnn::MeanDescriptor descriptor;
3193 descriptor.m_Axis.assign(uniqueAxis.begin(), uniqueAxis.end());
3194 descriptor.m_KeepDims = keepDims > 0;
3195
3196 bool isSupported = false;
3197 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3198 IsMeanSupported,
3199 data.m_Backends,
3200 isSupported,
3201 inputInfo,
3202 outputInfo,
3203 descriptor);
3204 if (!isSupported)
3205 {
3206 return false;
3207 }
3208
3209 armnn::IConnectableLayer* const layer = data.m_Network->AddMeanLayer(descriptor);
3210 assert(layer != nullptr);
3211 input.Connect(layer->GetInputSlot(0));
3212
3213 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3214}
3215
3216template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003217 typename HalOperation = typename HalPolicy::Operation,
3218 typename HalModel = typename HalPolicy::Model>
3219bool ConvertMul(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003220{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003221 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003222
3223 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3224 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3225
3226 if (!input0.IsValid() || !input1.IsValid())
3227 {
3228 return Fail("%s: Operation has invalid inputs", __func__);
3229 }
3230
3231 // The FuseActivation parameter is always the input index 2
3232 // and it should be optional
3233 ActivationFn activationFunction;
3234 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3235 {
3236 return Fail("%s: Operation has invalid inputs", __func__);
3237 }
3238
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003239 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003240
3241 if (outputOperand == nullptr)
3242 {
3243 return false;
3244 }
3245
3246 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*outputOperand);
3247 if (IsDynamicTensor(outputInfo))
3248 {
3249 return Fail("%s: Dynamic output tensors are not supported", __func__);
3250 }
3251
3252 bool isSupported = false;
3253 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3254 IsMultiplicationSupported,
3255 data.m_Backends,
3256 isSupported,
3257 input0.GetTensorInfo(),
3258 input1.GetTensorInfo(),
3259 outputInfo);
3260 if (!isSupported)
3261 {
3262 return false;
3263 }
3264
3265 armnn::IConnectableLayer* const startLayer = data.m_Network->AddMultiplicationLayer();
3266 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3267
3268 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3269 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3270
3271 if (endLayer != nullptr)
3272 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003273 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003274 if (!isReshapeSupported)
3275 {
3276 return false;
3277 }
3278
Mike Kelly46272802019-08-14 17:00:48 +01003279 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
3280 }
3281 else
3282 {
3283 return Fail("%s: ProcessActivation failed", __func__);
3284 }
3285}
3286
3287template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003288 typename HalOperation = typename HalPolicy::Operation,
3289 typename HalModel = typename HalPolicy::Model>
3290bool ConvertPad(HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003291{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003292 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003293
Mike Kelly3c673942019-07-25 09:26:06 +01003294 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3295 if (!input.IsValid())
3296 {
3297 return Fail("%s: Operation has invalid inputs", __func__);
3298 }
3299
3300 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3301 unsigned int rank = inputInfo.GetNumDimensions();
3302
3303 armnn::PadDescriptor descriptor;
3304 if (!ConvertPaddings<HalPolicy>(operation, model, data, rank, descriptor))
3305 {
3306 return Fail("%s: Could not convert paddings", __func__);
3307 }
3308
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003309 // For a ANEURALNETWORKS_TENSOR_QUANT8_ASYMM and ANEURALNETWORKS_TENSOR_QUANT8_ASYMM_SIGNED tensor,
3310 // the scale and zeroPoint must be the same as input0
Mike Kelly3c673942019-07-25 09:26:06 +01003311 // Before Android Q, the pad value for ANEURALNETWORKS_TENSOR_QUANT8_ASYMM was undefined. Since Android Q the pad
3312 // value must be "logical zero" we set it to be equal to the QuantizationOffset so effectively it ends up as
3313 // (QuantizationOffset - QuantizationOffset) * scale = 0.
Sadik Armagan7b9ce8d2020-04-21 10:39:28 +01003314 if (inputInfo.GetDataType() == armnn::DataType::QAsymmU8 || inputInfo.GetDataType() == armnn::DataType::QAsymmS8)
Mike Kelly3c673942019-07-25 09:26:06 +01003315 {
3316 descriptor.m_PadValue = inputInfo.GetQuantizationOffset();
3317 }
3318
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003319 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly3c673942019-07-25 09:26:06 +01003320 if (!output)
3321 {
3322 return Fail("%s: Could not read output", __func__);
3323 }
3324
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003325 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Mike Kelly3c673942019-07-25 09:26:06 +01003326 if (IsDynamicTensor(outputInfo))
3327 {
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003328 return Fail("%s: Dynamic output tensors are not supported", __func__);
Mike Kelly3c673942019-07-25 09:26:06 +01003329 }
3330
3331 bool isSupported = false;
3332 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3333 IsPadSupported,
3334 data.m_Backends,
3335 isSupported,
3336 inputInfo,
3337 outputInfo,
3338 descriptor);
3339 if (!isSupported)
3340 {
3341 return false;
3342 }
3343
3344 armnn::IConnectableLayer* const layer = data.m_Network->AddPadLayer(descriptor);
3345 assert(layer != nullptr);
3346 input.Connect(layer->GetInputSlot(0));
3347 layer->GetOutputSlot(0).SetTensorInfo(outputInfo);
3348
Aron Virginas-Tarb7421e52019-07-26 13:14:39 +01003349 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
Mike Kelly3c673942019-07-25 09:26:06 +01003350}
3351
Mike Kelly0a879362019-07-29 16:56:31 +01003352template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003353 typename HalOperation = typename HalPolicy::Operation,
3354 typename HalModel = typename HalPolicy::Model>
3355bool ConvertReshape(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003356{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003357 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003358
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003359 const HalOperand* inputOperand = GetInputOperand<HalPolicy>(operation, 0, model);
3360 const HalOperand* requestedShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3361 const HalOperand* outputOperand = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003362
3363 if (inputOperand == nullptr
3364 || requestedShapeOperand == nullptr
3365 || outputOperand == nullptr)
3366 {
3367 return Fail("%s: Operation has invalid inputs", __func__);
3368 }
3369
3370 if (requestedShapeOperand->dimensions.size() != 1)
3371 {
3372 return Fail("%s: Input 1 expected to be one-dimensional (found %i dimensions)",
3373 __func__, requestedShapeOperand->dimensions.size());
3374 }
3375
3376 std::vector<int32_t> targetDimensions;
3377 if (!GetTensorInt32Values<HalPolicy>(*requestedShapeOperand, targetDimensions, model, data))
3378 {
3379 return Fail("%s: Could not read values of input 1", __func__);
3380 }
3381
3382 const Shape inputOperandShape = GetOperandShape(*inputOperand);
3383
3384 Shape requestedShape;
3385 // targetDimensions may contain special values (e.g. -1). reshapePrepare() is an AndroidNN provided utility
3386 // function that resolves these values into a fully specified tensor shape.
3387 if (!reshapePrepare(inputOperandShape, targetDimensions.data(), targetDimensions.size(), &requestedShape))
3388 {
3389 return Fail("%s: Failed to resolve the requested shape", __func__);
3390 }
3391
3392 const Shape outputOperandShape = GetOperandShape(*outputOperand);
3393 if (!SameShape(requestedShape, outputOperandShape))
3394 {
3395 return Fail("%s: Shape of output operand does not match resolved requested shape", __func__);
3396 }
3397
3398 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3399 if (!input.IsValid())
3400 {
3401 return Fail("%s: Could not read input 0", __func__);
3402 }
3403
3404 armnn::ReshapeDescriptor reshapeDescriptor;
3405 reshapeDescriptor.m_TargetShape = armnn::TensorShape(requestedShape.dimensions.size(),
3406 requestedShape.dimensions.data());
3407
3408 bool isSupported = false;
3409 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3410 IsReshapeSupported,
3411 data.m_Backends,
3412 isSupported,
3413 input.GetTensorInfo(),
Kevin Mayaed08ac2019-12-12 16:33:31 +00003414 GetTensorInfoForOperand(*outputOperand),
Mike Kelly46272802019-08-14 17:00:48 +01003415 reshapeDescriptor);
3416 if (!isSupported)
3417 {
3418 return false;
3419 }
3420
3421 armnn::IConnectableLayer* layer = data.m_Network->AddReshapeLayer(reshapeDescriptor);
3422 assert(layer != nullptr);
3423 input.Connect(layer->GetInputSlot(0));
3424
3425 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3426}
3427
3428template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003429 typename HalOperation = typename HalPolicy::Operation,
3430 typename HalModel = typename HalPolicy::Model>
3431bool ConvertSub(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly0a879362019-07-29 16:56:31 +01003432{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003433 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003434
Mike Kelly0a879362019-07-29 16:56:31 +01003435 LayerInputHandle input0 = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3436 LayerInputHandle input1 = ConvertToLayerInputHandle<HalPolicy>(operation, 1, model, data);
3437
3438 if (!input0.IsValid() || !input1.IsValid())
3439 {
3440 return Fail("%s: Operation has invalid inputs", __func__);
3441 }
3442
3443 // The FuseActivation parameter is always the input index 2
3444 // and it should be optional
3445 ActivationFn activationFunction;
3446 if (!GetOptionalInputActivation<HalPolicy>(operation, 2, activationFunction, model, data))
3447 {
3448 return Fail("%s: Operation has invalid inputs", __func__);
3449 }
3450
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003451 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly0a879362019-07-29 16:56:31 +01003452 if (!output)
3453 {
3454 return Fail("%s: Could not read output 0", __func__);
3455 }
3456
3457 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3458 if (IsDynamicTensor(outputInfo))
3459 {
3460 return Fail("%s: Dynamic output tensors are not supported", __func__);
3461 }
3462
3463 bool isSupported = false;
3464 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3465 IsSubtractionSupported,
3466 data.m_Backends,
3467 isSupported,
3468 input0.GetTensorInfo(),
3469 input1.GetTensorInfo(),
3470 outputInfo);
3471 if (!isSupported)
3472 {
3473 return false;
3474 }
3475
3476 armnn::IConnectableLayer* const startLayer = data.m_Network->AddSubtractionLayer();
3477 armnn::IConnectableLayer* const endLayer = ProcessActivation(outputInfo, activationFunction, startLayer, data);
3478
3479 const armnn::TensorInfo& inputTensorInfo0 = input0.GetTensorInfo();
3480 const armnn::TensorInfo& inputTensorInfo1 = input1.GetTensorInfo();
3481
3482 if (endLayer)
3483 {
Derek Lamberti6fd4ceb2019-12-19 15:45:35 +00003484 bool isReshapeSupported = BroadcastTensor(input0, input1, startLayer, data);
Sadik Armagan64b19b52019-08-19 09:49:58 +01003485 if (!isReshapeSupported)
3486 {
3487 return false;
3488 }
Mike Kelly0a879362019-07-29 16:56:31 +01003489 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *endLayer, model, data);
3490 }
3491
3492 return Fail("%s: ProcessActivation failed", __func__);
3493}
3494
Finn Williams23b87b32019-07-30 11:44:05 +01003495template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003496 typename HalOperation = typename HalPolicy::Operation,
3497 typename HalModel = typename HalPolicy::Model>
3498bool ConvertSqueeze(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003499{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003500 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003501
3502 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3503 if (!input.IsValid())
3504 {
3505 return Fail("%s: Operation has invalid inputs", __func__);
3506 }
3507
3508 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3509 unsigned int rank = inputInfo.GetNumDimensions();
3510 if (rank > 4)
3511 {
3512 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3513 }
3514
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003515 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003516 if (!output)
3517 {
3518 return Fail("%s: Could not read output 0", __func__);
3519 }
3520
3521 if (IsDynamicTensor(GetTensorInfoForOperand(*output)))
3522 {
3523 return Fail("%s: Dynamic output tensors are not supported", __func__);
3524 }
3525
3526 // NOTE: Axis is an optional parameter to SQUEEZE, therefore we do not want to generate a failure
3527 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003528 const HalOperand* axisOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003529
3530 const uint32_t dimensionSequence[] = { 0, 1, 2, 3 };
3531
3532 std::vector<int32_t> axis;
3533 if (!axisOperand)
3534 {
3535 axis.assign(dimensionSequence,
3536 dimensionSequence + rank);
3537 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003538 else if (!GetTensorInt32Values<HalPolicy>(*axisOperand, axis, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003539 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003540 return Fail("%s: Operation has an invalid or unsupported axis operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003541 }
3542
3543 std::vector<uint32_t> outputDims;
3544 for (unsigned int i = 0; i < rank; i++)
3545 {
3546 bool skipSqueeze = (std::find(axis.begin(), axis.end(), i) == axis.end());
3547 auto currentDimension = inputInfo.GetShape()[i];
3548 if (skipSqueeze || currentDimension != 1)
3549 {
3550 outputDims.push_back(currentDimension);
3551 }
3552 }
3553
3554 armnn::TensorShape outShape = armnn::TensorShape(outputDims.size(), outputDims.data());
3555
3556 armnn::TensorInfo outputInfo = inputInfo;
3557 outputInfo.SetShape(outShape);
3558
3559 armnn::ReshapeDescriptor reshapeDesc;
3560 reshapeDesc.m_TargetShape = outputInfo.GetShape();
3561
3562 bool isSupported = false;
3563 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3564 IsReshapeSupported,
3565 data.m_Backends,
3566 isSupported,
3567 inputInfo,
Kevin Mayaed08ac2019-12-12 16:33:31 +00003568 outputInfo,
Mike Kelly46272802019-08-14 17:00:48 +01003569 reshapeDesc);
3570 if (!isSupported)
3571 {
3572 return false;
3573 }
3574
3575 armnn::IConnectableLayer* const layer = data.m_Network->AddReshapeLayer(reshapeDesc);
3576 assert(layer != nullptr);
3577 input.Connect(layer->GetInputSlot(0));
3578
3579 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3580}
3581
3582template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003583 typename HalOperation = typename HalPolicy::Operation,
3584 typename HalModel = typename HalPolicy::Model>
3585bool ConvertStridedSlice(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003586{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003587 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003588
3589 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3590 if (!input.IsValid())
3591 {
3592 return Fail("%s: Operation has invalid inputs", __func__);
3593 }
3594
3595 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3596 unsigned int rank = inputInfo.GetNumDimensions();
3597 if (rank > 4)
3598 {
3599 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3600 }
3601
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003602 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003603 if (!output)
3604 {
3605 return Fail("%s: Could not read output 0", __func__);
3606 }
3607
3608 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3609 if (IsDynamicTensor(outputInfo))
3610 {
3611 return Fail("%s: Dynamic output tensors are not supported", __func__);
3612 }
3613
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003614 const HalOperand* beginOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3615 const HalOperand* endOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3616 const HalOperand* stridesOperand = GetInputOperand<HalPolicy>(operation, 3, model);
Mike Kelly46272802019-08-14 17:00:48 +01003617
3618 std::vector<int32_t> beginValues;
3619 std::vector<int32_t> endValues;
3620 std::vector<int32_t> stridesValues;
3621
3622 // The length of the beginOperand, endOperand and stridesOperand must be of a rank(input)
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003623 auto ValidateInputOperands = [&] (const HalOperand& operand, std::vector<int32_t>& operandValues)
Mike Kelly46272802019-08-14 17:00:48 +01003624 {
3625 if (!GetTensorInt32Values<HalPolicy>(operand, operandValues, model, data))
3626 {
3627 return false;
3628 }
3629
3630 if (operandValues.size() != rank)
3631 {
3632 return false;
3633 }
3634
3635 return true;
3636 };
3637
3638 if (!ValidateInputOperands(*beginOperand, beginValues)
3639 || !ValidateInputOperands(*endOperand, endValues)
3640 || !ValidateInputOperands(*stridesOperand, stridesValues))
3641 {
3642 return Fail("%s: Operation has invalid input operand", __func__);
3643 }
3644
3645 // Stride cannot have value '0'
3646 if (std::any_of(stridesValues.cbegin(), stridesValues.cend(), [](int32_t i){ return i == 0; }))
3647 {
3648 return Fail("%s: Stride must be non-zero value.", __func__);
3649 }
3650
3651 armnn::StridedSliceDescriptor descriptor;
3652 descriptor.m_Begin.assign(beginValues.cbegin(), beginValues.cend());
3653 descriptor.m_End.assign(endValues.cbegin(), endValues.cend());
3654 descriptor.m_Stride.assign(stridesValues.cbegin(), stridesValues.cend());
3655 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3656
3657 // Get the "begin_mask", "end_mask", and "shrink_axis_mask" flags
3658 if (!GetInputInt32<HalPolicy>(operation, 4, descriptor.m_BeginMask, model, data) ||
3659 !GetInputInt32<HalPolicy>(operation, 5, descriptor.m_EndMask, model, data) ||
3660 !GetInputInt32<HalPolicy>(operation, 6, descriptor.m_ShrinkAxisMask, model, data))
3661 {
3662 return Fail("%s: Operation has invalid inputs", __func__);
3663 }
3664
3665 bool isSupported = false;
3666 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3667 IsStridedSliceSupported,
3668 data.m_Backends,
3669 isSupported,
3670 inputInfo,
3671 outputInfo,
3672 descriptor);
3673 if (!isSupported)
3674 {
3675 return false;
3676 }
3677
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003678 // Check if slice can fit in a inferred output
3679 armnn::TensorShape inputShape = inputInfo.GetShape();
3680 for (unsigned int i = 0; i < inputShape.GetNumDimensions(); i++)
3681 {
3682 int stride = descriptor.m_Stride[i];
3683 int start = descriptor.GetStartForAxis(inputShape, i);
3684 int stop = descriptor.GetStopForAxis(inputShape, i, start);
3685
3686 if (descriptor.m_ShrinkAxisMask & (1 << i))
3687 {
3688 // If the difference between the start point and the end point of the slice on an axis being shrunk
3689 // is greater than 1 then throw an error as the output will not be large enough to hold the slice
3690 if (((descriptor.m_Begin[i] - descriptor.m_End[i]) > 1)
3691 || ((descriptor.m_Begin[i] - descriptor.m_End[i]) < -1))
3692 {
3693 return Fail("%s: StridedSlice: Output will not be large enough to hold the slice", __func__);
3694 }
Ryan OShea00b586b2020-07-03 11:31:20 +01003695
3696 if(stride < 0)
3697 {
3698 return Fail("%s: StridedSlice: Stride can not be negative while ShrinkAxisMask is set.", __func__);
3699 }
Sadik Armaganbe6b3c22020-05-14 11:51:33 +01003700 }
3701 }
3702
Mike Kelly46272802019-08-14 17:00:48 +01003703 armnn::IConnectableLayer* const layer = data.m_Network->AddStridedSliceLayer(descriptor);
3704 assert(layer != nullptr);
3705 input.Connect(layer->GetInputSlot(0));
3706
3707 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3708}
3709
3710template<typename HalPolicy,
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003711 typename HalOperation = typename HalPolicy::Operation,
3712 typename HalModel = typename HalPolicy::Model>
3713bool ConvertTranspose(const HalOperation& operation, const HalModel& model, ConversionData& data)
Mike Kelly46272802019-08-14 17:00:48 +01003714{
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003715 using HalOperand = typename HalPolicy::Operand;
Mike Kelly46272802019-08-14 17:00:48 +01003716
3717 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3718 if (!input.IsValid())
3719 {
3720 return Fail("%s: Operation has invalid inputs", __func__);
3721 }
3722
3723 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3724 unsigned int rank = inputInfo.GetNumDimensions();
3725 if (rank > 4)
3726 {
3727 Fail("%s: Inputs with rank greater than 4 are not supported", __func__);
3728 }
3729
3730 // NOTE: Axis is an optional parameter to TRANSPOSE, therefore we do not want to generate a failure
3731 // if the operand index is out of bounds.
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003732 const HalOperand* permOperand = GetInputOperand<HalPolicy>(operation, 1, model, false);
Mike Kelly46272802019-08-14 17:00:48 +01003733
3734 std::vector<int32_t> perm(rank);
3735 if (!permOperand)
3736 {
3737 // NOTE: If perm is not given, it is set to (n-1...0), where n is the rank of the tensor
3738 for (unsigned int i = rank; i > 0; i--)
3739 {
3740 perm[rank - i] = boost::numeric_cast<int> (i - 1);
3741 }
3742 }
Mike Kellyeec836e2020-02-18 10:03:30 +00003743 else if (!GetTensorInt32Values<HalPolicy>(*permOperand, perm, model, data))
Mike Kelly46272802019-08-14 17:00:48 +01003744 {
Mike Kellyeec836e2020-02-18 10:03:30 +00003745 return Fail("%s: Operation has an invalid or unsupported permutation operand", __func__);
Mike Kelly46272802019-08-14 17:00:48 +01003746 }
3747
3748 std::vector<uint32_t> outputDims(perm.begin(), perm.begin() + rank);
3749
Mike Kelly4a956582020-02-28 10:32:09 +00003750 armnn::TransposeDescriptor transposeDesc;
3751 transposeDesc.m_DimMappings = armnn::PermutationVector(outputDims.data(), outputDims.size());
Mike Kelly46272802019-08-14 17:00:48 +01003752
Aron Virginas-Taraa5df2d2019-11-19 12:49:55 +00003753 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
Mike Kelly46272802019-08-14 17:00:48 +01003754 if (!output)
3755 {
3756 return Fail("%s: Could not read output 0", __func__);
3757 }
3758
3759 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
Matthew Bentham0182fd32019-12-06 09:45:13 +00003760 if (IsDynamicTensor(outputInfo))
3761 {
3762 return Fail("%s: Dynamic output tensors are not supported", __func__);
3763 }
3764
Mike Kelly46272802019-08-14 17:00:48 +01003765
3766 bool isSupported = false;
3767 FORWARD_LAYER_SUPPORT_FUNC(__func__,
Mike Kelly4a956582020-02-28 10:32:09 +00003768 IsTransposeSupported,
Mike Kelly46272802019-08-14 17:00:48 +01003769 data.m_Backends,
3770 isSupported,
3771 inputInfo,
3772 outputInfo,
Mike Kelly4a956582020-02-28 10:32:09 +00003773 transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003774 if (!isSupported)
3775 {
3776 return false;
3777 }
3778
Mike Kelly4a956582020-02-28 10:32:09 +00003779 armnn::IConnectableLayer* const layer = data.m_Network->AddTransposeLayer(transposeDesc);
Mike Kelly46272802019-08-14 17:00:48 +01003780 assert(layer != nullptr);
3781 input.Connect(layer->GetInputSlot(0));
3782
3783 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3784}
3785
3786template<typename HalPolicy,
Finn Williams23b87b32019-07-30 11:44:05 +01003787 typename HalOperation = typename HalPolicy::Operation,
Finn Williams0e4e4392019-07-31 10:56:27 +01003788 typename HalOperand = typename HalPolicy::Operand,
Finn Williams23b87b32019-07-30 11:44:05 +01003789 typename HalModel = typename HalPolicy::Model>
3790bool ConvertBatchToSpaceNd(const HalOperation& operation,
3791 const HalModel& model,
3792 ConversionData& data)
3793{
Finn Williams23b87b32019-07-30 11:44:05 +01003794
3795 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3796 if (!input.IsValid())
3797 {
3798 return Fail("%s: Operation has invalid inputs", __func__);
3799 }
3800
3801 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3802 if (!output)
3803 {
3804 return Fail("%s: Could not read output 0", __func__);
3805 }
3806
3807 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3808 if (IsDynamicTensor(outputInfo))
3809 {
3810 return Fail("%s: Dynamic output tensors are not supported", __func__);
3811 }
3812
3813 const HalOperand* blockOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3814 if (!blockOperand)
3815 {
3816 return Fail("%s: Could not read input 1", __func__);
3817 }
3818
3819 // Convert the block operand to int32
3820 std::vector<int32_t> block;
3821 if (!GetTensorInt32Values<HalPolicy>(*blockOperand, block, model, data))
3822 {
3823 return Fail("%s: Input 1 has invalid values", __func__);
3824 }
3825
3826 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3827
3828 unsigned int rank = inputInfo.GetNumDimensions();
3829 if (rank != 4)
3830 {
3831 Fail("%s: Only inputs with rank equal to 4 are supported", __func__);
3832 }
3833
3834 if (std::any_of(block.cbegin(), block.cend(), [](int32_t i){ return i < 1; }))
3835 {
3836 return Fail("%s: Block sizes for each spatial dimension of the input tensor must be"
3837 " greater than or equal to 1", __func__);
3838 }
3839
3840 armnn::BatchToSpaceNdDescriptor batchToSpaceNdDesc;
3841 batchToSpaceNdDesc.m_BlockShape.assign(block.cbegin(), block.cend());
3842 batchToSpaceNdDesc.m_DataLayout = armnn::DataLayout::NHWC;
3843
Kevin May42477c12020-03-26 13:34:14 +00003844 if (Is12OrLaterOperand(*output))
Finn Williams23b87b32019-07-30 11:44:05 +01003845 {
Finn Williams0e4e4392019-07-31 10:56:27 +01003846 batchToSpaceNdDesc.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 2, model, data);
Finn Williams23b87b32019-07-30 11:44:05 +01003847 }
3848 // Setting crops to 0,0 0,0 as it is not supported in Android NN API
3849 batchToSpaceNdDesc.m_Crops = {{0, 0}, {0, 0}};
3850
3851 bool isSupported = false;
3852 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3853 IsBatchToSpaceNdSupported,
3854 data.m_Backends,
3855 isSupported,
3856 inputInfo,
3857 outputInfo,
3858 batchToSpaceNdDesc);
3859 if (!isSupported)
3860 {
3861 return false;
3862 }
3863
3864 armnn::IConnectableLayer* const layer = data.m_Network->AddBatchToSpaceNdLayer(batchToSpaceNdDesc);
3865 assert(layer != nullptr);
3866 input.Connect(layer->GetInputSlot(0));
3867
3868 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3869}
Mike Kelly0a879362019-07-29 16:56:31 +01003870
Finn Williamsd74c5052019-07-30 17:06:00 +01003871template<typename HalPolicy,
3872 typename HalOperation = typename HalPolicy::Operation,
3873 typename HalOperand = typename HalPolicy::Operand,
3874 typename HalModel = typename HalPolicy::Model>
3875bool ConvertSpaceToBatchNd(const HalOperation& operation, const HalModel& model, ConversionData& data)
3876{
3877 LayerInputHandle input = ConvertToLayerInputHandle<HalPolicy>(operation, 0, model, data);
3878 if (!input.IsValid())
3879 {
3880 return Fail("%s: Operation has invalid inputs", __func__);
3881 }
3882
3883 const armnn::TensorInfo& inputInfo = input.GetTensorInfo();
3884 unsigned int rank = inputInfo.GetNumDimensions();
3885 unsigned int spatialDim = rank - 2;
3886
3887 if (rank != 4)
3888 {
3889 Fail("%s: Only inputs with rank 4 are supported", __func__);
3890 }
3891
3892 const HalOperand* output = GetOutputOperand<HalPolicy>(operation, 0, model);
3893 if (!output)
3894 {
3895 return Fail("%s: Could not read output 0", __func__);
3896 }
3897
3898 const armnn::TensorInfo& outputInfo = GetTensorInfoForOperand(*output);
3899 if (IsDynamicTensor(outputInfo))
3900 {
3901 return Fail("%s: Dynamic output tensors are not supported", __func__);
3902 }
3903
3904 const HalOperand* blockShapeOperand = GetInputOperand<HalPolicy>(operation, 1, model);
3905 const HalOperand* paddingsOperand = GetInputOperand<HalPolicy>(operation, 2, model);
3906
3907 armnn::TensorShape blockShapeOperandShape = GetTensorShapeForOperand(*blockShapeOperand);
3908 if (blockShapeOperandShape.GetNumDimensions() != 1 || blockShapeOperandShape.GetNumElements() != spatialDim)
3909 {
3910 return Fail("%s: Operation has invalid block shape operand: expected shape [%d]", __func__, spatialDim);
3911 }
3912
3913 std::vector<int32_t> blockShape;
Mike Kellyeec836e2020-02-18 10:03:30 +00003914 if (!GetTensorInt32Values<HalPolicy>(*blockShapeOperand, blockShape, model, data))
3915 {
3916 return Fail("%s: Operation has an invalid or unsupported block size operand", __func__);
3917 }
Finn Williamsd74c5052019-07-30 17:06:00 +01003918 if (std::any_of(blockShape.cbegin(), blockShape.cend(), [](int32_t i){ return i < 1; }))
3919 {
3920 return Fail("%s: Block shape must be at least 1 in all dimensions.", __func__);
3921 }
3922
3923 armnn::TensorShape paddingsOperandShape = GetTensorShapeForOperand(*paddingsOperand);
3924 if (paddingsOperandShape.GetNumDimensions() != 2 || paddingsOperandShape.GetNumElements() != 2 * spatialDim)
3925 {
3926 return Fail("%s: Operation has invalid paddings operand: expected shape [%d, 2]", __func__, spatialDim);
3927 }
3928
3929 std::vector<std::pair<unsigned int, unsigned int>> paddingList;
3930 std::vector<int32_t> paddings;
Mike Kellyeec836e2020-02-18 10:03:30 +00003931 if (!GetTensorInt32Values<HalPolicy>(*paddingsOperand, paddings, model, data))
3932 {
3933 return Fail("%s: Operation has an invalid or unsupported paddings operand", __func__);
3934 }
Finn Williamsd74c5052019-07-30 17:06:00 +01003935 for (unsigned int i = 0; i < paddings.size() - 1; i += 2)
3936 {
3937 int paddingBeforeInput = paddings[i];
3938 int paddingAfterInput = paddings[i + 1];
3939 if (paddingBeforeInput < 0 || paddingAfterInput < 0)
3940 {
3941 return Fail("%s: Operation has invalid paddings operand, invalid padding values.", __func__);
3942 }
3943
3944 paddingList.emplace_back((unsigned int) paddingBeforeInput, (unsigned int) paddingAfterInput);
3945 }
3946
3947 armnn::SpaceToBatchNdDescriptor descriptor;
3948 descriptor.m_DataLayout = armnn::DataLayout::NHWC;
3949 descriptor.m_BlockShape.assign(blockShape.cbegin(), blockShape.cend());
3950 descriptor.m_PadList.assign(paddingList.cbegin(), paddingList.cend());
3951
Kevin May42477c12020-03-26 13:34:14 +00003952 if (Is12OrLaterOperand(*output))
Finn Williamsd74c5052019-07-30 17:06:00 +01003953 {
3954 descriptor.m_DataLayout = OptionalDataLayout<HalPolicy>(operation, 3, model, data);
3955 }
3956
3957 bool isSupported = false;
3958 FORWARD_LAYER_SUPPORT_FUNC(__func__,
3959 IsSpaceToBatchNdSupported,
3960 data.m_Backends,
3961 isSupported,
3962 inputInfo,
3963 outputInfo,
3964 descriptor);
3965 if (!isSupported)
3966 {
3967 return false;
3968 }
3969
3970 armnn::IConnectableLayer* const layer = data.m_Network->AddSpaceToBatchNdLayer(descriptor);
3971 assert(layer != nullptr);
3972 input.Connect(layer->GetInputSlot(0));
3973
3974 return SetupAndTrackLayerOutputSlot<HalPolicy>(operation, 0, *layer, model, data);
3975}
3976
saoste01b8471482018-10-10 09:44:51 +01003977} // namespace armnn_driver